1
0

mcp-daemon.test.ts 21 KB

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