mcp-daemon.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499
  1. /**
  2. * Shared MCP daemon — issue #411.
  3. *
  4. * Validates the daemon architecture in `src/mcp/{daemon,proxy,session,index}.ts`
  5. * AFTER the review fixes:
  6. *
  7. * - The daemon is a *detached* background process; every `serve --mcp`
  8. * invocation is a thin proxy to it. Two invocations against one project
  9. * share ONE daemon.
  10. * - Concurrent launchers converge on a single daemon (the must-fix-1
  11. * lockfile-race: an empty-pidfile window used to let a racing candidate
  12. * delete the winner's lock → two daemons).
  13. * - Killing the launcher that spawned the daemon does NOT take the daemon
  14. * down — other attached clients keep working (the must-fix-2 detach: the
  15. * in-process daemon used to die with its launcher's process group and
  16. * orphan on host SIGKILL, regressing #277).
  17. * - A stale lockfile (dead pid) is cleared; `CODEGRAPH_NO_DAEMON=1` opts out;
  18. * the proxy refuses to attach across a version mismatch; the daemon
  19. * idle-times-out after the last client leaves (so a single session can't
  20. * leak a daemon forever).
  21. *
  22. * These tests intentionally spawn real `node dist/bin/codegraph.js` processes
  23. * over real sockets/pipes — the same surface a Claude Code / Cursor / Codex
  24. * install exercises. The daemon logs to `.codegraph/daemon.log` (it has no
  25. * client stderr of its own), so daemon-side assertions read that file.
  26. *
  27. * `realRoot` vs `tempDir`: processes are spawned with the (possibly symlinked)
  28. * `tempDir` as cwd/rootUri — on macOS `os.tmpdir()` lives under `/var`, a
  29. * symlink to `/private/var`, and a spawned child's `process.cwd()` is already
  30. * realpath'd. The daemon canonicalizes the root with `realpathSync`, so all
  31. * path assertions use `realRoot` (the canonical form). That this matches end to
  32. * end is itself the proof the canonicalization works.
  33. */
  34. import { afterEach, beforeEach, describe, expect, it } from 'vitest';
  35. import { ChildProcessWithoutNullStreams, spawn } from 'child_process';
  36. import * as fs from 'fs';
  37. import * as os from 'os';
  38. import * as path from 'path';
  39. import { CodeGraph } from '../src';
  40. import { getDaemonSocketPath } from '../src/mcp/daemon-paths';
  41. import { CodeGraphPackageVersion } from '../src/mcp/version';
  42. const BIN = path.resolve(__dirname, '../dist/bin/codegraph.js');
  43. interface SpawnedServer {
  44. child: ChildProcessWithoutNullStreams;
  45. stdout: string[];
  46. stderr: string[];
  47. }
  48. function spawnServer(cwd: string, env: NodeJS.ProcessEnv = {}): SpawnedServer {
  49. const child = spawn(process.execPath, [BIN, 'serve', '--mcp'], {
  50. cwd,
  51. stdio: ['pipe', 'pipe', 'pipe'],
  52. // #618: the daemon-attach log line is now off by default; opt the test
  53. // harness into it (CODEGRAPH_MCP_LOG_ATTACH=1) so the attach assertions
  54. // below can still observe a successful attach. A per-test env still wins.
  55. env: { CODEGRAPH_MCP_LOG_ATTACH: '1', ...process.env, ...env },
  56. }) as ChildProcessWithoutNullStreams;
  57. // Swallow spawn/EPIPE errors so killing a child mid-write can't surface as an
  58. // unhandled error that crashes the vitest worker.
  59. child.on('error', () => { /* ignore */ });
  60. child.stdin.on('error', () => { /* ignore */ });
  61. const stdout: string[] = [];
  62. const stderr: string[] = [];
  63. let stdoutBuf = '';
  64. let stderrBuf = '';
  65. child.stdout.on('data', (chunk: Buffer) => {
  66. stdoutBuf += chunk.toString('utf8');
  67. let idx: number;
  68. while ((idx = stdoutBuf.indexOf('\n')) !== -1) {
  69. stdout.push(stdoutBuf.slice(0, idx));
  70. stdoutBuf = stdoutBuf.slice(idx + 1);
  71. }
  72. });
  73. child.stderr.on('data', (chunk: Buffer) => {
  74. stderrBuf += chunk.toString('utf8');
  75. let idx: number;
  76. while ((idx = stderrBuf.indexOf('\n')) !== -1) {
  77. stderr.push(stderrBuf.slice(0, idx));
  78. stderrBuf = stderrBuf.slice(idx + 1);
  79. }
  80. });
  81. return { child, stdout, stderr };
  82. }
  83. function sendMessage(child: ChildProcessWithoutNullStreams, msg: unknown): void {
  84. try { child.stdin.write(JSON.stringify(msg) + '\n'); } catch { /* child may be gone */ }
  85. }
  86. function sendInitialize(child: ChildProcessWithoutNullStreams, rootUri: string, id: number): void {
  87. sendMessage(child, {
  88. jsonrpc: '2.0',
  89. id,
  90. method: 'initialize',
  91. params: {
  92. protocolVersion: '2024-11-05',
  93. capabilities: {},
  94. clientInfo: { name: 'test', version: '0.0.0' },
  95. rootUri,
  96. },
  97. });
  98. }
  99. /** Find a JSON-RPC response with the given id (result OR error) on stdout. */
  100. function findResponse(stdout: string[], id: number): any | null {
  101. for (const line of stdout) {
  102. if (!line.trim()) continue;
  103. try {
  104. const parsed = JSON.parse(line);
  105. if (parsed && parsed.id === id && (parsed.result !== undefined || parsed.error !== undefined)) {
  106. return parsed;
  107. }
  108. } catch { /* not JSON */ }
  109. }
  110. return null;
  111. }
  112. function waitFor<T>(
  113. predicate: () => T | undefined | null | false,
  114. timeoutMs: number,
  115. pollMs = 25,
  116. label = '',
  117. ): Promise<T> {
  118. return new Promise((resolve, reject) => {
  119. const started = Date.now();
  120. const tick = () => {
  121. let v: T | undefined | null | false;
  122. try { v = predicate(); } catch (e) { return reject(e); }
  123. if (v) return resolve(v as T);
  124. if (Date.now() - started > timeoutMs) {
  125. // Name the wait: an async stack loses the await site, so an unlabeled
  126. // timeout can't tell WHICH step flaked (the #662 test's recurring
  127. // timeout was undiagnosable for exactly this reason).
  128. return reject(new Error(`Timed out after ${timeoutMs}ms${label ? ` waiting for: ${label}` : ''}`));
  129. }
  130. setTimeout(tick, pollMs);
  131. };
  132. tick();
  133. });
  134. }
  135. function isAlive(pid: number): boolean {
  136. try { process.kill(pid, 0); return true; } catch { return false; }
  137. }
  138. function readLockPid(root: string): number | null {
  139. try {
  140. const raw = fs.readFileSync(path.join(root, '.codegraph', 'daemon.pid'), 'utf8');
  141. const info = JSON.parse(raw);
  142. return typeof info.pid === 'number' ? info.pid : null;
  143. } catch { return null; }
  144. }
  145. function readDaemonLog(root: string): string {
  146. try { return fs.readFileSync(path.join(root, '.codegraph', 'daemon.log'), 'utf8'); }
  147. catch { return ''; }
  148. }
  149. function countListeningLines(root: string): number {
  150. return readDaemonLog(root).split('\n').filter((l) => l.includes('[CodeGraph daemon] Listening on')).length;
  151. }
  152. function killTree(...procs: ChildProcessWithoutNullStreams[]): void {
  153. for (const p of procs) {
  154. if (!p.killed) { try { p.kill('SIGKILL'); } catch { /* gone */ } }
  155. }
  156. }
  157. async function waitProcessExit(pid: number, timeoutMs: number): Promise<boolean> {
  158. return waitFor(() => !isAlive(pid), timeoutMs).then(() => true).catch(() => false);
  159. }
  160. describe('Shared MCP daemon (issue #411)', () => {
  161. let tempDir: string; // the (possibly symlinked) path processes are spawned with
  162. let realRoot: string; // its canonical form — what the daemon keys paths on
  163. const servers: SpawnedServer[] = [];
  164. beforeEach(async () => {
  165. tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-mcp-daemon-'));
  166. const cg = await CodeGraph.init(tempDir);
  167. cg.close();
  168. realRoot = fs.realpathSync(tempDir);
  169. });
  170. afterEach(async () => {
  171. killTree(...servers.map((s) => s.child));
  172. // The daemon is detached (not a tracked child) — reap it explicitly via the
  173. // pid it recorded, so a test can't leak a background daemon. Guard against
  174. // our own pid: the version-mismatch test plants `pid: process.pid` in the
  175. // lockfile, and we must never SIGKILL the vitest worker.
  176. const daemonPid = readLockPid(realRoot);
  177. if (daemonPid && daemonPid !== process.pid && isAlive(daemonPid)) {
  178. try { process.kill(daemonPid, 'SIGKILL'); } catch { /* race */ }
  179. }
  180. await new Promise((r) => setTimeout(r, 50));
  181. servers.length = 0;
  182. fs.rmSync(tempDir, { recursive: true, force: true });
  183. });
  184. it('two invocations share ONE detached daemon; both attach as proxies', async () => {
  185. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  186. const first = spawnServer(tempDir, env);
  187. servers.push(first);
  188. sendInitialize(first.child, `file://${tempDir}`, 1);
  189. const firstResp = await waitFor(() => findResponse(first.stdout, 1), 10000);
  190. expect(firstResp.result.serverInfo.name).toBe('codegraph');
  191. // The launcher is a PROXY (not the daemon itself) — that's the detach fix.
  192. await waitFor(() => first.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  193. // A detached daemon came up and recorded itself.
  194. await waitFor(() => fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid')), 8000);
  195. await waitFor(() => countListeningLines(realRoot) >= 1, 8000);
  196. const daemonPid = readLockPid(realRoot);
  197. expect(daemonPid).toBeTruthy();
  198. expect(isAlive(daemonPid!)).toBe(true);
  199. // The socket exists at the path the code computes from the canonical root.
  200. // On Windows the daemon listens on a named pipe (\\.\pipe\...), which isn't
  201. // a filesystem entry — existsSync doesn't apply there, and the "Attached to
  202. // shared daemon" proof above already confirms the proxy reached it.
  203. if (process.platform !== 'win32') {
  204. expect(fs.existsSync(getDaemonSocketPath(realRoot))).toBe(true);
  205. }
  206. // Second invocation attaches as a proxy to the SAME daemon.
  207. const second = spawnServer(tempDir, env);
  208. servers.push(second);
  209. sendInitialize(second.child, `file://${tempDir}`, 2);
  210. const secondResp = await waitFor(() => findResponse(second.stdout, 2), 10000);
  211. expect(secondResp.result.serverInfo.name).toBe('codegraph');
  212. await waitFor(() => second.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  213. // Exactly one daemon ever bound, and it's the same pid both attached to.
  214. expect(countListeningLines(realRoot)).toBe(1);
  215. expect(readLockPid(realRoot)).toBe(daemonPid);
  216. }, 40000);
  217. it('concurrent launchers converge on a single daemon (lockfile race — must-fix 1)', async () => {
  218. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  219. // Fire three launchers as close to simultaneously as possible — this is the
  220. // race window where the old code could end up with two daemons.
  221. const procs = [spawnServer(tempDir, env), spawnServer(tempDir, env), spawnServer(tempDir, env)];
  222. procs.forEach((p, i) => { servers.push(p); sendInitialize(p.child, `file://${tempDir}`, i + 1); });
  223. // All three get a valid initialize response...
  224. for (let i = 0; i < procs.length; i++) {
  225. const resp = await waitFor(() => findResponse(procs[i].stdout, i + 1), 12000);
  226. expect(resp.result.serverInfo.name).toBe('codegraph');
  227. }
  228. // ...and all three attached as proxies (none fell back / wedged).
  229. for (const p of procs) {
  230. await waitFor(() => p.stderr.some((l) => l.includes('Attached to shared daemon')), 10000);
  231. }
  232. // The decisive assertion: exactly ONE daemon bound the socket. Losing
  233. // candidates log "already holds the lock; exiting" and never listen.
  234. expect(countListeningLines(realRoot)).toBe(1);
  235. const daemonPid = readLockPid(realRoot);
  236. expect(daemonPid).toBeTruthy();
  237. expect(isAlive(daemonPid!)).toBe(true);
  238. }, 45000);
  239. it('daemon survives the first client dying; a second client keeps working (must-fix 2 / #277)', async () => {
  240. // Idle high so the daemon doesn't reap mid-test; poll fast so proxy 1
  241. // notices its dead parent quickly.
  242. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '30000', CODEGRAPH_PPID_POLL_MS: '200' };
  243. const first = spawnServer(tempDir, env);
  244. servers.push(first);
  245. sendInitialize(first.child, `file://${tempDir}`, 1);
  246. await waitFor(() => findResponse(first.stdout, 1), 10000);
  247. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  248. const daemonPid = readLockPid(realRoot)!;
  249. expect(isAlive(daemonPid)).toBe(true);
  250. const second = spawnServer(tempDir, env);
  251. servers.push(second);
  252. sendInitialize(second.child, `file://${tempDir}`, 1);
  253. await waitFor(() => findResponse(second.stdout, 1), 10000);
  254. await waitFor(() => second.stderr.some((l) => l.includes('Attached to shared daemon')), 8000);
  255. // Kill the launcher that spawned the daemon. With the old in-process design
  256. // this would take the daemon (and thus the second client) down.
  257. killTree(first.child);
  258. // The daemon is detached — it must still be alive a beat later.
  259. await new Promise((r) => setTimeout(r, 1500));
  260. expect(isAlive(daemonPid)).toBe(true);
  261. // And the second client can still drive a real tool call through it.
  262. sendMessage(second.child, { jsonrpc: '2.0', id: 2, method: 'tools/list' });
  263. const toolsResp = await waitFor(() => findResponse(second.stdout, 2), 10000);
  264. expect(Array.isArray(toolsResp.result.tools)).toBe(true);
  265. expect(toolsResp.result.tools.length).toBeGreaterThan(0);
  266. }, 45000);
  267. it('CODEGRAPH_NO_DAEMON=1 keeps each process independent (no socket/pidfile)', async () => {
  268. const env = { CODEGRAPH_NO_DAEMON: '1' };
  269. const first = spawnServer(tempDir, env);
  270. servers.push(first);
  271. sendInitialize(first.child, `file://${tempDir}`, 1);
  272. await waitFor(() => findResponse(first.stdout, 1), 10000);
  273. // Direct mode — no daemon machinery touched.
  274. expect(first.stderr.some((l) => l.includes('Attached to shared daemon'))).toBe(false);
  275. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid'))).toBe(false);
  276. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.log'))).toBe(false);
  277. }, 20000);
  278. it('clears a stale (dead-pid) lockfile and a fresh daemon takes over', async () => {
  279. // Plant a lockfile pointing at a definitely-dead pid + the real socket path.
  280. fs.writeFileSync(
  281. path.join(realRoot, '.codegraph', 'daemon.pid'),
  282. JSON.stringify({
  283. pid: 999_999,
  284. version: '0.0.0-fake',
  285. socketPath: getDaemonSocketPath(realRoot),
  286. startedAt: Date.now() - 1000,
  287. }),
  288. );
  289. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '15000' };
  290. const server = spawnServer(tempDir, env);
  291. servers.push(server);
  292. sendInitialize(server.child, `file://${tempDir}`, 1);
  293. const resp = await waitFor(() => findResponse(server.stdout, 1), 10000).catch((e) => {
  294. throw new Error(`${(e as Error).message}\nstderr:\n${server.stderr.join('\n')}\ndaemon.log:\n${readDaemonLog(realRoot)}`);
  295. });
  296. expect(resp.result.serverInfo.name).toBe('codegraph');
  297. await waitFor(() => countListeningLines(realRoot) >= 1, 10000);
  298. // The pidfile now names a live daemon, not the planted-dead 999999.
  299. const livePid = readLockPid(realRoot);
  300. expect(livePid).not.toBe(999_999);
  301. expect(isAlive(livePid!)).toBe(true);
  302. }, 40000);
  303. it('takes over after SIGKILL even when the stale PID has been reused (#1553)', async () => {
  304. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '30000' };
  305. const first = spawnServer(tempDir, env);
  306. servers.push(first);
  307. sendInitialize(first.child, `file://${tempDir}`, 1);
  308. await waitFor(() => findResponse(first.stdout, 1), 10000);
  309. await waitFor(() => countListeningLines(realRoot) >= 1, 10000);
  310. const killedPid = readLockPid(realRoot)!;
  311. process.kill(killedPid, 'SIGKILL');
  312. expect(await waitProcessExit(killedPid, 8000)).toBe(true);
  313. // Model OS PID reuse without risking another process: the stale lock now
  314. // names this live vitest worker, but no daemon answers the leftover socket.
  315. fs.writeFileSync(
  316. path.join(realRoot, '.codegraph', 'daemon.pid'),
  317. JSON.stringify({
  318. pid: process.pid,
  319. version: CodeGraphPackageVersion,
  320. socketPath: getDaemonSocketPath(realRoot),
  321. startedAt: Date.now() - 60_000,
  322. }),
  323. );
  324. const second = spawnServer(tempDir, env);
  325. servers.push(second);
  326. sendInitialize(second.child, `file://${tempDir}`, 2);
  327. const response = await waitFor(() => findResponse(second.stdout, 2), 12000);
  328. expect(response.result.serverInfo.name).toBe('codegraph');
  329. await waitFor(() => countListeningLines(realRoot) >= 2, 10000);
  330. const replacementPid = readLockPid(realRoot)!;
  331. expect(replacementPid).not.toBe(killedPid);
  332. expect(replacementPid).not.toBe(process.pid);
  333. expect(isAlive(replacementPid)).toBe(true);
  334. expect(isAlive(process.pid)).toBe(true);
  335. }, 50000);
  336. it('proxy falls back to direct mode on a daemon version mismatch', async () => {
  337. const net = await import('net');
  338. const sockPath = getDaemonSocketPath(realRoot);
  339. // Plant a live-pid lockfile so the launcher treats the lock as held, and a
  340. // mini-server that answers with a mismatched-version hello.
  341. fs.writeFileSync(
  342. path.join(realRoot, '.codegraph', 'daemon.pid'),
  343. JSON.stringify({ pid: process.pid, version: '0.0.0-mismatch', socketPath: sockPath, startedAt: Date.now() }),
  344. );
  345. const miniServer = net.createServer((sock) => {
  346. sock.write(JSON.stringify({ codegraph: '0.0.0-mismatch', pid: 1, socketPath: sockPath, protocol: 1 }) + '\n');
  347. });
  348. await new Promise<void>((resolve) => miniServer.listen(sockPath, () => resolve()));
  349. try {
  350. const server = spawnServer(tempDir);
  351. servers.push(server);
  352. sendInitialize(server.child, `file://${tempDir}`, 1);
  353. // Despite the mismatched daemon, the client still gets an initialize
  354. // response — the proxy answers the handshake locally and, refusing to
  355. // attach across the version mismatch, serves the session in-process.
  356. const resp = await waitFor(() => findResponse(server.stdout, 1), 10000);
  357. expect(resp.result.serverInfo.name).toBe('codegraph');
  358. await waitFor(
  359. () => server.stderr.some((l) => l.includes('serving this session in-process')),
  360. 6000,
  361. );
  362. } finally {
  363. await new Promise<void>((resolve) => miniServer.close(() => resolve()));
  364. }
  365. }, 30000);
  366. // The over-the-wire client-hello → record → sweep path, and the inactivity
  367. // backstop's liveness gate, are covered by the deterministic unit tests in
  368. // daemon-client-liveness (`reapDeadClients`, `backstopShouldExit`) — a
  369. // raw-socket variant here was flaky under heavy parallel load. What stays
  370. // here is the lifecycle behavior that needs real procs: a live-but-quiet
  371. // client must SURVIVE the inactivity backstop. Reaping it used to silently
  372. // degrade the session (and any others sharing the daemon) to an in-process
  373. // engine; on a real machine the backstop fired on live sessions far more
  374. // often than on the phantoms it exists for. The phantom case it still covers
  375. // (an unknown-pid connection) is the `backstopShouldExit` unit test.
  376. it('does NOT reap a live-but-quiet client on the inactivity backstop (#692)', async () => {
  377. // Backstop short, idle timeout long: with a client connected the idle timer
  378. // never arms, so the inactivity backstop is the only thing that could take
  379. // the daemon down — and it must not, because the client's peer is alive.
  380. const env = { CODEGRAPH_DAEMON_MAX_IDLE_MS: '1200', CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '60000' };
  381. const server = spawnServer(tempDir, env);
  382. servers.push(server);
  383. sendInitialize(server.child, `file://${tempDir}`, 1);
  384. await waitFor(() => findResponse(server.stdout, 1), 10000);
  385. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  386. const daemonPid = readLockPid(realRoot)!;
  387. expect(isAlive(daemonPid)).toBe(true);
  388. // Stay silent well past several backstop windows. The live session's peer is
  389. // provably alive, so the daemon must keep running (and never log a backstop
  390. // shutdown), with its lockfile intact.
  391. await new Promise((r) => setTimeout(r, 4000)); // > 3× maxIdle
  392. expect(isAlive(daemonPid)).toBe(true);
  393. expect(readDaemonLog(realRoot)).not.toContain('inactivity backstop');
  394. expect(readLockPid(realRoot)).toBe(daemonPid);
  395. }, 30000);
  396. it('daemon idle-times-out after the last client disconnects', async () => {
  397. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '800', CODEGRAPH_PPID_POLL_MS: '200' };
  398. const server = spawnServer(tempDir, env);
  399. servers.push(server);
  400. sendInitialize(server.child, `file://${tempDir}`, 1);
  401. await waitFor(() => findResponse(server.stdout, 1), 10000);
  402. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000);
  403. const daemonPid = readLockPid(realRoot)!;
  404. // Close the only client's stdin → proxy exits → daemon refcount hits 0 →
  405. // idle timer fires → daemon exits and cleans up its lockfile.
  406. server.child.stdin.end();
  407. expect(await waitProcessExit(daemonPid, 10000)).toBe(true);
  408. expect(fs.existsSync(path.join(realRoot, '.codegraph', 'daemon.pid'))).toBe(false);
  409. }, 30000);
  410. it('proxy survives the daemon dying mid-session and keeps serving (#662)', async () => {
  411. // The #662 scenario: an MCP host SIGTERM's the shared daemon while a session
  412. // is live. The proxy must NOT exit (losing CodeGraph for that session) — it
  413. // falls back to an in-process engine and keeps answering.
  414. const env = { CODEGRAPH_DAEMON_IDLE_TIMEOUT_MS: '30000', CODEGRAPH_PPID_POLL_MS: '5000' };
  415. const server = spawnServer(tempDir, env);
  416. servers.push(server);
  417. sendInitialize(server.child, `file://${tempDir}`, 1);
  418. await waitFor(() => findResponse(server.stdout, 1), 20000, 25, 'initialize response');
  419. await waitFor(() => server.stderr.some((l) => l.includes('Attached to shared daemon')), 8000, 25, 'daemon attach log');
  420. await waitFor(() => (readLockPid(realRoot) ?? 0) > 0, 8000, 25, 'daemon pidfile');
  421. const daemonPid = readLockPid(realRoot)!;
  422. // A warm call goes through the daemon.
  423. sendMessage(server.child, { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
  424. try {
  425. await waitFor(() => findResponse(server.stdout, 2), 30000, 25, 'warm tools/call via daemon');
  426. } catch (e) {
  427. // This is the wait that historically flaked — surface WHERE the request
  428. // died: proxy side (stderr) or daemon side (daemon.log).
  429. let daemonLog = '<no daemon.log>';
  430. try { daemonLog = fs.readFileSync(path.join(realRoot, '.codegraph', 'daemon.log'), 'utf8').split('\n').slice(-25).join('\n'); } catch { /* absent */ }
  431. throw new Error(
  432. `${(e as Error).message}\ndaemonAlive=${isAlive(daemonPid)} proxyAlive=${isAlive(server.child.pid!)}\n` +
  433. `--- proxy stderr tail ---\n${server.stderr.slice(-15).join('')}\n--- daemon.log tail ---\n${daemonLog}`
  434. );
  435. }
  436. // Kill the daemon out from under the live proxy.
  437. process.kill(daemonPid, 'SIGTERM');
  438. expect(await waitProcessExit(daemonPid, 8000)).toBe(true);
  439. // The proxy must still be alive and still answer — served in-process now.
  440. expect(isAlive(server.child.pid!)).toBe(true);
  441. await waitFor(() => server.stderr.some((l) => l.includes('serving this session in-process')), 8000, 25, 'in-process failover log');
  442. sendMessage(server.child, { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'codegraph_status', arguments: {} } });
  443. const resp = await waitFor(() => findResponse(server.stdout, 3), 15000);
  444. expect(resp.result !== undefined || resp.error !== undefined).toBe(true);
  445. expect(isAlive(server.child.pid!)).toBe(true);
  446. }, 45000);
  447. });