(projectRoot: string)
| 718 | * drive that's strictly better than the daemon never starting at all. |
| 719 | */ |
| 720 | export function tryAcquireDaemonLock(projectRoot: string): AcquireResult { |
| 721 | const pidPath = getDaemonPidPath(projectRoot); |
| 722 | // Make sure the .codegraph/ directory exists — the daemon may be the first |
| 723 | // thing to touch it on a fresh-clone-but-already-initialized checkout. |
| 724 | fs.mkdirSync(path.dirname(pidPath), { recursive: true }); |
| 725 | |
| 726 | const info: DaemonLockInfo = { |
| 727 | pid: process.pid, |
| 728 | version: CodeGraphPackageVersion, |
| 729 | socketPath: getDaemonSocketPath(projectRoot), |
| 730 | startedAt: Date.now(), |
| 731 | }; |
| 732 | |
| 733 | // Temp name is pid-scoped so racing candidates never collide on it. |
| 734 | const tmp = `${pidPath}.${process.pid}.tmp`; |
| 735 | let acquired = false; |
| 736 | try { |
| 737 | fs.writeFileSync(tmp, encodeLockInfo(info), { mode: 0o600 }); |
| 738 | try { |
| 739 | fs.linkSync(tmp, pidPath); // atomic + exclusive (race-free; see must-fix 1) |
| 740 | acquired = true; |
| 741 | } catch (err: unknown) { |
| 742 | if ((err as NodeJS.ErrnoException).code === 'EEXIST') { |
| 743 | // Lost the race — another candidate already holds it. Fall through to read. |
| 744 | } else { |
| 745 | // link() failed for a non-conflict reason — nearly always "this filesystem |
| 746 | // has no hard links" (ExFAT/FAT external volumes, some network mounts), |
| 747 | // which surfaces as a DIFFERENT errno on every OS: ENOTSUP on macOS, EPERM |
| 748 | // on Linux, EISDIR on Windows (#997). Enumerating them is whack-a-mole and |
| 749 | // unnecessary: the `tmp` write above already proved this directory is |
| 750 | // writable, so an O_EXCL create is a valid atomic+exclusive substitute. If |
| 751 | // IT fails too, that's a genuine error and propagates. EEXIST ⇒ taken. |
| 752 | acquired = acquireLockViaExclusiveOpen(pidPath, info); |
| 753 | } |
| 754 | } |
| 755 | } finally { |
| 756 | try { fs.unlinkSync(tmp); } catch { /* temp already gone */ } |
| 757 | } |
| 758 | |
| 759 | if (acquired) return { kind: 'acquired', pidPath, info }; |
| 760 | |
| 761 | // Taken. Because the pidfile was link'd atomically it always holds a complete |
| 762 | // record — `existing` is null only for a genuinely corrupt leftover, never a |
| 763 | // mid-write race. |
| 764 | let existing: DaemonLockInfo | null = null; |
| 765 | let lockContents: string | null = null; |
| 766 | try { |
| 767 | lockContents = fs.readFileSync(pidPath, 'utf8'); |
| 768 | existing = decodeLockInfo(lockContents); |
| 769 | } catch { /* unreadable lockfile — treat as malformed */ } |
| 770 | return { kind: 'taken', existing, lockContents, pidPath }; |
| 771 | } |
| 772 | |
| 773 | /** |
| 774 | * Exclusive-create the pidfile (O_CREAT|O_EXCL via the `wx` flag) and write the |
no test coverage detected