Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
fix(open-knowledge): duplicate server per contentDir — hold server.lock until process exit, fail closed on live pids (#2438)
mike-inkeep004aee35e03a
diff --git a/.changeset/duplicate-server-teardown-race.md b/.changeset/duplicate-server-teardown-race.mdnew file mode 100644index 000000000..ff5e3cd7d--- /dev/null+++ b/.changeset/duplicate-server-teardown-race.md@@ -0,0 +1,20 @@+---+"@inkeep/open-knowledge": patch+---++Fix duplicate servers per project during teardown/restart windows. Previously a+server released its `server.lock` seconds before its process actually exited+(and, after an idle shutdown, sometimes never exited at all), so restart flows —+desktop relaunch, auto-update, MCP auto-start — could spawn a second server+alongside a still-live predecessor, losing in-app threads and splitting writes+from the preview. The lock now stays owned (marked `draining`) until the process+truly exits; spawners wait out a draining predecessor instead of racing it; the+desktop waits for process death rather than lock disappearance before+respawning; and idle shutdown now exits the process explicitly, logging any+leaked handles that previously produced immortal zombie servers. Lock identity+also moved from the OS hostname (which macOS renames on network changes) to a+stable per-machine ID at `~/.ok/machine-id` — a hostname rename no longer lets a+new server silently steal a live server's lock; ambiguous cases now fail closed+with a clear "already running" error. When the desktop can't open a project+because a conflicting server holds its lock, the error dialog now offers+"Stop Server & Retry" to resolve it in one click.diff --git a/packages/app/src/components/NavigatorApp.dom.test.tsx b/packages/app/src/components/NavigatorApp.dom.test.tsxindex c7d450c5e..2d3e27d90 100644--- a/packages/app/src/components/NavigatorApp.dom.test.tsx+++ b/packages/app/src/components/NavigatorApp.dom.test.tsx@@ -201,6 +201,39 @@ describe('NavigatorApp launcher runtime behavior', () => {});});+ test('shows the "Opening…" overlay while a project open is in flight, then clears it', async () => {+ const bridge = createBridge();+ // Defer the open so the overlay is observable mid-flight — this mirrors+ // production, where `project.open` stays pending through the whole+ // main-side spawn + lock-poll (and the Stop-Server-Retry path).+ let resolveOpen: (() => void) | undefined;+ bridge.project.open = mock(+ () =>+ new Promise<void>((resolve) => {+ resolveOpen = resolve;+ }),+ );+ await renderNavigator(bridge);++ expect(screen.queryByTestId('nav-opening-overlay')).toBeNull();+ fireEvent.click(await screen.findByText('Recent Project'));++ const overlay = await screen.findByTestId('nav-opening-overlay');+ // Label is the path's last segment, not the full path.+ expect(overlay.textContent).toContain('Opening recent');+ expect(overlay.getAttribute('role')).toBe('status');++ // Failure-path parity: the main-side wrapper swallows errors and resolves+ // the invoke, so the overlay must clear on resolution (on the success path+ // main closes this window instead).+ act(() => {+ resolveOpen?.();+ });+ await waitFor(() => {+ expect(screen.queryByTestId('nav-opening-overlay')).toBeNull();+ });+ });+test('labels a linked-worktree recent with its branch over its base project, leaving plain projects unchanged', async () => {const bridge = createBridge();bridge.project.listRecent = mock(() =>diff --git a/packages/app/src/components/NavigatorApp.test.ts b/packages/app/src/components/NavigatorApp.test.tsindex 09c88d3d8..357b49e37 100644--- a/packages/app/src/components/NavigatorApp.test.ts+++ b/packages/app/src/components/NavigatorApp.test.ts@@ -255,4 +255,14 @@ describe('NavigatorApp error-state helpers', () => {afterAwait = true;expect(afterAwait).toBe(true);});++ test('displayNameForPath returns the last path segment for the Opening… overlay', async () => {+ const { displayNameForPath } = await import('./NavigatorApp');+ expect(displayNameForPath('/Users/me/Documents/oktest')).toBe('oktest');+ expect(displayNameForPath('/Users/me/Documents/oktest/')).toBe('oktest');+ expect(displayNameForPath('C:\\Users\\me\\oktest')).toBe('oktest');+ // Separator-less / root inputs fall back to the whole string.+ expect(displayNameForPath('oktest')).toBe('oktest');+ expect(displayNameForPath('/')).toBe('/');+ });});diff --git a/packages/app/src/components/NavigatorApp.tsx b/packages/app/src/components/NavigatorApp.tsxindex a8fecd628..f70614239 100644--- a/packages/app/src/components/NavigatorApp.tsx+++ b/packages/app/src/components/NavigatorApp.tsx@@ -77,6 +77,12 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {const [recentBranches, setRecentBranches] = useState<Map<string, string | null>>(new Map());const [loading, setLoading] = useState(true);const [error, setError] = useState<string | null>(null);+ // Non-null while a project open is in flight. `bridge.project.open` stays+ // pending for the entire main-side flow — server spawn, the up-to-15s lock+ // poll, and (on the collision path) the "Stop Server & Retry" kill ++ // respawn — so one flag covers every silent wait with no extra IPC. Holds+ // the display label for the overlay message.+ const [openingLabel, setOpeningLabel] = useState<string | null>(null);const [cloneDialogOpen, setCloneDialogOpen] = useState(false);const [createDialogOpen, setCreateDialogOpen] = useState(false);const [authModalOpen, setAuthModalOpen] = useState(false);@@ -191,21 +197,35 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {const runWithErrorState = (fn: () => Promise<void>, fallback: string) =>runWithErrorStatePure(fn, fallback, setError);+ // Open a project with the full-window "Opening…" overlay held for the whole+ // main-side flow. On success main closes this Navigator window (the overlay+ // vanishes with it); on failure `openProjectOrFallbackToNavigator` shows its+ // own dialog and resolves the invoke, so the `finally` restores the+ // interactive Navigator. `label` is the human name shown in the overlay.+ // `.finally()` (a method call), NOT try/finally — the React Compiler's+ // Babel lowering can't handle a TryStatement without a catch clause and+ // fails the production build (typecheck + bun test don't run the compiler,+ // so this only surfaces at build time).+ const openWithIndicator = (path: string, entryPoint: OkProjectEntryPoint, label: string) =>+ runWithErrorState(() => {+ setOpeningLabel(label);+ return openProject(bridge, path, entryPoint).finally(() => setOpeningLabel(null));+ }, t`Failed to open project.`);+const onClone = () => setCloneDialogOpen(true);const onOpenFolder = () =>runWithErrorState(async () => {const path = await bridge.dialog.openFolder();if (!path) return;- await openProject(bridge, path, 'pick-existing');+ setOpeningLabel(displayNameForPath(path));+ await openProject(bridge, path, 'pick-existing').finally(() => setOpeningLabel(null));}, t`Failed to open folder.`);const onCreate = () => setCreateDialogOpen(true);const onOpenRecent = (path: string) =>- runWithErrorState(async () => {- await openProject(bridge, path, 'recents');- }, t`Failed to open project.`);+ openWithIndicator(path, 'recents', displayNameForPath(path));const onRemoveRecent = (path: string) =>runWithErrorState(async () => {@@ -254,6 +274,17 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {data-electron-drag={isElectronHost ? '' : undefined}data-testid="nav-chrome-row"/>+ {openingLabel !== null ? (+ <div+ className="absolute inset-0 z-20 flex flex-col items-center justify-center gap-3 bg-primary-foreground/85 dark:bg-background/85 backdrop-blur-sm"+ data-testid="nav-opening-overlay"+ role="status"+ aria-live="polite"+ >+ <Loader2Icon className="size-6 animate-spin text-muted-foreground" />+ <p className="text-muted-foreground text-sm">{t`Opening ${openingLabel}…`}</p>+ </div>+ ) : null}<div className="mx-auto flex h-full w-full max-w-5xl flex-col overflow-hidden px-12 py-12"><div className="my-auto flex min-h-0 flex-col space-y-10"><header className="shrink-0 flex-wrap flex items-center gap-2.5">@@ -410,10 +441,10 @@ export function NavigatorApp({ bridge }: { bridge: OkDesktopBridge }) {// lands like a freshly-picked existing folder, so the consent// dialog gate is the right surface for the user to review scope// before scaffolding.- void runWithErrorState(- () => openProject(bridge, dir, 'pick-existing'),- t`Failed to open cloned project.`,- );+ void runWithErrorState(() => {+ setOpeningLabel(displayNameForPath(dir));+ return openProject(bridge, dir, 'pick-existing').finally(() => setOpeningLabel(null));+ }, t`Failed to open cloned project.`);}}/>@@ -562,3 +593,13 @@ async function openProject(): Promise<void> {await bridge.project.open({ path, target: 'new-window', entryPoint });}++/**+ * Human-readable project name for the "Opening…" overlay — the last path+ * segment (works for both `/` and `\` separators), falling back to the full+ * path for a root or separator-less input.+ */+export function displayNameForPath(path: string): string {+ const segments = path.split(/[/\\]/).filter(Boolean);+ return segments.length > 0 ? (segments[segments.length - 1] ?? path) : path;+}diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex ac1def4a7..653912b15 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -2113,6 +2113,7 @@"s061i4": ["Relative path"],"s0IDhW": ["This file could not be found."],"s0J_k9": [["0", "plural", { "one": ["#", " key"], "other": ["#", " keys"] }]],+ "s0_GnA": ["Opening ", ["openingLabel"], "…"],"s1c0ja": ["Bullet List"],"s3caR3": ["Deleting"],"sE7R19": [diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex 7ff1663db..c36ca60b7 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -4849,6 +4849,10 @@ msgstr "Open worktree"msgid "Open, navigate, accept, or dismiss CodeMirror completion suggestions."msgstr "Open, navigate, accept, or dismiss CodeMirror completion suggestions."+#: src/components/NavigatorApp.tsx+msgid "Opening {openingLabel}…"+msgstr "Opening {openingLabel}…"+#: src/components/ShareReceiveDialog.tsxmsgid "Opening..."msgstr "Opening..."diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 7be9f4e30..9619fa878 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -2113,6 +2113,7 @@"s061i4": ["Ŕēĺàţĩvē ƥàţĥ"],"s0IDhW": ["Ţĥĩś ƒĩĺē ćōũĺď ńōţ ƀē ƒōũńď."],"s0J_k9": [["0", "plural", { "one": ["#", " ķēŷ"], "other": ["#", " ķēŷś"] }]],+ "s0_GnA": ["Ōƥēńĩńĝ ", ["openingLabel"], "…"],"s1c0ja": ["ßũĺĺēţ Ĺĩśţ"],"s3caR3": ["Ďēĺēţĩńĝ"],"sE7R19": [diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 9eedaeab8..efc3410b3 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -4844,6 +4844,10 @@ msgstr ""msgid "Open, navigate, accept, or dismiss CodeMirror completion suggestions."msgstr ""+#: src/components/NavigatorApp.tsx+msgid "Opening {openingLabel}…"+msgstr ""+#: src/components/ShareReceiveDialog.tsxmsgid "Opening..."msgstr ""diff --git a/packages/app/tests/integration/idle-shutdown-multi-client.test.ts b/packages/app/tests/integration/idle-shutdown-multi-client.test.tsindex a4e29becd..987727a2a 100644--- a/packages/app/tests/integration/idle-shutdown-multi-client.test.ts+++ b/packages/app/tests/integration/idle-shutdown-multi-client.test.ts@@ -2,11 +2,20 @@* Server lifetime follows connected WebSocket clients, not the process that* launched the server. One remaining sibling client keeps the lock* alive past the idle window; after the last client disconnects, idle-shutdown- * releases the lock.+ * tears the server down and marks the lock draining (the unlink itself is+ * deferred to process exit).*/import { afterAll, beforeAll, expect, test } from 'bun:test';-import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ rmSync,+ writeFileSync,+} from 'node:fs';import { tmpdir } from 'node:os';import { join, resolve } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';@@ -102,23 +111,39 @@ test('closing spawning editor leaves sibling editor connected; idle-shutdown firexpect(providerB.isSynced).toBe(true);// Now editor B disconnects — counter goes to zero, idle-shutdown schedules,- // and the server tears down within the configured window.+ // and the server tears down within the configured window. Teardown no+ // longer unlinks the lock (that is deferred to actual process exit, which a+ // same-process test can't observe); the observable teardown signal is the+ // `draining` flag flipping on.providerB.destroy();yDocB.destroy();+ const readDraining = (): boolean => {+ try {+ const parsed = JSON.parse(readFileSync(lockPath, 'utf-8')) as { draining?: boolean };+ return parsed.draining === true;+ } catch {+ return false;+ }+ };const deadline = Date.now() + 5_000;- while (existsSync(lockPath) && Date.now() < deadline) {+ while (!readDraining() && Date.now() < deadline) {await wait(25);}- expect(existsSync(lockPath)).toBe(false);+ expect(readDraining()).toBe(true);// Regression guard: idle-shutdown must run the FULL destroy chain, not just// destroyHocuspocus(). Pre-fix, the lock file release above passed (Hocuspocus// releases it directly) while httpServer.listening stayed true, leaving a// zombie listener that survived for the lifetime of the parent process.// `boot.ts`'s destroy() runs httpServer.close() before destroyHocuspocus(),- // so by the time the lock is gone the listener is gone too — no extra wait- // needed. boot.test.ts has a faster spot-test for this but is skipped on CI- // (oven-sh/bun#11892); this assertion is the CI-side guard.+ // so by the time the lock is draining the listener teardown is in the same+ // chain — poll it to completion. boot.test.ts has a faster spot-test for+ // this but is skipped on CI (oven-sh/bun#11892); this assertion is the+ // CI-side guard.+ const listenDeadline = Date.now() + 5_000;+ while (server.httpServer.listening && Date.now() < listenDeadline) {+ await wait(25);+ }expect(server.httpServer.listening).toBe(false);});diff --git a/packages/cli/src/commands/lock-state.ts b/packages/cli/src/commands/lock-state.tsindex e25b842ec..f849a6de6 100644--- a/packages/cli/src/commands/lock-state.ts+++ b/packages/cli/src/commands/lock-state.ts@@ -11,6 +11,7 @@import { existsSync, readFileSync } from 'node:fs';import { hostname } from 'node:os';import {+ getMachineId,isProcessAlive,isValidLockPid,type LockName,@@ -30,6 +31,8 @@ interface InspectLockOptions {isAlive?: (pid: number) => boolean;/** Override for tests. Defaults to `os.hostname()`. */host?: string;+ /** Override for tests. Defaults to `getMachineId()` from the server package. */+ machineId?: string;}export function inspectLock(@@ -70,6 +73,15 @@ export function inspectLock(if (!aliveProbe(lock.pid)) {return { status: 'dead-pid', lockPath, lock };}+ // Machine identity first: a lock stamped with this machine's stable ID is+ // `alive` even when the recorded hostname has since drifted (the drift+ // class the comment above describes). Hostname comparison survives only+ // for legacy locks written by binaries that predate `machineId`.+ if (typeof lock.machineId === 'string') {+ return lock.machineId === (opts.machineId ?? getMachineId())+ ? { status: 'alive', lockPath, lock }+ : { status: 'foreign-host', lockPath, lock };+ }const localHost = opts.host ?? hostname();if (lock.hostname !== localHost) {return { status: 'foreign-host', lockPath, lock };diff --git a/packages/cli/src/commands/start.test.ts b/packages/cli/src/commands/start.test.tsindex 8f0bb7b50..7ee52e3c7 100644--- a/packages/cli/src/commands/start.test.ts+++ b/packages/cli/src/commands/start.test.ts@@ -29,6 +29,7 @@ import {tryDescribeLockCollision,type UiSpawnDecision,withEphemeralTempDirReap,+ withIdleShutdownProcessExit,} from './start.ts';import { closeHttpServers, startUiServer, type UiServerHandle } from './ui.ts';@@ -505,6 +506,87 @@ describe('shouldConnectToExistingServer (main-checkout connect guard)', () => {expect(shouldConnectToExistingServer(39848, null)).toBe(false);expect(shouldConnectToExistingServer(39848, { port: 0 })).toBe(false);});+ test('false for a draining server (teardown in progress — boot path waits it out)', () => {+ expect(shouldConnectToExistingServer(39848, { port: 49530, draining: true })).toBe(false);+ });+});++describe('withIdleShutdownProcessExit (idle-path zombie prevention)', () => {+ test('exits 0 after the handler completes, logging an open-handle summary', async () => {+ const order: string[] = [];+ const logged: object[] = [];+ let exitCode: number | undefined;+ const wrapped = withIdleShutdownProcessExit(+ async () => {+ order.push('handler');+ },+ {+ log: {+ info: (obj) => {+ logged.push(obj);+ },+ error: () => {},+ },+ exit: (code) => {+ order.push('exit');+ exitCode = code;+ },+ getActiveHandles: () => [new (class Socket {})(), new (class Socket {})(), null],+ },+ );+ await wrapped();+ expect(order).toEqual(['handler', 'exit']);+ expect(exitCode).toBe(0);+ const event = logged.find((o) => (o as { event?: string }).event === 'idle-shutdown-exit') as+ | { openHandles: Record<string, number> }+ | undefined;+ expect(event).toBeDefined();+ expect(event?.openHandles.Socket).toBe(2);+ });++ test('reports handlesAvailable: false when the runtime cannot enumerate handles (Bun)', async () => {+ // Bun lacks process._getActiveHandles — the production path. The exit+ // must still fire, and the log must mark the empty summary as a data+ // gap rather than a clean state.+ const logged: object[] = [];+ let exitCode: number | undefined;+ const wrapped = withIdleShutdownProcessExit(async () => {}, {+ log: {+ info: (obj) => {+ logged.push(obj);+ },+ error: () => {},+ },+ exit: (code) => {+ exitCode = code;+ },+ getActiveHandles: () => null,+ });+ await wrapped();+ expect(exitCode).toBe(0);+ const event = logged.find((o) => (o as { event?: string }).event === 'idle-shutdown-exit') as+ | { openHandles: Record<string, number>; handlesAvailable: boolean }+ | undefined;+ expect(event?.handlesAvailable).toBe(false);+ expect(event?.openHandles).toEqual({});+ });++ test('exits 1 when the handler throws — a failed teardown must not zombify', async () => {+ let exitCode: number | undefined;+ const wrapped = withIdleShutdownProcessExit(+ async () => {+ throw new Error('destroy blew up');+ },+ {+ exit: (code) => {+ exitCode = code;+ },+ getActiveHandles: () => [],+ },+ );+ await wrapped();+ expect(exitCode).toBe(1);+ });});describe('computeConnectExitCode (connect-sibling exit mapping)', () => {diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.tsindex b0cc74482..d19549f4e 100644--- a/packages/cli/src/commands/start.ts+++ b/packages/cli/src/commands/start.ts@@ -219,14 +219,22 @@ export function resolveCollabPort(* True only on the worktree-preview path (`--ui-port` set) when a live* `server.lock` exists for this folder — the main-checkout case, where booting* would collide and exit 1. Pure so this safety decision is unit-tested.- * (`readServerLock` already filters dead/cross-host locks, so a non-null- * `liveServer` with `port > 0` is a genuinely-live same-host server.)+ * (`readServerLock` already filters dead/cross-machine locks, so a non-null+ * `liveServer` with `port > 0` is a genuinely-live same-machine server —+ * unless it is `draining`, i.e. seconds from exit. Connecting to a draining+ * server would bind the preview to a dying backend, so fall through to the+ * boot path, whose drain-wait handles the handoff.)*/export function shouldConnectToExistingServer(requestedUiPort: number | undefined,- liveServer: { port: number } | null,+ liveServer: { port: number; draining?: boolean } | null,): boolean {- return requestedUiPort !== undefined && liveServer !== null && liveServer.port > 0;+ return (+ requestedUiPort !== undefined &&+ liveServer !== null &&+ liveServer.port > 0 &&+ liveServer.draining !== true+ );}/**@@ -453,6 +461,84 @@ export function withEphemeralTempDirReap(};}+/**+ * Wrap the idle-shutdown handler so the process EXITS once teardown+ * completes. Without this, exit relies on the event loop draining naturally —+ * and any handle the destroy sequence doesn't cover (a native watcher+ * subscription that didn't fully detach, a lingering pipe) leaves an+ * immortal zombie: a process that released its lock and closed its port+ * hours ago but still sits in memory holding the project's in-memory state.+ * The signal path already exits explicitly after destroy; this gives the+ * idle path the same discipline.+ *+ * Before exiting, log a bounded summary of still-open handles (constructor+ * names + counts via the undocumented-but-stable `process._getActiveHandles`)+ * so the leak class that WOULD have zombified gets named in the wild instead+ * of silently absorbed by the exit.+ *+ * Exit runs in `finally` — a throwing destroy must still terminate the+ * process (exit code 1), otherwise the zombie returns exactly when teardown+ * is least healthy.+ */+export function withIdleShutdownProcessExit(+ handler: () => Promise<void>,+ deps: {+ log?: { info: (obj: object, msg: string) => void; error: (obj: object, msg: string) => void };+ exit?: (code: number) => void;+ /** Return `null` when the runtime does not expose active handles (Bun). */+ getActiveHandles?: () => unknown[] | null;+ } = {},+): () => Promise<void> {+ const exit = deps.exit ?? ((code: number) => process.exit(code));+ const getActiveHandles =+ deps.getActiveHandles ??+ (() => {+ // Bun does not implement `_getActiveHandles` — report "unavailable"+ // (null) rather than an empty list, so an empty summary in the logs+ // is distinguishable from a runtime that simply can't see handles.+ const probe = (process as unknown as { _getActiveHandles?: () => unknown[] })+ ._getActiveHandles;+ return probe ? probe.call(process) : null;+ });+ return async () => {+ let failed = false;+ try {+ await handler();+ } catch (err) {+ failed = true;+ // Pass the Error object itself — pino's std serializer keeps the stack;+ // a pre-stringified message would drop it.+ deps.log?.error({ err }, 'idle-shutdown: destroy failed — exiting anyway');+ } finally {+ let handleSummary: Record<string, number> | null = null;+ try {+ const handles = getActiveHandles();+ if (handles !== null) {+ handleSummary = {};+ for (const handle of handles) {+ const name =+ (handle as { constructor?: { name?: string } } | null)?.constructor?.name ??+ 'unknown';+ handleSummary[name] = (handleSummary[name] ?? 0) + 1;+ }+ }+ } catch {+ handleSummary = null;+ }+ deps.log?.info(+ {+ event: 'idle-shutdown-exit',+ exitCode: failed ? 1 : 0,+ openHandles: handleSummary ?? {},+ handlesAvailable: handleSummary !== null,+ },+ 'idle-shutdown: teardown finished — exiting process',+ );+ exit(failed ? 1 : 0);+ }+ };+}+export function buildIdleShutdownHandler(input: BuildIdleShutdownHandlerInput,): () => Promise<void> {@@ -547,6 +633,13 @@ interface BootStartServerOptions {spawn?: typeof NativeSpawn;/** Override idle-shutdown threshold; default 30 min. Tests use small values. */idleThresholdMs?: number;+ /**+ * Override the process-exit call fired after an idle-shutdown teardown+ * completes (see `withIdleShutdownProcessExit`). Default `process.exit`.+ * Tests that drive idle-shutdown through `bootStartServer` MUST inject+ * this — the default would take down the test runner.+ */+ idleExit?: (code: number) => void;/*** Max wall-clock to wait for the auto-spawned `ok ui` to bind its port* (populated via `updateUiLockPort`). Default 3 000 ms — ample for a@@ -692,9 +785,15 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Booconst { existsSync, mkdirSync } = await import('node:fs');const { basename, dirname } = await import('node:path');- const { bootServer, getLogger, isProcessAlive, readUiLock, resolveContentDir } = await import(- '@inkeep/open-knowledge-server'- );+ const {+ bootServer,+ getLogger,+ isProcessAlive,+ readUiLock,+ resolveContentDir,+ resolveLockDir,+ waitForServerLockDrain,+ } = await import('@inkeep/open-knowledge-server');const log = opts.log ?? getLogger('start');@@ -859,6 +958,35 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boo// AND an agent opts a search into semantic.const embeddingsKeyStore = makeLazyEmbeddingsKeyStore();+ // A predecessor server mid-teardown holds its lock (marked draining) until+ // it actually exits. Racing it would collide loudly inside createServer, so+ // wait for the drain to finish first — restart flows (desktop respawn, MCP+ // auto-start, manual `ok start` right after closing a window) land here+ // within the predecessor's last seconds. On timeout we proceed anyway and+ // let the acquire collide: a wedged teardown should fail loud, not spawn a+ // duplicate.+ {+ const drainLockDir = resolveLockDir(ephemeral ? ephemeralProjectDir : cwd);+ const drainWaitStartedAt = Date.now();+ const drainOutcome = await waitForServerLockDrain(drainLockDir);+ if (drainOutcome !== 'no-drain') {+ // `waitedMs` is the tuning signal for the 10s drain timeout: released+ // durations creeping toward it mean real teardowns are outgrowing the+ // budget and would start colliding under normal load.+ log.info(+ {+ event: 'start-waited-for-draining-predecessor',+ outcome: drainOutcome,+ waitedMs: Date.now() - drainWaitStartedAt,+ drainLockDir,+ },+ drainOutcome === 'released'+ ? '[start] predecessor server finished draining — proceeding'+ : '[start] predecessor server still draining after wait — proceeding to collide',+ );+ }+ }+const booted: BootedServer = await bootServer({config,contentDir,@@ -906,7 +1034,10 @@ export async function bootStartServer(opts: BootStartServerOptions): Promise<Boodestroy: destroyServer,log,});- return ephemeral ? withEphemeralTempDirReap(handler, ephemeralProjectDir) : handler;+ const reaped = ephemeral ? withEphemeralTempDirReap(handler, ephemeralProjectDir) : handler;+ // Outermost: the exit fires only after destroy AND the ephemeral temp+ // dir reap have both run.+ return withIdleShutdownProcessExit(reaped, { log, exit: opts.idleExit });},log,// Single-origin opt-ins for desktop-spawned servers. Forwarded onlydiff --git a/packages/cli/src/mcp/shim.test.ts b/packages/cli/src/mcp/shim.test.tsindex 400d97f4e..feda70785 100644--- a/packages/cli/src/mcp/shim.test.ts+++ b/packages/cli/src/mcp/shim.test.ts@@ -84,6 +84,61 @@ describe('MCP stdio shim server resolution', () => {await rm(tmp, { recursive: true, force: true });});+ test('draining lock waits for the predecessor to exit, then spawns', async () => {+ const drainingLock: ServerLockMetadata = { ...liveLock, draining: true };+ let reads = 0;+ const calls: string[] = [];+ // Read sequence: initial check (draining) → 2 drain polls (draining) →+ // drain poll sees release (null) → post-drain re-check (null) → spawn →+ // spawn poll picks up the fresh child lock.+ const url = await resolveMcpHttpUrl({+ lockDir,+ contentDir: tmp,+ readLock: () => {+ reads += 1;+ if (reads <= 3) return drainingLock;+ if (reads <= 5) return null;+ return liveLock;+ },+ isAlive: () => true,+ sleep: async () => {},+ openErrorLog: () => 123,+ closeFd: () => {},+ spawn: ((cmd: string) => {+ calls.push(cmd);+ return { on: () => {}, unref: () => {} };+ }) as never,+ timeoutMs: 1000,+ pollIntervalMs: 1,+ });++ expect(url).toBe('http://127.0.0.1:4123/mcp');+ expect(calls).toHaveLength(1);+ });++ test('draining lock replaced by a fresh live server resolves WITHOUT spawning', async () => {+ const drainingLock: ServerLockMetadata = { ...liveLock, draining: true };+ const freshLock: ServerLockMetadata = { ...liveLock, pid: 5678, port: 4999 };+ let reads = 0;+ const url = await resolveMcpHttpUrl({+ lockDir,+ contentDir: tmp,+ readLock: () => {+ reads += 1;+ return reads <= 2 ? drainingLock : freshLock;+ },+ isAlive: () => true,+ sleep: async () => {},+ spawn: (() => {+ throw new Error('should not spawn — a fresh server appeared during the drain wait');+ }) as never,+ timeoutMs: 1000,+ pollIntervalMs: 1,+ });++ expect(url).toBe('http://127.0.0.1:4999/mcp');+ });+test('live lock resolves directly to the /mcp HTTP URL', async () => {const url = await resolveMcpHttpUrl({lockDir,diff --git a/packages/cli/src/mcp/shim.ts b/packages/cli/src/mcp/shim.tsindex 08e88d72f..714ea247d 100644--- a/packages/cli/src/mcp/shim.ts+++ b/packages/cli/src/mcp/shim.ts@@ -195,6 +195,9 @@ function livePortFromLock(isAlive: (pid: number) => boolean,): number | undefined {if (!lock || lock.port <= 0) return undefined;+ // A draining holder is tearing down: its HTTP surface closes before the+ // lock disappears, so the advertised port must never be dialed.+ if (lock.draining === true) return undefined;if (!isAlive(lock.pid)) return undefined;return lock.port;}@@ -260,7 +263,8 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promisereturn mcpUrlForPort(DEFAULT_SERVER_HOST, parsed);}- const existingPort = livePortFromLock(readLock(), isAlive);+ const initialLock = readLock();+ const existingPort = livePortFromLock(initialLock, isAlive);if (existingPort !== undefined) return mcpUrlForPort(DEFAULT_SERVER_HOST, existingPort);if (opts.envAutoStart === '0') {@@ -269,6 +273,35 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promise);}+ // A draining holder still owns the lock while it finishes exiting. Spawning+ // now would just collide with it; wait for the drain first (bounded to the+ // same timeout DURATION as the post-spawn poll below — the two phases have+ // independent deadlines, so the worst case is ≈2× timeoutMs total). If a+ // fresh server appears meanwhile — another spawner won the restart race —+ // use it directly.+ if (initialLock !== null && initialLock.draining === true && isAlive(initialLock.pid)) {+ const drainWaitStartedAt = Date.now();+ const drainDeadline = drainWaitStartedAt + timeoutMs;+ let drainTimedOut = true;+ while (Date.now() < drainDeadline) {+ const lock = readLock();+ if (lock === null || lock.draining !== true || !isAlive(lock.pid)) {+ drainTimedOut = false;+ break;+ }+ await sleep(pollIntervalMs);+ }+ // stderr, not stdout — stdout carries the MCP stdio protocol. Same tuning+ // signal as start.ts's start-waited-for-draining-predecessor event: waits+ // creeping toward the timeout mean teardowns are outgrowing the budget.+ console.error(+ `[mcp-shim] waited ${Date.now() - drainWaitStartedAt}ms for a draining predecessor server` ++ `${drainTimedOut ? ' (timed out — proceeding anyway)' : ''}`,+ );+ const portAfterDrain = livePortFromLock(readLock(), isAlive);+ if (portAfterDrain !== undefined) return mcpUrlForPort(DEFAULT_SERVER_HOST, portAfterDrain);+ }+if (!existsSync(opts.lockDir)) mkdirSync(opts.lockDir, { recursive: true });const stderrPath = join(opts.lockDir, SPAWN_ERROR_LOG);const stderrFd = openErrorLog(stderrPath);diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 22ada0ef7..38285e3fb 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -1791,6 +1791,61 @@ async function openProjectOrFallbackToNavigator(dialogTitle = 'OpenKnowledge is already running for this project';dialogBody = `${projectPath}\n\n${errorMessage}`;}+ // A spawn that timed out because a holder is in the way (fail-closed+ // collision — visible in the child's stderr tail), or a direct lock+ // collision, has a one-click remedy: stop the conflicting holder and+ // retry. Everything else keeps the plain error box.+ const holderInTheWay =+ kind === 'lock-collision' ||+ (kind === 'spawn-lock-timeout' && errorMessage.includes('already running'));+ if (holderInTheWay) {+ const { response } = await dialog.showMessageBox({+ type: 'warning',+ title: dialogTitle,+ message: dialogTitle,+ detail:+ `${dialogBody}\n\n` ++ `OpenKnowledge can stop the conflicting server process and retry opening the project.`,+ buttons: ['Stop Server & Retry', 'Cancel'],+ defaultId: 0,+ cancelId: 1,+ });+ if (response === 0) {+ ensureWindowManager();+ const stop = await wm.forceStopConflictingServer(projectPath);+ if (stop.ok) {+ try {+ // Single retry — a second failure falls through to the plain+ // error box rather than looping the dialog.+ await openProject(+ projectPath,+ entryPoint,+ pendingDeepLinkTarget,+ pendingBranch,+ pendingMultiCandidate,+ pendingShareBranchSwitch,+ pendingTargetMissing,+ );+ return;+ } catch (retryErr) {+ dialog.showErrorBox(+ 'Unable to open project',+ `${projectPath}\n\n${(retryErr as Error).message}`,+ );+ }+ } else {+ dialog.showErrorBox(+ 'Unable to open project',+ `${projectPath}\n\n` ++ (stop.reason === 'eperm'+ ? 'The conflicting server belongs to another user account and cannot be stopped from here. Quit it from that account and try again.'+ : 'Could not stop the conflicting server. Quit it manually (`ok stop`) and try again.'),+ );+ }+ }+ openNavigator();+ return;+ }dialog.showErrorBox(dialogTitle, dialogBody);openNavigator();}diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 4765cdbef..4fe18a1af 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -232,6 +232,17 @@ export interface ServerLockMetadataLike {*/protocolVersion?: number;runtimeVersion?: string;+ /**+ * Stable machine identity (see server package `machine-id.ts`). Locks that+ * carry it are machine-checked by `readServerLock` itself; absence means a+ * legacy lock where hostname comparison is the only provenance signal.+ */+ machineId?: string;+ /**+ * Holder has begun teardown but still owns the lock until process exit.+ * Draining locks are neither attachable nor a spawn-readiness signal.+ */+ draining?: boolean;}interface ProjectContext {@@ -921,7 +932,6 @@ export class WindowManager {signalStopOwnedUtilityForks(this.windowsByPath.values(), this.deps.log);// Detached-spawn pids — two-phase SIGTERM → poll → SIGKILL.- const readLock = this.deps.readServerLock;const stopOne = async (canonicalKey: string, pid: number): Promise<void> => {// The map key IS `realpathSync(resolve(projectPath))`, so the lock// directory is computable directly without depending on@@ -932,11 +942,9 @@ export class WindowManager {// This is the exact scenario the spec is designed for (MCP agents// writing while the editor window is closed).const projectPath = canonicalKey;- const lockDir = getLocalDir(projectPath);// SIGTERM first. `killProbe` (test-injectable wrapper around// `process.kill`) throws if the pid is already gone (ESRCH) — treat- // that as success (server already released the lock, we're done- // with this entry).+ // that as success (server already exited, we're done with this entry).try {this.deps.killProbe(pid, 'SIGTERM');} catch (err) {@@ -948,20 +956,16 @@ export class WindowManager {'SIGTERM failed during stopAllOwnedServers',);}- // Poll the lock for release. If `readServerLock` is not wired (back-- // compat for tests that don't exercise this path), skip the poll- // and proceed directly to SIGKILL — without a way to confirm release- // we can't know we should wait.- if (readLock) {+ // Poll for PROCESS death, not lock release. The lock disappears while+ // the process is still flushing telemetry/logs (and historically,+ // seconds before exit) — treating lock-gone as stopped is exactly the+ // window that let a relaunch spawn a duplicate alongside a live+ // predecessor. Pid death is the only signal that means "gone".+ {const graceMs = this.deps.sigtermGraceMs ?? DEFAULT_SIGTERM_GRACE_MS;const deadline = Date.now() + graceMs;while (Date.now() < deadline) {- const lock = readLock(lockDir);- if (lock === null || lock.pid !== pid) {- // Lock released (gone) OR taken over by a different pid —- // either way our SIGTERM target is no longer holding it.- return;- }+ if (!this.isPidAlive(pid)) return;await new Promise<void>((resolveSleep) => {this.deps.setTimeout(() => {resolveSleep();@@ -1072,6 +1076,23 @@ export class WindowManager {}}+ /**+ * Pid liveness probe for the SIGTERM grace polls. Prefers the injected+ * `isProcessAlive` (shared with attach validation); falls back to a+ * signal-0 `killProbe` so tests that wire only `killProbe` keep working.+ * EPERM means "exists but not signalable" — alive.+ */+ private isPidAlive(pid: number): boolean {+ const probe = this.deps.isProcessAlive;+ if (probe) return probe(pid);+ try {+ this.deps.killProbe(pid, 0);+ return true;+ } catch (err) {+ return (err as NodeJS.ErrnoException).code === 'EPERM';+ }+ }+/*** Terminate a server by pid using the same SIGTERM → grace-poll → SIGKILL* ladder as `stopAllOwnedServers`, but returning a caller-consumable outcome@@ -1083,10 +1104,9 @@ export class WindowManager {* `killProbe` / `readServerLock` / the poll interval with that path.*/private async terminateServerByPid(- lockDir: string,+ _lockDir: string,pid: number,): Promise<{ ok: true; escalated: boolean } | { ok: false; reason: 'eperm' | 'other' }> {- const readLock = this.deps.readServerLock;try {this.deps.killProbe(pid, 'SIGTERM');} catch (err) {@@ -1094,14 +1114,15 @@ export class WindowManager {if (code === 'ESRCH') return { ok: true, escalated: false };return { ok: false, reason: code === 'EPERM' ? 'eperm' : 'other' };}- if (readLock) {- // Restart-specific grace (shorter than the auto-update teardown). Test- // override via `sigtermGraceMs` still wins.+ {+ // Poll for PROCESS death, not lock release — lock-gone precedes exit+ // (see `stopAllOwnedServers`), and respawning inside that window is+ // the duplicate-server bug. Restart-specific grace (shorter than the+ // auto-update teardown). Test override via `sigtermGraceMs` still wins.const graceMs = this.deps.sigtermGraceMs ?? RESTART_SIGTERM_GRACE_MS;const deadline = Date.now() + graceMs;while (Date.now() < deadline) {- const lock = readLock(lockDir);- if (lock === null || lock.pid !== pid) return { ok: true, escalated: false };+ if (!this.isPidAlive(pid)) return { ok: true, escalated: false };await new Promise<void>((resolveSleep) => {this.deps.setTimeout(() => resolveSleep(), DEFAULT_SIGTERM_POLL_MS);});@@ -1117,6 +1138,50 @@ export class WindowManager {}}+ /**+ * Explicit-user-consent recovery: stop whatever process holds this+ * project's server.lock so a fresh open can proceed. Reached from the+ * "Unable to open project" dialog's "Stop Server & Retry" button after a+ * spawn collided with a holder that attach refused (foreign machineId+ * after a hostname flap on a legacy lock, a tampered lock file, a wedged+ * teardown that outlived the drain wait).+ *+ * Reads the RAW lock pid — deliberately bypassing `readServerLock`'s+ * machine-identity filter, because the defining feature of this state is+ * that identity checks refused the holder. Safe because it only runs on an+ * explicit user click, the pid is range-validated, and never targets our+ * own process. Uses the same SIGTERM → pid-death poll → SIGKILL ladder as+ * the restart path. The dead holder's lock file is left behind for+ * acquire-side dead-pid stale detection to replace on the retry.+ */+ async forceStopConflictingServer(+ projectPath: string,+ ): Promise<{ ok: true } | { ok: false; reason: 'eperm' | 'other' }> {+ const lockDir = getLocalDir(resolve(projectPath));+ let pid: unknown;+ try {+ pid = (JSON.parse(readFileSync(join(lockDir, 'server.lock'), 'utf-8')) as { pid?: unknown })+ ?.pid;+ } catch {+ // No lock / unreadable — nothing to stop; the retry will proceed.+ return { ok: true };+ }+ if (!isValidLockPidLocal(pid) || pid === process.pid) {+ return { ok: true };+ }+ const term = await this.terminateServerByPid(lockDir, pid);+ this.deps.log?.info(+ {+ event: 'desktop-force-stop-conflicting-server',+ pid,+ projectPath,+ outcome: term.ok ? 'stopped' : term.reason,+ },+ '[window-manager] force-stopped conflicting server holder on user request',+ );+ return term.ok ? { ok: true } : term;+ }+/*** Restart a project's server to match this app's version. Terminates the* attached (not-owned) server the window connected to, then recreates the@@ -2039,7 +2104,10 @@ export class WindowManager {const deadline = Date.now() + deadlineMs;while (Date.now() < deadline) {const lock = reader(lockDir);- if (lock !== null && lock.port > 0 && lock.kind !== undefined) {+ // A draining lock is the PREDECESSOR still exiting, not the fresh+ // spawn's readiness signal — keep polling until the successor's+ // (non-draining) lock appears.+ if (lock !== null && lock.draining !== true && lock.port > 0 && lock.kind !== undefined) {return lock;}await new Promise<void>((resolveSleep) => {@@ -2094,8 +2162,19 @@ export class WindowManager {return null;};if (!isValidLockPidLocal(lock.pid)) return refuse('invalid-lock-pid');- if (lock.hostname !== getHost()) return refuse('foreign-hostname');+ // Machine identity: locks carrying `machineId` were already machine-+ // checked inside `readServerLock` (machineId-first, hostname only as the+ // legacy fallback) — re-checking the hostname here would wrongly refuse+ // a same-machine lock written before a hostname drift/rename. Only+ // legacy locks (no machineId) still need the hostname comparison.+ if (lock.machineId === undefined && lock.hostname !== getHost()) {+ return refuse('foreign-hostname');+ }if (!alive(lock.pid)) return refuse('lock-pid-dead');+ // Draining = teardown began; the port closes before the process exits.+ // Attaching would bind the window to a dying backend — fall through to+ // spawn mode, whose `ok start` child waits out the drain.+ if (lock.draining === true) return refuse('lock-draining');if (lock.port <= 0) return refuse('lock-port-zero');if (lock.kind === undefined) return refuse('legacy-lock-no-kind');if (lock.capabilities !== undefined && !lock.capabilities.includes('ws')) {diff --git a/packages/desktop/tests/main/window-manager-ephemeral.test.ts b/packages/desktop/tests/main/window-manager-ephemeral.test.tsindex e60bf7dbb..aba1923c9 100644--- a/packages/desktop/tests/main/window-manager-ephemeral.test.ts+++ b/packages/desktop/tests/main/window-manager-ephemeral.test.ts@@ -100,8 +100,12 @@ function buildEphemeralEnv(): EphemeralEnv {const removedDirs: string[] = [];const effectLog: string[] = [];const killCalls: EphemeralEnv['killCalls'] = [];- // lockDir → live lock; the spawn stub publishes, killProbe(SIGTERM) releases.+ // lockDir → live lock; the spawn stub publishes. killProbe(SIGTERM) kills+ // the pid AND drops its lock — mirroring a real exit, where the unlink+ // happens in the dying process's exit handler. The teardown poll watches+ // pid death (not lock release), so liveness must track the kill.const locks = new Map<string, ServerLockMetadataLike>();+ const killedPids = new Set<number>();let tempCounter = 0;let pidCounter = 42000;@@ -141,12 +145,14 @@ function buildEphemeralEnv(): EphemeralEnv {killCalls.push({ pid, signal });if (signal === 'SIGTERM') {effectLog.push(`sigterm:${pid}`);- // Release every lock this pid holds (mirrors a graceful drain).+ killedPids.add(pid);+ // Release every lock this pid holds (mirrors process exit).for (const [dir, lock] of locks) {if (lock.pid === pid) locks.delete(dir);}}},+ isProcessAlive: (pid) => !killedPids.has(pid),readServerLock: (lockDir) => locks.get(lockDir) ?? null,showGate,createEphemeralProjectDir: (contentDir) => {diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex 171aef0d0..1702a3720 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -1,4 +1,7 @@import { beforeEach, describe, expect, mock, test } from 'bun:test';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';import type { ShowGateRegistry } from '../../src/main/show-gate.ts';import {@@ -781,6 +784,9 @@ describe('WindowManager', () => {});enableAttachProbe({readServerLock: () => (spawned ? freshLock : killed ? null : oldLock),+ // The terminate poll watches PID death (not lock release) — the old+ // server "exits" as soon as SIGTERM lands.+ isProcessAlive: (pid) => (pid === 5555 ? !killed : true),});env.deps.killProbe = killProbe;env.deps.spawnDetachedServer = async () => {@@ -840,7 +846,10 @@ describe('WindowManager', () => {env.deps.selfRuntimeVersion = '0.8.2';let killed = false;const oldLock = { ...liveLock, pid: 5555, protocolVersion: 1, runtimeVersion: '0.8.0' };- enableAttachProbe({ readServerLock: () => (killed ? null : oldLock) });+ enableAttachProbe({+ readServerLock: () => (killed ? null : oldLock),+ isProcessAlive: (pid) => (pid === 5555 ? !killed : true),+ });env.deps.killProbe = mock((_pid: number, signal: string) => {if (signal === 'SIGTERM') killed = true;});@@ -873,10 +882,14 @@ describe('WindowManager', () => {if (signal === 'SIGTERM') killed = true;});env.deps.killProbe = killProbe;- // Foreign lock at attach-decision time; gone right after SIGTERM so the- // terminate poll returns on its first check (the env setTimeout never- // fires, so a poll that had to sleep would hang the test).- enableAttachProbe({ readServerLock: () => (killed ? null : liveLock) });+ // Foreign lock at attach-decision time; the holder pid dies right after+ // SIGTERM so the terminate poll (pid-death, not lock release) returns on+ // its first check (the env setTimeout never fires, so a poll that had+ // to sleep would hang the test).+ enableAttachProbe({+ readServerLock: () => (killed ? null : liveLock),+ isProcessAlive: () => !killed,+ });const wm = new WindowManager(env.deps);const promise = wm.createProjectWindow({ projectPath: '/tmp/dragon' });@@ -1015,6 +1028,35 @@ describe('WindowManager', () => {await p;});+ test('draining lock (teardown in progress) falls through to spawn mode', async () => {+ enableAttachProbe({+ readServerLock: () => ({ ...liveLock, draining: true }),+ });++ const wm = new WindowManager(env.deps);+ const p = wm.createProjectWindow({ projectPath: '/tmp/dragon' });+ await new Promise((r) => setTimeout(r, 5));+ expect(env.utilities.length).toBe(1);+ env.utilities[0]?.fire({ type: 'ready', port: 40005, apiOrigin: 'http://localhost:40005' });+ await p;+ });++ test('machineId-carrying lock with a drifted hostname still attaches', async () => {+ // readServerLock (production) already machine-checked a lock that+ // carries machineId; the window-manager's own hostname gate must not+ // re-refuse it after a macOS hostname rename.+ enableAttachProbe({+ readServerLock: () => ({ ...liveLock, machineId: 'stable-machine-id' }),+ hostname: () => 'renamed-since-lock-was-written',+ });++ const wm = new WindowManager(env.deps);+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/dragon' });+ expect(env.utilities.length).toBe(0);+ expect(ctx.ownsServer).toBe(false);+ expect(ctx.port).toBe(59534);+ });+test('foreign-host lock falls through (D44 case c)', async () => {enableAttachProbe({ hostname: () => 'different-host' });@@ -1258,6 +1300,41 @@ describe('WindowManager', () => {expect(env.utilities.length).toBe(0);});+ test('spawn-poll skips a draining predecessor lock and connects to the fresh spawn', async () => {+ enableSyncTimers();+ // Restart window: the dying predecessor still holds its lock (marked+ // draining — the file survives until its process exits). The attach+ // gate must refuse it, and the spawn-readiness poll must NOT mistake+ // it for the fresh spawn's lock — only the successor's non-draining+ // lock is the readiness signal.+ const drainingPredecessor: ServerLockMetadataLike = {+ ...spawnedLock,+ pid: 77001,+ port: 55555,+ draining: true,+ };+ let readCount = 0;+ env.deps.readServerLock = () => {+ readCount++;+ // Attach gate + first poll reads see the draining predecessor;+ // then the fresh spawn's lock lands.+ return readCount <= 3 ? drainingPredecessor : spawnedLock;+ };+ env.deps.isProcessAlive = () => true;+ env.deps.hostname = () => 'my-host';+ env.deps.probeWsUpgrade = () => Promise.resolve(true);+ const spawn = mock(() => Promise.resolve({ pid: 91001 }));+ env.deps.spawnDetachedServer = spawn;++ const wm = new WindowManager(env.deps);+ const ctx = await wm.createProjectWindow({ projectPath: '/tmp/spawned-project' });++ expect(spawn).toHaveBeenCalledTimes(1);+ // Connected to the successor's port — never the draining predecessor's.+ expect(ctx.port).toBe(spawnedLock.port);+ expect(ctx.ownsServer).toBe(false);+ });+test('attach-eligible lock pre-empts detached spawn (does NOT spawn a duplicate)', async () => {enableSyncTimers();// An attachable lock is already present — the desktop attaches rather@@ -1278,6 +1355,89 @@ describe('WindowManager', () => {});});+ describe('forceStopConflictingServer (dialog "Stop Server & Retry")', () => {+ function seedRawLock(pid: number): string {+ const projectPath = mkdtempSync(join(tmpdir(), 'ok-force-stop-'));+ const lockDir = join(projectPath, '.ok', 'local');+ mkdirSync(lockDir, { recursive: true });+ // Tampered/foreign identity on purpose — the method must bypass the+ // machine-identity filter and act on the raw pid.+ writeFileSync(+ join(lockDir, 'server.lock'),+ JSON.stringify({+ pid,+ hostname: 'some-old-hostname',+ machineId: 'not-this-machine',+ port: 61000,+ startedAt: '2026-07-07T00:00:00.000Z',+ worktreeRoot: projectPath,+ kind: 'interactive',+ }),+ 'utf-8',+ );+ return projectPath;+ }++ test('SIGTERMs the raw lock pid even when its identity looks foreign', async () => {+ const killedPids = new Set<number>();+ const killCalls: Array<{ pid: number; signal: NodeJS.Signals | number }> = [];+ env.deps.killProbe = (pid, signal) => {+ killCalls.push({ pid, signal });+ if (signal === 'SIGTERM') killedPids.add(pid);+ };+ env.deps.isProcessAlive = (pid) => !killedPids.has(pid);+ const projectPath = seedRawLock(64321);++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(outcome).toEqual({ ok: true });+ expect(killCalls).toContainEqual({ pid: 64321, signal: 'SIGTERM' });+ });++ test('no lock file → ok without signalling anything', async () => {+ const killCalls: number[] = [];+ env.deps.killProbe = (pid) => {+ killCalls.push(pid);+ };+ const projectPath = mkdtempSync(join(tmpdir(), 'ok-force-stop-empty-'));++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(outcome).toEqual({ ok: true });+ expect(killCalls).toHaveLength(0);+ });++ test('EPERM (other user account) surfaces as a failure', async () => {+ env.deps.killProbe = () => {+ const err = new Error('operation not permitted') as NodeJS.ErrnoException;+ err.code = 'EPERM';+ throw err;+ };+ const projectPath = seedRawLock(64322);++ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);++ expect(outcome).toEqual({ ok: false, reason: 'eperm' });+ });++ test('never signals a hostile lock pid (0/1/self)', async () => {+ const killCalls: number[] = [];+ env.deps.killProbe = (pid) => {+ killCalls.push(pid);+ };+ for (const badPid of [0, 1, process.pid]) {+ const projectPath = seedRawLock(badPid);+ const wm = new WindowManager(env.deps);+ const outcome = await wm.forceStopConflictingServer(projectPath);+ expect(outcome).toEqual({ ok: true });+ }+ expect(killCalls).toHaveLength(0);+ });+ });+describe('keepalive lifecycle (FR4)', () => {function makeKeepaliveMock() {const calls: Array<{ lockDir: string }> = [];@@ -1381,13 +1541,16 @@ describe('WindowManager', () => {// post-stop reads via the kill mock).return n === 1 ? null : (lockByCwd.get(lockDir) ?? null);};- env.deps.isProcessAlive = () => true;+ // Liveness follows the kill mock below: a SIGTERMed pid counts as+ // exited (the stop poll watches pid death, not lock release).+ const killedPids = new Set<number>();+ env.deps.isProcessAlive = (pid) => !killedPids.has(pid);env.deps.hostname = () => 'my-host';env.deps.probeWsUpgrade = () => Promise.resolve(true);let nextSpawnPid = 91001;env.deps.spawnDetachedServer = () => Promise.resolve({ pid: nextSpawnPid++ });- // Inject killProbe so we record signals + simulate lock release.+ // Inject killProbe so we record signals + simulate the server exiting.// The dep is already wired in WindowManagerDeps (used by the// post-exit liveness probe + now also by stopAllOwnedServers// and the spawn-lock-timeout orphan cleanup) — cleaner than@@ -1395,8 +1558,10 @@ describe('WindowManager', () => {const killCalls: Array<{ pid: number; signal: NodeJS.Signals | 0 }> = [];env.deps.killProbe = (pid: number, signal: NodeJS.Signals | 0) => {killCalls.push({ pid, signal });- // Simulate the server reacting to SIGTERM by releasing its lock.+ // Simulate the server reacting to SIGTERM by exiting (pid dies,+ // and its lock file goes with it via the exit-time unlink).if (signal === 'SIGTERM') {+ killedPids.add(pid);for (const [dir, lock] of lockByCwd.entries()) {if (lock.pid === pid) {lockByCwd.delete(dir);diff --git a/packages/server/src/boot.test.ts b/packages/server/src/boot.test.tsindex eaeb9eb64..feb02f22f 100644--- a/packages/server/src/boot.test.ts+++ b/packages/server/src/boot.test.ts@@ -541,9 +541,16 @@ describe('bootServer — reactShellDistDir + ui.lock advertisement', () => {expect(parsed.port).toBe(booted.port);} finally {await booted.destroy();- // We owned the lock (acquired by replacing the stale entry), so we- // release on destroy.- expect(existsSync(resolve(lockDir, 'ui.lock'))).toBe(false);+ // We owned the lock (acquired by replacing the stale entry), so destroy+ // releases our claim — but the file survives marked draining until the+ // process actually exits (unlink is deferred to the exit handler).+ const postDestroy = JSON.parse(+ await import('node:fs/promises').then((m) =>+ m.readFile(resolve(lockDir, 'ui.lock'), 'utf-8'),+ ),+ ) as { pid: number; draining?: boolean };+ expect(postDestroy.pid).toBe(process.pid);+ expect(postDestroy.draining).toBe(true);}});@@ -571,9 +578,12 @@ describe('bootServer — reactShellDistDir + ui.lock advertisement', () => {const uiLockPath = resolve(projectDir, '.ok', 'local', 'ui.lock');expect(existsSync(uiLockPath)).toBe(true);await booted1.destroy();- expect(existsSync(uiLockPath)).toBe(false);+ // Draining until process exit — not unlinked at destroy time.+ const drained = JSON.parse(readFileSync(uiLockPath, 'utf-8')) as { draining?: boolean };+ expect(drained.draining).toBe(true);- // A second boot for the same project acquires cleanly.+ // A second boot for the same project acquires cleanly (same-pid+ // idempotent rewrite clears the draining flag).const booted2 = await bootServer({host: '127.0.0.1',config: TEST_CONFIG,@@ -589,6 +599,12 @@ describe('bootServer — reactShellDistDir + ui.lock advertisement', () => {try {await booted2.ready;expect(existsSync(uiLockPath)).toBe(true);+ const reacquired = JSON.parse(readFileSync(uiLockPath, 'utf-8')) as {+ pid: number;+ draining?: boolean;+ };+ expect(reacquired.pid).toBe(process.pid);+ expect(reacquired.draining).toBeUndefined();} finally {await booted2.destroy();}diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex a6445d93a..adaa90a19 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -76,7 +76,13 @@ import {// Stale locks (dead pid) are pruned automatically by `acquireProcessLock`.// Only the writer releases on destroy — a desktop quit must not take down a// peer's advertisement. Ownership is tracked locally via `ownsUiLock` below.-import { acquireUiLock, releaseUiLock, UiLockCollisionError, updateUiLockPort } from './ui-lock.ts';+import {+ acquireUiLock,+ markUiLockDraining,+ releaseUiLock,+ UiLockCollisionError,+ updateUiLockPort,+} from './ui-lock.ts';/*** Names of per-machine runtime files that pre-date the `.ok/local/` move.@@ -494,7 +500,9 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// environment for typechecking without pulling network deps at parse time.// `ws` (the WebSocket server) is loaded by `mountMcpAndApi` further down.const { createServer: createHttpServer } = await import('node:http');- const { updateServerLockPort } = await import('./server-lock.ts');+ const { markServerLockDraining, releaseServerLock, updateServerLockPort } = await import(+ './server-lock.ts'+ );// Pre-createServer scaffold hook. CLI passes initContent; desktop omits.let didAutoInit = false;@@ -727,6 +735,11 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {await destroyHocuspocus().catch(() => {/* best-effort — surface the original error */});+ // Boot failed but this process may keep living (Electron utility+ // surfaces the error over IPC). destroyHocuspocus defers its unlink+ // to process exit, which would strand a live-pid draining lock that+ // blocks every future start — release it for real here.+ releaseServerLock(lockDir);throw err;}}@@ -851,6 +864,10 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {await destroyHocuspocus().catch(() => {/* best-effort — surface the original listen error */});+ // Same rationale as the ui.lock error path above: the process may keep+ // living after a failed boot, so the deferred-to-exit unlink would strand+ // a live-pid draining lock. Release immediately on this error path.+ releaseServerLock(lockDir);throw err;}@@ -911,6 +928,17 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {}};+ // Advertise teardown before the first close step so discovery and+ // supervisors stop treating this server as dialable the moment shutdown+ // begins — not seconds later when the Hocuspocus destroy reaches its own+ // draining mark. Idempotent with the mark inside `destroyHocuspocus`.+ try {+ markServerLockDraining(lockDir);+ if (ownsUiLock) markUiLockDraining(lockDir);+ } catch (err) {+ log.warn({ err, step: 'markLocksDraining' }, 'bootServer destroy step failed');+ }+try {idleHandle?.detach();} catch (err) {@@ -948,8 +976,11 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {// Release ONLY if we own it. If we yielded at boot to a live holder,// that holder's advertisement must survive our destroy — taking down// ui.lock on quit-without-ownership would silently break their- // preview-URL discovery.- await runStep('releaseUiLock', async () => releaseUiLock(lockDir));+ // preview-URL discovery. Unlink deferred to process exit for the same+ // reason as server.lock: lock-gone must mean process-gone.+ await runStep('releaseUiLock', async () =>+ releaseUiLock(lockDir, { deferUnlinkToExit: true }),+ );}// Flush pending spans/metrics so the teardown sequence itself is// observable. shutdownTelemetry is idempotent and has its own timeout.diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 8c24f6d78..d257f0e24 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -256,6 +256,7 @@ export {type PinoLoggerConfig,} from './logger.ts';export { isAllowedWorkspaceHostHeader, isLoopbackAddress } from './loopback.ts';+export { getMachineId } from './machine-id.ts';export {type RenameRewriteResult,rewriteMarkdownLinksForDocumentRename,@@ -402,11 +403,13 @@ export { serializeError } from './serialize-error.ts';export { createServer, type ServerInstance, type ServerOptions } from './server-factory.ts';export {acquireServerLock,+ markServerLockDraining,readServerLock,releaseServerLock,ServerLockCollisionError,type ServerLockMetadata,updateServerLockPort,+ waitForServerLockDrain,} from './server-lock.ts';export {createServerObserverExtension,diff --git a/packages/server/src/machine-id.test.ts b/packages/server/src/machine-id.test.tsnew file mode 100644index 000000000..4014a64beBinary files /dev/null and b/packages/server/src/machine-id.test.ts differdiff --git a/packages/server/src/machine-id.ts b/packages/server/src/machine-id.tsnew file mode 100644index 000000000..02ffd2a19--- /dev/null+++ b/packages/server/src/machine-id.ts@@ -0,0 +1,85 @@+/**+ * Stable per-machine identity for process-lock ownership checks.+ *+ * `os.hostname()` is NOT stable on macOS — it follows the network-derived+ * kernel hostname (DHCP/DNS renames, user renames in System Settings), and a+ * rename makes every lock written under the old name look foreign. A lock+ * that looks foreign gets replaced even though its holder is alive on this+ * very machine, which is how duplicate servers per contentDir happen.+ *+ * Instead we mint a random UUID once and persist it at `~/.ok/machine-id`+ * (owner-only, mode 0600 — sibling of `~/.ok/auth.yml` and `~/.ok/logs/`).+ * Deliberately NOT a hardware identifier (IOPlatformUUID, /etc/machine-id):+ * those need platform-specific subprocess calls in the boot-critical lock+ * path, and writing persistent hardware IDs into lock files that can land on+ * shared volumes is a needless privacy leak.+ *+ * Scope note: the file lives under the user's home, so two OS user accounts+ * on one machine get different IDs. That is safe because every lock judgment+ * that involves a foreign/unknown machine ID falls back to local pid+ * liveness and fails CLOSED (collision, not stale-replace) — see+ * `acquireProcessLock`.+ *+ * Failure posture: if `~/.ok` is unreadable/unwritable, fall back to an+ * ephemeral per-process UUID. Locks written under an ephemeral ID look+ * foreign to every other process, which degrades to the same fail-closed+ * pid-liveness judgment — never to silent lock replacement.+ */++import { randomUUID } from 'node:crypto';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { homedir } from 'node:os';+import { dirname, join } from 'node:path';++/**+ * Accepts UUIDs and other short opaque tokens; rejects whitespace/control+ * garbage from a corrupt file so a truncated write can't produce an ID that+ * breaks lock-file JSON round-trips or log lines.+ */+const MACHINE_ID_RE = /^[A-Za-z0-9-]{8,64}$/;++let cachedMachineId: string | null = null;++export function machineIdFilePath(homedirOverride?: string): string {+ return join(homedirOverride ?? homedir(), '.ok', 'machine-id');+}++/**+ * Read (or mint) the stable machine ID. Cached per process after the first+ * call — the lock hot paths (acquire/read/release) must not re-hit disk.+ *+ * `homedirOverride` is test-only, mirroring `secrets-store.ts`.+ */+export function getMachineId(homedirOverride?: string): string {+ if (homedirOverride === undefined && cachedMachineId !== null) return cachedMachineId;++ const filePath = machineIdFilePath(homedirOverride);+ let id: string | null = null;+ try {+ const raw = readFileSync(filePath, 'utf-8').trim();+ if (MACHINE_ID_RE.test(raw)) id = raw;+ } catch {+ // Missing or unreadable — mint below.+ }++ if (id === null) {+ id = randomUUID();+ try {+ mkdirSync(dirname(filePath), { recursive: true });+ writeFileSync(filePath, `${id}\n`, { encoding: 'utf-8', mode: 0o600 });+ } catch (err) {+ // Unwritable home — keep the ephemeral ID for this process. Foreign-ID+ // judgments fail closed on pid liveness, so this degrades safely — but+ // loudly: every collision error this process later hits will blame+ // "already running" while the real root cause is this write failure.+ console.warn(+ `[machine-id] Failed to persist ${filePath} — using an ephemeral per-process id; ` ++ `lock ownership checks will fail closed (collision) instead of recognizing this machine: ` ++ `${err instanceof Error ? err.message : String(err)}`,+ );+ }+ }++ if (homedirOverride === undefined) cachedMachineId = id;+ return id;+}diff --git a/packages/server/src/process-lock.test.ts b/packages/server/src/process-lock.test.tsindex 7153c0c6f..67f9305c1 100644--- a/packages/server/src/process-lock.test.ts+++ b/packages/server/src/process-lock.test.ts@@ -1,19 +1,22 @@import { afterEach, beforeEach, describe, expect, test } from 'bun:test';-import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';import { mkdtemp, rm } from 'node:fs/promises';import { hostname, tmpdir } from 'node:os';import { resolve } from 'node:path';import { LOCAL_DIR } from '@inkeep/open-knowledge-core';+import { getMachineId } from './machine-id';import {acquireProcessLock,type LockName,lockFilePath,+ markProcessLockDraining,ProcessLockCollisionError,type ProcessLockMetadata,readProcessLock,readProcessLockDetailed,releaseProcessLock,updateProcessLockPort,+ waitForProcessLockDrain,} from './process-lock';import { PROTOCOL_VERSION, RUNTIME_VERSION } from './version-constants';@@ -826,3 +829,336 @@ describe('lock-pid security validation', () => {expect(isValidLockPid(process.ppid > 1 ? process.ppid : 12345)).toBe(true);});});++describe('machine identity + fail-closed liveness (duplicate-server regression)', () => {+ test('stamps machineId into the lock on acquire', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 3000, worktreeRoot: '/wt' },+ });+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.machineId).toBe(getMachineId());+ });++ test('collides on a live local pid even when hostname AND machineId look foreign (hostname-flap regression)', () => {+ // A macOS hostname rename (or another OS user account's machine-id file)+ // makes a same-machine lock look foreign. Pre-fix, acquire classified it+ // as stale and REPLACED it while its holder was alive and serving —+ // producing two fully-live servers for one contentDir.+ const livePid = aliveForeignPid();+ mkdirSync(lockDir, { recursive: true });+ const flapped: ProcessLockMetadata = {+ pid: livePid,+ hostname: `${hostname()}-before-rename`,+ port: 9000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/other',+ machineId: 'some-other-machine-id',+ };+ writeFileSync(lockPath, JSON.stringify(flapped), 'utf-8');++ expect(() =>+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 3000, worktreeRoot: '/me' },+ }),+ ).toThrow(ProcessLockCollisionError);+ // The live holder's lock survives untouched.+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.pid).toBe(livePid);+ });++ test('replaces a foreign-machine lock whose pid is dead locally', () => {+ mkdirSync(lockDir, { recursive: true });+ const remote: ProcessLockMetadata = {+ pid: 99999999,+ hostname: 'some-other-host',+ port: 9000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/remote',+ machineId: 'some-other-machine-id',+ };+ writeFileSync(lockPath, JSON.stringify(remote), 'utf-8');++ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 3001, worktreeRoot: '/me' },+ });+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.pid).toBe(process.pid);+ });++ test('readProcessLock returns null for a foreign-machine lock WITHOUT unlinking it', () => {+ mkdirSync(lockDir, { recursive: true });+ const livePid = aliveForeignPid();+ const foreign: ProcessLockMetadata = {+ pid: livePid,+ hostname: hostname(),+ port: 9000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/other',+ machineId: 'some-other-machine-id',+ };+ writeFileSync(lockPath, JSON.stringify(foreign), 'utf-8');++ expect(readProcessLock({ lockName: LOCK_NAME, lockDir })).toBeNull();+ expect(existsSync(lockPath)).toBe(true);+ });++ test('same-machine lock with a drifted hostname still reads as ours via machineId', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 4000, worktreeRoot: '/wt' },+ });+ // Simulate the hostname changing AFTER the lock was written.+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ md.hostname = `${hostname()}-renamed-since`;+ writeFileSync(lockPath, JSON.stringify(md), 'utf-8');++ const read = readProcessLock({ lockName: LOCK_NAME, lockDir });+ expect(read?.pid).toBe(process.pid);+ expect(read?.port).toBe(4000);+ });+});++describe('draining lifecycle (lock held until process exit)', () => {+ test('markProcessLockDraining sets the flag and preserves every other field', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 5000, worktreeRoot: '/wt' },+ });+ markProcessLockDraining({ lockName: LOCK_NAME, lockDir });++ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.draining).toBe(true);+ expect(md.pid).toBe(process.pid);+ expect(md.port).toBe(5000);+ expect(md.worktreeRoot).toBe('/wt');+ expect(md.machineId).toBe(getMachineId());+ });++ test('markProcessLockDraining refuses locks we do not own', () => {+ mkdirSync(lockDir, { recursive: true });+ const livePid = aliveForeignPid();+ const foreign: ProcessLockMetadata = {+ pid: livePid,+ hostname: hostname(),+ port: 9000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/other',+ };+ writeFileSync(lockPath, JSON.stringify(foreign), 'utf-8');+ markProcessLockDraining({ lockName: LOCK_NAME, lockDir });++ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.draining).toBeUndefined();+ });++ test('markProcessLockDraining no-ops while another in-process acquire is active (Vite restart)', () => {+ acquireProcessLock({ lockName: LOCK_NAME, lockDir, metadata: { port: 1, worktreeRoot: '/a' } });+ acquireProcessLock({ lockName: LOCK_NAME, lockDir, metadata: { port: 2, worktreeRoot: '/b' } });++ // Two active acquires — pass-1's teardown must not mark pass-2's lock.+ markProcessLockDraining({ lockName: LOCK_NAME, lockDir });+ let md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.draining).toBeUndefined();++ releaseProcessLock({ lockName: LOCK_NAME, lockDir });+ // Last active acquire — now the mark applies.+ markProcessLockDraining({ lockName: LOCK_NAME, lockDir });+ md = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.draining).toBe(true);+ });++ test('release with deferUnlinkToExit keeps the file on disk, marked draining', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 5000, worktreeRoot: '/wt' },+ });+ releaseProcessLock({ lockName: LOCK_NAME, lockDir, deferUnlinkToExit: true });++ expect(existsSync(lockPath)).toBe(true);+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.pid).toBe(process.pid);+ expect(md.draining).toBe(true);+ });++ test('plain release still unlinks immediately (error-path contract)', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 5000, worktreeRoot: '/wt' },+ });+ releaseProcessLock({ lockName: LOCK_NAME, lockDir });+ expect(existsSync(lockPath)).toBe(false);+ });++ test('same-pid re-acquire after a deferred release clears the draining flag', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 5000, worktreeRoot: '/wt' },+ });+ releaseProcessLock({ lockName: LOCK_NAME, lockDir, deferUnlinkToExit: true });++ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 6000, worktreeRoot: '/wt' },+ });+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.draining).toBeUndefined();+ expect(md.port).toBe(6000);+ // Balance the re-acquire so later tests see a clean refcount.+ releaseProcessLock({ lockName: LOCK_NAME, lockDir });+ });++ test('updateProcessLockPort preserves the draining flag', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 0, worktreeRoot: '/wt' },+ });+ markProcessLockDraining({ lockName: LOCK_NAME, lockDir });+ updateProcessLockPort({ lockName: LOCK_NAME, lockDir, port: 7777 });++ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.port).toBe(7777);+ expect(md.draining).toBe(true);+ });++ test('readProcessLockDetailed propagates draining and machineId (desktop attach guard depends on both)', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 8100, worktreeRoot: '/wt' },+ });+ markProcessLockDraining({ lockName: LOCK_NAME, lockDir });++ const result = readProcessLockDetailed({ lockName: LOCK_NAME, lockDir });+ expect(result.status).toBe('live');+ if (result.status === 'live') {+ expect(result.lock.draining).toBe(true);+ expect(result.lock.machineId).toBe(getMachineId());+ }+ });++ test('readProcessLock surfaces the draining flag on a live same-machine holder', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 8000, worktreeRoot: '/wt' },+ });+ markProcessLockDraining({ lockName: LOCK_NAME, lockDir });++ const read = readProcessLock({ lockName: LOCK_NAME, lockDir });+ expect(read?.draining).toBe(true);+ expect(read?.port).toBe(8000);+ });+});++describe('waitForProcessLockDrain', () => {+ const immediateSleep = async () => {};++ test('returns no-drain when no lock exists', async () => {+ const outcome = await waitForProcessLockDrain({+ lockName: LOCK_NAME,+ lockDir,+ readLock: () => null,+ sleep: immediateSleep,+ });+ expect(outcome).toBe('no-drain');+ });++ test('returns no-drain for a live non-draining holder', async () => {+ const live: ProcessLockMetadata = {+ pid: process.pid,+ hostname: hostname(),+ port: 9000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/wt',+ };+ const outcome = await waitForProcessLockDrain({+ lockName: LOCK_NAME,+ lockDir,+ readLock: () => live,+ sleep: immediateSleep,+ });+ expect(outcome).toBe('no-drain');+ });++ test('returns released once the draining holder exits', async () => {+ const draining: ProcessLockMetadata = {+ pid: process.pid,+ hostname: hostname(),+ port: 9000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/wt',+ draining: true,+ };+ let reads = 0;+ const outcome = await waitForProcessLockDrain({+ lockName: LOCK_NAME,+ lockDir,+ readLock: () => {+ reads += 1;+ return reads >= 4 ? null : draining;+ },+ sleep: immediateSleep,+ });+ expect(outcome).toBe('released');+ });++ test('returns no-drain when a live non-draining successor replaces the draining holder mid-wait', async () => {+ const draining: ProcessLockMetadata = {+ pid: process.pid,+ hostname: hostname(),+ port: 9000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/wt',+ draining: true,+ };+ const successor: ProcessLockMetadata = {+ ...draining,+ pid: process.pid,+ draining: undefined,+ port: 9100,+ };+ let reads = 0;+ const outcome = await waitForProcessLockDrain({+ lockName: LOCK_NAME,+ lockDir,+ readLock: () => {+ reads += 1;+ return reads >= 3 ? successor : draining;+ },+ sleep: immediateSleep,+ });+ expect(outcome).toBe('no-drain');+ });++ test('returns timeout when the draining holder outlives the budget', async () => {+ const draining: ProcessLockMetadata = {+ pid: process.pid,+ hostname: hostname(),+ port: 9000,+ startedAt: new Date().toISOString(),+ worktreeRoot: '/wt',+ draining: true,+ };+ const outcome = await waitForProcessLockDrain({+ lockName: LOCK_NAME,+ lockDir,+ timeoutMs: 20,+ pollIntervalMs: 1,+ readLock: () => draining,+ });+ expect(outcome).toBe('timeout');+ });+});diff --git a/packages/server/src/process-lock.ts b/packages/server/src/process-lock.tsindex 37b5701bf..0c79cfab2 100644--- a/packages/server/src/process-lock.ts+++ b/packages/server/src/process-lock.ts@@ -21,6 +21,7 @@ import {} from 'node:fs';import { hostname } from 'node:os';import { resolve } from 'node:path';+import { getMachineId } from './machine-id.ts';import { isProcessAlive, isValidLockPid } from './process-alive.ts';import { PROTOCOL_VERSION, RUNTIME_VERSION } from './version-constants.ts';@@ -36,11 +37,32 @@ export type LockKind = 'interactive' | 'mcp-spawned';export interface ProcessLockMetadata {pid: number;+ /**+ * Display/diagnostic only — NOT an identity signal. `os.hostname()` follows+ * macOS network renames, so hostname comparison misclassifies same-machine+ * locks as foreign after a rename. Identity checks use `machineId`;+ * hostname comparison survives only as the legacy fallback for locks+ * written by binaries that predate `machineId`.+ */hostname: string;/** HTTP/WebSocket port. 0 means "starting — port not yet bound". */port: number;startedAt: string;worktreeRoot: string;+ /**+ * Stable machine identity from `~/.ok/machine-id` (see `machine-id.ts`).+ * Absent on locks written by older binaries — readers fall back to the+ * hostname comparison, and ambiguous cases resolve fail-closed on local+ * pid liveness.+ */+ machineId?: string;+ /**+ * Set when the holder has begun teardown. The holder still OWNS the lock —+ * the file is unlinked only when the process actually exits — but the+ * advertised port is no longer safe to dial and supervisors should wait+ * for pid death rather than lock disappearance. Absent means "serving".+ */+ draining?: boolean;/*** Optional — absent on locks written by older binaries. Readers MUST* tolerate `undefined` and fall through to conservative paths@@ -152,6 +174,59 @@ function dropActiveLockRef(lockPath: string): boolean {return false;}+/**+ * Machine-identity test for lock ownership judgments. `machineId` is the+ * primary signal; the hostname comparison survives only for locks written by+ * binaries that predate `machineId`. Callers must treat a `false` result as+ * "unknown provenance" and fall back to LOCAL pid liveness with fail-closed+ * semantics (collision, not stale-replace) — a foreign-looking lock can be a+ * same-machine lock written under a renamed hostname or another OS user+ * account's `~/.ok/machine-id`.+ */+function isSameMachine(existing: ProcessLockMetadata): boolean {+ if (typeof existing.machineId === 'string') return existing.machineId === getMachineId();+ return existing.hostname === hostname();+}++/**+ * Locks owned by this process that must be unlinked when the process+ * actually exits. One shared `'exit'` listener over a registry — a listener+ * per lockPath would trip Node's MaxListeners warning under the test runner,+ * which acquires thousands of per-test lock paths in one process.+ *+ * The handler is ownership-guarded (pid + machine), so a path that was+ * already released early, or re-acquired by another process, is left alone.+ * SIGKILL bypasses `'exit'`; the dead-pid stale detection in+ * `acquireProcessLock`/`readProcessLock` is the backstop for that case.+ */+const exitUnlinkPaths = new Set<string>();+let exitUnlinkHandlerRegistered = false;++function registerExitUnlink(lockPath: string): void {+ exitUnlinkPaths.add(lockPath);+ if (exitUnlinkHandlerRegistered) return;+ exitUnlinkHandlerRegistered = true;+ process.on('exit', () => {+ for (const path of exitUnlinkPaths) {+ try {+ const parsed = JSON.parse(readFileSync(path, 'utf-8')) as Partial<ProcessLockMetadata>;+ if (parsed?.pid !== process.pid) continue;+ if (typeof parsed.machineId === 'string' && parsed.machineId !== getMachineId()) continue;+ if (+ parsed.machineId === undefined &&+ typeof parsed.hostname === 'string' &&+ parsed.hostname !== hostname()+ ) {+ continue;+ }+ unlinkSync(path);+ } catch {+ // Missing or corrupt — nothing of ours to clean.+ }+ }+ });+}+function parseLock(lockPath: string, logPrefix: string): ProcessLockMetadata | null {try {const parsed = JSON.parse(readFileSync(lockPath, 'utf-8'));@@ -170,9 +245,20 @@ function parseLock(lockPath: string, logPrefix: string): ProcessLockMetadata | n* Acquire an exclusive process lock.** - No existing lock → write ours atomically via O_CREAT|O_EXCL.- * - Stale lock (dead pid OR foreign host) → replace with warning.- * - Our own pid → idempotent rewrite (refreshes port/startedAt).- * - Live foreign pid on same host → throw ProcessLockCollisionError.+ * - Our own pid (same machine) → idempotent rewrite (refreshes+ * port/startedAt, clears any draining flag).+ * - Pid alive on THIS host → throw ProcessLockCollisionError — regardless of+ * the lock's recorded machineId/hostname. Fail closed: a "foreign-looking"+ * lock can be this very machine under a renamed hostname (macOS renames+ * follow the network) or another OS user account; replacing it would start+ * a duplicate server against a live one. The cost is a rare false+ * collision on a shared volume (another machine's lock whose pid number+ * coincides with a live local process) — a loud, self-explanatory error,+ * preferred over a silent split-brain.+ * - Pid dead locally → stale → replace with warning. This preserves the+ * availability posture for shared volumes: a genuinely-remote holder's+ * lock (pid meaningless here, almost always dead-looking) never blocks a+ * local start.* - Corrupt lock file → treat as stale.** Create uses `openSync(path, 'wx')` (O_CREAT|O_EXCL) rather than a@@ -211,6 +297,7 @@ export function acquireProcessLock(opts: {port: init.port,startedAt: new Date().toISOString(),worktreeRoot: init.worktreeRoot,+ machineId: getMachineId(),...(init.kind !== undefined && { kind: init.kind }),...(init.parentPid !== undefined && { parentPid: init.parentPid }),...(init.capabilities !== undefined && { capabilities: init.capabilities }),@@ -232,6 +319,7 @@ export function acquireProcessLock(opts: {closeSync(fd);}bumpActiveLockRef(lockPath);+ registerExitUnlink(lockPath);return buildHandle({ lockName, lockDir, lockPath });} catch (err) {if ((err as NodeJS.ErrnoException).code !== 'EEXIST') throw err;@@ -241,19 +329,24 @@ export function acquireProcessLock(opts: {const existing = parseLock(lockPath, logPrefix);if (existing) {- const sameHost = existing.hostname === hostname();- if (sameHost && existing.pid === process.pid) {+ if (isSameMachine(existing) && existing.pid === process.pid) {// Idempotent rewrite — our own lock. Safe to overwrite in place;// O_EXCL is not needed here (we can't race ourselves). Bumps the// refcount so the corresponding releaseProcessLock decrement// doesn't unlink the file out from under the prior holder. See// `activeLockRefs` doc for the Vite-restart scenario this- // protects against.+ // protects against. The fresh payload carries no `draining` flag, so+ // a same-process re-acquire after a prior teardown (restartable test+ // servers) returns the lock to the serving state.writeFileSync(lockPath, payload, { encoding: 'utf-8', mode: 0o600 });bumpActiveLockRef(lockPath);+ registerExitUnlink(lockPath);return buildHandle({ lockName, lockDir, lockPath });}- if (sameHost && isProcessAlive(existing.pid)) {+ // Fail closed on ANY live local pid — deliberately not gated on+ // machineId/hostname. See the function docstring for why replacing a+ // foreign-looking live lock is the duplicate-server bug, not a cleanup.+ if (isProcessAlive(existing.pid)) {throw new ProcessLockCollisionError(existing, lockPath, lockName);}console.warn(@@ -324,9 +417,9 @@ export function updateProcessLockPort(opts: {return;}if (existing.pid !== process.pid) return;- // Match the cross-host guard in releaseProcessLock — pid alone can collide- // across hosts on a shared content volume (NFS, etc.).- if (typeof existing.hostname === 'string' && existing.hostname !== hostname()) return;+ // Match the cross-machine guard in releaseProcessLock — pid alone can+ // collide across machines on a shared content volume (NFS, etc.).+ if (!isSameMachine(existing)) return;existing.port = port;try {@@ -343,10 +436,75 @@ export function updateProcessLockPort(opts: {}}+/**+ * Mark our own lock as draining — teardown has begun, the advertised port is+ * no longer safe to dial, but the process still owns the lock until it+ * actually exits. No-op (with a warning) when the lock is missing, corrupt,+ * or not ours — a supervisor may legitimately have replaced it already.+ *+ * Idempotent; preserves every other field.+ */+export function markProcessLockDraining(opts: { lockName: LockName; lockDir: string }): void {+ const { lockName, lockDir } = opts;+ const logPrefix = `[${lockName}-lock]`;+ const lockPath = lockFilePath(lockDir, lockName);++ // Refcount-aware: draining means "the LAST holder is tearing down". When+ // another in-process acquire is still active (Vite restart: pass-2 serves+ // while pass-1 destroys), the lock must keep advertising a live server —+ // marking it draining here would make discovery refuse a healthy one.+ if ((activeLockRefs.get(lockPath) ?? 0) > 1) return;++ let existing: ProcessLockMetadata;+ try {+ const parsed = JSON.parse(readFileSync(lockPath, 'utf-8'));+ if (+ !parsed ||+ typeof parsed !== 'object' ||+ !isValidLockPid((parsed as { pid?: unknown }).pid)+ ) {+ console.warn(`${logPrefix} Corrupt lock at ${lockPath} during draining mark — skipping`);+ return;+ }+ existing = parsed as ProcessLockMetadata;+ } catch (err) {+ // Missing file is a normal double-release/error-path case — stay quiet.+ // Anything else (unreadable, corrupt JSON) has the same consequence as a+ // failed WRITE (server keeps looking live during teardown), so it must be+ // as attributable as the write-failure warn below.+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') {+ console.warn(+ `${logPrefix} Unreadable lock at ${lockPath} during draining mark — skipping: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+ return;+ }+ if (existing.pid !== process.pid) return;+ if (!isSameMachine(existing)) return;+ if (existing.draining === true) return;++ existing.draining = true;+ try {+ writeFileSync(lockPath, JSON.stringify(existing, null, 2), {+ encoding: 'utf-8',+ mode: 0o600,+ });+ } catch (err) {+ console.warn(+ `${logPrefix} Failed to mark ${lockPath} draining: ${err instanceof Error ? err.message : String(err)}`,+ );+ }+}+/*** Read the lock if it exists and the holder is alive on this host.- * Returns null for missing, stale, cross-host, or corrupt locks. Cleans- * up a stale lock as a side effect (same host, dead pid only).+ * Returns null for missing, stale, cross-machine, or corrupt locks. Cleans+ * up a stale lock as a side effect (same machine, dead pid only).+ *+ * A returned lock may carry `draining: true` — the holder is alive but+ * tearing down. Callers that dial the port or treat the holder as+ * attachable MUST check `draining`; callers that only need "is someone+ * alive holding this" can ignore it.** Locks missing the version fields (`protocolVersion` / `runtimeVersion`)* are returned as-is — the legacy callers (`tryAttachExistingServer` in the@@ -372,7 +530,7 @@ export function readProcessLock(opts: {return null;}- if (existing.hostname !== hostname()) return null;+ if (!isSameMachine(existing)) return null;if (!isProcessAlive(existing.pid)) {try {unlinkSync(lockPath);@@ -443,11 +601,13 @@ export function readProcessLockDetailed(opts: {port: r.port,startedAt: r.startedAt,worktreeRoot: r.worktreeRoot,+ machineId: typeof r.machineId === 'string' ? r.machineId : undefined,+ draining: r.draining === true ? true : undefined,protocolVersion: typeof r.protocolVersion === 'number' ? r.protocolVersion : undefined,runtimeVersion: typeof r.runtimeVersion === 'string' ? r.runtimeVersion : undefined,};- if (lock.hostname !== hostname()) return { status: 'stale', lock };+ if (!isSameMachine(lock)) return { status: 'stale', lock };if (!isProcessAlive(lock.pid)) {try {unlinkSync(lockPath);@@ -464,22 +624,85 @@ export function readProcessLockDetailed(opts: {return { status: 'live', lock };}+/**+ * Wait for a draining holder to finish exiting before proceeding.+ *+ * Spawners (CLI `ok start`, the MCP shim's auto-start, the desktop's+ * detached spawn) call this before acquiring: a draining lock means the+ * previous server is seconds from exit, and racing it either collides+ * loudly or, worse, dials a dying port. Polls until the lock is gone or+ * replaced by a non-draining one.+ *+ * Returns:+ * - `'no-drain'` — no lock, or a live non-draining holder. Proceed to the+ * normal acquire/attach logic immediately.+ * - `'released'` — a draining holder was present and has since exited+ * (lock gone or dead-pid-cleaned). Safe to acquire.+ * - `'timeout'` — the draining holder outlived `timeoutMs`. Proceed to+ * the normal logic; acquire will collide loudly, which is+ * the correct fail-closed outcome for a wedged teardown.+ */+export async function waitForProcessLockDrain(opts: {+ lockName: LockName;+ lockDir: string;+ timeoutMs?: number;+ pollIntervalMs?: number;+ /** Injectable for tests. */+ readLock?: () => ProcessLockMetadata | null;+ sleep?: (ms: number) => Promise<void>;+}): Promise<'no-drain' | 'released' | 'timeout'> {+ const { lockName, lockDir } = opts;+ const timeoutMs = opts.timeoutMs ?? 10_000;+ const pollIntervalMs = opts.pollIntervalMs ?? 100;+ const readLock = opts.readLock ?? (() => readProcessLock({ lockName, lockDir }));+ const sleep =+ opts.sleep ??+ ((ms: number) => new Promise<void>((resolveSleep) => setTimeout(resolveSleep, ms)));++ const initial = readLock();+ if (initial === null || initial.draining !== true) return 'no-drain';++ const deadline = Date.now() + timeoutMs;+ while (Date.now() < deadline) {+ await sleep(pollIntervalMs);+ const lock = readLock();+ if (lock === null) return 'released';+ if (lock.draining !== true) return 'no-drain';+ }+ return 'timeout';+}+/*** Release the lock. Safe to call multiple times. Only removes the lock if- * we own it (pid AND hostname match) — prevents a rogue process from- * unlinking a real server's lock. The hostname check matters on shared- * content directories (NFS-mounted home, remote content volumes) where two- * hosts can legitimately run processes with the same pid — without the- * check we'd unlink a peer's lock.+ * we own it (pid AND machine match; hostname for legacy locks) — prevents a+ * rogue process from unlinking a real server's lock. The machine check+ * matters on shared content directories (NFS-mounted home, remote content+ * volumes) where two machines can legitimately run processes with the same+ * pid — without the check we'd unlink a peer's lock.** Refcount-aware: when this process holds multiple active acquires for the* same lockPath (Vite plugin per-`configureServer` createServer lifecycle),* release decrements the in-process refcount; the file is only unlinked* when the LAST active acquire releases. See `activeLockRefs` for the bug* class this protects against.+ *+ * `deferUnlinkToExit` — the teardown-to-exit contract. When set and the+ * refcount reaches zero, the file is NOT unlinked now: it stays on disk+ * marked `draining` and the process-exit handler (registered at acquire)+ * removes it when the process actually dies. This closes the window where+ * a released lock made a still-alive server invisible, so supervisors and+ * discovery spawned a duplicate alongside it. Callers whose process keeps+ * living after the release (error-path cleanup, the Vite dev plugin's+ * restart cycle) MUST leave this unset — deferring there would leave a+ * live-pid draining lock that blocks every future start until the dev+ * process dies.*/-export function releaseProcessLock(opts: { lockName: LockName; lockDir: string }): void {- const { lockName, lockDir } = opts;+export function releaseProcessLock(opts: {+ lockName: LockName;+ lockDir: string;+ deferUnlinkToExit?: boolean;+}): void {+ const { lockName, lockDir, deferUnlinkToExit = false } = opts;const logPrefix = `[${lockName}-lock]`;const lockPath = lockFilePath(lockDir, lockName);if (!dropActiveLockRef(lockPath)) {@@ -487,13 +710,20 @@ export function releaseProcessLock(opts: { lockName: LockName; lockDir: string }// the file so cross-process collision detection keeps working.return;}+ if (deferUnlinkToExit) {+ // Ensure the draining flag is visible to readers between now and exit;+ // the exit handler owns the actual unlink.+ markProcessLockDraining({ lockName, lockDir });+ return;+ }if (!existsSync(lockPath)) return;try {const parsed = JSON.parse(readFileSync(lockPath, 'utf-8'));if (!parsed || typeof parsed !== 'object' || typeof parsed.pid !== 'number') return;if (parsed.pid !== process.pid) return;- if (typeof parsed.hostname === 'string' && parsed.hostname !== hostname()) return;+ if (!isSameMachine(parsed as ProcessLockMetadata)) return;unlinkSync(lockPath);+ exitUnlinkPaths.delete(lockPath);} catch (err) {console.warn(`${logPrefix} Failed to release ${lockPath}: ${err instanceof Error ? err.message : String(err)}`,diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex a76e369ae..36ba245b9 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -271,8 +271,14 @@ describe('createServer().destroy() — graceful shutdown flush', () => {expect(captures[0]?.contentOnDisk).toBe(true);expect(captures[0]?.payload).toContain('order-marker');- // Post-destroy: lock is gone, content survived. The standard end-state.- expect(existsSync(lockPath)).toBe(false);+ // Post-destroy: the lock file SURVIVES, marked draining, still owned by+ // this pid — the unlink is deferred to actual process exit so no other+ // server can acquire while a live predecessor is still winding down.+ // Content survived. The standard end-state.+ expect(existsSync(lockPath)).toBe(true);+ const postDestroyLock = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(postDestroyLock.pid).toBe(process.pid);+ expect(postDestroyLock.draining).toBe(true);expect(readFileSync(contentPath, 'utf-8')).toContain('order-marker');});@@ -1263,7 +1269,7 @@ describe('createServer() server-lock integration (V0-1)', () => {await rm(tmpDir, { recursive: true, force: true });});- test('acquires server.lock at createServer(), releases on destroy()', async () => {+ test('acquires server.lock at createServer(), drains on destroy() (unlink deferred to exit)', async () => {const server = createServer({contentDir: tmpDir,projectDir: tmpDir,@@ -1276,10 +1282,17 @@ describe('createServer() server-lock integration (V0-1)', () => {const md = JSON.parse(readFileSync(lockPath, 'utf-8'));expect(md.pid).toBe(process.pid);expect(md.worktreeRoot).toBe(tmpDir);+ expect(md.draining).toBeUndefined();await server.destroy();- expect(existsSync(lockPath)).toBe(false);+ // The file survives, marked draining, until the process actually exits —+ // lock-gone must mean process-gone, so a successor can never overlap a+ // still-alive predecessor.+ expect(existsSync(lockPath)).toBe(true);+ const drained = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(drained.pid).toBe(process.pid);+ expect(drained.draining).toBe(true);});test('exposes lockDir on ServerInstance', async () => {@@ -1364,7 +1377,7 @@ describe('createServer() server-lock integration (V0-1)', () => {await server.destroy();});- test('destroy() releases server.lock even when a shutdown phase throws (CC8)', async () => {+ test('destroy() drains server.lock even when a shutdown phase throws (CC8)', async () => {const server = createServer({contentDir: tmpDir,projectDir: tmpDir,@@ -1383,7 +1396,10 @@ describe('createServer() server-lock integration (V0-1)', () => {};await server.destroy();- expect(existsSync(lockPath)).toBe(false);+ // Phase 6 still ran despite the phase-2 throw: our claim is released+ // (draining flag set); the file itself survives until process exit.+ const drained = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(drained.draining).toBe(true);});});diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 386967469..bf5c835fe 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -138,7 +138,7 @@ import {setRenameLogIndex,sweepLazyPopOrphans,} from './rename-log.ts';-import { acquireServerLock, releaseServerLock } from './server-lock.ts';+import { acquireServerLock, markServerLockDraining, releaseServerLock } from './server-lock.ts';import { createServerObserverExtension } from './server-observer-extension.ts';import type { PairedWriteOrigin } from './server-observers.ts';import {@@ -2166,6 +2166,19 @@ export function createServer(options: ServerOptions): ServerInstance {const phaseErrors: Array<{ phase: string; error: string }> = [];shutdownAllowsUnload = true;+ // Advertise teardown FIRST — before any flush work. Readers (MCP+ // discovery, desktop attach, spawners) see `draining: true` and stop+ // dialing our port or treating lock-presence as "serving"; supervisors+ // wait for pid death instead of lock disappearance. The lock file+ // itself survives until the process actually exits (phase 6 defers the+ // unlink to the process-exit handler), so no second server can slip in+ // between "lock released" and "process gone".+ try {+ markServerLockDraining(lockDir);+ } catch (err) {+ log.warn({ err }, '[server] failed to mark server.lock draining');+ }+// Cancel any pending debounced backlink cache write so the timer doesn't// fire after resources are torn down.if (backlinkSaveTimer !== null) {@@ -2378,11 +2391,15 @@ export function createServer(options: ServerOptions): ServerInstance {}} finally {// Phase 6: release server lock LAST — after shadow repo release,- // agent session drain, L1/L2 flush. If an earlier phase threw, we still- // release so a subsequent start can succeed. Invariant: no other process- // may acquire this lock until every prior phase has run.+ // agent session drain, L1/L2 flush. If an earlier phase threw, we+ // still release so a subsequent start can succeed. Deferred to exit:+ // the refcount drops now, but the file stays on disk (marked+ // draining) until the process actually dies — the exit handler in+ // process-lock.ts owns the unlink. Invariant: no other process may+ // acquire this lock until this process has exited, so a successor+ // can never overlap a still-alive predecessor.try {- releaseServerLock(lockDir);+ releaseServerLock(lockDir, { deferUnlinkToExit: true });} catch (err) {phaseErrors.push({phase: 'server-lock-release',diff --git a/packages/server/src/server-lock.ts b/packages/server/src/server-lock.tsindex 61e5409cd..a823278b2 100644--- a/packages/server/src/server-lock.ts+++ b/packages/server/src/server-lock.ts@@ -17,11 +17,13 @@import {acquireProcessLock,type LockKind,+ markProcessLockDraining,ProcessLockCollisionError,type ProcessLockMetadata,readProcessLock,releaseProcessLock,updateProcessLockPort,+ waitForProcessLockDrain,} from './process-lock.ts';export type ServerLockMetadata = ProcessLockMetadata;@@ -63,6 +65,19 @@ export function readServerLock(lockDir: string): ServerLockMetadata | null {return readProcessLock({ lockName: 'server', lockDir });}-export function releaseServerLock(lockDir: string): void {- releaseProcessLock({ lockName: 'server', lockDir });+export function releaseServerLock(lockDir: string, opts?: { deferUnlinkToExit?: boolean }): void {+ releaseProcessLock({ lockName: 'server', lockDir, ...opts });+}++/** Mark our server.lock draining — teardown began; unlink happens at exit. */+export function markServerLockDraining(lockDir: string): void {+ markProcessLockDraining({ lockName: 'server', lockDir });+}++/** Wait for a draining server holder to exit before acquiring/attaching. */+export function waitForServerLockDrain(+ lockDir: string,+ opts?: { timeoutMs?: number; pollIntervalMs?: number },+): Promise<'no-drain' | 'released' | 'timeout'> {+ return waitForProcessLockDrain({ lockName: 'server', lockDir, ...opts });}diff --git a/packages/server/src/ui-lock.ts b/packages/server/src/ui-lock.tsindex a43e65519..8eb597652 100644--- a/packages/server/src/ui-lock.ts+++ b/packages/server/src/ui-lock.ts@@ -16,6 +16,7 @@import {acquireProcessLock,type LockKind,+ markProcessLockDraining,ProcessLockCollisionError,type ProcessLockMetadata,readProcessLock,@@ -61,6 +62,11 @@ export function readUiLock(lockDir: string): UiLockMetadata | null {return readProcessLock({ lockName: 'ui', lockDir });}-export function releaseUiLock(lockDir: string): void {- releaseProcessLock({ lockName: 'ui', lockDir });+export function releaseUiLock(lockDir: string, opts?: { deferUnlinkToExit?: boolean }): void {+ releaseProcessLock({ lockName: 'ui', lockDir, ...opts });+}++/** Mark our ui.lock draining — teardown began; unlink happens at exit. */+export function markUiLockDraining(lockDir: string): void {+ markProcessLockDraining({ lockName: 'ui', lockDir });}