Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
feat(ok): Wave 0 characterization suite + health endpoints (PRD-7778) (#3192)
omar-inkeep1e85137cb085
diff --git a/.changeset/healthz-readyz-endpoints.md b/.changeset/healthz-readyz-endpoints.mdnew file mode 100644index 000000000..ca85c1ff0--- /dev/null+++ b/.changeset/healthz-readyz-endpoints.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++The project server now exposes standard health-check endpoints: `GET /healthz` answers 200 as soon as the listener is up (process liveness), and `GET /readyz` reports 503 while the project runtime is still initializing, then 200 with a `degraded` list naming any subsystems that failed to start. The moment shutdown begins, `/readyz` flips to 503 with status `draining` so probe-driven routers stop sending traffic before the listener closes. Both endpoints are exempt from the Host/Origin admission checks so container orchestrators and reverse-proxy health probes (which send IP Host headers and traverse proxies) work without configuration.diff --git a/packages/server/src/api-admission-composition.test.ts b/packages/server/src/api-admission-composition.test.tsnew file mode 100644index 000000000..d24568c43--- /dev/null+++ b/packages/server/src/api-admission-composition.test.ts@@ -0,0 +1,155 @@+import { mkdtempSync, writeFileSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';++/**+ * Characterization: the `/api/*` admission gates as experienced over a REAL+ * socket through the composed `bootServer` stack. The gates themselves have+ * unit coverage (predicates) and in-process coverage (`api-request-id.test.ts`+ * invokes `onRequest` directly), but before this suite no test drove them+ * through the actual listener + mcp-mount dispatch + api-extension chain —+ * the exact layering the server refactor rewires. Assertions pin CURRENT+ * behavior, including behavior that is a known pre-auth exposure (read+ * routes answering under a rebound Host): if one of these starts failing,+ * the admission surface changed and the change must be intentional.+ */++let tmpRoot: string;+let normal: BootedServer;+let ephemeral: BootedServer;++beforeAll(async () => {+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-admission-'));++ const normalDir = mkdtempSync(resolve(tmpRoot, 'normal-'));+ normal = await bootCompositionRig(normalDir);+ await normal.ready;++ const ephemeralDir = mkdtempSync(resolve(tmpRoot, 'ephemeral-'));+ writeFileSync(resolve(ephemeralDir, 'note.md'), '# note\n', 'utf-8');+ ephemeral = await bootCompositionRig(ephemeralDir, {+ ephemeral: true,+ singleDocRelPath: 'note.md',+ });+ await ephemeral.ready;+}, 60_000);++afterAll(async () => {+ await Promise.allSettled([normal?.destroy(), ephemeral?.destroy()]);+ await rm(tmpRoot, { recursive: true, force: true });+});++describe('/api admission over the composed listener — normal mode', () => {+ test('read route with a foreign Origin is refused before dispatch', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/api/server-info`, {+ headers: { Origin: 'https://evil.example' },+ });+ expect(res.status).toBe(403);+ expect(res.headers.get('content-type')).toBe('application/problem+json');+ const body = (await res.json()) as { type?: string; title?: string };+ expect(body.type).toBe('urn:ok:error:invalid-origin');+ expect(body.title).toBe('Origin not allowed.');+ });++ test('read route with an allowed browser Origin gets CORS reflection', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/api/server-info`, {+ headers: { Origin: 'http://localhost:5173' },+ });+ expect(res.status).toBe(200);+ expect(res.headers.get('access-control-allow-origin')).toBe('http://localhost:5173');+ expect(res.headers.get('vary')).toContain('Origin');+ });++ test('read route ANSWERS under a rebound Host (current pre-auth exposure)', async () => {+ // Deliberate pin of today's posture: read-shaped /api routes are Origin-+ // gated but NOT Host/loopback-gated, so a DNS-rebound page's no-Origin+ // fetch can read them. The hosted-auth work changes this on purpose;+ // when it does, this assertion must be flipped in the same PR.+ const res = await rawRequest(normal.port, '/api/server-info', {+ headers: { Host: 'evil.example' },+ });+ expect(res.status).toBe(200);+ });++ test('mutating route under a rebound Host is refused', async () => {+ const res = await rawRequest(normal.port, '/api/create-page', {+ method: 'POST',+ headers: { Host: 'evil.example', 'Content-Type': 'application/json' },+ body: '{}',+ });+ expect(res.status).toBe(403);+ const body = parseProblem(res.body);+ expect(body.type).toBe('urn:ok:error:host-not-allowed');+ });++ test('mutating route with loopback Host passes the gate (fails later on payload, not admission)', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/api/create-page`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: '{}',+ });+ expect(res.status).not.toBe(403);+ expect(res.status).toBe(400);+ });++ test('local-op prefix routes are Host-gated as a family', async () => {+ const res = await rawRequest(normal.port, '/api/local-op/auth/status', {+ headers: { Host: 'evil.example' },+ });+ expect(res.status).toBe(403);+ });++ test('host-disclosing read handler /api/workspace carries its own inline Host gate', async () => {+ const res = await rawRequest(normal.port, '/api/workspace', {+ headers: { Host: 'evil.example' },+ });+ expect(res.status).toBe(403);+ });++ test('any forwarding header trips the proxied-request refusal on /api', async () => {+ const res = await rawRequest(normal.port, '/api/server-info', {+ headers: { 'X-Forwarded-For': '203.0.113.7' },+ });+ expect(res.status).toBe(403);+ const body = parseProblem(res.body);+ expect(body.type).toBe('urn:ok:error:host-not-allowed');+ expect(body.detail ?? body.title).toContain('Proxied request refused');+ });++ test('OPTIONS preflight on an /api route answers 204 with CORS methods', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/api/create-page`, {+ method: 'OPTIONS',+ headers: { Origin: 'http://localhost:5173' },+ });+ expect(res.status).toBe(204);+ expect(res.headers.get('access-control-allow-methods')).toBe('GET, POST, PUT, DELETE, OPTIONS');+ });+});++describe('/api admission over the composed listener — ephemeral mode', () => {+ test('read route via localhost is served', async () => {+ const res = await fetch(`http://127.0.0.1:${ephemeral.port}/api/server-info`);+ expect(res.status).toBe(200);+ });++ test('EVERY /api route is Host-gated, including reads', async () => {+ // The ephemeral contentDir is the opened file's parent directory, so the+ // normal-mode read posture would let a rebound page enumerate sibling+ // files. Ephemeral mode therefore gates all of /api, not just mutations.+ const res = await rawRequest(ephemeral.port, '/api/server-info', {+ headers: { Host: 'evil.example' },+ });+ expect(res.status).toBe(403);+ });++ test('/mcp is unmounted in ephemeral mode', async () => {+ const res = await fetch(`http://127.0.0.1:${ephemeral.port}/mcp`, {+ method: 'OPTIONS',+ });+ expect(res.status).toBe(404);+ });+});diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.tsindex f0043b551..7a5f03b09 100644--- a/packages/server/src/boot.ts+++ b/packages/server/src/boot.ts@@ -63,7 +63,7 @@ import { scanGlobalInPlaceSkills, scanInPlaceSkills } from './in-place-skills.tsimport { resolveLocalSinkConfig } from './local-sink-resolver.ts';import { getLogger, loggerFactory, type PinoLogger } from './logger.ts';import { createMcpHttpHandler } from './mcp-http.ts';-import { mountMcpAndApi } from './mcp-mount.ts';+import { mountMcpAndApi, type ReadinessState } from './mcp-mount.ts';import { MissingOkConfigError } from './missing-ok-config-error.ts';import { RemoteConfigError, resolveRemoteAccess } from './remote-access.ts';import { createServer, type ServerInstance, type ServerOptions } from './server-factory.ts';@@ -895,11 +895,28 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {log.info({ url: remoteAccess.url }, '[remote] remote access enabled (trust-the-tunnel)');}+ // Readiness snapshot for /readyz. Both callbacks handle the promise so a+ // failed async init cannot surface as an unhandled rejection here (the+ // caller still owns `ready` and observes the real error there).+ let readinessState: ReadinessState = 'pending';+ ready.then(+ () => {+ readinessState = 'ready';+ },+ () => {+ readinessState = 'failed';+ },+ );+const mount = mountMcpAndApi({httpServer,hocuspocus,mcpHttpHandler,remoteAccess,+ health: {+ readiness: () => readinessState,+ degraded: () => degraded,+ },log,sessionManager,agentFocusBroadcaster,@@ -1045,6 +1062,10 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {destroy = async (): Promise<void> => {if (destroyed) return;destroyed = true;+ // Flip /readyz to not-ready synchronously, before any teardown step, so+ // probe-driven routers stop sending traffic during the drain window —+ // the HTTP mirror of the lock-file draining mark below.+ readinessState = 'draining';const errors: unknown[] = [];const runStep = async (name: string, work: () => Promise<void>): Promise<void> => {try {diff --git a/packages/server/src/composition-precedence.test.ts b/packages/server/src/composition-precedence.test.tsnew file mode 100644index 000000000..bff2f5f35--- /dev/null+++ b/packages/server/src/composition-precedence.test.ts@@ -0,0 +1,203 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+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';++/**+ * Characterization: cross-surface route precedence, readiness, and shutdown+ * as observed over the composed `bootServer` listener. The existing shell+ * end-to-end test pins shell/content/API precedence; this suite pins the+ * surfaces that had no composed-rig coverage — /mcp vs /api vs static+ * discrimination, exact-match quirks (trailing slash, case), 405 method+ * dispatch, mode-differential 404 bodies, readiness as seen from a socket,+ * and teardown draining a live collab WebSocket.+ */++let tmpRoot: string;+let normal: BootedServer;++beforeAll(async () => {+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-precedence-'));+ const normalDir = mkdtempSync(resolve(tmpRoot, 'normal-'));+ normal = await bootCompositionRig(normalDir);+ await normal.ready;+}, 60_000);++afterAll(async () => {+ await normal?.destroy();+ await rm(tmpRoot, { recursive: true, force: true });+});++describe('route dispatch and precedence — normal mode (no React shell)', () => {+ test('known API route answers JSON on the composed port', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/api/server-info`);+ expect(res.status).toBe(200);+ expect(res.headers.get('content-type')).toContain('application/json');+ });++ test('unknown /api path 404s from the API dispatcher, with the API-specific body', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/api/definitely-not-a-route`);+ expect(res.status).toBe(404);+ expect(res.headers.get('content-type')).toBe('application/problem+json');+ const body = parseProblem(await res.text());+ expect(body.type).toBe('urn:ok:error:not-found');+ expect(body.title).toBe('API endpoint not found.');+ });++ test('route matching is exact: a trailing slash misses the route table', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/api/server-info/`);+ expect(res.status).toBe(404);+ const body = parseProblem(await res.text());+ expect(body.title).toBe('API endpoint not found.');+ });++ test('route matching is case-sensitive: /API/* is not API traffic and falls to static 404', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/API/server-info`);+ expect(res.status).toBe(404);+ const body = parseProblem(await res.text());+ expect(body.title).toBe('Not found.');+ });++ test('unknown non-API path 404s with the ok-ui hint when no shell is mounted', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/definitely/not/here`);+ expect(res.status).toBe(404);+ const body = parseProblem(await res.text());+ expect(body.type).toBe('urn:ok:error:not-found');+ expect(body.detail).toContain('ok ui');+ });++ test('/mcp is mounted at the exact path only', async () => {+ const exact = await fetch(`http://127.0.0.1:${normal.port}/mcp`, { method: 'OPTIONS' });+ expect(exact.status).toBe(204);++ const slash = await fetch(`http://127.0.0.1:${normal.port}/mcp/`, { method: 'OPTIONS' });+ expect(slash.status).toBe(404);+ });++ test('wrong method on a declared-method route yields 405 with an Allow header, before body read', async () => {+ const res = await fetch(`http://127.0.0.1:${normal.port}/api/create-page`, {+ method: 'GET',+ });+ expect(res.status).toBe(405);+ expect(res.headers.get('allow')).toBe('POST');+ const body = parseProblem(await res.text());+ expect(body.type).toBe('urn:ok:error:method-not-allowed');+ });++ test('a live /collab WebSocket connects through the composed upgrade path', async () => {+ const ws = new WebSocket(`ws://127.0.0.1:${normal.port}/collab`);+ await new Promise<void>((resolvePromise, reject) => {+ ws.on('open', () => resolvePromise());+ ws.on('error', reject);+ });+ ws.close();+ await new Promise<void>((resolvePromise) => ws.on('close', () => resolvePromise()));+ });+});++describe('desktop-shape composition (React shell mounted)', () => {+ let desktop: BootedServer;+ let desktopTmp: string;++ beforeAll(async () => {+ desktopTmp = await mkdtemp(resolve(tmpdir(), 'ok-precedence-desktop-'));+ const projectDir = mkdtempSync(resolve(desktopTmp, 'proj-'));+ const shellDistDir = mkdtempSync(resolve(desktopTmp, 'dist-'));+ writeFileSync(+ resolve(shellDistDir, 'index.html'),+ '<!DOCTYPE html><html><body data-test="shell">ok</body></html>',+ 'utf-8',+ );+ desktop = await bootCompositionRig(projectDir, {+ reactShellDistDir: shellDistDir,+ serveContentAssets: true,+ });+ await desktop.ready;+ }, 60_000);++ afterAll(async () => {+ await desktop?.destroy();+ await rm(desktopTmp, { recursive: true, force: true });+ });++ 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);+ expect(await deep.text()).toContain('data-test="shell"');++ const mcp = await fetch(`http://127.0.0.1:${desktop.port}/mcp`, { method: 'OPTIONS' });+ expect(mcp.status).toBe(204);++ const api = await fetch(`http://127.0.0.1:${desktop.port}/api/definitely-not-a-route`);+ expect(api.status).toBe(404);+ expect(api.headers.get('content-type')).toBe('application/problem+json');+ });+});++describe('readiness and shutdown over the composed listener', () => {+ test('a document-list request racing async init never sees a false-empty index', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-ready-race-'));+ try {+ mkdirSync(resolve(tmp, 'docs'), { recursive: true });+ writeFileSync(resolve(tmp, 'docs', 'seeded-note.md'), '# seeded\n', 'utf-8');+ const booted = await bootCompositionRig(tmp);+ try {+ // Deliberately no `await booted.ready` — the request must park on+ // readiness server-side rather than answer from a half-built index.+ // Bounded abort so a genuine readiness hang reads as an abort, not+ // an indistinguishable test-runner timeout.+ const res = await fetch(`http://127.0.0.1:${booted.port}/api/documents`, {+ signal: AbortSignal.timeout(75_000),+ });+ expect(res.status).toBe(200);+ expect(await res.text()).toContain('seeded-note');+ } finally {+ await booted.destroy();+ }+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ // 90s: this test pays for a full boot; under whole-suite CPU saturation+ // the boot alone has been observed to exceed 30s on a loaded runner.+ }, 90_000);++ test('destroy() drains a live collab WebSocket, closes the listener, and marks server.lock draining', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-shutdown-'));+ try {+ const booted = await bootCompositionRig(tmp);+ await booted.ready;++ const ws = new WebSocket(`ws://127.0.0.1:${booted.port}/collab`);+ await new Promise<void>((resolvePromise, reject) => {+ ws.on('open', () => resolvePromise());+ ws.on('error', reject);+ });++ const wsClosed = new Promise<void>((resolvePromise) =>+ ws.on('close', () => resolvePromise()),+ );++ const lockPath = resolve(booted.lockDir, 'server.lock');+ expect(existsSync(lockPath)).toBe(true);++ await booted.destroy();++ await wsClosed;+ expect(booted.httpServer.listening).toBe(false);+ // The lock is NOT unlinked by in-process destroy(): release marks it+ // draining and defers the unlink to process exit, so discovery stops+ // dialing immediately while crash-vs-clean-exit stays distinguishable+ // on disk. Only process exit removes the file (pinned by the CLI e2e's+ // SIGTERM case).+ expect(existsSync(lockPath)).toBe(true);+ const lock = JSON.parse(readFileSync(lockPath, 'utf-8')) as { draining?: boolean };+ expect(lock.draining).toBe(true);+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }, 30_000);+});diff --git a/packages/server/src/composition-rig.test-helper.ts b/packages/server/src/composition-rig.test-helper.tsnew file mode 100644index 000000000..ea161eb37--- /dev/null+++ b/packages/server/src/composition-rig.test-helper.ts@@ -0,0 +1,140 @@+import { mkdirSync, writeFileSync } from 'node:fs';+import { request as httpRequest } from 'node:http';+import { resolve } from 'node:path';+import { OK_DIR } from '@inkeep/open-knowledge-core';+import { type BootedServer, type BootServerOptions, bootServer } from './boot.ts';+import { ConfigSchema } from './config/schema.ts';++/**+ * Characterization rig for the composed server surface: boots the REAL+ * `bootServer` composition (mcp-mount dispatch + api-extension gates + collab+ * upgrade path) on an ephemeral loopback port so tests can probe routing,+ * admission, and lifecycle exactly as an HTTP client experiences them.+ *+ * `bootServer` refuses to boot without `<projectDir>/.ok/config.yml`; the+ * scaffold seeds it (plus `.ok/.gitignore` to keep the one-time hygiene+ * warning out of test stderr). No `git init`: every rig boots with+ * `gitEnabled: false`, which skips the git preflight and shadow-repo init, so+ * the rig never spawns child processes.+ */+function seedOkScaffold(projectDir: string): void {+ const okDir = resolve(projectDir, OK_DIR);+ mkdirSync(okDir, { recursive: true });+ writeFileSync(resolve(okDir, 'config.yml'), '', 'utf-8');+ writeFileSync(resolve(okDir, '.gitignore'), '', 'utf-8');+}++const TEST_CONFIG = ConfigSchema.parse({});++export async function bootCompositionRig(+ contentDir: string,+ overrides: Partial<BootServerOptions> = {},+): Promise<BootedServer> {+ seedOkScaffold(contentDir);+ return bootServer({+ host: '127.0.0.1',+ config: TEST_CONFIG,+ contentDir,+ port: 0,+ quiet: true,+ gitEnabled: false,+ idleShutdownMs: null,+ attachUiSibling: false,+ ...overrides,+ });+}++export interface RawResponse {+ status: number;+ headers: Record<string, string | string[] | undefined>;+ body: string;+}++/**+ * Issue a request with full header control. `fetch` refuses to override+ * `Host` (forbidden header), so the DNS-rebinding shape — loopback TCP peer+ * carrying an attacker-controlled Host — needs the raw `http.request`.+ */+export async function rawRequest(+ port: number,+ path: string,+ options: {+ method?: string;+ headers?: Record<string, string>;+ body?: string | Buffer;+ } = {},+): Promise<RawResponse> {+ return new Promise((resolvePromise, reject) => {+ let settled = false;+ const req = httpRequest(+ {+ hostname: '127.0.0.1',+ port,+ path,+ method: options.method ?? 'GET',+ headers: options.headers,+ // Fresh socket per request. The server resets the connection after+ // refusing an oversized body, and a keep-alive agent would hand that+ // poisoned socket to the NEXT rawRequest → spurious ECONNRESET.+ agent: false,+ },+ (res) => {+ const chunks: Buffer[] = [];+ res.on('data', (chunk) => chunks.push(Buffer.from(chunk)));+ res.on('end', () => {+ settled = true;+ resolvePromise({+ status: res.statusCode ?? 0,+ headers: res.headers,+ body: Buffer.concat(chunks).toString('utf-8'),+ });+ });+ },+ );+ // A server that rejects mid-body (413) responds and tears down while the+ // client is still uploading; the resulting EPIPE/ECONNRESET on the+ // request side must not fail a call whose response was already read.+ req.on('error', (err) => {+ if (!settled) reject(err);+ });+ req.setTimeout(10_000, () => req.destroy(new Error(`timed out: ${path}`)));++ const body = options.body;+ if (body === undefined) {+ req.end();+ return;+ }+ // Stream the body in bounded chunks and abandon the remainder as soon as+ // a response arrives — pumping the rest into a socket the server has+ // already answered on just races an EPIPE.+ const buf = Buffer.isBuffer(body) ? body : Buffer.from(body);+ let offset = 0;+ let responded = false;+ req.on('response', () => {+ responded = true;+ });+ const pump = (): void => {+ while (offset < buf.length && !responded) {+ const chunk = buf.subarray(offset, offset + 65_536);+ offset += chunk.length;+ if (!req.write(chunk)) {+ req.once('drain', pump);+ return;+ }+ }+ req.end();+ };+ pump();+ });+}++export interface ProblemJson {+ type?: string;+ title?: string;+ status?: number;+ detail?: string;+}++export function parseProblem(body: string): ProblemJson {+ return JSON.parse(body) as ProblemJson;+}diff --git a/packages/server/src/desktop-attach-contract.test.ts b/packages/server/src/desktop-attach-contract.test.tsnew file mode 100644index 000000000..0d9c4a17d--- /dev/null+++ b/packages/server/src/desktop-attach-contract.test.ts@@ -0,0 +1,169 @@+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import { hostname, tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { describe, expect, test, vi } from 'vitest';+import { bootCompositionRig, parseProblem } from './composition-rig.test-helper.ts';+import { acquireUiLock, readUiLock, releaseUiLock, updateUiLockPort } from './ui-lock.ts';++/**+ * The Claude Desktop attach contract, as it exists today. Sandboxed agent+ * panes (Claude Desktop's embedded browser) cannot be handed an arbitrary+ * URL out of band — they attach by asking the stdio MCP for a preview URL,+ * and that answer is derived entirely from `ui.lock`:+ *+ * <projectDir>/.ok/local/ui.lock → http://localhost:<ui.lock.port>+ *+ * The contract the readers (preview-url tools, `ok ui` collision resolver,+ * `decideUiSpawn`, the data-server 404 hint) rely on:+ *+ * 1. FIELDS — every real lock carries pid, hostname, port, startedAt,+ * worktreeRoot, protocolVersion, runtimeVersion. The optional+ * kind/parentPid/capabilities fields are NOT written by today's+ * writers; nothing may start requiring them without changing writers.+ * 2. PORT SENTINEL — the lock exists with port 0 from acquire (pre-listen)+ * until updateUiLockPort stamps the bound port. Readers must treat+ * port 0 as "starting" (poll), never as an address.+ * 3. YIELD — a booting server that finds a live holder does not collide:+ * it proceeds without owning the lock, leaves the peer's advertisement+ * untouched (including on its own destroy), and emits a structured+ * yield event.+ * 4. DISCOVERY HINT — a data server not serving the shell points humans+ * at `ui.lock.port` in its 404 body.+ *+ * Whatever replaces the `ok ui` sibling must keep all four observable+ * behaviors (or migrate every reader in the same release): the preview-pane+ * flow is downstream of `ui.lock`, not of which process serves the shell.+ */++describe('ui.lock — the Desktop attach advertisement', () => {+ test('the real writer advertises exactly the documented field set', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-fields-'));+ try {+ const projectDir = mkdtempSync(resolve(tmp, 'proj-'));+ const shellDistDir = mkdtempSync(resolve(tmp, 'dist-'));+ writeFileSync(resolve(shellDistDir, 'index.html'), '<html>shell</html>', 'utf-8');++ const booted = await bootCompositionRig(projectDir, { reactShellDistDir: shellDistDir });+ try {+ await booted.ready;+ const raw = readFileSync(resolve(projectDir, '.ok', 'local', 'ui.lock'), 'utf-8');+ const lock = JSON.parse(raw) as Record<string, unknown>;++ expect(lock.pid).toBe(process.pid);+ expect(lock.port).toBe(booted.port);+ expect(lock.hostname).toBe(hostname());+ expect(typeof lock.startedAt).toBe('string');+ expect(Number.isNaN(Date.parse(lock.startedAt as string))).toBe(false);+ expect(lock.worktreeRoot).toBe(projectDir);+ expect(typeof lock.protocolVersion).toBe('number');+ expect(typeof lock.runtimeVersion).toBe('string');++ // Optional fields the writers do not populate today. A reader that+ // starts gating on these (e.g. a desktop attach check on `kind`)+ // would silently reject every real lock.+ expect('kind' in lock).toBe(false);+ expect('parentPid' in lock).toBe(false);+ expect('capabilities' in lock).toBe(false);+ } finally {+ await booted.destroy();+ }+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }, 30_000);++ test('port sentinel: acquire writes 0, updateUiLockPort stamps the bound port, release unlinks', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-sentinel-'));+ try {+ const lockDir = resolve(tmp, '.ok', 'local');+ mkdirSync(lockDir, { recursive: true });++ acquireUiLock(lockDir, { port: 0, worktreeRoot: tmp });+ expect(readUiLock(lockDir)?.port).toBe(0);++ updateUiLockPort(lockDir, 24_680);+ expect(readUiLock(lockDir)?.port).toBe(24_680);++ releaseUiLock(lockDir);+ expect(readUiLock(lockDir)).toBeNull();+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ });++ test('yield-to-live-holder emits the structured event operators grep for', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-yield-'));+ try {+ const projectDir = mkdtempSync(resolve(tmp, 'proj-'));+ const shellDistDir = mkdtempSync(resolve(tmp, 'dist-'));+ writeFileSync(resolve(shellDistDir, 'index.html'), '<html>shell</html>', 'utf-8');++ // A live peer: process.ppid is alive for the duration of the test and+ // is not process.pid (which would take the same-pid rewrite path).+ const lockDir = resolve(projectDir, '.ok', 'local');+ mkdirSync(lockDir, { recursive: true });+ writeFileSync(+ resolve(lockDir, 'ui.lock'),+ JSON.stringify({+ pid: process.ppid,+ hostname: hostname(),+ port: 65_432,+ startedAt: new Date().toISOString(),+ worktreeRoot: projectDir,+ protocolVersion: 1,+ runtimeVersion: '0.0.0-test-peer',+ }),+ 'utf-8',+ );++ const calls: Array<Record<string, unknown>> = [];+ const capture = (obj: unknown) => {+ if (typeof obj === 'object' && obj !== null) calls.push(obj as Record<string, unknown>);+ };+ const log = {+ info: vi.fn(capture),+ warn: vi.fn(capture),+ error: vi.fn(capture),+ debug: vi.fn(capture),+ child: () => log,+ };++ const booted = await bootCompositionRig(projectDir, {+ reactShellDistDir: shellDistDir,+ log: log as never,+ });+ try {+ await booted.ready;+ const yielded = calls.find((c) => c.event === 'ui-lock-yielded-to-live-holder');+ expect(yielded).toBeDefined();+ expect(yielded?.existingPid).toBe(process.ppid);+ expect(yielded?.existingPort).toBe(65_432);+ } finally {+ await booted.destroy();+ }+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }, 30_000);++ test('a data server without the shell points the 404 at ui.lock.port', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-attach-hint-'));+ try {+ const booted = await bootCompositionRig(tmp);+ try {+ await booted.ready;+ const res = await fetch(`http://127.0.0.1:${booted.port}/`);+ expect(res.status).toBe(404);+ const body = parseProblem(await res.text());+ expect(body.detail).toContain('ok ui');+ expect(body.detail).toContain('ui.lock');+ expect(existsSync(resolve(tmp, '.ok', 'local', 'ui.lock'))).toBe(false);+ } finally {+ await booted.destroy();+ }+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }, 30_000);+});diff --git a/packages/server/src/health-routes.test.ts b/packages/server/src/health-routes.test.tsnew file mode 100644index 000000000..0afc380db--- /dev/null+++ b/packages/server/src/health-routes.test.ts@@ -0,0 +1,212 @@+import { mkdtempSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import { createServer } from 'node:http';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import type { Hocuspocus } from '@hocuspocus/server';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';+import { getFreeLoopbackPort } from './loopback-rig-test-helpers.ts';+import { mountMcpAndApi } from './mcp-mount.ts';++/**+ * /healthz + /readyz over the composed listener. The load-bearing property is+ * the admission EXEMPTION: orchestrator probes arrive with an IP Host header,+ * no Origin, and often through a proxy that adds forwarding headers — every+ * other surface refuses those, the health surface must not.+ */++let tmpRoot: string;+let booted: BootedServer;++beforeAll(async () => {+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-health-'));+ booted = await bootCompositionRig(mkdtempSync(resolve(tmpRoot, 'proj-')));+}, 60_000);++afterAll(async () => {+ await booted?.destroy();+ await rm(tmpRoot, { recursive: true, force: true });+});++describe('/healthz', () => {+ test('answers 200 ok with no-store, independent of readiness', async () => {+ const res = await fetch(`http://127.0.0.1:${booted.port}/healthz`);+ expect(res.status).toBe(200);+ expect(await res.text()).toBe('ok');+ expect(res.headers.get('cache-control')).toBe('no-store');+ expect(res.headers.get('x-content-type-options')).toBe('nosniff');+ });++ test('is exempt from the Host gate (orchestrator probes send IP hosts)', async () => {+ const res = await rawRequest(booted.port, '/healthz', {+ headers: { Host: '10.0.0.7:8080' },+ });+ expect(res.status).toBe(200);+ expect(res.body).toBe('ok');+ });++ test('is exempt from the forwarding-header tripwire (probes traverse proxies)', async () => {+ const res = await rawRequest(booted.port, '/healthz', {+ headers: { 'X-Forwarded-For': '203.0.113.7' },+ });+ expect(res.status).toBe(200);+ });++ test('non-GET is refused with 405 and an Allow header', async () => {+ const res = await rawRequest(booted.port, '/healthz', { method: 'POST' });+ expect(res.status).toBe(405);+ expect(res.headers.allow).toBe('GET, HEAD');+ expect(parseProblem(res.body).type).toBe('urn:ok:error:method-not-allowed');+ });++ test('query strings do not break the exact match', async () => {+ const res = await fetch(`http://127.0.0.1:${booted.port}/healthz?probe=1`);+ expect(res.status).toBe(200);+ });+});++describe('/readyz', () => {+ test('reports 200 with the single-shaped body once init settles', async () => {+ await booted.ready;+ const res = await fetch(`http://127.0.0.1:${booted.port}/readyz`);+ expect(res.status).toBe(200);+ const body = (await res.json()) as { ready: boolean; status: string; degraded: string[] };+ expect(body.ready).toBe(true);+ expect(body.status).toBe('ready');+ expect(Array.isArray(body.degraded)).toBe(true);+ });++ test('during boot answers either 503 not-ready or 200 ready, never a gate refusal', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-readyz-race-'));+ try {+ const racing = await bootCompositionRig(tmp);+ try {+ // No `await racing.ready` — init may or may not have settled; the pin+ // is that the surface is mounted and shaped correctly from the first+ // instant the listener exists.+ const res = await fetch(`http://127.0.0.1:${racing.port}/readyz`);+ expect([200, 503]).toContain(res.status);+ const body = (await res.json()) as { ready: boolean };+ expect(body.ready).toBe(res.status === 200);+ await racing.ready;+ const settled = await fetch(`http://127.0.0.1:${racing.port}/readyz`);+ expect(settled.status).toBe(200);+ } finally {+ await racing.destroy();+ }+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }, 30_000);++ test('is exempt from the Host gate like /healthz', async () => {+ const res = await rawRequest(booted.port, '/readyz', {+ headers: { Host: 'kb.internal:8080' },+ });+ expect(res.status).toBe(200);+ });++ test('destroy() flips readiness to draining before the listener closes', async () => {+ const tmp = await mkdtemp(resolve(tmpdir(), 'ok-readyz-drain-'));+ try {+ const draining = await bootCompositionRig(tmp);+ await draining.ready;++ // No await: `readinessState = 'draining'` is the first synchronous+ // statement of destroy(), so any probe dispatched after this call+ // observes either 503 (listener still up) or a refused connection+ // (listener already closed) — never a 200 that routes traffic in.+ const destroyed = draining.destroy();+ let probe: { status: number; body?: { ready: boolean; status: string } } | 'refused';+ try {+ const res = await fetch(`http://127.0.0.1:${draining.port}/readyz`);+ probe = {+ status: res.status,+ body: (await res.json()) as { ready: boolean; status: string },+ };+ } catch {+ probe = 'refused';+ }+ await destroyed;++ if (probe !== 'refused') {+ expect(probe.status).toBe(503);+ expect(probe.body?.ready).toBe(false);+ expect(probe.body?.status).toBe('draining');+ }+ } finally {+ await rm(tmp, { recursive: true, force: true });+ }+ }, 30_000);+});++describe('/readyz provider states (mounted harness)', () => {+ // bootServer only ever produces pending→ready|failed→draining transitions+ // organically; the failed and draining response shapes are pinned here at+ // the mount level with a canned provider so the wire contract cannot+ // silently drift.+ const fakeLog = {+ error: () => {},+ warn: () => {},+ info: () => {},+ debug: () => {},+ child: () => fakeLog,+ };+ const fakeHocuspocus = {+ hooks: async () => {},+ handleConnection: () => ({ handleMessage: () => {}, handleClose: () => {} }),+ } as unknown as Hocuspocus;++ async function probeWithReadiness(+ readiness: 'ready' | 'failed' | 'draining' | undefined,+ ): Promise<{ status: number; body: { ready: boolean; status: string; degraded: string[] } }> {+ const httpServer = createServer();+ const mount = mountMcpAndApi({+ httpServer,+ hocuspocus: fakeHocuspocus,+ log: fakeLog as never,+ ...(readiness === undefined+ ? {}+ : { health: { readiness: () => readiness, degraded: () => ['shadow-repo'] } }),+ });+ const port = await getFreeLoopbackPort();+ await new Promise<void>((r) => httpServer.listen(port, '127.0.0.1', () => r()));+ try {+ const res = await fetch(`http://127.0.0.1:${port}/readyz`);+ return {+ status: res.status,+ body: (await res.json()) as { ready: boolean; status: string; degraded: string[] },+ };+ } finally {+ await mount.shutdown();+ await new Promise<void>((r) => mount.wss.close(() => r()));+ await new Promise<void>((r) => httpServer.close(() => r()));+ }+ }++ test('failed init reports 503 with status failed and an empty degraded list', async () => {+ const probe = await probeWithReadiness('failed');+ expect(probe.status).toBe(503);+ expect(probe.body).toEqual({ ready: false, status: 'failed', degraded: [] });+ });++ test('draining reports 503 with status draining', async () => {+ const probe = await probeWithReadiness('draining');+ expect(probe.status).toBe(503);+ expect(probe.body).toEqual({ ready: false, status: 'draining', degraded: [] });+ });++ test('ready passes the degraded list through into the 200 body', async () => {+ const probe = await probeWithReadiness('ready');+ expect(probe.status).toBe(200);+ expect(probe.body).toEqual({ ready: true, status: 'ready', degraded: ['shadow-repo'] });+ });++ test('an omitted provider reports ready (synchronous-init harness posture)', async () => {+ const probe = await probeWithReadiness(undefined);+ expect(probe.status).toBe(200);+ expect(probe.body).toEqual({ ready: true, status: 'ready', degraded: [] });+ });+});diff --git a/packages/server/src/http-limits.test.ts b/packages/server/src/http-limits.test.tsnew file mode 100644index 000000000..ed03356c7--- /dev/null+++ b/packages/server/src/http-limits.test.ts@@ -0,0 +1,88 @@+import { mkdtempSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig, parseProblem, rawRequest } from './composition-rig.test-helper.ts';++/**+ * Characterization: HTTP request-size and timeout protections as observed+ * over the composed listener. The JSON body cap and the slowloris body+ * timeout live in the shared `withValidation` read path; before this suite+ * neither had any test at any layer. The body-read timeout (30 s) is too+ * slow to exercise for real in a unit run, so this suite pins the+ * server-level timeout knobs structurally and leaves live 408 timing to a+ * future injectable-clock change if flake-free timing ever matters.+ */++let tmpRoot: string;+let booted: BootedServer;++beforeAll(async () => {+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-http-limits-'));+ const dir = mkdtempSync(resolve(tmpRoot, 'proj-'));+ booted = await bootCompositionRig(dir);+ await booted.ready;+}, 60_000);++afterAll(async () => {+ await booted?.destroy();+ await rm(tmpRoot, { recursive: true, force: true });+});++describe('request body size cap', () => {+ test('a JSON body over 1 MiB is refused with 413 payload-too-large', async () => {+ // Barely over the cap on purpose. The refusal path responds 413 and then+ // destroys the socket WITHOUT draining unread request bytes, so a client+ // still uploading a grossly oversized body can get a TCP reset before it+ // reads the 413 (kernel-buffer race; reproduced under parallel-suite+ // load with a 2 MiB body). Just-over-cap means the server consumes+ // essentially the whole body before refusing, making the 413 readable+ // deterministically. The lost-413-on-big-uploads wart is part of the+ // characterized behavior.+ const oversized = `{"docName":"a","content":"${'x'.repeat(1_048_576)}"}`;+ const res = await rawRequest(booted.port, '/api/create-page', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: oversized,+ });+ expect(res.status).toBe(413);+ const body = parseProblem(res.body);+ expect(body.type).toBe('urn:ok:error:payload-too-large');+ expect(body.title).toBe('Payload too large.');+ });++ test('a body under the cap is read in full and fails on schema, not size', async () => {+ const underCap = `{"unexpected":"${'x'.repeat(64 * 1024)}"}`;+ const res = await rawRequest(booted.port, '/api/create-page', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: underCap,+ });+ expect(res.status).toBe(400);+ const body = parseProblem(res.body);+ expect(body.type).toBe('urn:ok:error:invalid-request');+ });++ test('a syntactically invalid JSON body is a 400, not a 500', async () => {+ const res = await rawRequest(booted.port, '/api/create-page', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: 'not json at all',+ });+ expect(res.status).toBe(400);+ const body = parseProblem(res.body);+ expect(body.type).toBe('urn:ok:error:invalid-request');+ });+});++describe('server-level timeout knobs', () => {+ test('slow-client protections are pinned on the composed listener', async () => {+ // Structural pin: these are the boot-time knobs that bound the header+ // and whole-request phases. If either changes, deployment guidance and+ // reverse-proxy buffering advice must be revisited alongside it.+ expect(booted.httpServer.headersTimeout).toBe(30_000);+ expect(booted.httpServer.requestTimeout).toBe(60_000);+ });+});diff --git a/packages/server/src/mcp-collab-composition.test.ts b/packages/server/src/mcp-collab-composition.test.tsnew file mode 100644index 000000000..82d1e2d60--- /dev/null+++ b/packages/server/src/mcp-collab-composition.test.ts@@ -0,0 +1,200 @@+import { mkdtempSync } from 'node:fs';+import { mkdtemp, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { resolve } from 'node:path';+import { MessageType } from '@hocuspocus/server';+import * as encoding from 'lib0/encoding';+import { afterAll, beforeAll, describe, expect, test } from 'vitest';+import { WebSocket as WsClient } from 'ws';+import { messageYjsUpdate } from 'y-protocols/sync';+import * as Y from 'yjs';+import type { BootedServer } from './boot.ts';+import { bootCompositionRig } from './composition-rig.test-helper.ts';++/**+ * Characterization: the MCP and collab transports over the REAL composed+ * `bootServer` stack. The existing MCP tests prove the handler in isolation+ * (hand-rolled http server, stubbed `/api/agent-write-md`) or the mount with+ * a fake Hocuspocus; the collab tests prove admission and the message-size+ * cap but never a document drop→reconnect. This file closes those loops:+ * MCP tool calls land on the real API handlers and real persistence, and a+ * collab client can drop and rejoin a document without losing served state.+ *+ * Also pins a negative that matters to the migration: this server has NO+ * server-initiated MCP streaming surface today — `GET /mcp` without a+ * session is a plain 400, and no notification is ever pushed. Anything the+ * router migration does to `/mcp` only has to carry request/response+ * traffic plus the SDK's (idle) session SSE channel.+ */++const MCP_PROTOCOL_VERSION = '2025-06-18';+const JSON_HEADERS = {+ 'content-type': 'application/json',+ accept: 'application/json, text/event-stream',+};++async function openMcpSession(base: string): Promise<Record<string, string>> {+ const init = await fetch(base, {+ method: 'POST',+ headers: JSON_HEADERS,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize',+ params: {+ protocolVersion: MCP_PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: 'composition-characterization', version: '0.0.0' },+ },+ }),+ });+ expect(init.status).toBe(200);+ const sessionId = init.headers.get('mcp-session-id');+ expect(sessionId).toBeTruthy();+ const headers = {+ ...JSON_HEADERS,+ 'mcp-session-id': sessionId as string,+ 'mcp-protocol-version': MCP_PROTOCOL_VERSION,+ };+ const notified = await fetch(base, {+ method: 'POST',+ headers,+ body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),+ });+ expect(notified.status).toBe(202);+ return headers;+}++function syncFrame(docName: string, update: Uint8Array): Uint8Array {+ const enc = encoding.createEncoder();+ encoding.writeVarString(enc, docName);+ encoding.writeVarUint(enc, MessageType.Sync);+ encoding.writeVarUint(enc, messageYjsUpdate);+ encoding.writeVarUint8Array(enc, update);+ return encoding.toUint8Array(enc);+}++async function openCollab(port: number): Promise<WsClient> {+ const ws = new WsClient(`ws://127.0.0.1:${port}/collab`);+ await new Promise<void>((resolvePromise, reject) => {+ ws.once('open', () => resolvePromise());+ ws.once('error', reject);+ });+ return ws;+}++let tmpRoot: string;+let booted: BootedServer;+let mcpBase: string;++beforeAll(async () => {+ tmpRoot = await mkdtemp(resolve(tmpdir(), 'ok-mcp-collab-'));+ booted = await bootCompositionRig(mkdtempSync(resolve(tmpRoot, 'proj-')));+ await booted.ready;+ mcpBase = `http://127.0.0.1:${booted.port}/mcp`;+}, 60_000);++afterAll(async () => {+ await booted?.destroy();+ await rm(tmpRoot, { recursive: true, force: true });+});++describe('MCP over the composed listener (real handlers, no stubs)', () => {+ test('initialize → tools/list round-trip returns the tool set as plain JSON', async () => {+ const headers = await openMcpSession(mcpBase);+ const list = await fetch(mcpBase, {+ method: 'POST',+ headers,+ body: JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' }),+ });+ expect(list.status).toBe(200);+ expect(list.headers.get('content-type')).toContain('application/json');+ const body = (await list.json()) as { result: { tools: Array<{ name: string }> } };+ const names = body.result.tools.map((t) => t.name);+ expect(names).toEqual(expect.arrayContaining(['search', 'exec', 'write']));+ }, 30_000);++ test('tools/call write lands a real document, observable over the API', async () => {+ const headers = await openMcpSession(mcpBase);+ const call = await fetch(mcpBase, {+ method: 'POST',+ headers,+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 3,+ method: 'tools/call',+ params: {+ name: 'write',+ arguments: {+ document: { path: 'mcp-written-note', content: 'written via mcp\n' },+ },+ },+ }),+ });+ expect(call.status).toBe(200);+ const body = (await call.json()) as { result?: { isError?: boolean } };+ expect(body.result).toBeDefined();+ expect(body.result?.isError).not.toBe(true);++ const doc = await fetch(+ `http://127.0.0.1:${booted.port}/api/document?docName=mcp-written-note`,+ );+ expect(doc.status).toBe(200);+ const content = ((await doc.json()) as { content: string }).content;+ expect(content).toContain('written via mcp');+ }, 30_000);++ test('no server-initiated streaming surface: sessionless GET /mcp is a 400', async () => {+ const res = await fetch(mcpBase, { method: 'GET', headers: JSON_HEADERS });+ expect(res.status).toBe(400);+ expect(await res.text()).toContain('Missing MCP session');+ });+});++describe('collab connection lifecycle over the composed listener', () => {+ // Deliberately connection-level, not content-level: `server-factory`+ // registers `onAuthenticate` gates (instance-ID auth token), so an+ // unauthenticated raw client's Sync frames are accepted on the wire but+ // never applied to a document — and the connection never registers in+ // `getConnectionsCount()` (whose baseline is the server's own internal+ // DirectConnections). Content-level sync is covered by the app package's+ // integration harness with a real client; what no test covered is the+ // drop→rejoin lifecycle through the composed listener with the REAL+ // Hocuspocus behind it (the admission tests use a fake).+ test('a raw client joins, hard-drops, and rejoins; each upgrade is admitted and the server survives', async () => {+ const seed = new Y.Doc();+ seed.getText('source').insert(0, 'collab payload\n');+ const update = Y.encodeStateAsUpdate(seed);+ const settle = (ms: number) => new Promise((r) => setTimeout(r, ms));++ const ws1 = await openCollab(booted.port);+ let ws1ClosedEarly = false;+ ws1.once('close', () => {+ ws1ClosedEarly = true;+ });+ ws1.send(syncFrame('collab-reconnect-doc', update));+ await settle(300);+ // Admitted and not rejected: the server holds the socket open even for+ // an unauthenticated peer (frames parked pending auth, not refused).+ expect(ws1ClosedEarly).toBe(false);++ // Hard drop — terminate without a close handshake (the crash shape).+ ws1.terminate();+ await settle(100);++ // Rejoin on the same listener: admitted again, still parked-not-refused,+ // and the server remains fully serviceable afterwards.+ const ws2 = await openCollab(booted.port);+ let ws2ClosedEarly = false;+ ws2.once('close', () => {+ ws2ClosedEarly = true;+ });+ ws2.send(syncFrame('collab-reconnect-doc', update));+ await settle(300);+ expect(ws2ClosedEarly).toBe(false);+ ws2.terminate();++ const health = await fetch(`http://127.0.0.1:${booted.port}/api/server-info`);+ expect(health.status).toBe(200);+ }, 30_000);+});diff --git a/packages/server/src/mcp-mount.ts b/packages/server/src/mcp-mount.tsindex dc2e5e3e4..ec4b6d974 100644--- a/packages/server/src/mcp-mount.ts+++ b/packages/server/src/mcp-mount.ts@@ -41,6 +41,9 @@ import {type ResolvedRemoteAccess,} from './remote-access.ts';+/** Async-init lifecycle as reported by /readyz. Only `ready` answers 200. */+export type ReadinessState = 'pending' | 'ready' | 'failed' | 'draining';+const MCP_CORS_HEADERS = {'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS','Access-Control-Allow-Headers':@@ -128,6 +131,17 @@ export interface MountMcpAndApiOptions {* serving is unchanged.*/ephemeral?: boolean;+ /**+ * Readiness provider for `/readyz`. `readiness()` reports the async-init+ * lifecycle; `degraded()` lists subsystems that failed to initialize (the+ * `BootedServer.degraded` list — stable only once readiness is `ready`).+ * When omitted (restartable test harness, whose init is synchronous), the+ * health routes still mount and report ready with no degraded subsystems.+ */+ health?: {+ readiness: () => ReadinessState;+ degraded: () => readonly string[];+ };/*** Resolved `remote:` config (null/undefined ⇒ remote access disabled).* When set, EVERY surface (`/mcp`, `/api/*`, `/collab`, content assets,@@ -204,6 +218,44 @@ export function mountMcpAndApi(opts: MountMcpAndApiOptions): MountMcpAndApiHandlconst onRequest = (req: IncomingMessage, res: ServerResponse): void => {const url = req.url?.split('?')[0];+ // Health surface, deliberately ABOVE every admission gate: orchestrator+ // probes (Docker healthcheck, k8s, Railway/Fly) arrive with an IP Host+ // header, no Origin, and often through a proxy that adds forwarding+ // headers — all three of which the gates below refuse. The exemption is+ // safe because the surface is liveness/readiness only; the sole+ // project-adjacent disclosure is degraded subsystem names.+ if (url === '/healthz' || url === '/readyz') {+ if (req.method !== 'GET' && req.method !== 'HEAD') {+ errorResponse(res, 405, 'urn:ok:error:method-not-allowed', 'Method not allowed.', {+ handler: 'health',+ extraHeaders: { Allow: 'GET, HEAD' },+ });+ return;+ }+ const probeHeaders = {+ 'Cache-Control': 'no-store',+ 'X-Content-Type-Options': 'nosniff',+ };+ if (url === '/healthz') {+ res.writeHead(200, { ...probeHeaders, 'Content-Type': 'text/plain; charset=utf-8' });+ res.end('ok');+ return;+ }+ // Single-shaped body in both branches so consumers can read `status`+ // and `degraded` unconditionally. `degraded` is only meaningful once+ // ready — mid-init the list is still being populated.+ const readiness = opts.health?.readiness() ?? 'ready';+ const ready = readiness === 'ready';+ res.writeHead(ready ? 200 : 503, { ...probeHeaders, 'Content-Type': 'application/json' });+ res.end(+ JSON.stringify({+ ready,+ status: readiness,+ degraded: ready ? (opts.health?.degraded() ?? []) : [],+ }),+ );+ return;+ }// Tripwire: proxy-forwarding headers on a server that never opted into// remote access mean a tunnel is pointed at us. Refuse with the fix// instruction — the alternative is silently serving a public tunnel with