* 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
()
| 400 | * and reaps itself via client-refcount + idle timeout (see {@link Daemon}). |
| 401 | */ |
| 402 | private async startDaemonProcess(): Promise<void> { |
| 403 | // In daemon mode stderr IS `.codegraph/daemon.log`; stamp every line so |
| 404 | // kills/restarts can be placed in time (#1431 — the log was undatable). |
| 405 | timestampStderrLines(); |
| 406 | const root = resolveDaemonRoot(this.projectPath) ?? this.projectPath ?? process.cwd(); |
| 407 | for (let attempt = 0; attempt < TAKEOVER_MAX_RETRIES; attempt++) { |
| 408 | const lock = tryAcquireDaemonLock(root); |
| 409 | |
| 410 | if (lock.kind === 'acquired') { |
| 411 | const daemon = new Daemon(root); |
| 412 | await daemon.start(); |
| 413 | this.daemon = daemon; |
| 414 | this.mode = 'daemon'; |
| 415 | // The detached daemon has no PPID watchdog or stdin lifeline, so a |
| 416 | // wedged main thread would pin a core forever (#850). The liveness |
| 417 | // watchdog is its only recovery path. |
| 418 | this.livenessWatchdog = installMainThreadWatchdog(watchdogProgressPaths(root)); |
| 419 | return; // the net.Server keeps the process alive |
| 420 | } |
| 421 | |
| 422 | // Taken. If the holder is alive, another daemon already serves (or is |
| 423 | // binding) — we're redundant; exit cleanly so the launcher proxies to it. |
| 424 | const existing = lock.existing; |
| 425 | if (existing && existing.pid > 0 && isProcessAlive(existing.pid)) { |
| 426 | process.stderr.write( |
| 427 | `[CodeGraph daemon] Another daemon (pid ${existing.pid}) already holds the lock; exiting.\n` |
| 428 | ); |
| 429 | process.exit(0); |
| 430 | } |
| 431 | |
| 432 | // Holder is dead (or the record is unreadable) — clear it (pid-verified, |
| 433 | // so we never delete a live daemon's lock) and retry the acquire. |
| 434 | clearStaleDaemonLock(lock.pidPath, existing?.pid); |
| 435 | await sleep(TAKEOVER_RETRY_DELAY_MS); |
| 436 | } |
| 437 | |
| 438 | process.stderr.write('[CodeGraph daemon] Could not acquire the daemon lock; exiting.\n'); |
| 439 | process.exit(0); |
| 440 | } |
| 441 | |
| 442 | /** |
| 443 | * Proxy mode (the common case). Serve the MCP handshake LOCALLY for instant |
no test coverage detected