mirror of
https://github.com/colbymchenry/codegraph.git
synced 2026-10-02 01:37:32 +08:00
* test: close resolution graphs before removing Windows fixtures
Close ArkTS and JVM graph connections in afterEach, including failed assertions. Verified both files on Windows 11 and macOS (32 tests).
* test: compare explore source lines across LF and CRLF checkouts
Normalize only line endings when matching emitted source against checked-out fixtures. Preserve the closure coverage and whole-line assertions. Both files pass on Windows 11 and macOS (15 tests).
* test: exercise old Git fallback without a POSIX shell shim
Inject only the unsupported ls-files invocation and run every other Git command against real repositories. Assert that each rejected call retries, use portable graph paths, and clean up fixtures. Passes on Windows 11 and macOS.
* test: normalize Python fixture before generating CRLF cases
The tests added in #2004 produced CRCRLF from a Windows checkout. Normalize the input to LF before constructing either variant. All 28 native and WASM cases pass on Windows 11 and macOS.
* test: allow time for eviction fixture indexes on Windows
The #2036 eviction test builds and reconciles nine real indexes and consistently exceeds its default five-second timeout on the VM. Allow 15 seconds for this test alone, preserving every assertion. The full file passes on Windows 11 and macOS (21 tests).
* test: finish MCP processes before resetting Windows fixtures
Launch actual servers with their runtime flags and await termination before directory removal. Use asynchronous removal retries for daemon fixtures. Establish a ready daemon and stop its first proxy before simulating PID reuse, then make source stale without opening a competing SQLite writer. Preserve lock and database byte-equality assertions. All touched files validated on Windows 11 and macOS.
* test: allow Windows named-pipe fallback polling to finish
The VM takes up to 25.7 seconds to complete the nominal six-second retry loop. Allow 30 seconds for the three fallback waits and 40 seconds for the two shorter enclosing tests, retaining their lock-preservation and read-only assertions. The full daemon file is validated on Windows 11 and macOS.
* fix(daemon): retry transient Windows PID-file sharing violations
A transient EPERM replacing daemon.pid aborted startup, observed in the quiet-client test and reproduced with a real locked handle at ba3c21e5. Retry only Windows sharing errors with five bounded delays, rechecking ownership each time and cleaning temporary files. Keep publication synchronous before client processing. Cover transient/permanent failures, changed ownership, non-retryable errors, and a real Windows handle; require a confirmed daemon round-trip before measuring a quiet session. Validated on Windows 11 and macOS.
187 lines
7.6 KiB
TypeScript
187 lines
7.6 KiB
TypeScript
/**
|
|
* 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';
|
|
import { once } from 'events';
|
|
import { WASM_RUNTIME_FLAGS } from '../src/extraction/wasm-runtime-flags';
|
|
|
|
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, [...WASM_RUNTIME_FLAGS, 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(async () => {
|
|
// Spawn with the runtime flags so this is the server, not a relauncher
|
|
// whose grandchild would retain the Windows cwd/database handles.
|
|
if (child && child.exitCode === null && child.signalCode === null) {
|
|
const closed = once(child, 'close');
|
|
child.kill('SIGKILL');
|
|
await closed;
|
|
}
|
|
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);
|
|
});
|