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