index.ts 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132
  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);
  238. } else if (opts.format === 'json') {
  239. return formatContextAsJson(context);
  240. }
  241. return context;
  242. }
  243. /**
  244. * Find relevant subgraph for a query
  245. *
  246. * Uses hybrid search combining exact symbol lookup with semantic search:
  247. * 1. Extract potential symbol names from query
  248. * 2. Look up exact matches for those symbols (high confidence)
  249. * 3. Use semantic search for concept matching
  250. * 4. Merge results, prioritizing exact matches
  251. * 5. Traverse graph from entry points
  252. *
  253. * @param query - Natural language query
  254. * @param options - Search and traversal options
  255. * @returns Subgraph of relevant nodes and edges
  256. */
  257. async findRelevantContext(
  258. query: string,
  259. options: FindRelevantContextOptions = {}
  260. ): Promise<Subgraph> {
  261. const opts = { ...DEFAULT_FIND_OPTIONS, ...options };
  262. // Start with empty subgraph
  263. const nodes = new Map<string, Node>();
  264. const edges: Edge[] = [];
  265. const roots: string[] = [];
  266. // Handle empty query - return empty subgraph
  267. if (!query || query.trim().length === 0) {
  268. return { nodes, edges, roots };
  269. }
  270. // === HYBRID SEARCH ===
  271. // Step 1: Extract potential symbol names from query
  272. const symbolsFromQuery = extractSymbolsFromQuery(query);
  273. logDebug('Extracted symbols from query', { query, symbols: symbolsFromQuery });
  274. // Step 2: Look up exact matches for extracted symbols
  275. let exactMatches: SearchResult[] = [];
  276. if (symbolsFromQuery.length > 0) {
  277. try {
  278. // Get more results so we can apply co-location boosting before trimming
  279. exactMatches = this.queries.findNodesByExactName(symbolsFromQuery, {
  280. limit: Math.ceil(opts.searchLimit * 5),
  281. kinds: opts.nodeKinds && opts.nodeKinds.length > 0 ? opts.nodeKinds : undefined,
  282. });
  283. // Co-location boost: when multiple extracted symbols appear in the same file,
  284. // those results are much more likely to be what the user is looking for.
  285. // E.g., "scrapeLoop" + "run" both in scrape/scrape.go → boost both.
  286. if (exactMatches.length > 1) {
  287. // Build a map of files → how many distinct symbol names matched in that file
  288. const fileSymbolCounts = new Map<string, Set<string>>();
  289. for (const r of exactMatches) {
  290. const names = fileSymbolCounts.get(r.node.filePath) || new Set();
  291. names.add(r.node.name.toLowerCase());
  292. fileSymbolCounts.set(r.node.filePath, names);
  293. }
  294. // Boost results in files where multiple query symbols co-occur
  295. exactMatches = exactMatches.map(r => {
  296. const symbolCount = fileSymbolCounts.get(r.node.filePath)?.size || 1;
  297. return {
  298. ...r,
  299. score: symbolCount > 1 ? r.score + (symbolCount - 1) * 20 : r.score,
  300. };
  301. });
  302. exactMatches.sort((a, b) => b.score - a.score);
  303. }
  304. // Trim back to reasonable size
  305. exactMatches = exactMatches.slice(0, Math.ceil(opts.searchLimit * 2));
  306. logDebug('Exact symbol matches', { count: exactMatches.length });
  307. } catch (error) {
  308. logDebug('Exact symbol lookup failed', { error: String(error) });
  309. }
  310. }
  311. // Step 2b: Search for extracted symbols as definition (class/interface) prefixes.
  312. // When the user writes "REST", "bulk", or "allocation", they usually mean classes
  313. // like RestController, BulkRequest, AllocationService — not nodes named exactly that.
  314. // Also tries stem variants: "caching" → "cache" finds Cache, CacheBuilder.
  315. if (symbolsFromQuery.length > 0) {
  316. const definitionKinds: NodeKind[] = ['class', 'interface', 'struct', 'trait',
  317. 'protocol', 'enum', 'type_alias'];
  318. // Expand symbols with stem variants for broader definition matching
  319. const expandedSymbols = new Set(symbolsFromQuery);
  320. for (const sym of symbolsFromQuery) {
  321. for (const variant of getStemVariants(sym)) {
  322. expandedSymbols.add(variant);
  323. }
  324. }
  325. for (const sym of expandedSymbols) {
  326. // Title-case the symbol: "REST" → "Rest", "bulk" → "Bulk", "allocation" → "Allocation"
  327. const titleCased = sym.charAt(0).toUpperCase() + sym.slice(1).toLowerCase();
  328. if (titleCased === sym) continue; // already title-case (e.g., "Engine") — handled by exact match
  329. // Fetch more results since popular prefixes have many matches
  330. const prefixResults = this.queries.searchNodes(titleCased, {
  331. limit: 30,
  332. kinds: definitionKinds,
  333. });
  334. const matched: SearchResult[] = [];
  335. for (const r of prefixResults) {
  336. if (r.node.name.toLowerCase().startsWith(titleCased.toLowerCase())) {
  337. // Favor shorter names: "AllocationService" (18 chars) over
  338. // "AllocationBalancingRoundMetrics" (31 chars). Core classes tend
  339. // to have concise names; test/helper classes are verbose.
  340. const brevityBonus = Math.max(0, 10 - (r.node.name.length - titleCased.length) / 3);
  341. matched.push({ ...r, score: r.score + 15 + brevityBonus });
  342. }
  343. }
  344. matched.sort((a, b) => b.score - a.score);
  345. for (const r of matched.slice(0, Math.ceil(opts.searchLimit))) {
  346. const existing = exactMatches.find(e => e.node.id === r.node.id);
  347. if (!existing) {
  348. exactMatches.push(r);
  349. }
  350. }
  351. }
  352. exactMatches.sort((a, b) => b.score - a.score);
  353. exactMatches = exactMatches.slice(0, Math.ceil(opts.searchLimit * 3));
  354. }
  355. // Step 3: Run text search for natural language term matching
  356. // This catches file-name and node-name matches that semantic search may miss,
  357. // which is critical for template-heavy codebases (e.g., Liquid/Shopify themes)
  358. // where file names are the primary identifiers.
  359. let textResults: SearchResult[] = [];
  360. try {
  361. const searchTerms = extractSearchTerms(query);
  362. if (searchTerms.length > 0) {
  363. // Search each term individually to get broader coverage,
  364. // then boost results that match multiple terms
  365. const termResultsMap = new Map<string, { result: SearchResult; termHits: number }>();
  366. // When no explicit kind filter is set, exclude imports — they flood FTS
  367. // results with qualified name matches (e.g., "REST" matches 445K import paths)
  368. // but are almost never what exploration queries want.
  369. const searchKinds = opts.nodeKinds && opts.nodeKinds.length > 0
  370. ? opts.nodeKinds
  371. : ['file', 'module', 'class', 'struct', 'interface', 'trait', 'protocol',
  372. 'function', 'method', 'property', 'field', 'variable', 'constant',
  373. 'enum', 'enum_member', 'type_alias', 'namespace', 'export',
  374. 'route', 'component'] as NodeKind[];
  375. for (const term of searchTerms) {
  376. const termResults = this.queries.searchNodes(term, {
  377. limit: opts.searchLimit * 2,
  378. kinds: searchKinds,
  379. });
  380. for (const r of termResults) {
  381. const existing = termResultsMap.get(r.node.id);
  382. if (existing) {
  383. existing.termHits++;
  384. existing.result.score = Math.max(existing.result.score, r.score);
  385. } else {
  386. termResultsMap.set(r.node.id, { result: r, termHits: 1 });
  387. }
  388. }
  389. }
  390. // Boost results matching multiple terms and sort
  391. textResults = Array.from(termResultsMap.values())
  392. .map(({ result, termHits }) => ({
  393. ...result,
  394. score: result.score + (termHits - 1) * 5,
  395. }))
  396. .sort((a, b) => b.score - a.score)
  397. .slice(0, opts.searchLimit * 2);
  398. }
  399. logDebug('Text search results', { count: textResults.length });
  400. } catch (error) {
  401. logDebug('Text search failed', { query, error: String(error) });
  402. }
  403. // Step 4: Merge results, taking the max score when duplicates appear
  404. // across search channels. Exact matches may have lower scores than FTS
  405. // results for the same node — use the best score from any channel.
  406. const resultById = new Map<string, SearchResult>();
  407. let searchResults: SearchResult[] = [];
  408. // Add exact matches first
  409. for (const result of exactMatches) {
  410. const existing = resultById.get(result.node.id);
  411. if (existing) {
  412. existing.score = Math.max(existing.score, result.score);
  413. } else {
  414. resultById.set(result.node.id, result);
  415. searchResults.push(result);
  416. }
  417. }
  418. // Add text search results, upgrading scores for duplicates
  419. for (const result of textResults) {
  420. const existing = resultById.get(result.node.id);
  421. if (existing) {
  422. existing.score = Math.max(existing.score, result.score);
  423. } else {
  424. resultById.set(result.node.id, result);
  425. searchResults.push(result);
  426. }
  427. }
  428. const queryLower = query.toLowerCase();
  429. const isTestQuery = queryLower.includes('test') || queryLower.includes('spec');
  430. // Deprioritize test files early so they don't take multi-term boost slots
  431. if (!isTestQuery) {
  432. for (const result of searchResults) {
  433. if (isTestFile(result.node.filePath)) {
  434. result.score *= 0.3;
  435. }
  436. }
  437. }
  438. // Step 5a: Multi-term co-occurrence re-ranking (applied BEFORE truncation).
  439. // For multi-word queries like "search execution from request to shard",
  440. // nodes matching 2+ query terms in their name or path are far more relevant
  441. // than nodes matching just one generic term. Without this, "ExecutionUtils"
  442. // (matches only "execution") fills budget slots meant for "ShardSearchRequest"
  443. // (matches "shard" + "search" + "request").
  444. const queryTermsForBoost = extractSearchTerms(query);
  445. if (queryTermsForBoost.length >= 2) {
  446. // Group terms that are substrings of each other (stem variants of the same
  447. // root word). "indexed", "indexe", "index" should count as ONE concept match,
  448. // not three. Without this, stem variants inflate matchCount and give false
  449. // multi-term boosts to symbols matching one root word multiple times.
  450. const termGroups: string[][] = [];
  451. const sorted = [...queryTermsForBoost].sort((a, b) => b.length - a.length);
  452. const assigned = new Set<string>();
  453. for (const term of sorted) {
  454. if (assigned.has(term)) continue;
  455. const group = [term];
  456. assigned.add(term);
  457. for (const other of sorted) {
  458. if (assigned.has(other)) continue;
  459. if (term.includes(other) || other.includes(term)) {
  460. group.push(other);
  461. assigned.add(other);
  462. }
  463. }
  464. termGroups.push(group);
  465. }
  466. // Build a set of exact-match node IDs so we can exempt them from dampening.
  467. // When the query is "LiveEditMode DevServerPreview", these are specific
  468. // symbols the user asked for — dampening them because they only match 1
  469. // term group is counter-productive.
  470. const exactMatchIds = new Set(exactMatches.map(r => r.node.id));
  471. for (const result of searchResults) {
  472. // Check term matches in name (substring) and path DIRECTORIES (exact).
  473. // Directory segments must match exactly — "search" matches directory
  474. // "search/" but NOT "elasticsearch/". The class name is checked
  475. // separately via substring match on the node name.
  476. const nameLower = result.node.name.toLowerCase();
  477. const dirSegments = path.dirname(result.node.filePath).toLowerCase().split('/');
  478. let matchCount = 0;
  479. for (const group of termGroups) {
  480. const groupMatches = group.some(term => {
  481. const inName = nameLower.includes(term);
  482. const inDir = dirSegments.some(seg => seg === term);
  483. return inName || inDir;
  484. });
  485. if (groupMatches) matchCount++;
  486. }
  487. if (matchCount >= 2) {
  488. // Multiplicative boost — 2 terms → 2x, 3 terms → 2.5x
  489. result.score *= 1 + matchCount * 0.5;
  490. } else if (!exactMatchIds.has(result.node.id)) {
  491. // Mild dampen for single-term matches — they might be generic
  492. // but could also be the right result (e.g., "Protocol" class for an IPC query).
  493. // Exempt exact name matches: they are specific symbols the user queried for.
  494. result.score *= 0.6;
  495. }
  496. }
  497. searchResults.sort((a, b) => b.score - a.score);
  498. }
  499. // Step 5b: CamelCase-boundary matching via LIKE query.
  500. // FTS can't find "Search" inside "TransportSearchAction" (one FTS token).
  501. // LIKE reliably finds these substring matches. Results are appended with
  502. // guaranteed slots so they don't compete with higher-scoring prefix matches.
  503. if (symbolsFromQuery.length > 0) {
  504. const camelDefinitionKinds: NodeKind[] = ['class', 'interface', 'struct', 'trait',
  505. 'protocol', 'enum', 'type_alias'];
  506. const camelSearchedTerms = new Set<string>();
  507. const searchIdSet = new Set(searchResults.map(r => r.node.id));
  508. // Track per-node term hits for multi-term boosting
  509. const camelNodeTerms = new Map<string, { result: SearchResult; termCount: number }>();
  510. const maxCamelPerTerm = Math.ceil(opts.searchLimit / 2);
  511. for (const sym of symbolsFromQuery) {
  512. const titleCased = sym.charAt(0).toUpperCase() + sym.slice(1).toLowerCase();
  513. if (titleCased.length < 3) continue;
  514. const termKey = titleCased.toLowerCase();
  515. if (camelSearchedTerms.has(termKey)) continue;
  516. camelSearchedTerms.add(termKey);
  517. // Fetch a large batch — popular terms like "Search" in Elasticsearch
  518. // have hundreds of substring matches. The LIKE scan cost is the same
  519. // regardless of LIMIT (SQLite scans all matches to sort), so we fetch
  520. // generously and let path-relevance scoring pick the best ones.
  521. const likeResults = this.queries.findNodesByNameSubstring(titleCased, {
  522. limit: 200,
  523. kinds: camelDefinitionKinds,
  524. excludePrefix: true,
  525. });
  526. // Filter to CamelCase boundaries, score by path relevance, and take top N
  527. const termCandidates: SearchResult[] = [];
  528. for (const r of likeResults) {
  529. const name = r.node.name;
  530. const idx = name.indexOf(titleCased);
  531. if (idx <= 0) continue;
  532. // Accept CamelCase boundary (lowercase before match) OR
  533. // acronym boundary (uppercase before match, e.g., RPCProtocol)
  534. if (!/[a-zA-Z]/.test(name.charAt(idx - 1))) continue;
  535. if (searchIdSet.has(r.node.id)) continue;
  536. if (isTestFile(r.node.filePath) && !isTestQuery) continue;
  537. const pathScore = scorePathRelevance(r.node.filePath, query);
  538. const brevityBonus = Math.max(0, 6 - (name.length - titleCased.length) / 4);
  539. termCandidates.push({ node: r.node, score: 8 + brevityBonus + pathScore });
  540. }
  541. termCandidates.sort((a, b) => b.score - a.score);
  542. // Widen the per-term pool for accumulation so multi-term co-occurrences
  543. // can be discovered. A class matching 3 query terms at CamelCase boundaries
  544. // is far more relevant than one matching just 1, but it needs to survive
  545. // the per-term cut for EACH term to accumulate its count.
  546. const accumPerTerm = maxCamelPerTerm * 4;
  547. for (const r of termCandidates.slice(0, accumPerTerm)) {
  548. const existing = camelNodeTerms.get(r.node.id);
  549. if (existing) {
  550. existing.termCount++;
  551. } else {
  552. camelNodeTerms.set(r.node.id, {
  553. result: r,
  554. termCount: 1,
  555. });
  556. }
  557. }
  558. }
  559. // Append CamelCase matches with multi-term boost.
  560. // These are structurally important (class names containing query terms at
  561. // CamelCase boundaries) but score much lower than FTS results. Scale their
  562. // scores up so multi-term CamelCase matches can compete with FTS results.
  563. const camelResults: SearchResult[] = [];
  564. for (const [, info] of camelNodeTerms) {
  565. // Multi-term CamelCase matches are extremely relevant — a class matching
  566. // 3+ query terms in its name (e.g., ExtensionHostProcess) is almost
  567. // certainly what the user wants. Scale aggressively.
  568. info.result.score = info.result.score * (1 + info.termCount) + (info.termCount - 1) * 30;
  569. camelResults.push(info.result);
  570. }
  571. camelResults.sort((a, b) => b.score - a.score);
  572. const maxCamelTotal = opts.searchLimit;
  573. for (const r of camelResults.slice(0, maxCamelTotal)) {
  574. searchResults.push(r);
  575. searchIdSet.add(r.node.id);
  576. }
  577. // Step 5c: Compound term matching — find classes whose name contains 2+
  578. // query terms at ANY position (not just CamelCase boundaries).
  579. // The CamelCase step above requires idx > 0, which misses classes that
  580. // START with a query term (e.g., "SearchShardsRequest" starts with "Search").
  581. // For multi-word queries, a class matching multiple query terms in its name
  582. // is almost certainly relevant regardless of position.
  583. if (symbolsFromQuery.length >= 2) {
  584. // Collect ALL LIKE results per term (reusing findNodesByNameSubstring)
  585. // but without the CamelCase boundary or prefix exclusion filters.
  586. const compoundTermMap = new Map<string, { node: Node; terms: Set<string> }>();
  587. for (const sym of symbolsFromQuery) {
  588. const titleCased = sym.charAt(0).toUpperCase() + sym.slice(1).toLowerCase();
  589. if (titleCased.length < 3) continue;
  590. const likeResults = this.queries.findNodesByNameSubstring(titleCased, {
  591. limit: 200,
  592. kinds: camelDefinitionKinds,
  593. excludePrefix: false,
  594. });
  595. for (const r of likeResults) {
  596. if (searchIdSet.has(r.node.id)) continue;
  597. if (isTestFile(r.node.filePath) && !isTestQuery) continue;
  598. const entry = compoundTermMap.get(r.node.id);
  599. if (entry) {
  600. entry.terms.add(titleCased);
  601. } else {
  602. compoundTermMap.set(r.node.id, { node: r.node, terms: new Set([titleCased]) });
  603. }
  604. }
  605. }
  606. // Keep only nodes matching 2+ distinct terms
  607. const compoundResults: SearchResult[] = [];
  608. for (const [, entry] of compoundTermMap) {
  609. if (entry.terms.size >= 2) {
  610. const pathScore = scorePathRelevance(entry.node.filePath, query);
  611. const brevityBonus = Math.max(0, 6 - entry.node.name.length / 8);
  612. compoundResults.push({
  613. node: entry.node,
  614. score: 10 + (entry.terms.size - 1) * 20 + pathScore + brevityBonus,
  615. });
  616. }
  617. }
  618. compoundResults.sort((a, b) => b.score - a.score);
  619. const maxCompound = Math.ceil(opts.searchLimit / 2);
  620. for (const r of compoundResults.slice(0, maxCompound)) {
  621. searchResults.push(r);
  622. searchIdSet.add(r.node.id);
  623. }
  624. }
  625. }
  626. // Final sort and truncation — all search channels (exact, text, CamelCase,
  627. // compound) have now contributed. Sort by score so multi-term matches from
  628. // later steps can outrank dampened single-term matches from earlier steps.
  629. searchResults.sort((a, b) => b.score - a.score);
  630. searchResults = searchResults.slice(0, opts.searchLimit * 3);
  631. // Filter by minimum score
  632. let filteredResults = searchResults.filter((r) => r.score >= opts.minScore);
  633. // Resolve imports/exports to their actual definitions
  634. // If someone searches "terminal" and finds `import { TerminalPanel }`,
  635. // they want the TerminalPanel class, not the import statement
  636. filteredResults = this.resolveImportsToDefinitions(filteredResults);
  637. // Cap entry points so traversal budget isn't spread too thin.
  638. // With 36 entry points and maxNodes=120, each gets only 3 nodes — useless.
  639. // Cap to searchLimit so each entry point gets a meaningful traversal budget.
  640. if (filteredResults.length > opts.searchLimit) {
  641. filteredResults = filteredResults.slice(0, opts.searchLimit);
  642. }
  643. // Add entry points to subgraph
  644. for (const result of filteredResults) {
  645. nodes.set(result.node.id, result.node);
  646. roots.push(result.node.id);
  647. }
  648. // Expand type hierarchy for class/interface entry points.
  649. // BFS often exhausts its per-entry-point budget on contained methods
  650. // before reaching extends/implements neighbors. This dedicated step
  651. // ensures subclasses and superclasses always appear in results.
  652. // Budget: up to maxNodes/4 hierarchy nodes to avoid flooding.
  653. const typeHierarchyKinds = new Set<string>(['class', 'interface', 'struct', 'trait', 'protocol']);
  654. const maxHierarchyNodes = Math.ceil(opts.maxNodes / 4);
  655. let hierarchyNodesAdded = 0;
  656. for (const result of filteredResults) {
  657. if (hierarchyNodesAdded >= maxHierarchyNodes) break;
  658. if (typeHierarchyKinds.has(result.node.kind)) {
  659. const hierarchy = this.traverser.getTypeHierarchy(result.node.id);
  660. for (const [id, node] of hierarchy.nodes) {
  661. if (!nodes.has(id)) {
  662. nodes.set(id, node);
  663. hierarchyNodesAdded++;
  664. }
  665. }
  666. for (const edge of hierarchy.edges) {
  667. const exists = edges.some(
  668. (e) => e.source === edge.source && e.target === edge.target && e.kind === edge.kind
  669. );
  670. if (!exists) {
  671. edges.push(edge);
  672. }
  673. }
  674. }
  675. }
  676. // Pass 2: expand hierarchy of newly-discovered parent types to find siblings.
  677. // E.g., InternalEngine → Engine (parent, from pass 1) → ReadOnlyEngine (sibling).
  678. if (hierarchyNodesAdded > 0) {
  679. const pass2Candidates = [...nodes.values()].filter(
  680. n => typeHierarchyKinds.has(n.kind) && !roots.includes(n.id)
  681. );
  682. for (const candidate of pass2Candidates) {
  683. if (hierarchyNodesAdded >= maxHierarchyNodes) break;
  684. const siblingHierarchy = this.traverser.getTypeHierarchy(candidate.id);
  685. for (const [id, node] of siblingHierarchy.nodes) {
  686. if (!nodes.has(id) && hierarchyNodesAdded < maxHierarchyNodes) {
  687. nodes.set(id, node);
  688. hierarchyNodesAdded++;
  689. }
  690. }
  691. for (const edge of siblingHierarchy.edges) {
  692. if (nodes.has(edge.source) && nodes.has(edge.target)) {
  693. const exists = edges.some(
  694. (e) => e.source === edge.source && e.target === edge.target && e.kind === edge.kind
  695. );
  696. if (!exists) {
  697. edges.push(edge);
  698. }
  699. }
  700. }
  701. }
  702. }
  703. // Traverse from each entry point
  704. for (const result of filteredResults) {
  705. const traversalResult = this.traverser.traverseBFS(result.node.id, {
  706. maxDepth: opts.traversalDepth,
  707. edgeKinds: opts.edgeKinds && opts.edgeKinds.length > 0 ? opts.edgeKinds : undefined,
  708. nodeKinds: opts.nodeKinds && opts.nodeKinds.length > 0 ? opts.nodeKinds : undefined,
  709. direction: 'both',
  710. limit: Math.ceil(opts.maxNodes / Math.max(1, filteredResults.length)),
  711. });
  712. // Merge nodes
  713. for (const [id, node] of traversalResult.nodes) {
  714. if (!nodes.has(id)) {
  715. nodes.set(id, node);
  716. }
  717. }
  718. // Merge edges (avoid duplicates)
  719. for (const edge of traversalResult.edges) {
  720. const exists = edges.some(
  721. (e) => e.source === edge.source && e.target === edge.target && e.kind === edge.kind
  722. );
  723. if (!exists) {
  724. edges.push(edge);
  725. }
  726. }
  727. }
  728. // Trim to max nodes if needed
  729. let finalNodes = nodes;
  730. let finalEdges = edges;
  731. if (nodes.size > opts.maxNodes) {
  732. // Prioritize entry points and their direct neighbors
  733. const priorityIds = new Set(roots);
  734. for (const edge of edges) {
  735. if (priorityIds.has(edge.source)) {
  736. priorityIds.add(edge.target);
  737. }
  738. if (priorityIds.has(edge.target)) {
  739. priorityIds.add(edge.source);
  740. }
  741. }
  742. // Keep priority nodes, then fill remaining slots
  743. finalNodes = new Map<string, Node>();
  744. for (const id of priorityIds) {
  745. const node = nodes.get(id);
  746. if (node && finalNodes.size < opts.maxNodes) {
  747. finalNodes.set(id, node);
  748. }
  749. }
  750. // Fill remaining from other nodes
  751. for (const [id, node] of nodes) {
  752. if (finalNodes.size >= opts.maxNodes) break;
  753. if (!finalNodes.has(id)) {
  754. finalNodes.set(id, node);
  755. }
  756. }
  757. // Filter edges to only include kept nodes
  758. finalEdges = edges.filter(
  759. (e) => finalNodes.has(e.source) && finalNodes.has(e.target)
  760. );
  761. }
  762. // Per-file diversity cap: prevent any single file from monopolizing the
  763. // node budget. When BFS traverses from a method, it follows `contains`
  764. // to the parent class, then back down to all sibling methods. With
  765. // multiple entry points in the same class, one file can consume 30-40%
  766. // of maxNodes. Cap each file to ~20% to ensure cross-file diversity.
  767. const maxPerFile = Math.max(5, Math.ceil(opts.maxNodes * 0.2));
  768. const fileCounts = new Map<string, string[]>();
  769. for (const [id, node] of finalNodes) {
  770. const ids = fileCounts.get(node.filePath) || [];
  771. ids.push(id);
  772. fileCounts.set(node.filePath, ids);
  773. }
  774. const rootSet = new Set(roots);
  775. for (const [, nodeIds] of fileCounts) {
  776. if (nodeIds.length <= maxPerFile) continue;
  777. // Sort: entry points first, then classes/interfaces, then others
  778. const kindPriority: Record<string, number> = {
  779. class: 3, interface: 3, struct: 3, trait: 3, protocol: 3, enum: 3,
  780. method: 1, function: 1, property: 0, field: 0, variable: 0,
  781. };
  782. nodeIds.sort((a, b) => {
  783. const aRoot = rootSet.has(a) ? 10 : 0;
  784. const bRoot = rootSet.has(b) ? 10 : 0;
  785. const aKind = kindPriority[finalNodes.get(a)!.kind] ?? 0;
  786. const bKind = kindPriority[finalNodes.get(b)!.kind] ?? 0;
  787. return (bRoot + bKind) - (aRoot + aKind);
  788. });
  789. // Remove excess nodes (keep the highest-priority ones)
  790. for (const id of nodeIds.slice(maxPerFile)) {
  791. finalNodes.delete(id);
  792. }
  793. }
  794. // Non-production node cap: limit test/sample/integration/example files to
  795. // at most 15% of the budget. Many codebases have dozens of near-identical
  796. // test implementations (e.g., 6 Guard classes in integration tests) that
  797. // individually survive score dampening but collectively flood the result.
  798. // Test entry points are NOT exempt — they should be evicted too.
  799. if (!isTestQuery) {
  800. const maxNonProd = Math.max(3, Math.ceil(opts.maxNodes * 0.15));
  801. const nonProdIds: string[] = [];
  802. for (const [id, node] of finalNodes) {
  803. if (isTestFile(node.filePath)) {
  804. nonProdIds.push(id);
  805. }
  806. }
  807. if (nonProdIds.length > maxNonProd) {
  808. for (const id of nonProdIds.slice(maxNonProd)) {
  809. finalNodes.delete(id);
  810. // Also remove from roots — test file entry points shouldn't anchor results
  811. const rootIdx = roots.indexOf(id);
  812. if (rootIdx !== -1) roots.splice(rootIdx, 1);
  813. }
  814. }
  815. }
  816. // Re-filter edges after per-file and non-production caps
  817. finalEdges = finalEdges.filter(
  818. (e) => finalNodes.has(e.source) && finalNodes.has(e.target)
  819. );
  820. // Edge recovery: BFS with many entry points leaves most nodes disconnected.
  821. // Discover edges between already-selected nodes to recover connectivity.
  822. const recoveryKinds: EdgeKind[] = ['calls', 'extends', 'implements', 'references', 'overrides'];
  823. const recoveredEdges = this.queries.findEdgesBetweenNodes(
  824. [...finalNodes.keys()],
  825. recoveryKinds,
  826. );
  827. const existingEdgeKeys = new Set(
  828. finalEdges.map((e) => `${e.source}:${e.target}:${e.kind}`)
  829. );
  830. for (const edge of recoveredEdges) {
  831. const key = `${edge.source}:${edge.target}:${edge.kind}`;
  832. if (!existingEdgeKeys.has(key)) {
  833. finalEdges.push(edge);
  834. existingEdgeKeys.add(key);
  835. }
  836. }
  837. return { nodes: finalNodes, edges: finalEdges, roots };
  838. }
  839. /**
  840. * Get the source code for a node
  841. *
  842. * Reads the file and extracts the code between startLine and endLine.
  843. *
  844. * @param nodeId - ID of the node
  845. * @returns Code string or null if not found
  846. */
  847. async getCode(nodeId: string): Promise<string | null> {
  848. const node = this.queries.getNodeById(nodeId);
  849. if (!node) {
  850. return null;
  851. }
  852. return this.extractNodeCode(node);
  853. }
  854. /**
  855. * Extract code from a node's source file
  856. */
  857. private async extractNodeCode(node: Node): Promise<string | null> {
  858. const filePath = validatePathWithinRoot(this.projectRoot, node.filePath);
  859. if (!filePath || !fs.existsSync(filePath)) {
  860. return null;
  861. }
  862. try {
  863. const content = fs.readFileSync(filePath, 'utf-8');
  864. const lines = content.split('\n');
  865. // Extract lines (1-indexed to 0-indexed)
  866. const startIdx = Math.max(0, node.startLine - 1);
  867. const endIdx = Math.min(lines.length, node.endLine);
  868. return lines.slice(startIdx, endIdx).join('\n');
  869. } catch (error) {
  870. logDebug('Failed to extract code from node', { nodeId: node.id, filePath: node.filePath, error: String(error) });
  871. return null;
  872. }
  873. }
  874. /**
  875. * Get entry points from a subgraph (the root nodes)
  876. */
  877. private getEntryPoints(subgraph: Subgraph): Node[] {
  878. return subgraph.roots
  879. .map((id) => subgraph.nodes.get(id))
  880. .filter((n): n is Node => n !== undefined);
  881. }
  882. /**
  883. * Extract code blocks for key nodes in the subgraph
  884. */
  885. private async extractCodeBlocks(
  886. subgraph: Subgraph,
  887. maxBlocks: number,
  888. maxBlockSize: number
  889. ): Promise<CodeBlock[]> {
  890. const blocks: CodeBlock[] = [];
  891. // Prioritize entry points, then functions/methods
  892. const priorityNodes: Node[] = [];
  893. // First: entry points
  894. for (const id of subgraph.roots) {
  895. const node = subgraph.nodes.get(id);
  896. if (node) {
  897. priorityNodes.push(node);
  898. }
  899. }
  900. // Then: functions and methods
  901. for (const node of subgraph.nodes.values()) {
  902. if (!subgraph.roots.includes(node.id)) {
  903. if (node.kind === 'function' || node.kind === 'method') {
  904. priorityNodes.push(node);
  905. }
  906. }
  907. }
  908. // Then: classes
  909. for (const node of subgraph.nodes.values()) {
  910. if (!subgraph.roots.includes(node.id)) {
  911. if (node.kind === 'class') {
  912. priorityNodes.push(node);
  913. }
  914. }
  915. }
  916. // Extract code for priority nodes
  917. for (const node of priorityNodes) {
  918. if (blocks.length >= maxBlocks) break;
  919. const code = await this.extractNodeCode(node);
  920. if (code) {
  921. // Truncate if too long
  922. const truncated = code.length > maxBlockSize
  923. ? code.slice(0, maxBlockSize) + '\n// ... truncated ...'
  924. : code;
  925. blocks.push({
  926. content: truncated,
  927. filePath: node.filePath,
  928. startLine: node.startLine,
  929. endLine: node.endLine,
  930. language: node.language,
  931. node,
  932. });
  933. }
  934. }
  935. return blocks;
  936. }
  937. /**
  938. * Get unique files from a subgraph
  939. */
  940. private getRelatedFiles(subgraph: Subgraph): string[] {
  941. const files = new Set<string>();
  942. for (const node of subgraph.nodes.values()) {
  943. files.add(node.filePath);
  944. }
  945. return Array.from(files).sort();
  946. }
  947. /**
  948. * Generate a summary of the context
  949. */
  950. private generateSummary(_query: string, subgraph: Subgraph, entryPoints: Node[]): string {
  951. const nodeCount = subgraph.nodes.size;
  952. const edgeCount = subgraph.edges.length;
  953. const files = this.getRelatedFiles(subgraph);
  954. const entryPointNames = entryPoints
  955. .slice(0, 3)
  956. .map((n) => n.name)
  957. .join(', ');
  958. const remaining = entryPoints.length > 3 ? ` and ${entryPoints.length - 3} more` : '';
  959. return `Found ${nodeCount} relevant code symbols across ${files.length} files. ` +
  960. `Key entry points: ${entryPointNames}${remaining}. ` +
  961. `${edgeCount} relationships identified.`;
  962. }
  963. /**
  964. * Resolve import/export nodes to their actual definitions
  965. *
  966. * When search returns `import { TerminalPanel }`, users want the TerminalPanel
  967. * class definition, not the import statement. This follows the `imports` edge
  968. * to find and return the actual definition instead.
  969. *
  970. * @param results - Search results that may include import/export nodes
  971. * @returns Results with imports resolved to definitions where possible
  972. */
  973. private resolveImportsToDefinitions(results: SearchResult[]): SearchResult[] {
  974. const resolved: SearchResult[] = [];
  975. const seenIds = new Set<string>();
  976. for (const result of results) {
  977. const { node, score } = result;
  978. // If it's not an import/export, keep it as-is
  979. if (node.kind !== 'import' && node.kind !== 'export') {
  980. if (!seenIds.has(node.id)) {
  981. seenIds.add(node.id);
  982. resolved.push(result);
  983. }
  984. continue;
  985. }
  986. // For imports/exports, try to find what they reference
  987. // Imports have outgoing 'imports' edges to the definition
  988. // Exports have outgoing 'exports' edges to the definition
  989. const edgeKind = node.kind === 'import' ? 'imports' : 'exports';
  990. const outgoingEdges = this.queries.getOutgoingEdges(node.id, [edgeKind as EdgeKind]);
  991. let foundDefinition = false;
  992. for (const edge of outgoingEdges) {
  993. const targetNode = this.queries.getNodeById(edge.target);
  994. if (targetNode && !seenIds.has(targetNode.id)) {
  995. // Found the definition - use it instead of the import
  996. seenIds.add(targetNode.id);
  997. resolved.push({
  998. node: targetNode,
  999. score: score, // Preserve the original score
  1000. });
  1001. foundDefinition = true;
  1002. logDebug('Resolved import to definition', {
  1003. import: node.name,
  1004. definition: targetNode.name,
  1005. kind: targetNode.kind,
  1006. });
  1007. }
  1008. }
  1009. // If we couldn't resolve the import, skip it (it's low-value on its own)
  1010. if (!foundDefinition) {
  1011. logDebug('Skipping unresolved import', { name: node.name, file: node.filePath });
  1012. }
  1013. }
  1014. return resolved;
  1015. }
  1016. }
  1017. /**
  1018. * Create a context builder
  1019. */
  1020. export function createContextBuilder(
  1021. projectRoot: string,
  1022. queries: QueryBuilder,
  1023. traverser: GraphTraverser
  1024. ): ContextBuilder {
  1025. return new ContextBuilder(projectRoot, queries, traverser);
  1026. }
  1027. // Re-export formatter
  1028. export { formatContextAsMarkdown, formatContextAsJson } from './formatter';