foundation.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. /**
  2. * Foundation Tests
  3. *
  4. * Tests for the CodeGraph foundation layer.
  5. */
  6. import { describe, it, expect, beforeEach, afterEach } from 'vitest';
  7. import * as fs from 'fs';
  8. import * as path from 'path';
  9. import * as os from 'os';
  10. import { CodeGraph } from '../src';
  11. import { Node, Edge } from '../src/types';
  12. import { isInitialized, getCodeGraphDir, validateDirectory, codeGraphDirName, isCodeGraphDataDir } from '../src/directory';
  13. import { DatabaseConnection, getDatabasePath, removeDatabaseFiles } from '../src/db';
  14. import { CURRENT_SCHEMA_VERSION } from '../src/db/migrations';
  15. // Create a temporary directory for each test
  16. function createTempDir(): string {
  17. return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
  18. }
  19. // Clean up temporary directory
  20. function cleanupTempDir(dir: string): void {
  21. if (fs.existsSync(dir)) {
  22. fs.rmSync(dir, { recursive: true, force: true });
  23. }
  24. }
  25. /** Normalize a PRAGMA read across return shapes (array | object | scalar). */
  26. function pragmaValue(raw: unknown, key: string): unknown {
  27. const row = Array.isArray(raw) ? raw[0] : raw;
  28. if (row !== null && typeof row === 'object') return (row as Record<string, unknown>)[key];
  29. return row;
  30. }
  31. describe('CodeGraph Foundation', () => {
  32. let tempDir: string;
  33. beforeEach(() => {
  34. tempDir = createTempDir();
  35. });
  36. afterEach(() => {
  37. cleanupTempDir(tempDir);
  38. });
  39. describe('Initialization', () => {
  40. it('should initialize a new project', () => {
  41. const cg = CodeGraph.initSync(tempDir);
  42. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  43. expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(true);
  44. expect(fs.existsSync(getDatabasePath(tempDir))).toBe(true);
  45. cg.close();
  46. });
  47. it('should create .gitignore in .CodeGraph directory', () => {
  48. const cg = CodeGraph.initSync(tempDir);
  49. const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
  50. expect(fs.existsSync(gitignorePath)).toBe(true);
  51. const content = fs.readFileSync(gitignorePath, 'utf-8');
  52. // Ignore everything in .codegraph/ except this file itself, so transient
  53. // files (db, daemon.pid, sockets, logs) never show up in git. (#492, #484)
  54. expect(content).toContain('*');
  55. expect(content).toContain('!.gitignore');
  56. cg.close();
  57. });
  58. it('should throw if already initialized', () => {
  59. const cg = CodeGraph.initSync(tempDir);
  60. cg.close();
  61. expect(() => CodeGraph.initSync(tempDir)).toThrow(/already initialized/i);
  62. });
  63. });
  64. describe('Opening Projects', () => {
  65. it('should open an existing project', () => {
  66. // First initialize
  67. const cg1 = CodeGraph.initSync(tempDir);
  68. cg1.close();
  69. // Then open
  70. const cg2 = CodeGraph.openSync(tempDir);
  71. expect(cg2.getProjectRoot()).toBe(path.resolve(tempDir));
  72. cg2.close();
  73. });
  74. it('should throw if not initialized', () => {
  75. expect(() => CodeGraph.openSync(tempDir)).toThrow(/not initialized/i);
  76. });
  77. });
  78. describe('Static Methods', () => {
  79. it('isInitialized should return false for new directory', () => {
  80. expect(CodeGraph.isInitialized(tempDir)).toBe(false);
  81. });
  82. it('isInitialized should return true after init', () => {
  83. const cg = CodeGraph.initSync(tempDir);
  84. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  85. cg.close();
  86. });
  87. });
  88. describe('Database', () => {
  89. it('should create database with correct schema', () => {
  90. const cg = CodeGraph.initSync(tempDir);
  91. // Check that we can get stats (requires tables to exist)
  92. const stats = cg.getStats();
  93. expect(stats.nodeCount).toBe(0);
  94. expect(stats.edgeCount).toBe(0);
  95. expect(stats.fileCount).toBe(0);
  96. cg.close();
  97. });
  98. it('restores every secondary index after a crash inside bulk parse load (#1556)', () => {
  99. const dbPath = getDatabasePath(tempDir);
  100. const first = DatabaseConnection.initialize(dbPath);
  101. const before = (first.getDb()
  102. .prepare("SELECT name FROM sqlite_master WHERE type = 'index' ORDER BY name")
  103. .all() as Array<{ name: string }>).map((r) => r.name);
  104. first.beginBulkParseLoad();
  105. first.close();
  106. const reopened = DatabaseConnection.open(dbPath);
  107. const after = (reopened.getDb()
  108. .prepare("SELECT name FROM sqlite_master WHERE type = 'index' ORDER BY name")
  109. .all() as Array<{ name: string }>).map((r) => r.name);
  110. reopened.close();
  111. expect(after).toEqual(before);
  112. });
  113. it('skips secondary-index DDL when the schema is already healthy', () => {
  114. const dbPath = getDatabasePath(tempDir);
  115. const connection = DatabaseConnection.initialize(dbPath);
  116. const db = connection.getDb();
  117. const originalExec = db.exec.bind(db);
  118. let execCalls = 0;
  119. db.exec = (sql: string) => {
  120. execCalls++;
  121. originalExec(sql);
  122. };
  123. (connection as any).healBulkSecondaryIndexes();
  124. connection.close();
  125. expect(execCalls).toBe(0);
  126. });
  127. it('should return correct database size', () => {
  128. const cg = CodeGraph.initSync(tempDir);
  129. const stats = cg.getStats();
  130. // Database should have some size (at least the schema)
  131. expect(stats.dbSizeBytes).toBeGreaterThan(0);
  132. cg.close();
  133. });
  134. it('should support optimize operation', () => {
  135. const cg = CodeGraph.initSync(tempDir);
  136. // Should not throw
  137. expect(() => cg.optimize()).not.toThrow();
  138. cg.close();
  139. });
  140. it('should support clear operation', () => {
  141. const cg = CodeGraph.initSync(tempDir);
  142. // Should not throw
  143. expect(() => cg.clear()).not.toThrow();
  144. const stats = cg.getStats();
  145. expect(stats.nodeCount).toBe(0);
  146. cg.close();
  147. });
  148. });
  149. // recreate() backs `codegraph index`: it discards the existing DB and returns
  150. // a fresh, empty instance rather than DELETE-clearing in place — the path that
  151. // recovers a poisoned/oversized prior index without wedging (#1067).
  152. describe('Recreate (#1067)', () => {
  153. it('returns a fresh, empty, usable instance', async () => {
  154. const cg = CodeGraph.initSync(tempDir);
  155. // Give the DB some content so "empty afterwards" is meaningful.
  156. fs.writeFileSync(path.join(tempDir, 'a.ts'), 'export function f() { return 1; }\n');
  157. await cg.indexAll();
  158. expect(cg.getStats().nodeCount).toBeGreaterThan(0);
  159. cg.close();
  160. const fresh = await CodeGraph.recreate(tempDir);
  161. try {
  162. // Empty graph, but a working instance: re-indexing repopulates it.
  163. expect(fresh.getStats().nodeCount).toBe(0);
  164. const result = await fresh.indexAll();
  165. expect(result.success).toBe(true);
  166. expect(fresh.getStats().nodeCount).toBeGreaterThan(0);
  167. } finally {
  168. fresh.close();
  169. }
  170. });
  171. it('discards the old database file rather than emptying it in place', async () => {
  172. const cg = CodeGraph.initSync(tempDir);
  173. await cg.indexAll();
  174. cg.close();
  175. // Stamp a sentinel into the existing DB header. PRAGMA user_version is
  176. // untouched by DELETE, so an in-place clear() would preserve it — but a
  177. // from-scratch recreate cannot. (An inode-equality check is unreliable:
  178. // ext4/overlayfs recycle the inode number after unlink+recreate, so a
  179. // "new inode" assertion false-fails on Linux while passing on macOS.)
  180. const dbPath = getDatabasePath(tempDir);
  181. const stamp = DatabaseConnection.open(dbPath);
  182. stamp.getDb().pragma('user_version = 4242');
  183. stamp.close();
  184. const fresh = await CodeGraph.recreate(tempDir);
  185. fresh.close();
  186. // The file exists, and the sentinel is gone — proof the old DB was
  187. // discarded and rebuilt, not row-DELETE'd in place (the path that wedged
  188. // on a poisoned graph, #1067).
  189. expect(fs.existsSync(dbPath)).toBe(true);
  190. const check = DatabaseConnection.open(dbPath);
  191. const userVersion = pragmaValue(check.getDb().pragma('user_version'), 'user_version');
  192. check.close();
  193. expect(Number(userVersion)).not.toBe(4242);
  194. });
  195. it('throws a clear error when the project is not initialized', async () => {
  196. await expect(CodeGraph.recreate(tempDir)).rejects.toThrow(/not initialized/i);
  197. });
  198. });
  199. describe('removeDatabaseFiles (#1067)', () => {
  200. it('deletes the database and its -wal/-shm sidecars', () => {
  201. const cg = CodeGraph.initSync(tempDir);
  202. cg.close();
  203. const dbPath = getDatabasePath(tempDir);
  204. // Materialise the WAL sidecars so we can prove they're cleaned up too.
  205. fs.writeFileSync(dbPath + '-wal', 'x');
  206. fs.writeFileSync(dbPath + '-shm', 'x');
  207. expect(fs.existsSync(dbPath)).toBe(true);
  208. removeDatabaseFiles(dbPath);
  209. expect(fs.existsSync(dbPath)).toBe(false);
  210. expect(fs.existsSync(dbPath + '-wal')).toBe(false);
  211. expect(fs.existsSync(dbPath + '-shm')).toBe(false);
  212. });
  213. it('is a no-op (does not throw) when the files are already gone', () => {
  214. const dbPath = getDatabasePath(tempDir);
  215. expect(fs.existsSync(dbPath)).toBe(false);
  216. expect(() => removeDatabaseFiles(dbPath)).not.toThrow();
  217. });
  218. });
  219. describe('Directory Management', () => {
  220. it('should validate directory structure', () => {
  221. const cg = CodeGraph.initSync(tempDir);
  222. cg.close();
  223. const validation = validateDirectory(tempDir);
  224. expect(validation.valid).toBe(true);
  225. expect(validation.errors).toHaveLength(0);
  226. });
  227. it('should detect invalid directory', () => {
  228. const validation = validateDirectory(tempDir);
  229. expect(validation.valid).toBe(false);
  230. expect(validation.errors.length).toBeGreaterThan(0);
  231. });
  232. it('upgrades a stale pre-wildcard .gitignore in place (issue #788)', () => {
  233. const cg = CodeGraph.initSync(tempDir);
  234. cg.close();
  235. const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
  236. // A .gitignore written by an older version (<= 0.9.9): an explicit
  237. // allowlist that never ignored daemon.pid, so the daemon's runtime
  238. // pidfile got committed.
  239. const staleV099 =
  240. '# CodeGraph data files\n' +
  241. '# These are local to each machine and should not be committed\n\n' +
  242. '# Database\n*.db\n*.db-wal\n*.db-shm\n\n' +
  243. '# Cache\ncache/\n\n# Logs\n*.log\n\n# Hook markers\n.dirty\n';
  244. fs.writeFileSync(gitignorePath, staleV099, 'utf-8');
  245. // Opening the project runs validateDirectory, which self-heals.
  246. const cg2 = CodeGraph.openSync(tempDir);
  247. cg2.close();
  248. const upgraded = fs.readFileSync(gitignorePath, 'utf-8');
  249. expect(upgraded).toContain('\n*\n'); // wildcard ignores everything…
  250. expect(upgraded).toContain('!.gitignore'); // …except this file
  251. expect(upgraded).not.toContain('.dirty'); // old explicit list is gone
  252. });
  253. it('leaves a user-customized .codegraph/.gitignore untouched', () => {
  254. const cg = CodeGraph.initSync(tempDir);
  255. cg.close();
  256. const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
  257. // No CodeGraph header → user-authored → must not be rewritten.
  258. const custom = '# my own rules\n*.db\n!keep-this.json\n';
  259. fs.writeFileSync(gitignorePath, custom, 'utf-8');
  260. const cg2 = CodeGraph.openSync(tempDir);
  261. cg2.close();
  262. expect(fs.readFileSync(gitignorePath, 'utf-8')).toBe(custom);
  263. });
  264. });
  265. describe('Uninitialize', () => {
  266. it('should remove .CodeGraph directory', () => {
  267. const cg = CodeGraph.initSync(tempDir);
  268. cg.uninitialize();
  269. expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(false);
  270. expect(CodeGraph.isInitialized(tempDir)).toBe(false);
  271. });
  272. });
  273. describe('Close/Destroy', () => {
  274. it('should close database but keep .CodeGraph directory', () => {
  275. const cg = CodeGraph.initSync(tempDir);
  276. cg.destroy(); // destroy is alias for close
  277. expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(true);
  278. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  279. });
  280. });
  281. describe('Graph Query Methods', () => {
  282. it('should throw "Node not found" for non-existent nodes', () => {
  283. const cg = CodeGraph.initSync(tempDir);
  284. // getContext throws for non-existent nodes
  285. expect(() => cg.getContext('non-existent')).toThrow(/not found/i);
  286. cg.close();
  287. });
  288. it('should return empty results for non-existent nodes', () => {
  289. const cg = CodeGraph.initSync(tempDir);
  290. // These methods return empty results instead of throwing
  291. const traverseResult = cg.traverse('non-existent');
  292. expect(traverseResult.nodes.size).toBe(0);
  293. const callGraph = cg.getCallGraph('non-existent');
  294. expect(callGraph.nodes.size).toBe(0);
  295. const typeHierarchy = cg.getTypeHierarchy('non-existent');
  296. expect(typeHierarchy.nodes.size).toBe(0);
  297. const usages = cg.findUsages('non-existent');
  298. expect(usages.length).toBe(0);
  299. cg.close();
  300. });
  301. });
  302. });
  303. describe('Database Connection', () => {
  304. let tempDir: string;
  305. beforeEach(() => {
  306. tempDir = createTempDir();
  307. });
  308. afterEach(() => {
  309. cleanupTempDir(tempDir);
  310. });
  311. it('should initialize new database', () => {
  312. const dbPath = path.join(tempDir, 'test.db');
  313. const db = DatabaseConnection.initialize(dbPath);
  314. expect(db.isOpen()).toBe(true);
  315. expect(fs.existsSync(dbPath)).toBe(true);
  316. db.close();
  317. });
  318. it('should get schema version', () => {
  319. const dbPath = path.join(tempDir, 'test.db');
  320. const db = DatabaseConnection.initialize(dbPath);
  321. const version = db.getSchemaVersion();
  322. expect(version).not.toBeNull();
  323. // A freshly initialized database records the current version outright
  324. // (schema.sql already contains every migration's end state).
  325. expect(version?.version).toBe(CURRENT_SCHEMA_VERSION);
  326. db.close();
  327. });
  328. it('should support transactions', () => {
  329. const dbPath = path.join(tempDir, 'test.db');
  330. const db = DatabaseConnection.initialize(dbPath);
  331. const result = db.transaction(() => {
  332. return 42;
  333. });
  334. expect(result).toBe(42);
  335. db.close();
  336. });
  337. it('should throw when opening non-existent database', () => {
  338. const dbPath = path.join(tempDir, 'nonexistent.db');
  339. expect(() => DatabaseConnection.open(dbPath)).toThrow(/not found/i);
  340. });
  341. });
  342. describe('Query Builder', () => {
  343. let tempDir: string;
  344. let cg: CodeGraph;
  345. beforeEach(() => {
  346. tempDir = createTempDir();
  347. cg = CodeGraph.initSync(tempDir);
  348. });
  349. afterEach(() => {
  350. cg.close();
  351. cleanupTempDir(tempDir);
  352. });
  353. it('should return null for non-existent node', () => {
  354. const node = cg.getNode('nonexistent');
  355. expect(node).toBeNull();
  356. });
  357. it('should return empty array for nodes in non-existent file', () => {
  358. const nodes = cg.getNodesInFile('nonexistent.ts');
  359. expect(nodes).toEqual([]);
  360. });
  361. it('should return empty array for edges from non-existent node', () => {
  362. const edges = cg.getOutgoingEdges('nonexistent');
  363. expect(edges).toEqual([]);
  364. });
  365. it('should return null for non-existent file', () => {
  366. const file = cg.getFile('nonexistent.ts');
  367. expect(file).toBeNull();
  368. });
  369. it('should return empty array for files when none tracked', () => {
  370. const files = cg.getFiles();
  371. expect(files).toEqual([]);
  372. });
  373. });
  374. // Two environments that share one working tree (Windows-native + WSL) must not
  375. // share one `.codegraph/`. CODEGRAPH_DIR overrides the data directory name so
  376. // each side keeps its own index in the same tree (issue #636).
  377. describe('CODEGRAPH_DIR override (#636)', () => {
  378. const saved = process.env.CODEGRAPH_DIR;
  379. let tempDir: string;
  380. beforeEach(() => {
  381. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-dirname-'));
  382. });
  383. afterEach(() => {
  384. if (saved === undefined) delete process.env.CODEGRAPH_DIR;
  385. else process.env.CODEGRAPH_DIR = saved;
  386. fs.rmSync(tempDir, { recursive: true, force: true });
  387. });
  388. describe('codeGraphDirName()', () => {
  389. it('defaults to .codegraph when unset', () => {
  390. delete process.env.CODEGRAPH_DIR;
  391. expect(codeGraphDirName()).toBe('.codegraph');
  392. });
  393. it('honors a valid override', () => {
  394. process.env.CODEGRAPH_DIR = '.codegraph-win';
  395. expect(codeGraphDirName()).toBe('.codegraph-win');
  396. });
  397. // Anything that isn't a plain segment could escape the project root or
  398. // clobber it, so it's ignored in favor of the default.
  399. it.each(['foo/bar', 'a\\b', '..', '../x', '.', '/abs/path', ' ', ''])(
  400. 'falls back to .codegraph for invalid value %j',
  401. (bad) => {
  402. process.env.CODEGRAPH_DIR = bad;
  403. expect(codeGraphDirName()).toBe('.codegraph');
  404. }
  405. );
  406. });
  407. describe('isCodeGraphDataDir()', () => {
  408. it('matches the default, the active override, and .codegraph-* siblings', () => {
  409. process.env.CODEGRAPH_DIR = '.codegraph-win';
  410. expect(isCodeGraphDataDir('.codegraph')).toBe(true); // the other env's dir
  411. expect(isCodeGraphDataDir('.codegraph-win')).toBe(true); // active override
  412. expect(isCodeGraphDataDir('.codegraph-wsl')).toBe(true); // any sibling
  413. });
  414. it('does not match unrelated directories', () => {
  415. delete process.env.CODEGRAPH_DIR;
  416. for (const name of ['src', 'node_modules', '.git', 'codegraph', '.codegraphextra']) {
  417. expect(isCodeGraphDataDir(name)).toBe(false);
  418. }
  419. });
  420. });
  421. it('init writes the index under the overridden directory, not .codegraph', () => {
  422. process.env.CODEGRAPH_DIR = '.codegraph-win';
  423. const cg = CodeGraph.initSync(tempDir);
  424. try {
  425. expect(fs.existsSync(path.join(tempDir, '.codegraph-win', 'codegraph.db'))).toBe(true);
  426. expect(fs.existsSync(path.join(tempDir, '.codegraph'))).toBe(false);
  427. expect(getCodeGraphDir(tempDir)).toBe(path.join(tempDir, '.codegraph-win'));
  428. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  429. } finally {
  430. cg.close();
  431. }
  432. });
  433. it('two index dirs coexist in one tree and the override side skips the sibling', async () => {
  434. // WSL side: default `.codegraph`, with a source file.
  435. delete process.env.CODEGRAPH_DIR;
  436. fs.writeFileSync(path.join(tempDir, 'app.ts'), 'export function onlyReal() {}\n');
  437. const wsl = await CodeGraph.init(tempDir, { index: true });
  438. wsl.close();
  439. // Windows side: override dir, same tree. Plant a decoy source file INSIDE
  440. // the WSL data dir — the override-side index must not pick it up.
  441. process.env.CODEGRAPH_DIR = '.codegraph-win';
  442. fs.writeFileSync(path.join(tempDir, '.codegraph', 'decoy.ts'), 'export function decoyLeak() {}\n');
  443. const win = await CodeGraph.init(tempDir, { index: true });
  444. try {
  445. expect(fs.existsSync(path.join(tempDir, '.codegraph', 'codegraph.db'))).toBe(true);
  446. expect(fs.existsSync(path.join(tempDir, '.codegraph-win', 'codegraph.db'))).toBe(true);
  447. expect(win.searchNodes('onlyReal').length).toBeGreaterThan(0);
  448. expect(win.searchNodes('decoyLeak')).toEqual([]); // sibling data dir not indexed
  449. } finally {
  450. win.close();
  451. }
  452. });
  453. });