Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

Make config race tests wait for progress and clean up writers (#5785)

Nick Gomez67b2db62fb09
diff --git a/knip.config.ts b/knip.config.ts
index d3638888e..65f0e8807 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -147,15 +147,11 @@ 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'],
- ignoreDependencies: [
- 'yjs',
- ],
+ ignoreDependencies: ['yjs'],
},
'packages/desktop': {
entry: [
diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
index 4549c74b3..a50b00123 100644
--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts
@@ -1,4 +1,3 @@
-
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
index 4fc2c11f9..6fcdc23f2 100644
--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { normalizeBridge } from '@inkeep/open-knowledge-core';
import { updateYFragment } from '@tiptap/y-tiptap';
diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.ts
index 9f2f6feb6..40b5cdfd6 100644
--- a/packages/app/tests/integration/interior-edit-freshness.test.ts
+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
index 2a085742b..93666af70 100644
--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.ts
index 878d5196b..867598d34 100644
--- a/packages/app/tests/integration/producer-guard-wiring.test.ts
+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts
@@ -1,4 +1,3 @@
-
import { setTimeout as wait } from 'node:timers/promises';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
index 4ada3cf26..0970ac12f 100644
--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts
@@ -1,4 +1,3 @@
-
import { randomUUID } from 'node:crypto';
import { afterEach, describe, expect, test } from 'vitest';
import { agentWriteMd, createTestServer, type TestServer } from './test-harness';
diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
index cbe2b705f..b632185e1 100644
--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts
@@ -1,4 +1,3 @@
-
import { execFileSync } from 'node:child_process';
import { randomUUID } from 'node:crypto';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
index 89bc9b4d9..c530ce4ba 100644
--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts
@@ -1,4 +1,3 @@
-
import { randomUUID } from 'node:crypto';
import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';
import type * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.ts
index a78aeb0e4..d3767adc9 100644
--- a/packages/app/tests/integration/undo-after-rollback.test.ts
+++ b/packages/app/tests/integration/undo-after-rollback.test.ts
@@ -1,4 +1,3 @@
-
import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.ts
index e7cc69c3f..b076f955c 100644
--- a/packages/app/tests/integration/undo-recycle-reset.test.ts
+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts
@@ -1,4 +1,3 @@
-
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.ts
index 9ddcd0730..7935e35f8 100644
--- a/packages/app/tests/integration/undo-rederive-survival.test.ts
+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts
@@ -1,4 +1,3 @@
-
import { prependFrontmatter } from '@inkeep/open-knowledge-core';
import { Plugin, PluginKey } from '@tiptap/pm/state';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/cli/tests/integration/_helpers/config-race-lifetime.test.ts b/packages/cli/tests/integration/_helpers/config-race-lifetime.test.ts
new file mode 100644
index 000000000..9f5affb36
--- /dev/null
+++ b/packages/cli/tests/integration/_helpers/config-race-lifetime.test.ts
@@ -0,0 +1,262 @@
+import { EventEmitter } from 'node:events';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PassThrough } from 'node:stream';
+import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest';
+import {
+ runConfigWriters,
+ type SpawnWriter,
+ spawnConfigWriter,
+} from './config-race.test-helper.ts';
+
+class ControlledWriter extends EventEmitter {
+ stderr = new PassThrough();
+ pid: number | undefined = 10_000;
+ exitCode: number | null = null;
+ signalCode: NodeJS.Signals | null = null;
+ signals: NodeJS.Signals[] = [];
+
+ kill(signal: NodeJS.Signals) {
+ this.signals.push(signal);
+ return true;
+ }
+
+ complete() {
+ this.exitCode = 0;
+ this.emit('exit', 0);
+ this.emit('close', 0);
+ }
+
+ terminate(signal: NodeJS.Signals) {
+ this.signalCode = signal;
+ this.emit('exit', null, signal);
+ this.emit('close', null, signal);
+ }
+}
+
+function arrangeWriters(count: number, signal?: AbortSignal) {
+ const children = Array.from({ length: count }, () => new ControlledWriter());
+ const keys = children.map((_, index) => `writer-${index}`);
+ const spawnWriter: SpawnWriter = (_path, key) => children[keys.indexOf(key)];
+ const result = runConfigWriters('/owned/config.json', keys, { spawnWriter, signal }).then(
+ (outcomes) => ({ status: 'passed' as const, outcomes }),
+ (error: unknown) => ({ status: 'failed' as const, error }),
+ );
+ return { children, result };
+}
+
+async function failureOf(result: ReturnType<typeof arrangeWriters>['result']) {
+ const settled = await result;
+ expect(settled.status).toBe('failed');
+ return settled.status === 'failed' ? settled.error : undefined;
+}
+
+function expectWriterFailure(error: unknown, writer: string, cause: Error) {
+ expect(error).toBeInstanceOf(Error);
+ expect((error as Error).message).toContain(writer);
+ expect((error as Error).cause).toBe(cause);
+}
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+describe('config writer cohort lifetime', () => {
+ it('does not publish completion before child streams close', async () => {
+ vi.useFakeTimers();
+ const { children, result } = arrangeWriters(1);
+ let settled = false;
+ void result.then(() => {
+ settled = true;
+ });
+ children[0].emit('exit', 0);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(settled).toBe(false);
+ children[0].emit('close', 0);
+ expect((await result).status).toBe('passed');
+ });
+
+ it('settles every acquired child before reporting a spawn error', async () => {
+ vi.useFakeTimers();
+ const { children, result } = arrangeWriters(2);
+ let settled = false;
+ void result.then(() => {
+ settled = true;
+ });
+ const cause = new Error('writer could not start');
+ children[0].pid = undefined;
+ children[0].emit('error', cause);
+ children[0].emit('close', -2);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(settled).toBe(false);
+ expect(children[1].signals).toEqual(['SIGKILL']);
+ children[1].complete();
+ expectWriterFailure(await failureOf(result), 'writer-0: phase=spawned', cause);
+ });
+
+ it('attributes a writer error to that writer with its last phase and stderr', async () => {
+ vi.useFakeTimers();
+ const { children, result } = arrangeWriters(2);
+ const cause = new Error('channel closed');
+ children[1].emit('message', 'started');
+ children[1].stderr.write('lock busy');
+ children[1].emit('error', cause);
+ for (const child of children) child.terminate('SIGKILL');
+ expectWriterFailure(await failureOf(result), 'writer-1: phase=started stderr=lock busy', cause);
+ });
+
+ it('reports the terminating signal and last phase of a writer killed outside the cohort', async () => {
+ vi.useFakeTimers();
+ const { children, result } = arrangeWriters(1);
+ children[0].emit('message', 'started');
+ children[0].terminate('SIGKILL');
+ expect(children[0].signals).toEqual([]);
+ expect(await result).toMatchObject({
+ status: 'passed',
+ outcomes: [{ serverKey: 'writer-0', exitCode: null, signal: 'SIGKILL', phase: 'started' }],
+ });
+ });
+
+ it('accepts a cohort that keeps completing writers past the original total bound', async () => {
+ vi.useFakeTimers();
+ const { children, result } = arrangeWriters(20);
+ for (const child of children) {
+ await vi.advanceTimersByTimeAsync(2_000);
+ child.complete();
+ }
+ expect(await result).toMatchObject({ status: 'passed' });
+ expect(children.flatMap((child) => child.signals)).toEqual([]);
+ });
+
+ it('stops an idle cohort and joins its close events before rejecting', async () => {
+ vi.useFakeTimers();
+ const { children, result } = arrangeWriters(2);
+ let settled = false;
+ void result.then(() => {
+ settled = true;
+ });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(children.map((child) => child.signals)).toEqual([['SIGKILL'], ['SIGKILL']]);
+ expect(settled).toBe(false);
+ for (const child of children) child.complete();
+ expect(await result).toMatchObject({
+ status: 'failed',
+ error: new Error(
+ 'Config writers made no progress for 30000ms:\nwriter-0: phase=spawned stderr=\nwriter-1: phase=spawned stderr=',
+ ),
+ });
+ });
+
+ it('counts new phases but never repeated messages as progress', async () => {
+ vi.useFakeTimers();
+ const { children, result } = arrangeWriters(1);
+ await vi.advanceTimersByTimeAsync(20_000);
+ children[0].emit('message', 'started');
+ await vi.advanceTimersByTimeAsync(20_000);
+ expect(children[0].signals).toEqual([]);
+ children[0].emit('message', 'started');
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(children[0].signals).toEqual(['SIGKILL']);
+ children[0].complete();
+ expect((await result).status).toBe('failed');
+ });
+
+ it('joins cancelled children and never signals a child that has exited', async () => {
+ vi.useFakeTimers();
+ const controller = new AbortController();
+ const { children, result } = arrangeWriters(2, controller.signal);
+ children[0].exitCode = 0;
+ children[0].emit('exit', 0);
+ controller.abort(new Error('test cancelled'));
+ expect(children.map((child) => child.signals)).toEqual([[], ['SIGKILL']]);
+ children[0].emit('close', 0);
+ children[1].complete();
+ expect(await result).toMatchObject({ status: 'failed', error: new Error('test cancelled') });
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('retains stderr delivered between exit and close', async () => {
+ vi.useFakeTimers();
+ const { children, result } = arrangeWriters(1);
+ children[0].exitCode = 1;
+ children[0].emit('exit', 1, null);
+ children[0].stderr.write('write failed');
+ children[0].emit('close', 1, null);
+ expect(await result).toEqual({
+ status: 'passed',
+ outcomes: [
+ {
+ serverKey: 'writer-0',
+ exitCode: 1,
+ signal: null,
+ phase: 'spawned',
+ stderr: 'write failed',
+ },
+ ],
+ });
+ });
+
+ it('does not start writers after cancellation', async () => {
+ const controller = new AbortController();
+ controller.abort(new Error('already cancelled'));
+ const spawnWriter = vi.fn<SpawnWriter>();
+ await expect(
+ runConfigWriters('/owned/config.json', ['writer'], {
+ spawnWriter,
+ signal: controller.signal,
+ }),
+ ).rejects.toThrow('already cancelled');
+ expect(spawnWriter).not.toHaveBeenCalled();
+ });
+
+ it('joins earlier children if spawning a later writer throws', async () => {
+ vi.useFakeTimers();
+ const child = new ControlledWriter();
+ const cause = new Error('spawn setup failed');
+ const spawnWriter: SpawnWriter = (_path, key) => {
+ if (key === 'later') throw cause;
+ return child;
+ };
+ const result = runConfigWriters('/owned/config.json', ['first', 'later'], {
+ spawnWriter,
+ }).catch((error: unknown) => error);
+ let settled = false;
+ void result.then(() => {
+ settled = true;
+ });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(settled).toBe(false);
+ expect(child.signals).toEqual(['SIGKILL']);
+ child.complete();
+ expectWriterFailure(await result, 'later: phase=spawned', cause);
+ });
+});
+
+it('joins real writer processes when their test is cancelled', async () => {
+ const controller = new AbortController();
+ const closed: string[] = [];
+ const spawned: ReturnType<typeof spawnConfigWriter>[] = [];
+ const root = mkdtempSync(join(tmpdir(), 'config-race-cancel-'));
+ const result = runConfigWriters(join(root, 'config.json'), ['first', 'second'], {
+ signal: controller.signal,
+ spawnWriter: (path, key) => {
+ const child = spawnConfigWriter(path, key);
+ spawned.push(child);
+ child.once('close', () => {
+ closed.push(key);
+ });
+ if (key === 'second') queueMicrotask(() => controller.abort(new Error('cancelled fixture')));
+ return child;
+ },
+ });
+ onTestFinished(async () => {
+ controller.abort();
+ await Promise.allSettled([result]);
+ rmSync(root, { recursive: true, force: true });
+ });
+ await expect(result).rejects.toThrow('cancelled fixture');
+ expect(spawned).toHaveLength(2);
+ expect(closed.sort()).toEqual(['first', 'second']);
+});
diff --git a/packages/cli/tests/integration/_helpers/config-race-worker.ts b/packages/cli/tests/integration/_helpers/config-race-worker.ts
index faae5f921..1db38b0fb 100644
--- a/packages/cli/tests/integration/_helpers/config-race-worker.ts
+++ b/packages/cli/tests/integration/_helpers/config-race-worker.ts
@@ -1,38 +1,40 @@
-#!/usr/bin/env -S npx tsx
-
-import { EDITOR_TARGETS } from '../../../src/commands/editors.ts';
-import { writeEditorMcpConfig } from '../../../src/commands/init.ts';
-
const [, , configPath, serverKey] = process.argv;
-if (!configPath || !serverKey) {
- process.stderr.write('config-race-worker: usage: <configPath> <serverKey>\n');
+if (!configPath || !serverKey || !process.send || !process.connected) {
+ process.stderr.write('config-race-worker: requires IPC and <configPath> <serverKey>\n');
process.exit(64);
}
-const baseTarget = EDITOR_TARGETS.cursor;
-const target = {
- ...baseTarget,
- configPath: () => configPath,
- serverName: () => serverKey,
-};
+const report = process.send.bind(process);
+report('started');
try {
- const result = await writeEditorMcpConfig(
- target,
- '',
- { mode: 'published', skipAvailabilityCheck: true },
- undefined,
- );
+ const [{ EDITOR_TARGETS }, { writeEditorMcpConfig }] = await Promise.all([
+ import('../../../src/commands/editors.ts'),
+ import('../../../src/commands/init.ts'),
+ ]);
+ const target = {
+ ...EDITOR_TARGETS.cursor,
+ configPath: () => configPath,
+ serverName: () => serverKey,
+ };
+ report('ready');
+ const result = writeEditorMcpConfig(target, '', {
+ mode: 'published',
+ skipAvailabilityCheck: true,
+ });
if (result.action === 'failed') {
process.stderr.write(
`config-race-worker(${process.pid}): writeEditorMcpConfig action=failed error=${result.error}\n`,
);
- process.exit(1);
+ process.exitCode = 1;
+ } else {
+ report('written');
+ process.exitCode = 0;
}
- process.exit(0);
} catch (err) {
process.stderr.write(
`config-race-worker(${process.pid}): unexpected throw: ${err instanceof Error ? err.message : String(err)}\n`,
);
- process.exit(1);
+ process.exitCode = 1;
}
+process.exit();
diff --git a/packages/cli/tests/integration/_helpers/config-race.test-helper.ts b/packages/cli/tests/integration/_helpers/config-race.test-helper.ts
new file mode 100644
index 000000000..6861af3d6
--- /dev/null
+++ b/packages/cli/tests/integration/_helpers/config-race.test-helper.ts
@@ -0,0 +1,141 @@
+import { type ChildProcess, spawn } from 'node:child_process';
+import { resolve } from 'node:path';
+
+type WriterProcess = Pick<
+ ChildProcess,
+ 'stderr' | 'on' | 'once' | 'kill' | 'pid' | 'exitCode' | 'signalCode'
+>;
+export type SpawnWriter = (configPath: string, serverKey: string) => WriterProcess;
+
+const WORKER_PATH = resolve(import.meta.dirname, 'config-race-worker.ts');
+const NO_PROGRESS_MS = 30_000;
+const PHASES = ['spawned', 'started', 'ready', 'written'];
+
+export function spawnConfigWriter(configPath: string, serverKey: string) {
+ return spawn(process.execPath, [WORKER_PATH, configPath, serverKey], {
+ stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
+ });
+}
+
+interface WorkerOutcome {
+ serverKey: string;
+ exitCode: number | null;
+ signal: NodeJS.Signals | null;
+ phase: string;
+ stderr: string;
+}
+
+interface WriterState {
+ proc: WriterProcess;
+ serverKey: string;
+ phase: number;
+ stderr: string;
+ stopRequested: boolean;
+}
+
+type WriterReport = Pick<WriterState, 'serverKey' | 'phase' | 'stderr'>;
+
+const describeWriter = (state: WriterReport) =>
+ `${state.serverKey}: phase=${PHASES[state.phase]} stderr=${state.stderr.trim()}`;
+
+const writerFailure = (state: WriterReport, cause: unknown) =>
+ new Error(`Config writer failed: ${describeWriter(state)}`, { cause });
+
+export async function runConfigWriters(
+ configPath: string,
+ serverKeys: string[],
+ options: { spawnWriter?: SpawnWriter; signal?: AbortSignal } = {},
+): Promise<WorkerOutcome[]> {
+ options.signal?.throwIfAborted();
+ const spawnWriter = options.spawnWriter ?? spawnConfigWriter;
+ const pending = new Set<WriterState>();
+ const completions: Promise<WorkerOutcome>[] = [];
+ let failure: Error | undefined;
+ let watchdog: ReturnType<typeof setTimeout> | undefined;
+
+ const stop = () => {
+ clearTimeout(watchdog);
+ for (const state of pending) {
+ if (
+ !state.stopRequested &&
+ state.proc.pid !== undefined &&
+ state.proc.exitCode === null &&
+ state.proc.signalCode === null
+ ) {
+ state.stopRequested = true;
+ state.proc.kill('SIGKILL');
+ }
+ }
+ };
+ const fail = (error: unknown) => {
+ failure ??= error instanceof Error ? error : new Error(String(error));
+ stop();
+ };
+ const progress = () => {
+ clearTimeout(watchdog);
+ if (failure || pending.size === 0) return;
+ watchdog = setTimeout(() => {
+ fail(
+ new Error(
+ `Config writers made no progress for ${NO_PROGRESS_MS}ms:\n${[...pending]
+ .map(describeWriter)
+ .join('\n')}`,
+ ),
+ );
+ }, NO_PROGRESS_MS);
+ };
+ const abort = () => fail(options.signal?.reason);
+ options.signal?.addEventListener('abort', abort, { once: true });
+
+ try {
+ for (const serverKey of serverKeys) {
+ if (failure) break;
+ let proc: WriterProcess;
+ try {
+ proc = spawnWriter(configPath, serverKey);
+ } catch (error) {
+ throw writerFailure({ serverKey, phase: 0, stderr: '' }, error);
+ }
+ const state: WriterState = { proc, serverKey, phase: 0, stderr: '', stopRequested: false };
+ pending.add(state);
+ completions.push(
+ new Promise((resolveClose) => {
+ proc.stderr?.on('data', (chunk: Buffer) => {
+ state.stderr += chunk.toString('utf-8');
+ });
+ proc.on('message', (message: unknown) => {
+ const phase = typeof message === 'string' ? PHASES.indexOf(message) : -1;
+ if (phase > state.phase) {
+ state.phase = phase;
+ progress();
+ }
+ });
+ proc.on('error', (error) => fail(writerFailure(state, error)));
+ proc.once('close', (exitCode, signal) => {
+ pending.delete(state);
+ resolveClose({
+ serverKey,
+ exitCode,
+ signal: signal ?? null,
+ phase: PHASES[state.phase],
+ stderr: state.stderr,
+ });
+ progress();
+ });
+ }),
+ );
+ progress();
+ }
+ } catch (error) {
+ fail(error);
+ }
+
+ try {
+ const outcomes = await Promise.all(completions);
+ if (failure) throw failure;
+ return outcomes;
+ } finally {
+ clearTimeout(watchdog);
+ options.signal?.removeEventListener('abort', abort);
+ }
+}
diff --git a/packages/cli/tests/integration/mcp-host-config-race.test.ts b/packages/cli/tests/integration/mcp-host-config-race.test.ts
index b06ac3366..e03545230 100644
--- a/packages/cli/tests/integration/mcp-host-config-race.test.ts
+++ b/packages/cli/tests/integration/mcp-host-config-race.test.ts
@@ -1,4 +1,3 @@
-import { spawn as nativeSpawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
@@ -6,54 +5,22 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { arrangeExpiredFileLock } from '../../../core/src/util/file-lock-deadline.test-helper.ts';
import { EDITOR_TARGETS } from '../../src/commands/editors.ts';
import { writeEditorMcpConfig } from '../../src/commands/init.ts';
+import { runConfigWriters } from './_helpers/config-race.test-helper.ts';
vi.mock('node:fs', async (importOriginal) => {
const fs = await importOriginal<typeof import('node:fs')>();
return { ...fs, openSync: vi.fn(fs.openSync) };
});
-const WORKER_PATH = resolve(__dirname, '_helpers', 'config-race-worker.ts');
-const WORKER_TIMEOUT_MS = 30_000;
-
-interface WorkerOutcome {
- serverKey: string;
- exitCode: number | null;
- stderr: string;
-}
-
-function spawnConfigWriter(configPath: string, serverKey: string): Promise<WorkerOutcome> {
- return new Promise((resolveSpawn, rejectSpawn) => {
- const proc = nativeSpawn('node', ['--import', 'tsx', WORKER_PATH, configPath, serverKey], {
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- let stderr = '';
- proc.stderr?.on('data', (chunk: Buffer) => {
- stderr += chunk.toString('utf-8');
- });
- const timeoutHandle = setTimeout(() => {
- try {
- proc.kill('SIGKILL');
- } catch {}
- rejectSpawn(
- new Error(`config-race-worker(${serverKey}) timed out after ${WORKER_TIMEOUT_MS}ms`),
- );
- }, WORKER_TIMEOUT_MS);
- proc.once('exit', (code) => {
- clearTimeout(timeoutHandle);
- resolveSpawn({ serverKey, exitCode: code, stderr });
- });
- proc.once('error', (err) => {
- clearTimeout(timeoutHandle);
- rejectSpawn(err);
- });
- });
-}
-
describe('mcp host config — concurrent-write race', () => {
let testRoot: string;
let configPath: string;
+ let controller: AbortController;
+ let writers: ReturnType<typeof runConfigWriters> | undefined;
beforeEach(() => {
+ controller = new AbortController();
+ writers = undefined;
testRoot = resolve(
tmpdir(),
`mcp-host-config-race-${Date.now()}-${Math.random().toString(36).slice(2)}`,
@@ -76,7 +43,9 @@ describe('mcp host config — concurrent-write race', () => {
);
});
- afterEach(() => {
+ afterEach(async () => {
+ controller.abort();
+ await Promise.allSettled(writers ? [writers] : []);
vi.restoreAllMocks();
vi.resetAllMocks();
rmSync(testRoot, { recursive: true, force: true });
@@ -104,18 +73,25 @@ describe('mcp host config — concurrent-write race', () => {
},
);
- it('N=20 concurrent writers all add their entries; no lost updates, no corruption, no destruction of pre-existing servers', async () => {
+ it('N=20 concurrent writers all add their entries; no lost updates, no corruption, no destruction of pre-existing servers', {
+ timeout: 0,
+ }, async ({ signal }) => {
const N = 20;
const expectedKeys = Array.from({ length: N }, (_, i) => `ok-writer-${i}`);
- const writers = expectedKeys.map((key) => spawnConfigWriter(configPath, key));
- const outcomes = await Promise.all(writers);
+ writers = runConfigWriters(configPath, expectedKeys, {
+ signal: AbortSignal.any([signal, controller.signal]),
+ });
+ const outcomes = await writers;
const workerFailures = outcomes.filter((o) => o.exitCode !== 0);
if (workerFailures.length > 0) {
throw new Error(
`${workerFailures.length} / ${N} workers failed:\n${workerFailures
- .map((f) => ` ${f.serverKey}: exit=${f.exitCode} stderr=${f.stderr.trim()}`)
+ .map(
+ (f) =>
+ ` ${f.serverKey}: exit=${f.exitCode} signal=${f.signal} phase=${f.phase} stderr=${f.stderr.trim()}`,
+ )
.join('\n')}`,
);
}
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/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/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.ts
index fb0ba5a7c..fc267cbea 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/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/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('|');