MCPcopy Create free account
hub / github.com/colbymchenry/codegraph / startDaemonProcess

Method startDaemonProcess

src/mcp/index.ts:361–396  ·  view source on GitHub ↗

* Run as the detached shared daemon (process spawned with * `CODEGRAPH_DAEMON_INTERNAL=1`). Arbitrate the O_EXCL lock, then either * become the daemon (bind the socket, serve forever) or — if a live daemon * already holds the lock — exit so we don't leak a redundant process. * * No PP

()

Source from the content-addressed store, hash-verified

359 * and reaps itself via client-refcount + idle timeout (see {@link Daemon}).
360 */
361 private async startDaemonProcess(): Promise<void> {
362 const root = resolveDaemonRoot(this.projectPath) ?? this.projectPath ?? process.cwd();
363 for (let attempt = 0; attempt < TAKEOVER_MAX_RETRIES; attempt++) {
364 const lock = tryAcquireDaemonLock(root);
365
366 if (lock.kind === 'acquired') {
367 const daemon = new Daemon(root);
368 await daemon.start();
369 this.daemon = daemon;
370 this.mode = 'daemon';
371 // The detached daemon has no PPID watchdog or stdin lifeline, so a
372 // wedged main thread would pin a core forever (#850). The liveness
373 // watchdog is its only recovery path.
374 this.livenessWatchdog = installMainThreadWatchdog();
375 return; // the net.Server keeps the process alive
376 }
377
378 // Taken. If the holder is alive, another daemon already serves (or is
379 // binding) — we're redundant; exit cleanly so the launcher proxies to it.
380 const existing = lock.existing;
381 if (existing && existing.pid > 0 && isProcessAlive(existing.pid)) {
382 process.stderr.write(
383 `[CodeGraph daemon] Another daemon (pid ${existing.pid}) already holds the lock; exiting.\n`
384 );
385 process.exit(0);
386 }
387
388 // Holder is dead (or the record is unreadable) — clear it (pid-verified,
389 // so we never delete a live daemon's lock) and retry the acquire.
390 clearStaleDaemonLock(lock.pidPath, existing?.pid);
391 await sleep(TAKEOVER_RETRY_DELAY_MS);
392 }
393
394 process.stderr.write('[CodeGraph daemon] Could not acquire the daemon lock; exiting.\n');
395 process.exit(0);
396 }
397
398 /**
399 * Proxy mode (the common case). Serve the MCP handshake LOCALLY for instant

Callers 1

startMethod · 0.95

Calls 8

startMethod · 0.95
tryAcquireDaemonLockFunction · 0.90
isProcessAliveFunction · 0.90
clearStaleDaemonLockFunction · 0.90
resolveDaemonRootFunction · 0.85
sleepFunction · 0.70
writeMethod · 0.45

Tested by

no test coverage detected