Initial commit: codegraph (local-first code intelligence library + MCP server)

This commit is contained in:
xiaowei
2026-05-24 17:16:20 +08:00
commit 4a9833e67b
176 changed files with 52092 additions and 0 deletions
+152
View File
@@ -0,0 +1,152 @@
/**
* Issue #238 — "database is locked" on concurrent MCP tool calls.
*
* With node:sqlite (real WAL) as the backend, the fixes that remain relevant:
* 1. busy_timeout is a bounded few-second wait (not a 2-minute hang) and WAL is
* active — so a reader never blocks on a concurrent writer.
* 2. The MCP ToolHandler reuses the default instance when a tool passes a
* projectPath pointing at the default project, instead of opening a SECOND
* connection to the same DB.
*/
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import CodeGraph from '../src';
import { ToolHandler } from '../src/mcp/tools';
import { DatabaseConnection } from '../src/db';
/** Normalize a PRAGMA read across return shapes (array | object | scalar). */
function pragmaValue(raw: unknown, key: string): unknown {
const row = Array.isArray(raw) ? raw[0] : raw;
if (row !== null && typeof row === 'object') return (row as Record<string, unknown>)[key];
return row;
}
describe('issue #238 — connection PRAGMAs (#1)', () => {
let dir: string;
let conn: DatabaseConnection;
beforeAll(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg238-pragma-'));
conn = DatabaseConnection.initialize(path.join(dir, 'codegraph.db'));
});
afterAll(() => {
conn.close();
fs.rmSync(dir, { recursive: true, force: true });
});
it('uses a bounded busy_timeout, not the old 2-minute hang', () => {
const ms = Number(pragmaValue(conn.getDb().pragma('busy_timeout'), 'timeout'));
expect(ms).toBeGreaterThan(0);
expect(ms).toBeLessThanOrEqual(30000); // far below the old 120000
});
it('runs in WAL mode — the mode that lets readers proceed during a write', () => {
const mode = String(pragmaValue(conn.getDb().pragma('journal_mode'), 'journal_mode')).toLowerCase();
expect(mode).toBe('wal');
});
it('getJournalMode() surfaces the effective mode for status triage', () => {
expect(conn.getJournalMode()).toBe('wal');
});
});
describe('issue #238 — WAL lets a reader proceed during a writer', () => {
let dir: string;
beforeAll(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg238-wal-'));
});
afterAll(() => {
fs.rmSync(dir, { recursive: true, force: true });
});
it('a read on a 2nd connection succeeds while a writer holds the lock', () => {
const dbPath = path.join(dir, 'codegraph.db');
const writer = DatabaseConnection.initialize(dbPath);
// The property only holds under WAL; skip if the filesystem couldn't enable it.
if (writer.getJournalMode() !== 'wal') {
writer.close();
return;
}
const reader = DatabaseConnection.open(dbPath);
try {
writer.getDb().prepare('BEGIN EXCLUSIVE').run(); // hard write lock, held open
const t0 = Date.now();
const row = reader.getDb().prepare('SELECT COUNT(*) AS c FROM nodes').get() as { c: number };
const waited = Date.now() - t0;
expect(row.c).toBe(0);
expect(waited).toBeLessThan(1000); // proceeds immediately, no busy wait
} finally {
try { writer.getDb().prepare('COMMIT').run(); } catch { /* ignore */ }
reader.close();
writer.close();
}
});
});
describe('issue #238 — ToolHandler reuses the default instance (#2)', () => {
let dir: string;
let cg: CodeGraph;
let root: string;
let handler: ToolHandler;
beforeAll(async () => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg238-tools-'));
fs.writeFileSync(path.join(dir, 'a.ts'), 'export function helper(): number { return 1; }\n');
fs.writeFileSync(
path.join(dir, 'b.ts'),
"import { helper } from './a';\nexport function main(): number { return helper(); }\n"
);
cg = await CodeGraph.init(dir, { index: true });
root = cg.getProjectRoot();
handler = new ToolHandler(cg);
});
afterAll(() => {
cg.close();
fs.rmSync(dir, { recursive: true, force: true });
});
it('getCodeGraph(defaultRoot) returns the default instance, not a new connection', () => {
const openSpy = vi.spyOn(CodeGraph, 'openSync');
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const resolved = (handler as any).getCodeGraph(root);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const nested = (handler as any).getCodeGraph(path.join(root, 'does', 'not', 'exist'));
expect(resolved).toBe(cg);
expect(nested).toBe(cg); // a sub-path resolves up to the same default project
expect(openSpy).not.toHaveBeenCalled(); // no second connection opened
} finally {
openSpy.mockRestore();
}
});
it('concurrent read tool calls (mixed projectPath) all succeed without "database is locked"', async () => {
const openSpy = vi.spyOn(CodeGraph, 'openSync');
try {
const calls: Promise<{ content: Array<{ text: string }>; isError?: boolean }>[] = [
handler.execute('codegraph_search', { query: 'helper' }),
handler.execute('codegraph_search', { query: 'helper', projectPath: root }),
handler.execute('codegraph_callers', { symbol: 'helper', projectPath: root }),
handler.execute('codegraph_callees', { symbol: 'main' }),
handler.execute('codegraph_files', { projectPath: root }),
handler.execute('codegraph_status', { projectPath: root }),
];
const results = await Promise.all(calls);
for (const r of results) {
expect(r.isError).not.toBe(true);
expect(r.content[0]?.text ?? '').not.toMatch(/database is locked/i);
}
// Passing the default project's own path must not open a second connection.
expect(openSpy).not.toHaveBeenCalled();
} finally {
openSpy.mockRestore();
}
});
});
+374
View File
@@ -0,0 +1,374 @@
/**
* Context Builder Tests
*
* Tests for the context building functionality.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import CodeGraph from '../src/index';
describe('Context Builder', () => {
let testDir: string;
let cg: CodeGraph;
beforeEach(async () => {
testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-context-test-'));
// Create a sample codebase
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir);
// Create a payment service file
fs.writeFileSync(
path.join(srcDir, 'payment.ts'),
`/**
* Payment Service
* Handles payment processing logic.
*/
export interface PaymentResult {
success: boolean;
transactionId: string;
amount: number;
}
export class PaymentService {
private apiKey: string;
constructor(apiKey: string) {
this.apiKey = apiKey;
}
/**
* Process a payment for the given amount
*/
async processPayment(amount: number): Promise<PaymentResult> {
// Validate amount
if (amount <= 0) {
throw new Error('Invalid amount');
}
// Process payment
const transactionId = this.generateTransactionId();
return {
success: true,
transactionId,
amount,
};
}
private generateTransactionId(): string {
return 'txn_' + Math.random().toString(36).substring(2);
}
}
export function createPaymentService(apiKey: string): PaymentService {
return new PaymentService(apiKey);
}
`
);
// Create a checkout controller file
fs.writeFileSync(
path.join(srcDir, 'checkout.ts'),
`/**
* Checkout Controller
* Handles the checkout flow.
*/
import { PaymentService, PaymentResult } from './payment';
export interface CartItem {
id: string;
name: string;
price: number;
quantity: number;
}
export class CheckoutController {
private paymentService: PaymentService;
constructor(paymentService: PaymentService) {
this.paymentService = paymentService;
}
/**
* Process checkout for the given cart
*/
async processCheckout(cart: CartItem[]): Promise<PaymentResult> {
const total = this.calculateTotal(cart);
if (total === 0) {
throw new Error('Cart is empty');
}
return this.paymentService.processPayment(total);
}
/**
* Calculate the total price of the cart
*/
calculateTotal(cart: CartItem[]): number {
return cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
}
`
);
// Create a utilities file
fs.writeFileSync(
path.join(srcDir, 'utils.ts'),
`/**
* Utility functions
*/
export function formatCurrency(amount: number): string {
return '$' + amount.toFixed(2);
}
export function validateEmail(email: string): boolean {
return email.includes('@');
}
`
);
// Initialize CodeGraph
cg = CodeGraph.initSync(testDir, {
config: {
include: ['**/*.ts'],
exclude: [],
},
});
// Index the codebase
await cg.indexAll();
});
afterEach(() => {
if (cg) {
cg.destroy();
}
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
describe('getCode()', () => {
it('should extract code for a node', async () => {
// Find the PaymentService class
const nodes = cg.getNodesByKind('class');
const paymentService = nodes.find((n) => n.name === 'PaymentService');
expect(paymentService).toBeDefined();
const code = await cg.getCode(paymentService!.id);
expect(code).not.toBeNull();
expect(code).toContain('class PaymentService');
expect(code).toContain('processPayment');
});
it('should return null for non-existent node', async () => {
const code = await cg.getCode('non-existent-id');
expect(code).toBeNull();
});
});
describe('findRelevantContext()', () => {
it('should find relevant nodes for a query', async () => {
// Use simple query that matches symbol names (FTS5 treats spaces as AND)
const result = await cg.findRelevantContext('PaymentService');
expect(result.nodes.size).toBeGreaterThan(0);
// Should find payment-related nodes
const nodeNames = Array.from(result.nodes.values()).map((n) => n.name);
expect(
nodeNames.some(
(name) =>
name.toLowerCase().includes('payment') ||
name.toLowerCase().includes('checkout')
)
).toBe(true);
});
it('should include edges in the result', async () => {
const result = await cg.findRelevantContext('checkout', {
traversalDepth: 2,
});
// Should have some edges from traversal
expect(result.edges).toBeDefined();
});
it('should respect maxNodes option', async () => {
const result = await cg.findRelevantContext('function', {
maxNodes: 5,
});
expect(result.nodes.size).toBeLessThanOrEqual(5);
});
});
describe('buildContext()', () => {
it('should build context with markdown format', async () => {
const result = await cg.buildContext('Fix checkout error', {
format: 'markdown',
maxCodeBlocks: 3,
});
expect(typeof result).toBe('string');
const markdown = result as string;
// Should contain markdown structure
expect(markdown).toContain('## Code Context');
expect(markdown).toContain('**Query:** Fix checkout error');
});
it('should build context with JSON format', async () => {
const result = await cg.buildContext('payment processing', {
format: 'json',
});
expect(typeof result).toBe('string');
const parsed = JSON.parse(result as string);
expect(parsed.query).toBe('payment processing');
expect(parsed.nodes).toBeDefined();
expect(Array.isArray(parsed.nodes)).toBe(true);
});
it('should accept object input with title and description', async () => {
const result = await cg.buildContext(
{
title: 'Checkout bug',
description: 'Cart total calculation is wrong',
},
{ format: 'markdown' }
);
expect(typeof result).toBe('string');
expect(result).toContain('Checkout bug: Cart total calculation is wrong');
});
it('should include code blocks when requested', async () => {
const result = await cg.buildContext('PaymentService', {
format: 'markdown',
includeCode: true,
maxCodeBlocks: 2,
});
const markdown = result as string;
// Should contain code blocks
expect(markdown).toContain('### Code');
expect(markdown).toContain('```typescript');
});
it('should exclude code blocks when requested', async () => {
const result = await cg.buildContext('payment', {
format: 'markdown',
includeCode: false,
});
const markdown = result as string;
// Should not contain code section
expect(markdown).not.toContain('### Code');
});
it('should include related symbols in compact format', async () => {
const result = await cg.buildContext('checkout', {
format: 'markdown',
maxNodes: 10,
});
const markdown = result as string;
// Compact format uses "Related Symbols" instead of verbose "Related Files"
// and groups symbols by file for compactness
expect(markdown).toContain('### Entry Points');
});
it('should have compact output without verbose stats footer', async () => {
const result = await cg.buildContext('payment', {
format: 'markdown',
});
const markdown = result as string;
// Compact format should NOT have verbose stats footer
expect(markdown).not.toMatch(/\*Context:.*symbols.*relationships.*files/);
// But should still have query
expect(markdown).toContain('**Query:**');
});
});
describe('Context structure', () => {
it('should find entry points from search', async () => {
const result = await cg.buildContext('PaymentService', {
format: 'json',
});
const parsed = JSON.parse(result as string);
expect(parsed.entryPoints).toBeDefined();
expect(parsed.entryPoints.length).toBeGreaterThan(0);
});
it('should traverse graph from entry points', async () => {
const result = await cg.buildContext('CheckoutController', {
format: 'json',
traversalDepth: 2,
});
const parsed = JSON.parse(result as string);
// Should have found related nodes through traversal
const nodeNames = parsed.nodes.map((n: { name: string }) => n.name);
// CheckoutController calls PaymentService, so both should be present
expect(
nodeNames.some((name: string) => name.includes('Checkout'))
).toBe(true);
});
});
describe('Edge cases', () => {
it('should handle empty query', async () => {
const result = await cg.buildContext('', { format: 'markdown' });
expect(typeof result).toBe('string');
});
it('should handle query with no matches', async () => {
const result = await cg.buildContext('xyznonexistent123', {
format: 'json',
});
const parsed = JSON.parse(result as string);
// Should return empty or minimal results
expect(parsed.nodes).toBeDefined();
});
it('should truncate long code blocks', async () => {
const result = await cg.buildContext('PaymentService', {
format: 'markdown',
maxCodeBlockSize: 100,
includeCode: true,
});
const markdown = result as string;
// Long code blocks should be truncated
if (markdown.includes('```typescript')) {
// If there's a code block, check for truncation marker if content was long
// This test validates the truncation logic works
expect(typeof markdown).toBe('string');
}
});
});
});
+161
View File
@@ -0,0 +1,161 @@
/**
* DB Performance / Correctness Tests
*
* Regression tests for three changes:
* 1. Batch `getNodesByIds` collapses graph-traversal N+1 reads.
* 2. `insertNode` invalidates the LRU cache so INSERT OR REPLACE
* doesn't serve a stale cached row on next `getNodeById`.
* 3. `runMaintenance` runs `PRAGMA optimize` + `wal_checkpoint(PASSIVE)`
* after indexAll/sync without throwing.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { DatabaseConnection } from '../src/db';
import { QueryBuilder } from '../src/db/queries';
import { Node } from '../src/types';
function makeNode(id: string, name = id): Node {
return {
id,
kind: 'function',
name,
qualifiedName: name,
filePath: 'a.ts',
language: 'typescript',
startLine: 1,
endLine: 1,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
}
describe('getNodesByIds (batch lookup)', () => {
let dir: string;
let db: DatabaseConnection;
let q: QueryBuilder;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'db-perf-batch-'));
db = DatabaseConnection.initialize(path.join(dir, 'test.db'));
q = new QueryBuilder(db.getDb());
});
afterEach(() => {
db.close();
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
});
it('returns a Map keyed by id, with one entry per existing node', () => {
q.insertNodes([makeNode('n1'), makeNode('n2'), makeNode('n3')]);
const out = q.getNodesByIds(['n1', 'n2', 'n3']);
expect(out.size).toBe(3);
expect(out.get('n1')!.name).toBe('n1');
expect(out.get('n3')!.name).toBe('n3');
});
it('omits missing IDs from the result map (no nulls, no exceptions)', () => {
q.insertNodes([makeNode('n1'), makeNode('n2')]);
const out = q.getNodesByIds(['n1', 'missing', 'n2']);
expect(out.size).toBe(2);
expect(out.has('missing')).toBe(false);
expect(out.has('n1')).toBe(true);
expect(out.has('n2')).toBe(true);
});
it('handles an empty input array', () => {
expect(q.getNodesByIds([]).size).toBe(0);
});
it('handles batches over the SQLite parameter limit (chunking)', () => {
// Insert 1500 nodes; the helper chunks at 500 internally.
const nodes = Array.from({ length: 1500 }, (_, i) => makeNode(`n${i}`));
q.insertNodes(nodes);
const ids = nodes.map((n) => n.id);
const out = q.getNodesByIds(ids);
expect(out.size).toBe(1500);
// Spot-check a few from the first / middle / last chunk.
expect(out.has('n0')).toBe(true);
expect(out.has('n750')).toBe(true);
expect(out.has('n1499')).toBe(true);
});
it('serves cache hits from memory and queries only the misses', () => {
q.insertNodes([makeNode('n1'), makeNode('n2'), makeNode('n3')]);
// Warm the cache for n1 only.
q.getNodeById('n1');
// Replace the underlying row to make a miss-vs-cache-hit detectable.
db.getDb().prepare('UPDATE nodes SET name = ? WHERE id = ?').run('changed', 'n1');
const out = q.getNodesByIds(['n1', 'n2']);
// The cached n1 (still 'n1', not 'changed') must be returned.
expect(out.get('n1')!.name).toBe('n1');
expect(out.get('n2')!.name).toBe('n2');
});
});
describe('insertNode cache invalidation', () => {
let dir: string;
let db: DatabaseConnection;
let q: QueryBuilder;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'db-perf-cache-'));
db = DatabaseConnection.initialize(path.join(dir, 'test.db'));
q = new QueryBuilder(db.getDb());
});
afterEach(() => {
db.close();
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
});
it('does not serve a stale cached node after INSERT OR REPLACE', () => {
// Regression: insertNode (which uses INSERT OR REPLACE) used to skip
// cache invalidation, so the next getNodeById returned the pre-replace
// version until LRU eviction.
const original = makeNode('n1', 'oldName');
q.insertNode(original);
const beforeReplace = q.getNodeById('n1');
expect(beforeReplace!.name).toBe('oldName');
// Replace via insertNode (the bug path).
q.insertNode({ ...original, name: 'newName', updatedAt: Date.now() });
const afterReplace = q.getNodeById('n1');
expect(afterReplace!.name).toBe('newName');
});
});
describe('runMaintenance', () => {
let dir: string;
let db: DatabaseConnection;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'db-perf-maint-'));
db = DatabaseConnection.initialize(path.join(dir, 'test.db'));
});
afterEach(() => {
db.close();
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
});
it('runs without throwing on a fresh database', () => {
expect(() => db.runMaintenance()).not.toThrow();
});
it('runs without throwing after writes', () => {
const q = new QueryBuilder(db.getDb());
q.insertNodes([makeNode('n1'), makeNode('n2')]);
expect(() => db.runMaintenance()).not.toThrow();
});
it('swallows failures rather than propagating (best-effort)', () => {
// Close the DB so the underlying handle would normally throw on any
// exec(). runMaintenance must still not propagate.
db.close();
expect(() => db.runMaintenance()).not.toThrow();
});
});
+518
View File
@@ -0,0 +1,518 @@
/**
* Tests for Drupal framework resolver.
*
* Unit tests cover drupalResolver.detect(), extract() (routes + hooks), and resolve().
* Integration tests use a real CodeGraph instance with a temporary Drupal project layout.
*/
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
import { CodeGraph } from '../src';
import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
import { drupalResolver } from '../src/resolution/frameworks/drupal';
import type { ResolutionContext } from '../src/resolution/types';
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function makeContext(
overrides: Partial<ResolutionContext> = {},
): ResolutionContext {
return {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: () => null,
getProjectRoot: () => '/project',
getAllFiles: () => [],
getNodesByLowerName: () => [],
getImportMappings: () => [],
...overrides,
};
}
// ---------------------------------------------------------------------------
// detect()
// ---------------------------------------------------------------------------
describe('drupalResolver.detect', () => {
it('returns true when composer.json has a drupal/ dependency', () => {
const ctx = makeContext({
readFile: (f) =>
f === 'composer.json'
? JSON.stringify({
require: {
'drupal/core-recommended': '~10.5',
'drush/drush': '^13',
},
})
: null,
});
expect(drupalResolver.detect(ctx)).toBe(true);
});
it('returns true when drupal/ dependency is in require-dev', () => {
const ctx = makeContext({
readFile: (f) =>
f === 'composer.json'
? JSON.stringify({ 'require-dev': { 'drupal/core': '^10' } })
: null,
});
expect(drupalResolver.detect(ctx)).toBe(true);
});
it('returns false when composer.json has no drupal/ dependencies', () => {
const ctx = makeContext({
readFile: (f) =>
f === 'composer.json'
? JSON.stringify({
require: { 'laravel/framework': '^10', php: '>=8.1' },
})
: null,
});
expect(drupalResolver.detect(ctx)).toBe(false);
});
it('returns false when composer.json is absent', () => {
const ctx = makeContext({ readFile: () => null });
expect(drupalResolver.detect(ctx)).toBe(false);
});
it('returns false when composer.json is malformed JSON', () => {
const ctx = makeContext({ readFile: () => '{ bad json' });
expect(drupalResolver.detect(ctx)).toBe(false);
});
});
// ---------------------------------------------------------------------------
// extract() — routing.yml
// ---------------------------------------------------------------------------
describe('drupalResolver.extract — routing.yml', () => {
const routing = `
mymodule.example:
path: '/mymodule/example'
defaults:
_controller: '\\Drupal\\mymodule\\Controller\\MyController::build'
_title: 'Example page'
requirements:
_permission: 'access content'
`;
it('emits a route node for each YAML route', () => {
const { nodes } = drupalResolver.extract!(
'mymodule/mymodule.routing.yml',
routing,
);
expect(nodes).toHaveLength(1);
expect(nodes[0]!.kind).toBe('route');
expect(nodes[0]!.name).toBe('/mymodule/example');
});
it('sets qualifiedName to filePath::routeName', () => {
const { nodes } = drupalResolver.extract!(
'mymodule/mymodule.routing.yml',
routing,
);
expect(nodes[0]!.qualifiedName).toBe(
'mymodule/mymodule.routing.yml::mymodule.example',
);
});
it('emits a references edge to the controller FQCN', () => {
const { references } = drupalResolver.extract!(
'mymodule/mymodule.routing.yml',
routing,
);
expect(references).toHaveLength(1);
expect(references[0]!.referenceName).toBe(
'\\Drupal\\mymodule\\Controller\\MyController::build',
);
expect(references[0]!.referenceKind).toBe('references');
});
it('emits a references edge to a _form handler', () => {
const src = `
mymodule.settings_form:
path: '/admin/config/mymodule'
defaults:
_form: '\\Drupal\\mymodule\\Form\\SettingsForm'
_title: 'MyModule settings'
requirements:
_permission: 'administer site configuration'
`;
const { nodes, references } = drupalResolver.extract!(
'mymodule/mymodule.routing.yml',
src,
);
expect(nodes).toHaveLength(1);
expect(references[0]!.referenceName).toBe(
'\\Drupal\\mymodule\\Form\\SettingsForm',
);
});
it('handles multiple routes in one file', () => {
const src = `
mod.page_one:
path: '/page-one'
defaults:
_controller: '\\Drupal\\mod\\Controller\\PageController::one'
requirements:
_permission: 'access content'
mod.page_two:
path: '/page-two'
defaults:
_controller: '\\Drupal\\mod\\Controller\\PageController::two'
requirements:
_permission: 'access content'
`;
const { nodes, references } = drupalResolver.extract!(
'mod/mod.routing.yml',
src,
);
expect(nodes).toHaveLength(2);
expect(nodes.map((n) => n.name)).toContain('/page-one');
expect(nodes.map((n) => n.name)).toContain('/page-two');
expect(references).toHaveLength(2);
});
it('skips commented-out lines', () => {
const src = `
mod.page:
path: '/page'
defaults:
#_controller: '\\Drupal\\mod\\Controller\\Old::build'
_controller: '\\Drupal\\mod\\Controller\\New::build'
requirements:
_permission: 'access content'
`;
const { references } = drupalResolver.extract!('mod/mod.routing.yml', src);
expect(references).toHaveLength(1);
expect(references[0]!.referenceName).toContain('New');
});
it('includes HTTP methods in the route node name when present', () => {
const src = `
mod.api:
path: '/api/resource'
defaults:
_controller: '\\Drupal\\mod\\Controller\\ApiController::get'
methods: [GET, POST]
requirements:
_permission: 'access content'
`;
const { nodes } = drupalResolver.extract!('mod/mod.routing.yml', src);
expect(nodes[0]!.name).toContain('GET');
expect(nodes[0]!.name).toContain('POST');
});
it('returns empty result for non-routing-yml files', () => {
const { nodes, references } = drupalResolver.extract!(
'mymodule.module',
'<?php\n',
);
// Module files go through hook detection, not route extraction
expect(nodes).toHaveLength(0);
});
it('returns empty result for files with no valid routes', () => {
const { nodes, references } = drupalResolver.extract!(
'some.routing.yml',
'# empty\n',
);
expect(nodes).toHaveLength(0);
expect(references).toHaveLength(0);
});
});
// ---------------------------------------------------------------------------
// extract() — hook detection in .module files
// ---------------------------------------------------------------------------
describe('drupalResolver.extract — hook detection', () => {
it('detects hook implementation via docblock (Strategy A)', () => {
const src = `<?php
/**
* Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, $form_state, $form_id) {
// ...
}
`;
const { references } = drupalResolver.extract!(
'web/modules/custom/mymodule/mymodule.module',
src,
);
const hookRef = references.find(
(r) => r.referenceName === 'hook_form_alter',
);
expect(hookRef).toBeDefined();
expect(hookRef!.referenceKind).toBe('references');
});
it('detects hook implementation via name pattern (Strategy B)', () => {
const src = `<?php
function mymodule_views_data() {
return [];
}
`;
const { references } = drupalResolver.extract!(
'web/modules/custom/mymodule/mymodule.module',
src,
);
const hookRef = references.find(
(r) => r.referenceName === 'hook_views_data',
);
expect(hookRef).toBeDefined();
});
it('does not emit a hook ref for non-hook helper functions', () => {
// 'other_module_helper' doesn't start with 'mymodule_', so no hook ref
const src = `<?php
function other_module_helper() {}
`;
const { references } = drupalResolver.extract!(
'web/modules/custom/mymodule/mymodule.module',
src,
);
expect(references).toHaveLength(0);
});
it('detects hooks in .install files', () => {
const src = `<?php
/**
* Implements hook_schema().
*/
function mymodule_schema() {
return [];
}
`;
const { references } = drupalResolver.extract!(
'web/modules/custom/mymodule/mymodule.install',
src,
);
const hookRef = references.find((r) => r.referenceName === 'hook_schema');
expect(hookRef).toBeDefined();
});
it('detects hooks in .theme files', () => {
const src = `<?php
/**
* Implements hook_preprocess_node().
*/
function mytheme_preprocess_node(&$variables) {}
`;
const { references } = drupalResolver.extract!(
'web/themes/custom/mytheme/mytheme.theme',
src,
);
const hookRef = references.find(
(r) => r.referenceName === 'hook_preprocess_node',
);
expect(hookRef).toBeDefined();
});
it('does not duplicate refs when both docblock and name pattern match', () => {
// Strategy A matches first and adds to docblockMatched set;
// Strategy B skips already-matched functions.
const src = `<?php
/**
* Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, $form_state, $form_id) {}
`;
const { references } = drupalResolver.extract!(
'web/modules/custom/mymodule/mymodule.module',
src,
);
const hookRefs = references.filter(
(r) => r.referenceName === 'hook_form_alter',
);
expect(hookRefs).toHaveLength(1);
});
});
// ---------------------------------------------------------------------------
// resolve()
// ---------------------------------------------------------------------------
describe('drupalResolver.resolve', () => {
it('resolves a _controller FQCN with ::method to the method node', () => {
const methodNode = {
id: 'method:abc123',
kind: 'method' as const,
name: 'build',
qualifiedName: 'MyController::build',
filePath: 'web/modules/custom/mymodule/src/Controller/MyController.php',
language: 'php' as const,
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: 0,
};
const classNode = {
id: 'class:def456',
kind: 'class' as const,
name: 'MyController',
qualifiedName: 'MyController',
filePath: 'web/modules/custom/mymodule/src/Controller/MyController.php',
language: 'php' as const,
startLine: 5,
endLine: 30,
startColumn: 0,
endColumn: 0,
updatedAt: 0,
};
const ctx = makeContext({
getNodesByName: (name) => (name === 'MyController' ? [classNode] : []),
getNodesInFile: () => [classNode, methodNode],
});
const ref = {
fromNodeId: 'route:x',
referenceName: '\\Drupal\\mymodule\\Controller\\MyController::build',
referenceKind: 'references' as const,
line: 1,
column: 0,
filePath: 'mymodule.routing.yml',
language: 'yaml' as const,
};
const resolved = drupalResolver.resolve(ref, ctx);
expect(resolved).not.toBeNull();
expect(resolved!.targetNodeId).toBe('method:abc123');
expect(resolved!.confidence).toBeGreaterThanOrEqual(0.85);
});
it('resolves a _form FQCN (no ::method) to the class node', () => {
const classNode = {
id: 'class:form123',
kind: 'class' as const,
name: 'SettingsForm',
qualifiedName: 'SettingsForm',
filePath: 'web/modules/custom/mymodule/src/Form/SettingsForm.php',
language: 'php' as const,
startLine: 1,
endLine: 50,
startColumn: 0,
endColumn: 0,
updatedAt: 0,
};
const ctx = makeContext({
getNodesByName: (name) => (name === 'SettingsForm' ? [classNode] : []),
});
const ref = {
fromNodeId: 'route:x',
referenceName: '\\Drupal\\mymodule\\Form\\SettingsForm',
referenceKind: 'references' as const,
line: 1,
column: 0,
filePath: 'mymodule.routing.yml',
language: 'yaml' as const,
};
const resolved = drupalResolver.resolve(ref, ctx);
expect(resolved).not.toBeNull();
expect(resolved!.targetNodeId).toBe('class:form123');
});
it('returns null when the target class cannot be found', () => {
const ctx = makeContext({ getNodesByName: () => [] });
const ref = {
fromNodeId: 'route:x',
referenceName: '\\Drupal\\mymodule\\Controller\\Missing::method',
referenceKind: 'references' as const,
line: 1,
column: 0,
filePath: 'mymodule.routing.yml',
language: 'yaml' as const,
};
expect(drupalResolver.resolve(ref, ctx)).toBeNull();
});
});
// ---------------------------------------------------------------------------
// End-to-end integration test
// ---------------------------------------------------------------------------
beforeAll(async () => {
await initGrammars();
await loadAllGrammars();
});
describe('Drupal end-to-end — route node linked to controller method', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('creates a route→controller edge from routing.yml to PHP class', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-drupal-'));
// Minimal composer.json to trigger Drupal detection
fs.writeFileSync(
path.join(tmpDir, 'composer.json'),
JSON.stringify({ require: { 'drupal/core-recommended': '~10.5' } }),
);
// Module directory structure
const modDir = path.join(tmpDir, 'web', 'modules', 'custom', 'my_module');
fs.mkdirSync(path.join(modDir, 'src', 'Controller'), { recursive: true });
// routing.yml
fs.writeFileSync(
path.join(modDir, 'my_module.routing.yml'),
[
'my_module.hello:',
" path: '/hello'",
' defaults:',
" _controller: '\\Drupal\\my_module\\Controller\\HelloController::build'",
" _title: 'Hello'",
' requirements:',
" _permission: 'access content'",
].join('\n') + '\n',
);
// PHP controller
fs.writeFileSync(
path.join(modDir, 'src', 'Controller', 'HelloController.php'),
[
'<?php',
'namespace Drupal\\my_module\\Controller;',
'use Drupal\\Core\\Controller\\ControllerBase;',
'class HelloController extends ControllerBase {',
' public function build() {',
" return ['#markup' => 'Hello'];",
' }',
'}',
].join('\n') + '\n',
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
// Route node must exist
const routes = cg.getNodesByKind('route');
expect(routes.length).toBeGreaterThan(0);
const route = routes.find((n) => n.name.includes('/hello'));
expect(route).toBeDefined();
// Controller method must be indexed
const methods = cg.getNodesByKind('method');
const buildMethod = methods.find((n) => n.name === 'build');
expect(buildMethod).toBeDefined();
// Edge: route → build method (or class fallback)
const edges = cg.getOutgoingEdges(route!.id);
expect(edges.length).toBeGreaterThan(0);
cg.close();
});
});
+123
View File
@@ -0,0 +1,123 @@
import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { CodeGraph } from '../../src/index.js';
import { scoreSearchNodes, scoreFindRelevantContext } from './scoring.js';
import { testCases } from './test-cases.js';
import type { EvalReport, EvalResult } from './types.js';
const codebasePath = process.env.EVAL_CODEBASE || process.argv[2];
if (!codebasePath) {
console.error('Usage: EVAL_CODEBASE=/path/to/codebase npx tsx __tests__/evaluation/runner.ts');
console.error(' or: npx tsx __tests__/evaluation/runner.ts /path/to/codebase');
process.exit(1);
}
const resolvedPath = path.resolve(codebasePath);
if (!fs.existsSync(path.join(resolvedPath, '.codegraph', 'codegraph.db'))) {
console.error(`No .codegraph/codegraph.db found at ${resolvedPath}`);
process.exit(1);
}
let codegraphSha = 'unknown';
try {
codegraphSha = execSync('git rev-parse --short HEAD', { encoding: 'utf-8' }).trim();
} catch {}
console.log(`\nCodeGraph Eval — ${path.basename(resolvedPath)}`);
console.log(`Codebase: ${resolvedPath}`);
console.log(`Commit: ${codegraphSha}`);
console.log(`Cases: ${testCases.length}`);
console.log('');
async function run() {
const cg = CodeGraph.openSync(resolvedPath);
const results: EvalResult[] = [];
for (const tc of testCases) {
const start = performance.now();
if (tc.api === 'searchNodes') {
const searchResults = cg.searchNodes(tc.query, {
limit: 10,
kinds: tc.kinds,
...(tc.options as Record<string, unknown>),
});
const latency = performance.now() - start;
const result = scoreSearchNodes(tc.id, tc.expectedSymbols, searchResults, latency);
results.push(result);
} else {
const subgraph = await cg.findRelevantContext(tc.query, {
searchLimit: 8,
traversalDepth: 3,
maxNodes: 80,
minScore: 0.2,
...(tc.options as Record<string, unknown>),
});
const latency = performance.now() - start;
const result = scoreFindRelevantContext(tc.id, tc.expectedSymbols, subgraph, latency);
results.push(result);
}
}
cg.close();
// Print results table
const maxIdLen = Math.max(...results.map((r) => r.caseId.length));
for (const r of results) {
const status = r.pass ? '\x1b[32mPASS\x1b[0m' : '\x1b[31mFAIL\x1b[0m';
const id = r.caseId.padEnd(maxIdLen);
const recall = `recall=${r.recall.toFixed(2)}`;
const extra =
r.edgeDensity !== undefined
? `density=${r.edgeDensity.toFixed(2)}`
: `mrr=${r.mrr.toFixed(2)}`;
const latency = `${Math.round(r.latencyMs)}ms`;
console.log(` ${id} ${status} ${recall} ${extra} ${latency}`);
if (r.missedSymbols.length > 0) {
console.log(` ${' '.repeat(maxIdLen)} missed: ${r.missedSymbols.join(', ')}`);
}
}
// Summary
const passed = results.filter((r) => r.pass).length;
const failed = results.length - passed;
const meanRecall = results.reduce((s, r) => s + r.recall, 0) / results.length;
const mrrResults = results.filter((r) => r.mrr > 0 || r.caseId.startsWith('search-'));
const meanMRR =
mrrResults.length > 0 ? mrrResults.reduce((s, r) => s + r.mrr, 0) / mrrResults.length : 0;
console.log('');
const summaryColor = failed === 0 ? '\x1b[32m' : '\x1b[33m';
console.log(
`${summaryColor}SUMMARY: ${passed}/${results.length} passed | recall=${meanRecall.toFixed(2)} | mrr=${meanMRR.toFixed(2)}\x1b[0m`
);
// Save JSON report
const report: EvalReport = {
timestamp: new Date().toISOString(),
codebasePath: resolvedPath,
codegraphSha,
summary: { total: results.length, passed, failed, meanRecall, meanMRR },
results,
};
const resultsDir = path.join(__dirname, 'results');
fs.mkdirSync(resultsDir, { recursive: true });
const reportFile = path.join(
resultsDir,
`${new Date().toISOString().replace(/[:.]/g, '-')}.json`
);
fs.writeFileSync(reportFile, JSON.stringify(report, null, 2));
console.log(`\nReport saved: ${reportFile}`);
process.exit(failed > 0 ? 1 : 0);
}
run().catch((err) => {
console.error(err);
process.exit(1);
});
+82
View File
@@ -0,0 +1,82 @@
import type { EvalResult } from './types.js';
export const PASS_THRESHOLD = 0.5;
export function scoreSearchNodes(
caseId: string,
expectedSymbols: string[],
results: Array<{ node: { name: string }; score: number }>,
latencyMs: number
): EvalResult {
const expectedLower = expectedSymbols.map((s) => s.toLowerCase());
const resultNames = results.map((r) => r.node.name.toLowerCase());
const found: string[] = [];
const missed: string[] = [];
let firstRank = 0;
for (let i = 0; i < expectedLower.length; i++) {
const idx = resultNames.indexOf(expectedLower[i]);
if (idx !== -1) {
found.push(expectedSymbols[i]);
if (firstRank === 0) firstRank = idx + 1;
} else {
missed.push(expectedSymbols[i]);
}
}
const recall = expectedSymbols.length > 0 ? found.length / expectedSymbols.length : 0;
const mrr = firstRank > 0 ? 1 / firstRank : 0;
return {
caseId,
pass: recall >= PASS_THRESHOLD,
recall,
mrr,
foundSymbols: found,
missedSymbols: missed,
latencyMs,
};
}
export function scoreFindRelevantContext(
caseId: string,
expectedSymbols: string[],
subgraph: { nodes: Map<string, { name: string }>; edges: unknown[]; roots: string[] },
latencyMs: number
): EvalResult {
const expectedLower = new Set(expectedSymbols.map((s) => s.toLowerCase()));
const nodeNames = new Set<string>();
for (const node of subgraph.nodes.values()) {
nodeNames.add(node.name.toLowerCase());
}
const found: string[] = [];
const missed: string[] = [];
for (const sym of expectedSymbols) {
if (nodeNames.has(sym.toLowerCase())) {
found.push(sym);
} else {
missed.push(sym);
}
}
const recall = expectedSymbols.length > 0 ? found.length / expectedSymbols.length : 0;
const nodeCount = subgraph.nodes.size;
const edgeCount = subgraph.edges.length;
const edgeDensity = nodeCount > 0 ? edgeCount / nodeCount : 0;
return {
caseId,
pass: recall >= PASS_THRESHOLD,
recall,
mrr: 0,
foundSymbols: found,
missedSymbols: missed,
nodeCount,
edgeCount,
edgeDensity,
latencyMs,
};
}
+93
View File
@@ -0,0 +1,93 @@
import type { EvalTestCase } from './types.js';
export const testCases: EvalTestCase[] = [
// === searchNodes: Symbol Lookup Precision ===
{
id: 'search-class-exact',
query: 'TransportService',
api: 'searchNodes',
expectedSymbols: ['TransportService'],
kinds: ['class'],
},
{
id: 'search-method-qualified',
query: 'TransportService sendRequest',
api: 'searchNodes',
expectedSymbols: ['sendRequest'],
kinds: ['method'],
},
{
id: 'search-interface',
query: 'ActionListener',
api: 'searchNodes',
expectedSymbols: ['ActionListener'],
kinds: ['interface'],
},
{
id: 'search-enum',
query: 'RestStatus',
api: 'searchNodes',
expectedSymbols: ['RestStatus'],
kinds: ['enum'],
},
{
id: 'search-exception',
query: 'SearchPhaseExecutionException',
api: 'searchNodes',
expectedSymbols: ['SearchPhaseExecutionException'],
kinds: ['class'],
},
{
id: 'search-nested-class',
query: 'Engine Index',
api: 'searchNodes',
expectedSymbols: ['Index'],
kinds: ['class'],
},
// === findRelevantContext: Exploration Quality ===
{
id: 'explore-rest-layer',
query: 'How does the REST layer handle HTTP requests?',
api: 'findRelevantContext',
expectedSymbols: ['RestController', 'RestHandler', 'BaseRestHandler', 'RestRequest'],
options: { searchLimit: 8, traversalDepth: 3, maxNodes: 80, minScore: 0.2 },
},
{
id: 'explore-search-execution',
query: 'How does search execution work from request to shard?',
api: 'findRelevantContext',
expectedSymbols: ['ShardSearchRequest', 'SearchShardsRequest', 'SearchShardsGroup'],
options: { searchLimit: 8, traversalDepth: 3, maxNodes: 80, minScore: 0.2 },
},
{
id: 'explore-bulk-indexing',
query: 'How does bulk indexing work?',
api: 'findRelevantContext',
expectedSymbols: ['TransportBulkAction', 'BulkRequest', 'BulkResponse'],
options: { searchLimit: 8, traversalDepth: 3, maxNodes: 80, minScore: 0.2 },
},
{
id: 'explore-shard-allocation',
query: 'How does shard rebalancing and allocation work?',
api: 'findRelevantContext',
expectedSymbols: ['AllocationService', 'BalancedShardsAllocator'],
options: { searchLimit: 8, traversalDepth: 3, maxNodes: 80, minScore: 0.2 },
},
{
id: 'explore-transport-search',
query: 'How does TransportService connect to SearchTransportService?',
api: 'findRelevantContext',
expectedSymbols: ['TransportService', 'SearchTransportService'],
options: { searchLimit: 8, traversalDepth: 3, maxNodes: 80, minScore: 0.2 },
},
{
id: 'explore-engine-implementations',
query: 'What are the Engine implementations for indexing?',
api: 'findRelevantContext',
expectedSymbols: ['InternalEngine', 'ReadOnlyEngine', 'Engine'],
options: { searchLimit: 8, traversalDepth: 3, maxNodes: 80, minScore: 0.2 },
},
];
+37
View File
@@ -0,0 +1,37 @@
import type { NodeKind } from '../../src/types.js';
export interface EvalTestCase {
id: string;
query: string;
api: 'searchNodes' | 'findRelevantContext';
expectedSymbols: string[];
kinds?: NodeKind[];
options?: Record<string, unknown>;
}
export interface EvalResult {
caseId: string;
pass: boolean;
recall: number;
mrr: number;
foundSymbols: string[];
missedSymbols: string[];
nodeCount?: number;
edgeCount?: number;
edgeDensity?: number;
latencyMs: number;
}
export interface EvalReport {
timestamp: string;
codebasePath: string;
codegraphSha: string;
summary: {
total: number;
passed: number;
failed: number;
meanRecall: number;
meanMRR: number;
};
results: EvalResult[];
}
+234
View File
@@ -0,0 +1,234 @@
/**
* Adaptive output budget for codegraph_explore (#185).
*
* The explore tool used to apply a fixed 35KB output cap regardless of
* project size, which on small codebases was a net loss vs. native
* grep+Read. These tests pin the per-tier budget shape so future tuning
* doesn't silently drift the small-project case back into bloat.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { getExploreOutputBudget, getExploreBudget, ToolHandler } from '../src/mcp/tools';
import CodeGraph from '../src/index';
describe('getExploreOutputBudget', () => {
it('returns a strictly smaller total cap for small projects than for huge ones', () => {
const small = getExploreOutputBudget(100);
const huge = getExploreOutputBudget(30000);
expect(small.maxOutputChars).toBeLessThan(huge.maxOutputChars);
expect(small.defaultMaxFiles).toBeLessThan(huge.defaultMaxFiles);
expect(small.maxCharsPerFile).toBeLessThan(huge.maxCharsPerFile);
});
it('caps total output well under 8000 tokens (~32k chars) on small projects', () => {
const small = getExploreOutputBudget(100);
expect(small.maxOutputChars).toBeLessThanOrEqual(20000);
});
it('keeps the historical 35k+ ceiling for medium-large projects so existing benchmarks do not regress', () => {
const large = getExploreOutputBudget(10000);
expect(large.maxOutputChars).toBeGreaterThanOrEqual(35000);
});
it('uses tier breakpoints matching getExploreBudget so call-count and output-budget agree on a project', () => {
// Anything in the same tier should pick the same total-output cap.
const tier1a = getExploreOutputBudget(50);
const tier1b = getExploreOutputBudget(499);
expect(tier1a.maxOutputChars).toBe(tier1b.maxOutputChars);
expect(getExploreBudget(50)).toBe(getExploreBudget(499));
const tier2a = getExploreOutputBudget(500);
const tier2b = getExploreOutputBudget(4999);
expect(tier2a.maxOutputChars).toBe(tier2b.maxOutputChars);
expect(getExploreBudget(500)).toBe(getExploreBudget(4999));
const tier3a = getExploreOutputBudget(5000);
const tier3b = getExploreOutputBudget(14999);
expect(tier3a.maxOutputChars).toBe(tier3b.maxOutputChars);
// And crossing a breakpoint changes the cap.
expect(tier1a.maxOutputChars).not.toBe(tier2a.maxOutputChars);
expect(tier2a.maxOutputChars).not.toBe(tier3a.maxOutputChars);
});
it('gates off "Additional relevant files", completeness signal, and budget note on small projects', () => {
const small = getExploreOutputBudget(100);
expect(small.includeAdditionalFiles).toBe(false);
expect(small.includeCompletenessSignal).toBe(false);
expect(small.includeBudgetNote).toBe(false);
});
it('keeps all meta-text on for projects that earn the breadth signal (>=500 files)', () => {
const medium = getExploreOutputBudget(1000);
expect(medium.includeAdditionalFiles).toBe(true);
expect(medium.includeCompletenessSignal).toBe(true);
expect(medium.includeBudgetNote).toBe(true);
});
it('keeps the Relationships section on for every tier — it is the cheapest structural signal', () => {
expect(getExploreOutputBudget(50).includeRelationships).toBe(true);
expect(getExploreOutputBudget(1000).includeRelationships).toBe(true);
expect(getExploreOutputBudget(10000).includeRelationships).toBe(true);
expect(getExploreOutputBudget(30000).includeRelationships).toBe(true);
});
it('caps the per-file header symbol list more tightly on small projects', () => {
// Without this cap, a file like Alamofire's Session.swift produced
// a 3.4KB symbol list in the `#### path — sym, sym, ...` header,
// dwarfing the per-file body cap.
const small = getExploreOutputBudget(100);
const huge = getExploreOutputBudget(30000);
expect(small.maxSymbolsInFileHeader).toBeLessThan(huge.maxSymbolsInFileHeader);
expect(small.maxSymbolsInFileHeader).toBeGreaterThan(0);
});
it('uses a tighter clustering gap threshold on small projects to break runaway single clusters', () => {
const small = getExploreOutputBudget(100);
const huge = getExploreOutputBudget(30000);
expect(small.gapThreshold).toBeLessThanOrEqual(huge.gapThreshold);
});
it('handles the boundary file counts exactly (off-by-one regression guard)', () => {
// 499 -> small tier, 500 -> medium tier
expect(getExploreOutputBudget(499).maxOutputChars).toBe(getExploreOutputBudget(100).maxOutputChars);
expect(getExploreOutputBudget(500).maxOutputChars).toBe(getExploreOutputBudget(1000).maxOutputChars);
// 4999 -> medium, 5000 -> large
expect(getExploreOutputBudget(4999).maxOutputChars).toBe(getExploreOutputBudget(1000).maxOutputChars);
expect(getExploreOutputBudget(5000).maxOutputChars).toBe(getExploreOutputBudget(10000).maxOutputChars);
// 14999 -> large, 15000 -> xlarge
expect(getExploreOutputBudget(14999).maxOutputChars).toBe(getExploreOutputBudget(10000).maxOutputChars);
expect(getExploreOutputBudget(15000).maxOutputChars).toBe(getExploreOutputBudget(30000).maxOutputChars);
});
});
/**
* End-to-end check that the budget is actually applied by handleExplore.
*
* Builds a tiny synthetic project (<500 files, so the small tier), indexes
* it, and confirms the output:
* - stays under the small-tier maxOutputChars cap
* - omits the meta-text the small tier gates off (completeness signal,
* budget note, "Additional relevant files")
*
* Regression guard for #185 — protects against future edits to handleExplore
* silently re-introducing the fixed 35KB cap on small projects.
*/
describe('codegraph_explore output respects the adaptive budget', () => {
let testDir: string;
let cg: CodeGraph;
let handler: ToolHandler;
beforeAll(async () => {
testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-explore-budget-'));
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir);
// A handful of files with one fat target file. The fat file mimics the
// Alamofire Session.swift case: many methods stacked on top of each other,
// which collapsed into one giant cluster pre-#185.
const fatLines: string[] = ['export class Session {'];
for (let i = 0; i < 30; i++) {
fatLines.push(` method${i}(arg: string): string {`);
fatLines.push(` return this.helper${i}(arg) + "${i}";`);
fatLines.push(` }`);
fatLines.push(` private helper${i}(arg: string): string {`);
fatLines.push(` return arg.repeat(${i + 1});`);
fatLines.push(` }`);
}
fatLines.push('}');
fs.writeFileSync(path.join(srcDir, 'session.ts'), fatLines.join('\n'));
// A few small supporting files so the project has >1 indexed file.
for (let i = 0; i < 5; i++) {
fs.writeFileSync(
path.join(srcDir, `support${i}.ts`),
`import { Session } from './session';\nexport function callSession${i}(s: Session) { return s.method${i}('hi'); }\n`
);
}
cg = CodeGraph.initSync(testDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
await cg.indexAll();
handler = new ToolHandler(cg);
});
afterAll(() => {
if (cg) cg.destroy();
if (testDir && fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('keeps total output under the small-project cap', async () => {
const result = await handler.execute('codegraph_explore', { query: 'Session method helper' });
const text = result.content?.[0]?.text ?? '';
const smallBudget = getExploreOutputBudget(100);
// Allow a small overshoot for the trailing markers — the cap is enforced
// per-file rather than as an absolute output ceiling.
expect(text.length).toBeLessThan(smallBudget.maxOutputChars + 500);
});
it('omits the meta-text gated off for small projects', async () => {
const result = await handler.execute('codegraph_explore', { query: 'Session method helper' });
const text = result.content?.[0]?.text ?? '';
expect(text).not.toContain('### Additional relevant files');
expect(text).not.toContain('Complete source code is included above');
expect(text).not.toContain('Explore budget:');
});
it('still includes the Relationships section — it is the cheapest structural signal', async () => {
const result = await handler.execute('codegraph_explore', { query: 'Session method helper' });
const text = result.content?.[0]?.text ?? '';
// Either there are relationships, or no edges were significant — both are fine.
// We just want to confirm we did not accidentally gate it off.
const hasRelationships = text.includes('### Relationships');
const sourceFollowsHeader = text.indexOf('### Source Code') > 0;
expect(hasRelationships || sourceFollowsHeader).toBe(true);
});
it('prefixes source lines with line numbers by default (cat -n style)', async () => {
delete process.env.CODEGRAPH_EXPLORE_LINENUMS;
const result = await handler.execute('codegraph_explore', { query: 'Session method helper' });
const text = result.content?.[0]?.text ?? '';
// At least one fenced source line should look like `<digits>\t<code>`.
expect(/\n\d+\t/.test(text)).toBe(true);
});
it('omits line numbers when CODEGRAPH_EXPLORE_LINENUMS=0', async () => {
process.env.CODEGRAPH_EXPLORE_LINENUMS = '0';
try {
const result = await handler.execute('codegraph_explore', { query: 'Session method helper' });
const text = result.content?.[0]?.text ?? '';
// The synthetic source has no tab-prefixed numeric lines of its own,
// so none should appear when the toggle is off.
expect(/\n\d+\t(?:export| )/.test(text)).toBe(false);
} finally {
delete process.env.CODEGRAPH_EXPLORE_LINENUMS;
}
});
it('uses language-neutral omission markers (no C-style // in the output)', async () => {
// The gap/trimmed separators must not assume `//` is a comment — that's
// wrong in Python, Ruby, etc. They render inside fenced source blocks.
const result = await handler.execute('codegraph_explore', { query: 'Session method helper' });
const text = result.content?.[0]?.text ?? '';
expect(text).not.toContain('// ... (gap)');
expect(text).not.toContain('// ... trimmed');
});
it('does not collapse a whole-file class into just its header (envelope filter)', async () => {
// The synthetic `Session` class spans the entire file. Without the
// envelope filter it would form one giant cluster that tail-trims to
// the class declaration, hiding the methods. Confirm real method bodies
// make it into the output. Regression guard for the #185 follow-up.
const result = await handler.execute('codegraph_explore', { query: 'Session method helper' });
const text = result.content?.[0]?.text ?? '';
// A method body line (`methodN(arg: string)`) should appear, not just
// the `export class Session {` opener.
const hasMethodBody = /method\d+\(arg: string\)/.test(text);
expect(hasMethodBody).toBe(true);
});
});
File diff suppressed because it is too large Load Diff
+305
View File
@@ -0,0 +1,305 @@
/**
* Foundation Tests
*
* Tests for the CodeGraph foundation layer.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph } from '../src';
import { Node, Edge } from '../src/types';
import { isInitialized, getCodeGraphDir, validateDirectory } from '../src/directory';
import { DatabaseConnection, getDatabasePath } from '../src/db';
// Create a temporary directory for each test
function createTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-test-'));
}
// Clean up temporary directory
function cleanupTempDir(dir: string): void {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
describe('CodeGraph Foundation', () => {
let tempDir: string;
beforeEach(() => {
tempDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(tempDir);
});
describe('Initialization', () => {
it('should initialize a new project', () => {
const cg = CodeGraph.initSync(tempDir);
expect(CodeGraph.isInitialized(tempDir)).toBe(true);
expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(true);
expect(fs.existsSync(getDatabasePath(tempDir))).toBe(true);
cg.close();
});
it('should create .gitignore in .CodeGraph directory', () => {
const cg = CodeGraph.initSync(tempDir);
const gitignorePath = path.join(getCodeGraphDir(tempDir), '.gitignore');
expect(fs.existsSync(gitignorePath)).toBe(true);
const content = fs.readFileSync(gitignorePath, 'utf-8');
expect(content).toContain('*.db');
cg.close();
});
it('should throw if already initialized', () => {
const cg = CodeGraph.initSync(tempDir);
cg.close();
expect(() => CodeGraph.initSync(tempDir)).toThrow(/already initialized/i);
});
});
describe('Opening Projects', () => {
it('should open an existing project', () => {
// First initialize
const cg1 = CodeGraph.initSync(tempDir);
cg1.close();
// Then open
const cg2 = CodeGraph.openSync(tempDir);
expect(cg2.getProjectRoot()).toBe(path.resolve(tempDir));
cg2.close();
});
it('should throw if not initialized', () => {
expect(() => CodeGraph.openSync(tempDir)).toThrow(/not initialized/i);
});
});
describe('Static Methods', () => {
it('isInitialized should return false for new directory', () => {
expect(CodeGraph.isInitialized(tempDir)).toBe(false);
});
it('isInitialized should return true after init', () => {
const cg = CodeGraph.initSync(tempDir);
expect(CodeGraph.isInitialized(tempDir)).toBe(true);
cg.close();
});
});
describe('Database', () => {
it('should create database with correct schema', () => {
const cg = CodeGraph.initSync(tempDir);
// Check that we can get stats (requires tables to exist)
const stats = cg.getStats();
expect(stats.nodeCount).toBe(0);
expect(stats.edgeCount).toBe(0);
expect(stats.fileCount).toBe(0);
cg.close();
});
it('should return correct database size', () => {
const cg = CodeGraph.initSync(tempDir);
const stats = cg.getStats();
// Database should have some size (at least the schema)
expect(stats.dbSizeBytes).toBeGreaterThan(0);
cg.close();
});
it('should support optimize operation', () => {
const cg = CodeGraph.initSync(tempDir);
// Should not throw
expect(() => cg.optimize()).not.toThrow();
cg.close();
});
it('should support clear operation', () => {
const cg = CodeGraph.initSync(tempDir);
// Should not throw
expect(() => cg.clear()).not.toThrow();
const stats = cg.getStats();
expect(stats.nodeCount).toBe(0);
cg.close();
});
});
describe('Directory Management', () => {
it('should validate directory structure', () => {
const cg = CodeGraph.initSync(tempDir);
cg.close();
const validation = validateDirectory(tempDir);
expect(validation.valid).toBe(true);
expect(validation.errors).toHaveLength(0);
});
it('should detect invalid directory', () => {
const validation = validateDirectory(tempDir);
expect(validation.valid).toBe(false);
expect(validation.errors.length).toBeGreaterThan(0);
});
});
describe('Uninitialize', () => {
it('should remove .CodeGraph directory', () => {
const cg = CodeGraph.initSync(tempDir);
cg.uninitialize();
expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(false);
expect(CodeGraph.isInitialized(tempDir)).toBe(false);
});
});
describe('Close/Destroy', () => {
it('should close database but keep .CodeGraph directory', () => {
const cg = CodeGraph.initSync(tempDir);
cg.destroy(); // destroy is alias for close
expect(fs.existsSync(getCodeGraphDir(tempDir))).toBe(true);
expect(CodeGraph.isInitialized(tempDir)).toBe(true);
});
});
describe('Graph Query Methods', () => {
it('should throw "Node not found" for non-existent nodes', () => {
const cg = CodeGraph.initSync(tempDir);
// getContext throws for non-existent nodes
expect(() => cg.getContext('non-existent')).toThrow(/not found/i);
cg.close();
});
it('should return empty results for non-existent nodes', () => {
const cg = CodeGraph.initSync(tempDir);
// These methods return empty results instead of throwing
const traverseResult = cg.traverse('non-existent');
expect(traverseResult.nodes.size).toBe(0);
const callGraph = cg.getCallGraph('non-existent');
expect(callGraph.nodes.size).toBe(0);
const typeHierarchy = cg.getTypeHierarchy('non-existent');
expect(typeHierarchy.nodes.size).toBe(0);
const usages = cg.findUsages('non-existent');
expect(usages.length).toBe(0);
cg.close();
});
});
});
describe('Database Connection', () => {
let tempDir: string;
beforeEach(() => {
tempDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(tempDir);
});
it('should initialize new database', () => {
const dbPath = path.join(tempDir, 'test.db');
const db = DatabaseConnection.initialize(dbPath);
expect(db.isOpen()).toBe(true);
expect(fs.existsSync(dbPath)).toBe(true);
db.close();
});
it('should get schema version', () => {
const dbPath = path.join(tempDir, 'test.db');
const db = DatabaseConnection.initialize(dbPath);
const version = db.getSchemaVersion();
expect(version).not.toBeNull();
expect(version?.version).toBe(4);
db.close();
});
it('should support transactions', () => {
const dbPath = path.join(tempDir, 'test.db');
const db = DatabaseConnection.initialize(dbPath);
const result = db.transaction(() => {
return 42;
});
expect(result).toBe(42);
db.close();
});
it('should throw when opening non-existent database', () => {
const dbPath = path.join(tempDir, 'nonexistent.db');
expect(() => DatabaseConnection.open(dbPath)).toThrow(/not found/i);
});
});
describe('Query Builder', () => {
let tempDir: string;
let cg: CodeGraph;
beforeEach(() => {
tempDir = createTempDir();
cg = CodeGraph.initSync(tempDir);
});
afterEach(() => {
cg.close();
cleanupTempDir(tempDir);
});
it('should return null for non-existent node', () => {
const node = cg.getNode('nonexistent');
expect(node).toBeNull();
});
it('should return empty array for nodes in non-existent file', () => {
const nodes = cg.getNodesInFile('nonexistent.ts');
expect(nodes).toEqual([]);
});
it('should return empty array for edges from non-existent node', () => {
const edges = cg.getOutgoingEdges('nonexistent');
expect(edges).toEqual([]);
});
it('should return null for non-existent file', () => {
const file = cg.getFile('nonexistent.ts');
expect(file).toBeNull();
});
it('should return empty array for files when none tracked', () => {
const files = cg.getFiles();
expect(files).toEqual([]);
});
});
+59
View File
@@ -0,0 +1,59 @@
import { describe, it, expect, beforeAll, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph } from '../src';
import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
beforeAll(async () => {
await initGrammars();
await loadAllGrammars();
});
describe('Django end-to-end framework extraction', () => {
let tmpDir: string | undefined;
afterEach(() => {
if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });
tmpDir = undefined;
});
it('creates a route->view edge from urls.py to view class', async () => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-django-'));
fs.writeFileSync(path.join(tmpDir, 'manage.py'), '# marker\n');
fs.writeFileSync(path.join(tmpDir, 'requirements.txt'), 'django==4.2\n');
fs.mkdirSync(path.join(tmpDir, 'users'));
fs.writeFileSync(path.join(tmpDir, 'users/__init__.py'), '');
fs.writeFileSync(
path.join(tmpDir, 'users/views.py'),
'class UserListView:\n def get(self, request): pass\n'
);
fs.writeFileSync(
path.join(tmpDir, 'users/urls.py'),
'from django.urls import path\n' +
'from users.views import UserListView\n' +
'urlpatterns = [path("users/", UserListView.as_view(), name="user-list")]\n'
);
const cg = CodeGraph.initSync(tmpDir);
await cg.indexAll();
// Route node exists
const routes = cg.getNodesByKind('route');
expect(routes.length).toBeGreaterThan(0);
const route = routes.find((n) => n.name === 'users/');
expect(route).toBeDefined();
// View class exists
const classNodes = cg.getNodesByKind('class');
const view = classNodes.find((n) => n.name === 'UserListView');
expect(view).toBeDefined();
// Edge route -> view exists
const edges = cg.getOutgoingEdges(route!.id);
const toView = edges.find((e) => e.target === view!.id);
expect(toView).toBeDefined();
expect(toView!.kind).toBe('references');
cg.close();
});
});
File diff suppressed because it is too large Load Diff
+129
View File
@@ -0,0 +1,129 @@
/**
* Git Sync Hooks Tests
*
* Covers installing/removing the opt-in commit/merge/checkout hooks that
* keep the index fresh when the live watcher is disabled (issue #199).
* Exercises real git repos in temp dirs — no mocking.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { execFileSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import {
installGitSyncHook,
removeGitSyncHook,
isSyncHookInstalled,
isGitRepo,
DEFAULT_SYNC_HOOKS,
} from '../src/sync/git-hooks';
function gitInit(dir: string): void {
execFileSync('git', ['init', '-q'], { cwd: dir, stdio: 'ignore' });
}
function isExecutable(file: string): boolean {
if (process.platform === 'win32') return true; // mode bits not meaningful
return (fs.statSync(file).mode & 0o111) !== 0;
}
describe('git sync hooks', () => {
let repo: string;
beforeEach(() => {
repo = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-githooks-'));
});
afterEach(() => {
if (fs.existsSync(repo)) fs.rmSync(repo, { recursive: true, force: true });
});
it('installs all default hooks, executable, invoking codegraph sync', () => {
gitInit(repo);
const result = installGitSyncHook(repo);
expect(result.installed.sort()).toEqual([...DEFAULT_SYNC_HOOKS].sort());
expect(result.skipped).toBeUndefined();
for (const hook of DEFAULT_SYNC_HOOKS) {
const file = path.join(repo, '.git', 'hooks', hook);
expect(fs.existsSync(file)).toBe(true);
const body = fs.readFileSync(file, 'utf8');
expect(body).toContain('codegraph sync');
expect(body).toContain('command -v codegraph'); // no-op when not on PATH
expect(isExecutable(file)).toBe(true);
}
expect(isSyncHookInstalled(repo)).toBe(true);
});
it('is idempotent — re-install does not duplicate the block', () => {
gitInit(repo);
installGitSyncHook(repo);
installGitSyncHook(repo);
const body = fs.readFileSync(path.join(repo, '.git', 'hooks', 'post-commit'), 'utf8');
const occurrences = body.split('# >>> codegraph sync hook >>>').length - 1;
expect(occurrences).toBe(1);
});
it('preserves a pre-existing user hook and appends our block', () => {
gitInit(repo);
const file = path.join(repo, '.git', 'hooks', 'post-commit');
fs.writeFileSync(file, '#!/bin/sh\necho "my custom hook"\n', { mode: 0o755 });
installGitSyncHook(repo, ['post-commit']);
const body = fs.readFileSync(file, 'utf8');
expect(body).toContain('echo "my custom hook"');
expect(body).toContain('codegraph sync');
});
it('remove strips our block; deletes a hook that was only ours', () => {
gitInit(repo);
installGitSyncHook(repo, ['post-commit']);
const file = path.join(repo, '.git', 'hooks', 'post-commit');
expect(fs.existsSync(file)).toBe(true);
const result = removeGitSyncHook(repo, ['post-commit']);
expect(result.installed).toEqual(['post-commit']);
expect(fs.existsSync(file)).toBe(false); // was ours-only → deleted
expect(isSyncHookInstalled(repo)).toBe(false);
});
it('remove keeps user content when the hook is shared', () => {
gitInit(repo);
const file = path.join(repo, '.git', 'hooks', 'post-commit');
fs.writeFileSync(file, '#!/bin/sh\necho "keep me"\n', { mode: 0o755 });
installGitSyncHook(repo, ['post-commit']);
removeGitSyncHook(repo, ['post-commit']);
expect(fs.existsSync(file)).toBe(true);
const body = fs.readFileSync(file, 'utf8');
expect(body).toContain('echo "keep me"');
expect(body).not.toContain('codegraph sync');
});
it('honors core.hooksPath', () => {
gitInit(repo);
const customHooks = path.join(repo, '.husky');
fs.mkdirSync(customHooks);
execFileSync('git', ['config', 'core.hooksPath', '.husky'], { cwd: repo, stdio: 'ignore' });
const result = installGitSyncHook(repo, ['post-commit']);
expect(result.hooksDir).toBe(customHooks);
expect(fs.existsSync(path.join(customHooks, 'post-commit'))).toBe(true);
// The default .git/hooks dir should NOT have received the hook.
expect(fs.existsSync(path.join(repo, '.git', 'hooks', 'post-commit'))).toBe(false);
});
it('skips cleanly when not a git repository', () => {
expect(isGitRepo(repo)).toBe(false);
const result = installGitSyncHook(repo);
expect(result.installed).toEqual([]);
expect(result.hooksDir).toBeNull();
expect(result.skipped).toMatch(/not a git repository/);
expect(isSyncHookInstalled(repo)).toBe(false);
});
});
+170
View File
@@ -0,0 +1,170 @@
/**
* Glyph fallback / Unicode-support detection.
*
* Pinned because the matrix is small and the consequence of regression
* is highly visible: shimmer-worker output on Windows mojibakes when
* UTF-8 glyphs are written via `fs.writeSync` (see #168). The detection
* + ASCII fallback is the contract that prevents this.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import {
supportsUnicode,
getGlyphs,
UNICODE_GLYPHS,
ASCII_GLYPHS,
_resetGlyphsCache,
} from '../src/ui/glyphs';
function withEnv(patch: Record<string, string | undefined>, fn: () => void): void {
const saved: Record<string, string | undefined> = {};
const savedPlatform = process.platform;
for (const key of Object.keys(patch)) {
saved[key] = process.env[key];
if (patch[key] === undefined) delete process.env[key];
else process.env[key] = patch[key];
}
_resetGlyphsCache();
try {
fn();
} finally {
for (const key of Object.keys(saved)) {
if (saved[key] === undefined) delete process.env[key];
else process.env[key] = saved[key];
}
Object.defineProperty(process, 'platform', { value: savedPlatform });
_resetGlyphsCache();
}
}
function setPlatform(value: NodeJS.Platform): void {
Object.defineProperty(process, 'platform', { value });
}
describe('supportsUnicode', () => {
let originalPlatform: NodeJS.Platform;
beforeEach(() => {
originalPlatform = process.platform;
_resetGlyphsCache();
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: originalPlatform });
_resetGlyphsCache();
});
it('returns false on Windows by default (mojibake-prone consoles)', () => {
withEnv({ CODEGRAPH_ASCII: undefined, CODEGRAPH_UNICODE: undefined, TERM: undefined }, () => {
setPlatform('win32');
expect(supportsUnicode()).toBe(false);
});
});
it('returns true on macOS by default', () => {
withEnv({ CODEGRAPH_ASCII: undefined, CODEGRAPH_UNICODE: undefined, TERM: undefined }, () => {
setPlatform('darwin');
expect(supportsUnicode()).toBe(true);
});
});
it('returns true on Linux by default', () => {
withEnv({ CODEGRAPH_ASCII: undefined, CODEGRAPH_UNICODE: undefined, TERM: undefined }, () => {
setPlatform('linux');
expect(supportsUnicode()).toBe(true);
});
});
it('returns false on Linux kernel console (TERM=linux)', () => {
withEnv({ CODEGRAPH_ASCII: undefined, CODEGRAPH_UNICODE: undefined, TERM: 'linux' }, () => {
setPlatform('linux');
expect(supportsUnicode()).toBe(false);
});
});
it('respects CODEGRAPH_UNICODE=1 on Windows (opt-in escape hatch)', () => {
withEnv({ CODEGRAPH_UNICODE: '1', CODEGRAPH_ASCII: undefined }, () => {
setPlatform('win32');
expect(supportsUnicode()).toBe(true);
});
});
it('respects CODEGRAPH_ASCII=1 on macOS (opt-out escape hatch)', () => {
withEnv({ CODEGRAPH_ASCII: '1', CODEGRAPH_UNICODE: undefined }, () => {
setPlatform('darwin');
expect(supportsUnicode()).toBe(false);
});
});
it('CODEGRAPH_ASCII takes precedence over CODEGRAPH_UNICODE', () => {
withEnv({ CODEGRAPH_ASCII: '1', CODEGRAPH_UNICODE: '1' }, () => {
setPlatform('darwin');
expect(supportsUnicode()).toBe(false);
});
});
});
describe('getGlyphs', () => {
let originalPlatform: NodeJS.Platform;
beforeEach(() => {
originalPlatform = process.platform;
_resetGlyphsCache();
});
afterEach(() => {
Object.defineProperty(process, 'platform', { value: originalPlatform });
_resetGlyphsCache();
});
it('returns ASCII glyphs on Windows', () => {
withEnv({ CODEGRAPH_ASCII: undefined, CODEGRAPH_UNICODE: undefined }, () => {
setPlatform('win32');
const g = getGlyphs();
expect(g).toBe(ASCII_GLYPHS);
expect(g.ok).toBe('[OK]');
expect(g.rail).toBe('|');
expect(g.phaseDone).toBe('*');
expect(g.dash).toBe('-');
});
});
it('returns Unicode glyphs on macOS', () => {
withEnv({ CODEGRAPH_ASCII: undefined, CODEGRAPH_UNICODE: undefined }, () => {
setPlatform('darwin');
const g = getGlyphs();
expect(g).toBe(UNICODE_GLYPHS);
expect(g.ok).toBe('✓');
expect(g.rail).toBe('│');
expect(g.phaseDone).toBe('◆');
expect(g.dash).toBe('—');
});
});
it('caches the result so repeated calls return the same object', () => {
withEnv({ CODEGRAPH_ASCII: undefined, CODEGRAPH_UNICODE: undefined }, () => {
setPlatform('darwin');
expect(getGlyphs()).toBe(getGlyphs());
});
});
});
describe('Glyph sets', () => {
it('ASCII and Unicode sets cover the same keys', () => {
expect(Object.keys(ASCII_GLYPHS).sort()).toEqual(Object.keys(UNICODE_GLYPHS).sort());
});
it('ASCII glyphs are all 7-bit ASCII', () => {
for (const [key, value] of Object.entries(ASCII_GLYPHS)) {
const flat = Array.isArray(value) ? value.join('') : value;
for (let i = 0; i < flat.length; i++) {
const codepoint = flat.charCodeAt(i);
expect(codepoint, `ASCII_GLYPHS.${key} contains non-ASCII char U+${codepoint.toString(16).toUpperCase().padStart(4, '0')}`).toBeLessThan(128);
}
}
});
it('ASCII spinner has the same frame count as the Unicode spinner', () => {
expect(ASCII_GLYPHS.spinner.length).toBe(UNICODE_GLYPHS.spinner.length);
});
});
+435
View File
@@ -0,0 +1,435 @@
/**
* Graph Query Tests
*
* Tests for graph traversal and query functionality.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import CodeGraph from '../src/index';
import { Node, Edge } from '../src/types';
describe('Graph Queries', () => {
let testDir: string;
let cg: CodeGraph;
beforeEach(async () => {
// Create temp directory
testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-graph-test-'));
// Create test files with relationships
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
// Create base class
fs.writeFileSync(
path.join(srcDir, 'base.ts'),
`
export class BaseClass {
protected value: number;
constructor(value: number) {
this.value = value;
}
getValue(): number {
return this.value;
}
}
export interface Printable {
print(): void;
}
`
);
// Create derived class
fs.writeFileSync(
path.join(srcDir, 'derived.ts'),
`
import { BaseClass, Printable } from './base';
export class DerivedClass extends BaseClass implements Printable {
private name: string;
constructor(value: number, name: string) {
super(value);
this.name = name;
}
print(): void {
console.log(this.getName(), this.getValue());
}
getName(): string {
return this.name;
}
}
`
);
// Create utility functions
fs.writeFileSync(
path.join(srcDir, 'utils.ts'),
`
export function formatValue(value: number): string {
return value.toFixed(2);
}
export function processValue(value: number): number {
const formatted = formatValue(value);
return parseFloat(formatted);
}
export function doubleValue(value: number): number {
return value * 2;
}
// Unused function (dead code)
function unusedHelper(): void {
console.log('never called');
}
`
);
// Create main file that uses everything
fs.writeFileSync(
path.join(srcDir, 'main.ts'),
`
import { DerivedClass } from './derived';
import { processValue, doubleValue } from './utils';
function main(): void {
const obj = new DerivedClass(10, 'test');
obj.print();
const result = processValue(doubleValue(obj.getValue()));
console.log(result);
}
export { main };
`
);
// Initialize and index
cg = CodeGraph.initSync(testDir, {
config: {
include: ['src/**/*.ts'],
exclude: [],
},
});
await cg.indexAll();
cg.resolveReferences();
});
afterEach(() => {
if (cg) {
cg.destroy();
}
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
describe('traverse()', () => {
it('should traverse graph from a starting node', () => {
const nodes = cg.getNodesByKind('function');
const mainFunc = nodes.find((n) => n.name === 'main');
if (!mainFunc) {
console.log('main function not found, skipping test');
return;
}
const subgraph = cg.traverse(mainFunc.id, {
maxDepth: 2,
direction: 'outgoing',
});
expect(subgraph.nodes.size).toBeGreaterThan(0);
expect(subgraph.roots).toContain(mainFunc.id);
});
it('should respect maxDepth option', () => {
const nodes = cg.getNodesByKind('function');
const mainFunc = nodes.find((n) => n.name === 'main');
if (!mainFunc) {
return;
}
const shallow = cg.traverse(mainFunc.id, { maxDepth: 1 });
const deep = cg.traverse(mainFunc.id, { maxDepth: 3 });
expect(deep.nodes.size).toBeGreaterThanOrEqual(shallow.nodes.size);
});
it('should support incoming direction', () => {
const nodes = cg.getNodesByKind('function');
const formatValue = nodes.find((n) => n.name === 'formatValue');
if (!formatValue) {
return;
}
const subgraph = cg.traverse(formatValue.id, {
maxDepth: 2,
direction: 'incoming',
});
expect(subgraph.nodes.size).toBeGreaterThan(0);
});
});
describe('getContext()', () => {
it('should return context for a node', () => {
const nodes = cg.getNodesByKind('class');
const derivedClass = nodes.find((n) => n.name === 'DerivedClass');
if (!derivedClass) {
console.log('DerivedClass not found, skipping test');
return;
}
const context = cg.getContext(derivedClass.id);
expect(context.focal).toBeDefined();
expect(context.focal.id).toBe(derivedClass.id);
expect(context.ancestors).toBeDefined();
expect(context.children).toBeDefined();
expect(context.incomingRefs).toBeDefined();
expect(context.outgoingRefs).toBeDefined();
});
it('should throw for non-existent node', () => {
expect(() => cg.getContext('non-existent-id')).toThrow('Node not found');
});
});
describe('getCallGraph()', () => {
it('should return call graph for a function', () => {
const nodes = cg.getNodesByKind('function');
const processValue = nodes.find((n) => n.name === 'processValue');
if (!processValue) {
console.log('processValue not found, skipping test');
return;
}
const callGraph = cg.getCallGraph(processValue.id, 2);
expect(callGraph.nodes.size).toBeGreaterThan(0);
expect(callGraph.nodes.has(processValue.id)).toBe(true);
});
});
describe('getTypeHierarchy()', () => {
it('should return type hierarchy for a class', () => {
const nodes = cg.getNodesByKind('class');
const derivedClass = nodes.find((n) => n.name === 'DerivedClass');
if (!derivedClass) {
return;
}
const hierarchy = cg.getTypeHierarchy(derivedClass.id);
expect(hierarchy.nodes.size).toBeGreaterThan(0);
expect(hierarchy.nodes.has(derivedClass.id)).toBe(true);
});
it('should return empty subgraph for non-existent node', () => {
const hierarchy = cg.getTypeHierarchy('non-existent-id');
expect(hierarchy.nodes.size).toBe(0);
expect(hierarchy.edges.length).toBe(0);
});
});
describe('findUsages()', () => {
it('should find usages of a symbol', () => {
const nodes = cg.getNodesByKind('class');
const baseClass = nodes.find((n) => n.name === 'BaseClass');
if (!baseClass) {
return;
}
const usages = cg.findUsages(baseClass.id);
// Should find at least the extends relationship
expect(usages).toBeDefined();
expect(Array.isArray(usages)).toBe(true);
});
});
describe('getCallers() and getCallees()', () => {
it('should get callers of a function', () => {
const nodes = cg.getNodesByKind('function');
const formatValue = nodes.find((n) => n.name === 'formatValue');
if (!formatValue) {
return;
}
const callers = cg.getCallers(formatValue.id);
// processValue calls formatValue
expect(Array.isArray(callers)).toBe(true);
});
it('should get callees of a function', () => {
const nodes = cg.getNodesByKind('function');
const processValue = nodes.find((n) => n.name === 'processValue');
if (!processValue) {
return;
}
const callees = cg.getCallees(processValue.id);
expect(Array.isArray(callees)).toBe(true);
});
});
describe('getImpactRadius()', () => {
it('should calculate impact radius', () => {
const nodes = cg.getNodesByKind('function');
const formatValue = nodes.find((n) => n.name === 'formatValue');
if (!formatValue) {
return;
}
const impact = cg.getImpactRadius(formatValue.id, 3);
expect(impact.nodes.size).toBeGreaterThan(0);
expect(impact.nodes.has(formatValue.id)).toBe(true);
});
});
describe('findPath()', () => {
it('should find path between connected nodes', () => {
const stats = cg.getStats();
if (stats.nodeCount < 2) {
return;
}
const functions = cg.getNodesByKind('function');
if (functions.length < 2) {
return;
}
// Try to find any path
const processValue = functions.find((n) => n.name === 'processValue');
const formatValue = functions.find((n) => n.name === 'formatValue');
if (processValue && formatValue) {
const path = cg.findPath(processValue.id, formatValue.id);
// Path might exist or might not depending on edge direction
expect(path === null || Array.isArray(path)).toBe(true);
}
});
it('should return null for disconnected nodes', () => {
// Create two nodes that definitely don't have a path
const path = cg.findPath('non-existent-1', 'non-existent-2');
expect(path).toBeNull();
});
});
describe('getAncestors() and getChildren()', () => {
it('should get ancestors of a node', () => {
const methods = cg.getNodesByKind('method');
const printMethod = methods.find((n) => n.name === 'print');
if (!printMethod) {
return;
}
const ancestors = cg.getAncestors(printMethod.id);
// Should have class and file as ancestors
expect(Array.isArray(ancestors)).toBe(true);
});
it('should get children of a node', () => {
const classes = cg.getNodesByKind('class');
const derivedClass = classes.find((n) => n.name === 'DerivedClass');
if (!derivedClass) {
return;
}
const children = cg.getChildren(derivedClass.id);
// Should have methods as children
expect(Array.isArray(children)).toBe(true);
});
});
describe('File dependency analysis', () => {
it('should get file dependencies', () => {
const deps = cg.getFileDependencies('src/main.ts');
expect(Array.isArray(deps)).toBe(true);
});
it('should get file dependents', () => {
const dependents = cg.getFileDependents('src/utils.ts');
expect(Array.isArray(dependents)).toBe(true);
});
});
describe('findCircularDependencies()', () => {
it('should detect circular dependencies', () => {
const cycles = cg.findCircularDependencies();
// Our test files don't have circular deps
expect(Array.isArray(cycles)).toBe(true);
});
});
describe('findDeadCode()', () => {
it('should find dead code', () => {
const deadCode = cg.findDeadCode(['function']);
expect(Array.isArray(deadCode)).toBe(true);
// unusedHelper should be detected
const hasUnused = deadCode.some((n) => n.name === 'unusedHelper');
// Note: This depends on extraction properly detecting function scope
expect(deadCode.length).toBeGreaterThanOrEqual(0);
});
});
describe('getNodeMetrics()', () => {
it('should return metrics for a node', () => {
const functions = cg.getNodesByKind('function');
const func = functions[0];
if (!func) {
return;
}
const metrics = cg.getNodeMetrics(func.id);
expect(metrics).toHaveProperty('incomingEdgeCount');
expect(metrics).toHaveProperty('outgoingEdgeCount');
expect(metrics).toHaveProperty('callCount');
expect(metrics).toHaveProperty('callerCount');
expect(metrics).toHaveProperty('childCount');
expect(metrics).toHaveProperty('depth');
expect(typeof metrics.incomingEdgeCount).toBe('number');
expect(typeof metrics.outgoingEdgeCount).toBe('number');
});
});
});
+890
View File
@@ -0,0 +1,890 @@
/**
* Multi-target installer tests.
*
* Each `AgentTarget` is exercised against the same contract:
* - `install` writes the expected files
* - re-running `install` is byte-identical (idempotent)
* - sibling MCP servers / unrelated config is preserved
* - `uninstall` reverses `install`
* - `printConfig` returns parseable, non-empty content
*
* For agent-config destinations we redirect HOME to a tmpdir via
* `os.homedir` spying, and CWD via `process.chdir` — same pattern as
* the legacy `installer.test.ts`. No real `~/.claude/` etc. ever
* touched.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { ALL_TARGETS, getTarget, resolveTargetFlag } from '../src/installer/targets/registry';
import { uninstallTargets } from '../src/installer';
import { upsertTomlTable, removeTomlTable, buildTomlTable } from '../src/installer/targets/toml';
import { cleanupLegacyHooks } from '../src/installer/targets/claude';
function mkTmpDir(label: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), `cg-targets-${label}-`));
}
// `os.homedir` is non-configurable on Node, so we redirect it via the
// `$HOME` (POSIX) / `$USERPROFILE` (Windows) env vars that
// `os.homedir()` reads first. Same trick the rest of the suite uses
// when it needs a mock home.
function setHome(dir: string): { restore: () => void } {
const prev = {
HOME: process.env.HOME,
USERPROFILE: process.env.USERPROFILE,
APPDATA: process.env.APPDATA,
XDG_CONFIG_HOME: process.env.XDG_CONFIG_HOME,
HERMES_HOME: process.env.HERMES_HOME,
};
process.env.HOME = dir;
process.env.USERPROFILE = dir;
process.env.APPDATA = path.join(dir, '.config');
process.env.XDG_CONFIG_HOME = path.join(dir, '.config');
delete process.env.HERMES_HOME;
return {
restore() {
if (prev.HOME === undefined) delete process.env.HOME; else process.env.HOME = prev.HOME;
if (prev.USERPROFILE === undefined) delete process.env.USERPROFILE; else process.env.USERPROFILE = prev.USERPROFILE;
if (prev.APPDATA === undefined) delete process.env.APPDATA; else process.env.APPDATA = prev.APPDATA;
if (prev.XDG_CONFIG_HOME === undefined) delete process.env.XDG_CONFIG_HOME; else process.env.XDG_CONFIG_HOME = prev.XDG_CONFIG_HOME;
if (prev.HERMES_HOME === undefined) delete process.env.HERMES_HOME; else process.env.HERMES_HOME = prev.HERMES_HOME;
},
};
}
describe('Installer targets — contract', () => {
let tmpHome: string;
let tmpCwd: string;
let origCwd: string;
let homeRestore: { restore: () => void };
beforeEach(() => {
tmpHome = mkTmpDir('home');
tmpCwd = mkTmpDir('cwd');
origCwd = process.cwd();
process.chdir(tmpCwd);
homeRestore = setHome(tmpHome);
});
afterEach(() => {
homeRestore.restore();
process.chdir(origCwd);
fs.rmSync(tmpHome, { recursive: true, force: true });
fs.rmSync(tmpCwd, { recursive: true, force: true });
});
for (const target of ALL_TARGETS) {
describe(target.id, () => {
const supportedLocations = (['global', 'local'] as const).filter((l) =>
target.supportsLocation(l),
);
for (const location of supportedLocations) {
describe(`location=${location}`, () => {
it('install writes files; detect.alreadyConfigured becomes true', () => {
expect(target.detect(location).alreadyConfigured).toBe(false);
const result = target.install(location, { autoAllow: true });
expect(result.files.length).toBeGreaterThan(0);
for (const file of result.files) {
if (file.action !== 'unchanged') {
expect(fs.existsSync(file.path)).toBe(true);
}
}
expect(target.detect(location).alreadyConfigured).toBe(true);
});
it('re-running install is idempotent (no actions other than unchanged)', () => {
target.install(location, { autoAllow: true });
const second = target.install(location, { autoAllow: true });
for (const file of second.files) {
expect(file.action).toBe('unchanged');
}
});
it('install preserves a pre-existing sibling MCP server (where applicable)', () => {
// Plant a sibling entry in the same JSON config, install,
// and verify the sibling survives. Skip for Codex (TOML)
// and any target with no JSON config — they get covered
// by their own dedicated tests below.
const paths = target.describePaths(location);
// Match .json or .jsonc — opencode prefers .jsonc.
const jsonPath = paths.find((p) => /\.jsonc?$/.test(p));
if (!jsonPath) return;
// Seed pre-existing config.
fs.mkdirSync(path.dirname(jsonPath), { recursive: true });
const seed: Record<string, any> = { mcpServers: { other: { command: 'x' } } };
// opencode uses `mcp` not `mcpServers`. Match its shape too.
if (target.id === 'opencode') {
delete seed.mcpServers;
seed.mcp = { other: { type: 'local', command: ['x'], enabled: true } };
}
fs.writeFileSync(jsonPath, JSON.stringify(seed, null, 2) + '\n');
target.install(location, { autoAllow: true });
const after = JSON.parse(fs.readFileSync(jsonPath, 'utf-8'));
if (target.id === 'opencode') {
expect(after.mcp.other).toBeDefined();
expect(after.mcp.codegraph).toBeDefined();
} else {
expect(after.mcpServers.other).toBeDefined();
expect(after.mcpServers.codegraph).toBeDefined();
}
});
it('uninstall reverses install (alreadyConfigured returns to false)', () => {
target.install(location, { autoAllow: true });
expect(target.detect(location).alreadyConfigured).toBe(true);
target.uninstall(location);
expect(target.detect(location).alreadyConfigured).toBe(false);
});
it('printConfig returns non-empty output without writing anything', () => {
const before = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
const out = target.printConfig(location);
expect(out.length).toBeGreaterThan(0);
const after = listAllFiles(tmpHome).concat(listAllFiles(tmpCwd));
expect(after.sort()).toEqual(before.sort());
});
});
}
});
}
});
describe('Installer targets — partial-state idempotency', () => {
let tmpHome: string;
let tmpCwd: string;
let origCwd: string;
let homeRestore: { restore: () => void };
beforeEach(() => {
tmpHome = mkTmpDir('home');
tmpCwd = mkTmpDir('cwd');
origCwd = process.cwd();
process.chdir(tmpCwd);
homeRestore = setHome(tmpHome);
});
afterEach(() => {
homeRestore.restore();
process.chdir(origCwd);
fs.rmSync(tmpHome, { recursive: true, force: true });
fs.rmSync(tmpCwd, { recursive: true, force: true });
});
it('codex: install after only config.toml exists — second pass is fully unchanged', () => {
const codex = getTarget('codex')!;
// First install creates both files.
codex.install('global', { autoAllow: false });
// Delete the AGENTS.md to simulate partial state (user wiped one file).
const agentsMd = path.join(tmpHome, '.codex', 'AGENTS.md');
expect(fs.existsSync(agentsMd)).toBe(true);
fs.unlinkSync(agentsMd);
// Reinstall — TOML stays unchanged, AGENTS.md is recreated.
const second = codex.install('global', { autoAllow: false });
const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
const mdEntry = second.files.find((f) => f.path.endsWith('AGENTS.md'))!;
expect(tomlEntry.action).toBe('unchanged');
expect(mdEntry.action).toBe('created');
// Third install — both unchanged (full idempotency restored).
const third = codex.install('global', { autoAllow: false });
for (const f of third.files) expect(f.action).toBe('unchanged');
});
it('opencode: prefers .jsonc when both .json and .jsonc exist', () => {
const opencode = getTarget('opencode')!;
const dir = path.join(tmpHome, '.config', 'opencode');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
fs.writeFileSync(path.join(dir, 'opencode.jsonc'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
const result = opencode.install('global', { autoAllow: true });
const written = result.files.find((f) => /\.jsonc$/.test(f.path))!;
expect(written).toBeDefined();
expect(written.action).not.toBe('not-found');
// The .json file is left alone.
const jsonText = fs.readFileSync(path.join(dir, 'opencode.json'), 'utf-8');
expect(jsonText).not.toContain('codegraph');
});
it('opencode: uses .json when only .json exists (no .jsonc)', () => {
const opencode = getTarget('opencode')!;
const dir = path.join(tmpHome, '.config', 'opencode');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'opencode.json'), '{\n "$schema": "https://opencode.ai/config.json"\n}\n');
const result = opencode.install('global', { autoAllow: true });
expect(result.files[0].path).toMatch(/opencode\.json$/);
expect(fs.existsSync(path.join(dir, 'opencode.jsonc'))).toBe(false);
});
it('opencode: defaults to .jsonc for fresh installs (no existing file)', () => {
const opencode = getTarget('opencode')!;
const result = opencode.install('global', { autoAllow: true });
expect(result.files[0].path).toMatch(/opencode\.jsonc$/);
expect(result.files[0].action).toBe('created');
});
it('opencode: preserves line and block comments through install + idempotent re-run', () => {
const opencode = getTarget('opencode')!;
const dir = path.join(tmpHome, '.config', 'opencode');
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, 'opencode.jsonc');
const original = [
'{',
' // top-level note about my opencode setup',
' "$schema": "https://opencode.ai/config.json",',
' /* multi-line block comment',
' describing the providers section */',
' "providers": {',
' "anthropic": { "model": "claude-opus-4-7" } // pinned',
' }',
'}',
'',
].join('\n');
fs.writeFileSync(file, original);
opencode.install('global', { autoAllow: true });
const afterInstall = fs.readFileSync(file, 'utf-8');
expect(afterInstall).toContain('// top-level note about my opencode setup');
expect(afterInstall).toContain('/* multi-line block comment');
expect(afterInstall).toContain('// pinned');
expect(afterInstall).toContain('"codegraph"');
expect(afterInstall).toContain('"providers"');
// Idempotent re-run reports unchanged, file is byte-identical.
const second = opencode.install('global', { autoAllow: true });
expect(second.files[0].action).toBe('unchanged');
expect(fs.readFileSync(file, 'utf-8')).toBe(afterInstall);
});
it('opencode: install writes AGENTS.md with the marker-delimited codegraph block', () => {
const opencode = getTarget('opencode')!;
opencode.install('global', { autoAllow: true });
const agentsMd = path.join(tmpHome, '.config', 'opencode', 'AGENTS.md');
expect(fs.existsSync(agentsMd)).toBe(true);
const body = fs.readFileSync(agentsMd, 'utf-8');
expect(body).toContain('<!-- CODEGRAPH_START -->');
expect(body).toContain('<!-- CODEGRAPH_END -->');
expect(body).toContain('codegraph_callers');
});
it('opencode: AGENTS.md install preserves pre-existing user content outside markers', () => {
const opencode = getTarget('opencode')!;
const dir = path.join(tmpHome, '.config', 'opencode');
fs.mkdirSync(dir, { recursive: true });
const agentsMd = path.join(dir, 'AGENTS.md');
fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
opencode.install('global', { autoAllow: true });
const body = fs.readFileSync(agentsMd, 'utf-8');
expect(body).toContain('# My personal opencode instructions');
expect(body).toContain('Always respond in pirate.');
expect(body).toContain('<!-- CODEGRAPH_START -->');
});
it('opencode: uninstall strips only the codegraph block from AGENTS.md', () => {
const opencode = getTarget('opencode')!;
const dir = path.join(tmpHome, '.config', 'opencode');
fs.mkdirSync(dir, { recursive: true });
const agentsMd = path.join(dir, 'AGENTS.md');
fs.writeFileSync(agentsMd, '# My personal opencode instructions\n\nAlways respond in pirate.\n');
opencode.install('global', { autoAllow: true });
opencode.uninstall('global');
const body = fs.readFileSync(agentsMd, 'utf-8');
expect(body).toContain('# My personal opencode instructions');
expect(body).toContain('Always respond in pirate.');
expect(body).not.toContain('CODEGRAPH_START');
expect(body).not.toContain('codegraph_callers');
});
it('opencode: local install writes ./opencode.jsonc and ./AGENTS.md in cwd', () => {
const opencode = getTarget('opencode')!;
const result = opencode.install('local', { autoAllow: true });
const paths = result.files.map((f) => f.path.replace(/\\/g, '/'));
// macOS realpath shenanigans (/var vs /private/var) — suffix match.
expect(paths.some((p) => p.endsWith('/opencode.jsonc'))).toBe(true);
expect(paths.some((p) => p.endsWith('/AGENTS.md'))).toBe(true);
});
it('hermes: install adds codegraph MCP server and cli toolset, preserving existing yaml', () => {
const hermes = getTarget('hermes')!;
const config = path.join(tmpHome, '.hermes', 'config.yaml');
fs.mkdirSync(path.dirname(config), { recursive: true });
fs.writeFileSync(config, [
'model:',
' default: qwen-3.7',
'mcp_servers:',
' other:',
' command: other',
'platform_toolsets:',
' cli:',
' - hermes-cli',
' discord:',
' - hermes-discord',
'',
].join('\n'));
const result = hermes.install('global', { autoAllow: true });
expect(result.files[0].action).toBe('updated');
const body = fs.readFileSync(config, 'utf-8');
expect(body).toContain('model:\n default: qwen-3.7');
expect(body).toContain('mcp_servers:\n other:\n command: other');
expect(body).toContain(' codegraph:\n command: codegraph');
expect(body).toContain(' - hermes-cli');
expect(body).toContain(' - mcp-codegraph');
expect(body).toContain(' discord:\n - hermes-discord');
const second = hermes.install('global', { autoAllow: true });
expect(second.files[0].action).toBe('unchanged');
});
it('hermes: uninstall removes only codegraph MCP server and toolset entry', () => {
const hermes = getTarget('hermes')!;
const config = path.join(tmpHome, '.hermes', 'config.yaml');
fs.mkdirSync(path.dirname(config), { recursive: true });
hermes.install('global', { autoAllow: true });
fs.appendFileSync(config, 'custom:\n keep: true\n');
hermes.uninstall('global');
const body = fs.readFileSync(config, 'utf-8');
expect(body).not.toContain('codegraph:');
expect(body).not.toContain('mcp-codegraph');
expect(body).toContain('custom:\n keep: true');
});
it('opencode: uninstall removes only mcp.codegraph, preserves comments and siblings', () => {
const opencode = getTarget('opencode')!;
const dir = path.join(tmpHome, '.config', 'opencode');
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, 'opencode.jsonc');
fs.writeFileSync(file, [
'{',
' // important comment',
' "$schema": "https://opencode.ai/config.json",',
' "mcp": {',
' "other": { "type": "local", "command": ["x"], "enabled": true }',
' }',
'}',
'',
].join('\n'));
opencode.install('global', { autoAllow: true });
const afterInstall = fs.readFileSync(file, 'utf-8');
expect(afterInstall).toContain('"codegraph"');
expect(afterInstall).toContain('"other"');
opencode.uninstall('global');
const afterUninstall = fs.readFileSync(file, 'utf-8');
expect(afterUninstall).not.toContain('codegraph');
expect(afterUninstall).toContain('// important comment');
expect(afterUninstall).toContain('"other"');
});
it('codex: user-added key inside [mcp_servers.codegraph] survives idempotent re-install', () => {
const codex = getTarget('codex')!;
codex.install('global', { autoAllow: false });
const tomlPath = path.join(tmpHome, '.codex', 'config.toml');
const original = fs.readFileSync(tomlPath, 'utf-8');
// User edits the block to add a custom key.
const edited = original.replace(
'args = ["serve", "--mcp"]',
'args = ["serve", "--mcp"]\nenabled = true',
);
fs.writeFileSync(tomlPath, edited);
// Re-install: our serializer doesn't know `enabled = true`, so
// the block no longer matches the canonical form — we'll
// overwrite it. This is the documented contract: we own the
// codegraph block exclusively.
const second = codex.install('global', { autoAllow: false });
const tomlEntry = second.files.find((f) => f.path.endsWith('config.toml'))!;
expect(tomlEntry.action).toBe('updated');
const after = fs.readFileSync(tomlPath, 'utf-8');
expect(after).not.toContain('enabled = true');
});
it('claude: local install writes ./.mcp.json (project scope), not ./.claude.json', () => {
const claude = getTarget('claude')!;
const result = claude.install('local', { autoAllow: false });
// The MCP entry lands in ./.mcp.json — the file Claude Code reads.
expect(result.files.some((f) => f.path.replace(/\\/g, '/').endsWith('/.mcp.json'))).toBe(true);
expect(fs.existsSync(path.join(tmpCwd, '.mcp.json'))).toBe(true);
expect(fs.existsSync(path.join(tmpCwd, '.claude.json'))).toBe(false);
const cfg = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
expect(cfg.mcpServers.codegraph).toBeDefined();
});
it('claude: global install targets ~/.claude.json (user scope)', () => {
const claude = getTarget('claude')!;
claude.install('global', { autoAllow: false });
const cfg = JSON.parse(fs.readFileSync(path.join(tmpHome, '.claude.json'), 'utf-8'));
expect(cfg.mcpServers.codegraph).toBeDefined();
});
it('claude: local install migrates a legacy ./.claude.json codegraph entry into ./.mcp.json', () => {
const claude = getTarget('claude')!;
const legacy = path.join(tmpCwd, '.claude.json');
fs.writeFileSync(
legacy,
JSON.stringify({ mcpServers: { codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] } } }, null, 2),
);
claude.install('local', { autoAllow: false });
// codegraph now lives in .mcp.json; the legacy file (which held only
// codegraph) is gone.
const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
expect(mcp.mcpServers.codegraph).toBeDefined();
expect(fs.existsSync(legacy)).toBe(false);
});
it('claude: legacy ./.claude.json migration preserves sibling servers and unrelated keys', () => {
const claude = getTarget('claude')!;
const legacy = path.join(tmpCwd, '.claude.json');
fs.writeFileSync(
legacy,
JSON.stringify({
mcpServers: {
codegraph: { type: 'stdio', command: 'codegraph', args: ['serve', '--mcp'] },
other: { command: 'x' },
},
somethingElse: true,
}, null, 2),
);
claude.install('local', { autoAllow: false });
// Only codegraph is stripped from the legacy file; siblings survive.
const after = JSON.parse(fs.readFileSync(legacy, 'utf-8'));
expect(after.mcpServers.codegraph).toBeUndefined();
expect(after.mcpServers.other).toBeDefined();
expect(after.somethingElse).toBe(true);
const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
expect(mcp.mcpServers.codegraph).toBeDefined();
});
it('claude: uninstall strips codegraph from ./.mcp.json and a legacy ./.claude.json', () => {
const claude = getTarget('claude')!;
// A user left with both the working .mcp.json and a stale .claude.json.
fs.writeFileSync(
path.join(tmpCwd, '.mcp.json'),
JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' } } }, null, 2),
);
fs.writeFileSync(
path.join(tmpCwd, '.claude.json'),
JSON.stringify({ mcpServers: { codegraph: { command: 'codegraph' }, other: { command: 'x' } } }, null, 2),
);
claude.uninstall('local');
const mcp = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.mcp.json'), 'utf-8'));
expect(mcp.mcpServers).toBeUndefined();
const legacy = JSON.parse(fs.readFileSync(path.join(tmpCwd, '.claude.json'), 'utf-8'));
expect(legacy.mcpServers.codegraph).toBeUndefined();
expect(legacy.mcpServers.other).toBeDefined();
});
// ---- Legacy auto-sync hook cleanup ----
// Pre-0.8 installs wrote `codegraph mark-dirty` / `sync-if-dirty`
// hooks to settings.json. Both subcommands were removed from the CLI,
// so the Stop hook fails every turn ("unknown command
// 'sync-if-dirty'"). The installer must strip them on upgrade and
// uninstall — without touching the user's unrelated hooks.
function seedSettings(loc: 'global' | 'local', settings: Record<string, any>): string {
const dir = path.join(loc === 'global' ? tmpHome : tmpCwd, '.claude');
fs.mkdirSync(dir, { recursive: true });
const file = path.join(dir, 'settings.json');
fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n');
return file;
}
// Realistic pre-0.8 settings.json: our two auto-sync hooks plus an
// unrelated GitKraken Stop hook the user added (matches the report).
function legacyHookSettings(): Record<string, any> {
return {
hooks: {
PostToolUse: [
{ matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'codegraph mark-dirty', async: true }] },
],
Stop: [
{ hooks: [{ type: 'command', command: 'codegraph sync-if-dirty' }] },
{ hooks: [{ type: 'command', command: '"/Users/me/gk" ai hook run --host claude-code' }] },
],
},
};
}
it('claude: install strips stale codegraph auto-sync hooks but keeps the user\'s GitKraken hook', () => {
const claude = getTarget('claude')!;
const file = seedSettings('global', legacyHookSettings());
claude.install('global', { autoAllow: true });
const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
// The only PostToolUse group held mark-dirty → the event is gone.
expect(after.hooks?.PostToolUse).toBeUndefined();
const stopCommands = (after.hooks?.Stop ?? []).flatMap((g: any) =>
(g.hooks ?? []).map((h: any) => h.command),
);
expect(stopCommands).not.toContain('codegraph sync-if-dirty');
// The unrelated GitKraken hook survives untouched.
expect(stopCommands.some((c: string) => c.includes('gk') && c.includes('ai hook run'))).toBe(true);
// Permissions still written as normal alongside the cleanup.
expect(after.permissions?.allow).toContain('mcp__codegraph__codegraph_search');
});
it('claude: cleanupLegacyHooks preserves a sibling hook sharing our matcher group', () => {
const file = seedSettings('global', {
hooks: {
Stop: [
{
hooks: [
{ type: 'command', command: 'codegraph sync-if-dirty' },
{ type: 'command', command: 'gk ai hook run --host claude-code' },
],
},
],
},
});
expect(cleanupLegacyHooks('global').action).toBe('removed');
const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
expect(after.hooks.Stop[0].hooks.map((h: any) => h.command)).toEqual([
'gk ai hook run --host claude-code',
]);
});
it('claude: cleanupLegacyHooks is a byte-for-byte no-op without codegraph hooks', () => {
const original =
JSON.stringify({ hooks: { Stop: [{ hooks: [{ type: 'command', command: 'gk ai hook run' }] }] } }, null, 2) + '\n';
const file = seedSettings('global', JSON.parse(original));
expect(cleanupLegacyHooks('global').action).toBe('unchanged');
expect(fs.readFileSync(file, 'utf-8')).toBe(original);
});
it('claude: cleanupLegacyHooks reports not-found when settings.json is absent', () => {
expect(cleanupLegacyHooks('global').action).toBe('not-found');
});
it('claude: re-running install after a legacy cleanup leaves settings.json unchanged', () => {
const claude = getTarget('claude')!;
const file = seedSettings('global', legacyHookSettings());
claude.install('global', { autoAllow: true });
const firstPass = fs.readFileSync(file, 'utf-8');
claude.install('global', { autoAllow: true });
expect(fs.readFileSync(file, 'utf-8')).toBe(firstPass);
});
it('claude: uninstall strips stale hooks written in the npx form (local)', () => {
const claude = getTarget('claude')!;
const file = seedSettings('local', {
hooks: {
PostToolUse: [
{ matcher: 'Edit|Write', hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph mark-dirty', async: true }] },
],
Stop: [
{ hooks: [{ type: 'command', command: 'npx @colbymchenry/codegraph sync-if-dirty' }] },
],
},
});
claude.uninstall('local');
const after = JSON.parse(fs.readFileSync(file, 'utf-8'));
// Both events emptied → the whole `hooks` object is removed.
expect(after.hooks).toBeUndefined();
});
});
describe('Installer targets — registry', () => {
it('getTarget returns the right target for each id', () => {
expect(getTarget('claude')?.id).toBe('claude');
expect(getTarget('cursor')?.id).toBe('cursor');
expect(getTarget('codex')?.id).toBe('codex');
expect(getTarget('opencode')?.id).toBe('opencode');
expect(getTarget('hermes')?.id).toBe('hermes');
expect(getTarget('not-a-real-target')).toBeUndefined();
});
it('resolveTargetFlag handles auto/all/none/csv', () => {
expect(resolveTargetFlag('none', 'global')).toEqual([]);
expect(resolveTargetFlag('all', 'global').length).toBe(ALL_TARGETS.length);
const csv = resolveTargetFlag('claude,cursor', 'global');
expect(csv.map((t) => t.id)).toEqual(['claude', 'cursor']);
});
it('resolveTargetFlag throws on unknown id', () => {
expect(() => resolveTargetFlag('claude,bogus', 'global')).toThrow(/Unknown --target/);
});
});
describe('Installer targets — TOML serializer (Codex backbone)', () => {
it('builds a [mcp_servers.codegraph] block with command + args', () => {
const block = buildTomlTable('mcp_servers.codegraph', {
command: 'codegraph',
args: ['serve', '--mcp'],
});
expect(block).toContain('[mcp_servers.codegraph]');
expect(block).toContain('command = "codegraph"');
expect(block).toContain('args = ["serve", "--mcp"]');
});
it('upsert inserts into empty content', () => {
const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
const { content, action } = upsertTomlTable('', 'mcp_servers.codegraph', block);
expect(action).toBe('inserted');
expect(content.startsWith('[mcp_servers.codegraph]')).toBe(true);
});
it('upsert is idempotent — second call returns unchanged', () => {
const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
const first = upsertTomlTable('', 'mcp_servers.codegraph', block);
const second = upsertTomlTable(first.content, 'mcp_servers.codegraph', block);
expect(second.action).toBe('unchanged');
expect(second.content).toBe(first.content);
});
it('upsert replaces an existing block in place, preserving sibling tables', () => {
const existing = [
'[other_table]',
'foo = "bar"',
'',
'[mcp_servers.codegraph]',
'command = "old-codegraph"',
'args = ["old"]',
'',
'[zzz]',
'baz = "qux"',
'',
].join('\n');
const newBlock = buildTomlTable('mcp_servers.codegraph', {
command: 'codegraph',
args: ['serve', '--mcp'],
});
const { content, action } = upsertTomlTable(existing, 'mcp_servers.codegraph', newBlock);
expect(action).toBe('replaced');
expect(content).toContain('[other_table]');
expect(content).toContain('foo = "bar"');
expect(content).toContain('[zzz]');
expect(content).toContain('baz = "qux"');
expect(content).toContain('command = "codegraph"');
expect(content).not.toContain('old-codegraph');
});
it('removeTomlTable strips the block and preserves siblings', () => {
const existing = [
'[other_table]',
'foo = "bar"',
'',
'[mcp_servers.codegraph]',
'command = "codegraph"',
'args = ["serve"]',
].join('\n');
const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
expect(action).toBe('removed');
expect(content).toContain('[other_table]');
expect(content).toContain('foo = "bar"');
expect(content).not.toContain('mcp_servers.codegraph');
});
it('removeTomlTable on missing table returns not-found, no content change', () => {
const existing = '[other]\nfoo = "bar"\n';
const { content, action } = removeTomlTable(existing, 'mcp_servers.codegraph');
expect(action).toBe('not-found');
expect(content).toBe(existing);
});
it('upsert preserves an array-of-tables sibling [[foo]]', () => {
const existing = [
'[[foo]]',
'name = "a"',
'',
'[[foo]]',
'name = "b"',
'',
].join('\n');
const block = buildTomlTable('mcp_servers.codegraph', { command: 'codegraph', args: ['serve'] });
const { content } = upsertTomlTable(existing, 'mcp_servers.codegraph', block);
expect(content.match(/\[\[foo\]\]/g)?.length).toBe(2);
expect(content).toContain('[mcp_servers.codegraph]');
});
});
describe('Installer — uninstallTargets sweep (codegraph uninstall)', () => {
let tmpHome: string;
let tmpCwd: string;
let origCwd: string;
let homeRestore: { restore: () => void };
beforeEach(() => {
tmpHome = mkTmpDir('un-home');
tmpCwd = mkTmpDir('un-cwd');
origCwd = process.cwd();
process.chdir(tmpCwd);
homeRestore = setHome(tmpHome);
});
afterEach(() => {
homeRestore.restore();
process.chdir(origCwd);
fs.rmSync(tmpHome, { recursive: true, force: true });
fs.rmSync(tmpCwd, { recursive: true, force: true });
});
it('sweeps every agent it was installed on and reports removed for each (global)', () => {
for (const t of ALL_TARGETS) {
if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
}
const reports = uninstallTargets(ALL_TARGETS, 'global');
for (const t of ALL_TARGETS) {
const r = reports.find((x) => x.id === t.id)!;
expect(r.status).toBe('removed');
expect(r.removedPaths.length).toBeGreaterThan(0);
// The actual config is gone afterward.
expect(t.detect('global').alreadyConfigured).toBe(false);
}
});
it('is safe on a clean slate — every agent reports not-configured, nothing removed', () => {
const reports = uninstallTargets(ALL_TARGETS, 'global');
for (const r of reports) {
expect(r.status).toBe('not-configured');
expect(r.removedPaths).toEqual([]);
}
});
it('reports removed only for agents that were actually configured', () => {
// Install on Claude only; the rest stay untouched.
getTarget('claude')!.install('global', { autoAllow: true });
const reports = uninstallTargets(ALL_TARGETS, 'global');
const claude = reports.find((r) => r.id === 'claude')!;
expect(claude.status).toBe('removed');
expect(claude.displayName).toBe(getTarget('claude')!.displayName);
for (const r of reports.filter((x) => x.id !== 'claude')) {
expect(r.status).toBe('not-configured');
}
});
it('marks global-only agents as unsupported for a local sweep (and never touches them)', () => {
const reports = uninstallTargets(ALL_TARGETS, 'local');
for (const t of ALL_TARGETS) {
const r = reports.find((x) => x.id === t.id)!;
if (t.supportsLocation('local')) {
expect(r.status).toBe('not-configured');
} else {
expect(r.status).toBe('unsupported');
expect(r.removedPaths).toEqual([]);
expect(r.notes[0]).toMatch(/global-only/);
}
}
});
it('is idempotent — a second sweep finds nothing left to remove', () => {
for (const t of ALL_TARGETS) {
if (t.supportsLocation('global')) t.install('global', { autoAllow: true });
}
const first = uninstallTargets(ALL_TARGETS, 'global');
expect(first.some((r) => r.status === 'removed')).toBe(true);
const second = uninstallTargets(ALL_TARGETS, 'global');
for (const r of second) {
expect(r.status).toBe('not-configured');
expect(r.removedPaths).toEqual([]);
}
});
it('a --target subset removes only the chosen agents, leaving siblings configured', () => {
getTarget('claude')!.install('global', { autoAllow: true });
getTarget('cursor')!.install('global', { autoAllow: true });
const reports = uninstallTargets(resolveTargetFlag('claude', 'global'), 'global');
expect(reports.map((r) => r.id)).toEqual(['claude']);
expect(reports[0].status).toBe('removed');
// Cursor was not in the subset — still configured.
expect(getTarget('cursor')!.detect('global').alreadyConfigured).toBe(true);
expect(getTarget('claude')!.detect('global').alreadyConfigured).toBe(false);
});
});
describe('Installer — Cursor rules file cleanup on uninstall', () => {
let tmpHome: string;
let tmpCwd: string;
let origCwd: string;
let homeRestore: { restore: () => void };
const cursor = getTarget('cursor')!;
beforeEach(() => {
tmpHome = mkTmpDir('cur-home');
tmpCwd = mkTmpDir('cur-cwd');
origCwd = process.cwd();
process.chdir(tmpCwd);
homeRestore = setHome(tmpHome);
});
afterEach(() => {
homeRestore.restore();
process.chdir(origCwd);
fs.rmSync(tmpHome, { recursive: true, force: true });
fs.rmSync(tmpCwd, { recursive: true, force: true });
});
const rulesFile = () => path.join(process.cwd(), '.cursor', 'rules', 'codegraph.mdc');
it('deletes the dedicated codegraph.mdc entirely (no orphaned frontmatter left behind)', () => {
cursor.install('local', { autoAllow: true });
expect(fs.existsSync(rulesFile())).toBe(true);
cursor.uninstall('local');
// The whole file — frontmatter included — is gone, not just the block.
expect(fs.existsSync(rulesFile())).toBe(false);
expect(cursor.detect('local').alreadyConfigured).toBe(false);
});
it('preserves user content added outside the codegraph markers (strips only our block)', () => {
cursor.install('local', { autoAllow: true });
const withUserContent =
fs.readFileSync(rulesFile(), 'utf-8') + '\n## My own rule\nkeep me\n';
fs.writeFileSync(rulesFile(), withUserContent);
cursor.uninstall('local');
expect(fs.existsSync(rulesFile())).toBe(true);
const after = fs.readFileSync(rulesFile(), 'utf-8');
expect(after).toContain('keep me');
// Our tool-usage block is gone.
expect(after).not.toContain('codegraph_search');
expect(after).not.toContain('CODEGRAPH_START');
});
});
function listAllFiles(dir: string): string[] {
if (!fs.existsSync(dir)) return [];
const out: string[] = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) out.push(...listAllFiles(full));
else out.push(full);
}
return out;
}
+220
View File
@@ -0,0 +1,220 @@
/**
* Installer Tests
*
* Tests for installer config-writer fixes:
* - readJsonFile error handling
* - writeClaudeMd section replacement
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
// We test the exported functions from config-writer
import {
writeMcpConfig,
writePermissions,
writeClaudeMd,
hasMcpConfig,
hasPermissions,
hasClaudeMdSection,
} from '../src/installer/config-writer';
function createTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-installer-test-'));
}
function cleanupTempDir(dir: string): void {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
describe('Installer Config Writer', () => {
let origCwd: string;
let tempDir: string;
beforeEach(() => {
tempDir = createTempDir();
origCwd = process.cwd();
process.chdir(tempDir);
});
afterEach(() => {
process.chdir(origCwd);
cleanupTempDir(tempDir);
});
describe('readJsonFile error handling', () => {
it('should return empty object for non-existent file', () => {
// writeMcpConfig reads .mcp.json - if it doesn't exist, it should create it
writeMcpConfig('local');
const mcpJson = path.join(tempDir, '.mcp.json');
expect(fs.existsSync(mcpJson)).toBe(true);
const content = JSON.parse(fs.readFileSync(mcpJson, 'utf-8'));
expect(content.mcpServers).toBeDefined();
expect(content.mcpServers.codegraph).toBeDefined();
});
it('should handle corrupted JSON by creating backup', () => {
// Create a corrupted .mcp.json
const mcpJson = path.join(tempDir, '.mcp.json');
fs.writeFileSync(mcpJson, '{ this is not valid json !!!');
// Suppress console.warn during test
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
// Should not throw - gracefully handles corruption
writeMcpConfig('local');
// Should have warned
expect(warnSpy).toHaveBeenCalled();
const warnMsg = warnSpy.mock.calls[0][0];
expect(warnMsg).toContain('Warning');
// Backup should exist
expect(fs.existsSync(mcpJson + '.backup')).toBe(true);
// Original backup content should be the corrupted content
const backup = fs.readFileSync(mcpJson + '.backup', 'utf-8');
expect(backup).toContain('this is not valid json');
// New file should be valid JSON with codegraph config
const content = JSON.parse(fs.readFileSync(mcpJson, 'utf-8'));
expect(content.mcpServers.codegraph).toBeDefined();
warnSpy.mockRestore();
});
it('should preserve existing valid config when adding codegraph', () => {
const mcpJson = path.join(tempDir, '.mcp.json');
fs.writeFileSync(mcpJson, JSON.stringify({
mcpServers: { other: { command: 'other-tool' } },
customField: 'preserved',
}, null, 2));
writeMcpConfig('local');
const content = JSON.parse(fs.readFileSync(mcpJson, 'utf-8'));
expect(content.mcpServers.codegraph).toBeDefined();
expect(content.mcpServers.other).toBeDefined();
expect(content.customField).toBe('preserved');
});
});
describe('writeClaudeMd section replacement', () => {
it('should create new CLAUDE.md with markers', () => {
const result = writeClaudeMd('local');
expect(result.created).toBe(true);
const content = fs.readFileSync(path.join(tempDir, '.claude', 'CLAUDE.md'), 'utf-8');
expect(content).toContain('<!-- CODEGRAPH_START -->');
expect(content).toContain('<!-- CODEGRAPH_END -->');
expect(content).toContain('## CodeGraph');
});
it('should replace marked section on update', () => {
// First write
writeClaudeMd('local');
// Modify file to add custom content before and after
const claudeMdPath = path.join(tempDir, '.claude', 'CLAUDE.md');
const original = fs.readFileSync(claudeMdPath, 'utf-8');
const modified = '## My Custom Section\n\nCustom content\n\n' + original + '\n\n## Another Section\n\nMore content\n';
fs.writeFileSync(claudeMdPath, modified);
// Second write should leave the marked block as-is (byte-identical
// body, so result is `created:false, updated:false` — both flags
// are off but the surrounding custom content must survive).
writeClaudeMd('local');
const final = fs.readFileSync(claudeMdPath, 'utf-8');
expect(final).toContain('## My Custom Section');
expect(final).toContain('Custom content');
expect(final).toContain('## Another Section');
expect(final).toContain('More content');
expect(final).toContain('## CodeGraph');
});
it('should use atomic writes (no temp files left behind)', () => {
writeClaudeMd('local');
const claudeDir = path.join(tempDir, '.claude');
const files = fs.readdirSync(claudeDir);
const tmpFiles = files.filter(f => f.includes('.tmp.'));
expect(tmpFiles).toHaveLength(0);
});
it('should not overwrite content after unmarked section with ### subsections', () => {
// Create a CLAUDE.md with an unmarked CodeGraph section that has ### subsections
// followed by another ## section
const claudeDir = path.join(tempDir, '.claude');
fs.mkdirSync(claudeDir, { recursive: true });
const claudeMdPath = path.join(claudeDir, 'CLAUDE.md');
fs.writeFileSync(claudeMdPath, [
'## Pre-existing Section',
'',
'Some content',
'',
'## CodeGraph',
'',
'### Subsection A',
'',
'Old codegraph content',
'',
'### Subsection B',
'',
'More old content',
'',
'## Important Section After',
'',
'This content must not be overwritten!',
'',
].join('\n'));
const result = writeClaudeMd('local');
expect(result.updated).toBe(true);
const final = fs.readFileSync(claudeMdPath, 'utf-8');
// The section after CodeGraph must be preserved
expect(final).toContain('## Important Section After');
expect(final).toContain('This content must not be overwritten!');
// Pre-existing section should also be preserved
expect(final).toContain('## Pre-existing Section');
// New CodeGraph content should be present with markers
expect(final).toContain('<!-- CODEGRAPH_START -->');
expect(final).toContain('<!-- CODEGRAPH_END -->');
});
it('should replace unmarked section without subsections', () => {
const claudeDir = path.join(tempDir, '.claude');
fs.mkdirSync(claudeDir, { recursive: true });
const claudeMdPath = path.join(claudeDir, 'CLAUDE.md');
// Note: regex needs \n before ## CodeGraph, so prefix with another section
fs.writeFileSync(claudeMdPath, [
'## Intro',
'',
'Preamble',
'',
'## CodeGraph',
'',
'Old simple content',
'',
'## Next Section',
'',
'Must be preserved',
'',
].join('\n'));
writeClaudeMd('local');
const final = fs.readFileSync(claudeMdPath, 'utf-8');
expect(final).toContain('<!-- CODEGRAPH_START -->');
expect(final).toContain('## Next Section');
expect(final).toContain('Must be preserved');
expect(final).not.toContain('Old simple content');
});
});
});
+244
View File
@@ -0,0 +1,244 @@
/**
* End-to-end pipeline integration tests
*
* Exercises the full happy path that unit tests cover in isolation:
* init → indexAll → resolveReferences → searchNodes/getCallers/buildContext → sync
*
* Also covers two error paths that were previously uncovered:
* - Indexing a file that contains a syntactically invalid snippet
* (parse errors must not abort the batch).
* - Sync correctly applies adds + modifies + removes in a single pass.
*
* A synthetic ~120-file project is generated per test (5k files would
* dwarf the test runner; 120 files of varied TS shape is enough to
* stress the resolver and graph layers without slowing the suite to a
* crawl).
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import CodeGraph from '../../src/index';
function createTempDir(prefix = 'codegraph-int-'): string {
return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
}
function cleanupTempDir(dir: string): void {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
/**
* Generate a synthetic TypeScript project with the given module count.
* Each module exports a function that calls the previous module's
* function so that the resolver has real import edges + call edges to
* resolve. The first module is a leaf; the last is the root.
*/
function generateSyntheticProject(root: string, moduleCount: number): void {
const srcDir = path.join(root, 'src');
fs.mkdirSync(srcDir, { recursive: true });
// Leaf module — no imports.
fs.writeFileSync(
path.join(srcDir, `mod0.ts`),
`export function fn0(x: number): number { return x + 1; }\n` +
`export class Mod0 { ping(): string { return 'mod0'; } }\n`
);
for (let i = 1; i < moduleCount; i++) {
const prev = i - 1;
fs.writeFileSync(
path.join(srcDir, `mod${i}.ts`),
`import { fn${prev}, Mod${prev} } from './mod${prev}';\n` +
`export function fn${i}(x: number): number { return fn${prev}(x) + 1; }\n` +
`export class Mod${i} extends Mod${prev} {\n` +
` call${i}(): number { return fn${i}(${i}); }\n` +
`}\n`
);
}
// Entry point file.
fs.writeFileSync(
path.join(srcDir, 'index.ts'),
`import { fn${moduleCount - 1}, Mod${moduleCount - 1} } from './mod${moduleCount - 1}';\n` +
`export function entry(): number {\n` +
` const m = new Mod${moduleCount - 1}();\n` +
` return fn${moduleCount - 1}(0) + m.call${moduleCount - 1}();\n` +
`}\n`
);
}
describe('Integration: full pipeline', () => {
let tempDir: string;
beforeEach(() => {
tempDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(tempDir);
});
it('runs init → index → resolve → search → callers → context → sync', async () => {
const MODULE_COUNT = 120;
generateSyntheticProject(tempDir, MODULE_COUNT);
// ── init ──────────────────────────────────────────────────────
const cg = await CodeGraph.init(tempDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
try {
// ── indexAll ────────────────────────────────────────────────
const indexResult = await cg.indexAll();
// Synthetic project: MODULE_COUNT mod files + 1 index file.
expect(indexResult.filesIndexed).toBeGreaterThanOrEqual(MODULE_COUNT);
const statsAfterIndex = cg.getStats();
expect(statsAfterIndex.fileCount).toBeGreaterThanOrEqual(MODULE_COUNT);
expect(statsAfterIndex.nodeCount).toBeGreaterThan(MODULE_COUNT * 2);
// ── resolveReferences ────────────────────────────────────────
// Many call-site edges are wired up during extraction itself, so
// the unresolved-reference queue may already be drained by the
// time we get here. We assert that resolve completes cleanly and
// returns a well-formed result; downstream callers/callees
// assertions verify the graph is actually populated.
cg.reinitializeResolver();
const resolution = cg.resolveReferences();
expect(resolution).toBeDefined();
expect(resolution.stats).toBeDefined();
expect(typeof resolution.stats.total).toBe('number');
expect(typeof resolution.stats.resolved).toBe('number');
// ── searchNodes ──────────────────────────────────────────────
const entryResults = cg.searchNodes('entry', { limit: 10 });
expect(entryResults.length).toBeGreaterThan(0);
const entryNode = entryResults.find((r) => r.node.name === 'entry');
expect(entryNode).toBeDefined();
const midResults = cg.searchNodes(`fn50`, { limit: 10 });
expect(midResults.find((r) => r.node.name === 'fn50')).toBeDefined();
// ── getCallers / getCallees ──────────────────────────────────
const fn0Results = cg.searchNodes('fn0', { limit: 5 });
const fn0Node = fn0Results.find((r) => r.node.name === 'fn0');
expect(fn0Node).toBeDefined();
const callers = cg.getCallers(fn0Node!.node.id);
// fn0 is called by fn1 (at least). After resolution this should
// be wired up.
expect(Array.isArray(callers)).toBe(true);
// ── buildContext ─────────────────────────────────────────────
const context = await cg.buildContext('entry function chain', {
maxNodes: 10,
format: 'markdown',
});
expect(typeof context).toBe('string');
expect((context as string).length).toBeGreaterThan(0);
// ── sync (add + modify + remove in one pass) ─────────────────
// Add: a new file referencing entry().
fs.writeFileSync(
path.join(tempDir, 'src', 'consumer.ts'),
`import { entry } from './index';\nexport const result = entry();\n`
);
// Modify: change mod0.
fs.writeFileSync(
path.join(tempDir, 'src', 'mod0.ts'),
`export function fn0(x: number): number { return x + 2; }\n` +
`export function newHelper(): string { return 'new'; }\n` +
`export class Mod0 { ping(): string { return 'mod0v2'; } }\n`
);
// Remove: drop mod1 — note this will leave dangling imports in
// mod2, which the resolver should tolerate.
fs.unlinkSync(path.join(tempDir, 'src', 'mod1.ts'));
const syncResult = await cg.sync();
expect(syncResult.filesAdded).toBeGreaterThanOrEqual(1);
expect(syncResult.filesModified).toBeGreaterThanOrEqual(1);
expect(syncResult.filesRemoved).toBeGreaterThanOrEqual(1);
// New symbol must now be findable; removed file's symbols gone.
expect(cg.searchNodes('newHelper').length).toBeGreaterThan(0);
// Removed file should no longer appear in the indexed file list.
// (FTS prefix matching makes name-based assertions unreliable here —
// Mod10/Mod11/… all start with "Mod1" — so we check the file set
// instead.)
const filesAfterSync = cg.getNodesInFile('src/mod1.ts');
expect(filesAfterSync).toHaveLength(0);
} finally {
cg.destroy();
}
}, 60_000);
it('keeps indexing files when one file has a parse error', async () => {
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
// Valid files
fs.writeFileSync(
path.join(srcDir, 'good1.ts'),
`export function good1(): number { return 1; }\n`
);
fs.writeFileSync(
path.join(srcDir, 'good2.ts'),
`export function good2(): number { return 2; }\n`
);
// Intentionally broken file — unclosed brace, stray tokens.
fs.writeFileSync(
path.join(srcDir, 'broken.ts'),
`export function broken(\n this is { not valid typescript at all\n`
);
const cg = await CodeGraph.init(tempDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
try {
const result = await cg.indexAll();
// The two good files must still be indexed regardless of the
// broken one. Tree-sitter is error-tolerant so it may still
// extract a partial AST from broken.ts — but the test only
// requires that the batch completes and finds the good symbols.
expect(result.filesIndexed).toBeGreaterThanOrEqual(2);
const good1 = cg.searchNodes('good1');
const good2 = cg.searchNodes('good2');
expect(good1.find((r) => r.node.name === 'good1')).toBeDefined();
expect(good2.find((r) => r.node.name === 'good2')).toBeDefined();
} finally {
cg.destroy();
}
}, 30_000);
it('handles repeated sync calls when nothing has changed', async () => {
generateSyntheticProject(tempDir, 10);
const cg = await CodeGraph.init(tempDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
try {
await cg.indexAll();
const statsBefore = cg.getStats();
const first = await cg.sync();
const second = await cg.sync();
// Subsequent sync with no changes should be a no-op.
expect(first.filesAdded + first.filesModified + first.filesRemoved).toBe(0);
expect(second.filesAdded + second.filesModified + second.filesRemoved).toBe(0);
const statsAfter = cg.getStats();
expect(statsAfter.fileCount).toBe(statsBefore.fileCount);
expect(statsAfter.nodeCount).toBe(statsBefore.nodeCount);
} finally {
cg.destroy();
}
}, 30_000);
});
+96
View File
@@ -0,0 +1,96 @@
/**
* LRUCache unit tests
*
* Covers the eviction guarantees that the resolver relies on:
* - capacity is enforced (never exceeds max)
* - LRU ordering: hot keys survive eviction passes
* - has()/get()/set()/clear() behave like the original Map shape
* - null values are storable (the fileCache uses null for "failed read")
*/
import { describe, it, expect } from 'vitest';
import { LRUCache } from '../../src/resolution/lru-cache';
describe('LRUCache', () => {
it('enforces capacity by evicting the oldest entry on overflow', () => {
const cache = new LRUCache<string, number>(3);
cache.set('a', 1);
cache.set('b', 2);
cache.set('c', 3);
cache.set('d', 4); // evicts 'a'
expect(cache.size).toBe(3);
expect(cache.has('a')).toBe(false);
expect(cache.get('a')).toBeUndefined();
expect(cache.get('b')).toBe(2);
expect(cache.get('c')).toBe(3);
expect(cache.get('d')).toBe(4);
});
it('promotes touched keys to most-recent so they survive eviction', () => {
const cache = new LRUCache<string, number>(3);
cache.set('a', 1);
cache.set('b', 2);
cache.set('c', 3);
// Touch 'a' — it should now be most-recent.
expect(cache.get('a')).toBe(1);
cache.set('d', 4); // evicts the LRU, which is now 'b' (not 'a')
expect(cache.has('a')).toBe(true);
expect(cache.has('b')).toBe(false);
expect(cache.has('c')).toBe(true);
expect(cache.has('d')).toBe(true);
});
it('overwriting an existing key refreshes its recency but does not grow size', () => {
const cache = new LRUCache<string, number>(2);
cache.set('a', 1);
cache.set('b', 2);
cache.set('a', 99); // 'a' is now most-recent
expect(cache.size).toBe(2);
expect(cache.get('a')).toBe(99);
cache.set('c', 3); // should evict 'b', not 'a'
expect(cache.has('a')).toBe(true);
expect(cache.has('b')).toBe(false);
expect(cache.has('c')).toBe(true);
});
it('stores null values (used by the file content cache)', () => {
const cache = new LRUCache<string, string | null>(2);
cache.set('missing.ts', null);
expect(cache.has('missing.ts')).toBe(true);
expect(cache.get('missing.ts')).toBeNull();
});
it('clear() resets the cache', () => {
const cache = new LRUCache<string, number>(3);
cache.set('a', 1);
cache.set('b', 2);
cache.clear();
expect(cache.size).toBe(0);
expect(cache.has('a')).toBe(false);
});
it('rejects non-positive capacity', () => {
expect(() => new LRUCache(0)).toThrow();
expect(() => new LRUCache(-1)).toThrow();
expect(() => new LRUCache(NaN)).toThrow();
});
it('stays bounded under heavy churn (regression for OOM scenario)', () => {
const cache = new LRUCache<string, number>(100);
for (let i = 0; i < 10_000; i++) {
cache.set(`key${i}`, i);
}
expect(cache.size).toBe(100);
// The last 100 keys should still be present, the rest evicted.
expect(cache.has('key9999')).toBe(true);
expect(cache.has('key9900')).toBe(true);
expect(cache.has('key0')).toBe(false);
});
});
@@ -0,0 +1,109 @@
/**
* MCP tool input-size limits
*
* Regression coverage for the DoS vector: MCP clients can ship
* unbounded payloads (`query`, `task`, `symbol`, `projectPath`,
* `path`, `pattern`). Before the cap, a 100MB string would hit
* the FTS5 layer and pin the server. These tests assert that the
* tool layer rejects oversize inputs early.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import CodeGraph from '../../src/index';
import { ToolHandler } from '../../src/mcp/tools';
describe('MCP input size limits', () => {
let tempDir: string;
let cg: CodeGraph;
let handler: ToolHandler;
beforeEach(async () => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-limits-'));
fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
fs.writeFileSync(
path.join(tempDir, 'src', 'a.ts'),
`export function alpha(): number { return 1; }\n`
);
cg = await CodeGraph.init(tempDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
await cg.indexAll();
handler = new ToolHandler(cg);
});
afterEach(() => {
if (cg) cg.destroy();
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
});
it('accepts a normal-sized query', async () => {
const result = await handler.execute('codegraph_search', { query: 'alpha' });
expect(result.isError).toBeFalsy();
});
it('rejects an oversize query on codegraph_search', async () => {
const huge = 'a'.repeat(20_000);
const result = await handler.execute('codegraph_search', { query: huge });
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toMatch(/maximum length/i);
});
it('rejects an oversize task on codegraph_context', async () => {
const huge = 'b'.repeat(50_000);
const result = await handler.execute('codegraph_context', { task: huge });
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toMatch(/maximum length/i);
});
it('rejects an oversize symbol on codegraph_callers', async () => {
const huge = 'c'.repeat(15_000);
const result = await handler.execute('codegraph_callers', { symbol: huge });
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toMatch(/maximum length/i);
});
it('rejects an oversize symbol on codegraph_impact', async () => {
const huge = 'd'.repeat(11_000);
const result = await handler.execute('codegraph_impact', { symbol: huge });
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toMatch(/maximum length/i);
});
it('rejects an oversize projectPath', async () => {
const hugePath = '/tmp/' + 'x'.repeat(5_000);
const result = await handler.execute('codegraph_search', {
query: 'alpha',
projectPath: hugePath,
});
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toMatch(/projectPath/);
});
it('rejects an oversize path filter on codegraph_files', async () => {
const hugePath = 'src/' + 'y'.repeat(5_000);
const result = await handler.execute('codegraph_files', { path: hugePath });
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toMatch(/path/);
});
it('rejects an oversize glob pattern on codegraph_files', async () => {
const hugePattern = '*'.repeat(5_000);
const result = await handler.execute('codegraph_files', { pattern: hugePattern });
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toMatch(/pattern/);
});
it('rejects a non-string projectPath', async () => {
const result = await handler.execute('codegraph_search', {
query: 'alpha',
projectPath: 12345 as unknown as string,
});
expect(result.isError).toBe(true);
expect(result.content[0]!.text).toMatch(/projectPath/);
});
});
+53
View File
@@ -0,0 +1,53 @@
/**
* isTestFile heuristic — test-file detection used to deprioritize test code in
* search/explore ranking.
*
* Regression coverage for the cold-query fix: the heuristic previously only
* knew Java/JS/Python conventions, so Kotlin (`*Test.kt`, `jvmTest/`), Swift
* (`*Tests.swift`), and camelCase test source-set dirs slipped through — which
* let OkHttp's tests flood `codegraph_explore` results on a plain-language
* query. The false-positive guards matter just as much: `latest.kt` /
* `manifest.kt` / a `RealCall.kt` production file must NOT be flagged.
*/
import { describe, it, expect } from 'vitest';
import { isTestFile } from '../src/search/query-utils';
describe('isTestFile', () => {
it('flags Kotlin test files and source sets', () => {
expect(isTestFile('okhttp/src/jvmTest/kotlin/okhttp3/CallTest.kt')).toBe(true);
expect(isTestFile('okhttp/src/commonTest/kotlin/okhttp3/CompressionInterceptorTest.kt')).toBe(true);
expect(isTestFile('app/src/androidTest/java/com/example/FooTest.kt')).toBe(true);
expect(isTestFile('module/src/integrationTest/kotlin/BarSpec.kt')).toBe(true);
});
it('flags Swift test files', () => {
expect(isTestFile('Tests/SessionTests.swift')).toBe(true);
expect(isTestFile('Sources/FooTest.swift')).toBe(true);
});
it('still flags the previously-supported conventions', () => {
expect(isTestFile('foo/test_bar.py')).toBe(true);
expect(isTestFile('pkg/bar_test.go')).toBe(true);
expect(isTestFile('src/foo.test.ts')).toBe(true);
expect(isTestFile('src/foo.spec.ts')).toBe(true);
expect(isTestFile('com/example/FooTest.java')).toBe(true);
expect(isTestFile('com/example/FooTestCase.java')).toBe(true);
expect(isTestFile('project/__tests__/foo.ts')).toBe(true);
expect(isTestFile('project/tests/foo.rb')).toBe(true);
});
it('does NOT flag production files that merely contain "test" lowercase', () => {
// The fix is capital-led so camelCase boundaries distinguish these.
expect(isTestFile('src/latest/loader.kt')).toBe(false);
expect(isTestFile('lib/manifest.kt')).toBe(false);
expect(isTestFile('okhttp/src/jvmMain/kotlin/okhttp3/internal/connection/RealCall.kt')).toBe(false);
expect(isTestFile('src/contestEntry.ts')).toBe(false);
expect(isTestFile('pkg/greatest.go')).toBe(false);
});
it('does NOT flag ordinary production source', () => {
expect(isTestFile('src/flask/app.py')).toBe(false);
expect(isTestFile('src/vs/workbench/api/common/extensionHostMain.ts')).toBe(false);
expect(isTestFile('okhttp/src/commonJvmAndroid/kotlin/okhttp3/OkHttpClient.kt')).toBe(false);
});
});
+149
View File
@@ -0,0 +1,149 @@
/**
* MCP `initialize` handshake regression tests.
*
* Issue #172: on slow filesystems (Docker Desktop VirtioFS on macOS, WSL2),
* the MCP server was blocking the initialize response on CodeGraph.open() and
* Parser.init() (web-tree-sitter WASM bootstrap), which could take longer than
* Claude Code's ~30s handshake timeout. The child process stayed alive and
* had received the request, but never sent a response, so tools never
* appeared in the client. The fix sends the initialize response before
* kicking off the heavy init in the background. These tests guard the
* contract that initialize is fast regardless of how much work init does.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph } from '../src';
const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
function spawnServer(cwd: string): ChildProcessWithoutNullStreams {
return spawn(process.execPath, [BIN, 'serve', '--mcp'], {
cwd,
stdio: ['pipe', 'pipe', 'pipe'],
}) as ChildProcessWithoutNullStreams;
}
function sendInitialize(child: ChildProcessWithoutNullStreams, projectPath: string) {
const msg = JSON.stringify({
jsonrpc: '2.0',
id: 0,
method: 'initialize',
params: {
protocolVersion: '2025-11-25',
capabilities: {},
clientInfo: { name: 'test', version: '0.0.0' },
rootUri: `file://${projectPath}`,
},
});
child.stdin.write(msg + '\n');
}
/**
* Collect stdout lines and stderr text from the child, tagging each piece
* with a monotonic sequence number. Lets us assert ordering between the
* JSON-RPC response (stdout) and side-effect logs (stderr).
*/
function tagStreams(child: ChildProcessWithoutNullStreams) {
const events: Array<{ seq: number; stream: 'stdout' | 'stderr'; text: string }> = [];
let seq = 0;
let stdoutBuf = '';
let stderrBuf = '';
child.stdout.on('data', (chunk) => {
stdoutBuf += chunk.toString('utf8');
let idx;
while ((idx = stdoutBuf.indexOf('\n')) !== -1) {
const line = stdoutBuf.slice(0, idx);
stdoutBuf = stdoutBuf.slice(idx + 1);
events.push({ seq: seq++, stream: 'stdout', text: line });
}
});
child.stderr.on('data', (chunk) => {
stderrBuf += chunk.toString('utf8');
let idx;
while ((idx = stderrBuf.indexOf('\n')) !== -1) {
const line = stderrBuf.slice(0, idx);
stderrBuf = stderrBuf.slice(idx + 1);
events.push({ seq: seq++, stream: 'stderr', text: line });
}
});
return events;
}
function waitFor<T>(
events: ReadonlyArray<{ seq: number; stream: string; text: string }>,
predicate: (e: { seq: number; stream: string; text: string }) => boolean,
timeoutMs: number,
): Promise<{ seq: number; stream: string; text: string }> {
return new Promise((resolve, reject) => {
const started = Date.now();
const tick = () => {
const hit = events.find(predicate);
if (hit) return resolve(hit);
if (Date.now() - started > timeoutMs) {
return reject(new Error(`Timed out waiting for predicate. Events: ${JSON.stringify(events)}`));
}
setTimeout(tick, 20);
};
tick();
});
}
describe('MCP initialize handshake (issue #172)', () => {
let tempDir: string;
let child: ChildProcessWithoutNullStreams | null = null;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-init-'));
});
afterEach(() => {
if (child && !child.killed) {
child.kill('SIGKILL');
child = null;
}
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('responds to initialize quickly when no .codegraph exists in cwd', async () => {
child = spawnServer(tempDir);
const events = tagStreams(child);
sendInitialize(child, tempDir);
const response = await waitFor(events, (e) => e.stream === 'stdout', 5000);
const json = JSON.parse(response.text);
expect(json.jsonrpc).toBe('2.0');
expect(json.id).toBe(0);
expect(json.result.protocolVersion).toBeDefined();
expect(json.result.capabilities.tools).toBeDefined();
}, 10000);
it('sends initialize response BEFORE tryInitializeDefault finishes', async () => {
// Seed a real .codegraph so the server's tryInitializeDefault path runs
// its full body: CodeGraph.open() (which awaits initGrammars()) and then
// startWatching() (which logs "File watcher active" to stderr). On any
// platform, that stderr log is observable evidence that tryInitializeDefault
// has completed. The contract we're protecting: the JSON-RPC response on
// stdout must arrive BEFORE that stderr log. If a future change re-awaits
// tryInitializeDefault before sendResult, this ordering inverts and the
// test fails — regardless of how fast the local filesystem is.
const cg = await CodeGraph.init(tempDir);
cg.close();
child = spawnServer(tempDir);
const events = tagStreams(child);
sendInitialize(child, tempDir);
const response = await waitFor(events, (e) => e.stream === 'stdout', 10000);
const watcherLog = await waitFor(
events,
(e) => e.stream === 'stderr' && e.text.includes('File watcher active'),
10000,
);
expect(response.seq).toBeLessThan(watcherLog.seq);
const json = JSON.parse(response.text);
expect(json.id).toBe(0);
expect(json.result.serverInfo.name).toBe('codegraph');
}, 20000);
});
+168
View File
@@ -0,0 +1,168 @@
/**
* PPID watchdog regression test (#277).
*
* On Linux, when an MCP host (Claude Code, opencode, …) is SIGKILL'd by the
* OOM killer / a force-quit / a container teardown, the kernel does NOT
* propagate the death to its `codegraph serve --mcp` child. The child gets
* reparented to init/systemd, its stdin stays half-open in some
* configurations, and the existing `stdin.on('end' | 'close')` handlers
* never fire — the server lingers indefinitely, holding inotify watches,
* file descriptors, and the SQLite WAL.
*
* `src/mcp/index.ts` polls `process.ppid` and shuts down the moment it
* diverges from the value observed at startup. This test stands up a
* four-tier process tree (vitest → wrapper → {stdin-holder, codegraph}) and
* SIGKILL's the wrapper. The stdin-holder is a long-lived sibling whose
* `stdout` pipe is dup'd into codegraph's `stdin`. After the wrapper dies
* the pipe stays open (stdin-holder still owns the write-end), so the
* existing stdin close handlers do **not** fire — the only thing that can
* terminate codegraph then is the PPID watchdog.
*
* Windows is excluded — `process.kill(pid, 'SIGKILL')` does not actually
* deliver SIGKILL there, and the per-OS reparenting semantics the watchdog
* relies on are POSIX-specific.
*/
import { describe, it, expect, afterEach } from 'vitest';
import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
function isAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
function waitForExit(pid: number, timeoutMs: number): Promise<boolean> {
return new Promise((resolve) => {
const start = Date.now();
const tick = () => {
if (!isAlive(pid)) return resolve(true);
if (Date.now() - start > timeoutMs) return resolve(false);
setTimeout(tick, 100);
};
tick();
});
}
describe.skipIf(process.platform === 'win32')('MCP PPID watchdog (#277)', () => {
let wrapper: ChildProcessWithoutNullStreams | null = null;
let childPid: number | null = null;
let stdinHolderPid: number | null = null;
afterEach(() => {
if (wrapper && !wrapper.killed) {
try { wrapper.kill('SIGKILL'); } catch { /* already gone */ }
}
// Belt and suspenders — don't leak processes if an assertion failed.
for (const pid of [childPid, stdinHolderPid]) {
if (pid !== null && isAlive(pid)) {
try { process.kill(pid, 'SIGKILL'); } catch { /* already gone */ }
}
}
wrapper = null;
childPid = null;
stdinHolderPid = null;
});
it("shuts down when its parent is SIGKILL'd and stdin stays open", async () => {
// The wrapper:
// 1. Spawns a "stdin-holder" — a tiny long-lived node process whose
// `stdout` pipe is dup'd into codegraph's `stdin`. As long as the
// stdin-holder is alive (it is — it's an orphan after the wrapper
// dies), codegraph's stdin never sees EOF.
// 2. Spawns codegraph with that pipe as fd 0 and its stderr redirected
// to a tmp file that survives the wrapper, then reports both PIDs.
// 3. Idles until SIGKILL'd from the test.
//
// CODEGRAPH_PPID_POLL_MS=200 keeps the watchdog responsive in test; the
// production default is 5000ms.
const stderrLog = path.join(
fs.mkdtempSync(path.join(os.tmpdir(), 'cg-ppid-watchdog-')),
'codegraph.stderr.log',
);
// The wrapper waits 800ms before reporting the PIDs so the codegraph
// child has time to finish its async start() (dynamic import + transport
// setup + watchdog registration). Otherwise the test races: it
// SIGKILL's the wrapper before the watchdog interval is installed, and
// nothing terminates codegraph.
const wrapperSrc = `
const { spawn } = require('child_process');
const fs = require('fs');
const stderrFd = fs.openSync(${JSON.stringify(stderrLog)}, 'a');
const stdinHolder = spawn(process.execPath, ['-e', 'setInterval(() => {}, 60000)'], {
stdio: ['ignore', 'pipe', 'ignore'],
detached: true,
});
stdinHolder.unref();
const child = spawn(process.execPath, [${JSON.stringify(BIN)}, 'serve', '--mcp'], {
stdio: [stdinHolder.stdout, 'ignore', stderrFd],
env: { ...process.env, CODEGRAPH_PPID_POLL_MS: '200' },
detached: true,
});
child.unref();
setTimeout(() => {
process.stdout.write(JSON.stringify({ pid: child.pid, stdinHolderPid: stdinHolder.pid }) + '\\n');
}, 800);
setInterval(() => {}, 60000);
`;
wrapper = spawn(process.execPath, ['-e', wrapperSrc], {
stdio: ['pipe', 'pipe', 'pipe'],
}) as ChildProcessWithoutNullStreams;
const pids = await new Promise<{ pid: number; stdinHolderPid: number }>((resolve, reject) => {
let buf = '';
const timer = setTimeout(
() => reject(new Error('wrapper did not report PIDs in time')),
10000,
);
wrapper!.stdout.on('data', (chunk: Buffer) => {
buf += chunk.toString('utf8');
const m = buf.match(/\{"pid":(\d+),"stdinHolderPid":(\d+)\}/);
if (m) {
clearTimeout(timer);
resolve({ pid: parseInt(m[1], 10), stdinHolderPid: parseInt(m[2], 10) });
}
});
wrapper!.on('exit', () => {
clearTimeout(timer);
reject(new Error('wrapper exited before reporting PIDs'));
});
});
childPid = pids.pid;
stdinHolderPid = pids.stdinHolderPid;
expect(isAlive(childPid)).toBe(true);
expect(isAlive(stdinHolderPid)).toBe(true);
// SIGKILL the wrapper — no cleanup runs, just like a real OOM kill.
// codegraph and the stdin-holder both get reparented to init/systemd.
// Crucially, the pipe between them stays open, so codegraph's stdin
// doesn't close: only the watchdog can take it down.
wrapper.kill('SIGKILL');
// Watchdog runs every 200ms in this test → 5s gives ~25 polls of headroom.
const exited = await waitForExit(childPid, 5000);
const stderrContent = fs.existsSync(stderrLog) ? fs.readFileSync(stderrLog, 'utf-8') : '<no stderr captured>';
expect(
exited,
`codegraph child (pid=${childPid}) did not exit within 5s after wrapper was SIGKILL'd.\nstderr:\n${stderrContent}`,
).toBe(true);
// The watchdog announces itself before tearing down — assert that the
// shutdown came from the parent-death path, not from any other signal.
expect(stderrContent).toMatch(/Parent process exited.*shutting down/);
// The stdin-holder is now an orphan — kill it explicitly so it doesn't
// outlive the test. It's still tracked in `stdinHolderPid` for the
// afterEach safety net, but we tidy up proactively here too.
if (isAlive(stdinHolderPid)) {
try { process.kill(stdinHolderPid, 'SIGKILL'); } catch { /* race */ }
}
}, 20000);
});
+180
View File
@@ -0,0 +1,180 @@
/**
* MCP project-resolution regression tests (issue #196).
*
* When an MCP client launches the server outside the project directory AND
* doesn't pass a `rootUri`/`workspaceFolders` in `initialize`, the server used
* to fall straight back to `process.cwd()` — which for many IDE clients is the
* wrong directory. Every tool call without an explicit `projectPath` then
* failed with a misleading "CodeGraph not initialized. Run 'codegraph init'."
*
* The fix: when no explicit path is provided, the server asks the client for
* its workspace root via the spec-blessed `roots/list` request (if the client
* advertised the `roots` capability), and only falls back to cwd otherwise.
* When it still can't resolve, the error now says exactly how to fix it.
*
* These tests drive the real stdio transport via a spawned subprocess — no
* mocking — so they also exercise the new bidirectional request/response path.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { spawn, ChildProcessWithoutNullStreams } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph } from '../src';
const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
function spawnServer(cwd: string): ChildProcessWithoutNullStreams {
// --no-watch keeps the test deterministic and avoids watcher startup noise.
return spawn(process.execPath, [BIN, 'serve', '--mcp', '--no-watch'], {
cwd,
stdio: ['pipe', 'pipe', 'pipe'],
}) as ChildProcessWithoutNullStreams;
}
/** Parse every JSON-RPC message the server writes to stdout into an array. */
function collectMessages(child: ChildProcessWithoutNullStreams): Array<Record<string, any>> {
const messages: Array<Record<string, any>> = [];
let buf = '';
child.stdout.on('data', (chunk) => {
buf += chunk.toString('utf8');
let idx;
while ((idx = buf.indexOf('\n')) !== -1) {
const line = buf.slice(0, idx).trim();
buf = buf.slice(idx + 1);
if (!line) continue;
try { messages.push(JSON.parse(line)); } catch { /* ignore non-JSON */ }
}
});
return messages;
}
function waitForMessage(
messages: ReadonlyArray<Record<string, any>>,
predicate: (m: Record<string, any>) => boolean,
timeoutMs: number,
): Promise<Record<string, any>> {
return new Promise((resolve, reject) => {
const started = Date.now();
const tick = () => {
const hit = messages.find(predicate);
if (hit) return resolve(hit);
if (Date.now() - started > timeoutMs) {
return reject(new Error(`Timed out. Messages so far: ${JSON.stringify(messages)}`));
}
setTimeout(tick, 20);
};
tick();
});
}
function send(child: ChildProcessWithoutNullStreams, msg: object): void {
child.stdin.write(JSON.stringify(msg) + '\n');
}
const CLIENT_INFO = { name: 'test', version: '0.0.0' };
describe('MCP project resolution via roots/list (issue #196)', () => {
let cwdDir: string; // where the server is launched — has NO .codegraph
let projectDir: string; // the real indexed project the client reports
let child: ChildProcessWithoutNullStreams | null = null;
beforeEach(() => {
cwdDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-cwd-'));
projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-proj-'));
});
afterEach(() => {
if (child && !child.killed) {
child.kill('SIGKILL');
child = null;
}
fs.rmSync(cwdDir, { recursive: true, force: true });
fs.rmSync(projectDir, { recursive: true, force: true });
});
it('resolves the project from the client roots/list when no rootUri is sent', async () => {
const cg = await CodeGraph.init(projectDir);
cg.close();
child = spawnServer(cwdDir);
const messages = collectMessages(child);
// Advertise the roots capability but pass NO rootUri/workspaceFolders.
send(child, {
jsonrpc: '2.0', id: 0, method: 'initialize',
params: { protocolVersion: '2025-11-25', capabilities: { roots: {} }, clientInfo: CLIENT_INFO },
});
await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000);
send(child, { jsonrpc: '2.0', method: 'notifications/initialized' });
// First tool call (no projectPath) drives the server to ask us for roots.
send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
const rootsReq = await waitForMessage(messages, (m) => m.method === 'roots/list', 5000);
expect(typeof rootsReq.id).toBe('string'); // server-initiated id
send(child, {
jsonrpc: '2.0', id: rootsReq.id,
result: { roots: [{ uri: `file://${projectDir}`, name: 'proj' }] },
});
// The status call now succeeds against the resolved project.
const resp = await waitForMessage(messages, (m) => m.id === 1, 8000);
const text = resp.result.content[0].text as string;
expect(text).toContain('CodeGraph Status');
expect(text).not.toContain('No CodeGraph project is loaded');
}, 20000);
it('returns an actionable error when there is no rootUri and no roots capability', async () => {
child = spawnServer(cwdDir);
const messages = collectMessages(child);
send(child, {
jsonrpc: '2.0', id: 0, method: 'initialize',
params: { protocolVersion: '2025-11-25', capabilities: {}, clientInfo: CLIENT_INFO },
});
await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000);
send(child, { jsonrpc: '2.0', method: 'notifications/initialized' });
send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
const resp = await waitForMessage(messages, (m) => m.id === 1, 8000);
const text = resp.result.content[0].text as string;
expect(text).toContain('No CodeGraph project is loaded');
expect(text).toContain('projectPath');
expect(text).toContain('--path');
// Names the directory it actually searched (the wrong cwd) so the user can
// see why detection missed. basename survives any symlink realpath-ing.
expect(text).toContain(path.basename(cwdDir));
// It must not have hung waiting on roots/list — the client never offered it.
expect(messages.some((m) => m.method === 'roots/list')).toBe(false);
}, 20000);
it('honors an explicit rootUri without asking the client for roots', async () => {
const cg = await CodeGraph.init(projectDir);
cg.close();
child = spawnServer(cwdDir);
const messages = collectMessages(child);
send(child, {
jsonrpc: '2.0', id: 0, method: 'initialize',
params: {
protocolVersion: '2025-11-25',
capabilities: { roots: {} },
clientInfo: CLIENT_INFO,
rootUri: `file://${projectDir}`,
},
});
await waitForMessage(messages, (m) => m.id === 0 && !!m.result, 5000);
send(child, { jsonrpc: '2.0', method: 'notifications/initialized' });
send(child, { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
const resp = await waitForMessage(messages, (m) => m.id === 1, 8000);
const text = resp.result.content[0].text as string;
expect(text).toContain('CodeGraph Status');
// rootUri is a stronger signal than roots — we never needed to ask.
expect(messages.some((m) => m.method === 'roots/list')).toBe(false);
}, 20000);
});
+71
View File
@@ -0,0 +1,71 @@
/**
* node:sqlite backend (issue #238 follow-up).
*
* node:sqlite (Node's built-in real SQLite) is now the sole backend. This drives
* a real index + queries through it, so WAL, FTS5 search, and @named-param
* writes are all exercised end-to-end.
*
* Skipped on Node < 22.5 where node:sqlite doesn't exist.
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import CodeGraph from '../src';
let nodeSqliteAvailable = false;
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
require('node:sqlite');
nodeSqliteAvailable = true;
} catch {
nodeSqliteAvailable = false;
}
describe.skipIf(!nodeSqliteAvailable)('node:sqlite backend — real index + queries', () => {
let dir: string;
let cg: CodeGraph;
beforeAll(async () => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-nodesqlite-'));
fs.writeFileSync(path.join(dir, 'a.ts'), 'export function helper(): number { return 1; }\n');
fs.writeFileSync(
path.join(dir, 'b.ts'),
"import { helper } from './a';\nexport function main(): number { return helper(); }\n"
);
cg = await CodeGraph.init(dir, { index: true });
});
afterAll(() => {
cg?.close();
fs.rmSync(dir, { recursive: true, force: true });
});
it('uses the node:sqlite backend', () => {
expect(cg.getBackend()).toBe('node-sqlite');
});
it('runs in WAL mode — the whole reason it beats the wasm fallback', () => {
expect(cg.getJournalMode()).toBe('wal');
});
it('indexed the project (write path: @named-param INSERTs via node:sqlite)', () => {
const stats = cg.getStats();
expect(stats.fileCount).toBe(2);
expect(stats.nodeCount).toBeGreaterThan(0);
});
it('FTS5 search returns the indexed symbol (read path)', () => {
const results = cg.searchNodes('helper');
const names = results.map(r => r.node.name);
expect(names).toContain('helper');
});
it('graph traversal resolves the cross-file caller', () => {
const helper = cg.searchNodes('helper').find(r => r.node.name === 'helper');
expect(helper).toBeTruthy();
const callers = cg.getCallers(helper!.node.id);
expect(callers.map(c => c.node.name)).toContain('main');
});
});
+69
View File
@@ -0,0 +1,69 @@
/**
* Pin the Node-25 block banner content. The banner replaced a soft
* `console.warn` because the warning was scrolling off-screen before
* the OOM crash 30 seconds later, generating duplicate bug reports
* (#54, #81, #140). The recipe and override env var below are
* load-bearing — if any of them get edited away, this test catches it.
*/
import { describe, it, expect } from 'vitest';
import { buildNode25BlockBanner, buildNodeTooOldBanner, MIN_NODE_MAJOR } from '../src/bin/node-version-check';
describe('buildNode25BlockBanner', () => {
it('embeds the reported Node version in the header', () => {
expect(buildNode25BlockBanner('25.9.0')).toContain(
'Unsupported Node.js version: 25.9.0'
);
});
it('names the V8 turboshaft WASM root cause and the OOM symptom', () => {
const banner = buildNode25BlockBanner('25.7.0');
expect(banner).toContain('V8 WASM JIT');
expect(banner).toContain('turboshaft');
expect(banner).toContain('Fatal process out of memory: Zone');
});
it('points users to Node 22 LTS via nvm and Homebrew', () => {
const banner = buildNode25BlockBanner('25.7.0');
expect(banner).toContain('Node.js 22 LTS');
expect(banner).toContain('nvm install 22');
expect(banner).toContain('brew install node@22');
});
it('documents the CODEGRAPH_ALLOW_UNSAFE_NODE override', () => {
const banner = buildNode25BlockBanner('25.7.0');
expect(banner).toContain('CODEGRAPH_ALLOW_UNSAFE_NODE=1');
});
it('links to issue #81 for the root-cause writeup', () => {
expect(buildNode25BlockBanner('25.7.0')).toContain(
'github.com/colbymchenry/codegraph/issues/81'
);
});
});
describe('buildNodeTooOldBanner', () => {
it('embeds the reported Node version in the header', () => {
expect(buildNodeTooOldBanner('18.20.0')).toContain(
'Unsupported Node.js version: 18.20.0'
);
});
it('states the supported floor matching MIN_NODE_MAJOR', () => {
expect(MIN_NODE_MAJOR).toBe(20);
expect(buildNodeTooOldBanner('18.0.0')).toContain(
`requires Node.js ${MIN_NODE_MAJOR} or newer`
);
});
it('points users to Node 22 LTS via nvm and Homebrew', () => {
const banner = buildNodeTooOldBanner('16.0.0');
expect(banner).toContain('Node.js 22 LTS');
expect(banner).toContain('nvm install 22');
expect(banner).toContain('brew install node@22');
});
it('documents the CODEGRAPH_ALLOW_UNSAFE_NODE override', () => {
expect(buildNodeTooOldBanner('18.0.0')).toContain('CODEGRAPH_ALLOW_UNSAFE_NODE=1');
});
});
+208
View File
@@ -0,0 +1,208 @@
/**
* npm thin-installer launcher (`scripts/npm-shim.js`) tests.
*
* The shim runs on the user's own Node, locates the per-platform optionalDependency
* bundle, and — when a registry mirror failed to deliver it (issue #303) — falls
* back to downloading the bundle from GitHub Releases. These tests exercise that
* shim as a real subprocess from a temp "main package" dir (its own package.json
* + node_modules), so resolution and version lookup behave hermetically.
*
* The download/checksum paths run against a local self-signed HTTPS server via
* CODEGRAPH_DOWNLOAD_BASE — no real network, no published release needed. The
* shim is launched with async `spawn` (not spawnSync), so the test's event loop
* stays free to serve those requests.
*
* POSIX only: the fake bundle launcher is a shell script and extraction uses the
* system `tar`. Skipped on Windows (where the shim's exec path differs anyway).
*/
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { spawn, execSync } from 'child_process';
import * as https from 'https';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import * as crypto from 'crypto';
import type { AddressInfo } from 'net';
const SHIM_SRC = path.join(__dirname, '..', 'scripts', 'npm-shim.js');
const target = `${process.platform}-${process.arch}`;
const asset = `codegraph-${target}.tar.gz`;
const isWindows = process.platform === 'win32';
function hasOpenssl(): boolean {
try { execSync('openssl version', { stdio: 'ignore' }); return true; } catch { return false; }
}
const CAN_NET = !isWindows && hasOpenssl();
function mkTmp(label: string): string {
return fs.mkdtempSync(path.join(os.tmpdir(), `cg-shim-${label}-`));
}
// A temp dir standing in for the installed @colbymchenry/codegraph main package.
function makePkg(version = '9.9.9-test'): string {
const dir = mkTmp('pkg');
fs.copyFileSync(SHIM_SRC, path.join(dir, 'npm-shim.js'));
fs.writeFileSync(path.join(dir, 'package.json'),
JSON.stringify({ name: '@colbymchenry/codegraph', version }) + '\n');
return dir;
}
// A fake bundle launcher that prints a marker + its args, so we can prove the
// shim found and exec'd it (and passed args through).
function writeLauncher(binDir: string): void {
fs.mkdirSync(binDir, { recursive: true });
const p = path.join(binDir, 'codegraph');
fs.writeFileSync(p, '#!/bin/sh\necho "FAKE_BUNDLE_RAN args:$*"\n');
fs.chmodSync(p, 0o755);
}
// Launch the shim with async spawn so the in-process HTTPS server can respond
// while it runs (spawnSync would block this event loop and deadlock).
function runShim(pkgDir: string, args: string[], env: Record<string, string>) {
return new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve) => {
const child = spawn(process.execPath, [path.join(pkgDir, 'npm-shim.js'), ...args], {
env: { ...process.env, ...env },
});
let stdout = '', stderr = '';
child.stdout.on('data', (d) => { stdout += d.toString(); });
child.stderr.on('data', (d) => { stderr += d.toString(); });
child.on('close', (status) => resolve({ status, stdout, stderr }));
});
}
describe.skipIf(isWindows)('npm-shim launcher', () => {
it('runs the installed optional-dependency bundle without any download', async () => {
const pkg = makePkg();
const platformPkg = path.join(pkg, 'node_modules', '@colbymchenry', `codegraph-${target}`);
writeLauncher(path.join(platformPkg, 'bin'));
fs.writeFileSync(path.join(platformPkg, 'package.json'),
JSON.stringify({ name: `@colbymchenry/codegraph-${target}`, version: '9.9.9-test' }) + '\n');
const cache = mkTmp('cache');
const r = await runShim(pkg, ['--probe-abc'], { CODEGRAPH_INSTALL_DIR: cache });
expect(r.status).toBe(0);
expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
expect(r.stdout).toContain('--probe-abc'); // args passed through
expect(r.stderr).not.toContain('downloading'); // never reached the fallback
expect(fs.existsSync(path.join(cache, 'bundles'))).toBe(false);
});
it('uses an already-cached bundle even when downloads are disabled', async () => {
const pkg = makePkg('1.2.3-cached');
const cache = mkTmp('cache');
writeLauncher(path.join(cache, 'bundles', `${target}-1.2.3-cached`, 'bin'));
const r = await runShim(pkg, ['--probe-xyz'], {
CODEGRAPH_INSTALL_DIR: cache,
CODEGRAPH_NO_DOWNLOAD: '1',
});
expect(r.status).toBe(0);
expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
expect(r.stdout).toContain('--probe-xyz');
expect(r.stderr).toBe('');
});
it('prints actionable guidance and exits 1 when disabled with no bundle', async () => {
const pkg = makePkg();
const r = await runShim(pkg, ['--version'], {
CODEGRAPH_INSTALL_DIR: mkTmp('cache'),
CODEGRAPH_NO_DOWNLOAD: '1',
});
expect(r.status).toBe(1);
expect(r.stderr).toContain(`no prebuilt bundle for ${target}`);
expect(r.stderr).toContain(`@colbymchenry/codegraph-${target}`);
expect(r.stderr).toContain('--registry=https://registry.npmjs.org');
expect(r.stderr).toContain('install.sh');
});
});
describe.skipIf(!CAN_NET)('npm-shim download fallback (local HTTPS)', () => {
let server: https.Server;
let port = 0;
let fixtureBytes: Buffer;
let fixtureSha: string;
let sumsBody: string | null = null; // per-test: SHA256SUMS contents, or null for 404
beforeAll(async () => {
// Self-signed cert for the mock release host.
const cdir = mkTmp('tls');
const keyP = path.join(cdir, 'key.pem');
const certP = path.join(cdir, 'cert.pem');
execSync(
`openssl req -x509 -newkey rsa:2048 -nodes -keyout ${keyP} -out ${certP} -days 1 -subj "/CN=localhost"`,
{ stdio: 'ignore' },
);
// Build a fake bundle archive (codegraph-<target>/bin/codegraph), like a real release asset.
const work = mkTmp('fixture');
writeLauncher(path.join(work, `codegraph-${target}`, 'bin'));
const archive = path.join(work, asset);
execSync(`tar -czf ${JSON.stringify(archive)} -C ${JSON.stringify(work)} codegraph-${target}`);
fixtureBytes = fs.readFileSync(archive);
fixtureSha = crypto.createHash('sha256').update(fixtureBytes).digest('hex');
server = https.createServer({ key: fs.readFileSync(keyP), cert: fs.readFileSync(certP) }, (req, res) => {
const url = req.url || '';
if (url.endsWith(`/${asset}`)) {
res.writeHead(200); res.end(fixtureBytes);
} else if (url.endsWith('/SHA256SUMS')) {
if (sumsBody === null) { res.writeHead(404); res.end('not found'); }
else { res.writeHead(200); res.end(sumsBody); }
} else {
res.writeHead(404); res.end('not found');
}
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
port = (server.address() as AddressInfo).port;
}, 30000);
afterAll(() => { server?.close(); });
function netEnv(cache: string): Record<string, string> {
return {
CODEGRAPH_INSTALL_DIR: cache,
CODEGRAPH_DOWNLOAD_BASE: `https://127.0.0.1:${port}`,
NODE_TLS_REJECT_UNAUTHORIZED: '0',
};
}
it('downloads, verifies the checksum, extracts, and execs the bundle', async () => {
sumsBody = `${fixtureSha} ${asset}\n`;
const pkg = makePkg('5.0.0-net');
const cache = mkTmp('cache');
const r = await runShim(pkg, ['--probe-net'], netEnv(cache));
expect(r.stderr).toContain('downloading');
expect(r.stderr).toContain('checksum verified');
expect(r.status).toBe(0);
expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
expect(r.stdout).toContain('--probe-net');
expect(fs.existsSync(path.join(cache, 'bundles', `${target}-5.0.0-net`, 'bin', 'codegraph'))).toBe(true);
}, 20000);
it('aborts (exit 1) on a checksum mismatch and caches nothing', async () => {
sumsBody = `${'0'.repeat(64)} ${asset}\n`;
const pkg = makePkg('5.0.0-bad');
const cache = mkTmp('cache');
const r = await runShim(pkg, ['--version'], netEnv(cache));
expect(r.status).toBe(1);
expect(r.stderr).toContain('checksum mismatch');
expect(r.stdout).not.toContain('FAKE_BUNDLE_RAN'); // never exec'd a tampered bundle
expect(fs.existsSync(path.join(cache, 'bundles', `${target}-5.0.0-bad`))).toBe(false);
}, 20000);
it('proceeds when no SHA256SUMS is published (older releases)', async () => {
sumsBody = null; // 404
const pkg = makePkg('5.0.0-nosums');
const cache = mkTmp('cache');
const r = await runShim(pkg, ['--version'], netEnv(cache));
expect(r.status).toBe(0);
expect(r.stderr).toContain('downloading');
expect(r.stderr).not.toContain('checksum verified'); // skipped, not failed
expect(r.stdout).toContain('FAKE_BUNDLE_RAN');
}, 20000);
});
+719
View File
@@ -0,0 +1,719 @@
/**
* PR #19 Improvement Tests
*
* Tests for changes ported from PR #15 and #16:
* - Lazy grammar loading
* - Arrow function extraction (body traversal)
* - Graph traversal 'both' direction fix
* - Best-candidate resolution picking
* - Schema v2 migration (filePath/language on unresolved_refs)
* - Batch insert for unresolved refs
* - SQLite performance pragmas
* - MCP symbol disambiguation and output truncation
* - CLI uninit command
*/
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { extractFromSource } from '../src/extraction';
import {
getParser,
isLanguageSupported,
getSupportedLanguages,
clearParserCache,
getUnavailableGrammarErrors,
initGrammars,
loadAllGrammars,
} from '../src/extraction/grammars';
beforeAll(async () => {
await initGrammars();
await loadAllGrammars();
});
// Create a temporary directory for each test
function createTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-pr19-test-'));
}
// Clean up temporary directory
function cleanupTempDir(dir: string): void {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
// Check if the node:sqlite backend is available (Node >= 22.5)
function hasSqliteBindings(): boolean {
try {
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(':memory:');
db.close();
return true;
} catch {
return false;
}
}
const HAS_SQLITE = hasSqliteBindings();
// =============================================================================
// Lazy Grammar Loading
// =============================================================================
describe('Lazy Grammar Loading', () => {
afterEach(() => {
clearParserCache();
});
it('should load grammars lazily on first use', () => {
// Clear cache to force fresh load
clearParserCache();
// TypeScript should be loadable
const parser = getParser('typescript');
expect(parser).not.toBeNull();
});
it('should cache loaded grammars', () => {
clearParserCache();
const parser1 = getParser('typescript');
const parser2 = getParser('typescript');
// Same reference from cache
expect(parser1).toBe(parser2);
});
it('should return null for unknown language', () => {
const parser = getParser('unknown');
expect(parser).toBeNull();
});
it('should handle unavailable grammars gracefully', () => {
// 'unknown' is not a valid grammar, should not crash
expect(isLanguageSupported('unknown')).toBe(false);
});
it('should report liquid as supported (custom extractor)', () => {
expect(isLanguageSupported('liquid')).toBe(true);
});
it('should include liquid in supported languages', () => {
const supported = getSupportedLanguages();
expect(supported).toContain('liquid');
});
it('should return unavailable grammar errors as a record', () => {
clearParserCache();
const errors = getUnavailableGrammarErrors();
// Should be a plain object (may or may not have entries depending on platform)
expect(typeof errors).toBe('object');
});
it('should support multiple languages independently', () => {
clearParserCache();
// Load two different languages - one failing shouldn't affect the other
const tsParser = getParser('typescript');
const pyParser = getParser('python');
expect(tsParser).not.toBeNull();
expect(pyParser).not.toBeNull();
expect(tsParser).not.toBe(pyParser);
});
it('should clear all caches on clearParserCache', () => {
// Load a grammar
getParser('typescript');
// Clear
clearParserCache();
// Errors should be cleared too
const errors = getUnavailableGrammarErrors();
expect(Object.keys(errors)).toHaveLength(0);
});
});
// =============================================================================
// Arrow Function Extraction - Body Traversal
// =============================================================================
describe('Arrow Function Body Traversal', () => {
it('should extract unresolved references from arrow function bodies', () => {
const code = `
export const useAuth = () => {
const user = getUser();
const token = generateToken(user);
return { user, token };
};
`;
const result = extractFromSource('hooks.ts', code);
// The arrow function should be extracted
const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'useAuth');
expect(funcNode).toBeDefined();
// Calls inside the body should be captured as unresolved references
const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
const callNames = calls.map((c) => c.referenceName);
expect(callNames).toContain('getUser');
expect(callNames).toContain('generateToken');
});
it('should extract unresolved references from function expression bodies', () => {
const code = `
export const processData = function(input: string): string {
const cleaned = sanitize(input);
return transform(cleaned);
};
`;
const result = extractFromSource('utils.ts', code);
const funcNode = result.nodes.find((n) => n.kind === 'function' && n.name === 'processData');
expect(funcNode).toBeDefined();
const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
const callNames = calls.map((c) => c.referenceName);
expect(callNames).toContain('sanitize');
expect(callNames).toContain('transform');
});
it('should not create duplicate nodes for arrow functions', () => {
const code = `
export const handler = () => {
doSomething();
};
`;
const result = extractFromSource('handler.ts', code);
// Should be exactly 1 function node, 0 variable nodes for 'handler'
const funcNodes = result.nodes.filter((n) => n.name === 'handler' && n.kind === 'function');
const varNodes = result.nodes.filter((n) => n.name === 'handler' && n.kind === 'variable');
expect(funcNodes).toHaveLength(1);
expect(varNodes).toHaveLength(0);
});
it('should extract nested calls in arrow functions in JavaScript', () => {
const code = `
export const fetchData = async () => {
const response = await fetchAPI('/data');
return parseResponse(response);
};
`;
const result = extractFromSource('api.js', code);
const funcNode = result.nodes.find((n) => n.name === 'fetchData');
expect(funcNode).toBeDefined();
expect(funcNode?.kind).toBe('function');
const calls = result.unresolvedReferences.filter((r) => r.referenceKind === 'calls');
const callNames = calls.map((c) => c.referenceName);
expect(callNames).toContain('fetchAPI');
expect(callNames).toContain('parseResponse');
});
});
// =============================================================================
// Graph Traversal 'both' Direction Fix
// (requires better-sqlite3 - will use CodeGraph integration)
// =============================================================================
describe('Graph Traversal Both Direction', () => {
let testDir: string;
beforeEach(() => {
testDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(testDir);
});
it.skipIf(!HAS_SQLITE)('should traverse both directions from a node', async () => {
const CodeGraph = (await import('../src/index')).default;
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
// A -> B -> C (A calls B, B calls C)
fs.writeFileSync(path.join(srcDir, 'a.ts'), `
import { funcB } from './b';
export function funcA(): void { funcB(); }
`);
fs.writeFileSync(path.join(srcDir, 'b.ts'), `
import { funcC } from './c';
export function funcB(): void { funcC(); }
`);
fs.writeFileSync(path.join(srcDir, 'c.ts'), `
export function funcC(): void { console.log('c'); }
`);
const cg = CodeGraph.initSync(testDir, {
config: { include: ['src/**/*.ts'], exclude: [] },
});
await cg.indexAll();
cg.resolveReferences();
const functions = cg.getNodesByKind('function');
const funcB = functions.find((n) => n.name === 'funcB');
if (!funcB) {
cg.destroy();
return;
}
// Traverse 'both' from B - should find A (incoming caller) and C (outgoing callee)
const subgraph = cg.traverse(funcB.id, {
maxDepth: 1,
direction: 'both',
});
// B itself + at least one neighbor in each direction
expect(subgraph.nodes.size).toBeGreaterThanOrEqual(2);
expect(subgraph.nodes.has(funcB.id)).toBe(true);
cg.destroy();
});
});
// =============================================================================
// Best-Candidate Resolution
// =============================================================================
describe('Best-Candidate Resolution', () => {
it.skipIf(!HAS_SQLITE)('should be testable via the resolution module types', async () => {
const { ReferenceResolver } = await import('../src/resolution');
expect(typeof ReferenceResolver.prototype.resolveOne).toBe('function');
});
});
// =============================================================================
// Schema v2 Migration
// =============================================================================
describe('Schema v2 Migration', () => {
it.skipIf(!HAS_SQLITE)('should have correct current schema version', async () => {
const { CURRENT_SCHEMA_VERSION } = await import('../src/db/migrations');
expect(CURRENT_SCHEMA_VERSION).toBe(4);
});
it.skipIf(!HAS_SQLITE)('should have migration for version 2', async () => {
const { getPendingMigrations } = await import('../src/db/migrations');
expect(typeof getPendingMigrations).toBe('function');
});
});
// =============================================================================
// Database Layer: Batch Insert, getAllNodes, Pragmas
// =============================================================================
describe('Database Layer Improvements', () => {
let testDir: string;
beforeEach(() => {
testDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(testDir);
});
it.skipIf(!HAS_SQLITE)('should support batch insert of unresolved refs', async () => {
const { DatabaseConnection } = await import('../src/db');
const { QueryBuilder } = await import('../src/db/queries');
const dbPath = path.join(testDir, 'codegraph.db');
const db = DatabaseConnection.initialize(dbPath);
const queries = new QueryBuilder(db.getDb());
// Insert a node first (needed as foreign key)
queries.insertNode({
id: 'func:test:1',
kind: 'function',
name: 'testFunc',
qualifiedName: 'test::testFunc',
filePath: 'test.ts',
language: 'typescript',
startLine: 1,
endLine: 5,
startColumn: 0,
endColumn: 1,
updatedAt: Date.now(),
});
// Batch insert unresolved refs with filePath and language
queries.insertUnresolvedRefsBatch([
{
fromNodeId: 'func:test:1',
referenceName: 'helperA',
referenceKind: 'calls',
line: 2,
column: 4,
filePath: 'test.ts',
language: 'typescript',
},
{
fromNodeId: 'func:test:1',
referenceName: 'helperB',
referenceKind: 'calls',
line: 3,
column: 4,
filePath: 'test.ts',
language: 'typescript',
},
]);
const refs = queries.getUnresolvedReferences();
expect(refs).toHaveLength(2);
expect(refs.map((r) => r.referenceName).sort()).toEqual(['helperA', 'helperB']);
// Verify filePath and language are persisted
expect(refs[0]?.filePath).toBe('test.ts');
expect(refs[0]?.language).toBe('typescript');
db.close();
});
it.skipIf(!HAS_SQLITE)('should support getAllNodes', async () => {
const { DatabaseConnection } = await import('../src/db');
const { QueryBuilder } = await import('../src/db/queries');
const dbPath = path.join(testDir, 'codegraph.db');
const db = DatabaseConnection.initialize(dbPath);
const queries = new QueryBuilder(db.getDb());
// Insert some nodes
for (let i = 0; i < 3; i++) {
queries.insertNode({
id: `func:test:${i}`,
kind: 'function',
name: `func${i}`,
qualifiedName: `test::func${i}`,
filePath: 'test.ts',
language: 'typescript',
startLine: i * 10 + 1,
endLine: i * 10 + 5,
startColumn: 0,
endColumn: 1,
updatedAt: Date.now(),
});
}
const allNodes = queries.getAllNodes();
expect(allNodes).toHaveLength(3);
expect(allNodes.map((n) => n.name).sort()).toEqual(['func0', 'func1', 'func2']);
db.close();
});
it.skipIf(!HAS_SQLITE)('should set performance pragmas on initialization', async () => {
const { DatabaseConnection } = await import('../src/db');
const dbPath = path.join(testDir, 'codegraph.db');
const db = DatabaseConnection.initialize(dbPath);
const rawDb = db.getDb();
// Check pragmas were set
const synchronous = rawDb.pragma('synchronous', { simple: true });
expect(synchronous).toBe(1); // NORMAL = 1
const cacheSize = rawDb.pragma('cache_size', { simple: true }) as number;
expect(cacheSize).toBe(-64000);
const tempStore = rawDb.pragma('temp_store', { simple: true });
expect(tempStore).toBe(2); // MEMORY = 2
const mmapSize = rawDb.pragma('mmap_size', { simple: true }) as number;
expect(mmapSize).toBe(268435456); // 256 MB
db.close();
});
it.skipIf(!HAS_SQLITE)('should handle empty batch insert gracefully', async () => {
const { DatabaseConnection } = await import('../src/db');
const { QueryBuilder } = await import('../src/db/queries');
const dbPath = path.join(testDir, 'codegraph.db');
const db = DatabaseConnection.initialize(dbPath);
const queries = new QueryBuilder(db.getDb());
// Should not throw on empty array
expect(() => queries.insertUnresolvedRefsBatch([])).not.toThrow();
db.close();
});
});
// =============================================================================
// Resolution Warm Caches
// =============================================================================
describe('Resolution Warm Caches', () => {
let testDir: string;
beforeEach(() => {
testDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(testDir);
});
it.skipIf(!HAS_SQLITE)('should warm caches and use them for lookups', async () => {
const CodeGraph = (await import('../src/index')).default;
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(path.join(srcDir, 'a.ts'), `
export function myFunc(): void {}
export function otherFunc(): void { myFunc(); }
`);
const cg = CodeGraph.initSync(testDir, {
config: { include: ['src/**/*.ts'], exclude: [] },
});
await cg.indexAll();
// resolveReferences internally calls warmCaches
const result = cg.resolveReferences();
// Should complete without error
expect(result.stats.total).toBeGreaterThanOrEqual(0);
cg.destroy();
});
});
// =============================================================================
// MCP Tool Improvements
// =============================================================================
describe('MCP Tool Improvements', () => {
it.skipIf(!HAS_SQLITE)('should export ToolHandler class', async () => {
const { ToolHandler } = await import('../src/mcp/tools');
expect(typeof ToolHandler).toBe('function');
});
it.skipIf(!HAS_SQLITE)('should have findSymbol and truncateOutput as private methods', async () => {
const { ToolHandler } = await import('../src/mcp/tools');
const proto = ToolHandler.prototype;
expect(typeof (proto as any).findSymbol).toBe('function');
expect(typeof (proto as any).truncateOutput).toBe('function');
});
it.skipIf(!HAS_SQLITE)('should truncate output exceeding MAX_OUTPUT_LENGTH', async () => {
const { ToolHandler } = await import('../src/mcp/tools');
// Access private method for testing
const handler = Object.create(ToolHandler.prototype);
const truncate = (handler as any).truncateOutput.bind(handler);
// Short text should not be truncated
const short = 'Hello world';
expect(truncate(short)).toBe(short);
// Long text should be truncated
const long = 'x'.repeat(20000);
const result = truncate(long);
expect(result.length).toBeLessThan(long.length);
expect(result).toContain('... (output truncated)');
});
it.skipIf(!HAS_SQLITE)('should truncate at a clean line boundary', async () => {
const { ToolHandler } = await import('../src/mcp/tools');
const handler = Object.create(ToolHandler.prototype);
const truncate = (handler as any).truncateOutput.bind(handler);
// Build text with newlines exceeding the limit
const lines: string[] = [];
for (let i = 0; i < 500; i++) {
lines.push(`Line ${i}: ${'a'.repeat(50)}`);
}
const text = lines.join('\n');
const result = truncate(text);
// Should end with truncation notice after a newline boundary
expect(result).toContain('... (output truncated)');
// Should not cut mid-line (the char before truncation notice should be \n)
const beforeTruncation = result.split('\n\n... (output truncated)')[0]!;
expect(beforeTruncation.endsWith('\n') || !beforeTruncation.includes('\0')).toBe(true);
});
describe('findSymbol disambiguation', () => {
it.skipIf(!HAS_SQLITE)('should prefer exact name matches', async () => {
const { ToolHandler } = await import('../src/mcp/tools');
const CodeGraph = (await import('../src/index')).default;
const tmpDir = createTempDir();
const srcDir = path.join(tmpDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(path.join(srcDir, 'a.ts'), `
export function getValue(): number { return 1; }
export function getValueFromCache(): number { return 2; }
`);
const cg = CodeGraph.initSync(tmpDir, {
config: { include: ['src/**/*.ts'], exclude: [] },
});
await cg.indexAll();
const handler = new ToolHandler(cg);
const findSymbol = (handler as any).findSymbol.bind(handler);
const match = findSymbol(cg, 'getValue');
expect(match).not.toBeNull();
expect(match.node.name).toBe('getValue');
// Should not have a disambiguation note for single exact match
expect(match.note).toBe('');
handler.closeAll();
cg.destroy();
cleanupTempDir(tmpDir);
});
it.skipIf(!HAS_SQLITE)('should note when multiple symbols share the same name', async () => {
const { ToolHandler } = await import('../src/mcp/tools');
const CodeGraph = (await import('../src/index')).default;
const tmpDir = createTempDir();
const srcDir = path.join(tmpDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
// Two files with the same function name
fs.writeFileSync(path.join(srcDir, 'a.ts'), `
export function handle(): void {}
`);
fs.writeFileSync(path.join(srcDir, 'b.ts'), `
export function handle(): void {}
`);
const cg = CodeGraph.initSync(tmpDir, {
config: { include: ['src/**/*.ts'], exclude: [] },
});
await cg.indexAll();
const handler = new ToolHandler(cg);
const findSymbol = (handler as any).findSymbol.bind(handler);
const match = findSymbol(cg, 'handle');
expect(match).not.toBeNull();
expect(match.node.name).toBe('handle');
// Should have a disambiguation note
expect(match.note).toContain('2 symbols named "handle"');
handler.closeAll();
cg.destroy();
cleanupTempDir(tmpDir);
});
it.skipIf(!HAS_SQLITE)('should return null when symbol is not found', async () => {
const { ToolHandler } = await import('../src/mcp/tools');
const CodeGraph = (await import('../src/index')).default;
const tmpDir = createTempDir();
const srcDir = path.join(tmpDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(path.join(srcDir, 'a.ts'), `export function foo(): void {}`);
const cg = CodeGraph.initSync(tmpDir, {
config: { include: ['src/**/*.ts'], exclude: [] },
});
await cg.indexAll();
const handler = new ToolHandler(cg);
const findSymbol = (handler as any).findSymbol.bind(handler);
const match = findSymbol(cg, 'nonExistentSymbol');
expect(match).toBeNull();
handler.closeAll();
cg.destroy();
cleanupTempDir(tmpDir);
});
});
});
// =============================================================================
// CLI uninit Command
// =============================================================================
describe('CLI uninit', () => {
let testDir: string;
beforeEach(() => {
testDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(testDir);
});
it.skipIf(!HAS_SQLITE)('should uninitialize a project via CodeGraph.uninitialize()', async () => {
const CodeGraph = (await import('../src/index')).default;
// Initialize
const cg = CodeGraph.initSync(testDir);
expect(CodeGraph.isInitialized(testDir)).toBe(true);
// Uninitialize
cg.uninitialize();
// .codegraph directory should be removed
expect(CodeGraph.isInitialized(testDir)).toBe(false);
});
});
// =============================================================================
// Tree-sitter Version Pinning
// =============================================================================
describe('Tree-sitter WASM Setup', () => {
it('should use web-tree-sitter and tree-sitter-wasms in dependencies', () => {
const pkgPath = path.join(__dirname, '..', 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
expect(pkg.dependencies['web-tree-sitter']).toBeDefined();
expect(pkg.dependencies['tree-sitter-wasms']).toBeDefined();
});
it('should not have native tree-sitter in dependencies', () => {
const pkgPath = path.join(__dirname, '..', 'package.json');
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
expect(pkg.dependencies['tree-sitter']).toBeUndefined();
expect(pkg.overrides).toBeUndefined();
});
});
// =============================================================================
// Embedder Float32Array Fix
// =============================================================================
describe('Float32Array Fix', () => {
it('should correctly convert typed arrays (regression check)', () => {
// Simulates the fix: Float32Array.from(Array.from(arr)) vs new Float32Array(arr.length)
const source = new Float64Array([1.5, 2.5, 3.5, 4.5]);
// The OLD buggy approach:
const buggy = new Float32Array(source.length);
// buggy is all zeros!
expect(buggy[0]).toBe(0);
expect(buggy[1]).toBe(0);
// The NEW fixed approach:
const fixed = Float32Array.from(Array.from(source));
expect(fixed[0]).toBeCloseTo(1.5);
expect(fixed[1]).toBeCloseTo(2.5);
expect(fixed[2]).toBeCloseTo(3.5);
expect(fixed[3]).toBeCloseTo(4.5);
});
});
+849
View File
@@ -0,0 +1,849 @@
/**
* Resolution Module Tests
*
* Tests for Phase 3: Reference Resolution
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { CodeGraph } from '../src';
import { Node, UnresolvedReference } from '../src/types';
import { ReferenceResolver, createResolver, ResolutionContext } from '../src/resolution';
import { matchReference } from '../src/resolution/name-matcher';
import { resolveImportPath, extractImportMappings } from '../src/resolution/import-resolver';
import { detectFrameworks, getAllFrameworkResolvers } from '../src/resolution/frameworks';
import { QueryBuilder } from '../src/db/queries';
import { DatabaseConnection } from '../src/db';
describe('Resolution Module', () => {
let tempDir: string;
let cg: CodeGraph;
beforeEach(() => {
// Create temp directory
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-resolution-test-'));
});
afterEach(() => {
// Clean up
if (cg) {
cg.destroy();
} else if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true });
}
});
describe('Name Matcher', () => {
it('should match exact name references', () => {
// Create a mock context
const mockNodes: Node[] = [
{
id: 'func:test.ts:myFunction:10',
kind: 'function',
name: 'myFunction',
qualifiedName: 'test.ts::myFunction',
filePath: 'test.ts',
language: 'typescript',
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
];
const context: ResolutionContext = {
getNodesInFile: () => mockNodes,
getNodesByName: (name) => mockNodes.filter((n) => n.name === name),
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => ['test.ts'],
};
const ref = {
fromNodeId: 'caller:main.ts:caller:5',
referenceName: 'myFunction',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'main.ts',
language: 'typescript' as const,
};
const result = matchReference(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('func:test.ts:myFunction:10');
expect(result?.resolvedBy).toBe('exact-match');
});
it('should prefer same-module candidates over cross-module matches', () => {
// Simulates a Python monorepo where multiple apps define navigate()
const candidateA: Node = {
id: 'func:apps/app_a/src/server.py:navigate:10',
kind: 'function',
name: 'navigate',
qualifiedName: 'apps/app_a/src/server.py::navigate',
filePath: 'apps/app_a/src/server.py',
language: 'python',
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
const candidateB: Node = {
id: 'func:apps/app_b/src/server.py:navigate:15',
kind: 'function',
name: 'navigate',
qualifiedName: 'apps/app_b/src/server.py::navigate',
filePath: 'apps/app_b/src/server.py',
language: 'python',
startLine: 15,
endLine: 25,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: (name) => name === 'navigate' ? [candidateA, candidateB] : [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => [],
getNodesByLowerName: () => [],
getImportMappings: () => [],
};
// Reference from app_a should resolve to app_a's navigate, not app_b's
const ref = {
fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
referenceName: 'navigate',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'apps/app_a/src/handler.py',
language: 'python' as const,
};
const result = matchReference(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('func:apps/app_a/src/server.py:navigate:10');
expect(result?.resolvedBy).toBe('exact-match');
});
it('should lower confidence for cross-module exact matches', () => {
// Only one candidate but in a completely different module
const candidates: Node[] = [
{
id: 'func:apps/app_b/src/server.py:navigate:10',
kind: 'function',
name: 'navigate',
qualifiedName: 'apps/app_b/src/server.py::navigate',
filePath: 'apps/app_b/src/server.py',
language: 'python',
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
{
id: 'func:apps/app_c/src/server.py:navigate:10',
kind: 'function',
name: 'navigate',
qualifiedName: 'apps/app_c/src/server.py::navigate',
filePath: 'apps/app_c/src/server.py',
language: 'python',
startLine: 10,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
];
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: (name) => name === 'navigate' ? candidates : [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => [],
getNodesByLowerName: () => [],
getImportMappings: () => [],
};
// Reference from app_a — neither candidate is in the same module
const ref = {
fromNodeId: 'func:apps/app_a/src/handler.py:handler:5',
referenceName: 'navigate',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'apps/app_a/src/handler.py',
language: 'python' as const,
};
const result = matchReference(ref, context);
// Should still resolve but with low confidence
expect(result).not.toBeNull();
expect(result?.confidence).toBeLessThanOrEqual(0.4);
});
it('should match qualified name references', () => {
const mockClassNode: Node = {
id: 'class:user.ts:User:5',
kind: 'class',
name: 'User',
qualifiedName: 'user.ts::User',
filePath: 'user.ts',
language: 'typescript',
startLine: 5,
endLine: 30,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
const mockMethodNode: Node = {
id: 'method:user.ts:User.save:15',
kind: 'method',
name: 'save',
qualifiedName: 'user.ts::User::save',
filePath: 'user.ts',
language: 'typescript',
startLine: 15,
endLine: 25,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
};
const context: ResolutionContext = {
getNodesInFile: (fp) => fp === 'user.ts' ? [mockClassNode, mockMethodNode] : [],
getNodesByName: (name) => {
if (name === 'User') return [mockClassNode];
if (name === 'save') return [mockMethodNode];
return [];
},
getNodesByQualifiedName: (qn) => {
if (qn === 'user.ts::User::save') return [mockMethodNode];
return [];
},
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => ['user.ts'],
};
const ref = {
fromNodeId: 'caller:main.ts:main:5',
referenceName: 'User.save',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'main.ts',
language: 'typescript' as const,
};
const result = matchReference(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('method:user.ts:User.save:15');
});
});
describe('Import Resolver', () => {
it('should resolve relative import paths', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: (p) => p === 'src/components/utils.ts' || p === 'src/components/utils/index.ts',
readFile: () => null,
getProjectRoot: () => '',
getAllFiles: () => ['src/components/utils.ts', 'src/components/utils/index.ts'],
};
const result = resolveImportPath(
'./utils',
'src/components/Button.ts',
'typescript',
context
);
expect(result).toBe('src/components/utils.ts');
});
it('should resolve parent directory imports', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: (p) => p === 'src/helpers.ts' || p === 'src/helpers/index.ts',
readFile: () => null,
getProjectRoot: () => '',
getAllFiles: () => ['src/helpers.ts', 'src/helpers/index.ts'],
};
const result = resolveImportPath(
'../helpers',
'src/components/Button.ts',
'typescript',
context
);
expect(result).toBe('src/helpers.ts');
});
it('should extract JS/TS import mappings', () => {
const content = `
import { foo } from './foo';
import bar from '../bar';
import * as utils from './utils';
import { baz, qux } from './baz';
`;
const mappings = extractImportMappings(
'src/index.ts',
content,
'typescript'
);
expect(mappings.length).toBeGreaterThan(0);
expect(mappings.some((m) => m.localName === 'foo')).toBe(true);
expect(mappings.some((m) => m.localName === 'bar')).toBe(true);
});
it('should extract Python import mappings', () => {
const content = `
from utils import helper
from .models import User
import os
from ..services import auth_service
`;
const mappings = extractImportMappings(
'src/main.py',
content,
'python'
);
expect(mappings.length).toBeGreaterThan(0);
expect(mappings.some((m) => m.localName === 'helper')).toBe(true);
expect(mappings.some((m) => m.localName === 'User')).toBe(true);
});
});
describe('Framework Detection', () => {
it('should detect React framework', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: (p) => {
if (p === 'package.json') {
return JSON.stringify({
dependencies: { react: '^18.0.0' },
});
}
return null;
},
getProjectRoot: () => '/test',
getAllFiles: () => ['package.json', 'src/App.tsx'],
};
const frameworks = detectFrameworks(context);
expect(frameworks.some((f) => f.name === 'react')).toBe(true);
});
it('should detect Express framework', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: (p) => {
if (p === 'package.json') {
return JSON.stringify({
dependencies: { express: '^4.18.0' },
});
}
return null;
},
getProjectRoot: () => '/test',
getAllFiles: () => ['package.json', 'src/app.js'],
};
const frameworks = detectFrameworks(context);
expect(frameworks.some((f) => f.name === 'express')).toBe(true);
});
it('should detect Laravel framework', () => {
const context: ResolutionContext = {
getNodesInFile: () => [],
getNodesByName: () => [],
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: (p) => p === 'artisan',
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => ['artisan', 'app/Http/Kernel.php'],
};
const frameworks = detectFrameworks(context);
expect(frameworks.some((f) => f.name === 'laravel')).toBe(true);
});
it('should return all framework resolvers', () => {
const resolvers = getAllFrameworkResolvers();
expect(resolvers.length).toBeGreaterThan(0);
expect(resolvers.some((r) => r.name === 'react')).toBe(true);
expect(resolvers.some((r) => r.name === 'express')).toBe(true);
expect(resolvers.some((r) => r.name === 'laravel')).toBe(true);
});
});
describe('React Framework Resolver', () => {
it('should resolve React component references', () => {
const mockNodes: Node[] = [
{
id: 'component:src/Button.tsx:Button:5',
kind: 'component',
name: 'Button',
qualifiedName: 'src/Button.tsx::Button',
filePath: 'src/Button.tsx',
language: 'tsx',
startLine: 5,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
];
const context: ResolutionContext = {
getNodesInFile: (fp) => (fp === 'src/Button.tsx' ? mockNodes : []),
getNodesByName: () => mockNodes,
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: (p) => {
if (p === 'package.json') {
return JSON.stringify({ dependencies: { react: '^18.0.0' } });
}
return null;
},
getProjectRoot: () => '/test',
getAllFiles: () => ['package.json', 'src/Button.tsx', 'src/App.tsx'],
};
const frameworks = detectFrameworks(context);
const reactResolver = frameworks.find((f) => f.name === 'react');
expect(reactResolver).toBeDefined();
const ref = {
fromNodeId: 'component:src/App.tsx:App:1',
referenceName: 'Button',
referenceKind: 'renders' as const,
line: 10,
column: 5,
filePath: 'src/App.tsx',
language: 'typescript' as const,
};
const result = reactResolver!.resolve(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('component:src/Button.tsx:Button:5');
});
it('should resolve custom hook references', () => {
const mockNodes: Node[] = [
{
id: 'hook:src/hooks/useAuth.ts:useAuth:1',
kind: 'function',
name: 'useAuth',
qualifiedName: 'src/hooks/useAuth.ts::useAuth',
filePath: 'src/hooks/useAuth.ts',
language: 'typescript',
startLine: 1,
endLine: 20,
startColumn: 0,
endColumn: 0,
updatedAt: Date.now(),
},
];
const context: ResolutionContext = {
getNodesInFile: (fp) => (fp.includes('useAuth') ? mockNodes : []),
getNodesByName: () => mockNodes,
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => false,
readFile: (p) => {
if (p === 'package.json') {
return JSON.stringify({ dependencies: { react: '^18.0.0' } });
}
return null;
},
getProjectRoot: () => '/test',
getAllFiles: () => ['package.json', 'src/hooks/useAuth.ts'],
};
const frameworks = detectFrameworks(context);
const reactResolver = frameworks.find((f) => f.name === 'react');
const ref = {
fromNodeId: 'component:src/App.tsx:App:1',
referenceName: 'useAuth',
referenceKind: 'calls' as const,
line: 5,
column: 10,
filePath: 'src/App.tsx',
language: 'typescript' as const,
};
const result = reactResolver!.resolve(ref, context);
expect(result).not.toBeNull();
expect(result?.targetNodeId).toBe('hook:src/hooks/useAuth.ts:useAuth:1');
});
});
describe('Integration Tests', () => {
it('should create resolver from CodeGraph instance', async () => {
// Create a simple TypeScript project
fs.writeFileSync(
path.join(tempDir, 'package.json'),
JSON.stringify({ name: 'test', dependencies: { react: '^18.0.0' } })
);
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir);
// Create utility file
fs.writeFileSync(
path.join(srcDir, 'utils.ts'),
`export function formatDate(date: Date): string {
return date.toISOString();
}
export function parseDate(str: string): Date {
return new Date(str);
}`
);
// Create main file that uses utils
fs.writeFileSync(
path.join(srcDir, 'main.ts'),
`import { formatDate, parseDate } from './utils';
function processDate(input: string): string {
const date = parseDate(input);
return formatDate(date);
}`
);
// Initialize and index
cg = await CodeGraph.init(tempDir, { index: true });
// Check that resolver detected React framework
const frameworks = cg.getDetectedFrameworks();
expect(frameworks).toContain('react');
// Get stats to verify indexing worked
const stats = cg.getStats();
expect(stats.fileCount).toBe(2);
expect(stats.nodeCount).toBeGreaterThan(0);
});
it('should resolve references after indexing', async () => {
// Create a project with references
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(
path.join(srcDir, 'helper.ts'),
`export function helperFunction(): void {
console.log('helper');
}`
);
fs.writeFileSync(
path.join(srcDir, 'main.ts'),
`import { helperFunction } from './helper';
function main(): void {
helperFunction();
}`
);
cg = await CodeGraph.init(tempDir, { index: true });
// Run reference resolution
const result = cg.resolveReferences();
// Should have attempted resolution
expect(result.stats.total).toBeGreaterThanOrEqual(0);
});
it('promotes calls→instantiates when target resolves to a class (Python)', async () => {
// Python has no `new` keyword — `Foo()` is the standard
// instantiation syntax. Extraction can't tell that apart from
// a function call without symbol info, so it emits a `calls`
// ref. Resolution promotes it to `instantiates` once the
// target is known to be a class.
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir, { recursive: true });
fs.writeFileSync(
path.join(srcDir, 'app.py'),
`class UserService:
def __init__(self):
self.db = None
def bootstrap():
return UserService()
`
);
cg = await CodeGraph.init(tempDir, { index: true });
cg.resolveReferences();
const bootstrap = cg
.getNodesByKind('function')
.find((n) => n.name === 'bootstrap');
expect(bootstrap).toBeDefined();
const outgoing = cg.getOutgoingEdges(bootstrap!.id);
const instantiates = outgoing.find((e) => e.kind === 'instantiates');
expect(instantiates).toBeDefined();
// Same edge must NOT also appear as a `calls` edge — promotion
// replaces the kind, doesn't duplicate.
const callsToUserService = outgoing.filter(
(e) => e.kind === 'calls' && e.target === instantiates!.target
);
expect(callsToUserService).toHaveLength(0);
});
});
describe('Name Matcher: kind bias for new ref kinds', () => {
const baseContext = (candidates: Node[]): ResolutionContext => ({
getNodesInFile: () => [],
getNodesByName: (name) => candidates.filter((c) => c.name === name),
getNodesByQualifiedName: () => [],
getNodesByKind: () => [],
fileExists: () => true,
readFile: () => null,
getProjectRoot: () => '/test',
getAllFiles: () => [],
getNodesByLowerName: () => [],
getImportMappings: () => [],
});
it('prefers a class candidate over a function for `instantiates` refs', () => {
// A class and a function share a name across the codebase.
// Without the kind bias, the function (which gets the +25 `calls`
// bonus historically applied to all candidates of that kind) would
// win. Now the instantiates branch reverses it.
const fn: Node = {
id: 'func:utils.ts:Logger:5', kind: 'function', name: 'Logger',
qualifiedName: 'utils.ts::Logger', filePath: 'utils.ts', language: 'typescript',
startLine: 5, endLine: 7, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
};
const cls: Node = {
id: 'class:logger.ts:Logger:10', kind: 'class', name: 'Logger',
qualifiedName: 'logger.ts::Logger', filePath: 'logger.ts', language: 'typescript',
startLine: 10, endLine: 30, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
};
const ref = {
fromNodeId: 'func:main.ts:bootstrap:1',
referenceName: 'Logger',
referenceKind: 'instantiates' as const,
line: 5, column: 0, filePath: 'main.ts', language: 'typescript' as const,
};
const result = matchReference(ref, baseContext([fn, cls]));
expect(result?.targetNodeId).toBe('class:logger.ts:Logger:10');
});
it('prefers a function candidate over a non-function for `decorates` refs', () => {
const variable: Node = {
id: 'var:config.ts:Inject:5', kind: 'variable', name: 'Inject',
qualifiedName: 'config.ts::Inject', filePath: 'config.ts', language: 'typescript',
startLine: 5, endLine: 5, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
};
const decorator: Node = {
id: 'func:di.ts:Inject:10', kind: 'function', name: 'Inject',
qualifiedName: 'di.ts::Inject', filePath: 'di.ts', language: 'typescript',
startLine: 10, endLine: 20, startColumn: 0, endColumn: 0, updatedAt: Date.now(),
};
const ref = {
fromNodeId: 'class:svc.ts:UserService:1',
referenceName: 'Inject',
referenceKind: 'decorates' as const,
line: 5, column: 0, filePath: 'svc.ts', language: 'typescript' as const,
};
const result = matchReference(ref, baseContext([variable, decorator]));
expect(result?.targetNodeId).toBe('func:di.ts:Inject:10');
});
});
describe('tsconfig path aliases', () => {
it('resolves an aliased import to the alias-mapped file (not a same-named file elsewhere)', async () => {
// Two same-named exports in different directories. Without alias
// resolution, name-matcher would pick whichever it finds first;
// with alias resolution, the import path uniquely picks one.
fs.mkdirSync(path.join(tempDir, 'src/utils'), { recursive: true });
fs.mkdirSync(path.join(tempDir, 'src/legacy'), { recursive: true });
fs.writeFileSync(
path.join(tempDir, 'src/utils/format.ts'),
`export function pickMe(): number { return 1; }\n`
);
fs.writeFileSync(
path.join(tempDir, 'src/legacy/format.ts'),
`export function pickMe(): number { return 99; }\n`
);
fs.writeFileSync(
path.join(tempDir, 'src/main.ts'),
`import { pickMe } from '@utils/format';\nexport function go(): number { return pickMe(); }\n`
);
fs.writeFileSync(
path.join(tempDir, 'tsconfig.json'),
JSON.stringify({
compilerOptions: {
baseUrl: './src',
paths: { '@utils/*': ['utils/*'] },
},
})
);
cg = await CodeGraph.init(tempDir, { index: true });
cg.resolveReferences();
// The two pickMe nodes live in different files. The aliased
// import should attach the call edge to the @utils-mapped one,
// not the legacy duplicate.
const all = cg.getNodesByKind('function').filter((n) => n.name === 'pickMe');
const utilsNode = all.find((n) => n.filePath === 'src/utils/format.ts');
const legacyNode = all.find((n) => n.filePath === 'src/legacy/format.ts');
expect(utilsNode).toBeDefined();
expect(legacyNode).toBeDefined();
const utilsCallers = cg.getCallers(utilsNode!.id);
const legacyCallers = cg.getCallers(legacyNode!.id);
expect(utilsCallers.length).toBeGreaterThan(0);
expect(utilsCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
// The legacy node should NOT have a caller from src/main.ts —
// the alias correctly picked the utils version.
expect(legacyCallers.some((c) => c.node.filePath === 'src/main.ts')).toBe(false);
});
it('falls back gracefully when tsconfig is absent', async () => {
fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
fs.writeFileSync(
path.join(tempDir, 'src/a.ts'),
`export function aFn(): void {}\n`
);
fs.writeFileSync(
path.join(tempDir, 'src/b.ts'),
`import { aFn } from './a';\nexport function bFn(): void { aFn(); }\n`
);
cg = await CodeGraph.init(tempDir, { index: true });
// No tsconfig present — index should still complete and the
// relative-import-based call edge should be created.
const aFn = cg.getNodesByKind('function').find((n) => n.name === 'aFn');
expect(aFn).toBeDefined();
const callers = cg.getCallers(aFn!.id);
expect(callers.some((c) => c.node.filePath === 'src/b.ts')).toBe(true);
});
});
describe('re-export chain following', () => {
it('chases a 3-hop barrel chain (wildcard → named → declaration)', async () => {
// main.ts → all.ts (wildcard) → index.ts (named) → auth.ts (declaration).
// Without chain following, `signIn` resolves to nothing because
// none of the barrel files declare it directly.
fs.mkdirSync(path.join(tempDir, 'src/services'), { recursive: true });
fs.writeFileSync(
path.join(tempDir, 'src/services/auth.ts'),
`export function signIn(): void {}\n`
);
fs.writeFileSync(
path.join(tempDir, 'src/services/index.ts'),
`export { signIn } from './auth';\n`
);
fs.writeFileSync(
path.join(tempDir, 'src/all.ts'),
`export * from './services/index';\n`
);
fs.writeFileSync(
path.join(tempDir, 'src/main.ts'),
`import { signIn } from './all';\nexport function go(): void { signIn(); }\n`
);
cg = await CodeGraph.init(tempDir, { index: true });
cg.resolveReferences();
const signInNode = cg
.getNodesByKind('function')
.find((n) => n.name === 'signIn' && n.filePath === 'src/services/auth.ts');
expect(signInNode).toBeDefined();
const callers = cg.getCallers(signInNode!.id);
expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
});
it('follows a renamed named re-export (export { foo as bar } from ...)', async () => {
// The chase has to look up `foo` in the upstream module even
// though the importer asked for `bar` — exercises the rename
// branch of findExportedSymbol.
fs.mkdirSync(path.join(tempDir, 'src'), { recursive: true });
fs.writeFileSync(
path.join(tempDir, 'src/auth.ts'),
`export function signIn(): void {}\n`
);
fs.writeFileSync(
path.join(tempDir, 'src/index.ts'),
`export { signIn as login } from './auth';\n`
);
fs.writeFileSync(
path.join(tempDir, 'src/main.ts'),
`import { login } from './index';\nexport function go(): void { login(); }\n`
);
cg = await CodeGraph.init(tempDir, { index: true });
cg.resolveReferences();
const signInNode = cg
.getNodesByKind('function')
.find((n) => n.name === 'signIn' && n.filePath === 'src/auth.ts');
expect(signInNode).toBeDefined();
const callers = cg.getCallers(signInNode!.id);
expect(callers.some((c) => c.node.filePath === 'src/main.ts')).toBe(true);
});
});
});
+142
View File
@@ -0,0 +1,142 @@
/**
* Unit tests for the field-qualified query parser and bounded
* edit distance — the two algorithms behind `kind:`/`lang:`/`path:`/
* `name:` filtering and the fuzzy typo fallback.
*/
import { describe, it, expect } from 'vitest';
import { parseQuery, boundedEditDistance } from '../src/search/query-parser';
describe('parseQuery', () => {
it('returns plain text for a query with no field prefixes', () => {
const r = parseQuery('authenticate user');
expect(r.text).toBe('authenticate user');
expect(r.kinds).toEqual([]);
expect(r.languages).toEqual([]);
expect(r.pathFilters).toEqual([]);
expect(r.nameFilters).toEqual([]);
});
it('extracts kind: filter and removes it from text', () => {
const r = parseQuery('kind:function auth');
expect(r.kinds).toEqual(['function']);
expect(r.text).toBe('auth');
});
it('extracts lang: and language: as the same filter family', () => {
const a = parseQuery('lang:typescript foo');
const b = parseQuery('language:typescript foo');
expect(a.languages).toEqual(['typescript']);
expect(b.languages).toEqual(['typescript']);
});
it('handles multiple kind: filters as an OR set', () => {
const r = parseQuery('kind:function kind:method auth');
expect(r.kinds.sort()).toEqual(['function', 'method']);
});
it('extracts path: and name: as substring filters (kept verbatim)', () => {
const r = parseQuery('path:src/api name:Handler');
expect(r.pathFilters).toEqual(['src/api']);
expect(r.nameFilters).toEqual(['Handler']);
});
it('preserves quoted spans as a single token (whitespace in path:)', () => {
const r = parseQuery('path:"my dir/file" foo');
expect(r.pathFilters).toEqual(['my dir/file']);
expect(r.text).toBe('foo');
});
it('passes URL-like tokens through to text (does not match http: as a field)', () => {
const r = parseQuery('http://example.com');
expect(r.text).toBe('http://example.com');
expect(r.kinds).toEqual([]);
});
it('passes empty-value tokens through as text (kind: → "kind:")', () => {
const r = parseQuery('kind: foo');
expect(r.kinds).toEqual([]);
// The trailing-colon token comes back as plain text
expect(r.text.includes('kind:')).toBe(true);
});
it('passes unknown field prefixes through as text (TODO: keeps the colon)', () => {
const r = parseQuery('TODO: needs review');
expect(r.text).toBe('TODO: needs review');
expect(r.kinds).toEqual([]);
});
it('rejects unknown values for kind: (passes the whole token to text)', () => {
const r = parseQuery('kind:invalid foo');
// Invalid kind value falls back to text
expect(r.kinds).toEqual([]);
expect(r.text).toContain('kind:invalid');
});
it('handles all-filters-no-text query', () => {
const r = parseQuery('kind:function lang:typescript');
expect(r.kinds).toEqual(['function']);
expect(r.languages).toEqual(['typescript']);
expect(r.text).toBe('');
});
it('survives empty input', () => {
const r = parseQuery('');
expect(r.text).toBe('');
expect(r.kinds).toEqual([]);
});
it('survives a very long input (no allocation explosion)', () => {
const huge = 'foo '.repeat(5000); // 20k chars
const r = parseQuery(huge);
expect(r.text.length).toBeGreaterThan(0);
});
});
describe('boundedEditDistance', () => {
it('returns 0 for identical strings', () => {
expect(boundedEditDistance('user', 'user', 2)).toBe(0);
});
it('returns 1 for a single substitution', () => {
expect(boundedEditDistance('user', 'usar', 2)).toBe(1);
});
it('returns 1 for a single insertion', () => {
expect(boundedEditDistance('user', 'users', 2)).toBe(1);
});
it('returns 1 for a single deletion', () => {
expect(boundedEditDistance('users', 'user', 2)).toBe(1);
});
it('returns 2 for a transposition (two edits in basic Levenshtein)', () => {
// 'aple' vs 'palp' would be 2; pick a clearer pair.
// 'foo' vs 'fou': substitution + insertion = 2 if different lengths.
expect(boundedEditDistance('confg', 'configX', 2)).toBe(2);
});
it('returns maxDist+1 when distance clearly exceeds budget', () => {
expect(boundedEditDistance('foo', 'completely-different', 2)).toBe(3);
});
it('respects length-difference shortcut', () => {
// |len(a) - len(b)| > maxDist must immediately be over budget
expect(boundedEditDistance('a', 'aaaaaaa', 2)).toBe(3);
});
it('handles empty inputs', () => {
expect(boundedEditDistance('', '', 2)).toBe(0);
expect(boundedEditDistance('a', '', 2)).toBe(1);
expect(boundedEditDistance('', 'abc', 2)).toBe(3);
});
it('is case-sensitive — caller must lowercase if case-insensitive match wanted', () => {
expect(boundedEditDistance('Foo', 'foo', 2)).toBe(1);
});
it('early-exits when row min exceeds budget (correctness, not just perf)', () => {
// 'aaaaa' vs 'bbbbb': distance is 5, well over budget 2
expect(boundedEditDistance('aaaaa', 'bbbbb', 2)).toBe(3);
});
});
+644
View File
@@ -0,0 +1,644 @@
/**
* Security Tests
*
* Tests for P0/P1 security fixes:
* - FileLock (cross-process locking)
* - Path traversal prevention
* - MCP input validation
* - Atomic writes
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { FileLock, validateProjectPath } from '../src/utils';
import CodeGraph from '../src/index';
import { ToolHandler, tools } from '../src/mcp/tools';
import { scanDirectory, isSourceFile } from '../src/extraction';
import { DatabaseConnection, getDatabasePath } from '../src/db';
import { QueryBuilder } from '../src/db/queries';
function createTempDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-security-test-'));
}
function cleanupTempDir(dir: string): void {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
}
describe('FileLock', () => {
let tempDir: string;
let lockPath: string;
beforeEach(() => {
tempDir = createTempDir();
lockPath = path.join(tempDir, 'test.lock');
});
afterEach(() => {
cleanupTempDir(tempDir);
});
it('should acquire and release a lock', () => {
const lock = new FileLock(lockPath);
lock.acquire();
expect(fs.existsSync(lockPath)).toBe(true);
const content = fs.readFileSync(lockPath, 'utf-8').trim();
expect(parseInt(content, 10)).toBe(process.pid);
lock.release();
expect(fs.existsSync(lockPath)).toBe(false);
});
it('should prevent double acquisition within same process', () => {
const lock1 = new FileLock(lockPath);
const lock2 = new FileLock(lockPath);
lock1.acquire();
// Second lock should fail because our PID is alive
expect(() => lock2.acquire()).toThrow(/locked by another process/);
lock1.release();
});
it('should detect and remove stale locks from dead processes', () => {
// Write a lock file with a PID that doesn't exist
// PID 99999999 is extremely unlikely to be a real process
fs.writeFileSync(lockPath, '99999999');
const lock = new FileLock(lockPath);
// Should succeed because the PID is dead
expect(() => lock.acquire()).not.toThrow();
lock.release();
});
it('should execute function with withLock', () => {
const lock = new FileLock(lockPath);
const result = lock.withLock(() => {
expect(fs.existsSync(lockPath)).toBe(true);
return 42;
});
expect(result).toBe(42);
expect(fs.existsSync(lockPath)).toBe(false);
});
it('should release lock even if function throws', () => {
const lock = new FileLock(lockPath);
expect(() => {
lock.withLock(() => {
throw new Error('test error');
});
}).toThrow('test error');
expect(fs.existsSync(lockPath)).toBe(false);
});
it('should execute async function with withLockAsync', async () => {
const lock = new FileLock(lockPath);
const result = await lock.withLockAsync(async () => {
expect(fs.existsSync(lockPath)).toBe(true);
return 'async-result';
});
expect(result).toBe('async-result');
expect(fs.existsSync(lockPath)).toBe(false);
});
it('should release lock even if async function throws', async () => {
const lock = new FileLock(lockPath);
await expect(
lock.withLockAsync(async () => {
throw new Error('async error');
})
).rejects.toThrow('async error');
expect(fs.existsSync(lockPath)).toBe(false);
});
it('release should be idempotent', () => {
const lock = new FileLock(lockPath);
lock.acquire();
lock.release();
// Second release should not throw
expect(() => lock.release()).not.toThrow();
});
});
describe('Path Traversal Prevention', () => {
let testDir: string;
let cg: CodeGraph;
beforeEach(async () => {
testDir = createTempDir();
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir);
fs.writeFileSync(
path.join(srcDir, 'hello.ts'),
`export function hello(): string { return "hi"; }\n`
);
cg = CodeGraph.initSync(testDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
await cg.indexAll();
});
afterEach(() => {
if (cg) cg.close();
cleanupTempDir(testDir);
});
it('should read code for valid nodes within project', async () => {
const nodes = cg.getNodesByKind('function');
const hello = nodes.find((n) => n.name === 'hello');
expect(hello).toBeDefined();
const code = await cg.getCode(hello!.id);
expect(code).toContain('hello');
});
it('should return null for non-existent node', async () => {
const code = await cg.getCode('does-not-exist');
expect(code).toBeNull();
});
});
describe('validateProjectPath — sensitive directory blocking', () => {
// POSIX-only: on Windows '/etc' resolves to C:\etc (non-existent), not a
// sensitive dir — the Windows case is covered by the win32-gated test below.
it.runIf(process.platform !== 'win32')('blocks POSIX system directories (exact match)', () => {
expect(validateProjectPath('/')).toMatch(/sensitive system directory/i);
expect(validateProjectPath('/etc')).toMatch(/sensitive system directory/i);
});
it('allows a normal, existing directory', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-validate-'));
try {
expect(validateProjectPath(dir)).toBeNull();
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
// SENSITIVE_PATHS stores the Windows entries lowercase and validateProjectPath
// matches via resolved.toLowerCase(), so 'C:\\Windows' and 'c:\\windows' are
// both blocked. path.resolve is platform-specific, so this only runs on Windows.
it.runIf(process.platform === 'win32')(
'blocks Windows system directories regardless of case',
() => {
expect(validateProjectPath('C:\\Windows')).toMatch(/sensitive system directory/i);
expect(validateProjectPath('c:\\windows')).toMatch(/sensitive system directory/i);
expect(validateProjectPath('C:\\WINDOWS\\System32')).toMatch(/sensitive system directory/i);
}
);
});
describe('MCP Input Validation', () => {
let testDir: string;
let cg: CodeGraph;
let handler: ToolHandler;
beforeEach(async () => {
testDir = createTempDir();
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir);
fs.writeFileSync(
path.join(srcDir, 'example.ts'),
`export function exampleFunc(): void {}\nexport class ExampleClass {}\n`
);
cg = CodeGraph.initSync(testDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
await cg.indexAll();
handler = new ToolHandler(cg);
});
afterEach(() => {
if (cg) cg.close();
cleanupTempDir(testDir);
});
it('should reject non-string query in codegraph_search', async () => {
const result = await handler.execute('codegraph_search', { query: null });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('non-empty string');
});
it('should reject empty string query in codegraph_search', async () => {
const result = await handler.execute('codegraph_search', { query: '' });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('non-empty string');
});
it('should accept valid query in codegraph_search', async () => {
const result = await handler.execute('codegraph_search', { query: 'example' });
expect(result.isError).toBeFalsy();
});
it('should clamp limit to valid range in codegraph_search', async () => {
// Extremely large limit should still work (clamped to 100)
const result = await handler.execute('codegraph_search', { query: 'example', limit: 999999 });
expect(result.isError).toBeFalsy();
});
it('should reject non-string symbol in codegraph_callers', async () => {
const result = await handler.execute('codegraph_callers', { symbol: 123 });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('non-empty string');
});
it('should reject non-string task in codegraph_context', async () => {
const result = await handler.execute('codegraph_context', { task: undefined });
expect(result.isError).toBe(true);
expect(result.content[0].text).toContain('non-empty string');
});
it('should truncate oversized codegraph_context output', async () => {
const oversizedContext = Array.from({ length: 400 }, (_, i) => `line-${i} ${'x'.repeat(80)}`).join('\n');
const fakeCg = {
buildContext: async () => oversizedContext,
};
const fakeHandler = new ToolHandler(fakeCg as unknown as CodeGraph);
const result = await fakeHandler.execute('codegraph_context', { task: 'find example' });
expect(result.isError).toBeFalsy();
expect(result.content[0].text.length).toBeLessThan(oversizedContext.length);
expect(result.content[0].text).toContain('... (output truncated)');
});
it('should reject non-string symbol in codegraph_impact', async () => {
const result = await handler.execute('codegraph_impact', { symbol: [] });
expect(result.isError).toBe(true);
});
it('should reject non-string symbol in codegraph_node', async () => {
const result = await handler.execute('codegraph_node', { symbol: false });
expect(result.isError).toBe(true);
});
it('should reject non-string symbol in codegraph_callees', async () => {
const result = await handler.execute('codegraph_callees', { symbol: {} });
expect(result.isError).toBe(true);
});
it('should handle NaN limit gracefully', async () => {
const result = await handler.execute('codegraph_search', { query: 'example', limit: 'abc' });
expect(result.isError).toBeFalsy();
});
it('should handle negative limit gracefully', async () => {
const result = await handler.execute('codegraph_search', { query: 'example', limit: -5 });
expect(result.isError).toBeFalsy();
});
// #230: getCodeGraph must reject a sensitive system directory passed as
// projectPath before opening it. The error surfaces through execute()'s
// catch as an isError result. /etc is sensitive on POSIX; C:\Windows on
// Windows (path.resolve is platform-specific, so each case is gated).
it.runIf(process.platform !== 'win32')(
'rejects a sensitive POSIX projectPath (/etc) via the MCP handler',
async () => {
const result = await handler.execute('codegraph_search', {
query: 'example',
projectPath: '/etc',
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toMatch(/sensitive system directory/i);
}
);
it.runIf(process.platform === 'win32')(
'rejects a sensitive Windows projectPath (C:\\Windows) via the MCP handler',
async () => {
const result = await handler.execute('codegraph_search', {
query: 'example',
projectPath: 'C:\\Windows',
});
expect(result.isError).toBe(true);
expect(result.content[0].text).toMatch(/sensitive system directory/i);
}
);
});
describe('Atomic Writes', () => {
let tempDir: string;
beforeEach(() => {
tempDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(tempDir);
});
it('should not leave temp files on success', () => {
// We test this indirectly through the config-writer module
// by checking that no .tmp files remain after writing
const configDir = path.join(tempDir, '.claude');
fs.mkdirSync(configDir, { recursive: true });
const testFile = path.join(configDir, 'test.json');
// Simulate what atomicWriteFileSync does
const tmpPath = testFile + '.tmp.' + process.pid;
fs.writeFileSync(tmpPath, '{"test": true}');
fs.renameSync(tmpPath, testFile);
expect(fs.existsSync(testFile)).toBe(true);
expect(fs.existsSync(tmpPath)).toBe(false);
const content = JSON.parse(fs.readFileSync(testFile, 'utf-8'));
expect(content.test).toBe(true);
});
});
describe('Source file detection (isSourceFile)', () => {
it('selects files by supported extension', () => {
expect(isSourceFile('src/index.ts')).toBe(true);
expect(isSourceFile('src/deep/nested/file.ts')).toBe(true);
expect(isSourceFile('src/component.tsx')).toBe(true);
expect(isSourceFile('lib/util.js')).toBe(true);
expect(isSourceFile('src/main.py')).toBe(true);
});
it('rejects unsupported extensions and extensionless files', () => {
expect(isSourceFile('src/component.css')).toBe(false);
expect(isSourceFile('README.md')).toBe(false);
expect(isSourceFile('Makefile')).toBe(false);
expect(isSourceFile('.gitignore')).toBe(false);
});
it('matches regardless of leading dot directories', () => {
expect(isSourceFile('.hidden/index.ts')).toBe(true);
});
});
describe('JSON.parse Error Boundaries in DB', () => {
let tempDir: string;
beforeEach(() => {
tempDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(tempDir);
});
it('should not crash when node has malformed JSON in decorators column', () => {
const dbPath = path.join(tempDir, 'test.db');
const db = DatabaseConnection.initialize(dbPath);
const queries = new QueryBuilder(db.getDb());
// Insert a node with malformed JSON in the decorators column
db.getDb().prepare(`
INSERT INTO nodes (id, kind, name, qualified_name, file_path, language, start_line, end_line, start_column, end_column, decorators, is_exported, is_async, is_static, is_abstract, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
'test-node-1', 'function', 'myFunc', 'myFunc', 'test.ts', 'typescript',
1, 5, 0, 0,
'{not valid json!!!}', // malformed decorators
0, 0, 0, 0, Date.now()
);
// Should not throw - should return node with undefined decorators
const node = queries.getNodeById('test-node-1');
expect(node).not.toBeNull();
expect(node!.name).toBe('myFunc');
expect(node!.decorators).toBeUndefined();
db.close();
});
it('should not crash when edge has malformed JSON in metadata column', () => {
const dbPath = path.join(tempDir, 'test.db');
const db = DatabaseConnection.initialize(dbPath);
const queries = new QueryBuilder(db.getDb());
// Insert two nodes first
const insertNode = db.getDb().prepare(`
INSERT INTO nodes (id, kind, name, qualified_name, file_path, language, start_line, end_line, start_column, end_column, is_exported, is_async, is_static, is_abstract, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
insertNode.run('node-a', 'function', 'funcA', 'funcA', 'a.ts', 'typescript', 1, 5, 0, 0, 0, 0, 0, 0, Date.now());
insertNode.run('node-b', 'function', 'funcB', 'funcB', 'b.ts', 'typescript', 1, 5, 0, 0, 0, 0, 0, 0, Date.now());
// Insert edge with malformed metadata
db.getDb().prepare(`
INSERT INTO edges (source, target, kind, metadata)
VALUES (?, ?, ?, ?)
`).run('node-a', 'node-b', 'calls', 'broken json {{{');
// Should not throw - should return edge with undefined metadata
const edges = queries.getOutgoingEdges('node-a');
expect(edges.length).toBe(1);
expect(edges[0].source).toBe('node-a');
expect(edges[0].target).toBe('node-b');
expect(edges[0].metadata).toBeUndefined();
db.close();
});
it('should not crash when file record has malformed JSON in errors column', () => {
const dbPath = path.join(tempDir, 'test.db');
const db = DatabaseConnection.initialize(dbPath);
const queries = new QueryBuilder(db.getDb());
// Insert a file with malformed errors JSON
db.getDb().prepare(`
INSERT INTO files (path, content_hash, language, size, modified_at, indexed_at, node_count, errors)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`).run('test.ts', 'abc123', 'typescript', 100, Date.now(), Date.now(), 5, 'not-an-array');
// Should not throw - should return file with undefined errors
const file = queries.getFileByPath('test.ts');
expect(file).not.toBeNull();
expect(file!.path).toBe('test.ts');
expect(file!.errors).toBeUndefined();
db.close();
});
});
describe('Symlink Cycle Detection', () => {
let tempDir: string;
beforeEach(() => {
tempDir = createTempDir();
});
afterEach(() => {
cleanupTempDir(tempDir);
});
it('should handle symlink cycle without infinite loop', () => {
// Create directory structure with a symlink cycle
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir);
fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;\n');
// Create a symlink from src/loop -> tempDir (parent directory)
try {
fs.symlinkSync(tempDir, path.join(srcDir, 'loop'), 'dir');
} catch {
// Skip test if symlinks not supported (e.g., Windows without admin)
return;
}
// This should complete without hanging
const files = scanDirectory(tempDir);
// Should find the real file but not loop infinitely
expect(files).toContain('src/index.ts');
// Should not find duplicates via the symlink path
const indexFiles = files.filter(f => f.endsWith('index.ts'));
expect(indexFiles.length).toBe(1);
});
it('should follow valid symlinks to directories', () => {
// Create source directory with a file
const realDir = path.join(tempDir, 'real');
fs.mkdirSync(realDir);
fs.writeFileSync(path.join(realDir, 'hello.ts'), 'export function hello() {}\n');
// Create a symlink to realDir
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir);
try {
fs.symlinkSync(realDir, path.join(srcDir, 'linked'), 'dir');
} catch {
return;
}
const files = scanDirectory(tempDir);
// Should find files from both the real dir and via the symlink
// But deduplicate since they resolve to the same real path
expect(files.some(f => f.includes('hello.ts'))).toBe(true);
});
it('should skip broken symlinks gracefully', () => {
const srcDir = path.join(tempDir, 'src');
fs.mkdirSync(srcDir);
fs.writeFileSync(path.join(srcDir, 'valid.ts'), 'export const y = 2;\n');
try {
fs.symlinkSync('/nonexistent/path', path.join(srcDir, 'broken'), 'dir');
} catch {
return;
}
// Should not throw
const files = scanDirectory(tempDir);
expect(files).toContain('src/valid.ts');
});
});
describe('Session marker symlink resistance', () => {
// The marker write lives in src/mcp/tools.ts behind handleContext. We exercise
// it end-to-end via ToolHandler.execute so the test exercises the same code
// path Claude Code drives. The session id is per-test so other parallel test
// runs can't collide with the marker file we plant a symlink at.
const SESSION_ID = `cg-test-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}`;
const crypto = require('crypto') as typeof import('crypto');
const hash = crypto.createHash('md5').update(SESSION_ID).digest('hex').slice(0, 16);
const markerPath = path.join(os.tmpdir(), `codegraph-consulted-${hash}`);
let projectDir: string;
let victimDir: string;
let victimFile: string;
beforeEach(async () => {
projectDir = createTempDir();
victimDir = createTempDir();
victimFile = path.join(victimDir, 'private.txt');
fs.writeFileSync(victimFile, 'SECRET-DO-NOT-OVERWRITE\n');
if (fs.existsSync(markerPath)) fs.unlinkSync(markerPath);
// A real .codegraph/ has to exist for handleContext to get past the
// "not initialized" guard — index a tiny fixture so the call reaches the
// marker write step rather than short-circuiting on missing project state.
fs.writeFileSync(path.join(projectDir, 'a.ts'), 'export const x = 1;\n');
const cg = await CodeGraph.init(projectDir);
await cg.indexAll();
cg.close();
});
afterEach(() => {
if (fs.existsSync(markerPath)) fs.unlinkSync(markerPath);
cleanupTempDir(projectDir);
cleanupTempDir(victimDir);
});
it('does not follow a pre-planted symlink at the marker path', async () => {
// Skip on platforms where the user can't create symlinks (Windows without
// dev mode + admin). The CWE-59 risk we're guarding against doesn't apply
// when symlinks aren't creatable, so the skip is correct, not a gap.
try {
fs.symlinkSync(victimFile, markerPath);
} catch {
return;
}
const cg = await CodeGraph.open(projectDir);
const handler = new ToolHandler(cg);
process.env.CLAUDE_SESSION_ID = SESSION_ID;
try {
await handler.execute('codegraph_context', { task: 'find x' });
} finally {
delete process.env.CLAUDE_SESSION_ID;
cg.close();
}
// The victim file's contents must be untouched — the old writeFileSync
// path would have followed the symlink and written an ISO timestamp here.
expect(fs.readFileSync(victimFile, 'utf8')).toBe('SECRET-DO-NOT-OVERWRITE\n');
// And the marker path itself must still be the symlink we planted —
// no fallback path that quietly unlinked + recreated it (which would
// also work, but is a behavior we don't want to silently rely on).
expect(fs.lstatSync(markerPath).isSymbolicLink()).toBe(true);
});
it('writes the marker file with 0o600 perms on a clean path', async () => {
// No symlink planted — happy path. Verifies the new openSync(mode: 0o600)
// call is what actually lands on disk (regression guard for the perm
// tightening that came with the O_NOFOLLOW fix).
const cg = await CodeGraph.open(projectDir);
const handler = new ToolHandler(cg);
process.env.CLAUDE_SESSION_ID = SESSION_ID;
try {
await handler.execute('codegraph_context', { task: 'find x' });
} finally {
delete process.env.CLAUDE_SESSION_ID;
cg.close();
}
expect(fs.existsSync(markerPath)).toBe(true);
// chmod's low 9 bits — strip the file-type bits for a clean compare.
// Windows can't enforce 0o600 in the POSIX sense; skip the assertion
// there since the underlying OS will normalize the mode anyway.
if (process.platform !== 'win32') {
const mode = fs.statSync(markerPath).mode & 0o777;
expect(mode).toBe(0o600);
}
});
});
+44
View File
@@ -0,0 +1,44 @@
/**
* SQLite backend reporting.
*
* node:sqlite (Node's built-in real SQLite) is the sole backend. Pin that
* DatabaseConnection / CodeGraph report it and come up in WAL.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { DatabaseConnection } from '../src/db';
import { CodeGraph } from '../src';
describe('DatabaseConnection — backend reporting', () => {
let dir: string;
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-backend-'));
});
afterEach(() => {
if (fs.existsSync(dir)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it('reports the node-sqlite backend in WAL for an initialized DB', () => {
const conn = DatabaseConnection.initialize(path.join(dir, 'test.db'));
expect(conn.getBackend()).toBe('node-sqlite');
expect(conn.getJournalMode()).toBe('wal');
conn.close();
});
it('CodeGraph.getBackend() delegates to the underlying DatabaseConnection', async () => {
fs.writeFileSync(path.join(dir, 'x.ts'), `export function x(): void {}\n`);
const cg = await CodeGraph.init(dir, { index: true });
try {
expect(cg.getBackend()).toBe('node-sqlite');
} finally {
cg.destroy();
}
});
});
+134
View File
@@ -0,0 +1,134 @@
import { describe, it, expect } from 'vitest';
import { stripCommentsForRegex } from '../src/resolution/strip-comments';
describe('stripCommentsForRegex', () => {
it('python: strips line comments', () => {
const src = "x = 1 # path('/fake/', View)\nreal = 2";
const out = stripCommentsForRegex(src, 'python');
expect(out).not.toMatch(/path\('\/fake\//);
expect(out).toMatch(/real = 2/);
});
it('python: strips triple-quoted docstrings', () => {
const src = `"""
path('/in-docstring/', View)
"""
real = 1
`;
const out = stripCommentsForRegex(src, 'python');
expect(out).not.toMatch(/in-docstring/);
expect(out).toMatch(/real = 1/);
});
it('python: keeps # inside strings', () => {
const src = `path('#/fragment/', View)\n`;
const out = stripCommentsForRegex(src, 'python');
expect(out).toContain("'#/fragment/'");
});
it('python: handles triple-single-quoted docstrings', () => {
const src = `'''\npath('/fake/')\n'''\nreal = 1\n`;
const out = stripCommentsForRegex(src, 'python');
expect(out).not.toMatch(/fake/);
expect(out).toMatch(/real = 1/);
});
it('typescript: strips //, /* */', () => {
const src =
"// app.get('/fake', x)\n/* app.get('/also-fake', y) */\napp.get('/real', z)";
const out = stripCommentsForRegex(src, 'typescript');
expect(out).not.toMatch(/fake/);
expect(out).toMatch(/'\/real'/);
});
it('typescript: keeps // inside strings', () => {
const src = `const url = "https://example.com/path";\n`;
const out = stripCommentsForRegex(src, 'typescript');
expect(out).toContain('https://example.com/path');
});
it('php: strips //, #, and /* */', () => {
const src =
"// Route::get('/a', X::class)\n# Route::get('/b', Y::class)\n/* Route::get('/c', Z::class) */\nReal::go();";
const out = stripCommentsForRegex(src, 'php');
expect(out).not.toMatch(/'\/a'/);
expect(out).not.toMatch(/'\/b'/);
expect(out).not.toMatch(/'\/c'/);
expect(out).toContain('Real::go();');
});
it('ruby: strips =begin/=end', () => {
const src =
"=begin\nget '/fake', to: 'x#y'\n=end\nget '/real', to: 'a#b'\n";
const out = stripCommentsForRegex(src, 'ruby');
expect(out).not.toMatch(/fake/);
expect(out).toMatch(/'\/real'/);
});
it('ruby: strips # comments', () => {
const src = "# get '/fake', to: 'x#y'\nget '/real', to: 'a#b'\n";
const out = stripCommentsForRegex(src, 'ruby');
expect(out).not.toMatch(/fake/);
expect(out).toMatch(/'\/real'/);
});
it('rust: handles nested block comments', () => {
const src =
'/* outer /* inner */ still in outer */ .route("/real", get(h))';
const out = stripCommentsForRegex(src, 'rust');
expect(out).not.toMatch(/inner/);
expect(out).toMatch(/\/real/);
});
it('go: keeps backtick raw strings intact, strips // comments', () => {
const src = '// r.GET("/fake", h)\nr.GET(`/real`, h2)\n';
const out = stripCommentsForRegex(src, 'go');
expect(out).not.toMatch(/fake/);
// backtick raw string contents preserved
expect(out).toMatch(/`\/real`/);
});
it('go: strips block comments containing route-shaped text', () => {
const src = '/* r.GET("/fake", h) */\nr.GET("/real", h2)\n';
const out = stripCommentsForRegex(src, 'go');
expect(out).not.toMatch(/fake/);
expect(out).toMatch(/"\/real"/);
});
it('java: strips // and /* */ comments', () => {
const src =
'// @GetMapping("/fake")\n/* @PostMapping("/also-fake") */\n@GetMapping("/real")\n';
const out = stripCommentsForRegex(src, 'java');
expect(out).not.toMatch(/fake/);
expect(out).toMatch(/"\/real"/);
});
it('csharp: strips // and /* */ comments', () => {
const src =
'// [HttpGet("/fake")]\n/* [HttpPost("/also-fake")] */\n[HttpGet("/real")]\n';
const out = stripCommentsForRegex(src, 'csharp');
expect(out).not.toMatch(/fake/);
expect(out).toMatch(/"\/real"/);
});
it('swift: strips // and /* */ comments', () => {
const src =
'// app.get("fake", use: x)\n/* app.get("also-fake", use: y) */\napp.get("real", use: z)\n';
const out = stripCommentsForRegex(src, 'swift');
expect(out).not.toMatch(/fake/);
expect(out).toMatch(/"real"/);
});
it('preserves line numbers (newlines retained)', () => {
const src = "line1\n# comment with path('/fake/')\nline3";
const out = stripCommentsForRegex(src, 'python');
expect(out.split('\n').length).toBe(3);
expect(out.split('\n')[2]).toBe('line3');
});
it('preserves overall length so source offsets stay valid', () => {
const src = "x = 1 # path('/fake/', View)\nreal = 2";
const out = stripCommentsForRegex(src, 'python');
expect(out.length).toBe(src.length);
});
});
+194
View File
@@ -0,0 +1,194 @@
/**
* Module-qualified symbol lookup (`stage_apply::run`, `Session.request`,
* `configurator/stage_apply`).
*
* Pinned because the lookup vocabulary is what makes codegraph useful
* in workspaces with same-named symbols across modules — Rust
* sub-pipelines, Python `__init__.py` packages, Java packages, etc.
* See #173 for the original report: a `run` function in
* `src/configurator/stage_apply.rs` was indexed but `stage_apply::run`
* returned "not found" because (a) FTS strips colons to nothing,
* leaving a useless query, and (b) `matchesSymbol` only understood
* `.`-style qualifiers.
*/
import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { initGrammars, loadAllGrammars } from '../src/extraction/grammars';
beforeAll(async () => {
await initGrammars();
await loadAllGrammars();
});
function hasSqliteBindings(): boolean {
try {
const { DatabaseSync } = require('node:sqlite');
const db = new DatabaseSync(':memory:');
db.close();
return true;
} catch {
return false;
}
}
const HAS_SQLITE = hasSqliteBindings();
function tmpRoot(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-symbol-lookup-'));
}
function rmTree(dir: string): void {
if (fs.existsSync(dir)) fs.rmSync(dir, { recursive: true, force: true });
}
async function buildRustWorkspace(): Promise<string> {
const root = tmpRoot();
const cfgDir = path.join(root, 'src', 'configurator');
fs.mkdirSync(cfgDir, { recursive: true });
fs.writeFileSync(
path.join(root, 'Cargo.toml'),
`[package]\nname = "fixture"\nversion = "0.1.0"\nedition = "2021"\n[lib]\npath = "src/lib.rs"\n`
);
fs.writeFileSync(path.join(root, 'src', 'lib.rs'), `pub mod configurator;\npub mod scheduler;\n`);
fs.writeFileSync(
path.join(cfgDir, 'mod.rs'),
`pub mod stage_apply;\npub mod stage_detect;\n`
);
fs.writeFileSync(
path.join(cfgDir, 'stage_apply.rs'),
`pub async fn run() -> Result<(), ()> {\n render_and_write();\n Ok(())\n}\n\nfn render_and_write() {}\n`
);
fs.writeFileSync(
path.join(cfgDir, 'stage_detect.rs'),
`pub async fn run() -> Result<(), ()> { Ok(()) }\n`
);
fs.writeFileSync(
path.join(root, 'src', 'scheduler.rs'),
`pub fn run_due_tasks() -> Result<(), ()> { Ok(()) }\n`
);
return root;
}
describe.skipIf(!HAS_SQLITE)('matchesSymbol — module-qualified lookups (#173)', () => {
let projectRoot: string;
let cg: any;
let handler: any;
let findSymbol: (cg: any, s: string) => { node: any; note: string } | null;
let findAllSymbols: (cg: any, s: string) => { nodes: any[]; note: string };
beforeEach(async () => {
projectRoot = await buildRustWorkspace();
const CodeGraph = (await import('../src/index')).default;
const { ToolHandler } = await import('../src/mcp/tools');
cg = CodeGraph.initSync(projectRoot, {
config: { include: ['**/*.rs'], exclude: [] },
});
await cg.indexAll();
handler = new ToolHandler(cg);
findSymbol = (handler as any).findSymbol.bind(handler);
findAllSymbols = (handler as any).findAllSymbols.bind(handler);
});
afterEach(() => {
handler?.closeAll();
cg?.destroy();
rmTree(projectRoot);
});
it('resolves `stage_apply::run` to the run in stage_apply.rs (not stage_detect.rs)', () => {
const match = findSymbol(cg, 'stage_apply::run');
expect(match).not.toBeNull();
expect(match!.node.name).toBe('run');
expect(match!.node.filePath).toMatch(/configurator\/stage_apply\.rs$/);
});
it('rejects `stage_apply::run` for the same-named function in a different module', () => {
const all = findAllSymbols(cg, 'stage_apply::run');
// All returned nodes must be in stage_apply.rs — never in stage_detect.rs
for (const node of all.nodes) {
expect(node.filePath).toMatch(/stage_apply\.rs$/);
}
expect(all.nodes.length).toBeGreaterThan(0);
});
it('resolves `configurator::stage_apply::run` (multi-level qualifier)', () => {
const match = findSymbol(cg, 'configurator::stage_apply::run');
expect(match).not.toBeNull();
expect(match!.node.name).toBe('run');
expect(match!.node.filePath).toMatch(/configurator\/stage_apply\.rs$/);
});
it('resolves `crate::configurator::stage_apply::run` (Rust path prefix stripped)', () => {
const match = findSymbol(cg, 'crate::configurator::stage_apply::run');
expect(match).not.toBeNull();
expect(match!.node.filePath).toMatch(/configurator\/stage_apply\.rs$/);
});
it('resolves `configurator/stage_apply` (slash qualifier)', () => {
const match = findSymbol(cg, 'configurator/stage_apply/run');
expect(match).not.toBeNull();
expect(match!.node.filePath).toMatch(/configurator\/stage_apply\.rs$/);
});
it('does not silently collide bare `run` with `run_due_tasks`', () => {
const match = findSymbol(cg, 'run');
expect(match).not.toBeNull();
// Whatever it picks, it must be an exact-name match, not a partial.
expect(match!.node.name).toBe('run');
});
it('aggregates all bare-name `run` matches across modules', () => {
const all = findAllSymbols(cg, 'run');
const names = all.nodes.map((n: any) => n.name);
expect(names.every((n: string) => n === 'run')).toBe(true);
expect(all.nodes.length).toBeGreaterThanOrEqual(2); // stage_apply + stage_detect
// The note should call out the ambiguity.
expect(all.note).toMatch(/Aggregated|symbols named "run"/);
});
it('still returns null for genuinely unknown qualified lookups', () => {
const match = findSymbol(cg, 'stage_apply::nonexistent_fn');
expect(match).toBeNull();
});
});
describe.skipIf(!HAS_SQLITE)('matchesSymbol — dotted lookups (regression for #173 fix)', () => {
let projectRoot: string;
let cg: any;
let handler: any;
let findSymbol: (cg: any, s: string) => { node: any; note: string } | null;
beforeEach(async () => {
projectRoot = tmpRoot();
const src = path.join(projectRoot, 'src');
fs.mkdirSync(src, { recursive: true });
fs.writeFileSync(
path.join(src, 'session.ts'),
`export class Session {\n request(): void {}\n}\nexport function request(): void {}\n`
);
const CodeGraph = (await import('../src/index')).default;
const { ToolHandler } = await import('../src/mcp/tools');
cg = CodeGraph.initSync(projectRoot, {
config: { include: ['src/**/*.ts'], exclude: [] },
});
await cg.indexAll();
handler = new ToolHandler(cg);
findSymbol = (handler as any).findSymbol.bind(handler);
});
afterEach(() => {
handler?.closeAll();
cg?.destroy();
rmTree(projectRoot);
});
it('`Session.request` resolves to the method, not the bare function', () => {
const match = findSymbol(cg, 'Session.request');
expect(match).not.toBeNull();
expect(match!.node.kind).toBe('method');
expect(match!.node.qualifiedName).toContain('Session::request');
});
});
+306
View File
@@ -0,0 +1,306 @@
/**
* Sync Module Tests
*
* Tests for sync functionality (incremental updates).
* Note: Git hooks functionality has been removed in favor of codegraph's
* Claude Code hooks integration.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { execFileSync } from 'child_process';
import CodeGraph from '../src/index';
describe('Sync Module', () => {
describe('Sync Functionality', () => {
let testDir: string;
let cg: CodeGraph;
beforeEach(async () => {
testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-sync-func-'));
// Create initial source files
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir);
fs.writeFileSync(
path.join(srcDir, 'index.ts'),
`export function hello() { return 'world'; }`
);
// Initialize and index
cg = CodeGraph.initSync(testDir, {
config: {
include: ['**/*.ts'],
exclude: [],
},
});
await cg.indexAll();
});
afterEach(() => {
if (cg) {
cg.destroy();
}
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
describe('getChangedFiles()', () => {
it('should detect added files', () => {
// Add a new file
fs.writeFileSync(
path.join(testDir, 'src', 'new.ts'),
`export function newFunc() { return 42; }`
);
const changes = cg.getChangedFiles();
expect(changes.added).toContain('src/new.ts');
expect(changes.modified).toHaveLength(0);
expect(changes.removed).toHaveLength(0);
});
it('should detect modified files', () => {
// Modify existing file
fs.writeFileSync(
path.join(testDir, 'src', 'index.ts'),
`export function hello() { return 'modified'; }`
);
const changes = cg.getChangedFiles();
expect(changes.added).toHaveLength(0);
expect(changes.modified).toContain('src/index.ts');
expect(changes.removed).toHaveLength(0);
});
it('should detect removed files', () => {
// Remove file
fs.unlinkSync(path.join(testDir, 'src', 'index.ts'));
const changes = cg.getChangedFiles();
expect(changes.added).toHaveLength(0);
expect(changes.modified).toHaveLength(0);
expect(changes.removed).toContain('src/index.ts');
});
});
describe('sync()', () => {
it('should reindex added files', async () => {
// Add a new file
fs.writeFileSync(
path.join(testDir, 'src', 'new.ts'),
`export function newFunc() { return 42; }`
);
const result = await cg.sync();
expect(result.filesAdded).toBe(1);
expect(result.filesModified).toBe(0);
expect(result.filesRemoved).toBe(0);
// Verify new function is in the graph
const nodes = cg.searchNodes('newFunc');
expect(nodes.length).toBeGreaterThan(0);
});
it('should reindex modified files', async () => {
// Modify existing file
fs.writeFileSync(
path.join(testDir, 'src', 'index.ts'),
`export function goodbye() { return 'farewell'; }`
);
const result = await cg.sync();
expect(result.filesModified).toBe(1);
// Verify new function is in the graph
const nodes = cg.searchNodes('goodbye');
expect(nodes.length).toBeGreaterThan(0);
// Verify old function is gone
const oldNodes = cg.searchNodes('hello');
expect(oldNodes.length).toBe(0);
});
it('should remove nodes from deleted files', async () => {
// Remove file
fs.unlinkSync(path.join(testDir, 'src', 'index.ts'));
const result = await cg.sync();
expect(result.filesRemoved).toBe(1);
// Verify function is gone
const nodes = cg.searchNodes('hello');
expect(nodes.length).toBe(0);
});
it('should report no changes when nothing changed', async () => {
const result = await cg.sync();
expect(result.filesAdded).toBe(0);
expect(result.filesModified).toBe(0);
expect(result.filesRemoved).toBe(0);
expect(result.filesChecked).toBeGreaterThan(0);
});
});
});
describe('Git-based sync', () => {
let testDir: string;
let cg: CodeGraph;
function git(...args: string[]) {
execFileSync('git', args, { cwd: testDir, stdio: 'pipe' });
}
beforeEach(async () => {
testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-git-sync-'));
// Initialize a git repo with an initial commit
git('init');
git('config', 'user.email', 'test@test.com');
git('config', 'user.name', 'Test');
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir);
fs.writeFileSync(
path.join(srcDir, 'index.ts'),
`export function hello() { return 'world'; }`
);
git('add', '-A');
git('commit', '-m', 'initial');
// Initialize CodeGraph and index
cg = CodeGraph.initSync(testDir, {
config: {
include: ['**/*.ts'],
exclude: [],
},
});
await cg.indexAll();
});
afterEach(() => {
if (cg) {
cg.destroy();
}
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('should detect modified files via git', async () => {
fs.writeFileSync(
path.join(testDir, 'src', 'index.ts'),
`export function hello() { return 'modified'; }`
);
const result = await cg.sync();
expect(result.filesModified).toBe(1);
expect(result.changedFilePaths).toContain('src/index.ts');
});
it('should detect new untracked files via git', async () => {
fs.writeFileSync(
path.join(testDir, 'src', 'new.ts'),
`export function newFunc() { return 42; }`
);
const result = await cg.sync();
expect(result.filesAdded).toBe(1);
expect(result.changedFilePaths).toContain('src/new.ts');
// Verify the function was indexed
const nodes = cg.searchNodes('newFunc');
expect(nodes.length).toBeGreaterThan(0);
});
it('should stop reporting untracked files once they are indexed (issue #206)', async () => {
// Untracked files stay `??` in git status even after codegraph indexes
// them. Change detection must compare them against the DB by hash, not
// report every untracked file as "added" on every sync/status.
fs.writeFileSync(
path.join(testDir, 'src', 'new.ts'),
`export function newFunc() { return 42; }`
);
// First sync indexes the untracked file.
const first = await cg.sync();
expect(first.filesAdded).toBe(1);
// The file is still untracked in git, but now lives in the DB.
expect(cg.searchNodes('newFunc').length).toBeGreaterThan(0);
// status must not keep flagging it as a pending addition...
const changes = cg.getChangedFiles();
expect(changes.added).not.toContain('src/new.ts');
expect(changes.modified).not.toContain('src/new.ts');
// ...and a second sync must be a no-op for it.
const second = await cg.sync();
expect(second.filesAdded).toBe(0);
expect(second.filesModified).toBe(0);
});
it('should re-index an untracked file when its contents change', async () => {
const filePath = path.join(testDir, 'src', 'new.ts');
fs.writeFileSync(filePath, `export function newFunc() { return 42; }`);
await cg.sync();
// Modify the still-untracked file.
fs.writeFileSync(filePath, `export function renamedFunc() { return 7; }`);
const changes = cg.getChangedFiles();
expect(changes.modified).toContain('src/new.ts');
const result = await cg.sync();
expect(result.filesModified).toBe(1);
expect(cg.searchNodes('renamedFunc').length).toBeGreaterThan(0);
expect(cg.searchNodes('newFunc').length).toBe(0);
});
it('should detect deleted files via git', async () => {
fs.unlinkSync(path.join(testDir, 'src', 'index.ts'));
const result = await cg.sync();
expect(result.filesRemoved).toBe(1);
// Verify function is gone
const nodes = cg.searchNodes('hello');
expect(nodes.length).toBe(0);
});
it('should skip files with unsupported extensions', async () => {
// A .txt file has no supported grammar, so sync must not index it.
fs.writeFileSync(
path.join(testDir, 'src', 'notes.txt'),
`just some notes`
);
const result = await cg.sync();
expect(result.filesAdded).toBe(0);
expect(result.filesModified).toBe(0);
});
it('should report no changes on clean working tree', async () => {
const result = await cg.sync();
expect(result.filesAdded).toBe(0);
expect(result.filesModified).toBe(0);
expect(result.filesRemoved).toBe(0);
expect(result.changedFilePaths).toBeUndefined();
});
});
});
+87
View File
@@ -0,0 +1,87 @@
/**
* WASM runtime flags — the workaround for the V8 turboshaft WASM Zone OOM
* (`Fatal process out of memory: Zone`) that crashed `codegraph index` on large
* polyglot repos under Node >= 22. See issues #293 and #298.
*
* The crash was reproduced with the real indexer on the bundled Node 24 runtime;
* empirically only `--liftoff-only` prevents it (`--no-wasm-tier-up` /
* `--no-wasm-dynamic-tiering` do not), and the flag must be on node's command
* line — `setFlagsFromString`, worker `execArgv`, and `NODE_OPTIONS` all fail.
* These tests pin that contract so it can't silently regress.
*/
import { describe, it, expect } from 'vitest';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import {
WASM_RUNTIME_FLAGS,
processHasWasmRuntimeFlags,
buildRelaunchArgv,
} from '../src/extraction/wasm-runtime-flags';
describe('WASM_RUNTIME_FLAGS', () => {
it('pins --liftoff-only (the only flag shown to stop the turboshaft Zone OOM)', () => {
// On Node 24, --no-wasm-tier-up and --no-wasm-dynamic-tiering both still
// crash; only --liftoff-only forces grammars onto the Liftoff baseline and
// off the optimizing tier. Pin it so it can't be swapped for an ineffective
// flag.
expect(WASM_RUNTIME_FLAGS).toContain('--liftoff-only');
});
it('every flag is a real, accepted flag on the running Node/V8 runtime', () => {
// node rejects unknown CLI flags at startup, so a renamed/removed flag would
// break the bundled launcher and make the relaunch guard a silent no-op.
// Prove each flag actually launches node here.
const res = spawnSync(
process.execPath,
[...WASM_RUNTIME_FLAGS, '-e', 'process.exit(0)'],
{ encoding: 'utf8' }
);
expect(res.status, `node rejected ${WASM_RUNTIME_FLAGS.join(' ')}:\n${res.stderr}`).toBe(0);
});
});
describe('processHasWasmRuntimeFlags', () => {
it('is true only when every required flag is present', () => {
expect(processHasWasmRuntimeFlags(['--liftoff-only'])).toBe(true);
expect(processHasWasmRuntimeFlags(['--liftoff-only', '--enable-source-maps'])).toBe(true);
});
it('is false when the flags are absent', () => {
expect(processHasWasmRuntimeFlags([])).toBe(false);
expect(processHasWasmRuntimeFlags(['--max-old-space-size=4096'])).toBe(false);
});
});
describe('buildRelaunchArgv', () => {
it('places the wasm flags first, then the script and its args', () => {
expect(buildRelaunchArgv('/x/codegraph.js', ['index', '/repo'], [])).toEqual([
'--liftoff-only',
'/x/codegraph.js',
'index',
'/repo',
]);
});
it('preserves other existing node flags without duplicating ours', () => {
expect(
buildRelaunchArgv('/x/codegraph.js', ['status'], ['--liftoff-only', '--enable-source-maps'])
).toEqual(['--liftoff-only', '--enable-source-maps', '/x/codegraph.js', 'status']);
});
it('produces an argv that actually launches node WITH the flag applied', () => {
// End-to-end proof of the delivery mechanism without needing the crash:
// run the constructed argv and confirm the child sees the flag in execArgv.
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'cg-relaunch-'));
try {
const harness = path.join(dir, 'harness.cjs');
fs.writeFileSync(harness, 'process.stdout.write(JSON.stringify(process.execArgv));');
const res = spawnSync(process.execPath, buildRelaunchArgv(harness, []), { encoding: 'utf8' });
expect(res.status, res.stderr).toBe(0);
expect(JSON.parse(res.stdout)).toContain('--liftoff-only');
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
+82
View File
@@ -0,0 +1,82 @@
/**
* Watch Policy Tests
*
* Covers the decision of whether the live file watcher runs, including the
* WSL2 /mnt auto-detect and the env-var escape hatches (issue #199), plus
* that FileWatcher.start() honors the decision.
*/
import { describe, it, expect, afterEach, vi } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { watchDisabledReason } from '../src/sync/watch-policy';
import { FileWatcher } from '../src/sync/watcher';
describe('watchDisabledReason', () => {
it('returns a reason when CODEGRAPH_NO_WATCH=1', () => {
const reason = watchDisabledReason('/home/me/project', {
env: { CODEGRAPH_NO_WATCH: '1' },
isWsl: false,
});
expect(reason).toBeTruthy();
expect(reason).toMatch(/CODEGRAPH_NO_WATCH/);
});
it('auto-disables on a WSL2 /mnt drive', () => {
const reason = watchDisabledReason('/mnt/d/code/project', { env: {}, isWsl: true });
expect(reason).toBeTruthy();
expect(reason).toMatch(/mnt/);
});
it('does NOT disable on a native WSL home path', () => {
expect(watchDisabledReason('/home/me/project', { env: {}, isWsl: true })).toBeNull();
});
it('does NOT disable on /mnt when not running under WSL', () => {
// A real Linux box may legitimately have a fast /mnt mount.
expect(watchDisabledReason('/mnt/d/code/project', { env: {}, isWsl: false })).toBeNull();
});
it('does NOT treat /mnt/wsl (fast Linux mount) as a Windows drive', () => {
expect(watchDisabledReason('/mnt/wsl/project', { env: {}, isWsl: true })).toBeNull();
});
it('CODEGRAPH_FORCE_WATCH=1 overrides WSL auto-detect', () => {
const reason = watchDisabledReason('/mnt/d/code/project', {
env: { CODEGRAPH_FORCE_WATCH: '1' },
isWsl: true,
});
expect(reason).toBeNull();
});
it('CODEGRAPH_NO_WATCH wins over CODEGRAPH_FORCE_WATCH', () => {
const reason = watchDisabledReason('/home/me/project', {
env: { CODEGRAPH_NO_WATCH: '1', CODEGRAPH_FORCE_WATCH: '1' },
isWsl: false,
});
expect(reason).toBeTruthy();
});
});
describe('FileWatcher honors the watch policy', () => {
let testDir: string;
afterEach(() => {
delete process.env.CODEGRAPH_NO_WATCH;
if (testDir && fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
it('does not start when CODEGRAPH_NO_WATCH=1', () => {
testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-nowatch-'));
process.env.CODEGRAPH_NO_WATCH = '1';
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
const watcher = new FileWatcher(testDir, syncFn);
expect(watcher.start()).toBe(false);
expect(watcher.isActive()).toBe(false);
});
});
+278
View File
@@ -0,0 +1,278 @@
/**
* FileWatcher Tests
*
* Tests for the file watcher that auto-syncs on changes.
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
import { FileWatcher } from '../src/sync/watcher';
import CodeGraph from '../src/index';
/**
* Helper to wait for a condition with timeout
*/
function waitFor(
condition: () => boolean,
timeoutMs = 10000,
intervalMs = 100
): Promise<void> {
return new Promise((resolve, reject) => {
const start = Date.now();
const check = () => {
if (condition()) return resolve();
if (Date.now() - start > timeoutMs) return reject(new Error('waitFor timed out'));
setTimeout(check, intervalMs);
};
check();
});
}
describe('FileWatcher', () => {
let testDir: string;
beforeEach(() => {
testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-watcher-'));
// Create a source file so the directory isn't empty
const srcDir = path.join(testDir, 'src');
fs.mkdirSync(srcDir);
fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
});
afterEach(() => {
if (fs.existsSync(testDir)) {
fs.rmSync(testDir, { recursive: true, force: true });
}
});
describe('start/stop lifecycle', () => {
it('should start and stop without errors', () => {
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
const watcher = new FileWatcher(testDir, syncFn);
const started = watcher.start();
expect(started).toBe(true);
expect(watcher.isActive()).toBe(true);
watcher.stop();
expect(watcher.isActive()).toBe(false);
});
it('should be idempotent on double start', () => {
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
const watcher = new FileWatcher(testDir, syncFn);
expect(watcher.start()).toBe(true);
expect(watcher.start()).toBe(true); // Should not throw
expect(watcher.isActive()).toBe(true);
watcher.stop();
});
it('should be idempotent on double stop', () => {
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
const watcher = new FileWatcher(testDir, syncFn);
watcher.start();
watcher.stop();
watcher.stop(); // Should not throw
expect(watcher.isActive()).toBe(false);
});
});
describe('debounced sync', () => {
it('should trigger sync after file change', async () => {
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 1, durationMs: 10 });
const watcher = new FileWatcher(testDir, syncFn, { debounceMs: 200 });
watcher.start();
// Create a new file
fs.writeFileSync(path.join(testDir, 'src', 'new.ts'), 'export const y = 2;');
// Wait for debounced sync to fire
await waitFor(() => syncFn.mock.calls.length > 0, 5000);
expect(syncFn).toHaveBeenCalled();
watcher.stop();
});
it('should debounce rapid changes into a single sync', async () => {
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 1, durationMs: 10 });
const watcher = new FileWatcher(testDir, syncFn, { debounceMs: 500 });
watcher.start();
// Rapid-fire changes
for (let i = 0; i < 5; i++) {
fs.writeFileSync(
path.join(testDir, 'src', `file${i}.ts`),
`export const v${i} = ${i};`
);
await new Promise((r) => setTimeout(r, 50));
}
// Wait for the single debounced sync
await waitFor(() => syncFn.mock.calls.length > 0, 5000);
// Should have been called once (debounced), not 5 times
expect(syncFn.mock.calls.length).toBe(1);
watcher.stop();
});
});
describe('filtering', () => {
it('should ignore files not matching include patterns', async () => {
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
const watcher = new FileWatcher(testDir, syncFn, { debounceMs: 200 });
watcher.start();
// Let watcher settle — fs.watch may fire residual events from beforeEach
await new Promise((r) => setTimeout(r, 400));
syncFn.mockClear();
// Create a file that doesn't match include patterns
fs.writeFileSync(path.join(testDir, 'src', 'readme.md'), '# Hello');
// Wait a bit longer than debounce — sync should NOT trigger
await new Promise((r) => setTimeout(r, 500));
expect(syncFn).not.toHaveBeenCalled();
watcher.stop();
});
it('should ignore .codegraph directory changes', async () => {
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
const watcher = new FileWatcher(testDir, syncFn, { debounceMs: 200 });
watcher.start();
// Let watcher settle — fs.watch may fire residual events from beforeEach
await new Promise((r) => setTimeout(r, 400));
syncFn.mockClear();
// Simulate a .codegraph directory change
const cgDir = path.join(testDir, '.codegraph');
fs.mkdirSync(cgDir, { recursive: true });
fs.writeFileSync(path.join(cgDir, 'db.sqlite'), 'fake');
// Wait — sync should NOT trigger
await new Promise((r) => setTimeout(r, 500));
expect(syncFn).not.toHaveBeenCalled();
watcher.stop();
});
});
describe('callbacks', () => {
it('should call onSyncComplete after successful sync', async () => {
const syncFn = vi.fn().mockResolvedValue({ filesChanged: 2, durationMs: 50 });
const onSyncComplete = vi.fn();
const watcher = new FileWatcher(testDir, syncFn, {
debounceMs: 200,
onSyncComplete,
});
watcher.start();
fs.writeFileSync(path.join(testDir, 'src', 'test.ts'), 'export const z = 3;');
await waitFor(() => onSyncComplete.mock.calls.length > 0, 5000);
expect(onSyncComplete).toHaveBeenCalledWith({ filesChanged: 2, durationMs: 50 });
watcher.stop();
});
it('should call onSyncError when sync throws', async () => {
const syncFn = vi.fn().mockRejectedValue(new Error('sync failed'));
const onSyncError = vi.fn();
const watcher = new FileWatcher(testDir, syncFn, {
debounceMs: 200,
onSyncError,
});
watcher.start();
fs.writeFileSync(path.join(testDir, 'src', 'test.ts'), 'export const z = 3;');
await waitFor(() => onSyncError.mock.calls.length > 0, 5000);
expect(onSyncError).toHaveBeenCalled();
expect(onSyncError.mock.calls[0]![0]).toBeInstanceOf(Error);
watcher.stop();
});
});
describe('CodeGraph integration', () => {
let cg: CodeGraph;
afterEach(() => {
if (cg) cg.close();
});
it('should watch and unwatch via CodeGraph API', async () => {
cg = CodeGraph.initSync(testDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
await cg.indexAll();
expect(cg.isWatching()).toBe(false);
const started = cg.watch({ debounceMs: 200 });
expect(started).toBe(true);
expect(cg.isWatching()).toBe(true);
cg.unwatch();
expect(cg.isWatching()).toBe(false);
});
it('should stop watching on close', async () => {
cg = CodeGraph.initSync(testDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
await cg.indexAll();
cg.watch({ debounceMs: 200 });
expect(cg.isWatching()).toBe(true);
cg.close();
// After close, isWatching should be false
// (we can't call isWatching after close since DB is closed,
// but we verify no errors are thrown)
});
it('should auto-sync when files change while watching', async () => {
cg = CodeGraph.initSync(testDir, {
config: { include: ['**/*.ts'], exclude: [] },
});
await cg.indexAll();
const initialStats = cg.getStats();
const initialNodes = initialStats.nodeCount;
cg.watch({ debounceMs: 300 });
// Add a new file with a function
fs.writeFileSync(
path.join(testDir, 'src', 'added.ts'),
'export function added() { return 42; }'
);
// Wait for auto-sync to pick it up
await waitFor(() => {
const stats = cg.getStats();
return stats.nodeCount > initialNodes;
}, 10000);
// The new function should be in the graph
const results = cg.searchNodes('added');
expect(results.length).toBeGreaterThan(0);
cg.unwatch();
});
});
});