index.ts 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. /**
  2. * Context Builder
  3. *
  4. * Builds rich context for tasks by combining FTS search with graph traversal.
  5. * Outputs structured context ready to inject into Claude.
  6. */
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import {
  10. Node,
  11. Edge,
  12. NodeKind,
  13. EdgeKind,
  14. Subgraph,
  15. CodeBlock,
  16. TaskContext,
  17. TaskInput,
  18. BuildContextOptions,
  19. FindRelevantContextOptions,
  20. SearchResult,
  21. } from '../types';
  22. import { QueryBuilder } from '../db/queries';
  23. import { GraphTraverser } from '../graph';
  24. import { formatContextAsMarkdown, formatContextAsJson } from './formatter';
  25. import { logDebug } from '../errors';
  26. import { validatePathWithinRoot } from '../utils';
  27. import { isTestFile, extractSearchTerms, scorePathRelevance, getStemVariants } from '../search/query-utils';
  28. /**
  29. * Extract likely symbol names from a natural language query
  30. *
  31. * Identifies potential code symbols using patterns:
  32. * - CamelCase: UserService, signInWithGoogle
  33. * - snake_case: user_service, sign_in
  34. * - SCREAMING_SNAKE: MAX_RETRIES
  35. * - dot.notation: app.isPackaged (extracts both sides)
  36. * - Single words that look like identifiers (no spaces, not common English words)
  37. *
  38. * @param query - Natural language query
  39. * @returns Array of potential symbol names
  40. */
  41. function extractSymbolsFromQuery(query: string): string[] {
  42. const symbols = new Set<string>();
  43. // Extract CamelCase identifiers (2+ chars, starts with letter)
  44. const camelCasePattern = /\b([A-Z][a-z]+(?:[A-Z][a-z]*)*|[a-z]+(?:[A-Z][a-z]*)+)\b/g;
  45. let match;
  46. while ((match = camelCasePattern.exec(query)) !== null) {
  47. if (match[1] && match[1].length >= 2) {
  48. symbols.add(match[1]);
  49. }
  50. }
  51. // Extract snake_case identifiers
  52. const snakeCasePattern = /\b([a-z][a-z0-9]*(?:_[a-z0-9]+)+)\b/gi;
  53. while ((match = snakeCasePattern.exec(query)) !== null) {
  54. if (match[1] && match[1].length >= 3) {
  55. symbols.add(match[1]);
  56. }
  57. }
  58. // Extract SCREAMING_SNAKE_CASE
  59. const screamingPattern = /\b([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)\b/g;
  60. while ((match = screamingPattern.exec(query)) !== null) {
  61. if (match[1]) {
  62. symbols.add(match[1]);
  63. }
  64. }
  65. // Extract ALL_CAPS acronyms (2+ chars, e.g., REST, HTTP, LRU, API)
  66. const acronymPattern = /\b([A-Z]{2,})\b/g;
  67. while ((match = acronymPattern.exec(query)) !== null) {
  68. if (match[1]) {
  69. symbols.add(match[1]);
  70. }
  71. }
  72. // Extract dot.notation and split into parts (e.g., "app.isPackaged" -> ["app", "isPackaged"])
  73. const dotPattern = /\b([a-zA-Z][a-zA-Z0-9]*(?:\.[a-zA-Z][a-zA-Z0-9]*)+)\b/g;
  74. while ((match = dotPattern.exec(query)) !== null) {
  75. if (match[1]) {
  76. // Add both the full path and individual parts
  77. symbols.add(match[1]);
  78. const parts = match[1].split('.');
  79. for (const part of parts) {
  80. if (part.length >= 2) {
  81. symbols.add(part);
  82. }
  83. }
  84. }
  85. }
  86. // Extract plain lowercase identifiers (3+ chars, not already matched)
  87. // Catches symbol names like "undo", "redo", "history", "render", "parse"
  88. const lowercasePattern = /\b([a-z][a-z0-9]{2,})\b/g;
  89. while ((match = lowercasePattern.exec(query)) !== null) {
  90. if (match[1]) {
  91. symbols.add(match[1]);
  92. }
  93. }
  94. // Filter out common English words that aren't likely symbol names
  95. const commonWords = new Set([
  96. 'the', 'and', 'for', 'with', 'from', 'this', 'that', 'have', 'been',
  97. 'will', 'would', 'could', 'should', 'does', 'done', 'make', 'made',
  98. 'use', 'used', 'using', 'work', 'works', 'find', 'found', 'show',
  99. 'call', 'called', 'calling', 'get', 'set', 'add', 'all', 'any',
  100. 'how', 'what', 'when', 'where', 'which', 'who', 'why',
  101. 'not', 'but', 'are', 'was', 'were', 'has', 'had', 'its',
  102. 'can', 'did', 'may', 'also', 'into', 'than', 'then', 'them',
  103. 'each', 'other', 'some', 'such', 'only', 'same', 'about',
  104. 'after', 'before', 'between', 'through', 'during', 'without',
  105. 'again', 'further', 'once', 'here', 'there', 'both', 'just',
  106. 'more', 'most', 'very', 'being', 'having', 'doing',
  107. 'system', 'need', 'needs', 'want', 'wants', 'like', 'look',
  108. 'change', 'changes', 'changed', 'changing',
  109. // Common English nouns/verbs that match thousands of unrelated code symbols
  110. 'layer', 'handle', 'handles', 'handling', 'incoming', 'outgoing',
  111. 'data', 'flow', 'flows', 'level', 'levels', 'request', 'requests',
  112. 'response', 'responses', 'implement', 'implements', 'implementation',
  113. 'interface', 'interfaces', 'class', 'classes', 'method', 'methods',
  114. 'trigger', 'triggers', 'affected', 'affect', 'affects',
  115. 'else', 'code', 'failing', 'failed', 'silently', 'decide', 'decides',
  116. 'return', 'returns', 'returned', 'take', 'takes', 'taken',
  117. 'check', 'checks', 'checked', 'create', 'creates', 'created',
  118. 'read', 'reads', 'write', 'writes', 'written',
  119. 'start', 'starts', 'stop', 'stops', 'run', 'runs', 'running',
  120. ]);
  121. return Array.from(symbols).filter(s => !commonWords.has(s.toLowerCase()));
  122. }
  123. /**
  124. * Default options for context building
  125. *
  126. * Tuned for minimal context usage while still providing useful results:
  127. * - Fewer nodes and code blocks by default
  128. * - Smaller code block size limit
  129. * - Shallower traversal
  130. */
  131. const DEFAULT_BUILD_OPTIONS: Required<BuildContextOptions> = {
  132. maxNodes: 20, // Reduced from 50 - most tasks don't need 50 symbols
  133. maxCodeBlocks: 5, // Reduced from 10 - only show most relevant code
  134. maxCodeBlockSize: 1500, // Reduced from 2000
  135. includeCode: true,
  136. format: 'markdown',
  137. searchLimit: 3, // Reduced from 5 - fewer entry points
  138. traversalDepth: 1, // Reduced from 2 - shallower graph expansion
  139. minScore: 0.3,
  140. };
  141. /**
  142. * Node kinds that provide high information value in context results.
  143. * Imports/exports are excluded because they have near-zero information density -
  144. * they tell you something exists, not how it works.
  145. */
  146. const HIGH_VALUE_NODE_KINDS: NodeKind[] = [
  147. 'function', 'method', 'class', 'interface', 'type_alias', 'struct', 'trait',
  148. 'component', 'route', 'variable', 'constant', 'enum', 'module', 'namespace',
  149. ];
  150. /**
  151. * Default options for finding relevant context
  152. */
  153. const DEFAULT_FIND_OPTIONS: Required<FindRelevantContextOptions> = {
  154. searchLimit: 3, // Reduced from 5
  155. traversalDepth: 1, // Reduced from 2
  156. maxNodes: 20, // Reduced from 50
  157. minScore: 0.3,
  158. edgeKinds: [],
  159. nodeKinds: HIGH_VALUE_NODE_KINDS, // Filter out imports/exports by default
  160. };
  161. /**
  162. * Context Builder
  163. *
  164. * Coordinates semantic search and graph traversal to build
  165. * comprehensive context for tasks.
  166. */
  167. export class ContextBuilder {
  168. private projectRoot: string;
  169. private queries: QueryBuilder;
  170. private traverser: GraphTraverser;
  171. constructor(
  172. projectRoot: string,
  173. queries: QueryBuilder,
  174. traverser: GraphTraverser
  175. ) {
  176. this.projectRoot = projectRoot;
  177. this.queries = queries;
  178. this.traverser = traverser;
  179. }
  180. /**
  181. * Build context for a task
  182. *
  183. * Pipeline:
  184. * 1. Parse task input (string or {title, description})
  185. * 2. Run semantic search to find entry points
  186. * 3. Expand graph around entry points
  187. * 4. Extract code blocks for key nodes
  188. * 5. Format output for Claude
  189. *
  190. * @param input - Task description or object with title/description
  191. * @param options - Build options
  192. * @returns TaskContext (structured) or formatted string
  193. */
  194. async buildContext(
  195. input: TaskInput,
  196. options: BuildContextOptions = {}
  197. ): Promise<TaskContext | string> {
  198. const opts = { ...DEFAULT_BUILD_OPTIONS, ...options };
  199. // Parse input
  200. const query = typeof input === 'string' ? input : `${input.title}${input.description ? `: ${input.description}` : ''}`;
  201. // Find relevant context (semantic search + graph expansion)
  202. const subgraph = await this.findRelevantContext(query, {
  203. searchLimit: opts.searchLimit,
  204. traversalDepth: opts.traversalDepth,
  205. maxNodes: opts.maxNodes,
  206. minScore: opts.minScore,
  207. });
  208. // Get entry points (nodes from semantic search)
  209. const entryPoints = this.getEntryPoints(subgraph);
  210. // Extract code blocks for key nodes
  211. const codeBlocks = opts.includeCode
  212. ? await this.extractCodeBlocks(subgraph, opts.maxCodeBlocks, opts.maxCodeBlockSize)
  213. : [];
  214. // Get related files
  215. const relatedFiles = this.getRelatedFiles(subgraph);
  216. // Generate summary
  217. const summary = this.generateSummary(query, subgraph, entryPoints);
  218. // Calculate stats
  219. const stats = {
  220. nodeCount: subgraph.nodes.size,
  221. edgeCount: subgraph.edges.length,
  222. fileCount: relatedFiles.length,
  223. codeBlockCount: codeBlocks.length,
  224. totalCodeSize: codeBlocks.reduce((sum, block) => sum + block.content.length, 0),
  225. };
  226. const context: TaskContext = {
  227. query,
  228. subgraph,
  229. entryPoints,
  230. codeBlocks,
  231. relatedFiles,
  232. summary,
  233. stats,
  234. };
  235. // Return formatted output or raw context
  236. if (opts.format === 'markdown') {
  237. return formatContextAsMarkdown(context) + this.buildCallPathsSection(subgraph);
  238. } else if (opts.format === 'json') {
  239. return formatContextAsJson(context);
  240. }
  241. return context;
  242. }
  243. /**
  244. * Surface short call-paths among the symbols this context already found,
  245. * derived in-memory from the subgraph's `calls` edges (no extra queries).
  246. *
  247. * This bakes the value of path-finding INTO the always-loaded `context` tool.
  248. * Agents reliably read context's output but do NOT discover/adopt a standalone
  249. * trace tool (in deferred-MCP harnesses they only ToolSearch-select tools they
  250. * already know). Delivering the flow here means "how does X reach Y" is
  251. * answered without the agent needing to find, load, or choose a new tool.
  252. * Chains stop where the static call graph ends (e.g. dynamic dispatch) — that
  253. * truncation is honest, and the agent can codegraph_node the last hop to bridge.
  254. */
  255. private buildCallPathsSection(subgraph: Subgraph): string {
  256. const adj = new Map<string, string[]>();
  257. for (const e of subgraph.edges) {
  258. if (e.kind !== 'calls') continue;
  259. if (!subgraph.nodes.has(e.source) || !subgraph.nodes.has(e.target)) continue;
  260. const list = adj.get(e.source);
  261. if (list) list.push(e.target);
  262. else adj.set(e.source, [e.target]);
  263. }
  264. if (adj.size === 0) return '';
  265. const MAX_HOPS = 6;
  266. const chains: string[][] = [];
  267. let budget = 2000; // bound DFS work on dense subgraphs
  268. const dfs = (id: string, path: string[], seen: Set<string>): void => {
  269. if (budget-- <= 0) return;
  270. const next = (adj.get(id) ?? []).filter((t) => !seen.has(t));
  271. if (next.length === 0 || path.length >= MAX_HOPS) {
  272. if (path.length >= 3) chains.push([...path]); // >=3 nodes = a real flow, not a single call
  273. return;
  274. }
  275. for (const t of next) {
  276. seen.add(t);
  277. dfs(t, [...path, t], seen);
  278. seen.delete(t);
  279. }
  280. };
  281. const starts = (subgraph.roots.length > 0
  282. ? subgraph.roots.filter((id) => adj.has(id))
  283. : [...adj.keys()]
  284. ).slice(0, 5);
  285. for (const s of starts) dfs(s, [s], new Set([s]));
  286. if (chains.length === 0) return '';
  287. // Keep only chains that connect TWO OR MORE query-relevant symbols (roots).
  288. // A chain from a root into an arbitrary callee (render → onMagicFrameGenerate)
  289. // is structurally valid but tangential to the question; requiring ≥2 roots
  290. // keeps the chain anchored to what the user actually asked about. Rank by
  291. // #roots then length, and drop any that are a sub-path of a longer kept chain.
  292. const rootSet = new Set(subgraph.roots);
  293. const rootCount = (c: string[]): number => c.reduce((n, id) => n + (rootSet.has(id) ? 1 : 0), 0);
  294. const relevant = chains.filter((c) => rootCount(c) >= 2);
  295. relevant.sort((a, b) => rootCount(b) - rootCount(a) || b.length - a.length);
  296. const kept: string[][] = [];
  297. for (const c of relevant) {
  298. const key = c.join('>');
  299. if (kept.some((k) => k.join('>').includes(key))) continue;
  300. kept.push(c);
  301. if (kept.length >= 3) break;
  302. }
  303. if (kept.length === 0) return '';
  304. const name = (id: string): string => subgraph.nodes.get(id)?.name ?? id;
  305. // Synthesized (dynamic-dispatch) hops are real `calls` edges but invisible to
  306. // static parsing — mark them inline so the agent sees WHERE the callback was
  307. // wired up (`registered @file:line`) instead of grepping for it. Keyed by
  308. // "source>target".
  309. const synthByPair = new Map<string, string>();
  310. for (const e of subgraph.edges) {
  311. if (e.kind !== 'calls' || e.provenance !== 'heuristic') continue;
  312. const m = e.metadata as Record<string, unknown> | undefined;
  313. if (!m?.synthesizedBy) continue;
  314. const at = typeof m.registeredAt === 'string' ? ` @${m.registeredAt}` : '';
  315. const label = m.synthesizedBy === 'callback'
  316. ? `callback via ${m.via ? `\`${String(m.via)}\`` : 'registrar'}${at}`
  317. : m.synthesizedBy === 'react-render'
  318. ? `React re-render via setState${at}`
  319. : m.synthesizedBy === 'jsx-render'
  320. ? `renders <${String(m.via || 'child')}>`
  321. : m.synthesizedBy === 'vue-handler'
  322. ? `Vue @${String(m.event || 'event')} handler`
  323. : `event ${m.event ? `\`${String(m.event)}\`` : ''}${at}`;
  324. synthByPair.set(`${e.source}>${e.target}`, label);
  325. }
  326. const renderChain = (c: string[]): string => {
  327. let s = name(c[0]!);
  328. for (let i = 1; i < c.length; i++) {
  329. const synth = synthByPair.get(`${c[i - 1]}>${c[i]}`);
  330. s += synth ? ` →[${synth}] ${name(c[i]!)}` : ` → ${name(c[i]!)}`;
  331. }
  332. return s;
  333. };
  334. const hasSynth = kept.some((c) => c.some((_, i) => i > 0 && synthByPair.has(`${c[i - 1]}>${c[i]}`)));
  335. const lines = [
  336. '',
  337. '## Call paths',
  338. '',
  339. 'Execution flow among the key symbols (traced through the call graph):',
  340. '',
  341. ...kept.map((c) => `- ${renderChain(c)}`),
  342. '',
  343. hasSynth
  344. ? '_Hops marked `[callback/event …]` are dynamic dispatch bridged by codegraph (with the registration site); the rest are direct calls. codegraph_node any symbol for its body._'
  345. : '_codegraph_node any symbol above for its source + its own callers/callees._',
  346. ];
  347. return '\n' + lines.join('\n') + '\n';
  348. }
  349. /**
  350. * Find relevant subgraph for a query
  351. *
  352. * Uses hybrid search combining exact symbol lookup with semantic search:
  353. * 1. Extract potential symbol names from query
  354. * 2. Look up exact matches for those symbols (high confidence)
  355. * 3. Use semantic search for concept matching
  356. * 4. Merge results, prioritizing exact matches
  357. * 5. Traverse graph from entry points
  358. *
  359. * @param query - Natural language query
  360. * @param options - Search and traversal options
  361. * @returns Subgraph of relevant nodes and edges
  362. */
  363. async findRelevantContext(
  364. query: string,
  365. options: FindRelevantContextOptions = {}
  366. ): Promise<Subgraph> {
  367. const opts = { ...DEFAULT_FIND_OPTIONS, ...options };
  368. // Start with empty subgraph
  369. const nodes = new Map<string, Node>();
  370. const edges: Edge[] = [];
  371. const roots: string[] = [];
  372. // Handle empty query - return empty subgraph
  373. if (!query || query.trim().length === 0) {
  374. return { nodes, edges, roots };
  375. }
  376. // === HYBRID SEARCH ===
  377. // Step 1: Extract potential symbol names from query
  378. const symbolsFromQuery = extractSymbolsFromQuery(query);
  379. logDebug('Extracted symbols from query', { query, symbols: symbolsFromQuery });
  380. // Step 2: Look up exact matches for extracted symbols
  381. let exactMatches: SearchResult[] = [];
  382. if (symbolsFromQuery.length > 0) {
  383. try {
  384. // Get more results so we can apply co-location boosting before trimming
  385. exactMatches = this.queries.findNodesByExactName(symbolsFromQuery, {
  386. limit: Math.ceil(opts.searchLimit * 5),
  387. kinds: opts.nodeKinds && opts.nodeKinds.length > 0 ? opts.nodeKinds : undefined,
  388. });
  389. // Co-location boost: when multiple extracted symbols appear in the same file,
  390. // those results are much more likely to be what the user is looking for.
  391. // E.g., "scrapeLoop" + "run" both in scrape/scrape.go → boost both.
  392. if (exactMatches.length > 1) {
  393. // Build a map of files → how many distinct symbol names matched in that file
  394. const fileSymbolCounts = new Map<string, Set<string>>();
  395. for (const r of exactMatches) {
  396. const names = fileSymbolCounts.get(r.node.filePath) || new Set();
  397. names.add(r.node.name.toLowerCase());
  398. fileSymbolCounts.set(r.node.filePath, names);
  399. }
  400. // Boost results in files where multiple query symbols co-occur
  401. exactMatches = exactMatches.map(r => {
  402. const symbolCount = fileSymbolCounts.get(r.node.filePath)?.size || 1;
  403. return {
  404. ...r,
  405. score: symbolCount > 1 ? r.score + (symbolCount - 1) * 20 : r.score,
  406. };
  407. });
  408. exactMatches.sort((a, b) => b.score - a.score);
  409. }
  410. // Trim back to reasonable size
  411. exactMatches = exactMatches.slice(0, Math.ceil(opts.searchLimit * 2));
  412. logDebug('Exact symbol matches', { count: exactMatches.length });
  413. } catch (error) {
  414. logDebug('Exact symbol lookup failed', { error: String(error) });
  415. }
  416. }
  417. // Step 2b: Search for extracted symbols as definition (class/interface) prefixes.
  418. // When the user writes "REST", "bulk", or "allocation", they usually mean classes
  419. // like RestController, BulkRequest, AllocationService — not nodes named exactly that.
  420. // Also tries stem variants: "caching" → "cache" finds Cache, CacheBuilder.
  421. if (symbolsFromQuery.length > 0) {
  422. const definitionKinds: NodeKind[] = ['class', 'interface', 'struct', 'trait',
  423. 'protocol', 'enum', 'type_alias'];
  424. // Expand symbols with stem variants for broader definition matching
  425. const expandedSymbols = new Set(symbolsFromQuery);
  426. for (const sym of symbolsFromQuery) {
  427. for (const variant of getStemVariants(sym)) {
  428. expandedSymbols.add(variant);
  429. }
  430. }
  431. for (const sym of expandedSymbols) {
  432. // Title-case the symbol: "REST" → "Rest", "bulk" → "Bulk", "allocation" → "Allocation"
  433. const titleCased = sym.charAt(0).toUpperCase() + sym.slice(1).toLowerCase();
  434. if (titleCased === sym) continue; // already title-case (e.g., "Engine") — handled by exact match
  435. // Fetch more results since popular prefixes have many matches
  436. const prefixResults = this.queries.searchNodes(titleCased, {
  437. limit: 30,
  438. kinds: definitionKinds,
  439. });
  440. const matched: SearchResult[] = [];
  441. for (const r of prefixResults) {
  442. if (r.node.name.toLowerCase().startsWith(titleCased.toLowerCase())) {
  443. // Favor shorter names: "AllocationService" (18 chars) over
  444. // "AllocationBalancingRoundMetrics" (31 chars). Core classes tend
  445. // to have concise names; test/helper classes are verbose.
  446. const brevityBonus = Math.max(0, 10 - (r.node.name.length - titleCased.length) / 3);
  447. matched.push({ ...r, score: r.score + 15 + brevityBonus });
  448. }
  449. }
  450. matched.sort((a, b) => b.score - a.score);
  451. for (const r of matched.slice(0, Math.ceil(opts.searchLimit))) {
  452. const existing = exactMatches.find(e => e.node.id === r.node.id);
  453. if (!existing) {
  454. exactMatches.push(r);
  455. }
  456. }
  457. }
  458. exactMatches.sort((a, b) => b.score - a.score);
  459. exactMatches = exactMatches.slice(0, Math.ceil(opts.searchLimit * 3));
  460. }
  461. // Step 3: Run text search for natural language term matching
  462. // This catches file-name and node-name matches that semantic search may miss,
  463. // which is critical for template-heavy codebases (e.g., Liquid/Shopify themes)
  464. // where file names are the primary identifiers.
  465. let textResults: SearchResult[] = [];
  466. try {
  467. const searchTerms = extractSearchTerms(query);
  468. if (searchTerms.length > 0) {
  469. // Search each term individually to get broader coverage,
  470. // then boost results that match multiple terms
  471. const termResultsMap = new Map<string, { result: SearchResult; termHits: number }>();
  472. // When no explicit kind filter is set, exclude imports — they flood FTS
  473. // results with qualified name matches (e.g., "REST" matches 445K import paths)
  474. // but are almost never what exploration queries want.
  475. const searchKinds = opts.nodeKinds && opts.nodeKinds.length > 0
  476. ? opts.nodeKinds
  477. : ['file', 'module', 'class', 'struct', 'interface', 'trait', 'protocol',
  478. 'function', 'method', 'property', 'field', 'variable', 'constant',
  479. 'enum', 'enum_member', 'type_alias', 'namespace', 'export',
  480. 'route', 'component'] as NodeKind[];
  481. for (const term of searchTerms) {
  482. const termResults = this.queries.searchNodes(term, {
  483. limit: opts.searchLimit * 2,
  484. kinds: searchKinds,
  485. });
  486. for (const r of termResults) {
  487. const existing = termResultsMap.get(r.node.id);
  488. if (existing) {
  489. existing.termHits++;
  490. existing.result.score = Math.max(existing.result.score, r.score);
  491. } else {
  492. termResultsMap.set(r.node.id, { result: r, termHits: 1 });
  493. }
  494. }
  495. }
  496. // Boost results matching multiple terms and sort
  497. textResults = Array.from(termResultsMap.values())
  498. .map(({ result, termHits }) => ({
  499. ...result,
  500. score: result.score + (termHits - 1) * 5,
  501. }))
  502. .sort((a, b) => b.score - a.score)
  503. .slice(0, opts.searchLimit * 2);
  504. }
  505. logDebug('Text search results', { count: textResults.length });
  506. } catch (error) {
  507. logDebug('Text search failed', { query, error: String(error) });
  508. }
  509. // Step 4: Merge results, taking the max score when duplicates appear
  510. // across search channels. Exact matches may have lower scores than FTS
  511. // results for the same node — use the best score from any channel.
  512. const resultById = new Map<string, SearchResult>();
  513. let searchResults: SearchResult[] = [];
  514. // Add exact matches first
  515. for (const result of exactMatches) {
  516. const existing = resultById.get(result.node.id);
  517. if (existing) {
  518. existing.score = Math.max(existing.score, result.score);
  519. } else {
  520. resultById.set(result.node.id, result);
  521. searchResults.push(result);
  522. }
  523. }
  524. // Add text search results, upgrading scores for duplicates
  525. for (const result of textResults) {
  526. const existing = resultById.get(result.node.id);
  527. if (existing) {
  528. existing.score = Math.max(existing.score, result.score);
  529. } else {
  530. resultById.set(result.node.id, result);
  531. searchResults.push(result);
  532. }
  533. }
  534. const queryLower = query.toLowerCase();
  535. const isTestQuery = queryLower.includes('test') || queryLower.includes('spec');
  536. // Deprioritize test files early so they don't take multi-term boost slots
  537. if (!isTestQuery) {
  538. for (const result of searchResults) {
  539. if (isTestFile(result.node.filePath)) {
  540. result.score *= 0.3;
  541. }
  542. }
  543. }
  544. // Iter7 — Core-directory boost. On projects with one file that holds
  545. // the dense majority of internal call edges (e.g. sinatra's
  546. // `lib/sinatra/base.rb` at 85% of all in-file edges), the agent's
  547. // task usually asks about the framework's core. Without this boost,
  548. // ranking favors small focused extension files (e.g. text search
  549. // picks `sinatra-contrib/lib/sinatra/multi_route.rb`'s 10-line
  550. // `route` method over `base.rb`'s `route!` because the extension
  551. // file's `route` matches the query verbatim AND the file is small,
  552. // dwarfing the longer name `route!` in a 1500-line file). Boost
  553. // results that share a directory prefix with the dominant file's
  554. // directory so the core file's siblings outrank sibling-package
  555. // extensions.
  556. try {
  557. const dominant = this.queries.getDominantFile?.();
  558. if (dominant && dominant.edgeCount >= 3 * dominant.nextEdgeCount) {
  559. // Take the directory of the dominant file (everything up to the
  560. // last slash). For `lib/sinatra/base.rb` → `lib/sinatra/`.
  561. const slash = dominant.filePath.lastIndexOf('/');
  562. if (slash > 0) {
  563. const coreDir = dominant.filePath.slice(0, slash + 1);
  564. for (const result of searchResults) {
  565. if (result.node.filePath.startsWith(coreDir)) {
  566. result.score += 25;
  567. }
  568. }
  569. }
  570. }
  571. } catch {
  572. // SQL failure — fall through, scoring works without the boost
  573. }
  574. // Step 5a: Multi-term co-occurrence re-ranking (applied BEFORE truncation).
  575. // For multi-word queries like "search execution from request to shard",
  576. // nodes matching 2+ query terms in their name or path are far more relevant
  577. // than nodes matching just one generic term. Without this, "ExecutionUtils"
  578. // (matches only "execution") fills budget slots meant for "ShardSearchRequest"
  579. // (matches "shard" + "search" + "request").
  580. const queryTermsForBoost = extractSearchTerms(query);
  581. if (queryTermsForBoost.length >= 2) {
  582. // Group terms that are substrings of each other (stem variants of the same
  583. // root word). "indexed", "indexe", "index" should count as ONE concept match,
  584. // not three. Without this, stem variants inflate matchCount and give false
  585. // multi-term boosts to symbols matching one root word multiple times.
  586. const termGroups: string[][] = [];
  587. const sorted = [...queryTermsForBoost].sort((a, b) => b.length - a.length);
  588. const assigned = new Set<string>();
  589. for (const term of sorted) {
  590. if (assigned.has(term)) continue;
  591. const group = [term];
  592. assigned.add(term);
  593. for (const other of sorted) {
  594. if (assigned.has(other)) continue;
  595. if (term.includes(other) || other.includes(term)) {
  596. group.push(other);
  597. assigned.add(other);
  598. }
  599. }
  600. termGroups.push(group);
  601. }
  602. // Build a set of exact-match node IDs so we can exempt them from dampening.
  603. // When the query is "LiveEditMode DevServerPreview", these are specific
  604. // symbols the user asked for — dampening them because they only match 1
  605. // term group is counter-productive.
  606. const exactMatchIds = new Set(exactMatches.map(r => r.node.id));
  607. for (const result of searchResults) {
  608. // Check term matches in name (substring) and path DIRECTORIES (exact).
  609. // Directory segments must match exactly — "search" matches directory
  610. // "search/" but NOT "elasticsearch/". The class name is checked
  611. // separately via substring match on the node name.
  612. const nameLower = result.node.name.toLowerCase();
  613. const dirSegments = path.dirname(result.node.filePath).toLowerCase().split('/');
  614. let matchCount = 0;
  615. for (const group of termGroups) {
  616. const groupMatches = group.some(term => {
  617. const inName = nameLower.includes(term);
  618. const inDir = dirSegments.some(seg => seg === term);
  619. return inName || inDir;
  620. });
  621. if (groupMatches) matchCount++;
  622. }
  623. if (matchCount >= 2) {
  624. // Multiplicative boost — 2 terms → 2x, 3 terms → 2.5x
  625. result.score *= 1 + matchCount * 0.5;
  626. } else if (!exactMatchIds.has(result.node.id)) {
  627. // Mild dampen for single-term matches — they might be generic
  628. // but could also be the right result (e.g., "Protocol" class for an IPC query).
  629. // Exempt exact name matches: they are specific symbols the user queried for.
  630. result.score *= 0.6;
  631. }
  632. }
  633. searchResults.sort((a, b) => b.score - a.score);
  634. }
  635. // Step 5b: CamelCase-boundary matching via LIKE query.
  636. // FTS can't find "Search" inside "TransportSearchAction" (one FTS token).
  637. // LIKE reliably finds these substring matches. Results are appended with
  638. // guaranteed slots so they don't compete with higher-scoring prefix matches.
  639. if (symbolsFromQuery.length > 0) {
  640. const camelDefinitionKinds: NodeKind[] = ['class', 'interface', 'struct', 'trait',
  641. 'protocol', 'enum', 'type_alias'];
  642. const camelSearchedTerms = new Set<string>();
  643. const searchIdSet = new Set(searchResults.map(r => r.node.id));
  644. // Track per-node term hits for multi-term boosting
  645. const camelNodeTerms = new Map<string, { result: SearchResult; termCount: number }>();
  646. const maxCamelPerTerm = Math.ceil(opts.searchLimit / 2);
  647. for (const sym of symbolsFromQuery) {
  648. const titleCased = sym.charAt(0).toUpperCase() + sym.slice(1).toLowerCase();
  649. if (titleCased.length < 3) continue;
  650. const termKey = titleCased.toLowerCase();
  651. if (camelSearchedTerms.has(termKey)) continue;
  652. camelSearchedTerms.add(termKey);
  653. // Fetch a large batch — popular terms like "Search" in Elasticsearch
  654. // have hundreds of substring matches. The LIKE scan cost is the same
  655. // regardless of LIMIT (SQLite scans all matches to sort), so we fetch
  656. // generously and let path-relevance scoring pick the best ones.
  657. const likeResults = this.queries.findNodesByNameSubstring(titleCased, {
  658. limit: 200,
  659. kinds: camelDefinitionKinds,
  660. excludePrefix: true,
  661. });
  662. // Filter to CamelCase boundaries, score by path relevance, and take top N
  663. const termCandidates: SearchResult[] = [];
  664. for (const r of likeResults) {
  665. const name = r.node.name;
  666. const idx = name.indexOf(titleCased);
  667. if (idx <= 0) continue;
  668. // Accept CamelCase boundary (lowercase before match) OR
  669. // acronym boundary (uppercase before match, e.g., RPCProtocol)
  670. if (!/[a-zA-Z]/.test(name.charAt(idx - 1))) continue;
  671. if (searchIdSet.has(r.node.id)) continue;
  672. if (isTestFile(r.node.filePath) && !isTestQuery) continue;
  673. const pathScore = scorePathRelevance(r.node.filePath, query);
  674. const brevityBonus = Math.max(0, 6 - (name.length - titleCased.length) / 4);
  675. termCandidates.push({ node: r.node, score: 8 + brevityBonus + pathScore });
  676. }
  677. termCandidates.sort((a, b) => b.score - a.score);
  678. // Widen the per-term pool for accumulation so multi-term co-occurrences
  679. // can be discovered. A class matching 3 query terms at CamelCase boundaries
  680. // is far more relevant than one matching just 1, but it needs to survive
  681. // the per-term cut for EACH term to accumulate its count.
  682. const accumPerTerm = maxCamelPerTerm * 4;
  683. for (const r of termCandidates.slice(0, accumPerTerm)) {
  684. const existing = camelNodeTerms.get(r.node.id);
  685. if (existing) {
  686. existing.termCount++;
  687. } else {
  688. camelNodeTerms.set(r.node.id, {
  689. result: r,
  690. termCount: 1,
  691. });
  692. }
  693. }
  694. }
  695. // Append CamelCase matches with multi-term boost.
  696. // These are structurally important (class names containing query terms at
  697. // CamelCase boundaries) but score much lower than FTS results. Scale their
  698. // scores up so multi-term CamelCase matches can compete with FTS results.
  699. const camelResults: SearchResult[] = [];
  700. for (const [, info] of camelNodeTerms) {
  701. // Multi-term CamelCase matches are extremely relevant — a class matching
  702. // 3+ query terms in its name (e.g., ExtensionHostProcess) is almost
  703. // certainly what the user wants. Scale aggressively.
  704. info.result.score = info.result.score * (1 + info.termCount) + (info.termCount - 1) * 30;
  705. camelResults.push(info.result);
  706. }
  707. camelResults.sort((a, b) => b.score - a.score);
  708. const maxCamelTotal = opts.searchLimit;
  709. for (const r of camelResults.slice(0, maxCamelTotal)) {
  710. searchResults.push(r);
  711. searchIdSet.add(r.node.id);
  712. }
  713. // Step 5c: Compound term matching — find classes whose name contains 2+
  714. // query terms at ANY position (not just CamelCase boundaries).
  715. // The CamelCase step above requires idx > 0, which misses classes that
  716. // START with a query term (e.g., "SearchShardsRequest" starts with "Search").
  717. // For multi-word queries, a class matching multiple query terms in its name
  718. // is almost certainly relevant regardless of position.
  719. if (symbolsFromQuery.length >= 2) {
  720. // Collect ALL LIKE results per term (reusing findNodesByNameSubstring)
  721. // but without the CamelCase boundary or prefix exclusion filters.
  722. const compoundTermMap = new Map<string, { node: Node; terms: Set<string> }>();
  723. for (const sym of symbolsFromQuery) {
  724. const titleCased = sym.charAt(0).toUpperCase() + sym.slice(1).toLowerCase();
  725. if (titleCased.length < 3) continue;
  726. const likeResults = this.queries.findNodesByNameSubstring(titleCased, {
  727. limit: 200,
  728. kinds: camelDefinitionKinds,
  729. excludePrefix: false,
  730. });
  731. for (const r of likeResults) {
  732. if (searchIdSet.has(r.node.id)) continue;
  733. if (isTestFile(r.node.filePath) && !isTestQuery) continue;
  734. const entry = compoundTermMap.get(r.node.id);
  735. if (entry) {
  736. entry.terms.add(titleCased);
  737. } else {
  738. compoundTermMap.set(r.node.id, { node: r.node, terms: new Set([titleCased]) });
  739. }
  740. }
  741. }
  742. // Keep only nodes matching 2+ distinct terms
  743. const compoundResults: SearchResult[] = [];
  744. for (const [, entry] of compoundTermMap) {
  745. if (entry.terms.size >= 2) {
  746. const pathScore = scorePathRelevance(entry.node.filePath, query);
  747. const brevityBonus = Math.max(0, 6 - entry.node.name.length / 8);
  748. compoundResults.push({
  749. node: entry.node,
  750. score: 10 + (entry.terms.size - 1) * 20 + pathScore + brevityBonus,
  751. });
  752. }
  753. }
  754. compoundResults.sort((a, b) => b.score - a.score);
  755. const maxCompound = Math.ceil(opts.searchLimit / 2);
  756. for (const r of compoundResults.slice(0, maxCompound)) {
  757. searchResults.push(r);
  758. searchIdSet.add(r.node.id);
  759. }
  760. }
  761. }
  762. // Final sort and truncation — all search channels (exact, text, CamelCase,
  763. // compound) have now contributed. Sort by score so multi-term matches from
  764. // later steps can outrank dampened single-term matches from earlier steps.
  765. searchResults.sort((a, b) => b.score - a.score);
  766. searchResults = searchResults.slice(0, opts.searchLimit * 3);
  767. // Filter by minimum score
  768. let filteredResults = searchResults.filter((r) => r.score >= opts.minScore);
  769. // Resolve imports/exports to their actual definitions
  770. // If someone searches "terminal" and finds `import { TerminalPanel }`,
  771. // they want the TerminalPanel class, not the import statement
  772. filteredResults = this.resolveImportsToDefinitions(filteredResults);
  773. // Cap entry points so traversal budget isn't spread too thin.
  774. // With 36 entry points and maxNodes=120, each gets only 3 nodes — useless.
  775. // Cap to searchLimit so each entry point gets a meaningful traversal budget.
  776. if (filteredResults.length > opts.searchLimit) {
  777. filteredResults = filteredResults.slice(0, opts.searchLimit);
  778. }
  779. // Add entry points to subgraph
  780. for (const result of filteredResults) {
  781. nodes.set(result.node.id, result.node);
  782. roots.push(result.node.id);
  783. }
  784. // Expand type hierarchy for class/interface entry points.
  785. // BFS often exhausts its per-entry-point budget on contained methods
  786. // before reaching extends/implements neighbors. This dedicated step
  787. // ensures subclasses and superclasses always appear in results.
  788. // Budget: up to maxNodes/4 hierarchy nodes to avoid flooding.
  789. const typeHierarchyKinds = new Set<string>(['class', 'interface', 'struct', 'trait', 'protocol']);
  790. const maxHierarchyNodes = Math.ceil(opts.maxNodes / 4);
  791. let hierarchyNodesAdded = 0;
  792. for (const result of filteredResults) {
  793. if (hierarchyNodesAdded >= maxHierarchyNodes) break;
  794. if (typeHierarchyKinds.has(result.node.kind)) {
  795. const hierarchy = this.traverser.getTypeHierarchy(result.node.id);
  796. for (const [id, node] of hierarchy.nodes) {
  797. if (!nodes.has(id)) {
  798. nodes.set(id, node);
  799. hierarchyNodesAdded++;
  800. }
  801. }
  802. for (const edge of hierarchy.edges) {
  803. const exists = edges.some(
  804. (e) => e.source === edge.source && e.target === edge.target && e.kind === edge.kind
  805. );
  806. if (!exists) {
  807. edges.push(edge);
  808. }
  809. }
  810. }
  811. }
  812. // Pass 2: expand hierarchy of newly-discovered parent types to find siblings.
  813. // E.g., InternalEngine → Engine (parent, from pass 1) → ReadOnlyEngine (sibling).
  814. if (hierarchyNodesAdded > 0) {
  815. const pass2Candidates = [...nodes.values()].filter(
  816. n => typeHierarchyKinds.has(n.kind) && !roots.includes(n.id)
  817. );
  818. for (const candidate of pass2Candidates) {
  819. if (hierarchyNodesAdded >= maxHierarchyNodes) break;
  820. const siblingHierarchy = this.traverser.getTypeHierarchy(candidate.id);
  821. for (const [id, node] of siblingHierarchy.nodes) {
  822. if (!nodes.has(id) && hierarchyNodesAdded < maxHierarchyNodes) {
  823. nodes.set(id, node);
  824. hierarchyNodesAdded++;
  825. }
  826. }
  827. for (const edge of siblingHierarchy.edges) {
  828. if (nodes.has(edge.source) && nodes.has(edge.target)) {
  829. const exists = edges.some(
  830. (e) => e.source === edge.source && e.target === edge.target && e.kind === edge.kind
  831. );
  832. if (!exists) {
  833. edges.push(edge);
  834. }
  835. }
  836. }
  837. }
  838. }
  839. // Traverse from each entry point
  840. for (const result of filteredResults) {
  841. const traversalResult = this.traverser.traverseBFS(result.node.id, {
  842. maxDepth: opts.traversalDepth,
  843. edgeKinds: opts.edgeKinds && opts.edgeKinds.length > 0 ? opts.edgeKinds : undefined,
  844. nodeKinds: opts.nodeKinds && opts.nodeKinds.length > 0 ? opts.nodeKinds : undefined,
  845. direction: 'both',
  846. limit: Math.ceil(opts.maxNodes / Math.max(1, filteredResults.length)),
  847. });
  848. // Merge nodes
  849. for (const [id, node] of traversalResult.nodes) {
  850. if (!nodes.has(id)) {
  851. nodes.set(id, node);
  852. }
  853. }
  854. // Merge edges (avoid duplicates)
  855. for (const edge of traversalResult.edges) {
  856. const exists = edges.some(
  857. (e) => e.source === edge.source && e.target === edge.target && e.kind === edge.kind
  858. );
  859. if (!exists) {
  860. edges.push(edge);
  861. }
  862. }
  863. }
  864. // Trim to max nodes if needed
  865. let finalNodes = nodes;
  866. let finalEdges = edges;
  867. if (nodes.size > opts.maxNodes) {
  868. // Prioritize entry points and their direct neighbors
  869. const priorityIds = new Set(roots);
  870. for (const edge of edges) {
  871. if (priorityIds.has(edge.source)) {
  872. priorityIds.add(edge.target);
  873. }
  874. if (priorityIds.has(edge.target)) {
  875. priorityIds.add(edge.source);
  876. }
  877. }
  878. // Keep priority nodes, then fill remaining slots
  879. finalNodes = new Map<string, Node>();
  880. for (const id of priorityIds) {
  881. const node = nodes.get(id);
  882. if (node && finalNodes.size < opts.maxNodes) {
  883. finalNodes.set(id, node);
  884. }
  885. }
  886. // Fill remaining from other nodes
  887. for (const [id, node] of nodes) {
  888. if (finalNodes.size >= opts.maxNodes) break;
  889. if (!finalNodes.has(id)) {
  890. finalNodes.set(id, node);
  891. }
  892. }
  893. // Filter edges to only include kept nodes
  894. finalEdges = edges.filter(
  895. (e) => finalNodes.has(e.source) && finalNodes.has(e.target)
  896. );
  897. }
  898. // Per-file diversity cap: prevent any single file from monopolizing the
  899. // node budget. When BFS traverses from a method, it follows `contains`
  900. // to the parent class, then back down to all sibling methods. With
  901. // multiple entry points in the same class, one file can consume 30-40%
  902. // of maxNodes. Cap each file to ~20% to ensure cross-file diversity.
  903. const maxPerFile = Math.max(5, Math.ceil(opts.maxNodes * 0.2));
  904. const fileCounts = new Map<string, string[]>();
  905. for (const [id, node] of finalNodes) {
  906. const ids = fileCounts.get(node.filePath) || [];
  907. ids.push(id);
  908. fileCounts.set(node.filePath, ids);
  909. }
  910. const rootSet = new Set(roots);
  911. for (const [, nodeIds] of fileCounts) {
  912. if (nodeIds.length <= maxPerFile) continue;
  913. // Sort: entry points first, then classes/interfaces, then others
  914. const kindPriority: Record<string, number> = {
  915. class: 3, interface: 3, struct: 3, trait: 3, protocol: 3, enum: 3,
  916. method: 1, function: 1, property: 0, field: 0, variable: 0,
  917. };
  918. nodeIds.sort((a, b) => {
  919. const aRoot = rootSet.has(a) ? 10 : 0;
  920. const bRoot = rootSet.has(b) ? 10 : 0;
  921. const aKind = kindPriority[finalNodes.get(a)!.kind] ?? 0;
  922. const bKind = kindPriority[finalNodes.get(b)!.kind] ?? 0;
  923. return (bRoot + bKind) - (aRoot + aKind);
  924. });
  925. // Remove excess nodes (keep the highest-priority ones)
  926. for (const id of nodeIds.slice(maxPerFile)) {
  927. finalNodes.delete(id);
  928. }
  929. }
  930. // Non-production node cap: limit test/sample/integration/example files to
  931. // at most 15% of the budget. Many codebases have dozens of near-identical
  932. // test implementations (e.g., 6 Guard classes in integration tests) that
  933. // individually survive score dampening but collectively flood the result.
  934. // Test entry points are NOT exempt — they should be evicted too.
  935. if (!isTestQuery) {
  936. const maxNonProd = Math.max(3, Math.ceil(opts.maxNodes * 0.15));
  937. const nonProdIds: string[] = [];
  938. for (const [id, node] of finalNodes) {
  939. if (isTestFile(node.filePath)) {
  940. nonProdIds.push(id);
  941. }
  942. }
  943. if (nonProdIds.length > maxNonProd) {
  944. for (const id of nonProdIds.slice(maxNonProd)) {
  945. finalNodes.delete(id);
  946. // Also remove from roots — test file entry points shouldn't anchor results
  947. const rootIdx = roots.indexOf(id);
  948. if (rootIdx !== -1) roots.splice(rootIdx, 1);
  949. }
  950. }
  951. }
  952. // Re-filter edges after per-file and non-production caps
  953. finalEdges = finalEdges.filter(
  954. (e) => finalNodes.has(e.source) && finalNodes.has(e.target)
  955. );
  956. // Edge recovery: BFS with many entry points leaves most nodes disconnected.
  957. // Discover edges between already-selected nodes to recover connectivity.
  958. const recoveryKinds: EdgeKind[] = ['calls', 'extends', 'implements', 'references', 'overrides'];
  959. const recoveredEdges = this.queries.findEdgesBetweenNodes(
  960. [...finalNodes.keys()],
  961. recoveryKinds,
  962. );
  963. const existingEdgeKeys = new Set(
  964. finalEdges.map((e) => `${e.source}:${e.target}:${e.kind}`)
  965. );
  966. for (const edge of recoveredEdges) {
  967. const key = `${edge.source}:${edge.target}:${edge.kind}`;
  968. if (!existingEdgeKeys.has(key)) {
  969. finalEdges.push(edge);
  970. existingEdgeKeys.add(key);
  971. }
  972. }
  973. return { nodes: finalNodes, edges: finalEdges, roots };
  974. }
  975. /**
  976. * Get the source code for a node
  977. *
  978. * Reads the file and extracts the code between startLine and endLine.
  979. *
  980. * @param nodeId - ID of the node
  981. * @returns Code string or null if not found
  982. */
  983. async getCode(nodeId: string): Promise<string | null> {
  984. const node = this.queries.getNodeById(nodeId);
  985. if (!node) {
  986. return null;
  987. }
  988. return this.extractNodeCode(node);
  989. }
  990. /**
  991. * Extract code from a node's source file
  992. */
  993. private async extractNodeCode(node: Node): Promise<string | null> {
  994. const filePath = validatePathWithinRoot(this.projectRoot, node.filePath);
  995. if (!filePath || !fs.existsSync(filePath)) {
  996. return null;
  997. }
  998. try {
  999. const content = fs.readFileSync(filePath, 'utf-8');
  1000. const lines = content.split('\n');
  1001. // Extract lines (1-indexed to 0-indexed)
  1002. const startIdx = Math.max(0, node.startLine - 1);
  1003. const endIdx = Math.min(lines.length, node.endLine);
  1004. return lines.slice(startIdx, endIdx).join('\n');
  1005. } catch (error) {
  1006. logDebug('Failed to extract code from node', { nodeId: node.id, filePath: node.filePath, error: String(error) });
  1007. return null;
  1008. }
  1009. }
  1010. /**
  1011. * Get entry points from a subgraph (the root nodes)
  1012. */
  1013. private getEntryPoints(subgraph: Subgraph): Node[] {
  1014. return subgraph.roots
  1015. .map((id) => subgraph.nodes.get(id))
  1016. .filter((n): n is Node => n !== undefined);
  1017. }
  1018. /**
  1019. * Extract code blocks for key nodes in the subgraph
  1020. */
  1021. private async extractCodeBlocks(
  1022. subgraph: Subgraph,
  1023. maxBlocks: number,
  1024. maxBlockSize: number
  1025. ): Promise<CodeBlock[]> {
  1026. const blocks: CodeBlock[] = [];
  1027. // Prioritize entry points, then functions/methods
  1028. const priorityNodes: Node[] = [];
  1029. // First: entry points
  1030. for (const id of subgraph.roots) {
  1031. const node = subgraph.nodes.get(id);
  1032. if (node) {
  1033. priorityNodes.push(node);
  1034. }
  1035. }
  1036. // Then: functions and methods
  1037. for (const node of subgraph.nodes.values()) {
  1038. if (!subgraph.roots.includes(node.id)) {
  1039. if (node.kind === 'function' || node.kind === 'method') {
  1040. priorityNodes.push(node);
  1041. }
  1042. }
  1043. }
  1044. // Then: classes
  1045. for (const node of subgraph.nodes.values()) {
  1046. if (!subgraph.roots.includes(node.id)) {
  1047. if (node.kind === 'class') {
  1048. priorityNodes.push(node);
  1049. }
  1050. }
  1051. }
  1052. // Extract code for priority nodes
  1053. for (const node of priorityNodes) {
  1054. if (blocks.length >= maxBlocks) break;
  1055. const code = await this.extractNodeCode(node);
  1056. if (code) {
  1057. // Truncate if too long. Language-neutral marker (no `//` — not a
  1058. // comment in Python, Ruby, etc.); this renders inside a fenced
  1059. // source block whose language varies.
  1060. const truncated = code.length > maxBlockSize
  1061. ? code.slice(0, maxBlockSize) + '\n... (truncated) ...'
  1062. : code;
  1063. blocks.push({
  1064. content: truncated,
  1065. filePath: node.filePath,
  1066. startLine: node.startLine,
  1067. endLine: node.endLine,
  1068. language: node.language,
  1069. node,
  1070. });
  1071. }
  1072. }
  1073. return blocks;
  1074. }
  1075. /**
  1076. * Get unique files from a subgraph
  1077. */
  1078. private getRelatedFiles(subgraph: Subgraph): string[] {
  1079. const files = new Set<string>();
  1080. for (const node of subgraph.nodes.values()) {
  1081. files.add(node.filePath);
  1082. }
  1083. return Array.from(files).sort();
  1084. }
  1085. /**
  1086. * Generate a summary of the context
  1087. */
  1088. private generateSummary(_query: string, subgraph: Subgraph, entryPoints: Node[]): string {
  1089. const nodeCount = subgraph.nodes.size;
  1090. const edgeCount = subgraph.edges.length;
  1091. const files = this.getRelatedFiles(subgraph);
  1092. const entryPointNames = entryPoints
  1093. .slice(0, 3)
  1094. .map((n) => n.name)
  1095. .join(', ');
  1096. const remaining = entryPoints.length > 3 ? ` and ${entryPoints.length - 3} more` : '';
  1097. return `Found ${nodeCount} relevant code symbols across ${files.length} files. ` +
  1098. `Key entry points: ${entryPointNames}${remaining}. ` +
  1099. `${edgeCount} relationships identified.`;
  1100. }
  1101. /**
  1102. * Resolve import/export nodes to their actual definitions
  1103. *
  1104. * When search returns `import { TerminalPanel }`, users want the TerminalPanel
  1105. * class definition, not the import statement. This follows the `imports` edge
  1106. * to find and return the actual definition instead.
  1107. *
  1108. * @param results - Search results that may include import/export nodes
  1109. * @returns Results with imports resolved to definitions where possible
  1110. */
  1111. private resolveImportsToDefinitions(results: SearchResult[]): SearchResult[] {
  1112. const resolved: SearchResult[] = [];
  1113. const seenIds = new Set<string>();
  1114. for (const result of results) {
  1115. const { node, score } = result;
  1116. // If it's not an import/export, keep it as-is
  1117. if (node.kind !== 'import' && node.kind !== 'export') {
  1118. if (!seenIds.has(node.id)) {
  1119. seenIds.add(node.id);
  1120. resolved.push(result);
  1121. }
  1122. continue;
  1123. }
  1124. // For imports/exports, try to find what they reference
  1125. // Imports have outgoing 'imports' edges to the definition
  1126. // Exports have outgoing 'exports' edges to the definition
  1127. const edgeKind = node.kind === 'import' ? 'imports' : 'exports';
  1128. const outgoingEdges = this.queries.getOutgoingEdges(node.id, [edgeKind as EdgeKind]);
  1129. let foundDefinition = false;
  1130. for (const edge of outgoingEdges) {
  1131. const targetNode = this.queries.getNodeById(edge.target);
  1132. if (targetNode && !seenIds.has(targetNode.id)) {
  1133. // Found the definition - use it instead of the import
  1134. seenIds.add(targetNode.id);
  1135. resolved.push({
  1136. node: targetNode,
  1137. score: score, // Preserve the original score
  1138. });
  1139. foundDefinition = true;
  1140. logDebug('Resolved import to definition', {
  1141. import: node.name,
  1142. definition: targetNode.name,
  1143. kind: targetNode.kind,
  1144. });
  1145. }
  1146. }
  1147. // If we couldn't resolve the import, skip it (it's low-value on its own)
  1148. if (!foundDefinition) {
  1149. logDebug('Skipping unresolved import', { name: node.name, file: node.filePath });
  1150. }
  1151. }
  1152. return resolved;
  1153. }
  1154. }
  1155. /**
  1156. * Create a context builder
  1157. */
  1158. export function createContextBuilder(
  1159. projectRoot: string,
  1160. queries: QueryBuilder,
  1161. traverser: GraphTraverser
  1162. ): ContextBuilder {
  1163. return new ContextBuilder(projectRoot, queries, traverser);
  1164. }
  1165. // Re-export formatter
  1166. export { formatContextAsMarkdown, formatContextAsJson } from './formatter';