foundation.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529
  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('should return correct database size', () => {
  99. const cg = CodeGraph.initSync(tempDir);
  100. const stats = cg.getStats();
  101. // Database should have some size (at least the schema)
  102. expect(stats.dbSizeBytes).toBeGreaterThan(0);
  103. cg.close();
  104. });
  105. it('should support optimize operation', () => {
  106. const cg = CodeGraph.initSync(tempDir);
  107. // Should not throw
  108. expect(() => cg.optimize()).not.toThrow();
  109. cg.close();
  110. });
  111. it('should support clear operation', () => {
  112. const cg = CodeGraph.initSync(tempDir);
  113. // Should not throw
  114. expect(() => cg.clear()).not.toThrow();
  115. const stats = cg.getStats();
  116. expect(stats.nodeCount).toBe(0);
  117. cg.close();
  118. });
  119. });
  120. // recreate() backs `codegraph index`: it discards the existing DB and returns
  121. // a fresh, empty instance rather than DELETE-clearing in place — the path that
  122. // recovers a poisoned/oversized prior index without wedging (#1067).
  123. describe('Recreate (#1067)', () => {
  124. it('returns a fresh, empty, usable instance', async () => {
  125. const cg = CodeGraph.initSync(tempDir);
  126. // Give the DB some content so "empty afterwards" is meaningful.
  127. fs.writeFileSync(path.join(tempDir, 'a.ts'), 'export function f() { return 1; }\n');
  128. await cg.indexAll();
  129. expect(cg.getStats().nodeCount).toBeGreaterThan(0);
  130. cg.close();
  131. const fresh = await CodeGraph.recreate(tempDir);
  132. try {
  133. // Empty graph, but a working instance: re-indexing repopulates it.
  134. expect(fresh.getStats().nodeCount).toBe(0);
  135. const result = await fresh.indexAll();
  136. expect(result.success).toBe(true);
  137. expect(fresh.getStats().nodeCount).toBeGreaterThan(0);
  138. } finally {
  139. fresh.close();
  140. }
  141. });
  142. it('discards the old database file rather than emptying it in place', async () => {
  143. const cg = CodeGraph.initSync(tempDir);
  144. await cg.indexAll();
  145. cg.close();
  146. // Stamp a sentinel into the existing DB header. PRAGMA user_version is
  147. // untouched by DELETE, so an in-place clear() would preserve it — but a
  148. // from-scratch recreate cannot. (An inode-equality check is unreliable:
  149. // ext4/overlayfs recycle the inode number after unlink+recreate, so a
  150. // "new inode" assertion false-fails on Linux while passing on macOS.)
  151. const dbPath = getDatabasePath(tempDir);
  152. const stamp = DatabaseConnection.open(dbPath);
  153. stamp.getDb().pragma('user_version = 4242');
  154. stamp.close();
  155. const fresh = await CodeGraph.recreate(tempDir);
  156. fresh.close();
  157. // The file exists, and the sentinel is gone — proof the old DB was
  158. // discarded and rebuilt, not row-DELETE'd in place (the path that wedged
  159. // on a poisoned graph, #1067).
  160. expect(fs.existsSync(dbPath)).toBe(true);
  161. const check = DatabaseConnection.open(dbPath);
  162. const userVersion = pragmaValue(check.getDb().pragma('user_version'), 'user_version');
  163. check.close();
  164. expect(Number(userVersion)).not.toBe(4242);
  165. });
  166. it('throws a clear error when the project is not initialized', async () => {
  167. await expect(CodeGraph.recreate(tempDir)).rejects.toThrow(/not initialized/i);
  168. });
  169. });
  170. describe('removeDatabaseFiles (#1067)', () => {
  171. it('deletes the database and its -wal/-shm sidecars', () => {
  172. const cg = CodeGraph.initSync(tempDir);
  173. cg.close();
  174. const dbPath = getDatabasePath(tempDir);
  175. // Materialise the WAL sidecars so we can prove they're cleaned up too.
  176. fs.writeFileSync(dbPath + '-wal', 'x');
  177. fs.writeFileSync(dbPath + '-shm', 'x');
  178. expect(fs.existsSync(dbPath)).toBe(true);
  179. removeDatabaseFiles(dbPath);
  180. expect(fs.existsSync(dbPath)).toBe(false);
  181. expect(fs.existsSync(dbPath + '-wal')).toBe(false);
  182. expect(fs.existsSync(dbPath + '-shm')).toBe(false);
  183. });
  184. it('is a no-op (does not throw) when the files are already gone', () => {
  185. const dbPath = getDatabasePath(tempDir);
  186. expect(fs.existsSync(dbPath)).toBe(false);
  187. expect(() => removeDatabaseFiles(dbPath)).not.toThrow();
  188. });
  189. });
  190. describe('Directory Management', () => {
  191. it('should validate directory structure', () => {
  192. const cg = CodeGraph.initSync(tempDir);
  193. cg.close();
  194. const validation = validateDirectory(tempDir);
  195. expect(validation.valid).toBe(true);
  196. expect(validation.errors).toHaveLength(0);
  197. });
  198. it('should detect invalid directory', () => {
  199. const validation = validateDirectory(tempDir);
  200. expect(validation.valid).toBe(false);
  201. expect(validation.errors.length).toBeGreaterThan(0);
  202. });
  203. it('upgrades a stale pre-wildcard .gitignore in place (issue #788)', () => {
  204. const cg = CodeGraph.initSync(tempDir);
  205. cg.close();
  206. const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
  207. // A .gitignore written by an older version (<= 0.9.9): an explicit
  208. // allowlist that never ignored daemon.pid, so the daemon's runtime
  209. // pidfile got committed.
  210. const staleV099 =
  211. '# CodeGraph data files\n' +
  212. '# These are local to each machine and should not be committed\n\n' +
  213. '# Database\n*.db\n*.db-wal\n*.db-shm\n\n' +
  214. '# Cache\ncache/\n\n# Logs\n*.log\n\n# Hook markers\n.dirty\n';
  215. fs.writeFileSync(gitignorePath, staleV099, 'utf-8');
  216. // Opening the project runs validateDirectory, which self-heals.
  217. const cg2 = CodeGraph.openSync(tempDir);
  218. cg2.close();
  219. const upgraded = fs.readFileSync(gitignorePath, 'utf-8');
  220. expect(upgraded).toContain('\n*\n'); // wildcard ignores everything…
  221. expect(upgraded).toContain('!.gitignore'); // …except this file
  222. expect(upgraded).not.toContain('.dirty'); // old explicit list is gone
  223. });
  224. it('leaves a user-customized .codegraph/.gitignore untouched', () => {
  225. const cg = CodeGraph.initSync(tempDir);
  226. cg.close();
  227. const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
  228. // No CodeGraph header → user-authored → must not be rewritten.
  229. const custom = '# my own rules\n*.db\n!keep-this.json\n';
  230. fs.writeFileSync(gitignorePath, custom, 'utf-8');
  231. const cg2 = CodeGraph.openSync(tempDir);
  232. cg2.close();
  233. expect(fs.readFileSync(gitignorePath, 'utf-8')).toBe(custom);
  234. });
  235. });
  236. describe('Uninitialize', () => {
  237. it('should remove .CodeGraph directory', () => {
  238. const cg = CodeGraph.initSync(tempDir);
  239. cg.uninitialize();
  240. expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(false);
  241. expect(CodeGraph.isInitialized(tempDir)).toBe(false);
  242. });
  243. });
  244. describe('Close/Destroy', () => {
  245. it('should close database but keep .CodeGraph directory', () => {
  246. const cg = CodeGraph.initSync(tempDir);
  247. cg.destroy(); // destroy is alias for close
  248. expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(true);
  249. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  250. });
  251. });
  252. describe('Graph Query Methods', () => {
  253. it('should throw "Node not found" for non-existent nodes', () => {
  254. const cg = CodeGraph.initSync(tempDir);
  255. // getContext throws for non-existent nodes
  256. expect(() => cg.getContext('non-existent')).toThrow(/not found/i);
  257. cg.close();
  258. });
  259. it('should return empty results for non-existent nodes', () => {
  260. const cg = CodeGraph.initSync(tempDir);
  261. // These methods return empty results instead of throwing
  262. const traverseResult = cg.traverse('non-existent');
  263. expect(traverseResult.nodes.size).toBe(0);
  264. const callGraph = cg.getCallGraph('non-existent');
  265. expect(callGraph.nodes.size).toBe(0);
  266. const typeHierarchy = cg.getTypeHierarchy('non-existent');
  267. expect(typeHierarchy.nodes.size).toBe(0);
  268. const usages = cg.findUsages('non-existent');
  269. expect(usages.length).toBe(0);
  270. cg.close();
  271. });
  272. });
  273. });
  274. describe('Database Connection', () => {
  275. let tempDir: string;
  276. beforeEach(() => {
  277. tempDir = createTempDir();
  278. });
  279. afterEach(() => {
  280. cleanupTempDir(tempDir);
  281. });
  282. it('should initialize new database', () => {
  283. const dbPath = path.join(tempDir, 'test.db');
  284. const db = DatabaseConnection.initialize(dbPath);
  285. expect(db.isOpen()).toBe(true);
  286. expect(fs.existsSync(dbPath)).toBe(true);
  287. db.close();
  288. });
  289. it('should get schema version', () => {
  290. const dbPath = path.join(tempDir, 'test.db');
  291. const db = DatabaseConnection.initialize(dbPath);
  292. const version = db.getSchemaVersion();
  293. expect(version).not.toBeNull();
  294. // A freshly initialized database records the current version outright
  295. // (schema.sql already contains every migration's end state).
  296. expect(version?.version).toBe(CURRENT_SCHEMA_VERSION);
  297. db.close();
  298. });
  299. it('should support transactions', () => {
  300. const dbPath = path.join(tempDir, 'test.db');
  301. const db = DatabaseConnection.initialize(dbPath);
  302. const result = db.transaction(() => {
  303. return 42;
  304. });
  305. expect(result).toBe(42);
  306. db.close();
  307. });
  308. it('should throw when opening non-existent database', () => {
  309. const dbPath = path.join(tempDir, 'nonexistent.db');
  310. expect(() => DatabaseConnection.open(dbPath)).toThrow(/not found/i);
  311. });
  312. });
  313. describe('Query Builder', () => {
  314. let tempDir: string;
  315. let cg: CodeGraph;
  316. beforeEach(() => {
  317. tempDir = createTempDir();
  318. cg = CodeGraph.initSync(tempDir);
  319. });
  320. afterEach(() => {
  321. cg.close();
  322. cleanupTempDir(tempDir);
  323. });
  324. it('should return null for non-existent node', () => {
  325. const node = cg.getNode('nonexistent');
  326. expect(node).toBeNull();
  327. });
  328. it('should return empty array for nodes in non-existent file', () => {
  329. const nodes = cg.getNodesInFile('nonexistent.ts');
  330. expect(nodes).toEqual([]);
  331. });
  332. it('should return empty array for edges from non-existent node', () => {
  333. const edges = cg.getOutgoingEdges('nonexistent');
  334. expect(edges).toEqual([]);
  335. });
  336. it('should return null for non-existent file', () => {
  337. const file = cg.getFile('nonexistent.ts');
  338. expect(file).toBeNull();
  339. });
  340. it('should return empty array for files when none tracked', () => {
  341. const files = cg.getFiles();
  342. expect(files).toEqual([]);
  343. });
  344. });
  345. // Two environments that share one working tree (Windows-native + WSL) must not
  346. // share one `.codegraph/`. CODEGRAPH_DIR overrides the data directory name so
  347. // each side keeps its own index in the same tree (issue #636).
  348. describe('CODEGRAPH_DIR override (#636)', () => {
  349. const saved = process.env.CODEGRAPH_DIR;
  350. let tempDir: string;
  351. beforeEach(() => {
  352. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-dirname-'));
  353. });
  354. afterEach(() => {
  355. if (saved === undefined) delete process.env.CODEGRAPH_DIR;
  356. else process.env.CODEGRAPH_DIR = saved;
  357. fs.rmSync(tempDir, { recursive: true, force: true });
  358. });
  359. describe('codeGraphDirName()', () => {
  360. it('defaults to .codegraph when unset', () => {
  361. delete process.env.CODEGRAPH_DIR;
  362. expect(codeGraphDirName()).toBe('.codegraph');
  363. });
  364. it('honors a valid override', () => {
  365. process.env.CODEGRAPH_DIR = '.codegraph-win';
  366. expect(codeGraphDirName()).toBe('.codegraph-win');
  367. });
  368. // Anything that isn't a plain segment could escape the project root or
  369. // clobber it, so it's ignored in favor of the default.
  370. it.each(['foo/bar', 'a\\b', '..', '../x', '.', '/abs/path', ' ', ''])(
  371. 'falls back to .codegraph for invalid value %j',
  372. (bad) => {
  373. process.env.CODEGRAPH_DIR = bad;
  374. expect(codeGraphDirName()).toBe('.codegraph');
  375. }
  376. );
  377. });
  378. describe('isCodeGraphDataDir()', () => {
  379. it('matches the default, the active override, and .codegraph-* siblings', () => {
  380. process.env.CODEGRAPH_DIR = '.codegraph-win';
  381. expect(isCodeGraphDataDir('.codegraph')).toBe(true); // the other env's dir
  382. expect(isCodeGraphDataDir('.codegraph-win')).toBe(true); // active override
  383. expect(isCodeGraphDataDir('.codegraph-wsl')).toBe(true); // any sibling
  384. });
  385. it('does not match unrelated directories', () => {
  386. delete process.env.CODEGRAPH_DIR;
  387. for (const name of ['src', 'node_modules', '.git', 'codegraph', '.codegraphextra']) {
  388. expect(isCodeGraphDataDir(name)).toBe(false);
  389. }
  390. });
  391. });
  392. it('init writes the index under the overridden directory, not .codegraph', () => {
  393. process.env.CODEGRAPH_DIR = '.codegraph-win';
  394. const cg = CodeGraph.initSync(tempDir);
  395. try {
  396. expect(fs.existsSync(path.join(tempDir, '.codegraph-win', 'codegraph.db'))).toBe(true);
  397. expect(fs.existsSync(path.join(tempDir, '.codegraph'))).toBe(false);
  398. expect(getCodeGraphDir(tempDir)).toBe(path.join(tempDir, '.codegraph-win'));
  399. expect(CodeGraph.isInitialized(tempDir)).toBe(true);
  400. } finally {
  401. cg.close();
  402. }
  403. });
  404. it('two index dirs coexist in one tree and the override side skips the sibling', async () => {
  405. // WSL side: default `.codegraph`, with a source file.
  406. delete process.env.CODEGRAPH_DIR;
  407. fs.writeFileSync(path.join(tempDir, 'app.ts'), 'export function onlyReal() {}\n');
  408. const wsl = await CodeGraph.init(tempDir, { index: true });
  409. wsl.close();
  410. // Windows side: override dir, same tree. Plant a decoy source file INSIDE
  411. // the WSL data dir — the override-side index must not pick it up.
  412. process.env.CODEGRAPH_DIR = '.codegraph-win';
  413. fs.writeFileSync(path.join(tempDir, '.codegraph', 'decoy.ts'), 'export function decoyLeak() {}\n');
  414. const win = await CodeGraph.init(tempDir, { index: true });
  415. try {
  416. expect(fs.existsSync(path.join(tempDir, '.codegraph', 'codegraph.db'))).toBe(true);
  417. expect(fs.existsSync(path.join(tempDir, '.codegraph-win', 'codegraph.db'))).toBe(true);
  418. expect(win.searchNodes('onlyReal').length).toBeGreaterThan(0);
  419. expect(win.searchNodes('decoyLeak')).toEqual([]); // sibling data dir not indexed
  420. } finally {
  421. win.close();
  422. }
  423. });
  424. });