1
0

foundation.test.ts 17 KB

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