Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): crash capture line + MCP stdio log mirror (#2738)

Andrew Mikofalvy9260a4c69404
diff --git a/.changeset/crash-capture-and-mcp-log-mirror.md b/.changeset/crash-capture-and-mcp-log-mirror.md
new file mode 100644
index 000000000..297afb217
--- /dev/null
+++ b/.changeset/crash-capture-and-mcp-log-mirror.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Bug-report bundles now capture why the server died and what the MCP server was doing. A fatal server crash (uncaught exception or unhandled rejection) writes a synchronous `last-server-crash.json` record — timestamp, error name/message/stack, pid, uptime — under `.ok/local/` plus a final fatal line in the server log, both collected into `ok bug-report` and `ok diagnose bundle` output; previously a hard crash lost the async log sink's tail and bundles could only say "server not running". The global MCP stdio server's `[mcp]` stderr diagnostics are now also mirrored to `~/.ok/logs/mcp.<date>.log` (pruned at each startup by a 7-day age window and an aggregate size cap), so bundles include the agent-ingress diagnostics that previously landed only in the MCP host's own log folder.
diff --git a/knip.config.ts b/knip.config.ts
index 9633755a0..16d637b4b 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -119,9 +119,7 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts'],
project: 'src/**',
- ignoreDependencies: [
- '@types/shell-quote',
- ],
+ ignoreDependencies: ['@types/shell-quote'],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts'],
diff --git a/packages/cli/src/commands/bug-report-bundle.test.ts b/packages/cli/src/commands/bug-report-bundle.test.ts
index 53d3889ec..a2a74be3a 100644
--- a/packages/cli/src/commands/bug-report-bundle.test.ts
+++ b/packages/cli/src/commands/bug-report-bundle.test.ts
@@ -88,6 +88,23 @@ describe('collectStandardBundle — project bundle', () => {
expect(typeof sysinfo.platform).toBe('string');
});
+ test('last-server-crash.json is packaged from the lock dir when the server recorded a crash', async () => {
+ const projectDir = makeProjectDir();
+ const body = '{"origin":"uncaughtException","error":{"name":"Error","message":"boom"}}\n';
+ writeAt(projectDir, '.ok/local/last-server-crash.json', body);
+ const outputPath = join(makeTmpDir(), 'report.zip');
+
+ const { zipPath } = await collectStandardBundle({
+ projectDir,
+ redact: true,
+ outputPath,
+ });
+
+ const entries = listZipEntries(zipPath);
+ expect(entries).toContain('lockdir/last-server-crash.json');
+ expect(readZipEntry(zipPath, 'lockdir/last-server-crash.json')).toBe(body);
+ });
+
test('MANIFEST.json mirrors the returned summary', async () => {
const projectDir = makeProjectDir();
writeAt(projectDir, '.ok/local/server.lock', '{"pid":1}\n');
diff --git a/packages/cli/src/commands/bug-report-bundle.ts b/packages/cli/src/commands/bug-report-bundle.ts
index 9f09049fe..721a2858a 100644
--- a/packages/cli/src/commands/bug-report-bundle.ts
+++ b/packages/cli/src/commands/bug-report-bundle.ts
@@ -15,7 +15,11 @@ import { createHash } from 'node:crypto';
import { createWriteStream, existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs';
import { freemem, homedir, type as osType, platform, release, totalmem, uptime } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
-import type { BundleManifest, BundleRedaction } from '@inkeep/open-knowledge-core';
+import {
+ type BundleManifest,
+ type BundleRedaction,
+ SERVER_CRASH_LOG,
+} from '@inkeep/open-knowledge-core';
import { withHiddenWindowsConsole } from '@inkeep/open-knowledge-server';
import type { ZipFile } from 'yazl';
// Keep this import type-only: `diagnose/bundle.ts` imports from this module
@@ -179,7 +183,7 @@ function collectLockDir(cwd: string): { files: string[] } {
const lockDir = join(cwd, '.ok', 'local');
if (!existsSync(lockDir)) return { files: [] };
- const candidates = ['server.lock', 'last-spawn-error.log'];
+ const candidates = ['server.lock', 'last-spawn-error.log', SERVER_CRASH_LOG];
const found = candidates.map((f) => join(lockDir, f)).filter((f) => existsSync(f));
return { files: found };
diff --git a/packages/cli/src/diagnose/bundle.test.ts b/packages/cli/src/diagnose/bundle.test.ts
index 37385c8db..fdc370fae 100644
--- a/packages/cli/src/diagnose/bundle.test.ts
+++ b/packages/cli/src/diagnose/bundle.test.ts
@@ -433,6 +433,34 @@ describe('collectBundle — state files', () => {
collected.cleanup();
});
+ test('last-server-crash.json is staged when the server recorded a fatal crash', async () => {
+ const contentDir = makeTmpDir();
+ const body = `${JSON.stringify(
+ {
+ timestamp: '2026-07-18T09:00:00.000Z',
+ origin: 'uncaughtException',
+ error: { name: 'TypeError', message: 'boom', stack: 'TypeError: boom\n at x' },
+ pid: 51502,
+ uptimeSec: 12.5,
+ },
+ null,
+ 2,
+ )}\n`;
+ writeAt(contentDir, '.ok/local/last-server-crash.json', body);
+ const collected = await collectBundle({ contentDir, deps: makeDeterministicDeps() });
+ expect(
+ readFileSync(join(collected.stagingDir, 'state', 'last-server-crash.json'), 'utf-8'),
+ ).toBe(body);
+ collected.cleanup();
+ });
+
+ test('last-server-crash.json is omitted when the server never crashed', async () => {
+ const contentDir = makeTmpDir();
+ const collected = await collectBundle({ contentDir, deps: makeDeterministicDeps() });
+ expect(existsSync(join(collected.stagingDir, 'state', 'last-server-crash.json'))).toBe(false);
+ collected.cleanup();
+ });
+
test('runtime.json carries ok, host blocks; desktop is null by default', async () => {
const contentDir = makeTmpDir();
const collected = await collectBundle({ contentDir, deps: makeDeterministicDeps() });
diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.ts
index 26f5e037e..971bdc454 100644
--- a/packages/cli/src/diagnose/bundle.ts
+++ b/packages/cli/src/diagnose/bundle.ts
@@ -29,7 +29,7 @@ import {
import { arch as osArch, platform as osPlatform, tmpdir } from 'node:os';
import { basename, dirname, join, relative, resolve, sep } from 'node:path';
import type { BundleRedaction as SecretScrubEntry } from '@inkeep/open-knowledge-core';
-import { SERVER_EXIT_LOG } from '@inkeep/open-knowledge-core';
+import { SERVER_CRASH_LOG, SERVER_EXIT_LOG } from '@inkeep/open-knowledge-core';
import {
DEFAULT_LOGS_MAX_BYTES,
DEFAULT_SPANS_MAX_BYTES,
@@ -716,6 +716,14 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB
// a managed shutdown, which `server-status.txt: not-running` alone cannot.
stageFileIfPresent(join(lockDir, SERVER_EXIT_LOG), join(stagingDir, 'state', SERVER_EXIT_LOG));
+ // last-server-crash.json — the server's own fatal-crash record (error name/
+ // message/stack written synchronously by the crash monitor). The inside
+ // view complementing SERVER_EXIT_LOG's outside view.
+ stageFileIfPresent(
+ join(lockDir, SERVER_CRASH_LOG),
+ join(stagingDir, 'state', SERVER_CRASH_LOG),
+ );
+
// Runtime + desktop block.
const runtime = readRuntime();
const desktop = readDesktopEnv();
diff --git a/packages/cli/src/mcp/server.ts b/packages/cli/src/mcp/server.ts
index dde52e1ec..e691e343f 100644
--- a/packages/cli/src/mcp/server.ts
+++ b/packages/cli/src/mcp/server.ts
@@ -58,6 +58,7 @@ import {
import { type HostLivenessWatchHandle, startHostLivenessWatch } from './host-liveness.ts';
import { attachLifecycleLogging } from './lifecycle-logging.ts';
import { parseSpawnTimeoutEnv, resolveMcpHttpUrl, resolveMcpKeepaliveWsUrl } from './shim.ts';
+import { createMcpStderrMirror } from './stderr-mirror.ts';
/**
* Stable in-bundle anchor used by the periodic bundle-identity self-check.
@@ -247,7 +248,17 @@ const CWD_REQUIRED_MESSAGE =
export async function startGlobalMcpServer(
opts: StartGlobalMcpServerOptions,
): Promise<StartGlobalMcpServerHandle> {
- const stderr = process.stderr;
+ // Every `[mcp]` diagnostic in this function writes through this binding, so
+ // wrapping it here mirrors all of them to `~/.ok/logs/mcp.<date>.log` for
+ // bug-report bundles while keeping the host-visible stderr bytes identical.
+ // Mirror first: a destroyed stderr (host gone) must not lose the file copy.
+ const mirror = createMcpStderrMirror();
+ const stderr = {
+ write: (chunk: string): boolean => {
+ mirror.write(chunk);
+ return process.stderr.write(chunk);
+ },
+ };
const spawnTimeoutMs =
opts.spawnTimeoutMs ?? parseSpawnTimeoutEnv(process.env.OK_MCP_SPAWN_TIMEOUT_MS);
const envAutoStart = opts.envAutoStart ?? process.env.OK_MCP_AUTOSTART;
diff --git a/packages/cli/src/mcp/stderr-mirror.test.ts b/packages/cli/src/mcp/stderr-mirror.test.ts
new file mode 100644
index 000000000..e14d65602
--- /dev/null
+++ b/packages/cli/src/mcp/stderr-mirror.test.ts
@@ -0,0 +1,164 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import {
+ closeSync,
+ existsSync,
+ ftruncateSync,
+ mkdirSync,
+ openSync,
+ readFileSync,
+ utimesSync,
+ writeFileSync,
+} from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { createMcpStderrMirror, pruneMirrorLogs } from './stderr-mirror.ts';
+
+let dir: string;
+
+beforeEach(async () => {
+ dir = await mkdtemp(join(tmpdir(), 'ok-mcp-mirror-'));
+});
+
+afterEach(async () => {
+ await rm(dir, { recursive: true, force: true });
+});
+
+function fixedClock(iso: string): () => Date {
+ return () => new Date(iso);
+}
+
+describe('createMcpStderrMirror', () => {
+ test('appends chunks to a date-named file with an ISO timestamp prefix', () => {
+ const mirror = createMcpStderrMirror({
+ logsDir: dir,
+ now: fixedClock('2026-07-18T10:00:00.000Z'),
+ pruneDelayMs: 0,
+ });
+ mirror.write('[mcp] global stdio server ready\n');
+ mirror.write('[mcp] stdin EOF\n');
+ const content = readFileSync(join(dir, 'mcp.2026-07-18.log'), 'utf-8');
+ expect(content).toBe(
+ '2026-07-18T10:00:00.000Z [mcp] global stdio server ready\n' +
+ '2026-07-18T10:00:00.000Z [mcp] stdin EOF\n',
+ );
+ });
+
+ test('creates the logs dir on first write when absent', () => {
+ const nested = join(dir, 'not', 'yet', 'there');
+ const mirror = createMcpStderrMirror({
+ logsDir: nested,
+ now: fixedClock('2026-07-18T10:00:00.000Z'),
+ pruneDelayMs: 0,
+ });
+ mirror.write('[mcp] hello\n');
+ expect(existsSync(join(nested, 'mcp.2026-07-18.log'))).toBe(true);
+ });
+
+ test('rolls to a new file when the date changes mid-session', () => {
+ let iso = '2026-07-18T23:59:59.000Z';
+ const mirror = createMcpStderrMirror({
+ logsDir: dir,
+ now: () => new Date(iso),
+ pruneDelayMs: 0,
+ });
+ mirror.write('[mcp] day one\n');
+ iso = '2026-07-19T00:00:01.000Z';
+ mirror.write('[mcp] day two\n');
+ expect(readFileSync(join(dir, 'mcp.2026-07-18.log'), 'utf-8')).toContain('day one');
+ expect(readFileSync(join(dir, 'mcp.2026-07-19.log'), 'utf-8')).toContain('day two');
+ });
+
+ test('recovers after the logs dir is removed mid-session instead of self-disabling', async () => {
+ const nested = join(dir, 'logs');
+ const mirror = createMcpStderrMirror({
+ logsDir: nested,
+ now: fixedClock('2026-07-18T10:00:00.000Z'),
+ pruneDelayMs: 0,
+ });
+ mirror.write('[mcp] before\n');
+ expect(existsSync(join(nested, 'mcp.2026-07-18.log'))).toBe(true);
+
+ // Something external (tmpwatch, user cleanup) removes the dir mid-session.
+ await rm(nested, { recursive: true, force: true });
+
+ // The write that raced the removal is lost, but the mirror re-ensures the
+ // dir on the next attempt rather than counting down to a permanent disable.
+ mirror.write('[mcp] lost\n');
+ mirror.write('[mcp] recovered\n');
+ const content = readFileSync(join(nested, 'mcp.2026-07-18.log'), 'utf-8');
+ expect(content).toContain('recovered');
+ });
+
+ test('write failures are swallowed and disable the mirror after repeated failures', () => {
+ // A regular file where the logs dir should be makes every write fail.
+ const blocked = join(dir, 'blocked');
+ writeFileSync(blocked, 'file, not dir');
+ const mirror = createMcpStderrMirror({
+ logsDir: join(blocked, 'logs'),
+ pruneDelayMs: 0,
+ });
+ for (let i = 0; i < 20; i++) {
+ expect(() => mirror.write('[mcp] doomed\n')).not.toThrow();
+ }
+ });
+});
+
+describe('pruneMirrorLogs', () => {
+ const DAY_MS = 24 * 60 * 60 * 1000;
+
+ function touch(name: string, ageMs: number, now: Date, bytes = 10): void {
+ const path = join(dir, name);
+ const fd = openSync(path, 'w');
+ // Sparse file: statSync reports the logical size without eating disk.
+ ftruncateSync(fd, bytes);
+ closeSync(fd);
+ const mtime = new Date(now.getTime() - ageMs);
+ utimesSync(path, mtime, mtime);
+ }
+
+ test('deletes mirror files older than the retention window, keeps recent ones', () => {
+ const now = new Date('2026-07-18T10:00:00.000Z');
+ touch('mcp.2026-07-01.log', 17 * DAY_MS, now);
+ touch('mcp.2026-07-17.log', 1 * DAY_MS, now);
+ pruneMirrorLogs(dir, () => now);
+ expect(existsSync(join(dir, 'mcp.2026-07-01.log'))).toBe(false);
+ expect(existsSync(join(dir, 'mcp.2026-07-17.log'))).toBe(true);
+ });
+
+ test('never touches non-mirror files in the shared logs dir', () => {
+ const now = new Date('2026-07-18T10:00:00.000Z');
+ touch('desktop.2026-06-01.log', 40 * DAY_MS, now);
+ touch('other.log', 40 * DAY_MS, now);
+ touch('mcp.2026-06-01.log', 40 * DAY_MS, now);
+ pruneMirrorLogs(dir, () => now);
+ expect(existsSync(join(dir, 'desktop.2026-06-01.log'))).toBe(true);
+ expect(existsSync(join(dir, 'other.log'))).toBe(true);
+ expect(existsSync(join(dir, 'mcp.2026-06-01.log'))).toBe(false);
+ });
+
+ test('deletes oldest-first until the aggregate size fits the cap', () => {
+ const now = new Date('2026-07-18T10:00:00.000Z');
+ const twentyMb = 20 * 1024 * 1024;
+ touch('mcp.2026-07-15.log', 3 * DAY_MS, now, twentyMb);
+ touch('mcp.2026-07-16.log', 2 * DAY_MS, now, twentyMb);
+ touch('mcp.2026-07-17.log', 1 * DAY_MS, now, twentyMb);
+ pruneMirrorLogs(dir, () => now);
+ // 60 MB total against the 45 MB cap: only the oldest goes.
+ expect(existsSync(join(dir, 'mcp.2026-07-15.log'))).toBe(false);
+ expect(existsSync(join(dir, 'mcp.2026-07-16.log'))).toBe(true);
+ expect(existsSync(join(dir, 'mcp.2026-07-17.log'))).toBe(true);
+ });
+
+ test('a missing dir is a no-op', () => {
+ expect(() => pruneMirrorLogs(join(dir, 'nope'))).not.toThrow();
+ });
+
+ test('startup sweep runs inline when pruneDelayMs is 0', () => {
+ const now = new Date('2026-07-18T10:00:00.000Z');
+ touch('mcp.2026-07-01.log', 17 * DAY_MS, now);
+ mkdirSync(dir, { recursive: true });
+ createMcpStderrMirror({ logsDir: dir, now: () => now, pruneDelayMs: 0 });
+ expect(existsSync(join(dir, 'mcp.2026-07-01.log'))).toBe(false);
+ });
+});
diff --git a/packages/cli/src/mcp/stderr-mirror.ts b/packages/cli/src/mcp/stderr-mirror.ts
new file mode 100644
index 000000000..a6b21cc57
--- /dev/null
+++ b/packages/cli/src/mcp/stderr-mirror.ts
@@ -0,0 +1,152 @@
+/**
+ * File mirror for the global MCP stdio server's stderr diagnostics.
+ *
+ * The stdio server's `[mcp]` breadcrumbs go to the host process's stderr —
+ * which lands wherever the host keeps its own logs (e.g. Claude Desktop's
+ * log folder), invisible to `ok bug-report`. This mirror appends a copy of
+ * every diagnostic line to `~/.ok/logs/mcp.<YYYY-MM-DD>.log`, matching the
+ * desktop logger's conventions in that directory (`desktop.<date>.log`
+ * naming; 7-day age + aggregate-size retention), so the bug-report bundle's
+ * user-log collection (`collectLogs` scans `~/.ok/logs/*.log`) picks it up
+ * with no collector changes.
+ *
+ * Best-effort by design — the mirror is a diagnostics side-channel on the
+ * agent-write ingress path, so a mirror failure must never break the MCP
+ * server or its host-visible stderr. Every write swallows errors, and after
+ * a run of consecutive failures the mirror disables itself for the rest of
+ * the process to avoid pointless syscall churn on an unwritable disk. This
+ * swallow-everything posture is sanctioned HERE only; application write
+ * paths must surface their failures.
+ *
+ * Each mirrored chunk is prefixed with an ISO timestamp (the host adds its
+ * own timestamps to stderr; the raw lines carry none). The stderr bytes the
+ * host sees are untouched — the caller writes them separately.
+ */
+
+import { appendFileSync, mkdirSync, readdirSync, statSync, unlinkSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+
+/** Matches the desktop logger's retention window for `~/.ok/logs`. */
+const MAX_AGE_DAYS = 7;
+/** Aggregate cap across mirror files — matches the desktop logger's dir cap. */
+const MAX_TOTAL_BYTES = 45 * 1024 * 1024;
+/** Consecutive write failures before the mirror disables itself. */
+const MAX_CONSECUTIVE_FAILURES = 5;
+
+const MIRROR_FILE_PATTERN = /^mcp\.\d{4}-\d{2}-\d{2}\.log$/;
+
+function defaultMcpLogsDir(): string {
+ return join(homedir(), '.ok', 'logs');
+}
+
+/**
+ * Retention sweep over the mirror's own files only (`mcp.<date>.log`) —
+ * never the desktop's files in the same directory, which the desktop prunes
+ * itself. Age pass first, then oldest-first deletion until the aggregate
+ * size fits the cap. Fully best-effort.
+ */
+export function pruneMirrorLogs(logsDir: string, now: () => Date = () => new Date()): void {
+ try {
+ const nowMs = now().getTime();
+ const maxAgeMs = MAX_AGE_DAYS * 24 * 60 * 60 * 1000;
+ const files = readdirSync(logsDir)
+ .filter((f) => MIRROR_FILE_PATTERN.test(f))
+ .flatMap((f) => {
+ try {
+ const stat = statSync(join(logsDir, f));
+ return [{ name: f, mtime: stat.mtimeMs, size: stat.size }];
+ } catch {
+ return [];
+ }
+ });
+
+ const remaining: { name: string; mtime: number; size: number }[] = [];
+ for (const f of files) {
+ if (nowMs - f.mtime > maxAgeMs) {
+ try {
+ unlinkSync(join(logsDir, f.name));
+ } catch {
+ // Already gone or unwritable — retention is advisory.
+ }
+ } else {
+ remaining.push(f);
+ }
+ }
+
+ remaining.sort((a, b) => a.mtime - b.mtime);
+ let totalSize = remaining.reduce((sum, f) => sum + f.size, 0);
+ for (const f of remaining) {
+ if (totalSize <= MAX_TOTAL_BYTES) break;
+ try {
+ unlinkSync(join(logsDir, f.name));
+ totalSize -= f.size;
+ } catch {
+ // Same as above.
+ }
+ }
+ } catch {
+ // Missing dir / permission problem — nothing to prune.
+ }
+}
+
+export interface McpStderrMirror {
+ /** Append `chunk` (already newline-terminated by callers) to today's mirror file. */
+ write: (chunk: string) => void;
+}
+
+export interface CreateMcpStderrMirrorOpts {
+ /** Override the mirror directory (tests). Defaults to `~/.ok/logs`. */
+ logsDir?: string;
+ /** Clock override (tests). Drives both the filename date and retention. */
+ now?: () => Date;
+ /**
+ * Delay before the startup retention sweep. Defaults to 5s (matching the
+ * desktop logger's deferred prune); tests pass 0 to run it inline.
+ */
+ pruneDelayMs?: number;
+}
+
+export function createMcpStderrMirror(opts: CreateMcpStderrMirrorOpts = {}): McpStderrMirror {
+ const logsDir = opts.logsDir ?? defaultMcpLogsDir();
+ const now = opts.now ?? (() => new Date());
+ const pruneDelayMs = opts.pruneDelayMs ?? 5000;
+
+ if (pruneDelayMs <= 0) {
+ pruneMirrorLogs(logsDir, now);
+ } else {
+ // unref so the pending sweep never keeps a shutting-down process alive.
+ const timer = setTimeout(() => pruneMirrorLogs(logsDir, now), pruneDelayMs);
+ timer.unref?.();
+ }
+
+ let consecutiveFailures = 0;
+ let dirEnsured = false;
+ return {
+ write(chunk: string): void {
+ if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) return;
+ try {
+ if (!dirEnsured) {
+ mkdirSync(logsDir, { recursive: true });
+ dirEnsured = true;
+ }
+ const timestamp = now().toISOString();
+ // Date resolved per write, not at creation: the stdio process can
+ // outlive its start date by days, and the date suffix IS the
+ // rotation mechanism.
+ const file = join(logsDir, `mcp.${timestamp.slice(0, 10)}.log`);
+ appendFileSync(file, `${timestamp} ${chunk}`);
+ consecutiveFailures = 0;
+ } catch {
+ // Re-ensure the dir on the next write: this is a process-lifetime
+ // object (an MCP stdio session can run for days), so the logs dir can
+ // be removed out from under it mid-session. Without clearing the flag
+ // one external `rm -rf ~/.ok/logs` would permanently disable the
+ // mirror after MAX_CONSECUTIVE_FAILURES even though a single mkdirSync
+ // retry restores it — same recovery posture as the desktop logger.
+ dirEnsured = false;
+ consecutiveFailures++;
+ }
+ },
+ };
+}
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index 8f9d95287..c014b1413 100644
--- a/packages/core/src/bridge/bind-frontmatter-doc.ts
+++ b/packages/core/src/bridge/bind-frontmatter-doc.ts
@@ -1,4 +1,3 @@
-
import type * as Y from 'yjs';
import type { Err, Ok, Result } from '../config/result.ts';
import { type FrontmatterValidationError, toFrontmatterIssue } from '../frontmatter/errors.ts';
diff --git a/packages/core/src/bridge/bridge-invariant.ts b/packages/core/src/bridge/bridge-invariant.ts
index 8bfdb40cd..005627195 100644
--- a/packages/core/src/bridge/bridge-invariant.ts
+++ b/packages/core/src/bridge/bridge-invariant.ts
@@ -1,4 +1,3 @@
-
import { fnv1aDigest } from './hash-util.ts';
export type BridgeInvariantSite = 'observer-b' | 'persistence' | 'test-harness';
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index c18c086d5..8890f6739 100644
--- a/packages/core/src/bridge/doc-boundary-space.ts
+++ b/packages/core/src/bridge/doc-boundary-space.ts
@@ -1,4 +1,3 @@
-
import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';
const LEADING_BOUNDARY_RE = /^(?:\r?\n)+/;
diff --git a/packages/core/src/bridge/growth-detect.ts b/packages/core/src/bridge/growth-detect.ts
index 463e89595..9d9c244b0 100644
--- a/packages/core/src/bridge/growth-detect.ts
+++ b/packages/core/src/bridge/growth-detect.ts
@@ -1,4 +1,3 @@
-
const DEFAULT_MIN_SUBSTANTIVE_LINE_LENGTH = 16;
export const DUPLICATION_GATE_MIN_LINE_LENGTH = 8;
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index 3c927eb47..3ab9cc6ef 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -38,7 +38,6 @@ function mergeThreeWayImpl(baseline: string, userText: string, agentText: string
return parts.join('\n');
}
-
export type BridgeMergeContentLossSide = 'user' | 'agent';
export type BridgeMergeContentLossWhich = 'substring' | 'order' | 'growth';
diff --git a/packages/core/src/bridge/normalize.ts b/packages/core/src/bridge/normalize.ts
index 3f0880aa5..4b8890476 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
const COMMONMARK_ESCAPE_RE = /\\([!"#$%&'()*+,\-./:;<=>?@[\]^_`{|}~])/g;
const TABLE_ALIGN_ROW_RE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)+\|?\s*$/;
diff --git a/packages/core/src/bridge/pm-structural-equivalence.ts b/packages/core/src/bridge/pm-structural-equivalence.ts
index 0be5203e4..754dc5cc2 100644
--- a/packages/core/src/bridge/pm-structural-equivalence.ts
+++ b/packages/core/src/bridge/pm-structural-equivalence.ts
@@ -32,7 +32,6 @@ const BR_SENTINEL: PmStructuralNode = { type: '__br__' };
const BR_LITERAL_RE = /^<br\s*\/?>$/i;
-
interface DegradeEntry {
readonly label: string;
readonly severity: ToleranceClassSeverity;
@@ -128,7 +127,6 @@ export interface ComparePmStructuralOptions {
ignoreAttrs?: (attrKey: string) => boolean;
}
-
/** Rebuild a node with `fn` applied to each child; identity when childless.
* Shared by the degrade canonicalizers so none re-implements the walk. */
function mapChildren(
@@ -250,7 +248,6 @@ function applyDegrades(tree: PmStructuralNode): {
return { normalized: current, fired };
}
-
export function comparePmStructural(
expected: PmStructuralNode,
actual: PmStructuralNode,
diff --git a/packages/core/src/bridge/subsequence.ts b/packages/core/src/bridge/subsequence.ts
index dca644141..af20de1e2 100644
--- a/packages/core/src/bridge/subsequence.ts
+++ b/packages/core/src/bridge/subsequence.ts
@@ -1,4 +1,3 @@
-
/** True when `needle` is a subsequence of `haystack` (two-pointer, O(n+m)):
* insertions in `haystack` are free; any dropped or substituted `needle` byte
* fails. */
diff --git a/packages/core/src/constants/lifecycle.ts b/packages/core/src/constants/lifecycle.ts
index 21c90b625..859688180 100644
--- a/packages/core/src/constants/lifecycle.ts
+++ b/packages/core/src/constants/lifecycle.ts
@@ -53,3 +53,18 @@ export const SPAWN_ERROR_LOG = 'last-spawn-error.log';
* probe only reports "unreachable" either way.
*/
export const SERVER_EXIT_LOG = 'last-server-exit.json';
+
+/**
+ * Filename under `<projectRoot>/.ok/local/` where the server process itself
+ * records a fatal crash (uncaught exception / unhandled rejection) on its way
+ * down — timestamp, error name/message/stack, pid, uptime. Written by the
+ * server's crash-capture monitor (`packages/server/src/crash-capture.ts`)
+ * with synchronous fs so the record survives the hard exit that loses the
+ * async log sink's unwritten tail. Collected into bug-report bundles beside
+ * `SERVER_EXIT_LOG`.
+ *
+ * Complements `SERVER_EXIT_LOG`: the desktop host records *that* the child
+ * died (exit code + reason) from the outside; this file records *why* from
+ * the inside — the stack no other artifact reliably captures.
+ */
+export const SERVER_CRASH_LOG = 'last-server-crash.json';
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 8dcdcde9e..c1f76c352 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1177,6 +1177,7 @@ export {
export {
DEFAULT_SIGTERM_GRACE_MS,
DEFAULT_SIGTERM_POLL_MS,
+ SERVER_CRASH_LOG,
SERVER_EXIT_LOG,
SPAWN_ERROR_LOG,
} from './constants/lifecycle.ts';
diff --git a/packages/core/src/markdown/callout-transformer.ts b/packages/core/src/markdown/callout-transformer.ts
index a363dfd54..83d47404a 100644
--- a/packages/core/src/markdown/callout-transformer.ts
+++ b/packages/core/src/markdown/callout-transformer.ts
@@ -1,4 +1,3 @@
-
import type { Blockquote, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 47f0d07e4..193e286b0 100644
--- a/packages/core/src/markdown/comment-promoter.ts
+++ b/packages/core/src/markdown/comment-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/dedent-block-jsx-close.ts b/packages/core/src/markdown/dedent-block-jsx-close.ts
index b6299a948..ece5c02a1 100644
--- a/packages/core/src/markdown/dedent-block-jsx-close.ts
+++ b/packages/core/src/markdown/dedent-block-jsx-close.ts
@@ -1,4 +1,3 @@
-
import { findFencedRegions, isInsideFence } from './fence-regions.ts';
const INDENTED_BLOCK_JSX_CLOSE_RE = /^([ ]{1,3})(<\/[A-Z][A-Za-z0-9_]*\s*>)([ \t]*)$/gm;
diff --git a/packages/core/src/markdown/details-accordion-promoter.ts b/packages/core/src/markdown/details-accordion-promoter.ts
index acd398aa6..54774764a 100644
--- a/packages/core/src/markdown/details-accordion-promoter.ts
+++ b/packages/core/src/markdown/details-accordion-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/fence-regions.ts b/packages/core/src/markdown/fence-regions.ts
index fb5ac8e8a..c7518d614 100644
--- a/packages/core/src/markdown/fence-regions.ts
+++ b/packages/core/src/markdown/fence-regions.ts
@@ -1,4 +1,3 @@
-
const FENCE_RE = /^(`{3,}|~{3,})/gm;
export function findFencedRegions(src: string): Array<[number, number]> {
diff --git a/packages/core/src/markdown/fixtures/index.ts b/packages/core/src/markdown/fixtures/index.ts
index 6931623c7..00f5771ee 100644
--- a/packages/core/src/markdown/fixtures/index.ts
+++ b/packages/core/src/markdown/fixtures/index.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -9,7 +8,6 @@ function fixturePath(...segments: string[]): string {
return resolve(FIXTURES_DIR, ...segments);
}
-
interface GfmExample {
section: string;
markdown: string;
@@ -19,7 +17,6 @@ export function loadGfmExamples(): GfmExample[] {
return JSON.parse(readFileSync(fixturePath('gfm', 'examples.json'), 'utf8')) as GfmExample[];
}
-
interface MdxCrashEntry {
id: string;
input: string;
@@ -71,7 +68,6 @@ export function loadLargeEmbedFixtures(): LargeEmbedFixture[] {
) as LargeEmbedFixture[];
}
-
export function loadPrd6955Before(): string {
return readFileSync(fixturePath('regression', 'prd-6955-before.md'), 'utf8');
}
@@ -80,7 +76,6 @@ export function loadPrd6955CorruptedTriplicated(): string {
return readFileSync(fixturePath('regression', 'prd-6955-corrupted-triplicated.md'), 'utf8');
}
-
export interface NgPinnedCase {
id: string;
name: string;
@@ -97,7 +92,6 @@ export function loadNgPinnedCases(): NgPinnedCase[] {
) as NgPinnedCase[];
}
-
export function loadLargeRealistic(): string {
return readFileSync(fixturePath('perf', 'large-realistic.md'), 'utf8');
}
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index daa3ef82b..8b1eb8519 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -11,7 +10,6 @@ const BASELINE_ONLY_COUNTS = [500, 2500] as const;
const SEED = 0xf1de1117;
-
function mulberry32(seed: number): () => number {
let a = seed >>> 0;
return () => {
@@ -38,7 +36,6 @@ function pickWeighted<T>(rand: () => number, items: readonly [T, number][]): T {
return items[items.length - 1][0];
}
-
const WORDS = [
'lorem',
'ipsum',
@@ -156,7 +153,6 @@ function mdxBlock(rand: () => number): string {
return `<${name}>\n\n${sentence(rand)}\n\n</${name}>`;
}
-
type BlockKind = 'paragraph' | 'heading' | 'list' | 'code' | 'table' | 'mdx';
const MIX: readonly [BlockKind, number][] = [
@@ -195,7 +191,6 @@ function generateDocument(blockCount: number, seed: number): string {
return `${blocks.join('\n\n')}\n`;
}
-
function main(): void {
for (const count of [...BLOCK_COUNTS, ...BASELINE_ONLY_COUNTS]) {
const doc = generateDocument(count, SEED);
diff --git a/packages/core/src/markdown/guard-flanking-matrix.ts b/packages/core/src/markdown/guard-flanking-matrix.ts
index 32c055c5b..420dc0fe5 100644
--- a/packages/core/src/markdown/guard-flanking-matrix.ts
+++ b/packages/core/src/markdown/guard-flanking-matrix.ts
@@ -7,7 +7,6 @@ import {
import { BACKSLASH_GUARD_SUBSTITUTIONS, encodeBackslashEscapes } from './backslash-escape-guard.ts';
import { ENTITY_REF_GUARD_SUBSTITUTIONS, encodeEntityRefs } from './entity-ref-guard.ts';
-
export const ATTENTION_DELIMITERS = ['*', '_', '**', '~~', '=='] as const;
export type FlankClass = 'whitespace' | 'punctuation' | 'other';
diff --git a/packages/core/src/markdown/handler-shadow-audit.ts b/packages/core/src/markdown/handler-shadow-audit.ts
index 283913255..2653473da 100644
--- a/packages/core/src/markdown/handler-shadow-audit.ts
+++ b/packages/core/src/markdown/handler-shadow-audit.ts
@@ -1,4 +1,3 @@
-
export interface HandlerShadowWitness {
input: string;
expect: 'byte' | 'byte-and-reparse-type';
diff --git a/packages/core/src/markdown/highlight-promoter.ts b/packages/core/src/markdown/highlight-promoter.ts
index 6319f264f..f55912407 100644
--- a/packages/core/src/markdown/highlight-promoter.ts
+++ b/packages/core/src/markdown/highlight-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, PhrasingContent, Root, Text } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/html-to-mdast.ts b/packages/core/src/markdown/html-to-mdast.ts
index 2f082e6d0..78fdfeb02 100644
--- a/packages/core/src/markdown/html-to-mdast.ts
+++ b/packages/core/src/markdown/html-to-mdast.ts
@@ -1,4 +1,3 @@
-
import type { Root as HastRoot } from 'hast';
import type { Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -76,8 +75,7 @@ export function htmlToMdast(html: string, options?: HtmlToMdastOptions): MdastRo
throw new HtmlPayloadTooLargeError(html.length, maxBytes);
}
- const processor = unified()
- .use(rehypeParse, { fragment: true });
+ const processor = unified().use(rehypeParse, { fragment: true });
for (const plugin of cleanupPlugins) {
processor.use(plugin);
diff --git a/packages/core/src/markdown/image-promoter.ts b/packages/core/src/markdown/image-promoter.ts
index 994eb6917..706fa9afb 100644
--- a/packages/core/src/markdown/image-promoter.ts
+++ b/packages/core/src/markdown/image-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Image, Paragraph, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/index.ts b/packages/core/src/markdown/index.ts
index fc30bda02..8b36807fd 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -197,7 +196,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -246,7 +244,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -266,7 +263,6 @@ function effectiveDirty(node: PmNode, freshnessChecker?: StructuralFreshnessChec
return freshnessChecker ? freshnessChecker.isDiverged(node.toJSON()) : false;
}
-
function isEmptyMdastParagraph(node: MdastNodes): boolean {
if (node.type !== 'paragraph') return false;
const children = node.children ?? [];
@@ -335,7 +331,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -582,7 +577,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -663,7 +657,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -942,7 +935,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1068,7 +1060,6 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
-
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index 207cd95c2..e78a1381d 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -29,7 +29,6 @@ const fullPluginShape = Object.fromEntries(
LINT_PLUGINS.map((plugin) => [plugin.id, plugin.sliceSchema]),
) as z.ZodRawShape;
-
export const LinterConfigSchema = z.object({
enabled: z.boolean(),
plugins: z.object(fullPluginShape),
diff --git a/packages/core/src/markdown/lint/default-config.ts b/packages/core/src/markdown/lint/default-config.ts
index a51f2ffb0..d48eea5e4 100644
--- a/packages/core/src/markdown/lint/default-config.ts
+++ b/packages/core/src/markdown/lint/default-config.ts
@@ -6,7 +6,6 @@ export const DEFAULT_MARKDOWNLINT_CONFIG: Record<string, MarkdownlintRuleSetting
MD013: false,
};
-
export function resolveMarkdownlintConfig(
rules: Record<string, MarkdownlintRuleSetting> | undefined,
): Configuration {
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index 3baacdeb7..d1a5ab4dc 100644
--- a/packages/core/src/markdown/lint/index.ts
+++ b/packages/core/src/markdown/lint/index.ts
@@ -1,4 +1,3 @@
-
import { LINT_PLUGINS, type LinterConfig } from './plugins.ts';
import type { LintDiagnostic } from './types.ts';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 65a1b564c..1cd40ef3a 100644
--- a/packages/core/src/markdown/lint/plugins.ts
+++ b/packages/core/src/markdown/lint/plugins.ts
@@ -1,4 +1,3 @@
-
import { z } from 'zod';
import { DEFAULT_MARKDOWNLINT_CONFIG, resolveMarkdownlintConfig } from './default-config.ts';
import { fixMarkdownText, runMarkdownlint } from './markdownlint-runner.ts';
@@ -9,7 +8,6 @@ import {
type MarkdownlintSlice,
} from './types.ts';
-
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index 3651bd7eb..617f6e5b9 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,4 +1,3 @@
-
export const LINT_PLUGIN_IDS = ['markdownlint'] as const;
export type LintPluginId = (typeof LINT_PLUGIN_IDS)[number];
@@ -42,7 +41,6 @@ export interface MarkdownlintSlice {
rules: Record<string, MarkdownlintRuleSetting>;
}
-
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/math-promoter.ts b/packages/core/src/markdown/math-promoter.ts
index bd79424c7..a5b511f25 100644
--- a/packages/core/src/markdown/math-promoter.ts
+++ b/packages/core/src/markdown/math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { Math as MdastMath } from 'mdast-util-math';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-hast-handlers.ts b/packages/core/src/markdown/mdast-to-hast-handlers.ts
index f84967798..679c72ef7 100644
--- a/packages/core/src/markdown/mdast-to-hast-handlers.ts
+++ b/packages/core/src/markdown/mdast-to-hast-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Properties } from 'hast';
import type { FootnoteDefinition, FootnoteReference } from 'mdast';
import type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx';
diff --git a/packages/core/src/markdown/mdast-to-html.ts b/packages/core/src/markdown/mdast-to-html.ts
index df788a80d..8ce2b2492 100644
--- a/packages/core/src/markdown/mdast-to-html.ts
+++ b/packages/core/src/markdown/mdast-to-html.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root as HastRoot, Text as HastText } from 'hast';
import type { Root as MdastRoot, Text as MdastText } from 'mdast';
import type { Handler } from 'mdast-util-to-hast';
diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.ts
index fa3cfcd86..bfd7e3109 100644
--- a/packages/core/src/markdown/merged-walker.ts
+++ b/packages/core/src/markdown/merged-walker.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import { SKIP, visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/mermaid-promoter.ts b/packages/core/src/markdown/mermaid-promoter.ts
index 17ed2b829..1a897fca8 100644
--- a/packages/core/src/markdown/mermaid-promoter.ts
+++ b/packages/core/src/markdown/mermaid-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Code, Root } from 'mdast';
import type { MdxJsxAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/parse-with-fallback.ts b/packages/core/src/markdown/parse-with-fallback.ts
index 7e4a9a48b..9864b3b60 100644
--- a/packages/core/src/markdown/parse-with-fallback.ts
+++ b/packages/core/src/markdown/parse-with-fallback.ts
@@ -168,7 +168,6 @@ export function parseRecursive(
}
}
-
interface VFilePlace {
offset?: number;
start?: { offset?: number };
@@ -187,7 +186,6 @@ function extractErrorOffset(err: unknown): number | undefined {
return undefined;
}
-
interface Region {
start: number;
end: number;
@@ -211,7 +209,6 @@ function nearestBlankLineAfter(src: string, offset: number): number | null {
return null;
}
-
export interface TagEvent {
kind: 'open' | 'close' | 'self-close';
name: string;
@@ -358,7 +355,6 @@ function findFallbackRegion(src: string, errorOffset: number): Region {
return { start: blockStart, end: blockEnd };
}
-
interface SourceBlock {
src: string;
start: number;
@@ -456,7 +452,6 @@ function tryPerBlockFallback(
};
}
-
function wholeDocRawText(source: string): JSONContent {
return {
type: 'doc',
diff --git a/packages/core/src/markdown/parser-drop-closure.ts b/packages/core/src/markdown/parser-drop-closure.ts
index 43d420187..e6ab4fd57 100644
--- a/packages/core/src/markdown/parser-drop-closure.ts
+++ b/packages/core/src/markdown/parser-drop-closure.ts
@@ -1,4 +1,3 @@
-
export type DroppedTokenAdjudication =
| {
kind: 'format-dof-axis';
diff --git a/packages/core/src/markdown/pipeline.ts b/packages/core/src/markdown/pipeline.ts
index e9e507469..7f2d5adca 100644
--- a/packages/core/src/markdown/pipeline.ts
+++ b/packages/core/src/markdown/pipeline.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromProseMirror,
diff --git a/packages/core/src/markdown/position-aware-join.ts b/packages/core/src/markdown/position-aware-join.ts
index f8f5e8530..5a5e4c42a 100644
--- a/packages/core/src/markdown/position-aware-join.ts
+++ b/packages/core/src/markdown/position-aware-join.ts
@@ -1,4 +1,3 @@
-
import type { Join } from 'mdast-util-to-markdown';
import type { Position } from 'unist';
diff --git a/packages/core/src/markdown/position-slice.ts b/packages/core/src/markdown/position-slice.ts
index e5b4c9eba..0f399d34c 100644
--- a/packages/core/src/markdown/position-slice.ts
+++ b/packages/core/src/markdown/position-slice.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Root } from 'mdast';
import { visit } from 'unist-util-visit';
import type { VFile } from 'vfile';
@@ -477,8 +476,7 @@ export function applyPositionSliceToNode(
const first = source[startOff];
if (first !== '[' && first !== '<' && !node.title) {
node.data.sourceStyle = 'gfm-autolink';
- }
- else if (first === '[') {
+ } else if (first === '[') {
const slice = source.slice(startOff, endOff);
const closeBracketIdx = slice.lastIndexOf('](');
if (closeBracketIdx !== -1) {
diff --git a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
index ca225ce9b..db10fa54b 100644
--- a/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
+++ b/packages/core/src/markdown/rehype-plugins/skip-notion-whitespace.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, Root, Text } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
index 3a2524a9a..34068d103 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-cocoa-meta.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
index 2279a0189..93151d43b 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gdocs-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
index a0f467c42..188f02d83 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-github-hovercard.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
index 4e8542a21..4ba2c3418 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gmail-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
index a3c96b24a..1a74b1272 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-gsheets-wrapper.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
index e95cf43d6..de35e7b79 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-mso-styles.ts
@@ -1,4 +1,3 @@
-
import type { Comment, Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
index ffdb4d5b5..b4be1b2ea 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-slack-classes.ts
@@ -1,4 +1,3 @@
-
import type { Element, ElementContent, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
index e2a96d1a7..3c8d88b7c 100644
--- a/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
+++ b/packages/core/src/markdown/rehype-plugins/strip-vscode-spans.ts
@@ -1,4 +1,3 @@
-
import type { Element, Root } from 'hast';
import type { Plugin } from 'unified';
diff --git a/packages/core/src/markdown/resolve-image-url.ts b/packages/core/src/markdown/resolve-image-url.ts
index 0389575ac..cf2c9da8e 100644
--- a/packages/core/src/markdown/resolve-image-url.ts
+++ b/packages/core/src/markdown/resolve-image-url.ts
@@ -1,4 +1,3 @@
-
import { isRelativeUrl } from './safe-url.ts';
function isDevDiagnosticContext(): boolean {
diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.ts
index 8be632ba4..4d3250d3a 100644
--- a/packages/core/src/markdown/safe-url.ts
+++ b/packages/core/src/markdown/safe-url.ts
@@ -1,4 +1,3 @@
-
export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;
const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 542204403..46cc6a074 100644
--- a/packages/core/src/markdown/serialize-helpers.ts
+++ b/packages/core/src/markdown/serialize-helpers.ts
@@ -1,4 +1,3 @@
-
import type { Node as PmNode } from '@tiptap/pm/model';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { PropDef, SerializeContext } from '../registry/types.ts';
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index fe73659e6..be97d4d62 100644
--- a/packages/core/src/markdown/single-dollar-math-promoter.ts
+++ b/packages/core/src/markdown/single-dollar-math-promoter.ts
@@ -1,4 +1,3 @@
-
import type { PhrasingContent, Root, Text } from 'mdast';
import type { InlineMath } from 'mdast-util-math';
import { SKIP, visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/to-markdown-handlers.ts b/packages/core/src/markdown/to-markdown-handlers.ts
index 7bce04302..8f4e9a41c 100644
--- a/packages/core/src/markdown/to-markdown-handlers.ts
+++ b/packages/core/src/markdown/to-markdown-handlers.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parents } from 'mdast';
import type { MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement } from 'mdast-util-mdx';
import type { Handle, Info, State } from 'mdast-util-to-markdown';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index c5bfd2386..cd245c38c 100644
--- a/packages/core/src/markdown/unknown-mdast-guard.ts
+++ b/packages/core/src/markdown/unknown-mdast-guard.ts
@@ -1,4 +1,3 @@
-
import type { Root as MdastRoot } from 'mdast';
import type { VFile } from 'vfile';
diff --git a/packages/core/src/markdown/whitespace-char-ref.ts b/packages/core/src/markdown/whitespace-char-ref.ts
index ac9f5239b..d578476a7 100644
--- a/packages/core/src/markdown/whitespace-char-ref.ts
+++ b/packages/core/src/markdown/whitespace-char-ref.ts
@@ -1,4 +1,3 @@
-
const INLINE_WHITESPACE_BY_CODE: ReadonlyMap<number, string> = new Map([
[0x20, ' '],
[0x09, '\t'],
diff --git a/packages/core/src/markdown/wiki-link-micromark.ts b/packages/core/src/markdown/wiki-link-micromark.ts
index afd9936fe..6dad26200 100644
--- a/packages/core/src/markdown/wiki-link-micromark.ts
+++ b/packages/core/src/markdown/wiki-link-micromark.ts
@@ -17,7 +17,6 @@ declare module 'micromark-util-types' {
}
}
-
const CODE_BANG = 33; // !
const CODE_LBRACKET = 91; // [
const CODE_RBRACKET = 93; // ]
@@ -261,7 +260,6 @@ export function wikiLinkSyntax(): Extension {
};
}
-
function enterWikiLink(this: CompileContext, token: Token) {
this.enter(
{
@@ -387,7 +385,6 @@ export const wikiLinkToMarkdown: {
unsafe: [{ character: '[', inConstruct: ['phrasing'] }],
};
-
const MICROMARK_EXT = wikiLinkSyntax();
export function remarkWikiLink(this: Processor) {
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index 28114d2da..753b387a3 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -41,6 +41,7 @@ import { createAssetServeMiddleware } from './asset-serve-middleware.ts';
import { bootElapsedMs, recordBootPhase, startBootTimings } from './boot-timings.ts';
import type { Config } from './config/schema.ts';
import { ConflictStore } from './conflict-storage.ts';
+import { installCrashCapture } from './crash-capture.ts';
import { stripDocExtension } from './doc-extensions.ts';
import { normalizeFsPath } from './fs-traced.ts';
import { listNames } from './git-paths.ts';
@@ -458,28 +459,57 @@ export async function bootServer(opts: BootServerOptions): Promise<BootedServer>
// (CLI `ok start`, tests, push-disabled), `ok.boot` stays a root span exactly
// as before. The propagator is registered by `initTelemetry` above; when OTel
// is disabled the extract is a cheap no-op over a no-op tracer.
+ // Arm fatal-crash capture before the boot sequence proper: an uncaught
+ // exception anywhere from here on (boot phase or steady state) leaves a
+ // synchronous `last-server-crash.json` + log-sink line behind. Observe-only —
+ // Node's default crash handling (stderr stack, non-zero exit) is untouched.
+ const crashCapture = installCrashCapture(sinkProjectDir);
+
const startupTraceparent = process.env.OK_STARTUP_TRACEPARENT;
const bootSpan = () =>
withSpan('ok.boot', { attributes: spanAttributes }, async () => bootServerInner(opts));
- if (startupTraceparent) {
- try {
- const parentCtx = propagation.extract(context.active(), { traceparent: startupTraceparent });
- return context.with(parentCtx, bootSpan);
- } catch (err) {
- // A malformed `OK_STARTUP_TRACEPARENT` must never break boot. The
- // registered W3C propagator degrades to an unparented context rather than
- // throwing, so this catch is belt-and-suspenders for a future non-standard
- // propagator — fall through to the unparented boot exactly as the
- // no-env-var path does. Warn so that disconnect is diagnosable: the
- // server's `ok.boot` would otherwise become a detached root in Tempo with
- // nothing in the logs to correlate against the missing join.
- getLogger('boot').warn(
- { err: err instanceof Error ? err.message : String(err) },
- 'ok.boot trace-join failed — starting unparented boot',
- );
+ const runBoot = (): Promise<BootedServer> => {
+ if (startupTraceparent) {
+ try {
+ const parentCtx = propagation.extract(context.active(), {
+ traceparent: startupTraceparent,
+ });
+ return context.with(parentCtx, bootSpan);
+ } catch (err) {
+ // A malformed `OK_STARTUP_TRACEPARENT` must never break boot. The
+ // registered W3C propagator degrades to an unparented context rather than
+ // throwing, so this catch is belt-and-suspenders for a future non-standard
+ // propagator — fall through to the unparented boot exactly as the
+ // no-env-var path does. Warn so that disconnect is diagnosable: the
+ // server's `ok.boot` would otherwise become a detached root in Tempo with
+ // nothing in the logs to correlate against the missing join.
+ getLogger('boot').warn(
+ { err: err instanceof Error ? err.message : String(err) },
+ 'ok.boot trace-join failed — starting unparented boot',
+ );
+ }
}
+ return bootSpan();
+ };
+ let booted: BootedServer;
+ try {
+ booted = await runBoot();
+ } catch (err) {
+ // Boot refused (config missing, lock collision, git preflight): the
+ // caller decides the exit path, so detach rather than leave a dead
+ // registry entry behind (tests boot-fail repeatedly in one process).
+ crashCapture.uninstall();
+ throw err;
}
- return bootSpan();
+ const innerDestroy = booted.destroy;
+ booted.destroy = async () => {
+ try {
+ await innerDestroy();
+ } finally {
+ crashCapture.uninstall();
+ }
+ };
+ return booted;
}
async function bootServerInner(opts: BootServerOptions): Promise<BootedServer> {
diff --git a/packages/server/src/crash-capture.test.ts b/packages/server/src/crash-capture.test.ts
new file mode 100644
index 000000000..b2baa9560
--- /dev/null
+++ b/packages/server/src/crash-capture.test.ts
@@ -0,0 +1,157 @@
+import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { mkdtemp, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { SERVER_CRASH_LOG } from '@inkeep/open-knowledge-core';
+import {
+ buildCrashRecord,
+ type CrashCaptureHandle,
+ installCrashCapture,
+ writeCrashArtifacts,
+} from './crash-capture.ts';
+
+let projectDir: string;
+const handles: CrashCaptureHandle[] = [];
+
+beforeEach(async () => {
+ projectDir = await mkdtemp(join(tmpdir(), 'ok-crash-capture-'));
+});
+
+afterEach(async () => {
+ for (const handle of handles.splice(0)) handle.uninstall();
+ await rm(projectDir, { recursive: true, force: true });
+});
+
+function emitMonitor(err: unknown, origin: string): void {
+ // Manual emit runs the registered monitor listeners without crashing the
+ // test process — the observe-only contract means no listener can alter
+ // control flow, so this exercises the production wiring end to end.
+ (process as unknown as NodeJS.EventEmitter).emit('uncaughtExceptionMonitor', err, origin);
+}
+
+const crashJsonPath = () => join(projectDir, '.ok', 'local', SERVER_CRASH_LOG);
+const logsPath = () => join(projectDir, '.ok', 'local', 'logs', 'server-current.jsonl');
+
+describe('buildCrashRecord', () => {
+ test('captures name, message, stack, pid, uptime from an Error', () => {
+ const record = buildCrashRecord(new TypeError('boom'), 'uncaughtException');
+ expect(record.origin).toBe('uncaughtException');
+ expect(record.error.name).toBe('TypeError');
+ expect(record.error.message).toBe('boom');
+ expect(record.error.stack).toContain('boom');
+ expect(record.pid).toBe(process.pid);
+ expect(record.uptimeSec).toBeGreaterThan(0);
+ expect(Number.isNaN(Date.parse(record.timestamp))).toBe(false);
+ });
+
+ test('normalizes a non-Error throw', () => {
+ const record = buildCrashRecord('plain string reason', 'unhandledRejection');
+ expect(record.origin).toBe('unhandledRejection');
+ expect(record.error.name).toBe('NonError');
+ expect(record.error.message).toBe('plain string reason');
+ expect(record.error.stack).toBeNull();
+ });
+});
+
+describe('writeCrashArtifacts', () => {
+ test('writes last-server-crash.json and appends a fatal JSONL line to the log sink', () => {
+ const record = buildCrashRecord(new Error('kaput'), 'uncaughtException');
+ writeCrashArtifacts(projectDir, record);
+
+ const crashJson = JSON.parse(readFileSync(crashJsonPath(), 'utf-8'));
+ expect(crashJson.error.message).toBe('kaput');
+ expect(crashJson.pid).toBe(process.pid);
+
+ const lines = readFileSync(logsPath(), 'utf-8').trim().split('\n');
+ expect(lines).toHaveLength(1);
+ const logLine = JSON.parse(lines[0]);
+ expect(logLine.level).toBe(60);
+ expect(logLine.name).toBe('crash');
+ expect(logLine.err.message).toBe('kaput');
+ expect(logLine.msg).toContain('uncaughtException');
+ });
+
+ test('appends to an existing log sink file instead of truncating it', () => {
+ mkdirSync(join(projectDir, '.ok', 'local', 'logs'), { recursive: true });
+ writeFileSync(logsPath(), '{"level":30,"msg":"earlier"}\n');
+ writeCrashArtifacts(projectDir, buildCrashRecord(new Error('later'), 'uncaughtException'));
+ const lines = readFileSync(logsPath(), 'utf-8').trim().split('\n');
+ expect(lines).toHaveLength(2);
+ expect(lines[0]).toContain('earlier');
+ expect(JSON.parse(lines[1]).err.message).toBe('later');
+ });
+
+ test('last-server-crash.json holds only the latest crash while the JSONL sink accumulates every one', () => {
+ writeCrashArtifacts(projectDir, buildCrashRecord(new Error('root cause'), 'uncaughtException'));
+ writeCrashArtifacts(
+ projectDir,
+ buildCrashRecord(new Error('restart symptom'), 'uncaughtException'),
+ );
+
+ // The standalone record is latest-only (truncate write).
+ const crashJson = JSON.parse(readFileSync(crashJsonPath(), 'utf-8'));
+ expect(crashJson.error.message).toBe('restart symptom');
+
+ // The full crash timeline — including the root-cause crash — survives in
+ // the append-mode JSONL sink, which the bundle collects alongside it.
+ const messages = readFileSync(logsPath(), 'utf-8')
+ .trim()
+ .split('\n')
+ .map((l) => JSON.parse(l).err.message);
+ expect(messages).toEqual(['root cause', 'restart symptom']);
+ });
+
+ test('swallows write failures instead of throwing', () => {
+ // `.ok/local` as a regular file makes both artifact writes fail.
+ mkdirSync(join(projectDir, '.ok'), { recursive: true });
+ writeFileSync(join(projectDir, '.ok', 'local'), 'not a directory');
+ expect(() =>
+ writeCrashArtifacts(projectDir, buildCrashRecord(new Error('x'), 'uncaughtException')),
+ ).not.toThrow();
+ });
+});
+
+describe('installCrashCapture', () => {
+ test('monitor event writes artifacts for the registered project', () => {
+ handles.push(installCrashCapture(projectDir));
+ emitMonitor(new Error('monitored crash'), 'uncaughtException');
+ expect(existsSync(crashJsonPath())).toBe(true);
+ const record = JSON.parse(readFileSync(crashJsonPath(), 'utf-8'));
+ expect(record.error.message).toBe('monitored crash');
+ expect(existsSync(logsPath())).toBe(true);
+ });
+
+ test('records unhandled-rejection origin distinctly', () => {
+ handles.push(installCrashCapture(projectDir));
+ emitMonitor(new Error('rejected'), 'unhandledRejection');
+ const record = JSON.parse(readFileSync(crashJsonPath(), 'utf-8'));
+ expect(record.origin).toBe('unhandledRejection');
+ });
+
+ test('uninstall stops writes for that project', () => {
+ const handle = installCrashCapture(projectDir);
+ handle.uninstall();
+ emitMonitor(new Error('after uninstall'), 'uncaughtException');
+ expect(existsSync(crashJsonPath())).toBe(false);
+ });
+
+ test('refcounted: project stays registered until every install is uninstalled', () => {
+ const first = installCrashCapture(projectDir);
+ const second = installCrashCapture(projectDir);
+ first.uninstall();
+ emitMonitor(new Error('still armed'), 'uncaughtException');
+ expect(existsSync(crashJsonPath())).toBe(true);
+ second.uninstall();
+ });
+
+ test('uninstall is idempotent and does not over-decrement peers', () => {
+ const first = installCrashCapture(projectDir);
+ const second = installCrashCapture(projectDir);
+ handles.push(second);
+ first.uninstall();
+ first.uninstall();
+ emitMonitor(new Error('peer survives'), 'uncaughtException');
+ expect(existsSync(crashJsonPath())).toBe(true);
+ });
+});
diff --git a/packages/server/src/crash-capture.ts b/packages/server/src/crash-capture.ts
new file mode 100644
index 000000000..4c7b40bd1
--- /dev/null
+++ b/packages/server/src/crash-capture.ts
@@ -0,0 +1,146 @@
+/**
+ * Fatal-crash capture for the collab server process.
+ *
+ * A hard crash (uncaught exception, unhandled rejection under Node's default
+ * throw mode) loses the async pino file sink's unwritten tail, so the log
+ * files a bug-report bundle collects end at some arbitrary point BEFORE the
+ * error that killed the process — bundles can prove the server is not
+ * running but never why it died. This module closes that gap by writing two
+ * synchronous artifacts on the way down:
+ *
+ * 1. One structured JSONL line appended to the same
+ * `<projectDir>/.ok/local/logs/server-current.jsonl` the bundle
+ * collector already harvests (pino-compatible: `level: 60` = fatal).
+ * 2. `<projectDir>/.ok/local/last-server-crash.json` — a small standalone record
+ * (timestamp, origin, error name/message/stack, pid, uptime) staged
+ * into bundles beside `last-server-exit.json`.
+ *
+ * The hook is `process.on('uncaughtExceptionMonitor')` — observe-only by
+ * contract, running BEFORE Node's default crash handling without replacing
+ * it, so crash semantics (stderr stack + non-zero exit) are preserved
+ * exactly and the process can never be turned into a zombie by this module.
+ * Under Node's default `--unhandled-rejections=throw` mode the monitor also
+ * fires for unhandled rejections (with `origin: 'unhandledRejection'`), so a
+ * separate `unhandledRejection` listener — which WOULD suppress the default
+ * crash — is deliberately not registered. Same posture as the MCP stdio
+ * server's lifecycle breadcrumbs in the CLI package.
+ *
+ * One process-level listener serves every registered project (integration
+ * tests boot many servers per process; a listener per boot would trip Node's
+ * MaxListeners warning — same registry pattern as `process-lock.ts`'s exit
+ * unlink handler). Everything in the crash path is wrapped so a write
+ * failure can never itself perturb the dying process.
+ */
+
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { SERVER_CRASH_LOG } from '@inkeep/open-knowledge-core';
+import { getLocalDir } from './config/paths.ts';
+import { logsCurrentPath } from './telemetry-file-sink.ts';
+
+export interface CrashRecord {
+ timestamp: string;
+ /** `'uncaughtException'` or `'unhandledRejection'` (Node's monitor origin). */
+ origin: string;
+ error: { name: string; message: string; stack: string | null };
+ pid: number;
+ uptimeSec: number;
+}
+
+/** Normalize an arbitrary thrown value into the crash-record error shape. */
+export function buildCrashRecord(err: unknown, origin: string): CrashRecord {
+ const error =
+ err instanceof Error
+ ? { name: err.name, message: err.message, stack: err.stack ?? null }
+ : { name: 'NonError', message: String(err), stack: null };
+ return {
+ timestamp: new Date().toISOString(),
+ origin,
+ error,
+ pid: process.pid,
+ uptimeSec: Math.round(process.uptime() * 1000) / 1000,
+ };
+}
+
+/**
+ * Write both crash artifacts for one project. Each write is independently
+ * best-effort: raw synchronous `node:fs`, NOT the `fs-traced.ts` wrappers —
+ * this runs mid-crash, after the async OTel/pino pipeline can no longer be
+ * trusted to flush, and a traced write would emit a span into the dying SDK
+ * (same carve-out as `RotatingAppender`'s observability-sink writes).
+ */
+export function writeCrashArtifacts(projectDir: string, record: CrashRecord): void {
+ const localDir = getLocalDir(projectDir);
+ try {
+ mkdirSync(localDir, { recursive: true });
+ // Truncate-write, latest-crash-only by design. In a crash-restart loop
+ // this holds the most recent crash rather than the root-cause one, but the
+ // full timeline (every crash, root cause included) is preserved by the
+ // append-mode JSONL sink below — which the bundle collects too. Keeping
+ // this write a single atomic truncate avoids a read-parse-append-write on
+ // a possibly-half-written prior file while the process is already dying.
+ writeFileSync(join(localDir, SERVER_CRASH_LOG), `${JSON.stringify(record, null, 2)}\n`);
+ } catch {
+ // Nothing safe to do mid-crash; the other artifact may still land.
+ }
+ try {
+ const logsPath = logsCurrentPath(projectDir);
+ mkdirSync(dirname(logsPath), { recursive: true });
+ const line = {
+ level: 60,
+ time: Date.parse(record.timestamp),
+ name: 'crash',
+ origin: record.origin,
+ err: record.error,
+ pid: record.pid,
+ uptimeSec: record.uptimeSec,
+ msg: `fatal ${record.origin} — process crashing`,
+ };
+ writeFileSync(logsPath, `${JSON.stringify(line)}\n`, { flag: 'a' });
+ } catch {
+ // Best-effort only.
+ }
+}
+
+/** Refcounted registry of project dirs the single monitor listener serves. */
+const capturedProjectDirs = new Map<string, number>();
+let monitorRegistered = false;
+
+function onMonitor(err: unknown, origin: string): void {
+ try {
+ const record = buildCrashRecord(err, origin);
+ for (const projectDir of capturedProjectDirs.keys()) {
+ writeCrashArtifacts(projectDir, record);
+ }
+ } catch {
+ // A throwing monitor would itself trigger Node's default crash path
+ // before the original exception is handled — swallow unconditionally.
+ }
+}
+
+export interface CrashCaptureHandle {
+ uninstall: () => void;
+}
+
+/**
+ * Arm crash capture for `projectDir`. Returns a handle whose `uninstall`
+ * detaches this project from the registry (the shared process listener stays
+ * attached — it is a no-op with an empty registry).
+ */
+export function installCrashCapture(projectDir: string): CrashCaptureHandle {
+ capturedProjectDirs.set(projectDir, (capturedProjectDirs.get(projectDir) ?? 0) + 1);
+ if (!monitorRegistered) {
+ monitorRegistered = true;
+ process.on('uncaughtExceptionMonitor', onMonitor);
+ }
+ let uninstalled = false;
+ return {
+ uninstall: () => {
+ if (uninstalled) return;
+ uninstalled = true;
+ const count = capturedProjectDirs.get(projectDir) ?? 0;
+ if (count <= 1) capturedProjectDirs.delete(projectDir);
+ else capturedProjectDirs.set(projectDir, count - 1);
+ },
+ };
+}