Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

chore(ok): remove the ui.lock legacy reap (PRD-8127) (#3909)

omar-inkeep11887049ed8e
diff --git a/.changeset/remove-uilock-legacy-reap.md b/.changeset/remove-uilock-legacy-reap.md
new file mode 100644
index 000000000..35c72c1b8
--- /dev/null
+++ b/.changeset/remove-uilock-legacy-reap.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Removed the transitional `ui.lock` cleanup that shipped alongside the `ui.lock` retirement. `ok stop` no longer SIGTERMs a lingering pre-retirement UI holder, `ok clean` no longer prunes a leftover `ui.lock`, and `ok stop all` / the uninstall flows no longer discover a lock directory that holds only a `ui.lock`. Builds before v0.60.0 wrote a `ui.lock` next to `server.lock` on every UI-serving start, so if one of those servers did not shut down cleanly the file may still be sitting in `<project>/.ok/local/`. It is inert — nothing reads it — but `ok clean` will no longer remove it: delete it with `rm .ok/local/ui.lock`. A server from one of those builds that is still running also still holds its `server.lock`, so `ok ps` and `ok stop` continue to see and stop it normally. What `ok` can no longer reach is a live UI process that is not the server itself: a standalone `ok ui` sidecar, an `--only ui --server-url` proxy, or the UI sibling that `ok start` auto-spawned before v0.53.0. In each of those, `cat .ok/local/ui.lock` reports the `pid` it recorded; stop it directly (`kill <pid>`, or `taskkill /F /PID <pid>` on Windows) before deleting the file.
diff --git a/.env.example b/.env.example
index 106700b95..d549ff0a2 100644
--- a/.env.example
+++ b/.env.example
@@ -20,5 +20,5 @@
# --- Dev server ---
# Custom port for the Vite dev server (pnpm run dev, default: 5173). The CLI
-# (ok start / ok ui) has its own port resolution and is not affected by this.
+# (ok start) has its own port resolution and is not affected by this.
# VITE_PORT=9999
diff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdx
index 551972dc9..94b257fa9 100644
--- a/docs/content/reference/cli.mdx
+++ b/docs/content/reference/cli.mdx
@@ -119,7 +119,7 @@ Each project runs its own local server. These commands let you see and stop them
| `ok status` | Show whether a server and UI are running for the current project |
| `ok ps` | List every running OpenKnowledge server on your machine |
| `ok stop` | Stop the server for the current directory — or pass a port, path, or PID to stop a specific server, or `all` to stop every server. Declines when something is still connected to the target, naming how many clients are attached; pass `--force` to stop it anyway. A server it cannot reach is stopped without the check |
-| `ok clean` | Remove stale lock files left behind by a crash (never touches live servers) |
+| `ok clean` | Remove a stale lock file left behind by a crash (never touches live servers) |
## Remote Control
diff --git a/packages/app/scripts/measure-sweep.sh b/packages/app/scripts/measure-sweep.sh
index b2d331abb..b9c32826c 100755
--- a/packages/app/scripts/measure-sweep.sh
+++ b/packages/app/scripts/measure-sweep.sh
@@ -180,11 +180,11 @@ echo "[measure-sweep] starting ok server on a kernel-assigned port…"
( cd "$SCRATCH" && exec node "$CLI_BIN" start --port 0 ) >"$SERVER_LOG" 2>&1 &
SERVER_PID=$!
-# The Editor SPA the browser drives is the `ui.lock` port; the API `server.lock`
-# confirms the collab/HTTP side is up. Both are written under <content>/.ok/local.
-read_lock_port() {
- local lock_name="$1" lock port
- lock="$(find "$SCRATCH/.ok" -name "$lock_name" 2>/dev/null | head -1 || true)"
+# Single-listener topology: one `server.lock` port (written under
+# <content>/.ok/local) serves both the Editor SPA and the API.
+read_server_port() {
+ local lock port
+ lock="$(find "$SCRATCH/.ok" -name server.lock 2>/dev/null | head -1 || true)"
[[ -z "$lock" ]] && return 1
port="$(jq -r '.port // 0' "$lock" 2>/dev/null || echo 0)"
[[ "$port" =~ ^[0-9]+$ ]] && (( port > 0 )) && { printf '%s\n' "$port"; return 0; }
@@ -193,7 +193,7 @@ read_lock_port() {
EDITOR_PORT=""
for i in $(seq 1 120); do
- if EDITOR_PORT="$(read_lock_port ui.lock)" && read_lock_port server.lock >/dev/null; then
+ if EDITOR_PORT="$(read_server_port)"; then
echo "[measure-sweep] editor ready on port $EDITOR_PORT (after $((i))*0.5s)"
break
fi
diff --git a/packages/cli/src/commands/clean.test.ts b/packages/cli/src/commands/clean.test.ts
index 71eeb83f0..c428c5d15 100644
--- a/packages/cli/src/commands/clean.test.ts
+++ b/packages/cli/src/commands/clean.test.ts
@@ -15,16 +15,16 @@ function alive(pid: number, port: number): LockState {
},
};
}
-function missing(name: string): LockState {
- return { status: 'missing', lockPath: `/tmp/${name}.lock` };
+function missing(): LockState {
+ return { status: 'missing', lockPath: '/tmp/server.lock' };
}
-function corrupt(name: string): LockState {
- return { status: 'corrupt', lockPath: `/tmp/${name}.lock` };
+function corrupt(): LockState {
+ return { status: 'corrupt', lockPath: '/tmp/server.lock' };
}
-function dead(name: string, pid: number): LockState {
+function dead(pid: number): LockState {
return {
status: 'dead-pid',
- lockPath: `/tmp/${name}.lock`,
+ lockPath: '/tmp/server.lock',
lock: {
pid,
port: 0,
@@ -34,10 +34,10 @@ function dead(name: string, pid: number): LockState {
},
};
}
-function foreign(name: string): LockState {
+function foreign(): LockState {
return {
status: 'foreign-host',
- lockPath: `/tmp/${name}.lock`,
+ lockPath: '/tmp/server.lock',
lock: {
pid: 1,
port: 3000,
@@ -49,33 +49,34 @@ function foreign(name: string): LockState {
}
describe('buildCleanPlan', () => {
- test('no stale → empty prune', () => {
- const plan = buildCleanPlan(alive(100, 3001), alive(200, 3000));
+ test('alive → empty prune', () => {
+ const plan = buildCleanPlan(alive(100, 3001));
expect(plan.prune).toEqual([]);
});
- test('dead + corrupt → both pruned', () => {
- const plan = buildCleanPlan(dead('server', 999), corrupt('ui'));
+ test('dead-pid → pruned', () => {
+ const plan = buildCleanPlan(dead(999));
expect(plan.prune).toEqual([
{ name: 'server', lockPath: '/tmp/server.lock', reason: 'dead-pid' },
- { name: 'ui', lockPath: '/tmp/ui.lock', reason: 'corrupt' },
+ ]);
+ });
+
+ test('corrupt → pruned', () => {
+ const plan = buildCleanPlan(corrupt());
+ expect(plan.prune).toEqual([
+ { name: 'server', lockPath: '/tmp/server.lock', reason: 'corrupt' },
]);
});
test('missing locks are not pruned', () => {
- const plan = buildCleanPlan(missing('server'), missing('ui'));
+ const plan = buildCleanPlan(missing());
expect(plan.prune).toEqual([]);
});
test('foreign-host locks are not pruned (not ours to touch)', () => {
- const plan = buildCleanPlan(foreign('server'), foreign('ui'));
+ const plan = buildCleanPlan(foreign());
expect(plan.prune).toEqual([]);
});
-
- test('mix: live server + stale ui → only ui pruned', () => {
- const plan = buildCleanPlan(alive(100, 3001), dead('ui', 999));
- expect(plan.prune.map((t) => t.name)).toEqual(['ui']);
- });
});
describe('runClean', () => {
@@ -84,7 +85,7 @@ describe('runClean', () => {
const unlinked: string[] = [];
const outcome = runClean({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? alive(100, 3001) : missing('ui')),
+ inspect: () => alive(100, 3001),
unlink: (p) => unlinked.push(p),
log: (msg) => logs.push(msg),
error: () => {},
@@ -94,54 +95,28 @@ describe('runClean', () => {
expect(logs).toEqual(['No stale locks.']);
});
- test('all stale → unlink both + summary', () => {
+ test('stale → unlink + summary with singular grammar', () => {
const logs: string[] = [];
const unlinked: string[] = [];
const outcome = runClean({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? dead('server', 999) : corrupt('ui')),
+ inspect: () => dead(999),
unlink: (p) => unlinked.push(p),
log: (msg) => logs.push(msg),
error: () => {},
});
- expect(unlinked).toEqual(['/tmp/server.lock', '/tmp/ui.lock']);
- expect(outcome.pruned).toHaveLength(2);
+ expect(unlinked).toEqual(['/tmp/server.lock']);
+ expect(outcome.pruned).toHaveLength(1);
expect(outcome.failed).toEqual([]);
- expect(logs.at(0)).toContain('Pruned 2 stale locks');
- expect(logs.at(0)).toContain('server (dead-pid)');
- expect(logs.at(0)).toContain('ui (corrupt)');
- });
-
- test('singular grammar when only one stale', () => {
- const logs: string[] = [];
- runClean({
- lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? dead('server', 999) : alive(200, 3000)),
- unlink: () => {},
- log: (msg) => logs.push(msg),
- error: () => {},
- });
expect(logs.at(0)).toContain('Pruned 1 stale lock:');
- });
-
- test('live + stale — only prunes stale, leaves live alone', () => {
- const unlinked: string[] = [];
- const outcome = runClean({
- lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? alive(100, 3001) : dead('ui', 999)),
- unlink: (p) => unlinked.push(p),
- log: () => {},
- error: () => {},
- });
- expect(unlinked).toEqual(['/tmp/ui.lock']);
- expect(outcome.pruned.map((t) => t.name)).toEqual(['ui']);
+ expect(logs.at(0)).toContain('server (dead-pid)');
});
test('unlink failure → reported as failed', () => {
const errors: string[] = [];
const outcome = runClean({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? dead('server', 999) : missing('ui')),
+ inspect: () => dead(999),
unlink: () => {
throw new Error('EACCES');
},
diff --git a/packages/cli/src/commands/clean.ts b/packages/cli/src/commands/clean.ts
index 9fc6c7c8d..5b552f954 100644
--- a/packages/cli/src/commands/clean.ts
+++ b/packages/cli/src/commands/clean.ts
@@ -1,5 +1,5 @@
/**
- * `open-knowledge clean` — prune stale / corrupt lock files; never touch live
+ * `open-knowledge clean` — prune a stale / corrupt lock file; never touch live
* or foreign-host locks.
*
* Split from `ok stop` so lock-hygiene is a distinct step. "Stale" here means
@@ -12,10 +12,10 @@
import { unlinkSync } from 'node:fs';
import { type Config, resolveLockDir } from '@inkeep/open-knowledge-server';
import { Command } from 'commander';
-import { inspectLegacyUiLock, inspectLock, type LockState } from './lock-state.ts';
+import { inspectLock, type LockState } from './lock-state.ts';
interface PruneTarget {
- name: 'server' | 'ui';
+ name: 'server';
lockPath: string;
reason: 'dead-pid' | 'corrupt';
}
@@ -28,19 +28,17 @@ interface CleanPlan {
* Pure plan builder — decides which lock files should be removed. `alive`,
* `missing`, and `foreign-host` states are all left alone.
*/
-export function buildCleanPlan(server: LockState, ui: LockState): CleanPlan {
+export function buildCleanPlan(server: LockState): CleanPlan {
const prune: PruneTarget[] = [];
- for (const [name, state] of [['server', server] as const, ['ui', ui] as const]) {
- if (state.status === 'dead-pid' || state.status === 'corrupt') {
- prune.push({ name, lockPath: state.lockPath, reason: state.status });
- }
+ if (server.status === 'dead-pid' || server.status === 'corrupt') {
+ prune.push({ name: 'server', lockPath: server.lockPath, reason: server.status });
}
return { prune };
}
interface RunCleanDeps {
lockDir: string;
- inspect?: (name: 'server' | 'ui') => LockState;
+ inspect?: () => LockState;
unlink?: (path: string) => void;
log?: (msg: string) => void;
error?: (msg: string) => void;
@@ -52,18 +50,12 @@ interface CleanOutcome {
}
export function runClean(deps: RunCleanDeps): CleanOutcome {
- // The `ui` slot is the one-release legacy reap: prune a leftover pre-migration
- // `ui.lock` (dead-pid / corrupt) for upgrade goodwill. The current binary
- // writes no `ui.lock`, so `server` is the only slot it can create.
- const inspect =
- deps.inspect ??
- ((name) =>
- name === 'ui' ? inspectLegacyUiLock(deps.lockDir) : inspectLock(deps.lockDir, name));
+ const inspect = deps.inspect ?? (() => inspectLock(deps.lockDir, 'server'));
const unlink = deps.unlink ?? ((path) => unlinkSync(path));
const log = deps.log ?? ((msg) => console.log(msg));
const error = deps.error ?? ((msg) => console.error(msg));
- const plan = buildCleanPlan(inspect('server'), inspect('ui'));
+ const plan = buildCleanPlan(inspect());
if (plan.prune.length === 0) {
log('No stale locks.');
@@ -97,7 +89,7 @@ export function runClean(deps: RunCleanDeps): CleanOutcome {
export function cleanCommand(getConfig: () => Config): Command {
return new Command('clean')
- .description('Prune stale / corrupt open-knowledge lock files (never touches live locks)')
+ .description('Prune a stale / corrupt open-knowledge lock file (never touches live locks)')
.action(() => {
// Lock anchor is the project root (cwd), not contentDir — see
// server-factory.ts. Loading config still surfaces project-config errors.
diff --git a/packages/cli/src/commands/diagnose-health-checks/server-lock.test.ts b/packages/cli/src/commands/diagnose-health-checks/server-lock.test.ts
index 39fb1c73a..bbb97eb71 100644
--- a/packages/cli/src/commands/diagnose-health-checks/server-lock.test.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/server-lock.test.ts
@@ -55,7 +55,7 @@ describe('server-lock check', () => {
test('passes when .ok/local exists but no server.lock', async () => {
const cwd = makeProjectWithLockDir();
const def = makeServerLockCheck({
- inspect: (_lockDir, _name): LockState => ({ status: 'missing', lockPath: '' }),
+ inspect: (): LockState => ({ status: 'missing', lockPath: '' }),
});
const result = await def.run({ cwd });
expect(result.status).toBe('pass');
@@ -65,7 +65,7 @@ describe('server-lock check', () => {
test('fails when a live server holds the lock', async () => {
const cwd = makeProjectWithLockDir();
const def = makeServerLockCheck({
- inspect: (_lockDir, _name): LockState => ({
+ inspect: (): LockState => ({
status: 'alive',
lockPath: '/x/server.lock',
lock: makeLockMeta(),
@@ -82,7 +82,7 @@ describe('server-lock check', () => {
test('warns on foreign-host', async () => {
const cwd = makeProjectWithLockDir();
const def = makeServerLockCheck({
- inspect: (_lockDir, _name): LockState => ({
+ inspect: (): LockState => ({
status: 'foreign-host',
lockPath: '/x/server.lock',
lock: makeLockMeta({ hostname: 'other-host' }),
@@ -97,7 +97,7 @@ describe('server-lock check', () => {
test('warns on dead-pid', async () => {
const cwd = makeProjectWithLockDir();
const def = makeServerLockCheck({
- inspect: (_lockDir, _name): LockState => ({
+ inspect: (): LockState => ({
status: 'dead-pid',
lockPath: '/x/server.lock',
lock: makeLockMeta({ pid: 999999 }),
@@ -112,7 +112,7 @@ describe('server-lock check', () => {
test('warns on corrupt lockfile', async () => {
const cwd = makeProjectWithLockDir();
const def = makeServerLockCheck({
- inspect: (_lockDir, _name): LockState => ({
+ inspect: (): LockState => ({
status: 'corrupt',
lockPath: '/x/server.lock',
}),
diff --git a/packages/cli/src/commands/diagnose-health-checks/server-lock.ts b/packages/cli/src/commands/diagnose-health-checks/server-lock.ts
index 2cfb723ad..8eff229fb 100644
--- a/packages/cli/src/commands/diagnose-health-checks/server-lock.ts
+++ b/packages/cli/src/commands/diagnose-health-checks/server-lock.ts
@@ -14,11 +14,11 @@ import { inspectLock, type LockState } from '../lock-state.ts';
import type { CheckContext, CheckDefinition, CheckResult } from './types.ts';
interface ServerLockCheckDeps {
- inspect?: (lockDir: string, name: 'server') => LockState;
+ inspect?: (lockDir: string) => LockState;
}
export function makeServerLockCheck(deps: ServerLockCheckDeps = {}): CheckDefinition {
- const inspect = deps.inspect ?? inspectLock;
+ const inspect = deps.inspect ?? ((dir) => inspectLock(dir, 'server'));
return {
name: 'server-lock',
run: async (ctx: CheckContext): Promise<CheckResult> => {
@@ -30,7 +30,7 @@ export function makeServerLockCheck(deps: ServerLockCheckDeps = {}): CheckDefini
summary: 'no server lock (no `.ok/local/` yet)',
};
}
- const state = inspect(lockDir, 'server');
+ const state = inspect(lockDir);
switch (state.status) {
case 'missing':
return {
diff --git a/packages/cli/src/commands/diagnose.test.ts b/packages/cli/src/commands/diagnose.test.ts
index 1f4d23831..dccbdb625 100644
--- a/packages/cli/src/commands/diagnose.test.ts
+++ b/packages/cli/src/commands/diagnose.test.ts
@@ -36,7 +36,7 @@ function makeServerLock(pid: number, worktreeRoot: string, port = 5173): LockSta
function makeBaseDeps(outDir: string) {
return {
discover: async () => [],
- inspect: (_: string, __: 'server'): LockState => ({ status: 'missing', lockPath: '' }),
+ inspect: (): LockState => ({ status: 'missing', lockPath: '' }),
resolveCommand: (_: number) => '/usr/local/bin/node /tmp/cli.ts start',
resolveUsage: (_: number) => ({ cpuPercent: 1.2, memPercent: 0.4 }),
collectLsofFn: (_: number) => 'COMMAND PID USER FD TYPE DEVICE SIZE NAME\n',
@@ -139,10 +139,7 @@ describe('runDiagnose', () => {
{
...makeBaseDeps(out),
discover: async () => [`${worktreeRoot}/.ok/local`],
- inspect: (_lockDir, name) =>
- name === 'server'
- ? makeServerLock(pid, worktreeRoot)
- : { status: 'missing', lockPath: '' },
+ inspect: () => makeServerLock(pid, worktreeRoot),
},
);
@@ -163,8 +160,7 @@ describe('runDiagnose', () => {
{
...makeBaseDeps(contentDir),
discover: async () => [`${contentDir}/.ok/local`],
- inspect: (_lockDir, name) =>
- name === 'server' ? makeServerLock(pid, contentDir) : { status: 'missing', lockPath: '' },
+ inspect: () => makeServerLock(pid, contentDir),
log: (m) => logs.push(m),
},
);
diff --git a/packages/cli/src/commands/diagnose.ts b/packages/cli/src/commands/diagnose.ts
index d63996568..4de4560a9 100644
--- a/packages/cli/src/commands/diagnose.ts
+++ b/packages/cli/src/commands/diagnose.ts
@@ -281,7 +281,7 @@ function summarizeProfile(profileJson: string): string {
interface DiagnoseProcessDeps {
discover?: () => Promise<string[]>;
- inspect?: (lockDir: string, name: 'server') => LockState;
+ inspect?: (lockDir: string) => LockState;
resolveCommand?: (pid: number) => string | null;
resolveUsage?: (pid: number) => ProcessUsage | null;
collectLsofFn?: (pid: number) => string | null;
@@ -317,7 +317,7 @@ export async function runDiagnose(
const { pid, cpuProfileSecs = 15, noInspector = false } = opts;
const log = deps.log ?? ((m: string) => console.log(m));
const discover = deps.discover ?? discoverLockDirs;
- const inspect = deps.inspect ?? inspectLock;
+ const inspect = deps.inspect ?? ((dir) => inspectLock(dir, 'server'));
const resolveCmd = deps.resolveCommand ?? processCommand;
const resolveUsage = deps.resolveUsage ?? processUsage;
const lsofFn = deps.collectLsofFn ?? collectLsof;
@@ -353,7 +353,7 @@ export async function runDiagnose(
let contentDir: string | null = null;
let lockInfo: unknown = null;
for (const lockDir of lockDirs) {
- const s = inspect(lockDir, 'server');
+ const s = inspect(lockDir);
if (s.status !== 'missing' && s.status !== 'corrupt' && s.lock.pid === pid) {
contentDir = s.lock.worktreeRoot;
lockInfo = { lockDir, state: s.status, lockPath: s.lockPath, lock: s.lock };
diff --git a/packages/cli/src/commands/lock-state.test.ts b/packages/cli/src/commands/lock-state.test.ts
index 6a76576d8..631d900af 100644
--- a/packages/cli/src/commands/lock-state.test.ts
+++ b/packages/cli/src/commands/lock-state.test.ts
@@ -2,7 +2,7 @@ import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { hostname, tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
-import { inspectLegacyUiLock, inspectLock } from './lock-state.ts';
+import { inspectLock } from './lock-state.ts';
function freshLockDir(): string {
const dir = mkdtempSync(join(tmpdir(), 'ok-lock-state-'));
@@ -20,14 +20,10 @@ describe('inspectLock', () => {
test('corrupt JSON', () => {
const dir = freshLockDir();
- writeFileSync(join(dir, 'ui.lock'), 'not-json{{{', 'utf-8');
- // `inspectLegacyUiLock` is the one-release reap's only `ui.lock` reader.
- // Reading it here proves LEGACY_UI_LOCK_FILENAME + the path join resolve to
- // `ui.lock` (a wrong filename would classify it 'missing', silently
- // skipping the reap in `ok stop` / `ok clean`).
- const result = inspectLegacyUiLock(dir);
+ writeFileSync(join(dir, 'server.lock'), 'not-json{{{', 'utf-8');
+ const result = inspectLock(dir, 'server');
expect(result.status).toBe('corrupt');
- expect(result.lockPath.endsWith('/ui.lock')).toBe(true);
+ expect(result.lockPath.endsWith('/server.lock')).toBe(true);
});
test('valid JSON but missing pid is treated as corrupt', () => {
@@ -138,7 +134,7 @@ describe('inspectLock', () => {
test('dead pid on same host', () => {
const dir = freshLockDir();
writeFileSync(
- join(dir, 'ui.lock'),
+ join(dir, 'server.lock'),
JSON.stringify({
pid: 999999,
hostname: hostname(),
@@ -148,7 +144,7 @@ describe('inspectLock', () => {
}),
'utf-8',
);
- const result = inspectLegacyUiLock(dir, { isAlive: () => false });
+ const result = inspectLock(dir, 'server', { isAlive: () => false });
expect(result.status).toBe('dead-pid');
if (result.status === 'dead-pid') {
expect(result.lock.pid).toBe(999999);
diff --git a/packages/cli/src/commands/lock-state.ts b/packages/cli/src/commands/lock-state.ts
index 00a3ea47c..1c4a7b37e 100644
--- a/packages/cli/src/commands/lock-state.ts
+++ b/packages/cli/src/commands/lock-state.ts
@@ -10,7 +10,6 @@
import { existsSync, readFileSync } from 'node:fs';
import { hostname } from 'node:os';
-import { join } from 'node:path';
import {
getMachineId,
isProcessAlive,
@@ -36,8 +35,13 @@ interface InspectLockOptions {
machineId?: string;
}
-/** Classify a lock file at an explicit path — never mutates the filesystem. */
-function inspectLockPath(lockPath: string, opts: InspectLockOptions): LockState {
+/** Classify a lock file — never mutates the filesystem. */
+export function inspectLock(
+ lockDir: string,
+ lockName: LockName,
+ opts: InspectLockOptions = {},
+): LockState {
+ const lockPath = lockFilePath(lockDir, lockName);
if (!existsSync(lockPath)) return { status: 'missing', lockPath };
let parsed: unknown;
@@ -85,26 +89,3 @@ function inspectLockPath(lockPath: string, opts: InspectLockOptions): LockState
}
return { status: 'alive', lockPath, lock };
}
-
-export function inspectLock(
- lockDir: string,
- lockName: LockName,
- opts: InspectLockOptions = {},
-): LockState {
- return inspectLockPath(lockFilePath(lockDir, lockName), opts);
-}
-
-/** Filename of the retired UI lock — only the legacy reap below reads it. */
-const LEGACY_UI_LOCK_FILENAME = 'ui.lock';
-
-/**
- * One-release legacy-reap carve-out: peek a leftover `ui.lock` written by a
- * pre-migration `ok ui` holder. The current binary never writes `ui.lock`
- * (`LockName` narrowed to `'server'`), so this is the only remaining reader —
- * `ok stop` SIGTERMs a live legacy holder and `ok clean` prunes a stale one for
- * one release of upgrade goodwill. Reads the filename directly (not via the
- * `LockName` surface) to stay isolated from the live lock. Delete with the reap.
- */
-export function inspectLegacyUiLock(lockDir: string, opts: InspectLockOptions = {}): LockState {
- return inspectLockPath(join(lockDir, LEGACY_UI_LOCK_FILENAME), opts);
-}
diff --git a/packages/cli/src/commands/ps.test.ts b/packages/cli/src/commands/ps.test.ts
index d27d5a964..a14c278b7 100644
--- a/packages/cli/src/commands/ps.test.ts
+++ b/packages/cli/src/commands/ps.test.ts
@@ -79,12 +79,12 @@ function makeForeignServer(overrides?: {
const missingLock: LockState = {
status: 'missing',
- lockPath: '/tmp/notes/.ok/ui.lock',
+ lockPath: '/tmp/notes/.ok/server.lock',
};
const corruptLock: LockState = {
status: 'corrupt',
- lockPath: '/tmp/notes/.ok/ui.lock',
+ lockPath: '/tmp/notes/.ok/server.lock',
};
// ---------------------------------------------------------------------------
diff --git a/packages/cli/src/commands/ps.ts b/packages/cli/src/commands/ps.ts
index 2847e2986..eb591fab9 100644
--- a/packages/cli/src/commands/ps.ts
+++ b/packages/cli/src/commands/ps.ts
@@ -106,12 +106,6 @@ function buildEntry(
command: string | null,
serverUsage: ProcessUsage | null,
): PsEntry | null {
- // Discard entries where server lock is missing or corrupt. This intentionally
- // hides a lone pre-migration `ui.lock` holder (a lockDir with no `server.lock`):
- // `ok ps` shows current-topology processes only. Such an orphan stays reap-able
- // — `process-scan`'s discovery keeps the `ui.lock` disjunct so `ok stop <pid>`,
- // `ok stop all`, and `ok clean` still reach it (all deleted together in the
- // reap-removal follow-up).
if (serverState.status === 'missing' || serverState.status === 'corrupt') {
return null;
}
@@ -285,7 +279,7 @@ export function renderTable(entries: PsEntry[]): string {
interface RunPsDeps {
discover?: () => Promise<string[]>;
- inspect?: (lockDir: string, name: 'server') => LockState;
+ inspect?: (lockDir: string) => LockState;
resolveCommand?: (pid: number) => string | null;
resolveUsage?: (pid: number) => ProcessUsage | null;
json?: boolean;
@@ -295,7 +289,7 @@ interface RunPsDeps {
export async function runPs(deps: RunPsDeps = {}): Promise<void> {
const discover = deps.discover ?? discoverLockDirs;
- const inspect = deps.inspect ?? inspectLock;
+ const inspect = deps.inspect ?? ((dir) => inspectLock(dir, 'server'));
const log = deps.log ?? ((msg) => console.log(msg));
const resolveCommand = deps.resolveCommand ?? processCommand;
const resolveUsage = deps.resolveUsage ?? processUsage;
@@ -304,7 +298,7 @@ export async function runPs(deps: RunPsDeps = {}): Promise<void> {
const entries: PsEntry[] = [];
for (const lockDir of lockDirs) {
- const serverState = inspect(lockDir, 'server');
+ const serverState = inspect(lockDir);
const command =
serverState.status === 'missing' || serverState.status === 'corrupt'
? null
@@ -322,14 +316,14 @@ export async function runPs(deps: RunPsDeps = {}): Promise<void> {
if (deps.json) {
// JSON: always include all statuses (caller filters). Each entry carries
// the computed `displayStatus` so tooling consumers don't have to
- // replicate the override rules (desktop/ui-orphan/stale derivation).
+ // replicate the override rules (desktop/stale derivation).
const enriched = entries.map((e) => ({ ...e, displayStatus: displayStatus(e) }));
log(JSON.stringify(enriched, null, 2));
return;
}
// Text mode: filter by displayStatus. Default shows running / desktop /
- // foreign / ui-orphan (everything except `stale`). `--all` adds stale.
+ // foreign (everything except `stale`). `--all` adds stale.
const filtered = deps.all
? entries
: entries.filter((e) => DEFAULT_VISIBLE.has(displayStatus(e)));
diff --git a/packages/cli/src/commands/status.ts b/packages/cli/src/commands/status.ts
index 972697fcb..35544d250 100644
--- a/packages/cli/src/commands/status.ts
+++ b/packages/cli/src/commands/status.ts
@@ -1,6 +1,6 @@
/**
- * `open-knowledge status` — human-readable inspection of the server / ui
- * lockfile state.
+ * `open-knowledge status` — whether the server and UI are running for this
+ * project, derived entirely from the server lockfile.
*
* Exits 0 regardless of whether processes are live; this is a pure query
* command. Prints formatted text by default, JSON with `--json`.
@@ -20,9 +20,8 @@ interface StatusEntry {
/** Resolved `alive` verdict — `true` for local-live locks, `false` for
* `missing` / `dead-pid` / `corrupt`, `'unknown'` for foreign-host. */
alive: boolean | 'unknown';
- /** UI only: the UI is served by the project server itself (single-listener
- * default — server.lock advertises the `ui` capability and no ui.lock
- * exists), rather than by a separate `ok ui` sibling. */
+ /** UI only: true when the project server itself serves the UI —
+ * `server.lock` advertises the `ui` capability. */
servedByServer?: boolean;
}
@@ -34,11 +33,11 @@ interface StatusReport {
export function buildStatusReport(server: LockState): StatusReport {
const serverEntry = summarize('server', server);
// Single-listener topology: plain `ok start` serves the UI from the project
- // server and writes NO ui.lock, so the ui row is derived entirely from
- // server.lock's `ui` capability via the shared `lockAdvertisesUi` predicate
- // (a missing `capabilities` field on a pre-v2 server is treated as ui-capable,
- // matching preview_url / the redirect). A bare `--only server` boot advertises
- // no `ui`, so its ui row is correctly empty.
+ // server, so the ui row is derived entirely from server.lock's `ui` capability
+ // via the shared `lockAdvertisesUi` predicate (a missing `capabilities` field
+ // on a pre-v2 server is treated as ui-capable, matching preview_url / the
+ // redirect). A bare `--only server` boot advertises no `ui`, so its ui row is
+ // correctly empty.
const uiEntry: StatusEntry =
server.status === 'alive' && lockAdvertisesUi(server.lock)
? {
@@ -140,7 +139,7 @@ export function runStatus(deps: RunStatusDeps): StatusReport {
export function statusCommand(getConfig: () => Config): Command {
return new Command('status')
- .description('Show live state of the server + ui lockfiles for this project')
+ .description('Show whether the server and UI are running for this project')
.option('--json', 'Emit structured JSON instead of formatted text')
.action((opts: { json?: boolean }) => {
// Lock anchor is the project root (cwd for the CLI), not contentDir —
diff --git a/packages/cli/src/commands/stop.test.ts b/packages/cli/src/commands/stop.test.ts
index c18a09362..58036e7c1 100644
--- a/packages/cli/src/commands/stop.test.ts
+++ b/packages/cli/src/commands/stop.test.ts
@@ -50,27 +50,17 @@ function foreign(pid: number, port: number): LockState {
}
describe('buildStopPlan', () => {
- test('both alive → both targeted', () => {
- const plan = buildStopPlan(aliveLock(100, 3001), aliveLock(200, 3000));
- expect(plan.targets).toEqual([
- { name: 'server', pid: 100, port: 3001 },
- { name: 'ui', pid: 200, port: 3000 },
- ]);
- });
-
- test('neither alive → no targets', () => {
- const plan = buildStopPlan(missing(), dead(999));
- expect(plan.targets).toEqual([]);
+ test('alive is targeted even when the pid probe reports dead', () => {
+ const plan = buildStopPlan(aliveLock(100, 3001), { isAlive: () => false });
+ expect(plan.targets).toEqual([{ name: 'server', pid: 100, port: 3001 }]);
});
- test('only server alive → only server targeted', () => {
- const plan = buildStopPlan(aliveLock(100, 3001), dead(999));
- expect(plan.targets).toEqual([{ name: 'server', pid: 100, port: 3001 }]);
+ test('missing → no targets', () => {
+ expect(buildStopPlan(missing()).targets).toEqual([]);
});
- test('only ui alive → only ui targeted', () => {
- const plan = buildStopPlan(missing(), aliveLock(200, 3000));
- expect(plan.targets).toEqual([{ name: 'ui', pid: 200, port: 3000 }]);
+ test('dead-pid → no targets', () => {
+ expect(buildStopPlan(dead(999)).targets).toEqual([]);
});
});
@@ -92,31 +82,27 @@ describe('runStop', () => {
expect(logs).toEqual(['No running open-knowledge processes.']);
});
- test('both alive → SIGTERM both, log stopped summary', async () => {
+ test('alive → SIGTERM sent, log stopped summary', async () => {
const logs: string[] = [];
const killed: Array<[number, string]> = [];
const outcome = await runStop({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? aliveLock(100, 3001) : aliveLock(200, 3000)),
+ inspect: () => aliveLock(100, 3001),
kill: (pid, sig) => killed.push([pid, sig]),
log: (msg) => logs.push(msg),
error: () => {},
});
- expect(killed).toEqual([
- [100, 'SIGTERM'],
- [200, 'SIGTERM'],
- ]);
- expect(outcome.stopped.map((t) => t.name)).toEqual(['server', 'ui']);
+ expect(killed).toEqual([[100, 'SIGTERM']]);
+ expect(outcome.stopped.map((t) => t.name)).toEqual(['server']);
expect(outcome.failed).toEqual([]);
expect(logs.at(0)).toContain('server (pid=100, port=3001)');
- expect(logs.at(0)).toContain('ui (pid=200, port=3000)');
});
test('EPERM on kill → failure reported, outcome.failed populated', async () => {
const errors: string[] = [];
const outcome = await runStop({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? aliveLock(100, 3001) : missing()),
+ inspect: () => aliveLock(100, 3001),
kill: () => {
throw new Error('EPERM');
},
@@ -130,35 +116,17 @@ describe('runStop', () => {
expect(errors.at(0)).toContain('server (pid=100)');
});
- test('mix of success + failure — reports both', async () => {
- const logs: string[] = [];
- const errors: string[] = [];
- const outcome = await runStop({
- lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? aliveLock(100, 3001) : aliveLock(200, 3000)),
- kill: (pid) => {
- if (pid === 200) throw new Error('EPERM');
- },
- log: (msg) => logs.push(msg),
- error: (msg) => errors.push(msg),
- });
- expect(outcome.stopped.map((t) => t.pid)).toEqual([100]);
- expect(outcome.failed.map((f) => f.target.pid)).toEqual([200]);
- expect(logs.some((l) => l.includes('server (pid=100'))).toBe(true);
- expect(errors.some((e) => e.includes('ui (pid=200)'))).toBe(true);
- });
-
test('dead/corrupt locks are not killed (ok clean will prune them)', async () => {
const killed: number[] = [];
const outcome = await runStop({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? dead(999) : aliveLock(200, 3000)),
+ inspect: () => dead(999),
kill: (pid) => killed.push(pid),
log: () => {},
error: () => {},
});
- expect(killed).toEqual([200]);
- expect(outcome.stopped.map((t) => t.pid)).toEqual([200]);
+ expect(killed).toEqual([]);
+ expect(outcome.hadTargets).toBe(false);
});
});
@@ -168,49 +136,16 @@ describe('runStop', () => {
describe('buildStopPlan with foreign-host states', () => {
test('foreign-host + locally-live PID → targeted (hostname drift)', () => {
- const plan = buildStopPlan(foreign(100, 3001), foreign(200, 3000), {
- isAlive: () => true,
- });
- expect(plan.targets).toEqual([
- { name: 'server', pid: 100, port: 3001 },
- { name: 'ui', pid: 200, port: 3000 },
- ]);
+ // Probe answers only for the pid, so this also pins that `isStoppableState`
+ // passes the lock's pid rather than its port.
+ const plan = buildStopPlan(foreign(100, 3001), { isAlive: (pid) => pid === 100 });
+ expect(plan.targets).toEqual([{ name: 'server', pid: 100, port: 3001 }]);
});
test('foreign-host + dead PID → skipped (truly cross-host or stale)', () => {
- const plan = buildStopPlan(foreign(100, 3001), foreign(200, 3000), {
- isAlive: () => false,
- });
+ const plan = buildStopPlan(foreign(100, 3001), { isAlive: () => false });
expect(plan.targets).toEqual([]);
});
-
- test('mix: alive + foreign-host-live → both targeted', () => {
- const plan = buildStopPlan(aliveLock(100, 3001), foreign(200, 3000), {
- isAlive: () => true,
- });
- expect(plan.targets).toEqual([
- { name: 'server', pid: 100, port: 3001 },
- { name: 'ui', pid: 200, port: 3000 },
- ]);
- });
-
- test('mix: alive + foreign-host-dead → only alive targeted', () => {
- const plan = buildStopPlan(aliveLock(100, 3001), foreign(200, 3000), {
- isAlive: () => false,
- });
- expect(plan.targets).toEqual([{ name: 'server', pid: 100, port: 3001 }]);
- });
-
- test('isAlive is consulted per-pid, not once', () => {
- const checked: number[] = [];
- buildStopPlan(foreign(100, 3001), foreign(200, 3000), {
- isAlive: (pid) => {
- checked.push(pid);
- return pid === 200;
- },
- });
- expect(checked).toEqual([100, 200]);
- });
});
describe('runStop with foreign-host states', () => {
@@ -218,24 +153,21 @@ describe('runStop with foreign-host states', () => {
const killed: Array<[number, string]> = [];
const outcome = await runStop({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? foreign(100, 3001) : foreign(200, 3000)),
+ inspect: () => foreign(100, 3001),
kill: (pid, sig) => killed.push([pid, sig]),
isAlive: () => true,
log: () => {},
error: () => {},
});
- expect(killed).toEqual([
- [100, 'SIGTERM'],
- [200, 'SIGTERM'],
- ]);
- expect(outcome.stopped.map((t) => t.pid)).toEqual([100, 200]);
+ expect(killed).toEqual([[100, 'SIGTERM']]);
+ expect(outcome.stopped.map((t) => t.pid)).toEqual([100]);
});
test('foreign-host + dead PID → no targets, no SIGTERM', async () => {
const killed: number[] = [];
const outcome = await runStop({
lockDir: '/tmp/x',
- inspect: (name) => (name === 'server' ? foreign(100, 3001) : foreign(200, 3000)),
+ inspect: () => foreign(100, 3001),
kill: (pid) => killed.push(pid),
isAlive: () => false,
log: () => {},
@@ -247,17 +179,16 @@ describe('runStop with foreign-host states', () => {
});
describe('runStop in-use guard', () => {
- const twoAlive = () => ({
+ const oneAlive = () => ({
lockDir: '/tmp/guard',
- inspect: (name: 'server' | 'ui') =>
- name === 'server' ? aliveLock(100, 3001) : aliveLock(200, 3000),
+ inspect: () => aliveLock(100, 3001),
});
test('declines when the target reports live collaboration clients', async () => {
const killed: Array<[number, string]> = [];
const errors: string[] = [];
const outcome = await runStop({
- ...twoAlive(),
+ ...oneAlive(),
kill: (pid, sig) => killed.push([pid, sig]),
log: () => {},
error: (msg) => errors.push(msg),
@@ -275,7 +206,7 @@ describe('runStop in-use guard', () => {
test('--force terminates despite live clients', async () => {
const killed: Array<[number, string]> = [];
const outcome = await runStop({
- ...twoAlive(),
+ ...oneAlive(),
force: true,
kill: (pid, sig) => killed.push([pid, sig]),
log: () => {},
@@ -283,40 +214,37 @@ describe('runStop in-use guard', () => {
probeClients: async () => 5,
});
- expect(killed).toEqual([
- [100, 'SIGTERM'],
- [200, 'SIGTERM'],
- ]);
+ expect(killed).toEqual([[100, 'SIGTERM']]);
expect(outcome.declined).toBeUndefined();
- expect(outcome.stopped).toHaveLength(2);
+ expect(outcome.stopped).toHaveLength(1);
});
test('an unreachable server (probe returns null) proceeds — it is already gone', async () => {
const killed: Array<[number, string]> = [];
const outcome = await runStop({
- ...twoAlive(),
+ ...oneAlive(),
kill: (pid, sig) => killed.push([pid, sig]),
log: () => {},
error: () => {},
probeClients: async () => null,
});
- expect(killed).toHaveLength(2);
+ expect(killed).toHaveLength(1);
expect(outcome.declined).toBeUndefined();
});
test('zero reported clients proceeds', async () => {
const killed: Array<[number, string]> = [];
const outcome = await runStop({
- ...twoAlive(),
+ ...oneAlive(),
kill: (pid, sig) => killed.push([pid, sig]),
log: () => {},
error: () => {},
probeClients: async () => 0,
});
- expect(killed).toHaveLength(2);
- expect(outcome.stopped).toHaveLength(2);
+ expect(killed).toHaveLength(1);
+ expect(outcome.stopped).toHaveLength(1);
});
});
@@ -339,7 +267,7 @@ describe('runStop durable record', () => {
const { logger, records } = captureLogger();
await runStop({
lockDir: '/tmp/target/.ok/local',
- inspect: (name) => (name === 'server' ? aliveLock(100, 3001) : aliveLock(200, 3000)),
+ inspect: () => aliveLock(100, 3001),
kill: () => {},
log: () => {},
error: () => {},
@@ -350,10 +278,7 @@ describe('runStop durable record', () => {
const record = records.find((r) => r.msg === 'stop signalled processes');
expect(record).toBeDefined();
expect(record?.obj.lockDir).toBe('/tmp/target/.ok/local');
- expect(record?.obj.signalled).toEqual([
- { name: 'server', pid: 100, port: 3001 },
- { name: 'ui', pid: 200, port: 3000 },
- ]);
+ expect(record?.obj.signalled).toEqual([{ name: 'server', pid: 100, port: 3001 }]);
expect(record?.obj.forced).toBe(false);
});
@@ -361,7 +286,7 @@ describe('runStop durable record', () => {
const { logger, records } = captureLogger();
await runStop({
lockDir: '/tmp/other/.ok/local',
- inspect: (name) => (name === 'server' ? aliveLock(7, 3001) : missing()),
+ inspect: () => aliveLock(7, 3001),
kill: () => {},
log: () => {},
error: () => {},
diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.ts
index f9d3d4a14..fdf4fbb67 100644
--- a/packages/cli/src/commands/stop.ts
+++ b/packages/cli/src/commands/stop.ts
@@ -1,10 +1,10 @@
/**
- * `open-knowledge stop` — SIGTERM the live server (plus a lingering legacy
- * `ok ui` holder, a one-release reap); leave stale locks untouched (they belong
- * to `ok clean`).
+ * `open-knowledge stop` — SIGTERM the live server; leave stale locks untouched
+ * (they belong to `ok clean`).
*
* Single-responsibility split from lock pruning. Exits 0 when there's
- * nothing live; exits 1 only when a SIGTERM fails (EPERM, etc).
+ * nothing live; exits 1 when a SIGTERM fails (EPERM, etc) or when the stop is
+ * declined because live collaboration clients are attached without `--force`.
*/
import { resolve } from 'node:path';
@@ -19,7 +19,7 @@ import type { Logger as PinoLoggerInstance } from 'pino';
import { getCliLogger } from '../cli-logger.ts';
import { getInvocationCwd } from '../project-anchor.ts';
import { discoverLockDirs } from '../utils/process-scan.ts';
-import { inspectLegacyUiLock, inspectLock, type LockState } from './lock-state.ts';
+import { inspectLock, type LockState } from './lock-state.ts';
import { runPs } from './ps.ts';
/** How long to wait for the target server to answer the in-use probe. */
@@ -84,7 +84,7 @@ export async function probeCollabClients(
}
interface StopTargetPlan {
- name: 'server' | 'ui';
+ name: 'server';
pid: number;
port: number;
}
@@ -100,32 +100,21 @@ interface BuildStopPlanDeps {
}
/**
- * Pure plan builder — from two inspected lock states, list which pids to
- * SIGTERM. `alive` states produce a target unconditionally. `foreign-host`
- * states produce a target only when the PID is locally live: macOS hostname
+ * Pure plan builder — from the inspected server lock state, list which pids to
+ * SIGTERM. An `alive` state produces a target unconditionally. A `foreign-host`
+ * state produces a target only when the PID is locally live: macOS hostname
* drift (BonjourName ↔ FQDN across DHCP/VPN/sleep) routinely flips
* same-machine entries to `foreign-host`, and refusing to stop them strands
* the process. Truly-cross-host locks fail the liveness check and are left
* alone. `missing` / `corrupt` / `dead-pid` belong to `ok clean`.
*/
-export function buildStopPlan(
- server: LockState,
- ui: LockState,
- deps: BuildStopPlanDeps = {},
-): StopPlan {
+export function buildStopPlan(server: LockState, deps: BuildStopPlanDeps = {}): StopPlan {
const isAlive = deps.isAlive ?? isProcessAlive;
- const targets: StopTargetPlan[] = [];
- for (const [name, state] of [
- ['server', server],
- ['ui', ui],
- ] as const) {
- if (state.status === 'alive') {
- targets.push({ name, pid: state.lock.pid, port: state.lock.port });
- } else if (state.status === 'foreign-host' && isAlive(state.lock.pid)) {
- targets.push({ name, pid: state.lock.pid, port: state.lock.port });
- }
- }
- return { targets };
+ return {
+ targets: isStoppableState(server, isAlive)
+ ? [{ name: 'server', pid: server.lock.pid, port: server.lock.port }]
+ : [],
+ };
}
interface RunStopDeps {
@@ -136,7 +125,7 @@ interface RunStopDeps {
* gets without opting in.
*/
force?: boolean;
- inspect?: (name: 'server' | 'ui') => LockState;
+ inspect?: () => LockState;
kill?: (pid: number, signal: NodeJS.Signals) => void;
isAlive?: (pid: number) => boolean;
log?: (msg: string) => void;
@@ -158,25 +147,19 @@ interface StopOutcome {
/**
* Execute a stop plan. Exported for tests so they can drive it without
* going through Commander. The Commander action wraps this and translates
- * `failed.length > 0` into `process.exitCode = 1`.
+ * `failed.length > 0` — or a decline for live clients — into
+ * `process.exitCode = 1`.
*/
export async function runStop(deps: RunStopDeps): Promise<StopOutcome> {
- // The `ui` slot is the one-release legacy reap: `inspectLegacyUiLock` peeks a
- // leftover pre-migration `ok ui` holder so a live one still gets SIGTERM'd.
- // The current binary writes no `ui.lock`, so `server` is the only live slot.
- const inspect =
- deps.inspect ??
- ((name) =>
- name === 'ui' ? inspectLegacyUiLock(deps.lockDir) : inspectLock(deps.lockDir, name));
+ const inspect = deps.inspect ?? (() => inspectLock(deps.lockDir, 'server'));
const kill = deps.kill ?? ((pid, signal) => process.kill(pid, signal));
const log = deps.log ?? ((msg) => console.log(msg));
const error = deps.error ?? ((msg) => console.error(msg));
const probeClients = deps.probeClients ?? probeCollabClients;
const logger = deps.logger ?? getCliLogger();
- const serverState = inspect('server');
- const uiState = inspect('ui');
- const plan = buildStopPlan(serverState, uiState, { isAlive: deps.isAlive });
+ const serverState = inspect();
+ const plan = buildStopPlan(serverState, { isAlive: deps.isAlive });
if (plan.targets.length === 0) {
log('No running open-knowledge processes.');
@@ -237,10 +220,9 @@ export async function runStop(deps: RunStopDeps): Promise<StopOutcome> {
}
/**
- * True if this lock state should be considered stoppable by `ok stop`.
- * `alive` is unconditional. `foreign-host` matches when the PID is locally
- * live — same hostname-drift logic as `buildStopPlan`. `dead-pid` /
- * `missing` / `corrupt` never match.
+ * True if this lock state should be considered stoppable by `ok stop`:
+ * `alive` unconditionally, `foreign-host` when the PID is locally live (the
+ * hostname-drift case). `dead-pid` / `missing` / `corrupt` never match.
*/
function isStoppableState(
state: LockState,
@@ -252,7 +234,7 @@ function isStoppableState(
}
/**
- * Find the lock dir matching a port or PID (either server or UI slot).
+ * Find the lock dir matching a port or PID.
* Port is checked before PID; returns null if nothing matches. Considers
* both `alive` and same-machine `foreign-host` (hostname-drift) states.
*/
@@ -264,13 +246,9 @@ async function findLockDirByNumber(
let pidMatch: string | null = null;
for (const lockDir of lockDirs) {
const server = inspectLock(lockDir, 'server');
- const ui = inspectLegacyUiLock(lockDir);
- if (isStoppableState(server, isAlive) && server.lock.port === n) return lockDir;
- if (isStoppableState(ui, isAlive) && ui.lock.port === n) return lockDir;
- if (pidMatch === null) {
- if (isStoppableState(server, isAlive) && server.lock.pid === n) pidMatch = lockDir;
- else if (isStoppableState(ui, isAlive) && ui.lock.pid === n) pidMatch = lockDir;
- }
+ if (!isStoppableState(server, isAlive)) continue;
+ if (server.lock.port === n) return lockDir;
+ if (pidMatch === null && server.lock.pid === n) pidMatch = lockDir;
}
return pidMatch;
}
@@ -318,12 +296,7 @@ async function countOtherRunningServers(exceptLockDir: string): Promise<number>
let count = 0;
for (const lockDir of lockDirs) {
if (lockDir === exceptLockDir) continue;
- if (
- isStoppableState(inspectLock(lockDir, 'server'), isProcessAlive) ||
- // Legacy `ok ui` holder: the current binary writes no `ui.lock`, so this
- // only matches a leftover pre-migration process.
- isStoppableState(inspectLegacyUiLock(lockDir), isProcessAlive)
- ) {
+ if (isStoppableState(inspectLock(lockDir, 'server'), isProcessAlive)) {
count++;
}
}
@@ -383,10 +356,7 @@ export function stopCommand(getConfig: () => Config): Command {
for (const lockDir of lockDirs) {
// Skip lockDirs with nothing stoppable to avoid noisy "no processes" messages.
// `foreign-host` with a locally-live PID counts (hostname drift).
- const server = inspectLock(lockDir, 'server');
- const ui = inspectLegacyUiLock(lockDir);
- if (!isStoppableState(server, isProcessAlive) && !isStoppableState(ui, isProcessAlive))
- continue;
+ if (!isStoppableState(inspectLock(lockDir, 'server'), isProcessAlive)) continue;
await executeStop(lockDir, force);
stopped++;
}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 53897ccc7..43c8eda11 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -94,10 +94,11 @@ export {
type PiTrustWriteAction,
probePiBridgeState,
} from './commands/pi-acp-bridge.ts';
-// `runStop` is the path-addressable stop primitive (SIGTERM the server + ui
-// pids recorded in `<lockDir>/{server,ui}.lock`). Desktop's
-// `ok:fs:remove-git-folder` IPC reuses it to deterministically tear down a
-// worktree's own collab server before deleting its `.git`.
+// `runStop` is the path-addressable stop primitive: SIGTERM the server pid
+// recorded in `<lockDir>/server.lock`, unless live collaboration clients are
+// attached — pass `force: true` to terminate anyway. Desktop's
+// `ok:fs:remove-git-folder` IPC reuses it (with `force`) to deterministically
+// tear down a worktree's own collab server before deleting its `.git`.
export { runStop } from './commands/stop.ts';
export { type LoadConfigResult, loadConfig } from './config/loader.ts';
export { type PreviewResult, previewContent } from './content/preview.ts';
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 67a4041a5..ea9f340fb 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -6721,8 +6721,8 @@ function registerIpcHandlers() {
// the per-session `recentGitRoots` membership set.
handle('ok:fs:remove-git-folder', async (_event, gitRoot) => {
// Primary teardown: deterministically stop this worktree's OWN collab
- // server (+ ui sibling) BEFORE removing its `.git`, so a deleted worktree
- // doesn't leave an orphaned server holding a now-dangling lockDir. Reuses
+ // server BEFORE removing its `.git`, so a deleted worktree doesn't leave
+ // an orphaned server holding a now-dangling lockDir. Reuses
// the path-addressable `runStop` against the worktree's lockDir. Scoped to
// the same `recentGitRoots` membership set that gates the delete itself, so
// a fabricated path can't drive a stray SIGTERM. Best-effort: a worktree
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 8add4857d..f5be8384b 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -10570,14 +10570,13 @@ export function createApiExtension(
/**
* Ensure a live project server at `dir` and return its browser-navigable
- * port. Resolution goes through `resolveUiRedirectPort` — server.lock
- * (`ui` capability) first, the still-supported `ui.lock` advertisement
- * second — so this surface agrees with `resolveUiInfo` on what "no UI"
- * means through the ui.lock compatibility window.
+ * port. Resolution goes through `resolveUiRedirectPort` — `server.lock`'s
+ * `ui` capability is the only source — so this surface agrees with
+ * `resolveUiInfo` on what "no UI" means.
*
* Three cases:
* 1. a live UI origin resolves → reuse its port.
- * 2. definitive no-UI (`--only server` holder, no sibling) → error.
+ * 2. definitive no-UI (`--only server` holder, or a degraded API-only boot) → error.
* 3. Nothing live → spawn `ok start` detached (it serves the shell by
* default) and poll for a bound ui-capable port.
*
diff --git a/packages/server/src/process-scan.test.ts b/packages/server/src/process-scan.test.ts
index ce3ca3764..449a3f0ab 100644
--- a/packages/server/src/process-scan.test.ts
+++ b/packages/server/src/process-scan.test.ts
@@ -405,7 +405,7 @@ describe('discoverLockDirs', () => {
expect(dirs).toHaveLength(0);
});
- it('discovers cwd-derived lock dirs when only ui.lock is present', async () => {
+ it('does not discover lock dirs holding only a legacy ui.lock', async () => {
const projectPath = '/Users/mike/notes';
const lockDir = `${projectPath}/.ok/local`;
@@ -422,7 +422,7 @@ describe('discoverLockDirs', () => {
existsSyncSpy.mockImplementation((p: unknown) => p === lockDir || p === `${lockDir}/ui.lock`);
const dirs = await discoverLockDirs();
- expect(dirs).toEqual([lockDir]);
+ expect(dirs).toHaveLength(0);
});
it('ignores Electron marker with empty payload', async () => {
diff --git a/packages/server/src/process-scan.ts b/packages/server/src/process-scan.ts
index b197f66ee..b6c6e66a3 100644
--- a/packages/server/src/process-scan.ts
+++ b/packages/server/src/process-scan.ts
@@ -300,18 +300,9 @@ function parseListeningPids(output: string): number[] {
return [...new Set(pids)];
}
-/**
- * Full discovery pipeline: finds all `.ok/local/` lock dirs for running
- * open-knowledge servers.
- *
- * Returns unique canonical directory paths (each is the lock dir,
- * i.e. `<contentDir>/.ok/local`).
- */
+/** A dir counts as a lock dir only when it holds a `server.lock`. */
function hasLockFile(lockDir: string): boolean {
- // The `ui.lock` disjunct is the one-release legacy-reap carve-out: a lingering
- // pre-migration `ok ui` holder with no companion `server.lock` must stay
- // discoverable so `ok stop all` / `ok clean` can reach it. Drops with the reap.
- return existsSync(join(lockDir, 'server.lock')) || existsSync(join(lockDir, 'ui.lock'));
+ return existsSync(join(lockDir, 'server.lock'));
}
function addLockDirsForCwd(candidateDirs: Set<string>, cwd: string): void {
@@ -363,6 +354,13 @@ function addLockDirsUnderCwd(candidateDirs: Set<string>, cwd: string): void {
walk(cwd, 0);
}
+/**
+ * Full discovery pipeline: finds all `.ok/local/` lock dirs for running
+ * open-knowledge servers.
+ *
+ * Returns unique canonical directory paths (each is the lock dir,
+ * i.e. `<contentDir>/.ok/local`).
+ */
export async function discoverLockDirs(): Promise<string[]> {
const candidateDirs = new Set<string>();