Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

v0.60.86.0 test(serve): start test servers on a kernel-reported free port and surface serve's output

garrytan760037e6bc77
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 3e72d6b0db..3c1a68adce 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.85.0",
+ "version": "0.60.86.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index e827f9616f..ea41091e34 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain",
- "version": "0.60.85.0",
+ "version": "0.60.86.0",
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
"author": {
"name": "Garry Tan",
diff --git a/BOOTSTRAP_FOR_AGENTS.md b/BOOTSTRAP_FOR_AGENTS.md
index 3ea7347149..0fbe9992ef 100644
--- a/BOOTSTRAP_FOR_AGENTS.md
+++ b/BOOTSTRAP_FOR_AGENTS.md
@@ -1,4 +1,4 @@
-<!-- gbrain-runbook-stamp: 0.60.85.0 -->
+<!-- gbrain-runbook-stamp: 0.60.86.0 -->
<!-- This stamp must equal the VERSION file at every release; CI enforces it
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
the installed binary and warns on skew. -->
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4e93828d6a..83974b39a0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [0.60.86.0] - 2026-10-06
+
+**Tests that start a real `gbrain serve --http` no longer fail when the random port they picked is already taken by another socket on the machine.**
+
+Eight test files picked the server's port at random (for example `43000 + Math.random() * 2000`). Most of those ranges sit inside Linux's ephemeral port range (32768 to 60999), where any other socket can hold the port: another test file's port-0 listener, a live loopback connection, or a client connection closed in the last 60 seconds (TIME_WAIT). `serve --http` then exits with `serve_port_in_use`. The read-only-grant journey test discarded serve's output, so all CI showed was 60 seconds of failed `/health` polls. The tests now ask the kernel for a free port, keep serve's output, and fail as soon as serve exits, with that output in the failure message. gbrain itself does not change.
+
+### For contributors
+
+- `test/helpers/serve-http.ts` adds `freePort()` (binds port 0 on 127.0.0.1, reads the port, releases it) and `startServeHttp({ cwd, env })`. `startServeHttp` starts `gbrain serve --http` on a free port and resolves once `/health` answers ok. If serve exits first, it throws at once with serve's stdout and stderr, and a deadline failure includes them too.
+- The read-only grant journey (`agent-journey-recovery`), the old-thin-client journey (`agent-journey-upgrade`), the shared-HTTP status-mode test, the thin-client E2E and `qm-provisioning` now call `startServeHttp`. The status-mode taken-port test binds its blocker to port 0 and reads the port back. `pglite-cli-exit`, `admin-embed-spawn` and `agent-voice-cors` get their port from `freePort()`, and the last two stop polling as soon as the server exits.
+- Forced probe: pin the old pick (`Math.random() -> 0`, so port 43000) and hold 43000 with an established loopback client connection. Before the fix the test fails exactly as CI did (`/health` never ok, 61.2 s, no output). After the fix it passes. A second probe takes the port the instant `freePort()` releases it: the test now fails in 2.3 s, and the message shows serve's `serve_port_in_use` error.
+
## [0.60.85.0] - 2026-10-06
**The Gmail attachment-repair command test no longer fails when its second seeded thread page is still publishing as the test hands the database to the command.**
diff --git a/VERSION b/VERSION
index e6297c1357..ca606af1bc 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.60.85.0
+0.60.86.0
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 6da96a2f64..899de71c88 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -1,7 +1,7 @@
{
"id": "gbrain-context-engine",
"name": "gbrain",
- "version": "0.60.85.0",
+ "version": "0.60.86.0",
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
"family": "bundle-plugin",
"kind": "context-engine",
diff --git a/package.json b/package.json
index 9887b679a4..19076d042f 100644
--- a/package.json
+++ b/package.json
@@ -224,7 +224,7 @@
"bun": ">=1.4.0"
},
"license": "MIT",
- "version": "0.60.85.0",
+ "version": "0.60.86.0",
"overrides": {
"@ai-sdk/provider-utils": "4.0.56",
"@hono/node-server": "^2.0.5",
diff --git a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
index 146d4dd706..589930485d 100644
--- a/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.85.0",
+ "version": "0.60.86.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
index 2f58cea1f3..6f86f6eb42 100644
--- a/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-coding/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-coding",
- "version": "0.60.85.0",
+ "version": "0.60.86.0",
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 21 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-coding/README.md b/plugin-variants/gbrain-coding/README.md
index 2cd89c8508..a412451f98 100644
--- a/plugin-variants/gbrain-coding/README.md
+++ b/plugin-variants/gbrain-coding/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.85.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.86.0 -->
# gbrain-coding (generated persona variant — do not hand-edit)
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
diff --git a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
index 625b446dda..b6b70d0a9f 100644
--- a/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.85.0",
+ "version": "0.60.86.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
index 1bbfc4c829..21ebadb0b8 100644
--- a/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
+++ b/plugin-variants/gbrain-daily/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "gbrain-daily",
- "version": "0.60.85.0",
+ "version": "0.60.86.0",
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
"author": {
"name": "Garry Tan",
diff --git a/plugin-variants/gbrain-daily/README.md b/plugin-variants/gbrain-daily/README.md
index 500b1ac47e..f1cff1720d 100644
--- a/plugin-variants/gbrain-daily/README.md
+++ b/plugin-variants/gbrain-daily/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.85.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.86.0 -->
# gbrain-daily (generated persona variant — do not hand-edit)
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
diff --git a/plugin/README.md b/plugin/README.md
index 337956dee8..b9e27328a6 100644
--- a/plugin/README.md
+++ b/plugin/README.md
@@ -1,4 +1,4 @@
-<!-- gbrain-plugin-tree-stamp: 0.60.85.0 -->
+<!-- gbrain-plugin-tree-stamp: 0.60.86.0 -->
# gbrain plugin skill tree (generated — do not hand-edit)
This tree is the curated skill set for the gbrain Codex and Claude Code
diff --git a/templates/bootstrap/template-repo/README.md b/templates/bootstrap/template-repo/README.md
index 0492207372..06fd10780f 100644
--- a/templates/bootstrap/template-repo/README.md
+++ b/templates/bootstrap/template-repo/README.md
@@ -1,6 +1,6 @@
# gbrain agent workspace — template
-<!-- gbrain-template-stamp: 0.60.85.0 -->
+<!-- gbrain-template-stamp: 0.60.86.0 -->
This repository is the **"Use this template"** distribution artifact for a
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
diff --git a/test/admin-embed-spawn.test.ts b/test/admin-embed-spawn.test.ts
index 72bbb6bb6a..ac974213e7 100644
--- a/test/admin-embed-spawn.test.ts
+++ b/test/admin-embed-spawn.test.ts
@@ -28,6 +28,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import type { Subprocess } from 'bun';
+import { freePort } from './helpers/serve-http.ts';
const REPO = new URL('..', import.meta.url).pathname.replace(/\/$/, '');
@@ -39,11 +40,6 @@ interface ServeProc {
cleanup: () => Promise<void>;
}
-function pickPort(): number {
- // High-random port. Collision is unlikely; test reruns get fresh ports.
- return 31000 + Math.floor(Math.random() * 4000);
-}
-
async function spawnServer(): Promise<ServeProc> {
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.
@@ -61,7 +57,7 @@ async function spawnServer(): Promise<ServeProc> {
// out of the startup banner (and the banner stays predictable across
// future formatting tweaks).
const bootstrapToken = 'test-bootstrap-token-aaaaaaaaaaaaaaaaaa'; // 41 chars
- const port = pickPort();
+ 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
@@ -100,7 +96,7 @@ async function spawnServer(): Promise<ServeProc> {
// 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) {
+ while (Date.now() < deadline && proc.exitCode === null) {
try {
const res = await fetch(`http://127.0.0.1:${port}/health`, {
signal: AbortSignal.timeout(2000),
@@ -135,7 +131,7 @@ async function spawnServer(): Promise<ServeProc> {
await cleanup();
const stderrText = await new Response(proc.stderr).text().catch(() => '');
throw new Error(
- `serve --http never became ready on port ${port} after 30s. stderr: ${stderrText.slice(0, 2000)}`,
+ `serve --http never became ready on port ${port} (exit code ${proc.exitCode}). stderr: ${stderrText.slice(0, 2000)}`,
);
}
diff --git a/test/agent-journey-recovery.serial.test.ts b/test/agent-journey-recovery.serial.test.ts
index b9546e5ada..23f39b09d5 100644
--- a/test/agent-journey-recovery.serial.test.ts
+++ b/test/agent-journey-recovery.serial.test.ts
@@ -40,7 +40,6 @@ import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
-import { spawn, type ChildProcess } from 'node:child_process';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { operations } from '../src/core/operations.ts';
@@ -49,8 +48,9 @@ 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 {
- 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';
+import { startServeHttp, type ServeHttp } from './helpers/serve-http.ts';
const MARKER = 'wombat-tier2-marker';
@@ -150,15 +150,14 @@ 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);
+ let http: ServeHttp | null = null;
beforeAll(async () => {
home = mkdtempSync(join(tmpdir(), 'gbrain-tier2-ro-'));
expect((await gb(home, ['init', '--pglite', '--no-embedding', '--json'])).exitCode).toBe(0);
expect((await gb(home, ['import', writeNotes(join(home, 'notes'), 2), '--no-embed', '--json'])).exitCode).toBe(0);
}, 300_000);
- afterAll(() => {
- if (http) try { http.kill('SIGTERM'); } catch { /* gone */ }
+ afterAll(async () => {
+ await http?.stop();
rmSync(home, { recursive: true, force: true });
});
@@ -167,11 +166,9 @@ 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);
+ http = await startServeHttp({ cwd: home, env: journeyEnv(home) });
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.base}/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..dcace20357 100644
--- a/test/agent-journey-upgrade.serial.test.ts
+++ b/test/agent-journey-upgrade.serial.test.ts
@@ -42,7 +42,6 @@
* Serial: subprocess CLIs and servers over temp PGLite brains.
*/
import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
-import { spawn, type ChildProcess } from 'node:child_process';
import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { delimiter, join } from 'node:path';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
@@ -50,6 +49,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 { startServeHttp, type ServeHttp } from './helpers/serve-http.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';
@@ -314,11 +314,9 @@ describe('(3) harness configs registered before the upgrade', () => {
describe('(4) an old thin client against a real new serve --http', () => {
let h: DoctorHome;
- let server: ChildProcess | null = null;
+ let server: ServeHttp | null = null;
let rw = '';
let ro = '';
- const PORT = 44000 + Math.floor(Math.random() * 2000);
- const URL_ = `http://127.0.0.1:${PORT}/mcp`;
beforeAll(async () => {
h = await upgradedBrain('upgrade-thin-client');
@@ -330,26 +328,17 @@ 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');
+ server = await startServeHttp({ cwd: h.work, env: childEnv(h) });
}, 180_000);
afterAll(async () => {
- if (!server) return;
- server.kill('SIGTERM');
- await new Promise(r => server!.once('exit', r));
+ await server?.stop();
});
/** The old client's wire: SDK Client + StreamableHTTP with the bearer it minted. */
async function oldClient(token: string): Promise<Client> {
const client = new Client({ name: 'gbrain-thin-client', version: '0.60.37.0' }, { capabilities: {} });
- await client.connect(new StreamableHTTPClientTransport(new URL(URL_), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));
+ await client.connect(new StreamableHTTPClientTransport(new URL(`${server!.base}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));
return client;
}
diff --git a/test/agent-voice-cors.test.ts b/test/agent-voice-cors.test.ts
index 700fc8c55a..0a83d55aa7 100644
--- a/test/agent-voice-cors.test.ts
+++ b/test/agent-voice-cors.test.ts
@@ -22,15 +22,12 @@
import { describe, test, expect } from 'bun:test';
import type { Subprocess } from 'bun';
+import { freePort } from './helpers/serve-http.ts';
import { join } from 'path';
const SERVER_SCRIPT = join(import.meta.dir, '..', 'recipes', 'agent-voice', 'code', 'server.mjs');
const EVIL = 'https://evil.example';
-function pickPort(): number {
- return 31000 + Math.floor(Math.random() * 4000);
-}
-
interface VoiceServer {
port: number;
base: string;
@@ -40,7 +37,7 @@ interface VoiceServer {
}
async function spawnVoice(extraEnv: Record<string, string> = {}): Promise<VoiceServer> {
- const port = pickPort();
+ const port = await freePort();
const env: Record<string, string> = {
...(process.env as Record<string, string>),
PORT: String(port),
@@ -73,7 +70,7 @@ async function spawnVoice(extraEnv: Record<string, string> = {}): Promise<VoiceS
const base = `http://127.0.0.1:${port}`;
const deadline = Date.now() + 30_000;
- while (Date.now() < deadline) {
+ 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 };
@@ -82,7 +79,7 @@ async function spawnVoice(extraEnv: Record<string, string> = {}): Promise<VoiceS
}
proc.kill();
const stderr = await new Response(proc.stderr).text();
- throw new Error(`agent-voice server did not become healthy in 30s\nstderr: ${stderr.slice(-800)}`);
+ throw new Error(`agent-voice server on port ${port} did not become healthy (exit code ${proc.exitCode})\nstderr: ${stderr.slice(-800)}`);
}
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..9705cefd39 100644
--- a/test/e2e/pglite-cli-exit.serial.test.ts
+++ b/test/e2e/pglite-cli-exit.serial.test.ts
@@ -33,6 +33,7 @@
import { describe, test, expect, beforeAll, afterAll } from 'bun:test';
import { spawn, spawnSync } from 'child_process';
+import { freePort } from '../helpers/serve-http.ts';
import {
cpSync,
mkdirSync,
@@ -491,10 +492,11 @@ 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
+ // A port the kernel reports free (a taken one would also exit early,
+ // and read as this regression). 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 port = await freePort();
const child = spawn(
SHIM_PATH,
['serve', '--http', '--port', String(port), '--token-ttl', '60'],
diff --git a/test/e2e/thin-client.test.ts b/test/e2e/thin-client.test.ts
index 2d5130bd1e..aab007ff05 100644
--- a/test/e2e/thin-client.test.ts
+++ b/test/e2e/thin-client.test.ts
@@ -28,6 +28,7 @@ import { mkdtempSync, rmSync, readFileSync, existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { keylessBrainEnv } from '../helpers/provider-env.ts';
+import { startServeHttp, type ServeHttp } from '../helpers/serve-http.ts';
import { cliDiagnostic, fixtureDiagnostic } from '../helpers/fixture-diagnostics.ts';
import { isolatedPersistencePostgres } from '../helpers/persistence-postgres.ts';
@@ -67,7 +68,7 @@ const describeWhen = DATABASE_URL ? describe : describe.skip;
describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
let hostHome: string; // GBRAIN_HOME for the host (with local engine)
let clientHome: string; // GBRAIN_HOME for the thin client (no engine)
- let serverProc: ReturnType<typeof Bun.spawn> | null = null;
+ let server: ServeHttp | null = null;
let serverPort: number;
let clientId: string;
let clientSecret: string;
@@ -91,32 +92,15 @@ 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).
- 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',
+ // 2-3. serve --http on a port the kernel reports free, healthy before the suite continues.
+ server = await startServeHttp({
+ cwd: process.cwd(),
+ env: keylessBrainEnv(process.env, hostHome, {
+ GBRAIN_REMOTE_CLIENT_SECRET: undefined, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: hostDatabaseUrl,
+ }),
+ timeoutMs: 20_000,
});
-
- // 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));
- }
+ serverPort = server.port;
// 4. Register a client with read,write,admin scope.
const reg = await spawn([
@@ -146,10 +130,7 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
}
afterAll(async () => {
- if (serverProc) {
- try { serverProc.kill(); } catch { /* best-effort */ }
- try { await serverProc.exited; } catch { /* ignore */ }
- }
+ await server?.stop();
try { rmSync(hostHome, { recursive: true, force: true }); } catch { /* best-effort */ }
try { rmSync(clientHome, { recursive: true, force: true }); } catch { /* best-effort */ }
await database?.close();
@@ -431,10 +412,7 @@ describeWhen('thin-client end-to-end (requires DATABASE_URL)', () => {
test('stopped host: routed verbs fail fast with the canonical unreachable error, not a hang', async () => {
// Kill the live serve. This test is LAST in the file by design (see the
// ordering note above); afterAll's kill is a no-op afterwards.
- if (serverProc) {
- serverProc.kill();
- await serverProc.exited;
- }
+ await server?.stop();
const t0 = Date.now();
// Routed-op lane (runThinClientRouted): connection refused surfaces the
// RemoteMcpError network/unreachable rendering with the mcp_url named.
diff --git a/test/helpers/serve-http.ts b/test/helpers/serve-http.ts
new file mode 100644
index 0000000000..3464a6c7b2
--- /dev/null
+++ b/test/helpers/serve-http.ts
@@ -0,0 +1,77 @@
+/**
+ * Starting a real `gbrain serve --http` from a test without a port race.
+ *
+ * A port picked at random (`43000 + Math.random() * 2000`) sits inside the
+ * kernel's ephemeral range (Linux 32768-60999). Any socket on the machine may
+ * already hold it: another file's port-0 listener, a live loopback connection,
+ * or a client connection closed in the last 60 s (TIME_WAIT). serve then
+ * exits with serve_port_in_use, and a harness that discards its output only
+ * sees /health fail until its deadline. `freePort()` asks the kernel for a
+ * port nothing holds, and `startServeHttp()` keeps serve's output and fails
+ * as soon as the child exits.
+ */
+import { spawn, type ChildProcess } from 'node:child_process';
+import { createServer, type AddressInfo } from 'node:net';
+import { join } from 'node:path';
+
+const CLI = join(import.meta.dir, '..', '..', 'src', 'cli.ts');
+
+/** A 127.0.0.1 port the kernel reports free right now: bind port 0, read it, release it. */
+export function freePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const probe = createServer();
+ probe.once('error', reject);
+ probe.listen(0, '127.0.0.1', () => {
+ const { port } = probe.address() as AddressInfo;
+ probe.close(() => resolve(port));
+ });
+ });
+}
+
+export interface ServeHttp {
+ port: number;
+ /** `http://127.0.0.1:<port>` */
+ base: string;
+ child: ChildProcess;
+ /** Everything serve wrote to stdout and stderr so far. */
+ output(): string;
+ /** SIGTERM, then wait for the exit. */
+ stop(): Promise<void>;
+}
+
+/**
+ * `gbrain serve --http --bind 127.0.0.1 --port <free port> [...args]`, resolved once
+ * GET /health answers ok. If serve exits first (a taken port, a held lock, a bad
+ * config) this throws at once with serve's output; a deadline failure carries it too.
+ */
+export async function startServeHttp(opts: { cwd: string; env: Record<string, string>; args?: string[]; timeoutMs?: number }): Promise<ServeHttp> {
+ const port = await freePort();
+ const base = `http://127.0.0.1:${port}`;
+ const child = spawn(process.execPath, ['--no-env-file', CLI, 'serve', '--http', '--bind', '127.0.0.1', '--port', String(port), ...(opts.args ?? [])],
+ { cwd: opts.cwd, env: opts.env, stdio: ['ignore', 'pipe', 'pipe'] });
+ let output = '';
+ child.stdout!.on('data', (d: Buffer) => { output += d.toString(); });
+ child.stderr!.on('data', (d: Buffer) => { output += d.toString(); });
+ const exited = new Promise<void>(resolve => child.once('exit', () => resolve()));
+ const drained = new Promise<void>(resolve => child.once('close', () => resolve()));
+ const settledOutput = async () => { await Promise.race([drained, Bun.sleep(1000)]); return output.slice(-4000); };
+ const running = () => child.exitCode === null && child.signalCode === null;
+ const stop = async () => {
+ if (running()) child.kill('SIGTERM');
+ await exited;
+ };
+ const timeoutMs = opts.timeoutMs ?? 60_000;
+ const deadline = Date.now() + timeoutMs;
+ for (;;) {
+ if (!running()) {
+ throw new Error(`gbrain serve --http on ${base} exited (code ${child.exitCode}, signal ${child.signalCode}) before /health answered ok. Its output:\n${await settledOutput()}`);
+ }
+ if ((await fetch(`${base}/health`).catch(() => null))?.ok) return { port, base, child, output: () => output, stop };
+ if (Date.now() >= deadline) {
+ child.kill('SIGKILL');
+ await exited;
+ throw new Error(`gbrain serve --http on ${base} did not answer /health ok within ${timeoutMs}ms. Its output:\n${await settledOutput()}`);
+ }
+ await Bun.sleep(250);
+ }
+}
diff --git a/test/qm-provisioning.test.ts b/test/qm-provisioning.test.ts
index 44f6730bb8..f5eb64e1f6 100644
--- a/test/qm-provisioning.test.ts
+++ b/test/qm-provisioning.test.ts
@@ -26,6 +26,7 @@ import { mkdtempSync, rmSync, writeFileSync, readFileSync, existsSync } from 'fs
import { join } from 'path';
import { tmpdir } from 'os';
import { keylessBrainEnv } from './helpers/provider-env.ts';
+import { startServeHttp, type ServeHttp } from './helpers/serve-http.ts';
import { cliDiagnostic, fixtureDiagnostic } from './helpers/fixture-diagnostics.ts';
function test(name: string, fn: () => void | Promise<unknown>): void {
@@ -61,7 +62,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {
let workDir: string;
let aliceHome: string;
let bobHome: string;
- let serverProc: ReturnType<typeof Bun.spawn> | null = null;
+ let server: ServeHttp | null = null;
let serverPort: number;
const creds: Record<string, { clientId: string; secret: string }> = {};
let rerunCredsGrew = true; // set false when idempotency holds
@@ -135,26 +136,14 @@ 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',
+ server = await startServeHttp({
+ cwd: process.cwd(),
+ env: keylessBrainEnv(process.env, hostHome, {
+ DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, GBRAIN_REMOTE_CLIENT_SECRET: undefined,
+ }),
+ timeoutMs: 30_000,
});
- 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');
+ serverPort = server.port;
// 6. Thin-client bootstrap for both scopes (the once-per-sandbox step).
// --oauth-client-secret (NOT the env var) on purpose: an env-sourced
@@ -175,10 +164,7 @@ describe('qm-harness provisioning + write fence (e2e, PGLite)', () => {
}, 300_000);
afterAll(async () => {
- if (serverProc) {
- serverProc.kill();
- await serverProc.exited.catch(() => {});
- }
+ await server?.stop();
for (const dir of [hostHome, workDir, aliceHome, bobHome]) {
if (dir) rmSync(dir, { recursive: true, force: true });
}
diff --git a/test/serve-status-mode.serial.test.ts b/test/serve-status-mode.serial.test.ts
index 35c20f955b..a5abc58890 100644
--- a/test/serve-status-mode.serial.test.ts
+++ b/test/serve-status-mode.serial.test.ts
@@ -25,9 +25,9 @@ import { join } from 'node:path';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
import { ToolListChangedNotificationSchema } from '@modelcontextprotocol/sdk/types.js';
-import { spawn, type ChildProcess } from 'node:child_process';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { keylessBrainEnv } from './helpers/provider-env.ts';
+import { freePort, startServeHttp, type ServeHttp } from './helpers/serve-http.ts';
const MARKER = 'zelkova-status-marker-4q7';
@@ -174,10 +174,8 @@ describe('status-only serve: no brain → init → recovery in place', () => {
describe('status-only serve: lock contention → one shared serve --http (b)', () => {
let home: string;
let env: Record<string, string>;
- let http: ChildProcess | null = null;
+ let http: ServeHttp | 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-'));
@@ -191,7 +189,7 @@ describe('status-only serve: lock contention → one shared serve --http (b)', (
afterAll(async () => {
for (const c of opened) { try { await c.client.close(); } catch { /* best-effort */ } }
- if (http) { try { http.kill('SIGTERM'); } catch { /* best-effort */ } }
+ await http?.stop();
rmSync(home, { recursive: true, force: true });
});
@@ -213,9 +211,7 @@ 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);
+ http = await startServeHttp({ cwd: process.cwd(), env });
// 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 +223,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.base}/mcp`), { requestInit: { headers: { Authorization: `Bearer ${token}` } } }));
try {
const found = await client.callTool({ name: 'search', arguments: { query: MARKER } });
expect(found.isError).toBeFalsy();
@@ -244,7 +240,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 +270,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, reject) => { blocker!.once('error', reject); 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 +332,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');