Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(cli): a serve that holds the datastore but has not bound its owner socket is an owner starting, not an owner gone

garrytan2dc3f145bde6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c33d8f19ad..23d288b5e0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -20,6 +20,7 @@ identifiers and attribution are available in the pre-removal Git revision
- **An already-applied correction is not a conflict.** When the working-tree bytes hash to exactly the canonical file this import would write, the import proceeds with no file write (`sync-prepare.ts`); any other newer bytes are protected as before.
- Tests: `test/managed-sync-page-fault-holds.test.ts` adds the three probes on PGLite and Postgres (live run held and cleared by the commit, already-applied writeback, older blocked cursor converted under `--retry-failed`); each fails on the previous release.
- Docs: [write refusals](docs/guides/write-refusals.md#worktree_dirty) describes the new hold case.
+- **A CLI call that lands while `gbrain serve` is still starting waits for the owner socket instead of failing `owner_unavailable` (`submission_status: not_sent`).** The serve takes the PGLite datastore lock before it binds its persistence socket (the MCP handshake sits in between), so a local command in that window saw a serve holder and no socket. `maybeDelegateLocalOperation` / `maybeDelegateLocalAdministration` now repeat the capability probe for up to 3 s while the same serve holds the lock; a released lock, a different holder or any other transport failure ends the wait at once, and nothing falls through to the engine path. Surfaced as a CI flake in `test/shared-skills-live-cli.test.ts`; probe in `test/persistence-local-client.test.ts` (fails on master).
Fixes #6513.
diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.ts
index e9f01ff95b..c6b6809677 100644
--- a/src/core/persistence/local-client.ts
+++ b/src/core/persistence/local-client.ts
@@ -78,17 +78,42 @@ export function readPersistenceCliRegistration(brainId: string): PersistenceIpcR
export type LocalDelegationResult = { handled: false } | { handled: true; result: unknown };
+/** How long a caller waits for a serve that already holds the datastore to bind its owner socket. */
+export const OWNER_STARTUP_WAIT_MS = 3_000;
+
+/**
+ * The resident owner's capabilities. A `gbrain serve` takes the datastore lock before it binds its persistence
+ * socket (the MCP handshake sits in between), so a call that lands in that window finds a serve holder and no
+ * socket. That is an owner starting, not an owner gone: the probe is repeated for a bounded wait while the same
+ * serve still holds the lock; a holder that is not a serve, a released lock or any answer other than "no socket"
+ * ends the wait at once. Never falls through to the engine path.
+ */
+async function residentOwnerCapabilities(socketPath: string, databasePath: string, holder: ReturnType<typeof inspectLockHolder>,
+ startupWaitMs = OWNER_STARTUP_WAIT_MS): Promise<PersistenceIpcCapabilities> {
+ const deadline = Date.now() + startupWaitMs;
+ for (;;) {
+ try { return await requestPersistenceCapabilities(socketPath); }
+ catch (error) {
+ const starting = error instanceof PersistenceIpcTransportError && !error.sent && holder.serve === true && Date.now() < deadline;
+ if (!starting) throw error;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ const again = inspectLockHolder(databasePath);
+ if (!again.held || again.serve !== true || again.pid !== holder.pid) throw error;
+ }
+ }
+}
+
/** Administration uses a separate CLI-only envelope and never manufactures a new credential. */
export async function maybeDelegateLocalAdministration(
operation: PersistenceAdminOperation, params: Record<string, unknown>, config: GBrainConfig,
- options: { timeoutMs?: number } = {},
+ options: { timeoutMs?: number; startupWaitMs?: number } = {},
): Promise<LocalDelegationResult> {
if (config.engine !== 'pglite' || !config.database_path || config.database_url) return { handled: false };
const holder = inspectLockHolder(config.database_path);
if (!holder.held) return { handled: false };
const socketPath = persistenceSocketPathForConfig(config);
if (!socketPath) throw noDiscoveryPath('The PGLite owner has no persistence discovery path.', holder);
- const capability = await requestPersistenceCapabilities(socketPath);
+ const capability = await residentOwnerCapabilities(socketPath, config.database_path, holder, options.startupWaitMs);
if (!capability.administration?.includes(operation)) throw new OperationError('owner_unavailable',
'The running owner does not support this local administration command.', 'Upgrade and restart the owner before administering this brain.');
const registration = readPersistenceCliRegistration(capability.brain_id);
@@ -115,7 +140,7 @@ export async function maybeDelegateLocalOperation(
operation: string,
params: Record<string, unknown>,
hostConfig: GBrainConfig | null,
- options: { brain?: string | null; source?: string | null; cwd?: string; timeoutMs?: number; writeWaitMs?: number } = {},
+ options: { brain?: string | null; source?: string | null; cwd?: string; timeoutMs?: number; writeWaitMs?: number; startupWaitMs?: number } = {},
): Promise<LocalDelegationResult> {
if (!isPersistenceIpcOperation(operation)) return { handled: false };
if (isPersistenceIpcMutation(operation)) {
@@ -139,7 +164,7 @@ export async function maybeDelegateLocalOperation(
if (sourceInParams) delete wireParams.source;
delete wireParams.json;
let capability: PersistenceIpcCapabilities;
- try { capability = await requestPersistenceCapabilities(socketPath); }
+ try { capability = await residentOwnerCapabilities(socketPath, config.database_path, holder, options.startupWaitMs); }
catch (error) {
// A holder that is not a serve and answers no owner socket is another
// command, such as a concurrent CLI call: the engine path waits for its lock.
diff --git a/test/persistence-local-client.test.ts b/test/persistence-local-client.test.ts
index d543942c7f..45b7f33bb1 100644
--- a/test/persistence-local-client.test.ts
+++ b/test/persistence-local-client.test.ts
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { persistenceConfigForBrain, readPersistenceCliRegistration, maybeDelegateLocalOperation, residentPersistenceConfig } from '../src/core/persistence/local-client.ts';
import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';
-import { PersistenceIpcTransportError } from '../src/core/persistence/ipc.ts';
+import { PersistenceIpcTransportError, persistenceSocketPathForConfig, startPersistenceIpcServer } from '../src/core/persistence/ipc.ts';
import { resolveSourceId } from '../src/core/source-resolver.ts';
import type { BrainEngine } from '../src/core/engine.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -81,11 +81,36 @@ describe('engine-free local persistence routing', () => {
holder('call');
expect(await maybeDelegateLocalOperation('forget', { id: '1' }, config, { brain: 'host', cwd: dir })).toEqual({ handled: false });
holder('serve');
- await expect(maybeDelegateLocalOperation('forget', { id: '1' }, config, { brain: 'host', cwd: dir })).rejects.toBeInstanceOf(PersistenceIpcTransportError);
+ await expect(maybeDelegateLocalOperation('forget', { id: '1' }, config, { brain: 'host', cwd: dir, startupWaitMs: 0 })).rejects.toBeInstanceOf(PersistenceIpcTransportError);
});
} finally { await releaseLock(lock); }
});
+ test('a serve that holds the datastore but has not bound its socket yet is an owner starting: the call waits for the socket instead of failing owner_unavailable (#6531)', async () => {
+ const dir = temp();
+ const config = { engine: 'pglite' as const, database_path: join(dir, 'db') };
+ const lock = await acquireLock(config.database_path, { timeoutMs: 1000 });
+ writeFileSync(lock.lockPath!, JSON.stringify({ ...JSON.parse(readFileSync(lock.lockPath!, 'utf8')), subcommand: 'serve' }));
+ const owner: { binding: Awaited<ReturnType<typeof startPersistenceIpcServer>> } = { binding: null };
+ try {
+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host' }, async () => {
+ const socketPath = persistenceSocketPathForConfig(config)!;
+ const bind = new Promise<void>(resolve => setTimeout(async () => {
+ owner.binding = await startPersistenceIpcServer(socketPath, { brainId: BRAIN, dispatch: async () => ({ ok: true }) });
+ resolve();
+ }, 400));
+ // The socket appears 400 ms into the wait: the probe reaches the owner, so the next refusal is the missing CLI registration, not the transport.
+ const started = Date.now();
+ await expect(maybeDelegateLocalOperation('forget', { id: '1' }, config, { brain: 'host', cwd: dir })).rejects.toMatchObject({ code: 'permission_denied' });
+ expect(Date.now() - started).toBeGreaterThanOrEqual(350);
+ await bind;
+ // Without the wait the same call fails on the transport at once.
+ owner.binding!.close(); owner.binding = null;
+ await expect(maybeDelegateLocalOperation('forget', { id: '1' }, config, { brain: 'host', cwd: dir, startupWaitMs: 0 })).rejects.toBeInstanceOf(PersistenceIpcTransportError);
+ });
+ } finally { owner.binding?.close(); await releaseLock(lock); }
+ });
+
test('owner source environment and dotfiles cannot redirect a client with no local signal', async () => {
const dir = temp();
writeFileSync(join(dir, '.gbrain-source'), 'owner-source');