frameworks-integration.test.ts 57 KB

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