Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): record the bound port, stop the spawn log erasing itself (PRD-8393) (#3918)

Andrew Mikofalvy9d0591ed9e79
diff --git a/.changeset/server-listen-and-spawn-log-evidence.md b/.changeset/server-listen-and-spawn-log-evidence.md
new file mode 100644
index 000000000..e5ae0fa9d
--- /dev/null
+++ b/.changeset/server-listen-and-spawn-log-evidence.md
@@ -0,0 +1,9 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Record what the server actually bound, and stop the spawn-error log destroying its own evidence.
+
+A `server.lock` advertises a port, but until now nothing recorded that a server had bound one — so a diagnostic bundle could not tell a live listener from a stale advertisement, or say which process owned a port when two servers had run for the same directory. The server now logs its pid, port, bound addresses and base URL at listen time.
+
+`last-spawn-error.log` was opened in truncate mode on every spawn, so a retry seconds after a failed spawn destroyed the output explaining the failure it was retrying. Both documented writers of that file — the desktop spawn and the MCP shim — now append behind a per-attempt header and start over only at a size cap, sharing one policy so neither erases what the other accumulated. The spawn-failure report bounds its stderr tail to the current attempt, so a child that dies silently no longer inherits the previous attempt's stack trace as its cause.
diff --git a/packages/cli/src/mcp/shim.test.ts b/packages/cli/src/mcp/shim.test.ts
index ee257a6c3..adfb87ea9 100644
--- a/packages/cli/src/mcp/shim.test.ts
+++ b/packages/cli/src/mcp/shim.test.ts
@@ -1,8 +1,14 @@
+import { mkdirSync, writeFileSync } from 'node:fs';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
-import { LOCAL_DIR, OK_DIR } from '@inkeep/open-knowledge-core';
+import {
+ formatSpawnAttemptHeader,
+ LOCAL_DIR,
+ OK_DIR,
+ SPAWN_ERROR_LOG,
+} from '@inkeep/open-knowledge-core';
import { AutoStartDisabledError, type ServerLockMetadata } from '@inkeep/open-knowledge-server';
import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
@@ -297,6 +303,78 @@ describe('MCP stdio shim server resolution', () => {
).rejects.toThrow('spawn failed: spawn EACCES stderr:\nboot failed loudly');
});
+ // Pins the DEFAULT reader, which every other test at this throw site
+ // replaces by injecting `readErrorLog`. The file appends across spawns now,
+ // so reading it whole would hand the previous attempt's stderr to this
+ // failure — and this is the tier where that string reaches an MCP client.
+ test('the default reader quotes only the current attempt', async () => {
+ mkdirSync(lockDir, { recursive: true });
+ writeFileSync(
+ resolve(lockDir, SPAWN_ERROR_LOG),
+ `${formatSpawnAttemptHeader(new Date('2026-08-25T10:00:00.000Z'), 11)}EADDRINUSE from before\n` +
+ `${formatSpawnAttemptHeader(new Date('2026-08-25T11:00:00.000Z'), 12)}the real cause\n`,
+ );
+
+ const err = await resolveMcpHttpUrl({
+ lockDir,
+ contentDir: tmp,
+ readLock: () => null,
+ isAlive: () => false,
+ sleep: async () => {},
+ openErrorLog: () => 123,
+ closeFd: () => {},
+ spawn: (() => {
+ throw new Error('spawn EACCES');
+ }) as never,
+ timeoutMs: 1000,
+ pollIntervalMs: 1,
+ }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ expect(err?.message).toContain('the real cause');
+ expect(err?.message).not.toContain('EADDRINUSE from before');
+ // Nor our own delimiter — the report quotes the child, not the parent.
+ expect(err?.message).not.toContain('spawn attempt');
+ });
+
+ // The reader's other property, and the one that decides how big a payload
+ // this hands an MCP client. The file's own cap is 256 KiB, so without this
+ // bound a single noisy attempt would be quoted whole into a JSON-RPC error.
+ test('the default reader bounds one huge attempt to a tail', async () => {
+ mkdirSync(lockDir, { recursive: true });
+ const oldest = 'FIRST-LINE-MARKER\n';
+ writeFileSync(
+ resolve(lockDir, SPAWN_ERROR_LOG),
+ `${formatSpawnAttemptHeader(new Date('2026-08-25T11:00:00.000Z'), 12)}${oldest}${'x'.repeat(20_000)}`,
+ );
+
+ const err = await resolveMcpHttpUrl({
+ lockDir,
+ contentDir: tmp,
+ readLock: () => null,
+ isAlive: () => false,
+ sleep: async () => {},
+ openErrorLog: () => 123,
+ closeFd: () => {},
+ spawn: (() => {
+ throw new Error('spawn EACCES');
+ }) as never,
+ timeoutMs: 1000,
+ pollIntervalMs: 1,
+ }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ // Truncated from the front, marked as truncated, and nowhere near the
+ // file's own 256 KiB cap.
+ expect(err?.message).not.toContain('FIRST-LINE-MARKER');
+ expect(err?.message).toContain('…');
+ expect(err?.message.length).toBeLessThan(9_000);
+ });
+
test('async spawn failure includes captured stderr', async () => {
let errorHandler: ((err: Error) => void) | undefined;
diff --git a/packages/cli/src/mcp/shim.ts b/packages/cli/src/mcp/shim.ts
index d35656d69..b5ff109e5 100644
--- a/packages/cli/src/mcp/shim.ts
+++ b/packages/cli/src/mcp/shim.ts
@@ -22,7 +22,7 @@
*/
import { type ChildProcess, spawn as nativeSpawn } from 'node:child_process';
import { randomUUID } from 'node:crypto';
-import { closeSync, existsSync, mkdirSync, openSync, readFileSync } from 'node:fs';
+import { closeSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import type { Readable, Writable } from 'node:stream';
import { setTimeout as wait } from 'node:timers/promises';
@@ -30,8 +30,10 @@ import {
clientVersionHeaders,
DEFAULT_SERVER_HOST,
SPAWN_ERROR_LOG,
+ sliceLastSpawnAttempt,
} from '@inkeep/open-knowledge-core';
import { startKeepalive as defaultStartKeepalive } from '@inkeep/open-knowledge-core/keepalive';
+import { openSpawnErrorLog } from '@inkeep/open-knowledge-core/server';
import {
AutoStartDisabledError,
isProcessAlive as defaultIsProcessAlive,
@@ -209,8 +211,32 @@ function liveBaseUrlFromLock(
return lockBaseUrl(lock, { fallbackHost: DEFAULT_SERVER_HOST }) ?? undefined;
}
+/**
+ * Mirrors the desktop reader's bound rather than the file's own 256 KiB cap:
+ * this string is interpolated into a JSON-RPC error handed to an MCP client,
+ * and a quarter-megabyte payload there is not a diagnostic.
+ *
+ * Counted in UTF-16 code units, not bytes, because that is what `String`
+ * length and `slice` measure. Non-ASCII stderr — a localised OS error, a CJK
+ * or Cyrillic path — can therefore reach roughly three times this in UTF-8.
+ * That is still a diagnostic rather than a blowup, which is why the simpler
+ * unit is kept; the number just should not be read as a byte ceiling.
+ */
+const SPAWN_STDERR_TAIL_UNITS = 8192;
+
+/**
+ * Bound to the CURRENT attempt, then to a tail. The file appends across spawns,
+ * so reading it whole would quote every earlier attempt's stderr as the cause
+ * of this failure — and a spawn that dies having written nothing would report
+ * the previous one's error as its own. Truncate-on-spawn is what used to make
+ * the unbounded read safe, and it no longer applies.
+ */
function readErrorLogDefault(path: string): string {
- return existsSync(path) ? readFileSync(path, 'utf-8').trim() : '';
+ if (!existsSync(path)) return '';
+ const attempt = sliceLastSpawnAttempt(readFileSync(path, 'utf-8')).trim();
+ return attempt.length > SPAWN_STDERR_TAIL_UNITS
+ ? `…${attempt.slice(-SPAWN_STDERR_TAIL_UNITS)}`
+ : attempt;
}
function formatTimeoutMessage(timeoutMs: number, stderr: string): string {
@@ -255,7 +281,12 @@ export async function resolveMcpHttpUrl(opts: ResolveMcpHttpUrlOptions): Promise
const sleep = opts.sleep ?? ((ms: number) => wait(ms));
const spawnFn = opts.spawn ?? nativeSpawn;
const readErrorLog = opts.readErrorLog ?? readErrorLogDefault;
- const openErrorLog = opts.openErrorLog ?? ((path: string) => openSync(path, 'w'));
+ // Appends behind a per-attempt header, matching the desktop spawn site. The
+ // two writers share this file by design, so a truncating peer would erase
+ // whatever the other accumulated and put the retry-destroys-evidence defect
+ // straight back on this path.
+ const openErrorLog =
+ opts.openErrorLog ?? ((path: string) => openSpawnErrorLog(path, process.pid));
const closeFd = opts.closeFd ?? closeSync;
const timeoutMs = opts.timeoutMs ?? DEFAULT_SPAWN_TIMEOUT_MS;
const pollIntervalMs = opts.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
diff --git a/packages/core/src/constants/lifecycle.test.ts b/packages/core/src/constants/lifecycle.test.ts
new file mode 100644
index 000000000..ab85fbe4b
--- /dev/null
+++ b/packages/core/src/constants/lifecycle.test.ts
@@ -0,0 +1,96 @@
+import { describe, expect, test } from 'vitest';
+import {
+ formatSpawnAttemptHeader,
+ SPAWN_ATTEMPT_MARKER,
+ SPAWN_ERROR_LOG_MAX_BYTES,
+ sliceLastSpawnAttempt,
+ spawnErrorLogOpenMode,
+} from './lifecycle.ts';
+
+describe('spawnErrorLogOpenMode', () => {
+ // The defect: a retry seconds after a failed spawn used to truncate the very
+ // output that explained the failure, so three failed spawns left 0 bytes.
+ test('appends to an existing sink rather than truncating it', () => {
+ expect(spawnErrorLogOpenMode(0)).toBe('a');
+ expect(spawnErrorLogOpenMode(1)).toBe('a');
+ expect(spawnErrorLogOpenMode(SPAWN_ERROR_LOG_MAX_BYTES - 1)).toBe('a');
+ });
+
+ test('starts over once the sink reaches the cap', () => {
+ expect(spawnErrorLogOpenMode(SPAWN_ERROR_LOG_MAX_BYTES)).toBe('w');
+ expect(spawnErrorLogOpenMode(SPAWN_ERROR_LOG_MAX_BYTES + 1)).toBe('w');
+ });
+
+ // `'a'` is never worse than `'w'` here and is sometimes the difference
+ // between keeping a log and destroying it: `'a'` creates an absent file, and
+ // a file that exists but could not be statted still has contents worth
+ // keeping. Callers reach this branch through a catch that cannot tell ENOENT
+ // from a transient error.
+ test('appends when the size is unknown, rather than truncating', () => {
+ expect(spawnErrorLogOpenMode(undefined)).toBe('a');
+ });
+
+ test('the cap is the documented 256 KiB, not just some threshold', () => {
+ expect(SPAWN_ERROR_LOG_MAX_BYTES).toBe(256 * 1024);
+ });
+});
+
+describe('formatSpawnAttemptHeader', () => {
+ test('carries the attempt time and the spawning pid', () => {
+ const header = formatSpawnAttemptHeader(new Date('2026-08-25T18:49:24.449Z'), 4242);
+ expect(header).toContain('2026-08-25T18:49:24.449Z');
+ expect(header).toContain('pid=4242');
+ });
+
+ test('opens on its own line so appended output stays separable', () => {
+ const header = formatSpawnAttemptHeader(new Date('2026-08-25T18:49:24.449Z'), 1);
+ expect(header.startsWith('\n')).toBe(true);
+ expect(header.endsWith('\n')).toBe(true);
+ });
+
+ // The two are one mechanism: the header is only worth writing because the
+ // slicer can find it again.
+ test('the header it writes is the boundary the slicer finds', () => {
+ const first = `${formatSpawnAttemptHeader(new Date('2026-08-25T10:00:00.000Z'), 1)}first boom\n`;
+ const second = `${formatSpawnAttemptHeader(new Date('2026-08-25T11:00:00.000Z'), 2)}second boom\n`;
+ const sliced = sliceLastSpawnAttempt(first + second);
+ expect(sliced).toContain('second boom');
+ expect(sliced).not.toContain('first boom');
+ // The header line itself is not output. A caller that renders a stderr
+ // section on truthiness would otherwise show the parent's own delimiter.
+ expect(sliced).not.toContain(SPAWN_ATTEMPT_MARKER);
+ });
+});
+
+describe('sliceLastSpawnAttempt', () => {
+ // The regression appending introduced, and the reason this function exists:
+ // a child that dies having written nothing leaves the previous attempt's
+ // trace as the newest text in the file, and the failure report quotes it as
+ // the cause of the current spawn.
+ test('a silent attempt inherits no output from the attempt before it', () => {
+ const noisy = `${formatSpawnAttemptHeader(new Date('2026-08-25T10:00:00.000Z'), 1)}EADDRINUSE\n`;
+ const silent = formatSpawnAttemptHeader(new Date('2026-08-25T11:00:00.000Z'), 2);
+ expect(sliceLastSpawnAttempt(noisy + silent)).not.toContain('EADDRINUSE');
+ });
+
+ // Load-bearing beyond tidiness: callers gate the whole stderr section on
+ // this being non-empty, so "the child printed nothing" has to stay
+ // expressible. Returning the header would make every attempt look noisy.
+ test('a silent attempt is empty, not a bare header', () => {
+ const silent = formatSpawnAttemptHeader(new Date('2026-08-25T11:00:00.000Z'), 2);
+ expect(sliceLastSpawnAttempt(silent)).toBe('');
+ });
+
+ // A header truncated mid-write has no output after it by construction.
+ test('a header with no terminating newline yields nothing', () => {
+ expect(sliceLastSpawnAttempt(`\n${SPAWN_ATTEMPT_MARKER}2026-08-25T11:00`)).toBe('');
+ });
+
+ // A file written before headers existed, or by a site that does not stamp
+ // one, is all the evidence there is — dropping it would be worse than the
+ // boundary being unknown.
+ test('returns an unmarked file whole', () => {
+ expect(sliceLastSpawnAttempt('legacy stack trace\n')).toBe('legacy stack trace\n');
+ expect(sliceLastSpawnAttempt('')).toBe('');
+ });
+});
diff --git a/packages/core/src/constants/lifecycle.ts b/packages/core/src/constants/lifecycle.ts
index 7d55164c6..64f8469c1 100644
--- a/packages/core/src/constants/lifecycle.ts
+++ b/packages/core/src/constants/lifecycle.ts
@@ -37,6 +37,79 @@ export const DEFAULT_SIGTERM_POLL_MS = 200;
*/
export const SPAWN_ERROR_LOG = 'last-spawn-error.log';
+/**
+ * Cap for `SPAWN_ERROR_LOG`, checked at open time. It bounds accumulation
+ * ACROSS spawn attempts — the crash-loop case, where a stack per attempt piles
+ * up and the file stops being evidence and becomes disk usage. It does NOT
+ * bound one long-lived child: that child inherits the fd and nothing re-stats
+ * until the next spawn. Narrow in practice, since pino writes to stdout and the
+ * file sink rather than raw stderr, but the guarantee is the weaker one.
+ */
+export const SPAWN_ERROR_LOG_MAX_BYTES = 256 * 1024;
+
+/** Literal that opens every attempt header; the boundary readers scan for. */
+export const SPAWN_ATTEMPT_MARKER = '=== spawn attempt ';
+
+/**
+ * Whether a spawn site should append to `SPAWN_ERROR_LOG` or start it over.
+ *
+ * Truncating per spawn is the obvious choice and the wrong one: the retry that
+ * follows a failed spawn arrives seconds later and overwrites the output that
+ * explained the failure it is retrying. A file whose whole purpose is to
+ * survive a failed spawn cannot be opened in truncate mode by the next spawn.
+ *
+ * Both documented writers above must agree on this, or whichever spawns second
+ * erases what the first accumulated.
+ *
+ * An unknown size answers `'a'`, because `'w'` is never better there and is
+ * sometimes the destruction this exists to prevent: Node's `'a'` is
+ * `O_APPEND|O_CREAT`, so an absent file is created either way, while a file
+ * that exists but could not be statted still has contents worth keeping.
+ * Callers reach this branch through a bare catch that cannot tell `ENOENT`
+ * from a transient error, so the branch has to be safe for both.
+ */
+export function spawnErrorLogOpenMode(currentSizeBytes: number | undefined): 'a' | 'w' {
+ if (currentSizeBytes === undefined) return 'a';
+ return currentSizeBytes >= SPAWN_ERROR_LOG_MAX_BYTES ? 'w' : 'a';
+}
+
+/**
+ * Delimiter written before an attempt's output. Appending without one turns N
+ * failures into a single undelimited wall of stack traces, and — load-bearing —
+ * it is what lets a reader bound the CURRENT attempt: see
+ * `sliceLastSpawnAttempt`.
+ */
+export function formatSpawnAttemptHeader(startedAt: Date, spawningPid: number): string {
+ return `\n${SPAWN_ATTEMPT_MARKER}${startedAt.toISOString()} pid=${spawningPid} ===\n`;
+}
+
+/**
+ * The last attempt's slice of an appended `SPAWN_ERROR_LOG`.
+ *
+ * A failure report that quotes this file is claiming "this is why THIS spawn
+ * failed". Under append that is only true of the text after the final header:
+ * a child that dies having written nothing would otherwise hand the previous
+ * attempt's stack trace to the current failure, which is a false record of
+ * exactly the kind this log exists to prevent.
+ *
+ * The header itself is excluded, not just the attempts before it. The parent
+ * writes that line BEFORE the spawn, so including it would make the result
+ * non-empty for a child that printed nothing — and a caller's emptiness check
+ * is exactly how it knows the child was silent. A report that renders a
+ * `--- stderr ---` section containing only the parent's own delimiter promises
+ * the child's output and delivers punctuation.
+ *
+ * A file with no marker predates the header (or was written by a site that
+ * does not stamp one) and is returned whole — there is no boundary to honor,
+ * and dropping it would lose the only evidence there is.
+ */
+export function sliceLastSpawnAttempt(raw: string): string {
+ const lastHeader = raw.lastIndexOf(SPAWN_ATTEMPT_MARKER);
+ if (lastHeader === -1) return raw;
+ const endOfHeaderLine = raw.indexOf('\n', lastHeader);
+ return endOfHeaderLine === -1 ? '' : raw.slice(endOfHeaderLine + 1);
+}
+
/**
* Filename under `<projectRoot>/.ok/local/` where the desktop host records why
* the server process last exited. Written by the desktop main process (which
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index e595e0ae0..76cc7837e 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1717,9 +1717,14 @@ export {
export {
DEFAULT_SIGTERM_GRACE_MS,
DEFAULT_SIGTERM_POLL_MS,
+ formatSpawnAttemptHeader,
SERVER_CRASH_LOG,
SERVER_EXIT_LOG,
+ SPAWN_ATTEMPT_MARKER,
SPAWN_ERROR_LOG,
+ SPAWN_ERROR_LOG_MAX_BYTES,
+ sliceLastSpawnAttempt,
+ spawnErrorLogOpenMode,
} from './constants/lifecycle.ts';
export {
type FrontmatterIssue,
diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts
index 241dc62e3..206df6b77 100644
--- a/packages/core/src/server.ts
+++ b/packages/core/src/server.ts
@@ -63,3 +63,4 @@ export {
withFileLock,
withFileLockSync,
} from './util/file-lock.ts';
+export { openSpawnErrorLog } from './util/spawn-error-log-open.ts';
diff --git a/packages/core/src/util/spawn-error-log-open.test.ts b/packages/core/src/util/spawn-error-log-open.test.ts
new file mode 100644
index 000000000..40f169fef
--- /dev/null
+++ b/packages/core/src/util/spawn-error-log-open.test.ts
@@ -0,0 +1,101 @@
+import {
+ chmodSync,
+ closeSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+ writeSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterEach, describe, expect, test } from 'vitest';
+import { SPAWN_ATTEMPT_MARKER, SPAWN_ERROR_LOG_MAX_BYTES } from '../constants/lifecycle.ts';
+import { openSpawnErrorLog } from './spawn-error-log-open.ts';
+
+const scratchDirs: string[] = [];
+
+function scratchPath(): string {
+ const dir = mkdtempSync(join(tmpdir(), 'ok-spawn-log-'));
+ scratchDirs.push(dir);
+ return join(dir, 'last-spawn-error.log');
+}
+
+afterEach(() => {
+ // One of these fixtures is the size cap, so leaving them behind costs real
+ // disk per run, not just clutter.
+ while (scratchDirs.length > 0) {
+ const dir = scratchDirs.pop();
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+/** Run one attempt end to end: open through the real sequence, write, close. */
+function attempt(path: string, childOutput: string, pid = 4242): void {
+ const fd = openSpawnErrorLog(path, pid);
+ try {
+ if (childOutput) writeSync(fd, childOutput);
+ } finally {
+ closeSync(fd);
+ }
+}
+
+// This module IS the fix — the predicates are separately unit-tested, but the
+// sequence they compose is what every spawn actually runs, and it is reachable
+// from a test only because it was extracted here.
+describe('openSpawnErrorLog', () => {
+ test('creates the log when absent, with the header and the output', () => {
+ const path = scratchPath();
+ attempt(path, 'boom\n');
+ const contents = readFileSync(path, 'utf-8');
+ expect(contents).toContain(SPAWN_ATTEMPT_MARKER);
+ expect(contents).toContain('boom');
+ });
+
+ // The defect the whole change exists to remove: a retry seconds later used
+ // to truncate the output that explained the failure it was retrying.
+ test('a second attempt appends rather than erasing the first', () => {
+ const path = scratchPath();
+ attempt(path, 'first failure\n', 11);
+ attempt(path, 'second failure\n', 12);
+ const contents = readFileSync(path, 'utf-8');
+ expect(contents).toContain('first failure');
+ expect(contents).toContain('second failure');
+ expect(contents.match(new RegExp(SPAWN_ATTEMPT_MARKER, 'g'))).toHaveLength(2);
+ });
+
+ test('every attempt stamps a header, so the boundary always exists', () => {
+ const path = scratchPath();
+ attempt(path, '', 11);
+ expect(readFileSync(path, 'utf-8')).toContain('pid=11');
+ });
+
+ test('starts over once the file has reached the cap', () => {
+ const path = scratchPath();
+ writeFileSync(path, 'x'.repeat(SPAWN_ERROR_LOG_MAX_BYTES));
+ attempt(path, 'after the reset\n');
+ const contents = readFileSync(path, 'utf-8');
+ expect(contents).toContain('after the reset');
+ expect(contents.length).toBeLessThan(SPAWN_ERROR_LOG_MAX_BYTES);
+ });
+
+ // `open(2)` honours its mode argument only on creation, so a log an older
+ // release created at the default 0644 would keep those permissions forever.
+ // A child's stderr carries absolute paths, and this sits beside a 0600 lock.
+ test('tightens an existing world-readable log to 0600', () => {
+ const path = scratchPath();
+ writeFileSync(path, 'from an older release\n');
+ // Explicit chmod, not the `writeFileSync` mode, which umask can mask.
+ chmodSync(path, 0o644);
+ expect(statSync(path).mode & 0o777).toBe(0o644);
+ attempt(path, 'next\n');
+ expect(statSync(path).mode & 0o777).toBe(0o600);
+ });
+
+ test('creates a new log at 0600', () => {
+ const path = scratchPath();
+ attempt(path, 'boom\n');
+ expect(statSync(path).mode & 0o777).toBe(0o600);
+ });
+});
diff --git a/packages/core/src/util/spawn-error-log-open.ts b/packages/core/src/util/spawn-error-log-open.ts
new file mode 100644
index 000000000..9e5ced416
--- /dev/null
+++ b/packages/core/src/util/spawn-error-log-open.ts
@@ -0,0 +1,56 @@
+import { fchmodSync, openSync, statSync, writeSync } from 'node:fs';
+import { formatSpawnAttemptHeader, spawnErrorLogOpenMode } from '../constants/lifecycle.ts';
+
+/**
+ * Open `SPAWN_ERROR_LOG` for one spawn attempt.
+ *
+ * Node-only, and shared rather than repeated: both documented writers of that
+ * file must agree on the whole sequence, not just the predicates. Stat failure
+ * handling, the file mode, and whether a missing header is fatal are each a
+ * decision that would otherwise be re-made per site, and two sites that drift
+ * on any of them put the retry-destroys-evidence defect back on one path.
+ */
+export function openSpawnErrorLog(path: string, spawningPid: number): number {
+ let existingSize: number | undefined;
+ try {
+ existingSize = statSync(path).size;
+ } catch {
+ // Deliberately undifferentiated: append is correct whether the file is
+ // absent or merely unstattable, so nothing here needs to tell them apart.
+ existingSize = undefined;
+ }
+ const fd = openSync(path, spawnErrorLogOpenMode(existingSize), 0o600);
+ try {
+ // A child's stderr carries absolute paths and can carry env-derived values,
+ // and this file sits beside a `server.lock` written 0600 for that reason.
+ // `open(2)` honours `mode` only when it CREATES the file, and the common
+ // path here is append onto one that already exists — including one an older
+ // release created at the default 0644. Nothing else would repair that: the
+ // size cap reopens with `'w'`, which truncates the contents and leaves the
+ // mode exactly as it found it.
+ //
+ // Unconditional rather than gated on the file being loose. Skipping the
+ // already-private case would save one `fchmod(2)` immediately before a
+ // `fork`/`exec` that costs orders of magnitude more, and would buy it with
+ // a stat result kept alive past the open for a branch ending at the same fd
+ // either way.
+ //
+ // Permission semantics here are POSIX's. Windows models them differently,
+ // so this is best-effort there; the file lives under the project directory
+ // the user chose, not under their profile, so no profile-level ACL can be
+ // assumed to be doing this job instead.
+ fchmodSync(fd, 0o600);
+ } catch {
+ // A filesystem that cannot chmod, or a file this euid does not own, still
+ // gets its spawn: the mode is hardening, not a precondition for logging.
+ }
+ try {
+ writeSync(fd, formatSpawnAttemptHeader(new Date(), spawningPid));
+ } catch {
+ // A header we could not write is not worth failing a spawn over — the
+ // child's stderr still lands on this fd, which is the part that matters.
+ // The cost is that this attempt's output merges into the one before it,
+ // since readers bound an attempt by the nearest preceding header.
+ }
+ return fd;
+}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index ea9f340fb..64b6e9797 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -34,7 +34,6 @@ import {
existsSync,
promises as fsPromises,
mkdirSync,
- openSync,
readFileSync,
realpathSync,
statSync,
@@ -94,6 +93,7 @@ import type {
OkTerminalDockStateWriteResult,
OkTerminalRestartSnapshot,
} from '@inkeep/open-knowledge-core/desktop-bridge';
+import { openSpawnErrorLog } from '@inkeep/open-knowledge-core/server';
import { parseSkillDir } from '@inkeep/open-knowledge-core/skills-catalog';
import {
assertGitAvailable,
@@ -1867,9 +1867,12 @@ function ensureWindowManager() {
// filename — one tail target for operators. `stdio: 'ignore'`
// would route everything to /dev/null and leave the user
// staring at a 15-second `spawn-lock-timeout` with no
- // breadcrumb. The fd is opened in 'w' mode (truncate-on-spawn)
- // so each boot starts with a fresh log; rotation lives at the
- // OS level if it ever matters.
+ // breadcrumb. The fd APPENDS behind a per-attempt header, because
+ // the retry after a failed spawn would otherwise erase the output
+ // explaining the failure it is retrying; it starts over only at
+ // `SPAWN_ERROR_LOG_MAX_BYTES`, so rotation is this policy's job
+ // and not the OS's. Both writers share the mode — see
+ // `spawnErrorLogOpenMode`.
const projectRoot = projectDir ?? contentDir;
const lockDir = getLocalDir(projectRoot);
if (!existsSync(lockDir)) {
@@ -1893,7 +1896,7 @@ function ensureWindowManager() {
const spawnErrorLogPath = join(lockDir, SPAWN_ERROR_LOG);
let spawnErrorLogFd: number;
try {
- spawnErrorLogFd = openSync(spawnErrorLogPath, 'w');
+ spawnErrorLogFd = openSpawnErrorLog(spawnErrorLogPath, process.pid);
} catch (err) {
throw Object.assign(
new Error(
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index 946510dde..be9e77eb0 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -32,6 +32,7 @@ import {
DEFAULT_SIGTERM_GRACE_MS,
DEFAULT_SIGTERM_POLL_MS,
SPAWN_ERROR_LOG,
+ sliceLastSpawnAttempt,
} from '@inkeep/open-knowledge-core';
import type { KeepaliveHandle } from '@inkeep/open-knowledge-core/keepalive';
import { getLocalDir } from '@inkeep/open-knowledge-server';
@@ -3403,8 +3404,18 @@ export class WindowManager {
const STDERR_TAIL_BYTES = 8192;
let stderrTail: string | undefined;
try {
- const raw = readFileSync(join(lockDir, SPAWN_ERROR_LOG), 'utf-8');
- stderrTail = raw.length > STDERR_TAIL_BYTES ? `…${raw.slice(-STDERR_TAIL_BYTES)}` : raw;
+ // Bound to THIS attempt first. The file appends across spawns, so a
+ // child that died having written nothing would otherwise hand the
+ // previous attempt's stack trace to this failure, labelled as its cause —
+ // a false record of exactly the kind this log exists to prevent.
+ // `.trim()` matching the sibling shim reader: without it, a child whose
+ // only output is a newline defeats the emptiness contract above and
+ // renders a stderr section containing whitespace.
+ const attempt = sliceLastSpawnAttempt(
+ readFileSync(join(lockDir, SPAWN_ERROR_LOG), 'utf-8'),
+ ).trim();
+ stderrTail =
+ attempt.length > STDERR_TAIL_BYTES ? `…${attempt.slice(-STDERR_TAIL_BYTES)}` : attempt;
} catch (readErr) {
// An absent log is expected — the child can die before opening the fd.
// Anything else (permissions, a bad path) would otherwise vanish here and
diff --git a/packages/desktop/tests/main/window-manager.test.ts b/packages/desktop/tests/main/window-manager.test.ts
index 1ce77ea34..0330d5a91 100644
--- a/packages/desktop/tests/main/window-manager.test.ts
+++ b/packages/desktop/tests/main/window-manager.test.ts
@@ -1,9 +1,9 @@
-import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
-import { DEFAULT_SERVER_HOST } from '@inkeep/open-knowledge-core';
-import { beforeEach, describe, expect, test, vi } from 'vitest';
+import { DEFAULT_SERVER_HOST, formatSpawnAttemptHeader } from '@inkeep/open-knowledge-core';
+import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { breakServerLockHeldBy } from '../../src/main/server-lock-break.ts';
import type { ShowGateRegistry } from '../../src/main/show-gate.ts';
import {
@@ -2484,12 +2484,23 @@ describe('WindowManager', () => {
expect(err?.message).toMatch(/exited before binding/);
});
+ const spawnStderrRoots: string[] = [];
+ afterEach(() => {
+ // One of these fixtures is 20 KB, so leaving them behind costs disk per
+ // run rather than just clutter.
+ while (spawnStderrRoots.length > 0) {
+ const root = spawnStderrRoots.pop();
+ if (root) rmSync(root, { recursive: true, force: true });
+ }
+ });
+
// The captured stderr is whatever the server printed on the way up, and
// on a healthy boot that is routinely a config advisory. Presenting it
// under a bare "stderr" header next to a failure sends the reader off to
// fix a warning that had nothing to do with it.
function projectWithSpawnErrorLog(contents: string): string {
const root = mkdtempSync(join(tmpdir(), 'ok-spawn-stderr-'));
+ spawnStderrRoots.push(root);
mkdirSync(join(root, '.ok', 'local'), { recursive: true });
writeFileSync(join(root, '.ok', 'local', 'last-spawn-error.log'), contents);
return root;
@@ -2540,6 +2551,100 @@ describe('WindowManager', () => {
expect(err?.message).not.toMatch(/probably not the cause/);
});
+ // Pins the WIRING, not the helper. `sliceLastSpawnAttempt` has its own
+ // unit tests in core, but dropping the call from this reader leaves those
+ // green — and this is the tier where the misattribution would actually
+ // reach a user. The file appends across spawns, so a second attempt that
+ // dies having written nothing must not inherit the first one's error.
+ test('a silent attempt does not report the previous attempt stderr as its cause', async () => {
+ enableSyncTimers();
+ const projectPath = projectWithSpawnErrorLog(
+ `${formatSpawnAttemptHeader(new Date('2026-08-25T10:00:00.000Z'), 4242)}` +
+ 'Error: EACCES on .ok/local\n' +
+ `${formatSpawnAttemptHeader(new Date('2026-08-25T11:00:00.000Z'), 4243)}`,
+ );
+ env.deps.readServerLock = () => null;
+ env.deps.isProcessAlive = () => false;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () =>
+ Promise.resolve({ pid: 88001, readExit: () => ({ code: 1, signal: null }) });
+ env.deps.spawnLockPollDeadlineMs = 1;
+
+ const wm = new WindowManager(env.deps);
+ const err = await wm.createProjectWindow({ projectPath }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ expect(err?.message).toMatch(/exited before binding/);
+ expect(err?.message).not.toMatch(/EACCES/);
+ // And no stderr section at all. The parent writes the header before the
+ // spawn, so a slice that kept it would render `--- stderr ---` over the
+ // app's own delimiter — promising the child's output and delivering
+ // punctuation. Emptiness here IS the "child printed nothing" signal.
+ expect(err?.message).not.toMatch(/^--- stderr ---$/m);
+ expect(err?.message).not.toMatch(/spawn attempt/);
+ });
+
+ // Whitespace is not output. Without the trim, a child whose only write is
+ // a newline renders a stderr section containing a blank line — which
+ // defeats the emptiness contract the attempt slice exists to preserve,
+ // and does it in the case that contract was written for.
+ test('a child that writes only whitespace still counts as silent', async () => {
+ enableSyncTimers();
+ const projectPath = projectWithSpawnErrorLog(
+ `${formatSpawnAttemptHeader(new Date('2026-08-25T11:00:00.000Z'), 4243)}\n \n`,
+ );
+ env.deps.readServerLock = () => null;
+ env.deps.isProcessAlive = () => false;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () =>
+ Promise.resolve({ pid: 88001, readExit: () => ({ code: 1, signal: null }) });
+ env.deps.spawnLockPollDeadlineMs = 1;
+
+ const wm = new WindowManager(env.deps);
+ const err = await wm.createProjectWindow({ projectPath }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ expect(err?.message).toMatch(/exited before binding/);
+ expect(err?.message).not.toMatch(/^--- stderr ---$/m);
+ });
+
+ // The bound's other half. `shim.ts` declares that its bound "mirrors the
+ // desktop reader", so the two are a stated pair — and this side is the
+ // worse one to leave unbounded: the file caps at 256 KiB and this string
+ // lands in a dialog a human reads, where the shim's lands in JSON a
+ // client can truncate.
+ test('a huge attempt is bounded to a tail before it reaches the failure report', async () => {
+ enableSyncTimers();
+ const projectPath = projectWithSpawnErrorLog(
+ `${formatSpawnAttemptHeader(new Date('2026-08-25T11:00:00.000Z'), 4243)}` +
+ 'FIRST-LINE-MARKER\n' +
+ 'x'.repeat(20_000),
+ );
+ env.deps.readServerLock = () => null;
+ env.deps.isProcessAlive = () => false;
+ env.deps.hostname = () => 'my-host';
+ env.deps.probeWsUpgrade = () => Promise.resolve(true);
+ env.deps.spawnDetachedServer = () =>
+ Promise.resolve({ pid: 88001, readExit: () => ({ code: 1, signal: null }) });
+ env.deps.spawnLockPollDeadlineMs = 1;
+
+ const wm = new WindowManager(env.deps);
+ const err = await wm.createProjectWindow({ projectPath }).then(
+ () => null,
+ (e: unknown) => e as Error,
+ );
+
+ expect(err?.message).not.toMatch(/FIRST-LINE-MARKER/);
+ expect(err?.message).toContain('…');
+ expect(err?.message.length).toBeLessThan(9_000);
+ });
+
// A hung start and a crash otherwise render as the same bare deadline.
// Naming the surviving process is what lets the reader tell them apart.
test('a deadline reached with the child alive says the process was still running', async () => {
diff --git a/packages/server/src/boot.test.ts b/packages/server/src/boot.test.ts
index fda7c0889..f4cd5c00b 100644
--- a/packages/server/src/boot.test.ts
+++ b/packages/server/src/boot.test.ts
@@ -1203,6 +1203,62 @@ describeEvenOnCI('bootServer — multi-address bind', () => {
await expect(fetch(`http://127.0.0.1:${booted.port}/healthz`)).rejects.toThrow();
});
+ // The lock advertises a port; nothing else recorded that a server actually
+ // bound one. Those are different claims — the lock outlives the process that
+ // wrote it — and with only the lock, a reader cannot tell a live listener
+ // from a stale advertisement, nor which pid owns a port when two servers have
+ // run for one directory. This pins the record AND pins that it agrees with
+ // the lock, since a record that disagreed would be worse than none.
+ test('the listen record names the bound port, pid and every address, and agrees with the lock', async () => {
+ const contentDir = mkdtempSync(resolve(tmpDir, 'listenlog-'));
+ await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
+ seedOkScaffold(contentDir);
+ const entries: Array<{ fields: Record<string, unknown>; msg: string }> = [];
+ const noop = (): void => {};
+ const captureLogger = {
+ info: (fields: Record<string, unknown>, msg: string) => entries.push({ fields, msg }),
+ warn: noop,
+ error: noop,
+ debug: noop,
+ trace: noop,
+ fatal: noop,
+ level: 'info',
+ silent: noop,
+ bindings: () => ({}),
+ child: () => captureLogger,
+ };
+ const booted = await bootServer({
+ host: '127.0.0.1',
+ bind: ['127.0.0.1', '::1'],
+ config: TEST_CONFIG,
+ contentDir,
+ port: 0,
+ quiet: true,
+ gitEnabled: false,
+ idleShutdownMs: null,
+ log: captureLogger as never,
+ });
+ try {
+ const listened = entries.filter((e) => e.fields.event === 'server-listening');
+ expect(listened).toHaveLength(1);
+ const fields = listened[0]?.fields ?? {};
+ expect(fields.port).toBe(booted.port);
+ expect(fields.pid).toBe(process.pid);
+ expect(fields.addresses).toEqual(['127.0.0.1', '::1']);
+ expect(typeof fields.url).toBe('string');
+ expect(String(fields.url)).toContain(String(booted.port));
+
+ // The corroboration that makes the record worth having: it must name the
+ // same port the lock advertises, from a different source.
+ const lock = JSON.parse(
+ readFileSync(resolve(contentDir, OK_DIR, 'local', 'server.lock'), 'utf-8'),
+ ) as { port: number };
+ expect(fields.port).toBe(lock.port);
+ } finally {
+ await booted.destroy();
+ }
+ });
+
test('duplicate bind entries collapse instead of failing with EADDRINUSE', async () => {
const contentDir = mkdtempSync(resolve(tmpDir, 'multibind-dup-'));
await execFileAsync('git', ['init', '--initial-branch=main', contentDir]);
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index b712885c9..8ab2ff36e 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -1203,6 +1203,24 @@ async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
// the self-call base structurally identical rather than two literals in sync.
const boundBaseUrl = internalBaseUrl();
updateServerLockPort(lockDir, realPort, boundBaseUrl);
+ // The only record that a server actually bound this port, as opposed to a
+ // lock file claiming it did. Those are different facts: the lock outlives the
+ // process that wrote it, so a reader with only the lock cannot tell a live
+ // listener from a stale advertisement, and cannot tell WHICH pid owns a port
+ // when two servers have run for one directory. Every address is named because
+ // a client failing on one family while another answers is otherwise
+ // indistinguishable from the port being dead.
+ log.info(
+ {
+ event: 'server-listening',
+ pid: process.pid,
+ port: realPort,
+ addresses: listenAddresses,
+ url: boundBaseUrl,
+ lockDir,
+ },
+ `[boot] listening on ${boundBaseUrl}`,
+ );
let destroyed = false;
const withDestroyTimeout = async (name: string, work: () => Promise<void>): Promise<void> => {