@aiready/ast-mcp-server 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
- searchCode,
4
3
  validateWorkspacePath
5
- } from "./chunk-FQP7SHLM.js";
4
+ } from "./chunk-EHE3VUUP.js";
6
5
 
7
6
  // src/index.ts
8
7
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -35,6 +34,16 @@ var FindImplementationsSchema = z.object({
35
34
  var GetFileStructureSchema = z.object({
36
35
  file: z.string().describe("Absolute path to the file to analyze")
37
36
  });
37
+ var GrepSearchSchema = z.object({
38
+ pattern: z.string().describe("Search pattern (regex by default)"),
39
+ path: z.string().describe("Directory to search in"),
40
+ include: z.array(z.string()).optional().describe('Include only these glob patterns (e.g., ["*.ts", "src/**"])'),
41
+ exclude: z.array(z.string()).optional().describe('Exclude these glob patterns (e.g., ["**/*.test.ts"])'),
42
+ limit: z.number().optional().default(50).describe("Max matches to return (default 50)"),
43
+ offset: z.number().optional().default(0).describe("Pagination offset (default 0)"),
44
+ context: z.number().optional().default(2).describe("Number of context lines before and after (default 2)"),
45
+ isRegex: z.boolean().optional().default(true).describe("Use regex mode (default true)")
46
+ });
38
47
  var SearchCodeSchema = z.object({
39
48
  pattern: z.string().describe("Search pattern (regex by default)"),
40
49
  path: z.string().describe("Directory to search in"),
@@ -511,8 +520,8 @@ var TypeScriptAdapter = class {
511
520
  const sourceFile = project.addSourceFileAtPathIfExists(hit.file);
512
521
  if (!sourceFile) return { references: [], total_count: 0 };
513
522
  try {
514
- const { searchCode: searchCode2 } = await import("./search-code-63QOEFQN.js");
515
- const searchResults = await searchCode2(
523
+ const { searchCode } = await import("./search-code-SYD75SEK.js");
524
+ const searchResults = await searchCode(
516
525
  symbolName,
517
526
  path5,
518
527
  "**/*.{ts,tsx,js,jsx}",
@@ -581,8 +590,8 @@ var TypeScriptAdapter = class {
581
590
  return { implementations: [], total_count: 0 };
582
591
  }
583
592
  try {
584
- const { searchCode: searchCode2 } = await import("./search-code-63QOEFQN.js");
585
- const searchResults = await searchCode2(
593
+ const { searchCode } = await import("./search-code-SYD75SEK.js");
594
+ const searchResults = await searchCode(
586
595
  symbolName,
587
596
  path5,
588
597
  "**/*.{ts,tsx,js,jsx}",
@@ -798,6 +807,9 @@ async function getFileStructure(file) {
798
807
  return await typescriptAdapter.getFileStructure(file);
799
808
  }
800
809
 
810
+ // src/index.ts
811
+ import { grepSearch } from "@aiready/core";
812
+
801
813
  // src/tools/get-symbol-docs.ts
802
814
  import { SyntaxKind } from "ts-morph";
803
815
  async function getSymbolDocs(symbol, filePath) {
@@ -1105,9 +1117,35 @@ var ASTExplorerServer = class {
1105
1117
  required: ["file"]
1106
1118
  }
1107
1119
  },
1120
+ {
1121
+ name: "grep_search",
1122
+ description: "Fast, context-aware text search via ripgrep. Supports context lines and result summarization.",
1123
+ inputSchema: {
1124
+ type: "object",
1125
+ properties: {
1126
+ pattern: { type: "string", description: "Search pattern" },
1127
+ path: { type: "string", description: "Directory to search" },
1128
+ include: {
1129
+ type: "array",
1130
+ items: { type: "string" },
1131
+ description: "Glob filter"
1132
+ },
1133
+ exclude: {
1134
+ type: "array",
1135
+ items: { type: "string" },
1136
+ description: "Exclusion filter"
1137
+ },
1138
+ limit: { type: "number", default: 50 },
1139
+ offset: { type: "number", default: 0 },
1140
+ context: { type: "number", default: 2 },
1141
+ isRegex: { type: "boolean", default: true }
1142
+ },
1143
+ required: ["pattern", "path"]
1144
+ }
1145
+ },
1108
1146
  {
1109
1147
  name: "search_code",
1110
- description: "Fast regex search via bundled ripgrep.",
1148
+ description: "Fast regex search via bundled ripgrep (alias for grep_search).",
1111
1149
  inputSchema: {
1112
1150
  type: "object",
1113
1151
  properties: {
@@ -1257,19 +1295,47 @@ var ASTExplorerServer = class {
1257
1295
  ]
1258
1296
  };
1259
1297
  }
1298
+ case "grep_search": {
1299
+ const {
1300
+ pattern,
1301
+ path: path5,
1302
+ include,
1303
+ exclude,
1304
+ limit,
1305
+ offset,
1306
+ context,
1307
+ isRegex
1308
+ } = GrepSearchSchema.parse(args);
1309
+ const result = await grepSearch({
1310
+ pattern,
1311
+ path: path5,
1312
+ include,
1313
+ exclude,
1314
+ limit,
1315
+ offset,
1316
+ context,
1317
+ isRegex
1318
+ });
1319
+ return {
1320
+ content: [
1321
+ { type: "text", text: JSON.stringify(result, null, 2) }
1322
+ ]
1323
+ };
1324
+ }
1260
1325
  case "search_code": {
1261
1326
  const { pattern, path: path5, filePattern, limit, offset, regex } = SearchCodeSchema.parse(args);
1262
- const results = await searchCode(
1327
+ const result = await grepSearch({
1263
1328
  pattern,
1264
- path5,
1265
- filePattern,
1329
+ path: path5,
1330
+ include: filePattern ? [filePattern] : [],
1266
1331
  limit,
1267
- regex,
1268
- offset
1269
- );
1332
+ offset,
1333
+ isRegex: regex,
1334
+ context: 0
1335
+ });
1270
1336
  return {
1271
1337
  content: [
1272
- { type: "text", text: JSON.stringify(results, null, 2) }
1338
+ { type: "text", text: JSON.stringify(result, null, 2) }
1273
1339
  ]
1274
1340
  };
1275
1341
  }
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/schemas.ts","../src/adapters/typescript-adapter.ts","../src/project-manager.ts","../src/index/symbol-index.ts","../src/worker/pool.ts","../src/utils/tool-utils.ts","../src/tools/resolve-definition.ts","../src/tools/find-references.ts","../src/tools/find-implementations.ts","../src/tools/get-file-structure.ts","../src/tools/get-symbol-docs.ts","../src/tools/build-symbol-index.ts","../src/tools/call-hierarchy.ts","../src/tools/check-symbol-grounding.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n ResolveDefinitionSchema,\n FindReferencesSchema,\n FindImplementationsSchema,\n GetFileStructureSchema,\n SearchCodeSchema,\n GetSymbolDocsSchema,\n BuildSymbolIndexSchema,\n GetCallHierarchySchema,\n CheckSymbolGroundingSchema,\n CodebaseAuditSchema,\n} from './schemas.js';\nimport { resolveDefinition } from './tools/resolve-definition.js';\nimport { findReferences } from './tools/find-references.js';\nimport { findImplementations } from './tools/find-implementations.js';\nimport { getFileStructure } from './tools/get-file-structure.js';\nimport { searchCode } from './tools/search-code.js';\nimport { getSymbolDocs } from './tools/get-symbol-docs.js';\nimport { buildSymbolIndex } from './tools/build-symbol-index.js';\nimport { getCallHierarchy } from './tools/call-hierarchy.js';\nimport { checkSymbolGrounding } from './tools/check-symbol-grounding.js';\nimport { symbolIndex } from './index/symbol-index.js';\nimport {\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * AST-aware Code Exploration MCP Server\n */\nexport class ASTExplorerServer {\n private server: Server;\n private version: string = '0.1.0';\n\n constructor() {\n this.server = new Server(\n {\n name: 'ast-explorer-server',\n version: this.version,\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n }\n );\n\n this.setupHandlers();\n\n this.server.onerror = (error) => {\n console.error('[MCP Error]', error);\n };\n }\n\n private setupHandlers() {\n // List available resources\n this.server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return {\n resources: [\n {\n uri: 'ast://file/symbols',\n name: 'File Symbol List',\n description: 'Get all symbols defined in a file.',\n mimeType: 'application/json',\n },\n ],\n };\n });\n\n // Read resource content\n this.server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request) => {\n const { uri } = request.params;\n const url = new URL(uri);\n\n if (url.protocol === 'ast:' && url.pathname === '//file/symbols') {\n const filePath = url.searchParams.get('path');\n if (!filePath) throw new Error('Missing \"path\" parameter in URI');\n\n const symbols = symbolIndex.lookupByFile(filePath);\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(symbols, null, 2),\n },\n ],\n };\n }\n\n throw new Error(`Resource not found: ${uri}`);\n }\n );\n\n // List available tools\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: [\n {\n name: 'resolve_definition',\n description: 'Find where a symbol is defined using TypeScript AST.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: {\n type: 'string',\n description: 'Symbol name (e.g., function, class)',\n },\n path: {\n type: 'string',\n description: 'Project root or target directory',\n },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'find_references',\n description: 'Find all usages of a symbol across the project.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string', description: 'Symbol name' },\n path: { type: 'string', description: 'Project root' },\n limit: { type: 'number', default: 50 },\n offset: { type: 'number', default: 0 },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'find_implementations',\n description:\n 'Find implementations of interfaces or abstract classes.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string', description: 'Interface/Class name' },\n path: { type: 'string', description: 'Project root' },\n limit: { type: 'number', default: 50 },\n offset: { type: 'number', default: 0 },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'get_file_structure',\n description:\n 'Get structural overview of a file (imports, exports, symbols).',\n inputSchema: {\n type: 'object',\n properties: {\n file: { type: 'string', description: 'Absolute path to file' },\n },\n required: ['file'],\n },\n },\n {\n name: 'search_code',\n description: 'Fast regex search via bundled ripgrep.',\n inputSchema: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Search pattern' },\n path: { type: 'string', description: 'Directory to search' },\n filePattern: { type: 'string', description: 'Glob filter' },\n limit: { type: 'number', default: 50 },\n offset: { type: 'number', default: 0 },\n regex: { type: 'boolean', default: true },\n },\n required: ['pattern', 'path'],\n },\n },\n {\n name: 'get_symbol_docs',\n description: 'Get JSDoc/TSDoc for a specific symbol.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string', description: 'Symbol name' },\n path: { type: 'string', description: 'Project root' },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'build_symbol_index',\n description: 'Warm the symbol index for faster navigation.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Project root to index' },\n },\n required: ['path'],\n },\n },\n {\n name: 'get_call_hierarchy',\n description: 'Find callers and callees for a symbol.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string' },\n path: { type: 'string' },\n direction: {\n type: 'string',\n enum: ['incoming', 'outgoing'],\n default: 'outgoing',\n },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'check_symbol_grounding',\n description:\n \"Assess a symbol's AI grounding quality (docs, type clarity, depth).\",\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string' },\n path: { type: 'string' },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'hygiene_audit',\n description:\n 'Performs a codebase-level hygiene check for technical debt (TODOs) and waste (empty dirs, orphans).',\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Project root directory to audit',\n },\n },\n required: ['path'],\n },\n },\n {\n name: 'metabolism_audit',\n description: 'Alias for hygiene_audit (Serverless Claw compat).',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string' },\n },\n required: ['path'],\n },\n },\n {\n name: 'codebase_audit',\n description: 'Alias for hygiene_audit.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string' },\n },\n required: ['path'],\n },\n },\n ],\n };\n });\n\n // Tool execution handler\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n switch (name) {\n case 'resolve_definition': {\n const { symbol, path } = ResolveDefinitionSchema.parse(args);\n const results = await resolveDefinition(symbol, path);\n return {\n content: [\n { type: 'text', text: JSON.stringify(results, null, 2) },\n ],\n };\n }\n case 'find_references': {\n const { symbol, path, limit, offset } =\n FindReferencesSchema.parse(args);\n const results = await findReferences(symbol, path, limit, offset);\n return {\n content: [\n { type: 'text', text: JSON.stringify(results, null, 2) },\n ],\n };\n }\n case 'find_implementations': {\n const { symbol, path, limit, offset } =\n FindImplementationsSchema.parse(args);\n const results = await findImplementations(\n symbol,\n path,\n limit,\n offset\n );\n return {\n content: [\n { type: 'text', text: JSON.stringify(results, null, 2) },\n ],\n };\n }\n case 'get_file_structure': {\n const { file } = GetFileStructureSchema.parse(args);\n const structure = await getFileStructure(file);\n return {\n content: [\n { type: 'text', text: JSON.stringify(structure, null, 2) },\n ],\n };\n }\n case 'search_code': {\n const { pattern, path, filePattern, limit, offset, regex } =\n SearchCodeSchema.parse(args);\n const results = await searchCode(\n pattern,\n path,\n filePattern,\n limit,\n regex,\n offset\n );\n return {\n content: [\n { type: 'text', text: JSON.stringify(results, null, 2) },\n ],\n };\n }\n case 'get_symbol_docs': {\n const { symbol, path } = GetSymbolDocsSchema.parse(args);\n const docs = await getSymbolDocs(symbol, path);\n return {\n content: [{ type: 'text', text: JSON.stringify(docs, null, 2) }],\n };\n }\n case 'build_symbol_index': {\n const { path } = BuildSymbolIndexSchema.parse(args);\n const stats = await buildSymbolIndex(path);\n return {\n content: [{ type: 'text', text: JSON.stringify(stats, null, 2) }],\n };\n }\n case 'get_call_hierarchy': {\n const { symbol, path, direction } =\n GetCallHierarchySchema.parse(args);\n const hierarchy = await getCallHierarchy(symbol, path, direction);\n return {\n content: [\n { type: 'text', text: JSON.stringify(hierarchy, null, 2) },\n ],\n };\n }\n case 'check_symbol_grounding': {\n const { symbol, path } = CheckSymbolGroundingSchema.parse(args);\n const result = await checkSymbolGrounding(symbol, path);\n return {\n content: [\n { type: 'text', text: JSON.stringify(result, null, 2) },\n ],\n };\n }\n case 'hygiene_audit':\n case 'metabolism_audit':\n case 'codebase_audit': {\n const { path: rootDir } = CodebaseAuditSchema.parse(args);\n // Dynamic import of the new hygiene-audit package logic\n const { HygieneAuditProvider } =\n await import('@aiready/hygiene-audit');\n const provider = new HygieneAuditProvider();\n const result = await provider.analyze({ rootDir });\n\n // Map ScanResult back to the flat structure serverlessclaw expects in metadata\n const allIssues = result.results.flatMap((r) => r.issues);\n const metadata = {\n debtMarkers: result.metadata?.debtMarkers || 0,\n emptyDirs: result.metadata?.emptyDirs || [],\n orphanedFiles: result.metadata?.orphanedFiles || [],\n findings: allIssues.map((i: any) => ({\n expected: i.recommendation || i.suggestion || '',\n actual: i.message,\n severity:\n i.severity === 'critical'\n ? 'P0'\n : i.severity === 'major'\n ? 'P1'\n : 'P2',\n recommendation: i.recommendation || i.suggestion || '',\n })),\n };\n\n return {\n content: [\n { type: 'text', text: JSON.stringify(result, null, 2) },\n ],\n metadata,\n };\n }\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n } catch (error: any) {\n return {\n content: [{ type: 'text', text: `Error: ${error.message}` }],\n isError: true,\n };\n }\n });\n }\n\n async run() {\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n console.error('AST Explorer MCP Server started');\n }\n}\n\n// Start the server\nconst server = new ASTExplorerServer();\nserver.run().catch((error) => {\n console.error('Fatal error starting AST Explorer MCP Server:', error);\n process.exit(1);\n});\n","import { z } from 'zod';\n\n/**\n * Tool 1: resolve_definition\n */\nexport const ResolveDefinitionSchema = z.object({\n symbol: z\n .string()\n .describe(\n 'Symbol name to resolve (function, class, type, interface, etc.)'\n ),\n path: z.string().describe('Project root or target directory'),\n});\n\n/**\n * Tool 2: find_references\n */\nexport const FindReferencesSchema = z.object({\n symbol: z.string().describe('Symbol name to find references for'),\n path: z.string().describe('Project root directory'),\n limit: z\n .number()\n .optional()\n .default(50)\n .describe('Max results per page (default 50)'),\n offset: z.number().optional().default(0).describe('Pagination offset'),\n});\n\n/**\n * Tool 3: find_implementations\n */\nexport const FindImplementationsSchema = z.object({\n symbol: z\n .string()\n .describe('Interface or abstract class name to find implementations for'),\n path: z.string().describe('Project root directory'),\n limit: z.number().optional().default(50).describe('Max results per page'),\n offset: z.number().optional().default(0).describe('Pagination offset'),\n});\n\n/**\n * Tool 4: get_file_structure\n */\nexport const GetFileStructureSchema = z.object({\n file: z.string().describe('Absolute path to the file to analyze'),\n});\n\n/**\n * Tool 5: search_code\n */\nexport const SearchCodeSchema = z.object({\n pattern: z.string().describe('Search pattern (regex by default)'),\n path: z.string().describe('Directory to search in'),\n filePattern: z.string().optional().describe('Glob filter (e.g., \"*.ts\")'),\n limit: z\n .number()\n .optional()\n .default(50)\n .describe('Max matches to return (default 50)'),\n offset: z\n .number()\n .optional()\n .default(0)\n .describe('Pagination offset (default 0)'),\n regex: z\n .boolean()\n .optional()\n .default(true)\n .describe('Use regex mode (default true)'),\n});\n\n/**\n * Tool 6: get_symbol_docs\n */\nexport const GetSymbolDocsSchema = z.object({\n symbol: z.string().describe('Symbol name to get documentation for'),\n path: z.string().describe('Project root directory'),\n});\n\n/**\n * Tool 7: build_symbol_index\n */\nexport const BuildSymbolIndexSchema = z.object({\n path: z.string().describe('Project root directory to index'),\n});\n/**\n * Tool 8: get_call_hierarchy\n */\nexport const GetCallHierarchySchema = z.object({\n symbol: z.string().describe('Symbol name to find callers/callees for'),\n path: z.string().describe('Project root directory'),\n direction: z\n .enum(['incoming', 'outgoing', 'both'])\n .optional()\n .default('both')\n .describe('Direction of calls (default: both)'),\n});\n/**\n * Tool 9: check_symbol_grounding\n */\nexport const CheckSymbolGroundingSchema = z.object({\n symbol: z.string().describe('Symbol name to assess grounding for'),\n path: z.string().describe('Project root directory'),\n});\n\n/**\n * Tool 10: codebase_audit\n */\nexport const CodebaseAuditSchema = z.object({\n path: z\n .string()\n .describe('Project root directory to audit for debt and bloat'),\n});\n","import { Node } from 'ts-morph';\nimport fs from 'fs';\nimport path from 'path';\nimport {\n DefinitionLocation,\n ReferenceLocation,\n FileStructure,\n SymbolKind,\n ClassInfo,\n FunctionInfo,\n InterfaceInfo,\n TypeAliasInfo,\n EnumInfo,\n} from '../types.js';\nimport { projectManager } from '../project-manager.js';\nimport { symbolIndex } from '../index/symbol-index.js';\nimport { validateWorkspacePath } from '../security.js';\nimport { WorkerPool } from '../worker/pool.js';\n\nexport class TypeScriptAdapter {\n private pool: WorkerPool;\n\n constructor() {\n const poolSize = parseInt(process.env.AST_WORKER_POOL_SIZE || '2');\n this.pool = new WorkerPool(poolSize);\n }\n\n private async ensureIndex(p: string): Promise<void> {\n if (!symbolIndex.isInitialized()) {\n const absolutePath = path.resolve(p);\n let searchPath = absolutePath;\n\n if (!fs.statSync(absolutePath).isDirectory()) {\n const tsconfig = await projectManager.findNearestTsConfig(absolutePath);\n searchPath = tsconfig\n ? path.dirname(tsconfig)\n : path.dirname(absolutePath);\n }\n\n console.error(\n `[AST] Index not initialized. Building for ${searchPath}...`\n );\n await symbolIndex.buildIndex(searchPath);\n }\n }\n\n public async resolveDefinition(\n symbolName: string,\n path: string\n ): Promise<DefinitionLocation[]> {\n validateWorkspacePath(path);\n await this.ensureIndex(path);\n\n // Fast path: index lookup (O(1)) to find the file\n const indexHits = symbolIndex.lookup(symbolName);\n if (indexHits.length > 0) {\n const results: DefinitionLocation[] = [];\n for (const hit of indexHits) {\n const tsconfig = await projectManager.findNearestTsConfig(hit.file);\n if (tsconfig) {\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(hit.file);\n if (sourceFile) {\n const exported = sourceFile\n .getExportedDeclarations()\n .get(symbolName);\n if (exported && exported.length > 0) {\n results.push(this.mapToDefinitionLocation(exported[0] as Node));\n continue;\n }\n }\n }\n // Fallback if ts-morph loading fails for the hit\n results.push({\n file: hit.file,\n line: hit.line,\n column: hit.column,\n kind: hit.kind,\n snippet: '',\n documentation: undefined,\n });\n }\n return results;\n }\n\n // Fallback: search specific file via ts-morph (useful for local files without full index)\n if (fs.statSync(path).isDirectory()) {\n return []; // Cannot load a directory as a single file\n }\n\n const tsconfig = await projectManager.findNearestTsConfig(path);\n if (!tsconfig) return [];\n\n // Use worker pool for heavy ts-morph operations\n try {\n const result = await this.pool.execute<DefinitionLocation[]>(\n 'resolve_definition',\n {\n tsconfig,\n file: path,\n symbol: symbolName,\n }\n );\n return result;\n } catch {\n // Fallback to main thread if worker fails\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(path);\n if (!sourceFile) return [];\n\n const exported = sourceFile.getExportedDeclarations().get(symbolName);\n if (!exported) return [];\n\n return exported.map((decl) => this.mapToDefinitionLocation(decl as Node));\n }\n }\n\n public async findReferences(\n symbolName: string,\n path: string,\n limit: number = 50,\n offset: number = 0\n ): Promise<{ references: ReferenceLocation[]; total_count: number }> {\n validateWorkspacePath(path);\n await this.ensureIndex(path);\n\n // Index lookup to find definition location\n const hits = symbolIndex.lookup(symbolName);\n if (hits.length === 0) return { references: [], total_count: 0 };\n\n // Load only the definition file\n const hit = hits[0];\n const tsconfig = await projectManager.findNearestTsConfig(hit.file);\n if (!tsconfig) return { references: [], total_count: 0 };\n\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(hit.file);\n if (!sourceFile) return { references: [], total_count: 0 };\n\n // Hybrid approach: to prevent OOM, we don't load all files in the project.\n // Instead, we use rg to find files that literally contain the symbol name,\n // and only load those into ts-morph for accurate reference resolution.\n try {\n const { searchCode } = await import('../tools/search-code.js');\n const searchResults = await searchCode(\n symbolName,\n path,\n '**/*.{ts,tsx,js,jsx}',\n 1000,\n false\n );\n const filesToLoad = [...new Set(searchResults.map((r) => r.file))];\n for (const file of filesToLoad) {\n project.addSourceFileAtPathIfExists(file);\n }\n project.resolveSourceFileDependencies();\n } catch (_e) {\n // Ignore search failures - fallback to existing project files\n }\n\n // We need the actual node. Instead of calculating position from line/col, let's just find the exported declaration.\n // IMPORTANT: Re-get source file or ensure it's up to date after resolving dependencies if needed.\n const exported = sourceFile.getExportedDeclarations().get(symbolName);\n if (!exported || exported.length === 0)\n return { references: [], total_count: 0 };\n\n const targetNode = exported[0];\n\n const refSymbols =\n 'findReferences' in targetNode &&\n typeof (targetNode as { findReferences?: () => any[] }).findReferences ===\n 'function'\n ? (targetNode as { findReferences: () => any[] }).findReferences()\n : undefined;\n if (!refSymbols) return { references: [], total_count: 0 };\n\n const results: ReferenceLocation[] = [];\n for (const refSymbol of refSymbols) {\n for (const ref of refSymbol.getReferences()) {\n const sf = ref.getSourceFile();\n const lc = sf.getLineAndColumnAtPos(ref.getTextSpan().getStart());\n results.push({\n file: sf.getFilePath(),\n line: lc.line,\n column: lc.column,\n text: ref.getNode().getParent()?.getText() || ref.getNode().getText(),\n });\n }\n }\n\n const unique = this.deduplicateLocations(results);\n return {\n references: unique.slice(offset, offset + limit),\n total_count: unique.length,\n };\n }\n\n public async findImplementations(\n symbolName: string,\n path: string,\n limit: number = 50,\n offset: number = 0\n ): Promise<{ implementations: ReferenceLocation[]; total_count: number }> {\n validateWorkspacePath(path);\n await this.ensureIndex(path);\n const hits = symbolIndex.lookup(symbolName);\n if (hits.length === 0) return { implementations: [], total_count: 0 };\n\n const hit = hits[0];\n const tsconfig = await projectManager.findNearestTsConfig(hit.file);\n if (!tsconfig) return { implementations: [], total_count: 0 };\n\n // Use worker pool for heavy ts-morph operations\n try {\n const result = await this.pool.execute<{\n implementations: ReferenceLocation[];\n total_count: number;\n }>('find_implementations', {\n tsconfig,\n file: hit.file,\n symbol: symbolName,\n });\n\n // Apply pagination\n return {\n implementations: result.implementations.slice(offset, offset + limit),\n total_count: result.total_count,\n };\n } catch {\n // Fallback to main thread if worker fails\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(hit.file);\n if (!sourceFile) return { implementations: [], total_count: 0 };\n\n const exported = sourceFile.getExportedDeclarations().get(symbolName);\n if (!exported || exported.length === 0)\n return { implementations: [], total_count: 0 };\n\n const targetNode = exported[0];\n if (\n !Node.isClassDeclaration(targetNode) &&\n !Node.isInterfaceDeclaration(targetNode)\n ) {\n return { implementations: [], total_count: 0 };\n }\n\n try {\n const { searchCode } = await import('../tools/search-code.js');\n const searchResults = await searchCode(\n symbolName,\n path,\n '**/*.{ts,tsx,js,jsx}',\n 1000,\n false\n );\n const filesToLoad = [...new Set(searchResults.map((r) => r.file))];\n for (const file of filesToLoad) {\n project.addSourceFileAtPathIfExists(file);\n }\n } catch (_e) {\n // Ignore search failures - fallback to existing project files\n }\n\n const results: ReferenceLocation[] = [];\n const implementations =\n 'getImplementations' in targetNode &&\n typeof (targetNode as { getImplementations?: () => any[] })\n .getImplementations === 'function'\n ? (\n targetNode as { getImplementations: () => any[] }\n ).getImplementations()\n : undefined;\n if (implementations) {\n for (const impl of implementations) {\n const sf = impl.getSourceFile();\n const lc = sf.getLineAndColumnAtPos(impl.getTextSpan().getStart());\n results.push({\n file: sf.getFilePath(),\n line: lc.line,\n column: lc.column,\n text:\n impl.getNode().getParent()?.getText() || impl.getNode().getText(),\n });\n }\n }\n\n const unique = this.deduplicateLocations(results);\n return {\n implementations: unique.slice(offset, offset + limit),\n total_count: unique.length,\n };\n }\n }\n\n public async getFileStructure(\n filePath: string\n ): Promise<FileStructure | undefined> {\n const safePath = validateWorkspacePath(filePath);\n const tsconfig = await projectManager.findNearestTsConfig(safePath);\n if (!tsconfig) return undefined;\n\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(safePath);\n if (!sourceFile) return undefined;\n\n const structure: FileStructure = {\n file: safePath,\n imports: sourceFile.getImportDeclarations().map((imp) => ({\n module: imp.getModuleSpecifierValue(),\n names: imp.getNamedImports().map((ni) => ni.getName()),\n })),\n exports: sourceFile.getExportSymbols().map((sym) => ({\n name: sym.getName(),\n kind: this.mapSymbolKind(sym),\n })),\n classes: sourceFile.getClasses().map((cls) => this.mapToClassInfo(cls)),\n functions: sourceFile\n .getFunctions()\n .map((fn) => this.mapToFunctionInfo(fn)),\n interfaces: sourceFile\n .getInterfaces()\n .map((itf) => this.mapToInterfaceInfo(itf)),\n typeAliases: sourceFile\n .getTypeAliases()\n .map((ta) => this.mapToTypeAliasInfo(ta)),\n enums: sourceFile.getEnums().map((enm) => this.mapToEnumInfo(enm)),\n };\n\n return structure;\n }\n\n public async shutdown(): Promise<void> {\n await this.pool.terminate();\n }\n\n private mapToDefinitionLocation(node: Node): DefinitionLocation {\n const sourceFile = node.getSourceFile();\n const lineAndColumn = sourceFile.getLineAndColumnAtPos(node.getStart());\n\n return {\n file: sourceFile.getFilePath(),\n line: lineAndColumn.line,\n column: lineAndColumn.column,\n kind: this.mapNodeToSymbolKind(node),\n snippet: node.getText(),\n documentation: this.getJsDoc(node),\n };\n }\n\n private mapNodeToSymbolKind(node: Node): SymbolKind {\n if (Node.isClassDeclaration(node)) return 'class';\n if (Node.isFunctionDeclaration(node)) return 'function';\n if (Node.isInterfaceDeclaration(node)) return 'interface';\n if (Node.isTypeAliasDeclaration(node)) return 'type_alias';\n if (Node.isEnumDeclaration(node)) return 'enum';\n if (Node.isVariableDeclaration(node)) return 'variable';\n if (Node.isMethodDeclaration(node)) return 'method';\n if (Node.isPropertyDeclaration(node)) return 'property';\n if (Node.isParameterDeclaration(node)) return 'parameter';\n return 'variable';\n }\n\n private mapSymbolKind(symbol: any): SymbolKind {\n const decls = symbol.getDeclarations();\n if (decls.length > 0) return this.mapNodeToSymbolKind(decls[0]);\n return 'variable';\n }\n\n private getJsDoc(node: Node): string | undefined {\n if (Node.isJSDocable(node)) {\n const docs = node.getJsDocs();\n if (docs.length > 0) {\n return docs[0].getCommentText();\n }\n }\n return undefined;\n }\n\n public getSymbolDocs(node: Node) {\n if (Node.isJSDocable(node)) {\n const docs = node.getJsDocs();\n if (docs.length > 0) {\n const doc = docs[0];\n return {\n documentation: doc.getCommentText(),\n tags: doc.getTags().map((tag) => ({\n name: tag.getTagName(),\n text: tag.getCommentText() || '',\n })),\n };\n }\n }\n return undefined;\n }\n\n private mapToClassInfo(cls: any): ClassInfo {\n return {\n name: cls.getName() || 'anonymous',\n ...this.getSymbolDocs(cls),\n methods: cls.getMethods().map((m: any) => this.mapToFunctionInfo(m)),\n properties: cls\n .getProperties()\n .map((p: any) => this.mapToPropertyInfo(p)),\n };\n }\n\n private mapToFunctionInfo(fn: unknown): FunctionInfo {\n return {\n name: (fn as any)?.getName?.() || 'anonymous',\n ...this.getSymbolDocs(fn as any),\n params: ((fn as any)?.getParameters?.() || []).map((p: any) => ({\n name: p.getName(),\n type: p.getType().getText(),\n })),\n returnType: (fn as any)?.getReturnType?.()?.getText?.() || 'unknown',\n };\n }\n\n private mapToPropertyInfo(p: unknown) {\n return {\n name: (p as any)?.getName?.() || 'unknown',\n type: (p as any)?.getType?.()?.getText?.() || 'unknown',\n ...this.getSymbolDocs(p as any),\n };\n }\n\n private mapToInterfaceInfo(itf: unknown): InterfaceInfo {\n return {\n name: (itf as any)?.getName?.() || 'unknown',\n ...this.getSymbolDocs(itf as any),\n properties:\n ((itf as any).getProperties?.() || []).map((p: any) =>\n this.mapToPropertyInfo(p)\n ) || [],\n methods:\n ((itf as any)?.getMethods?.() || []).map((m: any) =>\n this.mapToFunctionInfo(m)\n ) || [],\n };\n }\n\n private mapToTypeAliasInfo(ta: unknown): TypeAliasInfo {\n return {\n name: (ta as any)?.getName?.() || 'unknown',\n type: (ta as any)?.getType?.()?.getText?.() || 'unknown',\n ...this.getSymbolDocs(ta as Node),\n };\n }\n\n private mapToEnumInfo(enm: unknown): EnumInfo {\n return {\n name: (enm as any)?.getName?.() || 'unknown',\n ...this.getSymbolDocs(enm as Node),\n members:\n ((enm as any)?.getMembers?.() || []).map((m: any) => m.getName()) || [],\n };\n }\n\n private deduplicateLocations<\n T extends { file: string; line: number; column: number },\n >(locations: T[]): T[] {\n const seen = new Set<string>();\n return locations.filter((loc) => {\n const key = `${loc.file}:${loc.line}:${loc.column}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n }\n}\n\nexport const typescriptAdapter = new TypeScriptAdapter();\n","import { Project } from 'ts-morph';\nimport path from 'path';\nimport fs from 'fs';\nimport { glob } from 'glob';\nimport { validateWorkspacePath } from './security.js';\n\n/**\n * ProjectManager handles tsconfig discovery and Project lifecycle.\n * One Project per tsconfig.json to handle monorepo project boundaries correctly.\n */\nexport class ProjectManager {\n private projects: Map<string, Project> = new Map();\n private tsconfigCache: Map<string, string[]> = new Map();\n private accessOrder: string[] = []; // MRU at front\n private maxProjects: number = 4;\n\n /**\n * Find all tsconfig.json files in a directory (recursive)\n */\n public async findTsConfigs(rootDir: string): Promise<string[]> {\n const safeRoot = validateWorkspacePath(rootDir);\n if (this.tsconfigCache.has(safeRoot)) {\n return this.tsconfigCache.get(safeRoot)!;\n }\n\n const configs = await glob('**/tsconfig.json', {\n cwd: safeRoot,\n absolute: true,\n ignore: ['**/node_modules/**', '**/dist/**'],\n });\n\n this.tsconfigCache.set(safeRoot, configs);\n return configs;\n }\n\n /**\n * Ensure a Project exists for a given tsconfig path, managing LRU cache\n */\n public ensureProject(tsconfigPath: string): Project {\n this.checkMemoryPressure();\n\n // Cache hit\n if (this.projects.has(tsconfigPath)) {\n this.moveToFront(tsconfigPath);\n return this.projects.get(tsconfigPath)!;\n }\n\n // Evict if full\n while (this.projects.size >= this.maxProjects) {\n const oldest = this.accessOrder.pop()!;\n this.disposeProject(oldest);\n }\n\n // Create with lazy file loading\n const project = new Project({\n tsConfigFilePath: tsconfigPath,\n skipAddingFilesFromTsConfig: true, // KEY: don't load all files\n });\n\n this.projects.set(tsconfigPath, project);\n this.accessOrder.unshift(tsconfigPath);\n return project;\n }\n\n /**\n * Move a tsconfig path to the front of the access order (MRU)\n */\n private moveToFront(tsconfigPath: string) {\n const index = this.accessOrder.indexOf(tsconfigPath);\n if (index > -1) {\n this.accessOrder.splice(index, 1);\n this.accessOrder.unshift(tsconfigPath);\n }\n }\n\n private checkMemoryPressure(): void {\n const heapUsed = process.memoryUsage().heapUsed / 1024 / 1024;\n const maxHeap = parseInt(process.env.AST_MAX_HEAP_MB || '1536', 10);\n\n while (heapUsed > maxHeap && this.projects.size > 1) {\n const oldest = this.accessOrder.pop()!;\n this.disposeProject(oldest);\n }\n }\n\n public disposeProject(tsconfigPath: string): void {\n const project = this.projects.get(tsconfigPath);\n if (project) {\n // Forget files explicitly\n for (const sourceFile of project.getSourceFiles()) {\n project.removeSourceFile(sourceFile);\n }\n this.projects.delete(tsconfigPath);\n }\n }\n\n /**\n * Find the nearest tsconfig.json for a file\n */\n public async findNearestTsConfig(\n filePath: string\n ): Promise<string | undefined> {\n const safePath = validateWorkspacePath(filePath);\n let currentDir = path.dirname(safePath);\n const root = path.parse(currentDir).root;\n\n while (currentDir !== root) {\n const tsconfigPath = path.join(currentDir, 'tsconfig.json');\n if (fs.existsSync(tsconfigPath)) {\n return tsconfigPath;\n }\n currentDir = path.dirname(currentDir);\n }\n\n return undefined;\n }\n\n /**\n * Get all tsconfigs for a path\n */\n public async getProjectsForPath(rootDir: string): Promise<string[]> {\n return this.findTsConfigs(rootDir);\n }\n\n /**\n * Dispose all projects to free memory\n */\n public disposeAll(): void {\n for (const [key] of this.projects) {\n this.disposeProject(key);\n }\n this.accessOrder = [];\n }\n}\n\nexport const projectManager = new ProjectManager();\n","import { projectManager } from '../project-manager.js';\nimport { IndexingStats, SymbolKind } from '../types.js';\nimport { validateWorkspacePath } from '../security.js';\nimport fs from 'fs';\nimport crypto from 'crypto';\nimport path from 'path';\nimport { Node } from 'ts-morph';\n\nexport interface SymbolEntry {\n name: string;\n kind: SymbolKind;\n file: string;\n line: number;\n column: number;\n exported: boolean;\n}\n\nexport interface DiskCache {\n version: 1;\n rootDir: string;\n builtAt: string;\n fileHashes: Record<string, number>; // file -> mtimeMs\n symbols: Record<string, SymbolEntry[]>;\n}\n\nexport class SymbolIndex {\n private index: Record<string, SymbolEntry[]> = {};\n\n private getCachePath(rootDir: string): string {\n const hash = crypto\n .createHash('sha256')\n .update(rootDir)\n .digest('hex')\n .slice(0, 12);\n return path.join(\n process.platform === 'win32' ? process.env.TEMP || 'c:/temp' : '/tmp',\n `ast-index-${hash}.json`\n );\n }\n\n private isCacheValid(cached: DiskCache, rootDir: string): boolean {\n if (cached.rootDir !== rootDir) return false;\n\n for (const [file, cachedMtime] of Object.entries(cached.fileHashes)) {\n if (!fs.existsSync(file)) return false;\n if (fs.statSync(file).mtimeMs !== cachedMtime) return false;\n }\n\n return true;\n }\n\n private computeStats(\n cache: DiskCache,\n duration_ms?: number,\n memory_mb?: number\n ): IndexingStats {\n const files = Object.keys(cache.fileHashes).length;\n let functions = 0;\n let classes = 0;\n let interfaces = 0;\n let types = 0;\n\n for (const entries of Object.values(cache.symbols)) {\n for (const entry of entries) {\n if (entry.kind === 'function' || entry.kind === 'method') functions++;\n if (entry.kind === 'class') classes++;\n if (entry.kind === 'interface') interfaces++;\n if (entry.kind === 'type_alias') types++;\n }\n }\n\n return {\n indexed: {\n files,\n functions,\n classes,\n interfaces,\n types,\n },\n duration_ms: duration_ms || 0,\n memory_mb: memory_mb || 0,\n };\n }\n\n private mapKind(node: Node): SymbolKind {\n if (Node.isClassDeclaration(node)) return 'class';\n if (Node.isFunctionDeclaration(node)) return 'function';\n if (Node.isInterfaceDeclaration(node)) return 'interface';\n if (Node.isTypeAliasDeclaration(node)) return 'type_alias';\n if (Node.isEnumDeclaration(node)) return 'enum';\n if (Node.isVariableDeclaration(node)) return 'variable';\n if (Node.isMethodDeclaration(node)) return 'method';\n if (Node.isPropertyDeclaration(node)) return 'property';\n if (Node.isParameterDeclaration(node)) return 'parameter';\n return 'variable';\n }\n\n /**\n * Build/Warm the index for a given path\n */\n public async buildIndex(rootDir: string): Promise<IndexingStats> {\n const startTime = Date.now();\n const safeRoot = validateWorkspacePath(rootDir);\n const cachePath = this.getCachePath(safeRoot);\n\n if (fs.existsSync(cachePath) && process.env.AST_DISABLE_CACHE !== 'true') {\n try {\n const cached: DiskCache = JSON.parse(\n fs.readFileSync(cachePath, 'utf-8')\n );\n if (this.isCacheValid(cached, safeRoot)) {\n this.index = cached.symbols;\n return this.computeStats(\n cached,\n Date.now() - startTime,\n process.memoryUsage().heapUsed / 1024 / 1024\n );\n }\n } catch {\n // Corrupt cache, ignore\n }\n }\n\n const tsconfigs = await projectManager.getProjectsForPath(safeRoot);\n const symbols: Record<string, SymbolEntry[]> = {};\n const fileHashes: Record<string, number> = {};\n\n for (const config of tsconfigs) {\n const project = projectManager.ensureProject(config);\n // We need to force load files for indexing\n project.addSourceFilesFromTsConfig(config);\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n try {\n fileHashes[filePath] = fs.statSync(filePath).mtimeMs;\n } catch {\n continue;\n }\n\n // Extract exported declarations\n for (const [name, decls] of sourceFile.getExportedDeclarations()) {\n for (const decl of decls) {\n const entry: SymbolEntry = {\n name,\n kind: this.mapKind(decl as Node),\n file: filePath,\n line: decl.getStartLineNumber(),\n column: decl.getStart() - decl.getStartLinePos(),\n exported: true,\n };\n (symbols[name] ||= []).push(entry);\n }\n }\n\n // Extract non-exported top-level declarations\n for (const fn of sourceFile.getFunctions()) {\n const name = fn.getName();\n if (\n name &&\n !symbols[name]?.some(\n (s) => s.file === filePath && s.line === fn.getStartLineNumber()\n )\n ) {\n const entry: SymbolEntry = {\n name,\n kind: 'function',\n file: filePath,\n line: fn.getStartLineNumber(),\n column: fn.getStart() - fn.getStartLinePos(),\n exported: false,\n };\n (symbols[name] ||= []).push(entry);\n }\n }\n for (const cls of sourceFile.getClasses()) {\n const name = cls.getName();\n if (\n name &&\n !symbols[name]?.some(\n (s) => s.file === filePath && s.line === cls.getStartLineNumber()\n )\n ) {\n const entry: SymbolEntry = {\n name,\n kind: 'class',\n file: filePath,\n line: cls.getStartLineNumber(),\n column: cls.getStart() - cls.getStartLinePos(),\n exported: false,\n };\n (symbols[name] ||= []).push(entry);\n }\n }\n }\n }\n\n const cache: DiskCache = {\n version: 1,\n rootDir: safeRoot,\n builtAt: new Date().toISOString(),\n fileHashes,\n symbols,\n };\n\n fs.mkdirSync(path.dirname(cachePath), { recursive: true });\n fs.writeFileSync(cachePath, JSON.stringify(cache));\n\n this.index = symbols;\n\n const duration = Date.now() - startTime;\n const memoryUsage = process.memoryUsage().heapUsed / 1024 / 1024;\n\n return this.computeStats(cache, duration, Math.round(memoryUsage));\n }\n\n public isInitialized(): boolean {\n return Object.keys(this.index).length > 0;\n }\n\n public lookup(name: string): SymbolEntry[] {\n return this.index[name] || [];\n }\n\n public lookupByFile(file: string): SymbolEntry[] {\n return Object.values(this.index)\n .flat()\n .filter((e) => e.file === file);\n }\n}\n\nexport const symbolIndex = new SymbolIndex();\n","import { Worker } from 'worker_threads';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\ninterface WorkerTask<T> {\n id: string;\n type: string;\n payload: unknown;\n resolve: (value: T) => void;\n reject: (error: Error) => void;\n}\n\nexport class WorkerPool {\n private workers: Worker[] = [];\n private available: Worker[] = [];\n private queue: WorkerTask<unknown>[] = [];\n private activeJobs = new Map<string, WorkerTask<unknown>>();\n private taskId = 0;\n\n constructor(private poolSize: number) {}\n\n async init(): Promise<void> {\n const __dirname = path.dirname(fileURLToPath(import.meta.url));\n const workerPath = path.join(__dirname, 'ast-worker.js'); // Assuming tsup builds this\n\n for (let i = 0; i < this.poolSize; i++) {\n const worker = new Worker(workerPath);\n worker.on('message', (msg) => this.handleResult(worker, msg));\n worker.on('error', (_err) => this.handleWorkerError(worker, _err));\n this.workers.push(worker);\n this.available.push(worker);\n }\n }\n\n async execute<T>(type: string, payload: unknown): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = String(++this.taskId);\n const task: WorkerTask<T> = { id, type, payload, resolve, reject };\n\n const worker = this.available.pop();\n if (worker) {\n this.dispatch(worker, task);\n } else {\n this.queue.push(task as WorkerTask<unknown>);\n }\n });\n }\n\n private dispatch<T>(worker: Worker, task: WorkerTask<T>): void {\n this.activeJobs.set(task.id, task as WorkerTask<unknown>);\n worker.postMessage({ id: task.id, type: task.type, payload: task.payload });\n }\n\n private handleResult(\n worker: Worker,\n msg: {\n id: string;\n result?: unknown;\n error?: string;\n }\n ): void {\n const task = this.activeJobs.get(msg.id);\n if (!task) return;\n\n this.activeJobs.delete(msg.id);\n\n if (msg.error) {\n task.reject(new Error(msg.error));\n } else {\n task.resolve(msg.result);\n }\n\n // Return worker to pool or dispatch next task\n const nextTask = this.queue.shift();\n if (nextTask) {\n this.dispatch(worker, nextTask);\n } else {\n this.available.push(worker);\n }\n }\n\n private handleWorkerError(worker: Worker, err: unknown): void {\n const idx = this.workers.indexOf(worker);\n if (idx !== -1) {\n worker.terminate();\n const __dirname = path.dirname(fileURLToPath(import.meta.url));\n const workerPath = path.join(__dirname, 'ast-worker.js');\n const newWorker = new Worker(workerPath);\n newWorker.on('message', (msg) => this.handleResult(newWorker, msg));\n newWorker.on('error', (_e) => this.handleWorkerError(newWorker, _e));\n this.workers[idx] = newWorker;\n this.available.push(newWorker);\n }\n }\n\n async terminate(): Promise<void> {\n await Promise.all(this.workers.map((w) => w.terminate()));\n this.workers = [];\n this.available = [];\n }\n}\n","import { typescriptAdapter } from '../adapters/typescript-adapter.js';\n\n/**\n * Generic wrapper for symbol-related adapter calls to reduce boilerplate.\n */\nexport async function wrapAdapterCall<T>(\n methodName: keyof typeof typescriptAdapter,\n symbol: string,\n path: string,\n ...args: any[]\n): Promise<T> {\n const method = typescriptAdapter[methodName] as (\n ...args: any[]\n ) => Promise<T>;\n return await method.apply(typescriptAdapter, [symbol, path, ...args]);\n}\n","import { wrapAdapterCall } from '../utils/tool-utils.js';\nimport { DefinitionLocation } from '../types.js';\n\n/**\n * Resolve the definition of a symbol.\n */\nexport async function resolveDefinition(\n symbol: string,\n path: string\n): Promise<DefinitionLocation[]> {\n return await wrapAdapterCall<DefinitionLocation[]>(\n 'resolveDefinition',\n symbol,\n path\n );\n}\n","import { wrapAdapterCall } from '../utils/tool-utils.js';\n\n/**\n * Find all references to a specific symbol in the project.\n */\nexport async function findReferences(\n symbol: string,\n path: string,\n limit: number = 50,\n offset: number = 0\n) {\n return await wrapAdapterCall('findReferences', symbol, path, limit, offset);\n}\n","import { wrapAdapterCall } from '../utils/tool-utils.js';\n\n/**\n * Find all implementations of a specific interface or class.\n */\nexport async function findImplementations(\n symbol: string,\n path: string,\n limit: number = 50,\n offset: number = 0\n) {\n return await wrapAdapterCall(\n 'findImplementations',\n symbol,\n path,\n limit,\n offset\n );\n}\n","import { typescriptAdapter } from '../adapters/typescript-adapter.js';\n\nexport async function getFileStructure(file: string) {\n return await typescriptAdapter.getFileStructure(file);\n}\n","import { typescriptAdapter } from '../adapters/typescript-adapter.js';\nimport { projectManager } from '../project-manager.js';\nimport { SyntaxKind, Node } from 'ts-morph';\nimport { validateWorkspacePath } from '../security.js';\n\nexport async function getSymbolDocs(\n symbol: string,\n filePath: string\n): Promise<any> {\n const safePath = validateWorkspacePath(filePath);\n const tsconfig = await projectManager.findNearestTsConfig(safePath);\n if (!tsconfig) return undefined;\n\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(safePath);\n\n if (sourceFile) {\n const node = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .find((id: Node) => id.getText() === symbol);\n\n if (node) {\n const decls = node.getSymbol()?.getDeclarations();\n if (decls && decls.length > 0) {\n const docs = typescriptAdapter.getSymbolDocs(decls[0]);\n if (docs) {\n return {\n symbol,\n file: sourceFile.getFilePath(),\n line: sourceFile.getLineAndColumnAtPos(decls[0].getStart()).line,\n ...docs,\n };\n }\n }\n }\n }\n\n return undefined;\n}\n","import { symbolIndex } from '../index/symbol-index.js';\n\nexport async function buildSymbolIndex(path: string) {\n return await symbolIndex.buildIndex(path);\n}\n","import { projectManager } from '../project-manager.js';\nimport { validateWorkspacePath } from '../security.js';\nimport { Node, SyntaxKind } from 'ts-morph';\n\nexport async function getCallHierarchy(\n symbolName: string,\n rootDir: string,\n direction: 'incoming' | 'outgoing' | 'both' = 'both'\n) {\n const safeRoot = validateWorkspacePath(rootDir);\n const configs = await projectManager.getProjectsForPath(safeRoot);\n\n const results: {\n symbol: string;\n incoming: Array<{ name: string; file: string; line: number }>;\n outgoing: Array<{ name: string; file: string; line: number }>;\n } = {\n symbol: symbolName,\n incoming: [],\n outgoing: [],\n };\n\n for (const config of configs) {\n const project = projectManager.ensureProject(config);\n project.addSourceFilesFromTsConfig(config);\n\n // Find the symbol definition\n const sourceFiles = project.getSourceFiles();\n let targetNode: Node | undefined;\n\n for (const file of sourceFiles) {\n const decls = file.getExportedDeclarations().get(symbolName) || [];\n if (decls.length > 0) {\n targetNode = decls[0] as Node;\n break;\n }\n\n // Also look for non-exported ones\n const fn = file.getFunction(symbolName);\n if (fn) {\n targetNode = fn;\n break;\n }\n\n const cls = file.getClass(symbolName);\n if (cls) {\n targetNode = cls;\n break;\n }\n }\n\n if (!targetNode) continue;\n\n // Incoming calls (references)\n if (direction === 'incoming' || direction === 'both') {\n const referencedSymbols = (targetNode as any).findReferences?.() || [];\n for (const referencedSymbol of referencedSymbols) {\n for (const reference of referencedSymbol.getReferences()) {\n const sourceFile = reference.getSourceFile();\n const fileName = sourceFile.getFilePath();\n const line = reference.getNode().getStartLineNumber();\n\n const caller =\n reference\n .getNode()\n .getFirstAncestorByKind(SyntaxKind.FunctionDeclaration) ||\n reference\n .getNode()\n .getFirstAncestorByKind(SyntaxKind.MethodDeclaration) ||\n reference\n .getNode()\n .getFirstAncestorByKind(SyntaxKind.ClassDeclaration);\n\n results.incoming.push({\n name: (caller as any)?.getName?.() || 'anonymous',\n file: fileName,\n line: line,\n });\n }\n }\n }\n\n // Outgoing calls\n if (direction === 'outgoing' || direction === 'both') {\n const calls = targetNode.getDescendantsOfKind(SyntaxKind.CallExpression);\n for (const call of calls) {\n const expression = call.getExpression();\n const symbol = (call as any).getReturnType?.()\n ? (call as any).getExpression().getSymbol()\n : undefined;\n\n results.outgoing.push({\n name: symbol?.getName() || expression.getText(),\n file: call.getSourceFile().getFilePath(),\n line: call.getStartLineNumber(),\n });\n }\n }\n }\n\n // Deduplicate results safely\n const uniqueIncoming = new Map<string, any>();\n for (const item of results.incoming) {\n uniqueIncoming.set(`${item.file}:${item.line}`, item);\n }\n results.incoming = Array.from(uniqueIncoming.values());\n\n const uniqueOutgoing = new Map<string, any>();\n for (const item of results.outgoing) {\n uniqueOutgoing.set(`${item.file}:${item.line}:${item.name}`, item);\n }\n results.outgoing = Array.from(uniqueOutgoing.values());\n\n return results;\n}\n","import { typescriptAdapter } from '../adapters/typescript-adapter.js';\nimport { projectManager } from '../project-manager.js';\nimport { SyntaxKind, Node } from 'ts-morph';\nimport { validateWorkspacePath } from '../security.js';\n\nexport interface GroundingScore {\n score: number;\n grade: string;\n breakdown: {\n documentation: number;\n typeClarity: number;\n depthImpact: number;\n };\n recommendations: string[];\n}\n\nexport async function checkSymbolGrounding(\n symbol: string,\n filePath: string\n): Promise<GroundingScore | undefined> {\n const safePath = validateWorkspacePath(filePath);\n const tsconfig = await projectManager.findNearestTsConfig(safePath);\n if (!tsconfig) return undefined;\n\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(safePath);\n\n if (!sourceFile) return undefined;\n\n const node = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .find((id: Node) => id.getText() === symbol);\n\n if (!node) return undefined;\n\n const decl = node.getSymbol()?.getDeclarations()?.[0];\n if (!decl) return undefined;\n\n let docScore = 0;\n let typeScore = 0;\n let depthScore = 30;\n const recommendations: string[] = [];\n\n // 1. Documentation Analysis\n const docs = typescriptAdapter.getSymbolDocs(decl as Node);\n if (docs) {\n docScore += 10;\n if (docs.documentation && docs.documentation.length > 20) docScore += 10;\n\n const hasParams = docs.tags.some((t) => t.name === 'param');\n const hasReturns = docs.tags.some(\n (t) => t.name === 'returns' || t.name === 'return'\n );\n\n if (hasParams) docScore += 10;\n else\n recommendations.push(\n 'Add @param tags to document implementation details for the agent.'\n );\n\n if (hasReturns) docScore += 10;\n else\n recommendations.push('Add @returns tag to clarify output expectations.');\n } else {\n recommendations.push(\n 'Missing JSDoc. Agents need explicit documentation to understand intent without reading the source.'\n );\n }\n\n // 2. Type Clarity Analysis\n const typeText = (decl as any).getType?.()?.getText?.() || '';\n if (typeText) {\n if (!typeText.includes('any')) typeScore += 15;\n else\n recommendations.push(\n 'Avoid \"any\" types. They break agentic reasoning and cause hallucinations.'\n );\n\n if (!typeText.includes('unknown')) typeScore += 15;\n else\n recommendations.push(\n 'Use specific interfaces instead of \"unknown\" to minimize agent probe requirements.'\n );\n }\n\n // 3. Depth Impact (Simulated for now based on imports in file)\n const importCount = sourceFile.getImportDeclarations().length;\n if (importCount > 10) {\n const penalty = Math.min(20, (importCount - 10) * 2);\n depthScore -= penalty;\n recommendations.push(\n `High dependency depth (${importCount} imports). Agents must load more files to understand this symbol's context.`\n );\n }\n\n const totalScore = docScore + typeScore + depthScore;\n let grade = 'F';\n if (totalScore >= 90) grade = 'S (Agent-Native)';\n else if (totalScore >= 80) grade = 'A (Highly Grounded)';\n else if (totalScore >= 70) grade = 'B (Good)';\n else if (totalScore >= 60) grade = 'C (Acceptable)';\n else if (totalScore >= 40) grade = 'D (Poor)';\n\n return {\n score: totalScore,\n grade,\n breakdown: {\n documentation: docScore,\n typeClarity: typeScore,\n depthImpact: depthScore,\n },\n recommendations,\n };\n}\n"],"mappings":";;;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACLP,SAAS,SAAS;AAKX,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,QAAQ,EACL,OAAO,EACP;AAAA,IACC;AAAA,EACF;AAAA,EACF,MAAM,EAAE,OAAO,EAAE,SAAS,kCAAkC;AAC9D,CAAC;AAKM,IAAM,uBAAuB,EAAE,OAAO;AAAA,EAC3C,QAAQ,EAAE,OAAO,EAAE,SAAS,oCAAoC;AAAA,EAChE,MAAM,EAAE,OAAO,EAAE,SAAS,wBAAwB;AAAA,EAClD,OAAO,EACJ,OAAO,EACP,SAAS,EACT,QAAQ,EAAE,EACV,SAAS,mCAAmC;AAAA,EAC/C,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,CAAC,EAAE,SAAS,mBAAmB;AACvE,CAAC;AAKM,IAAM,4BAA4B,EAAE,OAAO;AAA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config","searchCode","Node","path","path","path","path","path","SyntaxKind","SyntaxKind","SyntaxKind","path"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/schemas.ts","../src/adapters/typescript-adapter.ts","../src/project-manager.ts","../src/index/symbol-index.ts","../src/worker/pool.ts","../src/utils/tool-utils.ts","../src/tools/resolve-definition.ts","../src/tools/find-references.ts","../src/tools/find-implementations.ts","../src/tools/get-file-structure.ts","../src/tools/get-symbol-docs.ts","../src/tools/build-symbol-index.ts","../src/tools/call-hierarchy.ts","../src/tools/check-symbol-grounding.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\nimport {\n ResolveDefinitionSchema,\n FindReferencesSchema,\n FindImplementationsSchema,\n GetFileStructureSchema,\n SearchCodeSchema,\n GrepSearchSchema,\n GetSymbolDocsSchema,\n BuildSymbolIndexSchema,\n GetCallHierarchySchema,\n CheckSymbolGroundingSchema,\n CodebaseAuditSchema,\n} from './schemas.js';\nimport { resolveDefinition } from './tools/resolve-definition.js';\nimport { findReferences } from './tools/find-references.js';\nimport { findImplementations } from './tools/find-implementations.js';\nimport { getFileStructure } from './tools/get-file-structure.js';\nimport { searchCode } from './tools/search-code.js';\nimport { grepSearch } from '@aiready/core';\nimport { getSymbolDocs } from './tools/get-symbol-docs.js';\nimport { buildSymbolIndex } from './tools/build-symbol-index.js';\nimport { getCallHierarchy } from './tools/call-hierarchy.js';\nimport { checkSymbolGrounding } from './tools/check-symbol-grounding.js';\nimport { symbolIndex } from './index/symbol-index.js';\nimport {\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\n/**\n * AST-aware Code Exploration MCP Server\n */\nexport class ASTExplorerServer {\n private server: Server;\n private version: string = '0.1.0';\n\n constructor() {\n this.server = new Server(\n {\n name: 'ast-explorer-server',\n version: this.version,\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n }\n );\n\n this.setupHandlers();\n\n this.server.onerror = (error) => {\n console.error('[MCP Error]', error);\n };\n }\n\n private setupHandlers() {\n // List available resources\n this.server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return {\n resources: [\n {\n uri: 'ast://file/symbols',\n name: 'File Symbol List',\n description: 'Get all symbols defined in a file.',\n mimeType: 'application/json',\n },\n ],\n };\n });\n\n // Read resource content\n this.server.setRequestHandler(\n ReadResourceRequestSchema,\n async (request) => {\n const { uri } = request.params;\n const url = new URL(uri);\n\n if (url.protocol === 'ast:' && url.pathname === '//file/symbols') {\n const filePath = url.searchParams.get('path');\n if (!filePath) throw new Error('Missing \"path\" parameter in URI');\n\n const symbols = symbolIndex.lookupByFile(filePath);\n return {\n contents: [\n {\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(symbols, null, 2),\n },\n ],\n };\n }\n\n throw new Error(`Resource not found: ${uri}`);\n }\n );\n\n // List available tools\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: [\n {\n name: 'resolve_definition',\n description: 'Find where a symbol is defined using TypeScript AST.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: {\n type: 'string',\n description: 'Symbol name (e.g., function, class)',\n },\n path: {\n type: 'string',\n description: 'Project root or target directory',\n },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'find_references',\n description: 'Find all usages of a symbol across the project.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string', description: 'Symbol name' },\n path: { type: 'string', description: 'Project root' },\n limit: { type: 'number', default: 50 },\n offset: { type: 'number', default: 0 },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'find_implementations',\n description:\n 'Find implementations of interfaces or abstract classes.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string', description: 'Interface/Class name' },\n path: { type: 'string', description: 'Project root' },\n limit: { type: 'number', default: 50 },\n offset: { type: 'number', default: 0 },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'get_file_structure',\n description:\n 'Get structural overview of a file (imports, exports, symbols).',\n inputSchema: {\n type: 'object',\n properties: {\n file: { type: 'string', description: 'Absolute path to file' },\n },\n required: ['file'],\n },\n },\n {\n name: 'grep_search',\n description:\n 'Fast, context-aware text search via ripgrep. Supports context lines and result summarization.',\n inputSchema: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Search pattern' },\n path: { type: 'string', description: 'Directory to search' },\n include: {\n type: 'array',\n items: { type: 'string' },\n description: 'Glob filter',\n },\n exclude: {\n type: 'array',\n items: { type: 'string' },\n description: 'Exclusion filter',\n },\n limit: { type: 'number', default: 50 },\n offset: { type: 'number', default: 0 },\n context: { type: 'number', default: 2 },\n isRegex: { type: 'boolean', default: true },\n },\n required: ['pattern', 'path'],\n },\n },\n {\n name: 'search_code',\n description:\n 'Fast regex search via bundled ripgrep (alias for grep_search).',\n inputSchema: {\n type: 'object',\n properties: {\n pattern: { type: 'string', description: 'Search pattern' },\n path: { type: 'string', description: 'Directory to search' },\n filePattern: { type: 'string', description: 'Glob filter' },\n limit: { type: 'number', default: 50 },\n offset: { type: 'number', default: 0 },\n regex: { type: 'boolean', default: true },\n },\n required: ['pattern', 'path'],\n },\n },\n {\n name: 'get_symbol_docs',\n description: 'Get JSDoc/TSDoc for a specific symbol.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string', description: 'Symbol name' },\n path: { type: 'string', description: 'Project root' },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'build_symbol_index',\n description: 'Warm the symbol index for faster navigation.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Project root to index' },\n },\n required: ['path'],\n },\n },\n {\n name: 'get_call_hierarchy',\n description: 'Find callers and callees for a symbol.',\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string' },\n path: { type: 'string' },\n direction: {\n type: 'string',\n enum: ['incoming', 'outgoing'],\n default: 'outgoing',\n },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'check_symbol_grounding',\n description:\n \"Assess a symbol's AI grounding quality (docs, type clarity, depth).\",\n inputSchema: {\n type: 'object',\n properties: {\n symbol: { type: 'string' },\n path: { type: 'string' },\n },\n required: ['symbol', 'path'],\n },\n },\n {\n name: 'hygiene_audit',\n description:\n 'Performs a codebase-level hygiene check for technical debt (TODOs) and waste (empty dirs, orphans).',\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Project root directory to audit',\n },\n },\n required: ['path'],\n },\n },\n {\n name: 'metabolism_audit',\n description: 'Alias for hygiene_audit (Serverless Claw compat).',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string' },\n },\n required: ['path'],\n },\n },\n {\n name: 'codebase_audit',\n description: 'Alias for hygiene_audit.',\n inputSchema: {\n type: 'object',\n properties: {\n path: { type: 'string' },\n },\n required: ['path'],\n },\n },\n ],\n };\n });\n\n // Tool execution handler\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n try {\n switch (name) {\n case 'resolve_definition': {\n const { symbol, path } = ResolveDefinitionSchema.parse(args);\n const results = await resolveDefinition(symbol, path);\n return {\n content: [\n { type: 'text', text: JSON.stringify(results, null, 2) },\n ],\n };\n }\n case 'find_references': {\n const { symbol, path, limit, offset } =\n FindReferencesSchema.parse(args);\n const results = await findReferences(symbol, path, limit, offset);\n return {\n content: [\n { type: 'text', text: JSON.stringify(results, null, 2) },\n ],\n };\n }\n case 'find_implementations': {\n const { symbol, path, limit, offset } =\n FindImplementationsSchema.parse(args);\n const results = await findImplementations(\n symbol,\n path,\n limit,\n offset\n );\n return {\n content: [\n { type: 'text', text: JSON.stringify(results, null, 2) },\n ],\n };\n }\n case 'get_file_structure': {\n const { file } = GetFileStructureSchema.parse(args);\n const structure = await getFileStructure(file);\n return {\n content: [\n { type: 'text', text: JSON.stringify(structure, null, 2) },\n ],\n };\n }\n case 'grep_search': {\n const {\n pattern,\n path,\n include,\n exclude,\n limit,\n offset,\n context,\n isRegex,\n } = GrepSearchSchema.parse(args);\n const result = await grepSearch({\n pattern,\n path,\n include,\n exclude,\n limit,\n offset,\n context,\n isRegex,\n });\n return {\n content: [\n { type: 'text', text: JSON.stringify(result, null, 2) },\n ],\n };\n }\n case 'search_code': {\n const { pattern, path, filePattern, limit, offset, regex } =\n SearchCodeSchema.parse(args);\n const result = await grepSearch({\n pattern,\n path,\n include: filePattern ? [filePattern] : [],\n limit,\n offset,\n isRegex: regex,\n context: 0,\n });\n return {\n content: [\n { type: 'text', text: JSON.stringify(result, null, 2) },\n ],\n };\n }\n case 'get_symbol_docs': {\n const { symbol, path } = GetSymbolDocsSchema.parse(args);\n const docs = await getSymbolDocs(symbol, path);\n return {\n content: [{ type: 'text', text: JSON.stringify(docs, null, 2) }],\n };\n }\n case 'build_symbol_index': {\n const { path } = BuildSymbolIndexSchema.parse(args);\n const stats = await buildSymbolIndex(path);\n return {\n content: [{ type: 'text', text: JSON.stringify(stats, null, 2) }],\n };\n }\n case 'get_call_hierarchy': {\n const { symbol, path, direction } =\n GetCallHierarchySchema.parse(args);\n const hierarchy = await getCallHierarchy(symbol, path, direction);\n return {\n content: [\n { type: 'text', text: JSON.stringify(hierarchy, null, 2) },\n ],\n };\n }\n case 'check_symbol_grounding': {\n const { symbol, path } = CheckSymbolGroundingSchema.parse(args);\n const result = await checkSymbolGrounding(symbol, path);\n return {\n content: [\n { type: 'text', text: JSON.stringify(result, null, 2) },\n ],\n };\n }\n case 'hygiene_audit':\n case 'metabolism_audit':\n case 'codebase_audit': {\n const { path: rootDir } = CodebaseAuditSchema.parse(args);\n // Dynamic import of the new hygiene-audit package logic\n const { HygieneAuditProvider } =\n await import('@aiready/hygiene-audit');\n const provider = new HygieneAuditProvider();\n const result = await provider.analyze({ rootDir });\n\n // Map ScanResult back to the flat structure serverlessclaw expects in metadata\n const allIssues = result.results.flatMap((r) => r.issues);\n const metadata = {\n debtMarkers: result.metadata?.debtMarkers || 0,\n emptyDirs: result.metadata?.emptyDirs || [],\n orphanedFiles: result.metadata?.orphanedFiles || [],\n findings: allIssues.map((i: any) => ({\n expected: i.recommendation || i.suggestion || '',\n actual: i.message,\n severity:\n i.severity === 'critical'\n ? 'P0'\n : i.severity === 'major'\n ? 'P1'\n : 'P2',\n recommendation: i.recommendation || i.suggestion || '',\n })),\n };\n\n return {\n content: [\n { type: 'text', text: JSON.stringify(result, null, 2) },\n ],\n metadata,\n };\n }\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n } catch (error: any) {\n return {\n content: [{ type: 'text', text: `Error: ${error.message}` }],\n isError: true,\n };\n }\n });\n }\n\n async run() {\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n console.error('AST Explorer MCP Server started');\n }\n}\n\n// Start the server\nconst server = new ASTExplorerServer();\nserver.run().catch((error) => {\n console.error('Fatal error starting AST Explorer MCP Server:', error);\n process.exit(1);\n});\n","import { z } from 'zod';\n\n/**\n * Tool 1: resolve_definition\n */\nexport const ResolveDefinitionSchema = z.object({\n symbol: z\n .string()\n .describe(\n 'Symbol name to resolve (function, class, type, interface, etc.)'\n ),\n path: z.string().describe('Project root or target directory'),\n});\n\n/**\n * Tool 2: find_references\n */\nexport const FindReferencesSchema = z.object({\n symbol: z.string().describe('Symbol name to find references for'),\n path: z.string().describe('Project root directory'),\n limit: z\n .number()\n .optional()\n .default(50)\n .describe('Max results per page (default 50)'),\n offset: z.number().optional().default(0).describe('Pagination offset'),\n});\n\n/**\n * Tool 3: find_implementations\n */\nexport const FindImplementationsSchema = z.object({\n symbol: z\n .string()\n .describe('Interface or abstract class name to find implementations for'),\n path: z.string().describe('Project root directory'),\n limit: z.number().optional().default(50).describe('Max results per page'),\n offset: z.number().optional().default(0).describe('Pagination offset'),\n});\n\n/**\n * Tool 4: get_file_structure\n */\nexport const GetFileStructureSchema = z.object({\n file: z.string().describe('Absolute path to the file to analyze'),\n});\n\n/**\n * Tool 5: grep_search\n */\nexport const GrepSearchSchema = z.object({\n pattern: z.string().describe('Search pattern (regex by default)'),\n path: z.string().describe('Directory to search in'),\n include: z\n .array(z.string())\n .optional()\n .describe('Include only these glob patterns (e.g., [\"*.ts\", \"src/**\"])'),\n exclude: z\n .array(z.string())\n .optional()\n .describe('Exclude these glob patterns (e.g., [\"**/*.test.ts\"])'),\n limit: z\n .number()\n .optional()\n .default(50)\n .describe('Max matches to return (default 50)'),\n offset: z\n .number()\n .optional()\n .default(0)\n .describe('Pagination offset (default 0)'),\n context: z\n .number()\n .optional()\n .default(2)\n .describe('Number of context lines before and after (default 2)'),\n isRegex: z\n .boolean()\n .optional()\n .default(true)\n .describe('Use regex mode (default true)'),\n});\n\n/**\n * Tool 6: search_code (legacy alias for grep_search)\n */\nexport const SearchCodeSchema = z.object({\n pattern: z.string().describe('Search pattern (regex by default)'),\n path: z.string().describe('Directory to search in'),\n filePattern: z.string().optional().describe('Glob filter (e.g., \"*.ts\")'),\n limit: z\n .number()\n .optional()\n .default(50)\n .describe('Max matches to return (default 50)'),\n offset: z\n .number()\n .optional()\n .default(0)\n .describe('Pagination offset (default 0)'),\n regex: z\n .boolean()\n .optional()\n .default(true)\n .describe('Use regex mode (default true)'),\n});\n\n/**\n * Tool 6: get_symbol_docs\n */\nexport const GetSymbolDocsSchema = z.object({\n symbol: z.string().describe('Symbol name to get documentation for'),\n path: z.string().describe('Project root directory'),\n});\n\n/**\n * Tool 7: build_symbol_index\n */\nexport const BuildSymbolIndexSchema = z.object({\n path: z.string().describe('Project root directory to index'),\n});\n/**\n * Tool 8: get_call_hierarchy\n */\nexport const GetCallHierarchySchema = z.object({\n symbol: z.string().describe('Symbol name to find callers/callees for'),\n path: z.string().describe('Project root directory'),\n direction: z\n .enum(['incoming', 'outgoing', 'both'])\n .optional()\n .default('both')\n .describe('Direction of calls (default: both)'),\n});\n/**\n * Tool 9: check_symbol_grounding\n */\nexport const CheckSymbolGroundingSchema = z.object({\n symbol: z.string().describe('Symbol name to assess grounding for'),\n path: z.string().describe('Project root directory'),\n});\n\n/**\n * Tool 10: codebase_audit\n */\nexport const CodebaseAuditSchema = z.object({\n path: z\n .string()\n .describe('Project root directory to audit for debt and bloat'),\n});\n","import { Node } from 'ts-morph';\nimport fs from 'fs';\nimport path from 'path';\nimport {\n DefinitionLocation,\n ReferenceLocation,\n FileStructure,\n SymbolKind,\n ClassInfo,\n FunctionInfo,\n InterfaceInfo,\n TypeAliasInfo,\n EnumInfo,\n} from '../types.js';\nimport { projectManager } from '../project-manager.js';\nimport { symbolIndex } from '../index/symbol-index.js';\nimport { validateWorkspacePath } from '../security.js';\nimport { WorkerPool } from '../worker/pool.js';\n\nexport class TypeScriptAdapter {\n private pool: WorkerPool;\n\n constructor() {\n const poolSize = parseInt(process.env.AST_WORKER_POOL_SIZE || '2');\n this.pool = new WorkerPool(poolSize);\n }\n\n private async ensureIndex(p: string): Promise<void> {\n if (!symbolIndex.isInitialized()) {\n const absolutePath = path.resolve(p);\n let searchPath = absolutePath;\n\n if (!fs.statSync(absolutePath).isDirectory()) {\n const tsconfig = await projectManager.findNearestTsConfig(absolutePath);\n searchPath = tsconfig\n ? path.dirname(tsconfig)\n : path.dirname(absolutePath);\n }\n\n console.error(\n `[AST] Index not initialized. Building for ${searchPath}...`\n );\n await symbolIndex.buildIndex(searchPath);\n }\n }\n\n public async resolveDefinition(\n symbolName: string,\n path: string\n ): Promise<DefinitionLocation[]> {\n validateWorkspacePath(path);\n await this.ensureIndex(path);\n\n // Fast path: index lookup (O(1)) to find the file\n const indexHits = symbolIndex.lookup(symbolName);\n if (indexHits.length > 0) {\n const results: DefinitionLocation[] = [];\n for (const hit of indexHits) {\n const tsconfig = await projectManager.findNearestTsConfig(hit.file);\n if (tsconfig) {\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(hit.file);\n if (sourceFile) {\n const exported = sourceFile\n .getExportedDeclarations()\n .get(symbolName);\n if (exported && exported.length > 0) {\n results.push(this.mapToDefinitionLocation(exported[0] as Node));\n continue;\n }\n }\n }\n // Fallback if ts-morph loading fails for the hit\n results.push({\n file: hit.file,\n line: hit.line,\n column: hit.column,\n kind: hit.kind,\n snippet: '',\n documentation: undefined,\n });\n }\n return results;\n }\n\n // Fallback: search specific file via ts-morph (useful for local files without full index)\n if (fs.statSync(path).isDirectory()) {\n return []; // Cannot load a directory as a single file\n }\n\n const tsconfig = await projectManager.findNearestTsConfig(path);\n if (!tsconfig) return [];\n\n // Use worker pool for heavy ts-morph operations\n try {\n const result = await this.pool.execute<DefinitionLocation[]>(\n 'resolve_definition',\n {\n tsconfig,\n file: path,\n symbol: symbolName,\n }\n );\n return result;\n } catch {\n // Fallback to main thread if worker fails\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(path);\n if (!sourceFile) return [];\n\n const exported = sourceFile.getExportedDeclarations().get(symbolName);\n if (!exported) return [];\n\n return exported.map((decl) => this.mapToDefinitionLocation(decl as Node));\n }\n }\n\n public async findReferences(\n symbolName: string,\n path: string,\n limit: number = 50,\n offset: number = 0\n ): Promise<{ references: ReferenceLocation[]; total_count: number }> {\n validateWorkspacePath(path);\n await this.ensureIndex(path);\n\n // Index lookup to find definition location\n const hits = symbolIndex.lookup(symbolName);\n if (hits.length === 0) return { references: [], total_count: 0 };\n\n // Load only the definition file\n const hit = hits[0];\n const tsconfig = await projectManager.findNearestTsConfig(hit.file);\n if (!tsconfig) return { references: [], total_count: 0 };\n\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(hit.file);\n if (!sourceFile) return { references: [], total_count: 0 };\n\n // Hybrid approach: to prevent OOM, we don't load all files in the project.\n // Instead, we use rg to find files that literally contain the symbol name,\n // and only load those into ts-morph for accurate reference resolution.\n try {\n const { searchCode } = await import('../tools/search-code.js');\n const searchResults = await searchCode(\n symbolName,\n path,\n '**/*.{ts,tsx,js,jsx}',\n 1000,\n false\n );\n const filesToLoad = [...new Set(searchResults.map((r) => r.file))];\n for (const file of filesToLoad) {\n project.addSourceFileAtPathIfExists(file);\n }\n project.resolveSourceFileDependencies();\n } catch (_e) {\n // Ignore search failures - fallback to existing project files\n }\n\n // We need the actual node. Instead of calculating position from line/col, let's just find the exported declaration.\n // IMPORTANT: Re-get source file or ensure it's up to date after resolving dependencies if needed.\n const exported = sourceFile.getExportedDeclarations().get(symbolName);\n if (!exported || exported.length === 0)\n return { references: [], total_count: 0 };\n\n const targetNode = exported[0];\n\n const refSymbols =\n 'findReferences' in targetNode &&\n typeof (targetNode as { findReferences?: () => any[] }).findReferences ===\n 'function'\n ? (targetNode as { findReferences: () => any[] }).findReferences()\n : undefined;\n if (!refSymbols) return { references: [], total_count: 0 };\n\n const results: ReferenceLocation[] = [];\n for (const refSymbol of refSymbols) {\n for (const ref of refSymbol.getReferences()) {\n const sf = ref.getSourceFile();\n const lc = sf.getLineAndColumnAtPos(ref.getTextSpan().getStart());\n results.push({\n file: sf.getFilePath(),\n line: lc.line,\n column: lc.column,\n text: ref.getNode().getParent()?.getText() || ref.getNode().getText(),\n });\n }\n }\n\n const unique = this.deduplicateLocations(results);\n return {\n references: unique.slice(offset, offset + limit),\n total_count: unique.length,\n };\n }\n\n public async findImplementations(\n symbolName: string,\n path: string,\n limit: number = 50,\n offset: number = 0\n ): Promise<{ implementations: ReferenceLocation[]; total_count: number }> {\n validateWorkspacePath(path);\n await this.ensureIndex(path);\n const hits = symbolIndex.lookup(symbolName);\n if (hits.length === 0) return { implementations: [], total_count: 0 };\n\n const hit = hits[0];\n const tsconfig = await projectManager.findNearestTsConfig(hit.file);\n if (!tsconfig) return { implementations: [], total_count: 0 };\n\n // Use worker pool for heavy ts-morph operations\n try {\n const result = await this.pool.execute<{\n implementations: ReferenceLocation[];\n total_count: number;\n }>('find_implementations', {\n tsconfig,\n file: hit.file,\n symbol: symbolName,\n });\n\n // Apply pagination\n return {\n implementations: result.implementations.slice(offset, offset + limit),\n total_count: result.total_count,\n };\n } catch {\n // Fallback to main thread if worker fails\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(hit.file);\n if (!sourceFile) return { implementations: [], total_count: 0 };\n\n const exported = sourceFile.getExportedDeclarations().get(symbolName);\n if (!exported || exported.length === 0)\n return { implementations: [], total_count: 0 };\n\n const targetNode = exported[0];\n if (\n !Node.isClassDeclaration(targetNode) &&\n !Node.isInterfaceDeclaration(targetNode)\n ) {\n return { implementations: [], total_count: 0 };\n }\n\n try {\n const { searchCode } = await import('../tools/search-code.js');\n const searchResults = await searchCode(\n symbolName,\n path,\n '**/*.{ts,tsx,js,jsx}',\n 1000,\n false\n );\n const filesToLoad = [...new Set(searchResults.map((r) => r.file))];\n for (const file of filesToLoad) {\n project.addSourceFileAtPathIfExists(file);\n }\n } catch (_e) {\n // Ignore search failures - fallback to existing project files\n }\n\n const results: ReferenceLocation[] = [];\n const implementations =\n 'getImplementations' in targetNode &&\n typeof (targetNode as { getImplementations?: () => any[] })\n .getImplementations === 'function'\n ? (\n targetNode as { getImplementations: () => any[] }\n ).getImplementations()\n : undefined;\n if (implementations) {\n for (const impl of implementations) {\n const sf = impl.getSourceFile();\n const lc = sf.getLineAndColumnAtPos(impl.getTextSpan().getStart());\n results.push({\n file: sf.getFilePath(),\n line: lc.line,\n column: lc.column,\n text:\n impl.getNode().getParent()?.getText() || impl.getNode().getText(),\n });\n }\n }\n\n const unique = this.deduplicateLocations(results);\n return {\n implementations: unique.slice(offset, offset + limit),\n total_count: unique.length,\n };\n }\n }\n\n public async getFileStructure(\n filePath: string\n ): Promise<FileStructure | undefined> {\n const safePath = validateWorkspacePath(filePath);\n const tsconfig = await projectManager.findNearestTsConfig(safePath);\n if (!tsconfig) return undefined;\n\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(safePath);\n if (!sourceFile) return undefined;\n\n const structure: FileStructure = {\n file: safePath,\n imports: sourceFile.getImportDeclarations().map((imp) => ({\n module: imp.getModuleSpecifierValue(),\n names: imp.getNamedImports().map((ni) => ni.getName()),\n })),\n exports: sourceFile.getExportSymbols().map((sym) => ({\n name: sym.getName(),\n kind: this.mapSymbolKind(sym),\n })),\n classes: sourceFile.getClasses().map((cls) => this.mapToClassInfo(cls)),\n functions: sourceFile\n .getFunctions()\n .map((fn) => this.mapToFunctionInfo(fn)),\n interfaces: sourceFile\n .getInterfaces()\n .map((itf) => this.mapToInterfaceInfo(itf)),\n typeAliases: sourceFile\n .getTypeAliases()\n .map((ta) => this.mapToTypeAliasInfo(ta)),\n enums: sourceFile.getEnums().map((enm) => this.mapToEnumInfo(enm)),\n };\n\n return structure;\n }\n\n public async shutdown(): Promise<void> {\n await this.pool.terminate();\n }\n\n private mapToDefinitionLocation(node: Node): DefinitionLocation {\n const sourceFile = node.getSourceFile();\n const lineAndColumn = sourceFile.getLineAndColumnAtPos(node.getStart());\n\n return {\n file: sourceFile.getFilePath(),\n line: lineAndColumn.line,\n column: lineAndColumn.column,\n kind: this.mapNodeToSymbolKind(node),\n snippet: node.getText(),\n documentation: this.getJsDoc(node),\n };\n }\n\n private mapNodeToSymbolKind(node: Node): SymbolKind {\n if (Node.isClassDeclaration(node)) return 'class';\n if (Node.isFunctionDeclaration(node)) return 'function';\n if (Node.isInterfaceDeclaration(node)) return 'interface';\n if (Node.isTypeAliasDeclaration(node)) return 'type_alias';\n if (Node.isEnumDeclaration(node)) return 'enum';\n if (Node.isVariableDeclaration(node)) return 'variable';\n if (Node.isMethodDeclaration(node)) return 'method';\n if (Node.isPropertyDeclaration(node)) return 'property';\n if (Node.isParameterDeclaration(node)) return 'parameter';\n return 'variable';\n }\n\n private mapSymbolKind(symbol: any): SymbolKind {\n const decls = symbol.getDeclarations();\n if (decls.length > 0) return this.mapNodeToSymbolKind(decls[0]);\n return 'variable';\n }\n\n private getJsDoc(node: Node): string | undefined {\n if (Node.isJSDocable(node)) {\n const docs = node.getJsDocs();\n if (docs.length > 0) {\n return docs[0].getCommentText();\n }\n }\n return undefined;\n }\n\n public getSymbolDocs(node: Node) {\n if (Node.isJSDocable(node)) {\n const docs = node.getJsDocs();\n if (docs.length > 0) {\n const doc = docs[0];\n return {\n documentation: doc.getCommentText(),\n tags: doc.getTags().map((tag) => ({\n name: tag.getTagName(),\n text: tag.getCommentText() || '',\n })),\n };\n }\n }\n return undefined;\n }\n\n private mapToClassInfo(cls: any): ClassInfo {\n return {\n name: cls.getName() || 'anonymous',\n ...this.getSymbolDocs(cls),\n methods: cls.getMethods().map((m: any) => this.mapToFunctionInfo(m)),\n properties: cls\n .getProperties()\n .map((p: any) => this.mapToPropertyInfo(p)),\n };\n }\n\n private mapToFunctionInfo(fn: unknown): FunctionInfo {\n return {\n name: (fn as any)?.getName?.() || 'anonymous',\n ...this.getSymbolDocs(fn as any),\n params: ((fn as any)?.getParameters?.() || []).map((p: any) => ({\n name: p.getName(),\n type: p.getType().getText(),\n })),\n returnType: (fn as any)?.getReturnType?.()?.getText?.() || 'unknown',\n };\n }\n\n private mapToPropertyInfo(p: unknown) {\n return {\n name: (p as any)?.getName?.() || 'unknown',\n type: (p as any)?.getType?.()?.getText?.() || 'unknown',\n ...this.getSymbolDocs(p as any),\n };\n }\n\n private mapToInterfaceInfo(itf: unknown): InterfaceInfo {\n return {\n name: (itf as any)?.getName?.() || 'unknown',\n ...this.getSymbolDocs(itf as any),\n properties:\n ((itf as any).getProperties?.() || []).map((p: any) =>\n this.mapToPropertyInfo(p)\n ) || [],\n methods:\n ((itf as any)?.getMethods?.() || []).map((m: any) =>\n this.mapToFunctionInfo(m)\n ) || [],\n };\n }\n\n private mapToTypeAliasInfo(ta: unknown): TypeAliasInfo {\n return {\n name: (ta as any)?.getName?.() || 'unknown',\n type: (ta as any)?.getType?.()?.getText?.() || 'unknown',\n ...this.getSymbolDocs(ta as Node),\n };\n }\n\n private mapToEnumInfo(enm: unknown): EnumInfo {\n return {\n name: (enm as any)?.getName?.() || 'unknown',\n ...this.getSymbolDocs(enm as Node),\n members:\n ((enm as any)?.getMembers?.() || []).map((m: any) => m.getName()) || [],\n };\n }\n\n private deduplicateLocations<\n T extends { file: string; line: number; column: number },\n >(locations: T[]): T[] {\n const seen = new Set<string>();\n return locations.filter((loc) => {\n const key = `${loc.file}:${loc.line}:${loc.column}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n }\n}\n\nexport const typescriptAdapter = new TypeScriptAdapter();\n","import { Project } from 'ts-morph';\nimport path from 'path';\nimport fs from 'fs';\nimport { glob } from 'glob';\nimport { validateWorkspacePath } from './security.js';\n\n/**\n * ProjectManager handles tsconfig discovery and Project lifecycle.\n * One Project per tsconfig.json to handle monorepo project boundaries correctly.\n */\nexport class ProjectManager {\n private projects: Map<string, Project> = new Map();\n private tsconfigCache: Map<string, string[]> = new Map();\n private accessOrder: string[] = []; // MRU at front\n private maxProjects: number = 4;\n\n /**\n * Find all tsconfig.json files in a directory (recursive)\n */\n public async findTsConfigs(rootDir: string): Promise<string[]> {\n const safeRoot = validateWorkspacePath(rootDir);\n if (this.tsconfigCache.has(safeRoot)) {\n return this.tsconfigCache.get(safeRoot)!;\n }\n\n const configs = await glob('**/tsconfig.json', {\n cwd: safeRoot,\n absolute: true,\n ignore: ['**/node_modules/**', '**/dist/**'],\n });\n\n this.tsconfigCache.set(safeRoot, configs);\n return configs;\n }\n\n /**\n * Ensure a Project exists for a given tsconfig path, managing LRU cache\n */\n public ensureProject(tsconfigPath: string): Project {\n this.checkMemoryPressure();\n\n // Cache hit\n if (this.projects.has(tsconfigPath)) {\n this.moveToFront(tsconfigPath);\n return this.projects.get(tsconfigPath)!;\n }\n\n // Evict if full\n while (this.projects.size >= this.maxProjects) {\n const oldest = this.accessOrder.pop()!;\n this.disposeProject(oldest);\n }\n\n // Create with lazy file loading\n const project = new Project({\n tsConfigFilePath: tsconfigPath,\n skipAddingFilesFromTsConfig: true, // KEY: don't load all files\n });\n\n this.projects.set(tsconfigPath, project);\n this.accessOrder.unshift(tsconfigPath);\n return project;\n }\n\n /**\n * Move a tsconfig path to the front of the access order (MRU)\n */\n private moveToFront(tsconfigPath: string) {\n const index = this.accessOrder.indexOf(tsconfigPath);\n if (index > -1) {\n this.accessOrder.splice(index, 1);\n this.accessOrder.unshift(tsconfigPath);\n }\n }\n\n private checkMemoryPressure(): void {\n const heapUsed = process.memoryUsage().heapUsed / 1024 / 1024;\n const maxHeap = parseInt(process.env.AST_MAX_HEAP_MB || '1536', 10);\n\n while (heapUsed > maxHeap && this.projects.size > 1) {\n const oldest = this.accessOrder.pop()!;\n this.disposeProject(oldest);\n }\n }\n\n public disposeProject(tsconfigPath: string): void {\n const project = this.projects.get(tsconfigPath);\n if (project) {\n // Forget files explicitly\n for (const sourceFile of project.getSourceFiles()) {\n project.removeSourceFile(sourceFile);\n }\n this.projects.delete(tsconfigPath);\n }\n }\n\n /**\n * Find the nearest tsconfig.json for a file\n */\n public async findNearestTsConfig(\n filePath: string\n ): Promise<string | undefined> {\n const safePath = validateWorkspacePath(filePath);\n let currentDir = path.dirname(safePath);\n const root = path.parse(currentDir).root;\n\n while (currentDir !== root) {\n const tsconfigPath = path.join(currentDir, 'tsconfig.json');\n if (fs.existsSync(tsconfigPath)) {\n return tsconfigPath;\n }\n currentDir = path.dirname(currentDir);\n }\n\n return undefined;\n }\n\n /**\n * Get all tsconfigs for a path\n */\n public async getProjectsForPath(rootDir: string): Promise<string[]> {\n return this.findTsConfigs(rootDir);\n }\n\n /**\n * Dispose all projects to free memory\n */\n public disposeAll(): void {\n for (const [key] of this.projects) {\n this.disposeProject(key);\n }\n this.accessOrder = [];\n }\n}\n\nexport const projectManager = new ProjectManager();\n","import { projectManager } from '../project-manager.js';\nimport { IndexingStats, SymbolKind } from '../types.js';\nimport { validateWorkspacePath } from '../security.js';\nimport fs from 'fs';\nimport crypto from 'crypto';\nimport path from 'path';\nimport { Node } from 'ts-morph';\n\nexport interface SymbolEntry {\n name: string;\n kind: SymbolKind;\n file: string;\n line: number;\n column: number;\n exported: boolean;\n}\n\nexport interface DiskCache {\n version: 1;\n rootDir: string;\n builtAt: string;\n fileHashes: Record<string, number>; // file -> mtimeMs\n symbols: Record<string, SymbolEntry[]>;\n}\n\nexport class SymbolIndex {\n private index: Record<string, SymbolEntry[]> = {};\n\n private getCachePath(rootDir: string): string {\n const hash = crypto\n .createHash('sha256')\n .update(rootDir)\n .digest('hex')\n .slice(0, 12);\n return path.join(\n process.platform === 'win32' ? process.env.TEMP || 'c:/temp' : '/tmp',\n `ast-index-${hash}.json`\n );\n }\n\n private isCacheValid(cached: DiskCache, rootDir: string): boolean {\n if (cached.rootDir !== rootDir) return false;\n\n for (const [file, cachedMtime] of Object.entries(cached.fileHashes)) {\n if (!fs.existsSync(file)) return false;\n if (fs.statSync(file).mtimeMs !== cachedMtime) return false;\n }\n\n return true;\n }\n\n private computeStats(\n cache: DiskCache,\n duration_ms?: number,\n memory_mb?: number\n ): IndexingStats {\n const files = Object.keys(cache.fileHashes).length;\n let functions = 0;\n let classes = 0;\n let interfaces = 0;\n let types = 0;\n\n for (const entries of Object.values(cache.symbols)) {\n for (const entry of entries) {\n if (entry.kind === 'function' || entry.kind === 'method') functions++;\n if (entry.kind === 'class') classes++;\n if (entry.kind === 'interface') interfaces++;\n if (entry.kind === 'type_alias') types++;\n }\n }\n\n return {\n indexed: {\n files,\n functions,\n classes,\n interfaces,\n types,\n },\n duration_ms: duration_ms || 0,\n memory_mb: memory_mb || 0,\n };\n }\n\n private mapKind(node: Node): SymbolKind {\n if (Node.isClassDeclaration(node)) return 'class';\n if (Node.isFunctionDeclaration(node)) return 'function';\n if (Node.isInterfaceDeclaration(node)) return 'interface';\n if (Node.isTypeAliasDeclaration(node)) return 'type_alias';\n if (Node.isEnumDeclaration(node)) return 'enum';\n if (Node.isVariableDeclaration(node)) return 'variable';\n if (Node.isMethodDeclaration(node)) return 'method';\n if (Node.isPropertyDeclaration(node)) return 'property';\n if (Node.isParameterDeclaration(node)) return 'parameter';\n return 'variable';\n }\n\n /**\n * Build/Warm the index for a given path\n */\n public async buildIndex(rootDir: string): Promise<IndexingStats> {\n const startTime = Date.now();\n const safeRoot = validateWorkspacePath(rootDir);\n const cachePath = this.getCachePath(safeRoot);\n\n if (fs.existsSync(cachePath) && process.env.AST_DISABLE_CACHE !== 'true') {\n try {\n const cached: DiskCache = JSON.parse(\n fs.readFileSync(cachePath, 'utf-8')\n );\n if (this.isCacheValid(cached, safeRoot)) {\n this.index = cached.symbols;\n return this.computeStats(\n cached,\n Date.now() - startTime,\n process.memoryUsage().heapUsed / 1024 / 1024\n );\n }\n } catch {\n // Corrupt cache, ignore\n }\n }\n\n const tsconfigs = await projectManager.getProjectsForPath(safeRoot);\n const symbols: Record<string, SymbolEntry[]> = {};\n const fileHashes: Record<string, number> = {};\n\n for (const config of tsconfigs) {\n const project = projectManager.ensureProject(config);\n // We need to force load files for indexing\n project.addSourceFilesFromTsConfig(config);\n\n for (const sourceFile of project.getSourceFiles()) {\n const filePath = sourceFile.getFilePath();\n try {\n fileHashes[filePath] = fs.statSync(filePath).mtimeMs;\n } catch {\n continue;\n }\n\n // Extract exported declarations\n for (const [name, decls] of sourceFile.getExportedDeclarations()) {\n for (const decl of decls) {\n const entry: SymbolEntry = {\n name,\n kind: this.mapKind(decl as Node),\n file: filePath,\n line: decl.getStartLineNumber(),\n column: decl.getStart() - decl.getStartLinePos(),\n exported: true,\n };\n (symbols[name] ||= []).push(entry);\n }\n }\n\n // Extract non-exported top-level declarations\n for (const fn of sourceFile.getFunctions()) {\n const name = fn.getName();\n if (\n name &&\n !symbols[name]?.some(\n (s) => s.file === filePath && s.line === fn.getStartLineNumber()\n )\n ) {\n const entry: SymbolEntry = {\n name,\n kind: 'function',\n file: filePath,\n line: fn.getStartLineNumber(),\n column: fn.getStart() - fn.getStartLinePos(),\n exported: false,\n };\n (symbols[name] ||= []).push(entry);\n }\n }\n for (const cls of sourceFile.getClasses()) {\n const name = cls.getName();\n if (\n name &&\n !symbols[name]?.some(\n (s) => s.file === filePath && s.line === cls.getStartLineNumber()\n )\n ) {\n const entry: SymbolEntry = {\n name,\n kind: 'class',\n file: filePath,\n line: cls.getStartLineNumber(),\n column: cls.getStart() - cls.getStartLinePos(),\n exported: false,\n };\n (symbols[name] ||= []).push(entry);\n }\n }\n }\n }\n\n const cache: DiskCache = {\n version: 1,\n rootDir: safeRoot,\n builtAt: new Date().toISOString(),\n fileHashes,\n symbols,\n };\n\n fs.mkdirSync(path.dirname(cachePath), { recursive: true });\n fs.writeFileSync(cachePath, JSON.stringify(cache));\n\n this.index = symbols;\n\n const duration = Date.now() - startTime;\n const memoryUsage = process.memoryUsage().heapUsed / 1024 / 1024;\n\n return this.computeStats(cache, duration, Math.round(memoryUsage));\n }\n\n public isInitialized(): boolean {\n return Object.keys(this.index).length > 0;\n }\n\n public lookup(name: string): SymbolEntry[] {\n return this.index[name] || [];\n }\n\n public lookupByFile(file: string): SymbolEntry[] {\n return Object.values(this.index)\n .flat()\n .filter((e) => e.file === file);\n }\n}\n\nexport const symbolIndex = new SymbolIndex();\n","import { Worker } from 'worker_threads';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\n\ninterface WorkerTask<T> {\n id: string;\n type: string;\n payload: unknown;\n resolve: (value: T) => void;\n reject: (error: Error) => void;\n}\n\nexport class WorkerPool {\n private workers: Worker[] = [];\n private available: Worker[] = [];\n private queue: WorkerTask<unknown>[] = [];\n private activeJobs = new Map<string, WorkerTask<unknown>>();\n private taskId = 0;\n\n constructor(private poolSize: number) {}\n\n async init(): Promise<void> {\n const __dirname = path.dirname(fileURLToPath(import.meta.url));\n const workerPath = path.join(__dirname, 'ast-worker.js'); // Assuming tsup builds this\n\n for (let i = 0; i < this.poolSize; i++) {\n const worker = new Worker(workerPath);\n worker.on('message', (msg) => this.handleResult(worker, msg));\n worker.on('error', (_err) => this.handleWorkerError(worker, _err));\n this.workers.push(worker);\n this.available.push(worker);\n }\n }\n\n async execute<T>(type: string, payload: unknown): Promise<T> {\n return new Promise((resolve, reject) => {\n const id = String(++this.taskId);\n const task: WorkerTask<T> = { id, type, payload, resolve, reject };\n\n const worker = this.available.pop();\n if (worker) {\n this.dispatch(worker, task);\n } else {\n this.queue.push(task as WorkerTask<unknown>);\n }\n });\n }\n\n private dispatch<T>(worker: Worker, task: WorkerTask<T>): void {\n this.activeJobs.set(task.id, task as WorkerTask<unknown>);\n worker.postMessage({ id: task.id, type: task.type, payload: task.payload });\n }\n\n private handleResult(\n worker: Worker,\n msg: {\n id: string;\n result?: unknown;\n error?: string;\n }\n ): void {\n const task = this.activeJobs.get(msg.id);\n if (!task) return;\n\n this.activeJobs.delete(msg.id);\n\n if (msg.error) {\n task.reject(new Error(msg.error));\n } else {\n task.resolve(msg.result);\n }\n\n // Return worker to pool or dispatch next task\n const nextTask = this.queue.shift();\n if (nextTask) {\n this.dispatch(worker, nextTask);\n } else {\n this.available.push(worker);\n }\n }\n\n private handleWorkerError(worker: Worker, err: unknown): void {\n const idx = this.workers.indexOf(worker);\n if (idx !== -1) {\n worker.terminate();\n const __dirname = path.dirname(fileURLToPath(import.meta.url));\n const workerPath = path.join(__dirname, 'ast-worker.js');\n const newWorker = new Worker(workerPath);\n newWorker.on('message', (msg) => this.handleResult(newWorker, msg));\n newWorker.on('error', (_e) => this.handleWorkerError(newWorker, _e));\n this.workers[idx] = newWorker;\n this.available.push(newWorker);\n }\n }\n\n async terminate(): Promise<void> {\n await Promise.all(this.workers.map((w) => w.terminate()));\n this.workers = [];\n this.available = [];\n }\n}\n","import { typescriptAdapter } from '../adapters/typescript-adapter.js';\n\n/**\n * Generic wrapper for symbol-related adapter calls to reduce boilerplate.\n */\nexport async function wrapAdapterCall<T>(\n methodName: keyof typeof typescriptAdapter,\n symbol: string,\n path: string,\n ...args: any[]\n): Promise<T> {\n const method = typescriptAdapter[methodName] as (\n ...args: any[]\n ) => Promise<T>;\n return await method.apply(typescriptAdapter, [symbol, path, ...args]);\n}\n","import { wrapAdapterCall } from '../utils/tool-utils.js';\nimport { DefinitionLocation } from '../types.js';\n\n/**\n * Resolve the definition of a symbol.\n */\nexport async function resolveDefinition(\n symbol: string,\n path: string\n): Promise<DefinitionLocation[]> {\n return await wrapAdapterCall<DefinitionLocation[]>(\n 'resolveDefinition',\n symbol,\n path\n );\n}\n","import { wrapAdapterCall } from '../utils/tool-utils.js';\n\n/**\n * Find all references to a specific symbol in the project.\n */\nexport async function findReferences(\n symbol: string,\n path: string,\n limit: number = 50,\n offset: number = 0\n) {\n return await wrapAdapterCall('findReferences', symbol, path, limit, offset);\n}\n","import { wrapAdapterCall } from '../utils/tool-utils.js';\n\n/**\n * Find all implementations of a specific interface or class.\n */\nexport async function findImplementations(\n symbol: string,\n path: string,\n limit: number = 50,\n offset: number = 0\n) {\n return await wrapAdapterCall(\n 'findImplementations',\n symbol,\n path,\n limit,\n offset\n );\n}\n","import { typescriptAdapter } from '../adapters/typescript-adapter.js';\n\nexport async function getFileStructure(file: string) {\n return await typescriptAdapter.getFileStructure(file);\n}\n","import { typescriptAdapter } from '../adapters/typescript-adapter.js';\nimport { projectManager } from '../project-manager.js';\nimport { SyntaxKind, Node } from 'ts-morph';\nimport { validateWorkspacePath } from '../security.js';\n\nexport async function getSymbolDocs(\n symbol: string,\n filePath: string\n): Promise<any> {\n const safePath = validateWorkspacePath(filePath);\n const tsconfig = await projectManager.findNearestTsConfig(safePath);\n if (!tsconfig) return undefined;\n\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(safePath);\n\n if (sourceFile) {\n const node = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .find((id: Node) => id.getText() === symbol);\n\n if (node) {\n const decls = node.getSymbol()?.getDeclarations();\n if (decls && decls.length > 0) {\n const docs = typescriptAdapter.getSymbolDocs(decls[0]);\n if (docs) {\n return {\n symbol,\n file: sourceFile.getFilePath(),\n line: sourceFile.getLineAndColumnAtPos(decls[0].getStart()).line,\n ...docs,\n };\n }\n }\n }\n }\n\n return undefined;\n}\n","import { symbolIndex } from '../index/symbol-index.js';\n\nexport async function buildSymbolIndex(path: string) {\n return await symbolIndex.buildIndex(path);\n}\n","import { projectManager } from '../project-manager.js';\nimport { validateWorkspacePath } from '../security.js';\nimport { Node, SyntaxKind } from 'ts-morph';\n\nexport async function getCallHierarchy(\n symbolName: string,\n rootDir: string,\n direction: 'incoming' | 'outgoing' | 'both' = 'both'\n) {\n const safeRoot = validateWorkspacePath(rootDir);\n const configs = await projectManager.getProjectsForPath(safeRoot);\n\n const results: {\n symbol: string;\n incoming: Array<{ name: string; file: string; line: number }>;\n outgoing: Array<{ name: string; file: string; line: number }>;\n } = {\n symbol: symbolName,\n incoming: [],\n outgoing: [],\n };\n\n for (const config of configs) {\n const project = projectManager.ensureProject(config);\n project.addSourceFilesFromTsConfig(config);\n\n // Find the symbol definition\n const sourceFiles = project.getSourceFiles();\n let targetNode: Node | undefined;\n\n for (const file of sourceFiles) {\n const decls = file.getExportedDeclarations().get(symbolName) || [];\n if (decls.length > 0) {\n targetNode = decls[0] as Node;\n break;\n }\n\n // Also look for non-exported ones\n const fn = file.getFunction(symbolName);\n if (fn) {\n targetNode = fn;\n break;\n }\n\n const cls = file.getClass(symbolName);\n if (cls) {\n targetNode = cls;\n break;\n }\n }\n\n if (!targetNode) continue;\n\n // Incoming calls (references)\n if (direction === 'incoming' || direction === 'both') {\n const referencedSymbols = (targetNode as any).findReferences?.() || [];\n for (const referencedSymbol of referencedSymbols) {\n for (const reference of referencedSymbol.getReferences()) {\n const sourceFile = reference.getSourceFile();\n const fileName = sourceFile.getFilePath();\n const line = reference.getNode().getStartLineNumber();\n\n const caller =\n reference\n .getNode()\n .getFirstAncestorByKind(SyntaxKind.FunctionDeclaration) ||\n reference\n .getNode()\n .getFirstAncestorByKind(SyntaxKind.MethodDeclaration) ||\n reference\n .getNode()\n .getFirstAncestorByKind(SyntaxKind.ClassDeclaration);\n\n results.incoming.push({\n name: (caller as any)?.getName?.() || 'anonymous',\n file: fileName,\n line: line,\n });\n }\n }\n }\n\n // Outgoing calls\n if (direction === 'outgoing' || direction === 'both') {\n const calls = targetNode.getDescendantsOfKind(SyntaxKind.CallExpression);\n for (const call of calls) {\n const expression = call.getExpression();\n const symbol = (call as any).getReturnType?.()\n ? (call as any).getExpression().getSymbol()\n : undefined;\n\n results.outgoing.push({\n name: symbol?.getName() || expression.getText(),\n file: call.getSourceFile().getFilePath(),\n line: call.getStartLineNumber(),\n });\n }\n }\n }\n\n // Deduplicate results safely\n const uniqueIncoming = new Map<string, any>();\n for (const item of results.incoming) {\n uniqueIncoming.set(`${item.file}:${item.line}`, item);\n }\n results.incoming = Array.from(uniqueIncoming.values());\n\n const uniqueOutgoing = new Map<string, any>();\n for (const item of results.outgoing) {\n uniqueOutgoing.set(`${item.file}:${item.line}:${item.name}`, item);\n }\n results.outgoing = Array.from(uniqueOutgoing.values());\n\n return results;\n}\n","import { typescriptAdapter } from '../adapters/typescript-adapter.js';\nimport { projectManager } from '../project-manager.js';\nimport { SyntaxKind, Node } from 'ts-morph';\nimport { validateWorkspacePath } from '../security.js';\n\nexport interface GroundingScore {\n score: number;\n grade: string;\n breakdown: {\n documentation: number;\n typeClarity: number;\n depthImpact: number;\n };\n recommendations: string[];\n}\n\nexport async function checkSymbolGrounding(\n symbol: string,\n filePath: string\n): Promise<GroundingScore | undefined> {\n const safePath = validateWorkspacePath(filePath);\n const tsconfig = await projectManager.findNearestTsConfig(safePath);\n if (!tsconfig) return undefined;\n\n const project = projectManager.ensureProject(tsconfig);\n const sourceFile = project.addSourceFileAtPathIfExists(safePath);\n\n if (!sourceFile) return undefined;\n\n const node = sourceFile\n .getDescendantsOfKind(SyntaxKind.Identifier)\n .find((id: Node) => id.getText() === symbol);\n\n if (!node) return undefined;\n\n const decl = node.getSymbol()?.getDeclarations()?.[0];\n if (!decl) return undefined;\n\n let docScore = 0;\n let typeScore = 0;\n let depthScore = 30;\n const recommendations: string[] = [];\n\n // 1. Documentation Analysis\n const docs = typescriptAdapter.getSymbolDocs(decl as Node);\n if (docs) {\n docScore += 10;\n if (docs.documentation && docs.documentation.length > 20) docScore += 10;\n\n const hasParams = docs.tags.some((t) => t.name === 'param');\n const hasReturns = docs.tags.some(\n (t) => t.name === 'returns' || t.name === 'return'\n );\n\n if (hasParams) docScore += 10;\n else\n recommendations.push(\n 'Add @param tags to document implementation details for the agent.'\n );\n\n if (hasReturns) docScore += 10;\n else\n recommendations.push('Add @returns tag to clarify output expectations.');\n } else {\n recommendations.push(\n 'Missing JSDoc. Agents need explicit documentation to understand intent without reading the source.'\n );\n }\n\n // 2. Type Clarity Analysis\n const typeText = (decl as any).getType?.()?.getText?.() || '';\n if (typeText) {\n if (!typeText.includes('any')) typeScore += 15;\n else\n recommendations.push(\n 'Avoid \"any\" types. They break agentic reasoning and cause hallucinations.'\n );\n\n if (!typeText.includes('unknown')) typeScore += 15;\n else\n recommendations.push(\n 'Use specific interfaces instead of \"unknown\" to minimize agent probe requirements.'\n );\n }\n\n // 3. Depth Impact (Simulated for now based on imports in file)\n const importCount = sourceFile.getImportDeclarations().length;\n if (importCount > 10) {\n const penalty = Math.min(20, (importCount - 10) * 2);\n depthScore -= penalty;\n recommendations.push(\n `High dependency depth (${importCount} imports). Agents must load more files to understand this symbol's context.`\n );\n }\n\n const totalScore = docScore + typeScore + depthScore;\n let grade = 'F';\n if (totalScore >= 90) grade = 'S (Agent-Native)';\n else if (totalScore >= 80) grade = 'A (Highly Grounded)';\n else if (totalScore >= 70) grade = 'B (Good)';\n else if (totalScore >= 60) grade = 'C (Acceptable)';\n else if (totalScore >= 40) grade = 'D (Poor)';\n\n return {\n score: totalScore,\n grade,\n breakdown: {\n documentation: docScore,\n typeClarity: typeScore,\n depthImpact: depthScore,\n },\n recommendations,\n };\n}\n"],"mappings":";;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACLP,SAAS,SAAS;AAKX,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,QAAQ,EACL,OAAO,EACP;AAAA,IACC;AAAA,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A,cAC1C,eAAe,OAAO,UAAU,iBAAiB,CAAC;AAAA,cAClD,UAAU,UAAU,IAAI,CAAC,OAAY;AAAA,gBACnC,UAAU,EAAE,kBAAkB,EAAE,cAAc;AAAA,gBAC9C,QAAQ,EAAE;AAAA,gBACV,UACE,EAAE,aAAa,aACX,OACA,EAAE,aAAa,UACb,OACA;AAAA,gBACR,gBAAgB,EAAE,kBAAkB,EAAE,cAAc;AAAA,cACtD,EAAE;AAAA,YACJ;AAEA,mBAAO;AAAA,cACL,SAAS;AAAA,gBACP,EAAE,MAAM,QAAQ,MAAM,KAAK,UAAU,QAAQ,MAAM,CAAC,EAAE;AAAA,cACxD;AAAA,cACA;AAAA,YACF;AAAA,UACF;AAAA,UACA;AACE,kBAAM,IAAI,MAAM,iBAAiB,IAAI,EAAE;AAAA,QAC3C;AAAA,MACF,SAAS,OAAY;AACnB,eAAO;AAAA,UACL,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,UAAU,MAAM,OAAO,GAAG,CAAC;AAAA,UAC3D,SAAS;AAAA,QACX;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,MAAM,MAAM;AACV,UAAM,YAAY,IAAI,qBAAqB;AAC3C,UAAM,KAAK,OAAO,QAAQ,SAAS;AACnC,YAAQ,MAAM,iCAAiC;AAAA,EACjD;AACF;AAGA,IAAM,SAAS,IAAI,kBAAkB;AACrC,OAAO,IAAI,EAAE,MAAM,CAAC,UAAU;AAC5B,UAAQ,MAAM,iDAAiD,KAAK;AACpE,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Node","fs","path","fs","path","path","__dirname","path","fs","tsconfig","Node","path","path","path","path","path","SyntaxKind","SyntaxKind","SyntaxKind","path"]}