* 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
()
| 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 |
no test coverage detected