Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Clear a Windows server.lock written before last boot (PRD-9932) (#7561)
Andrew Mikofalvy8571e80661ce
diff --git a/.changeset/stale-lock-before-boot.md b/.changeset/stale-lock-before-boot.mdnew file mode 100644index 000000000..4f331621e--- /dev/null+++ b/.changeset/stale-lock-before-boot.md@@ -0,0 +1,6 @@+---+'@inkeep/open-knowledge': patch+'@inkeep/open-knowledge-server': patch+---++A project now opens after a restart even when its old server's process ID was reused by a process OpenKnowledge cannot inspect, such as a protected Windows service.diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex ab75cf866..0dc2e7399 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -162,7 +162,7 @@ A lock from this machine whose PID now belongs to a process that started after t- The lock records only another host name and no process start. If that host is another machine, stop the server there. If it is an earlier name of this machine, confirm that the process is an OpenKnowledge server before ending it yourself, and remove the lock file once no OpenKnowledge server is running for the project.- The lock does not record its owning machine and its process is still running. Check whether that process is an OpenKnowledge server; if it is, stop it yourself, and do not remove the lock while it is running. `ok stop all` and `ok stop` with a port or PID skip such a lock instead.-For the first five, confirm that the process the error names is an OpenKnowledge server before ending it yourself, then remove the lock file the error names once no OpenKnowledge server is running for the project. In those five cases `ok status`, `ok ps` and the server-lock health check still report the server as running (`state: "alive"` in `ok status --json`) and `ok clean` keeps its lock; only `ok stop` says why the process cannot be confirmed.+For the first five, confirm that the process the error names is an OpenKnowledge server before ending it yourself, then remove the lock file the error names once no OpenKnowledge server is running for the project. In those five cases `ok status`, `ok ps` and the server-lock health check still report the server as running (`state: "alive"` in `ok status --json`) and `ok clean` keeps its lock; only `ok stop` says why the process cannot be confirmed. On Windows the first reason has one exception, because a restart can give the server's PID to a protected process your account cannot inspect: a lock from this machine written more than 5 minutes before Windows last started is stale. `ok status`, `ok ps` and the server-lock health check report it the way they report a reused PID (`state: "reused-pid"` in `ok status --json`), `ok clean` removes it, `ok start` replaces it, and `ok stop` leaves that process unsignalled and exits `0`. A shutdown with Fast Startup enabled does not count as a restart here, so such a lock still reads as running until Windows is restarted.A lock records a process start, as its `processStart` field, only when the server that wrote it could read its own start. Locks written before that field existed have none, and on Linux a server records one only while `/proc/sys/kernel/random/boot_id` is readable. For a lock without a recorded start, `ok stop` treats the running process as the lock's server only when the lock carries this machine's ID and the process did not start well after the lock's `startedAt`; a lock from this machine whose process started well after it is stale, as described above. It refuses a lock whose `startedAt` is well after the current time, a lock that records no machine ID, and a lock that carries another machine's ID. That ID is read from `~/.ok/machine-id` in the home folder of whoever runs the command, so running `ok stop` with a different home folder from the server's (`HOME`, or `USERPROFILE` on Windows) reads its lock as another machine's. Restarting the server on a release that writes `processStart` records its start, after which `ok stop` can confirm it from either home folder. "Well after" means more than 10 seconds on macOS and Windows and more than 5 minutes on Linux, where a process's start time is derived from the boot time and shifts whenever the clock is set forward. So on Linux, a still-running server whose lock has no `processStart` reads as stale once the clock has moved forward by more than 5 minutes since it wrote its lock, as after a long VM or WSL2 pause or a clock set by hand. `ok clean` then removes its lock, and if that server predates the filesystem lease described above, `ok start` can start a second server for the same project. Restart such servers so that their lock records `processStart` to rule this out.diff --git a/packages/cli/src/commands/lock-state.test.ts b/packages/cli/src/commands/lock-state.test.tsindex 0586b39c1..b1f074d22 100644--- a/packages/cli/src/commands/lock-state.test.ts+++ b/packages/cli/src/commands/lock-state.test.ts@@ -10,6 +10,7 @@ const startedBeforeFixtureLocks = (): ProcessStart => ({startedAtMs: Date.parse('2026-04-15T00:00:00Z'),clock: 'creation',});+const bootedBeforeFixtureLocks = () => Date.parse('2026-04-15T00:00:00Z');const tempDir = createTempDirFactory(afterEach);@@ -257,7 +258,13 @@ describe('inspectLock', () => {] as const)('a live pid whose holder %s stays alive', (_case, readProcessStart) => {const dir = freshLockDir();const lock = writeSameHostLock(dir);- expect(inspectLock(dir, 'server', { isAlive: () => true, readProcessStart })).toEqual({+ expect(+ inspectLock(dir, 'server', {+ isAlive: () => true,+ readProcessStart,+ readBootInstant: bootedBeforeFixtureLocks,+ }),+ ).toEqual({status: 'alive',lockPath: join(dir, 'server.lock'),lock,diff --git a/packages/cli/src/commands/lock-state.ts b/packages/cli/src/commands/lock-state.tsindex 71caaac60..65f14cdf1 100644--- a/packages/cli/src/commands/lock-state.ts+++ b/packages/cli/src/commands/lock-state.ts@@ -33,6 +33,7 @@ export type LockState =interface InspectLockOptions {isAlive?: (pid: number) => boolean;readProcessStart?: ProcessStartReader;+ readBootInstant?: () => number | null;host?: string;machineId?: string;}@@ -81,6 +82,7 @@ export function inspectLock(const assessment = assessLockHolder(lock, {isAlive: opts.isAlive,readProcessStart: opts.readProcessStart,+ readBootInstant: opts.readBootInstant,sameMachine: hasOwner,});switch (assessment.verdict) {diff --git a/packages/cli/src/commands/stop.test.ts b/packages/cli/src/commands/stop.test.tsindex 26e50a08a..eca259b87 100644--- a/packages/cli/src/commands/stop.test.ts+++ b/packages/cli/src/commands/stop.test.ts@@ -447,6 +447,8 @@ describe('runStop identity check at the signal', () => {startedAtMs: Date.parse('2026-04-17T12:00:00Z'),clock: 'creation' as const,});+ const bootedBeforeTheLock = () => Date.parse('2026-01-01T00:00:00Z');+ const bootedLongAfterTheLock = () => Date.parse('2026-04-17T12:00:00Z');function lockState(status: 'alive' | 'foreign-host', owner: Record<string, string>): LockState {return {@@ -479,6 +481,7 @@ describe('runStop identity check at the signal', () => {error: (msg) => errors.push(msg),probeClients: async () => null,logger,+ readBootInstant: bootedBeforeTheLock,...overrides,});return { outcome, killed, logs, errors, warnings };@@ -670,6 +673,29 @@ describe('runStop identity check at the signal', () => {]);});+ test('on Windows a holder the OS refuses to open, named by a lock written before the last boot, is reported stale and not signalled', async () => {+ const { outcome, killed, logs, errors, warnings } = run(thisMachine(), {+ isAlive: () => true,+ readProcessStart: (_pid, options) => {+ options?.onNativeFailure?.({+ kind: 'query-failed',+ reason: 'readProcessStart failed: OpenProcess: os error 5',+ });+ return null;+ },+ platform: 'win32',+ readBootInstant: bootedLongAfterTheLock,+ });++ expect(await outcome).toEqual({ stopped: [], failed: [], hadTargets: true });+ expect(killed).toEqual([]);+ expect(logs).toEqual([]);+ expect(errors).toEqual([+ `Process 100 is no longer the server that wrote ${lockPath}; it was not signalled. Run \`ok clean\` to remove the stale lock.`,+ ]);+ expect(warnings).toEqual([]);+ });+test('a holder whose start cannot be compared with the recorded start fails without a signal', async () => {const state = lockState('alive', { hostname: hostname(), machineId: getMachineId() });if (state.status !== 'alive') throw new Error('expected an alive lock state');diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.tsindex 3c37be67c..f3334f32a 100644--- a/packages/cli/src/commands/stop.ts+++ b/packages/cli/src/commands/stop.ts@@ -122,6 +122,7 @@ interface RunStopDeps {logger?: PinoLoggerInstance;selfChannel?: 'stable' | 'beta' | 'dev';platform?: NodeJS.Platform;+ readBootInstant?: () => number | null;refuseHolderStartedAfterLock?: boolean;}@@ -292,6 +293,8 @@ export async function runStop(deps: RunStopDeps): Promise<StopOutcome> {isAlive: deps.isAlive ?? isProcessAlive,readProcessStart: () => holderStart,refuseHolderStartedAfterLock: deps.refuseHolderStartedAfterLock,+ platform,+ readBootInstant: deps.readBootInstant,});switch (assessment.verdict) {case 'writer':diff --git a/packages/desktop/src/main/boot-session.test.ts b/packages/desktop/src/main/boot-session.test.tsindex 79c6ab573..da1754399 100644--- a/packages/desktop/src/main/boot-session.test.ts+++ b/packages/desktop/src/main/boot-session.test.ts@@ -1,5 +1,5 @@import { describe, expect, test } from 'vitest';-import { readBootSessionUuid, readBootStartedAtMs } from './boot-session.ts';+import { readBootSessionUuid } from './boot-session.ts';const onDarwin = process.platform === 'darwin' ? test : test.skip;const onLinux = process.platform === 'linux' ? test : test.skip;@@ -28,26 +28,3 @@ describe('readBootSessionUuid', () => {expect(crossPlatformProbe).toBeNull();});});--describe('readBootStartedAtMs', () => {- test('dates the boot by subtracting uptime from now', () => {- expect(readBootStartedAtMs(1_000_000_000, () => 120.4)).toBe(1_000_000_000 - 120_400);- });-- test('an unusable uptime fails open to null rather than throwing', () => {- expect(readBootStartedAtMs(1_000_000_000, () => 0)).toBeNull();- expect(readBootStartedAtMs(1_000_000_000, () => Number.NaN)).toBeNull();- expect(- readBootStartedAtMs(1_000_000_000, () => {- throw new Error('uptime unavailable');- }),- ).toBeNull();- });-- test('the live boot instant precedes now', () => {- const now = Date.now();- const bootStartedAtMs = readBootStartedAtMs(now);- expect(bootStartedAtMs).not.toBeNull();- expect(bootStartedAtMs).toBeLessThan(now);- });-});diff --git a/packages/desktop/src/main/boot-session.ts b/packages/desktop/src/main/boot-session.tsindex 0e7acaea3..e1213d6ce 100644--- a/packages/desktop/src/main/boot-session.ts+++ b/packages/desktop/src/main/boot-session.ts@@ -1,6 +1,5 @@import { execFileSync } from 'node:child_process';import { readFileSync } from 'node:fs';-import { uptime } from 'node:os';export function readBootSessionUuid(platform: NodeJS.Platform = process.platform): string | null {try {@@ -21,19 +20,6 @@ export function readBootSessionUuid(platform: NodeJS.Platform = process.platform}}-export function readBootStartedAtMs(- nowMs: number = Date.now(),- readUptimeSeconds: () => number = uptime,-): number | null {- try {- const uptimeSeconds = readUptimeSeconds();- if (!Number.isFinite(uptimeSeconds) || uptimeSeconds <= 0) return null;- return nowMs - Math.round(uptimeSeconds * 1000);- } catch {- return null;- }-}-function normalize(raw: string): string | null {const value = raw.trim();return value === '' ? null : value;diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.tsindex 3d9048f93..203d03d09 100644--- a/packages/desktop/src/main/index.ts+++ b/packages/desktop/src/main/index.ts@@ -93,6 +93,7 @@ import {prepareSpawnProjectLogsDir,type ResolvedSkillHost,RUNTIME_VERSION,+ readBootStartedAtMs,readBundleDecision,readProcessStart,readServerLock,@@ -200,7 +201,7 @@ import {resolveDesktopLocaleForPushed,} from './boot-locale.ts';import { resolveBootRestoreDecision, resolveRestoreActions } from './boot-restore-decision.ts';-import { readBootSessionUuid, readBootStartedAtMs } from './boot-session.ts';+import { readBootSessionUuid } from './boot-session.ts';import { runBootstrap } from './bootstrap.ts';import {type BranchInfoProxyDeps,diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 9b57d888b..efaca6b15 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -16,6 +16,7 @@ import {getLocalDir,type LockHolderIdentity,type ProcessStart,+ readBootStartedAtMs,readProcessStart,} from '@inkeep/open-knowledge-server';import {@@ -483,6 +484,7 @@ export interface WindowManagerDeps {removeServerLock?(lockDir: string, expected: { pid: number }): boolean;isProcessAlive?(pid: number): boolean;readProcessStart?(pid: number): ProcessStart | null;+ readBootInstant?(): number | null;hostname?(): string;probeWsUpgrade?(url: string, timeoutMs: number): Promise<boolean>;utilityInitTimeoutMs?: number;@@ -853,6 +855,11 @@ export class WindowManager {return read ? read(pid) : readProcessStart(pid);}+ private readBootInstant(): number | null {+ const read = this.deps.readBootInstant;+ return read ? read() : readBootStartedAtMs();+ }+private settleUnlessLockWriter(lock: LockHolderIdentity,sigtermSent: boolean,@@ -860,6 +867,7 @@ export class WindowManager {const assessment = assessLockHolder(lock, {isAlive: (pid) => this.isPidAlive(pid),readProcessStart: (pid) => this.readHolderStart(pid),+ readBootInstant: () => this.readBootInstant(),});const withheld = sigtermSent ? 'SIGKILL' : 'SIGTERM';switch (assessment.verdict) {diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.tsindex 02b734e2f..8d68e7605 100644--- a/packages/desktop/tests/main/window-manager.test.ts+++ b/packages/desktop/tests/main/window-manager.test.ts@@ -226,6 +226,7 @@ function buildEnv(): TestEnv {startedAtMs: Date.parse('2026-01-01T00:00:00Z'),clock: 'creation',}),+ readBootInstant: () => Date.parse('2026-01-01T00:00:00Z'),activateApp,showGate,log: {diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex 719dd6d3c..46d87b012 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -452,6 +452,7 @@ export {type ProcessStartToken,parseProcessStartToken,processStartToken,+ readBootStartedAtMs,readProcessStart,recordsLockOwner,registerNativeProcessStartReader,diff --git a/packages/server/src/process-identity.test.ts b/packages/server/src/process-identity.test.tsindex 0aa992856..5ea469018 100644--- a/packages/server/src/process-identity.test.ts+++ b/packages/server/src/process-identity.test.ts@@ -24,6 +24,7 @@ import {type ProcessStart,parseProcessStartToken,processStartToken,+ readBootStartedAtMs,readProcessStart,readPsProcessStart,registerNativeProcessStartReader,@@ -46,6 +47,12 @@ function creationStart(offsetFromWrittenMs: number): ProcessStart {return { startedAtMs: WRITTEN_AT_MS + offsetFromWrittenMs, clock: 'creation' };}+function bootedAt(offsetFromWrittenMs: number): () => number {+ return () => WRITTEN_AT_MS + offsetFromWrittenMs;+}++const BOOTED_BEFORE_LOCK = bootedAt(-THIRTY_SIX_HOURS_MS);+function bootDerivedStart(offsetFromWrittenMs: number,pair?: { bootId: string; startTicks: number },@@ -293,6 +300,7 @@ describe('assessLockHolder', () => {{isAlive: () => true,readProcessStart: () => live,+ readBootInstant: BOOTED_BEFORE_LOCK,sameMachine: true,refuseHolderStartedAfterLock,},@@ -398,6 +406,129 @@ describe('assessLockHolder', () => {}),).toEqual({ verdict: 'gone' });});++ test('an unreadable holder of a lock written before this machine booted is replaced', () => {+ expect(+ assessLockHolder(lockWrittenAt({ machineId: getMachineId() }), {+ isAlive: () => true,+ readProcessStart: () => null,+ platform: 'win32',+ readBootInstant: bootedAt(THIRTY_SIX_HOURS_MS),+ }),+ ).toEqual({ verdict: 'replaced' });+ });++ test('an unreadable holder of a lock naming only this hostname written before boot is replaced', () => {+ expect(+ assessLockHolder(lockWrittenAt({ hostname: hostname() }), {+ isAlive: () => true,+ readProcessStart: () => null,+ platform: 'win32',+ readBootInstant: bootedAt(THIRTY_SIX_HOURS_MS),+ }),+ ).toEqual({ verdict: 'replaced' });+ });++ test('a lock whose recorded process start is after boot is not dated by an earlier startedAt', () => {+ expect(+ assessLockHolder(+ lockWrittenAt({+ machineId: getMachineId(),+ processStart: { startedAtMs: WRITTEN_AT_MS + 2 * THIRTY_SIX_HOURS_MS },+ }),+ {+ isAlive: () => true,+ readProcessStart: () => null,+ platform: 'win32',+ readBootInstant: bootedAt(THIRTY_SIX_HOURS_MS),+ },+ ),+ ).toEqual({ verdict: 'unverified', cause: 'process-start-unreadable' });+ });++ test('an unreadable holder of a lock written minutes before boot stays unverified', () => {+ expect(+ assessLockHolder(lockWrittenAt({ machineId: getMachineId() }), {+ isAlive: () => true,+ readProcessStart: () => null,+ platform: 'win32',+ readBootInstant: bootedAt(60_000),+ }),+ ).toEqual({ verdict: 'unverified', cause: 'process-start-unreadable' });+ });++ test('an unreadable holder of a lock that records no write time stays unverified', () => {+ expect(+ assessLockHolder(+ { pid: HOLDER_PID, machineId: getMachineId() },+ {+ isAlive: () => true,+ readProcessStart: () => null,+ platform: 'win32',+ readBootInstant: bootedAt(THIRTY_SIX_HOURS_MS),+ },+ ),+ ).toEqual({ verdict: 'unverified', cause: 'process-start-unreadable' });+ });++ test('an unreadable holder stays unverified when the boot time cannot be read', () => {+ expect(+ assessLockHolder(lockWrittenAt({ machineId: getMachineId() }), {+ isAlive: () => true,+ readProcessStart: () => null,+ platform: 'win32',+ readBootInstant: () => null,+ }),+ ).toEqual({ verdict: 'unverified', cause: 'process-start-unreadable' });+ });++ test('a lock from another machine written before this machine booted still names that machine', () => {+ expect(+ assessLockHolder(lockWrittenAt({ machineId: 'another-machine-0000' }), {+ isAlive: () => true,+ readProcessStart: () => null,+ platform: 'win32',+ readBootInstant: bootedAt(THIRTY_SIX_HOURS_MS),+ }),+ ).toEqual({ verdict: 'unverified', cause: 'foreign-host' });+ });++ test.each(['linux', 'darwin'] as const)(+ 'on %s an unreadable holder of a lock written before this machine booted stays unverified',+ (platform) => {+ expect(+ assessLockHolder(lockWrittenAt({ machineId: getMachineId() }), {+ isAlive: () => true,+ readProcessStart: () => null,+ platform,+ readBootInstant: bootedAt(THIRTY_SIX_HOURS_MS),+ }),+ ).toEqual({ verdict: 'unverified', cause: 'process-start-unreadable' });+ },+ );+});++describe('readBootStartedAtMs', () => {+ test('dates the boot by subtracting uptime from now', () => {+ expect(readBootStartedAtMs(1_000_000_000, () => 120.4)).toBe(1_000_000_000 - 120_400);+ });++ test('an unusable uptime fails open to null rather than throwing', () => {+ expect(readBootStartedAtMs(1_000_000_000, () => 0)).toBeNull();+ expect(readBootStartedAtMs(1_000_000_000, () => Number.NaN)).toBeNull();+ expect(+ readBootStartedAtMs(1_000_000_000, () => {+ throw new Error('uptime unavailable');+ }),+ ).toBeNull();+ });++ test('the live boot instant precedes now', () => {+ const now = Date.now();+ const bootStartedAtMs = readBootStartedAtMs(now);+ expect(bootStartedAtMs).not.toBeNull();+ expect(bootStartedAtMs).toBeLessThan(now);+ });});describe('classifyLockHolder', () => {@@ -418,6 +549,7 @@ describe('classifyLockHolder', () => {classifyLockHolder(lockWrittenAt({ machineId: getMachineId() }), {isAlive: () => true,readProcessStart: () => null,+ readBootInstant: BOOTED_BEFORE_LOCK,}),).toBe('unverified');});diff --git a/packages/server/src/process-identity.ts b/packages/server/src/process-identity.tsindex 7b47e093e..b2a8a56e6 100644--- a/packages/server/src/process-identity.ts+++ b/packages/server/src/process-identity.ts@@ -1,6 +1,6 @@import { type ExecFileSyncOptionsWithStringEncoding, execFileSync } from 'node:child_process';import { readFileSync } from 'node:fs';-import { hostname } from 'node:os';+import { hostname, uptime } from 'node:os';import {LOCAL_OP_PIPE_STDIO_OPTIONS,withHiddenWindowsConsole,@@ -91,11 +91,14 @@ export interface ClassifyLockHolderOptions {sameMachine?: boolean;formatRecordsMachineId?: boolean;refuseHolderStartedAfterLock?: boolean;+ platform?: NodeJS.Platform;+ readBootInstant?: () => number | null;}const TOKEN_TOLERANCE_MS = 1000;const LEGACY_MARGIN_CREATION_MS = 10_000;const LEGACY_MARGIN_BOOT_DERIVED_MS = 300_000;+const LOCK_BEFORE_BOOT_MARGIN_MS = 300_000;const MAX_PROCESS_ID = 0xffff_ffff;const MAX_BOOT_ID_LENGTH = 64;@@ -385,6 +388,35 @@ function compareLockHolderStart(return drift > 0 ? { verdict: 'replaced' } : MISMATCH;}+export function readBootStartedAtMs(+ nowMs: number = Date.now(),+ readUptimeSeconds: () => number = uptime,+): number | null {+ try {+ const uptimeSeconds = readUptimeSeconds();+ if (!Number.isFinite(uptimeSeconds) || uptimeSeconds <= 0) return null;+ return nowMs - Math.round(uptimeSeconds * 1000);+ } catch {+ return null;+ }+}++function lockWrittenAtMs(lock: LockHolderIdentity): number | null {+ const token = parseProcessStartToken(lock.processStart);+ const writtenAtMs = [+ token !== undefined && 'startedAtMs' in token ? token.startedAtMs : Number.NaN,+ typeof lock.startedAt === 'string' ? Date.parse(lock.startedAt) : Number.NaN,+ ].filter(Number.isFinite);+ return writtenAtMs.length === 0 ? null : Math.max(...writtenAtMs);+}++function lockPredatesBoot(lock: LockHolderIdentity, readBootInstant: () => number | null): boolean {+ const writtenAtMs = lockWrittenAtMs(lock);+ if (writtenAtMs === null) return false;+ const bootStartedAtMs = readBootInstant();+ return bootStartedAtMs !== null && bootStartedAtMs - writtenAtMs > LOCK_BEFORE_BOOT_MARGIN_MS;+}+function recordsProcessStart(lock: LockHolderIdentity): boolean {return parseProcessStartToken(lock.processStart) !== undefined;}@@ -401,6 +433,14 @@ export function assessLockHolder(const read = options.readProcessStart ?? readProcessStart;const start = read(lock.pid);if (start === null && !isAlive(lock.pid)) return { verdict: 'gone' };+ if (+ start === null &&+ sameMachine &&+ (options.platform ?? process.platform) === 'win32' &&+ lockPredatesBoot(lock, options.readBootInstant ?? (() => readBootStartedAtMs()))+ ) {+ return { verdict: 'replaced' };+ }const comparison = compareLockHolderStart(lock,start,