frameworks-integration.test.ts 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390
  1. import { describe, it, expect, beforeAll, afterEach } from 'vitest';
  2. import * as fs from 'fs';
  3. import * as path from 'path';
  4. import * as os from 'os';
  5. import { CodeGraph } from '../src';
  6. import { DatabaseConnection, getDatabasePath } from '../src/db';
  7. import { QueryBuilder } from '../src/db/queries';
  8. import { createResolver } from '../src/resolution';
  9. import type { Node } from '../src/types';
  10. import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
  11. beforeAll(async () => {
  12. await initGrammars();
  13. await loadAllGrammars();
  14. });
  15. describe('Express middleware imports', () => {
  16. it('does not resolve package imports into license headings', async () => {
  17. const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-express-doc-import-'));
  18. let cg: CodeGraph | undefined;
  19. try {
  20. fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({ dependencies: { express: '*', cors: '*' } }));
  21. fs.writeFileSync(path.join(tmpDir, 'LICENSE.md'), '# cors\n\n# host-validation-middleware\n');
  22. fs.writeFileSync(path.join(tmpDir, 'local.js'), 'export function localMiddleware() {}\n');
  23. fs.writeFileSync(path.join(tmpDir, 'server.js'), [
  24. "import corsMiddleware from 'cors'",
  25. "import { hostValidationMiddleware as originalHostValidationMiddleware } from 'host-validation-middleware'",
  26. "import { localMiddleware } from './local.js'",
  27. 'localMiddleware()',
  28. ].join('\n'));
  29. cg = await CodeGraph.init(tmpDir, { index: true });
  30. const local = cg.getNodesByKind('function').find((n) => n.name === 'localMiddleware');
  31. expect(local).toBeDefined();
  32. expect(cg.getIncomingEdges(local!.id).some((e) => e.kind === 'imports')).toBe(true);
  33. expect(cg.getIncomingEdges(local!.id).some((e) => e.kind === 'calls')).toBe(true);
  34. cg.close();
  35. cg = undefined;
  36. const db = DatabaseConnection.open(getDatabasePath(tmpDir));
  37. try {
  38. const queries = new QueryBuilder(db.getDb());
  39. for (const name of ['cors', 'host-validation-middleware']) {
  40. queries.insertNode({
  41. id: `heading:${name}`, name, qualifiedName: `LICENSE.md#${name}`,
  42. kind: 'module', language: 'markdown' as Node['language'], filePath: 'LICENSE.md',
  43. startLine: 1, endLine: 1, startColumn: 0, endColumn: 0, updatedAt: 0,
  44. });
  45. }
  46. const resolver = createResolver(tmpDir, queries);
  47. for (const referenceName of ['cors', 'corsMiddleware', 'host-validation-middleware']) {
  48. expect(resolver.resolveOne({
  49. fromNodeId: 'file:server.js', referenceName, referenceKind: 'imports',
  50. filePath: 'server.js', language: 'javascript', line: 1, column: 0,
  51. })).toBeNull();
  52. }
  53. } finally {
  54. db.close();
  55. }
  56. } finally {
  57. cg?.close();
  58. fs.rmSync(tmpDir, { recursive: true, force: true });
  59. }
  60. });
  61. });
  62. describe('Django end-to-end framework extraction', () => {
  63. let tmpDir: string | undefined;
  64. afterEach(() => {
  65. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  66. tmpDir = undefined;
  67. });
  68. it('creates a route->view edge from urls.py to view class', async () => {
  69. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-django-'));
  70. fs.writeFileSync(path.join(tmpDir, 'manage.py'), '# marker\n');
  71. fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'django==4.2\n');
  72. fs.mkdirSync(path.join(tmpDir, 'users'));
  73. fs.writeFileSync(path.join(tmpDir, 'users/__init__.py'), '');
  74. fs.writeFileSync(
  75. path.join(tmpDir, 'users/views.py'),
  76. 'class UserListView:\n def get(self, request): pass\n'
  77. );
  78. fs.writeFileSync(
  79. path.join(tmpDir, 'users/urls.py'),
  80. 'from django.urls import path\n' +
  81. 'from users.views import UserListView\n' +
  82. 'urlpatterns = [path("users/", UserListView.as_view(), name="user-list")]\n'
  83. );
  84. const cg = CodeGraph.initSync(tmpDir);
  85. await cg.indexAll();
  86. // Route node exists
  87. const routes = cg.getNodesByKind('route');
  88. expect(routes.length).toBeGreaterThan(0);
  89. const route = routes.find((n) => n.name === 'users/');
  90. expect(route).toBeDefined();
  91. // View class exists
  92. const classNodes = cg.getNodesByKind('class');
  93. const view = classNodes.find((n) => n.name === 'UserListView');
  94. expect(view).toBeDefined();
  95. // Edge route -> view exists
  96. const edges = cg.getOutgoingEdges(route!.id);
  97. const toView = edges.find((e) => e.target === view!.id);
  98. expect(toView).toBeDefined();
  99. expect(toView!.kind).toBe('references');
  100. cg.close();
  101. });
  102. });
  103. describe('Flask end-to-end framework extraction', () => {
  104. let tmpDir: string | undefined;
  105. afterEach(() => {
  106. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  107. tmpDir = undefined;
  108. });
  109. it('resolves stacked routes across @login_required to a view named after a builtin (index)', async () => {
  110. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-flask-'));
  111. fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'flask==3.0\n');
  112. fs.writeFileSync(
  113. path.join(tmpDir, 'app.py'),
  114. 'from flask import Blueprint, render_template\n' +
  115. 'from flask_login import login_required\n' +
  116. 'bp = Blueprint("main", __name__)\n' +
  117. '\n' +
  118. '@bp.route("/", methods=["GET", "POST"])\n' +
  119. '@bp.route("/index", methods=["GET", "POST"])\n' +
  120. '@login_required\n' +
  121. 'def index():\n' +
  122. ' return render_template("index.html")\n'
  123. );
  124. const cg = CodeGraph.initSync(tmpDir);
  125. await cg.indexAll();
  126. // Both stacked @bp.route decorators are extracted (the second was previously
  127. // dropped because @login_required broke the "def must follow" assumption).
  128. const routes = cg.getNodesByKind('route');
  129. expect(routes.map((r) => r.name).sort()).toEqual(['GET /', 'GET /index']);
  130. // The view function exists even though its name is a Python builtin method.
  131. const fn = cg.getNodesByKind('function').find((n) => n.name === 'index');
  132. expect(fn).toBeDefined();
  133. // Both routes resolve to it — exercises the bare-name builtin guard, which
  134. // previously filtered the `index` reference as a builtin method.
  135. for (const route of routes) {
  136. const edges = cg.getOutgoingEdges(route.id);
  137. const toView = edges.find((e) => e.target === fn!.id && e.kind === 'references');
  138. expect(toView, `route ${route.name} should resolve to index()`).toBeDefined();
  139. }
  140. cg.close();
  141. });
  142. });
  143. describe('Flutter end-to-end — setState→build synthesis', () => {
  144. let tmpDir: string | undefined;
  145. afterEach(() => {
  146. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  147. tmpDir = undefined;
  148. });
  149. it('synthesizes a handler→build edge when a State method calls setState', async () => {
  150. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-flutter-'));
  151. fs.writeFileSync(
  152. path.join(tmpDir, 'main.dart'),
  153. 'import "package:flutter/material.dart";\n' +
  154. 'class CounterPage extends StatefulWidget {\n' +
  155. ' @override\n' +
  156. ' State<CounterPage> createState() => _CounterPageState();\n' +
  157. '}\n' +
  158. 'class _CounterPageState extends State<CounterPage> {\n' +
  159. ' int _count = 0;\n' +
  160. ' void _increment() {\n' +
  161. ' setState(() {\n' +
  162. ' _count++;\n' +
  163. ' });\n' +
  164. ' }\n' +
  165. ' @override\n' +
  166. ' Widget build(BuildContext context) {\n' +
  167. ' return Text("$_count");\n' +
  168. ' }\n' +
  169. '}\n'
  170. );
  171. const cg = CodeGraph.initSync(tmpDir);
  172. await cg.indexAll();
  173. const methods = cg.getNodesByKind('method');
  174. const increment = methods.find((n) => n.name === '_increment');
  175. const build = methods.find((n) => n.name === 'build');
  176. expect(increment).toBeDefined();
  177. expect(build).toBeDefined();
  178. // setState re-runs build (Flutter-internal, no static edge). The synthesizer
  179. // bridges the handler → build so the "tap → setState → rebuilt UI" flow connects.
  180. const edges = cg.getOutgoingEdges(increment!.id);
  181. const toBuild = edges.find((e) => e.target === build!.id && e.kind === 'calls');
  182. expect(toBuild, '_increment should reach build via setState synthesis').toBeDefined();
  183. cg.close();
  184. });
  185. });
  186. describe('C++ end-to-end — virtual override synthesis', () => {
  187. let tmpDir: string | undefined;
  188. afterEach(() => {
  189. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  190. tmpDir = undefined;
  191. });
  192. it('resolves callers through typed object pointers', async () => {
  193. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  194. let cg: CodeGraph | undefined;
  195. try {
  196. fs.writeFileSync(
  197. path.join(tmpDir, 'detect.hpp'),
  198. 'class CDetect {\n' +
  199. ' public:\n' +
  200. ' int Processing();\n' +
  201. '};\n' +
  202. 'class CDetector {\n' +
  203. ' private:\n' +
  204. ' CDetect* m_cpAlg = nullptr;\n' +
  205. ' public:\n' +
  206. ' int Run();\n' +
  207. ' int Flush();\n' +
  208. '};\n'
  209. );
  210. fs.writeFileSync(
  211. path.join(tmpDir, 'detect.cpp'),
  212. '#include "detect.hpp"\n' +
  213. 'int CDetector::Run() { return m_cpAlg->Processing(); }\n' +
  214. 'int CDetector::Flush() { return m_cpAlg->Processing(); }\n' +
  215. 'int CDetect::Processing() { return 0; }\n'
  216. );
  217. cg = CodeGraph.initSync(tmpDir);
  218. await cg.indexAll();
  219. const processing = cg
  220. .getNodesByKind('method')
  221. .find((n) => n.qualifiedName.endsWith('CDetect::Processing'));
  222. expect(processing).toBeDefined();
  223. const callers = cg.getCallers(processing!.id).map((c) => c.node.qualifiedName);
  224. expect(callers).toContain('CDetector::Run');
  225. expect(callers).toContain('CDetector::Flush');
  226. const runMethod = cg
  227. .getNodesByKind('method')
  228. .find((n) => n.qualifiedName.endsWith('CDetector::Run'));
  229. expect(runMethod).toBeDefined();
  230. const callees = cg.getCallees(runMethod!.id).map((c) => c.node.qualifiedName);
  231. expect(callees).toContain('CDetect::Processing');
  232. } finally {
  233. cg?.close();
  234. }
  235. });
  236. it('resolves typed pointer callers when the method name is ambiguous and the call sits inside a return/declaration', async () => {
  237. // Regression: an earlier version of the C++ receiver-type inference matched
  238. // the call line itself (`return m_cpAlg->Processing()`) and treated `return`
  239. // as the type, OR grabbed `int r =` as a type from the prefix. With Strategy
  240. // 3's "unique method name" fallback, the original issue example resolved
  241. // anyway — but as soon as two classes share a method name (very common in
  242. // real C++), both calls go unresolved.
  243. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  244. let cg: CodeGraph | undefined;
  245. try {
  246. fs.writeFileSync(
  247. path.join(tmpDir, 'detect.hpp'),
  248. 'class CDetect { public: int Processing(); };\n' +
  249. 'class CWidget { public: int Processing(); };\n' +
  250. 'class CDetector {\n' +
  251. ' private:\n' +
  252. ' CDetect* m_cpAlg = nullptr;\n' +
  253. ' public:\n' +
  254. ' int RunReturn();\n' +
  255. ' int RunAssign();\n' +
  256. '};\n'
  257. );
  258. fs.writeFileSync(
  259. path.join(tmpDir, 'detect.cpp'),
  260. '#include "detect.hpp"\n' +
  261. 'int CDetector::RunReturn() { return m_cpAlg->Processing(); }\n' +
  262. 'int CDetector::RunAssign() { int r = m_cpAlg->Processing(); return r; }\n' +
  263. 'int CDetect::Processing() { return 0; }\n' +
  264. 'int CWidget::Processing() { return 0; }\n'
  265. );
  266. cg = CodeGraph.initSync(tmpDir);
  267. await cg.indexAll();
  268. const detectProc = cg
  269. .getNodesByKind('method')
  270. .find((n) => n.qualifiedName === 'CDetect::Processing');
  271. const widgetProc = cg
  272. .getNodesByKind('method')
  273. .find((n) => n.qualifiedName === 'CWidget::Processing');
  274. expect(detectProc).toBeDefined();
  275. expect(widgetProc).toBeDefined();
  276. const detectCallers = cg.getCallers(detectProc!.id).map((c) => c.node.qualifiedName);
  277. expect(detectCallers).toContain('CDetector::RunReturn');
  278. expect(detectCallers).toContain('CDetector::RunAssign');
  279. // CWidget::Processing is never called — calls must NOT misroute here.
  280. const widgetCallers = cg.getCallers(widgetProc!.id).map((c) => c.node.qualifiedName);
  281. expect(widgetCallers).not.toContain('CDetector::RunReturn');
  282. expect(widgetCallers).not.toContain('CDetector::RunAssign');
  283. } finally {
  284. cg?.close();
  285. }
  286. });
  287. it('bridges a base virtual method to the subclass override', async () => {
  288. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-cpp-'));
  289. fs.writeFileSync(
  290. path.join(tmpDir, 'iter.cpp'),
  291. 'class Iterator {\n' +
  292. ' public:\n' +
  293. ' virtual void Next() { }\n' +
  294. '};\n' +
  295. 'class DBIter : public Iterator {\n' +
  296. ' public:\n' +
  297. ' void Next() override { advance(); }\n' +
  298. ' void advance() { }\n' +
  299. '};\n'
  300. );
  301. const cg = CodeGraph.initSync(tmpDir);
  302. await cg.indexAll();
  303. // Two methods named Next: the base virtual (lower line) and the override.
  304. const nexts = cg
  305. .getNodesByKind('method')
  306. .filter((n) => n.name === 'Next')
  307. .sort((a, b) => a.startLine - b.startLine);
  308. expect(nexts.length).toBe(2);
  309. const [baseNext, overrideNext] = nexts;
  310. // A vtable call to Iterator::Next dispatches to DBIter::Next — bridge it so
  311. // trace/callees from the interface method reaches the implementation.
  312. const edge = cg
  313. .getOutgoingEdges(baseNext!.id)
  314. .find((e) => e.target === overrideNext!.id && e.kind === 'calls');
  315. expect(edge, 'Iterator::Next should reach DBIter::Next via override synthesis').toBeDefined();
  316. cg.close();
  317. });
  318. });
  319. describe('Java end-to-end — field-injected bean trace (issue #389)', () => {
  320. let tmpDir: string | undefined;
  321. afterEach(() => {
  322. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  323. tmpDir = undefined;
  324. });
  325. // Mirrors the issue's Spring MVC pattern:
  326. // UserAction(@Resource UserBO userbo).toLogin2() -> this.userbo.toLogin2()
  327. // -> UserBO.toLogin2() -> userService.toLogin() -> UserService.toLogin (iface)
  328. // -> UserServiceImpl.toLogin() via interface→impl synthesis.
  329. // Without the extractor `this.` strip + field-typed receiver lookup, the very
  330. // first hop (controller -> bean) was missing entirely, breaking trace.
  331. it('connects controller -> @Resource bean -> interface -> impl end-to-end', async () => {
  332. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-bean-'));
  333. const javaDir = path.join(tmpDir, 'src/main/java/com/example/user');
  334. fs.mkdirSync(path.join(javaDir, 'action'), { recursive: true });
  335. fs.mkdirSync(path.join(javaDir, 'bo'), { recursive: true });
  336. fs.mkdirSync(path.join(javaDir, 'service'), { recursive: true });
  337. fs.mkdirSync(path.join(javaDir, 'service/impl'), { recursive: true });
  338. fs.writeFileSync(
  339. path.join(tmpDir, 'pom.xml'),
  340. '<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies></project>\n'
  341. );
  342. fs.writeFileSync(
  343. path.join(javaDir, 'action/UserAction.java'),
  344. 'package com.example.user.action;\n' +
  345. 'import com.example.user.bo.UserBO;\n' +
  346. 'import javax.annotation.Resource;\n' +
  347. '@org.springframework.stereotype.Controller\n' +
  348. 'public class UserAction {\n' +
  349. ' @Resource(name = "userBO") private UserBO userbo;\n' +
  350. ' public void toLogin2() { this.userbo.toLogin2(); }\n' +
  351. '}\n'
  352. );
  353. fs.writeFileSync(
  354. path.join(javaDir, 'bo/UserBO.java'),
  355. 'package com.example.user.bo;\n' +
  356. 'import com.example.user.service.UserService;\n' +
  357. 'import javax.annotation.Resource;\n' +
  358. '@org.springframework.stereotype.Component("userBO")\n' +
  359. 'public class UserBO {\n' +
  360. ' @Resource private UserService userService;\n' +
  361. ' public void toLogin2() { userService.toLogin(); }\n' +
  362. '}\n'
  363. );
  364. fs.writeFileSync(
  365. path.join(javaDir, 'service/UserService.java'),
  366. 'package com.example.user.service;\n' +
  367. 'public interface UserService { void toLogin(); }\n'
  368. );
  369. fs.writeFileSync(
  370. path.join(javaDir, 'service/impl/UserServiceImpl.java'),
  371. 'package com.example.user.service.impl;\n' +
  372. 'import com.example.user.service.UserService;\n' +
  373. '@org.springframework.stereotype.Service("userService")\n' +
  374. 'public class UserServiceImpl implements UserService {\n' +
  375. ' public void toLogin() { }\n' +
  376. '}\n'
  377. );
  378. const cg = CodeGraph.initSync(tmpDir);
  379. await cg.indexAll();
  380. const methods = cg.getNodesByKind('method');
  381. const find = (cls: string, name: string) =>
  382. methods.find((m) => m.name === name && m.filePath.endsWith(`${cls}.java`));
  383. const action = find('UserAction', 'toLogin2');
  384. const bo = find('UserBO', 'toLogin2');
  385. const svc = find('UserService', 'toLogin');
  386. const impl = find('UserServiceImpl', 'toLogin');
  387. expect(action).toBeDefined();
  388. expect(bo).toBeDefined();
  389. expect(svc).toBeDefined();
  390. expect(impl).toBeDefined();
  391. // UserAction.toLogin2 -> UserBO.toLogin2 (the regressed hop — `this.userbo`
  392. // receiver was emitted verbatim and the field-type lookup didn't exist).
  393. const actionToBo = cg.getOutgoingEdges(action!.id).find((e) => e.target === bo!.id);
  394. expect(actionToBo, 'controller `this.userbo.toLogin2()` should reach UserBO.toLogin2').toBeDefined();
  395. expect(actionToBo!.kind).toBe('calls');
  396. // UserBO.toLogin2 -> UserService.toLogin (plain identifier receiver, works pre-fix).
  397. const boToSvc = cg.getOutgoingEdges(bo!.id).find((e) => e.target === svc!.id);
  398. expect(boToSvc).toBeDefined();
  399. // UserService.toLogin -> UserServiceImpl.toLogin (interface->impl synth).
  400. const svcToImpl = cg.getOutgoingEdges(svc!.id).find((e) => e.target === impl!.id);
  401. expect(svcToImpl).toBeDefined();
  402. cg.close();
  403. });
  404. it('bridges a Java mapper interface method to its MyBatis XML statement (incl. SQL fragments)', async () => {
  405. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-mybatis-'));
  406. const javaDir = path.join(tmpDir, 'src/main/java/com/example/dao');
  407. const xmlDir = path.join(tmpDir, 'src/main/resources/mappers');
  408. fs.mkdirSync(javaDir, { recursive: true });
  409. fs.mkdirSync(xmlDir, { recursive: true });
  410. fs.writeFileSync(
  411. path.join(tmpDir, 'pom.xml'),
  412. '<project><dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId></dependency></dependencies></project>\n'
  413. );
  414. fs.writeFileSync(
  415. path.join(javaDir, 'UserDAOMapper.java'),
  416. 'package com.example.dao;\n' +
  417. 'public interface UserDAOMapper {\n' +
  418. ' Object getById(int id);\n' +
  419. ' int updateUser(Object u);\n' +
  420. '}\n'
  421. );
  422. fs.writeFileSync(
  423. path.join(xmlDir, 'UserDAOMapper.xml'),
  424. '<?xml version="1.0" encoding="UTF-8"?>\n' +
  425. '<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">\n' +
  426. '<mapper namespace="com.example.dao.UserDAOMapper">\n' +
  427. ' <sql id="userCols">id, name, email</sql>\n' +
  428. ' <select id="getById" parameterType="int" resultType="User">\n' +
  429. ' SELECT <include refid="userCols"/> FROM users WHERE id = #{id}\n' +
  430. ' </select>\n' +
  431. ' <update id="updateUser" parameterType="User">\n' +
  432. ' UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id}\n' +
  433. ' </update>\n' +
  434. '</mapper>\n'
  435. );
  436. const cg = CodeGraph.initSync(tmpDir);
  437. await cg.indexAll();
  438. const methods = cg.getNodesByKind('method');
  439. const getByIdJava = methods.find((m) => m.name === 'getById' && m.language === 'java');
  440. const getByIdXml = methods.find((m) => m.name === 'getById' && m.language === 'xml');
  441. const updateJava = methods.find((m) => m.name === 'updateUser' && m.language === 'java');
  442. const updateXml = methods.find((m) => m.name === 'updateUser' && m.language === 'xml');
  443. const sqlFrag = methods.find((m) => m.name === 'userCols' && m.language === 'xml');
  444. expect(getByIdJava).toBeDefined();
  445. expect(getByIdXml).toBeDefined();
  446. expect(updateJava).toBeDefined();
  447. expect(updateXml).toBeDefined();
  448. expect(sqlFrag).toBeDefined();
  449. // XML statement qualified name must be `<namespace>::<id>` so the
  450. // synthesizer can match against the Java method's `<Class>::<method>`
  451. // suffix — this is the load-bearing contract between extractor + synthesis.
  452. expect(getByIdXml!.qualifiedName).toBe('com.example.dao.UserDAOMapper::getById');
  453. // Bridge: Java mapper method -> XML statement, kind 'calls'.
  454. const j2xGet = cg.getOutgoingEdges(getByIdJava!.id).find((e) => e.target === getByIdXml!.id);
  455. expect(j2xGet, 'Java getById should reach the XML <select id="getById">').toBeDefined();
  456. expect(j2xGet!.kind).toBe('calls');
  457. const j2xUpd = cg.getOutgoingEdges(updateJava!.id).find((e) => e.target === updateXml!.id);
  458. expect(j2xUpd, 'Java updateUser should reach the XML <update id="updateUser">').toBeDefined();
  459. // <include refid="userCols"/> inside <select> -> <sql id="userCols"> in same mapper.
  460. const incEdge = cg.getOutgoingEdges(getByIdXml!.id).find((e) => e.target === sqlFrag!.id);
  461. expect(incEdge, '<include refid="userCols"/> should reach the <sql> fragment').toBeDefined();
  462. cg.close();
  463. });
  464. it('covers legacy iBatis <sqlMap> statements and keeps same-line vendor-split pairs (#1182)', async () => {
  465. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-ibatis-'));
  466. const xmlDir = path.join(tmpDir, 'src/main/resources/sqlmaps');
  467. fs.mkdirSync(xmlDir, { recursive: true });
  468. // iBatis 2 sqlMap with an explicit namespace.
  469. fs.writeFileSync(
  470. path.join(xmlDir, 'Account.xml'),
  471. '<?xml version="1.0" encoding="UTF-8"?>\n' +
  472. '<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">\n' +
  473. "<sqlMap namespace='Account'>\n" +
  474. " <sql id='cols'>id, name, email</sql>\n" +
  475. " <select id='getById' resultClass='Account'>SELECT <include refid='cols'/> FROM account WHERE id = #id#</select>\n" +
  476. " <insert id='insert' parameterClass='Account'>INSERT INTO account (id) VALUES (#id#)</insert>\n" +
  477. ' <!-- <select id="disabled">SELECT 0</select> -->\n' +
  478. '</sqlMap>\n'
  479. );
  480. // Namespace-less sqlMap whose ids carry the qualifier as `Map.statement`.
  481. fs.writeFileSync(
  482. path.join(xmlDir, 'LegacyDao.xml'),
  483. '<sqlMap>\n' +
  484. ' <select id="LegacyDao.findAll" resultClass="Row">SELECT * FROM t</select>\n' +
  485. '</sqlMap>\n'
  486. );
  487. // MyBatis mapper with a vendor-split databaseId pair written on ONE line —
  488. // same qualifiedName + same start line. Before the id-hash fold both nodes
  489. // hashed identically and INSERT OR REPLACE dropped one.
  490. fs.writeFileSync(
  491. path.join(xmlDir, 'VendorMapper.xml'),
  492. '<mapper namespace="com.example.VendorMapper">\n' +
  493. '<select id="findUser" databaseId="oracle">SELECT 1 FROM dual</select><select id="findUser" databaseId="mysql">SELECT 1</select>\n' +
  494. '</mapper>\n'
  495. );
  496. const cg = CodeGraph.initSync(tmpDir);
  497. await cg.indexAll();
  498. const xmlMethods = cg.getNodesByKind('method').filter((n) => n.language === 'xml');
  499. const qnames = xmlMethods.map((n) => n.qualifiedName);
  500. // iBatis statements now land in the graph (was zero coverage before #1182).
  501. expect(qnames).toContain('Account::getById');
  502. expect(qnames).toContain('Account::insert');
  503. expect(qnames).toContain('Account::cols');
  504. expect(qnames).toContain('LegacyDao::findAll');
  505. // The commented-out statement produced no node.
  506. expect(qnames).not.toContain('Account::disabled');
  507. // <include refid='cols'/> resolves to the <sql> fragment in the same map.
  508. const getById = xmlMethods.find((n) => n.qualifiedName === 'Account::getById');
  509. const cols = xmlMethods.find((n) => n.qualifiedName === 'Account::cols');
  510. expect(getById).toBeDefined();
  511. expect(cols).toBeDefined();
  512. const incEdge = cg.getOutgoingEdges(getById!.id).find((e) => e.target === cols!.id);
  513. expect(incEdge, "iBatis <include refid='cols'/> should reach the <sql> fragment").toBeDefined();
  514. // Both vendor-split statements survive the DB write (the collision fix).
  515. const findUser = xmlMethods.filter((n) => n.name === 'findUser');
  516. expect(findUser, 'both databaseId variants of findUser should survive').toHaveLength(2);
  517. expect(new Set(findUser.map((n) => n.id)).size).toBe(2);
  518. cg.close();
  519. });
  520. it('binds @Value / @ConfigurationProperties to YAML + .properties keys (incl. relaxed binding)', async () => {
  521. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-config-'));
  522. const javaDir = path.join(tmpDir, 'src/main/java/com/example');
  523. const resDir = path.join(tmpDir, 'src/main/resources');
  524. fs.mkdirSync(javaDir, { recursive: true });
  525. fs.mkdirSync(resDir, { recursive: true });
  526. fs.writeFileSync(
  527. path.join(tmpDir, 'pom.xml'),
  528. '<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency></dependencies></project>\n'
  529. );
  530. fs.writeFileSync(
  531. path.join(resDir, 'application.yml'),
  532. 'app:\n' +
  533. ' cache:\n' +
  534. ' name:\n' +
  535. ' user-token: "example-service:auth:token"\n' +
  536. ' enabled: true\n' +
  537. 'db:\n' +
  538. ' url: "jdbc:mysql://localhost/x"\n'
  539. );
  540. fs.writeFileSync(
  541. path.join(resDir, 'application.properties'),
  542. 'app.retry-count=3\n'
  543. );
  544. fs.writeFileSync(
  545. path.join(javaDir, 'CacheConfig.java'),
  546. 'package com.example;\n' +
  547. 'import org.springframework.beans.factory.annotation.Value;\n' +
  548. 'public class CacheConfig {\n' +
  549. ' @Value("${app.cache.name.user-token}") private String tokenCacheName;\n' +
  550. ' @Value("${app.cache.enabled:true}") private boolean enabled;\n' +
  551. ' // relaxed binding: java camelCase, properties kebab-case\n' +
  552. ' @Value("${app.retryCount}") private int retry;\n' +
  553. '}\n'
  554. );
  555. fs.writeFileSync(
  556. path.join(javaDir, 'CacheProperties.java'),
  557. 'package com.example;\n' +
  558. 'import org.springframework.boot.context.properties.ConfigurationProperties;\n' +
  559. '@ConfigurationProperties(prefix = "app.cache")\n' +
  560. 'public class CacheProperties { private boolean enabled; }\n'
  561. );
  562. const cg = CodeGraph.initSync(tmpDir);
  563. await cg.indexAll();
  564. // YAML/properties leaf keys: one constant node per dotted path.
  565. const cfgKeys = cg
  566. .getNodesByKind('constant')
  567. .filter((n) => n.language === 'yaml' || n.language === 'properties');
  568. const cfgByQn = (qn: string) => cfgKeys.find((n) => n.qualifiedName === qn);
  569. expect(cfgByQn('app.cache.name.user-token')).toBeDefined();
  570. expect(cfgByQn('app.cache.enabled')).toBeDefined();
  571. expect(cfgByQn('db.url')).toBeDefined();
  572. expect(cfgByQn('app.retry-count')).toBeDefined();
  573. // @Value("${app.cache.name.user-token}") -> the YAML leaf key.
  574. const valueBindings = cg
  575. .getNodesByKind('constant')
  576. .filter((n) => n.id.startsWith('spring-value:'));
  577. const userToken = valueBindings.find((n) => n.name === 'app.cache.name.user-token');
  578. expect(userToken).toBeDefined();
  579. const userTokenEdges = cg.getOutgoingEdges(userToken!.id);
  580. const userTokenTarget = userTokenEdges.find((e) =>
  581. cfgKeys.some((c) => c.id === e.target && c.qualifiedName === 'app.cache.name.user-token'),
  582. );
  583. expect(userTokenTarget, '@Value should reference the YAML leaf key').toBeDefined();
  584. // Default-value form `${k:default}` — strip the `:default` and bind the key.
  585. const enabledBind = valueBindings.find((n) => n.name === 'app.cache.enabled');
  586. expect(enabledBind).toBeDefined();
  587. expect(cg.getOutgoingEdges(enabledBind!.id).some((e) => {
  588. const t = cfgByQn('app.cache.enabled');
  589. return t && e.target === t.id;
  590. })).toBe(true);
  591. // Relaxed binding: `app.retryCount` (camel) -> `app.retry-count` (kebab).
  592. const retryBind = valueBindings.find((n) => n.name === 'app.retryCount');
  593. expect(retryBind).toBeDefined();
  594. expect(cg.getOutgoingEdges(retryBind!.id).some((e) => {
  595. const t = cfgByQn('app.retry-count');
  596. return t && e.target === t.id;
  597. })).toBe(true);
  598. // @ConfigurationProperties(prefix="app.cache") -> a key under that prefix.
  599. const cpBindings = cg
  600. .getNodesByKind('constant')
  601. .filter((n) => n.id.startsWith('spring-cp:'));
  602. const cpAppCache = cpBindings.find((n) => n.name === 'app.cache');
  603. expect(cpAppCache).toBeDefined();
  604. const cpEdges = cg.getOutgoingEdges(cpAppCache!.id);
  605. expect(cpEdges.length).toBeGreaterThan(0);
  606. cg.close();
  607. });
  608. it('binds a config key only for `references` refs, never a same-named method call (#1180)', async () => {
  609. // `service.process` is BOTH a yaml key and a `service.process()` method call.
  610. // canonicalConfigKey collapses them to the same token, so before #1180 the
  611. // method call (kind `calls`) fell into the Spring config-key branch and
  612. // mis-resolved to the YAML constant at 0.9 confidence — a wrong edge, and the
  613. // uncached constant scan that made large Java/Kotlin indexes take ~1h. The
  614. // branch is now gated to `references` (only @Value/@ConfigurationProperties).
  615. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-spring-kindgate-'));
  616. const javaDir = path.join(tmpDir, 'src/main/java/com/example');
  617. const resDir = path.join(tmpDir, 'src/main/resources');
  618. fs.mkdirSync(javaDir, { recursive: true });
  619. fs.mkdirSync(resDir, { recursive: true });
  620. fs.writeFileSync(
  621. path.join(tmpDir, 'pom.xml'),
  622. '<project><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency></dependencies></project>\n'
  623. );
  624. fs.writeFileSync(path.join(resDir, 'application.yml'), 'service:\n process: "enabled"\n');
  625. fs.writeFileSync(
  626. path.join(javaDir, 'Worker.java'),
  627. 'package com.example;\n' +
  628. 'import org.springframework.beans.factory.annotation.Value;\n' +
  629. 'class Processor { void process() {} }\n' +
  630. 'public class Worker {\n' +
  631. ' private Processor service;\n' +
  632. ' @Value("${service.process}") private String sp;\n' +
  633. ' void run() { service.process(); }\n' +
  634. '}\n'
  635. );
  636. const cg = CodeGraph.initSync(tmpDir);
  637. await cg.indexAll();
  638. const yamlKey = cg
  639. .getNodesByKind('constant')
  640. .find((n) => n.language === 'yaml' && n.qualifiedName === 'service.process');
  641. expect(yamlKey, 'yaml key service.process should be indexed').toBeDefined();
  642. // `references` ref (@Value) DOES bind to the config key.
  643. const valueBind = cg
  644. .getNodesByKind('constant')
  645. .find((n) => n.id.startsWith('spring-value:') && n.name === 'service.process');
  646. expect(valueBind).toBeDefined();
  647. expect(
  648. cg.getOutgoingEdges(valueBind!.id).some((e) => e.target === yamlKey!.id),
  649. '@Value should still bind to the yaml key',
  650. ).toBe(true);
  651. // `calls` ref (service.process()) must NOT bind to the config key.
  652. const run = cg.getNodesByKind('method').find((n) => n.name === 'run');
  653. expect(run).toBeDefined();
  654. expect(
  655. cg.getOutgoingEdges(run!.id).some((e) => e.target === yamlKey!.id),
  656. 'a method call must never resolve to a config-key constant',
  657. ).toBe(false);
  658. cg.close();
  659. });
  660. it('emits only a file node for non-MyBatis XML (pom.xml, beans.xml, log4j.xml)', async () => {
  661. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-xml-non-mybatis-'));
  662. fs.writeFileSync(
  663. path.join(tmpDir, 'pom.xml'),
  664. '<project><groupId>x</groupId><artifactId>y</artifactId></project>\n'
  665. );
  666. fs.writeFileSync(
  667. path.join(tmpDir, 'log4j.xml'),
  668. '<?xml version="1.0"?><Configuration><Loggers><Root level="info"/></Loggers></Configuration>\n'
  669. );
  670. const cg = CodeGraph.initSync(tmpDir);
  671. await cg.indexAll();
  672. // No method nodes — non-mapper XML produces no symbols (just file rows).
  673. expect(cg.getNodesByKind('method').filter((n) => n.language === 'xml').length).toBe(0);
  674. cg.close();
  675. });
  676. it('resolves a `this.field.method()` call to a unique implementation class', async () => {
  677. // Standalone test of the extractor `this.` strip: even without Spring annotations,
  678. // `this.svc.run()` where `svc` is typed as a concrete class should route to that
  679. // class's method. This is the general Java fix, Spring is only one consumer.
  680. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-java-this-field-'));
  681. fs.writeFileSync(
  682. path.join(tmpDir, 'App.java'),
  683. 'class Svc { public void run() { } }\n' +
  684. 'class App {\n' +
  685. ' private Svc svc;\n' +
  686. ' public void go() { this.svc.run(); }\n' +
  687. '}\n'
  688. );
  689. const cg = CodeGraph.initSync(tmpDir);
  690. await cg.indexAll();
  691. const methods = cg.getNodesByKind('method');
  692. const go = methods.find((m) => m.name === 'go');
  693. const run = methods.find((m) => m.name === 'run');
  694. expect(go && run).toBeTruthy();
  695. const edge = cg.getOutgoingEdges(go!.id).find((e) => e.target === run!.id);
  696. expect(edge, '`this.svc.run()` should resolve to Svc.run').toBeDefined();
  697. cg.close();
  698. });
  699. });
  700. describe('JVM FQN imports — end-to-end', () => {
  701. let tmpDir: string | undefined;
  702. afterEach(() => {
  703. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  704. tmpDir = undefined;
  705. });
  706. it('resolves a Kotlin import when the file name differs from the class name', async () => {
  707. // Bar lives in Models.kt — the filesystem-based Java-style path lookup
  708. // (com/example/Bar.kt) misses this; only FQN-via-qualifiedName finds it.
  709. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  710. fs.writeFileSync(
  711. path.join(tmpDir, 'Models.kt'),
  712. 'package com.example\n\nclass Bar {\n fun greet(): String = "hi"\n}\n'
  713. );
  714. fs.writeFileSync(
  715. path.join(tmpDir, 'Caller.kt'),
  716. 'package com.example.app\n\nimport com.example.Bar\n\nclass App {\n fun run() { Bar().greet() }\n}\n'
  717. );
  718. const cg = CodeGraph.initSync(tmpDir);
  719. await cg.indexAll();
  720. const bar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example::Bar');
  721. expect(bar, 'Bar should be extracted with package-qualified name').toBeDefined();
  722. const importNode = cg.getNodesByKind('import').find((n) => n.name === 'com.example.Bar');
  723. expect(importNode, 'import statement node should exist').toBeDefined();
  724. // The imports edge may originate from the import node OR from a parent
  725. // scope (file / namespace) — accept either, but require that an
  726. // imports-kind edge to Bar exists.
  727. const reachesBar = cg
  728. .getIncomingEdges(bar!.id)
  729. .find((e) => e.kind === 'imports');
  730. expect(reachesBar, 'an imports edge should resolve to Bar via FQN').toBeDefined();
  731. cg.close();
  732. });
  733. it('resolves a Kotlin top-level function import', async () => {
  734. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  735. fs.writeFileSync(
  736. path.join(tmpDir, 'Utils.kt'),
  737. 'package com.example\n\nfun util(): Int = 42\n'
  738. );
  739. fs.writeFileSync(
  740. path.join(tmpDir, 'Caller.kt'),
  741. 'package com.example.app\n\nimport com.example.util\n\nfun main() { util() }\n'
  742. );
  743. const cg = CodeGraph.initSync(tmpDir);
  744. await cg.indexAll();
  745. const util = cg.getNodesByKind('function').find((n) => n.qualifiedName === 'com.example::util');
  746. expect(util, 'top-level util() should be extracted under com.example').toBeDefined();
  747. const edge = cg.getIncomingEdges(util!.id).find((e) => e.kind === 'imports');
  748. expect(edge, 'imports edge should reach the top-level function by FQN').toBeDefined();
  749. });
  750. it('resolves cross-language: Kotlin importing a Java class', async () => {
  751. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  752. fs.writeFileSync(
  753. path.join(tmpDir, 'JavaBar.java'),
  754. 'package com.example;\n\npublic class JavaBar {\n public String greet() { return "hi"; }\n}\n'
  755. );
  756. fs.writeFileSync(
  757. path.join(tmpDir, 'Caller.kt'),
  758. 'package com.example.app\n\nimport com.example.JavaBar\n\nfun main() { JavaBar().greet() }\n'
  759. );
  760. const cg = CodeGraph.initSync(tmpDir);
  761. await cg.indexAll();
  762. const javaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example::JavaBar');
  763. expect(javaBar, 'JavaBar should be extracted under com.example regardless of language').toBeDefined();
  764. const edge = cg.getIncomingEdges(javaBar!.id).find((e) => e.kind === 'imports');
  765. expect(edge, 'Kotlin caller should resolve its import to the Java class').toBeDefined();
  766. });
  767. it('disambiguates a class-name collision across packages', async () => {
  768. // Two `Bar` classes in different packages — each importer should reach
  769. // ITS Bar, not the other one. This is the central failure mode that
  770. // name-matcher alone cannot disambiguate.
  771. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-jvm-imp-'));
  772. fs.writeFileSync(
  773. path.join(tmpDir, 'AlphaBar.kt'),
  774. 'package com.example.alpha\n\nclass Bar { fun who() = "alpha" }\n'
  775. );
  776. fs.writeFileSync(
  777. path.join(tmpDir, 'BetaBar.kt'),
  778. 'package com.example.beta\n\nclass Bar { fun who() = "beta" }\n'
  779. );
  780. fs.writeFileSync(
  781. path.join(tmpDir, 'CallerA.kt'),
  782. 'package app\n\nimport com.example.alpha.Bar\n\nfun a() { Bar().who() }\n'
  783. );
  784. fs.writeFileSync(
  785. path.join(tmpDir, 'CallerB.kt'),
  786. 'package app\n\nimport com.example.beta.Bar\n\nfun b() { Bar().who() }\n'
  787. );
  788. const cg = CodeGraph.initSync(tmpDir);
  789. await cg.indexAll();
  790. const alphaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example.alpha::Bar');
  791. const betaBar = cg.getNodesByKind('class').find((n) => n.qualifiedName === 'com.example.beta::Bar');
  792. expect(alphaBar).toBeDefined();
  793. expect(betaBar).toBeDefined();
  794. expect(alphaBar!.id).not.toBe(betaBar!.id);
  795. // Each Bar receives exactly one imports edge — from its own caller.
  796. const alphaIncoming = cg.getIncomingEdges(alphaBar!.id).filter((e) => e.kind === 'imports');
  797. const betaIncoming = cg.getIncomingEdges(betaBar!.id).filter((e) => e.kind === 'imports');
  798. expect(alphaIncoming.length).toBeGreaterThan(0);
  799. expect(betaIncoming.length).toBeGreaterThan(0);
  800. // Sanity: the edges don't cross — alpha's incoming sources don't include
  801. // beta's filePath and vice versa.
  802. const sourceFiles = (edges: typeof alphaIncoming) =>
  803. edges.map((e) => cg.getNode(e.source)?.filePath).filter(Boolean);
  804. expect(sourceFiles(alphaIncoming).some((p) => p?.includes('CallerA.kt'))).toBe(true);
  805. expect(sourceFiles(betaIncoming).some((p) => p?.includes('CallerB.kt'))).toBe(true);
  806. });
  807. });
  808. describe('Java anonymous-class override synthesis — end-to-end', () => {
  809. let tmpDir: string | undefined;
  810. afterEach(() => {
  811. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  812. tmpDir = undefined;
  813. });
  814. it('bridges an abstract base method to overrides inside `new Base() { ... }`', async () => {
  815. // Mirrors guava Splitter: a factory returns `new BaseIter() {
  816. // @Override int separatorStart(...) { ... } }`. Without anon-class
  817. // extraction the override is invisible — Phase 5.5 interface-impl
  818. // has no class to bridge — and an agent investigating `BaseIter.separatorStart`
  819. // can't see its real implementation without reading the file.
  820. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-anon-java-'));
  821. fs.writeFileSync(
  822. path.join(tmpDir, 'Splitter.java'),
  823. 'package com.example;\n' +
  824. '\n' +
  825. 'abstract class BaseIter {\n' +
  826. ' abstract int separatorStart(int start);\n' +
  827. '}\n' +
  828. '\n' +
  829. 'public class Splitter {\n' +
  830. ' public BaseIter make() {\n' +
  831. ' return new BaseIter() {\n' +
  832. ' @Override\n' +
  833. ' int separatorStart(int start) { return start + 1; }\n' +
  834. ' };\n' +
  835. ' }\n' +
  836. '}\n'
  837. );
  838. const cg = CodeGraph.initSync(tmpDir);
  839. await cg.indexAll();
  840. // The anon class is extracted and contains the override.
  841. const anonClass = cg
  842. .getNodesByKind('class')
  843. .find((n) => /BaseIter\$anon@/.test(n.name));
  844. expect(anonClass, 'anonymous BaseIter subclass should be a class node').toBeDefined();
  845. const baseAbstract = cg
  846. .getNodesByKind('method')
  847. .find((n) => n.qualifiedName === 'com.example::BaseIter::separatorStart');
  848. const anonOverride = cg
  849. .getNodesByKind('method')
  850. .find(
  851. (n) =>
  852. n.name === 'separatorStart' &&
  853. n.qualifiedName.includes('$anon@') &&
  854. n.qualifiedName.startsWith('com.example::Splitter::make::')
  855. );
  856. expect(baseAbstract, 'base abstract method should be in the graph').toBeDefined();
  857. expect(anonOverride, 'anon-class override should be in the graph').toBeDefined();
  858. // Phase 5.5 interface-impl: the abstract method has a synthesized
  859. // `calls` edge to the anon override. Without this hop the agent
  860. // would have to Read the file to discover the implementation.
  861. const synthEdge = cg
  862. .getOutgoingEdges(baseAbstract!.id)
  863. .find((e) => e.target === anonOverride!.id && e.kind === 'calls');
  864. expect(synthEdge, 'BaseIter.separatorStart should bridge to anon.separatorStart').toBeDefined();
  865. expect(synthEdge!.provenance).toBe('heuristic');
  866. expect((synthEdge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy).toBe(
  867. 'interface-impl'
  868. );
  869. cg.close();
  870. });
  871. });
  872. describe('Go gRPC stub→impl synthesis', () => {
  873. let tmpDir: string | undefined;
  874. afterEach(() => {
  875. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  876. tmpDir = undefined;
  877. });
  878. it('bridges UnimplementedMsgServer methods to the hand-written keeper impl', async () => {
  879. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-grpc-'));
  880. // Mimic protoc-gen-go-grpc output: `*_grpc.pb.go` carrying the
  881. // UnimplementedMsgServer stub.
  882. fs.writeFileSync(
  883. path.join(tmpDir, 'tx_grpc.pb.go'),
  884. 'package banktypes\n\n' +
  885. 'type UnimplementedMsgServer struct{}\n\n' +
  886. 'func (UnimplementedMsgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) { return nil, nil }\n' +
  887. 'func (UnimplementedMsgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) { return nil, nil }\n' +
  888. 'func (UnimplementedMsgServer) mustEmbedUnimplementedMsgServer() {}\n' +
  889. 'func (UnimplementedMsgServer) testEmbeddedByValue() {}\n'
  890. );
  891. // Hand-written impl in a non-generated file — what an agent actually
  892. // wants the trace to land on.
  893. fs.writeFileSync(
  894. path.join(tmpDir, 'msg_server.go'),
  895. 'package keeper\n\n' +
  896. 'type msgServer struct{ k Keeper }\n\n' +
  897. 'func (m msgServer) Send(ctx context.Context, req *MsgSend) (*MsgSendResponse, error) {\n' +
  898. ' return m.k.SendCoins(ctx, req.From, req.To, req.Amount)\n' +
  899. '}\n' +
  900. 'func (m msgServer) MultiSend(ctx context.Context, req *MsgMultiSend) (*MsgMultiSendResponse, error) {\n' +
  901. ' return nil, nil\n' +
  902. '}\n'
  903. );
  904. let cg: CodeGraph | undefined;
  905. try {
  906. cg = CodeGraph.initSync(tmpDir);
  907. await cg.indexAll();
  908. const stubSend = cg
  909. .getNodesByKind('method')
  910. .find((n) => n.qualifiedName.endsWith('UnimplementedMsgServer::Send'));
  911. const implSend = cg
  912. .getNodesByKind('method')
  913. .find((n) => n.qualifiedName.endsWith('msgServer::Send'));
  914. expect(stubSend, 'UnimplementedMsgServer.Send should be indexed').toBeDefined();
  915. expect(implSend, 'msgServer.Send should be indexed').toBeDefined();
  916. const bridge = cg
  917. .getOutgoingEdges(stubSend!.id)
  918. .find((e) => e.target === implSend!.id && e.kind === 'calls');
  919. expect(bridge, 'stub Send should bridge to impl Send').toBeDefined();
  920. expect(bridge!.provenance).toBe('heuristic');
  921. expect((bridge!.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy).toBe(
  922. 'go-grpc-stub-impl'
  923. );
  924. } finally {
  925. cg?.close();
  926. }
  927. });
  928. it('does not bridge to candidates living in another generated file', async () => {
  929. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-go-grpc-sib-'));
  930. // `*_grpc.pb.go` also contains a sibling `msgClient` struct that
  931. // happens to satisfy the same method set. We must NOT bridge to it —
  932. // it's not the hand-written impl, just the gRPC client wrapper.
  933. fs.writeFileSync(
  934. path.join(tmpDir, 'tx_grpc.pb.go'),
  935. 'package banktypes\n\n' +
  936. 'type UnimplementedMsgServer struct{}\n' +
  937. 'func (UnimplementedMsgServer) Send() {}\n' +
  938. 'func (UnimplementedMsgServer) MultiSend() {}\n\n' +
  939. 'type msgClient struct{}\n' +
  940. 'func (m msgClient) Send() {}\n' +
  941. 'func (m msgClient) MultiSend() {}\n'
  942. );
  943. let cg: CodeGraph | undefined;
  944. try {
  945. cg = CodeGraph.initSync(tmpDir);
  946. await cg.indexAll();
  947. const stub = cg
  948. .getNodesByKind('struct')
  949. .find((n) => n.name === 'UnimplementedMsgServer');
  950. expect(stub).toBeDefined();
  951. const bridges = cg
  952. .getNodesByKind('method')
  953. .filter((n) => n.qualifiedName.endsWith('UnimplementedMsgServer::Send'))
  954. .flatMap((stubSend) => cg!.getOutgoingEdges(stubSend.id))
  955. .filter(
  956. (e) =>
  957. e.kind === 'calls' &&
  958. (e.metadata as { synthesizedBy?: string } | undefined)?.synthesizedBy ===
  959. 'go-grpc-stub-impl',
  960. );
  961. expect(bridges, 'no bridge to msgClient (also generated)').toHaveLength(0);
  962. } finally {
  963. cg?.close();
  964. }
  965. });
  966. });
  967. describe('React Router end-to-end route extraction (.tsx/.jsx)', () => {
  968. let tmpDir: string | undefined;
  969. afterEach(() => {
  970. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  971. tmpDir = undefined;
  972. });
  973. // Regression for the resolver language-gate bug: the `react` resolver's
  974. // `extract()` was filtered out of the .tsx/.jsx grammars, so `<Route>` routes
  975. // — which only live in JSX files — were never indexed through the real
  976. // indexing path (the unit tests call extract() directly and so missed this).
  977. it('indexes <Route element={<X/>}> routes from a .tsx file and links them to the component', async () => {
  978. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-rr-'));
  979. fs.writeFileSync(
  980. path.join(tmpDir, 'package.json'),
  981. '{"dependencies":{"react":"^18.0.0","react-router-dom":"^6.0.0"}}'
  982. );
  983. fs.writeFileSync(
  984. path.join(tmpDir, 'Home.tsx'),
  985. 'export function Home() { return null; }\n'
  986. );
  987. fs.writeFileSync(
  988. path.join(tmpDir, 'routes.tsx'),
  989. `import { Routes, Route } from 'react-router-dom';
  990. import { Home } from './Home';
  991. export function AppRoutes() {
  992. return (
  993. <Routes>
  994. <Route path="/home" element={<Home/>} />
  995. </Routes>
  996. );
  997. }
  998. `
  999. );
  1000. const cg = CodeGraph.initSync(tmpDir);
  1001. await cg.indexAll();
  1002. try {
  1003. // The route node from the .tsx file exists (the bug: it didn't).
  1004. const route = cg.getNodesByKind('route').find((n) => n.name === '/home');
  1005. expect(route, '/home route from .tsx should be indexed').toBeDefined();
  1006. // ...and it links to the Home component.
  1007. const home = cg.getNodesByName('Home').find((n) => n.kind === 'function');
  1008. expect(home).toBeDefined();
  1009. const toHome = cg.getOutgoingEdges(route!.id).find((e) => e.target === home!.id);
  1010. expect(toHome, 'route → Home component edge').toBeDefined();
  1011. } finally {
  1012. cg.close();
  1013. }
  1014. });
  1015. });
  1016. describe('Terraform end-to-end module-boundary resolution', () => {
  1017. let tmpDir: string | undefined;
  1018. afterEach(() => {
  1019. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  1020. tmpDir = undefined;
  1021. });
  1022. function writeMultiModuleRepo(root: string) {
  1023. fs.mkdirSync(path.join(root, 'modules/vpc'), { recursive: true });
  1024. fs.mkdirSync(path.join(root, 'modules/other'), { recursive: true });
  1025. fs.mkdirSync(path.join(root, 'envs'), { recursive: true });
  1026. fs.writeFileSync(
  1027. path.join(root, 'main.tf'),
  1028. 'variable "vpc_cidr" {\n type = string\n}\n\n' +
  1029. 'module "vpc" {\n source = "./modules/vpc"\n cidr = var.vpc_cidr\n}\n\n' +
  1030. 'module "registry_thing" {\n source = "terraform-aws-modules/s3-bucket/aws"\n bucket = "x"\n}\n\n' +
  1031. 'output "vpc_id" {\n value = module.vpc.vpc_id\n}\n'
  1032. );
  1033. fs.writeFileSync(
  1034. path.join(root, 'modules/vpc/variables.tf'),
  1035. 'variable "cidr" {\n type = string\n}\n'
  1036. );
  1037. fs.writeFileSync(
  1038. path.join(root, 'modules/vpc/main.tf'),
  1039. 'resource "aws_vpc" "this" {\n cidr_block = var.cidr\n}\n'
  1040. );
  1041. fs.writeFileSync(
  1042. path.join(root, 'modules/vpc/outputs.tf'),
  1043. 'output "vpc_id" {\n value = aws_vpc.this.id\n}\n'
  1044. );
  1045. // Same-named variable in an UNRELATED module — must never receive edges
  1046. // from outside its own directory.
  1047. fs.writeFileSync(
  1048. path.join(root, 'modules/other/variables.tf'),
  1049. 'variable "cidr" {\n type = string\n}\nvariable "orphan_ref_target" {}\n'
  1050. );
  1051. // References a variable that has no same-dir declaration: must stay unlinked.
  1052. fs.writeFileSync(
  1053. path.join(root, 'modules/other/main.tf'),
  1054. 'resource "aws_eip" "e" {\n tags = { Name = var.undeclared_here_elsewhere_yes }\n}\n'
  1055. );
  1056. fs.writeFileSync(path.join(root, 'envs/prod.tfvars'), 'vpc_cidr = "10.0.0.0/16"\n');
  1057. }
  1058. it('bridges module inputs/outputs/source and enforces directory scoping', async () => {
  1059. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-terraform-'));
  1060. writeMultiModuleRepo(tmpDir);
  1061. const cg = CodeGraph.initSync(tmpDir);
  1062. await cg.indexAll();
  1063. try {
  1064. const byQname = (q: string, file?: string) =>
  1065. cg
  1066. .getNodesByName(q.split('.').pop()!)
  1067. .filter((n) => n.qualifiedName === q && (!file || n.filePath === file));
  1068. const moduleDecl = byQname('module.vpc')[0];
  1069. expect(moduleDecl, 'module.vpc declaration node').toBeDefined();
  1070. const childCidr = byQname('var.cidr', 'modules/vpc/variables.tf')[0];
  1071. expect(childCidr, "child module's var.cidr").toBeDefined();
  1072. const childOutput = byQname('output.vpc_id', 'modules/vpc/outputs.tf')[0];
  1073. expect(childOutput, "child module's output.vpc_id").toBeDefined();
  1074. const rootOutput = byQname('output.vpc_id', 'main.tf')[0];
  1075. expect(rootOutput, 'root output.vpc_id').toBeDefined();
  1076. const declEdges = cg.getOutgoingEdges(moduleDecl!.id);
  1077. // Input wiring: module block → child variable (cross-directory).
  1078. expect(
  1079. declEdges.find((e) => e.target === childCidr!.id),
  1080. 'module.vpc → child var.cidr input edge'
  1081. ).toBeDefined();
  1082. // Source wiring: module block → child entry file.
  1083. const fileNode = cg
  1084. .getNodesInFile('modules/vpc/main.tf')
  1085. .find((n) => n.kind === 'file');
  1086. expect(fileNode).toBeDefined();
  1087. const importEdge = declEdges.find((e) => e.target === fileNode!.id);
  1088. expect(importEdge, 'module.vpc → modules/vpc/main.tf imports edge').toBeDefined();
  1089. expect(importEdge!.kind).toBe('imports');
  1090. // Output bridge: root output → child output (not just the declaration).
  1091. const rootOutEdges = cg.getOutgoingEdges(rootOutput!.id);
  1092. expect(
  1093. rootOutEdges.find((e) => e.target === childOutput!.id),
  1094. 'root output.vpc_id → child output.vpc_id'
  1095. ).toBeDefined();
  1096. expect(
  1097. rootOutEdges.find((e) => e.target === moduleDecl!.id),
  1098. 'root output.vpc_id → module.vpc declaration'
  1099. ).toBeDefined();
  1100. // tfvars assignment walks up to the ROOT variable.
  1101. const rootVar = byQname('var.vpc_cidr', 'main.tf')[0];
  1102. expect(rootVar).toBeDefined();
  1103. const tfvarsFile = cg.getNodesInFile('envs/prod.tfvars').find((n) => n.kind === 'file');
  1104. expect(tfvarsFile).toBeDefined();
  1105. expect(
  1106. cg.getOutgoingEdges(tfvarsFile!.id).find((e) => e.target === rootVar!.id),
  1107. 'envs/prod.tfvars → var.vpc_cidr'
  1108. ).toBeDefined();
  1109. // Directory scoping: the unrelated module's same-named var.cidr gets
  1110. // NO incoming edges from outside its own directory…
  1111. const otherCidr = byQname('var.cidr', 'modules/other/variables.tf')[0];
  1112. expect(otherCidr).toBeDefined();
  1113. const incomingOther = cg.getIncomingEdges(otherCidr!.id).filter((e) => e.kind !== 'contains');
  1114. expect(incomingOther, 'unrelated module var.cidr must stay isolated').toHaveLength(0);
  1115. // …and a reference with no same-dir declaration stays unlinked rather
  1116. // than borrowing another module's declaration.
  1117. const orphanEdges = cg
  1118. .getNodesInFile('modules/other/main.tf')
  1119. .filter((n) => n.qualifiedName === 'aws_eip.e')
  1120. .flatMap((n) => cg.getOutgoingEdges(n.id))
  1121. .filter((e) => e.kind === 'references');
  1122. const orphanTargets = orphanEdges.map((e) => cg.getNode(e.target)?.qualifiedName);
  1123. expect(orphanTargets).not.toContain('var.undeclared_here_elsewhere_yes');
  1124. // Registry-sourced module: inputs stay unresolved (no guessed edges).
  1125. const registryDecl = byQname('module.registry_thing')[0];
  1126. expect(registryDecl).toBeDefined();
  1127. const registryEdges = cg
  1128. .getOutgoingEdges(registryDecl!.id)
  1129. .filter((e) => e.kind !== 'contains');
  1130. expect(registryEdges, 'registry module must not link anywhere').toHaveLength(0);
  1131. } finally {
  1132. cg.close();
  1133. }
  1134. });
  1135. });
  1136. describe('Terraform follow-ups: remote-state bridge, provider alias, moved blocks', () => {
  1137. let tmpDir: string | undefined;
  1138. afterEach(() => {
  1139. if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
  1140. tmpDir = undefined;
  1141. });
  1142. it('bridges atmos remote-state to the target component, resolves provider aliases up the tree, links moved blocks', async () => {
  1143. tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-terraform-fu-'));
  1144. // Component producing state.
  1145. fs.mkdirSync(path.join(tmpDir, 'components/terraform/vpc'), { recursive: true });
  1146. fs.writeFileSync(
  1147. path.join(tmpDir, 'components/terraform/vpc/outputs.tf'),
  1148. 'output "vpc_id" {\n value = "vpc-123"\n}\n'
  1149. );
  1150. // Component consuming it via the cloudposse remote-state module.
  1151. fs.mkdirSync(path.join(tmpDir, 'components/terraform/eks/cluster'), { recursive: true });
  1152. fs.writeFileSync(
  1153. path.join(tmpDir, 'components/terraform/eks/cluster/remote-state.tf'),
  1154. 'module "vpc" {\n' +
  1155. ' source = "cloudposse/stack-config/yaml//modules/remote-state"\n' +
  1156. ' component = var.vpc_component_name\n' +
  1157. '}\n' +
  1158. 'variable "vpc_component_name" {\n' +
  1159. ' type = string\n' +
  1160. ' default = "vpc"\n' +
  1161. '}\n'
  1162. );
  1163. fs.writeFileSync(
  1164. path.join(tmpDir, 'components/terraform/eks/cluster/main.tf'),
  1165. 'resource "aws_eks_cluster" "this" {\n vpc_id = module.vpc.outputs.vpc_id\n}\n'
  1166. );
  1167. // Ambiguous component name — two directories called "dns" with the same
  1168. // output; the bridge must refuse to pick one.
  1169. fs.mkdirSync(path.join(tmpDir, 'components/terraform/dns'), { recursive: true });
  1170. fs.mkdirSync(path.join(tmpDir, 'legacy/dns'), { recursive: true });
  1171. fs.writeFileSync(path.join(tmpDir, 'components/terraform/dns/outputs.tf'), 'output "zone_id" {\n value = "z1"\n}\n');
  1172. fs.writeFileSync(path.join(tmpDir, 'legacy/dns/outputs.tf'), 'output "zone_id" {\n value = "z2"\n}\n');
  1173. fs.writeFileSync(
  1174. path.join(tmpDir, 'components/terraform/eks/cluster/dns.tf'),
  1175. 'module "dns" {\n' +
  1176. ' source = "cloudposse/stack-config/yaml//modules/remote-state"\n' +
  1177. ' component = "dns"\n' +
  1178. '}\n' +
  1179. 'output "zone" {\n value = module.dns.outputs.zone_id\n}\n'
  1180. );
  1181. // Provider alias declared at the root, selected inside a module dir.
  1182. fs.writeFileSync(
  1183. path.join(tmpDir, 'providers.tf'),
  1184. 'provider "aws" {\n region = "us-east-1"\n}\n' +
  1185. 'provider "aws" {\n alias = "east"\n region = "us-east-2"\n}\n'
  1186. );
  1187. fs.mkdirSync(path.join(tmpDir, 'modules/app'), { recursive: true });
  1188. fs.writeFileSync(
  1189. path.join(tmpDir, 'modules/app/main.tf'),
  1190. 'resource "aws_s3_bucket" "b" {\n provider = aws.east\n bucket = "x"\n}\n'
  1191. );
  1192. // Moved block referencing a live resource.
  1193. fs.writeFileSync(
  1194. path.join(tmpDir, 'main.tf'),
  1195. 'resource "aws_instance" "renamed" {}\n' +
  1196. 'moved {\n from = aws_instance.old\n to = aws_instance.renamed\n}\n'
  1197. );
  1198. const cg = CodeGraph.initSync(tmpDir);
  1199. await cg.indexAll();
  1200. try {
  1201. const byQname = (q: string, file?: string) =>
  1202. cg
  1203. .getNodesByName(q.split('.').pop()!)
  1204. .filter((n) => n.qualifiedName === q && (!file || n.filePath === file));
  1205. // 1. remote-state bridge: consumer resource → producer component's output.
  1206. const consumer = byQname('aws_eks_cluster.this')[0] ??
  1207. cg.getNodesInFile('components/terraform/eks/cluster/main.tf').find((n) => n.qualifiedName === 'aws_eks_cluster.this');
  1208. expect(consumer, 'consumer resource').toBeDefined();
  1209. const producerOut = byQname('output.vpc_id', 'components/terraform/vpc/outputs.tf')[0];
  1210. expect(producerOut, "producer component's output").toBeDefined();
  1211. expect(
  1212. cg.getOutgoingEdges(consumer!.id).find((e) => e.target === producerOut!.id),
  1213. 'remote-state bridge edge eks/cluster → vpc output'
  1214. ).toBeDefined();
  1215. // 2. Ambiguous component name → no bridge edge to either candidate.
  1216. const zoneOut = byQname('output.zone', 'components/terraform/eks/cluster/dns.tf')[0];
  1217. expect(zoneOut).toBeDefined();
  1218. const zoneTargets = cg
  1219. .getOutgoingEdges(zoneOut!.id)
  1220. .map((e) => cg.getNode(e.target))
  1221. .filter((n) => n?.qualifiedName === 'output.zone_id');
  1222. expect(zoneTargets, 'ambiguous component must not be guessed').toHaveLength(0);
  1223. // 3. Provider alias: nodes are distinct, and the selection inside the
  1224. // module resolves up the tree to the aliased configuration.
  1225. const provNodes = cg.getNodesInFile('providers.tf');
  1226. const aliased = provNodes.find((n) => n.qualifiedName === 'provider.aws.east');
  1227. const defaultProv = provNodes.find((n) => n.qualifiedName === 'provider.aws');
  1228. expect(aliased, 'aliased provider node').toBeDefined();
  1229. expect(defaultProv, 'default provider node').toBeDefined();
  1230. const bucket = cg.getNodesInFile('modules/app/main.tf').find((n) => n.qualifiedName === 'aws_s3_bucket.b');
  1231. expect(bucket).toBeDefined();
  1232. const bucketEdges = cg.getOutgoingEdges(bucket!.id);
  1233. expect(
  1234. bucketEdges.find((e) => e.target === aliased!.id),
  1235. 'provider = aws.east → aliased provider (ancestor walk)'
  1236. ).toBeDefined();
  1237. expect(bucketEdges.find((e) => e.target === defaultProv!.id), 'must not link the default provider').toBeUndefined();
  1238. // 4. moved block: the file references the live resource.
  1239. const renamed = cg.getNodesInFile('main.tf').find((n) => n.qualifiedName === 'aws_instance.renamed');
  1240. expect(renamed).toBeDefined();
  1241. const rootFile = cg.getNodesInFile('main.tf').find((n) => n.kind === 'file');
  1242. expect(
  1243. cg.getOutgoingEdges(rootFile!.id).find((e) => e.target === renamed!.id),
  1244. 'moved block → live resource edge'
  1245. ).toBeDefined();
  1246. } finally {
  1247. cg.close();
  1248. }
  1249. });
  1250. });