@magic5644/graph-it-live 1.25.1 → 1.25.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.
@@ -3355,7 +3355,7 @@ ${e.toon}`,a=Lp(JSON.stringify(e,null,2),n);return Pr.record({toolName:"graphitl
3355
3355
  `,format:"toon"};try{let a=gw(e,t)?.content??vt([typeof e=="object"?e:{value:e}],{objectName:t}),r=JSON.stringify(e,null,2),i=Lp(r,a);return Pr.record({toolName:n??"unknown",jsonTokens:i.jsonTokens,toonTokens:i.toonTokens,savings:i.savings,truncated:!1,timestamp:Date.now()}),{content:a,format:"toon",tokenSavings:i}}catch(a){return $O.error("[formatDataAsToon] TOON conversion failed:",a),{content:JSON.stringify(e,null,2),format:"json"}}}function qO(e){if(!Array.isArray(e)||e.length===0)return"data";let t=e[0];if(typeof t!="object"||t===null)return"data";let n=Object.keys(t);return n.includes("file")||n.includes("filePath")?"files":n.includes("symbolName")||n.includes("symbol")?"symbols":n.includes("source")&&n.includes("target")?"edges":n.includes("node")||n.includes("id")?"nodes":n.includes("dependency")||n.includes("dependencies")?"dependencies":n.includes("caller")||n.includes("callers")?"callers":"data"}function GO(e){return qO(e.data)}zw();var ba="For an open-ended question, start with graphitlive_graph_context and come here when you need this specific cut.",Mw="REFERENCES: a function passed as an argument (register(save), items.map(format), Python cb=save, Java this::save, C# Register(Save)), and in .jsx/.tsx files a JSX component (<Card />, <UI.Card />) or an attribute value (onClick={save}, render={Row}), is a REFERENCES edge: rendered or passed, never reported as a call; register(save()) and onClick={() => save()} are CALLS edges at their line. REACT: Imports resolve through aliases, barrels and default exports to the declaration (a default export keeps its declared name), and memo(), forwardRef() and lazy(() => import('./literal')) to the wrapped component. Lowercase intrinsic tags, parameters or locals named like a function, members of objects other than this/self, non-literal or unknown wrappers, and unimported or ambiguous names stay unresolved, never guessed; props contracts are not analysed. VUE: a Vue 3 .vue file has a component node named after the file at its <template>; a template <Child />, handler (@click=save) or interpolation is a REFERENCES edge from it and save() a CALLS edge, also from an HTML <template src> of the workspace. Global, auto-imported and dynamic :is components stay unresolved.",XO="output capped by tokenBudget (default 4000, 0 = no limit); a cut sets truncated=true, omitted counts and nextOffset - pass it as offset to read the rest.",a_="needs the call graph index, built in the background when the Graph-It-Live view first loads (graph-it-live.preIndexCallGraph) or when the Call Graph panel opens; until then the tool returns an error.",QO={set_workspace:{summary:"Points this server session at the project root the other tools analyse.",lines:["WHEN: once per session, as setup before the first analysis. The root resolved at startup comes from WORKSPACE_ROOT or the working directory the client happened to spawn the server in, so it is often absent or points at the wrong project. Call this again during a session only to switch projects, or to reach a path outside the current root (paths outside it are rejected).","NOT THIS TOOL: it is setup, and answers no question about code. It is never the reply to a question about architecture, callers, dependencies, dead code or documentation - once the root is set, call the tool that answers the question. One call holds for the whole session; repeating it re-indexes for nothing.","RETURNS: workspace name (the path itself is reported relative to the new root), previous workspace, number of files indexed, indexing duration."]},graph_context:{summary:"Returns a token-bounded subgraph answering a question about the codebase - the default entry point for graph questions.",lines:["WHEN: any question spanning file dependencies, symbol calls, implementations, tests or impact; reach for a specialised tool only when this cannot express the cut you need.","WHY: one deterministic gateway over the same index the specialised tools use, with an explicit token budget so large graphs come back bounded instead of truncated arbitrarily.","MODES: search, neighbors, path, impact, refactor, overview.","RETURNS: nodes and edges with workspace-relative paths, an index revision and a freshness flag, and a cursor when results are paginated.",{lm:`LIMITS: ${a_}`}]},analyze_dependencies:{summary:"Lists the import/export statements of one file, with each specifier resolved to a path on disk.",lines:[`WHEN: "what does this file import", "what are this file's dependencies".`,"WHY: read from the parsed source, so tsconfig path aliases, implicit extensions and index files are already resolved.",{mcp:"RETURNS: per statement - module specifier, resolved absolute path, workspace-relative path, import type (import, require, export, dynamic, side-effect, mod = Rust `mod x;` declaration), line number.",lm:"RETURNS: one entry per resolved workspace file - module specifier, workspace-relative path, import type (import, require, export, dynamic, side-effect, mod = Rust `mod x;` declaration), line number. Unresolved and external imports are left out."},"SUPPORTS: TypeScript, JavaScript, Vue 3 (<script src> and <template src> are dependencies), Svelte, GraphQL."]},crawl_dependency_graph:{summary:"Builds the transitive file dependency graph reachable from one entry file.",lines:[{mcp:"WHEN: project architecture, full dependency tree from an entry point, circular-import detection.",lm:"WHEN: project architecture, full dependency tree from an entry point."},"WHY: crawls real import edges across the workspace rather than inferring structure from file names.",{mcp:"RETURNS: nodes (path, extension, dependency count, dependent count, circular flag, communityId/communityKey: by folder, or by import structure with communityMode 'louvain') and edges (import relations); paginated via offset/limit.",lm:"RETURNS: nodes (workspace-relative path) and edges (import relations, source and target). maxDepth defaults to the configured graph-it-live.maxDepth, else 3."},{mcp:`LIMITS: ${XO}`},ba]},find_referencing_files:{summary:"Lists every file that imports or references a given file (reverse dependency lookup).",lines:['WHEN: impact analysis, "who uses this file", refactoring-safety checks before changing or deleting a file.',"WHY: served from a prebuilt reverse index, so it covers the whole workspace rather than the files already in context.",{mcp:"RETURNS: absolute and workspace-relative path of each referencing file.",lm:"RETURNS: workspace-relative path, import type, line and module specifier of each referencing file."},"BARRELS: files that import the target's exports through re-export barrels (export { x } from, export *, chained) are listed after the direct importers, with via = the barrel they import.",ba]},expand_node:{summary:"Returns the dependencies of one file that are not already in a set of paths you provide.",lines:["WHEN: exploring a large graph incrementally, or lazily loading one node at a time.","WHY: crawls the file's transitive dependencies and drops what you already hold, so only newly discovered files come back.","RETURNS: the new nodes and edges only, with the same fields as crawl_dependency_graph."]},parse_imports:{summary:"Returns the import statements of one file: module specifier, import type and line.",lines:["WHEN: inspecting import style or alias usage, without the resolved paths.","WHY: uses the language-aware parser pipeline, so it is more accurate than a text search.","RETURNS: module specifier as written, import type, line number.","LIMITS: lists only imports that resolve to a workspace file, once per file - use graphitlive_resolve_module_path to debug one that does not."]},verify_dependency_usage:{summary:"Reports whether a source file actually uses any symbol from a target file it imports.",lines:["WHEN: identifying unused imports, or confirming a dependency edge is real before acting on it.","WHY: AST analysis of actual references, so an import that is never used is distinguished from one that is.","RETURNS: boolean."]},resolve_module_path:{summary:"Resolves one module specifier, as seen from a given file, to a path on disk.",lines:['WHEN: "where does this import point", or debugging alias and extension resolution.',"WHY: applies tsconfig path aliases, implicit extensions (.ts, .tsx, .js, .jsx, .vue, .svelte, .gql) and index-file resolution.",{mcp:"RETURNS: resolved absolute path and whether it lies inside the workspace, or null for an unresolvable or external module.",lm:"RETURNS: whether resolution succeeded and the resolved workspace-relative path."}]},get_index_status:{summary:"Reports the state of the dependency index backing the other tools.",lines:["WHEN: checking readiness before a large analysis, or explaining unexpectedly empty or incomplete results.",'WHY: distinguishes "no results" from "index not built yet", and tells whether imports were skipped because they resolve outside the workspace root (a monorepo sub-package misses its sibling packages).',{mcp:"RETURNS: index state, files indexed, reverse-index statistics, cache size and hit rate, warmup completion and duration, cacheFiles (on-disk bytes of the cached reverse index and call graph), and outOfRootImports (with examples, the relative monorepoRoot and a warning when above 0).",lm:"RETURNS: index state, readiness flag, whether the reverse index exists, cache size, reverse-index statistics (files indexed included), cacheFiles (on-disk bytes of the cached reverse index and call graph), and outOfRootImports (with examples, the relative monorepoRoot and a warning when above 0)."}]},invalidate_files:{summary:"Drops the cached analysis for specific files so the next query re-reads them.",lines:[{mcp:"WHEN: after editing files outside the watched workspace, when results look stale.",lm:"WHEN: results look stale after edits the file watcher missed. Paths must lie inside an open workspace folder."},"WHY: analysis is cached per file; the cache is otherwise refreshed by the file watcher.",{mcp:"RETURNS: how many files were invalidated, which were cleared, and which held no cache entry. The call graph re-extracts these files on the next graph query.",lm:"RETURNS: how many files were invalidated, which were cleared, and which held no cache entry."}]},rebuild_index:{summary:"Clears all cached analysis and re-indexes the whole workspace.",lines:["WHEN: after a branch switch or large refactor when the index no longer matches the tree; invalidate_files is enough for a few files.","WHY: restores a graph that is consistent with what is on disk.",{mcp:"RETURNS: files re-indexed, duration, new cache size, reverse-index statistics, and the call graph rebuilt from scratch (files, symbols, relations) or why it could not be.",lm:"RETURNS: rebuild duration and new cache size."},"LIMITS: takes seconds on a large workspace."]},get_symbol_graph:{summary:"Lists the symbols a file exports and the symbols OUTSIDE the file that each of them depends on.",lines:['WHEN: "which function in this file calls the database / uses X", scoping a refactor to one symbol rather than the whole file.',"WHY: ts-morph AST parsing, so import aliases are tracked back to their original names and type-only imports are separated from runtime ones.",{mcp:"RETURNS: exported symbols (name, kind, line, category) and symbol-to-symbol edges tagged runtime or type-only.",lm:"RETURNS: every symbol of the file (name, kind, line, category, internal ones included) and symbol-to-symbol edges tagged runtime or type-only."},"NOT THIS TOOL: for calls between symbols defined in the same file, use graphitlive_generate_codemap (its call flow section). This tool crosses the file boundary outward; that one stays inside it.",ba]},find_unused_symbols:{summary:"Lists the symbols a file exports that nothing else in the workspace imports.",lines:["WHEN: dead-code cleanup in one file, or checking which parts of an API are consumed.","WHY: cross-references the file's exports against the reverse index, then widens the used set through the file's internal call graph so a symbol reached only indirectly is not reported.","RETURNS: unused exported symbols (name, kind, line, category, confidence, reasons, evidence: importer count and first importers), unused and total counts, unused percentage, byConfidence.","CONFIDENCE: every item has confidence and reasons. high (importers-use-other-exports): the file is imported, no importer uses the export and no other evidence of use was found: a deletion candidate. medium: test-only-use (only tests use it), dynamic-import-in-workspace (a computed import() / require() / import_module may reach the file, or a Python importer reads attributes by computed name), convention:decorated (a Python decorator may register it), named-in-own-file (its file writes the name again: dropping export may be the fix), name-written-elsewhere (Rust: another Rust file writes the name), convention:test-file, named-in-deploy-manifest (a Dockerfile, compose, serverless, SAM or Procfile writes module.name, such as a Lambda handler), convention:generated (the file header says it is generated), published-deep-import (a published package without an exports map that the workspace imports by deep path, so outside projects may too). low (no-importer): nothing imports the file, often an entry point by convention (script, handler, config), review only. minConfidence (default high) sets the lowest level listed; byConfidence counts every item found and hint says how to list the others.","ENTRY POINTS: an export a manifest declares is never listed, nor what it re-exports or calls: package.json main, module, browser, types, exports, bin (npm default index.js for a publishable package without them), pyproject / setup.cfg / setup.py scripts and entry points, __main__.py, __all__, the pub items of a Cargo lib crate, Rust #[no_mangle] / #[proc_macro] functions; so is a JSX or Vue default export (convention:framework-default-export).","LIMITS: methods and nested functions are never exports; an export reached only through a string-keyed lookup can still be listed, so confirm a medium or low item before deleting."]},get_symbol_dependents:{summary:"Lists the symbols that use one given symbol - one hop, computed from source at call time.",lines:["WHEN: changing a signature and needing every call site, or assessing the blast radius of a symbol-level change.","WHY: walks the symbol graphs of every file that references the target, so file-level imports count as well as calls.","RETURNS: caller symbol id, file path and workspace-relative path per dependent, plus a total count.","PICKING BETWEEN THE THREE: this one for every reference, including file-level imports, computed fresh; graphitlive_get_symbol_callers for call sites only; graphitlive_query_call_graph for multi-hop traversal, callees, or relation types."]},trace_function_execution:{summary:"Follows the call chain outward from one symbol, recursively, across files.",lines:["WHEN: tracing a request through controller, service and repository, or mapping what a feature actually reaches.","WHY: follows calls through multiple files instead of stopping at direct dependencies; stops at external modules, at maxDepth, or on a cycle.","RETURNS: root symbol, call chain entries (depth, caller, callee, resolved path, 1-based line, relation=REFERENCES for a reference that is not a call), visited symbols, and whether maxDepth was hit. A name the imported module does not export has a null resolved path.",Mw,ba]},get_symbol_callers:{summary:"Lists the call sites of one given symbol - one hop, from the call graph index.",lines:['WHEN: the plain question "who calls X"; finding call sites before a rename; spotting a symbol with no callers.',"WHY: reads CALLS and REFERENCES edges from the indexed call graph, so it returns the symbols that call or render X, each labelled. File-level imports are not callers; use graphitlive_get_symbol_dependents for those.","RETURNS: one entry per caller symbol with workspace-relative path, line of its first edge, relation (CALLS, REFERENCES or USES; a call wins over a reference, a reference over a type use) and a type-only flag, plus runtime, reference and type-only counts. Type-only references are added only with includeTypeOnly. The source field says whether the call graph or the symbol dependents fallback answered (the call graph is used once indexed; line is null in the fallback).","PICKING BETWEEN THE THREE: this one for call sites; graphitlive_get_symbol_dependents for every reference (imports included) computed fresh from source; graphitlive_query_call_graph when you need more than one hop, callees as well as callers, or relation types such as INHERITS and IMPLEMENTS."]},analyze_breaking_changes:{summary:"Compares two versions of a file and reports which signature changes break callers.",lines:["WHEN: validating an edit before committing, or writing migration notes for an API change.","WHY: diffs the parsed signatures rather than the text, so added optional parameters are separated from breaking ones.",{mcp:"RETURNS: breaking changes with kind and description, severity, suggested migration steps, and the callers that need updating.",lm:"RETURNS: breaking changes (type, symbol, description, severity, old and new value, line) and non-breaking changes. Without newContent the current file on disk is used."},{mcp:"DETECTS: added required parameter, removed parameter, changed parameter type, changed return type, parameter reordering.",lm:"DETECTS: added required parameter, removed parameter, changed parameter or return type, optional made required, reduced visibility, removed or changed interface member, changed type alias."},"INPUT: oldContent must be the full previous file content, not a placeholder. With symbolName, an unknown symbol returns an error listing close name matches, a symbol missing from a non-empty oldContent that declares nothing returns an error, and a symbol new in newContent is reported as a non-breaking change."]},review_pr:{summary:"Reviews a local Git diff and reports the risk it carries, with per-symbol evidence.",lines:["WHEN: before opening a pull request, or as a CI gate.","WHY: combines the parsed signatures of both revisions with the workspace index, so signature changes are scored against their real callers.","RETURNS: deterministic risk level, per-symbol evidence, impact counts, and an explicit list of what could not be analysed. With graphit.architecture.json, `architecture` says whether the diff degrades or improves the declared rules: new, resolved and unchanged violations per rule, unit cycles, rules-file edits; a new error violation raises the risk. A changed .vue lists the props and events it adds or removes by name (no type check), a contract typed by an imported type or built at runtime as partial.",{mcp:"LIMITS: maxFiles caps changed files (default 200, no upper bound); time and memory grow with it, the call stops after 10 minutes and other tool calls wait until it ends.",lm:"LIMITS: runs git in the first workspace folder; impact counts are incomplete while background indexing runs; maxFiles caps changed files (default 200, no upper bound), time and memory grow with it."}]},get_impact_analysis:{summary:"Reports everything affected by changing one symbol, direct and transitive.",lines:["WHEN: assessing a refactor before starting it, or prioritising which call sites to update first.","WHY: walks the symbol reverse index outward, keeping runtime and type-only impact separate and aggregating per file.",{mcp:"RETURNS: impact level (high, medium, low), total impact count, runtime versus type-only breakdown, impacted symbols with depth (1 = direct), affected files, and a written summary. An unknown symbol returns an error listing close name matches.",lm:"RETURNS: impact level (high, medium, low), total impact count, runtime versus type-only breakdown, impacted symbols with depth (1 = direct) and affected files. Transitive impact only with includeTransitive. An unknown symbol returns an error listing close name matches."},"An item that renders or passes the symbol without calling it (<Card />, onClick={save}) is a runtime impact with relation=REFERENCES.",ba]},analyze_file_logic:{summary:"Returns the call hierarchy among the symbols defined INSIDE one file, ignoring anything it imports.",lines:["WHEN: understanding how a file works internally, or spotting recursion before a refactor.","WHY: built from the file's AST, so no language server is needed. Calls are matched by name within the file.","RETURNS: nodes (symbol id, LSP SymbolKind number, type, export status, start/end line range), call edges with call-site line numbers, and cycle detection with the symbols involved.","NOT THIS TOOL: for what this file's symbols reach in OTHER files, use graphitlive_get_symbol_graph.","SUPPORTS: TypeScript, JavaScript, Python, Rust.",ba]},generate_codemap:{summary:"Returns one file's exports, internals, dependencies, dependents and internal call flow in a single call.",lines:["WHEN: getting oriented in an unfamiliar file, or gathering the full context of a file before refactoring it.","WHY: one call in place of analyze_dependencies, get_symbol_graph and find_referencing_files together, plus the calls between the file's own symbols.","RETURNS: path, language, line count, exported and internal symbols, dependencies, dependents, intra-file call flow, cycle detection.","SUPPORTS: TypeScript, JavaScript, Python, Rust, Vue 3, Svelte."]},query_call_graph:{summary:"Traces calls across files for several hops, in either direction, from a SQLite-backed call graph.",lines:['WHEN: "who calls X" (direction=callers, depth=1), "what does X call" (direction=callees), multi-hop traversal ("three levels deep"), or cycle detection across modules.',{mcp:"WHY: built from tree-sitter AST analysis, so it holds real call edges (CALLS, INHERITS, IMPLEMENTS) and runtime references (REFERENCES) rather than import edges. Type-only references (USES) are added with includeTypeOnly.",lm:"WHY: built from tree-sitter AST analysis, so it holds real call edges (CALLS, INHERITS, IMPLEMENTS), runtime references (REFERENCES) and type-only references (USES) rather than import edges. Every relation type is returned unless relationTypes narrows it."},Mw,{mcp:"RETURNS: the matched symbol, its callers and callees with file and line, relation type, and a cyclic flag per edge.",lm:"RETURNS: the matched symbol, its callers and callees with file and call-site line, relation type, and a cyclic flag per edge. Defaults: direction=both, depth=2."},"SELECTING: two same-name methods in one file return reason=ambiguous with candidates; pass one candidate's symbolId or startLine to select it exactly. A stale selector returns reason=stale_selector (ids embed the line and change after edits); 'Class.method' names are not supported.","NOT THIS TOOL: for every file that imports a file, use graphitlive_find_referencing_files.",{mcp:"LIMITS: the first call indexes the workspace (3-8s); later queries are fast. Output capped by tokenBudget (default 4000, 0 = no limit); a cut sets truncated=true, omitted counts and nextOffset - pass it as offset to read the rest.",lm:`LIMITS: ${a_}`}]},scan_dead_code:{summary:"Lists the unused exported symbols across a whole workspace or directory.",lines:["WHEN: auditing code quality, or cleaning up before a refactor; use find_unused_symbols for a single file.","WHY: combines the reverse index with per-file symbol analysis, so the scan stays linear instead of comparing every file against every other.","RETURNS: files scanned, files holding dead code, total unused symbols, per-file unused symbol lists (each with confidence, reasons and evidence), byConfidence, scan duration, and truncated with filesBeyondLimit when maxFiles stopped the scan. Without maxFiles every analysable file in scope is scanned (no upper bound). truncated=true means a partial result: report it as partial, never as the whole workspace.","CONFIDENCE: every item has confidence and reasons. high (importers-use-other-exports): the file is imported, no importer uses the export and no other evidence of use was found: a deletion candidate. medium: test-only-use (only tests use it), dynamic-import-in-workspace (a computed import() / require() / import_module may reach the file, or a Python importer reads attributes by computed name), convention:decorated (a Python decorator may register it), named-in-own-file (its file writes the name again: dropping export may be the fix), name-written-elsewhere (Rust: another Rust file writes the name), convention:test-file, named-in-deploy-manifest (a Dockerfile, compose, serverless, SAM or Procfile writes module.name, such as a Lambda handler), convention:generated (the file header says it is generated), published-deep-import (a published package without an exports map that the workspace imports by deep path, so outside projects may too). low (no-importer): nothing imports the file, often an entry point by convention (script, handler, config), review only. minConfidence (default high) sets the lowest level listed; byConfidence counts every item found and hint says how to list the others.",{mcp:"ENTRY POINTS: an export a manifest declares is never listed, nor what it re-exports or calls: package.json main, module, browser, types, exports, bin (npm default index.js for a publishable package without them), pyproject / setup.cfg / setup.py scripts and entry points, __main__.py, __all__, the pub items of a Cargo lib crate, Rust #[no_mangle] / #[proc_macro] functions; so is a JSX or Vue default export (convention:framework-default-export). verbose=true lists them as excluded, each with its reason (declared:package.json#main, attribute:#[no_mangle], ...).",lm:"ENTRY POINTS: an export a manifest declares is never listed, nor what it re-exports or calls: package.json main, module, browser, types, exports, bin (npm default index.js for a publishable package without them), pyproject / setup.cfg / setup.py scripts and entry points, __main__.py, __all__, the pub items of a Cargo lib crate, Rust #[no_mangle] / #[proc_macro] functions; so is a JSX or Vue default export (convention:framework-default-export)."},"UNREFERENCED FILES: unreferencedFiles=true lists whole files instead (the cheapest deletions), from the reverse index without symbol analysis: low (no-importer) when no workspace file imports the file, directly or as a barrel's target; medium (test-only-use) when only tests import it, with testImporters = the tests to delete or clean up with it, a quick cleanup win. Other reasons as for exports: dynamic-import-in-workspace, named-in-deploy-manifest, convention:generated, published-deep-import. Each file has exports (0 for a script or side-effect module); minConfidence defaults to low. Left out, and listed as excluded with verbose: test files, manifest entry points, files whose path a non-test file writes (named-in:<file>: a bundler entry, a package.json script, a CI workflow or action, a Makefile, justfile, Taskfile or .sh script, working-directory and cd honoured), JSX/Vue default exports, files a framework loads by file name (convention:framework-route, when a package.json above depends on it: Next.js app/pages routes, SvelteKit, Remix, Nuxt incl. layers, Astro, Expo Router, Gatsby, Storybook stories), files a bundler loads (import.meta.glob, new URL(..., import.meta.url), an HTML page's script entry), files named by a run-time template (config.${mode}.ts), migrations folders (convention:migration), .<tool>rc files, .d.ts/.d.mts/.d.cts declarations, tool configs (*.config.ts), files a folder's .gitignore ignores (build output) and Python package __init__.py. CASCADE: then the files only those dead files and tests import, chains and dead cycles included, listed after them with reason cascade, via = their dead importers, at a confidence never above theirs (low for a cycle nothing else imports); an entry point, a live importer, a dead file something may still load (dynamic import, deploy manifest) or a dead file that runs as a program (no export like main.ts, or a __main__ guard) stops it. Every dead file has tests = the tests that import nothing but dead files, to delete with it.",{mcp:"LIMITS: needs background indexing to have finished; duration grows with file count (about 90 s for 12,000 files), the call stops after 10 minutes and other tool calls wait until it ends, so narrow scopePath or set maxFiles on very large repositories; an export reached only through a dynamic lookup can still be listed.",lm:"LIMITS: scopePath must be an absolute path inside the workspace; results are incomplete while background indexing runs; duration grows with file count (about 90 s for 12,000 files); an export reached only through a dynamic lookup can still be listed."}]},query_natural_language:{summary:"Returns the subgraph relevant to a plain-language question, for you to turn into an answer.",lines:["WHEN: exploring a codebase from a concept rather than a known file or symbol name.",'WHY: extracts keywords (English, French, German, Spanish, Chinese or Russian questions, mapped to English identifier stems), scores seed nodes by keyword specificity and file path over the call graph index, then traverses outward from them. English identifier-like keywords in the question ("reference compute python") give the most precise seeds.',"RETURNS: the question, the extracted keywords, the subgraph, and timing and truncation metadata.",{mcp:"LIMITS: returns graph data, not prose - you write the answer from it. The first call indexes the workspace (3-8s).",lm:`LIMITS: returns graph data, not prose - you write the answer from it; ${a_}`}]},generate_wiki:{summary:"Writes a navigable markdown wiki of the workspace from the call graph index.",lines:["WHEN: producing browsable documentation, or a persistent overview of files and their relationships.","WHY: one article per source file, cross-linked through real caller and callee edges.","RETURNS: number of articles written, index path, articles directory, and the top files by hub score.","LIMITS: writes files to disk, and fails instead of replacing an index.md or article it did not generate. The first call indexes the workspace (3-8s)."]},explore_architecture:{summary:"Explores the workspace architecture step by step: groups, one group's boundary, then the file pairs behind a group edge.",lines:['WHEN: "how is this project structured", "what depends on the analyzer layer", "why does group A import group B".',"WHY: aggregates the whole import graph by folder domain (communityMode 'path') or import structure ('louvain') before any paging, so counts match graph-it architecture --groups and every group edge is backed by its file pairs.","RETURNS: no group/from/to - totals, unassigned files, the largest groups and group edges; group (a number is an id, a string a key or label) - its files and incoming / outgoing group edges; from + to - the distinct file pairs of that edge; level 'units' - packages (else top-level folders) with their layer (0 = depends on no other unit), role (function, micro-frontend, frontend, service, library, tooling, unknown) with its confidence (inferred, or declared in graphit.architecture.json) and evidence, roleCounts, layerCount, unit edges flagged down, upward or cycle, and the cycle count; level 'units' + from + to (unit keys, e.g. 'apps/web', '(root)') - the file pairs of that unit edge, sorted by target then source, total = the edge's file-pair count; folder (a unit key, or a group key of a folder level, path mode) - the same views one level down: its sub-folders and own files as groups, nestedGroups those that go deeper; view 'matrix' (with level 'units', folder or neither) - the level's dependency structure matrix: rows by layer with each cycle's rows together, non-zero cells (row imports column, diagonal = pairs inside, upward = above the diagonal), Ce/Ca/instability per row with the formula, cycles and totals. Each response states its context (grouping, graph kind, truncation, revision) and separates code facts from computed groupings.","LIMITS: import relations only (static analysis, not observed execution); every list (groups, group edges, files, incoming, outgoing, pairs, matrix cells) paginated by offset/limit (default 50) with totals, truncated and nextOffset; analyses every source file on each call, so pass the previous context.revision with a group id or offset: the call fails if the architecture changed, and you restart from the summary. Symbols and lines come from graphitlive_find_referencing_files, graphitlive_query_call_graph and graphitlive_get_impact_analysis."]},check_architecture:{summary:"Checks the workspace imports against the architecture rules declared in graphit.architecture.json.",lines:['WHEN: "does this change break the architecture", "may the frontend import the backend", before adding an import across packages, or to list the violations a CI gate reports.',"WHY: rules are human annotation (elements selected by path patterns, units or unit roles; forbid, allowOnly, noCycles); the check compares every static import pair with them, as graph-it check-architecture does, and a baseline separates accepted violations from new ones.","RETURNS: passed (false when an error-severity violation is new), totals per severity, each rule with its violation count and element pairs, the violating file pairs (source, target, import line, element pairs, new) sorted by rule, files no element selects, baseline entries no longer found (resolved), and config warnings (patterns matching nothing). Invalid configs fail with the JSON path of each error.","LIMITS: import relations only (static analysis), no rule on symbols or calls; violations paginated by offset/limit (default 50) with totals; analyses every source file on each call, so pass the previous context.revision with an offset: the call fails if the code, rules or baseline changed. Pair it with graphitlive_explore_architecture to see the units and edges the rules refer to."]},export_architecture_diagram:{summary:"Draws a static architecture diagram of the workspace (units, one unit or folder's groups, or their dependency matrix) as SVG or self-contained HTML, or returns its data as a diagram spec.",lines:[`WHEN: "draw the architecture", "give me a diagram for the README / the PR / the design doc", or to share as a picture the structure that graph-it architecture reports as data. For a polished or branded diagram drawn by a diagram skill, use diagramFormat 'diagram-spec' and draw only the nodes and edges it lists.`,"WHY: the same diagram as graph-it diagram and the VS Code Architecture view: layers top to bottom (layer 0 at the bottom), cycle members in one block, stroke widths by file-pair count; with rules, the violations of graphit.architecture.json in the error colour and the baseline's accepted ones dashed. Deterministic: one index revision gives one geometry, with no network and no absolute path in the output.","RETURNS: format, counts (one line, e.g. '7 units \xB7 3 layers \xB7 1 cycle \xB7 0 violations', covering the whole level), and either markup (the SVG or HTML, inline up to 60,000 characters) or path (workspace-relative file written, when output is set or the diagram is over the cap; default architecture.<diagramFormat>, architecture.diagram-spec.json for a spec) with its size in characters. A diagram-spec is JSON (schemas/diagram-spec.schema.json): every node with label, layer, file count and role, layers, weighted edges with kind and broken rules, cycles, violations and the caption lines.","LIMITS: import relations only (static analysis); at most 60 nodes drawn (a spec lists them all), the largest kept and a note counting the others, so draw one folder at a time on large levels; output must stay inside the workspace and an existing file there is replaced; analyses every source file on each call."]},get_session_stats:{summary:"Reports how large this session's TOON responses were against their JSON equivalent, plus real token usage.",lines:["WHEN: asked how much the TOON encoding is saving, or for a summary of tool usage.","WHY: encoding sizes are counted with the cl100k_base tokenizer, an estimate of what a model reads; provider-reported LLM usage is reported separately and never mixed into that estimate.","RETURNS: per-tool and total encoding sizes for this session, llmUsage as its own section, the persisted history window (last 50 sessions per source: mcp, cli, vscode) by source and in total, and cumulative totals since the first counted session.","LIMITS: compares two encodings of the same data - not a saving attributable to the tools themselves."]}};function ez(e,t){let{summary:n,lines:a}=QO[e],r=a.map(i=>typeof i=="string"?i:i[t]).filter(i=>i!==void 0);return`${n}
3356
3356
 
3357
3357
  ${r.join(`
3358
- `)}`}function Ue(e){return ez(e,"mcp")}import*as _a from"node:path";var o_=["path","louvain"];var Lw=["units","folder","matrix"],Fw=["svg","html","diagram-spec"];var Bw=["light","dark"];function jw(e,t){let n=t?.replaceAll("\\","/");return{view:e??(n===void 0?"units":"folder"),folder:n}}cr();var p6=new Set("(,=:[!&|?{};~+-*%<>^");var Uw=["high","medium","low"];cr();jp();cr();var Ws="1.1.0",Hw="1.25.1",k6=U.enum(["json","toon"]).default("json").describe("Output format: 'json' (default) or 'toon' (Token-Oriented Object Notation for reduced token usage)"),dn={FILE_PATH:1024,SYMBOL_NAME:500,FILE_CONTENT:1024*1024,GENERIC_STRING:10*1024},nt=U.string().max(dn.FILE_PATH,`File path exceeds maximum length of ${dn.FILE_PATH} bytes`).refine(e=>!e.includes("\0"),"File path contains null bytes"),Sa=U.string().max(dn.SYMBOL_NAME,`Symbol name exceeds maximum length of ${dn.SYMBOL_NAME} bytes`).refine(e=>!e.includes("\0"),"Symbol name contains null bytes"),qw=U.string().max(dn.FILE_CONTENT,`File content exceeds maximum size of ${dn.FILE_CONTENT} bytes (~1 MB)`).refine(e=>!e.includes("\0"),"File content contains null bytes"),Ea=U.string().max(dn.GENERIC_STRING,`String exceeds maximum length of ${dn.GENERIC_STRING} bytes`).refine(e=>!e.includes("\0"),"String contains null bytes"),va={MAX_LIMIT:1e4,MAX_OFFSET:1e5,DEFAULT_LIMIT:1e3},tz=U.object({hubScore:U.number().min(0,"hubScore must be >= 0").max(1,"hubScore must be <= 1"),loc:U.number().int().positive().optional(),fileExtension:U.string().optional(),communityId:U.number().int().min(0).optional(),communityKey:U.string().optional()}),rz=U.object({source:U.string(),target:U.string(),relationType:U.enum(["dependency","call","reference","containment"]).optional()}),w6=U.object({nodes:U.array(U.string()),edges:U.array(rz),nodeLabels:U.record(U.string(),U.string()).optional(),parentCounts:U.record(U.string(),U.number()).optional(),unusedEdges:U.array(U.string()).optional(),nodeMetadata:U.record(U.string(),tz).optional()}),Vw=U.object({workspacePath:nt.describe("Absolute path to the project/workspace directory to analyze"),tsConfigPath:nt.optional().describe("Optional path to tsconfig.json for path alias resolution. Omitted: kept when the same workspace is selected again, otherwise each file uses its nearest tsconfig.json"),excludeNodeModules:U.boolean().optional().describe("Whether to exclude node_modules (default: true)"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum crawl depth (default: 50, min: 1, max: 100)")}),Ww=U.object({filePath:nt.describe("Absolute path to the file to analyze")}),Kw=U.union([U.literal(0),U.number().int().min(500).max(16e3)]).default(4e3).optional().describe("Maximum output size in tokens (default: 4000, 500-16000, or 0 for no limit). A larger result is cut and reports truncated=true, omitted counts and nextOffset; pass nextOffset as offset to read the rest."),c_=U.number().int().min(0).max(va.MAX_OFFSET).optional().describe("Items to skip, usually the nextOffset of the previous response (default: 0)"),Jw=U.object({entryFile:nt.describe("Absolute path to the entry file"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum depth to crawl (default: from config, min: 1, max: 100)"),limit:U.number().min(1).max(va.MAX_LIMIT).optional().describe(`Maximum number of nodes to return (for pagination, max: ${va.MAX_LIMIT})`),offset:U.number().min(0).max(va.MAX_OFFSET).optional().describe(`Number of nodes to skip (for pagination, max: ${va.MAX_OFFSET})`),onlyUsed:U.boolean().optional().describe("If true, only returns edges where symbols are actually used (requires AST analysis, slower)"),communityMode:U.enum(o_).optional().describe("How nodes are grouped into communityId/communityKey: 'path' (default) by folder, 'louvain' by import structure (deterministic Louvain over the crawled graph)"),tokenBudget:Kw}),Zw=U.object({targetPath:nt.describe("Absolute path to the file to find references for")}),Yw=U.object({sourceFile:nt.describe("Absolute path to the source file (the one importing using symbols)"),targetFile:nt.describe("Absolute path to the target file (the one providing symbols)")}),Xw=U.object({fromFile:nt.describe("Absolute path of the file containing the import"),moduleSpecifier:Ea.describe('The module specifier to resolve (e.g., "./utils", "@/components/Button")')}),R6=U.object({}),Gw=1e4,Qw=U.object({filePaths:U.array(nt).max(Gw).describe(`Array of absolute file paths to invalidate from the cache (max: ${Gw} per call; use rebuild_index for the whole workspace). Needed only for edits the file watcher missed: it invalidates changed files on its own.`)}),T6=U.object({}),e1=U.object({filePath:nt.describe("Absolute path to the file to analyze for symbols")}),t1=U.enum(Uw).optional().describe("Lowest confidence listed (default: high). high: the file is imported, no importer uses the export and no other evidence of use was found: a deletion candidate. medium: only tests use it, a computed import may reach it, a decorator may register it, its name is written again in its file (or, in Rust, in another file), or it sits in a test file. low: nothing imports the file (entry point by convention, script, config), review only. Unlisted items are counted in byConfidence."),r1=U.object({filePath:nt.describe("Absolute path to the file to check for unused exported symbols"),minConfidence:t1}),n1=U.object({filePath:nt.describe("Absolute path to the file containing the root symbol"),symbolName:Sa.describe("Name of the root symbol to trace from"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum depth to trace the call chain (default: 10, min: 1, max: 100)")}),i1=U.object({filePath:nt.describe("Absolute path to the file to analyze"),symbolName:Sa.optional().describe("Optional: Only analyze changes to this specific symbol"),oldContent:qw.describe("The old version of the file content"),newContent:qw.optional().describe("The new version of the file content (if not provided, reads current file)")}),a1=U.object({baseRef:Ea.describe("Git base ref to compare against, for example origin/main"),headRef:Ea.optional().describe("Optional Git head ref; defaults to the checked-out worktree"),maxFiles:U.number().int().min(1).optional().describe("Optional cap on changed files analysed (default: 200, no upper bound)"),maxDepth:U.number().int().min(1).max(10).optional()}),o1=U.object({filePath:nt.describe("Absolute path to the file being modified"),symbolName:Sa.describe("Name of the symbol being modified"),includeTransitive:U.boolean().optional().describe("Include transitive dependents (default: false)"),maxDepth:U.number().min(1).max(20).optional().describe("Maximum depth for transitive analysis (default: 3, min: 1, max: 20)")}),I6=U.object({filePath:nt.describe("Absolute path to the file to analyze"),includeExternal:U.boolean().optional().describe("Include calls to external modules (default: false)")}),P6=U.object({filePath:nt.describe("Absolute path to the file to generate a codemap for")}),s1=U.object({filePath:nt.describe("Absolute path to the file containing the target symbol."),symbolName:Sa.describe("Name of the symbol to query (function, class, method). A bare name shared by several symbols in the file returns reason='ambiguous' with candidates; qualified names such as 'Class.method' are not supported."),symbolId:Sa.optional().describe("Exact node id taken from a previous result or candidate (valid for the current index only, since ids embed the line). Narrows symbolName to that node; a stale id returns reason='stale_selector'."),startLine:U.number().int().min(0).optional().describe("Declaration line of the symbol, 0-based like 'startLine' in results and candidates (editor line 3 is 2). Selects one of several same-name symbols."),direction:U.enum(["callers","callees","both"]).optional().describe("Direction of traversal: 'callers', 'callees', or 'both' (default: 'both')"),depth:U.number().min(1).max(10).optional().describe("Maximum BFS traversal depth (default: 2, min: 1, max: 10)"),relationTypes:U.array(U.enum(["CALLS","INHERITS","IMPLEMENTS","USES","REFERENCES"])).optional().describe("Filter by relation types (default: CALLS, INHERITS, IMPLEMENTS and REFERENCES; USES is added with includeTypeOnly)"),includeTypeOnly:U.boolean().optional().describe("Also include USES edges (type-only references such as interfaces and type aliases). Default is false. Ignored when relationTypes is set."),offset:c_,tokenBudget:Kw}),l1=U.object({question:U.string().max(1024).describe("Natural language question about the codebase"),depth:U.number().int().min(1).max(5).default(2).optional().describe("BFS traversal depth from seed nodes (default: 2, min: 1, max: 5)"),tokenBudget:U.number().int().min(500).max(16e3).default(4e3).optional().describe("Maximum token budget for the output subgraph (default: 4000)"),fileFilter:U.string().max(256).optional().describe("Glob pattern to restrict search scope"),outputFormat:U.enum(["toon","json"]).default("toon").optional().describe("Output format. 'toon' (default): compact TOON encoding (header+rows), typically 30-50% fewer tokens than JSON for node/edge lists \u2014 prefer this unless you need to re-parse structured JSON programmatically. 'json': short-key JSON object per node/edge \u2014 use when the calling client needs to JSON.parse() the result directly (e.g. building its own graph structure).")}),s_=U.object({id:Ea.refine(e=>e.trim().length>0,"Seed ID must not be empty").optional(),filePath:nt.refine(e=>e.trim().length>0,"Seed file path must not be empty").optional(),symbolName:Sa.refine(e=>e.trim().length>0,"Seed symbol name must not be empty").optional(),label:Ea.refine(e=>e.trim().length>0,"Seed label must not be empty").optional()}).refine(e=>e.id!==void 0||e.filePath!==void 0||e.symbolName!==void 0||e.label!==void 0,"A seed must contain an id, filePath, symbolName, or label"),nz=U.enum(["CONTAINS","IMPORTS","CALLS","INHERITS","IMPLEMENTS","USES","TESTED_BY","IMPACTED_BY","BELONGS_TO","REFERENCES","EXPLAINS","DOCUMENTS"]),c1=U.object({question:U.string().max(1024).optional(),seeds:U.array(s_).max(500).optional(),mode:U.enum(["search","neighbors","path","impact","refactor","overview"]).optional(),from:s_.optional(),to:s_.optional(),relations:U.array(nz).max(12).refine(e=>new Set(e).size===e.length,"Relations must be unique").optional(),scope:U.string().max(256).optional(),depth:U.number().int().min(1).max(5).optional(),maxNodes:U.number().int().min(1).max(500).optional(),tokenBudget:U.number().int().min(500).max(16e3).optional(),directed:U.boolean().optional(),cursor:U.string().min(1).max(4096).optional(),detail:U.enum(["compact","standard","full"]).optional(),response_format:U.enum(["json","markdown","toon"]).optional()}).superRefine((e,t)=>{let n=e.question!==void 0&&e.question.trim().length>0,a=(e.seeds?.length??0)>0,r=e.from!==void 0,i=e.to!==void 0;r!==i&&t.addIssue({code:"custom",message:"Both from and to are required for a path request"}),e.mode==="path"&&!(r&&i)&&t.addIssue({code:"custom",message:"Path mode requires both from and to"}),e.mode!==void 0&&e.mode!=="path"&&(r||i)&&t.addIssue({code:"custom",message:"from and to are only valid in path mode"}),e.mode===void 0&&r&&i&&(n||a)&&t.addIssue({code:"custom",message:"Set mode to path when combining endpoints with a question or seeds"}),!n&&!a&&!(r&&i)&&t.addIssue({code:"custom",message:"Provide a question, at least one seed, or both from and to"})}).transform(e=>{let t=e.question!==void 0&&e.question.trim().length>0,n=(e.seeds?.length??0)>0,a=e.from!==void 0&&e.to!==void 0;return e.mode===void 0&&!t&&!n&&a?{...e,mode:"path"}:e}),D6=U.object({outputDir:nt.optional().refine(e=>e===void 0||!_a.isAbsolute(e),"Output directory must be relative to the workspace").describe("Workspace-relative output directory for wiki files (default: wiki)"),topHubsLimit:U.number().int().min(1).max(50).optional().describe("Number of top hub files to list (max: 50, default: 10)"),scope:nt.optional().refine(e=>e===void 0||!_a.isAbsolute(e),"Scope must be relative to the workspace").describe("Relative path within workspace to restrict wiki to (e.g. 'src/')"),exclude:U.array(Ea).max(100).optional().describe("Relative glob-like patterns to exclude")}).strict(),l_=U.union([U.number().int().min(0),U.string().min(1).max(256)]).describe("Numeric group id from a previous response, or a group key (e.g. 'analyzer') or label as a string; 0 or 'unassigned' for files without a group"),u1=U.object({communityMode:U.enum(o_).optional().describe("How files are grouped: 'path' (default) by folder domain, 'louvain' by import structure"),maxFiles:U.number().int().min(1).max(va.MAX_OFFSET).optional().describe("Analyse only the first maxFiles source files, like graph-it architecture --maxFiles (default: all)"),level:U.enum(["groups","units"]).optional().describe("groups (default): folder or Louvain groups; units: packages (else top-level folders) with their layers, roles and role evidence, unit edges (down, upward, cycle) and cycles, like graph-it architecture --level units"),folder:U.string().min(1).max(1024).optional().describe("communityMode 'path' only: walk down one level, below this unit key (from level units) or group key; groups are then its sub-folders plus its own files (key = folder), nestedGroups those holding sub-folders; group, from and to then name groups of this level"),view:U.enum(["matrix"]).optional().describe("matrix: the dependency structure matrix of the level (units with level units, a folder's groups with folder, else the groups): rows ordered by layer with each cycle's rows together, non-zero cells (row imports column, diagonal = pairs inside) paged by offset/limit, per-row Ce/Ca/instability with their formula, cycles and totals of every cell, like graph-it architecture --matrix"),group:l_.optional().describe("Return this group's files and its incoming / outgoing group edges"),from:l_.optional().describe("Source group of the edge whose file pairs to return (requires to); with level units, a unit key such as 'apps/web' or '(root)'"),to:l_.optional().describe("Target group of the edge whose file pairs to return (requires from); with level units, a unit key"),limit:U.number().int().min(1).max(500).optional().describe("Items per page: groups and group edges, a group's files and its incoming and outgoing edges, or file pairs (default: 50)"),offset:c_,revision:U.string().regex(/^[0-9a-f]{64}$/).optional().describe("context.revision of the response the group ids or offset come from; the call fails if the architecture has changed since"),response_format:U.enum(["json","markdown","toon"]).optional().describe("Output format: 'json', 'markdown', or 'toon' (default: toon)")}).superRefine((e,t)=>{e.from===void 0!=(e.to===void 0)&&t.addIssue({code:"custom",message:"Both from and to are required for edge evidence"}),e.group!==void 0&&e.from!==void 0&&t.addIssue({code:"custom",message:"Pass either group or from and to, not both"}),e.level==="units"&&e.group!==void 0&&t.addIssue({code:"custom",message:"level units lists units and unit edges, or with from and to a unit edge's file pairs: drop group"}),e.folder!==void 0&&(e.level==="units"||e.communityMode==="louvain")&&t.addIssue({code:"custom",message:"folder walks the path-mode folders: drop level units and communityMode louvain"}),e.view==="matrix"&&(e.group!==void 0||e.from!==void 0)&&t.addIssue({code:"custom",message:"view matrix returns the whole level: drop group, from and to (call them afterwards for a row or a cell)"})}),Vs=U.string().min(1).max(1024).refine(e=>!_a.isAbsolute(e)&&!_a.win32.isAbsolute(e),"Must be relative to the workspace"),d1=U.object({config:Vs.optional().describe("Rules file, relative to the workspace (default: graphit.architecture.json)"),baseline:Vs.optional().describe("Accepted violations, relative to the workspace (default: graphit.architecture.baseline.json when it exists)"),rule:U.string().min(1).max(128).optional().describe("Return only the violations of this rule"),limit:U.number().int().min(1).max(500).optional().describe("Violations per page; also caps unmatchedFiles and resolved (default: 50)"),offset:c_,revision:U.string().regex(/^[0-9a-f]{64}$/).optional().describe("context.revision of the response the offset comes from; the call fails if the code, rules or baseline changed since"),response_format:U.enum(["json","markdown","toon"]).optional().describe("Output format: 'json', 'markdown', or 'toon' (default: toon)")}).strict(),p1=U.object({view:U.enum(Lw).optional().describe("'units' (default): every unit; 'folder': the groups of the unit or folder named by folder (default when folder is set); 'matrix': the dependency structure matrix of that level"),folder:U.string().min(1).max(1024).optional().describe("Unit or folder key, '/'-separated as explore_architecture returns it (e.g. 'src/analyzer')"),diagramFormat:U.enum(Fw).optional().describe("'svg' (default): a bare SVG; 'html': one self-contained page following the reader's light or dark scheme; 'diagram-spec': the level's data as JSON (schemas/diagram-spec.schema.json) for a diagram skill"),theme:U.enum(Bw).optional().describe("Colours of the SVG (default: light); svg only"),rules:U.boolean().optional().describe("Draw the violations of graphit.architecture.json in the error colour, and the baseline's accepted ones dashed"),config:Vs.optional().describe("Rules file with rules, relative to the workspace (default: graphit.architecture.json)"),baseline:Vs.optional().describe("Accepted violations with rules, relative to the workspace (default: graphit.architecture.baseline.json when it exists)"),output:Vs.optional().describe("File to write, relative to the workspace and inside it; without it, a diagram over the inline cap goes to architecture.<diagramFormat> (architecture.diagram-spec.json for a spec)"),response_format:U.enum(["json","markdown","toon"]).optional().describe("Output format: 'json', 'markdown', or 'toon' (default: toon)")}).strict().superRefine((e,t)=>{let{view:n}=jw(e.view,e.folder);n==="folder"&&e.folder===void 0&&t.addIssue({code:"custom",message:"view folder draws the groups of one unit or folder: pass folder"}),n==="units"&&e.folder!==void 0&&t.addIssue({code:"custom",message:"view units draws every unit: drop folder, or use view folder"}),e.theme!==void 0&&(e.diagramFormat??"svg")!=="svg"&&t.addIssue({code:"custom",message:"theme sets the colours of diagramFormat svg; the HTML page follows the reader's scheme and a spec has none"}),!e.rules&&(e.config!==void 0||e.baseline!==void 0)&&t.addIssue({code:"custom",message:"config and baseline apply to the rules overlay: add rules: true"})}),m1=U.object({scopePath:nt.optional().describe("Absolute path to a directory to scope the scan (default: workspace root). Must be inside the workspace."),maxFiles:U.number().int().min(1).optional().describe("Optional cap on analysed files (default: every analysable file in scope, no upper bound). When the cap stops the scan, truncated=true and filesBeyondLimit > 0: the result is partial."),minConfidence:t1,verbose:U.boolean().optional().describe('Also list the unused exports left out as excluded, each with its reason: the manifest field that declares it (declared:package.json#exports["./x"]), a Rust attribute, or convention:framework-default-export (default: false)'),unreferencedFiles:U.boolean().optional().describe("List whole files no production file imports instead of unused exports (default: false): low (no-importer) when nothing imports the file, medium (test-only-use) when only tests do. minConfidence then defaults to low. medium items list testImporters, the tests to delete or clean up with the file. Left out (excluded with verbose): test files, manifest entry points, files a non-test file names by path (bundler entry, package.json script, CI workflow, Makefile, shell script), JSX/Vue default exports, framework route files (Next.js, SvelteKit, Remix, Nuxt, Astro...), files a bundler loads (import.meta.glob, new URL, HTML entry), migrations, .d.ts files, *.config.* files, files a folder's .gitignore ignores, Python package __init__.py. Then the files only dead files and tests import (reason cascade, via = their dead importers); tests = the tests that import nothing but dead files.")});function h1(e,t){return Bp(e,t)}function Up(e,t,n,a,r){return{success:!0,data:e,metadata:{executionTimeMs:t,toolVersion:Ws,timestamp:new Date().toISOString(),workspaceRoot:n,...r&&{indexedAt:r.indexedAt,stale:r.stale}},...a&&{pagination:a}}}function Zn(e,t,n){return{success:!1,data:null,error:e,metadata:{executionTimeMs:t,toolVersion:Ws,timestamp:new Date().toISOString(),workspaceRoot:n}}}import*as d_ from"node:path";g1();cr();jp();var f1=U.object({outputDir:U.string().optional().refine(e=>e===void 0||!d_.isAbsolute(e),"Output directory must be relative to the workspace").describe("Workspace-relative output directory. Defaults to wiki."),topHubsLimit:U.number().int().min(1).max(50).optional().describe("Number of top hub files to include (default: 10, max: 50)."),scope:U.string().optional().describe("Relative path within workspace to restrict wiki to (e.g. 'src/'). Defaults to entire workspace."),exclude:U.array(U.string()).optional().describe("Relative glob-like patterns to exclude (e.g. ['tests/**', '**/*.test.ts']). When omitted, default exclusions apply: tests/, dist/, *.test.ts, etc.")}).strict();import*as _t from"node:fs";import*as b1 from"node:os";import*as Yn from"node:path";var y1=50,p_="cumulative.totals",az=500,oz=3e4;function qp(){return Yn.join(b1.homedir(),".graph-it","stats")}function sz(){return process.env.GRAPH_IT_NO_STATS==="1"}function lz(e){_t.mkdirSync(e,{recursive:!0,mode:448})}function v1(e){return`${e.source}-${e.sessionId}.json`}function cz(e){return e.totals.calls>0||e.llmUsage.calls>0}function uz(e,t){if(sz()||!cz(e))return;let n=t??qp();lz(n);let a=v1(e);_1(n,a,JSON.stringify(e,null,2)),pz(n),fz(n,e.startedAt)}function _1(e,t,n){let a=Yn.join(e,`.${t}.${process.pid}.tmp`);_t.writeFileSync(a,n,"utf8"),_t.renameSync(a,Yn.join(e,t))}var dz=Date.parse("2026-08-28T14:13:27Z");function m_(e,t=!1){let n=e??qp(),a=o=>{t||console.warn(o)},r;try{r=_t.readdirSync(n)}catch{return[]}let i=[];for(let o of r){if(!o.endsWith(".json"))continue;let s=Yn.join(n,o);try{let l=_t.readFileSync(s,"utf8"),c=JSON.parse(l);if(c&&typeof c=="object"&&c.schemaVersion===1&&typeof c.startedAt=="number"){if(c.startedAt<dz)continue;i.push({...c,estimationMethod:"cl100k_base"})}else a(`graph-it stats: skipping invalid stats file: ${o}`)}catch{a(`graph-it stats: skipping corrupted stats file: ${o}`)}}return i}function pz(e){let t=e??qp(),n;try{n=_t.readdirSync(t)}catch{return}let a=new Map;for(let r of n){if(!r.endsWith(".json"))continue;let i=r.indexOf("-");if(i<=0)continue;let o=r.slice(0,i),s=Yn.join(t,r);try{let l=_t.statSync(s),c=a.get(o);c||(c=[],a.set(o,c)),c.push({filePath:s,mtimeMs:l.mtimeMs})}catch{}}for(let r of a.values()){if(r.length<=y1)continue;r.sort((o,s)=>o.mtimeMs-s.mtimeMs);let i=r.length-y1;for(let o=0;o<i;o++)try{_t.unlinkSync(r[o].filePath)}catch{}}}function h_(){return{sessions:0,calls:0,jsonTokens:0,toonTokens:0,savings:0,truncations:0,llmCalls:0,llmTokensUsed:0}}function g_(e,t){let n=e[t.source]??=h_();n.sessions+=1,n.calls+=t.totals.calls,n.jsonTokens+=t.totals.jsonTokens,n.toonTokens+=t.totals.toonTokens,n.savings+=t.totals.savings,n.truncations+=t.totals.truncations,n.llmCalls+=t.llmUsage.calls,n.llmTokensUsed+=t.llmUsage.tokensUsed}function mz(e,t){for(let n of Object.keys(e))e[n]+=t[n]}function S1(e){let t=h_();for(let n of Object.values(e))mz(t,n);return t}function f_(e){let t={};for(let n of e)g_(t,n);return{persistedSessions:e.length,bySource:t,total:S1(t)}}function hz(e){let{source:t,startedAt:n,totals:a,llmUsage:r}=e;return{source:t,startedAt:n,totals:a,llmUsage:r}}function gz(e){let t=e;return typeof t=="object"&&t!==null&&t.schemaVersion===1&&typeof t.since=="number"&&typeof t.retired=="object"&&t.retired!==null&&typeof t.sessions=="object"&&t.sessions!==null&&(t.evicted===void 0||typeof t.evicted=="object"&&t.evicted!==null)}function E1(e){let t;try{t=_t.readFileSync(Yn.join(e,p_),"utf8")}catch{return}try{let n=JSON.parse(t);if(gz(n))return n}catch{}console.warn(`graph-it stats: ignoring invalid cumulative totals file: ${p_}`)}function fz(e,t){let n=E1(e),a={},r=n?.since??t;for(let c of m_(e,!0))a[v1(c)]=hz(c),r=Math.min(r,c.startedAt);let i={...n?.evicted};for(let[c,u]of Object.entries(n?.sessions??{}))c in a||(i[c]=u);for(let c of Object.keys(a))delete i[c];let o=n?.retired??{},s=Object.entries(i).sort(([,c],[,u])=>c.startedAt-u.startedAt);for(let[c,u]of s.slice(0,Math.max(0,s.length-az)))g_(o,u),delete i[c];_1(e,p_,JSON.stringify({schemaVersion:1,since:r,retired:o,evicted:i,sessions:a}))}function C1(e){let t=E1(e??qp());if(!t)return;let n={};for(let[a,r]of Object.entries(t.retired))n[a]={...h_(),...r};for(let a of[...Object.values(t.evicted??{}),...Object.values(t.sessions)])g_(n,a);return{since:new Date(t.since).toISOString(),bySource:n,total:S1(n)}}function A1(e,{delayMs:t=oz,baseDir:n,onError:a}={}){let r,i=()=>{clearTimeout(r),r=void 0;try{uz(e.snapshot(),n)}catch(s){a?.(s)}},o=e.onRecord(()=>{r||(r=setTimeout(i,t),r.unref())});return{dispose(){o(),r&&i()}}}var k1=U.object({});function w1(e){let t=Pr.snapshot(),n=f_([]),a;try{n=f_(m_(e)),a=C1(e)}catch{}let r=t.source==="mcp"&&t.llmUsage.calls===0?"llmUsage is tracked for CLI `graph-it query` only \u2014 the MCP server delegates LLM synthesis to the calling client and makes no LLM API calls itself":"llmUsage is real provider-reported token consumption; it is never summed into the estimated encoding totals";return{description:"TOON encoding size vs JSON equivalent",estimationNote:bw,llmUsageNote:r,currentSession:t,history:n,...a&&{cumulative:a}}}import*as Gp from"node:fs";import*as Xn from"node:path";var R1={typescript:["package.json","tsconfig.json","jsconfig.json","deno.json","deno.jsonc"],python:["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile"],rust:["Cargo.toml"],csharp:["*.csproj","*.sln","*.slnx","Directory.Build.props"],go:["go.mod","go.work"],java:["pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts"]},yz=new Set(Object.values(R1).flat().filter(e=>!e.startsWith("*"))),bz=Object.values(R1).flat().filter(e=>e.startsWith("*")).map(e=>e.slice(1));function vz(e){let t;try{t=Gp.readdirSync(e)}catch{return!1}return t.some(n=>yz.has(n)||bz.some(a=>n.endsWith(a)))}function T1(e){let t=Xn.resolve(e);for(;!vz(t);){let n=Xn.dirname(t);if(n===t)return null;t=n}return t}R_({createLogger(e,t){return new pl(e,t)}});var v_=process.env.DEBUG_MCP==="true",Wp=`${x1.homedir()}/mcp-debug.log`,_z=5*1024*1024,y_=`${Wp}.1`;function Sz(){if(v_)try{It.statSync(Wp).size>=_z&&(It.existsSync(y_)&&It.unlinkSync(y_),It.renameSync(Wp,y_))}catch{}}function ke(...e){let t=e.map(n=>typeof n=="string"?n:JSON.stringify(n)).join(" ");if(process.stderr.write(t.endsWith(`
3358
+ `)}`}function Ue(e){return ez(e,"mcp")}import*as _a from"node:path";var o_=["path","louvain"];var Lw=["units","folder","matrix"],Fw=["svg","html","diagram-spec"];var Bw=["light","dark"];function jw(e,t){let n=t?.replaceAll("\\","/");return{view:e??(n===void 0?"units":"folder"),folder:n}}cr();var p6=new Set("(,=:[!&|?{};~+-*%<>^");var Uw=["high","medium","low"];cr();jp();cr();var Ws="1.1.0",Hw="1.25.2",k6=U.enum(["json","toon"]).default("json").describe("Output format: 'json' (default) or 'toon' (Token-Oriented Object Notation for reduced token usage)"),dn={FILE_PATH:1024,SYMBOL_NAME:500,FILE_CONTENT:1024*1024,GENERIC_STRING:10*1024},nt=U.string().max(dn.FILE_PATH,`File path exceeds maximum length of ${dn.FILE_PATH} bytes`).refine(e=>!e.includes("\0"),"File path contains null bytes"),Sa=U.string().max(dn.SYMBOL_NAME,`Symbol name exceeds maximum length of ${dn.SYMBOL_NAME} bytes`).refine(e=>!e.includes("\0"),"Symbol name contains null bytes"),qw=U.string().max(dn.FILE_CONTENT,`File content exceeds maximum size of ${dn.FILE_CONTENT} bytes (~1 MB)`).refine(e=>!e.includes("\0"),"File content contains null bytes"),Ea=U.string().max(dn.GENERIC_STRING,`String exceeds maximum length of ${dn.GENERIC_STRING} bytes`).refine(e=>!e.includes("\0"),"String contains null bytes"),va={MAX_LIMIT:1e4,MAX_OFFSET:1e5,DEFAULT_LIMIT:1e3},tz=U.object({hubScore:U.number().min(0,"hubScore must be >= 0").max(1,"hubScore must be <= 1"),loc:U.number().int().positive().optional(),fileExtension:U.string().optional(),communityId:U.number().int().min(0).optional(),communityKey:U.string().optional()}),rz=U.object({source:U.string(),target:U.string(),relationType:U.enum(["dependency","call","reference","containment"]).optional()}),w6=U.object({nodes:U.array(U.string()),edges:U.array(rz),nodeLabels:U.record(U.string(),U.string()).optional(),parentCounts:U.record(U.string(),U.number()).optional(),unusedEdges:U.array(U.string()).optional(),nodeMetadata:U.record(U.string(),tz).optional()}),Vw=U.object({workspacePath:nt.describe("Absolute path to the project/workspace directory to analyze"),tsConfigPath:nt.optional().describe("Optional path to tsconfig.json for path alias resolution. Omitted: kept when the same workspace is selected again, otherwise each file uses its nearest tsconfig.json"),excludeNodeModules:U.boolean().optional().describe("Whether to exclude node_modules (default: true)"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum crawl depth (default: 50, min: 1, max: 100)")}),Ww=U.object({filePath:nt.describe("Absolute path to the file to analyze")}),Kw=U.union([U.literal(0),U.number().int().min(500).max(16e3)]).default(4e3).optional().describe("Maximum output size in tokens (default: 4000, 500-16000, or 0 for no limit). A larger result is cut and reports truncated=true, omitted counts and nextOffset; pass nextOffset as offset to read the rest."),c_=U.number().int().min(0).max(va.MAX_OFFSET).optional().describe("Items to skip, usually the nextOffset of the previous response (default: 0)"),Jw=U.object({entryFile:nt.describe("Absolute path to the entry file"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum depth to crawl (default: from config, min: 1, max: 100)"),limit:U.number().min(1).max(va.MAX_LIMIT).optional().describe(`Maximum number of nodes to return (for pagination, max: ${va.MAX_LIMIT})`),offset:U.number().min(0).max(va.MAX_OFFSET).optional().describe(`Number of nodes to skip (for pagination, max: ${va.MAX_OFFSET})`),onlyUsed:U.boolean().optional().describe("If true, only returns edges where symbols are actually used (requires AST analysis, slower)"),communityMode:U.enum(o_).optional().describe("How nodes are grouped into communityId/communityKey: 'path' (default) by folder, 'louvain' by import structure (deterministic Louvain over the crawled graph)"),tokenBudget:Kw}),Zw=U.object({targetPath:nt.describe("Absolute path to the file to find references for")}),Yw=U.object({sourceFile:nt.describe("Absolute path to the source file (the one importing using symbols)"),targetFile:nt.describe("Absolute path to the target file (the one providing symbols)")}),Xw=U.object({fromFile:nt.describe("Absolute path of the file containing the import"),moduleSpecifier:Ea.describe('The module specifier to resolve (e.g., "./utils", "@/components/Button")')}),R6=U.object({}),Gw=1e4,Qw=U.object({filePaths:U.array(nt).max(Gw).describe(`Array of absolute file paths to invalidate from the cache (max: ${Gw} per call; use rebuild_index for the whole workspace). Needed only for edits the file watcher missed: it invalidates changed files on its own.`)}),T6=U.object({}),e1=U.object({filePath:nt.describe("Absolute path to the file to analyze for symbols")}),t1=U.enum(Uw).optional().describe("Lowest confidence listed (default: high). high: the file is imported, no importer uses the export and no other evidence of use was found: a deletion candidate. medium: only tests use it, a computed import may reach it, a decorator may register it, its name is written again in its file (or, in Rust, in another file), or it sits in a test file. low: nothing imports the file (entry point by convention, script, config), review only. Unlisted items are counted in byConfidence."),r1=U.object({filePath:nt.describe("Absolute path to the file to check for unused exported symbols"),minConfidence:t1}),n1=U.object({filePath:nt.describe("Absolute path to the file containing the root symbol"),symbolName:Sa.describe("Name of the root symbol to trace from"),maxDepth:U.number().min(1).max(100).optional().describe("Maximum depth to trace the call chain (default: 10, min: 1, max: 100)")}),i1=U.object({filePath:nt.describe("Absolute path to the file to analyze"),symbolName:Sa.optional().describe("Optional: Only analyze changes to this specific symbol"),oldContent:qw.describe("The old version of the file content"),newContent:qw.optional().describe("The new version of the file content (if not provided, reads current file)")}),a1=U.object({baseRef:Ea.describe("Git base ref to compare against, for example origin/main"),headRef:Ea.optional().describe("Optional Git head ref; defaults to the checked-out worktree"),maxFiles:U.number().int().min(1).optional().describe("Optional cap on changed files analysed (default: 200, no upper bound)"),maxDepth:U.number().int().min(1).max(10).optional()}),o1=U.object({filePath:nt.describe("Absolute path to the file being modified"),symbolName:Sa.describe("Name of the symbol being modified"),includeTransitive:U.boolean().optional().describe("Include transitive dependents (default: false)"),maxDepth:U.number().min(1).max(20).optional().describe("Maximum depth for transitive analysis (default: 3, min: 1, max: 20)")}),I6=U.object({filePath:nt.describe("Absolute path to the file to analyze"),includeExternal:U.boolean().optional().describe("Include calls to external modules (default: false)")}),P6=U.object({filePath:nt.describe("Absolute path to the file to generate a codemap for")}),s1=U.object({filePath:nt.describe("Absolute path to the file containing the target symbol."),symbolName:Sa.describe("Name of the symbol to query (function, class, method). A bare name shared by several symbols in the file returns reason='ambiguous' with candidates; qualified names such as 'Class.method' are not supported."),symbolId:Sa.optional().describe("Exact node id taken from a previous result or candidate (valid for the current index only, since ids embed the line). Narrows symbolName to that node; a stale id returns reason='stale_selector'."),startLine:U.number().int().min(0).optional().describe("Declaration line of the symbol, 0-based like 'startLine' in results and candidates (editor line 3 is 2). Selects one of several same-name symbols."),direction:U.enum(["callers","callees","both"]).optional().describe("Direction of traversal: 'callers', 'callees', or 'both' (default: 'both')"),depth:U.number().min(1).max(10).optional().describe("Maximum BFS traversal depth (default: 2, min: 1, max: 10)"),relationTypes:U.array(U.enum(["CALLS","INHERITS","IMPLEMENTS","USES","REFERENCES"])).optional().describe("Filter by relation types (default: CALLS, INHERITS, IMPLEMENTS and REFERENCES; USES is added with includeTypeOnly)"),includeTypeOnly:U.boolean().optional().describe("Also include USES edges (type-only references such as interfaces and type aliases). Default is false. Ignored when relationTypes is set."),offset:c_,tokenBudget:Kw}),l1=U.object({question:U.string().max(1024).describe("Natural language question about the codebase"),depth:U.number().int().min(1).max(5).default(2).optional().describe("BFS traversal depth from seed nodes (default: 2, min: 1, max: 5)"),tokenBudget:U.number().int().min(500).max(16e3).default(4e3).optional().describe("Maximum token budget for the output subgraph (default: 4000)"),fileFilter:U.string().max(256).optional().describe("Glob pattern to restrict search scope"),outputFormat:U.enum(["toon","json"]).default("toon").optional().describe("Output format. 'toon' (default): compact TOON encoding (header+rows), typically 30-50% fewer tokens than JSON for node/edge lists \u2014 prefer this unless you need to re-parse structured JSON programmatically. 'json': short-key JSON object per node/edge \u2014 use when the calling client needs to JSON.parse() the result directly (e.g. building its own graph structure).")}),s_=U.object({id:Ea.refine(e=>e.trim().length>0,"Seed ID must not be empty").optional(),filePath:nt.refine(e=>e.trim().length>0,"Seed file path must not be empty").optional(),symbolName:Sa.refine(e=>e.trim().length>0,"Seed symbol name must not be empty").optional(),label:Ea.refine(e=>e.trim().length>0,"Seed label must not be empty").optional()}).refine(e=>e.id!==void 0||e.filePath!==void 0||e.symbolName!==void 0||e.label!==void 0,"A seed must contain an id, filePath, symbolName, or label"),nz=U.enum(["CONTAINS","IMPORTS","CALLS","INHERITS","IMPLEMENTS","USES","TESTED_BY","IMPACTED_BY","BELONGS_TO","REFERENCES","EXPLAINS","DOCUMENTS"]),c1=U.object({question:U.string().max(1024).optional(),seeds:U.array(s_).max(500).optional(),mode:U.enum(["search","neighbors","path","impact","refactor","overview"]).optional(),from:s_.optional(),to:s_.optional(),relations:U.array(nz).max(12).refine(e=>new Set(e).size===e.length,"Relations must be unique").optional(),scope:U.string().max(256).optional(),depth:U.number().int().min(1).max(5).optional(),maxNodes:U.number().int().min(1).max(500).optional(),tokenBudget:U.number().int().min(500).max(16e3).optional(),directed:U.boolean().optional(),cursor:U.string().min(1).max(4096).optional(),detail:U.enum(["compact","standard","full"]).optional(),response_format:U.enum(["json","markdown","toon"]).optional()}).superRefine((e,t)=>{let n=e.question!==void 0&&e.question.trim().length>0,a=(e.seeds?.length??0)>0,r=e.from!==void 0,i=e.to!==void 0;r!==i&&t.addIssue({code:"custom",message:"Both from and to are required for a path request"}),e.mode==="path"&&!(r&&i)&&t.addIssue({code:"custom",message:"Path mode requires both from and to"}),e.mode!==void 0&&e.mode!=="path"&&(r||i)&&t.addIssue({code:"custom",message:"from and to are only valid in path mode"}),e.mode===void 0&&r&&i&&(n||a)&&t.addIssue({code:"custom",message:"Set mode to path when combining endpoints with a question or seeds"}),!n&&!a&&!(r&&i)&&t.addIssue({code:"custom",message:"Provide a question, at least one seed, or both from and to"})}).transform(e=>{let t=e.question!==void 0&&e.question.trim().length>0,n=(e.seeds?.length??0)>0,a=e.from!==void 0&&e.to!==void 0;return e.mode===void 0&&!t&&!n&&a?{...e,mode:"path"}:e}),D6=U.object({outputDir:nt.optional().refine(e=>e===void 0||!_a.isAbsolute(e),"Output directory must be relative to the workspace").describe("Workspace-relative output directory for wiki files (default: wiki)"),topHubsLimit:U.number().int().min(1).max(50).optional().describe("Number of top hub files to list (max: 50, default: 10)"),scope:nt.optional().refine(e=>e===void 0||!_a.isAbsolute(e),"Scope must be relative to the workspace").describe("Relative path within workspace to restrict wiki to (e.g. 'src/')"),exclude:U.array(Ea).max(100).optional().describe("Relative glob-like patterns to exclude")}).strict(),l_=U.union([U.number().int().min(0),U.string().min(1).max(256)]).describe("Numeric group id from a previous response, or a group key (e.g. 'analyzer') or label as a string; 0 or 'unassigned' for files without a group"),u1=U.object({communityMode:U.enum(o_).optional().describe("How files are grouped: 'path' (default) by folder domain, 'louvain' by import structure"),maxFiles:U.number().int().min(1).max(va.MAX_OFFSET).optional().describe("Analyse only the first maxFiles source files, like graph-it architecture --maxFiles (default: all)"),level:U.enum(["groups","units"]).optional().describe("groups (default): folder or Louvain groups; units: packages (else top-level folders) with their layers, roles and role evidence, unit edges (down, upward, cycle) and cycles, like graph-it architecture --level units"),folder:U.string().min(1).max(1024).optional().describe("communityMode 'path' only: walk down one level, below this unit key (from level units) or group key; groups are then its sub-folders plus its own files (key = folder), nestedGroups those holding sub-folders; group, from and to then name groups of this level"),view:U.enum(["matrix"]).optional().describe("matrix: the dependency structure matrix of the level (units with level units, a folder's groups with folder, else the groups): rows ordered by layer with each cycle's rows together, non-zero cells (row imports column, diagonal = pairs inside) paged by offset/limit, per-row Ce/Ca/instability with their formula, cycles and totals of every cell, like graph-it architecture --matrix"),group:l_.optional().describe("Return this group's files and its incoming / outgoing group edges"),from:l_.optional().describe("Source group of the edge whose file pairs to return (requires to); with level units, a unit key such as 'apps/web' or '(root)'"),to:l_.optional().describe("Target group of the edge whose file pairs to return (requires from); with level units, a unit key"),limit:U.number().int().min(1).max(500).optional().describe("Items per page: groups and group edges, a group's files and its incoming and outgoing edges, or file pairs (default: 50)"),offset:c_,revision:U.string().regex(/^[0-9a-f]{64}$/).optional().describe("context.revision of the response the group ids or offset come from; the call fails if the architecture has changed since"),response_format:U.enum(["json","markdown","toon"]).optional().describe("Output format: 'json', 'markdown', or 'toon' (default: toon)")}).superRefine((e,t)=>{e.from===void 0!=(e.to===void 0)&&t.addIssue({code:"custom",message:"Both from and to are required for edge evidence"}),e.group!==void 0&&e.from!==void 0&&t.addIssue({code:"custom",message:"Pass either group or from and to, not both"}),e.level==="units"&&e.group!==void 0&&t.addIssue({code:"custom",message:"level units lists units and unit edges, or with from and to a unit edge's file pairs: drop group"}),e.folder!==void 0&&(e.level==="units"||e.communityMode==="louvain")&&t.addIssue({code:"custom",message:"folder walks the path-mode folders: drop level units and communityMode louvain"}),e.view==="matrix"&&(e.group!==void 0||e.from!==void 0)&&t.addIssue({code:"custom",message:"view matrix returns the whole level: drop group, from and to (call them afterwards for a row or a cell)"})}),Vs=U.string().min(1).max(1024).refine(e=>!_a.isAbsolute(e)&&!_a.win32.isAbsolute(e),"Must be relative to the workspace"),d1=U.object({config:Vs.optional().describe("Rules file, relative to the workspace (default: graphit.architecture.json)"),baseline:Vs.optional().describe("Accepted violations, relative to the workspace (default: graphit.architecture.baseline.json when it exists)"),rule:U.string().min(1).max(128).optional().describe("Return only the violations of this rule"),limit:U.number().int().min(1).max(500).optional().describe("Violations per page; also caps unmatchedFiles and resolved (default: 50)"),offset:c_,revision:U.string().regex(/^[0-9a-f]{64}$/).optional().describe("context.revision of the response the offset comes from; the call fails if the code, rules or baseline changed since"),response_format:U.enum(["json","markdown","toon"]).optional().describe("Output format: 'json', 'markdown', or 'toon' (default: toon)")}).strict(),p1=U.object({view:U.enum(Lw).optional().describe("'units' (default): every unit; 'folder': the groups of the unit or folder named by folder (default when folder is set); 'matrix': the dependency structure matrix of that level"),folder:U.string().min(1).max(1024).optional().describe("Unit or folder key, '/'-separated as explore_architecture returns it (e.g. 'src/analyzer')"),diagramFormat:U.enum(Fw).optional().describe("'svg' (default): a bare SVG; 'html': one self-contained page following the reader's light or dark scheme; 'diagram-spec': the level's data as JSON (schemas/diagram-spec.schema.json) for a diagram skill"),theme:U.enum(Bw).optional().describe("Colours of the SVG (default: light); svg only"),rules:U.boolean().optional().describe("Draw the violations of graphit.architecture.json in the error colour, and the baseline's accepted ones dashed"),config:Vs.optional().describe("Rules file with rules, relative to the workspace (default: graphit.architecture.json)"),baseline:Vs.optional().describe("Accepted violations with rules, relative to the workspace (default: graphit.architecture.baseline.json when it exists)"),output:Vs.optional().describe("File to write, relative to the workspace and inside it; without it, a diagram over the inline cap goes to architecture.<diagramFormat> (architecture.diagram-spec.json for a spec)"),response_format:U.enum(["json","markdown","toon"]).optional().describe("Output format: 'json', 'markdown', or 'toon' (default: toon)")}).strict().superRefine((e,t)=>{let{view:n}=jw(e.view,e.folder);n==="folder"&&e.folder===void 0&&t.addIssue({code:"custom",message:"view folder draws the groups of one unit or folder: pass folder"}),n==="units"&&e.folder!==void 0&&t.addIssue({code:"custom",message:"view units draws every unit: drop folder, or use view folder"}),e.theme!==void 0&&(e.diagramFormat??"svg")!=="svg"&&t.addIssue({code:"custom",message:"theme sets the colours of diagramFormat svg; the HTML page follows the reader's scheme and a spec has none"}),!e.rules&&(e.config!==void 0||e.baseline!==void 0)&&t.addIssue({code:"custom",message:"config and baseline apply to the rules overlay: add rules: true"})}),m1=U.object({scopePath:nt.optional().describe("Absolute path to a directory to scope the scan (default: workspace root). Must be inside the workspace."),maxFiles:U.number().int().min(1).optional().describe("Optional cap on analysed files (default: every analysable file in scope, no upper bound). When the cap stops the scan, truncated=true and filesBeyondLimit > 0: the result is partial."),minConfidence:t1,verbose:U.boolean().optional().describe('Also list the unused exports left out as excluded, each with its reason: the manifest field that declares it (declared:package.json#exports["./x"]), a Rust attribute, or convention:framework-default-export (default: false)'),unreferencedFiles:U.boolean().optional().describe("List whole files no production file imports instead of unused exports (default: false): low (no-importer) when nothing imports the file, medium (test-only-use) when only tests do. minConfidence then defaults to low. medium items list testImporters, the tests to delete or clean up with the file. Left out (excluded with verbose): test files, manifest entry points, files a non-test file names by path (bundler entry, package.json script, CI workflow, Makefile, shell script), JSX/Vue default exports, framework route files (Next.js, SvelteKit, Remix, Nuxt, Astro...), files a bundler loads (import.meta.glob, new URL, HTML entry), migrations, .d.ts files, *.config.* files, files a folder's .gitignore ignores, Python package __init__.py. Then the files only dead files and tests import (reason cascade, via = their dead importers); tests = the tests that import nothing but dead files.")});function h1(e,t){return Bp(e,t)}function Up(e,t,n,a,r){return{success:!0,data:e,metadata:{executionTimeMs:t,toolVersion:Ws,timestamp:new Date().toISOString(),workspaceRoot:n,...r&&{indexedAt:r.indexedAt,stale:r.stale}},...a&&{pagination:a}}}function Zn(e,t,n){return{success:!1,data:null,error:e,metadata:{executionTimeMs:t,toolVersion:Ws,timestamp:new Date().toISOString(),workspaceRoot:n}}}import*as d_ from"node:path";g1();cr();jp();var f1=U.object({outputDir:U.string().optional().refine(e=>e===void 0||!d_.isAbsolute(e),"Output directory must be relative to the workspace").describe("Workspace-relative output directory. Defaults to wiki."),topHubsLimit:U.number().int().min(1).max(50).optional().describe("Number of top hub files to include (default: 10, max: 50)."),scope:U.string().optional().describe("Relative path within workspace to restrict wiki to (e.g. 'src/'). Defaults to entire workspace."),exclude:U.array(U.string()).optional().describe("Relative glob-like patterns to exclude (e.g. ['tests/**', '**/*.test.ts']). When omitted, default exclusions apply: tests/, dist/, *.test.ts, etc.")}).strict();import*as _t from"node:fs";import*as b1 from"node:os";import*as Yn from"node:path";var y1=50,p_="cumulative.totals",az=500,oz=3e4;function qp(){return Yn.join(b1.homedir(),".graph-it","stats")}function sz(){return process.env.GRAPH_IT_NO_STATS==="1"}function lz(e){_t.mkdirSync(e,{recursive:!0,mode:448})}function v1(e){return`${e.source}-${e.sessionId}.json`}function cz(e){return e.totals.calls>0||e.llmUsage.calls>0}function uz(e,t){if(sz()||!cz(e))return;let n=t??qp();lz(n);let a=v1(e);_1(n,a,JSON.stringify(e,null,2)),pz(n),fz(n,e.startedAt)}function _1(e,t,n){let a=Yn.join(e,`.${t}.${process.pid}.tmp`);_t.writeFileSync(a,n,"utf8"),_t.renameSync(a,Yn.join(e,t))}var dz=Date.parse("2026-08-28T14:13:27Z");function m_(e,t=!1){let n=e??qp(),a=o=>{t||console.warn(o)},r;try{r=_t.readdirSync(n)}catch{return[]}let i=[];for(let o of r){if(!o.endsWith(".json"))continue;let s=Yn.join(n,o);try{let l=_t.readFileSync(s,"utf8"),c=JSON.parse(l);if(c&&typeof c=="object"&&c.schemaVersion===1&&typeof c.startedAt=="number"){if(c.startedAt<dz)continue;i.push({...c,estimationMethod:"cl100k_base"})}else a(`graph-it stats: skipping invalid stats file: ${o}`)}catch{a(`graph-it stats: skipping corrupted stats file: ${o}`)}}return i}function pz(e){let t=e??qp(),n;try{n=_t.readdirSync(t)}catch{return}let a=new Map;for(let r of n){if(!r.endsWith(".json"))continue;let i=r.indexOf("-");if(i<=0)continue;let o=r.slice(0,i),s=Yn.join(t,r);try{let l=_t.statSync(s),c=a.get(o);c||(c=[],a.set(o,c)),c.push({filePath:s,mtimeMs:l.mtimeMs})}catch{}}for(let r of a.values()){if(r.length<=y1)continue;r.sort((o,s)=>o.mtimeMs-s.mtimeMs);let i=r.length-y1;for(let o=0;o<i;o++)try{_t.unlinkSync(r[o].filePath)}catch{}}}function h_(){return{sessions:0,calls:0,jsonTokens:0,toonTokens:0,savings:0,truncations:0,llmCalls:0,llmTokensUsed:0}}function g_(e,t){let n=e[t.source]??=h_();n.sessions+=1,n.calls+=t.totals.calls,n.jsonTokens+=t.totals.jsonTokens,n.toonTokens+=t.totals.toonTokens,n.savings+=t.totals.savings,n.truncations+=t.totals.truncations,n.llmCalls+=t.llmUsage.calls,n.llmTokensUsed+=t.llmUsage.tokensUsed}function mz(e,t){for(let n of Object.keys(e))e[n]+=t[n]}function S1(e){let t=h_();for(let n of Object.values(e))mz(t,n);return t}function f_(e){let t={};for(let n of e)g_(t,n);return{persistedSessions:e.length,bySource:t,total:S1(t)}}function hz(e){let{source:t,startedAt:n,totals:a,llmUsage:r}=e;return{source:t,startedAt:n,totals:a,llmUsage:r}}function gz(e){let t=e;return typeof t=="object"&&t!==null&&t.schemaVersion===1&&typeof t.since=="number"&&typeof t.retired=="object"&&t.retired!==null&&typeof t.sessions=="object"&&t.sessions!==null&&(t.evicted===void 0||typeof t.evicted=="object"&&t.evicted!==null)}function E1(e){let t;try{t=_t.readFileSync(Yn.join(e,p_),"utf8")}catch{return}try{let n=JSON.parse(t);if(gz(n))return n}catch{}console.warn(`graph-it stats: ignoring invalid cumulative totals file: ${p_}`)}function fz(e,t){let n=E1(e),a={},r=n?.since??t;for(let c of m_(e,!0))a[v1(c)]=hz(c),r=Math.min(r,c.startedAt);let i={...n?.evicted};for(let[c,u]of Object.entries(n?.sessions??{}))c in a||(i[c]=u);for(let c of Object.keys(a))delete i[c];let o=n?.retired??{},s=Object.entries(i).sort(([,c],[,u])=>c.startedAt-u.startedAt);for(let[c,u]of s.slice(0,Math.max(0,s.length-az)))g_(o,u),delete i[c];_1(e,p_,JSON.stringify({schemaVersion:1,since:r,retired:o,evicted:i,sessions:a}))}function C1(e){let t=E1(e??qp());if(!t)return;let n={};for(let[a,r]of Object.entries(t.retired))n[a]={...h_(),...r};for(let a of[...Object.values(t.evicted??{}),...Object.values(t.sessions)])g_(n,a);return{since:new Date(t.since).toISOString(),bySource:n,total:S1(n)}}function A1(e,{delayMs:t=oz,baseDir:n,onError:a}={}){let r,i=()=>{clearTimeout(r),r=void 0;try{uz(e.snapshot(),n)}catch(s){a?.(s)}},o=e.onRecord(()=>{r||(r=setTimeout(i,t),r.unref())});return{dispose(){o(),r&&i()}}}var k1=U.object({});function w1(e){let t=Pr.snapshot(),n=f_([]),a;try{n=f_(m_(e)),a=C1(e)}catch{}let r=t.source==="mcp"&&t.llmUsage.calls===0?"llmUsage is tracked for CLI `graph-it query` only \u2014 the MCP server delegates LLM synthesis to the calling client and makes no LLM API calls itself":"llmUsage is real provider-reported token consumption; it is never summed into the estimated encoding totals";return{description:"TOON encoding size vs JSON equivalent",estimationNote:bw,llmUsageNote:r,currentSession:t,history:n,...a&&{cumulative:a}}}import*as Gp from"node:fs";import*as Xn from"node:path";var R1={typescript:["package.json","tsconfig.json","jsconfig.json","deno.json","deno.jsonc"],python:["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile"],rust:["Cargo.toml"],csharp:["*.csproj","*.sln","*.slnx","Directory.Build.props"],go:["go.mod","go.work"],java:["pom.xml","build.gradle","build.gradle.kts","settings.gradle","settings.gradle.kts"]},yz=new Set(Object.values(R1).flat().filter(e=>!e.startsWith("*"))),bz=Object.values(R1).flat().filter(e=>e.startsWith("*")).map(e=>e.slice(1));function vz(e){let t;try{t=Gp.readdirSync(e)}catch{return!1}return t.some(n=>yz.has(n)||bz.some(a=>n.endsWith(a)))}function T1(e){let t=Xn.resolve(e);for(;!vz(t);){let n=Xn.dirname(t);if(n===t)return null;t=n}return t}R_({createLogger(e,t){return new pl(e,t)}});var v_=process.env.DEBUG_MCP==="true",Wp=`${x1.homedir()}/mcp-debug.log`,_z=5*1024*1024,y_=`${Wp}.1`;function Sz(){if(v_)try{It.statSync(Wp).size>=_z&&(It.existsSync(y_)&&It.unlinkSync(y_),It.renameSync(Wp,y_))}catch{}}function ke(...e){let t=e.map(n=>typeof n=="string"?n:JSON.stringify(n)).join(" ");if(process.stderr.write(t.endsWith(`
3359
3359
  `)?t:`${t}
3360
3360
  `),!!v_)try{Sz();let a=`[${new Date().toISOString()}] ${t}
3361
3361
  `;It.appendFileSync(Wp,a)}catch{}}v_?(ke("[McpServer] ===== PROCESS STARTING (DEBUG MODE) ====="),ke("[McpServer] Node version:",process.version),ke("[McpServer] PID:",process.pid),ke("[McpServer] cwd:",process.cwd()),ke("[McpServer] argv:",JSON.stringify(process.argv)),ke("[McpServer] Environment vars:"),ke(" WORKSPACE_ROOT:",process.env.WORKSPACE_ROOT??"(not set)"),ke(" TSCONFIG_PATH:",process.env.TSCONFIG_PATH??"(not set)"),ke(" EXCLUDE_NODE_MODULES:",process.env.EXCLUDE_NODE_MODULES??"(not set)"),ke(" MAX_DEPTH:",process.env.MAX_DEPTH??"(not set)")):process.stderr.write(`[McpServer] Starting (debug logging disabled - set DEBUG_MCP=true to enable)
package/dist/mcpWorker.js CHANGED
@@ -46078,7 +46078,7 @@ Additional information: BADCLIENT: Bad error code, ${U} not found in range ${v}.
46078
46078
  JOIN nodes n_tgt ON e.target_id = n_tgt.id
46079
46079
  WHERE n_src.path = ?
46080
46080
  ORDER BY e.source_line ASC
46081
- `);for(m.bind([o]);m.step();){let g=m.getAsObject();c.push({name:g.callee_name,filePath:Ur(g.callee_path),callSiteLine:g.source_line})}m.free()}catch{}return c}}});var fwr={};module.exports=EKn(fwr);var Rbn=require("node:worker_threads");var Hkn=Mu(require("node:fs")),Cxt=Mu(require("node:path")),$kn=require("node:worker_threads");o3();var XGe=O1("AstWorkerHost"),ltt=class{worker=null;nextId=1;pendingRequests=new Map;workerPath;extensionPath;rootDir;isStopping=!1;isDisposed=!1;stopPromise=null;constructor(o,c,m){if(this.extensionPath=c,this.rootDir=m,o)this.workerPath=o;else{let g=[Cxt.join(__dirname,"astWorker.js"),Cxt.join(__dirname,"../../../dist/astWorker.js"),Cxt.join(__dirname,"../../../../dist/astWorker.js"),Cxt.join(process.cwd(),"dist/astWorker.js")],b="";for(let w of g)if(Hkn.existsSync(w)){b=w;break}this.workerPath=b||Cxt.join(process.cwd(),"dist/astWorker.js")}}async start(){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||this.isStopping){XGe.warn("AstWorker already started");return}XGe.info(`Starting AstWorker from ${this.workerPath}`);try{this.worker=new $kn.Worker(this.workerPath,{workerData:{extensionPath:this.extensionPath,rootDir:this.rootDir}}),this.worker.on("message",o=>{this.handleResponse(o)}),this.worker.on("error",o=>{XGe.error("AstWorker error:",o);for(let[c,m]of this.pendingRequests)m.reject(new Error(`AstWorker crashed: ${o.message}`)),this.pendingRequests.delete(c)}),this.worker.on("exit",o=>{o!==0&&!this.isStopping&&XGe.error(`AstWorker exited with code ${o}`),this.worker=null,this.stopPromise||(this.isStopping=!1)}),XGe.info("AstWorker started successfully")}catch(o){let c=o instanceof Error?o.message:String(o);throw XGe.error(`Failed to start AstWorker: ${c}`),new Error(`Failed to start AstWorker: ${c}`,{cause:o})}}stop(){if(this.isDisposed=!0,this.stopPromise)return this.stopPromise;let o=this.worker;if(!o)return Promise.resolve();XGe.debug("Stopping AstWorker");for(let[c,m]of this.pendingRequests)m.reject(new Error("AstWorker stopped")),this.pendingRequests.delete(c);return this.isStopping=!0,this.stopPromise=o.terminate().then(()=>{}).finally(()=>{this.worker===o&&(this.worker=null),this.isStopping=!1,this.stopPromise=null,XGe.debug("AstWorker stopped")}),this.stopPromise}async analyzeFile(o,c){return await this.sendRequest({type:"analyzeFile",id:0,filePath:o,content:c})}async getInternalExportDependencyGraph(o,c){let g=await this.sendRequest({type:"getInternalExportDeps",id:0,filePath:o,content:c});return new Map(Object.entries(g).map(([b,w])=>[b,new Set(w)]))}async extractSignatures(o,c){return await this.sendRequest({type:"extractSignatures",id:0,filePath:o,content:c})}async extractInterfaceMembers(o,c){let g=await this.sendRequest({type:"extractInterfaceMembers",id:0,filePath:o,content:c});return new Map(Object.entries(g))}async extractTypeAliases(o,c){return await this.sendRequest({type:"extractTypeAliases",id:0,filePath:o,content:c})}async compareSignatures(o,c){return await this.sendRequest({type:"compareSignatures",id:0,oldSig:o,newSig:c})}async analyzeBreakingChanges(o,c,m,g){return await this.sendRequest({type:"analyzeBreakingChanges",id:0,filePath:o,oldContent:c,newContent:m,symbolName:g})}async reset(){await this.sendRequest({type:"reset",id:0})}async getFileCount(){return await this.sendRequest({type:"getFileCount",id:0})}async sendRequest(o){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||await this.start(),this.isDisposed)throw new Error("AstWorker has been stopped");let c=this.nextId++,m={...o,id:c};return new Promise((g,b)=>{this.pendingRequests.set(c,{resolve:g,reject:b}),this.worker?.postMessage(m)})}handleResponse(o){let c=this.pendingRequests.get(o.id);if(!c){XGe.warn(`Received response for unknown request ${o.id}`);return}if(this.pendingRequests.delete(o.id),o.type==="success")c.resolve(o.result);else{let m=new Error(o.error);o.stack&&(m.stack=o.stack),c.reject(m)}}};var D4=Mu(require("node:fs")),YB=Mu(require("node:path"));dtt();o3();V_();var ZLn=require("node:crypto"),gGt=Mu(require("node:fs")),iAt=Mu(require("node:path"));cce();o3();V_();a3();hGt();var mtr=O1("configFingerprint");function dcn(u,o){try{let c=tOn(eOn(u,o));return(0,ZLn.createHash)("sha256").update(JSON.stringify([...c].sort(([m],[g])=>m.localeCompare(g)))).digest("hex")}catch(c){mtr.info(`Index cache disabled: ${c instanceof Error?c.message:String(c)}`);return}}function fcn(u,o){return[...tOn(eOn(u,o)).keys()]}function pcn(u,o){return o.filter(c=>!P5t.test(c)&&Dpe(c,u))}function eOn(u,o){let c=new Set([Ur(u)]);for(let m of o){let g=Ur(iAt.dirname(m));for(;!c.has(g);){if(!Dpe(g,u))throw new Error(`source file outside the workspace: ${Ur(m)}`);c.add(g),g=Ur(iAt.dirname(g))}}return c}function tOn(u){let o=[...u].flatMap(g=>[iAt.join(g,"tsconfig.json"),iAt.join(g,"package.json")]),c=new Set,m=new Map;for(let g=o.shift();g;g=o.shift()){let b=Ur(g);if(c.has(b)||!gGt.existsSync(g))continue;c.add(b);let w=_tr(g);m.set(b,w),o.push(..._Gt(g,zmt(g,w)?.extends))}return m}function _tr(u){try{return gGt.readFileSync(u,"utf-8")}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`cannot read resolver config ${Ur(u)}: ${c}`,{cause:o})}}var aAt=O1("IndexCache"),nOn=2,rOn="1.25.1",htr=.2,iOn=10*6e4,gtr=250,mcn="meta.json",aOt="reverse-index.json",yGt="callgraph.db",oOn="index.lock",oAt=new Map,hcn=()=>{};function _cn(u,o){let c=YB.join(YB.dirname(u),`.${YB.basename(u)}.${process.pid}.tmp`);D4.writeFileSync(c,o),D4.renameSync(c,u)}function ytr(u){try{return process.kill(u,0),!0}catch(o){return o.code==="EPERM"}}function vtr(u,o){return u?.excludeNodeModules===o.excludeNodeModules&&u?.ignoreTypeImports===o.ignoreTypeImports}var sAt=class u{dir;sourceFiles;workspaceRoot;fingerprint;constructor(o,c){this.workspaceRoot=YB.resolve(o),this.dir=u.dirFor(this.workspaceRoot),this.sourceFiles=c,this.fingerprint=dcn(this.workspaceRoot,c)}static dirFor(o){return YB.join(o,".graph-it","cache")}static async open(o){let c=await new UY({excludeNodeModules:!0,yieldIntervalMs:30,isCancelled:()=>!1}).collectAllSourceFiles(o);return new u(o,c)}get enabled(){return this.fingerprint!==void 0}get callGraphPath(){return YB.join(this.dir,yGt)}isValid(){return this.matches(this.readMeta())}readReverseIndex(o){let c=this.readMeta();if(!this.matches(c)||!vtr(c?.reverseIndexOptions,o))return null;try{return D4.readFileSync(YB.join(this.dir,aOt),"utf-8")}catch{return null}}save(o){let c=this.currentFingerprint();if(!c)return!1;try{D4.mkdirSync(this.dir,{recursive:!0}),this.ensureGitignore();let m=this.readMeta(),g=this.matches(m,c),b=YB.join(this.dir,aOt);o.reverseIndex?_cn(b,o.reverseIndex.data):g||D4.rmSync(b,{force:!0}),o.callGraph?_cn(this.callGraphPath,o.callGraph):g||D4.rmSync(this.callGraphPath,{force:!0});let w={schema:nOn,version:rOn,savedAt:new Date().toISOString(),workspaceRoot:this.workspaceRoot,configFingerprint:c,reverseIndexOptions:o.reverseIndex?.options??(g?m?.reverseIndexOptions:void 0)};_cn(YB.join(this.dir,mcn),JSON.stringify(w,null,2));let D=u.fileSizes(this.dir);return aAt.info(`Saved index cache: ${aOt} ${D.reverseIndexBytes} B, ${yGt} ${D.callGraphBytes} B`),!0}catch(m){return aAt.warn("Could not save index cache:",m instanceof Error?m.message:String(m)),!1}}static fileSizes(o){let c=m=>{try{return D4.statSync(YB.join(o,m)).size}catch{return 0}};return{reverseIndexBytes:c(aOt),callGraphBytes:c(yGt)}}clear(){for(let o of[mcn,aOt,yGt])D4.rmSync(YB.join(this.dir,o),{force:!0});try{D4.rmdirSync(this.dir)}catch{}}tryLock(){if(!this.enabled)return hcn;let o=YB.join(this.dir,oOn),c=oAt.get(Ur(o));if(c)return oAt.set(Ur(o),c+1),this.releaser(o);try{if(D4.mkdirSync(this.dir,{recursive:!0}),!this.createLockFile(o)&&(!this.isLockStale(o)||(D4.rmSync(o,{force:!0}),!this.createLockFile(o))))return null}catch(m){return aAt.warn("Could not lock index cache:",m instanceof Error?m.message:String(m)),hcn}return oAt.set(Ur(o),1),this.releaser(o)}async lock(o){let c=!1;for(;;){let m=this.tryLock();if(m)return m;c||(c=!0,o?.(this.readLockHolder(YB.join(this.dir,oOn))?.pid)),await new Promise(g=>setTimeout(g,gtr))}}releaser(o){let c=!1;return()=>{if(c)return;c=!0;let m=Ur(o),g=(oAt.get(m)??1)-1;if(g>0){oAt.set(m,g);return}oAt.delete(m),this.readLockHolder(o)?.pid===process.pid&&D4.rmSync(o,{force:!0})}}createLockFile(o){let c={pid:process.pid,acquiredAt:Date.now()};try{return D4.writeFileSync(o,JSON.stringify(c),{flag:"wx"}),!0}catch(m){if(m.code==="EEXIST")return!1;throw m}}readLockHolder(o){try{let c=JSON.parse(D4.readFileSync(o,"utf-8"));return typeof c.pid=="number"?c:void 0}catch{return}}isLockStale(o){let c=this.readLockHolder(o);if(!c)try{return Date.now()-D4.statSync(o).mtimeMs>iOn}catch{return!0}return c.pid===process.pid?!0:Date.now()-c.acquiredAt>iOn||!ytr(c.pid)}ensureGitignore(){try{D4.writeFileSync(YB.join(YB.dirname(this.dir),".gitignore"),`*
46081
+ `);for(m.bind([o]);m.step();){let g=m.getAsObject();c.push({name:g.callee_name,filePath:Ur(g.callee_path),callSiteLine:g.source_line})}m.free()}catch{}return c}}});var fwr={};module.exports=EKn(fwr);var Rbn=require("node:worker_threads");var Hkn=Mu(require("node:fs")),Cxt=Mu(require("node:path")),$kn=require("node:worker_threads");o3();var XGe=O1("AstWorkerHost"),ltt=class{worker=null;nextId=1;pendingRequests=new Map;workerPath;extensionPath;rootDir;isStopping=!1;isDisposed=!1;stopPromise=null;constructor(o,c,m){if(this.extensionPath=c,this.rootDir=m,o)this.workerPath=o;else{let g=[Cxt.join(__dirname,"astWorker.js"),Cxt.join(__dirname,"../../../dist/astWorker.js"),Cxt.join(__dirname,"../../../../dist/astWorker.js"),Cxt.join(process.cwd(),"dist/astWorker.js")],b="";for(let w of g)if(Hkn.existsSync(w)){b=w;break}this.workerPath=b||Cxt.join(process.cwd(),"dist/astWorker.js")}}async start(){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||this.isStopping){XGe.warn("AstWorker already started");return}XGe.info(`Starting AstWorker from ${this.workerPath}`);try{this.worker=new $kn.Worker(this.workerPath,{workerData:{extensionPath:this.extensionPath,rootDir:this.rootDir}}),this.worker.on("message",o=>{this.handleResponse(o)}),this.worker.on("error",o=>{XGe.error("AstWorker error:",o);for(let[c,m]of this.pendingRequests)m.reject(new Error(`AstWorker crashed: ${o.message}`)),this.pendingRequests.delete(c)}),this.worker.on("exit",o=>{o!==0&&!this.isStopping&&XGe.error(`AstWorker exited with code ${o}`),this.worker=null,this.stopPromise||(this.isStopping=!1)}),XGe.info("AstWorker started successfully")}catch(o){let c=o instanceof Error?o.message:String(o);throw XGe.error(`Failed to start AstWorker: ${c}`),new Error(`Failed to start AstWorker: ${c}`,{cause:o})}}stop(){if(this.isDisposed=!0,this.stopPromise)return this.stopPromise;let o=this.worker;if(!o)return Promise.resolve();XGe.debug("Stopping AstWorker");for(let[c,m]of this.pendingRequests)m.reject(new Error("AstWorker stopped")),this.pendingRequests.delete(c);return this.isStopping=!0,this.stopPromise=o.terminate().then(()=>{}).finally(()=>{this.worker===o&&(this.worker=null),this.isStopping=!1,this.stopPromise=null,XGe.debug("AstWorker stopped")}),this.stopPromise}async analyzeFile(o,c){return await this.sendRequest({type:"analyzeFile",id:0,filePath:o,content:c})}async getInternalExportDependencyGraph(o,c){let g=await this.sendRequest({type:"getInternalExportDeps",id:0,filePath:o,content:c});return new Map(Object.entries(g).map(([b,w])=>[b,new Set(w)]))}async extractSignatures(o,c){return await this.sendRequest({type:"extractSignatures",id:0,filePath:o,content:c})}async extractInterfaceMembers(o,c){let g=await this.sendRequest({type:"extractInterfaceMembers",id:0,filePath:o,content:c});return new Map(Object.entries(g))}async extractTypeAliases(o,c){return await this.sendRequest({type:"extractTypeAliases",id:0,filePath:o,content:c})}async compareSignatures(o,c){return await this.sendRequest({type:"compareSignatures",id:0,oldSig:o,newSig:c})}async analyzeBreakingChanges(o,c,m,g){return await this.sendRequest({type:"analyzeBreakingChanges",id:0,filePath:o,oldContent:c,newContent:m,symbolName:g})}async reset(){await this.sendRequest({type:"reset",id:0})}async getFileCount(){return await this.sendRequest({type:"getFileCount",id:0})}async sendRequest(o){if(this.isDisposed)throw new Error("AstWorker has been stopped");if(this.worker||await this.start(),this.isDisposed)throw new Error("AstWorker has been stopped");let c=this.nextId++,m={...o,id:c};return new Promise((g,b)=>{this.pendingRequests.set(c,{resolve:g,reject:b}),this.worker?.postMessage(m)})}handleResponse(o){let c=this.pendingRequests.get(o.id);if(!c){XGe.warn(`Received response for unknown request ${o.id}`);return}if(this.pendingRequests.delete(o.id),o.type==="success")c.resolve(o.result);else{let m=new Error(o.error);o.stack&&(m.stack=o.stack),c.reject(m)}}};var D4=Mu(require("node:fs")),YB=Mu(require("node:path"));dtt();o3();V_();var ZLn=require("node:crypto"),gGt=Mu(require("node:fs")),iAt=Mu(require("node:path"));cce();o3();V_();a3();hGt();var mtr=O1("configFingerprint");function dcn(u,o){try{let c=tOn(eOn(u,o));return(0,ZLn.createHash)("sha256").update(JSON.stringify([...c].sort(([m],[g])=>m.localeCompare(g)))).digest("hex")}catch(c){mtr.info(`Index cache disabled: ${c instanceof Error?c.message:String(c)}`);return}}function fcn(u,o){return[...tOn(eOn(u,o)).keys()]}function pcn(u,o){return o.filter(c=>!P5t.test(c)&&Dpe(c,u))}function eOn(u,o){let c=new Set([Ur(u)]);for(let m of o){let g=Ur(iAt.dirname(m));for(;!c.has(g);){if(!Dpe(g,u))throw new Error(`source file outside the workspace: ${Ur(m)}`);c.add(g),g=Ur(iAt.dirname(g))}}return c}function tOn(u){let o=[...u].flatMap(g=>[iAt.join(g,"tsconfig.json"),iAt.join(g,"package.json")]),c=new Set,m=new Map;for(let g=o.shift();g;g=o.shift()){let b=Ur(g);if(c.has(b)||!gGt.existsSync(g))continue;c.add(b);let w=_tr(g);m.set(b,w),o.push(..._Gt(g,zmt(g,w)?.extends))}return m}function _tr(u){try{return gGt.readFileSync(u,"utf-8")}catch(o){let c=o instanceof Error?o.message:String(o);throw new Error(`cannot read resolver config ${Ur(u)}: ${c}`,{cause:o})}}var aAt=O1("IndexCache"),nOn=2,rOn="1.25.2",htr=.2,iOn=10*6e4,gtr=250,mcn="meta.json",aOt="reverse-index.json",yGt="callgraph.db",oOn="index.lock",oAt=new Map,hcn=()=>{};function _cn(u,o){let c=YB.join(YB.dirname(u),`.${YB.basename(u)}.${process.pid}.tmp`);D4.writeFileSync(c,o),D4.renameSync(c,u)}function ytr(u){try{return process.kill(u,0),!0}catch(o){return o.code==="EPERM"}}function vtr(u,o){return u?.excludeNodeModules===o.excludeNodeModules&&u?.ignoreTypeImports===o.ignoreTypeImports}var sAt=class u{dir;sourceFiles;workspaceRoot;fingerprint;constructor(o,c){this.workspaceRoot=YB.resolve(o),this.dir=u.dirFor(this.workspaceRoot),this.sourceFiles=c,this.fingerprint=dcn(this.workspaceRoot,c)}static dirFor(o){return YB.join(o,".graph-it","cache")}static async open(o){let c=await new UY({excludeNodeModules:!0,yieldIntervalMs:30,isCancelled:()=>!1}).collectAllSourceFiles(o);return new u(o,c)}get enabled(){return this.fingerprint!==void 0}get callGraphPath(){return YB.join(this.dir,yGt)}isValid(){return this.matches(this.readMeta())}readReverseIndex(o){let c=this.readMeta();if(!this.matches(c)||!vtr(c?.reverseIndexOptions,o))return null;try{return D4.readFileSync(YB.join(this.dir,aOt),"utf-8")}catch{return null}}save(o){let c=this.currentFingerprint();if(!c)return!1;try{D4.mkdirSync(this.dir,{recursive:!0}),this.ensureGitignore();let m=this.readMeta(),g=this.matches(m,c),b=YB.join(this.dir,aOt);o.reverseIndex?_cn(b,o.reverseIndex.data):g||D4.rmSync(b,{force:!0}),o.callGraph?_cn(this.callGraphPath,o.callGraph):g||D4.rmSync(this.callGraphPath,{force:!0});let w={schema:nOn,version:rOn,savedAt:new Date().toISOString(),workspaceRoot:this.workspaceRoot,configFingerprint:c,reverseIndexOptions:o.reverseIndex?.options??(g?m?.reverseIndexOptions:void 0)};_cn(YB.join(this.dir,mcn),JSON.stringify(w,null,2));let D=u.fileSizes(this.dir);return aAt.info(`Saved index cache: ${aOt} ${D.reverseIndexBytes} B, ${yGt} ${D.callGraphBytes} B`),!0}catch(m){return aAt.warn("Could not save index cache:",m instanceof Error?m.message:String(m)),!1}}static fileSizes(o){let c=m=>{try{return D4.statSync(YB.join(o,m)).size}catch{return 0}};return{reverseIndexBytes:c(aOt),callGraphBytes:c(yGt)}}clear(){for(let o of[mcn,aOt,yGt])D4.rmSync(YB.join(this.dir,o),{force:!0});try{D4.rmdirSync(this.dir)}catch{}}tryLock(){if(!this.enabled)return hcn;let o=YB.join(this.dir,oOn),c=oAt.get(Ur(o));if(c)return oAt.set(Ur(o),c+1),this.releaser(o);try{if(D4.mkdirSync(this.dir,{recursive:!0}),!this.createLockFile(o)&&(!this.isLockStale(o)||(D4.rmSync(o,{force:!0}),!this.createLockFile(o))))return null}catch(m){return aAt.warn("Could not lock index cache:",m instanceof Error?m.message:String(m)),hcn}return oAt.set(Ur(o),1),this.releaser(o)}async lock(o){let c=!1;for(;;){let m=this.tryLock();if(m)return m;c||(c=!0,o?.(this.readLockHolder(YB.join(this.dir,oOn))?.pid)),await new Promise(g=>setTimeout(g,gtr))}}releaser(o){let c=!1;return()=>{if(c)return;c=!0;let m=Ur(o),g=(oAt.get(m)??1)-1;if(g>0){oAt.set(m,g);return}oAt.delete(m),this.readLockHolder(o)?.pid===process.pid&&D4.rmSync(o,{force:!0})}}createLockFile(o){let c={pid:process.pid,acquiredAt:Date.now()};try{return D4.writeFileSync(o,JSON.stringify(c),{flag:"wx"}),!0}catch(m){if(m.code==="EEXIST")return!1;throw m}}readLockHolder(o){try{let c=JSON.parse(D4.readFileSync(o,"utf-8"));return typeof c.pid=="number"?c:void 0}catch{return}}isLockStale(o){let c=this.readLockHolder(o);if(!c)try{return Date.now()-D4.statSync(o).mtimeMs>iOn}catch{return!0}return c.pid===process.pid?!0:Date.now()-c.acquiredAt>iOn||!ytr(c.pid)}ensureGitignore(){try{D4.writeFileSync(YB.join(YB.dirname(this.dir),".gitignore"),`*
46082
46082
  `,{flag:"wx"})}catch(o){if(o.code!=="EEXIST")throw o}}readMeta(){try{return JSON.parse(D4.readFileSync(YB.join(this.dir,mcn),"utf-8"))}catch{return}}currentFingerprint(){return this.fingerprint&&dcn(this.workspaceRoot,this.sourceFiles)}matches(o,c=this.currentFingerprint()){return c!==void 0&&o?.schema===nOn&&o.version===rOn&&o.configFingerprint===c&&typeof o.workspaceRoot=="string"&&Ur(o.workspaceRoot)===Ur(this.workspaceRoot)}};async function aOn(u,o){let{cache:c}=o,m=c?await c.lock(o.onWait):hcn;try{let g=c?.readReverseIndex(o.reverseIndexOptions),b=g?u.enableReverseIndex(g):!1;b&&aAt.info("Restored reverse index from cache");let w=c&&b?await btr(u,c,o):null,{deleted:D,...G}=w??await Str(u,o),Y=!G.fromCache||G.filesAnalyzed>0||D>0;if(c&&Y&&!G.cancelled){let re=u.getSerializedReverseIndex();re&&c.save({reverseIndex:{data:re,options:o.reverseIndexOptions}})}return G}finally{m()}}async function btr(u,o,c){let m=await u.validateReverseIndex(htr,o.sourceFiles);if(!m?.isValid)return aAt.info("Cached index too stale, rebuilding from scratch"),null;for(let w of m.missingFiles)u.handleFileDeleted(w);m.staleFiles.length>0&&c.onReindexStart?.(m.staleFiles.length);let g=await u.reindexStaleFiles(m.staleFiles);return aAt.info(`Incremental index: ${g} changed, ${m.missingFiles.length} deleted`),{filesIndexed:u.getCacheStats().reverseIndexStats?.indexedFiles??0,filesFound:o.sourceFiles.length,filesAnalyzed:g,fromCache:!0,cancelled:!1,deleted:m.missingFiles.length}}async function Str(u,o){u.clearCache();let c=await o.buildFullIndex();return{filesIndexed:u.getCacheStats().reverseIndexStats?.indexedFiles??c.indexedFiles,filesFound:c.indexedFiles,filesAnalyzed:c.indexedFiles,fromCache:!1,cancelled:c.cancelled,deleted:0}}var Gmt=Mu(require("node:fs/promises")),vGt=Mu(require("node:fs"));u3();o3();var Ttr=O1("FileReader"),Etr=5*1024*1024,xtr=64*1024,Atr=3e4,P4=class{maxSize;chunkSize;timeout;constructor(o={}){this.maxSize=o.maxSize??Etr,this.chunkSize=o.chunkSize??xtr,this.timeout=o.timeout??Atr}async getFileSize(o){try{let c=await Gmt.stat(o);return{size:c.size,isLarge:c.size>this.maxSize,path:o}}catch(c){throw tE.fromError(c,o)}}async readFile(o,c){let m=c?.maxSize??this.maxSize,g=c?.timeout??this.timeout,b=c?.streaming??!1,w;try{w=await Gmt.stat(o)}catch(Y){throw tE.fromError(Y,o)}if(w.size>m)throw new tE(`File too large: ${o} (${this.formatSize(w.size)} > ${this.formatSize(m)})`,"FILE_TOO_LARGE",{filePath:o});let D,G=new Promise((Y,re)=>{D=setTimeout(()=>{re(new tE(`File read timed out after ${g}ms: ${o}`,"TIMEOUT",{filePath:o}))},g)});try{let Y;return b||w.size>1024*1024?(Ttr.debug(`Streaming read for large file: ${o} (${this.formatSize(w.size)})`),Y=await Promise.race([this.readFileStreaming(o),G])):Y=await Promise.race([Gmt.readFile(o,"utf-8"),G]),clearTimeout(D),Y}catch(Y){throw clearTimeout(D),Y instanceof tE?Y:tE.fromError(Y,o)}}async readFileStreaming(o){return new Promise((c,m)=>{let g=[],b=vGt.createReadStream(o,{highWaterMark:this.chunkSize});b.on("data",w=>{g.push(Buffer.isBuffer(w)?w:Buffer.from(w))}),b.on("end",()=>{let w=Buffer.concat(g).toString("utf-8");c(w)}),b.on("error",w=>{m(tE.fromError(w,o))})})}async readFileIfExists(o){try{return await this.readFile(o)}catch(c){if(c instanceof tE&&c.code==="FILE_NOT_FOUND")return null;throw c}}async canRead(o){try{return await Gmt.access(o,vGt.constants.R_OK),!0}catch{return!1}}formatSize(o){return o<1024?`${o}B`:o<1024*1024?`${(o/1024).toFixed(1)}KB`:`${(o/(1024*1024)).toFixed(1)}MB`}};var Ctr=new Set(["return","typeof","instanceof","in","of","new","delete","void","throw","case","do","else","yield","await"]),wtr=new Set("(,=:[!&|?{};~+-*%<>^");function cOn(u){return u===void 0?!1:u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||u===95||u===36}function Itr(u){return u===32||u===9||u===10||u===13}function gcn(u,o,c){c<=o||(u.parts.push(u.src.slice(u.copied,o),u.src.slice(o,c).replaceAll(/[^\n\r]/g," ")),u.copied=c)}function ktr(u){let{src:o}=u,c=u.i-1;for(;c>=0;)if(c<u.commentEnd&&c>=u.commentStart)c=u.commentStart-1;else if(Itr(o.codePointAt(c)))c--;else break;if(c<0)return"";if(!cOn(o.codePointAt(c)))return o[c];let m=c;for(;m>0&&cOn(o.codePointAt(m-1));)m--;return o.slice(m,c+1)}function Dtr(u){return u===""||wtr.has(u)||Ctr.has(u)}function Ptr(u,o){let c=u[o],m=o+1;for(;m<u.length&&u[m]!==c&&u[m]!==`
46083
46083
  `;)m+=u[m]==="\\"?2:1;return u[m]===c?m+1:Math.min(m,u.length)}function Ntr(u,o){let c=!1;for(let m=o+1;m<u.length;m++){let g=u[m];if(g===`
46084
46084
  `)return-1;if(g==="\\")m++;else if(g==="[")c=!0;else if(g==="]")c=!1;else if(g==="/"&&!c)return m+1}return-1}function lOn(u){let{src:o}=u,c=u.i;for(;c<o.length&&o[c]!=="`"&&!(o[c]==="$"&&o[c+1]==="{");)c+=o[c]==="\\"?2:1;c=Math.min(c,o.length),gcn(u,u.i,c),o[c]==="$"?(u.templates.push(u.braceDepth),u.braceDepth++,u.i=c+2):u.i=c+1}function Rtr(u){let{src:o,i:c}=u;if(o[c]!=="/"||o[c+1]!=="/"&&o[c+1]!=="*")return!1;let m;return o[c+1]==="/"?m=o.indexOf(`