symbol-lookup.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. /**
  2. * Module-qualified symbol lookup (`stage_apply::run`, `Session.request`,
  3. * `configurator/stage_apply`).
  4. *
  5. * Pinned because the lookup vocabulary is what makes codegraph useful
  6. * in workspaces with same-named symbols across modules — Rust
  7. * sub-pipelines, Python `__init__.py` packages, Java packages, etc.
  8. * See #173 for the original report: a `run` function in
  9. * `src/configurator/stage_apply.rs` was indexed but `stage_apply::run`
  10. * returned "not found" because (a) FTS strips colons to nothing,
  11. * leaving a useless query, and (b) `matchesSymbol` only understood
  12. * `.`-style qualifiers.
  13. */
  14. import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
  15. import * as fs from 'fs';
  16. import * as path from 'path';
  17. import * as os from 'os';
  18. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  19. import { matchesSymbol, lookupSymbolNodes, isQualifiedSymbol } from '../src/graph/symbol-lookup';
  20. import type { Node } from '../src/types';
  21. beforeAll(async () => {
  22. await initGrammars();
  23. await loadAllGrammars();
  24. });
  25. function hasSqliteBindings(): boolean {
  26. try {
  27. const { DatabaseSync } = require('node:sqlite');
  28. const db = new DatabaseSync(':memory:');
  29. db.close();
  30. return true;
  31. } catch {
  32. return false;
  33. }
  34. }
  35. const HAS_SQLITE = hasSqliteBindings();
  36. function tmpRoot(): string {
  37. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-symbol-lookup-'));
  38. }
  39. function rmTree(dir: string): void {
  40. if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
  41. }
  42. async function buildRustWorkspace(): Promise<string> {
  43. const root = tmpRoot();
  44. const cfgDir = path.join(root, 'src', 'configurator');
  45. fs.mkdirSync(cfgDir, { recursive: true });
  46. fs.writeFileSync(
  47. path.join(root, 'Cargo.toml'),
  48. `[package]\nname = "fixture"\nversion = "0.1.0"\nedition = "2021"\n[lib]\npath = "src/lib.rs"\n`
  49. );
  50. fs.writeFileSync(path.join(root, 'src', 'lib.rs'), `pub mod configurator;\npub mod scheduler;\n`);
  51. fs.writeFileSync(
  52. path.join(cfgDir, 'mod.rs'),
  53. `pub mod stage_apply;\npub mod stage_detect;\n`
  54. );
  55. fs.writeFileSync(
  56. path.join(cfgDir, 'stage_apply.rs'),
  57. `pub async fn run() -> Result<(), ()> {\n render_and_write();\n Ok(())\n}\n\nfn render_and_write() {}\n`
  58. );
  59. fs.writeFileSync(
  60. path.join(cfgDir, 'stage_detect.rs'),
  61. `pub async fn run() -> Result<(), ()> { Ok(()) }\n`
  62. );
  63. fs.writeFileSync(
  64. path.join(root, 'src', 'scheduler.rs'),
  65. `pub fn run_due_tasks() -> Result<(), ()> { Ok(()) }\n`
  66. );
  67. return root;
  68. }
  69. describe.skipIf(!HAS_SQLITE)('matchesSymbol — module-qualified lookups (#173)', () => {
  70. let projectRoot: string;
  71. let cg: any;
  72. let handler: any;
  73. // findSymbolMatches returns ALL ranked matches; [0] is the resolved/picked one.
  74. let findSymbolMatches: (cg: any, s: string) => any[];
  75. let findAllSymbols: (cg: any, s: string) => { nodes: any[]; note: string };
  76. beforeEach(async () => {
  77. projectRoot = await buildRustWorkspace();
  78. const CodeGraph = (await import('../src/index')).default;
  79. const { ToolHandler } = await import('../src/mcp/tools');
  80. cg = CodeGraph.initSync(projectRoot, {
  81. config: { include: ['**/*.rs'], exclude: [] },
  82. });
  83. await cg.indexAll();
  84. handler = new ToolHandler(cg);
  85. findSymbolMatches = (handler as any).findSymbolMatches.bind(handler);
  86. findAllSymbols = (handler as any).findAllSymbols.bind(handler);
  87. });
  88. afterEach(() => {
  89. handler?.closeAll();
  90. cg?.destroy();
  91. rmTree(projectRoot);
  92. });
  93. it('resolves `stage_apply::run` to the run in stage_apply.rs (not stage_detect.rs)', () => {
  94. const matches = findSymbolMatches(cg, 'stage_apply::run');
  95. expect(matches.length).toBeGreaterThan(0);
  96. expect(matches[0]!.name).toBe('run');
  97. // Every match must be in stage_apply.rs — never stage_detect.rs.
  98. for (const n of matches) expect(n.filePath).toMatch(/configurator\/stage_apply\.rs$/);
  99. });
  100. it('rejects `stage_apply::run` for the same-named function in a different module', () => {
  101. const all = findAllSymbols(cg, 'stage_apply::run');
  102. // All returned nodes must be in stage_apply.rs — never in stage_detect.rs
  103. for (const node of all.nodes) {
  104. expect(node.filePath).toMatch(/stage_apply\.rs$/);
  105. }
  106. expect(all.nodes.length).toBeGreaterThan(0);
  107. });
  108. it('resolves `configurator::stage_apply::run` (multi-level qualifier)', () => {
  109. const matches = findSymbolMatches(cg, 'configurator::stage_apply::run');
  110. expect(matches.length).toBeGreaterThan(0);
  111. expect(matches[0]!.name).toBe('run');
  112. expect(matches[0]!.filePath).toMatch(/configurator\/stage_apply\.rs$/);
  113. });
  114. it('resolves `crate::configurator::stage_apply::run` (Rust path prefix stripped)', () => {
  115. const matches = findSymbolMatches(cg, 'crate::configurator::stage_apply::run');
  116. expect(matches.length).toBeGreaterThan(0);
  117. expect(matches[0]!.filePath).toMatch(/configurator\/stage_apply\.rs$/);
  118. });
  119. it('resolves `configurator/stage_apply` (slash qualifier)', () => {
  120. const matches = findSymbolMatches(cg, 'configurator/stage_apply/run');
  121. expect(matches.length).toBeGreaterThan(0);
  122. expect(matches[0]!.filePath).toMatch(/configurator\/stage_apply\.rs$/);
  123. });
  124. it('does not silently collide bare `run` with `run_due_tasks`', () => {
  125. const matches = findSymbolMatches(cg, 'run');
  126. expect(matches.length).toBeGreaterThan(0);
  127. // Whatever it picks, every match must be an exact-name match, not a partial.
  128. for (const n of matches) expect(n.name).toBe('run');
  129. });
  130. it('aggregates all bare-name `run` matches across modules', () => {
  131. const all = findAllSymbols(cg, 'run');
  132. const names = all.nodes.map((n: any) => n.name);
  133. expect(names.every((n: string) => n === 'run')).toBe(true);
  134. expect(all.nodes.length).toBeGreaterThanOrEqual(2); // stage_apply + stage_detect
  135. // The note should call out the ambiguity.
  136. expect(all.note).toMatch(/Aggregated|symbols named "run"/);
  137. });
  138. it('still returns nothing for genuinely unknown qualified lookups', () => {
  139. const matches = findSymbolMatches(cg, 'stage_apply::nonexistent_fn');
  140. expect(matches.length).toBe(0);
  141. });
  142. it('findAllSymbols rejects a fuzzy-only bare prefix with a suggestion (#1473)', () => {
  143. expect(cg.getNodesByName('run_due')).toEqual([]);
  144. expect(cg.searchNodes('run_due').length).toBeGreaterThan(0);
  145. const all = findAllSymbols(cg, 'run_due');
  146. expect(all.nodes).toEqual([]);
  147. expect(all.note).toMatch(/Did you mean:.*run_due_tasks/);
  148. });
  149. it('findAllSymbols rejects an unknown qualifier even when the bare tail exists (#173)', () => {
  150. expect(cg.getNodesByName('run').length).toBeGreaterThan(0);
  151. expect(findAllSymbols(cg, 'missing::run').nodes).toEqual([]);
  152. });
  153. it('preserves codegraph_node file-basename lookup (#1473)', () => {
  154. expect(cg.getNodesByName('stage_apply')).toEqual([]);
  155. const matches = findSymbolMatches(cg, 'stage_apply');
  156. expect(matches.length).toBeGreaterThan(0);
  157. expect(matches[0]!.filePath).toMatch(/configurator\/stage_apply\.rs$/);
  158. });
  159. it('codegraph_node with a `file` hint pins an overloaded name to that file', async () => {
  160. // `run` is defined in BOTH stage_apply.rs and stage_detect.rs. A bare lookup
  161. // returns both; the `file` hint narrows to the one the caller saw in a trail.
  162. const res = await handler.execute('codegraph_node', {
  163. symbol: 'run',
  164. includeCode: true,
  165. file: 'stage_detect.rs',
  166. });
  167. const text = res.content?.[0]?.text ?? '';
  168. expect(text).toMatch(/stage_detect\.rs/);
  169. expect(text).not.toMatch(/stage_apply\.rs/);
  170. });
  171. });
  172. describe.skipIf(!HAS_SQLITE)('matchesSymbol — dotted lookups (regression for #173 fix)', () => {
  173. let projectRoot: string;
  174. let cg: any;
  175. let handler: any;
  176. let findSymbolMatches: (cg: any, s: string) => any[];
  177. beforeEach(async () => {
  178. projectRoot = tmpRoot();
  179. const src = path.join(projectRoot, 'src');
  180. fs.mkdirSync(src, { recursive: true });
  181. fs.writeFileSync(
  182. path.join(src, 'session.ts'),
  183. `export class Session {\n request(): void { fetch('x'); }\n}\nexport function request(): void {}\n`
  184. );
  185. const CodeGraph = (await import('../src/index')).default;
  186. const { ToolHandler } = await import('../src/mcp/tools');
  187. cg = CodeGraph.initSync(projectRoot, {
  188. config: { include: ['src/**/*.ts'], exclude: [] },
  189. });
  190. await cg.indexAll();
  191. handler = new ToolHandler(cg);
  192. findSymbolMatches = (handler as any).findSymbolMatches.bind(handler);
  193. });
  194. afterEach(() => {
  195. handler?.closeAll();
  196. cg?.destroy();
  197. rmTree(projectRoot);
  198. });
  199. it('`Session.request` resolves to the method, not the bare function', () => {
  200. const matches = findSymbolMatches(cg, 'Session.request');
  201. expect(matches.length).toBeGreaterThan(0);
  202. expect(matches[0]!.kind).toBe('method');
  203. expect(matches[0]!.qualifiedName).toContain('Session::request');
  204. });
  205. it('codegraph_node on an ambiguous bare name returns ALL overloads with bodies (no guess)', async () => {
  206. // `request` is BOTH a method (Session.request) and a free function. The old
  207. // behavior returned one + a dead-end "Others:" note, forcing a Read to get
  208. // the other overload; now both bodies come back in one call.
  209. const res = await handler.execute('codegraph_node', { symbol: 'request', includeCode: true });
  210. const text = res.content?.[0]?.text ?? '';
  211. expect(text).toContain('2 definitions named "request"');
  212. // Both definitions are rendered (method + function), each with a Location.
  213. expect(text).toMatch(/\(method\)/);
  214. expect(text).toMatch(/\(function\)/);
  215. expect((text.match(/\*\*Location:\*\*/g) || []).length).toBeGreaterThanOrEqual(2);
  216. });
  217. });
  218. /**
  219. * One resolution path for every verb that takes a symbol NAME.
  220. *
  221. * `callers` / `callees` / `impact` used to carry their own filter, comparing
  222. * the query against the BARE name only:
  223. *
  224. * node.name === symbol || node.name.endsWith('.' + symbol)
  225. *
  226. * which fails in two opposite directions at once. A bare name matched every
  227. * same-named symbol in the repository and their results were merged under one
  228. * heading with nothing saying they were different symbols; a qualified name
  229. * could never equal a bare `node.name`, so every candidate failed the filter
  230. * and the code fell through to an arbitrary top-of-FTS hit — or reported "not
  231. * found" for a symbol that plainly exists. Both now go through
  232. * `lookupSymbolNodes`.
  233. */
  234. function fakeNode(over: Partial<Node>): Node {
  235. return {
  236. id: 'n1', kind: 'function', name: 'group', qualifiedName: 'group',
  237. filePath: 'lib/format.ex', language: 'typescript',
  238. startLine: 1, endLine: 2, startColumn: 0, endColumn: 0, updatedAt: 0,
  239. ...over,
  240. } as Node;
  241. }
  242. describe('matchesSymbol — containers whose own name contains a separator', () => {
  243. // Splitting on EVERY separator assumes no scope component contains one. That
  244. // is false for any language whose module names are themselves dotted, and
  245. // there the stored qualifiedName (`A.B::c`) can never equal the split-and-
  246. // rejoined query spelling (`A::B::c`) — so a perfectly precise qualified
  247. // query resolved to nothing.
  248. const node = fakeNode({ name: 'group', qualifiedName: 'AppWeb.Format::group' });
  249. it('matches a dotted module qualifier written with dots', () => {
  250. expect(matchesSymbol(node, 'AppWeb.Format.group')).toBe(true);
  251. });
  252. it('matches the same query written with the extractor separator', () => {
  253. expect(matchesSymbol(node, 'AppWeb.Format::group')).toBe(true);
  254. });
  255. it('matches a partial container suffix on a separator boundary', () => {
  256. expect(matchesSymbol(node, 'Format.group')).toBe(true);
  257. });
  258. it('does not match a container that merely shares a suffix substring', () => {
  259. // `ebFormat.group` is not a boundary-aligned suffix of `AppWeb.Format.group`.
  260. expect(matchesSymbol(node, 'ebFormat.group')).toBe(false);
  261. });
  262. it('does not match a different container', () => {
  263. expect(matchesSymbol(node, 'Other.Format.group')).toBe(false);
  264. });
  265. it('still requires the last part to be the node name', () => {
  266. expect(matchesSymbol(node, 'AppWeb.Format.other')).toBe(false);
  267. });
  268. it('classifies bare vs qualified queries', () => {
  269. expect(isQualifiedSymbol('group')).toBe(false);
  270. expect(isQualifiedSymbol('A.B.group')).toBe(true);
  271. expect(isQualifiedSymbol('A::group')).toBe(true);
  272. expect(isQualifiedSymbol('a/b')).toBe(true);
  273. });
  274. });
  275. describe.skipIf(!HAS_SQLITE)('lookupSymbolNodes — the shared path used by callers/callees/impact', () => {
  276. let projectRoot: string;
  277. let cg: any;
  278. beforeEach(async () => {
  279. projectRoot = tmpRoot();
  280. const client = path.join(projectRoot, 'client');
  281. const pkg = path.join(projectRoot, 'pkg', 'fmtutil');
  282. fs.mkdirSync(client, { recursive: true });
  283. fs.mkdirSync(pkg, { recursive: true });
  284. // The SAME short name defined in two languages — the collision profile of a
  285. // polyglot repository, where the colliding identifiers are the common ones.
  286. fs.writeFileSync(
  287. path.join(client, 'chart.ts'),
  288. `export function group(rows: number[][]): number[][] { return rows; }\n`
  289. );
  290. fs.writeFileSync(
  291. path.join(client, 'Editor.tsx'),
  292. `import { group } from './chart';\nexport function Editor(r: number[][]) { return group(r); }\n`
  293. );
  294. fs.writeFileSync(
  295. path.join(pkg, 'format.py'),
  296. `def group(items, size):\n return items\n`
  297. );
  298. fs.writeFileSync(
  299. path.join(projectRoot, 'pkg', 'planner.py'),
  300. `from pkg.fmtutil.format import group\n\ndef plan_a(items): return group(items, 3)\ndef plan_b(items): return group(items, 5)\n`
  301. );
  302. const CodeGraph = (await import('../src/index')).default;
  303. cg = CodeGraph.initSync(projectRoot, {
  304. config: { include: ['**/*.ts', '**/*.tsx', '**/*.py'], exclude: [] },
  305. });
  306. await cg.indexAll();
  307. });
  308. afterEach(() => {
  309. cg?.destroy();
  310. rmTree(projectRoot);
  311. });
  312. it('a bare name resolves to EVERY definition and reports the ambiguity', () => {
  313. const { nodes, ambiguous } = lookupSymbolNodes(cg, 'group');
  314. const defs = nodes.filter((n) => n.kind === 'function');
  315. expect(defs.length).toBe(2);
  316. expect(new Set(defs.map((n) => n.language))).toEqual(new Set(['typescript', 'python']));
  317. // The flag is what stops an aggregate being presented as one symbol's answer.
  318. expect(ambiguous).toBe(true);
  319. });
  320. it('a qualified name selects one definition and is no longer ambiguous', () => {
  321. const { nodes, ambiguous } = lookupSymbolNodes(cg, 'chart.group');
  322. expect(nodes.length).toBe(1);
  323. expect(nodes[0]!.language).toBe('typescript');
  324. expect(nodes[0]!.filePath).toMatch(/chart\.ts$/);
  325. expect(ambiguous).toBe(false);
  326. });
  327. it('a qualified name selects the other language just as precisely', () => {
  328. const { nodes } = lookupSymbolNodes(cg, 'fmtutil.format.group');
  329. expect(nodes.length).toBe(1);
  330. expect(nodes[0]!.language).toBe('python');
  331. expect(nodes[0]!.filePath).toMatch(/fmtutil\/format\.py$/);
  332. });
  333. it('resolves a qualified name even when full-text search finds nothing for it', () => {
  334. // FTS tokenises separators away, so a qualified query can score zero hits
  335. // while the symbol plainly exists. Resolution consults the exact-name index
  336. // first precisely so it cannot depend on search ranking — this is the
  337. // "reported not found for a symbol that exists" half of the defect.
  338. const fts = cg.searchNodes('fmtutil.format.group', { limit: 50 });
  339. const { nodes } = lookupSymbolNodes(cg, 'fmtutil.format.group');
  340. expect(nodes.length).toBe(1);
  341. expect(nodes[0]!.filePath).toMatch(/format\.py$/);
  342. // Guard the premise: if FTS ever starts answering this, the test above stops
  343. // proving independence and should be re-pointed at a query that still fails.
  344. expect(Array.isArray(fts)).toBe(true);
  345. });
  346. it('callers of a qualified name exclude the other language entirely', () => {
  347. const { nodes } = lookupSymbolNodes(cg, 'chart.group');
  348. const callerFiles = nodes.flatMap((n: any) =>
  349. cg.getCallers(n.id).map((c: any) => c.node.filePath)
  350. );
  351. expect(callerFiles.length).toBeGreaterThan(0);
  352. for (const f of callerFiles) expect(f).not.toMatch(/\.py$/);
  353. });
  354. it('callers of the bare name span both languages — the union that must be disclosed', () => {
  355. const { nodes, ambiguous } = lookupSymbolNodes(cg, 'group');
  356. const callerFiles = nodes.flatMap((n: any) =>
  357. cg.getCallers(n.id).map((c: any) => c.node.filePath)
  358. );
  359. expect(ambiguous).toBe(true);
  360. expect(callerFiles.some((f: string) => f.endsWith('.py'))).toBe(true);
  361. expect(callerFiles.some((f: string) => f.endsWith('.tsx'))).toBe(true);
  362. });
  363. it('an unknown qualified name resolves to nothing rather than a fuzzy hit', () => {
  364. const { nodes } = lookupSymbolNodes(cg, 'chart.nonexistent_fn');
  365. expect(nodes.length).toBe(0);
  366. });
  367. it.each(['grou', 'Group'])('rejects fuzzy-only bare name "%s" (#1473)', (symbol) => {
  368. expect(cg.getNodesByName(symbol)).toEqual([]);
  369. expect(cg.searchNodes(symbol).length).toBeGreaterThan(0);
  370. expect(lookupSymbolNodes(cg, symbol)).toEqual({ nodes: [], ambiguous: false });
  371. });
  372. it('rejects an unknown qualifier even when the bare tail exists (#173)', () => {
  373. expect(cg.getNodesByName('group').length).toBeGreaterThan(0);
  374. expect(lookupSymbolNodes(cg, 'missing.group')).toEqual({ nodes: [], ambiguous: false });
  375. });
  376. });