Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

test: spawned servers take OS-assigned free ports through one helper (test/helpers/free-port.ts)

garrytan5bed09e93294
diff --git a/test/admin-embed-spawn.test.ts b/test/admin-embed-spawn.test.ts
index 8df5ee2c29..2c99e28b5f 100644
--- a/test/admin-embed-spawn.test.ts
+++ b/test/admin-embed-spawn.test.ts
@@ -28,7 +28,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import type { Subprocess } from 'bun';
-import { createServer, type AddressInfo } from 'node:net';
+import { ExitedEarly, startOnFreePort, waitForHealthy } from './helpers/free-port.ts';
const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, '');
@@ -40,28 +40,7 @@ interface ServeProc {
cleanup: () => Promise<void>;
}
-/** A loopback port the OS reports free. */
-async function freePort(): Promise<number> {
- const probe = createServer();
- await new Promise<void>(resolve => probe.listen(0, '127.0.0.1', resolve));
- const { port } = probe.address() as AddressInfo;
- await new Promise<void>(resolve => probe.close(() => resolve()));
- return port;
-}
-
-/**
- * Another process can take the port between the probe and serve's bind; a
- * server that exits before it is ready is retried on a fresh port.
- */
-async function spawnServer(): Promise<ServeProc> {
- for (let attempt = 1; ; attempt++) {
- const started = await spawnServerOnce();
- if ('proc' in started) return started;
- if (!started.exitedEarly || attempt === 3) throw new Error(started.error);
- }
-}
-
-async function spawnServerOnce(): Promise<ServeProc | { exitedEarly: boolean; error: string }> {
+async function spawnServer(port: number): Promise<ServeProc | ExitedEarly> {
const home = mkdtempSync(join(tmpdir(), 'gbrain-admin-embed-'));
// serve never creates a configured PGLite brain that is missing (status-only `missing_brain`); the data dir exists, empty.
mkdirSync(join(home, '.gbrain', 'brain.pglite'), { recursive: true });
@@ -78,7 +57,6 @@ async function spawnServerOnce(): Promise<ServeProc | { exitedEarly: boolean; er
// out of the startup banner (and the banner stays predictable across
// future formatting tweaks).
const bootstrapToken = 'test-bootstrap-token-aaaaaaaaaaaaaaaaaa'; // 41 chars
- const port = await freePort();
// CRITICAL: cwd is the tmpdir, NOT the repo. This forces serve-http to
// fall into the embedded-manifest branch because cwd/admin/dist does
@@ -115,20 +93,7 @@ async function spawnServerOnce(): Promise<ServeProc | { exitedEarly: boolean; er
// Wait for readiness by polling /health. Bun's readable streams don't
// give us a synchronous "stderr line" API and the startup banner format
// is allowed to drift; a /health probe is the contract that matters.
- const deadline = Date.now() + 30_000;
- let ready = false;
- while (Date.now() < deadline && proc.exitCode === null) {
- try {
- const res = await fetch(`http://127.0.0.1:${port}/health`, {
- signal: AbortSignal.timeout(2000),
- });
- if (res.ok) {
- ready = true;
- break;
- }
- } catch { /* not ready yet */ }
- await new Promise(r => setTimeout(r, 250));
- }
+ const state = await waitForHealthy(`http://127.0.0.1:${port}/health`, () => proc.exitCode !== null, 30_000);
const cleanup = async () => {
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -148,11 +113,11 @@ async function spawnServerOnce(): Promise<ServeProc | { exitedEarly: boolean; er
}
};
- if (!ready) {
- const exitedEarly = proc.exitCode !== null;
+ if (state !== 'healthy') {
await cleanup();
- const stderrText = await new Response(proc.stderr).text().catch(() => '');
- return { exitedEarly, error: `serve --http never became ready on port ${port}. stderr: ${stderrText.slice(0, 2000)}` };
+ const stderrText = (await new Response(proc.stderr).text().catch(() => '')).slice(0, 2000);
+ if (state === 'exited') return new ExitedEarly(stderrText);
+ throw new Error(`serve --http never became ready on port ${port} after 30s. stderr: ${stderrText}`);
}
return { proc, port, home, bootstrapToken, cleanup };
@@ -162,7 +127,7 @@ describe('admin embed E2E — /admin served from embedded manifest (v0.36.1.x #1
let server: ServeProc;
beforeAll(async () => {
- server = await spawnServer();
+ server = await startOnFreePort(spawnServer);
}, 90_000);
afterAll(async () => {
diff --git a/test/agent-journey-recovery.serial.test.ts b/test/agent-journey-recovery.serial.test.ts
index b9546e5ada..a53e870fed 100644
--- a/test/agent-journey-recovery.serial.test.ts
+++ b/test/agent-journey-recovery.serial.test.ts
@@ -48,8 +48,9 @@ import { shellQuote } from '../src/core/agent-output.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
+import { ExitedEarly, startOnFreePort, waitForHealthy } from './helpers/free-port.ts';
import {
- REPO, body, call, expectOneBlockError, gb, journeyEnv, mcp, oneDocument, waitFor, type GbResult,
+ REPO, body, call, expectOneBlockError, gb, journeyEnv, mcp, oneDocument, type GbResult,
} from './helpers/agent-journey.ts';
const MARKER = 'wombat-tier2-marker';
@@ -151,7 +152,6 @@ describe('H1b: --surface starter', () => {
describe('H1b: read-only grant over HTTP', () => {
let home = '';
let http: ChildProcess | null = null;
- const PORT = 43000 + Math.floor(Math.random() * 2000);
beforeAll(async () => {
home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-ro-'));
expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
@@ -167,11 +167,17 @@ describe('H1b: read-only grant over HTTP', () => {
expect(minted.exitCode, minted.stderr).toBe(0);
const token = (minted.stdout.match(/gbrain_[a-f0-9]{64}/) ?? [''])[0];
expect(token).toBeTruthy();
- http = spawn('bun', ['--no-env-file', 'run', join(REPO, 'src', 'cli.ts'), 'serve', '--http', '--bind', '127.0.0.1', '--port', String(PORT)],
- { cwd: home, env: journeyEnv(home), stdio: ['ignore', 'ignore', 'ignore'] });
- expect(await waitFor(async () => (await fetch(`http://127.0.0.1:${PORT}/health`).catch(() => null))?.ok === true, 60_000)).toBe(true);
+ const port = await startOnFreePort(async candidate => {
+ const child = spawn('bun', ['--no-env-file', 'run', join(REPO, 'src', 'cli.ts'), 'serve', '--http', '--bind', '127.0.0.1', '--port', String(candidate)],
+ { cwd: home, env: journeyEnv(home), stdio: ['ignore', 'ignore', 'ignore'] });
+ http = child;
+ const state = await waitForHealthy(`http://127.0.0.1:${candidate}/health`, () => child.exitCode !== null || child.signalCode !== null, 60_000);
+ if (state === 'exited') return new ExitedEarly(`serve --http exited with ${child.exitCode ?? child.signalCode}`);
+ expect(state).toBe('healthy');
+ return candidate;
+ });
const client = new Client({ name: 'ro-harness', version: '1' }, { capabilities: {} });
- await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${PORT}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));
+ await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));
try {
const listed = (await client.listTools()).tools;
const byName = new Map(operations.map(op => [op.name, op]));
diff --git a/test/agent-journey-upgrade.serial.test.ts b/test/agent-journey-upgrade.serial.test.ts
index e0d97a9d5d..17a463977b 100644
--- a/test/agent-journey-upgrade.serial.test.ts
+++ b/test/agent-journey-upgrade.serial.test.ts
@@ -50,6 +50,7 @@ import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js'
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { makeDoctorHome, runGbrain, type DoctorHome, type GbrainRun } from './helpers/doctor-json-golden.ts';
import { PROVIDER_ENV_KEYS } from './helpers/provider-env.ts';
+import { ExitedEarly, startOnFreePort, waitForHealthy } from './helpers/free-port.ts';
import { oldReadError, oldUnpack } from './fixtures/agent-contract/frozen-thin-client-v0.60.37.ts';
import { extractToolErrorDetail } from '../src/core/mcp-client.ts';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
@@ -317,8 +318,7 @@ describe('(4) an old thin client against a real new serve --http', () => {
let server: ChildProcess | null = null;
let rw = '';
let ro = '';
- const PORT = 44000 + Math.floor(Math.random() * 2000);
- const URL_ = `http://127.0.0.1:${PORT}/mcp`;
+ let URL_ = '';
beforeAll(async () => {
h = await upgradedBrain('upgrade-thin-client');
@@ -330,14 +330,16 @@ describe('(4) an old thin client against a real new serve --http', () => {
rw = await token('old-thin-client', 'read,write');
ro = await token('old-thin-reader', 'read');
expect(rw && ro).toBeTruthy();
- server = spawn(process.execPath, ['--no-env-file', CLI, 'serve', '--http', '--bind', '127.0.0.1', '--port', String(PORT)],
- { cwd: h.work, env: childEnv(h), stdio: ['ignore', 'ignore', 'ignore'] });
- const end = Date.now() + 60_000;
- while (Date.now() < end) {
- if ((await fetch(`http://127.0.0.1:${PORT}/health`).catch(() => null))?.ok) return;
- await Bun.sleep(500);
- }
- throw new Error('serve --http never became healthy');
+ const port = await startOnFreePort(async candidate => {
+ const child = spawn(process.execPath, ['--no-env-file', CLI, 'serve', '--http', '--bind', '127.0.0.1', '--port', String(candidate)],
+ { cwd: h.work, env: childEnv(h), stdio: ['ignore', 'ignore', 'ignore'] });
+ server = child;
+ const state = await waitForHealthy(`http://127.0.0.1:${candidate}/health`, () => child.exitCode !== null || child.signalCode !== null, 60_000);
+ if (state === 'exited') return new ExitedEarly(`serve --http exited with ${child.exitCode ?? child.signalCode}`);
+ if (state === 'timeout') throw new Error('serve --http never became healthy');
+ return candidate;
+ });
+ URL_ = `http://127.0.0.1:${port}/mcp`;
}, 180_000);
afterAll(async () => {
diff --git a/test/agent-voice-cors.test.ts b/test/agent-voice-cors.test.ts
index bc81354cc4..e1055e71d5 100644
--- a/test/agent-voice-cors.test.ts
+++ b/test/agent-voice-cors.test.ts
@@ -23,20 +23,11 @@
import { describe, test, expect } from 'bun:test';
import type { Subprocess } from 'bun';
import { join } from 'path';
-import { createServer, type AddressInfo } from 'node:net';
+import { ExitedEarly, startOnFreePort, waitForHealthy } from './helpers/free-port.ts';
const SERVER_SCRIPT = join(import.meta.dir, '..', 'recipes', 'agent-voice', 'code', 'server.mjs');
const EVIL = 'https://evil.example';
-/** A port the OS reports free on every interface (the server may bind 0.0.0.0). */
-async function freePort(): Promise<number> {
- const probe = createServer();
- await new Promise<void>(resolve => probe.listen(0, '0.0.0.0', resolve));
- const { port } = probe.address() as AddressInfo;
- await new Promise<void>(resolve => probe.close(() => resolve()));
- return port;
-}
-
interface VoiceServer {
port: number;
base: string;
@@ -46,9 +37,7 @@ interface VoiceServer {
}
async function spawnVoice(extraEnv: Record<string, string> = {}): Promise<VoiceServer> {
- let stderr = '';
- for (let attempt = 0; attempt < 3; attempt++) {
- const port = await freePort();
+ return startOnFreePort(async port => {
const env: Record<string, string> = {
...(process.env as Record<string, string>),
PORT: String(port),
@@ -79,23 +68,14 @@ async function spawnVoice(extraEnv: Record<string, string> = {}): Promise<VoiceS
} catch { /* stream closed on shutdown */ }
})();
- // A server that exits before it is healthy (another process took the port
- // between the probe and the bind) is retried on a fresh port.
const base = `http://127.0.0.1:${port}`;
- const deadline = Date.now() + 30_000;
- while (Date.now() < deadline && proc.exitCode === null) {
- try {
- const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(2000) });
- if (res.ok) return { port, base, proc, stdout: () => out };
- } catch { /* not up yet */ }
- await new Promise(r => setTimeout(r, 250));
- }
- const exitedEarly = proc.exitCode !== null;
+ const state = await waitForHealthy(`${base}/health`, () => proc.exitCode !== null, 30_000);
+ if (state === 'healthy') return { port, base, proc, stdout: () => out };
proc.kill();
- stderr = await new Response(proc.stderr).text();
- if (!exitedEarly) break;
- }
- throw new Error(`agent-voice server did not become healthy\nstderr: ${stderr.slice(-800)}`);
+ const stderr = (await new Response(proc.stderr).text()).slice(-800);
+ if (state === 'exited') return new ExitedEarly(stderr);
+ throw new Error(`agent-voice server did not become healthy in 30s\nstderr: ${stderr}`);
+ }, { host: '0.0.0.0' });
}
async function stopVoice(server: VoiceServer): Promise<void> {
diff --git a/test/e2e/pglite-cli-exit.serial.test.ts b/test/e2e/pglite-cli-exit.serial.test.ts
index a9cbbd0875..2a19d397e4 100644
--- a/test/e2e/pglite-cli-exit.serial.test.ts
+++ b/test/e2e/pglite-cli-exit.serial.test.ts
@@ -47,6 +47,7 @@ import { tmpdir } from 'os';
import { join, resolve } from 'path';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import type { EngineConfig } from '../../src/core/types.ts';
+import { ExitedEarly, startOnFreePort } from '../helpers/free-port.ts';
const REPO_ROOT = resolve(import.meta.dir, '..', '..');
const BIN_CACHE = join(REPO_ROOT, 'test', '.cache');
@@ -491,42 +492,46 @@ describe('WAL-repair wave — corrupt persistent brain, auto-repair off: owned e
describe('v0.41.8.0 — daemon survival (regression guard for narrow force-exit)', () => {
test('gbrain serve --http stays alive past the timeout window', async () => {
- // Pick a likely-free ephemeral port. We're testing "still alive
- // 3 seconds after startup" — if the force-exit guard misfired
- // on 'serve', the process would die immediately after binding.
- const port = 31000 + Math.floor(Math.random() * 1000);
- const child = spawn(
- SHIM_PATH,
- ['serve', '--http', '--port', String(port), '--token-ttl', '60'],
- {
- cwd: REPO_ROOT,
- env: runEnv,
- detached: false,
- },
- );
-
- let exitedEarly = false;
- let earlyCode: number | null = null;
- child.on('exit', (code) => {
- exitedEarly = true;
- earlyCode = code;
- });
-
- // Give the server 3 seconds. If the force-exit narrow guard is
- // working, the daemon stays alive past this window.
- await new Promise((r) => setTimeout(r, 3_000));
-
- const wasAlive = !exitedEarly;
- try {
- child.kill('SIGTERM');
- // Give it a moment to clean up
- await new Promise((r) => setTimeout(r, 1_000));
- if (!exitedEarly) {
- try { child.kill('SIGKILL'); } catch { /* already dead */ }
+ // An OS-assigned free port; a "port in use" exit (another process took it
+ // before serve bound) is retried, any other early exit is the regression.
+ const { wasAlive, earlyCode } = await startOnFreePort(async port => {
+ const child = spawn(
+ SHIM_PATH,
+ ['serve', '--http', '--port', String(port), '--token-ttl', '60'],
+ {
+ cwd: REPO_ROOT,
+ env: runEnv,
+ detached: false,
+ },
+ );
+ let stderr = '';
+ child.stderr?.on('data', chunk => { stderr += String(chunk); });
+
+ let exitedEarly = false;
+ let code: number | null = null;
+ child.on('exit', (c) => {
+ exitedEarly = true;
+ code = c;
+ });
+
+ // Give the server 3 seconds. If the force-exit narrow guard is
+ // working, the daemon stays alive past this window.
+ await new Promise((r) => setTimeout(r, 3_000));
+
+ const alive = !exitedEarly;
+ try {
+ child.kill('SIGTERM');
+ // Give it a moment to clean up
+ await new Promise((r) => setTimeout(r, 1_000));
+ if (!exitedEarly) {
+ try { child.kill('SIGKILL'); } catch { /* already dead */ }
+ }
+ } catch {
+ /* already dead */
}
- } catch {
- /* already dead */
- }
+ if (!alive && /serve_port_in_use|in use\?/.test(stderr)) return new ExitedEarly(stderr.slice(-400));
+ return { wasAlive: alive, earlyCode: code };
+ });
if (!wasAlive) {
throw new Error(
diff --git a/test/e2e/thin-client.test.ts b/test/e2e/thin-client.test.ts
index 2d5130bd1e..cecd21957f 100644
--- a/test/e2e/thin-client.test.ts
+++ b/test/e2e/thin-client.test.ts
@@ -30,6 +30,7 @@ import { tmpdir } from 'os';
import { keylessBrainEnv } from '../helpers/provider-env.ts';
import { cliDiagnostic, fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
+import { ExitedEarly, startOnFreePort, waitForHealthy } from '../helpers/free-port.ts';
function test(name: string, fn: () => void | Promise<unknown>): void {
testRaw(name, fn, 120000);
@@ -91,33 +92,25 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
const init = await spawn(['init', '--non-interactive', '--no-embedding', '--url', hostDatabaseUrl], hostHome);
if (init.exitCode !== 0) throw new Error(cliDiagnostic(`host init failed`, init));
- // 2. Pick a random free port for serve --http.
- serverPort = 30000 + Math.floor(Math.random() * 30000);
-
- // 3. Spawn serve --http (background, async).
+ // 2-3. Spawn serve --http on a free port (background, async) and wait
+ // for the discovery endpoint.
const env = keylessBrainEnv(process.env, hostHome, {
GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: hostDatabaseUrl,
});
- serverProc = Bun.spawn({
- cmd: ['bun', '--no-env-file', 'run', CLI, 'serve', '--http', '--port', String(serverPort)],
- env,
- stdin: 'ignore',
- stdout: 'pipe',
- stderr: 'pipe',
+ serverPort = await startOnFreePort(async port => {
+ const proc = Bun.spawn({
+ cmd: ['bun', '--no-env-file', 'run', CLI, 'serve', '--http', '--port', String(port)],
+ env,
+ stdin: 'ignore',
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ serverProc = proc;
+ const state = await waitForHealthy(`http://127.0.0.1:${port}/.well-known/oauth-authorization-server`, () => proc.exitCode !== null, 20_000);
+ if (state === 'exited') return new ExitedEarly((await new Response(proc.stderr).text()).slice(-800));
+ return port;
});
- // Wait for the server to be ready (poll the discovery endpoint).
- const deadline = Date.now() + 20_000;
- while (Date.now() < deadline) {
- try {
- const res = await fetch(`http://127.0.0.1:${serverPort}/.well-known/oauth-authorization-server`, {
- signal: AbortSignal.timeout(500),
- });
- if (res.ok) break;
- } catch { /* retry */ }
- await new Promise(r => setTimeout(r, 250));
- }
-
// 4. Register a client with read,write,admin scope.
const reg = await spawn([
'auth', 'register-client', 'thin-client-test',
diff --git a/test/helpers/free-port.ts b/test/helpers/free-port.ts
new file mode 100644
index 0000000000..a461d2c9ef
--- /dev/null
+++ b/test/helpers/free-port.ts
@@ -0,0 +1,57 @@
+/**
+ * Ports for tests that spawn a server process.
+ *
+ * A random port from a fixed range can already be taken on a busy runner; the
+ * server then exits with "port in use" and the test waits out its health
+ * deadline. `freePort` asks the OS for a port that is free right now, and
+ * `startOnFreePort` retries on a fresh port when the server still exits
+ * before it is healthy (another process took the port between the probe and
+ * the bind).
+ */
+import { createServer, type AddressInfo } from 'node:net';
+
+/** A port the OS reports free on `host` (use '0.0.0.0' when the server may bind every interface). */
+export async function freePort(host = '127.0.0.1'): Promise<number> {
+ const probe = createServer();
+ await new Promise<void>((resolve, reject) => { probe.once('error', reject); probe.listen(0, host, resolve); });
+ const { port } = probe.address() as AddressInfo;
+ await new Promise<void>(resolve => probe.close(() => resolve()));
+ return port;
+}
+
+/** A start attempt whose server exited before it was healthy; `startOnFreePort` retries it on a fresh port. */
+export class ExitedEarly {
+ constructor(readonly reason: string) {}
+}
+
+/**
+ * Run `start` on a free port; when it returns `ExitedEarly`, try again on a
+ * fresh port, at most `attempts` times, then throw the last reason. `start`
+ * throws on its own for anything else (a timeout is not retried).
+ */
+export async function startOnFreePort<T>(start: (port: number) => Promise<T | ExitedEarly>, opts: { attempts?: number; host?: string } = {}): Promise<T> {
+ const attempts = opts.attempts ?? 3;
+ let reason = '';
+ for (let attempt = 1; attempt <= attempts; attempt++) {
+ const outcome = await start(await freePort(opts.host));
+ if (!(outcome instanceof ExitedEarly)) return outcome;
+ reason = outcome.reason;
+ }
+ throw new Error(`server exited before it was healthy on ${attempts} fresh ports; last: ${reason}`);
+}
+
+/**
+ * Poll `url` until it answers 2xx, the process exits, or `timeoutMs` passes.
+ * `exited` reports whether the server process has exited.
+ */
+export async function waitForHealthy(url: string, exited: () => boolean, timeoutMs: number): Promise<'healthy' | 'exited' | 'timeout'> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (exited()) return 'exited';
+ try {
+ if ((await fetch(url, { signal: AbortSignal.timeout(2000) })).ok) return 'healthy';
+ } catch { /* not up yet */ }
+ await new Promise(r => setTimeout(r, 250));
+ }
+ return exited() ? 'exited' : 'timeout';
+}
diff --git a/test/qm-provisioning.test.ts b/test/qm-provisioning.test.ts
index 44f6730bb8..3476c3dbc3 100644
--- a/test/qm-provisioning.test.ts
+++ b/test/qm-provisioning.test.ts
@@ -27,6 +27,7 @@ import { join } from 'path';
import { tmpdir } from 'os';
import { keylessBrainEnv } from './helpers/provider-env.ts';
import { cliDiagnostic, fixtureDiagnostic } from './helpers/fixture-diagnostics.ts';
+import { ExitedEarly, startOnFreePort, waitForHealthy } from './helpers/free-port.ts';
function test(name: string, fn: () => void | Promise<unknown>): void {
testRaw(name, fn, 120000);
@@ -135,26 +136,20 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {
};
// 5. Serve over HTTP MCP (holds the PGLite lock from here on).
- serverPort = 30000 + Math.floor(Math.random() * 30000);
const env = keylessBrainEnv(process.env, hostHome, {
DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,
});
- serverProc = Bun.spawn({
- cmd: ['bun', '--no-env-file', 'run', CLI, 'serve', '--http', '--port', String(serverPort)],
- env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ serverPort = await startOnFreePort(async port => {
+ const proc = Bun.spawn({
+ cmd: ['bun', '--no-env-file', 'run', CLI, 'serve', '--http', '--port', String(port)],
+ env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe',
+ });
+ serverProc = proc;
+ const state = await waitForHealthy(`http://127.0.0.1:${port}/.well-known/oauth-authorization-server`, () => proc.exitCode !== null, 30_000);
+ if (state === 'exited') return new ExitedEarly((await new Response(proc.stderr).text()).slice(-800));
+ if (state === 'timeout') throw new Error('serve --http did not come up');
+ return port;
});
- const deadline = Date.now() + 30_000;
- let up = false;
- while (Date.now() < deadline) {
- try {
- const res = await fetch(`http://127.0.0.1:${serverPort}/.well-known/oauth-authorization-server`, {
- signal: AbortSignal.timeout(500),
- });
- if (res.ok) { up = true; break; }
- } catch { /* retry */ }
- await new Promise(r => setTimeout(r, 250));
- }
- if (!up) throw new Error('serve --http did not come up');
// 6. Thin-client bootstrap for both scopes (the once-per-sandbox step).
// --oauth-client-secret (NOT the env var) on purpose: an env-sourced
diff --git a/test/serve-status-mode.serial.test.ts b/test/serve-status-mode.serial.test.ts
index 35c20f955b..6c77cf5f18 100644
--- a/test/serve-status-mode.serial.test.ts
+++ b/test/serve-status-mode.serial.test.ts
@@ -28,6 +28,7 @@ import { ToolListChangedNotificationSchema } from '@modelcontextprotocol/sdk/typ
import { spawn, type ChildProcess } from 'node:child_process';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { keylessBrainEnv } from './helpers/provider-env.ts';
+import { ExitedEarly, freePort, startOnFreePort, waitForHealthy } from './helpers/free-port.ts';
const MARKER = 'zelkova-status-marker-4q7';
@@ -176,8 +177,6 @@ describe('status-only serve: lock contention → one shared serve --http (b)', (
let env: Record<string, string>;
let http: ChildProcess | null = null;
const opened: Array<{ client: Client; transport: StdioClientTransport }> = [];
- const PORT = 41000 + Math.floor(Math.random() * 2000);
- const URL_ = `http://127.0.0.1:${PORT}/mcp`;
beforeAll(() => {
home = mkdtempSync(join(tmpdir(), 'gbrain-status-http-'));
@@ -213,9 +212,15 @@ describe('status-only serve: lock contention → one shared serve --http (b)', (
});
expect(tokens.every(Boolean)).toBe(true);
// Step 2: one shared HTTP server owns the brain.
- http = spawn('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--bind', '127.0.0.1', '--port', String(PORT)],
- { cwd: process.cwd(), env, stdio: ['ignore', 'ignore', 'ignore'] });
- expect(await waitFor(async () => (await fetch(`http://127.0.0.1:${PORT}/health`).catch(() => null))?.ok === true, 60_000)).toBe(true);
+ const port = await startOnFreePort(async candidate => {
+ const child = spawn('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--bind', '127.0.0.1', '--port', String(candidate)],
+ { cwd: process.cwd(), env, stdio: ['ignore', 'ignore', 'ignore'] });
+ http = child;
+ const state = await waitForHealthy(`http://127.0.0.1:${candidate}/health`, () => child.exitCode !== null || child.signalCode !== null, 60_000);
+ if (state === 'exited') return new ExitedEarly(`serve --http exited with ${child.exitCode ?? child.signalCode}`);
+ expect(state).toBe('healthy');
+ return candidate;
+ });
// The stale stdio server cannot take the brain back; it names the HTTP owner and the rewiring fix.
const after = body(await stale.client.callTool({ name: 'gbrain_status', arguments: {} }));
@@ -227,7 +232,7 @@ describe('status-only serve: lock contention → one shared serve --http (b)', (
// Step 3: each harness, rewired to the shared server, recalls.
for (const token of tokens) {
const client = new Client({ name: 'shared-http', version: '1' }, { capabilities: {} });
- await client.connect(new StreamableHTTPClientTransport(new URL(URL_), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));
+ await client.connect(new StreamableHTTPClientTransport(new URL(`http://127.0.0.1:${port}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));
try {
const found = await client.callTool({ name: 'search', arguments: { query: MARKER } });
expect(found.isError).toBeFalsy();
@@ -244,7 +249,6 @@ describe('status-only serve: the shared-HTTP transition fails midway (H2)', () =
let env: Record<string, string>;
let blocker: ReturnType<typeof import('node:http').createServer> | null = null;
const opened: Array<{ client: Client; transport: StdioClientTransport }> = [];
- const PORT = 44000 + Math.floor(Math.random() * 2000);
beforeAll(() => {
home = mkdtempSync(join(tmpdir(), 'gbrain-status-midway-'));
@@ -275,7 +279,8 @@ describe('status-only serve: the shared-HTTP transition fails midway (H2)', () =
// Step 2 fails: the port is taken, so the shared server cannot start.
const http = await import('node:http');
blocker = http.createServer((_q, r) => { r.end('not gbrain'); });
- await new Promise<void>(r => blocker!.listen(PORT, '127.0.0.1', () => r()));
+ await new Promise<void>(r => blocker!.listen(0, '127.0.0.1', () => r()));
+ const PORT = (blocker.address() as import('node:net').AddressInfo).port;
const started = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--bind', '127.0.0.1', '--port', String(PORT)],
{ cwd: process.cwd(), env, input: '', encoding: 'utf8', timeout: 60_000 });
expect(started.signal, 'serve --http on a taken port must exit, not hang holding the brain').toBeNull();
@@ -336,12 +341,12 @@ describe('status-only serve: one re-probe for both transports; Postgres keeps th
expect(stderr).toContain('"event":"serve_status_mode_recovered","reason":"lock_held","transport":"stdio"');
}, 180_000);
- test('a Postgres connect failure on --http takes the degraded-engine path, not status-only mode', () => {
+ test('a Postgres connect failure on --http takes the degraded-engine path, not status-only mode', async () => {
const pgHome = mkdtempSync(join(tmpdir(), 'gbrain-status-pg-'));
try {
mkdirSync(join(pgHome, '.gbrain'), { recursive: true });
writeFileSync(join(pgHome, '.gbrain', 'config.json'), JSON.stringify({ engine: 'postgres', database_url: 'postgresql://127.0.0.1:1/gbrain' }));
- const r = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--bind', '127.0.0.1', '--port', String(46000 + Math.floor(Math.random() * 2000))],
+ const r = spawnSync('bun', ['--no-env-file', 'run', 'src/cli.ts', 'serve', '--http', '--bind', '127.0.0.1', '--port', String(await freePort())],
{ cwd: process.cwd(), env: { ...envFor(pgHome), GBRAIN_NO_RETRY_CONNECT: '1' }, encoding: 'utf8', timeout: 60_000, input: '' });
expect(r.stderr).toContain('GBRAIN_DB_ACCESS');
expect(r.stderr).not.toContain('serve_status_mode_enter');