Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(serve): a surviving serve re-binds resolve IPC once the owner is gone (#6647)
garrytan225062d28157
diff --git a/docs/architecture/key-files/mcp.md b/docs/architecture/key-files/mcp.mdindex a963f7225d..682bcdbd3b 100644--- a/docs/architecture/key-files/mcp.md+++ b/docs/architecture/key-files/mcp.md@@ -14,7 +14,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/mcp/result-rows.ts` — the transport side of the `search`/`query` row shape. `resolveResultRowsMode(engine, config)`: dual-plane `mcp.result_rows` (DB > file > 'lean'; a failed DB read falls to the file plane). `resultRowsForRequest(header, hostMode)`: the `X-Gbrain-Client` header naming `gbrain-remote-cli` (sent by `src/core/mcp-client.ts`) selects full rows, otherwise the host mode. The OAuth HTTP transport resolves both per request, the legacy bearer transport per tools/call, and stdio once at start (file plane only when the engine is degraded). The header is unverified and selects a row shape only; it must never gate anything security-relevant. Pinned by `test/mcp-result-rows-skew.test.ts`.-- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live listener (another serve) returns the null binding (that serve is the IPC provider). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.+- `src/mcp/resolve-ipc-binding.ts` — shared resolve-IPC listener wiring for BOTH serve transports. `bindResolveIpcForServe(engine, defaultSource)` binds the retrieval-reflex `resolve`, `turn_context`, and `context_pack` kinds (on Postgres the socket is keyed by `hash12(database_url)` plus `hash12(source)` of the serve's bound source under `~/.gbrain/run`, and the legacy URL-only socket is also bound when free; hooks pick theirs with `hookResolveSocketForConfig` — own source first, legacy fallback; the secret stays URL-keyed and the persistence socket brain-keyed; the bound-source posture rejects requests naming any other source; pinned by `test/resolve-ipc-source-keyed.test.ts`) plus the serve-delegated sync (`sync_start`/`sync_status`/`sync_abort` → `src/core/serve-sync-runner.ts`) and maintenance-sweep (`sweep_start`/`sweep_status` → `src/core/serve-sweep-runner.ts`) kinds — each delegation family in its OWN try/catch, so a runner failure logs `[serve-sync]`/`[serve-sweep] handlers unavailable` and the core kinds still start; both families share the `GBRAIN_SERVE_SYNC_IPC=0` kill switch. Engine-uniform: Postgres brains listen too (the hook lane is engine-free by design, so IPC through a serve is its only DB path there). Best-effort by contract — a bind failure never blocks the serve, and a socket already owned by a live or unresponsive listener (another serve) is left to it (that serve is the IPC provider, #4896). Each socket the serve could not bind (its source socket, the legacy socket, also when only the persistence listener came up) is retried on its own unref'd timer (`RESOLVE_IPC_REBIND_INTERVAL_MS` = 30 s plus up to 5 s jitter, `rebindDelayMs` injectable) through the same `startResolveIpcServer`, so a surviving serve takes over once the owner probes dead and logs `[resolve-ipc] took over <path>`; bind attempts are serialized per serve, `close()` clears the timers and closes a bind that lands after it, and persistence is never re-set-up (#6647, pinned by `test/resolve-ipc-rebind.serial.test.ts`). Reflex-channel event logging fires at DELIVERY (`onDelivered`/`onTurnContextDelivered`), never inside the resolver. Pinned by `test/resolve-ipc-binding.test.ts`.- `src/mcp/server.ts` — MCP stdio server. initialize and tools/list are built from `OPERATION_MANIFEST` (`src/core/operation-manifest.generated.ts`, every op minus its handler) so the handler graph behind `src/core/operations.ts` stays unloaded until it is needed; byte-identity with the eager registry across surfaces, strict params, read-only access, publish gates and the advertised surface is pinned by `test/mcp-tool-list-snapshot.test.ts`. Engine-dependent boot (`bootEngineDependents`: source scope, persistence consumer, resolve-IPC bind, startup sweep) and the dispatch/hot-memory imports wait for the handshake (`deferredBoot`, boot phase `initialize_wait`): they start when the first tools/list is answered, `BOOT_LIST_GRACE_MS` after initialize with no tools/list in flight, or `BOOT_WITHOUT_INITIALIZE_MS` after connect for a client that never initializes. Every tools/call and skill resource read awaits that boot, and a boot failure rejects them with the boot error while `startMcpServer` still rejects with it. Status-only mode (F4, `src/mcp/status-mode.ts`): over a status engine it lists only `gbrain_status`, answers other tools with one `serve_status_only` block, and every tool call re-probes and may recover in place (then `tools/list_changed`). `gbrain://capabilities` carries readiness[], the probed worker status (`stdioCapabilityReadiness`), and `surface`/`surface_source`. One `StdioSurfaceState` (`createStdioSurfaceState` in `surface.ts`) per process is the allow-set tools/list, dispatch (`allowedOps`, `stdioSurface`), skill resources and `gbrain_status` read; `request_tools {surface}` widens it for the session (stderr `surface_widened` audit line, then `tools/list_changed`), and `mcp.allow_session_widen` is resolved at boot. An ignored `GBRAIN_SURFACE` (`invalidSurfaceEnv`) adds one `surface_env_invalid` notice to the first successful tool result. After the engine boots it starts the onboarding cache (`startOnboardingRefresher` from `src/core/onboard/mcp-onboarding.ts`) with an idle gate on the in-flight RPC counter. `startMcpServer`'s optional `onBootPhase` reports each boot phase (`source_preflight` … `startup_sweep`) so `serve`'s boot-deadline line can name the one that never finished. Its SDK `Server` is initialized with the shared contract from `src/mcp/instructions.ts`, so a real client's `getInstructions()` is populated during the initialize handshake. `createDefaultWriteAdvisory(engine, {enabled, write?})` is the stdio lane's once-per-process unscoped-default-write advisory: on a mutating call whose source resolved to tier `seed_default` it runs `assessUnscopedDefaultWrite` (`src/core/source-resolver.ts`) and prints the warning to stderr; it latches on the first SUCCESSFUL assessment whatever the verdict (the aggregate is expensive and its inputs are process-stable), never latches on a failed one (fail-open for that write; the next mutating seed_default call retries), coalesces concurrent calls onto one in-flight assessment, and never blocks a write (a throwing writer still counts as assessed). Non-mutating calls and non-seed tiers return early without latching. Tool-call handler delegates to `dispatchToolCall` from `src/mcp/dispatch.ts` so stdio + HTTP transports share one validation, context-build, and error-format path. Stdin `'end'` / `'close'` shutdown hooks are skipped when `process.env.MCP_STDIO === '1'` — gateway-piped stdio MCP wrappers (OpenClaw's `bundle-mcp`) pipe the handshake then close their stdin half, which would otherwise kill the server before the first tool call; signal handlers (SIGTERM/SIGINT/SIGHUP) + the parent-process watchdog still cover legitimate disconnects. `src/commands/serve.ts` exposes `ServeOptions.mcpStdio?: boolean` as a test seam so the guard is exercisable without process.env mutation. The resolve-IPC listener (retrieval-reflex resolve / turn_context / context_pack + the serve-delegated sync and sweep kinds) binds through `src/mcp/resolve-ipc-binding.ts` (next entry) on BOTH serve transports — stdio here and `gbrain serve --http`; the shutdown chain awaits `shutdownDelegatedSync()` before `engine.disconnect()`. Pinned by `test/serve-stdio-lifecycle.test.ts` and `test/serve-stdio-roundtrip.test.ts`.diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex 42c4786099..55ba007a55 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -416,3 +416,4 @@ test/write-path-no-egress.serial.test.ts global-state global-state: binds a locatest/write-path-zero-llm.serial.test.ts R1 R1: mutates process.env (ANTHROPIC_API_KEY, OPENAI_API_KEY) so gated chat and embedding paths are livetest/writeback-nudge.serial.test.ts global-state global-state: patches process stdout/stderr/consoletest/writeback-review-fixes.serial.test.ts global-state global-state: process-wide test seams __resetCheckpointHarvestForTests; patches process stdout/stderr/console+test/resolve-ipc-rebind.serial.test.ts global-state global-state: binds real Unix sockets and spawns a child serve that is SIGKILLed; withEnv scopes GBRAIN_HOMEdiff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.tsindex f59099c1e3..14d59f8c5e 100644--- a/src/mcp/resolve-ipc-binding.ts+++ b/src/mcp/resolve-ipc-binding.ts@@ -42,10 +42,10 @@ import { persistenceSocketPathForConfig, startPersistenceIpcServer, type Persistimport { residentPersistenceConfig } from '../core/persistence/local-client.ts';export interface ResolveIpcBinding {- /** The bound listener, or null when binding was skipped/failed (best-effort). */- server: Server | null;- /** The socket path the listener bound (null when not bound). */- socketPath: string | null;+ /** The bound listener for this serve's own resolve socket, or null while it is not bound (best-effort). */+ readonly server: Server | null;+ /** The socket path the listener bound (null while not bound). */+ readonly socketPath: string | null;/** Dedicated persistence listener; its larger frames never enter hook handlers. */persistence?: PersistenceIpcBinding;/** Idempotent teardown: close the listener + reap the socket file. */@@ -54,6 +54,14 @@ export interface ResolveIpcBinding {const NULL_BINDING: ResolveIpcBinding = { server: null, socketPath: null, close: () => {} };+/** #6647: a serve that could not bind a resolve socket retries it this often (plus jitter). */+export const RESOLVE_IPC_REBIND_INTERVAL_MS = 30_000;+const RESOLVE_IPC_REBIND_JITTER_MS = 5_000;++function defaultRebindDelayMs(): number {+ return RESOLVE_IPC_REBIND_INTERVAL_MS + Math.floor(Math.random() * RESOLVE_IPC_REBIND_JITTER_MS);+}+/*** The turn_context assembly the serve answers with (minus the pressure gate).* Wave 5 D5 proactive brief (default off): the legacy block is assembled@@ -130,7 +138,11 @@ export async function bindResolveIpcForServe(engine: BrainEngine,defaultSource: string,persistenceProvider?: PersistenceIpcProvider,- opts: { rememberCallable?: boolean | (() => boolean) } = {},+ opts: {+ rememberCallable?: boolean | (() => boolean);+ /** Delay before each re-bind attempt of a socket this serve does not hold; tests inject a short one. */+ rebindDelayMs?: () => number;+ } = {},): Promise<ResolveIpcBinding> {let persistence: PersistenceIpcBinding | null = null;try {@@ -285,28 +297,49 @@ export async function bindResolveIpcForServe(boundSourceId: defaultSource,secret: ipcSecret,};- const server = await startResolveIpcServer(resolveSocket, handlers, serverOpts);- const legacyServer = legacySocket === resolveSocket ? null : await startResolveIpcServer(legacySocket, handlers, serverOpts);-- // startResolveIpcServer returns null when the socket is already owned- // by a live listener (another serve) — that serve is the IPC provider.- if (!server && !persistence) {- try { legacyServer?.close(); } catch { /* noop */ }- return NULL_BINDING;- }-+ // #6647: every socket this serve could not bind (its source socket, the+ // legacy socket) is retried on its own unref'd timer through the same+ // startResolveIpcServer, which still defers to a live or unknown owner+ // (#4896), so a surviving serve takes over only once the owner probes+ // dead. Bind attempts and close() run one at a time per serve; a bind+ // that completes after close() is closed at once. Persistence is never+ // re-set-up here.+ const slots = [resolveSocket, ...(legacySocket === resolveSocket ? [] : [legacySocket])]+ .map(path => ({ path, server: null as Server | null, timer: undefined as ReturnType<typeof setTimeout> | undefined }));+ const rebindDelayMs = opts.rebindDelayMs ?? defaultRebindDelayMs;let closed = false;+ let lifecycle: Promise<void> = Promise.resolve();+ const serialized = (step: () => Promise<void>): Promise<void> => (lifecycle = lifecycle.then(step, step));+ const bind = async (slot: (typeof slots)[number], retry: boolean): Promise<void> => {+ if (closed || slot.server) return;+ const server = await startResolveIpcServer(slot.path, handlers, serverOpts).catch(() => null);+ if (closed) { try { server?.close(); } catch { /* noop */ } return; }+ if (!server) { schedule(slot); return; }+ slot.server = server;+ if (retry) process.stderr.write(`[resolve-ipc] took over ${slot.path} after its previous owner exited\n`);+ };+ const schedule = (slot: (typeof slots)[number]): void => {+ if (closed) return;+ slot.timer = setTimeout(() => {+ slot.timer = undefined;+ void serialized(() => bind(slot, true));+ }, rebindDelayMs());+ slot.timer.unref?.();+ };+ await serialized(async () => { for (const slot of slots) await bind(slot, false); });++ const own = slots[0]!;return {- server,- socketPath: server ? resolveSocket : null,+ get server() { return own.server; },+ get socketPath() { return own.server ? resolveSocket : null; },...(persistence ? { persistence } : {}),close: () => {if (closed) return;closed = true;+ for (const slot of slots) clearTimeout(slot.timer);// server.close() unlinks the pathname THIS listener bound; never// blind-unlink the path — it may belong to a newer live serve (#4896).- try { server?.close(); } catch { /* noop */ }- try { legacyServer?.close(); } catch { /* noop */ }+ for (const slot of slots) { try { slot.server?.close(); } catch { /* noop */ } }persistence?.close();},};diff --git a/test/resolve-ipc-rebind.serial.test.ts b/test/resolve-ipc-rebind.serial.test.tsnew file mode 100644index 0000000000..06ab38f34e--- /dev/null+++ b/test/resolve-ipc-rebind.serial.test.ts@@ -0,0 +1,180 @@+/**+ * #6647 (option B): a serve that could not bind its resolve sockets because another serve owned them takes them over+ * once that owner is gone, on its own retry timer, without ever displacing a live owner (#4896).+ *+ * Protects: two serves for one source; the owner (a real child process) is SIGKILLed, leaving its socket file+ * behind; within one injected retry interval the survivor binds the source socket AND the legacy socket and answers+ * an authenticated `turn_context`; while the owner is alive the survivor keeps deferring; `close()` stops the retry+ * timers, and a bind that lands after `close()` is closed rather than left listening. Fails on master: the survivor+ * binds once at boot, gets nothing, and never retries, so the hook gets `IPC_UNAVAILABLE` until a serve restarts.+ *+ * Serial: spawns a child serve and binds real Unix sockets under a temp GBRAIN_HOME.+ */+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { spawn, type ChildProcess } from 'node:child_process';+import { once } from 'node:events';+import { bindResolveIpcForServe, type ResolveIpcBinding } from '../src/mcp/resolve-ipc-binding.ts';+import {+ IPC_UNAVAILABLE,+ readIpcSecretForConfig,+ requestTurnContext,+ resolveSocketPathForConfig,+ socketHasLiveListener,+ startResolveIpcServer,+} from '../src/core/context/resolve-ipc.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';++const INTERVAL_MS = 300;+const cfg = { engine: 'postgres' as const, database_url: 'postgresql://user:[email protected]:5432/rebind-brain' };+const BINDING_MODULE = new URL('../src/mcp/resolve-ipc-binding.ts', import.meta.url).pathname;++let engine: PGLiteEngine;+let tmp: string;+let child: ChildProcess | null = null;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { if (engine) await engine.disconnect(); }, 60_000);++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), 'gb-ipc-rebind-'));+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify(cfg));+});+afterEach(() => {+ if (child && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');+ child = null;+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ GBRAIN_HOME: tmp, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined, GBRAIN_SERVE_SYNC_IPC: '0' });+const inBrain = <T>(fn: () => Promise<T>) => withEnv(env(), fn);++/** A real serve process that binds the source + legacy sockets and then just stays alive. */+async function startOwnerProcess(source: string): Promise<ChildProcess> {+ const script = `+ const { bindResolveIpcForServe } = await import(${JSON.stringify(BINDING_MODULE)});+ const binding = await bindResolveIpcForServe({}, ${JSON.stringify(source)}, undefined, { rebindDelayMs: () => 3_600_000 });+ process.stdout.write((binding.socketPath ? 'bound ' + binding.socketPath : 'unbound') + '\\n');+ setInterval(() => {}, 1_000);+ `;+ const proc = spawn(process.execPath, ['-e', script], {+ env: { ...process.env, GBRAIN_HOME: tmp, GBRAIN_SERVE_SYNC_IPC: '0', GBRAIN_DATABASE_URL: '', DATABASE_URL: '' },+ stdio: ['ignore', 'pipe', 'pipe'],+ });+ let out = '';+ let err = '';+ proc.stderr!.on('data', d => { err += String(d); });+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => reject(new Error(`owner did not start: ${out} ${err}`)), 30_000);+ proc.stdout!.on('data', d => {+ out += String(d);+ if (out.includes('\n')) { clearTimeout(timer); resolve(); }+ });+ proc.on('exit', code => { clearTimeout(timer); reject(new Error(`owner exited ${code}: ${err}`)); });+ });+ expect(out.startsWith('bound ')).toBe(true);+ return proc;+}++async function waitUntil(predicate: () => Promise<boolean>, ms: number): Promise<boolean> {+ const until = Date.now() + ms;+ while (Date.now() < until) {+ if (await predicate()) return true;+ await new Promise(resolve => setTimeout(resolve, 25));+ }+ return predicate();+}++async function closeBinding(binding: ResolveIpcBinding): Promise<void> {+ const server = binding.server;+ const closed = server ? once(server, 'close') : Promise.resolve();+ binding.close();+ await closed;+}++describe('resolve IPC re-bind after the owning serve exits (#6647)', () => {+ it('a surviving serve takes over both sockets within one interval and answers turn_context', async () => {+ child = await startOwnerProcess('alpha');+ await inBrain(async () => {+ const own = resolveSocketPathForConfig(cfg, 'resolve', 'alpha')!;+ const legacy = resolveSocketPathForConfig(cfg)!;+ const survivor = await bindResolveIpcForServe(engine as unknown as BrainEngine, 'alpha', undefined, { rebindDelayMs: () => INTERVAL_MS });+ try {+ expect(survivor.server).toBeNull();+ // The owner is alive: the survivor keeps deferring across several intervals (#4896).+ await new Promise(resolve => setTimeout(resolve, INTERVAL_MS * 3));+ expect(survivor.server).toBeNull();++ child!.kill('SIGKILL');+ await once(child!, 'exit');+ expect(existsSync(own)).toBe(true);+ const killedAt = Date.now();++ const tookOver = await waitUntil(async () => survivor.server !== null, INTERVAL_MS * 2 + 500);+ expect(tookOver).toBe(true);+ expect(Date.now() - killedAt).toBeLessThan(INTERVAL_MS * 2 + 500);+ expect(survivor.socketPath).toBe(own);+ expect(await waitUntil(() => socketHasLiveListener(legacy), INTERVAL_MS * 2 + 500)).toBe(true);++ const secret = readIpcSecretForConfig(cfg)!;+ const reply = await requestTurnContext(own, { secret, sourceId: 'alpha', window: [{ role: 'user', text: 'hello' }] }, { timeoutMs: 5_000 });+ expect(reply).not.toBe(IPC_UNAVAILABLE);+ expect(reply).toMatchObject({ ok: true, protocol: 2 });+ } finally {+ await closeBinding(survivor);+ }+ });+ }, 60_000);++ it('close() stops the retry timer: a serve closed while deferring never binds later', async () => {+ child = await startOwnerProcess('beta');+ await inBrain(async () => {+ const own = resolveSocketPathForConfig(cfg, 'resolve', 'beta')!;+ const deferred = await bindResolveIpcForServe(engine as unknown as BrainEngine, 'beta', undefined, { rebindDelayMs: () => INTERVAL_MS });+ expect(deferred.server).toBeNull();+ deferred.close();+ child!.kill('SIGKILL');+ await once(child!, 'exit');+ await new Promise(resolve => setTimeout(resolve, INTERVAL_MS * 3));+ expect(deferred.server).toBeNull();+ expect(await socketHasLiveListener(own)).toBe(false);+ });+ }, 60_000);++ it('a bind that completes after close() is closed instead of left listening', async () => {+ await inBrain(async () => {+ const own = resolveSocketPathForConfig(cfg, 'resolve', 'gamma')!;+ const legacy = resolveSocketPathForConfig(cfg)!;+ // Close lands at every point of a 1 ms retry loop: before, during and after the claim/probe/listen.+ for (let closeAfterMs = 0; closeAfterMs <= 8; closeAfterMs++) {+ const owner = await startResolveIpcServer(own, { resolve: async () => null }, { boundSourceId: 'gamma' });+ const legacyOwner = await startResolveIpcServer(legacy, { resolve: async () => null }, { boundSourceId: 'gamma' });+ expect(owner).not.toBeNull();+ expect(legacyOwner).not.toBeNull();+ let scheduled = 0;+ const deferred = await bindResolveIpcForServe(engine as unknown as BrainEngine, 'gamma', undefined, {+ rebindDelayMs: () => { scheduled++; return 1; },+ });+ expect(deferred.server).toBeNull();+ await Promise.all([once(owner!, 'close'), once(legacyOwner!, 'close'), owner!.close(), legacyOwner!.close()]);+ await new Promise(resolve => setTimeout(resolve, closeAfterMs));+ deferred.close();+ await new Promise(resolve => setTimeout(resolve, 100));+ expect(await socketHasLiveListener(own)).toBe(false);+ expect(await socketHasLiveListener(legacy)).toBe(false);+ const after = scheduled;+ await new Promise(resolve => setTimeout(resolve, 50));+ expect(scheduled).toBe(after);+ }+ });+ }, 60_000);+});