symbol-lookup.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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('codegraph_node with a `file` hint pins an overloaded name to that file', async () => {
  143. // `run` is defined in BOTH stage_apply.rs and stage_detect.rs. A bare lookup
  144. // returns both; the `file` hint narrows to the one the caller saw in a trail.
  145. const res = await handler.execute('codegraph_node', {
  146. symbol: 'run',
  147. includeCode: true,
  148. file: 'stage_detect.rs',
  149. });
  150. const text = res.content?.[0]?.text ?? '';
  151. expect(text).toMatch(/stage_detect\.rs/);
  152. expect(text).not.toMatch(/stage_apply\.rs/);
  153. });
  154. });
  155. describe.skipIf(!HAS_SQLITE)('matchesSymbol — dotted lookups (regression for #173 fix)', () => {
  156. let projectRoot: string;
  157. let cg: any;
  158. let handler: any;
  159. let findSymbolMatches: (cg: any, s: string) => any[];
  160. beforeEach(async () => {
  161. projectRoot = tmpRoot();
  162. const src = path.join(projectRoot, 'src');
  163. fs.mkdirSync(src, { recursive: true });
  164. fs.writeFileSync(
  165. path.join(src, 'session.ts'),
  166. `export class Session {\n request(): void { fetch('x'); }\n}\nexport function request(): void {}\n`
  167. );
  168. const CodeGraph = (await import('../src/index')).default;
  169. const { ToolHandler } = await import('../src/mcp/tools');
  170. cg = CodeGraph.initSync(projectRoot, {
  171. config: { include: ['src/**/*.ts'], exclude: [] },
  172. });
  173. await cg.indexAll();
  174. handler = new ToolHandler(cg);
  175. findSymbolMatches = (handler as any).findSymbolMatches.bind(handler);
  176. });
  177. afterEach(() => {
  178. handler?.closeAll();
  179. cg?.destroy();
  180. rmTree(projectRoot);
  181. });
  182. it('`Session.request` resolves to the method, not the bare function', () => {
  183. const matches = findSymbolMatches(cg, 'Session.request');
  184. expect(matches.length).toBeGreaterThan(0);
  185. expect(matches[0]!.kind).toBe('method');
  186. expect(matches[0]!.qualifiedName).toContain('Session::request');
  187. });
  188. it('codegraph_node on an ambiguous bare name returns ALL overloads with bodies (no guess)', async () => {
  189. // `request` is BOTH a method (Session.request) and a free function. The old
  190. // behavior returned one + a dead-end "Others:" note, forcing a Read to get
  191. // the other overload; now both bodies come back in one call.
  192. const res = await handler.execute('codegraph_node', { symbol: 'request', includeCode: true });
  193. const text = res.content?.[0]?.text ?? '';
  194. expect(text).toContain('2 definitions named "request"');
  195. // Both definitions are rendered (method + function), each with a Location.
  196. expect(text).toMatch(/\(method\)/);
  197. expect(text).toMatch(/\(function\)/);
  198. expect((text.match(/\*\*Location:\*\*/g) || []).length).toBeGreaterThanOrEqual(2);
  199. });
  200. });
  201. /**
  202. * One resolution path for every verb that takes a symbol NAME.
  203. *
  204. * `callers` / `callees` / `impact` used to carry their own filter, comparing
  205. * the query against the BARE name only:
  206. *
  207. * node.name === symbol || node.name.endsWith('.' + symbol)
  208. *
  209. * which fails in two opposite directions at once. A bare name matched every
  210. * same-named symbol in the repository and their results were merged under one
  211. * heading with nothing saying they were different symbols; a qualified name
  212. * could never equal a bare `node.name`, so every candidate failed the filter
  213. * and the code fell through to an arbitrary top-of-FTS hit — or reported "not
  214. * found" for a symbol that plainly exists. Both now go through
  215. * `lookupSymbolNodes`.
  216. */
  217. function fakeNode(over: Partial<Node>): Node {
  218. return {
  219. id: 'n1', kind: 'function', name: 'group', qualifiedName: 'group',
  220. filePath: 'lib/format.ex', language: 'typescript',
  221. startLine: 1, endLine: 2, startColumn: 0, endColumn: 0, updatedAt: 0,
  222. ...over,
  223. } as Node;
  224. }
  225. describe('matchesSymbol — containers whose own name contains a separator', () => {
  226. // Splitting on EVERY separator assumes no scope component contains one. That
  227. // is false for any language whose module names are themselves dotted, and
  228. // there the stored qualifiedName (`A.B::c`) can never equal the split-and-
  229. // rejoined query spelling (`A::B::c`) — so a perfectly precise qualified
  230. // query resolved to nothing.
  231. const node = fakeNode({ name: 'group', qualifiedName: 'AppWeb.Format::group' });
  232. it('matches a dotted module qualifier written with dots', () => {
  233. expect(matchesSymbol(node, 'AppWeb.Format.group')).toBe(true);
  234. });
  235. it('matches the same query written with the extractor separator', () => {
  236. expect(matchesSymbol(node, 'AppWeb.Format::group')).toBe(true);
  237. });
  238. it('matches a partial container suffix on a separator boundary', () => {
  239. expect(matchesSymbol(node, 'Format.group')).toBe(true);
  240. });
  241. it('does not match a container that merely shares a suffix substring', () => {
  242. // `ebFormat.group` is not a boundary-aligned suffix of `AppWeb.Format.group`.
  243. expect(matchesSymbol(node, 'ebFormat.group')).toBe(false);
  244. });
  245. it('does not match a different container', () => {
  246. expect(matchesSymbol(node, 'Other.Format.group')).toBe(false);
  247. });
  248. it('still requires the last part to be the node name', () => {
  249. expect(matchesSymbol(node, 'AppWeb.Format.other')).toBe(false);
  250. });
  251. it('classifies bare vs qualified queries', () => {
  252. expect(isQualifiedSymbol('group')).toBe(false);
  253. expect(isQualifiedSymbol('A.B.group')).toBe(true);
  254. expect(isQualifiedSymbol('A::group')).toBe(true);
  255. expect(isQualifiedSymbol('a/b')).toBe(true);
  256. });
  257. });
  258. describe.skipIf(!HAS_SQLITE)('lookupSymbolNodes — the shared path used by callers/callees/impact', () => {
  259. let projectRoot: string;
  260. let cg: any;
  261. beforeEach(async () => {
  262. projectRoot = tmpRoot();
  263. const client = path.join(projectRoot, 'client');
  264. const pkg = path.join(projectRoot, 'pkg', 'fmtutil');
  265. fs.mkdirSync(client, { recursive: true });
  266. fs.mkdirSync(pkg, { recursive: true });
  267. // The SAME short name defined in two languages — the collision profile of a
  268. // polyglot repository, where the colliding identifiers are the common ones.
  269. fs.writeFileSync(
  270. path.join(client, 'chart.ts'),
  271. `export function group(rows: number[][]): number[][] { return rows; }\n`
  272. );
  273. fs.writeFileSync(
  274. path.join(client, 'Editor.tsx'),
  275. `import { group } from './chart';\nexport function Editor(r: number[][]) { return group(r); }\n`
  276. );
  277. fs.writeFileSync(
  278. path.join(pkg, 'format.py'),
  279. `def group(items, size):\n return items\n`
  280. );
  281. fs.writeFileSync(
  282. path.join(projectRoot, 'pkg', 'planner.py'),
  283. `from pkg.fmtutil.format import group\n\ndef plan_a(items): return group(items, 3)\ndef plan_b(items): return group(items, 5)\n`
  284. );
  285. const CodeGraph = (await import('../src/index')).default;
  286. cg = CodeGraph.initSync(projectRoot, {
  287. config: { include: ['**/*.ts', '**/*.tsx', '**/*.py'], exclude: [] },
  288. });
  289. await cg.indexAll();
  290. });
  291. afterEach(() => {
  292. cg?.destroy();
  293. rmTree(projectRoot);
  294. });
  295. it('a bare name resolves to EVERY definition and reports the ambiguity', () => {
  296. const { nodes, ambiguous } = lookupSymbolNodes(cg, 'group');
  297. const defs = nodes.filter((n) => n.kind === 'function');
  298. expect(defs.length).toBe(2);
  299. expect(new Set(defs.map((n) => n.language))).toEqual(new Set(['typescript', 'python']));
  300. // The flag is what stops an aggregate being presented as one symbol's answer.
  301. expect(ambiguous).toBe(true);
  302. });
  303. it('a qualified name selects one definition and is no longer ambiguous', () => {
  304. const { nodes, ambiguous } = lookupSymbolNodes(cg, 'chart.group');
  305. expect(nodes.length).toBe(1);
  306. expect(nodes[0]!.language).toBe('typescript');
  307. expect(nodes[0]!.filePath).toMatch(/chart\.ts$/);
  308. expect(ambiguous).toBe(false);
  309. });
  310. it('a qualified name selects the other language just as precisely', () => {
  311. const { nodes } = lookupSymbolNodes(cg, 'fmtutil.format.group');
  312. expect(nodes.length).toBe(1);
  313. expect(nodes[0]!.language).toBe('python');
  314. expect(nodes[0]!.filePath).toMatch(/fmtutil\/format\.py$/);
  315. });
  316. it('resolves a qualified name even when full-text search finds nothing for it', () => {
  317. // FTS tokenises separators away, so a qualified query can score zero hits
  318. // while the symbol plainly exists. Resolution consults the exact-name index
  319. // first precisely so it cannot depend on search ranking — this is the
  320. // "reported not found for a symbol that exists" half of the defect.
  321. const fts = cg.searchNodes('fmtutil.format.group', { limit: 50 });
  322. const { nodes } = lookupSymbolNodes(cg, 'fmtutil.format.group');
  323. expect(nodes.length).toBe(1);
  324. expect(nodes[0]!.filePath).toMatch(/format\.py$/);
  325. // Guard the premise: if FTS ever starts answering this, the test above stops
  326. // proving independence and should be re-pointed at a query that still fails.
  327. expect(Array.isArray(fts)).toBe(true);
  328. });
  329. it('callers of a qualified name exclude the other language entirely', () => {
  330. const { nodes } = lookupSymbolNodes(cg, 'chart.group');
  331. const callerFiles = nodes.flatMap((n: any) =>
  332. cg.getCallers(n.id).map((c: any) => c.node.filePath)
  333. );
  334. expect(callerFiles.length).toBeGreaterThan(0);
  335. for (const f of callerFiles) expect(f).not.toMatch(/\.py$/);
  336. });
  337. it('callers of the bare name span both languages — the union that must be disclosed', () => {
  338. const { nodes, ambiguous } = lookupSymbolNodes(cg, 'group');
  339. const callerFiles = nodes.flatMap((n: any) =>
  340. cg.getCallers(n.id).map((c: any) => c.node.filePath)
  341. );
  342. expect(ambiguous).toBe(true);
  343. expect(callerFiles.some((f: string) => f.endsWith('.py'))).toBe(true);
  344. expect(callerFiles.some((f: string) => f.endsWith('.tsx'))).toBe(true);
  345. });
  346. it('an unknown qualified name resolves to nothing rather than a fuzzy hit', () => {
  347. const { nodes } = lookupSymbolNodes(cg, 'chart.nonexistent_fn');
  348. expect(nodes.length).toBe(0);
  349. });
  350. });