Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): server.lock v2 schema, one-URL contract (PRD-7811) (#3318)
omar-inkeepf39df248e40e
diff --git a/.changeset/server-lock-v2-url-contract.md b/.changeset/server-lock-v2-url-contract.mdnew file mode 100644index 000000000..9a3f8e328--- /dev/null+++ b/.changeset/server-lock-v2-url-contract.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Server and UI lock files now advertise a full base URL (`url`) alongside the port, and `capabilities` accurately lists the surfaces the process actually serves, including `"ui"` when the process itself hosts the web app. Discovery consumers (the MCP stdio shim, `preview_url`, desktop attach, and the off-cwd resolver) prefer the advertised URL and fall back to the port for locks written by older versions, so mixed-version setups keep working through the upgrade. `preview_url` can now tell "no UI is mounted" apart from "the UI runs in a sibling process" instead of ever returning a dead link.diff --git a/packages/app/src/server/hocuspocus-plugin.ts b/packages/app/src/server/hocuspocus-plugin.tsindex 1b84bb634..63e196b8a 100644--- a/packages/app/src/server/hocuspocus-plugin.ts+++ b/packages/app/src/server/hocuspocus-plugin.ts@@ -193,6 +193,9 @@ export function hocuspocusPlugin(): Plugin {// dev server resolves stored embeddings keys (dev/prod parity — without// this, semantic search only ever resolves the env key / keyless).embeddingsKeyStore: makeLazyEmbeddingsKeyStore(),+ // Vite serves the React app from the SAME listener this lock+ // advertises, so the dev process genuinely mounts the UI surface.+ capabilities: ['http', 'ws', 'ui'],...(isEphemeralTest ? { ephemeral: true, singleDocRelPath: SINGLE_DOC_REL_PATH } : {}),});@@ -220,7 +223,7 @@ export function hocuspocusPlugin(): Plugin {server.httpServer?.once('listening', () => {const addr = server.httpServer?.address();if (typeof addr === 'object' && addr !== null) {- updateServerLockPort(currentSrv.lockDir, addr.port);+ updateServerLockPort(currentSrv.lockDir, addr.port, `http://localhost:${addr.port}`);}});diff --git a/packages/cli/src/commands/ui.ts b/packages/cli/src/commands/ui.tsindex 2da11c5b0..381be3514 100644--- a/packages/cli/src/commands/ui.ts+++ b/packages/cli/src/commands/ui.ts@@ -558,7 +558,10 @@ export async function startUiServer(opts: StartUiServerOptions): Promise<UiServeconst realPort = boundPort;resolvedPort = realPort;- updateUiLockPort(lockDir, realPort);+ // `localhost` (not numeric loopback): the bind loop covers both loopback+ // families, and this origin is browser-facing — matching what pre-`url`+ // preview readers derived from `port`.+ updateUiLockPort(lockDir, realPort, `http://localhost:${realPort}`);// Schedule the safety-net self-shutdown. The timer is cancelled by// `release()` (the canonical "I'm shutting down" signal) so andiff --git a/packages/cli/src/mcp/shim.test.ts b/packages/cli/src/mcp/shim.test.tsindex 77d5c6828..ee257a6c3 100644--- a/packages/cli/src/mcp/shim.test.ts+++ b/packages/cli/src/mcp/shim.test.ts@@ -155,6 +155,39 @@ describe('MCP stdio shim server resolution', () => {expect(url).toBe('http://127.0.0.1:4123/mcp');});+ test('live lock with url prefers the advertised origin over the port', async () => {+ // The origin deliberately differs from the port-derived fallback+ // (`http://127.0.0.1:4123`) in both host and port, so a silent fall-back+ // to the port branch fails this assertion.+ const lockWithUrl: ServerLockMetadata = { ...liveLock, url: 'http://localhost:4999' };+ const url = await resolveMcpHttpUrl({+ lockDir,+ contentDir: tmp,+ readLock: () => lockWithUrl,+ isAlive: (pid) => pid === lockWithUrl.pid,+ spawn: (() => {+ throw new Error('should not spawn');+ }) as never,+ });++ expect(url).toBe('http://localhost:4999/mcp');+ });++ test('live lock with an unusable url falls back to the port-derived origin', async () => {+ const lockWithBadUrl: ServerLockMetadata = { ...liveLock, url: 'not a url' };+ const url = await resolveMcpHttpUrl({+ lockDir,+ contentDir: tmp,+ readLock: () => lockWithBadUrl,+ isAlive: (pid) => pid === lockWithBadUrl.pid,+ spawn: (() => {+ throw new Error('should not spawn');+ }) as never,+ });++ expect(url).toBe('http://127.0.0.1:4123/mcp');+ });+test('missing lock spawns ok start and polls until a live port appears', async () => {const calls: Array<{cmd: string;@@ -334,6 +367,20 @@ describe('MCP stdio shim server resolution', () => {// binds. Only the port-override branch below reuses the endpoint host.).toBe('ws://127.0.0.1:4123');+ expect(+ resolveMcpKeepaliveWsUrl(+ {+ lockDir,+ contentDir: tmp,+ readLock: () => ({ ...liveLock, url: 'http://localhost:4999' }),+ isAlive: () => true,+ },+ 'http://localhost:4123/mcp',+ ),+ // A url-carrying lock wins over the port: the WS endpoint derives from+ // the advertised origin, not DEFAULT_SERVER_HOST + port.+ ).toBe('ws://localhost:4999');+expect(resolveMcpKeepaliveWsUrl({diff --git a/packages/cli/src/mcp/shim.ts b/packages/cli/src/mcp/shim.tsindex a355c65f0..d35656d69 100644--- a/packages/cli/src/mcp/shim.ts+++ b/packages/cli/src/mcp/shim.ts@@ -35,6 +35,7 @@ import { startKeepalive as defaultStartKeepalive } from '@inkeep/open-knowledge-import {AutoStartDisabledError,isProcessAlive as defaultIsProcessAlive,+ lockBaseUrl,MCP_CONNECTION_ID_HEADER,RUNTIME_VERSION,readServerLock,@@ -177,8 +178,12 @@ function mcpUrlForPort(host: string, port: number): string {return `http://${formatHost(host)}:${port}/mcp`;}-function wsUrlForPort(host: string, port: number): string {- return `ws://${formatHost(host)}:${port}`;+function mcpUrlForBase(baseUrl: string): string {+ return `${baseUrl}/mcp`;+}++function wsUrlForBase(baseUrl: string): string {+ return baseUrl.replace(/^http/, 'ws');}function wsUrlFromMcpEndpoint(endpointUrl: string): string {@@ -190,16 +195,18 @@ function wsUrlFromMcpEndpoint(endpointUrl: string): string {return url.toString().replace(/\/$/, '');}-function livePortFromLock(+function liveBaseUrlFromLock(lock: ServerLockMetadata | null,isAlive: (pid: number) => boolean,-): number | undefined {- if (!lock || lock.port <= 0) return undefined;+): string | undefined {+ if (!lock) return undefined;// A draining holder is tearing down: its HTTP surface closes before the- // lock disappears, so the advertised port must never be dialed.+ // lock disappears, so the advertised origin must never be dialed.if (lock.draining === true) return undefined;if (!isAlive(lock.pid)) return undefined;- return lock.port;+ // Prefer the lock's one-URL origin; the numeric-loopback fallback covers+ // pre-`url` locks (see `DEFAULT_SERVER_HOST` for why not `localhost`).+ return lockBaseUrl(lock, { fallbackHost: DEFAULT_SERVER_HOST }) ?? undefined;}function readErrorLogDefault(path: string): string {@@ -264,8 +271,8 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promise}const initialLock = readLock();- const existingPort = livePortFromLock(initialLock, isAlive);- if (existingPort !== undefined) return mcpUrlForPort(DEFAULT_SERVER_HOST, existingPort);+ const existingBase = liveBaseUrlFromLock(initialLock, isAlive);+ if (existingBase !== undefined) return mcpUrlForBase(existingBase);if (opts.envAutoStart === '0') {throw new AutoStartDisabledError(@@ -298,8 +305,8 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promise`[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);+ const baseAfterDrain = liveBaseUrlFromLock(readLock(), isAlive);+ if (baseAfterDrain !== undefined) return mcpUrlForBase(baseAfterDrain);}if (!existsSync(opts.lockDir)) mkdirSync(opts.lockDir, { recursive: true });@@ -349,8 +356,8 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promisethrow new Error(`spawn failed: ${asyncSpawnError}${stderrBlock}`);}await sleep(pollIntervalMs);- const port = livePortFromLock(readLock(), isAlive);- if (port !== undefined) return mcpUrlForPort(DEFAULT_SERVER_HOST, port);+ const base = liveBaseUrlFromLock(readLock(), isAlive);+ if (base !== undefined) return mcpUrlForBase(base);}if (asyncSpawnError) {@@ -369,8 +376,8 @@ export function resolveMcpKeepaliveWsUrl(if (opts.portOverride !== undefined) return wsUrlFromMcpEndpoint(endpointUrl);const readLock = opts.readLock ?? (() => readServerLock(opts.lockDir));const isAlive = opts.isAlive ?? defaultIsProcessAlive;- const port = livePortFromLock(readLock(), isAlive);- if (port !== undefined) return wsUrlForPort(DEFAULT_SERVER_HOST, port);+ const base = liveBaseUrlFromLock(readLock(), isAlive);+ if (base !== undefined) return wsUrlForBase(base);return undefined;}diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.tsindex 7bb18ed8b..8543813ea 100644--- a/packages/desktop/src/main/window-manager.ts+++ b/packages/desktop/src/main/window-manager.ts@@ -246,6 +246,13 @@ export interface ServerLockMetadataLike {pid: number;hostname: string;port: number;+ /**+ * One-URL contract origin (see the server package's `process-lock.ts`):+ * every surface of the holder is reachable at this base. Optional for+ * legacy-lock tolerance; `lockApiOrigin` below prefers it and falls back+ * to `port`.+ */+ url?: string;startedAt: string;worktreeRoot: string;kind?: 'interactive' | 'mcp-spawned';@@ -271,6 +278,46 @@ export interface ServerLockMetadataLike {draining?: boolean;}+/**+ * Base HTTP origin to dial for a lock holder — prefers the lock's `url`+ * (validated: http(s) + loopback hostname only, since the string comes off+ * disk and becomes renderer arguments), falling back to `port` for locks+ * written by binaries predating the field or whose `url` fails validation.+ *+ * Drift warning: mirrors `lockBaseUrl`/`dialableLockOrigin` in the server+ * package's `process-lock.ts`. This module is deliberately structurally+ * independent of that package (see `ServerLockMetadataLike`), so TypeScript+ * cannot catch divergence — parity is pinned by+ * `tests/main/lock-api-origin-parity.test.ts`. One deliberate difference:+ * the canonical helper returns `null` when nothing is dialable (`port` 0,+ * no usable `url`); this one returns `http://localhost:0` — safe because+ * every caller reaches it with a post-listen lock (`port > 0` guaranteed),+ * also pinned by the parity test.+ */+export function lockApiOrigin(lock: Pick<ServerLockMetadataLike, 'port' | 'url'>): string {+ if (typeof lock.url === 'string' && lock.url.length > 0) {+ let parsed: URL | null = null;+ try {+ parsed = new URL(lock.url);+ } catch {+ parsed = null;+ }+ if (parsed && (parsed.protocol === 'http:' || parsed.protocol === 'https:')) {+ // WHATWG URL keeps the brackets in `hostname` for IPv6 literals.+ const host = parsed.hostname;+ const loopback =+ host === 'localhost' || host === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);+ if (loopback) return parsed.origin;+ }+ }+ return `http://localhost:${lock.port}`;+}++/** `/collab` WebSocket endpoint derived from the same origin as `lockApiOrigin`. */+export function lockCollabUrl(lock: Pick<ServerLockMetadataLike, 'port' | 'url'>): string {+ return `${lockApiOrigin(lock).replace(/^http/, 'ws')}/collab`;+}+interface ProjectContext {/*** User-facing absolute project path — as the caller supplied it after@@ -1760,7 +1807,7 @@ export class WindowManager {// its `startedAt` (clock-skew term) + `apiOrigin` (server-info fetch).this.deps.startup?.markServerLockReady?.({startedAt: lock.startedAt,- apiOrigin: `http://localhost:${lock.port}`,+ apiOrigin: lockApiOrigin(lock),});return this.attachToExistingServer({projectPath,@@ -2212,7 +2259,7 @@ export class WindowManager {}const port = lock.port;- const apiOrigin = `http://localhost:${port}`;+ const apiOrigin = lockApiOrigin(lock);this.deps.log?.info({event: 'desktop-ephemeral-server-spawned',@@ -2226,7 +2273,7 @@ export class WindowManager {const window = this.deps.createWindow({additionalArguments: [- `--ok-collab-url=ws://localhost:${port}/collab`,+ `--ok-collab-url=${lockCollabUrl(lock)}`,`--ok-api-origin=${apiOrigin}`,// The renderer's project label / asset base is the file's real parent.`--ok-project-path=${opts.contentDir}`,@@ -2607,7 +2654,7 @@ export class WindowManager {private async probeAttachableLock(lock: ServerLockMetadataLike): Promise<boolean> {const probe = this.deps.probeWsUpgrade;if (!probe) return true;- const url = `ws://localhost:${lock.port}/collab/__attach_probe__`;+ const url = `${lockCollabUrl(lock)}/__attach_probe__`;let upgradeOk = false;try {upgradeOk = await probe(url, 500);@@ -2669,7 +2716,7 @@ export class WindowManager {freshlyCreated,} = args;const port = lock.port;- const apiOrigin = `http://localhost:${port}`;+ const apiOrigin = lockApiOrigin(lock);this.deps.log?.info({ projectPath, holderPid: lock.pid, port, startedAt: lock.startedAt },@@ -2683,7 +2730,7 @@ export class WindowManager {const window = this.deps.createWindow({additionalArguments: [- `--ok-collab-url=ws://localhost:${port}/collab`,+ `--ok-collab-url=${lockCollabUrl(lock)}`,`--ok-api-origin=${apiOrigin}`,`--ok-project-path=${projectPath}`,`--ok-project-name=${projectName}`,diff --git a/packages/desktop/tests/main/lock-api-origin-parity.test.ts b/packages/desktop/tests/main/lock-api-origin-parity.test.tsnew file mode 100644index 000000000..c1dff6b05--- /dev/null+++ b/packages/desktop/tests/main/lock-api-origin-parity.test.ts@@ -0,0 +1,54 @@+import { lockBaseUrl } from '@inkeep/open-knowledge-server';+import { describe, expect, test } from 'vitest';+import { lockApiOrigin, lockCollabUrl } from '../../src/main/window-manager';++/**+ * Pins the hand-maintained mirror in `window-manager.ts` to the canonical+ * `lockBaseUrl` in the server package. The desktop module is deliberately+ * structurally independent of the server package at runtime, so nothing but+ * this test catches the two implementations drifting apart. Test-only+ * import — not a production coupling.+ */++const DIALABLE_MATRIX: Array<{ label: string; lock: { port: number; url?: string } }> = [+ { label: 'port fallback (no url)', lock: { port: 4123 } },+ { label: 'url preferred over port', lock: { port: 4123, url: 'http://127.0.0.1:9999' } },+ { label: 'localhost url', lock: { port: 4123, url: 'http://localhost:9999' } },+ { label: 'trailing slash normalized', lock: { port: 4123, url: 'http://localhost:9999/' } },+ {+ label: 'stray path normalized to origin',+ lock: { port: 4123, url: 'http://127.0.0.1:9999/x' },+ },+ { label: 'https loopback accepted', lock: { port: 4123, url: 'https://127.0.0.1:9999' } },+ { label: 'ipv6 loopback accepted', lock: { port: 4123, url: 'http://[::1]:9999' } },+ { label: 'corrupt url falls back to port', lock: { port: 4123, url: 'not a url' } },+ {+ label: 'non-loopback host rejected',+ lock: { port: 4123, url: 'http://evil.example.com:9999' },+ },+ { label: 'private-network host rejected', lock: { port: 4123, url: 'http://10.0.0.1:9999' } },+ { label: 'non-http scheme rejected', lock: { port: 4123, url: 'ftp://127.0.0.1:9999' } },+];++describe('lockApiOrigin parity with the canonical lockBaseUrl', () => {+ test.each(DIALABLE_MATRIX)('$label', ({ lock }) => {+ expect(lockApiOrigin(lock)).toBe(lockBaseUrl(lock) ?? `http://localhost:${lock.port}`);+ });++ test('port-0 divergence is deliberate: desktop returns a string, canonical returns null', () => {+ // Desktop callers only reach lockApiOrigin with post-listen locks+ // (port > 0), so the non-null fallback is safe there; the canonical+ // helper serves callers that need "nothing dialable" as a signal.+ expect(lockBaseUrl({ port: 0 })).toBeNull();+ expect(lockApiOrigin({ port: 0 })).toBe('http://localhost:0');+ });++ test('collab URL rides the same validated origin', () => {+ expect(lockCollabUrl({ port: 4123, url: 'http://127.0.0.1:9999' })).toBe(+ 'ws://127.0.0.1:9999/collab',+ );+ expect(lockCollabUrl({ port: 4123, url: 'http://evil.example.com:9999' })).toBe(+ 'ws://localhost:4123/collab',+ );+ });+});diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex c4a30036f..6fa698f55 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -718,6 +718,10 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {authStreamHeartbeatMs: opts.authStreamHeartbeatMs,onAgentWrite: opts.onAgentWrite,lockKind,+ // `"ui"` iff THIS process serves the React shell — the accuracy contract+ // that lets `preview_url` distinguish "no UI mounted" (an API-only+ // profile) from "UI served by a sibling" (which advertises via ui.lock).+ capabilities: opts.reactShellDistDir ? ['http', 'ws', 'ui'] : ['http', 'ws'],skipStateManifestCheck: opts.skipStateManifestCheck,detectGh: opts.detectGh,tokenStore: opts.tokenStore,@@ -1033,12 +1037,15 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {const addr = httpServer.address();const realPort = typeof addr === 'object' && addr !== null ? addr.port : (opts.port ?? 0);boundPort = realPort;- updateServerLockPort(lockDir, realPort);+ // One-URL contract: the advertised origin is the same one `getServerUrl`+ // hands MCP/ACP consumers — every surface of this listener lives there.+ const boundBaseUrl = `http://${mcpHost}:${realPort}`;+ updateServerLockPort(lockDir, realPort, boundBaseUrl);if (ownsUiLock) {// Flip the sentinel port=0 to the bound port so preview-URL consumers see// a reachable URL. Only writes if we still own the lock (paranoia in// case an out-of-band release happened between acquire and listen).- updateUiLockPort(lockDir, realPort);+ updateUiLockPort(lockDir, realPort, boundBaseUrl);}// UI-sibling spawn — CLI wrapper injects `spawnUiSiblingFn`; desktop leavesdiff --git a/packages/server/src/composition-precedence.test.ts b/packages/server/src/composition-precedence.test.tsindex bff2f5f35..b61f5643b 100644--- a/packages/server/src/composition-precedence.test.ts+++ b/packages/server/src/composition-precedence.test.ts@@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, test } from 'vitest';import { WebSocket } from 'ws';import type { BootedServer } from './boot.ts';import { bootCompositionRig, parseProblem } from './composition-rig.test-helper.ts';+import type { ProcessLockMetadata } from './process-lock.ts';/*** Characterization: cross-surface route precedence, readiness, and shutdown@@ -97,6 +98,19 @@ describe('route dispatch and precedence — normal mode (no React shell)', () =>ws.close();await new Promise<void>((resolvePromise) => ws.on('close', () => resolvePromise()));});++ test('server.lock advertises the one-URL contract: url present, agreeing with port, no ui surface', () => {+ const lock = JSON.parse(+ readFileSync(resolve(normal.lockDir, 'server.lock'), 'utf-8'),+ ) as Partial<ProcessLockMetadata>;+ expect(lock.port).toBe(normal.port);+ expect(typeof lock.url).toBe('string');+ expect(new URL(lock.url as string).port).toBe(String(normal.port));+ expect(lock.capabilities).toContain('http');+ expect(lock.capabilities).toContain('ws');+ // No React shell in this process — the accuracy contract says no `ui`.+ expect(lock.capabilities).not.toContain('ui');+ });});describe('desktop-shape composition (React shell mounted)', () => {@@ -124,6 +138,15 @@ describe('desktop-shape composition (React shell mounted)', () => {await rm(desktopTmp, { recursive: true, force: true });});+ test('server.lock advertises the ui surface iff this process mounts the React shell', () => {+ const lock = JSON.parse(+ readFileSync(resolve(desktop.lockDir, 'server.lock'), 'utf-8'),+ ) as Partial<ProcessLockMetadata>;+ expect(lock.capabilities).toEqual(['http', 'ws', 'ui']);+ expect(typeof lock.url).toBe('string');+ expect(new URL(lock.url as string).port).toBe(String(desktop.port));+ });+test('SPA fallback does not shadow /mcp or /api', async () => {const deep = await fetch(`http://127.0.0.1:${desktop.port}/some/deep/route`);expect(deep.status).toBe(200);diff --git a/packages/server/src/index.ts b/packages/server/src/index.tsindex adc5d60cc..27f2be366 100644--- a/packages/server/src/index.ts+++ b/packages/server/src/index.ts@@ -368,6 +368,7 @@ export { isProcessAlive, isValidLockPid } from './process-alive.ts';export {acquireProcessLock,type LockName,+ lockBaseUrl,lockFilePath,ProcessLockCollisionError,type ProcessLockHandle,diff --git a/packages/server/src/mcp/tools/preview-url.test.ts b/packages/server/src/mcp/tools/preview-url.test.tsindex 463e53c50..1a88e1453 100644--- a/packages/server/src/mcp/tools/preview-url.test.ts+++ b/packages/server/src/mcp/tools/preview-url.test.ts@@ -11,8 +11,18 @@ import { mkdtemp, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { resolve } from 'node:path';import { LOCAL_DIR, OK_DIR } from '@inkeep/open-knowledge-core';-import { acquireUiLock, updateUiLockPort } from '../../ui-lock.ts';-import { encodeSkillRoute, resolvePreviewUrl, resolveSkillPreviewUrl } from './preview-url.ts';+import {+ acquireServerLock,+ markServerLockDraining,+ updateServerLockPort,+} from '../../server-lock.ts';+import { acquireUiLock, markUiLockDraining, updateUiLockPort } from '../../ui-lock.ts';+import {+ encodeSkillRoute,+ resolvePreviewUrl,+ resolveSkillPreviewUrl,+ resolveUiInfo,+} from './preview-url.ts';let tmpDir: string;let lockDir: string;@@ -183,3 +193,71 @@ describe('resolvePreviewUrl — round-trip via docNameFromHash', () => {expect(hash).toBe('#/trail/');});});++describe('resolveUiInfo — surface-aware source chain', () => {+ test('prefers a server.lock advertising the ui surface (single-listener topology)', () => {+ acquireServerLock(lockDir, {+ port: 0,+ worktreeRoot: tmpDir,+ capabilities: ['http', 'ws', 'ui'],+ });+ updateServerLockPort(lockDir, 6060, 'http://127.0.0.1:6060');+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://127.0.0.1:6060' });+ });++ test('server.lock without the ui surface falls through to ui.lock (sibling topology)', () => {+ acquireServerLock(lockDir, { port: 0, worktreeRoot: tmpDir, capabilities: ['http', 'ws'] });+ updateServerLockPort(lockDir, 6060, 'http://127.0.0.1:6060');+ acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });+ updateUiLockPort(lockDir, 5173, 'http://localhost:5173');+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://localhost:5173' });+ });++ test('pre-url ui.lock falls back to a port-derived localhost origin', () => {+ acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });+ updateUiLockPort(lockDir, 5173);+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://localhost:5173' });+ });++ test('no lock at all yields a null base', () => {+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: null });+ });++ test('a draining holder is never returned from either branch (single-listener teardown)', () => {+ // Single-listener teardown marks BOTH locks draining on the same+ // process. The server.lock draining guard must not be defeated by+ // falling through to that same dying process's ui.lock.+ acquireServerLock(lockDir, {+ port: 0,+ worktreeRoot: tmpDir,+ capabilities: ['http', 'ws', 'ui'],+ });+ updateServerLockPort(lockDir, 6060, 'http://127.0.0.1:6060');+ acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });+ updateUiLockPort(lockDir, 6060, 'http://localhost:6060');+ markServerLockDraining(lockDir);+ markUiLockDraining(lockDir);+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: null });+ });++ test('server.lock with ui capability but no dialable origin (pre-bind) falls through to ui.lock', () => {+ // The window between acquireServerLock and updateServerLockPort: port 0,+ // no url, but the ui capability already declared. The null-origin case+ // must fall through to the ui.lock branch, not answer "no UI".+ acquireServerLock(lockDir, {+ port: 0,+ worktreeRoot: tmpDir,+ capabilities: ['http', 'ws', 'ui'],+ });+ acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });+ updateUiLockPort(lockDir, 5173, 'http://localhost:5173');+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: 'http://localhost:5173' });+ });++ test('a draining ui.lock alone is not returned either', () => {+ acquireUiLock(lockDir, { port: 0, worktreeRoot: tmpDir });+ updateUiLockPort(lockDir, 5173, 'http://localhost:5173');+ markUiLockDraining(lockDir);+ expect(resolveUiInfo({ lockDir })).toEqual({ baseUrl: null });+ });+});diff --git a/packages/server/src/mcp/tools/preview-url.ts b/packages/server/src/mcp/tools/preview-url.tsindex 452232570..97dfe34f8 100644--- a/packages/server/src/mcp/tools/preview-url.ts+++ b/packages/server/src/mcp/tools/preview-url.ts@@ -32,6 +32,8 @@* ever needed again.*/import { resolveLockDir } from '../../config/paths.ts';+import { lockBaseUrl } from '../../process-lock.ts';+import { readServerLock } from '../../server-lock.ts';import { readUiLock } from '../../ui-lock.ts';import type { ConfigOrResolver } from './shared.ts';@@ -209,10 +211,32 @@ export interface UiInfo {* emit a `ui` block, so the base does not ride per-response payloads.*/export function resolveUiInfo(ctx: PreviewUrlContext): UiInfo {+ // Single-listener topology first: a server.lock advertising the `ui`+ // surface means THIS process serves the React shell at its own origin —+ // no ui.lock involved. A server.lock without `ui` is not "no UI": in the+ // sibling topology (`ok start` + `ok ui`) the UI advertises via ui.lock,+ // so fall through to it. Only when neither lock yields a base is the+ // answer a definitive "no UI running".+ try {+ const serverLock = readServerLock(ctx.lockDir);+ if (serverLock && serverLock.draining !== true && serverLock.capabilities?.includes('ui')) {+ const baseUrl = lockBaseUrl(serverLock);+ if (baseUrl !== null) return { baseUrl };+ }+ } catch (err) {+ process.stderr.write(+ `[preview-url] readServerLock failed at ${ctx.lockDir} while resolving ui info: ${err instanceof Error ? err.message : String(err)}\n`,+ );+ }try {const lock = readUiLock(ctx.lockDir);- if (lock && lock.port > 0) {- return { baseUrl: `http://localhost:${lock.port}` };+ // Draining check on THIS branch too, not just server.lock above:+ // single-listener teardown marks BOTH locks draining on the same+ // process, so without it the server.lock guard is defeated by falling+ // through to the same dying process's ui.lock.+ if (lock && lock.draining !== true) {+ const baseUrl = lockBaseUrl(lock);+ if (baseUrl !== null) return { baseUrl };}} catch (err) {process.stderr.write(@@ -311,26 +335,15 @@ export function resolveSkillPreviewUrl(/*** Shared reachability gate for the route resolvers: returns the route verbatim- * (no scheme/host/port) when `ui.lock` reports a running UI, else `null`.+ * (no scheme/host/port) when a running UI is reachable, else `null`.*- * The lock is read only for reachability — server.lock points at collab-only in- * the post-split lifecycle; ui.lock (CLI `ok ui` + OK Electron) is the universal- * signal that a navigable React app exists.+ * Same two-source chain as `resolveUiInfo`: a server.lock advertising the+ * `ui` surface (single-listener topology), else ui.lock (CLI `ok ui` + OK+ * Electron sibling topology) — the universal signal that a navigable React+ * app exists.*/function previewForRoute(hash: string, ctx: PreviewUrlContext): PreviewUrlResult | null {- try {- const lock = readUiLock(ctx.lockDir);- if (lock && lock.port > 0) {- return { url: hash, source: 'lock' };- }- } catch (err) {- // Lock file exists but is corrupt or unreadable. No further sources- // remain in the chain — surface the error so operators debugging- // "why won't the preview URL resolve?" aren't left in the dark.- process.stderr.write(- `[preview-url] readUiLock failed at ${ctx.lockDir}: ${err instanceof Error ? err.message : String(err)}\n`,- );- }-+ const { baseUrl } = resolveUiInfo(ctx);+ if (baseUrl !== null) return { url: hash, source: 'lock' };return null;}diff --git a/packages/server/src/off-cwd-resolver.ts b/packages/server/src/off-cwd-resolver.tsindex 78f66d189..3270c3035 100644--- a/packages/server/src/off-cwd-resolver.ts+++ b/packages/server/src/off-cwd-resolver.ts@@ -25,6 +25,7 @@ import { realpath as fsRealpath } from 'node:fs/promises';import { dirname, relative, resolve, sep } from 'node:path';import { readConfigSafely, resolveConfigPath } from '@inkeep/open-knowledge-core/server';import { isProcessAlive } from './process-alive.ts';+import { lockBaseUrl } from './process-lock.ts';import { discoverLockDirs } from './process-scan.ts';import { readUiLock } from './ui-lock.ts';@@ -135,9 +136,16 @@ export function createOffCwdResolverDeps(): OffCwdResolverDeps {return null;}const lock = readUiLock(lockDir);- const port = lock?.port ?? 0;- const alive = lock != null && port > 0 && isProcessAlive(lock.pid);- return { lockDir, contentDir, baseUrl: `http://localhost:${port}`, alive };+ // Liveness and URL derivation share one source of truth: a candidate+ // is alive only when it has a non-draining, dialable origin — the same+ // coupling as the shim's liveBaseUrlFromLock. The draining check+ // matters because single-listener teardown marks BOTH locks draining+ // while the pid is still alive.+ const resolvedBase = lock ? lockBaseUrl(lock) : null;+ const baseUrl = resolvedBase ?? `http://localhost:${lock?.port ?? 0}`;+ const alive =+ lock != null && lock.draining !== true && resolvedBase !== null && isProcessAlive(lock.pid);+ return { lockDir, contentDir, baseUrl, alive };},};}diff --git a/packages/server/src/process-lock.test.ts b/packages/server/src/process-lock.test.tsindex c9071bd5b..6b3882846 100644--- a/packages/server/src/process-lock.test.ts+++ b/packages/server/src/process-lock.test.ts@@ -8,6 +8,7 @@ import { getMachineId } from './machine-id';import {acquireProcessLock,type LockName,+ lockBaseUrl,lockFilePath,markProcessLockDraining,ProcessLockCollisionError,@@ -179,7 +180,7 @@ describe('acquireProcessLock', () => {expect(err.existing.port).toBe(9000);expect(err.lockName).toBe(LOCK_NAME);expect(err.lockPath).toBe(lockPath);- expect(err.message).toContain('already running on port 9000');+ expect(err.message).toContain('already running at port 9000');expect(err.message).toContain(LOCK_NAME);}}@@ -323,6 +324,145 @@ describe('acquireProcessLock', () => {});});+describe('one-URL contract (url field + lockBaseUrl)', () => {+ test('acquire omits url by default; updatePort(port, url) writes both in agreement', () => {+ const handle = acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 0, worktreeRoot: '/wt' },+ });+ const before: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(before.url).toBeUndefined();++ handle.updatePort(8080, 'http://127.0.0.1:8080');+ const after: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(after.port).toBe(8080);+ expect(after.url).toBe('http://127.0.0.1:8080');+ // port/url agreement: the origin's port is the port field.+ expect(new URL(after.url as string).port).toBe(String(after.port));+ });++ test('acquire round-trips an explicit url', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 4242, url: 'http://127.0.0.1:4242', worktreeRoot: '/wt' },+ });+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.url).toBe('http://127.0.0.1:4242');+ });++ test('updatePort WITHOUT url drops a previously advertised url (stale-origin guard)', () => {+ const handle = acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 0, worktreeRoot: '/wt' },+ });+ handle.updatePort(8080, 'http://127.0.0.1:8080');+ handle.updatePort(9090);+ const md: ProcessLockMetadata = JSON.parse(readFileSync(lockPath, 'utf-8'));+ expect(md.port).toBe(9090);+ expect(md.url).toBeUndefined();+ });++ test('readProcessLockDetailed carries url + capabilities through its reconstruction', () => {+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: {+ port: 4242,+ url: 'http://127.0.0.1:4242',+ worktreeRoot: '/wt',+ capabilities: ['http', 'ws', 'ui'],+ },+ });+ const result = readProcessLockDetailed({ lockName: LOCK_NAME, lockDir });+ expect(result.status).toBe('live');+ if (result.status !== 'live') return;+ expect(result.lock.url).toBe('http://127.0.0.1:4242');+ expect(result.lock.capabilities).toEqual(['http', 'ws', 'ui']);+ });++ test('lockBaseUrl prefers url over port and strips trailing slashes', () => {+ expect(lockBaseUrl({ port: 1111, url: 'http://127.0.0.1:2222/' })).toBe(+ 'http://127.0.0.1:2222',+ );+ });++ test('lockBaseUrl falls back to port with localhost by default', () => {+ expect(lockBaseUrl({ port: 3333 })).toBe('http://localhost:3333');+ });++ test('lockBaseUrl honors fallbackHost for numeric-loopback dialers', () => {+ expect(lockBaseUrl({ port: 3333 }, { fallbackHost: '127.0.0.1' })).toBe(+ 'http://127.0.0.1:3333',+ );+ });++ test('lockBaseUrl returns null when nothing is dialable (port 0, no url)', () => {+ expect(lockBaseUrl({ port: 0 })).toBeNull();+ });++ test('lockBaseUrl normalizes wildcard fallback hosts to localhost', () => {+ expect(lockBaseUrl({ port: 3000 }, { fallbackHost: '0.0.0.0' })).toBe('http://localhost:3000');+ expect(lockBaseUrl({ port: 3000 }, { fallbackHost: '::' })).toBe('http://localhost:3000');+ });++ test('lockBaseUrl brackets a bare IPv6 fallback host', () => {+ expect(lockBaseUrl({ port: 3000 }, { fallbackHost: '::1' })).toBe('http://[::1]:3000');+ });++ test('lockBaseUrl rejects a corrupt url and falls back to the port', () => {+ expect(lockBaseUrl({ port: 3000, url: 'not a url' })).toBe('http://localhost:3000');+ });++ test('lockBaseUrl rejects a non-loopback url and falls back to the port', () => {+ expect(lockBaseUrl({ port: 3000, url: 'http://evil.example.com:9999' })).toBe(+ 'http://localhost:3000',+ );+ expect(lockBaseUrl({ port: 3000, url: 'http://10.0.0.1:9999' })).toBe('http://localhost:3000');+ });++ test('lockBaseUrl rejects a non-http scheme and falls back to the port', () => {+ expect(lockBaseUrl({ port: 3000, url: 'ftp://127.0.0.1:9999' })).toBe('http://localhost:3000');+ });++ test('lockBaseUrl accepts https and IPv6 loopback origins, normalizing stray paths', () => {+ expect(lockBaseUrl({ port: 3000, url: 'https://127.0.0.1:9999' })).toBe(+ 'https://127.0.0.1:9999',+ );+ expect(lockBaseUrl({ port: 3000, url: 'http://[::1]:9999' })).toBe('http://[::1]:9999');+ expect(lockBaseUrl({ port: 3000, url: 'http://127.0.0.1:9999/some/path' })).toBe(+ 'http://127.0.0.1:9999',+ );+ });++ test('lockBaseUrl rejection of a corrupt url beats port 0 (still null)', () => {+ expect(lockBaseUrl({ port: 0, url: 'not a url' })).toBeNull();+ });++ test('collision error surfaces the advertised url when the holder has one', () => {+ const live: ProcessLockMetadata = {+ pid: aliveForeignPid(),+ hostname: hostname(),+ port: 9000,+ url: 'http://127.0.0.1:9000',+ startedAt: new Date().toISOString(),+ worktreeRoot: '/other',+ };+ mkdirSync(lockDir, { recursive: true });+ writeFileSync(lockPath, JSON.stringify(live), 'utf-8');++ expect(() =>+ acquireProcessLock({+ lockName: LOCK_NAME,+ lockDir,+ metadata: { port: 3000, worktreeRoot: '/me' },+ }),+ ).toThrow(/already running at http:\/\/127\.0\.0\.1:9000/);+ });+});+describe('updateProcessLockPort', () => {test('no-op when lock file is missing', () => {updateProcessLockPort({ lockName: LOCK_NAME, lockDir, port: 3000 });diff --git a/packages/server/src/process-lock.ts b/packages/server/src/process-lock.tsindex 9f0f22a70..0e55160b3 100644--- a/packages/server/src/process-lock.ts+++ b/packages/server/src/process-lock.ts@@ -4,7 +4,13 @@* Only one OpenKnowledge process with a given `lockName` may own a lockDir* at a time. `lockDir` is `<contentDir>/.ok/local` by convention; the* lock file sits at `<lockDir>/<lockName>.lock` and contains JSON metadata- * used for stale detection and port discovery.+ * used for stale detection and discovery.+ *+ * The lock is FIRST a mutex — the double-start guard protecting the+ * single-writer invariant — and only secondarily a discovery channel. That+ * is why it is written even in environments where nothing reads it+ * (containers): discovery fields ride on the mutex, not the reverse.+ * Acquisition happens before listen; nothing here may weaken that ordering.** Used by both `server-lock.ts` (server.lock) and `ui-lock.ts` (ui.lock).*/@@ -49,8 +55,26 @@ export interface ProcessLockMetadata {* written by binaries that predate `machineId`.*/hostname: string;- /** HTTP/WebSocket port. 0 means "starting — port not yet bound". */+ /**+ * HTTP/WebSocket port. 0 means "starting — port not yet bound".+ *+ * DEPRECATED as a dial target in favor of `url` — kept written through the+ * ui.lock-retirement compatibility window so binaries predating `url` keep+ * discovering. New readers go through `lockBaseUrl` (prefer `url`, fall+ * back to `port`). Retirement rides the `protocolVersion` 1→2 bump at the+ * ui.lock-removal wave, NOT before.+ */port: number;+ /**+ * One-origin contract: the base URL every surface of this process is+ * reachable at (`/`, `/api`, `/mcp`, `/collab` — whichever of those+ * `capabilities` advertises). Loopback origin, no trailing slash, e.g.+ * `http://127.0.0.1:61023`. Written by `updateProcessLockPort` once the+ * listener binds; absent while `port` is 0 and on locks written by+ * binaries predating the field. Readers prefer this over `port` via+ * `lockBaseUrl`.+ */+ url?: string;startedAt: string;worktreeRoot: string;/**@@ -63,8 +87,14 @@ export interface ProcessLockMetadata {/*** 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+ * advertised origin is no longer safe to dial and supervisors should wait* for pid death rather than lock disappearance. Absent means "serving".+ *+ * Deliberate two-signal design, not a wart: the flag stops discovery+ * dialing immediately, while deferring the unlink to exit keeps+ * crash-vs-clean-exit distinguishable on disk (crashed holder =+ * non-draining lock + dead pid; clean teardown = draining lock until+ * exit). "Fixing" the deferred unlink deletes the crash-detection signal.*/draining?: boolean;/**@@ -81,9 +111,16 @@ export interface ProcessLockMetadata {*/parentPid?: number;/**- * Protocol/feature surfaces this server exposes. v1: `["http", "ws"]`- * for any server booted via `bootServer`. Forward-compat for variants- * that lack one or the other.+ * Protocol/feature surfaces this server exposes. On server.lock, writers+ * that also emit `url` MUST list mounted surfaces accurately — in+ * particular `"ui"` is present iff the process itself serves the React+ * shell, so `preview_url` can distinguish "no UI mounted" from "UI served+ * elsewhere". Baseline for any `bootServer` boot is `["http", "ws"]`. On+ * server.locks without `url` (older writers) the array is best-effort+ * hints only: absence of `"ui"` is indeterminate and readers keep the+ * ui.lock fallback. On ui.lock the accuracy requirement does not apply —+ * that file's very existence is the UI signal, no reader consults its+ * `capabilities`, and the sibling retires with the ui.lock-removal wave.*/capabilities?: string[];/**@@ -106,7 +143,7 @@ export interface ProcessLockMetadata {export interface ProcessLockHandle {lockPath: string;release: () => void;- updatePort: (port: number) => void;+ updatePort: (port: number, url?: string) => void;}export class ProcessLockCollisionError extends Error {@@ -115,7 +152,7 @@ export class ProcessLockCollisionError extends Error {readonly lockName: LockName;constructor(existing: ProcessLockMetadata, lockPath: string, lockName: LockName) {super(- `OpenKnowledge ${lockName} already running on port ${existing.port} ` ++ `OpenKnowledge ${lockName} already running at ${existing.url ?? `port ${existing.port}`} ` +`(pid ${existing.pid}, started ${existing.startedAt}). ` +`Stop it first or use a different directory. Lock: ${lockPath}`,);@@ -279,6 +316,10 @@ export function acquireProcessLock(opts: {lockDir: string;metadata: {port: number;+ /** Base origin per the one-URL contract. Usually set later, alongside the+ * bound port, via `updateProcessLockPort` — pass here only when the+ * listener is already bound at acquire time. */+ url?: string;worktreeRoot: string;kind?: LockKind;parentPid?: number;@@ -299,6 +340,7 @@ export function acquireProcessLock(opts: {pid: process.pid,hostname: hostname(),port: init.port,+ ...(init.url !== undefined && { url: init.url }),startedAt: new Date().toISOString(),worktreeRoot: init.worktreeRoot,machineId: getMachineId(),@@ -383,20 +425,94 @@ function buildHandle(args: {return {lockPath,release: () => releaseProcessLock({ lockName, lockDir }),- updatePort: (port) => updateProcessLockPort({ lockName, lockDir, port }),+ updatePort: (port, url) => updateProcessLockPort({ lockName, lockDir, port, url }),};}/**- * Update only the port field of our own lock. Preserves all other fields.- * No-op if the lock file is missing, corrupt, or not ours.+ * Validate a lock's advertised `url` before any dialer sees it. The lock is+ * plain JSON on disk, and this string flows into `new URL()` dialers (the+ * MCP shim) and Electron renderer arguments (desktop attach) — so it is+ * checked, not trusted: only an http(s) origin with a loopback hostname is+ * accepted; anything corrupt, truncated, off-scheme, or pointing off the+ * machine is rejected so the caller falls through to the `port` path, which+ * is exactly what every pre-`url` reader dialed. Every legitimate writer+ * emits a loopback origin today; a non-loopback bind keeps its v1 port-+ * fallback behavior until a trusted non-loopback advertisement exists.+ * Returns the parsed origin (normalizes away trailing slashes or stray+ * paths), or null on rejection.+ *+ * Drift warning: hand-mirrored by `lockApiOrigin` in the desktop's+ * `window-manager.ts` (that package is deliberately structurally independent+ * of this one) — keep the two in sync on change; parity is pinned by the+ * desktop's lock-api-origin-parity test.+ */+function dialableLockOrigin(raw: string): string | null {+ let parsed: URL;+ try {+ parsed = new URL(raw);+ } catch {+ return null;+ }+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;+ // WHATWG URL keeps the brackets in `hostname` for IPv6 literals.+ const host = parsed.hostname;+ const loopback =+ host === 'localhost' || host === '[::1]' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host);+ if (!loopback) return null;+ return parsed.origin;+}++/**+ * Reader-side half of the one-URL contract: the base origin to dial for a+ * lock, preferring a validated `url` and falling back to `port` for locks+ * written by binaries predating the field (or whose `url` fails the+ * `dialableLockOrigin` check above). This is THE place the fallback logic+ * lives — don't re-derive origins from `port` at call sites.+ *+ * `fallbackHost` defaults to `localhost` (matches what the pre-`url` readers+ * dialed); callers that must dial numeric IPv4 loopback (the MCP shim — see+ * `DEFAULT_SERVER_HOST`'s JSDoc for the Windows ECONNREFUSED trap) pass it+ * explicitly. Returns `null` when the lock advertises no dialable origin+ * (`port` 0 and no usable `url`).+ */+export function lockBaseUrl(+ lock: Pick<ProcessLockMetadata, 'port' | 'url'>,+ opts?: { fallbackHost?: string },+): string | null {+ if (typeof lock.url === 'string' && lock.url.length > 0) {+ const origin = dialableLockOrigin(lock.url);+ if (origin !== null) return origin;+ }+ if (lock.port > 0) {+ const host = opts?.fallbackHost ?? 'localhost';+ const formatted =+ host === '0.0.0.0' || host === '::'+ ? 'localhost'+ : host.includes(':') && !host.startsWith('[')+ ? `[${host}]`+ : host;+ return `http://${formatted}:${lock.port}`;+ }+ return null;+}++/**+ * Update the port (and, per the one-URL contract, the `url`) of our own+ * lock. Preserves all other fields. No-op if the lock file is missing,+ * corrupt, or not ours.+ *+ * When `url` is omitted, any previously written `url` is DROPPED, not kept:+ * a port change invalidates the advertised origin, and a stale `url` would+ * send prefer-`url` readers to a dead port while `port` says otherwise.*/export function updateProcessLockPort(opts: {lockName: LockName;lockDir: string;port: number;+ url?: string;}): void {- const { lockName, lockDir, port } = opts;+ const { lockName, lockDir, port, url } = opts;const logPrefix = `[${lockName}-lock]`;const lockPath = lockFilePath(lockDir, lockName);@@ -436,6 +552,11 @@ export function updateProcessLockPort(opts: {if (!isSameMachine(existing)) return;existing.port = port;+ if (url !== undefined) {+ existing.url = url;+ } else {+ delete existing.url;+ }try {// `mode: 0o600` — owner-only readable. Matches `acquireProcessLock`'s// atomic-create mode so port updates don't drop back to default (0644).@@ -619,10 +740,15 @@ export function readProcessLockDetailed(opts: {pid: r.pid,hostname: r.hostname,port: r.port,+ url: typeof r.url === 'string' ? r.url : undefined,startedAt: r.startedAt,worktreeRoot: r.worktreeRoot,machineId: typeof r.machineId === 'string' ? r.machineId : undefined,draining: r.draining === true ? true : undefined,+ capabilities:+ Array.isArray(r.capabilities) && r.capabilities.every((c) => typeof c === 'string')+ ? r.capabilities+ : undefined,protocolVersion: typeof r.protocolVersion === 'number' ? r.protocolVersion : undefined,runtimeVersion: typeof r.runtimeVersion === 'string' ? r.runtimeVersion : undefined,};diff --git a/packages/server/src/server-factory.test.ts b/packages/server/src/server-factory.test.tsindex 21f6e3ca1..bf370cab7 100644--- a/packages/server/src/server-factory.test.ts+++ b/packages/server/src/server-factory.test.ts@@ -1840,7 +1840,7 @@ describe('createServer() server-lock integration (V0-1)', () => {);expect(() => createServer({ contentDir: tmpDir, projectDir: tmpDir, quiet: true })).toThrow(- /already running on port 9999/,+ /already running at port 9999/,);// Restore our own lock so destroy() cleans updiff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.tsindex 5b0204257..6a7df9c17 100644--- a/packages/server/src/server-factory.ts+++ b/packages/server/src/server-factory.ts@@ -297,6 +297,17 @@ export interface ServerOptions {* attach validation refuses to attach to non-interactive locks.*/lockKind?: 'interactive' | 'mcp-spawned';+ /**+ * Surfaces this process serves, written into the lock's `capabilities`+ * for discovery — advertisement only, this does not enable or disable+ * anything. Defaults to `["http", "ws"]` (every `createServer` boot wires+ * both). Callers whose process ALSO serves the React shell (the Electron+ * utility's `reactShellDistDir` boot, the Vite dev plugin) add `"ui"` so+ * `preview_url` can answer "no UI mounted" from server.lock alone. Must+ * accurately list what this process mounts — see the field's contract in+ * `process-lock.ts`.+ */+ capabilities?: string[];/*** Skip the durable state-manifest pre-flight gate* (`assertCompatibleStateManifest` from `state-manifest.ts`). Default `false`.@@ -960,9 +971,10 @@ export function createServer(options: ServerOptions): ServerInstance {worktreeRoot: projectDir,kind: options.lockKind ?? 'interactive',// Every server booted through `createServer` wires Hocuspocus + WS- // upgrade in `boot.ts`. The capability flag lets future variants- // (e.g. an HTTP-only relay) advertise differently.- capabilities: ['http', 'ws'],+ // upgrade in `boot.ts`; callers that also mount the React shell pass+ // `capabilities` with `"ui"` appended (accuracy contract in+ // `process-lock.ts`).+ capabilities: options.capabilities ?? ['http', 'ws'],});// Durable state-manifest gate. Runs AFTER lock acquisition so twodiff --git a/packages/server/src/server-lock.test.ts b/packages/server/src/server-lock.test.tsindex 41ca28f0e..857e5a5ab 100644--- a/packages/server/src/server-lock.test.ts+++ b/packages/server/src/server-lock.test.ts@@ -109,7 +109,7 @@ describe('acquireServerLock', () => {if (err instanceof ServerLockCollisionError) {expect(err.existing.pid).toBe(livePid);expect(err.existing.port).toBe(9000);- expect(err.message).toContain('already running on port 9000');+ expect(err.message).toContain('already running at port 9000');}}});diff --git a/packages/server/src/server-lock.ts b/packages/server/src/server-lock.tsindex a823278b2..ec3763b12 100644--- a/packages/server/src/server-lock.ts+++ b/packages/server/src/server-lock.ts@@ -39,6 +39,7 @@ export function acquireServerLock(lockDir: string,init: {port: number;+ url?: string;worktreeRoot: string;kind?: LockKind;parentPid?: number;@@ -57,8 +58,8 @@ export function acquireServerLock(}}-export function updateServerLockPort(lockDir: string, port: number): void {- updateProcessLockPort({ lockName: 'server', lockDir, port });+export function updateServerLockPort(lockDir: string, port: number, url?: string): void {+ updateProcessLockPort({ lockName: 'server', lockDir, port, url });}export function readServerLock(lockDir: string): ServerLockMetadata | null {diff --git a/packages/server/src/ui-lock.ts b/packages/server/src/ui-lock.tsindex 8eb597652..e8cf7a13b 100644--- a/packages/server/src/ui-lock.ts+++ b/packages/server/src/ui-lock.ts@@ -37,6 +37,7 @@ export function acquireUiLock(lockDir: string,init: {port: number;+ url?: string;worktreeRoot: string;kind?: LockKind;parentPid?: number;@@ -54,8 +55,8 @@ export function acquireUiLock(}}-export function updateUiLockPort(lockDir: string, port: number): void {- updateProcessLockPort({ lockName: 'ui', lockDir, port });+export function updateUiLockPort(lockDir: string, port: number, url?: string): void {+ updateProcessLockPort({ lockName: 'ui', lockDir, port, url });}export function readUiLock(lockDir: string): UiLockMetadata | null {