resolution.test.ts 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  1. /**
  2. * Resolution Module Tests
  3. *
  4. * Tests for Phase 3: Reference Resolution
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { Node, UnresolvedReference } from '../src/types';
  12. import { ReferenceResolver, createResolver, ResolutionContext } from '../src/resolution';
  13. import { matchReference } from '../src/resolution/name-matcher';
  14. import { resolveImportPath, extractImportMappings } from '../src/resolution/import-resolver';
  15. import { detectFrameworks, getAllFrameworkResolvers } from '../src/resolution/frameworks';
  16. import { QueryBuilder } from '../src/db/queries';
  17. import { DatabaseConnection } from '../src/db';
  18. describe('Resolution Module', () => {
  19. let tempDir: string;
  20. let cg: CodeGraph;
  21. beforeEach(() => {
  22. // Create temp directory
  23. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-resolution-test-'));
  24. });
  25. afterEach(() => {
  26. // Clean up
  27. if (cg) {
  28. cg.destroy();
  29. } else if (fs.existsSync(tempDir)) {
  30. fs.rmSync(tempDir, { recursive: true });
  31. }
  32. });
  33. describe('Name Matcher', () => {
  34. it('should match exact name references', () => {
  35. // Create a mock context
  36. const mockNodes: Node[] = [
  37. {
  38. id: 'func:test.ts:myFunction:10',
  39. kind: 'function',
  40. name: 'myFunction',
  41. qualifiedName: 'test.ts::myFunction',
  42. filePath: 'test.ts',
  43. language: 'typescript',
  44. startLine: 10,
  45. endLine: 20,
  46. startColumn: 0,
  47. endColumn: 0,
  48. updatedAt: Date.now(),
  49. },
  50. ];
  51. const context: ResolutionContext = {
  52. getNodesInFile: () => mockNodes,
  53. getNodesByName: (name) => mockNodes.filter((n) => n.name === name),
  54. getNodesByQualifiedName: () => [],
  55. getNodesByKind: () => [],
  56. fileExists: () => true,
  57. readFile: () => null,
  58. getProjectRoot: () => '/test',
  59. getAllFiles: () => ['test.ts'],
  60. };
  61. const ref = {
  62. fromNodeId: 'caller:main.ts:caller:5',
  63. referenceName: 'myFunction',
  64. referenceKind: 'calls' as const,
  65. line: 5,
  66. column: 10,
  67. filePath: 'main.ts',
  68. language: 'typescript' as const,
  69. };
  70. const result = matchReference(ref, context);
  71. expect(result).not.toBeNull();
  72. expect(result?.targetNodeId).toBe('func:test.ts:myFunction:10');
  73. expect(result?.resolvedBy).toBe('exact-match');
  74. });
  75. it('should prefer same-module candidates over cross-module matches', () => {
  76. // Simulates a Python monorepo where multiple apps define navigate()
  77. const candidateA: Node = {
  78. id: 'func:apps/app_a/src/server.py:navigate:10',
  79. kind: 'function',
  80. name: 'navigate',
  81. qualifiedName: 'apps/app_a/src/server.py::navigate',
  82. filePath: 'apps/app_a/src/server.py',
  83. language: 'python',
  84. startLine: 10,
  85. endLine: 20,
  86. startColumn: 0,
  87. endColumn: 0,
  88. updatedAt: Date.now(),
  89. };
  90. const candidateB: Node = {
  91. id: 'func:apps/app_b/src/server.py:navigate:15',
  92. kind: 'function',
  93. name: 'navigate',
  94. qualifiedName: 'apps/app_b/src/server.py::navigate',
  95. filePath: 'apps/app_b/src/server.py',
  96. language: 'python',
  97. startLine: 15,
  98. endLine: 25,
  99. startColumn: 0,
  100. endColumn: 0,
  101. updatedAt: Date.now(),
  102. };
  103. const context: ResolutionContext = {
  104. getNodesInFile: () => [],
  105. getNodesByName: (name) => name === 'navigate' ? [candidateA, candidateB] : [],
  106. getNodesByQualifiedName: () => [],
  107. getNodesByKind: () => [],
  108. fileExists: () => true,
  109. readFile: () => null,
  110. getProjectRoot: () => '/test',
  111. getAllFiles: () => [],
  112. getNodesByLowerName: () => [],
  113. getImportMappings: () => [],
  114. };
  115. // Reference from app_a should resolve to app_a's navigate, not app_b's
  116. const ref = {
  117. fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
  118. referenceName: 'navigate',
  119. referenceKind: 'calls' as const,
  120. line: 5,
  121. column: 10,
  122. filePath: 'apps/app_a/src/handler.py',
  123. language: 'python' as const,
  124. };
  125. const result = matchReference(ref, context);
  126. expect(result).not.toBeNull();
  127. expect(result?.targetNodeId).toBe('func:apps/app_a/src/server.py:navigate:10');
  128. expect(result?.resolvedBy).toBe('exact-match');
  129. });
  130. it('should lower confidence for cross-module exact matches', () => {
  131. // Only one candidate but in a completely different module
  132. const candidates: Node[] = [
  133. {
  134. id: 'func:apps/app_b/src/server.py:navigate:10',
  135. kind: 'function',
  136. name: 'navigate',
  137. qualifiedName: 'apps/app_b/src/server.py::navigate',
  138. filePath: 'apps/app_b/src/server.py',
  139. language: 'python',
  140. startLine: 10,
  141. endLine: 20,
  142. startColumn: 0,
  143. endColumn: 0,
  144. updatedAt: Date.now(),
  145. },
  146. {
  147. id: 'func:apps/app_c/src/server.py:navigate:10',
  148. kind: 'function',
  149. name: 'navigate',
  150. qualifiedName: 'apps/app_c/src/server.py::navigate',
  151. filePath: 'apps/app_c/src/server.py',
  152. language: 'python',
  153. startLine: 10,
  154. endLine: 20,
  155. startColumn: 0,
  156. endColumn: 0,
  157. updatedAt: Date.now(),
  158. },
  159. ];
  160. const context: ResolutionContext = {
  161. getNodesInFile: () => [],
  162. getNodesByName: (name) => name === 'navigate' ? candidates : [],
  163. getNodesByQualifiedName: () => [],
  164. getNodesByKind: () => [],
  165. fileExists: () => true,
  166. readFile: () => null,
  167. getProjectRoot: () => '/test',
  168. getAllFiles: () => [],
  169. getNodesByLowerName: () => [],
  170. getImportMappings: () => [],
  171. };
  172. // Reference from app_a — neither candidate is in the same module
  173. const ref = {
  174. fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
  175. referenceName: 'navigate',
  176. referenceKind: 'calls' as const,
  177. line: 5,
  178. column: 10,
  179. filePath: 'apps/app_a/src/handler.py',
  180. language: 'python' as const,
  181. };
  182. const result = matchReference(ref, context);
  183. // Should still resolve but with low confidence
  184. expect(result).not.toBeNull();
  185. expect(result?.confidence).toBeLessThanOrEqual(0.4);
  186. });
  187. it('should match qualified name references', () => {
  188. const mockClassNode: Node = {
  189. id: 'class:user.ts:User:5',
  190. kind: 'class',
  191. name: 'User',
  192. qualifiedName: 'user.ts::User',
  193. filePath: 'user.ts',
  194. language: 'typescript',
  195. startLine: 5,
  196. endLine: 30,
  197. startColumn: 0,
  198. endColumn: 0,
  199. updatedAt: Date.now(),
  200. };
  201. const mockMethodNode: Node = {
  202. id: 'method:user.ts:User.save:15',
  203. kind: 'method',
  204. name: 'save',
  205. qualifiedName: 'user.ts::User::save',
  206. filePath: 'user.ts',
  207. language: 'typescript',
  208. startLine: 15,
  209. endLine: 25,
  210. startColumn: 0,
  211. endColumn: 0,
  212. updatedAt: Date.now(),
  213. };
  214. const context: ResolutionContext = {
  215. getNodesInFile: (fp) => fp === 'user.ts' ? [mockClassNode, mockMethodNode] : [],
  216. getNodesByName: (name) => {
  217. if (name === 'User') return [mockClassNode];
  218. if (name === 'save') return [mockMethodNode];
  219. return [];
  220. },
  221. getNodesByQualifiedName: (qn) => {
  222. if (qn === 'user.ts::User::save') return [mockMethodNode];
  223. return [];
  224. },
  225. getNodesByKind: () => [],
  226. fileExists: () => true,
  227. readFile: () => null,
  228. getProjectRoot: () => '/test',
  229. getAllFiles: () => ['user.ts'],
  230. };
  231. const ref = {
  232. fromNodeId: 'caller:main.ts:main:5',
  233. referenceName: 'User.save',
  234. referenceKind: 'calls' as const,
  235. line: 5,
  236. column: 10,
  237. filePath: 'main.ts',
  238. language: 'typescript' as const,
  239. };
  240. const result = matchReference(ref, context);
  241. expect(result).not.toBeNull();
  242. expect(result?.targetNodeId).toBe('method:user.ts:User.save:15');
  243. });
  244. });
  245. describe('Import Resolver', () => {
  246. it('should resolve relative import paths', () => {
  247. const context: ResolutionContext = {
  248. getNodesInFile: () => [],
  249. getNodesByName: () => [],
  250. getNodesByQualifiedName: () => [],
  251. getNodesByKind: () => [],
  252. fileExists: (p) => p === 'src/components/utils.ts' || p === 'src/components/utils/index.ts',
  253. readFile: () => null,
  254. getProjectRoot: () => '',
  255. getAllFiles: () => ['src/components/utils.ts', 'src/components/utils/index.ts'],
  256. };
  257. const result = resolveImportPath(
  258. './utils',
  259. 'src/components/Button.ts',
  260. 'typescript',
  261. context
  262. );
  263. expect(result).toBe('src/components/utils.ts');
  264. });
  265. it('should resolve parent directory imports', () => {
  266. const context: ResolutionContext = {
  267. getNodesInFile: () => [],
  268. getNodesByName: () => [],
  269. getNodesByQualifiedName: () => [],
  270. getNodesByKind: () => [],
  271. fileExists: (p) => p === 'src/helpers.ts' || p === 'src/helpers/index.ts',
  272. readFile: () => null,
  273. getProjectRoot: () => '',
  274. getAllFiles: () => ['src/helpers.ts', 'src/helpers/index.ts'],
  275. };
  276. const result = resolveImportPath(
  277. '../helpers',
  278. 'src/components/Button.ts',
  279. 'typescript',
  280. context
  281. );
  282. expect(result).toBe('src/helpers.ts');
  283. });
  284. it('should extract JS/TS import mappings', () => {
  285. const content = `
  286. import { foo } from './foo';
  287. import bar from '../bar';
  288. import * as utils from './utils';
  289. import { baz, qux } from './baz';
  290. `;
  291. const mappings = extractImportMappings(
  292. 'src/index.ts',
  293. content,
  294. 'typescript'
  295. );
  296. expect(mappings.length).toBeGreaterThan(0);
  297. expect(mappings.some((m) => m.localName === 'foo')).toBe(true);
  298. expect(mappings.some((m) => m.localName === 'bar')).toBe(true);
  299. });
  300. it('should extract Python import mappings', () => {
  301. const content = `
  302. from utils import helper
  303. from .models import User
  304. import os
  305. from ..services import auth_service
  306. `;
  307. const mappings = extractImportMappings(
  308. 'src/main.py',
  309. content,
  310. 'python'
  311. );
  312. expect(mappings.length).toBeGreaterThan(0);
  313. expect(mappings.some((m) => m.localName === 'helper')).toBe(true);
  314. expect(mappings.some((m) => m.localName === 'User')).toBe(true);
  315. });
  316. });
  317. describe('Framework Detection', () => {
  318. it('should detect React framework', () => {
  319. const context: ResolutionContext = {
  320. getNodesInFile: () => [],
  321. getNodesByName: () => [],
  322. getNodesByQualifiedName: () => [],
  323. getNodesByKind: () => [],
  324. fileExists: () => false,
  325. readFile: (p) => {
  326. if (p === 'package.json') {
  327. return JSON.stringify({
  328. dependencies: { react: '^18.0.0' },
  329. });
  330. }
  331. return null;
  332. },
  333. getProjectRoot: () => '/test',
  334. getAllFiles: () => ['package.json', 'src/App.tsx'],
  335. };
  336. const frameworks = detectFrameworks(context);
  337. expect(frameworks.some((f) => f.name === 'react')).toBe(true);
  338. });
  339. it('should detect Express framework', () => {
  340. const context: ResolutionContext = {
  341. getNodesInFile: () => [],
  342. getNodesByName: () => [],
  343. getNodesByQualifiedName: () => [],
  344. getNodesByKind: () => [],
  345. fileExists: () => false,
  346. readFile: (p) => {
  347. if (p === 'package.json') {
  348. return JSON.stringify({
  349. dependencies: { express: '^4.18.0' },
  350. });
  351. }
  352. return null;
  353. },
  354. getProjectRoot: () => '/test',
  355. getAllFiles: () => ['package.json', 'src/app.js'],
  356. };
  357. const frameworks = detectFrameworks(context);
  358. expect(frameworks.some((f) => f.name === 'express')).toBe(true);
  359. });
  360. it('should detect Laravel framework', () => {
  361. const context: ResolutionContext = {
  362. getNodesInFile: () => [],
  363. getNodesByName: () => [],
  364. getNodesByQualifiedName: () => [],
  365. getNodesByKind: () => [],
  366. fileExists: (p) => p === 'artisan',
  367. readFile: () => null,
  368. getProjectRoot: () => '/test',
  369. getAllFiles: () => ['artisan', 'app/Http/Kernel.php'],
  370. };
  371. const frameworks = detectFrameworks(context);
  372. expect(frameworks.some((f) => f.name === 'laravel')).toBe(true);
  373. });
  374. it('should return all framework resolvers', () => {
  375. const resolvers = getAllFrameworkResolvers();
  376. expect(resolvers.length).toBeGreaterThan(0);
  377. expect(resolvers.some((r) => r.name === 'react')).toBe(true);
  378. expect(resolvers.some((r) => r.name === 'express')).toBe(true);
  379. expect(resolvers.some((r) => r.name === 'laravel')).toBe(true);
  380. });
  381. });
  382. describe('React Framework Resolver', () => {
  383. it('should resolve React component references', () => {
  384. const mockNodes: Node[] = [
  385. {
  386. id: 'component:src/Button.tsx:Button:5',
  387. kind: 'component',
  388. name: 'Button',
  389. qualifiedName: 'src/Button.tsx::Button',
  390. filePath: 'src/Button.tsx',
  391. language: 'tsx',
  392. startLine: 5,
  393. endLine: 20,
  394. startColumn: 0,
  395. endColumn: 0,
  396. updatedAt: Date.now(),
  397. },
  398. ];
  399. const context: ResolutionContext = {
  400. getNodesInFile: (fp) => (fp === 'src/Button.tsx' ? mockNodes : []),
  401. getNodesByName: () => mockNodes,
  402. getNodesByQualifiedName: () => [],
  403. getNodesByKind: () => [],
  404. fileExists: () => false,
  405. readFile: (p) => {
  406. if (p === 'package.json') {
  407. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  408. }
  409. return null;
  410. },
  411. getProjectRoot: () => '/test',
  412. getAllFiles: () => ['package.json', 'src/Button.tsx', 'src/App.tsx'],
  413. };
  414. const frameworks = detectFrameworks(context);
  415. const reactResolver = frameworks.find((f) => f.name === 'react');
  416. expect(reactResolver).toBeDefined();
  417. const ref = {
  418. fromNodeId: 'component:src/App.tsx:App:1',
  419. referenceName: 'Button',
  420. referenceKind: 'renders' as const,
  421. line: 10,
  422. column: 5,
  423. filePath: 'src/App.tsx',
  424. language: 'typescript' as const,
  425. };
  426. const result = reactResolver!.resolve(ref, context);
  427. expect(result).not.toBeNull();
  428. expect(result?.targetNodeId).toBe('component:src/Button.tsx:Button:5');
  429. });
  430. it('should resolve custom hook references', () => {
  431. const mockNodes: Node[] = [
  432. {
  433. id: 'hook:src/hooks/useAuth.ts:useAuth:1',
  434. kind: 'function',
  435. name: 'useAuth',
  436. qualifiedName: 'src/hooks/useAuth.ts::useAuth',
  437. filePath: 'src/hooks/useAuth.ts',
  438. language: 'typescript',
  439. startLine: 1,
  440. endLine: 20,
  441. startColumn: 0,
  442. endColumn: 0,
  443. updatedAt: Date.now(),
  444. },
  445. ];
  446. const context: ResolutionContext = {
  447. getNodesInFile: (fp) => (fp.includes('useAuth') ? mockNodes : []),
  448. getNodesByName: () => mockNodes,
  449. getNodesByQualifiedName: () => [],
  450. getNodesByKind: () => [],
  451. fileExists: () => false,
  452. readFile: (p) => {
  453. if (p === 'package.json') {
  454. return JSON.stringify({ dependencies: { react: '^18.0.0' } });
  455. }
  456. return null;
  457. },
  458. getProjectRoot: () => '/test',
  459. getAllFiles: () => ['package.json', 'src/hooks/useAuth.ts'],
  460. };
  461. const frameworks = detectFrameworks(context);
  462. const reactResolver = frameworks.find((f) => f.name === 'react');
  463. const ref = {
  464. fromNodeId: 'component:src/App.tsx:App:1',
  465. referenceName: 'useAuth',
  466. referenceKind: 'calls' as const,
  467. line: 5,
  468. column: 10,
  469. filePath: 'src/App.tsx',
  470. language: 'typescript' as const,
  471. };
  472. const result = reactResolver!.resolve(ref, context);
  473. expect(result).not.toBeNull();
  474. expect(result?.targetNodeId).toBe('hook:src/hooks/useAuth.ts:useAuth:1');
  475. });
  476. });
  477. describe('Integration Tests', () => {
  478. it('should create resolver from CodeGraph instance', async () => {
  479. // Create a simple TypeScript project
  480. fs.writeFileSync(
  481. path.join(tempDir, 'package.json'),
  482. JSON.stringify({ name: 'test', dependencies: { react: '^18.0.0' } })
  483. );
  484. const srcDir = path.join(tempDir, 'src');
  485. fs.mkdirSync(srcDir);
  486. // Create utility file
  487. fs.writeFileSync(
  488. path.join(srcDir, 'utils.ts'),
  489. `export function formatDate(date: Date): string {
  490. return date.toISOString();
  491. }
  492. export function parseDate(str: string): Date {
  493. return new Date(str);
  494. }`
  495. );
  496. // Create main file that uses utils
  497. fs.writeFileSync(
  498. path.join(srcDir, 'main.ts'),
  499. `import { formatDate, parseDate } from './utils';
  500. function processDate(input: string): string {
  501. const date = parseDate(input);
  502. return formatDate(date);
  503. }`
  504. );
  505. // Initialize and index
  506. cg = await CodeGraph.init(tempDir, { index: true });
  507. // Check that resolver detected React framework
  508. const frameworks = cg.getDetectedFrameworks();
  509. expect(frameworks).toContain('react');
  510. // Get stats to verify indexing worked
  511. const stats = cg.getStats();
  512. expect(stats.fileCount).toBe(2);
  513. expect(stats.nodeCount).toBeGreaterThan(0);
  514. });
  515. it('should resolve references after indexing', async () => {
  516. // Create a project with references
  517. const srcDir = path.join(tempDir, 'src');
  518. fs.mkdirSync(srcDir, { recursive: true });
  519. fs.writeFileSync(
  520. path.join(srcDir, 'helper.ts'),
  521. `export function helperFunction(): void {
  522. console.log('helper');
  523. }`
  524. );
  525. fs.writeFileSync(
  526. path.join(srcDir, 'main.ts'),
  527. `import { helperFunction } from './helper';
  528. function main(): void {
  529. helperFunction();
  530. }`
  531. );
  532. cg = await CodeGraph.init(tempDir, { index: true });
  533. // Run reference resolution
  534. const result = cg.resolveReferences();
  535. // Should have attempted resolution
  536. expect(result.stats.total).toBeGreaterThanOrEqual(0);
  537. });
  538. it('promotes calls→instantiates when target resolves to a class (Python)', async () => {
  539. // Python has no `new` keyword — `Foo()` is the standard
  540. // instantiation syntax. Extraction can't tell that apart from
  541. // a function call without symbol info, so it emits a `calls`
  542. // ref. Resolution promotes it to `instantiates` once the
  543. // target is known to be a class.
  544. const srcDir = path.join(tempDir, 'src');
  545. fs.mkdirSync(srcDir, { recursive: true });
  546. fs.writeFileSync(
  547. path.join(srcDir, 'app.py'),
  548. `class UserService:
  549. def __init__(self):
  550. self.db = None
  551. def bootstrap():
  552. return UserService()
  553. `
  554. );
  555. cg = await CodeGraph.init(tempDir, { index: true });
  556. cg.resolveReferences();
  557. const bootstrap = cg
  558. .getNodesByKind('function')
  559. .find((n) => n.name === 'bootstrap');
  560. expect(bootstrap).toBeDefined();
  561. const outgoing = cg.getOutgoingEdges(bootstrap!.id);
  562. const instantiates = outgoing.find((e) => e.kind === 'instantiates');
  563. expect(instantiates).toBeDefined();
  564. // Same edge must NOT also appear as a `calls` edge — promotion
  565. // replaces the kind, doesn't duplicate.
  566. const callsToUserService = outgoing.filter(
  567. (e) => e.kind === 'calls' && e.target === instantiates!.target
  568. );
  569. expect(callsToUserService).toHaveLength(0);
  570. });
  571. it('resolves Go cross-package qualified calls via go.mod module path (#388)', async () => {
  572. // Pre-#388, every `pkga.FuncX(...)` call in a Go monorepo was flagged
  573. // external (isExternalImport returned true for any non-`/internal/`
  574. // import without `.`-prefix) and resolution fell through to name-match
  575. // with path proximity — recall on cross-package callers was ~<1%.
  576. fs.writeFileSync(
  577. path.join(tempDir, 'go.mod'),
  578. 'module github.com/example/myproject\n\ngo 1.21\n'
  579. );
  580. const pkgaDir = path.join(tempDir, 'pkga');
  581. const pkgbDir = path.join(tempDir, 'pkgb');
  582. const pkgcDir = path.join(tempDir, 'pkgc');
  583. fs.mkdirSync(pkgaDir);
  584. fs.mkdirSync(pkgbDir);
  585. fs.mkdirSync(pkgcDir);
  586. // Same-name exported function in two packages — only the imported one
  587. // should resolve. Exercises disambiguation, not just connectivity.
  588. fs.writeFileSync(
  589. path.join(pkgaDir, 'conv.go'),
  590. 'package pkga\nfunc Convert(x int) int { return x * 2 }\n'
  591. );
  592. fs.writeFileSync(
  593. path.join(pkgbDir, 'conv.go'),
  594. 'package pkgb\nfunc Convert(x int) int { return x + 1 }\n'
  595. );
  596. fs.writeFileSync(
  597. path.join(pkgcDir, 'use.go'),
  598. `package pkgc
  599. import "github.com/example/myproject/pkga"
  600. func UsePkga() {
  601. pkga.Convert(5)
  602. }
  603. `
  604. );
  605. cg = await CodeGraph.init(tempDir, { index: true });
  606. const usePkga = cg.getNodesByKind('function').filter((n) => n.name ==='UsePkga')[0];
  607. expect(usePkga).toBeDefined();
  608. const outgoing = cg.getOutgoingEdges(usePkga!.id);
  609. const callEdges = outgoing.filter((e) => e.kind === 'calls');
  610. expect(callEdges).toHaveLength(1);
  611. const target = cg.getNode(callEdges[0]!.target);
  612. expect(target?.name).toBe('Convert');
  613. // Critical: the resolver must pick the imported pkga's Convert,
  614. // not pkgb's. With the broken (pre-fix) resolver this lands on
  615. // whichever Convert happens to be cheaper under path proximity.
  616. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkga/conv.go');
  617. });
  618. it('resolves Go aliased imports across packages (#388)', async () => {
  619. fs.writeFileSync(
  620. path.join(tempDir, 'go.mod'),
  621. 'module github.com/example/myproject\n\ngo 1.21\n'
  622. );
  623. fs.mkdirSync(path.join(tempDir, 'pkgb'));
  624. fs.mkdirSync(path.join(tempDir, 'pkgd'));
  625. fs.writeFileSync(
  626. path.join(tempDir, 'pkgb', 'lib.go'),
  627. 'package pkgb\nfunc Compute(x int) int { return x }\n'
  628. );
  629. fs.writeFileSync(
  630. path.join(tempDir, 'pkgd', 'use.go'),
  631. `package pkgd
  632. import (
  633. "fmt"
  634. alias "github.com/example/myproject/pkgb"
  635. )
  636. func UseAliased() {
  637. fmt.Println("hi")
  638. alias.Compute(3)
  639. }
  640. `
  641. );
  642. cg = await CodeGraph.init(tempDir, { index: true });
  643. const useAliased = cg.getNodesByKind('function').filter((n) => n.name ==='UseAliased')[0];
  644. expect(useAliased).toBeDefined();
  645. const calls = cg.getOutgoingEdges(useAliased!.id).filter((e) => e.kind === 'calls');
  646. // fmt.Println is stdlib — must stay external. alias.Compute must resolve.
  647. expect(calls).toHaveLength(1);
  648. const target = cg.getNode(calls[0]!.target);
  649. expect(target?.name).toBe('Compute');
  650. expect(target?.filePath.replace(/\\/g, '/')).toBe('pkgb/lib.go');
  651. });
  652. it('TS type_alias object-shape members resolve method calls (#359)', async () => {
  653. // Pre-#359, `recorder.stop()` (recorder: RecorderHandle) attached
  654. // to `StdioMcpClient.stop` in a sibling directory via path-proximity
  655. // because the type_alias had no `stop` node — only the unrelated
  656. // class did. Now type_alias produces member nodes (property/method),
  657. // so the camelCase receiver↔type word overlap pulls the call to
  658. // `RecorderHandle::stop` instead of the look-alike class.
  659. fs.mkdirSync(path.join(tempDir, 'voice'));
  660. fs.mkdirSync(path.join(tempDir, 'codegraph'));
  661. fs.writeFileSync(
  662. path.join(tempDir, 'voice', 'recorder.ts'),
  663. `export type RecorderHandle = {
  664. wavPath: string;
  665. stop: () => Promise<{ ok: true }>;
  666. };
  667. `
  668. );
  669. fs.writeFileSync(
  670. path.join(tempDir, 'voice', 'controller.ts'),
  671. `import type { RecorderHandle } from "./recorder";
  672. export async function finaliseRecording(recorder: RecorderHandle) {
  673. return await recorder.stop();
  674. }
  675. `
  676. );
  677. fs.writeFileSync(
  678. path.join(tempDir, 'codegraph', 'stdio-client.ts'),
  679. `export class StdioMcpClient {
  680. private stopped = false;
  681. async stop(): Promise<void> { this.stopped = true; }
  682. }
  683. `
  684. );
  685. cg = await CodeGraph.init(tempDir, { index: true });
  686. const handleStop = cg
  687. .getNodesByKind('method')
  688. .find((n) => n.qualifiedName === 'RecorderHandle::stop');
  689. expect(handleStop).toBeDefined();
  690. const clientStop = cg
  691. .getNodesByKind('method')
  692. .find((n) => n.qualifiedName === 'StdioMcpClient::stop');
  693. expect(clientStop).toBeDefined();
  694. const handleCallers = cg.getIncomingEdges(handleStop!.id).filter((e) => e.kind === 'calls');
  695. const clientCallers = cg.getIncomingEdges(clientStop!.id).filter((e) => e.kind === 'calls');
  696. expect(handleCallers.length).toBeGreaterThanOrEqual(1);
  697. // The class method must have NO callers — voice/'s call must NOT
  698. // mis-attribute. A non-empty list would mean the false-positive
  699. // path is still firing.
  700. expect(clientCallers).toHaveLength(0);
  701. // Function-typed property surfaces as a `method` node, not `property`,
  702. // because `stop()` semantics at the call site are method semantics.
  703. expect(handleStop!.kind).toBe('method');
  704. });
  705. it('C# extracts references from method/property/field types (#381)', async () => {
  706. // Pre-#381, every C# project produced ZERO `references` edges:
  707. // csharp.ts was missing returnField, and the type-leaf walker
  708. // only recognized TS/Java's `type_identifier` nodes — C# uses
  709. // `identifier`/`predefined_type`/`qualified_name`/`generic_name`.
  710. const srcDir = path.join(tempDir, 'src');
  711. fs.mkdirSync(srcDir, { recursive: true });
  712. fs.writeFileSync(
  713. path.join(srcDir, 'Dtos.cs'),
  714. `namespace MyApp;
  715. public class SessionInfoDto { public string Id { get; set; } = ""; }
  716. public class UserDto { public string Name { get; set; } = ""; }
  717. `
  718. );
  719. fs.writeFileSync(
  720. path.join(srcDir, 'Service.cs'),
  721. `using System.Threading.Tasks;
  722. namespace MyApp;
  723. public class DataExporter
  724. {
  725. public SessionInfoDto Build(UserDto user, SessionInfoDto session) { return session; }
  726. public Task<SessionInfoDto> BuildAsync(UserDto user) { return Task.FromResult(new SessionInfoDto()); }
  727. public SessionInfoDto Latest { get; set; } = new();
  728. private UserDto _cached;
  729. }
  730. `
  731. );
  732. cg = await CodeGraph.init(tempDir, { index: true });
  733. const sessionDto = cg
  734. .getNodesByKind('class')
  735. .find((n) => n.name === 'SessionInfoDto');
  736. const userDto = cg
  737. .getNodesByKind('class')
  738. .find((n) => n.name === 'UserDto');
  739. expect(sessionDto).toBeDefined();
  740. expect(userDto).toBeDefined();
  741. const sessionIncoming = cg
  742. .getIncomingEdges(sessionDto!.id)
  743. .filter((e) => e.kind === 'references');
  744. const userIncoming = cg
  745. .getIncomingEdges(userDto!.id)
  746. .filter((e) => e.kind === 'references');
  747. // SessionInfoDto: Build return, Build param, BuildAsync return (inside Task<>), Latest property.
  748. // UserDto: Build param, BuildAsync param, _cached field.
  749. expect(sessionIncoming.length).toBeGreaterThanOrEqual(4);
  750. expect(userIncoming.length).toBeGreaterThanOrEqual(3);
  751. });
  752. it('Go: leaves stdlib calls (fmt.Println, etc.) external', async () => {
  753. fs.writeFileSync(
  754. path.join(tempDir, 'go.mod'),
  755. 'module github.com/example/myproject\n\ngo 1.21\n'
  756. );
  757. fs.writeFileSync(
  758. path.join(tempDir, 'main.go'),
  759. `package main
  760. import "fmt"
  761. func main() {
  762. fmt.Println("hi")
  763. }
  764. `
  765. );
  766. cg = await CodeGraph.init(tempDir, { index: true });
  767. const mainFn = cg.getNodesByKind('function').filter((n) => n.name ==='main')[0];
  768. const calls = cg.getOutgoingEdges(mainFn!.id).filter((e) => e.kind === 'calls');
  769. // No spurious in-project edge — fmt.* must stay unresolved/external.
  770. expect(calls).toHaveLength(0);
  771. });
  772. });
  773. describe('Name Matcher: kind bias for new ref kinds', () => {
  774. const baseContext = (candidates: Node[]): ResolutionContext => ({
  775. getNodesInFile: () => [],
  776. getNodesByName: (name) => candidates.filter((c) => c.name === name),
  777. getNodesByQualifiedName: () => [],
  778. getNodesByKind: () => [],
  779. fileExists: () => true,
  780. readFile: () => null,
  781. getProjectRoot: () => '/test',
  782. getAllFiles: () => [],
  783. getNodesByLowerName: () => [],
  784. getImportMappings: () => [],
  785. });
  786. it('prefers a class candidate over a function for `instantiates` refs', () => {
  787. // A class and a function share a name across the codebase.
  788. // Without the kind bias, the function (which gets the +25 `calls`
  789. // bonus historically applied to all candidates of that kind) would
  790. // win. Now the instantiates branch reverses it.
  791. const fn: Node = {
  792. id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
  793. qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
  794. startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  795. };
  796. const cls: Node = {
  797. id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
  798. qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
  799. startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  800. };
  801. const ref = {
  802. fromNodeId: 'func:main.ts:bootstrap:1',
  803. referenceName: 'Logger',
  804. referenceKind: 'instantiates' as const,
  805. line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
  806. };
  807. const result = matchReference(ref, baseContext([fn, cls]));
  808. expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
  809. });
  810. it('prefers a function candidate over a non-function for `decorates` refs', () => {
  811. const variable: Node = {
  812. id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
  813. qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
  814. startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  815. };
  816. const decorator: Node = {
  817. id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
  818. qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
  819. startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
  820. };
  821. const ref = {
  822. fromNodeId: 'class:svc.ts:UserService:1',
  823. referenceName: 'Inject',
  824. referenceKind: 'decorates' as const,
  825. line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
  826. };
  827. const result = matchReference(ref, baseContext([variable, decorator]));
  828. expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
  829. });
  830. });
  831. describe('tsconfig path aliases', () => {
  832. it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
  833. // Two same-named exports in different directories. Without alias
  834. // resolution, name-matcher would pick whichever it finds first;
  835. // with alias resolution, the import path uniquely picks one.
  836. fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
  837. fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
  838. fs.writeFileSync(
  839. path.join(tempDir, 'src/utils/format.ts'),
  840. `export function pickMe(): number { return 1; }\n`
  841. );
  842. fs.writeFileSync(
  843. path.join(tempDir, 'src/legacy/format.ts'),
  844. `export function pickMe(): number { return 99; }\n`
  845. );
  846. fs.writeFileSync(
  847. path.join(tempDir, 'src/main.ts'),
  848. `import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
  849. );
  850. fs.writeFileSync(
  851. path.join(tempDir, 'tsconfig.json'),
  852. JSON.stringify({
  853. compilerOptions: {
  854. baseUrl: './src',
  855. paths: { '@utils/*': ['utils/*'] },
  856. },
  857. })
  858. );
  859. cg = await CodeGraph.init(tempDir, { index: true });
  860. cg.resolveReferences();
  861. // The two pickMe nodes live in different files. The aliased
  862. // import should attach the call edge to the @utils-mapped one,
  863. // not the legacy duplicate.
  864. const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
  865. const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
  866. const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
  867. expect(utilsNode).toBeDefined();
  868. expect(legacyNode).toBeDefined();
  869. const utilsCallers = cg.getCallers(utilsNode!.id);
  870. const legacyCallers = cg.getCallers(legacyNode!.id);
  871. expect(utilsCallers.length).toBeGreaterThan(0);
  872. expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  873. // The legacy node should NOT have a caller from src/main.ts —
  874. // the alias correctly picked the utils version.
  875. expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
  876. });
  877. it('falls back gracefully when tsconfig is absent', async () => {
  878. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  879. fs.writeFileSync(
  880. path.join(tempDir, 'src/a.ts'),
  881. `export function aFn(): void {}\n`
  882. );
  883. fs.writeFileSync(
  884. path.join(tempDir, 'src/b.ts'),
  885. `import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
  886. );
  887. cg = await CodeGraph.init(tempDir, { index: true });
  888. // No tsconfig present — index should still complete and the
  889. // relative-import-based call edge should be created.
  890. const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
  891. expect(aFn).toBeDefined();
  892. const callers = cg.getCallers(aFn!.id);
  893. expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
  894. });
  895. });
  896. describe('re-export chain following', () => {
  897. it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
  898. // main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
  899. // Without chain following, `signIn` resolves to nothing because
  900. // none of the barrel files declare it directly.
  901. fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
  902. fs.writeFileSync(
  903. path.join(tempDir, 'src/services/auth.ts'),
  904. `export function signIn(): void {}\n`
  905. );
  906. fs.writeFileSync(
  907. path.join(tempDir, 'src/services/index.ts'),
  908. `export { signIn } from './auth';\n`
  909. );
  910. fs.writeFileSync(
  911. path.join(tempDir, 'src/all.ts'),
  912. `export * from './services/index';\n`
  913. );
  914. fs.writeFileSync(
  915. path.join(tempDir, 'src/main.ts'),
  916. `import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
  917. );
  918. cg = await CodeGraph.init(tempDir, { index: true });
  919. cg.resolveReferences();
  920. const signInNode = cg
  921. .getNodesByKind('function')
  922. .find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
  923. expect(signInNode).toBeDefined();
  924. const callers = cg.getCallers(signInNode!.id);
  925. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  926. });
  927. it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
  928. // The chase has to look up `foo` in the upstream module even
  929. // though the importer asked for `bar` — exercises the rename
  930. // branch of findExportedSymbol.
  931. fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
  932. fs.writeFileSync(
  933. path.join(tempDir, 'src/auth.ts'),
  934. `export function signIn(): void {}\n`
  935. );
  936. fs.writeFileSync(
  937. path.join(tempDir, 'src/index.ts'),
  938. `export { signIn as login } from './auth';\n`
  939. );
  940. fs.writeFileSync(
  941. path.join(tempDir, 'src/main.ts'),
  942. `import { login } from './index';\nexport function go(): void { login(); }\n`
  943. );
  944. cg = await CodeGraph.init(tempDir, { index: true });
  945. cg.resolveReferences();
  946. const signInNode = cg
  947. .getNodesByKind('function')
  948. .find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
  949. expect(signInNode).toBeDefined();
  950. const callers = cg.getCallers(signInNode!.id);
  951. expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
  952. });
  953. });
  954. });