Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(serve): bind the persistence owner for the brain the engine opened (#5237)
garrytan650f0b4b215b
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 514b383454..a60653c6f9 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -51,7 +51,7 @@ The page operations that submit through this layer are in [Core Services (2/3)](- `src/core/persistence/native-file-target.ts` — shared preparation/Git execution spelling resolution. Native directory-entry inode/device identity proves aliases; no global case folding or separator rewrite. Missing suffixes retain exact spelling, descendant symlinks and ambiguous aliases refuse, and physical root identity is rechecked. Exact POSIX case-distinct names and literal backslashes remain distinct.-- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`.+- `src/core/persistence/{ipc,local-client}.ts` — dedicated local persistence socket and engine-free CLI delegation. The narrow protocol carries a durable brain UUID, existing local writer registration, client source/cwd, and one request UUID; the production provider verifies current authority and dispatches through operations. Max frame 32 MiB (five-million-byte content even with JSON escaping), eight connections/in-flight dispatches, incomplete-frame timeout 15s. Lost responses preserve the original request ID with unknown submission state and never automatically replay or open another engine. Brain/mount routing precedes lock inspection; owner-side `resolveSourceId(..., { skipLocalSignals: true })` prevents serve env/dotfiles from overriding client routing. `bindResolveIpcForServe` accepts the provider as its third argument and closes the dedicated listener with hook IPC. `residentPersistenceConfig` resolves a resident serve's brain the same way (`--brain`, `GBRAIN_BRAIN_ID`, `.gbrain-mount`, mount path), so the owner socket and the provider's consumer config follow a mounted brain instead of the host config (#5237); hook IPC stays keyed off the host config. Tests: `test/persistence-ipc.test.ts`, `test/persistence-local-client.test.ts`, `test/resolve-ipc-binding.test.ts`, `test/serve-mounted-owner.serial.test.ts`.- `src/core/persistence/{schema,model,journal,authority,identity,ownership,coordinator,consumer,service,page-mutations,page-prepare,source-storage,control,context,digest,prepared-import}.ts` — dedicated durable mutation admission and permanent principal-scoped replay IDs, atomic quota reservations, registered canonical worktree ownership, native lock publication, conditional file recovery, and coherent receipt completion. Recovery presence blocks its whole worktree even when the receipt is terminal; admission and publication both enforce the fence. Migration 159 adds a partial worktree/sequence recovery index so permanent receipt retention does not turn the fence into a history scan. Canonical file preparation honors a recorded source path or contained absolute capture file URI within the registered owner root (relative or host-only `file://` URIs are absent); symlink confinement and coherent snapshot checks still apply. A slug under a `storage.db_only` dir declared in `gbrain.yml` (matched case-insensitively, derive-phase defaults excluded) publishes database-only when a live page's file is absent (the case that otherwise refuses as an uncoordinated removal), with receipt `write_through.skipped: db_only`; new pages, tombstones, missing-file-tolerant callers and present cache files keep the full file treatment and never read `gbrain.yml`. `gbrain.yml` is read from the source root, like doctor, export and backup, not the git root `manageGitignore` uses, which differs for a monorepo-subdir source. `source-storage.ts` caches the parsed file per version and logs an invalid one (unreadable, overlapping tiers, db_only declared in syntax that resolves nothing) once; that missing-file refusal then reports `storage_error`, and the Git effect treats the page as not db_only. The drift guard applies the import rule for a file without an explicit `type:` (the stored type stands) and compares titles trimmed, as the parser reads them; a real drift refuses with `detail: file_database_drift` and a filled `sources reconcile` command. The first write that binds an origin in a Git-subdirectory source with no slug-root pin pins the inferred mode in its publication transaction (a concurrent different pin refuses with `revision_conflict`), so later pages cannot flip the inference. A new page captured from a file inside the source (`capture_path`, resolved from the trusted CLI `local_file` in `page-mutations`, only when sync would give that file the capture slug under the source's slug-root mode) publishes to that file when its bytes are exactly the captured input; otherwise capture records `source_uri: cli-file`, never a host path. `acquireWorktree(binding, waitMs, signal, engine)` re-stamps a device-only physical-root change under the native lock (see `physical-root.ts`); without an engine, or when birth time is zero, it refuses with `detail: physical_root_device_changed` and the filled self-transfer commands. Version snapshots retain nullable `is_deleted`: new snapshots restore recorded deletion state atomically with content, tags, files and receipts; legacy NULL preserves current deletion state. Canonical no-op detection compares deletion state as well as content. Page replacement preconditions are checked before no-op detection; providers prepare outside publication transactions; recovery never restores unexpected bytes. Local registrations retain immutable CLI/stdio trust lanes and hashed credentials; accepted authority is intersected with current grants. `limits.ts` reads every `persistence.limits.*` cap and `persistence.receipt_retention_days` (default 30) from the database config table (`JOURNAL_CONFIG_KEYS`, registered for `gbrain config set`; malformed values are rejected at set time). Cumulative defaults (250,000 lifetime IDs and 1.5 GiB receipt bytes per principal, 8 GiB brain receipt bytes) cover 600 admissions a day for a year; each admission reserves at least 16 KiB and a compacted receipt keeps about 4 KiB. A cumulative `queue_capacity` refusal names its key in `detail` and suggests a `gbrain config set` value covering one more year at the recent admission rate (`oneYearCapacity`). Compaction filters out receipts with unfinished effects before its batch limit. `test/persistence-journal.test.ts` exercises real PGLite and optional guarded Postgres admission, cancellation, compaction, conflict and publication recovery; `test/persistence-capacity.test.ts` covers retention, the compaction filter, capacity hints and default sizing. `service.ts` also dispatches operation `decide_proposal` (S9 proposal accept/undo) to `facts/proposal-supersede.ts`.diff --git a/src/commands/serve-http.ts b/src/commands/serve-http.tsindex 25e0aa2cdd..d349e4a537 100644--- a/src/commands/serve-http.ts+++ b/src/commands/serve-http.ts@@ -42,6 +42,7 @@ import { canonicalOAuthResource } from '../core/oauth-grants.ts';import type { McpSurface } from '../mcp/surface.ts';import { bindResolveIpcForServe } from '../mcp/resolve-ipc-binding.ts';import { createPersistenceIpcProvider } from '../core/persistence/provider.ts';+import { residentPersistenceConfig } from '../core/persistence/local-client.ts';import { resolveMcpStdioSourceScope } from '../mcp/server.ts';import { loadConfig, type GBrainConfig } from '../core/config.ts';import { buildError } from '../core/errors.ts';@@ -880,7 +881,7 @@ ${bootstrapFromEnvconst ipcBinding = await bindResolveIpcForServe(engine,(await resolveMcpStdioSourceScope(engine)).sourceId,- await createPersistenceIpcProvider(engine, config),+ await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? config),);if (ipcBinding.socketPath) {console.error(` Resolve IPC: ${ipcBinding.socketPath}`);diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.tsindex 1211254fb4..3477a08564 100644--- a/src/core/persistence/local-client.ts+++ b/src/core/persistence/local-client.ts@@ -4,6 +4,7 @@ import { readFileSync } from 'node:fs';import { join } from 'node:path';import { configDir, type GBrainConfig } from '../config.ts';import { resolveBrainId } from '../brain-resolver.ts';+import { getCliOptions } from '../cli-options.ts';import { loadMounts, type MountEntry } from '../brain-registry.ts';import { inspectLockHolder } from '../pglite-lock.ts';import { resolveSourceIdEngineFree } from '../source-resolver.ts';@@ -29,6 +30,19 @@ export function persistenceConfigForBrain(return { engine: mount.engine, database_path: mount.database_path, database_url: mount.database_url } as GBrainConfig;}+/**+ * The persistence config of the brain a resident serve's engine opened, resolved+ * exactly as the CLI resolves it (--brain, GBRAIN_BRAIN_ID, .gbrain-mount, mount+ * path), so a mounted serve binds the owner socket the CLI probes (#5237).+ * Host-level settings stay; only the datastore identity follows the mount.+ */+export function residentPersistenceConfig(hostConfig: GBrainConfig | null, cwd = process.cwd()): GBrainConfig | null {+ const brainId = resolveBrainId(getCliOptions().brain, cwd);+ if (brainId === 'host') return hostConfig;+ const brain = persistenceConfigForBrain(hostConfig, brainId, loadMounts())!;+ return { ...hostConfig, engine: brain.engine, database_path: brain.database_path, database_url: brain.database_url } as GBrainConfig;+}+/** Reads an existing registration only. Revocation/missing credentials never create a new principal. */export function readPersistenceCliRegistration(brainId: string): PersistenceIpcRegistration {// Capability validation has already constrained this filename component to a UUID.diff --git a/src/mcp/resolve-ipc-binding.ts b/src/mcp/resolve-ipc-binding.tsindex 62ef4f49e3..fe06ede53a 100644--- a/src/mcp/resolve-ipc-binding.ts+++ b/src/mcp/resolve-ipc-binding.ts@@ -34,6 +34,7 @@ import { assembleTurnContext } from '../core/context/turn-context.ts';import { makeContextPackIpcHandler } from './context-pack-handler.ts';import { logTurnContextDeliveryFireAndForget } from '../core/context/volunteer-events.ts';import { persistenceSocketPathForConfig, startPersistenceIpcServer, type PersistenceIpcProvider, type PersistenceIpcBinding } from '../core/persistence/ipc.ts';+import { residentPersistenceConfig } from '../core/persistence/local-client.ts';export interface ResolveIpcBinding {/** The bound listener, or null when binding was skipped/failed (best-effort). */@@ -92,8 +93,10 @@ export async function bindResolveIpcForServe(const resolveSocket = resolveSocketPathForConfig(cfg);if (!resolveSocket) return NULL_BINDING;- if (persistenceProvider && cfg?.engine === 'pglite') {- const persistenceSocket = persistenceSocketPathForConfig(cfg);+ // The owner socket follows the brain the engine opened, which may be a mount (#5237).+ const owner = residentPersistenceConfig(cfg);+ if (persistenceProvider && owner?.engine === 'pglite') {+ const persistenceSocket = persistenceSocketPathForConfig(owner);if (persistenceSocket) {try { persistence = await startPersistenceIpcServer(persistenceSocket, persistenceProvider); }catch {diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex f96df71f56..dbcd490de2 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -15,6 +15,7 @@ import { loadConfig } from '../core/config.ts';import { gcSessionContextState } from '../core/context/session-state.ts';import { bindResolveIpcForServe } from './resolve-ipc-binding.ts';import { createPersistenceIpcProvider } from '../core/persistence/provider.ts';+import { residentPersistenceConfig } from '../core/persistence/local-client.ts';import { resolveMcpInstructions } from './instructions.ts';import { installCapabilitiesResource, mcpAdministrationGuidance } from './capabilities.ts';import { createSkillResources } from './skill-resources.ts';@@ -362,7 +363,7 @@ export async function startMcpServer(engine: BrainEngine, opts: { surface?: McpSipcBinding = await bindResolveIpcForServe(engine,(await resolveMcpStdioSourceScope(engine)).sourceId,- await createPersistenceIpcProvider(engine, config ?? { engine: engine.kind }),+ await createPersistenceIpcProvider(engine, residentPersistenceConfig(config) ?? { engine: engine.kind }),);// v0.45.7 ambient recall: age out stale session cursors once per serve bootdiff --git a/test/persistence-local-client.test.ts b/test/persistence-local-client.test.tsindex 156bdb3bef..d413f53a5d 100644--- a/test/persistence-local-client.test.ts+++ b/test/persistence-local-client.test.ts@@ -1,8 +1,8 @@import { afterEach, describe, expect, test } from 'bun:test';-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { persistenceConfigForBrain, readPersistenceCliRegistration, maybeDelegateLocalOperation } from '../src/core/persistence/local-client.ts';+import { persistenceConfigForBrain, readPersistenceCliRegistration, maybeDelegateLocalOperation, residentPersistenceConfig } from '../src/core/persistence/local-client.ts';import { resolveSourceId } from '../src/core/source-resolver.ts';import type { BrainEngine } from '../src/core/engine.ts';import { withEnv } from './helpers/with-env.ts';@@ -22,6 +22,18 @@ describe('engine-free local persistence routing', () => {expect(() => persistenceConfigForBrain(host, 'example-brain', [{ ...mounts[0], enabled: false }])).toThrow('not an enabled mount');});+ test('a resident owner takes the datastore of the brain its engine opened (#5237)', async () => {+ const dir = temp(), project = join(dir, 'project'), mounts = join(dir, 'mounts.json');+ mkdirSync(project);+ writeFileSync(join(project, '.gbrain-mount'), 'example-brain\n'); chmodSync(join(project, '.gbrain-mount'), 0o644);+ writeFileSync(mounts, JSON.stringify({ version: 1, mounts: [{ id: 'example-brain', engine: 'pglite', path: join(dir, 'clone'), database_path: '/mount/db' }] }), { mode: 0o600 });+ const host = { engine: 'postgres' as const, database_url: 'postgresql://example.invalid/host', embedding_model: 'example-model' };+ await withEnv({ GBRAIN_MOUNTS_PATH: mounts, GBRAIN_BRAIN_ID: undefined }, () => {+ expect(residentPersistenceConfig(host, dir)).toBe(host);+ expect(residentPersistenceConfig(host, project)).toEqual({ ...host, engine: 'pglite', database_path: '/mount/db', database_url: undefined });+ });+ });+test('missing registration never allocates a replacement principal', async () => {const dir = temp();await withEnv({ GBRAIN_HOME: dir }, () => {diff --git a/test/serve-mounted-owner.serial.test.ts b/test/serve-mounted-owner.serial.test.tsnew file mode 100644index 0000000000..367bd76b00--- /dev/null+++ b/test/serve-mounted-owner.serial.test.ts@@ -0,0 +1,125 @@+/**+ * #5237: a resident `gbrain serve` started in a `.gbrain-mount` project opens the+ * mounted brain, so its persistence owner socket must follow that brain. A CLI+ * write from the same project then reaches the owner and commits instead of+ * failing `owner_unavailable`; a serve on the host brain is unchanged.+ *+ * Serial: real `gbrain serve` and CLI subprocesses on PGLite under a sandboxed+ * HOME/GBRAIN_HOME; every serve child is stopped in afterEach.+ */+import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { createEngine } from '../src/core/engine-factory.ts';+import { resolveSocketPath } from '../src/core/context/resolve-ipc.ts';+import { persistenceSocketPathForConfig } from '../src/core/persistence/ipc.ts';++const REPO_ROOT = resolve(import.meta.dir, '..');+const CLI = join(REPO_ROOT, 'src', 'cli.ts');+const MOUNT = 'example-mount';++let root: string, home: string, hostDb: string, mountDb: string, project: string, neutral: string;+let serve: ReturnType<typeof Bun.spawn> | null = null;+let serveStderr = '';++function env(): Record<string, string> {+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(process.env)) if (value !== undefined) out[key] = value;+ for (const key of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_BRAIN_ID', 'GBRAIN_SOURCE', 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'VOYAGE_API_KEY']) delete out[key];+ return { ...out, HOME: home, GBRAIN_HOME: home, GBRAIN_MOUNTS_PATH: join(home, '.gbrain', 'mounts.json'),+ GBRAIN_SELF_UPGRADE_MODE: 'off', GBRAIN_SKIP_STARTUP_HOOKS: '1', GBRAIN_SWEEP: '0', GBRAIN_SERVE_BOOT_TIMEOUT_SECONDS: '300' };+}++async function initBrain(path: string) {+ const config = { engine: 'pglite' as const, database_path: path };+ const engine = await createEngine(config);+ await engine.connect(config);+ await engine.initSchema();+ await engine.disconnect();+}++async function pageExists(path: string, slug: string): Promise<boolean> {+ const config = { engine: 'pglite' as const, database_path: path };+ const engine = await createEngine(config);+ await engine.connect(config);+ try { return (await engine.executeRaw('SELECT slug FROM pages WHERE slug=$1', [slug])).length === 1; }+ finally { await engine.disconnect(); }+}++async function startServe(cwd: string, readyDb: string) {+ serveStderr = '';+ serve = Bun.spawn(['bun', 'run', CLI, 'serve'], { cwd, env: env(), stdin: 'pipe', stdout: 'pipe', stderr: 'pipe' });+ void (async () => {+ const reader = (serve!.stderr as ReadableStream<Uint8Array>).getReader();+ const decoder = new TextDecoder();+ try { while (true) { const { value, done } = await reader.read(); if (done) break; serveStderr += decoder.decode(value, { stream: true }); } } catch { /* child gone */ }+ })();+ // The persistence listener binds before the resolve listener in the same helper.+ const socket = resolveSocketPath(readyDb);+ const deadline = Date.now() + 120_000;+ while (!existsSync(socket)) {+ if (serve.exitCode !== null) throw new Error(`serve exited early (${serve.exitCode})\n${serveStderr}`);+ if (Date.now() > deadline) throw new Error(`serve never bound ${socket}\n${serveStderr}`);+ await Bun.sleep(150);+ }+}++async function stopServe() {+ if (!serve) return;+ if (serve.exitCode === null) { serve.kill('SIGTERM'); await Promise.race([serve.exited, Bun.sleep(15_000)]); }+ if (serve.exitCode === null) { serve.kill('SIGKILL'); await serve.exited; }+ serve = null;+}++async function cli(args: string[], cwd: string) {+ const proc = Bun.spawn(['bun', 'run', CLI, ...args], { cwd, env: env(), stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' });+ const [stdout, stderr, exitCode] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);+ return { stdout, stderr, exitCode };+}++beforeAll(async () => {+ root = mkdtempSync(join(tmpdir(), 'gb-5237-'));+ home = join(root, 'h');+ hostDb = join(root, 'hdb');+ mountDb = join(root, 'mdb');+ project = join(root, 'p');+ neutral = join(root, 'n');+ for (const dir of [join(home, '.gbrain'), project, neutral, join(root, 'mount-clone')]) mkdirSync(dir, { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: hostDb }));+ writeFileSync(join(home, '.gbrain', 'mounts.json'), JSON.stringify({ version: 1, mounts: [+ { id: MOUNT, path: join(root, 'mount-clone'), engine: 'pglite', database_path: mountDb, enabled: true },+ ] }), { mode: 0o600 });+ const dotfile = join(project, '.gbrain-mount');+ writeFileSync(dotfile, `${MOUNT}\n`);+ chmodSync(dotfile, 0o644);+ await initBrain(hostDb);+ await initBrain(mountDb);+}, 240_000);++afterEach(stopServe, 30_000);+afterAll(() => { rmSync(root, { recursive: true, force: true }); });++describe('resident serve owner on a mounted brain (#5237)', () => {+ test('a CLI write from a .gbrain-mount project commits through the mounted serve owner', async () => {+ await startServe(project, hostDb);+ expect(existsSync(persistenceSocketPathForConfig({ engine: 'pglite', database_path: mountDb })!)).toBe(true);+ const put = await cli(['put', 'notes/mounted-example', '--content', '# Mounted example\n\nWritten through the resident owner.'], project);+ expect(put.stderr).not.toContain('owner_unavailable');+ expect(put.exitCode).toBe(0);+ await stopServe();+ expect(await pageExists(mountDb, 'notes/mounted-example')).toBe(true);+ expect(await pageExists(hostDb, 'notes/mounted-example')).toBe(false);+ }, 240_000);++ test('a serve on the host brain still owns the host socket and commits host writes', async () => {+ await startServe(neutral, hostDb);+ expect(existsSync(persistenceSocketPathForConfig({ engine: 'pglite', database_path: hostDb })!)).toBe(true);+ expect(existsSync(persistenceSocketPathForConfig({ engine: 'pglite', database_path: mountDb })!)).toBe(false);+ const put = await cli(['put', 'notes/host-example', '--content', '# Host example\n\nWritten through the host owner.'], neutral);+ expect(put.exitCode).toBe(0);+ await stopServe();+ expect(await pageExists(hostDb, 'notes/host-example')).toBe(true);+ expect(await pageExists(mountDb, 'notes/host-example')).toBe(false);+ }, 240_000);+});