opencode-swarm 7.103.0 → 7.103.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{dispatch-kb69qw40.js → dispatch-e4ejrsz8.js} +1 -1
- package/dist/cli/{guardrail-explain-346nar9k.js → guardrail-explain-4pnnjmyb.js} +3 -3
- package/dist/cli/{index-j21pr24p.js → index-3ahcme4e.js} +8 -8
- package/dist/cli/{index-a50d5e0h.js → index-4fnw0ebs.js} +3 -3
- package/dist/cli/{index-gvf9afe8.js → index-5xy6kv7p.js} +1 -1
- package/dist/cli/{index-adz3nk9b.js → index-8w4d325g.js} +110 -2
- package/dist/cli/index.js +2 -2
- package/dist/graph/types.d.ts +1 -1
- package/dist/index.js +6 -6
- package/dist/lang/symbol-graph.d.ts +8 -1
- package/dist/tools/repo-graph/builder.d.ts +1 -1
- package/dist/tools/repo-graph/types.d.ts +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.103.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm-pr-feedback",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","drift:check":"bun run scripts/drift-check.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});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"],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]});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_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},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","critic_oversight","explorer","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},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"]},quality_budget:{description:"code quality budget check",agents:["architect"]},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","critic_oversight","explorer","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","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},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"]},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_oversight","test_engineer"]},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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},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","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},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","critic_oversight","explorer","coder","test_engineer"]},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"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["architect","sme","docs","docs_design","designer","spec_writer","reviewer","explorer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",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"]},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","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, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_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"]},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"]},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"]},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_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"]},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","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: 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.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is 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.",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","coder"]},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_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES),TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,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.103.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm-pr-feedback",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","drift:check":"bun run scripts/drift-check.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});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"],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]});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_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},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","critic_oversight","explorer","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},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"]},quality_budget:{description:"code quality budget check",agents:["architect"]},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","critic_oversight","explorer","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","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},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"]},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_oversight","test_engineer"]},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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},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","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},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","critic_oversight","explorer","coder","test_engineer"]},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"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["architect","sme","docs","docs_design","designer","spec_writer","reviewer","explorer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",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"]},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","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, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_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"]},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"]},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"]},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_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"]},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","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: 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.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is 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.",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","coder"]},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_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES),TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,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
|
|
|
@@ -1261,7 +1261,7 @@ Flags:
|
|
|
1261
1261
|
`))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 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}=debug,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)}`,warnings=[];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(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_knowledge_events();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_synonym_map();init_version_check();({version:version3}=package_default)});import*as child_process6 from"node:child_process";import{existsSync as existsSync37,readdirSync as readdirSync7,readFileSync as readFileSync20,statSync as statSync12}from"node:fs";import path68 from"node:path";import{fileURLToPath as fileURLToPath2}from"node:url";function resolveCachePackageRoot(cachePath){let nestedPackageRoot=path68.join(cachePath,"node_modules","opencode-swarm");return existsSync37(nestedPackageRoot)?nestedPackageRoot:cachePath}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=readdirSync7(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(!existsSync37(directory)||!statSync12(directory).isDirectory())return{name:"Git Repository",status:"❌",detail:"Invalid directory — cannot check git status"};return child_process6.execSync("git 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=path68.join(directory,".opencode/opencode-swarm.json");if(!existsSync37(configPath))return{name:"Config Parseability",status:"✅",detail:"No project config file present (using defaults)"};try{let content=readFileSync20(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?path68.join(thisDir,"..","lang","grammars"):path68.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=path68.dirname(fileURLToPath2(import.meta.url)),grammarDir=resolveGrammarDir(thisDir),missing=[];if(!existsSync37(path68.join(grammarDir,"tree-sitter.wasm")))missing.push("tree-sitter.wasm (core runtime)");for(let file3 of grammarFiles)if(!existsSync37(path68.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 manifestPath=path68.join(directory,".swarm/checkpoints.json");if(!existsSync37(manifestPath))return{name:"Checkpoint Manifest",status:"✅",detail:"No checkpoint manifest (no checkpoints saved)"};try{let content=readFileSync20(manifestPath,"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 cp of parsed.checkpoints)if(typeof cp.label!=="string"||typeof cp.sha!=="string"||typeof cp.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){let eventsPath=path68.join(directory,".swarm/events.jsonl");if(!existsSync37(eventsPath))return{name:"Event Stream",status:"✅",detail:"No events.jsonl present"};try{let lines=readFileSync20(eventsPath,"utf-8").split(`
|
|
1262
1262
|
`).filter((line)=>line.trim()!==""),malformedCount=0;for(let line of lines)try{JSON.parse(line)}catch{malformedCount++}if(malformedCount===0)return{name:"Event Stream",status:"✅",detail:`events.jsonl is valid — ${lines.length} event(s)`};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){let eventsPath=path68.join(directory,".swarm/events.jsonl");if(!existsSync37(eventsPath))return{name:"Steering Directives",status:"✅",detail:"No events.jsonl — no steering directives to check"};try{let lines=readFileSync20(eventsPath,"utf-8").split(`
|
|
1263
1263
|
`).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)"};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 checkCurator(directory){try{if(!loadPluginConfig(directory).curator?.enabled)return{name:"Curator",status:"✅",detail:"Disabled (enable via curator.enabled)"};let summaryPath=path68.join(directory,".swarm/curator-summary.json");if(!existsSync37(summaryPath))return{name:"Curator",status:"✅",detail:"Enabled, no summary yet (waiting for first phase)"};try{let content=readFileSync20(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(){try{let mechanism=(await _internals44.detectSandboxCapability()).mechanism??"none";if(await _internals44.getSandboxExecutor()!==null)return{name:"Sandbox",status:"✅",detail:`Mechanism: ${mechanism.toLowerCase()} | Available: yes | Sandboxing commands: yes`};if(mechanism!=="none")return{name:"Sandbox",status:"⚠️",detail:`Mechanism: ${mechanism.toLowerCase()} | Available: no (silent pass-through) | Commands NOT sandboxed`};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 getDiagnoseData(directory){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});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"})}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()),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));try{let evidenceDir=path68.join(directory,".swarm","evidence"),snapshotFiles=existsSync37(evidenceDir)?readdirSync7(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 (run with verbose logs for details)`});let cachePaths=getPluginCachePaths(),cacheRows=[];for(let cachePath of cachePaths)try{if(!existsSync37(cachePath)){cacheRows.push(`⬜ ${cachePath} — absent`);continue}let packageRoot=resolveCachePackageRoot(cachePath),cacheLabel=packageRoot===cachePath?cachePath:`${cachePath} -> ${packageRoot}`,missingGrammarAssets=REQUIRED_CACHE_GRAMMAR_ASSETS.filter((file3)=>!existsSync37(path68.join(packageRoot,"dist","lang","grammars",file3))),pkgJsonPath=path68.join(packageRoot,"package.json");try{let raw=readFileSync20(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?"✅":"⬜";checks5.push({name:"Plugin Caches",status:cacheStatus2,detail:cacheRows.join(" | ")});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(`
|
|
1264
|
-
`)}async function handleDiagnoseCommand(directory,_args){let diagnoseData=await getDiagnoseData(directory);return formatDiagnoseMarkdown(diagnoseData)}var version4,sandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS,_internals44;var init_diagnose_service=__esm(()=>{init_package();init_cache_paths();init_loader();init_gate_bridge();init_manager2();init_utils2();init_manager();init_capability_probe();init_executor();init_effective_spec();init_knowledge_diagnostics();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"];_internals44={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,applySafeAutoFixes:()=>applySafeAutoFixes});import*as crypto6 from"node:crypto";import*as fs32 from"node:fs";import*as os15 from"node:os";import*as path69 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(key,value,findings){if(value!==void 0&&(typeof value!=="object"||Array.isArray(value)||value===null))findings.push({id:`invalid-${key}-type`,title:`Invalid ${key} type`,description:`"${key}" must be an object, got ${typeof value}`,severity:"error",path:key,currentValue:value,autoFixable:!1})}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||path69.join(os15.homedir(),".config")}function getConfigPaths(directory){let userConfigPath=path69.join(getUserConfigDir3(),"opencode","opencode-swarm.json"),projectConfigPath=path69.join(directory,".opencode","opencode-swarm.json");return{userConfigPath,projectConfigPath}}function computeHash(content){return crypto6.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=path69.resolve(configPath),resolvedUser=path69.resolve(userConfigPath),resolvedProject=path69.resolve(projectConfigPath);if(resolvedConfig!==resolvedUser&&resolvedConfig!==resolvedProject)return!1;try{if(fs32.existsSync(resolvedConfig)){if(fs32.realpathSync(resolvedConfig)!==resolvedConfig)return!1}}catch{}return!0}catch{return!1}}function atomicWriteFileSync(filePath,content){let tmpPath=`${filePath}.tmp.${process.pid}`;fs32.writeFileSync(tmpPath,content,"utf-8");try{fs32.renameSync(tmpPath,filePath)}catch{try{fs32.unlinkSync(filePath)}catch{}fs32.renameSync(tmpPath,filePath)}}function createConfigBackup(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,content=null;if(fs32.existsSync(projectConfigPath))try{content=fs32.readFileSync(projectConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] project config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}if(content===null&&fs32.existsSync(userConfigPath)){configPath=userConfigPath;try{content=fs32.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=path69.join(directory,".swarm");if(!fs32.existsSync(swarmDir))fs32.mkdirSync(swarmDir,{recursive:!0});let backupFilename=`config-backup-${backup.createdAt}.json`,backupPath=path69.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(!fs32.existsSync(backupPath))return null;let swarmDir=path69.resolve(path69.join(directory,".swarm")),resolvedBackup=path69.resolve(backupPath);if(!resolvedBackup.startsWith(swarmDir+path69.sep)&&resolvedBackup!==swarmDir)return null;try{let artifact=JSON.parse(fs32.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=path69.dirname(targetPath);if(!fs32.existsSync(targetDir))fs32.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(fs32.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs32.readFileSync(projectConfigPath,"utf-8");else if(fs32.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs32.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(path70,value){let findings=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(path70===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(path70){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"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 hooks=value,validHooks=["system_enhancer","compaction","agent_activity","delegation_tracker","agent_awareness_max_chars","delegation_gate","delegation_max_chars"];for(let hookName of Object.keys(hooks))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:hooks[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"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"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"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"automation":{emitObjectTypeMismatch("automation",value,findings);break}case"knowledge":{emitObjectTypeMismatch("knowledge",value,findings);break}case"memory":{emitObjectTypeMismatch("memory",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"full_auto":{emitObjectTypeMismatch("full_auto",value,findings);break}case"pr_monitor":{emitObjectTypeMismatch("pr_monitor",value,findings);break}case"external_skills":{emitObjectTypeMismatch("external_skills",value,findings);break}default:{let topLevel=path70.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 "${path70}" is not in the schema. Did you mean "${suggestion}"?`,severity:"warn",path:path70,currentValue:value,autoFixable:!1});else findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path70}" is not in the schema.`,severity:"warn",path:path70,currentValue:value,autoFixable:!1});break}}return findings}function walkConfigAndValidate(obj,path70,findings,visited=new WeakSet){if(obj===null||obj===void 0)return;if(path70&&typeof obj==="object"&&!Array.isArray(obj)){let keyFindings=validateConfigKey(path70,obj);findings.push(...keyFindings)}if(typeof obj!=="object"){let keyFindings=validateConfigKey(path70,obj);findings.push(...keyFindings);return}if(visited.has(obj)){findings.push({id:"circular-reference",title:`Circular reference detected at ${path70}`,description:`Config value at "${path70}" contains a circular reference. Validation stopped at this path to prevent stack overflow.`,severity:"error",path:path70,currentValue:"[circular]",autoFixable:!1});return}if(visited.add(obj),Array.isArray(obj)){let arrayFindings=validateConfigKey(path70,obj);findings.push(...arrayFindings),obj.forEach((item,index)=>{walkConfigAndValidate(item,`${path70}[${index}]`,findings,visited)});return}for(let[key,value]of Object.entries(obj)){let newPath=path70?`${path70}.${key}`:key;walkConfigAndValidate(value,newPath,findings,visited)}}function runConfigDoctor(config3,directory){let findings=[];walkConfigAndValidate(config3,"",findings),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(fs32.existsSync(projectConfigPath))configSource=projectConfigPath;else if(fs32.existsSync(userConfigPath))configSource=userConfigPath;return{findings,summary,hasAutoFixableIssues,timestamp:Date.now(),configSource}}function isDangerousPathSegment(segment){return DANGEROUS_PATH_SEGMENTS.has(segment)}function isPathSafe2(fixPath){let segments=fixPath.split(".");for(let segment of segments)if(isDangerousPathSegment(segment))return!1;return!0}function applySafeAutoFixes(directory,result){let appliedFixes=[],updatedConfigPath=null,{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent;if(fs32.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs32.readFileSync(projectConfigPath,"utf-8");else if(fs32.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs32.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");for(let finding of safeFixes){let fix=finding.proposedFix;if(!fix)continue;if(!isPathSafe2(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&¤t!==void 0&&typeof current==="object")delete current[lastPart],appliedFixes.push(fix);break;case"update":if(current!==null&¤t!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break;case"add":if(current!==null&¤t!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break}}if(appliedFixes.length>0){let configDir=path69.dirname(configPath);if(!fs32.existsSync(configDir))fs32.mkdirSync(configDir,{recursive:!0});atomicWriteFileSync(configPath,JSON.stringify(config3,null,2)),updatedConfigPath=configPath}return{appliedFixes,updatedConfigPath}}function readDoctorArtifact(directory){try{let artifactPath=path69.join(directory,".swarm","config-doctor.json");if(!fs32.existsSync(artifactPath))return null;let content=fs32.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=path69.join(directory,".swarm");if(!fs32.existsSync(swarmDir))fs32.mkdirSync(swarmDir,{recursive:!0});let artifactPath=path69.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}: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){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);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_DEPTH2=10,MAX_CONTENTS_ENTRIES=20;function walk(dir,depth){if(depth>10)return;let entries;try{entries=fs32.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(!entry.isDirectory())continue;let name=entry.name,fullPath=path69.join(dir,name);if(SKIP_DIRS.has(name))continue;let gitPath=path69.join(fullPath,".git");try{let gitStat=fs32.statSync(gitPath);if(gitStat.isFile()||gitStat.isDirectory())continue}catch{}if(name===".swarm"){if(path69.dirname(fullPath)===projectRoot)continue;let contents=[];try{contents=fs32.readdirSync(fullPath)}catch{contents=["<unreadable>"]}findings.push({path:path69.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=fs32.realpathSync(projectRoot),canonicalStray=fs32.realpathSync(path69.isAbsolute(strayPath)?strayPath:path69.resolve(projectRoot,strayPath))}catch(err){return{success:!1,message:`Failed to resolve paths: ${err instanceof Error?err.message:String(err)}`}}let rootSwarm=path69.join(canonicalRoot,".swarm");if(canonicalStray===rootSwarm||canonicalStray===canonicalRoot)return{success:!1,message:"Refusing to remove root .swarm/ directory"};if(!canonicalStray.startsWith(canonicalRoot+path69.sep))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 fs32.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 KNOWN_TOP_LEVEL_KEYS,DEPRECATED_FIELDS,DANGEROUS_PATH_SEGMENTS;var init_config_doctor=__esm(()=>{init_constants();init_schema();init_utils();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}],["skill_improver.fallback_models",{message:"deprecated",replacement:"agents.skill_improver.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0}],["spec_writer.model",{message:"deprecated",replacement:"agents.spec_writer.model",isDefaultValue:(v)=>v===null}],["spec_writer.fallback_models",{message:"deprecated",replacement:"agents.spec_writer.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0}]]);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 / JavaScript",tier:1,extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs"],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:"npx tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"npx 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:"npx jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"npx 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:"npx 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:null,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 readdir6}from"node:fs/promises";import{extname as extname3,join as join54}from"node:path";function getProfileForFile(filePath){let ext=extname3(filePath);if(!ext)return;return LANGUAGE_REGISTRY.getByExtension(ext)}async function detectProjectLanguages(projectDir){let detected=new Set;async function scanDir(dir){let dirEntries,entries;try{dirEntries=await readdir6(dir,{withFileTypes:!0}),entries=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()&®ex.test(e.name))){detected.add(profile.id);break}continue}try{await access4(join54(dir,detectFile)),detected.add(profile.id);break}catch{}}for(let entry of entries){let ext=extname3(entry);if(!ext)continue;let profile=LANGUAGE_REGISTRY.getByExtension(ext);if(profile)detected.add(profile.id)}}await scanDir(projectDir);try{let topEntries=await readdir6(projectDir,{withFileTypes:!0});for(let entry of topEntries)if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules")await scanDir(join54(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 fs33 from"node:fs";import*as path70 from"node:path";function isCommandAvailable(command){if(toolchainCache.has(command))return toolchainCache.get(command);let isWindows=process.platform==="win32",cmd=isWindows?`${command}.exe`:command;try{let available=_internals45.spawnSyncImpl(isWindows?["where",cmd]:["which",cmd],{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)=>isCommandAvailable(cmd))}function findBuildFiles(workingDir,patterns){for(let pattern of patterns)if(pattern.includes("*")){let dir=workingDir;try{let files=fs33.readdirSync(dir),regex=simpleGlobToRegex(pattern),matches=files.filter((f)=>regex.test(f));if(matches.length>0)return path70.join(dir,matches[0])}catch{}}else{let filePath=path70.join(workingDir,pattern);if(fs33.existsSync(filePath))return filePath}return null}function getRepoDefinedScripts(workingDir,scripts){let packageJsonPath=path70.join(workingDir,"package.json");if(!fs33.existsSync(packageJsonPath))return[];try{let content=fs33.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content);if(!pkg.scripts||typeof pkg.scripts!=="object")return[];let found=[];for(let scriptName of scripts)if(pkg.scripts[scriptName])found.push({script:`npm run ${scriptName}`,priority:0});return found}catch{return[]}}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=path70.join(workingDir,pattern);if(fs33.existsSync(filePath))allBuildFiles.add(filePath)}return Array.from(allBuildFiles)}function findFilesRecursive(dir,regex,results){try{let entries=fs33.readdirSync(dir,{withFileTypes:!0});for(let entry of entries){let fullPath=path70.join(dir,entry.name);if(entry.isDirectory()&&!["node_modules",".git","dist","build","target"].includes(entry.name))findFilesRecursive(fullPath,regex,results);else if(entry.isFile()&®ex.test(entry.name))results.add(fullPath)}}catch{}}async function discoverBuildCommandsFromProfiles(workingDir){let commands=[],skipped=[],detectedProfiles=await detectProjectLanguages(workingDir);for(let profile of detectedProfiles){let fullProfile=LANGUAGE_REGISTRY.get(profile.id);if(!fullProfile){warn(`[build-discovery] profile ${profile.id} not found in registry, skipping`);continue}let sortedCommands=[...fullProfile.build.commands].sort((a,b)=>a.priority-b.priority),foundCommand=!1;for(let cmd of sortedCommands){if(cmd.detectFile){let detectFilePath=path70.join(workingDir,cmd.detectFile);if(!fs33.existsSync(detectFilePath))continue}let binaryName=cmd.cmd.split(" ")[0];if(isCommandAvailable(binaryName)){commands.push({ecosystem:fullProfile.id,command:cmd.cmd,cwd:workingDir,priority:cmd.priority}),foundCommand=!0;break}}if(!foundCommand){let triedBinaries=sortedCommands.map((c)=>c.name||c.cmd.split(" ")[0]).join(", "),reason=`No binary available for profile ${fullProfile.id}: tried ${triedBinaries}`;skipped.push({ecosystem:fullProfile.id,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 _internals45.discoverBuildCommandsFromProfiles(workingDir),profileCommands=profileResult.commands,profileSkipped=profileResult.skipped,coveredEcosystems=new Set;for(let cmd of profileCommands){let ecosystemNames=PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[];for(let name of ecosystemNames)coveredEcosystems.add(name)}let commands=[...profileCommands],skipped=[...profileSkipped];for(let ecosystem of ECOSYSTEMS){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,reason:`Toolchain not found: ${ecosystem.toolchainCommands.join(" or ")} not on PATH`});continue}if(!findBuildFiles(workingDir,ecosystem.buildFiles)){skipped.push({ecosystem:ecosystem.ecosystem,reason:`No build file found: ${ecosystem.buildFiles.join(", ")}`});continue}let availableCommands=ecosystem.commands;if(ecosystem.repoDefinedScripts){let repoScripts=getRepoDefinedScripts(workingDir,ecosystem.repoDefinedScripts);if(repoScripts.length>0)availableCommands=repoScripts.map((s)=>({command:s.script,priority:s.priority}))}for(let cmd of availableCommands)commands.push({ecosystem:ecosystem.ecosystem,command:cmd.command,cwd:workingDir,priority:cmd.priority})}return commands.sort((a,b)=>a.priority-b.priority),{commands,skipped}}function clearToolchainCache(){toolchainCache.clear()}function getEcosystems(){return ECOSYSTEMS.map((e)=>e.ecosystem)}var ECOSYSTEMS,PROFILE_TO_ECOSYSTEM_NAMES,toolchainCache,IS_COMMAND_AVAILABLE_TIMEOUT_MS=3000,_internals45,build_discovery;var init_discovery=__esm(()=>{init_dist();init_detector();init_profiles();init_utils();init_bun_compat();ECOSYSTEMS=[{ecosystem:"node",buildFiles:["package.json"],toolchainCommands:["npm","yarn","pnpm"],commands:[{command:"npm run build",priority:1},{command:"npm run typecheck",priority:2},{command:"npm run check",priority:3}],repoDefinedScripts:["build","typecheck","check","compile"]},{ecosystem:"rust",buildFiles:["Cargo.toml"],toolchainCommands:["cargo"],commands:[{command:"cargo build",priority:1},{command:"cargo check",priority:2}]},{ecosystem:"go",buildFiles:["go.mod"],toolchainCommands:["go"],commands:[{command:"go build ./...",priority:1}]},{ecosystem:"python",buildFiles:["pyproject.toml","setup.py","setup.cfg"],toolchainCommands:["python","python3","py"],commands:[{command:"python -m py_compile",priority:1},{command:"python -m build",priority:2}]},{ecosystem:"java-maven",buildFiles:["pom.xml"],toolchainCommands:["mvn"],commands:[{command:"mvn compile",priority:1}]},{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:1},{command:"gradle build",priority:2}]},{ecosystem:"dotnet",buildFiles:["*.csproj","*.fsproj","*.vbproj"],toolchainCommands:["dotnet"],commands:[{command:"dotnet build",priority:1}]},{ecosystem:"swift",buildFiles:["Package.swift"],toolchainCommands:["swift"],commands:[{command:"swift build",priority:1}]},{ecosystem:"dart",buildFiles:["pubspec.yaml","pubspec.lock"],toolchainCommands:["dart","flutter"],commands:[{command:"dart analyze",priority:1},{command:"dart compile",priority:2}]},{ecosystem:"cpp",buildFiles:["Makefile","CMakeLists.txt"],toolchainCommands:["make","cmake"],commands:[{command:"make",priority:1},{command:"cmake -B build && cmake --build build",priority:2}]},{ecosystem:"php-composer",buildFiles:["composer.json"],toolchainCommands:["composer"],commands:[{command:"composer install --no-interaction --prefer-dist",priority:1}]}],PROFILE_TO_ECOSYSTEM_NAMES={typescript:["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;_internals45={isCommandAvailable,discoverBuildCommandsFromProfiles,discoverBuildCommands,clearToolchainCache,getEcosystems,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(`
|
|
1264
|
+
`)}async function handleDiagnoseCommand(directory,_args){let diagnoseData=await getDiagnoseData(directory);return formatDiagnoseMarkdown(diagnoseData)}var version4,sandboxCapabilityProbe,REQUIRED_CACHE_GRAMMAR_ASSETS,_internals44;var init_diagnose_service=__esm(()=>{init_package();init_cache_paths();init_loader();init_gate_bridge();init_manager2();init_utils2();init_manager();init_capability_probe();init_executor();init_effective_spec();init_knowledge_diagnostics();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"];_internals44={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,applySafeAutoFixes:()=>applySafeAutoFixes});import*as crypto6 from"node:crypto";import*as fs32 from"node:fs";import*as os15 from"node:os";import*as path69 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(key,value,findings){if(value!==void 0&&(typeof value!=="object"||Array.isArray(value)||value===null))findings.push({id:`invalid-${key}-type`,title:`Invalid ${key} type`,description:`"${key}" must be an object, got ${typeof value}`,severity:"error",path:key,currentValue:value,autoFixable:!1})}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||path69.join(os15.homedir(),".config")}function getConfigPaths(directory){let userConfigPath=path69.join(getUserConfigDir3(),"opencode","opencode-swarm.json"),projectConfigPath=path69.join(directory,".opencode","opencode-swarm.json");return{userConfigPath,projectConfigPath}}function computeHash(content){return crypto6.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=path69.resolve(configPath),resolvedUser=path69.resolve(userConfigPath),resolvedProject=path69.resolve(projectConfigPath);if(resolvedConfig!==resolvedUser&&resolvedConfig!==resolvedProject)return!1;try{if(fs32.existsSync(resolvedConfig)){if(fs32.realpathSync(resolvedConfig)!==resolvedConfig)return!1}}catch{}return!0}catch{return!1}}function atomicWriteFileSync(filePath,content){let tmpPath=`${filePath}.tmp.${process.pid}`;fs32.writeFileSync(tmpPath,content,"utf-8");try{fs32.renameSync(tmpPath,filePath)}catch{try{fs32.unlinkSync(filePath)}catch{}fs32.renameSync(tmpPath,filePath)}}function createConfigBackup(directory){let{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,content=null;if(fs32.existsSync(projectConfigPath))try{content=fs32.readFileSync(projectConfigPath,"utf-8")}catch(error93){log("[ConfigDoctor] project config read failed",{error:error93 instanceof Error?error93.message:String(error93)})}if(content===null&&fs32.existsSync(userConfigPath)){configPath=userConfigPath;try{content=fs32.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=path69.join(directory,".swarm");if(!fs32.existsSync(swarmDir))fs32.mkdirSync(swarmDir,{recursive:!0});let backupFilename=`config-backup-${backup.createdAt}.json`,backupPath=path69.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(!fs32.existsSync(backupPath))return null;let swarmDir=path69.resolve(path69.join(directory,".swarm")),resolvedBackup=path69.resolve(backupPath);if(!resolvedBackup.startsWith(swarmDir+path69.sep)&&resolvedBackup!==swarmDir)return null;try{let artifact=JSON.parse(fs32.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=path69.dirname(targetPath);if(!fs32.existsSync(targetDir))fs32.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(fs32.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs32.readFileSync(projectConfigPath,"utf-8");else if(fs32.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs32.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(path70,value){let findings=[];for(let[depPath,depInfo]of DEPRECATED_FIELDS)if(path70===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(path70){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"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 hooks=value,validHooks=["system_enhancer","compaction","agent_activity","delegation_tracker","agent_awareness_max_chars","delegation_gate","delegation_max_chars"];for(let hookName of Object.keys(hooks))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:hooks[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"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"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"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"automation":{emitObjectTypeMismatch("automation",value,findings);break}case"knowledge":{emitObjectTypeMismatch("knowledge",value,findings);break}case"memory":{emitObjectTypeMismatch("memory",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"full_auto":{emitObjectTypeMismatch("full_auto",value,findings);break}case"pr_monitor":{emitObjectTypeMismatch("pr_monitor",value,findings);break}case"external_skills":{emitObjectTypeMismatch("external_skills",value,findings);break}default:{let topLevel=path70.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 "${path70}" is not in the schema. Did you mean "${suggestion}"?`,severity:"warn",path:path70,currentValue:value,autoFixable:!1});else findings.push({id:"unknown-config-key",title:`Unknown config key: ${topLevel}`,description:`Unknown config key "${path70}" is not in the schema.`,severity:"warn",path:path70,currentValue:value,autoFixable:!1});break}}return findings}function walkConfigAndValidate(obj,path70,findings,visited=new WeakSet){if(obj===null||obj===void 0)return;if(path70&&typeof obj==="object"&&!Array.isArray(obj)){let keyFindings=validateConfigKey(path70,obj);findings.push(...keyFindings)}if(typeof obj!=="object"){let keyFindings=validateConfigKey(path70,obj);findings.push(...keyFindings);return}if(visited.has(obj)){findings.push({id:"circular-reference",title:`Circular reference detected at ${path70}`,description:`Config value at "${path70}" contains a circular reference. Validation stopped at this path to prevent stack overflow.`,severity:"error",path:path70,currentValue:"[circular]",autoFixable:!1});return}if(visited.add(obj),Array.isArray(obj)){let arrayFindings=validateConfigKey(path70,obj);findings.push(...arrayFindings),obj.forEach((item,index)=>{walkConfigAndValidate(item,`${path70}[${index}]`,findings,visited)});return}for(let[key,value]of Object.entries(obj)){let newPath=path70?`${path70}.${key}`:key;walkConfigAndValidate(value,newPath,findings,visited)}}function runConfigDoctor(config3,directory){let findings=[];walkConfigAndValidate(config3,"",findings),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(fs32.existsSync(projectConfigPath))configSource=projectConfigPath;else if(fs32.existsSync(userConfigPath))configSource=userConfigPath;return{findings,summary,hasAutoFixableIssues,timestamp:Date.now(),configSource}}function isDangerousPathSegment(segment){return DANGEROUS_PATH_SEGMENTS.has(segment)}function isPathSafe2(fixPath){let segments=fixPath.split(".");for(let segment of segments)if(isDangerousPathSegment(segment))return!1;return!0}function applySafeAutoFixes(directory,result){let appliedFixes=[],updatedConfigPath=null,{userConfigPath,projectConfigPath}=getConfigPaths(directory),configPath=projectConfigPath,configContent;if(fs32.existsSync(projectConfigPath))configPath=projectConfigPath,configContent=fs32.readFileSync(projectConfigPath,"utf-8");else if(fs32.existsSync(userConfigPath))configPath=userConfigPath,configContent=fs32.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");for(let finding of safeFixes){let fix=finding.proposedFix;if(!fix)continue;if(!isPathSafe2(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&¤t!==void 0&&typeof current==="object")delete current[lastPart],appliedFixes.push(fix);break;case"update":if(current!==null&¤t!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break;case"add":if(current!==null&¤t!==void 0&&typeof current==="object")current[lastPart]=fix.value,appliedFixes.push(fix);break}}if(appliedFixes.length>0){let configDir=path69.dirname(configPath);if(!fs32.existsSync(configDir))fs32.mkdirSync(configDir,{recursive:!0});atomicWriteFileSync(configPath,JSON.stringify(config3,null,2)),updatedConfigPath=configPath}return{appliedFixes,updatedConfigPath}}function readDoctorArtifact(directory){try{let artifactPath=path69.join(directory,".swarm","config-doctor.json");if(!fs32.existsSync(artifactPath))return null;let content=fs32.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=path69.join(directory,".swarm");if(!fs32.existsSync(swarmDir))fs32.mkdirSync(swarmDir,{recursive:!0});let artifactPath=path69.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}: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){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);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_DEPTH2=10,MAX_CONTENTS_ENTRIES=20;function walk(dir,depth){if(depth>10)return;let entries;try{entries=fs32.readdirSync(dir,{withFileTypes:!0})}catch{return}for(let entry of entries){if(!entry.isDirectory())continue;let name=entry.name,fullPath=path69.join(dir,name);if(SKIP_DIRS.has(name))continue;let gitPath=path69.join(fullPath,".git");try{let gitStat=fs32.statSync(gitPath);if(gitStat.isFile()||gitStat.isDirectory())continue}catch{}if(name===".swarm"){if(path69.dirname(fullPath)===projectRoot)continue;let contents=[];try{contents=fs32.readdirSync(fullPath)}catch{contents=["<unreadable>"]}findings.push({path:path69.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=fs32.realpathSync(projectRoot),canonicalStray=fs32.realpathSync(path69.isAbsolute(strayPath)?strayPath:path69.resolve(projectRoot,strayPath))}catch(err){return{success:!1,message:`Failed to resolve paths: ${err instanceof Error?err.message:String(err)}`}}let rootSwarm=path69.join(canonicalRoot,".swarm");if(canonicalStray===rootSwarm||canonicalStray===canonicalRoot)return{success:!1,message:"Refusing to remove root .swarm/ directory"};if(!canonicalStray.startsWith(canonicalRoot+path69.sep))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 fs32.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 KNOWN_TOP_LEVEL_KEYS,DEPRECATED_FIELDS,DANGEROUS_PATH_SEGMENTS;var init_config_doctor=__esm(()=>{init_constants();init_schema();init_utils();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}],["skill_improver.fallback_models",{message:"deprecated",replacement:"agents.skill_improver.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0}],["spec_writer.model",{message:"deprecated",replacement:"agents.spec_writer.model",isDefaultValue:(v)=>v===null}],["spec_writer.fallback_models",{message:"deprecated",replacement:"agents.spec_writer.fallback_models",isDefaultValue:(v)=>Array.isArray(v)&&v.length===0}]]);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:"npx tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"npx 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:"npx jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"npx 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:"npx 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:"npx tsc --noEmit",detectFile:"tsconfig.json",priority:9},{name:"vite build",cmd:"npx 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:"npx jest",priority:9},{name:"bun:test",detect:"bun.lock",cmd:"bun test",priority:8},{name:"mocha",detect:".mocharc.json",cmd:"npx 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:"npx 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:null,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 readdir6}from"node:fs/promises";import{extname as extname3,join as join54}from"node:path";function getProfileForFile(filePath){let ext=extname3(filePath);if(!ext)return;return LANGUAGE_REGISTRY.getByExtension(ext)}async function detectProjectLanguages(projectDir){let detected=new Set;async function scanDir(dir){let dirEntries,entries;try{dirEntries=await readdir6(dir,{withFileTypes:!0}),entries=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()&®ex.test(e.name))){detected.add(profile.id);break}continue}try{await access4(join54(dir,detectFile)),detected.add(profile.id);break}catch{}}for(let entry of entries){let ext=extname3(entry);if(!ext)continue;let profile=LANGUAGE_REGISTRY.getByExtension(ext);if(profile)detected.add(profile.id)}}await scanDir(projectDir);try{let topEntries=await readdir6(projectDir,{withFileTypes:!0});for(let entry of topEntries)if(entry.isDirectory()&&!entry.name.startsWith(".")&&entry.name!=="node_modules")await scanDir(join54(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 fs33 from"node:fs";import*as path70 from"node:path";function isCommandAvailable(command){if(toolchainCache.has(command))return toolchainCache.get(command);let isWindows=process.platform==="win32",cmd=isWindows?`${command}.exe`:command;try{let available=_internals45.spawnSyncImpl(isWindows?["where",cmd]:["which",cmd],{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)=>isCommandAvailable(cmd))}function findBuildFiles(workingDir,patterns){for(let pattern of patterns)if(pattern.includes("*")){let dir=workingDir;try{let files=fs33.readdirSync(dir),regex=simpleGlobToRegex(pattern),matches=files.filter((f)=>regex.test(f));if(matches.length>0)return path70.join(dir,matches[0])}catch{}}else{let filePath=path70.join(workingDir,pattern);if(fs33.existsSync(filePath))return filePath}return null}function getRepoDefinedScripts(workingDir,scripts){let packageJsonPath=path70.join(workingDir,"package.json");if(!fs33.existsSync(packageJsonPath))return[];try{let content=fs33.readFileSync(packageJsonPath,"utf-8"),pkg=JSON.parse(content);if(!pkg.scripts||typeof pkg.scripts!=="object")return[];let found=[];for(let scriptName of scripts)if(pkg.scripts[scriptName])found.push({script:`npm run ${scriptName}`,priority:0});return found}catch{return[]}}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=path70.join(workingDir,pattern);if(fs33.existsSync(filePath))allBuildFiles.add(filePath)}return Array.from(allBuildFiles)}function findFilesRecursive(dir,regex,results){try{let entries=fs33.readdirSync(dir,{withFileTypes:!0});for(let entry of entries){let fullPath=path70.join(dir,entry.name);if(entry.isDirectory()&&!["node_modules",".git","dist","build","target"].includes(entry.name))findFilesRecursive(fullPath,regex,results);else if(entry.isFile()&®ex.test(entry.name))results.add(fullPath)}}catch{}}async function discoverBuildCommandsFromProfiles(workingDir){let commands=[],skipped=[],detectedProfiles=await detectProjectLanguages(workingDir);for(let profile of detectedProfiles){let fullProfile=LANGUAGE_REGISTRY.get(profile.id);if(!fullProfile){warn(`[build-discovery] profile ${profile.id} not found in registry, skipping`);continue}let sortedCommands=[...fullProfile.build.commands].sort((a,b)=>a.priority-b.priority),foundCommand=!1;for(let cmd of sortedCommands){if(cmd.detectFile){let detectFilePath=path70.join(workingDir,cmd.detectFile);if(!fs33.existsSync(detectFilePath))continue}let binaryName=cmd.cmd.split(" ")[0];if(isCommandAvailable(binaryName)){commands.push({ecosystem:fullProfile.id,command:cmd.cmd,cwd:workingDir,priority:cmd.priority}),foundCommand=!0;break}}if(!foundCommand){let triedBinaries=sortedCommands.map((c)=>c.name||c.cmd.split(" ")[0]).join(", "),reason=`No binary available for profile ${fullProfile.id}: tried ${triedBinaries}`;skipped.push({ecosystem:fullProfile.id,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 _internals45.discoverBuildCommandsFromProfiles(workingDir),profileCommands=profileResult.commands,profileSkipped=profileResult.skipped,coveredEcosystems=new Set;for(let cmd of profileCommands){let ecosystemNames=PROFILE_TO_ECOSYSTEM_NAMES[cmd.ecosystem]??[];for(let name of ecosystemNames)coveredEcosystems.add(name)}let commands=[...profileCommands],skipped=[...profileSkipped];for(let ecosystem of ECOSYSTEMS){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,reason:`Toolchain not found: ${ecosystem.toolchainCommands.join(" or ")} not on PATH`});continue}if(!findBuildFiles(workingDir,ecosystem.buildFiles)){skipped.push({ecosystem:ecosystem.ecosystem,reason:`No build file found: ${ecosystem.buildFiles.join(", ")}`});continue}let availableCommands=ecosystem.commands;if(ecosystem.repoDefinedScripts){let repoScripts=getRepoDefinedScripts(workingDir,ecosystem.repoDefinedScripts);if(repoScripts.length>0)availableCommands=repoScripts.map((s)=>({command:s.script,priority:s.priority}))}for(let cmd of availableCommands)commands.push({ecosystem:ecosystem.ecosystem,command:cmd.command,cwd:workingDir,priority:cmd.priority})}return commands.sort((a,b)=>a.priority-b.priority),{commands,skipped}}function clearToolchainCache(){toolchainCache.clear()}function getEcosystems(){return ECOSYSTEMS.map((e)=>e.ecosystem)}var ECOSYSTEMS,PROFILE_TO_ECOSYSTEM_NAMES,toolchainCache,IS_COMMAND_AVAILABLE_TIMEOUT_MS=3000,_internals45,build_discovery;var init_discovery=__esm(()=>{init_dist();init_detector();init_profiles();init_utils();init_bun_compat();ECOSYSTEMS=[{ecosystem:"node",buildFiles:["package.json"],toolchainCommands:["npm","yarn","pnpm"],commands:[{command:"npm run build",priority:1},{command:"npm run typecheck",priority:2},{command:"npm run check",priority:3}],repoDefinedScripts:["build","typecheck","check","compile"]},{ecosystem:"rust",buildFiles:["Cargo.toml"],toolchainCommands:["cargo"],commands:[{command:"cargo build",priority:1},{command:"cargo check",priority:2}]},{ecosystem:"go",buildFiles:["go.mod"],toolchainCommands:["go"],commands:[{command:"go build ./...",priority:1}]},{ecosystem:"python",buildFiles:["pyproject.toml","setup.py","setup.cfg"],toolchainCommands:["python","python3","py"],commands:[{command:"python -m py_compile",priority:1},{command:"python -m build",priority:2}]},{ecosystem:"java-maven",buildFiles:["pom.xml"],toolchainCommands:["mvn"],commands:[{command:"mvn compile",priority:1}]},{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:1},{command:"gradle build",priority:2}]},{ecosystem:"dotnet",buildFiles:["*.csproj","*.fsproj","*.vbproj"],toolchainCommands:["dotnet"],commands:[{command:"dotnet build",priority:1}]},{ecosystem:"swift",buildFiles:["Package.swift"],toolchainCommands:["swift"],commands:[{command:"swift build",priority:1}]},{ecosystem:"dart",buildFiles:["pubspec.yaml","pubspec.lock"],toolchainCommands:["dart","flutter"],commands:[{command:"dart analyze",priority:1},{command:"dart compile",priority:2}]},{ecosystem:"cpp",buildFiles:["Makefile","CMakeLists.txt"],toolchainCommands:["make","cmake"],commands:[{command:"make",priority:1},{command:"cmake -B build && cmake --build build",priority:2}]},{ecosystem:"php-composer",buildFiles:["composer.json"],toolchainCommands:["composer"],commands:[{command:"composer install --no-interaction --prefer-dist",priority:1}]}],PROFILE_TO_ECOSYSTEM_NAMES={typescript:["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;_internals45={isCommandAvailable,discoverBuildCommandsFromProfiles,discoverBuildCommands,clearToolchainCache,getEcosystems,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(`
|
|
1265
1265
|
`)}function runToolDoctor(_directory,_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(`
|
|
1266
1266
|
`)}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.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(`
|
|
1267
1267
|
`)}async function handleDoctorCommand(directory,args2){let enableAutoFix=args2.includes("--fix")||args2.includes("-f"),config3=loadPluginConfig(directory),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);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)
|
|
@@ -5308,15 +5308,15 @@ ${originalText}`})}}init_constants();import*as path142 from"node:path";init_prof
|
|
|
5308
5308
|
(namespace_use_declaration) @import
|
|
5309
5309
|
`,refs:`
|
|
5310
5310
|
(name) @ref.identifier
|
|
5311
|
-
`,exports:""}},CAPTURE_KIND={func:"function",class:"class",const:"const",type:"type",interface:"interface",enum:"enum",method:"method",struct:"type",impl:"type",object:"class",mixin:"type",protocol:"interface"},DEF_TYPES=new Set(["function_declaration","class_declaration","variable_declaration","type_alias_declaration","interface_declaration","enum_declaration","method_definition","function_item","function_signature","class_specifier","struct_specifier","struct_item","struct_declaration","method_declaration","type_declaration","object_declaration","protocol_declaration","mixin_declaration","function_definition","generator_function_declaration","class_definition","lexical_declaration","impl_item","method","class"]),PARAM_TYPES=new Set(["formal_parameters","required_parameter","optional_parameter","rest_parameter","array_pattern","object_pattern"]);async function extractFileSymbols(grammarId,source){let treeRef={value:null},timeoutId;try{return await Promise.race([(async()=>{try{if(!_QueryCtor)_QueryCtor=(await import("web-tree-sitter")).Query;let{loadGrammar:loadGrammarDynamic}=await Promise.resolve().then(() => (init_runtime(),exports_runtime)),parser=await loadGrammarDynamic(grammarId);if(treeRef.value=parser.parse(source),!treeRef.value)return null;let qs=QUERIES[grammarId];if(!qs)return null;return buildFacts(treeRef.value,qs,grammarId)}finally{if(treeRef.value)treeRef.value.delete(),treeRef.value=null}})(),new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("AST_TIMEOUT")),AST_TIMEOUT_MS)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)})}catch{return null}}function asTs(node){return node}function buildFacts(tree,qs,grammarId){let root=asTs(tree.rootNode),lang=tree.language;if(!lang)return{defs:[],imports:[],refs:[]};let defMatches=safeMatches(lang,qs.defs,root),importMatches=safeMatches(lang,qs.imports,root),refMatches=safeMatches(lang,qs.refs,root),exportMatches=safeMatches(lang,qs.exports,root),exportNodes=[];for(let m of exportMatches){let cap=m.captures.find((c)=>c.name==="export");if(cap)exportNodes.push(asTs(cap.node))}let commonJsExports=isEsMGrammar(grammarId)?collectCommonJsExports(root.text):new Map,pythonAllNames=grammarId==="python"?collectPythonAllNames(root.text):null,defs=[],defNodes=[],defNameKeys=new Set;for(let m of defMatches){let defCap=m.captures.find((c)=>c.name.endsWith(".def")),nameCaps=m.captures.filter((c)=>c.name.endsWith(".name"));if(!defCap||nameCaps.length===0)continue;let kindKey=defCap.name.replace(/\.def$/,""),kind=CAPTURE_KIND[kindKey]??"function",originalDefNode=asTs(defCap.node),defNode=originalDefNode,explicitExported=exportNodes.some((en)=>isNodeInside(en,defNode)),isDefaultExport=!1;if(explicitExported&&isEsMGrammar(grammarId))isDefaultExport=exportNodes.some((en)=>isNodeInside(en,defNode)&&isDefaultExportStatement(en));if(grammarId==="dart"&&defNode.type==="function_signature"){let rawBody=defNode.nextSibling;if(rawBody){let bodyNode=asTs(rawBody);if(bodyNode.type==="function_body")defNode=asTs({...defNode,endIndex:bodyNode.endIndex,endPosition:bodyNode.endPosition})}}for(let nc of nameCaps){let nameNode=asTs(nc.node),localName=nameNode.text,commonJsExport=commonJsExports.get(localName),visibilityInfo=getSymbolVisibilityInfo({grammarId,localName,kind,defNode:originalDefNode,rootNode:root,isTopLevel:isTopLevelDef(originalDefNode,root),explicitExported,commonJsExport,pythonAllNames}),exportedName=isDefaultExport?"default":commonJsExport?.exportedName??localName;defs.push({name:exportedName,kind,exported:visibilityInfo.exported,visibilityInfo,startLine:defNode.startPosition.row+1,endLine:defNode.endPosition.row+1}),defNodes.push({node:defNode,name:localName}),defNameKeys.add(nodeKey(nameNode))}}let imports=[];for(let m of importMatches){let importCap=m.captures.find((c)=>c.name==="import");if(importCap){let rawText=importCap.node.text.trim();if(grammarId==="go"&&rawText.startsWith("import (")){let specListNode=asTs(importCap.node).children.find((c)=>c!==null&&c.type==="import_spec_list");if(specListNode){for(let spec of asTs(specListNode).children)if(spec&&spec.type==="import_spec"){let parsed=parseGoImport(spec.text.trim());if(parsed)imports.push(parsed)}}}else{let parsed=parseImport(grammarId,rawText);if(parsed)imports.push(parsed)}}if(grammarId==="ruby"){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){let fnText=asTs(reqName.node).text;if(fnText==="require"||fnText==="require_relative"){let callNode=asTs(reqName.node).parent,rawText=callNode?callNode.text:asTs(reqSpec.node).text,parsed=parseRubyRequire(rawText);if(parsed)imports.push(parsed)}}}if(isEsMGrammar(grammarId)){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){if(asTs(reqName.node).text==="require"){let specText=asTs(reqSpec.node).text.replace(/['"]/g,"");imports.push({specifier:specText,importType:"commonjs",bindings:[]})}}}}let topLevelDefs=defNodes.filter((d)=>isTopLevelDef(d.node,root)).map((d)=>({name:d.name,node:d.node})),refs=[];for(let m of refMatches){let cap=m.captures.find((c)=>c.name==="ref.identifier");if(!cap)continue;let refNode=asTs(cap.node);if(defNameKeys.has(nodeKey(refNode)))continue;if(hasAncestorOfType(refNode,"import_statement"))continue;if(isInsideImportStatement(refNode))continue;if(hasAncestorOfType(refNode,PARAM_TYPES))continue;if(refNode.text==="require"&&isInsideRequireCall(refNode))continue;refs.push({identifier:refNode.text,line:refNode.startPosition.row+1,enclosingDecl:findEnclosingDecl(refNode,topLevelDefs)})}return{defs,imports,refs}}function safeMatches(lang,pattern,root){if(!_QueryCtor)return[];try{return new _QueryCtor(lang,pattern).matches(root)}catch{return[]}}function parseEsmImport(text){let t=text.trim(),isTypeOnlyImport=/^import\s+type\s/.test(t),withoutTypeQualifier=t.replace(/^import\s+type\s+/,"import "),named=withoutTypeQualifier.match(/^import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(named){if(isTypeOnlyImport)return{specifier:named[2],importType:"named",bindings:[]};let bindings=[];for(let part of named[1].split(",")){let p=part.trim();if(!p)continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else bindings.push({imported:stripped,local:stripped})}return{specifier:named[2],importType:"named",bindings}}let combined=withoutTypeQualifier.match(/^import\s+(\w+)\s*,\s*\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]/);if(combined)return{specifier:combined[3],importType:"named",bindings:[{imported:"default",local:combined[1]},{imported:"*",local:combined[2]}]};let combinedNamed=withoutTypeQualifier.match(/^import\s+(\w+)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(combinedNamed){if(isTypeOnlyImport)return{specifier:combinedNamed[3],importType:"named",bindings:[]};let bindings=[{imported:"default",local:combinedNamed[1]}];for(let part of combinedNamed[2].split(",")){let p=part.trim();if(!p)continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else bindings.push({imported:stripped,local:stripped})}return{specifier:combinedNamed[3],importType:"named",bindings}}let ns=t.match(/^import\s+\*\s+as\s+(\w+)\s+from\s+['"]([^'"]+)['"]/);if(ns)return{specifier:ns[2],importType:"namespace",bindings:[{imported:"*",local:ns[1]}]};let def=t.match(/^import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/);if(def)return{specifier:def[2],importType:"default",bindings:[{imported:"default",local:def[1]}]};return null}function parseImport(grammarId,text){switch(grammarId){case"python":return parsePythonImport(text);case"rust":return parseRustUse(text);case"go":return parseGoImport(text);case"java":return parseJavaImport(text);case"kotlin":return parseKotlinImport(text);case"csharp":return parseCSharpUsing(text);case"cpp":return parseCppInclude(text);case"swift":return parseSwiftImport(text);case"dart":return parseDartImport(text);case"ruby":return parseRubyRequire(text);case"php":return parsePhpUse(text);case"typescript":case"tsx":case"javascript":return parseEsmImport(text);default:return null}}function parsePythonImport(text){let t=text.trim(),fullImport=t.match(/^import\s+(.+)$/);if(fullImport){let rest=fullImport[1].trim(),alias=rest.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)return{specifier:alias[1],importType:"named",bindings:[{imported:alias[1],local:alias[2]}]};return{specifier:rest,importType:"namespace",bindings:[]}}let fromImport=t.match(/^from\s+(\S+)\s+import\s+(.+)$/);if(fromImport){let bindings=[];for(let part of fromImport[2].split(",")){let p=part.trim();if(!p)continue;let alias=p.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else bindings.push({imported:p,local:p})}return{specifier:fromImport[1],importType:"named",bindings}}return null}function parseRustUse(text){let t=text.trim(),m=t.match(/^use\s+(.+?)\s*as\s+(\w+)\s*;?\s*$/);if(m)return{specifier:m[1].trim(),importType:"named",bindings:[{imported:m[1].trim(),local:m[2]}]};let simple=t.match(/^use\s+(.+?)\s*;?\s*$/);if(simple)return{specifier:simple[1].trim(),importType:"namespace",bindings:[]};return null}function parseGoImport(text){let t=text.trim();if(t.startsWith("import ("))return null;let bareAliased=t.match(/^(\w+)\s+"([^"]+)"$/);if(bareAliased)return{specifier:bareAliased[2],importType:"named",bindings:[{imported:bareAliased[2],local:bareAliased[1]}]};let aliased=t.match(/^import\s+(\w+)\s+"([^"]+)"/);if(aliased)return{specifier:aliased[2],importType:"named",bindings:[{imported:aliased[2],local:aliased[1]}]};let simple=t.match(/^import\s+"([^"]+)"|^"([^"]+)"$/);if(simple)return{specifier:simple[1]??simple[2],importType:"namespace",bindings:[]};return null}function parseJavaImport(text){let m=text.trim().match(/^import\s+(?:static\s+)?([^;\s]+)\s*;?\s*$/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseKotlinImport(text){let t=text.trim(),aliased=t.match(/^import\s+([^;\s]+)\s+as\s+(\w+)/);if(aliased)return{specifier:aliased[1],importType:"named",bindings:[{imported:aliased[1],local:aliased[2]}]};let simple=t.match(/^import\s+([^;\s]+)/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseCSharpUsing(text){let m=text.trim().match(/^using\s+(?:static\s+)?([^=;\s]+)\s*(?:=\s*(.+?))?\s*;?\s*$/);if(m){let specifier=m[2]?m[2].trim():m[1].trim();if(m[2])return{specifier,importType:"named",bindings:[{imported:specifier,local:m[1].trim()}]};return{specifier:m[1].trim(),importType:"namespace",bindings:[]}}return null}function parseCppInclude(text){let t=text.trim(),include=t.match(/^#\s*include\s+[<"]([^>"]+)[>"]/);if(include)return{specifier:include[1],importType:"namespace",bindings:[]};let using=t.match(/^using\s+(?:namespace\s+)?(.+?)\s*;?\s*$/);if(using)return{specifier:using[1].trim(),importType:"namespace",bindings:[]};return null}function parseSwiftImport(text){let m=text.trim().match(/^import\s+(?:class\s+)?([^;\s]+)/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseDartImport(text){let t=text.trim(),m=t.match(/^import\s+['"]([^'"]+)['"]\s+as\s+(\w+)/);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^import\s+['"]([^'"]+)['"]/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseRubyRequire(text){let t=text.trim(),stripped=t.replace(/^(?:require(?:_relative)?)\s+['"]?/,"").replace(/['"]$/,"");if(!stripped||stripped===t)return null;let isRelative=stripped.startsWith("./")||stripped.startsWith("../");return{specifier:stripped,importType:isRelative?"default":"namespace",bindings:[]}}function parsePhpUse(text){let t=text.trim(),m=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s+as\s+(\w+)\s*;?\s*$/i);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s*;?\s*$/i);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function isTopLevelDef(defNode,root){let parent=defNode.parent;while(parent&&parent!==root){if(DEF_TYPES.has(parent.type))return!1;parent=parent.parent}return!0}function findEnclosingDecl(refNode,topLevelDefs){let best=null,bestDist=1/0;for(let def of topLevelDefs)if(isNodeInside(def.node,refNode)){let dist=refNode.startPosition.row-def.node.startPosition.row;if(dist<bestDist)bestDist=dist,best=def}return best?.name??"<module>"}function isNodeInside(outer,inner){return inner.startIndex>=outer.startIndex&&inner.endIndex<=outer.endIndex}function hasAncestorOfType(node,types2){let typeSet=typeof types2==="string"?new Set([types2]):types2,current=node.parent;while(current){if(typeSet.has(current.type))return!0;current=current.parent}return!1}function isInsideRequireCall(node){let current=node.parent;while(current){if(current.type==="call_expression"){let fn2=current.children.find((c)=>c&&c.type==="identifier");if(fn2&&fn2.text==="require")return!0}if(DEF_TYPES.has(current.type))return!1;current=current.parent}return!1}var IMPORT_ANCESTOR_TYPES=new Set(["import_statement","import_from_statement","import_declaration","import_header","use_declaration","using_directive","namespace_use_declaration","library_import"]);function isInsideImportStatement(node){return hasAncestorOfType(node,IMPORT_ANCESTOR_TYPES)}function nodeKey(node){return`${node.startPosition.row},${node.startPosition.column}-${node.endPosition.row},${node.endPosition.column}`}function isDefaultExportStatement(en){if(en.children.some((c)=>c!==null&&c.type==="default"))return!0;return/^export\s+default\b/.test(en.text)}function isEsMGrammar(grammarId){return grammarId==="typescript"||grammarId==="tsx"||grammarId==="javascript"}init_logger();init_path_security();init_zod();init_create_tool();init_path_security();import*as fs77 from"node:fs";import*as path134 from"node:path";var MAX_FILE_SIZE_BYTES2=1048576,MAX_WORKSPACE_RESULTS=50,MAX_WORKSPACE_SCANNED_FILES=200,WORKSPACE_TIMEOUT_MS=1e4,WINDOWS_RESERVED_NAMES2=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i,SYMBOL_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py"]),SKIP_DIRECTORIES=new Set(["node_modules",".git","dist","build","out",".next","coverage","__pycache__"]);function containsWindowsAttacks(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES2.test(part))return!0;return!1}function isPathInWorkspace(filePath,workspace){try{let resolvedPath=path134.resolve(workspace,filePath),realWorkspace=fs77.realpathSync(workspace),realResolvedPath=fs77.realpathSync(resolvedPath),relativePath=path134.relative(realWorkspace,realResolvedPath);if(relativePath.startsWith("..")||path134.isAbsolute(relativePath))return!1;return!0}catch{return!1}}function validatePathForRead(filePath,workspace){return isPathInWorkspace(filePath,workspace)}function extractTSSymbols(filePath,cwd){let fullPath=path134.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return[];let content;try{let stats2=fs77.statSync(fullPath);if(stats2.size>MAX_FILE_SIZE_BYTES2)throw Error(`File too large: ${stats2.size} bytes (max: ${MAX_FILE_SIZE_BYTES2})`);content=fs77.readFileSync(fullPath,"utf-8")}catch{return[]}let lines=content.split(`
|
|
5311
|
+
`,exports:""}},CAPTURE_KIND={func:"function",class:"class",const:"const",type:"type",interface:"interface",enum:"enum",method:"method",struct:"type",impl:"type",object:"class",mixin:"type",protocol:"interface"},DEF_TYPES=new Set(["function_declaration","class_declaration","variable_declaration","type_alias_declaration","interface_declaration","enum_declaration","method_definition","function_item","function_signature","class_specifier","struct_specifier","struct_item","struct_declaration","method_declaration","type_declaration","object_declaration","protocol_declaration","mixin_declaration","function_definition","generator_function_declaration","class_definition","lexical_declaration","impl_item","method","class"]),PARAM_TYPES=new Set(["formal_parameters","required_parameter","optional_parameter","rest_parameter","array_pattern","object_pattern"]);async function extractFileSymbols(grammarId,source){let treeRef={value:null},timeoutId;try{return await Promise.race([(async()=>{try{if(!_QueryCtor)_QueryCtor=(await import("web-tree-sitter")).Query;let{loadGrammar:loadGrammarDynamic}=await Promise.resolve().then(() => (init_runtime(),exports_runtime)),parser=await loadGrammarDynamic(grammarId);if(treeRef.value=parser.parse(source),!treeRef.value)return null;let qs=QUERIES[grammarId];if(!qs)return null;return buildFacts(treeRef.value,qs,grammarId)}finally{if(treeRef.value)treeRef.value.delete(),treeRef.value=null}})(),new Promise((_,reject)=>{timeoutId=setTimeout(()=>reject(Error("AST_TIMEOUT")),AST_TIMEOUT_MS)})]).finally(()=>{if(timeoutId)clearTimeout(timeoutId)})}catch{return null}}function asTs(node){return node}function buildFacts(tree,qs,grammarId){let root=asTs(tree.rootNode),lang=tree.language;if(!lang)return{defs:[],imports:[],refs:[]};let defMatches=safeMatches(lang,qs.defs,root),importMatches=safeMatches(lang,qs.imports,root),refMatches=safeMatches(lang,qs.refs,root),exportMatches=safeMatches(lang,qs.exports,root),exportNodes=[];for(let m of exportMatches){let cap=m.captures.find((c)=>c.name==="export");if(cap)exportNodes.push(asTs(cap.node))}let commonJsExports=isEsMGrammar(grammarId)?collectCommonJsExports(root.text):new Map,pythonAllNames=grammarId==="python"?collectPythonAllNames(root.text):null,defs=[],defNodes=[],defNameKeys=new Set;for(let m of defMatches){let defCap=m.captures.find((c)=>c.name.endsWith(".def")),nameCaps=m.captures.filter((c)=>c.name.endsWith(".name"));if(!defCap||nameCaps.length===0)continue;let kindKey=defCap.name.replace(/\.def$/,""),kind=CAPTURE_KIND[kindKey]??"function",originalDefNode=asTs(defCap.node),defNode=originalDefNode,explicitExported=exportNodes.some((en)=>isNodeInside(en,defNode)),isDefaultExport=!1;if(explicitExported&&isEsMGrammar(grammarId))isDefaultExport=exportNodes.some((en)=>isNodeInside(en,defNode)&&isDefaultExportStatement(en));if(grammarId==="dart"&&defNode.type==="function_signature"){let rawBody=defNode.nextSibling;if(rawBody){let bodyNode=asTs(rawBody);if(bodyNode.type==="function_body")defNode=asTs({...defNode,endIndex:bodyNode.endIndex,endPosition:bodyNode.endPosition})}}for(let nc of nameCaps){let nameNode=asTs(nc.node),localName=nameNode.text,commonJsExport=commonJsExports.get(localName),visibilityInfo=getSymbolVisibilityInfo({grammarId,localName,kind,defNode:originalDefNode,rootNode:root,isTopLevel:isTopLevelDef(originalDefNode,root),explicitExported,commonJsExport,pythonAllNames}),exportedName=isDefaultExport?"default":commonJsExport?.exportedName??localName;defs.push({name:exportedName,kind,exported:visibilityInfo.exported,visibilityInfo,startLine:defNode.startPosition.row+1,endLine:defNode.endPosition.row+1}),defNodes.push({node:defNode,name:localName}),defNameKeys.add(nodeKey(nameNode))}}let importsWithIndex=[],addImport=(entry,node)=>{if(!entry)return;importsWithIndex.push({index:node.startIndex,entry:entry.reExport?{...entry,startLine:node.startPosition.row+1,endLine:node.endPosition.row+1}:entry})};for(let m of importMatches){let importCap=m.captures.find((c)=>c.name==="import");if(importCap){let importNode=asTs(importCap.node),rawText=importNode.text.trim();if(grammarId==="go"&&rawText.startsWith("import (")){let specListNode=importNode.children.find((c)=>c!==null&&c.type==="import_spec_list");if(specListNode){for(let spec of asTs(specListNode).children)if(spec&&spec.type==="import_spec"){let parsed=parseGoImport(spec.text.trim());addImport(parsed,asTs(spec))}}}else{let parsed=parseImport(grammarId,rawText);addImport(parsed,importNode)}}if(grammarId==="ruby"){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){let fnText=asTs(reqName.node).text;if(fnText==="require"||fnText==="require_relative"){let callNode=asTs(reqName.node).parent,rawText=callNode?callNode.text:asTs(reqSpec.node).text,parsed=parseRubyRequire(rawText);addImport(parsed,asTs(callNode??reqSpec.node))}}}if(isEsMGrammar(grammarId)){let reqName=m.captures.find((c)=>c.name==="require.name"),reqSpec=m.captures.find((c)=>c.name==="require.specifier");if(reqName&&reqSpec){if(asTs(reqName.node).text==="require"){let specText=asTs(reqSpec.node).text.replace(/['"]/g,"");addImport({specifier:specText,importType:"commonjs",bindings:[]},asTs(reqName.node))}}}}if(isEsMGrammar(grammarId))for(let exportNode of exportNodes)addImport(parseImport(grammarId,exportNode.text.trim()),exportNode);let imports=importsWithIndex.sort((a,b)=>a.index-b.index).map((item)=>item.entry),topLevelDefs=defNodes.filter((d)=>isTopLevelDef(d.node,root)).map((d)=>({name:d.name,node:d.node})),refs=[];for(let m of refMatches){let cap=m.captures.find((c)=>c.name==="ref.identifier");if(!cap)continue;let refNode=asTs(cap.node);if(defNameKeys.has(nodeKey(refNode)))continue;if(hasAncestorOfType(refNode,"import_statement"))continue;if(isInsideImportStatement(refNode))continue;if(hasAncestorOfType(refNode,PARAM_TYPES))continue;if(refNode.text==="require"&&isInsideRequireCall(refNode))continue;refs.push({identifier:refNode.text,line:refNode.startPosition.row+1,enclosingDecl:findEnclosingDecl(refNode,topLevelDefs)})}return{defs,imports,refs}}function safeMatches(lang,pattern,root){if(!_QueryCtor)return[];try{return new _QueryCtor(lang,pattern).matches(root)}catch{return[]}}function parseEsmImport(text){let t=text.trim(),sideEffect=t.match(/^import\s+['"]([^'"]+)['"]/);if(sideEffect)return{specifier:sideEffect[1],importType:"sideeffect",bindings:[]};let reExportAllAs=t.match(/^export\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(reExportAllAs)return{specifier:reExportAllAs[2],importType:"namespace",bindings:[{imported:"*",local:reExportAllAs[1]}],reExport:!0,exportedBindings:[{imported:"*",exported:reExportAllAs[1]}]};let reExportAll=t.match(/^export\s+\*\s+from\s+['"]([^'"]+)['"]/);if(reExportAll)return{specifier:reExportAll[1],importType:"namespace",bindings:[],reExport:!0};let namedTypeReExport=t.match(/^export\s+type\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedTypeReExport)return{specifier:namedTypeReExport[2],importType:"type",bindings:[],reExport:!0};let namedReExport=t.match(/^export\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(namedReExport){let bindings=[],exportedBindings=[];for(let rawPart of namedReExport[1].split(",")){let p=rawPart.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let alias=p.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/),imported=alias?alias[1]:p,exported=alias?alias[2]:p;if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(exported))continue;bindings.push({imported,local:exported}),exportedBindings.push({imported,exported})}return{specifier:namedReExport[2],importType:"named",bindings,reExport:!0,exportedBindings}}let isTypeOnlyImport=/^import\s+type\s/.test(t),withoutTypeQualifier=t.replace(/^import\s+type\s+/,"import "),named=withoutTypeQualifier.match(/^import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(named){if(isTypeOnlyImport)return{specifier:named[2],importType:"named",bindings:[]};let bindings=[];for(let part of named[1].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:named[2],importType:"named",bindings}}let combined=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(combined){if(isTypeOnlyImport)return{specifier:combined[3],importType:"named",bindings:[]};return{specifier:combined[3],importType:"named",bindings:[{imported:"default",local:combined[1]},{imported:"*",local:combined[2]}]}}let combinedNamed=withoutTypeQualifier.match(/^import\s+([A-Za-z_$][\w$]*)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/);if(combinedNamed){if(isTypeOnlyImport)return{specifier:combinedNamed[3],importType:"named",bindings:[]};let bindings=[{imported:"default",local:combinedNamed[1]}];for(let part of combinedNamed[2].split(",")){let p=part.trim();if(!p)continue;if(/^type\s+/.test(p))continue;let stripped=p.replace(/^type\s+/,"");if(!stripped)continue;let alias=stripped.match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else if(/^[A-Za-z_$][\w$]*$/.test(stripped))bindings.push({imported:stripped,local:stripped})}return{specifier:combinedNamed[3],importType:"named",bindings}}let ns=t.match(/^import\s+\*\s+as\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(ns)return{specifier:ns[2],importType:"namespace",bindings:[{imported:"*",local:ns[1]}]};let def=t.match(/^import\s+([A-Za-z_$][\w$]*)\s+from\s+['"]([^'"]+)['"]/);if(def)return{specifier:def[2],importType:"default",bindings:[{imported:"default",local:def[1]}]};return null}function parseImport(grammarId,text){switch(grammarId){case"python":return parsePythonImport(text);case"rust":return parseRustUse(text);case"go":return parseGoImport(text);case"java":return parseJavaImport(text);case"kotlin":return parseKotlinImport(text);case"csharp":return parseCSharpUsing(text);case"cpp":return parseCppInclude(text);case"swift":return parseSwiftImport(text);case"dart":return parseDartImport(text);case"ruby":return parseRubyRequire(text);case"php":return parsePhpUse(text);case"typescript":case"tsx":case"javascript":return parseEsmImport(text);default:return null}}function parsePythonImport(text){let t=text.trim(),fullImport=t.match(/^import\s+(.+)$/);if(fullImport){let rest=fullImport[1].trim(),alias=rest.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)return{specifier:alias[1],importType:"named",bindings:[{imported:alias[1],local:alias[2]}]};return{specifier:rest,importType:"namespace",bindings:[]}}let fromImport=t.match(/^from\s+(\S+)\s+import\s+(.+)$/);if(fromImport){let bindings=[];for(let part of fromImport[2].split(",")){let p=part.trim();if(!p)continue;let alias=p.match(/^(\w+)\s+as\s+(\w+)$/);if(alias)bindings.push({imported:alias[1],local:alias[2]});else bindings.push({imported:p,local:p})}return{specifier:fromImport[1],importType:"named",bindings}}return null}function parseRustUse(text){let t=text.trim(),m=t.match(/^use\s+(.+?)\s*as\s+(\w+)\s*;?\s*$/);if(m)return{specifier:m[1].trim(),importType:"named",bindings:[{imported:m[1].trim(),local:m[2]}]};let simple=t.match(/^use\s+(.+?)\s*;?\s*$/);if(simple)return{specifier:simple[1].trim(),importType:"namespace",bindings:[]};return null}function parseGoImport(text){let t=text.trim();if(t.startsWith("import ("))return null;let bareAliased=t.match(/^(\w+)\s+"([^"]+)"$/);if(bareAliased)return{specifier:bareAliased[2],importType:"named",bindings:[{imported:bareAliased[2],local:bareAliased[1]}]};let aliased=t.match(/^import\s+(\w+)\s+"([^"]+)"/);if(aliased)return{specifier:aliased[2],importType:"named",bindings:[{imported:aliased[2],local:aliased[1]}]};let simple=t.match(/^import\s+"([^"]+)"|^"([^"]+)"$/);if(simple)return{specifier:simple[1]??simple[2],importType:"namespace",bindings:[]};return null}function parseJavaImport(text){let m=text.trim().match(/^import\s+(?:static\s+)?([^;\s]+)\s*;?\s*$/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseKotlinImport(text){let t=text.trim(),aliased=t.match(/^import\s+([^;\s]+)\s+as\s+(\w+)/);if(aliased)return{specifier:aliased[1],importType:"named",bindings:[{imported:aliased[1],local:aliased[2]}]};let simple=t.match(/^import\s+([^;\s]+)/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseCSharpUsing(text){let m=text.trim().match(/^using\s+(?:static\s+)?([^=;\s]+)\s*(?:=\s*(.+?))?\s*;?\s*$/);if(m){let specifier=m[2]?m[2].trim():m[1].trim();if(m[2])return{specifier,importType:"named",bindings:[{imported:specifier,local:m[1].trim()}]};return{specifier:m[1].trim(),importType:"namespace",bindings:[]}}return null}function parseCppInclude(text){let t=text.trim(),include=t.match(/^#\s*include\s+[<"]([^>"]+)[>"]/);if(include)return{specifier:include[1],importType:"namespace",bindings:[]};let using=t.match(/^using\s+(?:namespace\s+)?(.+?)\s*;?\s*$/);if(using)return{specifier:using[1].trim(),importType:"namespace",bindings:[]};return null}function parseSwiftImport(text){let m=text.trim().match(/^import\s+(?:class\s+)?([^;\s]+)/);if(m)return{specifier:m[1],importType:"namespace",bindings:[]};return null}function parseDartImport(text){let t=text.trim(),m=t.match(/^import\s+['"]([^'"]+)['"]\s+as\s+(\w+)/);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^import\s+['"]([^'"]+)['"]/);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function parseRubyRequire(text){let t=text.trim(),stripped=t.replace(/^(?:require(?:_relative)?)\s+['"]?/,"").replace(/['"]$/,"");if(!stripped||stripped===t)return null;let isRelative=stripped.startsWith("./")||stripped.startsWith("../");return{specifier:stripped,importType:isRelative?"default":"namespace",bindings:[]}}function parsePhpUse(text){let t=text.trim(),m=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s+as\s+(\w+)\s*;?\s*$/i);if(m)return{specifier:m[1],importType:"named",bindings:[{imported:m[1],local:m[2]}]};let simple=t.match(/^use\s+(?:(?:function|const)\s+)?([^;\s]+)\s*;?\s*$/i);if(simple)return{specifier:simple[1],importType:"namespace",bindings:[]};return null}function isTopLevelDef(defNode,root){let parent=defNode.parent;while(parent&&parent!==root){if(DEF_TYPES.has(parent.type))return!1;parent=parent.parent}return!0}function findEnclosingDecl(refNode,topLevelDefs){let best=null,bestDist=1/0;for(let def of topLevelDefs)if(isNodeInside(def.node,refNode)){let dist=refNode.startPosition.row-def.node.startPosition.row;if(dist<bestDist)bestDist=dist,best=def}return best?.name??"<module>"}function isNodeInside(outer,inner){return inner.startIndex>=outer.startIndex&&inner.endIndex<=outer.endIndex}function hasAncestorOfType(node,types2){let typeSet=typeof types2==="string"?new Set([types2]):types2,current=node.parent;while(current){if(typeSet.has(current.type))return!0;current=current.parent}return!1}function isInsideRequireCall(node){let current=node.parent;while(current){if(current.type==="call_expression"){let fn2=current.children.find((c)=>c&&c.type==="identifier");if(fn2&&fn2.text==="require")return!0}if(DEF_TYPES.has(current.type))return!1;current=current.parent}return!1}var IMPORT_ANCESTOR_TYPES=new Set(["import_statement","import_from_statement","import_declaration","import_header","use_declaration","using_directive","namespace_use_declaration","library_import"]);function isInsideImportStatement(node){return hasAncestorOfType(node,IMPORT_ANCESTOR_TYPES)}function nodeKey(node){return`${node.startPosition.row},${node.startPosition.column}-${node.endPosition.row},${node.endPosition.column}`}function isDefaultExportStatement(en){if(en.children.some((c)=>c!==null&&c.type==="default"))return!0;return/^export\s+default\b/.test(en.text)}function isEsMGrammar(grammarId){return grammarId==="typescript"||grammarId==="tsx"||grammarId==="javascript"}init_logger();init_path_security();init_zod();init_create_tool();init_path_security();import*as fs77 from"node:fs";import*as path134 from"node:path";var MAX_FILE_SIZE_BYTES2=1048576,MAX_WORKSPACE_RESULTS=50,MAX_WORKSPACE_SCANNED_FILES=200,WORKSPACE_TIMEOUT_MS=1e4,WINDOWS_RESERVED_NAMES2=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i,SYMBOL_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py"]),SKIP_DIRECTORIES=new Set(["node_modules",".git","dist","build","out",".next","coverage","__pycache__"]);function containsWindowsAttacks(str){if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES2.test(part))return!0;return!1}function isPathInWorkspace(filePath,workspace){try{let resolvedPath=path134.resolve(workspace,filePath),realWorkspace=fs77.realpathSync(workspace),realResolvedPath=fs77.realpathSync(resolvedPath),relativePath=path134.relative(realWorkspace,realResolvedPath);if(relativePath.startsWith("..")||path134.isAbsolute(relativePath))return!1;return!0}catch{return!1}}function validatePathForRead(filePath,workspace){return isPathInWorkspace(filePath,workspace)}function extractTSSymbols(filePath,cwd){let fullPath=path134.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return[];let content;try{let stats2=fs77.statSync(fullPath);if(stats2.size>MAX_FILE_SIZE_BYTES2)throw Error(`File too large: ${stats2.size} bytes (max: ${MAX_FILE_SIZE_BYTES2})`);content=fs77.readFileSync(fullPath,"utf-8")}catch{return[]}let lines=content.split(`
|
|
5312
5312
|
`),symbols=[];for(let i=0;i<lines.length;i++){let line=lines[i],lineNum=i+1,jsdoc;if(i>0&&lines[i-1].trim().endsWith("*/")){let jsdocLines=[];for(let j=i-1;j>=0;j--)if(jsdocLines.unshift(lines[j]),lines[j].trim().startsWith("/**"))break;if(jsdoc=jsdocLines.join(`
|
|
5313
5313
|
`).trim(),jsdoc.length>300)jsdoc=`${jsdoc.substring(0,300)}...`}let fnMatch=line.match(/^export\s+(?:async\s+)?function\s+(\w+)\s*(<[^>]*>)?\s*\(([^)]*)\)(?:\s*:\s*(.+?))?(?:\s*\{|$)/);if(fnMatch){symbols.push({name:fnMatch[1],kind:"function",exported:!0,signature:`function ${fnMatch[1]}${fnMatch[2]||""}(${fnMatch[3].trim()})${fnMatch[4]?`: ${fnMatch[4].trim()}`:""}`,line:lineNum,jsdoc});continue}let constMatch=line.match(/^export\s+const\s+(\w+)(?:\s*:\s*(.+?))?\s*=/);if(constMatch){let restOfLine=line.substring(line.indexOf("=")+1).trim(),isArrow=restOfLine.startsWith("(")||restOfLine.startsWith("async (")||restOfLine.match(/^\w+\s*=>/);symbols.push({name:constMatch[1],kind:isArrow?"function":"const",exported:!0,signature:`const ${constMatch[1]}${constMatch[2]?`: ${constMatch[2].trim()}`:""}`,line:lineNum,jsdoc});continue}let classMatch=line.match(/^export\s+(?:abstract\s+)?class\s+(\w+)(?:\s+(?:extends|implements)\s+(.+?))?(?:\s*\{|$)/);if(classMatch){symbols.push({name:classMatch[1],kind:"class",exported:!0,signature:`class ${classMatch[1]}${classMatch[2]?` extends/implements ${classMatch[2].trim()}`:""}`,line:lineNum,jsdoc});let braceDepth=(line.match(/\{/g)||[]).length-(line.match(/\}/g)||[]).length;for(let j=i+1;j<lines.length&&braceDepth>0;j++){let memberLine=lines[j];braceDepth+=(memberLine.match(/\{/g)||[]).length-(memberLine.match(/\}/g)||[]).length;let methodMatch=memberLine.match(/^\s+(?:public\s+)?(?:async\s+)?(\w+)\s*\(([^)]*)\)(?:\s*:\s*(.+?))?(?:\s*\{|;|$)/);if(methodMatch&&!memberLine.includes("private")&&!memberLine.includes("protected")&&!memberLine.trim().startsWith("//"))symbols.push({name:`${classMatch[1]}.${methodMatch[1]}`,kind:"method",exported:!0,signature:`${methodMatch[1]}(${methodMatch[2].trim()})${methodMatch[3]?`: ${methodMatch[3].trim()}`:""}`,line:j+1});let propMatch=memberLine.match(/^\s+(?:public\s+)?(?:readonly\s+)?(\w+)(?:\?)?:\s*(.+?)(?:\s*[;=]|$)/);if(propMatch&&!memberLine.includes("private")&&!memberLine.includes("protected")&&!memberLine.trim().startsWith("//"))symbols.push({name:`${classMatch[1]}.${propMatch[1]}`,kind:"property",exported:!0,signature:`${propMatch[1]}: ${propMatch[2].trim()}`,line:j+1})}continue}let ifaceMatch=line.match(/^export\s+interface\s+(\w+)(?:\s*<([^>]+)>)?(?:\s+extends\s+(.+?))?(?:\s*\{|$)/);if(ifaceMatch){symbols.push({name:ifaceMatch[1],kind:"interface",exported:!0,signature:`interface ${ifaceMatch[1]}${ifaceMatch[2]?`<${ifaceMatch[2]}>`:""}${ifaceMatch[3]?` extends ${ifaceMatch[3].trim()}`:""}`,line:lineNum,jsdoc});continue}let typeMatch=line.match(/^export\s+type\s+(\w+)(?:\s*<([^>]+)>)?\s*=/);if(typeMatch){let typeValue=line.substring(line.indexOf("=")+1).trim().substring(0,100);symbols.push({name:typeMatch[1],kind:"type",exported:!0,signature:`type ${typeMatch[1]}${typeMatch[2]?`<${typeMatch[2]}>`:""} = ${typeValue}`,line:lineNum,jsdoc});continue}let enumMatch=line.match(/^export\s+(?:const\s+)?enum\s+(\w+)/);if(enumMatch){symbols.push({name:enumMatch[1],kind:"enum",exported:!0,signature:`enum ${enumMatch[1]}`,line:lineNum,jsdoc});continue}let defaultMatch=line.match(/^export\s+default\s+(?:function\s+)?(\w+)/);if(defaultMatch)symbols.push({name:defaultMatch[1],kind:"function",exported:!0,signature:`default ${defaultMatch[1]}`,line:lineNum,jsdoc})}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function extractPythonSymbols(filePath,cwd){let fullPath=path134.join(cwd,filePath);if(!validatePathForRead(fullPath,cwd))return[];let content;try{let stats2=fs77.statSync(fullPath);if(stats2.size>MAX_FILE_SIZE_BYTES2)throw Error(`File too large: ${stats2.size} bytes (max: ${MAX_FILE_SIZE_BYTES2})`);content=fs77.readFileSync(fullPath,"utf-8")}catch{return[]}let lines=content.split(`
|
|
5314
5314
|
`),symbols=[],allMatch=content.match(/__all__\s*=\s*\[([^\]]+)\]/),explicitExports=allMatch?allMatch[1].split(",").map((s)=>s.trim().replace(/['"]/g,"")):null;for(let i=0;i<lines.length;i++){let line=lines[i];if(line.startsWith(" ")||line.startsWith("\t"))continue;let fnMatch=line.match(/^(?:async\s+)?def\s+(\w+)\s*\(([^)]*)\)(?:\s*->\s*(.+?))?:/);if(fnMatch&&!fnMatch[1].startsWith("_")){let exported=!explicitExports||explicitExports.includes(fnMatch[1]);symbols.push({name:fnMatch[1],kind:"function",exported,signature:`def ${fnMatch[1]}(${fnMatch[2].trim()})${fnMatch[3]?` -> ${fnMatch[3].trim()}`:""}`,line:i+1})}let classMatch=line.match(/^class\s+(\w+)(?:\(([^)]*)\))?:/);if(classMatch&&!classMatch[1].startsWith("_")){let exported=!explicitExports||explicitExports.includes(classMatch[1]);symbols.push({name:classMatch[1],kind:"class",exported,signature:`class ${classMatch[1]}${classMatch[2]?`(${classMatch[2].trim()})`:""}`,line:i+1})}let constMatch=line.match(/^([A-Z][A-Z0-9_]+)\s*[:=]/);if(constMatch)symbols.push({name:constMatch[1],kind:"const",exported:!0,signature:line.trim().substring(0,100),line:i+1})}return symbols.sort((a,b)=>{if(a.line!==b.line)return a.line-b.line;return a.name.localeCompare(b.name)})}function findSourceFiles(cwd,maxFiles){let files=[];return walkDir(cwd,cwd,files,maxFiles),files}function walkDir(currentDir,rootDir,files,maxFiles){let entries;try{entries=fs77.readdirSync(currentDir,{withFileTypes:!0})}catch{return}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));for(let entry of entries){if(files.length>=maxFiles)return;if(SKIP_DIRECTORIES.has(entry.name))continue;let fullPath=path134.join(currentDir,entry.name);if(entry.isDirectory())walkDir(fullPath,rootDir,files,maxFiles);else if(entry.isFile()&&SYMBOL_EXTENSIONS.has(path134.extname(entry.name).toLowerCase()))files.push(path134.relative(rootDir,fullPath))}}function searchWorkspaceSymbols(cwd,name,exportedOnly=!0){let startTime=Date.now(),sourceFiles=findSourceFiles(cwd,MAX_WORKSPACE_SCANNED_FILES),files=[],scannedCount=0,truncated=!1;if(sourceFiles.length>=MAX_WORKSPACE_SCANNED_FILES)truncated=!0;let totalSymbols=0;for(let relFile of sourceFiles){if(Date.now()-startTime>WORKSPACE_TIMEOUT_MS){truncated=!0;break}scannedCount++;let syms;switch(path134.extname(relFile).toLowerCase()){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(relFile,cwd);break;case".py":syms=extractPythonSymbols(relFile,cwd);break;default:continue}if(exportedOnly)syms=syms.filter((s)=>s.exported);if(name)syms=syms.filter((s)=>s.name.includes(name));if(syms.length>0){let remaining=MAX_WORKSPACE_RESULTS-totalSymbols;if(remaining<=0){truncated=!0;break}let cappedSyms=syms.slice(0,remaining);if(files.push({file:relFile,symbolCount:cappedSyms.length,symbols:cappedSyms}),totalSymbols+=cappedSyms.length,totalSymbols>=MAX_WORKSPACE_RESULTS){truncated=syms.length>remaining||scannedCount<sourceFiles.length;break}}}return{query:{workspace:!0,name},fileCount:files.length,scannedFileCount:scannedCount,totalSymbols,files,truncated}}var symbols=createSwarmTool({description:"Extract all exported symbols from a source file: functions with signatures, classes with public members, interfaces, types, enums, constants. Supports TypeScript/JavaScript and Python. Use for architect planning, designer scaffolding, and understanding module public API surface.",args:{file:exports_external.string().optional().describe('File path to extract symbols from (e.g., "src/auth/login.ts"). Required when not using workspace mode.'),exported_only:exports_external.boolean().default(!0).describe("If true, only return exported/public symbols. If false, include all top-level symbols."),workspace:exports_external.boolean().optional().describe("When true, search across the workspace instead of a single file. Returns per-file symbol summaries."),name:exports_external.string().optional().describe("Search for symbols by name (case-sensitive substring match). When provided without workspace, only searches the specified file.")},execute:async(args2,directory)=>{let file3,exportedOnly=!0,workspace=!1,name;try{let obj=args2;file3=obj.file!=null&&typeof obj.file==="string"?obj.file:void 0,exportedOnly=obj.exported_only===!0,workspace=obj.workspace===!0,name=obj.name!=null&&typeof obj.name==="string"?obj.name:void 0}catch{return JSON.stringify({file:"<unknown>",error:"Invalid arguments: could not extract parameters",symbols:[]},null,2)}let cwd=directory;if(workspace)return JSON.stringify(searchWorkspaceSymbols(cwd,name,exportedOnly),null,2);if(!file3)return JSON.stringify({error:"file parameter is required when not using workspace mode",symbols:[]},null,2);if(containsControlChars(file3))return JSON.stringify({file:file3,error:"Path contains invalid control characters",symbols:[]},null,2);if(containsPathTraversal(file3))return JSON.stringify({file:file3,error:"Path contains path traversal sequence",symbols:[]},null,2);if(containsWindowsAttacks(file3))return JSON.stringify({file:file3,error:"Path contains invalid Windows-specific sequence",symbols:[]},null,2);if(!isPathInWorkspace(file3,cwd))return JSON.stringify({file:file3,error:"Path is outside workspace",symbols:[]},null,2);let ext=path134.extname(file3),syms;switch(ext){case".ts":case".tsx":case".js":case".jsx":case".mjs":case".cjs":syms=extractTSSymbols(file3,cwd);break;case".py":syms=extractPythonSymbols(file3,cwd);break;default:return JSON.stringify({file:file3,error:`Unsupported file extension: ${ext}. Supported: .ts, .tsx, .js, .jsx, .mjs, .cjs, .py`,symbols:[]},null,2)}if(exportedOnly)syms=syms.filter((s)=>s.exported);if(name)syms=syms.filter((s)=>s.name.includes(name));return JSON.stringify({file:file3,symbolCount:syms.length,symbols:syms},null,2)}});import*as path135 from"node:path";var HTTP_METHODS=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD"],MAX_FACTS_PER_KIND=50;function stripComments(content){let out="",i=0,state="code";while(i<content.length){let ch=content[i],next=i+1<content.length?content[i+1]:"";switch(state){case"code":if(ch==="/"&&next==="/")state="line",i+=2;else if(ch==="/"&&next==="*")state="block",i+=2;else{if(ch==="'")state="single";else if(ch==='"')state="double";else if(ch==="`")state="template";out+=ch,i++}break;case"single":case"double":case"template":{let quote=state==="single"?"'":state==="double"?'"':"`";if(ch==="\\")out+=ch+next,i+=2;else{if(ch===quote)state="code";out+=ch,i++}break}case"line":if(ch===`
|
|
5315
5315
|
`)state="code",out+=ch;i++;break;case"block":if(ch==="*"&&next==="/")state="code",i+=2;else{if(ch===`
|
|
5316
|
-
`)out+=ch;i++}break}}return out}function normalizeModuleName(moduleName){return moduleName.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}function uniqueSorted(values){return[...new Set(values)].sort((a,b)=>a.localeCompare(b))}function addRole(roles,role){roles.add(role)}function boundaryForModule(moduleName){let parts=normalizeModuleName(moduleName).split("/").filter(Boolean);if(parts.length===0)return".";if((parts[0]==="packages"||parts[0]==="crates")&&parts.length>=2)return`${parts[0]}/${parts[1]}`;if(parts[0]==="src"&&parts.length>=3){if(parts[1]==="tools"&&parts[2]==="repo-graph")return"src/tools/repo-graph";return`src/${parts[1]}`}if(parts[0]==="tests"&&parts.length>=2)return`tests/${parts[1]}`;return parts[0]}function inferRoles(moduleName,content){let normalized=normalizeModuleName(moduleName).toLowerCase(),roles=new Set;if(/(^|\/)(__tests__|tests?)\//.test(normalized)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"test_file");if(/(^|\/)(app\/api|pages\/api)\//.test(normalized)||/(^|\/)(routes?|controllers?)\//.test(normalized)||/\/route\.[cm]?[jt]sx?$/.test(normalized)||/\b(router|app|server)\s*\.\s*(get|post|put|patch|delete|all)\s*\(/i.test(content))addRole(roles,"api_route");if(/(^|\/)middleware\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"middleware");if(normalized.startsWith("src/tools/"))addRole(roles,"swarm_tool");if(normalized.startsWith("src/hooks/"))addRole(roles,"hook");if(normalized.startsWith("src/agents/"))addRole(roles,"agent");if(normalized.startsWith("src/cli/")||normalized.startsWith("src/commands/"))addRole(roles,"cli_command");if(normalized.startsWith("src/config/")||/(^|\/)(config|settings)\.[cm]?[jt]s$/.test(normalized))addRole(roles,"config");if(/(^|\/)(schema|schemas|types)\//.test(normalized)||/\b(z\.object|type\s+\w+\s*=|interface\s+\w+)/.test(content))addRole(roles,"schema");if(/(^|\/)(db|database|repositories?|models?|migrations?)\//.test(normalized)||/\b(prisma|drizzle|sequelize|knex|sqlite|sql`|db\.)/i.test(content))addRole(roles,"data_module");if(/(^|\/)(services?|lib|utils?)\//.test(normalized)||/\bexport\s+(async\s+)?function\b/.test(content))addRole(roles,"service_module");if(/\.(md|mdx|rst)$/.test(normalized))addRole(roles,"documentation");if(roles.size===0)addRole(roles,"source_module");return uniqueSorted(roles)}function pathRouteFromModule(moduleName){let parts=normalizeModuleName(moduleName).split("/"),appApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="app"});if(appApi>=0)return`/${parts.slice(appApi).filter((part)=>!/^route\.[cm]?[jt]sx?$/.test(part)).map(routeSegment).join("/")}`.replace(/\/+/g,"/");let pagesApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="pages"});if(pagesApi>=0){let last=parts[parts.length-1]?.replace(/\.[^.]+$/,"");return`/${[...parts.slice(pagesApi,-1),last].filter(Boolean).map(routeSegment).join("/")}`.replace(/\/+/g,"/")}return null}function routeSegment(segment){return segment.replace(/^\[(\.\.\.)?(.+)]$/,(_m,rest,name)=>rest?`:${name}*`:`:${name}`).replace(/\.[^.]+$/,"")}function extractRoutes(moduleName,content){let routes=[],pathRoute=pathRouteFromModule(moduleName),lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let line=lines[i];for(let method of HTTP_METHODS){let exportPattern=new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const)\\s+${method}\\b`);if(pathRoute&&exportPattern.test(line))routes.push({method,path:pathRoute,line:i+1,source:"handler_export"})}let routerMatch=line.match(/\b(?:router|app|server)\s*\.\s*(get|post|put|patch|delete|options|head|all)\s*\(\s*['"`]([^'"`\0\r\n]+)['"`]/i);if(routerMatch)routes.push({method:routerMatch[1].toUpperCase(),path:routerMatch[2],line:i+1,source:"router_call"})}if(pathRoute&&routes.length===0)routes.push({method:"ALL",path:pathRoute,source:"file_path"});return routes.slice(0,MAX_FACTS_PER_KIND)}function classifyDataOperation(line){let trimmed=line.trim(),lower=trimmed.toLowerCase(),evidence=trimmed.slice(0,160),operation=null,access5="unknown",entity;if(/\b(transaction|begintransaction|commit|rollback)\b/i.test(trimmed))operation="transaction",access5="database";if(/\b(migrate|migration|schema\.alter|createTable|dropTable)\b/i.test(trimmed))operation="migration",access5="database";if(/\b(findMany|findUnique|findFirst|select|query|count|aggregate)\b/.test(trimmed))operation??="read";if(/\b(create|insert|update|upsert|save|patch)\b/.test(trimmed))operation??="write";if(/\b(delete|deleteMany|remove|destroy)\b/.test(trimmed))operation="delete";if(/\b(sql`|\bselect\b|\binsert\b|\bupdate\b|\bdelete\b|\bfrom\b)/i.test(trimmed))access5="sql";if(/\b(prisma|drizzle|sequelize|knex|db\.|database\.|repository\.)/i.test(trimmed))access5=access5==="sql"?"sql":"orm";if(/\b(readFile|writeFile|appendFile|rmSync|unlink)\b/.test(trimmed))access5="filesystem",operation??=lower.includes("read")?"read":"write";if(/\b(fetch|axios|http\.|https\.)\b/.test(trimmed))access5="network",operation??="read";let entityMatch=trimmed.match(/\b(?:prisma|db|database)\.(\w+)/i);if(entityMatch)entity=entityMatch[1];if(!operation)return null;return{operation,access:access5,entity,line:0,evidence}}function extractDataOperations(content){let facts=[],lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let fact=classifyDataOperation(lines[i]);if(!fact)continue;if(fact.line=i+1,facts.push(fact),facts.length>=MAX_FACTS_PER_KIND)break}return facts}function extractSecurityFacts(content){let facts=[],lines=content.split(/\r?\n/),push=(kind,line,evidence,confidence)=>{facts.push({kind,line,evidence:evidence.trim().slice(0,160),confidence})};for(let i=0;i<lines.length&&facts.length<MAX_FACTS_PER_KIND;i++){let line=lines[i];if(/\b(requireAuth|requireUser|getServerSession|currentUser|verifyToken|jwt|isAuthenticated|ctx\.user|session)\b/i.test(line))push("authentication",i+1,line,"high");if(/\b(requireRole|hasPermission|authorize|authorization|isAdmin|rbac|policy\.check|can\()\b/i.test(line))push("authorization",i+1,line,"high");if(/\b(z\.object|safeParse|\.parse\(|joi\.|yup\.|validate\w*)\b/i.test(line))push("input_validation",i+1,line,"high");if(/\b(csrf|csrfToken|sameSite)\b/i.test(line))push("csrf",i+1,line,"medium");if(/\b(sanitize|escapeHtml|DOMPurify|xss)\b/i.test(line))push("sanitization",i+1,line,"medium");if(/\b(secret|api[_-]?key|token|password)\b/i.test(line))push("secret_handling",i+1,line,"low")}return facts}function extractConventions(moduleName,roles,routes){let conventions=[];if(roles.includes("test_file"))conventions.push({name:"test_file_naming",evidence:`${path135.basename(moduleName)} matches test/spec naming`});if(routes.some((route)=>route.source==="handler_export"))conventions.push({name:"next_app_route_handler",evidence:"HTTP method exports map to route handlers"});if(roles.includes("swarm_tool"))conventions.push({name:"swarm_tool_module",evidence:"module lives under src/tools"});if(roles.includes("hook"))conventions.push({name:"hook_module",evidence:"module lives under src/hooks"});return conventions}function buildFindings(roles,routes,dataOperations,security){let findings=[],hasAuth=security.some((fact)=>fact.kind==="authentication"||fact.kind==="authorization"||fact.kind==="csrf"),hasValidation=security.some((fact)=>fact.kind==="input_validation"||fact.kind==="sanitization"),mutatingRoute=routes.some((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method)),writes=dataOperations.filter((fact)=>["write","delete","migration"].includes(fact.operation)),hasTransaction=dataOperations.some((fact)=>fact.operation==="transaction");if(roles.includes("api_route")&&routes.length>0&&!hasAuth)findings.push({code:"api_route_without_detected_auth",severity:"medium",message:"No authentication, authorization, or CSRF guard was detected near this route.",line:routes[0]?.line});if(mutatingRoute&&!hasValidation)findings.push({code:"mutating_route_without_detected_validation",severity:"medium",message:"Route appears to mutate state without a detected validation or sanitization fact.",line:routes.find((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method))?.line});if(writes.length>1&&!hasTransaction)findings.push({code:"multiple_writes_without_detected_transaction",severity:"low",message:"Multiple write/delete operations were detected without a transaction fact.",line:writes[0]?.line});return findings}function extractFileOntology(input){let moduleName=normalizeModuleName(input.moduleName),content=stripComments(input.content),roles=inferRoles(moduleName,content),routes=extractRoutes(moduleName,content),dataOperations=extractDataOperations(content),security=extractSecurityFacts(content),conventions=extractConventions(moduleName,roles,routes),findings=buildFindings(roles,routes,dataOperations,security);return{roles,packageBoundary:boundaryForModule(moduleName),routes,dataOperations,security,conventions,findings}}import{realpathSync as realpathSync14}from"node:fs";function safeRealpathSync(targetPath,fallback,realpathResolver=realpathSync14){try{return realpathResolver(targetPath)}catch(error93){if(error93 instanceof Error&&error93.code==="ENOENT")return fallback;return null}}import*as path136 from"node:path";var REPO_GRAPH_FILENAME="repo-graph.json",GRAPH_SCHEMA_VERSION="1.2.0";function isSchemaVersionAtLeast(version5,minimum){let parse10=(v)=>v.split(".").map((part)=>{let n=Number.parseInt(part,10);return Number.isFinite(n)?n:0}),a=parse10(version5??""),b=parse10(minimum),len=Math.max(a.length,b.length);for(let i=0;i<len;i++){let av=a[i]??0,bv=b[i]??0;if(av>bv)return!0;if(av<bv)return!1}return!0}var FILE_ROLE_VALUES=["api_route","middleware","service_module","data_module","swarm_tool","agent","hook","config","schema","test_file","cli_command","documentation","source_module"],ROUTE_METHOD_VALUES=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD","ALL"],ROUTE_SOURCE_VALUES=["file_path","handler_export","router_call"],DATA_OPERATION_VALUES=["read","write","delete","transaction","migration"],DATA_ACCESS_VALUES=["database","orm","sql","filesystem","network","unknown"],SECURITY_KIND_VALUES=["authentication","authorization","input_validation","csrf","sanitization","secret_handling"],SECURITY_CONFIDENCE_VALUES=["low","medium","high"],ONTOLOGY_FINDING_SEVERITY_VALUES=["info","low","medium","high"],IMPORT_TYPE_VALUES=["default","named","namespace","require","sideeffect"];function normalizeGraphPath(filePath){return path136.normalize(filePath).replace(/\\/g,"/")}function createEmptyGraph(workspaceRoot){return{schema_version:GRAPH_SCHEMA_VERSION,workspaceRoot:path136.normalize(workspaceRoot),nodes:{},edges:[],metadata:{generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:0,edgeCount:0}}}function updateGraphMetadata(graph){graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length}}init_path_security();var FILE_ROLE_SET=new Set(FILE_ROLE_VALUES),ROUTE_METHOD_SET=new Set(ROUTE_METHOD_VALUES),ROUTE_SOURCE_SET=new Set(ROUTE_SOURCE_VALUES),DATA_OPERATION_SET=new Set(DATA_OPERATION_VALUES),DATA_ACCESS_SET=new Set(DATA_ACCESS_VALUES),SECURITY_KIND_SET=new Set(SECURITY_KIND_VALUES),SECURITY_CONFIDENCE_SET=new Set(SECURITY_CONFIDENCE_VALUES),ONTOLOGY_FINDING_SEVERITY_SET=new Set(ONTOLOGY_FINDING_SEVERITY_VALUES),IMPORT_TYPE_SET=new Set(IMPORT_TYPE_VALUES),ONTOLOGY_NAME_PATTERN=/^[a-z][a-z0-9_]*$/;function validateWorkspace(workspace){if(!workspace||typeof workspace!=="string"||workspace.trim()==="")throw Error("Invalid workspace: must be a non-empty string");if(containsControlChars(workspace))throw Error("Invalid workspace: control characters detected");if(containsPathTraversal(workspace))throw Error("Invalid workspace: path traversal detected")}function validateGraphNode(node){if(!node||typeof node!=="object")throw Error("Invalid node: must be an object");if(!node.filePath||typeof node.filePath!=="string")throw Error("Invalid node: filePath is required");if(!node.filePath.startsWith("/")&&!/^[A-Za-z]:[/\\]/.test(node.filePath))throw Error("Invalid node: filePath must be absolute");if(containsPathTraversal(node.filePath))throw Error("Invalid node: filePath contains path traversal");if(containsControlChars(node.filePath))throw Error("Invalid node: filePath contains control characters");if(!node.moduleName||typeof node.moduleName!=="string")throw Error("Invalid node: moduleName is required");if(node.moduleName.startsWith("/")||node.moduleName.startsWith("\\")||/^[A-Za-z]:[/\\]/.test(node.moduleName))throw Error("Invalid node: moduleName must be relative");if(containsPathTraversal(node.moduleName))throw Error("Invalid node: moduleName contains path traversal");if(containsControlChars(node.moduleName))throw Error("Invalid node: moduleName contains control characters");if(typeof node.language!=="string")throw Error("Invalid node: language is required");if(typeof node.mtime!=="string")throw Error("Invalid node: mtime is required");if(!Array.isArray(node.exports))throw Error("Invalid node: exports must be an array");for(let exp of node.exports){if(typeof exp!=="string")throw Error("Invalid node: exports must be an array of strings");if(containsControlChars(exp)){let preview=exp.slice(0,120);throw Error(`Invalid node: exports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(!Array.isArray(node.imports))throw Error("Invalid node: imports must be an array");for(let imp of node.imports){if(typeof imp!=="string")throw Error("Invalid node: imports must be an array of strings");if(containsControlChars(imp)){let preview=imp.slice(0,120);throw Error(`Invalid node: imports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(node.exportLines!==void 0){if(typeof node.exportLines!=="object"||node.exportLines===null||Array.isArray(node.exportLines))throw Error("Invalid node: exportLines must be an object");for(let[name,line]of Object.entries(node.exportLines)){if(containsControlChars(name))throw Error("Invalid node: exportLines key contains control characters");if(typeof line!=="number"||!Number.isFinite(line)||line<0)throw Error("Invalid node: exportLines values must be non-negative numbers")}}if(node.exportRanges!==void 0){if(typeof node.exportRanges!=="object"||node.exportRanges===null||Array.isArray(node.exportRanges))throw Error("Invalid node: exportRanges must be an object");for(let[name,range]of Object.entries(node.exportRanges)){if(containsControlChars(name))throw Error("Invalid node: exportRanges key contains control characters");if(typeof range!=="object"||range===null||Array.isArray(range))throw Error("Invalid node: exportRanges values must be objects");let r=range;if(typeof r.startLine!=="number"||!Number.isFinite(r.startLine)||!Number.isInteger(r.startLine)||r.startLine<1||typeof r.endLine!=="number"||!Number.isFinite(r.endLine)||!Number.isInteger(r.endLine)||r.endLine<1)throw Error("Invalid node: exportRanges value must have positive integer startLine and endLine (1-based)");if(r.startLine>r.endLine)throw Error("Invalid node: exportRanges value must have startLine <= endLine")}}if(node.ontology!==void 0)validateOntologyStrings(node)}function validateOntologyStrings(node){let ontology=node.ontology;if(!ontology||typeof ontology!=="object")throw Error("Invalid node: ontology must be an object");let values=[...ontology.roles??[],ontology.packageBoundary,...(ontology.routes??[]).flatMap((route)=>[route.method,route.path,route.source]),...(ontology.dataOperations??[]).flatMap((fact)=>[fact.operation,fact.access,fact.entity??"",fact.evidence]),...(ontology.security??[]).flatMap((fact)=>[fact.kind,fact.evidence,fact.confidence]),...(ontology.conventions??[]).flatMap((fact)=>[fact.name,fact.evidence]),...(ontology.findings??[]).flatMap((finding)=>[finding.code,finding.severity,finding.message])];for(let value of values){if(typeof value!=="string")throw Error("Invalid node: ontology contains non-string value");if(containsControlChars(value)){let preview=value.slice(0,120);throw Error(`Invalid node: ontology contains control characters (file=${node.filePath}, value="${preview}")`)}}for(let role of ontology.roles??[])validateAllowedOntologyValue(node,"ontology.roles",role,FILE_ROLE_SET);for(let route of ontology.routes??[])validateAllowedOntologyValue(node,"ontology.routes.method",route.method,ROUTE_METHOD_SET),validateAllowedOntologyValue(node,"ontology.routes.source",route.source,ROUTE_SOURCE_SET);for(let fact of ontology.dataOperations??[])validateAllowedOntologyValue(node,"ontology.dataOperations.operation",fact.operation,DATA_OPERATION_SET),validateAllowedOntologyValue(node,"ontology.dataOperations.access",fact.access,DATA_ACCESS_SET);for(let fact of ontology.security??[])validateAllowedOntologyValue(node,"ontology.security.kind",fact.kind,SECURITY_KIND_SET),validateAllowedOntologyValue(node,"ontology.security.confidence",fact.confidence,SECURITY_CONFIDENCE_SET);for(let finding of ontology.findings??[])validateOntologyName(node,"ontology.findings.code",finding.code),validateAllowedOntologyValue(node,"ontology.findings.severity",finding.severity,ONTOLOGY_FINDING_SEVERITY_SET)}function validateOntologyName(node,field,value){if(ONTOLOGY_NAME_PATTERN.test(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} must be lower_snake_case (file=${node.filePath}, value="${preview}")`)}function validateAllowedOntologyValue(node,field,value,allowed){if(allowed.has(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} contains invalid value (file=${node.filePath}, value="${preview}")`)}function validateGraphEdge(edge){if(!edge||typeof edge!=="object")throw Error("Invalid edge: must be an object");if(!edge.source||typeof edge.source!=="string")throw Error("Invalid edge: source is required");if(!edge.target||typeof edge.target!=="string")throw Error("Invalid edge: target is required");if(containsPathTraversal(edge.source)||containsPathTraversal(edge.target))throw Error("Invalid edge: path traversal detected");if(containsControlChars(edge.source)||containsControlChars(edge.target))throw Error("Invalid edge: control characters detected");if(!edge.importSpecifier||typeof edge.importSpecifier!=="string")throw Error("Invalid edge: importSpecifier is required");if(containsControlChars(edge.importSpecifier))throw Error("Invalid edge: importSpecifier contains control characters");if(!IMPORT_TYPE_SET.has(edge.importType))throw Error("Invalid edge: importType is invalid");if(edge.importedSymbols!==void 0){if(!Array.isArray(edge.importedSymbols))throw Error("Invalid edge: importedSymbols must be an array");for(let symbol3 of edge.importedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: importedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: importedSymbols contains control characters")}}if(edge.usedSymbols!==void 0){if(!Array.isArray(edge.usedSymbols))throw Error("Invalid edge: usedSymbols must be an array");for(let symbol3 of edge.usedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: usedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: usedSymbols contains control characters")}}}var _internals83={safeRealpathSync,extractTSSymbols,extractPythonSymbols,parseFileImports,extractFileOntology,stripComments:stripComments2,computeUsedSymbols,extractFileSymbols},SKIP_DIRECTORIES2=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg",".svelte-kit"]);function resolveSkipDirectories(excludeDirs){let extras=excludeDirs?.filter((d)=>d.length>0)??[];if(extras.length===0)return SKIP_DIRECTORIES2;return new Set([...SKIP_DIRECTORIES2,...extras])}var SUPPORTED_EXTENSIONS=new Set(LANGUAGE_REGISTRY.getAll().filter((p)=>!p.parserOnly).flatMap((p)=>p.extensions)),DEFAULT_WALK_FILE_CAP=1e4,DEFAULT_WALK_BUDGET_MS=5000,ASYNC_WALK_YIELD_INTERVAL=200,MAX_DIAGNOSTIC_ENTRIES=200,EXTENSION_TO_LANGUAGE={};for(let profile of LANGUAGE_REGISTRY.getAll()){if(profile.parserOnly)continue;for(let ext of profile.extensions)EXTENSION_TO_LANGUAGE[ext]=profile.treeSitter.grammarId}function upsertNode(graph,node){validateGraphNode(node);let key=normalizeGraphPath(node.filePath);graph.nodes[key]=node,updateGraphMetadata(graph)}function addEdge(graph,edge){if(validateGraphEdge(edge),!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))graph.edges.push(edge),updateGraphMetadata(graph)}function buildLoopEdgeKey(edge){return`${edge.source}\x00${edge.target}\x00${edge.importSpecifier}`}function appendNodeFast(graph,node){validateGraphNode(node),graph.nodes[normalizeGraphPath(node.filePath)]=node}function appendEdgeFast(graph,edge,seenEdgeKeys){validateGraphEdge(edge);let key=buildLoopEdgeKey(edge);if(seenEdgeKeys.has(key))return;seenEdgeKeys.add(key),graph.edges.push(edge)}function resolveModuleSpecifier(workspaceRoot,sourceFile,specifier){if(containsControlChars(specifier))return null;if(specifier.startsWith("/")||specifier.startsWith("\\"))return null;if(/^[A-Za-z]:[/\\]/.test(specifier))return null;if(specifier.startsWith("http://")||specifier.startsWith("https://"))return null;try{if(specifier.startsWith(".")){let sourceDir=path137.dirname(sourceFile),resolved=path137.resolve(sourceDir,specifier),initialRealResolved=_internals83.safeRealpathSync(resolved,resolved);if(initialRealResolved===null)return null;let realResolved=initialRealResolved,realRoot=_internals83.safeRealpathSync(workspaceRoot,path137.normalize(workspaceRoot));if(realRoot===null)return null;if(!existsSync77(resolved)){let EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".json"],found=null;for(let ext of EXTENSIONS){let candidate=resolved+ext;if(existsSync77(candidate)){found=candidate;break}}if(found){let foundRealPath=_internals83.safeRealpathSync(found,found);if(foundRealPath===null)return null;realResolved=foundRealPath,resolved=found}else return null}let normalizedResolved=path137.normalize(realResolved),normalizedRoot=path137.normalize(realRoot);if(!normalizedResolved.startsWith(normalizedRoot+path137.sep)&&normalizedResolved!==normalizedRoot)return null;return resolved}return null}catch{return null}}function isRefusedWorkspaceRoot(target){let resolved;try{resolved=realpathSync15(target)}catch{resolved=path137.resolve(target)}let refused=new Set,add2=(p)=>{if(typeof p==="string"&&p.length>0)refused.add(path137.resolve(p))};if(add2(os20.homedir()),add2(os20.tmpdir()),add2("/"),add2("/Users"),add2("/home"),add2("/root"),process.platform==="win32")add2("C:\\"),add2("C:\\Users");return refused.has(resolved)}function createEmptyDiagnostics(){return{extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],lowConfidenceEdgeCount:0}}function diagnosticsHaveEntries(diagnostics){return(diagnostics.extractionFailures?.length??0)>0||(diagnostics.unresolvedImports?.length??0)>0||(diagnostics.oversizedFiles?.length??0)>0||(diagnostics.unsupportedFiles?.length??0)>0||(diagnostics.binaryFiles?.length??0)>0||(diagnostics.unreadableFiles?.length??0)>0||(diagnostics.lowConfidenceEdgeCount??0)>0}function pushCapped(target,value){if(target.length<MAX_DIAGNOSTIC_ENTRIES)target.push(value)}function mergeDiagnostics(target,source){if(!source)return;for(let entry of source.extractionFailures??[])pushCapped(target.extractionFailures,entry);for(let entry of source.unresolvedImports??[])pushCapped(target.unresolvedImports,entry);for(let entry of source.oversizedFiles??[])pushCapped(target.oversizedFiles,entry);for(let entry of source.unsupportedFiles??[])pushCapped(target.unsupportedFiles,entry);for(let entry of source.binaryFiles??[])pushCapped(target.binaryFiles,entry);for(let entry of source.unreadableFiles??[])pushCapped(target.unreadableFiles,entry);target.lowConfidenceEdgeCount+=source.lowConfidenceEdgeCount??0}function isRelativeImportSpecifier(specifier){return specifier==="."||specifier===".."||specifier.startsWith("./")||specifier.startsWith("../")}function unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot){let unresolved=[],moduleName=toModuleName(filePath,absoluteRoot);for(let parsed of parsedImports){if(!isRelativeImportSpecifier(parsed.specifier))continue;if(resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier)===null)unresolved.push({file:moduleName,specifier:parsed.specifier})}return unresolved}var REGEX_ALLOWED_AFTER=new Set("(,=:[!&|?{};*+-~^<>%".split(""));function stripComments2(content){let out="",i=0,n=content.length,state="code",prevSignificant="",regexInClass=!1;while(i<n){let ch=content[i],next=i+1<n?content[i+1]:"";switch(state){case"code":if(ch==="/"&&next==="/")state="line",i+=2;else if(ch==="/"&&next==="*")state="block",i+=2;else if(ch==="/"&®EX_ALLOWED_AFTER.has(prevSignificant))state="regex",regexInClass=!1,out+=ch,i+=1;else{if(ch==="'")state="single";else if(ch==='"')state="double";else if(ch==="`")state="template";if(out+=ch,ch.trim()!=="")prevSignificant=ch;i+=1}break;case"single":case"double":case"template":{let quote=state==="single"?"'":state==="double"?'"':"`";if(ch==="\\")out+=ch+next,i+=2;else{if(ch===quote)state="code",prevSignificant=quote;out+=ch,i+=1}break}case"regex":if(ch==="\\")out+=ch+next,i+=2;else if(ch===`
|
|
5316
|
+
`)out+=ch;i++}break}}return out}function normalizeModuleName(moduleName){return moduleName.replace(/\\/g,"/").replace(/^(?:\.\/)+/,"")}function uniqueSorted(values){return[...new Set(values)].sort((a,b)=>a.localeCompare(b))}function addRole(roles,role){roles.add(role)}function boundaryForModule(moduleName){let parts=normalizeModuleName(moduleName).split("/").filter(Boolean);if(parts.length===0)return".";if((parts[0]==="packages"||parts[0]==="crates")&&parts.length>=2)return`${parts[0]}/${parts[1]}`;if(parts[0]==="src"&&parts.length>=3){if(parts[1]==="tools"&&parts[2]==="repo-graph")return"src/tools/repo-graph";return`src/${parts[1]}`}if(parts[0]==="tests"&&parts.length>=2)return`tests/${parts[1]}`;return parts[0]}function inferRoles(moduleName,content){let normalized=normalizeModuleName(moduleName).toLowerCase(),roles=new Set;if(/(^|\/)(__tests__|tests?)\//.test(normalized)||/\.(test|spec)\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"test_file");if(/(^|\/)(app\/api|pages\/api)\//.test(normalized)||/(^|\/)(routes?|controllers?)\//.test(normalized)||/\/route\.[cm]?[jt]sx?$/.test(normalized)||/\b(router|app|server)\s*\.\s*(get|post|put|patch|delete|all)\s*\(/i.test(content))addRole(roles,"api_route");if(/(^|\/)middleware\.[cm]?[jt]sx?$/.test(normalized))addRole(roles,"middleware");if(normalized.startsWith("src/tools/"))addRole(roles,"swarm_tool");if(normalized.startsWith("src/hooks/"))addRole(roles,"hook");if(normalized.startsWith("src/agents/"))addRole(roles,"agent");if(normalized.startsWith("src/cli/")||normalized.startsWith("src/commands/"))addRole(roles,"cli_command");if(normalized.startsWith("src/config/")||/(^|\/)(config|settings)\.[cm]?[jt]s$/.test(normalized))addRole(roles,"config");if(/(^|\/)(schema|schemas|types)\//.test(normalized)||/\b(z\.object|type\s+\w+\s*=|interface\s+\w+)/.test(content))addRole(roles,"schema");if(/(^|\/)(db|database|repositories?|models?|migrations?)\//.test(normalized)||/\b(prisma|drizzle|sequelize|knex|sqlite|sql`|db\.)/i.test(content))addRole(roles,"data_module");if(/(^|\/)(services?|lib|utils?)\//.test(normalized)||/\bexport\s+(async\s+)?function\b/.test(content))addRole(roles,"service_module");if(/\.(md|mdx|rst)$/.test(normalized))addRole(roles,"documentation");if(roles.size===0)addRole(roles,"source_module");return uniqueSorted(roles)}function pathRouteFromModule(moduleName){let parts=normalizeModuleName(moduleName).split("/"),appApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="app"});if(appApi>=0)return`/${parts.slice(appApi).filter((part)=>!/^route\.[cm]?[jt]sx?$/.test(part)).map(routeSegment).join("/")}`.replace(/\/+/g,"/");let pagesApi=parts.findIndex((part,index)=>{return part==="api"&&index>0&&parts[index-1]==="pages"});if(pagesApi>=0){let last=parts[parts.length-1]?.replace(/\.[^.]+$/,"");return`/${[...parts.slice(pagesApi,-1),last].filter(Boolean).map(routeSegment).join("/")}`.replace(/\/+/g,"/")}return null}function routeSegment(segment){return segment.replace(/^\[(\.\.\.)?(.+)]$/,(_m,rest,name)=>rest?`:${name}*`:`:${name}`).replace(/\.[^.]+$/,"")}function extractRoutes(moduleName,content){let routes=[],pathRoute=pathRouteFromModule(moduleName),lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let line=lines[i];for(let method of HTTP_METHODS){let exportPattern=new RegExp(`\\bexport\\s+(?:async\\s+)?(?:function|const)\\s+${method}\\b`);if(pathRoute&&exportPattern.test(line))routes.push({method,path:pathRoute,line:i+1,source:"handler_export"})}let routerMatch=line.match(/\b(?:router|app|server)\s*\.\s*(get|post|put|patch|delete|options|head|all)\s*\(\s*['"`]([^'"`\0\r\n]+)['"`]/i);if(routerMatch)routes.push({method:routerMatch[1].toUpperCase(),path:routerMatch[2],line:i+1,source:"router_call"})}if(pathRoute&&routes.length===0)routes.push({method:"ALL",path:pathRoute,source:"file_path"});return routes.slice(0,MAX_FACTS_PER_KIND)}function classifyDataOperation(line){let trimmed=line.trim(),lower=trimmed.toLowerCase(),evidence=trimmed.slice(0,160),operation=null,access5="unknown",entity;if(/\b(transaction|begintransaction|commit|rollback)\b/i.test(trimmed))operation="transaction",access5="database";if(/\b(migrate|migration|schema\.alter|createTable|dropTable)\b/i.test(trimmed))operation="migration",access5="database";if(/\b(findMany|findUnique|findFirst|select|query|count|aggregate)\b/.test(trimmed))operation??="read";if(/\b(create|insert|update|upsert|save|patch)\b/.test(trimmed))operation??="write";if(/\b(delete|deleteMany|remove|destroy)\b/.test(trimmed))operation="delete";if(/\b(sql`|\bselect\b|\binsert\b|\bupdate\b|\bdelete\b|\bfrom\b)/i.test(trimmed))access5="sql";if(/\b(prisma|drizzle|sequelize|knex|db\.|database\.|repository\.)/i.test(trimmed))access5=access5==="sql"?"sql":"orm";if(/\b(readFile|writeFile|appendFile|rmSync|unlink)\b/.test(trimmed))access5="filesystem",operation??=lower.includes("read")?"read":"write";if(/\b(fetch|axios|http\.|https\.)\b/.test(trimmed))access5="network",operation??="read";let entityMatch=trimmed.match(/\b(?:prisma|db|database)\.(\w+)/i);if(entityMatch)entity=entityMatch[1];if(!operation)return null;return{operation,access:access5,entity,line:0,evidence}}function extractDataOperations(content){let facts=[],lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let fact=classifyDataOperation(lines[i]);if(!fact)continue;if(fact.line=i+1,facts.push(fact),facts.length>=MAX_FACTS_PER_KIND)break}return facts}function extractSecurityFacts(content){let facts=[],lines=content.split(/\r?\n/),push=(kind,line,evidence,confidence)=>{facts.push({kind,line,evidence:evidence.trim().slice(0,160),confidence})};for(let i=0;i<lines.length&&facts.length<MAX_FACTS_PER_KIND;i++){let line=lines[i];if(/\b(requireAuth|requireUser|getServerSession|currentUser|verifyToken|jwt|isAuthenticated|ctx\.user|session)\b/i.test(line))push("authentication",i+1,line,"high");if(/\b(requireRole|hasPermission|authorize|authorization|isAdmin|rbac|policy\.check|can\()\b/i.test(line))push("authorization",i+1,line,"high");if(/\b(z\.object|safeParse|\.parse\(|joi\.|yup\.|validate\w*)\b/i.test(line))push("input_validation",i+1,line,"high");if(/\b(csrf|csrfToken|sameSite)\b/i.test(line))push("csrf",i+1,line,"medium");if(/\b(sanitize|escapeHtml|DOMPurify|xss)\b/i.test(line))push("sanitization",i+1,line,"medium");if(/\b(secret|api[_-]?key|token|password)\b/i.test(line))push("secret_handling",i+1,line,"low")}return facts}function extractConventions(moduleName,roles,routes){let conventions=[];if(roles.includes("test_file"))conventions.push({name:"test_file_naming",evidence:`${path135.basename(moduleName)} matches test/spec naming`});if(routes.some((route)=>route.source==="handler_export"))conventions.push({name:"next_app_route_handler",evidence:"HTTP method exports map to route handlers"});if(roles.includes("swarm_tool"))conventions.push({name:"swarm_tool_module",evidence:"module lives under src/tools"});if(roles.includes("hook"))conventions.push({name:"hook_module",evidence:"module lives under src/hooks"});return conventions}function buildFindings(roles,routes,dataOperations,security){let findings=[],hasAuth=security.some((fact)=>fact.kind==="authentication"||fact.kind==="authorization"||fact.kind==="csrf"),hasValidation=security.some((fact)=>fact.kind==="input_validation"||fact.kind==="sanitization"),mutatingRoute=routes.some((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method)),writes=dataOperations.filter((fact)=>["write","delete","migration"].includes(fact.operation)),hasTransaction=dataOperations.some((fact)=>fact.operation==="transaction");if(roles.includes("api_route")&&routes.length>0&&!hasAuth)findings.push({code:"api_route_without_detected_auth",severity:"medium",message:"No authentication, authorization, or CSRF guard was detected near this route.",line:routes[0]?.line});if(mutatingRoute&&!hasValidation)findings.push({code:"mutating_route_without_detected_validation",severity:"medium",message:"Route appears to mutate state without a detected validation or sanitization fact.",line:routes.find((route)=>["POST","PUT","PATCH","DELETE","ALL"].includes(route.method))?.line});if(writes.length>1&&!hasTransaction)findings.push({code:"multiple_writes_without_detected_transaction",severity:"low",message:"Multiple write/delete operations were detected without a transaction fact.",line:writes[0]?.line});return findings}function extractFileOntology(input){let moduleName=normalizeModuleName(input.moduleName),content=stripComments(input.content),roles=inferRoles(moduleName,content),routes=extractRoutes(moduleName,content),dataOperations=extractDataOperations(content),security=extractSecurityFacts(content),conventions=extractConventions(moduleName,roles,routes),findings=buildFindings(roles,routes,dataOperations,security);return{roles,packageBoundary:boundaryForModule(moduleName),routes,dataOperations,security,conventions,findings}}import{realpathSync as realpathSync14}from"node:fs";function safeRealpathSync(targetPath,fallback,realpathResolver=realpathSync14){try{return realpathResolver(targetPath)}catch(error93){if(error93 instanceof Error&&error93.code==="ENOENT")return fallback;return null}}import*as path136 from"node:path";var REPO_GRAPH_FILENAME="repo-graph.json",GRAPH_SCHEMA_VERSION="1.2.0";function isSchemaVersionAtLeast(version5,minimum){let parse10=(v)=>v.split(".").map((part)=>{let n=Number.parseInt(part,10);return Number.isFinite(n)?n:0}),a=parse10(version5??""),b=parse10(minimum),len=Math.max(a.length,b.length);for(let i=0;i<len;i++){let av=a[i]??0,bv=b[i]??0;if(av>bv)return!0;if(av<bv)return!1}return!0}var FILE_ROLE_VALUES=["api_route","middleware","service_module","data_module","swarm_tool","agent","hook","config","schema","test_file","cli_command","documentation","source_module"],ROUTE_METHOD_VALUES=["GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD","ALL"],ROUTE_SOURCE_VALUES=["file_path","handler_export","router_call"],DATA_OPERATION_VALUES=["read","write","delete","transaction","migration"],DATA_ACCESS_VALUES=["database","orm","sql","filesystem","network","unknown"],SECURITY_KIND_VALUES=["authentication","authorization","input_validation","csrf","sanitization","secret_handling"],SECURITY_CONFIDENCE_VALUES=["low","medium","high"],ONTOLOGY_FINDING_SEVERITY_VALUES=["info","low","medium","high"],IMPORT_TYPE_VALUES=["default","named","namespace","require","sideeffect","type"];function normalizeGraphPath(filePath){return path136.normalize(filePath).replace(/\\/g,"/")}function createEmptyGraph(workspaceRoot){return{schema_version:GRAPH_SCHEMA_VERSION,workspaceRoot:path136.normalize(workspaceRoot),nodes:{},edges:[],metadata:{generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:0,edgeCount:0}}}function updateGraphMetadata(graph){graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length}}init_path_security();var FILE_ROLE_SET=new Set(FILE_ROLE_VALUES),ROUTE_METHOD_SET=new Set(ROUTE_METHOD_VALUES),ROUTE_SOURCE_SET=new Set(ROUTE_SOURCE_VALUES),DATA_OPERATION_SET=new Set(DATA_OPERATION_VALUES),DATA_ACCESS_SET=new Set(DATA_ACCESS_VALUES),SECURITY_KIND_SET=new Set(SECURITY_KIND_VALUES),SECURITY_CONFIDENCE_SET=new Set(SECURITY_CONFIDENCE_VALUES),ONTOLOGY_FINDING_SEVERITY_SET=new Set(ONTOLOGY_FINDING_SEVERITY_VALUES),IMPORT_TYPE_SET=new Set(IMPORT_TYPE_VALUES),ONTOLOGY_NAME_PATTERN=/^[a-z][a-z0-9_]*$/;function validateWorkspace(workspace){if(!workspace||typeof workspace!=="string"||workspace.trim()==="")throw Error("Invalid workspace: must be a non-empty string");if(containsControlChars(workspace))throw Error("Invalid workspace: control characters detected");if(containsPathTraversal(workspace))throw Error("Invalid workspace: path traversal detected")}function validateGraphNode(node){if(!node||typeof node!=="object")throw Error("Invalid node: must be an object");if(!node.filePath||typeof node.filePath!=="string")throw Error("Invalid node: filePath is required");if(!node.filePath.startsWith("/")&&!/^[A-Za-z]:[/\\]/.test(node.filePath))throw Error("Invalid node: filePath must be absolute");if(containsPathTraversal(node.filePath))throw Error("Invalid node: filePath contains path traversal");if(containsControlChars(node.filePath))throw Error("Invalid node: filePath contains control characters");if(!node.moduleName||typeof node.moduleName!=="string")throw Error("Invalid node: moduleName is required");if(node.moduleName.startsWith("/")||node.moduleName.startsWith("\\")||/^[A-Za-z]:[/\\]/.test(node.moduleName))throw Error("Invalid node: moduleName must be relative");if(containsPathTraversal(node.moduleName))throw Error("Invalid node: moduleName contains path traversal");if(containsControlChars(node.moduleName))throw Error("Invalid node: moduleName contains control characters");if(typeof node.language!=="string")throw Error("Invalid node: language is required");if(typeof node.mtime!=="string")throw Error("Invalid node: mtime is required");if(!Array.isArray(node.exports))throw Error("Invalid node: exports must be an array");for(let exp of node.exports){if(typeof exp!=="string")throw Error("Invalid node: exports must be an array of strings");if(containsControlChars(exp)){let preview=exp.slice(0,120);throw Error(`Invalid node: exports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(!Array.isArray(node.imports))throw Error("Invalid node: imports must be an array");for(let imp of node.imports){if(typeof imp!=="string")throw Error("Invalid node: imports must be an array of strings");if(containsControlChars(imp)){let preview=imp.slice(0,120);throw Error(`Invalid node: imports contains control characters (file=${node.filePath}, value="${preview}")`)}}if(node.exportLines!==void 0){if(typeof node.exportLines!=="object"||node.exportLines===null||Array.isArray(node.exportLines))throw Error("Invalid node: exportLines must be an object");for(let[name,line]of Object.entries(node.exportLines)){if(containsControlChars(name))throw Error("Invalid node: exportLines key contains control characters");if(typeof line!=="number"||!Number.isFinite(line)||line<0)throw Error("Invalid node: exportLines values must be non-negative numbers")}}if(node.exportRanges!==void 0){if(typeof node.exportRanges!=="object"||node.exportRanges===null||Array.isArray(node.exportRanges))throw Error("Invalid node: exportRanges must be an object");for(let[name,range]of Object.entries(node.exportRanges)){if(containsControlChars(name))throw Error("Invalid node: exportRanges key contains control characters");if(typeof range!=="object"||range===null||Array.isArray(range))throw Error("Invalid node: exportRanges values must be objects");let r=range;if(typeof r.startLine!=="number"||!Number.isFinite(r.startLine)||!Number.isInteger(r.startLine)||r.startLine<1||typeof r.endLine!=="number"||!Number.isFinite(r.endLine)||!Number.isInteger(r.endLine)||r.endLine<1)throw Error("Invalid node: exportRanges value must have positive integer startLine and endLine (1-based)");if(r.startLine>r.endLine)throw Error("Invalid node: exportRanges value must have startLine <= endLine")}}if(node.ontology!==void 0)validateOntologyStrings(node)}function validateOntologyStrings(node){let ontology=node.ontology;if(!ontology||typeof ontology!=="object")throw Error("Invalid node: ontology must be an object");let values=[...ontology.roles??[],ontology.packageBoundary,...(ontology.routes??[]).flatMap((route)=>[route.method,route.path,route.source]),...(ontology.dataOperations??[]).flatMap((fact)=>[fact.operation,fact.access,fact.entity??"",fact.evidence]),...(ontology.security??[]).flatMap((fact)=>[fact.kind,fact.evidence,fact.confidence]),...(ontology.conventions??[]).flatMap((fact)=>[fact.name,fact.evidence]),...(ontology.findings??[]).flatMap((finding)=>[finding.code,finding.severity,finding.message])];for(let value of values){if(typeof value!=="string")throw Error("Invalid node: ontology contains non-string value");if(containsControlChars(value)){let preview=value.slice(0,120);throw Error(`Invalid node: ontology contains control characters (file=${node.filePath}, value="${preview}")`)}}for(let role of ontology.roles??[])validateAllowedOntologyValue(node,"ontology.roles",role,FILE_ROLE_SET);for(let route of ontology.routes??[])validateAllowedOntologyValue(node,"ontology.routes.method",route.method,ROUTE_METHOD_SET),validateAllowedOntologyValue(node,"ontology.routes.source",route.source,ROUTE_SOURCE_SET);for(let fact of ontology.dataOperations??[])validateAllowedOntologyValue(node,"ontology.dataOperations.operation",fact.operation,DATA_OPERATION_SET),validateAllowedOntologyValue(node,"ontology.dataOperations.access",fact.access,DATA_ACCESS_SET);for(let fact of ontology.security??[])validateAllowedOntologyValue(node,"ontology.security.kind",fact.kind,SECURITY_KIND_SET),validateAllowedOntologyValue(node,"ontology.security.confidence",fact.confidence,SECURITY_CONFIDENCE_SET);for(let finding of ontology.findings??[])validateOntologyName(node,"ontology.findings.code",finding.code),validateAllowedOntologyValue(node,"ontology.findings.severity",finding.severity,ONTOLOGY_FINDING_SEVERITY_SET)}function validateOntologyName(node,field,value){if(ONTOLOGY_NAME_PATTERN.test(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} must be lower_snake_case (file=${node.filePath}, value="${preview}")`)}function validateAllowedOntologyValue(node,field,value,allowed){if(allowed.has(value))return;let preview=value.slice(0,120);throw Error(`Invalid node: ${field} contains invalid value (file=${node.filePath}, value="${preview}")`)}function validateGraphEdge(edge){if(!edge||typeof edge!=="object")throw Error("Invalid edge: must be an object");if(!edge.source||typeof edge.source!=="string")throw Error("Invalid edge: source is required");if(!edge.target||typeof edge.target!=="string")throw Error("Invalid edge: target is required");if(containsPathTraversal(edge.source)||containsPathTraversal(edge.target))throw Error("Invalid edge: path traversal detected");if(containsControlChars(edge.source)||containsControlChars(edge.target))throw Error("Invalid edge: control characters detected");if(!edge.importSpecifier||typeof edge.importSpecifier!=="string")throw Error("Invalid edge: importSpecifier is required");if(containsControlChars(edge.importSpecifier))throw Error("Invalid edge: importSpecifier contains control characters");if(!IMPORT_TYPE_SET.has(edge.importType))throw Error("Invalid edge: importType is invalid");if(edge.importedSymbols!==void 0){if(!Array.isArray(edge.importedSymbols))throw Error("Invalid edge: importedSymbols must be an array");for(let symbol3 of edge.importedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: importedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: importedSymbols contains control characters")}}if(edge.usedSymbols!==void 0){if(!Array.isArray(edge.usedSymbols))throw Error("Invalid edge: usedSymbols must be an array");for(let symbol3 of edge.usedSymbols){if(typeof symbol3!=="string")throw Error("Invalid edge: usedSymbols must be an array of strings");if(containsControlChars(symbol3))throw Error("Invalid edge: usedSymbols contains control characters")}}}var _internals83={safeRealpathSync,extractTSSymbols,extractPythonSymbols,parseFileImports,extractFileOntology,stripComments:stripComments2,computeUsedSymbols,extractFileSymbols},SKIP_DIRECTORIES2=new Set(["node_modules",".git","dist","build","out","coverage",".next",".nuxt",".cache","vendor",".svn",".hg",".svelte-kit"]);function resolveSkipDirectories(excludeDirs){let extras=excludeDirs?.filter((d)=>d.length>0)??[];if(extras.length===0)return SKIP_DIRECTORIES2;return new Set([...SKIP_DIRECTORIES2,...extras])}var SUPPORTED_EXTENSIONS=new Set(LANGUAGE_REGISTRY.getAll().filter((p)=>!p.parserOnly).flatMap((p)=>p.extensions)),DEFAULT_WALK_FILE_CAP=1e4,DEFAULT_WALK_BUDGET_MS=5000,ASYNC_WALK_YIELD_INTERVAL=200,MAX_DIAGNOSTIC_ENTRIES=200,EXTENSION_TO_LANGUAGE={};for(let profile of LANGUAGE_REGISTRY.getAll()){if(profile.parserOnly)continue;for(let ext of profile.extensions)EXTENSION_TO_LANGUAGE[ext]=profile.treeSitter.grammarId}var JS_FAMILY_EXTENSION_TO_LANGUAGE={".js":"javascript",".jsx":"javascript",".mjs":"javascript",".cjs":"javascript",".ts":"typescript",".tsx":"tsx"};function upsertNode(graph,node){validateGraphNode(node);let key=normalizeGraphPath(node.filePath);graph.nodes[key]=node,updateGraphMetadata(graph)}function addEdge(graph,edge){if(validateGraphEdge(edge),!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))graph.edges.push(edge),updateGraphMetadata(graph)}function buildLoopEdgeKey(edge){return`${edge.source}\x00${edge.target}\x00${edge.importSpecifier}`}function appendNodeFast(graph,node){validateGraphNode(node),graph.nodes[normalizeGraphPath(node.filePath)]=node}function appendEdgeFast(graph,edge,seenEdgeKeys){validateGraphEdge(edge);let key=buildLoopEdgeKey(edge);if(seenEdgeKeys.has(key))return;seenEdgeKeys.add(key),graph.edges.push(edge)}function resolveModuleSpecifier(workspaceRoot,sourceFile,specifier){if(containsControlChars(specifier))return null;if(specifier.startsWith("/")||specifier.startsWith("\\"))return null;if(/^[A-Za-z]:[/\\]/.test(specifier))return null;if(specifier.startsWith("http://")||specifier.startsWith("https://"))return null;try{if(specifier.startsWith(".")){let sourceDir=path137.dirname(sourceFile),resolved=path137.resolve(sourceDir,specifier),initialRealResolved=_internals83.safeRealpathSync(resolved,resolved);if(initialRealResolved===null)return null;let realResolved=initialRealResolved,realRoot=_internals83.safeRealpathSync(workspaceRoot,path137.normalize(workspaceRoot));if(realRoot===null)return null;if(!existsSync77(resolved)){let EXTENSIONS=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".json"],found=null;for(let ext of EXTENSIONS){let candidate=resolved+ext;if(existsSync77(candidate)){found=candidate;break}}if(found){let foundRealPath=_internals83.safeRealpathSync(found,found);if(foundRealPath===null)return null;realResolved=foundRealPath,resolved=found}else return null}let normalizedResolved=path137.normalize(realResolved),normalizedRoot=path137.normalize(realRoot);if(!normalizedResolved.startsWith(normalizedRoot+path137.sep)&&normalizedResolved!==normalizedRoot)return null;return resolved}return null}catch{return null}}function isRefusedWorkspaceRoot(target){let resolved;try{resolved=realpathSync15(target)}catch{resolved=path137.resolve(target)}let refused=new Set,add2=(p)=>{if(typeof p==="string"&&p.length>0)refused.add(path137.resolve(p))};if(add2(os20.homedir()),add2(os20.tmpdir()),add2("/"),add2("/Users"),add2("/home"),add2("/root"),process.platform==="win32")add2("C:\\"),add2("C:\\Users");return refused.has(resolved)}function createEmptyDiagnostics(){return{extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],lowConfidenceEdgeCount:0}}function diagnosticsHaveEntries(diagnostics){return(diagnostics.extractionFailures?.length??0)>0||(diagnostics.unresolvedImports?.length??0)>0||(diagnostics.oversizedFiles?.length??0)>0||(diagnostics.unsupportedFiles?.length??0)>0||(diagnostics.binaryFiles?.length??0)>0||(diagnostics.unreadableFiles?.length??0)>0||(diagnostics.lowConfidenceEdgeCount??0)>0}function pushCapped(target,value){if(target.length<MAX_DIAGNOSTIC_ENTRIES)target.push(value)}function mergeDiagnostics(target,source){if(!source)return;for(let entry of source.extractionFailures??[])pushCapped(target.extractionFailures,entry);for(let entry of source.unresolvedImports??[])pushCapped(target.unresolvedImports,entry);for(let entry of source.oversizedFiles??[])pushCapped(target.oversizedFiles,entry);for(let entry of source.unsupportedFiles??[])pushCapped(target.unsupportedFiles,entry);for(let entry of source.binaryFiles??[])pushCapped(target.binaryFiles,entry);for(let entry of source.unreadableFiles??[])pushCapped(target.unreadableFiles,entry);target.lowConfidenceEdgeCount+=source.lowConfidenceEdgeCount??0}function isRelativeImportSpecifier(specifier){return specifier==="."||specifier===".."||specifier.startsWith("./")||specifier.startsWith("../")}function unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot){let unresolved=[],moduleName=toModuleName(filePath,absoluteRoot);for(let parsed of parsedImports){if(!isRelativeImportSpecifier(parsed.specifier))continue;if(resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier)===null)unresolved.push({file:moduleName,specifier:parsed.specifier})}return unresolved}var REGEX_ALLOWED_AFTER=new Set("(,=:[!&|?{};*+-~^<>%".split(""));function stripComments2(content){let out="",i=0,n=content.length,state="code",prevSignificant="",regexInClass=!1;while(i<n){let ch=content[i],next=i+1<n?content[i+1]:"";switch(state){case"code":if(ch==="/"&&next==="/")state="line",i+=2;else if(ch==="/"&&next==="*")state="block",i+=2;else if(ch==="/"&®EX_ALLOWED_AFTER.has(prevSignificant))state="regex",regexInClass=!1,out+=ch,i+=1;else{if(ch==="'")state="single";else if(ch==='"')state="double";else if(ch==="`")state="template";if(out+=ch,ch.trim()!=="")prevSignificant=ch;i+=1}break;case"single":case"double":case"template":{let quote=state==="single"?"'":state==="double"?'"':"`";if(ch==="\\")out+=ch+next,i+=2;else{if(ch===quote)state="code",prevSignificant=quote;out+=ch,i+=1}break}case"regex":if(ch==="\\")out+=ch+next,i+=2;else if(ch===`
|
|
5317
5317
|
`)state="code",out+=ch,i+=1;else{if(ch==="[")regexInClass=!0;else if(ch==="]")regexInClass=!1;else if(ch==="/"&&!regexInClass)state="code",prevSignificant="/";out+=ch,i+=1}break;case"line":if(ch===`
|
|
5318
5318
|
`)state="code",out+=ch;i+=1;break;case"block":if(ch==="*"&&next==="/")state="code",i+=2;else{if(ch===`
|
|
5319
|
-
`)out+=ch;i+=1}break}}return out}function parseFileImports(rawContent){let imports=[],content=stripComments2(rawContent),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s+['"`]([^'"`\0\t\r\n]+)['"`]|require\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)|export\s*\{[^}]*\}\s*from\s+['"`]([^'"`\0\t\r\n]+)['"`]|export\s+\*(?:\s+as\s+\w+)?\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)/g;for(let match of content.matchAll(importRegex)){let modulePath=match[1]||match[2]||match[3]||match[4]||match[5]||match[6];if(!modulePath)continue;if(containsControlChars(modulePath))continue;let matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s*\(/.test(matchedString))importType="sideeffect";else if(/^export\s*\{/.test(matchedString))importType="named";else if(/^export\s+\*/.test(matchedString))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";imports.push({specifier:modulePath,importType,importedSymbols:parseImportedSymbols(matchedString,importType),bindings:parseImportBindings(matchedString,importType),reExport:/^\s*export\b/.test(matchedString)})}return imports}function parseImportBindings(matchedString,importType){if(importType==="namespace")return[];if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/);return defaultMatch?[{imported:"default",local:defaultMatch[1]}]:[]}if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let bindings=[],seen=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim().replace(/^type\s+/,"");if(!part)continue;let aliasSplit=part.split(/\s+as\s+/i),imported=aliasSplit[0].trim(),local=(aliasSplit[1]??aliasSplit[0]).trim();if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(local))continue;if(seen.has(imported))continue;seen.add(imported),bindings.push({imported,local})}return bindings}var SAFE_USAGE_IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;function computeUsedSymbols(strippedContent,bindings){if(bindings.length===0)return[];let used=new Set;for(let binding of bindings){if(!SAFE_USAGE_IDENTIFIER.test(binding.local)){used.add(binding.imported);continue}let re=new RegExp(`\\b${binding.local}\\b`,"g"),count=0;for(let _match of strippedContent.matchAll(re))if(count++,count>1)break;if(count>1)used.add(binding.imported)}return[...used].sort((a,b)=>a.localeCompare(b))}function usedSymbolsForImport(parsed,strippedContent){if(parsed.importType==="namespace"||parsed.importType==="sideeffect"||parsed.importType==="require")return;if(parsed.reExport)return[...new Set(parsed.bindings.map((b)=>b.imported))].sort((a,b)=>a.localeCompare(b));return computeUsedSymbols(strippedContent,parsed.bindings)}function collectExports(symbols2){let exported=symbols2.filter((s)=>s.exported),exports=exported.map((s)=>s.signature===`default ${s.name}`?"default":s.name),exportLines={};for(let i=0;i<exported.length;i++){let s=exported[i],name=exports[i];if(typeof s.line==="number"&&Number.isFinite(s.line)&&exportLines[name]===void 0)exportLines[name]=s.line}return{exports,exportLines}}function parseImportedSymbols(matchedString,importType){if(importType==="namespace")return["*"];if(importType==="default")return matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/)?["default"]:[];if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let symbols2=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim();if(!part)continue;let cleaned=part.replace(/^type\s+/,"").split(/\s+as\s+/i)[0].trim();if(/^[A-Za-z_$][\w$]*$/.test(cleaned))symbols2.add(cleaned)}return[...symbols2].sort((a,b)=>a.localeCompare(b))}function isWalkBudgetExceeded(ctx){if(ctx.abortReason!==void 0)return!0;if(Date.now()-ctx.startedAt>ctx.walkBudgetMs)return ctx.abortReason="budget",!0;return!1}function isFileCapReached(ctx,filesLength){if(filesLength>=ctx.maxFiles)return ctx.abortReason="cap",!0;return!1}async function canonicalDirKeyAsync(dir){try{return await fsPromises5.realpath(dir)}catch{return null}}async function findSourceFilesAsync(dir,stats2,options){let ctx={stats:stats2,seenRealPaths:new Set,startedAt:Date.now(),walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,maxFiles:options?.maxFiles??DEFAULT_WALK_FILE_CAP,followSymlinks:options?.followSymlinks??!1,skipDirs:resolveSkipDirectories(options?.excludeDirs)},files=[],queue=[dir],processed=0;while(queue.length>0){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;let current=queue.shift(),key=await canonicalDirKeyAsync(current);if(key!==null){if(ctx.seenRealPaths.has(key)){ctx.stats.skippedDirs++;continue}ctx.seenRealPaths.add(key)}let entries;try{entries=await fsPromises5.readdir(current,{withFileTypes:!0})}catch{continue}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));for(let entry of entries){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;if(ctx.skipDirs.has(entry.name)){ctx.stats.skippedDirs++;continue}let fullPath=path137.join(current,entry.name);if(entry.isSymbolicLink()&&!ctx.followSymlinks){ctx.stats.skippedDirs++;continue}if(entry.isDirectory())queue.push(fullPath);else if(entry.isFile()){let ext=path137.extname(fullPath).toLowerCase();if(SUPPORTED_EXTENSIONS.has(ext))files.push(fullPath)}if(processed++,processed%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}}if(ctx.abortReason==="cap"||ctx.abortReason==="budget")ctx.stats.truncated=!0;return files}function toModuleName(filePath,workspaceRoot){return path137.relative(workspaceRoot,filePath).split(path137.sep).join("/")}function getLanguage(filePath){let ext=path137.extname(filePath).toLowerCase();return EXTENSION_TO_LANGUAGE[ext]??"unknown"}function isBinaryContent(content){if(content.includes("\x00"))return!0;return!1}function scanFile(filePath,absoluteRoot,maxFileSize){let content,fileStats;try{if(fileStats=fsSync8.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[]};content=fsSync8.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[]}}if(isBinaryContent(content))return{node:null,edges:[]};let ext=path137.extname(filePath).toLowerCase(),exports=[],exportLines={};try{if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(ext)){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractTSSymbols(relativePath,absoluteRoot)))}else if(ext===".py"){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractPythonSymbols(relativePath,absoluteRoot)))}let parsedImports=_internals83.parseFileImports(content),strippedForUsage=parsedImports.length>0?_internals83.stripComments(content):"",moduleName=toModuleName(filePath,absoluteRoot),node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},imports:parsedImports.map((p)=>p.specifier),language:getLanguage(filePath),mtime:fileStats.mtime.toISOString(),ontology:_internals83.extractFileOntology({moduleName,filePath,content,language:getLanguage(filePath),exports,imports:parsedImports.map((p)=>p.specifier)})},edges=[],sortedImports=[...parsedImports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let parsed of sortedImports){let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier);if(resolvedTarget!==null){let usedSymbols=usedSymbolsForImport(parsed,strippedForUsage);edges.push({source:filePath,target:resolvedTarget,importSpecifier:parsed.specifier,importType:parsed.importType,importedSymbols:parsed.importedSymbols,...usedSymbols!==void 0?{usedSymbols}:{}})}}return{node,edges}}catch{return{node:null,edges:[]}}}async function scanFileAsync(filePath,absoluteRoot,maxFileSize){let content,fileStats;try{if(fileStats=fsSync8.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[],symbolEdges:[],diagnostics:{oversizedFiles:[toModuleName(filePath,absoluteRoot)]}};content=fsSync8.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[],symbolEdges:[],diagnostics:{unreadableFiles:[toModuleName(filePath,absoluteRoot)]}}}if(isBinaryContent(content))return{node:null,edges:[],symbolEdges:[],diagnostics:{binaryFiles:[toModuleName(filePath,absoluteRoot)]}};let grammarId=getLanguage(filePath),facts=await _internals83.extractFileSymbols(grammarId,content);if(facts===null){let fallback=scanFile(filePath,absoluteRoot,maxFileSize),parsedImports=[];try{parsedImports=_internals83.parseFileImports(content)}catch{parsedImports=[]}return{...fallback,symbolEdges:[],diagnostics:{extractionFailures:[{file:toModuleName(filePath,absoluteRoot),language:grammarId,reason:"symbol_extraction_failed"}],unresolvedImports:unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot)}}}let exportedDefs=facts.defs.filter((d)=>d.exported),exports=exportedDefs.map((d)=>d.name),exportLines={},exportRanges={};for(let d of exportedDefs)exportLines[d.name]=d.startLine,exportRanges[d.name]={startLine:d.startLine,endLine:d.endLine};let imports=facts.imports.map((i)=>i.specifier),moduleName=toModuleName(filePath,absoluteRoot),language=grammarId,node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},...Object.keys(exportRanges).length>0?{exportRanges}:{},imports,language,mtime:fileStats.mtime.toISOString(),ontology:_internals83.extractFileOntology({moduleName,filePath,content,language,exports,imports})},edges=[],sortedImports=[...facts.imports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let imp of sortedImports){let edgeImportType=imp.importType==="commonjs"?"require":imp.importType,resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(resolvedTarget!==null){let usedBindings=imp.bindings.filter((b)=>facts.refs.some((r)=>r.identifier===b.local)),usedSymbols=edgeImportType!=="namespace"&&edgeImportType!=="require"?usedBindings.map((b)=>b.imported):void 0;edges.push({source:filePath,target:resolvedTarget,importSpecifier:imp.specifier,importType:edgeImportType,importedSymbols:imp.bindings.map((b)=>b.imported),...usedSymbols!==void 0?{usedSymbols}:{}})}}let unresolvedImports=sortedImports.filter((imp)=>isRelativeImportSpecifier(imp.specifier)).filter((imp)=>resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier)===null).map((imp)=>({file:moduleName,specifier:imp.specifier})),symbolEdges=[],localToImported=new Map;for(let imp of facts.imports)for(let binding of imp.bindings)localToImported.set(binding.local,{specifier:imp.specifier,imported:binding.imported});let seenSymbolEdgeKeys=new Set;for(let ref of facts.refs){let mapping=localToImported.get(ref.identifier);if(!mapping)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,mapping.specifier);if(!resolvedTarget)continue;let fromSymbol=ref.enclosingDecl??"<module>",key=filePath+"\x00"+fromSymbol+"\x00"+resolvedTarget+"\x00"+mapping.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol,toFile:resolvedTarget,toSymbol:mapping.imported})}return{node,edges,symbolEdges,diagnostics:unresolvedImports.length>0?{unresolvedImports}:void 0}}async function buildWorkspaceGraphAsync(workspaceRoot,options){validateWorkspace(workspaceRoot);let maxFileSize=options?.maxFileSizeBytes??1048576,maxFiles=options?.maxFiles??DEFAULT_WALK_FILE_CAP,walkBudgetMs=options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,followSymlinks=options?.followSymlinks??!1,absoluteRoot=path137.resolve(workspaceRoot);if(!existsSync77(absoluteRoot))throw Error(`Workspace directory does not exist: ${workspaceRoot}`);if(isRefusedWorkspaceRoot(absoluteRoot))throw Error(`Refusing to scan top-level system path as workspace: ${absoluteRoot}. Set workspaceRoot to a project directory.`);let graph=createEmptyGraph(workspaceRoot),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1},diagnostics=createEmptyDiagnostics(),sourceFiles=await findSourceFilesAsync(absoluteRoot,stats2,{walkBudgetMs,maxFiles,followSymlinks,excludeDirs:options?.excludeDirs});if(sourceFiles.sort((a,b)=>{let normA=normalizeGraphPath(a),normB=normalizeGraphPath(b);return normA.localeCompare(normB)}),stats2.truncated)warn(`[repo-graph] Walk truncated: collected ${sourceFiles.length} files within ${walkBudgetMs}ms / ${maxFiles}-file budget.`);let seenEdges=new Set,seenSymbolEdges=new Set,allSymbolEdges=[],processedSinceYield=0;for(let filePath of sourceFiles){let result=await scanFileAsync(filePath,absoluteRoot,maxFileSize);if(mergeDiagnostics(diagnostics,result.diagnostics),result.node){let appended=!1;try{appendNodeFast(graph,result.node),appended=!0}catch{stats2.skippedFiles++}if(appended){for(let edge of result.edges)try{appendEdgeFast(graph,edge,seenEdges)}catch{}for(let symbolEdge of result.symbolEdges){let key=symbolEdge.fromFile+"\x00"+symbolEdge.fromSymbol+"\x00"+symbolEdge.toFile+"\x00"+symbolEdge.toSymbol;if(!seenSymbolEdges.has(key))seenSymbolEdges.add(key),allSymbolEdges.push(symbolEdge)}stats2.filesScanned++}}else stats2.skippedFiles++;if(processedSinceYield++,processedSinceYield%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}if(graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length},allSymbolEdges.length>0)graph.symbolEdges=allSymbolEdges;if(graph.diagnostics=diagnosticsHaveEntries(diagnostics)?diagnostics:createEmptyDiagnostics(),stats2.skippedFiles>0||stats2.skippedDirs>0||stats2.truncated)log(`[repo-graph] Scan stats: ${stats2.filesScanned} files scanned, ${stats2.skippedFiles} files skipped, ${stats2.skippedDirs} dirs skipped`+(stats2.truncated?", TRUNCATED":""));return graph}import*as path138 from"node:path";var graphCache=new Map,dirtyFlags=new Map,mtimeCache=new Map;function getCachedGraph(workspace){return graphCache.get(path138.normalize(workspace))}function setCachedGraph(workspace,graph,mtime){let normalized=path138.normalize(workspace);if(graphCache.set(normalized,graph),dirtyFlags.set(normalized,!1),mtime!==void 0)mtimeCache.set(normalized,mtime)}function isDirty(workspace){return dirtyFlags.get(path138.normalize(workspace))??!1}function clearCache(workspace){let normalized=path138.normalize(workspace);graphCache.delete(normalized),dirtyFlags.delete(normalized),mtimeCache.delete(normalized)}function getCachedMtime(workspace){return mtimeCache.get(path138.normalize(workspace))}init_logger();init_path_security();import{existsSync as existsSync79}from"node:fs";import*as fsPromises7 from"node:fs/promises";import*as path141 from"node:path";init_path_security();import*as fsSync9 from"node:fs";import*as path139 from"node:path";var GRAPH_HEALTH_OUTPUT_LIMIT=50,MAX_HEALTH_PATH_LENGTH=500,cachedReverseIndex=null;function normalizeLookupPath(input){return normalizeGraphPath(input).replace(/^(?:\.\/)+/,"")}function graphRoot(graph){return path139.resolve(graph.workspaceRoot)}function toModuleName2(graph,input){let normalized=normalizeLookupPath(input);if(path139.isAbsolute(normalized)||/^[A-Za-z]:\//.test(normalized))return normalizeLookupPath(path139.relative(graphRoot(graph),normalized));return normalized}function absoluteKeyForModule(graph,moduleName){return normalizeGraphPath(path139.resolve(graphRoot(graph),moduleName))}function getGraphNode(graph,input){let moduleName=toModuleName2(graph,input),direct=graph.nodes[absoluteKeyForModule(graph,moduleName)];if(direct)return direct;return getQueryIndexes(graph).moduleNameIndex.get(moduleName)}function moduleNameForEdgePath(graph,edgePath){let key=normalizeGraphPath(edgePath),node=graph.nodes[key];if(node)return normalizeLookupPath(node.moduleName);return normalizeLookupPath(path139.relative(graphRoot(graph),edgePath))}function buildReverseIndex(graph){let reverse=new Map,forward=new Map,moduleNameIndex=new Map;for(let node of Object.values(graph.nodes))moduleNameIndex.set(normalizeLookupPath(node.moduleName),node);for(let edge of graph.edges){let source=normalizeGraphPath(edge.source),target=normalizeGraphPath(edge.target),sourceRef={file:moduleNameForEdgePath(graph,edge.source),importType:edge.importType},targetRef={file:moduleNameForEdgePath(graph,edge.target),importType:edge.importType},reverseRefs=reverse.get(target);if(reverseRefs)reverseRefs.push(sourceRef);else reverse.set(target,[sourceRef]);let forwardRefs=forward.get(source);if(forwardRefs)forwardRefs.push(targetRef);else forward.set(source,[targetRef])}for(let refs of reverse.values())refs.sort((a,b)=>a.file.localeCompare(b.file));for(let refs of forward.values())refs.sort((a,b)=>a.file.localeCompare(b.file));return cachedReverseIndex={graph,index:reverse,forwardIndex:forward,moduleNameIndex},reverse}function getQueryIndexes(graph){if(cachedReverseIndex&&cachedReverseIndex.graph===graph)return cachedReverseIndex;return buildReverseIndex(graph),cachedReverseIndex}function getReverseIndex(graph){return getQueryIndexes(graph).index}function getForwardIndex(graph){return getQueryIndexes(graph).forwardIndex}function resetQueryCache(){cachedReverseIndex=null}function isGraphFresh(graph,maxAgeMs=300000){if(!graph)return!1;let built=Date.parse(graph.metadata?.generatedAt??"");if(!Number.isFinite(built))return!1;return Date.now()-built<=maxAgeMs}function isSafeHealthPath(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value)||containsPathTraversal(value))return!1;if(path139.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value))return!1;return!0}function isSafeHealthText(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value))return!1;return!0}function cap(entries){return entries.slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function sanitizeExtractionFailures(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.language)&&isSafeHealthText(entry.reason))entries.push({file:entry.file,language:entry.language,reason:entry.reason})}return cap(entries)}function sanitizeUnresolvedImports(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.specifier))entries.push({file:entry.file,specifier:entry.specifier})}return cap(entries)}function sanitizePathList(value){if(!Array.isArray(value))return[];return cap(value.filter(isSafeHealthPath))}function getStaleFiles(graph,workspaceRoot){let built=Date.parse(graph.metadata.generatedAt);if(!Number.isFinite(built))return[];let root=workspaceRoot??graph.workspaceRoot,stale=[];for(let node of Object.values(graph.nodes)){let moduleName=normalizeGraphPath(node.moduleName);if(!isSafeHealthPath(moduleName))continue;let filePath=path139.join(root,moduleName);try{if(fsSync9.statSync(filePath).mtimeMs>built){if(stale.push(moduleName),stale.length>=GRAPH_HEALTH_OUTPUT_LIMIT)break}}catch{}}return stale}function getGraphHealth(graph,workspaceRoot){if(!graph)return{schemaVersion:null,fresh:!1,staleFiles:[],extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],lowConfidenceEdgeCount:0,notes:['No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.']};let diagnostics=graph.diagnostics,fresh=isGraphFresh(graph),staleFiles=getStaleFiles(graph,workspaceRoot),notes=[];if(!fresh||staleFiles.length>0)notes.push('Graph is stale. Run repo_map with action="build" to refresh.');if(!diagnostics)notes.push('Graph has no recorded diagnostics. Rebuild with repo_map action="build" to collect health details.');let binaryFiles=sanitizePathList(diagnostics?.binaryFiles),binaryCount=binaryFiles.length;if(binaryCount>0)notes.push(`${binaryCount} binary files skipped during last build.`);let unreadableFiles=sanitizePathList(diagnostics?.unreadableFiles),unreadableCount=unreadableFiles.length;if(unreadableCount>0)notes.push(`${unreadableCount} unreadable files skipped during last build.`);return{schemaVersion:graph.schema_version,fresh,staleFiles,extractionFailures:sanitizeExtractionFailures(diagnostics?.extractionFailures),unresolvedImports:sanitizeUnresolvedImports(diagnostics?.unresolvedImports),oversizedFiles:sanitizePathList(diagnostics?.oversizedFiles),unsupportedFiles:sanitizePathList(diagnostics?.unsupportedFiles),binaryFiles,unreadableFiles,lowConfidenceEdgeCount:typeof diagnostics?.lowConfidenceEdgeCount==="number"&&Number.isFinite(diagnostics.lowConfidenceEdgeCount)&&diagnostics.lowConfidenceEdgeCount>0?Math.floor(diagnostics.lowConfidenceEdgeCount):0,notes}}function getImporters(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];return getReverseIndex(graph).get(normalizeGraphPath(node.filePath))??[]}function getDependencies(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];let sourceKey=normalizeGraphPath(node.filePath);return getForwardIndex(graph).get(sourceKey)??[]}function getSymbolConsumers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[];for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;let importedSymbols=edge.importedSymbols??[];if(edge.importType==="namespace"){refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:"*"});continue}if(importedSymbols.includes(symbolName))refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:symbolName})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getCallers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[],seen=new Set;for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;let file3=moduleNameForEdgePath(graph,edge.source);if(seen.has(file3))continue;if(edge.usedSymbols!==void 0){if(edge.usedSymbols.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"used"});continue}let imported=edge.importedSymbols??[];if(edge.importType==="namespace"||imported.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"imported"})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}var DEAD_EXPORT_EXCLUDED_ROLES=new Set(["api_route","cli_command","test_file","agent","hook","middleware"]);function getDeadExports(graph,options){if(!isSchemaVersionAtLeast(graph.schema_version,"1.1.0"))return{schemaSupported:!1,analyzedFiles:0,skippedUnresolvable:0,candidates:[],note:'Graph predates schema 1.1.0 (no usedSymbols data). Run repo_map action="build" to enable dead_exports.'};let usage=new Map;for(let edge of graph.edges){let target=normalizeGraphPath(edge.target),entry=usage.get(target);if(!entry)entry={used:new Set,unresolvable:!1},usage.set(target,entry);if(edge.importType==="namespace"||edge.importType==="sideeffect"||edge.importType==="require")entry.unresolvable=!0;else if(edge.usedSymbols)for(let symbol3 of edge.usedSymbols)entry.used.add(symbol3)}let reverse=getReverseIndex(graph),candidates=[],analyzedFiles=0,skippedUnresolvable=0;for(let node of Object.values(graph.nodes)){if(node.exports.length===0)continue;let key=normalizeGraphPath(node.filePath),importerCount=reverse.get(key)?.length??0;if(importerCount===0)continue;if((node.ontology?.roles??[]).some((r)=>DEAD_EXPORT_EXCLUDED_ROLES.has(r)))continue;let entry=usage.get(key);if(entry?.unresolvable){skippedUnresolvable++;continue}analyzedFiles++;let used=entry?.used??new Set;for(let symbol3 of node.exports){if(symbol3==="default")continue;if(used.has(symbol3))continue;candidates.push({file:node.moduleName,symbol:symbol3,line:node.exportLines?.[symbol3],importerCount})}}candidates.sort((a,b)=>a.file.localeCompare(b.file)||a.symbol.localeCompare(b.symbol));let limit=options?.maxCandidates??100,truncated=candidates.length>limit;return{schemaSupported:!0,analyzedFiles,skippedUnresolvable,candidates:candidates.slice(0,limit),note:"Advisory: exported symbols with no detected in-repo reference, limited to files imported by >=1 other file. Regex analysis cannot see dynamic dispatch, string-keyed access, or namespace/barrel re-export usage; verify before removing."+(truncated?` Showing ${limit} of ${candidates.length}.`:"")}}function getBlastRadius(graph,filePaths,maxDepth=3){let targetNodes=filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0),targets=targetNodes.map((node)=>normalizeLookupPath(node.moduleName));if(maxDepth<=0||targetNodes.length===0)return{target:filePaths.map((filePath)=>toModuleName2(graph,filePath)),directDependents:[],transitiveDependents:[],depthReached:0,totalDependents:0,riskLevel:"low"};let reverse=getReverseIndex(graph),visited=new Set(targetNodes.map((node)=>normalizeGraphPath(node.filePath))),direct=new Set,transitive=new Set,depthReached=0,queue=targetNodes.map((node)=>({key:normalizeGraphPath(node.filePath),depth:0}));while(queue.length>0){let next=[];for(let{key,depth}of queue){let importers=reverse.get(key)??[];for(let ref of importers){let importerNode=getGraphNode(graph,ref.file);if(!importerNode)continue;let importerKey=normalizeGraphPath(importerNode.filePath);if(visited.has(importerKey))continue;if(visited.add(importerKey),depth===0)direct.add(ref.file);else transitive.add(ref.file);if(depthReached=Math.max(depthReached,depth+1),depth+1<maxDepth)next.push({key:importerKey,depth:depth+1})}}queue=next}let totalDependents=direct.size+transitive.size;return{target:targets,directDependents:[...direct].sort(),transitiveDependents:[...transitive].sort(),depthReached,totalDependents,riskLevel:classifyRisk(totalDependents)}}function classifyRisk(count){if(count<=3)return"low";if(count<=10)return"medium";if(count<=25)return"high";return"critical"}function getKeyFiles(graph,topN=10){let reverse=getReverseIndex(graph),scored=Object.values(graph.nodes).map((node)=>({node,inDegree:reverse.get(normalizeGraphPath(node.filePath))?.length??0}));return scored.sort((a,b)=>{if(b.inDegree!==a.inDegree)return b.inDegree-a.inDegree;return a.node.moduleName.localeCompare(b.node.moduleName)}),scored.slice(0,topN).map((item)=>item.node)}function getFileOntology(graph,filePath){return getGraphNode(graph,filePath)?.ontology??null}function getLocalizationContext(graph,filePath,options={}){let target=toModuleName2(graph,filePath),node=getGraphNode(graph,target),importers=getImporters(graph,target),dependencies=getDependencies(graph,target),blast=getBlastRadius(graph,[target],options.maxDepth??2),externalSymbols=collectExternallyUsedSymbols(graph,node),summary=formatLocalizationSummary({target,importers,dependencies,blast,externalSymbols,ontology:node?.ontology??null,maxImporters:options.maxImporters??5,maxDeps:options.maxDeps??5});return{target,importerCount:importers.length,importers:importers.slice(0,options.maxImporters??5),dependencyCount:dependencies.length,dependencies:dependencies.slice(0,options.maxDeps??5),exportedSymbolsUsedExternally:externalSymbols,blastRadius:blast,summary}}function getContextPack(graph,file3,symbol3,options={}){if(!isSchemaVersionAtLeast(graph.schema_version,"1.2.0"))return{schemaSupported:!1,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:'rebuild with repo_map action="build"'};let maxDepth=options.maxDepth??2,maxTokens=options.maxTokens??4000,targetNode=getGraphNode(graph,file3);if(!targetNode)return{schemaSupported:!0,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:"Target file not found in graph"};let targetFile=normalizeGraphPath(targetNode.filePath),forward=new Map,reverse=new Map,symbolEdges=graph.symbolEdges??[];for(let edge of symbolEdges){let fromKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`,toKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`,fromEdges=forward.get(fromKey);if(fromEdges)fromEdges.push(edge);else forward.set(fromKey,[edge]);let toEdges=reverse.get(toKey);if(toEdges)toEdges.push(edge);else reverse.set(toKey,[edge])}let targetKey=`${targetFile}\x00${symbol3}`,visited=new Map,queue=[{key:targetKey,depth:0}];visited.set(targetKey,0);let reached=[],queueHead=0;while(queueHead<queue.length){let{key,depth}=queue[queueHead];queueHead++;let[curFile,curSymbol]=key.split("\x00",2);if(reached.push({file:curFile,symbol:curSymbol,depth}),depth>=maxDepth)continue;let outEdges=forward.get(key)??[];for(let edge of outEdges){let nextKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}let inEdges=reverse.get(key)??[];for(let edge of inEdges){let nextKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}}let TOKENS_PER_LINE=12,TOKENS_PER_SIGNATURE=10,spansWithDepth=[];for(let{file:symFile,symbol:sym,depth:d}of reached){let range=graph.nodes[symFile]?.exportRanges?.[sym];if(!range)continue;let mode=d===0?"full":d<maxDepth?"full":"signature";spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:range.startLine,endLine:range.endLine,mode},depth:d})}spansWithDepth.sort((a,b)=>{let aIsTarget=a.span.file===targetFile&&a.span.symbol===symbol3?0:1,bIsTarget=b.span.file===targetFile&&b.span.symbol===symbol3?0:1;if(aIsTarget!==bIsTarget)return aIsTarget-bIsTarget;if(a.depth!==b.depth)return a.depth-b.depth;let fileCmp=a.span.file.localeCompare(b.span.file);if(fileCmp!==0)return fileCmp;return a.span.symbol.localeCompare(b.span.symbol)});let estimatedTokens=0,finalSpans=[],truncated=!1;for(let{span}of spansWithDepth){let spanTokens=span.mode==="full"?(span.endLine-span.startLine+1)*TOKENS_PER_LINE:TOKENS_PER_SIGNATURE;if(finalSpans.length>0&&estimatedTokens+spanTokens>maxTokens){truncated=!0;break}finalSpans.push(span),estimatedTokens+=spanTokens}return{schemaSupported:!0,target:{file:targetFile,symbol:symbol3},spans:finalSpans,truncated,estimatedTokens}}function collectExternallyUsedSymbols(graph,node){if(!node)return[];let exported=new Set(node.exports),used=new Set,targetKey=normalizeGraphPath(node.filePath);for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;for(let symbol3 of edge.importedSymbols??[])if(exported.has(symbol3))used.add(symbol3)}return[...used].sort((a,b)=>a.localeCompare(b))}function formatLocalizationSummary(opts){let importerList=opts.importers.length===0?"(none)":opts.importers.slice(0,opts.maxImporters).map((ref)=>ref.file).join(", ")+(opts.importers.length>opts.maxImporters?`, +${opts.importers.length-opts.maxImporters} more`:""),depList=opts.dependencies.length===0?"(none)":opts.dependencies.slice(0,opts.maxDeps).map((ref)=>ref.file).join(", ")+(opts.dependencies.length>opts.maxDeps?`, +${opts.dependencies.length-opts.maxDeps} more`:""),symbolList=opts.externalSymbols.length===0?"(none used externally)":opts.externalSymbols.slice(0,8).join(", ")+(opts.externalSymbols.length>8?`, +${opts.externalSymbols.length-8} more`:""),roles=opts.ontology?.roles.join(", ")||"unknown",findings=opts.ontology?.findings.length??0;return["LOCALIZATION CONTEXT",` Target: ${opts.target}`,` Roles: ${roles}`,` Imported by (${opts.importers.length}): ${importerList}`,` Imports (${opts.dependencies.length}): ${depList}`,` Exports used externally: ${symbolList}`,` Blast radius: ${opts.blast.totalDependents} files (${opts.blast.riskLevel} risk)`,` Ontology findings: ${findings}`].join(`
|
|
5319
|
+
`)out+=ch;i+=1}break}}return out}function parseFileImports(rawContent){let imports=[],content=stripComments2(rawContent),importRegex=/import\s+(?:\{[\s\S]*?\}|(?:\*\s+as\s+\w+)|\w+)\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s+['"`]([^'"`\0\t\r\n]+)['"`]|require\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)|export\s*\{[^}]*\}\s*from\s+['"`]([^'"`\0\t\r\n]+)['"`]|export\s+\*(?:\s+as\s+\w+)?\s+from\s+['"`]([^'"`\0\t\r\n]+)['"`]|import\s*\(\s*['"`]([^'"`\0\t\r\n]+)['"`]\s*\)/g;for(let match of content.matchAll(importRegex)){let modulePath=match[1]||match[2]||match[3]||match[4]||match[5]||match[6];if(!modulePath)continue;if(containsControlChars(modulePath))continue;let matchedString=match[0],importType="named";if(matchedString.includes("* as"))importType="namespace";else if(/^import\s*\(/.test(matchedString))importType="sideeffect";else if(/^export\s*\{/.test(matchedString))importType="named";else if(/^export\s+\*/.test(matchedString))importType="namespace";else if(/^import\s+\{/.test(matchedString))importType="named";else if(/^import\s+\w+\s+from\s+['"`]/.test(matchedString))importType="default";else if(/^import\s+['"`]/m.test(matchedString))importType="sideeffect";else if(matchedString.includes("require("))importType="require";imports.push({specifier:modulePath,importType,importedSymbols:parseImportedSymbols(matchedString,importType),bindings:parseImportBindings(matchedString,importType),reExport:/^\s*export\b/.test(matchedString)})}return imports}function parseImportBindings(matchedString,importType){if(importType==="namespace")return[];if(importType==="default"){let defaultMatch=matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/);return defaultMatch?[{imported:"default",local:defaultMatch[1]}]:[]}if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let bindings=[],seen=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim().replace(/^type\s+/,"");if(!part)continue;let aliasSplit=part.split(/\s+as\s+/i),imported=aliasSplit[0].trim(),local=(aliasSplit[1]??aliasSplit[0]).trim();if(!/^[A-Za-z_$][\w$]*$/.test(imported))continue;if(!/^[A-Za-z_$][\w$]*$/.test(local))continue;if(seen.has(imported))continue;seen.add(imported),bindings.push({imported,local})}return bindings}var SAFE_USAGE_IDENTIFIER=/^[A-Za-z_][A-Za-z0-9_]*$/;function computeUsedSymbols(strippedContent,bindings){if(bindings.length===0)return[];let used=new Set;for(let binding of bindings){if(!SAFE_USAGE_IDENTIFIER.test(binding.local)){used.add(binding.imported);continue}let re=new RegExp(`\\b${binding.local}\\b`,"g"),count=0;for(let _match of strippedContent.matchAll(re))if(count++,count>1)break;if(count>1)used.add(binding.imported)}return[...used].sort((a,b)=>a.localeCompare(b))}function usedSymbolsForImport(parsed,strippedContent){if(parsed.importType==="namespace"||parsed.importType==="sideeffect"||parsed.importType==="require")return;if(parsed.reExport)return[...new Set(parsed.bindings.map((b)=>b.imported))].sort((a,b)=>a.localeCompare(b));return computeUsedSymbols(strippedContent,parsed.bindings)}function collectExports(symbols2){let exported=symbols2.filter((s)=>s.exported),exports=exported.map((s)=>s.signature===`default ${s.name}`?"default":s.name),exportLines={};for(let i=0;i<exported.length;i++){let s=exported[i],name=exports[i];if(typeof s.line==="number"&&Number.isFinite(s.line)&&exportLines[name]===void 0)exportLines[name]=s.line}return{exports,exportLines}}function parseImportedSymbols(matchedString,importType){if(importType==="namespace")return["*"];if(importType==="default")return matchedString.match(/^import\s+(\w+)\s+from\s+['"`]/)?["default"]:[];if(importType!=="named")return[];let braceMatch=matchedString.match(/\{\s*([\s\S]*?)\s*\}/);if(!braceMatch)return[];let symbols2=new Set;for(let rawPart of braceMatch[1].split(",")){let part=rawPart.trim();if(!part)continue;let cleaned=part.replace(/^type\s+/,"").split(/\s+as\s+/i)[0].trim();if(/^[A-Za-z_$][\w$]*$/.test(cleaned))symbols2.add(cleaned)}return[...symbols2].sort((a,b)=>a.localeCompare(b))}function isWalkBudgetExceeded(ctx){if(ctx.abortReason!==void 0)return!0;if(Date.now()-ctx.startedAt>ctx.walkBudgetMs)return ctx.abortReason="budget",!0;return!1}function isFileCapReached(ctx,filesLength){if(filesLength>=ctx.maxFiles)return ctx.abortReason="cap",!0;return!1}async function canonicalDirKeyAsync(dir){try{return await fsPromises5.realpath(dir)}catch{return null}}async function findSourceFilesAsync(dir,stats2,options){let ctx={stats:stats2,seenRealPaths:new Set,startedAt:Date.now(),walkBudgetMs:options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,maxFiles:options?.maxFiles??DEFAULT_WALK_FILE_CAP,followSymlinks:options?.followSymlinks??!1,skipDirs:resolveSkipDirectories(options?.excludeDirs)},files=[],queue=[dir],processed=0;while(queue.length>0){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;let current=queue.shift(),key=await canonicalDirKeyAsync(current);if(key!==null){if(ctx.seenRealPaths.has(key)){ctx.stats.skippedDirs++;continue}ctx.seenRealPaths.add(key)}let entries;try{entries=await fsPromises5.readdir(current,{withFileTypes:!0})}catch{continue}entries.sort((a,b)=>a.name.toLowerCase().localeCompare(b.name.toLowerCase()));for(let entry of entries){if(isWalkBudgetExceeded(ctx)||isFileCapReached(ctx,files.length))break;if(ctx.skipDirs.has(entry.name)){ctx.stats.skippedDirs++;continue}let fullPath=path137.join(current,entry.name);if(entry.isSymbolicLink()&&!ctx.followSymlinks){ctx.stats.skippedDirs++;continue}if(entry.isDirectory())queue.push(fullPath);else if(entry.isFile()){let ext=path137.extname(fullPath).toLowerCase();if(SUPPORTED_EXTENSIONS.has(ext))files.push(fullPath)}if(processed++,processed%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}}if(ctx.abortReason==="cap"||ctx.abortReason==="budget")ctx.stats.truncated=!0;return files}function toModuleName(filePath,workspaceRoot){return path137.relative(workspaceRoot,filePath).split(path137.sep).join("/")}function getLanguage(filePath){let ext=path137.extname(filePath).toLowerCase(),jsFamilyLanguage=JS_FAMILY_EXTENSION_TO_LANGUAGE[ext];if(jsFamilyLanguage)return jsFamilyLanguage;return EXTENSION_TO_LANGUAGE[ext]??"unknown"}function isBinaryContent(content){if(content.includes("\x00"))return!0;return!1}function scanFile(filePath,absoluteRoot,maxFileSize){let content,fileStats;try{if(fileStats=fsSync8.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[]};content=fsSync8.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[]}}if(isBinaryContent(content))return{node:null,edges:[]};let ext=path137.extname(filePath).toLowerCase(),exports=[],exportLines={};try{if([".ts",".tsx",".js",".jsx",".mjs",".cjs"].includes(ext)){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractTSSymbols(relativePath,absoluteRoot)))}else if(ext===".py"){let relativePath=path137.relative(absoluteRoot,filePath);({exports,exportLines}=collectExports(_internals83.extractPythonSymbols(relativePath,absoluteRoot)))}let parsedImports=_internals83.parseFileImports(content),strippedForUsage=parsedImports.length>0?_internals83.stripComments(content):"",moduleName=toModuleName(filePath,absoluteRoot),node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},imports:parsedImports.map((p)=>p.specifier),language:getLanguage(filePath),mtime:fileStats.mtime.toISOString(),ontology:_internals83.extractFileOntology({moduleName,filePath,content,language:getLanguage(filePath),exports,imports:parsedImports.map((p)=>p.specifier)})},edges=[],sortedImports=[...parsedImports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let parsed of sortedImports){let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,parsed.specifier);if(resolvedTarget!==null){let usedSymbols=usedSymbolsForImport(parsed,strippedForUsage);edges.push({source:filePath,target:resolvedTarget,importSpecifier:parsed.specifier,importType:parsed.importType,importedSymbols:parsed.importedSymbols,...usedSymbols!==void 0?{usedSymbols}:{}})}}return{node,edges}}catch{return{node:null,edges:[]}}}async function scanFileAsync(filePath,absoluteRoot,maxFileSize){let content,fileStats;try{if(fileStats=fsSync8.statSync(filePath),fileStats.size>maxFileSize)return{node:null,edges:[],symbolEdges:[],diagnostics:{oversizedFiles:[toModuleName(filePath,absoluteRoot)]}};content=fsSync8.readFileSync(filePath,"utf-8")}catch{return{node:null,edges:[],symbolEdges:[],diagnostics:{unreadableFiles:[toModuleName(filePath,absoluteRoot)]}}}if(isBinaryContent(content))return{node:null,edges:[],symbolEdges:[],diagnostics:{binaryFiles:[toModuleName(filePath,absoluteRoot)]}};let grammarId=getLanguage(filePath),facts=await _internals83.extractFileSymbols(grammarId,content);if(facts===null){let fallback=scanFile(filePath,absoluteRoot,maxFileSize),parsedImports=[];try{parsedImports=_internals83.parseFileImports(content)}catch{parsedImports=[]}return{...fallback,symbolEdges:[],diagnostics:{extractionFailures:[{file:toModuleName(filePath,absoluteRoot),language:grammarId,reason:"symbol_extraction_failed"}],unresolvedImports:unresolvedRelativeImportsFor(parsedImports,filePath,absoluteRoot)}}}let exportedDefs=facts.defs.filter((d)=>d.exported),exports=exportedDefs.map((d)=>d.name),exportLines={},exportRanges={};for(let d of exportedDefs)exportLines[d.name]=d.startLine,exportRanges[d.name]={startLine:d.startLine,endLine:d.endLine};let exportsSet=new Set(exports);for(let imp of facts.imports){if(!imp.reExport||!imp.exportedBindings)continue;for(let binding of imp.exportedBindings){if(binding.imported==="*"){if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine};continue}if(!exportsSet.has(binding.exported))exportsSet.add(binding.exported),exports.push(binding.exported);if(imp.startLine!==void 0&&exportLines[binding.exported]===void 0)exportLines[binding.exported]=imp.startLine;if(imp.startLine!==void 0&&imp.endLine!==void 0&&exportRanges[binding.exported]===void 0)exportRanges[binding.exported]={startLine:imp.startLine,endLine:imp.endLine}}}let imports=facts.imports.map((i)=>i.specifier),moduleName=toModuleName(filePath,absoluteRoot),language=grammarId,node={filePath,moduleName,exports,...Object.keys(exportLines).length>0?{exportLines}:{},...Object.keys(exportRanges).length>0?{exportRanges}:{},imports,language,mtime:fileStats.mtime.toISOString(),ontology:_internals83.extractFileOntology({moduleName,filePath,content,language,exports,imports})},edges=[],sortedImports=[...facts.imports].sort((a,b)=>a.specifier.localeCompare(b.specifier));for(let imp of sortedImports){let edgeImportType=imp.importType==="commonjs"?"require":imp.importType,resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(resolvedTarget!==null){let usedBindings=imp.reExport?imp.bindings:imp.bindings.filter((b)=>facts.refs.some((r)=>r.identifier===b.local)),usedSymbols=edgeImportType!=="namespace"&&edgeImportType!=="require"&&edgeImportType!=="sideeffect"?usedBindings.map((b)=>b.imported):void 0;edges.push({source:filePath,target:resolvedTarget,importSpecifier:imp.specifier,importType:edgeImportType,importedSymbols:imp.bindings.map((b)=>b.imported),...usedSymbols!==void 0?{usedSymbols}:{}})}}let unresolvedImports=sortedImports.filter((imp)=>isRelativeImportSpecifier(imp.specifier)).filter((imp)=>resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier)===null).map((imp)=>({file:moduleName,specifier:imp.specifier})),symbolEdges=[],localToImported=new Map;for(let imp of facts.imports){if(imp.reExport)continue;for(let binding of imp.bindings)localToImported.set(binding.local,{specifier:imp.specifier,imported:binding.imported})}let seenSymbolEdgeKeys=new Set;for(let ref of facts.refs){let mapping=localToImported.get(ref.identifier);if(!mapping)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,mapping.specifier);if(!resolvedTarget)continue;let fromSymbol=ref.enclosingDecl??"<module>",key=filePath+"\x00"+fromSymbol+"\x00"+resolvedTarget+"\x00"+mapping.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol,toFile:resolvedTarget,toSymbol:mapping.imported})}for(let imp of facts.imports){if(!imp.reExport||!imp.exportedBindings)continue;let resolvedTarget=resolveModuleSpecifier(absoluteRoot,filePath,imp.specifier);if(!resolvedTarget)continue;for(let binding of imp.exportedBindings){if(binding.imported==="*")continue;let key=filePath+"\x00"+binding.exported+"\x00"+resolvedTarget+"\x00"+binding.imported;if(seenSymbolEdgeKeys.has(key))continue;seenSymbolEdgeKeys.add(key),symbolEdges.push({fromFile:filePath,fromSymbol:binding.exported,toFile:resolvedTarget,toSymbol:binding.imported})}}return{node,edges,symbolEdges,diagnostics:unresolvedImports.length>0?{unresolvedImports}:void 0}}async function buildWorkspaceGraphAsync(workspaceRoot,options){validateWorkspace(workspaceRoot);let maxFileSize=options?.maxFileSizeBytes??1048576,maxFiles=options?.maxFiles??DEFAULT_WALK_FILE_CAP,walkBudgetMs=options?.walkBudgetMs??DEFAULT_WALK_BUDGET_MS,followSymlinks=options?.followSymlinks??!1,absoluteRoot=path137.resolve(workspaceRoot);if(!existsSync77(absoluteRoot))throw Error(`Workspace directory does not exist: ${workspaceRoot}`);if(isRefusedWorkspaceRoot(absoluteRoot))throw Error(`Refusing to scan top-level system path as workspace: ${absoluteRoot}. Set workspaceRoot to a project directory.`);let graph=createEmptyGraph(workspaceRoot),stats2={filesScanned:0,skippedDirs:0,skippedFiles:0,truncated:!1},diagnostics=createEmptyDiagnostics(),sourceFiles=await findSourceFilesAsync(absoluteRoot,stats2,{walkBudgetMs,maxFiles,followSymlinks,excludeDirs:options?.excludeDirs});if(sourceFiles.sort((a,b)=>{let normA=normalizeGraphPath(a),normB=normalizeGraphPath(b);return normA.localeCompare(normB)}),stats2.truncated)warn(`[repo-graph] Walk truncated: collected ${sourceFiles.length} files within ${walkBudgetMs}ms / ${maxFiles}-file budget.`);let seenEdges=new Set,seenSymbolEdges=new Set,allSymbolEdges=[],processedSinceYield=0;for(let filePath of sourceFiles){let result=await scanFileAsync(filePath,absoluteRoot,maxFileSize);if(mergeDiagnostics(diagnostics,result.diagnostics),result.node){let appended=!1;try{appendNodeFast(graph,result.node),appended=!0}catch{stats2.skippedFiles++}if(appended){for(let edge of result.edges)try{appendEdgeFast(graph,edge,seenEdges)}catch{}for(let symbolEdge of result.symbolEdges){let key=symbolEdge.fromFile+"\x00"+symbolEdge.fromSymbol+"\x00"+symbolEdge.toFile+"\x00"+symbolEdge.toSymbol;if(!seenSymbolEdges.has(key))seenSymbolEdges.add(key),allSymbolEdges.push(symbolEdge)}stats2.filesScanned++}}else stats2.skippedFiles++;if(processedSinceYield++,processedSinceYield%ASYNC_WALK_YIELD_INTERVAL===0)await yieldToEventLoop()}if(graph.metadata={generatedAt:new Date().toISOString(),generator:"repo-graph",nodeCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length},allSymbolEdges.length>0)graph.symbolEdges=allSymbolEdges;if(graph.diagnostics=diagnosticsHaveEntries(diagnostics)?diagnostics:createEmptyDiagnostics(),stats2.skippedFiles>0||stats2.skippedDirs>0||stats2.truncated)log(`[repo-graph] Scan stats: ${stats2.filesScanned} files scanned, ${stats2.skippedFiles} files skipped, ${stats2.skippedDirs} dirs skipped`+(stats2.truncated?", TRUNCATED":""));return graph}import*as path138 from"node:path";var graphCache=new Map,dirtyFlags=new Map,mtimeCache=new Map;function getCachedGraph(workspace){return graphCache.get(path138.normalize(workspace))}function setCachedGraph(workspace,graph,mtime){let normalized=path138.normalize(workspace);if(graphCache.set(normalized,graph),dirtyFlags.set(normalized,!1),mtime!==void 0)mtimeCache.set(normalized,mtime)}function isDirty(workspace){return dirtyFlags.get(path138.normalize(workspace))??!1}function clearCache(workspace){let normalized=path138.normalize(workspace);graphCache.delete(normalized),dirtyFlags.delete(normalized),mtimeCache.delete(normalized)}function getCachedMtime(workspace){return mtimeCache.get(path138.normalize(workspace))}init_logger();init_path_security();import{existsSync as existsSync79}from"node:fs";import*as fsPromises7 from"node:fs/promises";import*as path141 from"node:path";init_path_security();import*as fsSync9 from"node:fs";import*as path139 from"node:path";var GRAPH_HEALTH_OUTPUT_LIMIT=50,MAX_HEALTH_PATH_LENGTH=500,cachedReverseIndex=null;function normalizeLookupPath(input){return normalizeGraphPath(input).replace(/^(?:\.\/)+/,"")}function graphRoot(graph){return path139.resolve(graph.workspaceRoot)}function toModuleName2(graph,input){let normalized=normalizeLookupPath(input);if(path139.isAbsolute(normalized)||/^[A-Za-z]:\//.test(normalized))return normalizeLookupPath(path139.relative(graphRoot(graph),normalized));return normalized}function absoluteKeyForModule(graph,moduleName){return normalizeGraphPath(path139.resolve(graphRoot(graph),moduleName))}function getGraphNode(graph,input){let moduleName=toModuleName2(graph,input),direct=graph.nodes[absoluteKeyForModule(graph,moduleName)];if(direct)return direct;return getQueryIndexes(graph).moduleNameIndex.get(moduleName)}function moduleNameForEdgePath(graph,edgePath){let key=normalizeGraphPath(edgePath),node=graph.nodes[key];if(node)return normalizeLookupPath(node.moduleName);return normalizeLookupPath(path139.relative(graphRoot(graph),edgePath))}function buildReverseIndex(graph){let reverse=new Map,forward=new Map,moduleNameIndex=new Map;for(let node of Object.values(graph.nodes))moduleNameIndex.set(normalizeLookupPath(node.moduleName),node);for(let edge of graph.edges){let source=normalizeGraphPath(edge.source),target=normalizeGraphPath(edge.target),sourceRef={file:moduleNameForEdgePath(graph,edge.source),importType:edge.importType},targetRef={file:moduleNameForEdgePath(graph,edge.target),importType:edge.importType},reverseRefs=reverse.get(target);if(reverseRefs)reverseRefs.push(sourceRef);else reverse.set(target,[sourceRef]);let forwardRefs=forward.get(source);if(forwardRefs)forwardRefs.push(targetRef);else forward.set(source,[targetRef])}for(let refs of reverse.values())refs.sort((a,b)=>a.file.localeCompare(b.file));for(let refs of forward.values())refs.sort((a,b)=>a.file.localeCompare(b.file));return cachedReverseIndex={graph,index:reverse,forwardIndex:forward,moduleNameIndex},reverse}function getQueryIndexes(graph){if(cachedReverseIndex&&cachedReverseIndex.graph===graph)return cachedReverseIndex;return buildReverseIndex(graph),cachedReverseIndex}function getReverseIndex(graph){return getQueryIndexes(graph).index}function getForwardIndex(graph){return getQueryIndexes(graph).forwardIndex}function resetQueryCache(){cachedReverseIndex=null}function isGraphFresh(graph,maxAgeMs=300000){if(!graph)return!1;let built=Date.parse(graph.metadata?.generatedAt??"");if(!Number.isFinite(built))return!1;return Date.now()-built<=maxAgeMs}function isSafeHealthPath(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value)||containsPathTraversal(value))return!1;if(path139.isAbsolute(value)||/^[A-Za-z]:[\\/]/.test(value))return!1;return!0}function isSafeHealthText(value){if(typeof value!=="string")return!1;if(value.length===0||value.length>MAX_HEALTH_PATH_LENGTH)return!1;if(containsControlChars(value))return!1;return!0}function cap(entries){return entries.slice(0,GRAPH_HEALTH_OUTPUT_LIMIT)}function sanitizeExtractionFailures(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.language)&&isSafeHealthText(entry.reason))entries.push({file:entry.file,language:entry.language,reason:entry.reason})}return cap(entries)}function sanitizeUnresolvedImports(value){if(!Array.isArray(value))return[];let entries=[];for(let raw of value){if(!raw||typeof raw!=="object")continue;let entry=raw;if(isSafeHealthPath(entry.file)&&isSafeHealthText(entry.specifier))entries.push({file:entry.file,specifier:entry.specifier})}return cap(entries)}function sanitizePathList(value){if(!Array.isArray(value))return[];return cap(value.filter(isSafeHealthPath))}function getStaleFiles(graph,workspaceRoot){let built=Date.parse(graph.metadata.generatedAt);if(!Number.isFinite(built))return[];let root=workspaceRoot??graph.workspaceRoot,stale=[];for(let node of Object.values(graph.nodes)){let moduleName=normalizeGraphPath(node.moduleName);if(!isSafeHealthPath(moduleName))continue;let filePath=path139.join(root,moduleName);try{if(fsSync9.statSync(filePath).mtimeMs>built){if(stale.push(moduleName),stale.length>=GRAPH_HEALTH_OUTPUT_LIMIT)break}}catch{}}return stale}function getGraphHealth(graph,workspaceRoot){if(!graph)return{schemaVersion:null,fresh:!1,staleFiles:[],extractionFailures:[],unresolvedImports:[],oversizedFiles:[],unsupportedFiles:[],binaryFiles:[],unreadableFiles:[],lowConfidenceEdgeCount:0,notes:['No repo graph found at .swarm/repo-graph.json. Run repo_map with action="build" first.']};let diagnostics=graph.diagnostics,fresh=isGraphFresh(graph),staleFiles=getStaleFiles(graph,workspaceRoot),notes=[];if(!fresh||staleFiles.length>0)notes.push('Graph is stale. Run repo_map with action="build" to refresh.');if(!diagnostics)notes.push('Graph has no recorded diagnostics. Rebuild with repo_map action="build" to collect health details.');let binaryFiles=sanitizePathList(diagnostics?.binaryFiles),binaryCount=binaryFiles.length;if(binaryCount>0)notes.push(`${binaryCount} binary files skipped during last build.`);let unreadableFiles=sanitizePathList(diagnostics?.unreadableFiles),unreadableCount=unreadableFiles.length;if(unreadableCount>0)notes.push(`${unreadableCount} unreadable files skipped during last build.`);return{schemaVersion:graph.schema_version,fresh,staleFiles,extractionFailures:sanitizeExtractionFailures(diagnostics?.extractionFailures),unresolvedImports:sanitizeUnresolvedImports(diagnostics?.unresolvedImports),oversizedFiles:sanitizePathList(diagnostics?.oversizedFiles),unsupportedFiles:sanitizePathList(diagnostics?.unsupportedFiles),binaryFiles,unreadableFiles,lowConfidenceEdgeCount:typeof diagnostics?.lowConfidenceEdgeCount==="number"&&Number.isFinite(diagnostics.lowConfidenceEdgeCount)&&diagnostics.lowConfidenceEdgeCount>0?Math.floor(diagnostics.lowConfidenceEdgeCount):0,notes}}function getImporters(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];return getReverseIndex(graph).get(normalizeGraphPath(node.filePath))??[]}function getDependencies(graph,filePath){let node=getGraphNode(graph,filePath);if(!node)return[];let sourceKey=normalizeGraphPath(node.filePath);return getForwardIndex(graph).get(sourceKey)??[]}function getSymbolConsumers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[];for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;let importedSymbols=edge.importedSymbols??[];if(edge.importType==="namespace"){refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:"*"});continue}if(importedSymbols.includes(symbolName))refs.push({file:moduleNameForEdgePath(graph,edge.source),importedAs:symbolName})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}function getCallers(graph,filePath,symbolName){let node=getGraphNode(graph,filePath);if(!node)return[];let targetKey=normalizeGraphPath(node.filePath),refs=[],seen=new Set;for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;let file3=moduleNameForEdgePath(graph,edge.source);if(seen.has(file3))continue;if(edge.usedSymbols!==void 0){if(edge.usedSymbols.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"used"});continue}let imported=edge.importedSymbols??[];if(edge.importType==="namespace"||imported.includes(symbolName))seen.add(file3),refs.push({file:file3,resolution:"imported"})}return refs.sort((a,b)=>a.file.localeCompare(b.file)),refs}var DEAD_EXPORT_EXCLUDED_ROLES=new Set(["api_route","cli_command","test_file","agent","hook","middleware"]);function getDeadExports(graph,options){if(!isSchemaVersionAtLeast(graph.schema_version,"1.1.0"))return{schemaSupported:!1,analyzedFiles:0,skippedUnresolvable:0,candidates:[],note:'Graph predates schema 1.1.0 (no usedSymbols data). Run repo_map action="build" to enable dead_exports.'};let usage=new Map;for(let edge of graph.edges){let target=normalizeGraphPath(edge.target),entry=usage.get(target);if(!entry)entry={used:new Set,unresolvable:!1},usage.set(target,entry);if(edge.importType==="namespace"||edge.importType==="sideeffect"||edge.importType==="require")entry.unresolvable=!0;else if(edge.usedSymbols)for(let symbol3 of edge.usedSymbols)entry.used.add(symbol3)}let reverse=getReverseIndex(graph),candidates=[],analyzedFiles=0,skippedUnresolvable=0;for(let node of Object.values(graph.nodes)){if(node.exports.length===0)continue;let key=normalizeGraphPath(node.filePath),importerCount=reverse.get(key)?.length??0;if(importerCount===0)continue;if((node.ontology?.roles??[]).some((r)=>DEAD_EXPORT_EXCLUDED_ROLES.has(r)))continue;let entry=usage.get(key);if(entry?.unresolvable){skippedUnresolvable++;continue}analyzedFiles++;let used=entry?.used??new Set;for(let symbol3 of node.exports){if(symbol3==="default")continue;if(used.has(symbol3))continue;candidates.push({file:node.moduleName,symbol:symbol3,line:node.exportLines?.[symbol3],importerCount})}}candidates.sort((a,b)=>a.file.localeCompare(b.file)||a.symbol.localeCompare(b.symbol));let limit=options?.maxCandidates??100,truncated=candidates.length>limit;return{schemaSupported:!0,analyzedFiles,skippedUnresolvable,candidates:candidates.slice(0,limit),note:"Advisory: exported symbols with no detected in-repo reference, limited to files imported by >=1 other file. Regex analysis cannot see dynamic dispatch, string-keyed access, or namespace/barrel re-export usage; verify before removing."+(truncated?` Showing ${limit} of ${candidates.length}.`:"")}}function getBlastRadius(graph,filePaths,maxDepth=3){let targetNodes=filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0),targets=targetNodes.map((node)=>normalizeLookupPath(node.moduleName));if(maxDepth<=0||targetNodes.length===0)return{target:filePaths.map((filePath)=>toModuleName2(graph,filePath)),directDependents:[],transitiveDependents:[],depthReached:0,totalDependents:0,riskLevel:"low"};let reverse=getReverseIndex(graph),visited=new Set(targetNodes.map((node)=>normalizeGraphPath(node.filePath))),direct=new Set,transitive=new Set,depthReached=0,queue=targetNodes.map((node)=>({key:normalizeGraphPath(node.filePath),depth:0}));while(queue.length>0){let next=[];for(let{key,depth}of queue){let importers=reverse.get(key)??[];for(let ref of importers){let importerNode=getGraphNode(graph,ref.file);if(!importerNode)continue;let importerKey=normalizeGraphPath(importerNode.filePath);if(visited.has(importerKey))continue;if(visited.add(importerKey),depth===0)direct.add(ref.file);else transitive.add(ref.file);if(depthReached=Math.max(depthReached,depth+1),depth+1<maxDepth)next.push({key:importerKey,depth:depth+1})}}queue=next}let totalDependents=direct.size+transitive.size;return{target:targets,directDependents:[...direct].sort(),transitiveDependents:[...transitive].sort(),depthReached,totalDependents,riskLevel:classifyRisk(totalDependents)}}function classifyRisk(count){if(count<=3)return"low";if(count<=10)return"medium";if(count<=25)return"high";return"critical"}function getKeyFiles(graph,topN=10){let reverse=getReverseIndex(graph),scored=Object.values(graph.nodes).map((node)=>({node,inDegree:reverse.get(normalizeGraphPath(node.filePath))?.length??0}));return scored.sort((a,b)=>{if(b.inDegree!==a.inDegree)return b.inDegree-a.inDegree;return a.node.moduleName.localeCompare(b.node.moduleName)}),scored.slice(0,topN).map((item)=>item.node)}function getFileOntology(graph,filePath){return getGraphNode(graph,filePath)?.ontology??null}function getLocalizationContext(graph,filePath,options={}){let target=toModuleName2(graph,filePath),node=getGraphNode(graph,target),importers=getImporters(graph,target),dependencies=getDependencies(graph,target),blast=getBlastRadius(graph,[target],options.maxDepth??2),externalSymbols=collectExternallyUsedSymbols(graph,node),summary=formatLocalizationSummary({target,importers,dependencies,blast,externalSymbols,ontology:node?.ontology??null,maxImporters:options.maxImporters??5,maxDeps:options.maxDeps??5});return{target,importerCount:importers.length,importers:importers.slice(0,options.maxImporters??5),dependencyCount:dependencies.length,dependencies:dependencies.slice(0,options.maxDeps??5),exportedSymbolsUsedExternally:externalSymbols,blastRadius:blast,summary}}function getContextPack(graph,file3,symbol3,options={}){if(!isSchemaVersionAtLeast(graph.schema_version,"1.2.0"))return{schemaSupported:!1,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:'rebuild with repo_map action="build"'};let maxDepth=options.maxDepth??2,maxTokens=options.maxTokens??4000,targetNode=getGraphNode(graph,file3);if(!targetNode)return{schemaSupported:!0,target:{file:file3,symbol:symbol3},spans:[],truncated:!1,estimatedTokens:0,note:"Target file not found in graph"};let targetFile=normalizeGraphPath(targetNode.filePath),forward=new Map,reverse=new Map,symbolEdges=graph.symbolEdges??[];for(let edge of symbolEdges){let fromKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`,toKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`,fromEdges=forward.get(fromKey);if(fromEdges)fromEdges.push(edge);else forward.set(fromKey,[edge]);let toEdges=reverse.get(toKey);if(toEdges)toEdges.push(edge);else reverse.set(toKey,[edge])}let targetKey=`${targetFile}\x00${symbol3}`,visited=new Map,queue=[{key:targetKey,depth:0}];visited.set(targetKey,0);let reached=[],queueHead=0;while(queueHead<queue.length){let{key,depth}=queue[queueHead];queueHead++;let[curFile,curSymbol]=key.split("\x00",2);if(reached.push({file:curFile,symbol:curSymbol,depth}),depth>=maxDepth)continue;let outEdges=forward.get(key)??[];for(let edge of outEdges){let nextKey=`${normalizeGraphPath(edge.toFile)}\x00${edge.toSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}let inEdges=reverse.get(key)??[];for(let edge of inEdges){let nextKey=`${normalizeGraphPath(edge.fromFile)}\x00${edge.fromSymbol}`;if(!visited.has(nextKey))visited.set(nextKey,depth+1),queue.push({key:nextKey,depth:depth+1})}}let TOKENS_PER_LINE=12,TOKENS_PER_SIGNATURE=10,spansWithDepth=[];for(let{file:symFile,symbol:sym,depth:d}of reached){let range=graph.nodes[symFile]?.exportRanges?.[sym];if(!range)continue;let mode=d===0?"full":d<maxDepth?"full":"signature";spansWithDepth.push({span:{file:symFile,symbol:sym,startLine:range.startLine,endLine:range.endLine,mode},depth:d})}spansWithDepth.sort((a,b)=>{let aIsTarget=a.span.file===targetFile&&a.span.symbol===symbol3?0:1,bIsTarget=b.span.file===targetFile&&b.span.symbol===symbol3?0:1;if(aIsTarget!==bIsTarget)return aIsTarget-bIsTarget;if(a.depth!==b.depth)return a.depth-b.depth;let fileCmp=a.span.file.localeCompare(b.span.file);if(fileCmp!==0)return fileCmp;return a.span.symbol.localeCompare(b.span.symbol)});let estimatedTokens=0,finalSpans=[],truncated=!1;for(let{span}of spansWithDepth){let spanTokens=span.mode==="full"?(span.endLine-span.startLine+1)*TOKENS_PER_LINE:TOKENS_PER_SIGNATURE;if(finalSpans.length>0&&estimatedTokens+spanTokens>maxTokens){truncated=!0;break}finalSpans.push(span),estimatedTokens+=spanTokens}return{schemaSupported:!0,target:{file:targetFile,symbol:symbol3},spans:finalSpans,truncated,estimatedTokens}}function collectExternallyUsedSymbols(graph,node){if(!node)return[];let exported=new Set(node.exports),used=new Set,targetKey=normalizeGraphPath(node.filePath);for(let edge of graph.edges){if(normalizeGraphPath(edge.target)!==targetKey)continue;for(let symbol3 of edge.importedSymbols??[])if(exported.has(symbol3))used.add(symbol3)}return[...used].sort((a,b)=>a.localeCompare(b))}function formatLocalizationSummary(opts){let importerList=opts.importers.length===0?"(none)":opts.importers.slice(0,opts.maxImporters).map((ref)=>ref.file).join(", ")+(opts.importers.length>opts.maxImporters?`, +${opts.importers.length-opts.maxImporters} more`:""),depList=opts.dependencies.length===0?"(none)":opts.dependencies.slice(0,opts.maxDeps).map((ref)=>ref.file).join(", ")+(opts.dependencies.length>opts.maxDeps?`, +${opts.dependencies.length-opts.maxDeps} more`:""),symbolList=opts.externalSymbols.length===0?"(none used externally)":opts.externalSymbols.slice(0,8).join(", ")+(opts.externalSymbols.length>8?`, +${opts.externalSymbols.length-8} more`:""),roles=opts.ontology?.roles.join(", ")||"unknown",findings=opts.ontology?.findings.length??0;return["LOCALIZATION CONTEXT",` Target: ${opts.target}`,` Roles: ${roles}`,` Imported by (${opts.importers.length}): ${importerList}`,` Imports (${opts.dependencies.length}): ${depList}`,` Exports used externally: ${symbolList}`,` Blast radius: ${opts.blast.totalDependents} files (${opts.blast.riskLevel} risk)`,` Ontology findings: ${findings}`].join(`
|
|
5320
5320
|
`)}function getPackageBoundaries(graph,topN=25){return summarizePackageBoundaries(Object.values(graph.nodes),graph.edges,topN)}function summarizePackageBoundaries(nodes,edges,topN){let groups=new Map,ensure=(node)=>{let name=node.ontology?.packageBoundary||inferBoundary(node.moduleName),group=groups.get(name);if(!group)group={name,root:name,fileCount:0,roles:{},dependsOn:[],dependedOnBy:[],routeCount:0,dataOperationCount:0,findingCount:0,publicFiles:[]},groups.set(name,group);return group},boundaryByPath=new Map;for(let node of nodes){let group=ensure(node);boundaryByPath.set(normalizeGraphPath(node.filePath),group.name),group.fileCount++;let ontology=node.ontology;for(let role of ontology?.roles??["source_module"])group.roles[role]=(group.roles[role]??0)+1;if(group.routeCount+=ontology?.routes.length??0,group.dataOperationCount+=ontology?.dataOperations.length??0,group.findingCount+=ontology?.findings.length??0,node.exports.length>0)group.publicFiles.push(node.moduleName)}let dependsOn=new Map,dependedOnBy=new Map;for(let edge of edges){let sourceBoundary=boundaryByPath.get(normalizeGraphPath(edge.source)),targetBoundary=boundaryByPath.get(normalizeGraphPath(edge.target));if(!sourceBoundary||!targetBoundary||sourceBoundary===targetBoundary)continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}for(let group of groups.values())group.dependsOn=[...dependsOn.get(group.name)??[]].sort(),group.dependedOnBy=[...dependedOnBy.get(group.name)??[]].sort(),group.publicFiles.sort((a,b)=>a.localeCompare(b)),group.publicFiles=group.publicFiles.slice(0,20);return[...groups.values()].sort((a,b)=>{if(b.findingCount!==a.findingCount)return b.findingCount-a.findingCount;if(b.fileCount!==a.fileCount)return b.fileCount-a.fileCount;return a.name.localeCompare(b.name)}).slice(0,topN)}function summarizeSelectedPackageBoundaries(graph,nodes,topN=25){let summaries=summarizePackageBoundaries(nodes,[],topN),boundaryByModule=new Map;for(let node of nodes)boundaryByModule.set(normalizeLookupPath(node.moduleName),node.ontology?.packageBoundary??inferBoundary(node.moduleName));let byName=new Map(summaries.map((summary)=>[summary.name,summary])),dependsOn=new Map,dependedOnBy=new Map;for(let node of nodes){let sourceBoundary=boundaryByModule.get(normalizeLookupPath(node.moduleName));if(!sourceBoundary)continue;for(let dep of getDependencies(graph,node.moduleName)){let targetBoundary=boundaryByModule.get(normalizeLookupPath(dep.file));if(!targetBoundary||sourceBoundary===targetBoundary||!byName.has(sourceBoundary)||!byName.has(targetBoundary))continue;if(!dependsOn.has(sourceBoundary))dependsOn.set(sourceBoundary,new Set);if(!dependedOnBy.has(targetBoundary))dependedOnBy.set(targetBoundary,new Set);dependsOn.get(sourceBoundary)?.add(targetBoundary),dependedOnBy.get(targetBoundary)?.add(sourceBoundary)}}for(let summary of summaries)summary.dependsOn=[...dependsOn.get(summary.name)??[]].sort(),summary.dependedOnBy=[...dependedOnBy.get(summary.name)??[]].sort();return summaries}function inferBoundary(moduleName){let parts=normalizeLookupPath(moduleName).split("/").filter(Boolean);if(parts[0]==="src"&&parts.length>=2)return`src/${parts[1]}`;if(parts.length>=2&&(parts[0]==="packages"||parts[0]==="crates"))return`${parts[0]}/${parts[1]}`;return parts[0]||"."}function buildOntologyPreflightPacket(graph,filePaths=[],options={}){let maxFiles=options.maxFiles??12,maxFindings=options.maxFindings??20,boundedNodes=(filePaths.length>0?filePaths.map((filePath)=>getGraphNode(graph,filePath)).filter((node)=>node!==void 0):getKeyFiles(graph,maxFiles)).slice(0,maxFiles),findings=boundedNodes.flatMap((node)=>(node.ontology?.findings??[]).map((finding)=>({file:node.moduleName,...finding}))).slice(0,maxFindings),routes=boundedNodes.flatMap((node)=>(node.ontology?.routes??[]).map((route)=>({file:node.moduleName,...route}))),dataOperations=boundedNodes.flatMap((node)=>(node.ontology?.dataOperations??[]).map((fact)=>({file:node.moduleName,...fact}))),security=boundedNodes.flatMap((node)=>(node.ontology?.security??[]).map((fact)=>({file:node.moduleName,...fact})));return{generatedAt:new Date().toISOString(),targets:boundedNodes.map((node)=>node.moduleName),summary:{fileCount:Object.keys(graph.nodes).length,edgeCount:graph.edges.length,targetCount:boundedNodes.length,findingCount:findings.length,routeCount:routes.length,dataOperationCount:dataOperations.length,securityFactCount:security.length},files:boundedNodes.map((node)=>({file:node.moduleName,roles:node.ontology?.roles??[],packageBoundary:node.ontology?.packageBoundary??inferBoundary(node.moduleName),importerCount:getImporters(graph,node.moduleName).length,dependencyCount:getDependencies(graph,node.moduleName).length,routeCount:node.ontology?.routes.length??0,dataOperationCount:node.ontology?.dataOperations.length??0,securityFactCount:node.ontology?.security.length??0,findingCount:node.ontology?.findings.length??0})),routes,dataOperations,security,findings,packageBoundaries:summarizeSelectedPackageBoundaries(graph,boundedNodes,options.maxBoundaries??10)}}init_utils2();init_logger();init_path_security();import{constants as constants5,existsSync as existsSync78,readFileSync as readFileSync53,statSync as statSync29}from"node:fs";import*as fsPromises6 from"node:fs/promises";import*as path140 from"node:path";var WINDOWS_RENAME_MAX_RETRIES2=5,WINDOWS_RENAME_RETRY_DELAY_MS2=100,_internals84={safeRealpathSync,fsRename:fsPromises6.rename.bind(fsPromises6),retryDelayMs:WINDOWS_RENAME_RETRY_DELAY_MS2};function validateLoadedGraph(parsed){if(!parsed.schema_version)throw Object.assign(Error("repo-graph.json missing schema_version"),{code:"CORRUPTION"});if(!parsed.nodes||typeof parsed.nodes!=="object")throw Object.assign(Error("repo-graph.json missing or invalid nodes"),{code:"CORRUPTION"});if(!Array.isArray(parsed.edges))throw Object.assign(Error("repo-graph.json missing or invalid edges"),{code:"CORRUPTION"});for(let[key,node]of Object.entries(parsed.nodes)){if(!key||typeof key!=="string")throw Object.assign(Error("repo-graph.json contains invalid node key"),{code:"CORRUPTION"});try{validateGraphNode(node)}catch(err){let msg=err instanceof Error?err.message:"Invalid node structure";throw Object.assign(Error(`repo-graph.json node validation failed: ${msg}`),{code:"CORRUPTION"})}}for(let edge of parsed.edges)try{validateGraphEdge(edge)}catch(err){let msg=err instanceof Error?err.message:"Invalid edge structure";throw Object.assign(Error(`repo-graph.json edge validation failed: ${msg}`),{code:"CORRUPTION"})}if(!parsed.metadata||typeof parsed.metadata!=="object"||typeof parsed.metadata.generatedAt!=="string"||typeof parsed.metadata.generator!=="string"||typeof parsed.metadata.nodeCount!=="number"||typeof parsed.metadata.edgeCount!=="number")throw Object.assign(Error("repo-graph.json missing or invalid metadata"),{code:"CORRUPTION"});if(parsed.symbolEdges!==void 0){if(!Array.isArray(parsed.symbolEdges))throw Object.assign(Error("repo-graph.json symbolEdges must be an array"),{code:"CORRUPTION"});for(let entry of parsed.symbolEdges)if(typeof entry!=="object"||entry===null||typeof entry.fromFile!=="string"||typeof entry.fromSymbol!=="string"||typeof entry.toFile!=="string"||typeof entry.toSymbol!=="string"||entry.fromFile===""||entry.fromSymbol===""||entry.toFile===""||entry.toSymbol===""||containsControlChars(entry.fromFile)||containsControlChars(entry.fromSymbol)||containsControlChars(entry.toFile)||containsControlChars(entry.toSymbol)||containsPathTraversal(entry.fromFile)||containsPathTraversal(entry.toFile))throw Object.assign(Error("repo-graph.json contains invalid symbolEdges entry"),{code:"CORRUPTION"})}}function getGraphPath(workspace){validateWorkspace(workspace);let basePath=validateSwarmPath(workspace,REPO_GRAPH_FILENAME);return validateSymlinkBoundary(basePath,workspace),basePath}async function loadGraph(workspace){validateWorkspace(workspace);let normalized=path140.normalize(workspace),cached3=getCachedGraph(normalized);if(cached3&&!isDirty(normalized))try{let graphPath=getGraphPath(workspace);if(existsSync78(graphPath)){let stats2=await fsPromises6.stat(graphPath),cachedMtime=getCachedMtime(normalized);if(cachedMtime!==void 0&&stats2.mtimeMs!==cachedMtime)clearCache(normalized);else return cached3}else clearCache(normalized)}catch{clearCache(normalized)}try{let graphPath=getGraphPath(workspace);if(!existsSync78(graphPath))return null;let stats2=await fsPromises6.stat(graphPath),content=await fsPromises6.readFile(graphPath,"utf-8");if(content.includes("\x00")||content.includes("�"))throw Object.assign(Error("repo-graph.json contains null bytes or invalid encoding"),{code:"CORRUPTION"});let parsed;try{parsed=JSON.parse(content)}catch{throw Object.assign(Error("repo-graph.json contains invalid JSON"),{code:"CORRUPTION"})}return validateLoadedGraph(parsed),setCachedGraph(normalized,parsed,stats2.mtimeMs),parsed}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="CORRUPTION")throw error93;if(error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT")return null;throw error93}}function loadGraphSync(workspace){validateWorkspace(workspace);let normalized=path140.normalize(workspace);try{let graphPath=getGraphPath(workspace);if(!existsSync78(graphPath))return null;let stats2=statSync29(graphPath),content=readFileSync53(graphPath,"utf-8");if(content.includes("\x00")||content.includes("�"))throw Object.assign(Error("repo-graph.json contains null bytes or invalid encoding"),{code:"CORRUPTION"});let parsed;try{parsed=JSON.parse(content)}catch{throw Object.assign(Error("repo-graph.json contains invalid JSON"),{code:"CORRUPTION"})}return validateLoadedGraph(parsed),setCachedGraph(normalized,parsed,stats2.mtimeMs),parsed}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="ENOENT")return null;throw error93}}async function saveGraph(workspace,graph,options){if(validateWorkspace(workspace),!graph.schema_version)throw Error("Graph must have schema_version");if(!graph.nodes||typeof graph.nodes!=="object")throw Error("Graph must have nodes object");if(!Array.isArray(graph.edges))throw Error("Graph must have edges array");let normalizedWorkspace=path140.normalize(workspace),realWorkspace=_internals84.safeRealpathSync(workspace,normalizedWorkspace);if(realWorkspace===null)throw Error(`Workspace realpath security check failed (non-ENOENT): ${workspace}`);let normalizedGraphRoot=path140.normalize(graph.workspaceRoot),realGraphRoot=_internals84.safeRealpathSync(graph.workspaceRoot,normalizedGraphRoot);if(realGraphRoot===null)throw Error(`Graph workspaceRoot realpath security check failed (non-ENOENT): ${graph.workspaceRoot}`);if(path140.normalize(realWorkspace)!==path140.normalize(realGraphRoot))throw Error(`Graph workspaceRoot mismatch: graph was built for "${graph.workspaceRoot}" but save was called for "${workspace}"`);let normalized=normalizedWorkspace,graphPath=getGraphPath(workspace);updateGraphMetadata(graph);let tempPath=`${graphPath}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;await fsPromises6.mkdir(path140.dirname(tempPath),{recursive:!0});let lastError=null;try{if(options?.createAtomic)try{let handle=await fsPromises6.open(tempPath,"wx",420);await handle.writeFile(JSON.stringify(graph,null,2),"utf-8"),await handle.close()}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code==="EEXIST")throw Error("file already exists");throw error93}else await fsPromises6.writeFile(tempPath,JSON.stringify(graph,null,2),"utf-8");if(options?.createAtomic)try{await fsPromises6.copyFile(tempPath,graphPath,constants5.COPYFILE_EXCL)}catch(error93){throw lastError=error93 instanceof Error?error93:Error(String(error93)),lastError}else{for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{await _internals84.fsRename(tempPath,graphPath),lastError=null;break}catch(error93){lastError=error93 instanceof Error?error93:Error(String(error93));let code=lastError.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES2-1)await new Promise((resolve49)=>setTimeout(resolve49,_internals84.retryDelayMs))}if(lastError)throw lastError}}finally{try{await fsPromises6.unlink(tempPath)}catch(error93){if(error93 instanceof Error&&"code"in error93&&error93.code!=="ENOENT")error48(`Failed to clean up temp file ${tempPath}:`,error93)}}let stats2=await fsPromises6.stat(graphPath);setCachedGraph(normalized,graph,stats2.mtimeMs)}async function updateGraphForFiles(workspaceRoot,filePaths,options){if(options?.forceRebuild){let graph2=await buildWorkspaceGraphAsync(workspaceRoot);return await saveGraph(workspaceRoot,graph2),graph2}let existingGraph=await loadGraph(workspaceRoot);if(!existingGraph){let graph2=await buildWorkspaceGraphAsync(workspaceRoot);return await saveGraph(workspaceRoot,graph2),graph2}let graph=existingGraph,absoluteRoot=path141.resolve(workspaceRoot),maxFileSize=1048576,updatedPaths=new Set;for(let rawFilePath of filePaths){let normalizedPath=normalizeGraphPath(rawFilePath);if(existsSync79(rawFilePath)){if(graph.edges=graph.edges.filter((e)=>normalizeGraphPath(e.source)!==normalizedPath),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((se)=>normalizeGraphPath(se.fromFile)!==normalizedPath);let result=await scanFileAsync(rawFilePath,absoluteRoot,maxFileSize);if(result.node){let sanitizedImports=result.node.imports.filter((imp)=>!containsControlChars(imp)),sanitizedNode={...result.node,imports:sanitizedImports};delete graph.nodes[normalizedPath],upsertNode(graph,sanitizedNode);for(let edge of result.edges)if(!graph.edges.some((e)=>e.source===edge.source&&e.target===edge.target&&e.importSpecifier===edge.importSpecifier))addEdge(graph,edge);if(result.symbolEdges.length>0){if(!graph.symbolEdges)graph.symbolEdges=[];let existingKeys=new Set(graph.symbolEdges.map((se)=>`${se.fromFile}\x00${se.fromSymbol}\x00${se.toFile}\x00${se.toSymbol}`));for(let symbolEdge of result.symbolEdges){let key=`${symbolEdge.fromFile}\x00${symbolEdge.fromSymbol}\x00${symbolEdge.toFile}\x00${symbolEdge.toSymbol}`;if(!existingKeys.has(key))graph.symbolEdges.push(symbolEdge),existingKeys.add(key)}}}}else if(delete graph.nodes[normalizedPath],graph.edges=graph.edges.filter((e)=>normalizeGraphPath(e.source)!==normalizedPath&&normalizeGraphPath(e.target)!==normalizedPath),graph.symbolEdges)graph.symbolEdges=graph.symbolEdges.filter((se)=>normalizeGraphPath(se.fromFile)!==normalizedPath&&normalizeGraphPath(se.toFile)!==normalizedPath);updatedPaths.add(normalizedPath)}let validationFailed=!1;for(let edge of graph.edges){let normalizedSource=normalizeGraphPath(edge.source),normalizedTarget=normalizeGraphPath(edge.target);if(!graph.nodes[normalizedSource]||!graph.nodes[normalizedTarget]){validationFailed=!0;break}}if(graph.symbolEdges&&graph.symbolEdges.length>0){let validSymbolEdges=[];for(let symbolEdge of graph.symbolEdges){let normalizedFromFile=normalizeGraphPath(symbolEdge.fromFile),normalizedToFile=normalizeGraphPath(symbolEdge.toFile);if(graph.nodes[normalizedFromFile]&&graph.nodes[normalizedToFile])validSymbolEdges.push(symbolEdge)}graph.symbolEdges=validSymbolEdges}if(validationFailed){warn("[repo-graph] Incremental update failed, falling back to full rebuild");let rebuiltGraph=await buildWorkspaceGraphAsync(workspaceRoot);return await saveGraph(workspaceRoot,rebuiltGraph),rebuiltGraph}let normalizedWorkspace=path141.normalize(workspaceRoot),loadedMtime=getCachedMtime(normalizedWorkspace);if(loadedMtime!==void 0)try{let graphPath=getGraphPath(workspaceRoot);if(existsSync79(graphPath)){if((await fsPromises7.stat(graphPath)).mtimeMs!==loadedMtime){warn("[repo-graph] Concurrent modification detected — falling back to full rebuild");let rebuiltGraph=await buildWorkspaceGraphAsync(workspaceRoot);return await saveGraph(workspaceRoot,rebuiltGraph),rebuiltGraph}}}catch{}if(graph.symbolEdges&&graph.symbolEdges.length===0)delete graph.symbolEdges;return updateGraphMetadata(graph),resetQueryCache(),await saveGraph(workspaceRoot,graph),graph}init_logger();var SUPPORTED_EXTENSIONS2=[".ts",".tsx",".js",".jsx",".mjs",".cjs",".py"];function extractFilePath(args2){if(!args2||typeof args2!=="object")return null;let a=args2,filePath=a.file_path??a.path??a.filePath;if(!filePath||typeof filePath!=="string")return null;for(let i=0;i<3;i++)try{let decoded=decodeURIComponent(filePath);if(decoded===filePath)break;filePath=decoded}catch{break}return filePath=filePath.replace(/./g,".").replace(///g,"/").replace(/․/g,"."),filePath}function isSupportedSourceFile(filePath){let ext=filePath.substring(filePath.lastIndexOf(".")).toLowerCase();return SUPPORTED_EXTENSIONS2.includes(ext)}function createRepoGraphBuilderHook(workspaceRoot,deps,options){let _buildWorkspaceGraph=deps?.buildWorkspaceGraph??buildWorkspaceGraphAsync,_saveGraph=deps?.saveGraph??saveGraph,_updateGraphForFiles=deps?.updateGraphForFiles??updateGraphForFiles,_safeRealpathSync=deps?.safeRealpathSync??safeRealpathSync,_excludeDirs=(options?.excludeDirs??[]).filter((d)=>d.length>0),_excludeDirSet=new Set(_excludeDirs),initStarted=!1,initPromise=Promise.resolve(),FAILURE_ADVISORY_THRESHOLD=3,FAILURE_DECAY_MS=300000,ADVISORY_COOLDOWN_MS=60000,MAX_TRACKED_SESSIONS=100,failuresBySession=new Map;function recordSuccess(sessionID){failuresBySession.delete(sessionID)}function recordFailure(sessionID,now){let state=failuresBySession.get(sessionID);if(state&&now-state.lastFailureAt>FAILURE_DECAY_MS)failuresBySession.delete(sessionID),state=void 0;if(!state){if(failuresBySession.size>=MAX_TRACKED_SESSIONS){let oldest=failuresBySession.keys().next().value;if(oldest!==void 0)failuresBySession.delete(oldest)}state={failures:0,lastFailureAt:0,lastAdvisoryAt:0},failuresBySession.set(sessionID,state)}state.failures+=1,state.lastFailureAt=now;let advise=!1;if(state.failures>=FAILURE_ADVISORY_THRESHOLD&&now-state.lastAdvisoryAt>=ADVISORY_COOLDOWN_MS)advise=!0,state.lastAdvisoryAt=now;return{count:state.failures,advise}}async function doInit(){await yieldToEventLoop();try{let graph=await _buildWorkspaceGraph(workspaceRoot,{excludeDirs:_excludeDirs});await _saveGraph(workspaceRoot,graph),log(`[repo-graph] Built graph: ${graph.metadata.nodeCount} nodes, ${graph.metadata.edgeCount} edges`)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);if(message.includes("does not exist")||message.includes("Refusing to scan")){log(`[repo-graph] Skipping scan: ${message}`);return}error48(`[repo-graph] Failed to build graph: ${message}`)}}return{init(){if(!initStarted)initStarted=!0,initPromise=doInit();return initPromise},async toolAfter(input,_output){if(await initPromise.catch(()=>{}),!WRITE_TOOL_NAMES.includes(input.tool))return;let filePath=extractFilePath(input.args);if(!filePath)return;if(filePath.includes("\x00"))return;if(!isSupportedSourceFile(filePath))return;if(_excludeDirSet.size>0&&filePath.split(/[/\\]/).some((segment)=>_excludeDirSet.has(segment)))return;let absoluteFilePath=path142.isAbsolute(filePath)?filePath:path142.resolve(workspaceRoot,filePath),realFilePath=_safeRealpathSync(absoluteFilePath,absoluteFilePath);if(realFilePath===null)return;let realWorkspace=_safeRealpathSync(workspaceRoot,workspaceRoot);if(realWorkspace===null)return;let normalizedAbsolute=realFilePath.replace(/\\/g,"/"),normalizedWorkspace=realWorkspace.replace(/\\/g,"/");if(!normalizedAbsolute.startsWith(`${normalizedWorkspace}/`)&&normalizedAbsolute!==normalizedWorkspace)return;try{await _updateGraphForFiles(workspaceRoot,[absoluteFilePath]),recordSuccess(input.sessionID),log(`[repo-graph] Incremental update for ${path142.basename(filePath)}`)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93),{count,advise}=recordFailure(input.sessionID,Date.now());if(error48(`[repo-graph] Incremental update failed: ${message}`),advise)warn(`[repo-graph] ${count} consecutive incremental update failures. The dependency graph may be stale. Consider reloading the workspace.`)}}}}init_review_receipt();init_constants();init_schema();init_manager2();init_detector();init_manager();init_state2();init_swarm_artifact_cache();import*as fs83 from"node:fs";import*as path148 from"node:path";init_utils2();init_manager();init_utils();import*as fs78 from"node:fs";import*as path143 from"node:path";var DEFAULT_DRIFT_CONFIG={staleThresholdPhases:1,detectContradictions:!0,maxSignals:5};function extractDecisionsFromContext(contextContent){let decisions=[],lines=contextContent.split(`
|
|
5321
5321
|
`),inDecisionsSection=!1,currentPhase=null,lineNumber=0;for(let i=0;i<lines.length;i++){let line=lines[i];lineNumber=i+1;let phaseMatch=line.match(/^## Phase (\d+)/);if(phaseMatch)currentPhase=parseInt(phaseMatch[1],10);if(line.trim()==="## Decisions"){inDecisionsSection=!0;continue}if(inDecisionsSection&&line.startsWith("## "))break;if(inDecisionsSection&&line.trim().startsWith("- ")){let text=line.trim().substring(2),confirmed=text.includes("✅")||text.includes("[confirmed]"),timestampMatch=text.match(/\[(\d{4}-\d{2}-\d{2}T[\d:.]+Z?)\]/),timestamp=timestampMatch?timestampMatch[1]:null,decisionPhaseMatch=text.match(/Phase (\d+)/),decisionPhase=decisionPhaseMatch?parseInt(decisionPhaseMatch[1],10):currentPhase;decisions.push({text:text.replace(/\s*\[.*?\]\s*/g,"").trim(),phase:decisionPhase,confirmed,timestamp,line:lineNumber})}}return decisions}function isDecisionStale(decision,currentPhase,threshold){if(decision.phase===null)return!decision.confirmed;let phaseDiff=currentPhase-decision.phase;if(phaseDiff>=threshold)return!0;if(phaseDiff===0&&!decision.confirmed)return!0;return!1}function findContradictions(decisions){let signals=[],contradictionPairs=[[["use","using","use ","adopt","implement","enable"],["not use","don't use","do not use","avoid","disable","remove"]],[["keep","retain","preserve"],["remove","delete","drop","eliminate"]],[["include","add","incorporate"],["exclude","skip","omit"]],[["require","mandatory","must"],["optional","skip","can skip"]],[["background","async"],["foreground","sync","synchronous"]]];for(let i=0;i<decisions.length;i++){let decisionA=decisions[i],textLower=decisionA.text.toLowerCase();for(let j=i+1;j<decisions.length;j++){let decisionB=decisions[j],textBLower=decisionB.text.toLowerCase();for(let[positiveKeywords,negativeKeywords]of contradictionPairs){let hasPositiveInA=positiveKeywords.some((k)=>textLower.includes(k)),hasNegativeInA=negativeKeywords.some((k)=>textLower.includes(k)),hasPositiveInB=positiveKeywords.some((k)=>textBLower.includes(k)),hasNegativeInB=negativeKeywords.some((k)=>textBLower.includes(k));if(hasPositiveInA&&hasNegativeInB||hasNegativeInA&&hasPositiveInB){let wordsA=textLower.split(/\s+/).slice(0,4).join(" "),wordsB=textBLower.split(/\s+/).slice(0,4).join(" ");if(wordsA.split(/\s+/).filter((w)=>w.length>2&&wordsB.includes(w)).length>0||wordsA.includes("file"))signals.push({id:`contradiction-${i}-${j}`,severity:"error",type:"contradiction",message:"Contradictory decisions detected",source:{file:"context.md",line:decisionA.line},relatedDecisions:[decisionA.text,decisionB.text],hint:"Review both decisions and clarify the intended approach."})}}}}return signals}function extractCurrentPhaseFromLegacy(planContent){if(!planContent)return null;let lines=planContent.split(`
|
|
5322
5322
|
`);for(let i=0;i<Math.min(30,lines.length);i++){let progressMatch=lines[i].trim().match(/^## Phase (\d+):?\s*(.*?)\s*\[IN PROGRESS\]/i);if(progressMatch)return parseInt(progressMatch[1],10)}for(let i=0;i<Math.min(5,lines.length);i++){let phaseMatch=lines[i].trim().match(/Phase:\s*(\d+)/i);if(phaseMatch)return parseInt(phaseMatch[1],10)}return null}async function analyzeDecisionDrift(directory,config3={}){let effectiveConfig={...DEFAULT_DRIFT_CONFIG,...config3},signals=[],analyzedAt=new Date().toISOString();try{let plan=await loadPlan(directory),currentPhase=plan?.current_phase??1;if(!plan){let legacyPhase=extractCurrentPhaseFromLegacy(await readSwarmFileAsync(directory,"plan.md")??"");if(legacyPhase!==null)currentPhase=legacyPhase}let contextPath=path143.join(directory,".swarm","context.md"),contextContent="";try{if(fs78.existsSync(contextPath))contextContent=fs78.readFileSync(contextPath,"utf-8")}catch(error93){return log("[DecisionDriftAnalyzer] context file read failed",{error:error93 instanceof Error?error93.message:String(error93)}),{hasDrift:!1,signals:[],summary:"",analyzedAt}}if(!contextContent)return{hasDrift:!1,signals:[],summary:"",analyzedAt};let decisions=extractDecisionsFromContext(contextContent);if(decisions.length===0)return{hasDrift:!1,signals:[],summary:"",analyzedAt};for(let decision of decisions)if(isDecisionStale(decision,currentPhase,effectiveConfig.staleThresholdPhases)){let hint;if(decision.phase!==null&&decision.phase<currentPhase)hint=`Decision was from Phase ${decision.phase}, current is Phase ${currentPhase}.`;else if(!decision.confirmed)hint="Decision has not been confirmed. Consider confirming or revisiting.";signals.push({id:`stale-${decision.line}`,severity:decision.phase!==null&&decision.phase<currentPhase?"warning":"warning",type:"stale",message:`Stale decision: "${decision.text.substring(0,50)}${decision.text.length>50?"...":""}"`,source:{file:"context.md",line:decision.line},hint})}if(effectiveConfig.detectContradictions){let contradictions=findContradictions(decisions);signals.push(...contradictions)}let limitedSignals=signals.slice(0,effectiveConfig.maxSignals),summary=buildDriftSummary(limitedSignals);return{hasDrift:limitedSignals.length>0,signals:limitedSignals,summary,analyzedAt}}catch(error93){return log("[DecisionDriftAnalyzer] drift analysis failed",{error:error93 instanceof Error?error93.message:String(error93)}),{hasDrift:!1,signals:[],summary:"",analyzedAt}}}function buildDriftSummary(signals){if(signals.length===0)return"";let warnings=signals.filter((s)=>s.severity==="warning"),errors5=signals.filter((s)=>s.severity==="error"),lines=["[SWARM DECISION DRIFT]"];if(errors5.length>0){lines.push(`⚠️ ${errors5.length} contradiction(s) detected:`);for(let err of errors5.slice(0,2)){let related=err.relatedDecisions?` (${err.relatedDecisions[0].substring(0,30)}... vs ${err.relatedDecisions[1].substring(0,30)}...)`:"";lines.push(` - ${err.type}: ${err.message}${related}`)}}if(warnings.length>0){lines.push(`\uD83D\uDCA1 ${warnings.length} stale decision(s) found:`);for(let warn2 of warnings.slice(0,3)){let hint=warn2.hint?` - ${warn2.hint}`:"";lines.push(` - ${warn2.message.substring(0,60)}${hint}`)}}return lines.push("See .swarm/context.md for details."),lines.join(`
|
|
@@ -5328,7 +5328,7 @@ ${checkpointMsg}
|
|
|
5328
5328
|
Recommendation: Consider escalating to user or taking a different approach
|
|
5329
5329
|
The current fix strategy appears to be cycling without progress`;return{eventLogged,checkpointCreated,message}}var recentToolCallsBySession=new Map,lastSpiralTimestampBySession=new Map,MAX_RECENT_CALLS=20,SPIRAL_THRESHOLD=5,SPIRAL_WINDOW_MS=300000,SPIRAL_COOLDOWN_MS=60000,MAX_TRACKED_SESSIONS2=500;function recordToolCall(tool3,args2,sessionId){let argsHash=typeof args2==="string"?args2.slice(0,100):JSON.stringify(args2??"").slice(0,100),calls=recentToolCallsBySession.get(sessionId);if(!calls)calls=[],recentToolCallsBySession.set(sessionId,calls);if(calls.push({tool:tool3,argsHash,timestamp:Date.now()}),calls.length>MAX_RECENT_CALLS)calls.shift()}async function detectDebuggingSpiral(_directory,sessionId){let now=Date.now(),lastTrigger=lastSpiralTimestampBySession.get(sessionId)??0;if(now-lastTrigger<SPIRAL_COOLDOWN_MS)return null;let windowCalls=(recentToolCallsBySession.get(sessionId)??[]).filter((c)=>now-c.timestamp<SPIRAL_WINDOW_MS);if(windowCalls.length<SPIRAL_THRESHOLD)return null;let lastN=windowCalls.slice(-SPIRAL_THRESHOLD),firstTool=lastN[0].tool,firstArgs=lastN[0].argsHash,allSameTool=lastN.every((c)=>c.tool===firstTool),allSimilarArgs=lastN.every((c)=>c.argsHash===firstArgs);if(allSameTool&&allSimilarArgs){if(lastSpiralTimestampBySession.set(sessionId,now),recentToolCallsBySession.delete(sessionId),lastSpiralTimestampBySession.size>MAX_TRACKED_SESSIONS2){for(let oldest of lastSpiralTimestampBySession.keys())if(oldest!==sessionId){lastSpiralTimestampBySession.delete(oldest),recentToolCallsBySession.delete(oldest);break}}return{pattern:"VELOCITY_RATIONALIZATION",severity:"HIGH",matchedText:`Tool '${firstTool}' called ${SPIRAL_THRESHOLD}+ times with identical args`,confidence:"HIGH"}}return null}function calculateAgeFactor(ageHours,config3){if(ageHours<=0)return 1;if(config3.mode==="exponential")return 2**(-ageHours/config3.half_life_hours);else{let linearFactor=1-ageHours/(config3.half_life_hours*2);return Math.max(0,linearFactor)}}function calculateBaseScore(candidate,weights,decayConfig){let{kind,metadata}=candidate,phase=kind==="phase"?1:0,currentTask=metadata.isCurrentTask?1:0,blockedTask=metadata.isBlockedTask?1:0,recentFailure=metadata.hasFailure?1:0,recentSuccess=metadata.hasSuccess?1:0,evidencePresence=metadata.hasEvidence?1:0,decisionRecency=0;if(kind==="decision"&&metadata.decisionAgeHours!==void 0)decisionRecency=calculateAgeFactor(metadata.decisionAgeHours,decayConfig);let dependencyProximity=1/(1+(metadata.dependencyDepth??0));return weights.phase*phase+weights.current_task*currentTask+weights.blocked_task*blockedTask+weights.recent_failure*recentFailure+weights.recent_success*recentSuccess+weights.evidence_presence*evidencePresence+weights.decision_recency*decisionRecency+weights.dependency_proximity*dependencyProximity}function rankCandidates(candidates,config3){if(!config3.enabled)return candidates.map((c)=>({...c,score:0}));if(candidates.length===0)return[];let scored=candidates.map((candidate)=>{let score=calculateBaseScore(candidate,config3.weights,config3.decision_decay);return{...candidate,score}});return scored.sort((a,b)=>{if(b.score!==a.score)return b.score-a.score;if(b.priority!==a.priority)return b.priority-a.priority;return a.id.localeCompare(b.id)}),scored.slice(0,config3.max_candidates)}init_extractors();init_knowledge_store();init_knowledge_validator();init_realtime_learning_nudge();import*as fs80 from"node:fs";var cache3=new Map;function getCachedGraph2(directory){let file3=getGraphPath(directory),stat13;try{stat13=fs80.statSync(file3)}catch{return cache3.delete(directory),null}let cached3=cache3.get(directory);if(cached3&&cached3.mtimeMs===stat13.mtimeMs&&cached3.size===stat13.size)return cached3.graph;let graph;try{graph=loadGraphSync(directory)}catch{return cache3.delete(directory),null}if(!graph)return cache3.delete(directory),null;return cache3.set(directory,{graph,mtimeMs:stat13.mtimeMs,size:stat13.size}),graph}function buildCoderLocalizationBlock(directory,targetFile){if(!targetFile)return null;let graph=getCachedGraph2(directory);if(!graph)return null;let normalized=targetFile.replace(/\\/g,"/").replace(/^\.\/+/,"");if(!getGraphNode(graph,normalized))return null;return["## REPO GRAPH — LOCALIZATION",getLocalizationContext(graph,normalized,{maxImporters:5,maxDeps:5,maxDepth:2}).summary,'_(Run `repo_map action="blast_radius"` for full transitive dependents.)_'].join(`
|
|
5330
5330
|
`)}function buildReviewerBlastRadiusBlock(directory,changedFiles){if(changedFiles.length===0)return null;let graph=getCachedGraph2(directory);if(!graph)return null;let normalized=changedFiles.map((f)=>f.replace(/\\/g,"/").replace(/^\.\/+/,"")).filter((f)=>getGraphNode(graph,f)!==void 0);if(normalized.length===0)return null;let blast=getBlastRadius(graph,normalized,3),directList=blast.directDependents.length===0?"(none)":blast.directDependents.slice(0,8).join(", ")+(blast.directDependents.length>8?`, +${blast.directDependents.length-8} more`:""),transitiveSummary=blast.transitiveDependents.length===0?"(none)":`${blast.transitiveDependents.length} files (depth ${blast.depthReached})`;return["## REPO GRAPH — BLAST RADIUS",` Changed: ${normalized.length<=3?normalized.join(", "):`${normalized.slice(0,3).join(", ")}, +${normalized.length-3} more`}`,` Direct dependents: ${directList}`,` Transitive dependents: ${transitiveSummary}`,` Risk: ${blast.riskLevel} (${blast.totalDependents} total)`,"_Verify these dependents still build/typecheck._"].join(`
|
|
5331
|
-
`)}import*as child_process9 from"node:child_process";import*as fs81 from"node:fs";import*as path145 from"node:path";import{extname as extname11}from"node:path";import{Query}from"web-tree-sitter";import{extname as extname10}from"node:path";var languageDefinitions=[{id:"javascript",extensions:[".js",".jsx"],commentNodes:["comment","line_comment","block_comment"]},{id:"typescript",extensions:[".ts"],commentNodes:["comment","line_comment","block_comment"]},{id:"python",extensions:[".py"],commentNodes:["comment"]},{id:"go",extensions:[".go"],commentNodes:["comment"]},{id:"rust",extensions:[".rs"],commentNodes:["line_comment","block_comment"]},{id:"php",extensions:[".php",".phtml"],commentNodes:["comment"]},{id:"java",extensions:[".java"],commentNodes:["line_comment","block_comment"]},{id:"c",extensions:[".c",".h"],commentNodes:["comment"]},{id:"cpp",extensions:[".cpp",".cxx",".cc",".hpp",".hxx",".hh"],commentNodes:["comment"]},{id:"csharp",extensions:[".cs"],commentNodes:["comment"]},{id:"ruby",extensions:[".rb"],commentNodes:["comment"]},{id:"swift",extensions:[".swift"],commentNodes:["comment","multiline_comment"]},{id:"kotlin",extensions:[".kt",".kts"],commentNodes:["line_comment","multiline_comment"]},{id:"dart",extensions:[".dart"],commentNodes:["comment","documentation_comment"]},{id:"css",extensions:[".css"],commentNodes:["comment"]},{id:"bash",extensions:[".sh",".bash"],commentNodes:["comment"]},{id:"powershell",extensions:[".ps1",".psm1"],commentNodes:["comment"]},{id:"ini",extensions:[".ini",".cfg",".conf"],commentNodes:["comment"]},{id:"regex",extensions:[".regex"],commentNodes:[]},{id:"tsx",extensions:[".tsx"],commentNodes:["comment"]}],extensionMap=new Map;for(let definition of languageDefinitions)for(let extension of definition.extensions)extensionMap.set(extension,definition);function getLanguageForExtension(extension){return extensionMap.get(extension.toLowerCase())}async function getParserForFile(filePath){let extension=extname10(filePath).toLowerCase(),language=getLanguageForExtension(extension);if(!language)return null;try{let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));return await loadGrammar2(language.id)}catch{return null}}init_runtime();var QUERIES2={javascript:`
|
|
5331
|
+
`)}import*as child_process9 from"node:child_process";import*as fs81 from"node:fs";import*as path145 from"node:path";import{extname as extname11}from"node:path";import{Query}from"web-tree-sitter";import{extname as extname10}from"node:path";var languageDefinitions=[{id:"javascript",extensions:[".js",".jsx",".mjs",".cjs"],commentNodes:["comment","line_comment","block_comment"]},{id:"typescript",extensions:[".ts"],commentNodes:["comment","line_comment","block_comment"]},{id:"python",extensions:[".py"],commentNodes:["comment"]},{id:"go",extensions:[".go"],commentNodes:["comment"]},{id:"rust",extensions:[".rs"],commentNodes:["line_comment","block_comment"]},{id:"php",extensions:[".php",".phtml"],commentNodes:["comment"]},{id:"java",extensions:[".java"],commentNodes:["line_comment","block_comment"]},{id:"c",extensions:[".c",".h"],commentNodes:["comment"]},{id:"cpp",extensions:[".cpp",".cxx",".cc",".hpp",".hxx",".hh"],commentNodes:["comment"]},{id:"csharp",extensions:[".cs"],commentNodes:["comment"]},{id:"ruby",extensions:[".rb"],commentNodes:["comment"]},{id:"swift",extensions:[".swift"],commentNodes:["comment","multiline_comment"]},{id:"kotlin",extensions:[".kt",".kts"],commentNodes:["line_comment","multiline_comment"]},{id:"dart",extensions:[".dart"],commentNodes:["comment","documentation_comment"]},{id:"css",extensions:[".css"],commentNodes:["comment"]},{id:"bash",extensions:[".sh",".bash"],commentNodes:["comment"]},{id:"powershell",extensions:[".ps1",".psm1"],commentNodes:["comment"]},{id:"ini",extensions:[".ini",".cfg",".conf"],commentNodes:["comment"]},{id:"regex",extensions:[".regex"],commentNodes:[]},{id:"tsx",extensions:[".tsx"],commentNodes:["comment"]}],extensionMap=new Map;for(let definition of languageDefinitions)for(let extension of definition.extensions)extensionMap.set(extension,definition);function getLanguageForExtension(extension){return extensionMap.get(extension.toLowerCase())}async function getParserForFile(filePath){let extension=extname10(filePath).toLowerCase(),language=getLanguageForExtension(extension);if(!language)return null;try{let{loadGrammar:loadGrammar2}=await Promise.resolve().then(() => (init_runtime(),exports_runtime));return await loadGrammar2(language.id)}catch{return null}}init_runtime();var QUERIES2={javascript:`
|
|
5332
5332
|
(function_declaration name: (identifier) @func.name) @func.def
|
|
5333
5333
|
(class_declaration name: (identifier) @class.name) @class.def
|
|
5334
5334
|
(export_statement) @export
|