Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
resolve IPC: key the Postgres resolve socket by database URL and source (#5042)
garrytan52ac5e8bb56f
diff --git a/src/commands/hook.ts b/src/commands/hook.tsindex 8902fa7620..8cab17b12a 100644--- a/src/commands/hook.ts+++ b/src/commands/hook.ts@@ -53,7 +53,7 @@ import {readIpcSecretForConfig,requestTurnContext,requestContextPack,- resolveSocketPathForConfig,+ hookResolveSocketForConfig,CONTEXT_PACK_CLIENT_TIMEOUT_MS,type TurnContextResponse,type ContextPackResponse,@@ -530,7 +530,7 @@ async function hookSessionStart(io: HookIo): Promise<number> {// Engine-uniform (#4245): same config-keyed socket/secret resolution// as the user-prompt and compact arms (PGLite data dir; Postgres// hash12(database_url) run-dir). Null → silent skip, as before.- const packSocket = resolveSocketPathForConfig(cfg);+ const packSocket = await hookResolveSocketForConfig(cfg, process.env.GBRAIN_SOURCE);if (packSocket) {const secret = readIpcSecretForConfig(cfg);if (secret) {@@ -1156,7 +1156,7 @@ async function hookUserPrompt(io: HookIo): Promise<number> {// Postgres off hash12(database_url) under ~/.gbrain/run. Null = no// keying material at all (no config, thin-client remote) — ENGINE-FREE// means no direct-engine fallback here; pull-mode covers it.- const socketPath = resolveSocketPathForConfig(cfg);+ const socketPath = await hookResolveSocketForConfig(cfg, process.env.GBRAIN_SOURCE);if (!socketPath) {return { outcome: 'degraded', reason: 'no_pglite_path' };}@@ -1358,7 +1358,7 @@ async function hookCompact(io: HookIo): Promise<number> {// leftover database_path must not probe the PGLite socket (the resolver// checks engine first); a Postgres brain probes its hash12(database_url)// run-dir socket instead. Null = no keying material → degrade.- const compactSocket = resolveSocketPathForConfig(cfg);+ const compactSocket = await hookResolveSocketForConfig(cfg, process.env.GBRAIN_SOURCE);if (!compactSocket) { outcome = 'degraded'; reason = 'no_pglite_path'; return; }const secret = readIpcSecretForConfig(cfg);if (!secret) { outcome = 'degraded'; reason = 'no_serve'; return; }@@ -1493,7 +1493,7 @@ async function hookStop(io: HookIo): Promise<number> {// exactly like the compact call (OV2-9/OV-A6); every failure below is// degraded-not-blocking: the banked file is the durable artifact and// the sweep extracts it when serve is away.- const socket = resolveSocketPathForConfig(cfg);+ const socket = await hookResolveSocketForConfig(cfg, process.env.GBRAIN_SOURCE);if (!socket) return 'no_pglite_path';const secret = readIpcSecretForConfig(cfg);if (!secret) return 'no_serve';diff --git a/src/core/context/resolve-ipc.ts b/src/core/context/resolve-ipc.tsindex a798610157..7e39d722ca 100644--- a/src/core/context/resolve-ipc.ts+++ b/src/core/context/resolve-ipc.ts@@ -351,20 +351,38 @@ export interface IpcPathConfig {* database_path must not key off the path — there is no PGLite brain (and* no serve) behind it (v0.45.7 gate, preserved).*- * Multi-serve note: on Postgres several serves for the SAME database_url- * share this path; the first LIVE provider wins — a later serve probes the- * socket, finds a live owner, and defers (null binding) instead of unlinking- * it (#4896). Bound-source rejection [CX2-10] still applies per request.+ * Multi-serve note (#5042): on Postgres every serve binds the resolve+ * socket of its own bound source (`sourceId` → `resolve-<hash12(url)>-+ * <hash12(source)>.sock`), so serves for different sources of one database+ * coexist. Without `sourceId` this returns the legacy URL-only path, which a+ * serve also binds when it is free (first LIVE provider wins; a later serve+ * defers instead of unlinking it, #4896). The persistence socket ignores+ * `sourceId`: it routes to the single resident owner, so it stays+ * brain-keyed. Bound-source rejection [CX2-10] still applies per request.*/-export function resolveSocketPathForConfig(cfg: IpcPathConfig | null | undefined, kind: 'resolve' | 'persistence' = 'resolve'): string | null {+export function resolveSocketPathForConfig(cfg: IpcPathConfig | null | undefined, kind: 'resolve' | 'persistence' = 'resolve', sourceId?: string): string | null {if (!cfg) return null;if (cfg.engine === 'pglite' && cfg.database_path) return localIpcSocketPath(join(cfg.database_path, `.gbrain-${kind}.sock`));if (cfg.engine === 'postgres' && cfg.database_url) {- return localIpcSocketPath(join(ipcRunDir(), `${kind}-${hash12(cfg.database_url)}.sock`));+ const sourceKey = kind === 'resolve' && sourceId ? `-${hash12(sourceId)}` : '';+ return localIpcSocketPath(join(ipcRunDir(), `${kind}-${hash12(cfg.database_url)}${sourceKey}.sock`));}return null;}+/**+ * The resolve socket a hook calls (#5042): its own source's socket+ * (`GBRAIN_SOURCE`, else `default`) when a serve listens there, else the+ * legacy URL-only socket (an older serve, or a serve bound to a source the+ * hook does not name). PGLite has a single path (one serve per data dir).+ */+export async function hookResolveSocketForConfig(cfg: IpcPathConfig | null | undefined, sourceId: string | undefined): Promise<string | null> {+ const legacy = resolveSocketPathForConfig(cfg);+ const keyed = resolveSocketPathForConfig(cfg, 'resolve', sourceId || 'default');+ if (!legacy || !keyed || keyed === legacy) return legacy;+ return (await socketHasLiveListener(keyed)) ? keyed : legacy;+}+/*** Canonical shared-secret path for a brain config — same engine-uniform* keying as resolveSocketPathForConfig (data dir on PGLite, hash12-keyeddiff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.tsindex fe06ede53a..c51e03de5c 100644--- a/src/mcp/resolve-ipc-binding.ts+++ b/src/mcp/resolve-ipc-binding.ts@@ -26,6 +26,7 @@ import {startResolveIpcServer,ensureIpcSecretForConfig,type IpcHandlers,+ type IpcServerOpts,} from '../core/context/resolve-ipc.ts';import { resolveEntitiesToPointers, logDeliveredReflexPointers } from '../core/context/retrieval-reflex.ts';import { lexicalArmsEnabled } from '../core/context/reflex.ts';@@ -90,8 +91,11 @@ export async function bindResolveIpcForServe(let persistence: PersistenceIpcBinding | null = null;try {const cfg = loadConfig();- const resolveSocket = resolveSocketPathForConfig(cfg);- if (!resolveSocket) return NULL_BINDING;+ // #5042: this serve's own source-keyed socket, plus the legacy URL-only+ // socket when it is free (older hooks and hooks naming no source).+ const resolveSocket = resolveSocketPathForConfig(cfg, 'resolve', defaultSource);+ const legacySocket = resolveSocketPathForConfig(cfg);+ if (!resolveSocket || !legacySocket) return NULL_BINDING;// The owner socket follows the brain the engine opened, which may be a mount (#5237).const owner = residentPersistenceConfig(cfg);@@ -159,90 +163,92 @@ export async function bindResolveIpcForServe(}}- const server = await startResolveIpcServer(- resolveSocket,- {- // [CX2-10] Bound-source posture for BOTH kinds: the IPC layer- // rejects any resolve/turn_context request naming a source other- // than boundSourceId ('source_mismatch'), so the only sourceId that- // reaches this handler is the bound one or absent — and the handler- // resolves against the server's OWN registered source regardless.- resolve: (req) =>- resolveEntitiesToPointers(- engine,- defaultSource,- req.candidates ?? [],- {- priorContextText: req.priorContextText,- maxPointers: req.maxPointers,- suppression: req.suppression,- // v0.46.15 kill switch: either side may disable — a client- // `false` wins, else the server's own file-config gate.- // Config is re-read PER REQUEST (adversarial F3): `gbrain- // serve` is long-running, and the switch's whole value is- // reverting a false-fire regression on the NEXT TURN with a- // config edit — a startup snapshot would freeze it until a- // serve restart. loadConfig is a file read (~1ms) inside the- // 400ms IPC budget.- lexicalArms: req.lexicalArms === false ? false : lexicalArmsEnabled(loadConfig()),- },- ),- // IPC v2 [ENG-3]: per-turn context assembly for the hook command.- // [CX2-10] Always assembles against the server's OWN registered- // source — cross-source requests are rejected in the IPC layer via- // boundSourceId below, and the handler never honors a caller source.- turn_context: (req) =>- assembleTurnContext(engine, {- sourceId: defaultSource,- window: req.window ?? [],+ const handlers: IpcHandlers = {+ // [CX2-10] Bound-source posture for BOTH kinds: the IPC layer+ // rejects any resolve/turn_context request naming a source other+ // than boundSourceId ('source_mismatch'), so the only sourceId that+ // reaches this handler is the bound one or absent — and the handler+ // resolves against the server's OWN registered source regardless.+ resolve: (req) =>+ resolveEntitiesToPointers(+ engine,+ defaultSource,+ req.candidates ?? [],+ {priorContextText: req.priorContextText,- sessionId: req.sessionId,- maxBytes: req.maxBytes,- // Per-request config read — same next-turn-revert rationale as- // the resolve handler above (adversarial F3).- lexicalArms: lexicalArmsEnabled(loadConfig()),- }),- // v0.45.7 ambient recall: boundary context pack. Extracted to- // context-pack-handler.ts (directly testable against a real engine);- // the runtime owns entity merge, banking, the since-cursor, and the- // complete-pack-only monotonic cursor advance.- context_pack: makeContextPackIpcHandler(engine, defaultSource),- ...syncHandlers,- ...sweepHandlers,- },- {- // The IPC resolve path IS the ambient reflex channel. Logging happens- // at DELIVERY (post-write), not inside the resolver — a block the- // client's 250ms budget abandoned was never injected, and counting it- // would corrupt the volunteered-vs-used precision stats (red-team).- // Volunteer-stage PROBE resolves (wide ungated pool) are skipped for- // the same reason: the pool is not injected pointers. NOTE (ship- // security review): on the PGLite/IPC rung the gated survivors are- // NOT re-logged anywhere (the client has no engine handle) — openclaw- // volunteer events cover the direct-Postgres rung only, see- // reflex.ts. The probe claim is a WIRE FIELD, so it is honored only- // when the request is volunteer-SHAPED (slug-only suppression + the- // wide volunteer pool cap): a normal pointer resolve stamping- // probe:'volunteer' to evade delivery telemetry still logs.- onDelivered: (block, req) => {- if (isVolunteerProbeShaped(req)) return;- logDeliveredReflexPointers(engine, block.pointers);- },- // The hook lane's feedback loop (#2095 closed over turn_context):- // the delivered block's post-trim volunteered pages + pointers land- // in context_volunteer_events under the request's channel. Body- // lives in volunteer-events.ts (logTurnContextDeliveryFireAndForget)- // so the shipped wiring is unit-testable.- onTurnContextDelivered: (result, req) =>- logTurnContextDeliveryFireAndForget(engine, result, req),- boundSourceId: defaultSource,- secret: ipcSecret,+ maxPointers: req.maxPointers,+ suppression: req.suppression,+ // v0.46.15 kill switch: either side may disable — a client+ // `false` wins, else the server's own file-config gate.+ // Config is re-read PER REQUEST (adversarial F3): `gbrain+ // serve` is long-running, and the switch's whole value is+ // reverting a false-fire regression on the NEXT TURN with a+ // config edit — a startup snapshot would freeze it until a+ // serve restart. loadConfig is a file read (~1ms) inside the+ // 400ms IPC budget.+ lexicalArms: req.lexicalArms === false ? false : lexicalArmsEnabled(loadConfig()),+ },+ ),+ // IPC v2 [ENG-3]: per-turn context assembly for the hook command.+ // [CX2-10] Always assembles against the server's OWN registered+ // source — cross-source requests are rejected in the IPC layer via+ // boundSourceId below, and the handler never honors a caller source.+ turn_context: (req) =>+ assembleTurnContext(engine, {+ sourceId: defaultSource,+ window: req.window ?? [],+ priorContextText: req.priorContextText,+ sessionId: req.sessionId,+ maxBytes: req.maxBytes,+ // Per-request config read — same next-turn-revert rationale as+ // the resolve handler above (adversarial F3).+ lexicalArms: lexicalArmsEnabled(loadConfig()),+ }),+ // v0.45.7 ambient recall: boundary context pack. Extracted to+ // context-pack-handler.ts (directly testable against a real engine);+ // the runtime owns entity merge, banking, the since-cursor, and the+ // complete-pack-only monotonic cursor advance.+ context_pack: makeContextPackIpcHandler(engine, defaultSource),+ ...syncHandlers,+ ...sweepHandlers,+ };+ const serverOpts: IpcServerOpts = {+ // The IPC resolve path IS the ambient reflex channel. Logging happens+ // at DELIVERY (post-write), not inside the resolver — a block the+ // client's 250ms budget abandoned was never injected, and counting it+ // would corrupt the volunteered-vs-used precision stats (red-team).+ // Volunteer-stage PROBE resolves (wide ungated pool) are skipped for+ // the same reason: the pool is not injected pointers. NOTE (ship+ // security review): on the PGLite/IPC rung the gated survivors are+ // NOT re-logged anywhere (the client has no engine handle) — openclaw+ // volunteer events cover the direct-Postgres rung only, see+ // reflex.ts. The probe claim is a WIRE FIELD, so it is honored only+ // when the request is volunteer-SHAPED (slug-only suppression + the+ // wide volunteer pool cap): a normal pointer resolve stamping+ // probe:'volunteer' to evade delivery telemetry still logs.+ onDelivered: (block, req) => {+ if (isVolunteerProbeShaped(req)) return;+ logDeliveredReflexPointers(engine, block.pointers);},- );+ // The hook lane's feedback loop (#2095 closed over turn_context):+ // the delivered block's post-trim volunteered pages + pointers land+ // in context_volunteer_events under the request's channel. Body+ // lives in volunteer-events.ts (logTurnContextDeliveryFireAndForget)+ // so the shipped wiring is unit-testable.+ onTurnContextDelivered: (result, req) =>+ logTurnContextDeliveryFireAndForget(engine, result, req),+ 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) return NULL_BINDING;+ if (!server && !persistence) {+ try { legacyServer?.close(); } catch { /* noop */ }+ return NULL_BINDING;+ }let closed = false;return {@@ -255,6 +261,7 @@ export async function bindResolveIpcForServe(// 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 */ }persistence?.close();},};diff --git a/test/resolve-ipc-source-keyed.test.ts b/test/resolve-ipc-source-keyed.test.tsnew file mode 100644index 0000000000..23690af875--- /dev/null+++ b/test/resolve-ipc-source-keyed.test.ts@@ -0,0 +1,90 @@+/**+ * #5042: on Postgres the resolve socket is keyed by database URL + source, so+ * several serves bound to different sources of one brain each own a socket+ * and each hook reaches the serve for its own source.+ *+ * Protects: a second serve for another source binds instead of deferring to+ * the first (pre-fix both computed the URL-only path, the second got a null+ * binding, and every hook naming its source got `source_mismatch` from the+ * first); hooks fall back to the legacy URL-only socket (older serves, hooks+ * naming no source); the persistence socket stays brain-keyed (O-ENG-15).+ */+import { afterEach, beforeEach, describe, expect, it } from 'bun:test';+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { once } from 'node:events';+import type { Server } from 'node:net';+import { bindResolveIpcForServe, type ResolveIpcBinding } from '../src/mcp/resolve-ipc-binding.ts';+import { hookResolveSocketForConfig, IPC_UNAVAILABLE, resolveSocketPathForConfig, resolveViaIpc, startResolveIpcServer } from '../src/core/context/resolve-ipc.ts';+import { persistenceSocketPathForConfig } from '../src/core/persistence/ipc.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { withEnv } from './helpers/with-env.ts';++let tmp: string;+beforeEach(() => { tmp = mkdtempSync(join(tmpdir(), 'gb-ipc-source-')); });+afterEach(() => { rmSync(tmp, { recursive: true, force: true }); });++const cfg = { engine: 'postgres' as const, database_url: 'postgresql://user:[email protected]:5432/brain' };+const inBrain = <T>(fn: () => Promise<T>) => {+ mkdirSync(join(tmp, '.gbrain'), { recursive: true });+ writeFileSync(join(tmp, '.gbrain', 'config.json'), JSON.stringify(cfg));+ return withEnv({ GBRAIN_HOME: tmp, GBRAIN_DATABASE_URL: undefined, DATABASE_URL: undefined, GBRAIN_SERVE_SYNC_IPC: '0' }, fn);+};+async function closeAll(bindings: ResolveIpcBinding[], servers: Array<Server | null> = []) {+ const all = [...bindings.map(b => b.server), ...servers].filter(Boolean) as Server[];+ const closed = all.map(server => once(server, 'close'));+ for (const binding of bindings) binding.close();+ for (const server of servers) server?.close();+ await Promise.all(closed);+}++describe('source-keyed resolve socket (#5042)', () => {+ it('serves for different sources coexist and each hook reaches its own source', async () => {+ await inBrain(async () => {+ const alpha = await bindResolveIpcForServe({} as BrainEngine, 'alpha');+ const beta = await bindResolveIpcForServe({} as BrainEngine, 'beta');+ try {+ expect(alpha.server).not.toBeNull();+ expect(beta.server).not.toBeNull();+ expect(alpha.socketPath).toBe(resolveSocketPathForConfig(cfg, 'resolve', 'alpha'));+ expect(beta.socketPath).toBe(resolveSocketPathForConfig(cfg, 'resolve', 'beta'));+ expect(alpha.socketPath).not.toBe(beta.socketPath);++ for (const source of ['alpha', 'beta']) {+ const socket = await hookResolveSocketForConfig(cfg, source);+ expect(socket).toBe(resolveSocketPathForConfig(cfg, 'resolve', source));+ expect(await resolveViaIpc(socket!, { candidates: [], sourceId: source })).toBeNull();+ }+ // A hook naming no source falls back to the legacy socket, which the first serve also holds.+ const legacy = resolveSocketPathForConfig(cfg)!;+ expect(await hookResolveSocketForConfig(cfg, undefined)).toBe(legacy);+ expect(await resolveViaIpc(legacy, { candidates: [] })).toBeNull();+ // The legacy socket alone is what every hook used to reach: wrong source for beta.+ expect(await resolveViaIpc(legacy, { candidates: [], sourceId: 'beta' })).toBe(IPC_UNAVAILABLE);+ } finally { await closeAll([alpha, beta]); }+ });+ });++ it('a hook still reaches an older serve that bound only the legacy socket', async () => {+ await inBrain(async () => {+ const legacy = resolveSocketPathForConfig(cfg)!;+ const old = await startResolveIpcServer(legacy, { resolve: async () => null }, { boundSourceId: 'beta' });+ try {+ expect(old).not.toBeNull();+ expect(await hookResolveSocketForConfig(cfg, 'beta')).toBe(legacy);+ expect(await resolveViaIpc(legacy, { candidates: [], sourceId: 'beta' })).toBeNull();+ } finally { await closeAll([], [old]); }+ });+ });++ it('the persistence socket stays brain-keyed and PGLite keeps one path', async () => {+ await inBrain(async () => {+ const persistence = persistenceSocketPathForConfig(cfg)!;+ expect(persistence).toBe(resolveSocketPathForConfig(cfg, 'persistence', 'alpha')!);+ expect(persistence).toBe(resolveSocketPathForConfig(cfg)!.replace(/resolve-([0-9a-f]{12})\.sock$/, 'persistence-$1.sock'));+ const pglite = { engine: 'pglite' as const, database_path: join(tmp, 'db') };+ expect(resolveSocketPathForConfig(pglite, 'resolve', 'alpha')).toBe(resolveSocketPathForConfig(pglite));+ });+ });+});