Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

fix(ok): record the server's death in packaged builds (PRD-8235) (#3827)

Andrew Mikofalvy1d0b665d85f9
diff --git a/.changeset/packaged-server-exit-record.md b/.changeset/packaged-server-exit-record.md
new file mode 100644
index 000000000..2a0ec6dba
--- /dev/null
+++ b/.changeset/packaged-server-exit-record.md
@@ -0,0 +1,11 @@
+---
+"@inkeep/open-knowledge": patch
+---
+
+Bug reports filed from an installed desktop app now say how the background server died. The app has recorded that for a while, but only in development builds: installed builds start the server as an ordinary background process rather than as one of the app's own child processes, and the code that wrote the record was wired only to the second kind. Every bug report from an installed build was therefore missing the one file that answers "did the server crash, or was it shut down on purpose", which is the question the record exists to settle. It is now written on both paths.
+
+The record also names the signal that ended the process. A server killed outright leaves no exit code at all, so until now the death this feature was built for was the one it could not describe: the record looked the same as an exit for no stated reason. Records written by older versions simply have no signal in them, which reads as unknown rather than as "none".
+
+Two honest limits worth stating. Where the app can classify a death itself it still does, but an installed build cannot classify this kind of process, so that field is now recorded as empty rather than filled in with a classification belonging to some other part of the app. The record now says which of the two it was, so an empty classification can be read as "there was never one to have" instead of "we looked and found nothing". And the record only covers a server this session started; when the app reconnects to a server that was already running from an earlier session, there is nothing watching it, so its death still leaves no record.
+
+Nothing new is collected about you or your documents. The record holds a timestamp, the process id, the exit code, the signal that ended it, and which part of the app was watching. It stays on your machine unless you send it. Running `ok diagnose bundle` yourself includes it, and so does a bug report filed with detailed diagnostics turned on; an ordinary bug report does not carry it yet.
diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdx
index b30e4ad38..e765a9821 100644
--- a/docs/content/reference/what-open-knowledge-writes.mdx
+++ b/docs/content/reference/what-open-knowledge-writes.mdx
@@ -113,6 +113,8 @@ The app runs a collaboration server for the open project. It writes runtime stat
| `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored |
| `.ok/local/sync-state.json`, `.ok/local/conflicts.json` | GitHub-sync engine state | In-project, gitignored |
| `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |
+| `.ok/local/last-server-exit.json` | Why the collaboration server the app started last exited — a timestamp, its process id, the exit code, the signal that ended it, and which part of the app was watching. One record, overwritten on each exit; a server the app only attached to, or one you started yourself with `ok start`, leaves none. No document content or paths | In-project, gitignored |
+| `.ok/local/last-server-crash.json` | The collaboration server's own account of a crash it did not survive — a timestamp, the error message and stack, its process id, and how long it had been running. Written by the server itself, so it covers `ok start` too. Holds the most recent crash only | In-project, gitignored |
| `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |
| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |
| `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored |
@@ -228,6 +230,7 @@ On Windows, Claude Desktop and OpenCode configs live under `%APPDATA%\Claude\` a
| `.ok/local/principal.json` | Your local identity (id, email) for edit attribution | In-project, gitignored |
| `.ok/local/sync-state.json`, `.ok/local/conflicts.json` | GitHub-sync engine state | In-project, gitignored |
| `.ok/local/state.json`, `.ok/local/last-spawn-error.log` | State-schema manifest and the last detached-spawn error log | In-project, gitignored |
+| `.ok/local/last-server-crash.json` | The server's own account of a crash it did not survive — a timestamp, the error message and stack, its process id, and how long it had been running. Holds the most recent crash only | In-project, gitignored |
| `.ok/local/telemetry/spans-*.jsonl` | Local diagnostic spans, rotated at ~50 MB | In-project, gitignored |
| `.ok/local/logs/server-*.jsonl` | Local server logs, rotated at ~25 MB | In-project, gitignored |
| `.ok/local/cache/<branch>/backlinks.json` | Backlink-graph cache | In-project, gitignored |
diff --git a/knip.config.ts b/knip.config.ts
index 8ad68f996..b61debe5e 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -124,9 +124,7 @@ export default {
'packages/server': {
entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],
project: 'src/**',
- ignoreDependencies: [
- '@types/shell-quote',
- ],
+ ignoreDependencies: ['@types/shell-quote'],
},
'packages/cli': {
entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],
diff --git a/packages/cli/src/diagnose/bundle.ts b/packages/cli/src/diagnose/bundle.ts
index a658875b6..cd31cda6b 100644
--- a/packages/cli/src/diagnose/bundle.ts
+++ b/packages/cli/src/diagnose/bundle.ts
@@ -863,9 +863,11 @@ export async function collectBundle(opts: CollectBundleOpts): Promise<CollectedB
join(stagingDir, 'state', 'last-spawn-error.log'),
);
- // last-server-exit.json — why the server process last exited (code +
- // Electron process-gone reason). Lets a bundle tell a crash / OS-kill from
- // a managed shutdown, which `server-status.txt: not-running` alone cannot.
+ // last-server-exit.json — why the server process last exited (timestamp,
+ // pid, code, killing signal, and Electron's process-gone reason where the
+ // host could observe one; see SERVER_EXIT_LOG for the per-host field
+ // availability). Lets a bundle tell a crash / OS-kill from 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/
diff --git a/packages/core/src/bridge/bind-frontmatter-doc.ts b/packages/core/src/bridge/bind-frontmatter-doc.ts
index dfd95ef49..d7a845280 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/compose.ts b/packages/core/src/bridge/compose.ts
index 2a597ec3d..f4cc8a286 100644
--- a/packages/core/src/bridge/compose.ts
+++ b/packages/core/src/bridge/compose.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';
export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';
diff --git a/packages/core/src/bridge/divergence-locate.ts b/packages/core/src/bridge/divergence-locate.ts
index d979f4b39..6b505314d 100644
--- a/packages/core/src/bridge/divergence-locate.ts
+++ b/packages/core/src/bridge/divergence-locate.ts
@@ -1,4 +1,3 @@
-
import { findFirstDivergenceIndex } from './tolerance-telemetry.ts';
export const BRIDGE_LINE_KINDS = [
diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.ts
index 01ef76a9f..8fb428b90 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';
import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';
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/intraline-predicate.ts b/packages/core/src/bridge/intraline-predicate.ts
index 0939885bb..c43fdd7e7 100644
--- a/packages/core/src/bridge/intraline-predicate.ts
+++ b/packages/core/src/bridge/intraline-predicate.ts
@@ -1,4 +1,3 @@
-
export function rawLineCounts(doc: string): Map<string, number> {
const counts = new Map<string, number>();
for (const line of doc.split('\n')) {
diff --git a/packages/core/src/bridge/merge-three-way.ts b/packages/core/src/bridge/merge-three-way.ts
index c0dc65705..251560a35 100644
--- a/packages/core/src/bridge/merge-three-way.ts
+++ b/packages/core/src/bridge/merge-three-way.ts
@@ -65,7 +65,6 @@ export function tryLineLevelCombine(
return { clean: true, merged };
}
-
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 dcc5b0690..01ac80099 100644
--- a/packages/core/src/bridge/normalize.ts
+++ b/packages/core/src/bridge/normalize.ts
@@ -1,4 +1,3 @@
-
import { stripFrontmatter } from '../extensions/frontmatter.ts';
import { bodyEdgeEmpties } from './doc-boundary-space.ts';
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 dc8226272..7d55164c6 100644
--- a/packages/core/src/constants/lifecycle.ts
+++ b/packages/core/src/constants/lifecycle.ts
@@ -39,11 +39,45 @@ export const SPAWN_ERROR_LOG = 'last-spawn-error.log';
/**
* Filename under `<projectRoot>/.ok/local/` where the desktop host records why
- * the server process last exited — the exit `code` plus Electron's
- * process-gone `reason` (`clean-exit` / `abnormal-exit` / `killed` / `crashed`
- * / `oom`). Written by the desktop main process (which observes the child's
- * death even when the child could not report it) and collected into a
- * bug-report bundle's `state/` dir beside `server.lock`.
+ * the server process last exited. Written by the desktop main process (which
+ * observes the child's death even when the child could not report it) and
+ * collected into a bug-report bundle's `state/` dir beside `server.lock`.
+ *
+ * JSON object, one record, last write wins — read `at` before anything else,
+ * since a record from a healthy session is simply the last exit, not a current
+ * one. Fields: `at` (ISO timestamp), `pid`, `code` (null when a signal killed
+ * it), `signal` (POSIX signal name; null or absent otherwise), `observer`
+ * (which host saw the death) and `reason` (Electron's process-gone
+ * classification, or null). Electron's reason values are forwarded verbatim
+ * and its set grows across releases — `clean-exit` / `abnormal-exit` /
+ * `killed` / `crashed` / `oom` / `launch-failed` / `integrity-failure` /
+ * `memory-eviction` as of Electron 43 — so treat an unrecognised string as a
+ * newer classification rather than a corrupt record. No format-version field:
+ * like `SentinelState`, the shape is read across app versions and stays
+ * compatible by being add-only, so a reader treats any field it does not find
+ * as unknown rather than as a value.
+ *
+ * `observer` says how the nullable fields read, because availability differs by
+ * which host saw the death. `utility-process` is the development Electron
+ * `utilityProcess` fork: it reports a `code` but never a `signal`, and Electron
+ * can classify it, so a null `reason` there means the correlation window
+ * produced nothing. `detached-spawn` is the packaged plain OS process: on POSIX
+ * it reports both `code` and `signal`, and Electron cannot classify it at all,
+ * so `reason` is always null there, meaning "not observable on this path"
+ * rather than "unclassified".
+ *
+ * On Windows `signal` is null for *every* death including the app's own: libuv
+ * records a signal only for a kill routed through the child's own handle, and
+ * the desktop kills by pid. `code` is no substitute — libuv terminates with
+ * `TerminateProcess(handle, 1)` for every supported signal and reports that
+ * literal status, so a managed stop and a voluntary `exit(1)` are both
+ * `{code: 1, signal: null}`. There the record narrows to `code: 0` = orderly
+ * stop, anything else = unresolved.
+ *
+ * Only a server the desktop session itself spawned is observed. When a window
+ * attaches to a server an earlier session left running there is no child handle
+ * and no exit listener, so an absent record means "this session never owned the
+ * child" as often as it means "nothing died".
*
* This closes a diagnostic gap: without it, a bundle can't tell a server that
* crashed or was OS-killed from one that shut down cleanly — the liveness
@@ -61,7 +95,9 @@ export const SERVER_EXIT_LOG = 'last-server-exit.json';
* `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.
+ * died (exit code, killing signal, and a classification where its host can
+ * observe one) from the outside; this file records *why* from the inside — the
+ * stack no other artifact reliably captures. Written by the server itself, so
+ * unlike its sibling it also covers a server started by `ok start`.
*/
export const SERVER_CRASH_LOG = 'last-server-crash.json';
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/code-fence.ts b/packages/core/src/markdown/code-fence.ts
index 4499dbc92..9807a7e82 100644
--- a/packages/core/src/markdown/code-fence.ts
+++ b/packages/core/src/markdown/code-fence.ts
@@ -1,4 +1,3 @@
-
export function selectFenceChar(info: string): '`' | '~' {
return info.includes('`') ? '~' : '`';
}
diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index 34704165b..7415c474a 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/div-align-promoter.ts b/packages/core/src/markdown/div-align-promoter.ts
index ba9b56384..43ecdc709 100644
--- a/packages/core/src/markdown/div-align-promoter.ts
+++ b/packages/core/src/markdown/div-align-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Paragraph, Parent, Root, Text } from 'mdast';
import type { 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 4513da9bb..6d3f3643e 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 5d1000cc4..da0a81d23 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 9681c0056..787315157 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 { Element as HastElement, Root as HastRoot } from 'hast';
import type { List, Nodes as MdastNodes, Root as MdastRoot } from 'mdast';
import rehypeParse from 'rehype-parse';
@@ -129,8 +128,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 ec1ac1b7e..779e27500 100644
--- a/packages/core/src/markdown/index.ts
+++ b/packages/core/src/markdown/index.ts
@@ -1,4 +1,3 @@
-
import {
type FromProseMirrorOptions,
fromPmMark,
@@ -207,7 +206,6 @@ export class MarkdownManager {
}
}
-
const registry = createRegistry();
function destructureAttrs(
@@ -256,7 +254,6 @@ function destructureAttrs(
return result;
}
-
function hasDirtyDescendant(node: PmNode): boolean {
let found = false;
node.descendants((child) => {
@@ -279,7 +276,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 ?? [];
@@ -348,7 +344,6 @@ function extractTextFromMdastNodes(nodes: MdastNodes[]): string {
return out;
}
-
import {
AUDIO_EXTENSIONS,
FILE_ATTACHMENT_EXTENSIONS,
@@ -601,7 +596,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.emphasis) {
handlers.emphasis = toPmMark(m.emphasis, (node: Emphasis) => ({
sourceDelimiter: node.data?.sourceDelimiter ?? '*',
@@ -682,7 +676,6 @@ function buildMdastToPmHandlers(
}));
}
-
if (m.link) {
const sourceLiteralMark = m.sourceLiteral;
handlers.link = (node: Link, _parent: MdastParent, state: MdastToPmState) => {
@@ -980,7 +973,6 @@ function buildMdastToPmHandlers(
};
}
-
const blockUnknownHandler = (node: {
type: string;
position?: { start: { offset: number }; end: { offset: number } };
@@ -1106,7 +1098,6 @@ function buildMdastToPmHandlers(
return handlers as RemarkProseMirrorOptions['handlers'];
}
-
function buildPmToMdastHandlers(
schema: Schema,
freshness: FreshnessCheckerHolder,
diff --git a/packages/core/src/markdown/lint/applies-to.ts b/packages/core/src/markdown/lint/applies-to.ts
index b79e9aef7..fa0be9e86 100644
--- a/packages/core/src/markdown/lint/applies-to.ts
+++ b/packages/core/src/markdown/lint/applies-to.ts
@@ -1,4 +1,3 @@
-
import picomatch from 'picomatch';
import { SUPPORTED_DOC_EXTENSIONS } from '../../constants/doc-extensions.ts';
diff --git a/packages/core/src/markdown/lint/config-files.ts b/packages/core/src/markdown/lint/config-files.ts
index 94b34dee1..312c9c74b 100644
--- a/packages/core/src/markdown/lint/config-files.ts
+++ b/packages/core/src/markdown/lint/config-files.ts
@@ -1,4 +1,3 @@
-
const MARKDOWNLINT_JSON_CONFIG_FILES: ReadonlySet<string> = new Set([
'.markdownlint.json',
'.markdownlint.jsonc',
diff --git a/packages/core/src/markdown/lint/config-schemas.ts b/packages/core/src/markdown/lint/config-schemas.ts
index fbbd309df..1a81aa524 100644
--- a/packages/core/src/markdown/lint/config-schemas.ts
+++ b/packages/core/src/markdown/lint/config-schemas.ts
@@ -52,7 +52,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/frontmatter-schema-edit.ts b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
index 9c9542661..ef478e268 100644
--- a/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
+++ b/packages/core/src/markdown/lint/frontmatter-schema-edit.ts
@@ -1,4 +1,3 @@
-
import { CANONICAL_SCHEMA_DIALECT_URIS, DEFAULT_SCHEMA_DIALECT } from './frontmatter-validate.ts';
export interface FrontmatterFieldConstraint {
diff --git a/packages/core/src/markdown/lint/frontmatter-validate.ts b/packages/core/src/markdown/lint/frontmatter-validate.ts
index b0e7833fd..5f953d667 100644
--- a/packages/core/src/markdown/lint/frontmatter-validate.ts
+++ b/packages/core/src/markdown/lint/frontmatter-validate.ts
@@ -1,4 +1,3 @@
-
import Ajv, { type ValidateFunction } from 'ajv';
import Ajv2019 from 'ajv/dist/2019.js';
import Ajv2020 from 'ajv/dist/2020.js';
diff --git a/packages/core/src/markdown/lint/index.ts b/packages/core/src/markdown/lint/index.ts
index ffd277a90..11b5abdfd 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/okf-frontmatter/materialize.ts b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
index f438f1b16..7a5af097e 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/materialize.ts
@@ -1,4 +1,3 @@
-
import type { OkfRuleId } from '../okf-rule-meta.ts';
import { fileNameFor, OKF_SCHEMA_DIR, okfSchemaPathFor } from './paths.ts';
import { OKF_FRONTMATTER_REGISTRY } from './registry.ts';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
index c290b6878..1ee913527 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/paths.ts
@@ -1,4 +1,3 @@
-
import type { OkfRuleId } from '../okf-rule-meta.ts';
export const OKF_SCHEMA_DIR = '.ok/okf';
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
index 53ecb619d..f325fbbb4 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/registry.ts
@@ -1,4 +1,3 @@
-
import { compileAppliesTo } from '../applies-to.ts';
import { validateFrontmatterSource } from '../frontmatter-validate.ts';
import {
diff --git a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
index 89845d3d5..f1c37671b 100644
--- a/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
+++ b/packages/core/src/markdown/lint/okf-frontmatter/schemas.ts
@@ -1,4 +1,3 @@
-
// file-level form is deliberate: the sibling `biome-ignore` must sit on the line
// oxlint-disable unicorn/no-thenable
diff --git a/packages/core/src/markdown/lint/okf-project/rules.ts b/packages/core/src/markdown/lint/okf-project/rules.ts
index 8b476332e..6d691ae2b 100644
--- a/packages/core/src/markdown/lint/okf-project/rules.ts
+++ b/packages/core/src/markdown/lint/okf-project/rules.ts
@@ -1,4 +1,3 @@
-
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from '../okf-rule-meta.ts';
diff --git a/packages/core/src/markdown/lint/okf-rule-meta.ts b/packages/core/src/markdown/lint/okf-rule-meta.ts
index 44913a9dc..4de50d79f 100644
--- a/packages/core/src/markdown/lint/okf-rule-meta.ts
+++ b/packages/core/src/markdown/lint/okf-rule-meta.ts
@@ -1,4 +1,3 @@
-
export const OKF_RULE_IDS = [
'no-wiki-links',
'log-shape',
diff --git a/packages/core/src/markdown/lint/okf-rules.ts b/packages/core/src/markdown/lint/okf-rules.ts
index d0999b62e..1d5538421 100644
--- a/packages/core/src/markdown/lint/okf-rules.ts
+++ b/packages/core/src/markdown/lint/okf-rules.ts
@@ -1,4 +1,3 @@
-
import { isOkfRuleEnabled, type OkfRuleId, type OkfRuleToggles } from './okf-rule-meta.ts';
import type { OkfRule } from './okf-runner.ts';
import { indexShape } from './rules/index-shape.ts';
diff --git a/packages/core/src/markdown/lint/okf-runner.ts b/packages/core/src/markdown/lint/okf-runner.ts
index fabb08d6e..de130e3f4 100644
--- a/packages/core/src/markdown/lint/okf-runner.ts
+++ b/packages/core/src/markdown/lint/okf-runner.ts
@@ -1,4 +1,3 @@
-
import type { Root } from 'mdast';
import remarkFrontmatter from 'remark-frontmatter';
import remarkGfm from 'remark-gfm';
diff --git a/packages/core/src/markdown/lint/plugins.ts b/packages/core/src/markdown/lint/plugins.ts
index 0a089990e..09c8450ee 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 {
@@ -24,7 +23,6 @@ import {
type OkfSlice,
} from './types.ts';
-
const MarkdownlintRuleSettingSchema = z.union([
z.boolean(),
z.enum(MARKDOWNLINT_RULE_SEVERITIES),
diff --git a/packages/core/src/markdown/lint/rules/index-shape.ts b/packages/core/src/markdown/lint/rules/index-shape.ts
index fcbb1b56c..59fe9b87d 100644
--- a/packages/core/src/markdown/lint/rules/index-shape.ts
+++ b/packages/core/src/markdown/lint/rules/index-shape.ts
@@ -1,4 +1,3 @@
-
import type { List, ListItem } from 'mdast';
import { EXIT, visit } from 'unist-util-visit';
import { defineScopedOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/log-shape.ts b/packages/core/src/markdown/lint/rules/log-shape.ts
index 431e4e9c8..e0159519f 100644
--- a/packages/core/src/markdown/lint/rules/log-shape.ts
+++ b/packages/core/src/markdown/lint/rules/log-shape.ts
@@ -1,4 +1,3 @@
-
import type { Heading } from 'mdast';
import { toString as headingText } from 'mdast-util-to-string';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/lint/rules/no-wiki-links.ts b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
index f75a04d15..2123e977f 100644
--- a/packages/core/src/markdown/lint/rules/no-wiki-links.ts
+++ b/packages/core/src/markdown/lint/rules/no-wiki-links.ts
@@ -1,4 +1,3 @@
-
import type { Point } from 'unist';
import { visit } from 'unist-util-visit';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/rules/reserved-casing.ts b/packages/core/src/markdown/lint/rules/reserved-casing.ts
index c8b4d8f28..89ef3e4a9 100644
--- a/packages/core/src/markdown/lint/rules/reserved-casing.ts
+++ b/packages/core/src/markdown/lint/rules/reserved-casing.ts
@@ -1,4 +1,3 @@
-
import { SUPPORTED_DOC_EXTENSIONS } from '../../../constants/doc-extensions.ts';
import { defineOkfRule } from '../okf-runner.ts';
diff --git a/packages/core/src/markdown/lint/types.ts b/packages/core/src/markdown/lint/types.ts
index c04fa4de0..6836b962d 100644
--- a/packages/core/src/markdown/lint/types.ts
+++ b/packages/core/src/markdown/lint/types.ts
@@ -1,4 +1,3 @@
-
import type { BrokenLinkReason } from '../../schemas/api/agent-write.ts';
import type { OkfRuleId } from './okf-rule-meta.ts';
@@ -113,7 +112,6 @@ export interface OkfSlice {
generate?: { index?: boolean };
}
-
interface RuleOptionSpecBase {
key: string;
description: string;
diff --git a/packages/core/src/markdown/lint/validation-counts.ts b/packages/core/src/markdown/lint/validation-counts.ts
index 437cc539a..98238656e 100644
--- a/packages/core/src/markdown/lint/validation-counts.ts
+++ b/packages/core/src/markdown/lint/validation-counts.ts
@@ -1,4 +1,3 @@
-
export interface ValidationSourceCounts {
errorCount: number;
warningCount: number;
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 00fbc0035..ed89371d0 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 4aa0490c4..d988f4b8b 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 55736041c..0e3224206 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 ccf06e94d..91cdf658f 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';
import { isBlankLineParagraph } from './zero-emission-blocks.ts';
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-fidelity.test-helper.ts b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
index 96304e7a5..0dd54070e 100644
--- a/packages/core/src/markdown/serialize-fidelity.test-helper.ts
+++ b/packages/core/src/markdown/serialize-fidelity.test-helper.ts
@@ -1,4 +1,3 @@
-
import type { JSONContent } from '@tiptap/core';
import type { Nodes } from 'mdast';
import { expect } from 'vitest';
diff --git a/packages/core/src/markdown/serialize-helpers.ts b/packages/core/src/markdown/serialize-helpers.ts
index 93798cf83..7cac5b042 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,
diff --git a/packages/core/src/markdown/single-dollar-math-promoter.ts b/packages/core/src/markdown/single-dollar-math-promoter.ts
index 8c08b7a04..b012a5aff 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 959cc0bd2..3e79f8cb6 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/underline-promoter.ts b/packages/core/src/markdown/underline-promoter.ts
index 6e6d73400..0f1b0f27d 100644
--- a/packages/core/src/markdown/underline-promoter.ts
+++ b/packages/core/src/markdown/underline-promoter.ts
@@ -1,4 +1,3 @@
-
import type { Nodes, Parent, Root } from 'mdast';
import type { MdxJsxTextElement } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
diff --git a/packages/core/src/markdown/unknown-mdast-guard.ts b/packages/core/src/markdown/unknown-mdast-guard.ts
index 932d7d2a8..1a082bda7 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/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 58034708c..7d8122fe3 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -400,6 +400,7 @@ import {
shouldRevealInactiveNow,
} from './restore-focus.ts';
import { handleRevealExternal } from './reveal-external.ts';
+import { attachServerExitObserver } from './server-exit-observer.ts';
import { createServerExitRecorder, type ServerExitRecorder } from './server-exit-record.ts';
import { startFirstRunHandshake } from './share-handoff.ts';
import { checkOutboundUrl, handleShellOpenExternal } from './shell-allowlist.ts';
@@ -1469,10 +1470,14 @@ let crashSentinelHeartbeat: NodeJS.Timeout | null = null;
let osShutdownNoted = false;
/**
- * Records the server's last exit (code + Electron process-gone reason) to
+ * Records the server's last exit (timestamp, pid, code, killing signal, which
+ * host observed it, and Electron's process-gone reason where one applies) to
* `<lockDir>/last-server-exit.json` for bug-report diagnosis. Lazy singleton so
- * the window-manager fork path and the `child-process-gone` listener — which
- * initialize on different boot paths — share one correlator.
+ * all three participants — the window-manager fork path, the `child-process-gone`
+ * listener, and the detached-spawn observer wired at the spawn closure below —
+ * share one correlator rather than each building its own. That sharing is what
+ * `tests/integration/server-exit-wiring.test.ts` pins: a per-path recorder would
+ * split the reason correlation the fork path depends on.
*/
let serverExitRecorder: ServerExitRecorder | null = null;
function getServerExitRecorder(): ServerExitRecorder {
@@ -2015,6 +2020,19 @@ function ensureWindowManager() {
childRef.on('exit', (code, signal) => {
exitRecord = { code, signal };
});
+ // `exitRecord` above only ever reaches the boot-time spawn-failure
+ // branches via `readExit()`; once a window has attached, nothing
+ // reads it again. A second listener on the same event persists the
+ // death for a later bug bundle instead, and in a packaged build it
+ // is the only observer of that death — `server-exit-observer.ts`
+ // holds the why, and owns the registration so that the shape of it
+ // is covered by a test rather than by review of this file.
+ // `tests/integration/server-exit-wiring.test.ts` pins the call.
+ attachServerExitObserver(childRef, {
+ lockDir,
+ recordExit: (info) => getServerExitRecorder().recordExit(info),
+ logger: getLogger('server-exit'),
+ });
childRef.unref();
const pid = childRef.pid;
if (pid === undefined) {
@@ -2093,7 +2111,11 @@ function ensureWindowManager() {
// the `desktop-upgrade-reconcile` upgrade signal, restart — reach
// `~/.ok/logs/`.
log: getLogger('window-manager'),
- recordServerExit: (info) => getServerExitRecorder().recordExit(info),
+ // The adapter, not the dep, names the host: `WindowManagerDeps` stays
+ // narrow (it has no signal and no observer to give), and this is the site
+ // that knows which of the two spawn paths it is wiring.
+ recordServerExit: (info) =>
+ getServerExitRecorder().recordExit({ ...info, observer: 'utility-process' }),
// Presence-invisible keepalive WS — registers the desktop as an active
// `/collab*` upgrade for as long as a project window is open, so a brief
// MCP disconnect does not trip the server's idle-shutdown timer. The
diff --git a/packages/desktop/src/main/server-exit-observer.test.ts b/packages/desktop/src/main/server-exit-observer.test.ts
new file mode 100644
index 000000000..628292b0f
--- /dev/null
+++ b/packages/desktop/src/main/server-exit-observer.test.ts
@@ -0,0 +1,180 @@
+/**
+ * Exit-to-record mapping and registration for the packaged detached server.
+ * Capturing stubs rather than spies, matching the sibling
+ * `server-exit-record.test.ts` posture. The call counts are exact: a death must
+ * produce one record and one log line, which is why the registration is
+ * exercised through `attachServerExitObserver` (the function production calls)
+ * on a real `EventEmitter` — a second listener added *inside that function*
+ * would double both, and a mapping test alone cannot see that. A duplicated
+ * call at the wiring site is out of reach here; `server-exit-wiring.test.ts`
+ * counts the call sites in `index.ts` instead.
+ */
+
+import { EventEmitter } from 'node:events';
+import { describe, expect, test } from 'vitest';
+import { attachServerExitObserver, createServerExitObserver } from './server-exit-observer.ts';
+import type { ServerExitInfo } from './server-exit-record.ts';
+
+const LOCK_DIR = '/tmp/ok-project/.ok/local';
+const PID = 51502;
+
+// `pid` is required rather than defaulted: passing `undefined` to a defaulted
+// parameter would silently restore the default, which is the exact case the
+// unavailable-pid test needs to exercise.
+function makeObserver(pid: number | undefined) {
+ const recorded: ServerExitInfo[] = [];
+ const logged: Array<{ payload: Record<string, unknown>; msg: string }> = [];
+ const observer = createServerExitObserver({
+ lockDir: LOCK_DIR,
+ readPid: () => pid,
+ recordExit: (info) => recorded.push(info),
+ logger: {
+ info: (payload: Record<string, unknown>, msg: string) => logged.push({ payload, msg }),
+ },
+ });
+ return { observer, recorded, logged };
+}
+
+describe('createServerExitObserver', () => {
+ test.each([
+ ['a clean exit', 0, null],
+ ['a non-zero exit', 1, null],
+ ['a signal kill', null, 'SIGKILL'],
+ ['a signalled managed stop', null, 'SIGTERM'],
+ ] as const)('%s records its code and signal verbatim', (_name, code, signal) => {
+ const { observer, recorded } = makeObserver(PID);
+
+ observer(code, signal);
+
+ // `observer: 'detached-spawn'` on every shape is the opt-out: no
+ // `child-process-gone` reason can describe a plain spawn child, so the
+ // recorder must never join one onto these records.
+ expect(recorded).toEqual([
+ { lockDir: LOCK_DIR, pid: PID, code, signal, observer: 'detached-spawn' },
+ ]);
+ });
+
+ test('an unavailable pid records null rather than skipping the record', () => {
+ const { observer, recorded } = makeObserver(undefined);
+
+ expect(() => observer(null, 'SIGKILL')).not.toThrow();
+
+ expect(recorded).toHaveLength(1);
+ expect(recorded[0]?.pid).toBeNull();
+ });
+
+ test('each exit emits exactly one info line naming the project, pid, code and signal', () => {
+ const { observer, logged } = makeObserver(PID);
+
+ observer(null, 'SIGTERM');
+
+ expect(logged).toHaveLength(1);
+ // `event` is the string a triager greps a bundle log for, so renaming it
+ // has to break something.
+ expect(logged[0]?.payload).toMatchObject({
+ event: 'server-exit.detached-child-exited',
+ lockDir: LOCK_DIR,
+ pid: PID,
+ code: null,
+ signal: 'SIGTERM',
+ });
+ });
+
+ test('the log line lands even when recording the exit fails', () => {
+ const logged: Array<{ payload: Record<string, unknown>; msg: string }> = [];
+ const observer = createServerExitObserver({
+ lockDir: LOCK_DIR,
+ readPid: () => PID,
+ recordExit: () => {
+ throw new Error('state dir unwritable');
+ },
+ logger: {
+ info: (payload: Record<string, unknown>, msg: string) => logged.push({ payload, msg }),
+ },
+ });
+
+ // Contained, not propagated: this listener runs inside an `EventEmitter`
+ // callback, so a throw escaping it becomes an `uncaughtException` and —
+ // this main process installing no userland handler by design — Electron's
+ // fatal error dialog. A diagnostic must not kill the app whose server just
+ // died.
+ expect(() => observer(null, 'SIGKILL')).not.toThrow();
+
+ expect(logged).toHaveLength(1);
+ });
+
+ test('a throwing logger does not take the process down with it', () => {
+ const recorded: ServerExitInfo[] = [];
+ const observer = createServerExitObserver({
+ lockDir: LOCK_DIR,
+ readPid: () => PID,
+ recordExit: (info) => recorded.push(info),
+ logger: {
+ // The real failure this guard is for: the desktop logger's first use
+ // lazily `mkdirSync`s `~/.ok/logs`, which can throw EACCES/ENOSPC.
+ info: () => {
+ throw Object.assign(new Error("EACCES: permission denied, mkdir '/x/.ok/logs'"), {
+ code: 'EACCES',
+ });
+ },
+ },
+ });
+
+ expect(() => observer(null, 'SIGKILL')).not.toThrow();
+ // The record still lands. The two sinks are unrelated trees — the log goes
+ // to `~/.ok/logs`, the record to `<projectRoot>/.ok/local` — and the record
+ // is the durable artifact, so a fault in one must not take the other with
+ // it. This assertion is what stops a future refactor collapsing the two
+ // guards back into one.
+ expect(recorded).toHaveLength(1);
+ });
+});
+
+describe('attachServerExitObserver', () => {
+ /** The slice of a spawned child the observer touches, with a settable pid. */
+ class FakeChild extends EventEmitter {
+ constructor(public pid: number | undefined) {
+ super();
+ }
+ }
+
+ test('one registration turns one exit into exactly one record and one log line', () => {
+ const child = new FakeChild(PID);
+ const recorded: ServerExitInfo[] = [];
+ const logged: Array<Record<string, unknown>> = [];
+
+ attachServerExitObserver(child, {
+ lockDir: LOCK_DIR,
+ recordExit: (info) => recorded.push(info),
+ logger: { info: (payload) => logged.push(payload) },
+ });
+
+ child.emit('exit', null, 'SIGKILL');
+
+ expect(recorded).toEqual([
+ { lockDir: LOCK_DIR, pid: PID, code: null, signal: 'SIGKILL', observer: 'detached-spawn' },
+ ]);
+ expect(logged).toHaveLength(1);
+ });
+
+ test('the pid is read through the child at exit time, not captured at registration', () => {
+ // Node resolves `subprocess.pid` at spawn and retains it past handle
+ // teardown, so reading late is safe — and reading late is what lets the
+ // registration sit above the spawn site's own `pid` binding, ahead of
+ // `unref()`. This pins the direction: a value captured at registration
+ // would still be the stale one here.
+ const child = new FakeChild(undefined);
+ const recorded: ServerExitInfo[] = [];
+
+ attachServerExitObserver(child, {
+ lockDir: LOCK_DIR,
+ recordExit: (info) => recorded.push(info),
+ logger: { info: () => {} },
+ });
+ child.pid = PID;
+
+ child.emit('exit', 0, null);
+
+ expect(recorded[0]?.pid).toBe(PID);
+ });
+});
diff --git a/packages/desktop/src/main/server-exit-observer.ts b/packages/desktop/src/main/server-exit-observer.ts
new file mode 100644
index 000000000..a43ade52a
--- /dev/null
+++ b/packages/desktop/src/main/server-exit-observer.ts
@@ -0,0 +1,148 @@
+/**
+ * Turns a detached project server's `'exit'` event into the forensic record and
+ * the one desktop log line that describe its death.
+ *
+ * In packaged builds the server is spawned with plain `child_process.spawn`
+ * (see `resolve-detached-spawn-args.ts`), which puts its death outside every
+ * mechanism that used to record one: it is an ordinary OS process, so Electron's
+ * `app.on('child-process-gone')` can never classify it (`type === 'Utility'` is
+ * structurally unreachable for it), and the `utilityProcess` exit handler that
+ * calls the recorder in dev never runs. The `'exit'` listener on the spawned
+ * child is the only observer of that death, and this is what it should do with
+ * what it observes.
+ *
+ * The same unreachability cuts the other way: every `child-process-gone` reason
+ * that can reach the recorder in a packaged build belongs to some other utility
+ * (a pty-host, say), so this path names itself `detached-spawn` on the record,
+ * which is what tells the recorder not to join a cause that describes a
+ * different process.
+ *
+ * Deps are injected and nothing here imports `electron` or `./index.ts`, so the
+ * mapping is unit-testable on its own — `index.ts` has no test file. Same
+ * posture as the sibling `resolve-detached-spawn-args.ts`. `attachServerExitObserver`
+ * exists so the registration itself is inside that testable surface rather than
+ * being a shape the integration test has to rebuild by hand.
+ *
+ * Observing is all it does. The server is deliberately detached and `unref`ed
+ * so it outlives the desktop process, so nothing here kills, restarts or
+ * re-parents it, and it holds no reference to the child beyond reading its pid.
+ */
+
+import type { ServerExitInfo } from './server-exit-record.ts';
+
+/** Structured `info` sink; `getLogger('server-exit')` satisfies it. */
+interface ServerExitObserverLogger {
+ info(payload: Record<string, unknown>, msg: string): void;
+}
+
+export interface ServerExitObserverDeps {
+ /** Where the record lands: `<lockDir>/last-server-exit.json`. */
+ lockDir: string;
+ /**
+ * The child's pid, read at exit time rather than taken by value. Safe because
+ * Node retains `subprocess.pid` past handle teardown — inside the `'exit'`
+ * handler `child._handle` is already null while `child.pid` still reads the
+ * spawned pid. That is what lets the registration sit above the spawn site's
+ * own `pid` binding, which is what keeps the listener ahead of `unref()`.
+ *
+ * `undefined` mirrors `ObservableChild.pid`, the only source this reads, and
+ * records as null rather than dropping the record. Unreachable through the
+ * one production caller, which resolves the pid from an already-awaited
+ * `'spawn'` event.
+ */
+ readPid(): number | undefined;
+ /** The shared `ServerExitRecorder`'s `recordExit`. */
+ recordExit(info: ServerExitInfo): void;
+ logger: ServerExitObserverLogger;
+}
+
+/** The `'exit'` listener signature this module produces and attaches. */
+type ExitListener = (code: number | null, signal: NodeJS.Signals | null) => void;
+
+/**
+ * The slice of a spawned child this module touches: its pid, and the one event
+ * it listens for. Structural rather than `ChildProcess` so nothing here depends
+ * on `node:child_process`, and so the shape makes the "no kill, no restart, no
+ * re-parenting" boundary a type-level fact rather than a promise in a comment.
+ */
+export interface ObservableChild {
+ readonly pid?: number | undefined;
+ on(event: 'exit', listener: ExitListener): unknown;
+}
+
+/**
+ * Build the `'exit'` listener for a detached project server. Exported for the
+ * unit tests, which drive the mapping directly; production and the integration
+ * test both go through `attachServerExitObserver` so the registration is
+ * covered too.
+ */
+export function createServerExitObserver(deps: ServerExitObserverDeps): ExitListener {
+ return (code, signal) => {
+ // A diagnostic must not be able to kill the process it observes. A throw out
+ // of an `EventEmitter` callback becomes an `uncaughtException`, and this main
+ // process deliberately installs no userland handler for those (see
+ // `process-safety-net.ts`), so it would surface as Electron's fatal "A
+ // JavaScript error occurred in the main process" dialog — at the exact moment
+ // the user's server just died, taking away the app that would have filed the
+ // report about it.
+ //
+ // One guard per artifact, not one around both. The two sinks live in
+ // unrelated trees — the record goes to `<projectRoot>/.ok/local`, the log to
+ // `~/.ok/logs` — so a fault in one says nothing about the other, and a shared
+ // guard would silently let the first failure delete the second artifact.
+ let pid: number | null = null;
+ try {
+ pid = deps.readPid() ?? null;
+ } catch {}
+
+ // The record first, because it is the durable artifact: `recordExit` writes
+ // synchronously and is on disk before it returns, while the desktop log
+ // destination is `sync: false` and only managed-shutdown paths flush it. It
+ // is also already fail-soft internally, so this guard is belt-and-braces —
+ // whereas the logger genuinely can throw, and stays broken for the rest of
+ // the session once it does (`getRootLogger` memoizes only *after* its
+ // `mkdirSync`). Ordering it second is what keeps a locked-down `~/.ok/logs`
+ // from costing us the record on a perfectly writable project dir.
+ try {
+ deps.recordExit({
+ lockDir: deps.lockDir,
+ pid,
+ code,
+ signal,
+ // No `child-process-gone` reason can describe this child (see header).
+ observer: 'detached-spawn',
+ });
+ } catch {}
+
+ // `lockDir` names which project lost its server, since a pid alone no longer
+ // resolves. Failure here is deliberately terminal rather than escalated: the
+ // only sink that could report it is the one that just failed. The record
+ // written above is the surviving evidence — a record with no matching
+ // `server-exit.detached-child-exited` line is itself the signal that this
+ // session's logging was degraded.
+ try {
+ deps.logger.info(
+ { event: 'server-exit.detached-child-exited', lockDir: deps.lockDir, pid, code, signal },
+ 'detached project server exited',
+ );
+ } catch {}
+ };
+}
+
+/**
+ * Register the exit observer on a spawned detached server.
+ *
+ * Production (`index.ts`'s `spawnDetachedServer`) and the integration test call
+ * this same function, so the registration — that the observer is attached to
+ * the child's `'exit'`, once, reading the pid through the child — is pinned by
+ * a test rather than resting on review of a ~9,000-line file with no test file
+ * of its own. Must be called before `unref()`; `unref()` releases the
+ * event-loop reference, not listeners, but keeping the order explicit keeps the
+ * spawn site readable.
+ */
+export function attachServerExitObserver(
+ child: ObservableChild,
+ deps: Omit<ServerExitObserverDeps, 'readPid'>,
+): void {
+ child.on('exit', createServerExitObserver({ ...deps, readPid: () => child.pid }));
+}
diff --git a/packages/desktop/src/main/server-exit-record.test.ts b/packages/desktop/src/main/server-exit-record.test.ts
index 43f3d72ce..5bd7176a7 100644
--- a/packages/desktop/src/main/server-exit-record.test.ts
+++ b/packages/desktop/src/main/server-exit-record.test.ts
@@ -3,7 +3,8 @@
* clock, and a capturing logger — the same injectable-deps posture as the
* sibling crash-detection tests. Covers the two arrival orders of the exit
* `code` and the process-gone `reason`, the correlation window that joins
- * them, and the fail-soft write path.
+ * them, the optional `signal` only the packaged spawn path observes, and the
+ * fail-soft write path.
*/
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
@@ -58,7 +59,7 @@ describe('createServerExitRecorder', () => {
const clock = makeClock();
const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
- recorder.recordExit({ lockDir, pid: 51502, code: 0 });
+ recorder.recordExit({ lockDir, pid: 51502, code: 0, observer: 'utility-process' });
const record = readRecord(lockDir);
expect(record.pid).toBe(51502);
@@ -72,11 +73,126 @@ describe('createServerExitRecorder', () => {
const clock = makeClock();
const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
- recorder.recordExit({ lockDir, pid: 999, code: null });
+ recorder.recordExit({ lockDir, pid: 999, code: null, observer: 'utility-process' });
expect(readRecord(lockDir).code).toBeNull();
});
+ test('a signal reaches the record verbatim', () => {
+ const lockDir = makeLockDir();
+ const clock = makeClock();
+ const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
+
+ recorder.recordExit({
+ lockDir,
+ pid: 4242,
+ code: null,
+ signal: 'SIGKILL',
+ observer: 'detached-spawn',
+ });
+
+ const record = readRecord(lockDir);
+ expect(record.signal).toBe('SIGKILL');
+ expect(record.code).toBeNull();
+ });
+
+ test('an exit reported without a signal records signal null', () => {
+ const lockDir = makeLockDir();
+ const clock = makeClock();
+ const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
+
+ // The dev `utilityProcess` exit event carries no signal, so its call site
+ // omits the field entirely.
+ recorder.recordExit({ lockDir, pid: 7, code: 0, observer: 'utility-process' });
+
+ const record = readRecord(lockDir);
+ expect(record.signal).toBeNull();
+ expect(record.pid).toBe(7);
+ expect(record.code).toBe(0);
+ });
+
+ test('the record names which host observed the death', () => {
+ const lockDir = makeLockDir();
+ const clock = makeClock();
+ const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
+
+ // Without this a triager cannot tell a `reason: null` that means "the
+ // correlation window produced nothing" from one that means "no such
+ // classification can exist for this process".
+ recorder.recordExit({ lockDir, pid: 7, code: 0, observer: 'utility-process' });
+ expect(readRecord(lockDir).observer).toBe('utility-process');
+
+ recorder.recordExit({
+ lockDir,
+ pid: 8,
+ code: null,
+ signal: 'SIGKILL',
+ observer: 'detached-spawn',
+ });
+ expect(readRecord(lockDir).observer).toBe('detached-spawn');
+ });
+
+ test('a later noteGoneReason patch preserves the signal', () => {
+ const lockDir = makeLockDir();
+ const clock = makeClock();
+ const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
+
+ recorder.recordExit({
+ lockDir,
+ pid: 1,
+ code: null,
+ signal: 'SIGKILL',
+ observer: 'utility-process',
+ });
+ clock.tick(100);
+ recorder.noteGoneReason('killed');
+
+ const record = readRecord(lockDir);
+ expect(record.reason).toBe('killed');
+ expect(record.signal).toBe('SIGKILL');
+ });
+
+ test('a detached-path record declines a reason that arrived before it', () => {
+ const lockDir = makeLockDir();
+ const clock = makeClock();
+ const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
+
+ // Packaged shape: the project server is a plain spawn child, so every
+ // `child-process-gone` reason that can reach the recorder describes some
+ // other Utility (a pty-host, say). Adopting one would label this death
+ // with a different process's cause.
+ recorder.noteGoneReason('killed');
+ clock.tick(50);
+ recorder.recordExit({
+ lockDir,
+ pid: 1,
+ code: null,
+ signal: 'SIGTERM',
+ observer: 'detached-spawn',
+ });
+
+ expect(readRecord(lockDir).reason).toBeNull();
+ expect(readRecord(lockDir).signal).toBe('SIGTERM');
+ });
+
+ test('a reason arriving after a detached-path record does not patch it', () => {
+ const lockDir = makeLockDir();
+ const clock = makeClock();
+ const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
+
+ recorder.recordExit({
+ lockDir,
+ pid: 1,
+ code: 0,
+ signal: null,
+ observer: 'detached-spawn',
+ });
+ clock.tick(50);
+ recorder.noteGoneReason('clean-exit');
+
+ expect(readRecord(lockDir).reason).toBeNull();
+ });
+
test('noteGoneReason before recordExit attaches the reason', () => {
const lockDir = makeLockDir();
const clock = makeClock();
@@ -84,7 +200,7 @@ describe('createServerExitRecorder', () => {
recorder.noteGoneReason('oom');
clock.tick(50);
- recorder.recordExit({ lockDir, pid: 1, code: null });
+ recorder.recordExit({ lockDir, pid: 1, code: null, observer: 'utility-process' });
expect(readRecord(lockDir).reason).toBe('oom');
});
@@ -94,7 +210,7 @@ describe('createServerExitRecorder', () => {
const clock = makeClock();
const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
- recorder.recordExit({ lockDir, pid: 1, code: 1 });
+ recorder.recordExit({ lockDir, pid: 1, code: 1, observer: 'utility-process' });
expect(readRecord(lockDir).reason).toBeNull();
clock.tick(100);
@@ -114,7 +230,7 @@ describe('createServerExitRecorder', () => {
recorder.noteGoneReason('killed');
clock.tick(3_001);
- recorder.recordExit({ lockDir, pid: 1, code: null });
+ recorder.recordExit({ lockDir, pid: 1, code: null, observer: 'utility-process' });
expect(readRecord(lockDir).reason).toBeNull();
});
@@ -124,7 +240,7 @@ describe('createServerExitRecorder', () => {
const clock = makeClock();
const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
- recorder.recordExit({ lockDir, pid: 1, code: 0 });
+ recorder.recordExit({ lockDir, pid: 1, code: 0, observer: 'utility-process' });
clock.tick(3_001);
recorder.noteGoneReason('clean-exit');
@@ -136,9 +252,9 @@ describe('createServerExitRecorder', () => {
const clock = makeClock();
const recorder = createServerExitRecorder({ now: clock.now, logger: makeLogger().logger });
- recorder.recordExit({ lockDir, pid: 1, code: 0 });
+ recorder.recordExit({ lockDir, pid: 1, code: 0, observer: 'utility-process' });
clock.tick(60_000);
- recorder.recordExit({ lockDir, pid: 2, code: 1 });
+ recorder.recordExit({ lockDir, pid: 2, code: 1, observer: 'utility-process' });
const record = readRecord(lockDir);
expect(record.pid).toBe(2);
@@ -156,8 +272,45 @@ describe('createServerExitRecorder', () => {
const { warnings, logger } = makeLogger();
const recorder = createServerExitRecorder({ now: clock.now, logger });
- expect(() => recorder.recordExit({ lockDir: badLockDir, pid: 1, code: 1 })).not.toThrow();
+ expect(() =>
+ recorder.recordExit({
+ lockDir: badLockDir,
+ pid: 1,
+ code: 1,
+ observer: 'utility-process',
+ }),
+ ).not.toThrow();
expect(warnings).toHaveLength(1);
expect(warnings[0]?.payload.event).toBe('server-exit-record.write-failed');
});
+
+ test('a throwing warn sink still cannot escape the write path', () => {
+ const parent = makeLockDir();
+ const filePath = join(parent, 'not-a-dir');
+ writeFileSync(filePath, 'x');
+ const badLockDir = join(filePath, 'nested');
+ const clock = makeClock();
+ // When the state dir is unwritable the desktop logger's own lazily-created
+ // `~/.ok/logs` often is too. Both failing at once must still not throw:
+ // `recordExit` runs inside an `'exit'` listener, so an escape becomes an
+ // `uncaughtException` and Electron's fatal dialog — the exact masking of a
+ // server death this fail-soft path exists to prevent.
+ const recorder = createServerExitRecorder({
+ now: clock.now,
+ logger: {
+ warn: () => {
+ throw new Error("EACCES: permission denied, mkdir '/x/.ok/logs'");
+ },
+ },
+ });
+
+ expect(() =>
+ recorder.recordExit({
+ lockDir: badLockDir,
+ pid: 1,
+ code: 1,
+ observer: 'utility-process',
+ }),
+ ).not.toThrow();
+ });
});
diff --git a/packages/desktop/src/main/server-exit-record.ts b/packages/desktop/src/main/server-exit-record.ts
index babeeaf3a..f5f8eaf06 100644
--- a/packages/desktop/src/main/server-exit-record.ts
+++ b/packages/desktop/src/main/server-exit-record.ts
@@ -23,6 +23,26 @@
* handlers never interleave, and a lone desktop rarely tears down two distinct
* servers within the same window. On a wider overlap the `reason` may attach to
* the wrong record, so it is advisory; the `code` and timing are authoritative.
+ *
+ * A third observer writes here in packaged builds, where the server is a plain
+ * `child_process.spawn` child rather than a `utilityProcess`: the detached-spawn
+ * exit observer (`server-exit-observer.ts`). Two consequences.
+ *
+ * Its `'exit'` carries the POSIX `signal` as well as the code. That is the field
+ * a SIGKILL needs: it leaves `code === null`, so without the signal the death
+ * the record exists to describe is the one it cannot tell apart from an
+ * unexplained exit. The dev `utilityProcess` path has no signal to give, so it
+ * stays optional and records as null there.
+ *
+ * And that child can never be the subject of a `child-process-gone` reason —
+ * an ordinary OS process is not classifiable as `Utility`, so every reason that
+ * can reach the recorder in a packaged build belongs to some *other* utility
+ * (a pty-host, say). Which is why each producer names itself on the record
+ * (`observer`) rather than passing a correlate-or-not preference: whether a
+ * death may carry a reason follows from how the process was created, so the
+ * recorder derives the rule from that fact and the record carries it forward.
+ * A `detached-spawn` record's `reason: null` therefore means "not observable on
+ * this path", not "the correlation window missed it".
*/
import { mkdirSync, writeFileSync } from 'node:fs';
@@ -32,22 +52,141 @@ import { SERVER_EXIT_LOG } from '@inkeep/open-knowledge-core';
/** How long a `code` and a `reason` for the same death may be apart. */
const REASON_CORRELATION_WINDOW_MS = 3_000;
+/**
+ * Which host observed the death. Determines how a null `reason` and a null
+ * `signal` read, and whether a `child-process-gone` reason may be joined at
+ * all — so it is the fact, not a caller preference, and every writer states it.
+ *
+ * - `utility-process` — the dev/test Electron `utilityProcess` fork. Reports a
+ * `code` but never a `signal`, and IS classifiable by Electron, so a reason
+ * may be correlated onto its record.
+ * - `detached-spawn` — the packaged plain `child_process.spawn` child. Reports
+ * both `code` and `signal`; an ordinary OS process can never be the subject
+ * of a `Utility` process-gone reason, so correlation is declined and `reason`
+ * is structurally null there.
+ */
+type ServerExitObserverHost = 'utility-process' | 'detached-spawn';
+
+/**
+ * Compile-time exhaustiveness guard for `ServerExitObserverHost` consumers. Per-DU
+ * helper rather than one shared `assertNever`, matching `assertNeverLinkTarget`
+ * (`packages/core/src/utils/link-targets.ts`) and `assertNeverDiskEvent`
+ * (`packages/server/src/file-watcher.ts`).
+ */
+function assertNeverObserverHost(value: never): never {
+ throw new Error(`Unhandled ServerExitObserverHost: ${JSON.stringify(value as unknown)}`);
+}
+
+/**
+ * Whether a death observed by this host may be joined to an
+ * `app.on('child-process-gone')` reason.
+ *
+ * A switch rather than `observer !== 'detached-spawn'` deliberately: the SPEC
+ * anticipates a third host (an attach-mode liveness poll), and under a negative
+ * check it would land silently on the correlatable side — inheriting exactly the
+ * unsafe default the `observer` discriminator replaced. A liveness poll is the
+ * worst case for that, since it can only ever observe `{code: null, signal: null}`,
+ * so a borrowed reason would be the record's only apparent content. Here a new
+ * member fails to compile until someone states its answer.
+ */
+function mayCorrelateGoneReason(observer: ServerExitObserverHost): boolean {
+ switch (observer) {
+ // Electron classifies its own `utilityProcess`, so the join describes this
+ // very child.
+ case 'utility-process':
+ return true;
+ // An ordinary OS process can never be the subject of a `Utility` reason, so
+ // every reason reaching the recorder here belongs to some other utility.
+ case 'detached-spawn':
+ return false;
+ default:
+ return assertNeverObserverHost(observer);
+ }
+}
+
export interface ServerExitRecord {
/** ISO timestamp of the exit the desktop host observed. */
at: string;
/** The server's pid, or null when the exit event carried none. */
pid: number | null;
- /** `utilityProcess` exit code; null when the process was killed by a signal. */
+ /**
+ * Exit code reported by whichever host observed the death; null when a signal
+ * killed the process.
+ *
+ * Not a fallback for a null `signal` on Windows. libuv terminates for every
+ * supported signal with `TerminateProcess(handle, 1)`, and the exit status it
+ * then reports is that literal 1 — so a SIGTERM, a SIGKILL escalation, a Task
+ * Manager "End task" and a voluntary `exit(1)` are all `{code: 1, signal:
+ * null}` there. On Windows this record narrows to `code: 0` = orderly stop,
+ * anything else = unresolved.
+ */
code: number | null;
/**
- * Electron's `child-process-gone` reason, or null when no reason arrived in
- * the correlation window. `killed` covers an OS OOM-kill / SIGKILL; `crashed`
- * / `oom` a genuine in-process crash; `clean-exit` / `abnormal-exit` a
- * managed shutdown or a nonzero self-exit.
+ * POSIX signal name that killed the process (`SIGKILL`, `SIGTERM`, ...), or
+ * null when it exited on its own, when the exit event carried no signal, or
+ * when the observing host cannot report one (see `observer`). Absent on a
+ * record written before this field existed, which reads as unknown.
+ *
+ * POSIX-only, and narrower on Windows than "we killed it, so we know". libuv
+ * records the signal on the `uv_process_t` handle, and only `uv_process_kill`
+ * — i.e. `subprocess.kill()` on that same `ChildProcess` object — writes it.
+ * `process.kill(pid, signal)` routes through `uv_kill`, which opens a handle
+ * by pid and calls `TerminateProcess` without touching the child's handle.
+ * This desktop kills the detached server exclusively by pid (`killProbe` in
+ * `window-manager.ts`), so on Windows the field is null for *every* death it
+ * observes, including its own managed shutdowns. A null signal there carries
+ * no information about who ended the process.
+ */
+ signal?: string | null;
+ /**
+ * Which host observed this death. Says how the two nullable fields above and
+ * below read: on `detached-spawn` a null `reason` means "no such
+ * classification can exist for this process", while on `utility-process` it
+ * means "the correlation window produced nothing"; a null `signal` is never
+ * observable on `utility-process` at all. Absent on a record written before
+ * this field existed, which reads as unknown.
+ */
+ observer?: ServerExitObserverHost;
+ /**
+ * Electron's `child-process-gone` reason, or null — either because no reason
+ * arrived in the correlation window, or because none can exist for this
+ * `observer`. `killed` covers an OS OOM-kill / SIGKILL; `crashed` / `oom` a
+ * genuine in-process crash; `clean-exit` / `abnormal-exit` a managed shutdown
+ * or a nonzero self-exit; `launch-failed` / `integrity-failure` /
+ * `memory-eviction` round out Electron 43's set. Forwarded verbatim and never
+ * validated, and Electron adds values across releases — an unrecognised
+ * string is a newer classification, not a corrupt record.
*/
reason: string | null;
}
+/**
+ * What this module actually writes today, as opposed to what a reader may find.
+ * The optionality on `ServerExitRecord` is a *read* affordance for the add-only
+ * discipline — absent means "written before that field existed". Producing a
+ * record that omits them would therefore forge that signal, so the write path
+ * requires both and the invariant is a type fact rather than an inspection one.
+ */
+type WrittenServerExitRecord = ServerExitRecord &
+ Required<Pick<ServerExitRecord, 'signal' | 'observer'>>;
+
+/**
+ * The one declaration of a `recordExit` payload. Both producers and the
+ * `WindowManagerDeps` dep narrow from this (`Pick<>`) rather than restating it,
+ * because a restated shape drifts silently: the adapters forward a typed
+ * variable rather than a fresh object literal, and TypeScript's excess-property
+ * check does not apply to variables — a renamed field on one copy compiles
+ * clean and the value is dropped.
+ */
+export interface ServerExitInfo {
+ lockDir: string;
+ pid: number | null;
+ code: number | null;
+ /** Absent from the dev path, which has no signal to report; records as null. */
+ signal?: string | null;
+ observer: ServerExitObserverHost;
+}
+
interface ServerExitRecorderLogger {
warn(payload: Record<string, unknown>, msg: string): void;
}
@@ -60,11 +199,15 @@ export interface ServerExitRecorderDeps {
export interface ServerExitRecorder {
/**
* Record an observed server exit. Called from the window manager's
- * `utilityProcess.on('exit')` handler, which knows the `lockDir`, pid, and
- * exit code. Attaches a `reason` if `noteGoneReason` fired for the same death
- * moments earlier.
+ * `utilityProcess.on('exit')` handler (dev/test) and from the packaged
+ * detached-spawn exit observer (`server-exit-observer.ts`); both know the
+ * `lockDir`, pid, and exit code. Attaches a `reason` if `noteGoneReason`
+ * fired for the same death moments earlier — but only for an `observer` whose
+ * child Electron can classify. A `detached-spawn` record opts out of that
+ * join in both directions (no reason is read at write time, and no later one
+ * may patch the record), so a foreign utility's reason is never adopted.
*/
- recordExit(info: { lockDir: string; pid: number | null; code: number | null }): void;
+ recordExit(info: ServerExitInfo): void;
/**
* Note Electron's classified process-gone reason. Called from
* `app.on('child-process-gone')`, which has the reason but no lockDir. Patches
@@ -74,37 +217,60 @@ export interface ServerExitRecorder {
}
export function createServerExitRecorder(deps: ServerExitRecorderDeps): ServerExitRecorder {
- let lastExit: { lockDir: string; record: ServerExitRecord; atMs: number } | null = null;
+ let lastExit: { lockDir: string; record: WrittenServerExitRecord; atMs: number } | null = null;
let lastReason: { reason: string; atMs: number } | null = null;
- function write(lockDir: string, record: ServerExitRecord): void {
+ function write(lockDir: string, record: WrittenServerExitRecord): void {
try {
mkdirSync(lockDir, { recursive: true });
writeFileSync(join(lockDir, SERVER_EXIT_LOG), `${JSON.stringify(record, null, 2)}\n`);
} catch (err) {
// Best-effort diagnostic — a server death must never be masked by an
// unwritable state dir. The bundle simply won't carry the record.
- deps.logger.warn(
- {
- event: 'server-exit-record.write-failed',
- err,
- },
- 'could not record server exit',
- );
+ //
+ // The warn is itself guarded because the desktop logger's first use
+ // lazily `mkdirSync`s `~/.ok/logs`: when the state dir is unwritable the
+ // log dir often is too, and a throw here would escape into the
+ // `'exit'` listener that called us — an `EventEmitter` callback, so an
+ // `uncaughtException` — turning "we could not write the record" into
+ // Electron's fatal error dialog. That is exactly the masking this catch
+ // exists to prevent.
+ try {
+ deps.logger.warn(
+ {
+ event: 'server-exit-record.write-failed',
+ err,
+ },
+ 'could not record server exit',
+ );
+ } catch {}
}
}
return {
- recordExit({ lockDir, pid, code }): void {
+ recordExit({ lockDir, pid, code, signal = null, observer }): void {
const now = deps.now();
const nowMs = now.getTime();
+ const correlatable = mayCorrelateGoneReason(observer);
const reason =
- lastReason !== null && nowMs - lastReason.atMs <= REASON_CORRELATION_WINDOW_MS
+ correlatable &&
+ lastReason !== null &&
+ nowMs - lastReason.atMs <= REASON_CORRELATION_WINDOW_MS
? lastReason.reason
: null;
- const record: ServerExitRecord = { at: now.toISOString(), pid, code, reason };
+ const record: WrittenServerExitRecord = {
+ at: now.toISOString(),
+ pid,
+ code,
+ signal,
+ observer,
+ reason,
+ };
write(lockDir, record);
- lastExit = { lockDir, record, atMs: nowMs };
+ // Clearing rather than storing is the other half of the opt-out: leaving
+ // this record in the slot would let the next `noteGoneReason` patch a
+ // reason onto it from behind.
+ lastExit = correlatable ? { lockDir, record, atMs: nowMs } : null;
},
noteGoneReason(reason): void {
@@ -117,7 +283,7 @@ export function createServerExitRecorder(deps: ServerExitRecorderDeps): ServerEx
lastExit.record.reason === null &&
nowMs - lastExit.atMs <= REASON_CORRELATION_WINDOW_MS
) {
- const patched: ServerExitRecord = { ...lastExit.record, reason };
+ const patched: WrittenServerExitRecord = { ...lastExit.record, reason };
write(lastExit.lockDir, patched);
lastExit = { ...lastExit, record: patched };
}
diff --git a/packages/desktop/src/main/window-manager.ts b/packages/desktop/src/main/window-manager.ts
index ef81c8365..33152d551 100644
--- a/packages/desktop/src/main/window-manager.ts
+++ b/packages/desktop/src/main/window-manager.ts
@@ -39,6 +39,7 @@ import type { OkServerRestartOutcome } from '../shared/bridge-contract.ts';
import { registerPendingDelivery } from '../shared/ipc-send.ts';
import type { AssetOpenResult } from './asset-allowlist.ts';
import { attachAssetSafetyNet } from './asset-safety-net.ts';
+import type { ServerExitInfo } from './server-exit-record.ts';
import type { ShowGateRegistry } from './show-gate.ts';
import type { RestoredWindow } from './state-store.ts';
import type { ShareDeepLinkBranchSwitchPayload } from './url-scheme.ts';
@@ -879,8 +880,14 @@ export interface WindowManagerDeps {
* Record why the server just exited to `<lockDir>/last-server-exit.json`, so
* a later bug-report bundle can tell an unexpected death from a managed
* shutdown. No-op when omitted (tests, web). See `server-exit-record.ts`.
+ *
+ * Narrowed from the recorder's own payload rather than restated, so the two
+ * cannot drift: the `utilityProcess` exit event this is called from carries
+ * no signal and does not name the observing host, so `index.ts`'s adapter
+ * supplies both. The record's `signal` is only ever filled by the packaged
+ * detached-spawn observer.
*/
- recordServerExit?(info: { lockDir: string; pid: number | null; code: number | null }): void;
+ recordServerExit?(info: Pick<ServerExitInfo, 'lockDir' | 'pid' | 'code'>): void;
/**
* Startup-instrumentation hooks (desktop launch waterfall). All optional and
* no-op when omitted (tests, web). Wired by `index.ts` only for the FIRST
diff --git a/packages/desktop/tests/integration/detached-lifecycle.test.ts b/packages/desktop/tests/integration/detached-lifecycle.test.ts
index fe672d98c..dcf28e6f7 100644
--- a/packages/desktop/tests/integration/detached-lifecycle.test.ts
+++ b/packages/desktop/tests/integration/detached-lifecycle.test.ts
@@ -14,25 +14,31 @@
* cwd: contentDir,
* }).unref()
*
- * What the test asserts:
+ * What the tests assert:
* 1. The CLI bootstraps to a writeable `server.lock` with a non-zero port.
* 2. The spawned pid is in a process group it owns (`pgid === pid`).
* This is the OS-level detachment property that decouples the server
* from Electron's process tree — closing the editor window or
* quitting Electron does not cascade SIGHUP/SIGTERM through this
* process group.
+ * 3. An unref-ed detached child's death still reaches the parent, and the
+ * parent turns it into a `last-server-exit.json` on disk naming the
+ * exit code and the signal.
*
- * Cleanup uses SIGKILL rather than SIGTERM because Bun's SIGTERM-handler
- * timing is known-flaky (see CLAUDE.md WARN — Bun's SIGTERM handling).
- * Production code already escalates to SIGKILL after
- * `DEFAULT_SIGTERM_GRACE_MS` via `stopAllOwnedServers`, so the cleanup
- * path is not part of this test's assertion surface.
+ * Cleanup uses SIGKILL rather than SIGTERM-then-poll: production already
+ * escalates to SIGKILL after `DEFAULT_SIGTERM_GRACE_MS` (`stopAllOwnedServers`),
+ * a graceful-drain test is a separate concern, and a slow drain here would
+ * only add flake to assertions that are not about shutdown.
*
- * The test runs against the actually-built `packages/cli/dist/cli.mjs`
- * (which the worktree's `bun install` produces transitively). When the
- * build is absent, the test fails loud — `bun run check` must run after
- * a successful build, so the absence of the CLI artifact IS a regression
- * signal worth surfacing.
+ * The test runs against the actually-built `packages/cli/dist/cli.mjs`. No
+ * install hook produces it — `packages/cli` has no `prepare`/`postinstall`, so
+ * `pnpm install` alone leaves it absent. The producer is this package's turbo
+ * `test` task, whose `dependsOn: ["^build"]` builds `@inkeep/open-knowledge`
+ * because `packages/desktop` depends on it via `workspace:*`. A bare
+ * `vitest run --filter` bypasses that; run `pnpm build` from `packages/cli`
+ * first, as the throw below says. When the build is absent the test fails loud,
+ * because the absence of the CLI artifact IS a regression signal worth
+ * surfacing.
*/
import { spawn } from 'node:child_process';
@@ -42,8 +48,14 @@ import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
import { fileURLToPath } from 'node:url';
-import { isProcessAlive } from '@inkeep/open-knowledge-server';
+import { SERVER_EXIT_LOG } from '@inkeep/open-knowledge-core';
+import { getLocalDir, isProcessAlive } from '@inkeep/open-knowledge-server';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
+import { attachServerExitObserver } from '../../src/main/server-exit-observer.ts';
+import {
+ createServerExitRecorder,
+ type ServerExitRecord,
+} from '../../src/main/server-exit-record.ts';
// Resolve the built CLI relative to this test file so the test runs from
// anywhere (root, packages/desktop, worktree).
@@ -116,7 +128,7 @@ describe('detached-server lifecycle integration', () => {
test('spawn-detached CLI is in its own process group + survives parent exit', async () => {
if (!existsSync(CLI_MJS_PATH)) {
throw new Error(
- `CLI dist not built at ${CLI_MJS_PATH}. Run 'bun run build' from packages/cli first.`,
+ `CLI dist not built at ${CLI_MJS_PATH}. Run 'pnpm build' from packages/cli first.`,
);
}
const lockDir = resolve(tmpDir, '.ok', 'local');
@@ -169,15 +181,11 @@ describe('detached-server lifecycle integration', () => {
expect(pgid).not.toBe(myPgid);
}
} finally {
- // Cleanup — force-kill the detached server. We use SIGKILL rather
- // than SIGTERM-then-poll because Bun's signal-handler timing is
- // known-flaky under SIGTERM (per CLAUDE.md WARN: "bun does not
- // always release the lock cleanly on SIGTERM — the bootServer
- // destroy chain races signal-exit"), and a flaky cleanup would
- // mask the actual invariant assertions above. Production code
- // escalates to SIGKILL after `DEFAULT_SIGTERM_GRACE_MS` already
- // (`stopAllOwnedServers` does this); the integration test for
- // graceful drain is a separate concern.
+ // Cleanup — force-kill the detached server. SIGKILL rather than
+ // SIGTERM-then-poll: production escalates to SIGKILL after
+ // `DEFAULT_SIGTERM_GRACE_MS` anyway (`stopAllOwnedServers`), the
+ // graceful-drain path is a separate test's concern, and waiting on a
+ // drain here would only let cleanup flake mask the assertions above.
if (lock !== null) {
try {
process.kill(lock.pid, 'SIGKILL');
@@ -256,4 +264,117 @@ describe('detached-server lifecycle integration', () => {
}
expect(exitRecord).toEqual({ code: null, signal: 'SIGKILL' });
}, 30_000);
+
+ /**
+ * Spawn a real detached child running `script`, wire it through the same
+ * `attachServerExitObserver` production calls (over a real
+ * `createServerExitRecorder`, registered before `unref()`), kill it with
+ * `killWith` (or let it exit on its own when null), and return the record
+ * that landed on disk plus everything the injected logger captured.
+ *
+ * Going through `attachServerExitObserver` rather than rebuilding the
+ * registration by hand is what makes the exactly-one-line assertion below a
+ * pin on production's wiring: a second listener added inside that function
+ * would double the record and the log line here. What it still cannot reach
+ * is that `index.ts` calls it at all — the bypass-pin in
+ * `server-exit-wiring.test.ts` covers that.
+ *
+ * `lockDir` is derived with the same `getLocalDir` production uses rather
+ * than a hand-written `.ok/local`, so the record is asserted at the path the
+ * bundle collector harvests instead of at a duplicate of it.
+ */
+ async function recordDeathOf(
+ script: string,
+ killWith: NodeJS.Signals | null,
+ ): Promise<{
+ record: ServerExitRecord;
+ infoLines: Array<Record<string, unknown>>;
+ warnings: string[];
+ }> {
+ const lockDir = getLocalDir(tmpDir);
+ const child = spawn(process.execPath, ['-e', script], { detached: true, stdio: 'ignore' });
+ await new Promise<void>((res, rej) => {
+ child.once('spawn', res);
+ child.once('error', rej);
+ });
+
+ const warnings: string[] = [];
+ const infoLines: Array<Record<string, unknown>> = [];
+ const recorder = createServerExitRecorder({
+ now: () => new Date(),
+ logger: { warn: (_payload, msg) => warnings.push(msg) },
+ });
+
+ // Production order: registered before unref(), and the pid read through the
+ // child, both of which `attachServerExitObserver` owns.
+ attachServerExitObserver(child, {
+ lockDir,
+ recordExit: (info) => {
+ recorder.recordExit(info);
+ },
+ logger: { info: (payload) => infoLines.push(payload) },
+ });
+ child.unref();
+
+ if (killWith !== null) process.kill(child.pid as number, killWith);
+
+ const recordPath = join(lockDir, SERVER_EXIT_LOG);
+ const deadline = Date.now() + 10_000;
+ let lastParseError: unknown = null;
+ while (Date.now() < deadline) {
+ if (existsSync(recordPath)) {
+ try {
+ const record = JSON.parse(readFileSync(recordPath, 'utf-8')) as ServerExitRecord;
+ return { record, infoLines, warnings };
+ } catch (err) {
+ // Partial write — wait and retry, same posture as `waitForLock`.
+ // Retained so a serialization regression reports as "never parsed"
+ // rather than as the file never showing up.
+ lastParseError = err;
+ }
+ }
+ await wait(25);
+ }
+ throw new Error(
+ lastParseError === null
+ ? `server exit record did not appear at ${recordPath}`
+ : `server exit record at ${recordPath} never parsed: ${
+ lastParseError instanceof Error ? lastParseError.message : String(lastParseError)
+ }`,
+ );
+ }
+
+ test('a SIGKILLed detached child leaves a record naming the signal', async () => {
+ const { record, infoLines, warnings } = await recordDeathOf(
+ 'setTimeout(() => {}, 60000)',
+ 'SIGKILL',
+ );
+
+ expect(record.code).toBeNull();
+ expect(record.signal).toBe('SIGKILL');
+ expect(record.pid).toBeGreaterThan(0);
+ expect(new Date(record.at).toISOString()).toBe(record.at);
+ // One death, one line — not zero, and not doubled by the registration.
+ expect(infoLines).toHaveLength(1);
+ expect(infoLines[0]).toMatchObject({
+ event: 'server-exit.detached-child-exited',
+ lockDir: getLocalDir(tmpDir),
+ code: null,
+ signal: 'SIGKILL',
+ });
+ // No `child-process-gone` reason can describe a plain spawn child, so the
+ // detached path records none rather than borrowing another utility's, and
+ // the record says which host observed it so a reader can tell that null
+ // from a correlation window that produced nothing.
+ expect(record.reason).toBeNull();
+ expect(record.observer).toBe('detached-spawn');
+ expect(warnings).toEqual([]);
+ }, 30_000);
+
+ test('a cleanly exiting detached child is distinguishable on disk', async () => {
+ const { record } = await recordDeathOf('process.exit(0)', null);
+
+ expect(record.code).toBe(0);
+ expect(record.signal).toBeNull();
+ }, 30_000);
});
diff --git a/packages/desktop/tests/integration/server-exit-wiring.test.ts b/packages/desktop/tests/integration/server-exit-wiring.test.ts
new file mode 100644
index 000000000..c14be8339
--- /dev/null
+++ b/packages/desktop/tests/integration/server-exit-wiring.test.ts
@@ -0,0 +1,83 @@
+/**
+ * Bypass-pin — `index.ts` must still wire the packaged detached server's exit
+ * to the observer, exactly once.
+ *
+ * The mapping, the record shape and the registration are all covered by tests
+ * that call the production functions directly (`server-exit-observer.test.ts`,
+ * `server-exit-record.test.ts`, `detached-lifecycle.test.ts`). Two facts those
+ * cannot reach: that `spawnDetachedServer` calls `attachServerExitObserver` at
+ * all, and that it calls it once, on the spawned child. `index.ts` is ~9,000
+ * lines, imports `electron` at module scope so it cannot be imported by a test,
+ * and the spawn closure is actively reworked — a rebase that drops the call,
+ * duplicates it, reorders it after an early return, or swaps the shared
+ * `getServerExitRecorder()` singleton for a fresh recorder leaves every other
+ * test green and the diagnostic dead, resurfacing months later as a triager
+ * opening a packaged bundle and finding the file absent again.
+ *
+ * A tight grep, not a structural parse — same posture and rationale as the
+ * bypass-pin in `dock-visibility.test.ts`, which guards the same spawn closure.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+
+const indexTsPath = resolve(fileURLToPath(new URL('../../src/main/index.ts', import.meta.url)));
+const src = readFileSync(indexTsPath, 'utf-8');
+
+const FIX = (what: string): string =>
+ `\n[server-exit] ${what}\n\n` +
+ `The packaged build spawns the project server with plain child_process.spawn, which no other\n` +
+ `mechanism observes: app.on('child-process-gone') guards on details.type === 'Utility' (structurally\n` +
+ `unreachable for an ordinary OS process) and the utilityProcess exit handler that records the death in\n` +
+ `dev never runs. Without this wiring every packaged bug report is missing last-server-exit.json — the\n` +
+ `one file that answers "did the server crash, or was it shut down on purpose". The full rationale is\n` +
+ `in the header of packages/desktop/src/main/server-exit-observer.ts.\n`;
+
+describe('packaged detached-server exit wiring (bypass-pin)', () => {
+ test('index.ts registers the exit observer on the spawned child, exactly once', () => {
+ // Anchored on `childRef`: an unanchored match would accept an attach to any
+ // handle, and a `utilityProcess` satisfies `ObservableChild` structurally —
+ // so that mis-wire would type-check and ship a record describing a
+ // pty-host's death as the project server's. The count is what catches a
+ // duplicated call, which would double both the record and the log line.
+ const calls = src.match(/attachServerExitObserver\s*\(\s*childRef\b/g) ?? [];
+ expect(
+ calls.length,
+ FIX(
+ `index.ts has ${calls.length} \`attachServerExitObserver(childRef, …)\` call(s); expected exactly 1.`,
+ ),
+ ).toBe(1);
+ });
+
+ test('the observer records through the shared recorder singleton', () => {
+ // A fresh `createServerExitRecorder()` here would still write records, but
+ // would break the reason-correlation slot `app.on('child-process-gone')`
+ // patches through and would double the recorder's state.
+ const wiring =
+ /attachServerExitObserver\s*\([\s\S]{0,600}?getServerExitRecorder\(\)\.recordExit/;
+ expect(
+ src,
+ FIX('the exit observer no longer records through getServerExitRecorder().'),
+ ).toMatch(wiring);
+ });
+
+ test('the observer logs on the server-exit subsystem', () => {
+ const wiring = /attachServerExitObserver\s*\([\s\S]{0,600}?getLogger\(['"]server-exit['"]\)/;
+ expect(src, FIX("the exit observer's logger is no longer getLogger('server-exit').")).toMatch(
+ wiring,
+ );
+ });
+
+ test('the listener is still registered before unref()', () => {
+ // `unref()` releases the event-loop reference, not listeners, so this is not
+ // a correctness requirement on its own — it is pinned because an acceptance
+ // criterion states it, and because keeping the two adjacent is what makes
+ // the spawn site readable.
+ const attachAt = src.indexOf('attachServerExitObserver(childRef');
+ const unrefAt = src.indexOf('childRef.unref()');
+ expect(unrefAt, FIX('childRef.unref() call not found.')).toBeGreaterThan(-1);
+ expect(attachAt, FIX('the exit observer is registered after unref().')).toBeLessThan(unrefAt);
+ });
+});