/** * Unit Tests — graph-db.js * Asserts the three P0 tables exist and that GRAPH_DB_PATH env override * actually redirects the underlying sqlite file (regression guard against * the benchmark-db.js "declared but never read" bug). */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import fs from 'fs'; import path from 'path'; import Database from 'better-sqlite3'; describe('graph-db', () => { let graphDb; const TEST_DB_PATH = '/tmp/test-graph-db.sqlite'; const DEFAULT_DB_PATH = path.resolve(__dirname, '../../../data/graph.sqlite'); beforeAll(() => { if (fs.existsSync(TEST_DB_PATH)) fs.unlinkSync(TEST_DB_PATH); process.env.GRAPH_DB_PATH = TEST_DB_PATH; delete require.cache[require.resolve('../../services/graph-db')]; graphDb = require('../../services/graph-db'); }); afterAll(() => { try { fs.unlinkSync(TEST_DB_PATH); } catch {} try { fs.unlinkSync(`${TEST_DB_PATH}-shm`); } catch {} try { fs.unlinkSync(`${TEST_DB_PATH}-wal`); } catch {} delete process.env.GRAPH_DB_PATH; }); it('should create all three tables', () => { const d = graphDb.getDb(); const tables = d.prepare("SELECT name FROM sqlite_master WHERE type='table'").all().map(r => r.name); expect(tables).toContain('system_agents'); expect(tables).toContain('org_graph_nodes'); expect(tables).toContain('org_graph_edges'); }); it('should honor GRAPH_DB_PATH env override for reads/writes', () => { const d = graphDb.getDb(); const now = new Date().toISOString(); d.prepare(` INSERT INTO system_agents (id, name, scope, owner_company_id, source_kind, legacy_path, status, benchmark_score, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `).run('test-agent-env-check', 'Test Agent', 'public', null, 'global_agent', 'system/agents/test-agent-env-check', 'active', null, now, now); // The row must have landed in the overridden file, not the default one. expect(fs.existsSync(TEST_DB_PATH)).toBe(true); // Prove the override actually redirected the file: the default-path DB // (opened independently, never touched by graph-db in this test run) // must NOT contain the row we just wrote. if (fs.existsSync(DEFAULT_DB_PATH)) { const defaultDb = new Database(DEFAULT_DB_PATH, { readonly: true }); try { const row = defaultDb.prepare('SELECT 1 FROM system_agents WHERE id = ?').get('test-agent-env-check'); expect(row).toBeUndefined(); } finally { defaultDb.close(); } } else { // Default DB file was never created at all -- also proves the write // went to the overridden path instead of the default one. expect(fs.existsSync(DEFAULT_DB_PATH)).toBe(false); } }); });