Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(persistence): pending-write exit contract and configurable CLI write wait (#5232)

garrytand8e39fb75d59
diff --git a/src/cli.ts b/src/cli.ts
index 034e9d26e6..821931dd7e 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -34,6 +34,7 @@ import { operations, OperationError } from './core/operations.ts';
import { resolveSourceIdEngineFree } from './core/source-resolver.ts';
import { formatVolunteeredPage } from './core/context/volunteer.ts';
import type { Operation, OperationContext } from './core/operations.ts';
+import { currentCliWriteWait } from './core/persistence/write-wait.ts';
import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';
import { serializeMarkdown } from './core/markdown.ts';
import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';
@@ -710,11 +711,13 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C
// (leaves facts/cache/eval-capture writes racing teardown). The finally's
// drain bounds teardown; the hard-deadline timer armed at teardown entry
// bounds a hung one.
+ // #5232: the reporter owns the write verdict (pending exits
+ // PENDING_WRITE_EXIT_CODE, or 0 with --accept-pending); never overwrite it.
const { reportPersistenceCliError } = await import('./commands/persistence-delegate.ts');
if (!await reportPersistenceCliError(e, params.json === true || !!(e as OperationError)?.writeRequest)) {
console.error(e instanceof Error ? e.message : String(e));
+ setCliExitVerdict(1);
}
- setCliExitVerdict(1);
} finally {
// 1s per-sink drain budget: read paths with no pending work pay the ~0ms
// fast path; capture/import that DO enqueue pay up to 1s (+ facts shutdown
@@ -776,6 +779,7 @@ async function runThinClientRouted(
const raw = await callRemoteTool(cfg, op.name, params, {
timeoutMs,
signal: sigintController.signal,
+ ...(op.mutating ? { writeWaitMs: currentCliWriteWait().waitMs } : {}),
});
// T15/FOV-1: lift the server's retrieval meta off the envelope before
// unpacking (old servers lack _meta — capture is simply skipped).
@@ -795,7 +799,7 @@ async function runThinClientRouted(
const { reportPersistenceCliError } = await import('./commands/persistence-delegate.ts');
if (await reportPersistenceCliError(e, params.json === true)) {
process.off('SIGINT', onSigint);
- process.exit(sigintController.signal.aborted ? 130 : 1);
+ process.exit(sigintController.signal.aborted ? 130 : currentExitCode());
}
const url = cfg.remote_mcp!.mcp_url;
switch (e.reason) {
@@ -1532,6 +1536,8 @@ export async function makeContext(engine: BrainEngine, params: Record<string, un
// confinement (e.g., cwd-locked file_upload).
remote: false,
cliOpts: getCliOptions(),
+ // #5232: CLI writes wait longer than agent writes (persistence/write-wait.ts).
+ writeWaitMs: currentCliWriteWait().waitMs,
// v0.34 D4: sourceId is REQUIRED at the type level. Fall back to 'default'
// when resolveSourceId returned undefined (fresh pre-init brain, no sources
// table). Matches dispatch.ts's auto-fill so the contract holds across
diff --git a/src/commands/call.ts b/src/commands/call.ts
index 7a4374e011..a46e9006cd 100644
--- a/src/commands/call.ts
+++ b/src/commands/call.ts
@@ -5,6 +5,7 @@ import { bigintToStringReplacer } from '../core/utils.ts';
import { writeStdoutFinal } from '../core/cli-force-exit.ts';
import { loadConfig } from '../core/config.ts';
import { getCliOptions } from '../core/cli-options.ts';
+import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
@@ -87,7 +88,7 @@ export async function runCall(
const sourceId = resolved.source_id;
const localFederated = await localFederatedSourceIds(connected, resolved.source_id, resolved.tier);
const result = await handleToolCall(connected, tool, params, {
- sourceId,
+ sourceId, writeWaitMs: currentCliWriteWait().waitMs,
...(localFederated ? { localFederatedSourceIds: localFederated } : {}),
});
// `gbrain call` bypasses cli.ts's op-output normalizer entirely, so this
diff --git a/src/commands/capture.ts b/src/commands/capture.ts
index f059bd9786..0d8559a18f 100644
--- a/src/commands/capture.ts
+++ b/src/commands/capture.ts
@@ -54,6 +54,7 @@ import {
import { randomUUID } from 'node:crypto';
import { parseMutationPrecondition } from '../core/persistence/preconditions.ts';
import { isWriteReceipt, type WriteReceipt } from '../core/persistence/types.ts';
+import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
@@ -383,7 +384,7 @@ export async function runCapture(engine: BrainEngine | null, args: string[], opt
};
let result: Record<string, unknown>;
if (isThinClient(cfg)) {
- const raw = await callRemoteTool(cfg!, 'capture', params, { timeoutMs: getCliOptions().timeoutMs ?? 30_000 });
+ const raw = await callRemoteTool(cfg!, 'capture', params, { timeoutMs: getCliOptions().timeoutMs ?? 30_000, writeWaitMs: currentCliWriteWait().waitMs });
result = unpackToolResult<Record<string, unknown>>(raw);
} else {
const cli = getCliOptions();
@@ -400,7 +401,7 @@ export async function runCapture(engine: BrainEngine | null, args: string[], opt
if (!captureOp) throw new OperationError('unavailable', 'The capture operation is missing; upgrade this installation.');
const ctx: OperationContext = {
engine, config: cfg ?? { engine: 'pglite' }, sourceId: resolvedSourceId,
- remote: false, dryRun: false,
+ remote: false, dryRun: false, writeWaitMs: currentCliWriteWait().waitMs,
logger: {
info: (message: string) => process.stderr.write(`[capture] ${message}\n`),
warn: (message: string) => process.stderr.write(`[capture] WARN: ${message}\n`),
diff --git a/src/commands/config.ts b/src/commands/config.ts
index 979fa6e7d2..61989ef337 100644
--- a/src/commands/config.ts
+++ b/src/commands/config.ts
@@ -53,6 +53,8 @@ const FILE_PLANE_DOTTED_KEYS: ReadonlySet<string> = new Set([
// transports build their initialize response from loadConfig()); the
// `mcp.` prefix made a DB-plane write accepted and silently ignored.
'mcp.instructions',
+ // #5232: the CLI resolves its write wait before choosing a transport, engine-free.
+ 'persistence.write_wait_ms',
]);
/** Ambient-writeback keys are DUAL-PLANE (OV2-5): the DB plane is
@@ -385,7 +387,7 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
if (FILE_PLANE_DOTTED_KEYS.has(key)) {
const { loadConfigFileOnly, saveConfig } = await import('../core/config.ts');
const cfg = loadConfigFileOnly();
- const [top, leaf] = key.split('.') as ['push' | 'hooks' | 'backup' | 'mcp', string];
+ const [top, leaf] = key.split('.') as ['push' | 'hooks' | 'backup' | 'mcp' | 'persistence', string];
const branch = cfg?.[top] as Record<string, unknown> | undefined;
if (cfg && branch && leaf in branch) {
delete branch[leaf];
@@ -731,6 +733,16 @@ export async function runConfig(engine: BrainEngine, args: string[]) {
cfg.backup = { ...(cfg.backup ?? {}), check_enabled: on };
saveConfig(cfg);
console.log(`Set ${key} = ${on} (file plane: ~/.gbrain/config.json)`);
+ } else if (key === 'persistence.write_wait_ms') {
+ const { MAX_WRITE_WAIT_MS } = await import('../core/persistence/write-wait.ts');
+ const n = /^\d+$/.test(value.trim()) ? Number(value) : NaN;
+ if (!Number.isSafeInteger(n) || n > MAX_WRITE_WAIT_MS) {
+ console.error(`[config] ${key} must be a whole number of milliseconds from 0 to ${MAX_WRITE_WAIT_MS}`);
+ process.exit(1);
+ }
+ cfg.persistence = { ...(cfg.persistence ?? {}), write_wait_ms: n };
+ saveConfig(cfg);
+ console.log(`Set ${key} = ${n} (file plane: ~/.gbrain/config.json; --wait and ${'GBRAIN_WRITE_WAIT_MS'} override it)`);
} else if (key === 'backup.check_interval_days') {
const n = Number.parseInt(value, 10);
if (!Number.isFinite(n) || n < 1) {
diff --git a/src/commands/persistence-delegate.ts b/src/commands/persistence-delegate.ts
index 78581be34e..434b45ee29 100644
--- a/src/commands/persistence-delegate.ts
+++ b/src/commands/persistence-delegate.ts
@@ -6,20 +6,32 @@ import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../core/
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
import { PersistenceIpcTransportError } from '../core/persistence/ipc.ts';
import { RemoteMcpError } from '../core/mcp-client.ts';
+import { getCliOptions } from '../core/cli-options.ts';
+import { PENDING_WRITE_EXIT_CODE } from '../core/exit-codes.ts';
+import { acceptPendingRequested, pendingReceiptOf, pollCommand, writeErrorExitCode } from '../core/persistence/write-wait.ts';
export async function reportPersistenceCliError(error: unknown, json = false,
out: (payload: string) => Promise<void> = writeStdoutFinal): Promise<boolean> {
if (!(error instanceof OperationError || error instanceof PersistenceIpcTransportError
|| error instanceof RemoteMcpError && (error.detail?.request_id || error.detail?.write_request))) return false;
const detail = error.toJSON();
- if (json) await out(JSON.stringify(detail, null, 2) + '\n');
- console.error(error instanceof OperationError || error instanceof RemoteMcpError
- ? `Error [${'write_error' in detail && detail.write_error || detail.error}]: ${detail.message}` : error.message);
+ // #5232: an admitted pending write is not a failure; it exits
+ // PENDING_WRITE_EXIT_CODE (0 with --accept-pending) and names how to poll.
+ const pending = pendingReceiptOf(error);
+ const acceptPending = acceptPendingRequested(getCliOptions().acceptPending);
+ if (json) await out(JSON.stringify(pending ? { ...detail, poll_command: pollCommand(pending.request_id) } : detail, null, 2) + '\n');
+ console.error(pending ? `Pending [write_pending]: ${detail.message} It may still commit.`
+ : error instanceof OperationError || error instanceof RemoteMcpError
+ ? `Error [${'write_error' in detail && detail.write_error || detail.error}]: ${detail.message}` : error.message);
if (detail.suggestion) console.error(`Fix: ${detail.suggestion}`);
const receipt = 'write_request' in detail ? detail.write_request : undefined;
const requestId = receipt?.request_id ?? ('request_id' in detail ? detail.request_id : undefined);
if (requestId) console.error(`Request: ${requestId}${receipt ? ` (${receipt.state})` : ''}`);
- setCliExitVerdict(1);
+ if (pending) {
+ console.error(`Poll: ${pollCommand(pending.request_id)}`);
+ if (!acceptPending) console.error(`Exit ${PENDING_WRITE_EXIT_CODE}: accepted, not yet committed. Wait longer with --wait <seconds>, or pass --accept-pending to exit 0.`);
+ }
+ setCliExitVerdict(writeErrorExitCode(error, acceptPending));
return true;
}
diff --git a/src/commands/takes-mutation.ts b/src/commands/takes-mutation.ts
index db1fbe2eb0..28899fbc6c 100644
--- a/src/commands/takes-mutation.ts
+++ b/src/commands/takes-mutation.ts
@@ -7,6 +7,7 @@ import { isThinClient, loadConfig, type GBrainConfig } from '../core/config.ts';
import { OperationError } from '../core/ops/contract.ts';
import { parseMutationPrecondition } from '../core/persistence/preconditions.ts';
import { isWriteReceipt } from '../core/persistence/types.ts';
+import { currentCliWriteWait } from '../core/persistence/write-wait.ts';
import { maybeDelegateLocalOperation } from '../core/persistence/local-client.ts';
import { resolveSourceId } from '../core/source-resolver.ts';
import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';
@@ -87,7 +88,7 @@ export async function runTakesMutation(engine: BrainEngine | (() => Promise<Brai
if (isThinClient(config)) {
if (args.some(arg => arg === '--outcome' || arg.startsWith('--outcome='))) console.error('[deprecated] --outcome is the v0.28 alias for --quality. Prefer --quality correct|incorrect|partial in new scripts.');
if (cli.brain || parsed.sourceId || params.local_dir !== undefined) throw invalid('--brain, --source-id, and --dir require a local brain host; the remote credential selects its source.');
- result = unpackToolResult(await callRemoteTool(config!, operation, params, { timeoutMs: cli.timeoutMs ?? 30_000 }));
+ result = unpackToolResult(await callRemoteTool(config!, operation, params, { timeoutMs: cli.timeoutMs ?? 30_000, writeWaitMs: currentCliWriteWait().waitMs }));
} else {
const delegated = await maybeDelegateLocalOperation(operation, params, config, {
brain: cli.brain, source: parsed.sourceId ?? null, timeoutMs: cli.timeoutMs ?? undefined,
@@ -98,7 +99,7 @@ export async function runTakesMutation(engine: BrainEngine | (() => Promise<Brai
const { operations } = await import('../core/operations.ts');
const op = operations.find(candidate => candidate.name === operation)!;
result = await op.handler({ engine: connected, config: config ?? { engine: 'pglite' }, remote: false,
- sourceId: await resolveSourceId(connected, parsed.sourceId ?? null), dryRun: false,
+ sourceId: await resolveSourceId(connected, parsed.sourceId ?? null), dryRun: false, writeWaitMs: currentCliWriteWait().waitMs,
logger: { info: message => console.error(message), warn: message => console.error(message), error: message => console.error(message) },
}, params) as Record<string, unknown>;
}
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 805505d87f..7806570e2d 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -284,7 +284,7 @@ function installedDespiteFailure(oldVersion: string): boolean {
}
}
-async function describeMigrationFailure(error: unknown, newVersion: string): Promise<string> {
+export async function describeMigrationFailure(error: unknown, newVersion: string): Promise<string> {
if ((error as { status?: number }).status === MIGRATIONS_RUNNING_EXIT_CODE) {
const { loadConfig } = await import('../core/config.ts');
const config = loadConfig();
diff --git a/src/core/cli-options.ts b/src/core/cli-options.ts
index 0edcafda49..7042444c27 100644
--- a/src/core/cli-options.ts
+++ b/src/core/cli-options.ts
@@ -38,6 +38,15 @@ export interface CliOptions {
* via src/core/brain-resolver.ts.
*/
brain: string | null;
+ /**
+ * #5232: `--wait <seconds>` — how long a write waits for its commit before
+ * the CLI reports it pending (persistence/write-wait.ts). `null` = resolve
+ * GBRAIN_WRITE_WAIT_MS / persistence.write_wait_ms / the 30 s default. Unset when
+ * the flag is absent.
+ */
+ writeWaitMs?: number | null;
+ /** #5232: `--accept-pending` (true) / `--no-accept-pending` (false); unset = GBRAIN_ACCEPT_PENDING. */
+ acceptPending?: boolean | null;
}
export const DEFAULT_CLI_OPTIONS: CliOptions = {
@@ -49,6 +58,15 @@ export const DEFAULT_CLI_OPTIONS: CliOptions = {
brain: null,
};
+/** `--wait` takes seconds (`--wait 45`, `--wait 2.5`), 0 to 600. A malformed value throws. */
+function parseWaitSeconds(val: string | undefined): number {
+ const seconds = val !== undefined && /^\d+(?:\.\d+)?$/.test(val) ? Number(val) : NaN;
+ if (!Number.isFinite(seconds) || seconds > 600) {
+ throw new Error(`--wait requires a number of seconds from 0 to 600 (got ${val === undefined ? 'nothing' : JSON.stringify(val)}).`);
+ }
+ return Math.round(seconds * 1000);
+}
+
/**
* Brain-id shape. Same regex as brain-registry's BRAIN_ID_RE (kept in sync;
* brain-resolver.ts follows the same convention). 'host' matches. Validated
@@ -189,6 +207,21 @@ export function parseGlobalFlags(argv: string[]): { cliOpts: CliOptions; rest: s
cliOpts.brain = parseBrainValue(a.slice('--brain='.length));
continue;
}
+ // #5232 write wait + pending opt-in. Global like --timeout so every write
+ // lane (generated ops, call, capture, remember, takes) reads one value.
+ if (a === '--wait') {
+ cliOpts.writeWaitMs = parseWaitSeconds(argv[i + 1]);
+ i++;
+ continue;
+ }
+ if (a.startsWith('--wait=')) {
+ cliOpts.writeWaitMs = parseWaitSeconds(a.slice('--wait='.length));
+ continue;
+ }
+ if (a === '--accept-pending' || a === '--no-accept-pending') {
+ cliOpts.acceptPending = a === '--accept-pending';
+ continue;
+ }
slots.push({ plain: a });
}
diff --git a/src/core/config.ts b/src/core/config.ts
index 47359e4b31..4f35c02e0e 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -69,6 +69,9 @@ export interface GBrainConfig {
integrations?: { memorable?: { enabled?: boolean } };
/** Monthly backup-coverage check. File-plane for engine-free hook children. */
backup?: { check_enabled?: boolean | string; check_interval_days?: number | string };
+ /** #5232: CLI write wait in ms, file-plane so the engine-free CLI reads it
+ * before choosing a transport (persistence/write-wait.ts). */
+ persistence?: { write_wait_ms?: number | string };
database_url?: string;
database_path?: string;
openai_api_key?: string;
@@ -1624,6 +1627,8 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'persistence.limits.principal_terminal_bytes', 'persistence.limits.brain_terminal_bytes',
'persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes',
'persistence.receipt_retention_days', 'persistence.unbound_write', // #5254: persistence/unbound-source.ts
+ // #5232: file-plane CLI write wait (persistence/write-wait.ts), routed by `config set`.
+ 'persistence.write_wait_ms',
];
/**
diff --git a/src/core/exit-codes.ts b/src/core/exit-codes.ts
new file mode 100644
index 0000000000..a5b9637a6c
--- /dev/null
+++ b/src/core/exit-codes.ts
@@ -0,0 +1,15 @@
+/**
+ * Process exit statuses with a contract beyond "0 ok / 1 failed". One home so
+ * a new status cannot silently reuse a value a caller already branches on.
+ */
+
+/** A runner refused because another runner holds the migration lock (EX_TEMPFAIL). */
+export const MIGRATIONS_RUNNING_EXIT_CODE = 75;
+
+/**
+ * #5232 (O-ENG-1): the write was admitted and is still pending; it may commit
+ * later. Distinct from 75, which `gbrain upgrade` reads as "another
+ * migration runner holds the lock". Exit 0 means committed; pass
+ * `--accept-pending` (or GBRAIN_ACCEPT_PENDING=1) to map pending to 0.
+ */
+export const PENDING_WRITE_EXIT_CODE = 10;
diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.ts
index 9d94507086..82d9545177 100644
--- a/src/core/mcp-client.ts
+++ b/src/core/mcp-client.ts
@@ -19,6 +19,7 @@
import { randomUUID } from 'node:crypto';
import { isPersistenceIpcMutation } from './persistence/ipc.ts';
+import { replayWhilePending } from './persistence/write-wait.ts';
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport, StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
@@ -325,6 +326,12 @@ export interface CallRemoteToolOptions {
timeoutMs?: number;
/** External AbortSignal (e.g. SIGINT handler). Composed with the timeout. */
signal?: AbortSignal;
+ /**
+ * #5232: keep a mutation's commit wait beyond the server's own bounded
+ * wait by replaying the identical request (same request_id) while it is
+ * pending. `timeoutMs` still bounds each exchange.
+ */
+ writeWaitMs?: number;
}
/**
@@ -390,6 +397,10 @@ export async function callRemoteTool(
// Retain on the caller's object so transport refresh and caller retries use
// the same durable identity. Explicit malformed IDs still reach validation.
if (isPersistenceIpcMutation(toolName) && args.request_id === undefined && args.dry_run !== true) args.request_id = randomUUID();
+ if (opts.writeWaitMs !== undefined && isPersistenceIpcMutation(toolName) && args.dry_run !== true) {
+ const { writeWaitMs, ...exchange } = opts;
+ return replayWhilePending(() => callRemoteTool(config, toolName, args, exchange), writeWaitMs);
+ }
const requestId = isPersistenceIpcMutation(toolName) && isWriteRequestId(args.request_id) ? args.request_id : undefined;
let submitted = false;
diff --git a/src/core/migration-orchestration-lock.ts b/src/core/migration-orchestration-lock.ts
index 059ecb536e..c696815077 100644
--- a/src/core/migration-orchestration-lock.ts
+++ b/src/core/migration-orchestration-lock.ts
@@ -28,8 +28,7 @@ import { getPgliteMigrationLockPath } from './pglite-lock.ts';
import { tryAcquireNativeLock } from './persistence/native-lock.ts';
export const MIGRATION_ORCHESTRATION_LOCK_ID = 'gbrain-apply-migrations';
-/** Exit status of a runner refused because another runner holds the lock (EX_TEMPFAIL). */
-export const MIGRATIONS_RUNNING_EXIT_CODE = 75;
+export { MIGRATIONS_RUNNING_EXIT_CODE } from './exit-codes.ts';
// Long enough to outlast a synchronous orchestrator phase (subprocess timeouts
// reach 30 minutes) that starves the refresh timer; ownership is rechecked
// before every orchestrator.
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 316c172e08..ea97b6d09e 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -371,6 +371,13 @@ export interface OperationContext {
* tokens from comments.)
*/
deferEmbeds?: boolean;
+ /**
+ * #5232: how long a coordinated write waits for its commit before returning
+ * `write_pending` with its receipt. Unset keeps the agent default (5 s);
+ * CLI entry points and the resident owner's CLI lane set it
+ * (persistence/write-wait.ts).
+ */
+ writeWaitMs?: number;
/**
* Resolved global CLI options (--quiet / --progress-json / --progress-interval).
* CLI callers populate this from `getCliOptions()`. MCP / library callers
diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.ts
index 8019e54d45..f8917efc60 100644
--- a/src/core/persistence/ipc.ts
+++ b/src/core/persistence/ipc.ts
@@ -46,6 +46,8 @@ export interface PersistenceIpcRequest {
registration: PersistenceIpcRegistration;
/** Client resolves flag/env/dotfile tiers; owner resolves DB tiers using this cwd. */
routing: { source: string | null; cwd: string };
+ /** #5232: the caller's commit wait; sent only to owners advertising `write_wait`. */
+ write_wait_ms?: number;
}
export interface PersistenceIpcCapabilities {
@@ -55,6 +57,8 @@ export interface PersistenceIpcCapabilities {
max_frame_bytes: number;
/** Optional for protocol compatibility with owners predating local administration. */
administration?: readonly PersistenceAdminOperation[];
+ /** #5232: the owner honors `write_wait_ms` on operation requests. */
+ write_wait?: true;
}
export interface PersistenceIpcAdminRequest {
@@ -117,8 +121,11 @@ export function isPersistenceIpcRegistration(value: unknown): value is Persisten
&& (value.lane === 'cli' || value.lane === 'stdio');
}
+const OPERATION_REQUEST_KEYS = ['version', 'kind', 'brain_id', 'operation', 'params', 'registration', 'routing'];
function operationRequest(value: unknown): value is PersistenceIpcRequest {
- if (!record(value) || !exactKeys(value, ['version', 'kind', 'brain_id', 'operation', 'params', 'registration', 'routing'])) return false;
+ if (!record(value) || !(exactKeys(value, OPERATION_REQUEST_KEYS) || exactKeys(value, [...OPERATION_REQUEST_KEYS, 'write_wait_ms']))) return false;
+ if (value.write_wait_ms !== undefined && !(typeof value.write_wait_ms === 'number'
+ && Number.isSafeInteger(value.write_wait_ms) && value.write_wait_ms >= 0)) return false;
if (value.version !== 1 || value.kind !== 'operation' || !isWriteRequestId(value.brain_id)
|| !isPersistenceIpcOperation(value.operation) || !record(value.params)
|| !isPersistenceIpcRegistration(value.registration) || !record(value.routing)
@@ -207,6 +214,7 @@ export async function startPersistenceIpcServer(
version: 1, brain_id: provider.brainId, operations: PERSISTENCE_IPC_OPERATIONS,
max_frame_bytes: PERSISTENCE_IPC_MAX_BYTES,
...(provider.administer ? { administration: PERSISTENCE_ADMIN_OPERATIONS } : {}),
+ write_wait: true,
} satisfies PersistenceIpcCapabilities }));
return;
}
diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.ts
index 499f1b8544..e43b3bdde1 100644
--- a/src/core/persistence/local-client.ts
+++ b/src/core/persistence/local-client.ts
@@ -17,6 +17,7 @@ import {
requestPersistenceAdministration,
} from './ipc.ts';
import type { PersistenceAdminOperation } from './admin-contract.ts';
+import { currentCliWriteWait, replayWhilePending, writeExchangeBudget } from './write-wait.ts';
/** The brain axis must be resolved before inspecting any host lock/socket. */
export function persistenceConfigForBrain(
@@ -91,7 +92,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 } = {},
+ options: { brain?: string | null; source?: string | null; cwd?: string; timeoutMs?: number; writeWaitMs?: number } = {},
): Promise<LocalDelegationResult> {
if (!isPersistenceIpcOperation(operation)) return { handled: false };
if (isPersistenceIpcMutation(operation)) {
@@ -127,9 +128,17 @@ export async function maybeDelegateLocalOperation(
'Upgrade and restart the owner, then retry with the same request ID.');
}
const registration = readPersistenceCliRegistration(capability.brain_id);
- const result = await requestPersistenceOperation(socketPath, {
- version: 1, kind: 'operation', brain_id: capability.brain_id,
- operation, params: wireParams, registration, routing: { source, cwd },
- }, options.timeoutMs);
+ const request = { version: 1 as const, kind: 'operation' as const, brain_id: capability.brain_id,
+ operation, params: wireParams, registration, routing: { source, cwd } };
+ if (!isPersistenceIpcMutation(operation)) return { handled: true, result: await requestPersistenceOperation(socketPath, request, options.timeoutMs) };
+ // #5232: the owner waits the caller's wait within one transport deadline; an
+ // owner without `write_wait` waits its own bound and the replay keeps the rest.
+ const waitMs = options.writeWaitMs ?? currentCliWriteWait().waitMs;
+ const deadline = Date.now() + waitMs;
+ const result = await replayWhilePending(() => {
+ const budget = writeExchangeBudget(Math.max(0, deadline - Date.now()), options.timeoutMs);
+ return requestPersistenceOperation(socketPath,
+ capability.write_wait ? { ...request, write_wait_ms: budget.waitMs } : request, budget.timeoutMs);
+ }, waitMs);
return { handled: true, result };
}
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index e87cd51111..2f9a1ead01 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -133,7 +133,7 @@ async function inferRememberTarget(ctx: OperationContext, sourceId: string, sour
export async function submitRememberMutation(ctx: OperationContext, params: Record<string, unknown>, waitMs?: number): Promise<Record<string, unknown>> {
registerMutationPreparer('remember', prepareMemoryMutation);
const sub = await submission(ctx, 'remember', params);
- if (sub.prior) return writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs));
+ if (sub.prior) return writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs));
const { p, sourceId, principal, callerIntent, requestId } = sub;
const [source] = await ctx.engine.executeRaw<RememberSource>(
"SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);
@@ -154,7 +154,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,
...(linked ? { entity_inferred: linked.via } : {}), ...(inference && 'warning' in inference ? { entity_warning: inference.warning } : {}) },
authority, worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });
- return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs));
+ return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, waitMs ?? ctx.writeWaitMs));
}
interface WithdrawalTarget { id: number; entity_slug: string | null; source_markdown_slug: string | null; expired_at: Date | null; }
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index 64e361505d..582997a39c 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -99,7 +99,7 @@ export async function submitPageMutation(ctx: OperationContext,
await submissionAuthority(ctx, prior.operation, prior.source_id, prior.source_incarnation, prior.slug);
await authorizeStoredRequest(ctx.engine, prior);
assertReplayIntent(prior, intentDigest({ operation: input.operation, sourceId, slug: prior.slug, callerIntent }));
- return writeResponse(await waitForWrite(ctx.engine, prior, ctx.config, input.waitMs));
+ return writeResponse(await waitForWrite(ctx.engine, prior, ctx.config, input.waitMs ?? ctx.writeWaitMs));
}
if (input.operation === 'delete_page') assertPurgeParams(p, ctx.remote);
const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(
@@ -196,5 +196,5 @@ export async function submitPageMutation(ctx: OperationContext,
const row = await admitWrite(ctx.engine, { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,
slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent, intent, authority,
worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null });
- return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, input.waitMs));
+ return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, input.waitMs ?? ctx.writeWaitMs));
}
diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.ts
index 42380714d8..cb09c7cd92 100644
--- a/src/core/persistence/provider.ts
+++ b/src/core/persistence/provider.ts
@@ -10,6 +10,7 @@ import { startPersistenceConsumer, assertPersistenceAccepting } from './service.
import { isWriteErrorCode, isWriteReceipt } from './types.ts';
import type { PersistenceIpcProvider } from './ipc.ts';
import { runPersistenceAdministration } from './administration.ts';
+import { boundedWriteWaitMs } from './write-wait.ts';
export { residentPersistenceConfig } from './local-client.ts';
import { projectionBacklog } from '../page-state/projections.ts';
@@ -48,8 +49,10 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:
allowedSources: unrestricted ? undefined : verified.grant.sourceIds };
const params = !unrestricted && request.operation === 'get_page' && request.params.source_id === undefined
? { ...request.params, source_id: sourceId } : request.params;
+ const writeWaitMs = boundedWriteWaitMs(request.write_wait_ms);
const result = await dispatchToolCall(engine, request.operation, params, {
config, remote: verified.remote, transport: verified.remote ? 'stdio' : undefined, sourceId, auth,
+ ...(writeWaitMs !== undefined ? { writeWaitMs } : {}),
...(unrestricted ? {} : { localFederatedSourceIds: verified.grant.sourceIds }),
});
const body = JSON.parse(result.content[0].text) as Record<string, unknown>;
diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.ts
index fff75f62a2..aa7c89d416 100644
--- a/src/core/persistence/types.ts
+++ b/src/core/persistence/types.ts
@@ -113,6 +113,18 @@ export function isWriteReceipt(value: unknown): value is WriteReceipt {
return true;
}
+/**
+ * #5249/#5232: the receipt of an admitted write still in flight. Keyed on the
+ * receipt's non-terminal state, never on an error code alone: a pre-admission
+ * refusal carries no receipt and is a failure (O-ENG-1).
+ */
+export function admittedPendingReceipt(envelope: unknown): WriteReceipt | null {
+ // Frozen memory verbs carry `error: 'unavailable'` with `write_error: 'write_pending'`.
+ if (!isRecord(envelope) || (envelope.error !== 'write_pending' && envelope.write_error !== 'write_pending')
+ || !isWriteReceipt(envelope.write_request)) return null;
+ return isTerminalWriteState(envelope.write_request.state) ? null : envelope.write_request;
+}
+
/** Select public fields explicitly so internal journal columns cannot ride error envelopes. */
export function publicWriteReceipt(receipt: WriteReceipt): WriteReceipt {
return {
diff --git a/src/core/persistence/write-wait.ts b/src/core/persistence/write-wait.ts
new file mode 100644
index 0000000000..30c2dc19ce
--- /dev/null
+++ b/src/core/persistence/write-wait.ts
@@ -0,0 +1,117 @@
+/**
+ * #5232: how long a caller waits for an admitted write to commit, and the CLI
+ * exit verdict when the wait ends first. Engine-free: the CLI resolves these
+ * before it knows whether a resident owner, a remote server or its own engine
+ * will run the write.
+ */
+import { loadConfig, type GBrainConfig } from '../config.ts';
+import { getCliOptions } from '../cli-options.ts';
+import { PENDING_WRITE_EXIT_CODE } from '../exit-codes.ts';
+import { admittedPendingReceipt, type WriteReceipt } from './types.ts';
+
+/** Agent and server callers keep the historical bounded wait. */
+export const AGENT_WRITE_WAIT_MS = 5_000;
+/** CLI default: long enough for a normal commit over a remote pooler (#5232 measured ~8 s). */
+export const CLI_WRITE_WAIT_MS = 30_000;
+export const MAX_WRITE_WAIT_MS = 600_000;
+/** Transport budget beyond the wait for identity checks and admission (O-DX-1). */
+export const WRITE_ADMISSION_HEADROOM_MS = 15_000;
+export const WRITE_WAIT_ENV = 'GBRAIN_WRITE_WAIT_MS';
+export const WRITE_WAIT_CONFIG_KEY = 'persistence.write_wait_ms';
+export const ACCEPT_PENDING_ENV = 'GBRAIN_ACCEPT_PENDING';
+
+export class WriteWaitConfigError extends Error {
+ readonly code = 'invalid_write_wait';
+ constructor(readonly where: string, value: unknown) {
+ super(`${where} must be a whole number of milliseconds from 0 to ${MAX_WRITE_WAIT_MS} (got ${JSON.stringify(value)}).`);
+ }
+}
+
+function parseMs(value: unknown, where: string): number | null {
+ if (value === undefined || value === null || value === '') return null;
+ const n = typeof value === 'number' ? value : typeof value === 'string' && /^\d+$/.test(value.trim()) ? Number(value) : NaN;
+ if (!Number.isSafeInteger(n) || n < 0 || n > MAX_WRITE_WAIT_MS) throw new WriteWaitConfigError(where, value);
+ return n;
+}
+
+/** CLI write wait: `--wait <s>` > GBRAIN_WRITE_WAIT_MS > persistence.write_wait_ms (file plane) > 30 s. */
+export function resolveCliWriteWaitMs(opts: {
+ flagMs?: number | null; env?: NodeJS.ProcessEnv; config?: GBrainConfig | null;
+} = {}): number {
+ if (opts.flagMs !== undefined && opts.flagMs !== null) return opts.flagMs;
+ const env = opts.env ?? process.env;
+ return parseMs(env[WRITE_WAIT_ENV], WRITE_WAIT_ENV)
+ ?? parseMs(opts.config?.persistence?.write_wait_ms, WRITE_WAIT_CONFIG_KEY)
+ ?? CLI_WRITE_WAIT_MS;
+}
+
+/** The wait and pending opt-in this CLI invocation resolved. */
+export function currentCliWriteWait(): { waitMs: number; acceptPending: boolean } {
+ const cli = getCliOptions();
+ return { waitMs: resolveCliWriteWaitMs({ flagMs: cli.writeWaitMs, config: loadConfig() }), acceptPending: acceptPendingRequested(cli.acceptPending) };
+}
+
+/** A wire-requested wait is honored only within the documented bound. */
+export function boundedWriteWaitMs(value: unknown): number | undefined {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
+ ? Math.min(value, MAX_WRITE_WAIT_MS) : undefined;
+}
+
+/**
+ * One transport exchange for a write: an explicit `--timeout` bounds the
+ * exchange, so the owner is asked to stop waiting early enough to return a
+ * pending receipt before that deadline. Otherwise the deadline is the wait
+ * plus admission headroom, so a slow commit is never an unknown submission.
+ */
+export function writeExchangeBudget(waitMs: number, explicitTimeoutMs?: number | null): { waitMs: number; timeoutMs: number } {
+ if (explicitTimeoutMs === undefined || explicitTimeoutMs === null) return { waitMs, timeoutMs: waitMs + WRITE_ADMISSION_HEADROOM_MS };
+ return { waitMs: Math.max(0, Math.min(waitMs, explicitTimeoutMs - WRITE_ADMISSION_HEADROOM_MS)), timeoutMs: explicitTimeoutMs };
+}
+
+/** `--accept-pending` / `--no-accept-pending` beat GBRAIN_ACCEPT_PENDING=1. */
+export function acceptPendingRequested(flag: boolean | null | undefined, env: NodeJS.ProcessEnv = process.env): boolean {
+ if (flag !== undefined && flag !== null) return flag;
+ return /^(1|true|yes|on)$/i.test(env[ACCEPT_PENDING_ENV]?.trim() ?? '');
+}
+
+/** The admitted, still-pending receipt carried by a thrown write error, if any. */
+export function pendingReceiptOf(error: unknown): WriteReceipt | null {
+ const json = (error as { toJSON?: () => unknown } | null)?.toJSON;
+ if (typeof json !== 'function') return null;
+ try { return admittedPendingReceipt(json.call(error)); } catch { return null; }
+}
+
+/**
+ * The one CLI exit verdict for a failed write (O-DX-1/O-ENG-1): an admitted
+ * pending receipt exits PENDING_WRITE_EXIT_CODE (0 with the opt-in); every
+ * other error, including a pre-admission `unavailable`, exits 1.
+ */
+export function writeErrorExitCode(error: unknown, acceptPending: boolean): number {
+ if (!pendingReceiptOf(error)) return 1;
+ return acceptPending ? 0 : PENDING_WRITE_EXIT_CODE;
+}
+
+/** The copy-paste poll command for a pending receipt. */
+export function pollCommand(requestId: string): string {
+ return `gbrain call get_write_request '${JSON.stringify({ request_id: requestId })}'`;
+}
+
+/**
+ * Keep the caller's wait across transports that wait less than it (an older
+ * owner, or a remote server's own bounded wait): replay the identical request
+ * (same request_id, so nothing new is admitted) until it settles or the wait
+ * is spent. Only an admitted pending receipt is replayed.
+ */
+export async function replayWhilePending<T>(send: () => Promise<T>, waitMs: number,
+ sleep: (ms: number) => Promise<void> = ms => new Promise(resolve => setTimeout(resolve, ms))): Promise<T> {
+ const deadline = Date.now() + waitMs;
+ for (;;) {
+ try { return await send(); }
+ catch (error) {
+ const receipt = pendingReceiptOf(error);
+ const remaining = deadline - Date.now();
+ if (!receipt || remaining <= 0) throw error;
+ await sleep(Math.min(Math.max(receipt.retry_after_ms ?? 1000, 50), remaining));
+ }
+ }
+}
diff --git a/src/core/shared-skills/publication.ts b/src/core/shared-skills/publication.ts
index e672aec36d..e5686ee761 100644
--- a/src/core/shared-skills/publication.ts
+++ b/src/core/shared-skills/publication.ts
@@ -177,7 +177,7 @@ export async function submitSharedSkillMutation(ctx: OperationContext, operation
await assertStoredSkillCapability(ctx.engine, prior.authority, 'skill_editor');
for (const target of (prior.authority as SkillAuthority).skillSlugsUsed ?? [prior.slug]) await authorizeWrite(ctx.engine, prior.authority, prior.operation, target);
assertReplayIntent(prior, intentDigest({ operation, sourceId, slug, callerIntent }));
- return writeResponse(await waitForWrite(ctx.engine, prior, ctx.config));
+ return writeResponse(await waitForWrite(ctx.engine, prior, ctx.config, ctx.writeWaitMs));
}
await assertSharedSkillPersistence(ctx.engine);
const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1', [sourceId]);
@@ -295,7 +295,7 @@ export async function submitSharedSkillMutation(ctx: OperationContext, operation
const row = await admitWrite(ctx.engine, { principal, operation, sourceId, sourceIncarnation: source.incarnation, slug, requestId,
targetKind: 'skill_bundle', protocolVersion: 2, callerIntent, intent: intent as unknown as Record<string, unknown>, authority,
worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });
- return writeResponse(await waitForWrite(ctx.engine, row, ctx.config));
+ return writeResponse(await waitForWrite(ctx.engine, row, ctx.config, ctx.writeWaitMs));
}
export async function prepareSharedSkillMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index 7d68a51f01..643676c37e 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -30,6 +30,7 @@ import { backupCheckDisabled, backupNagGate, backupNoticeText, loadBackupStatus
import { maybeRefreshBackupStatusInProcess } from '../core/backup/coverage.ts';
import { operationScopesAllowed } from '../core/scope.ts';
import { invalidateHotMemoryForEngine } from '../core/facts/meta-hook.ts';
+import { admittedPendingReceipt, type WriteReceipt } from '../core/persistence/types.ts';
import { currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';
// WP3: normalization + validation moved to validate-params.ts (direct unit
@@ -235,6 +236,8 @@ export interface DispatchOpts {
* treated as 'full'.
*/
surfaceCeiling?: 'verbs' | 'starter' | 'full';
+ /** #5232: commit wait for coordinated writes (OperationContext.writeWaitMs); unset = agent default. */
+ writeWaitMs?: number;
}
/**
@@ -388,13 +391,22 @@ export function isListLevelDenialEnvelope(parsed: unknown): boolean {
}
/** The mcp_request_log status classes a dispatched tool result maps onto. */
-export type RequestLogStatus = 'success' | 'success_with_warnings' | 'denied_after_list' | 'error';
+export type RequestLogStatus = 'success' | 'success_with_warnings' | 'accepted_pending' | 'denied_after_list' | 'error';
+
+/** #5249: the receipt of a write the dispatcher returned as accepted but not yet committed. */
+export function acceptedPendingReceipt(result: ToolResult): WriteReceipt | null {
+ if (!result.isError) return null;
+ try { return admittedPendingReceipt(JSON.parse(result.content[0]?.text ?? '{}')); }
+ catch { return null; }
+}
/**
* The ONE `mcp_request_log.status` decision for a dispatched tool result
* (serve-http's tools/call persistence + SSE broadcast both consume this):
* - errors whose envelope is a list-level denial (isListLevelDenialEnvelope
* above) → 'denied_after_list' (amendment 33 / D10 trend-to-zero metric);
+ * - `write_pending` carrying a non-terminal receipt → 'accepted_pending'
+ * (#5249: admitted work still in flight, not a failure);
* other errors (including unparseable content) → 'error';
* - successes whose `_meta.warnings` is a non-empty array →
* 'success_with_warnings' (WP3 amendment 13 warn-mode observability;
@@ -407,6 +419,7 @@ export function requestLogStatusForResult(result: ToolResult): RequestLogStatus
try {
const parsed: unknown = JSON.parse(result.content[0]?.text ?? '{}');
if (isListLevelDenialEnvelope(parsed)) return 'denied_after_list';
+ if (admittedPendingReceipt(parsed)) return 'accepted_pending';
} catch { /* unparseable error content stays plain 'error' */ }
return 'error';
}
@@ -494,6 +507,7 @@ export function buildOperationContext(
...(opts.localFederatedSourceIds ? { localFederatedSourceIds: opts.localFederatedSourceIds } : {}),
...(opts.explicitReadBinding ? { explicitReadBinding: opts.explicitReadBinding } : {}),
...(opts.surfaceCeiling ? { surfaceCeiling: opts.surfaceCeiling } : {}),
+ ...(opts.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),
auth: opts.auth,
};
}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 48f8c5ee2f..79b23c9d22 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -469,7 +469,7 @@ export async function handleToolCall(
engine: BrainEngine,
tool: string,
params: Record<string, unknown>,
- opts?: { sourceId?: string; localFederatedSourceIds?: string[] },
+ opts?: { sourceId?: string; localFederatedSourceIds?: string[]; writeWaitMs?: number },
): Promise<unknown> {
const op = operations.find(o => o.name === tool);
if (!op) throw new Error(`Unknown tool: ${tool}`);
@@ -481,6 +481,7 @@ export async function handleToolCall(
remote: false,
logger: { info: console.log, warn: console.warn, error: console.error },
...(opts?.sourceId ? { sourceId: opts.sourceId } : {}),
+ ...(opts?.writeWaitMs !== undefined ? { writeWaitMs: opts.writeWaitMs } : {}),
...(opts?.localFederatedSourceIds
? { localFederatedSourceIds: opts.localFederatedSourceIds }
: {}),
diff --git a/test/pending-write-exit-owner.serial.test.ts b/test/pending-write-exit-owner.serial.test.ts
new file mode 100644
index 0000000000..5b1b2ae05f
--- /dev/null
+++ b/test/pending-write-exit-owner.serial.test.ts
@@ -0,0 +1,117 @@
+/**
+ * #5232 / O-DX-1 against real writers: a resident PGLite owner whose consumer
+ * is paused (the canonical worktree lock is held elsewhere) and the direct
+ * path where the CLI opens the brain itself. Exit codes are asserted on real
+ * CLI processes; the paused write commits once the lock is released and the
+ * same request_id replays to the committed receipt.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { once } from 'node:events';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { createPersistenceIpcProvider } from '../src/core/persistence/provider.ts';
+import { startPersistenceIpcServer, persistenceSocketPathForConfig } from '../src/core/persistence/ipc.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { acquireWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';
+
+const CLI = join(import.meta.dir, '../src/cli.ts');
+let dir: string;
+let config: { engine: 'pglite'; database_path: string };
+let engine: PGLiteEngine;
+const page = (body: string) => `---\ntitle: Example\ntype: note\n---\n\n${body}\n`;
+
+async function cli(args: string[], stdin?: string, env: Record<string, string> = {}) {
+ const childEnv: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_NO_BANNER: '1',
+ GBRAIN_BACKUP_CHECK: '0', GBRAIN_WRITE_WAIT_MS: undefined, GBRAIN_ACCEPT_PENDING: undefined, ...env };
+ for (const name of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SOURCE']) delete childEnv[name];
+ const child = Bun.spawn([process.execPath, CLI, ...args], { cwd: dir, env: childEnv,
+ stdin: stdin === undefined ? 'ignore' : new Blob([stdin]), stdout: 'pipe', stderr: 'pipe' });
+ const watchdog = setTimeout(() => child.kill('SIGKILL'), 60_000);
+ try {
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, code };
+ } finally { clearTimeout(watchdog); }
+}
+
+async function holdWorktree() {
+ const binding = await getWorktreeBinding(engine, 'default');
+ expect(binding).not.toBeNull();
+ const lock = await acquireWorktree(binding!);
+ expect(lock).not.toBeNull();
+ return lock!;
+}
+
+beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), 'gb-pending-owner-'));
+ config = { engine: 'pglite', database_path: join(dir, 'db') };
+ mkdirSync(join(dir, '.gbrain'), { recursive: true });
+ mkdirSync(join(dir, 'brain'), { recursive: true });
+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify(config));
+ engine = new PGLiteEngine();
+});
+afterAll(async () => {
+ await disposePersistenceConsumer(engine);
+ await engine.disconnect().catch(() => {});
+ rmSync(dir, { recursive: true, force: true });
+});
+
+describe('paused writers and the CLI exit contract', () => {
+ test('resident owner: pending exits 10 with its receipt, opt-in exits 0, the same request_id commits after release', async () => {
+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ await engine.connect(config); await engine.initSchema();
+ await engine.setConfig('sync.repo_path', join(dir, 'brain'));
+ const provider = await createPersistenceIpcProvider(engine, config);
+ const binding = await startPersistenceIpcServer(persistenceSocketPathForConfig(config)!, provider);
+ try {
+ const seeded = await cli(['put', 'notes/seed', '--json'], page('Seed body.'));
+ expect({ code: seeded.code, stderr: seeded.stderr }).toMatchObject({ code: 0 });
+ const lock = await holdWorktree();
+ const id = randomUUID();
+ try {
+ const pending = await cli(['put', 'notes/paused', '--request-id', id, '--wait', '1', '--json'], page('Paused body.'));
+ expect({ code: pending.code, stderr: pending.stderr }).toMatchObject({ code: PENDING_WRITE_EXIT_CODE });
+ expect(JSON.parse(pending.stdout).write_request).toMatchObject({ request_id: id });
+ expect(pending.stderr).toContain('Poll: gbrain call get_write_request');
+ const accepted = await cli(['call', 'put_page', JSON.stringify({ slug: 'notes/paused', content: page('Paused body.'), request_id: id }),
+ '--wait', '0', '--accept-pending']);
+ expect({ code: accepted.code, stderr: accepted.stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(accepted.stdout).write_request.state).not.toBe('committed');
+ } finally { await lock.release(); }
+ const committed = await cli(['put', 'notes/paused', '--request-id', id, '--wait', '30', '--json'], page('Paused body.'));
+ expect({ code: committed.code, stderr: committed.stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(committed.stdout)).toMatchObject({ request_id: id, state: 'committed' });
+ const stale = await cli(['put', 'notes/seed', '--expected-revision', randomUUID(), '--json'], page('Stale body.'));
+ expect({ code: stale.code }).toMatchObject({ code: 1 });
+ } finally {
+ if (binding) { const closed = once(binding.server, 'close'); binding.close(); await closed; }
+ await disposePersistenceConsumer(engine);
+ }
+ });
+ }, 180_000);
+
+ test('direct path: the CLI that opens the brain itself waits its --wait, then exits 10 or 0', async () => {
+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host' }, async () => {
+ const lock = await holdWorktree();
+ await engine.disconnect();
+ const id = randomUUID();
+ try {
+ const started = Date.now();
+ const pending = await cli(['put', 'notes/direct', '--request-id', id, '--wait', '2', '--json'], page('Direct body.'));
+ expect({ code: pending.code, stderr: pending.stderr }).toMatchObject({ code: PENDING_WRITE_EXIT_CODE });
+ expect(Date.now() - started).toBeGreaterThanOrEqual(2_000);
+ expect(JSON.parse(pending.stdout).write_request.request_id).toBe(id);
+ const accepted = await cli(['put', 'notes/direct', '--request-id', id, '--wait', '0', '--json'], page('Direct body.'),
+ { GBRAIN_ACCEPT_PENDING: '1' });
+ expect({ code: accepted.code, stderr: accepted.stderr }).toMatchObject({ code: 0 });
+ } finally { await lock.release(); }
+ const committed = await cli(['put', 'notes/direct', '--request-id', id, '--json'], page('Direct body.'));
+ expect({ code: committed.code, stderr: committed.stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(committed.stdout).state).toBe('committed');
+ });
+ }, 180_000);
+});
diff --git a/test/pending-write-exit.serial.test.ts b/test/pending-write-exit.serial.test.ts
new file mode 100644
index 0000000000..655dcdb67a
--- /dev/null
+++ b/test/pending-write-exit.serial.test.ts
@@ -0,0 +1,243 @@
+/**
+ * #5232 / O-DX-1 / O-ENG-1: the CLI write exit contract, asserted on real CLI
+ * processes. Committed → 0; admitted but pending → PENDING_WRITE_EXIT_CODE
+ * (0 with --accept-pending or GBRAIN_ACCEPT_PENDING=1); terminal failure → 1;
+ * pre-admission refusal → 1 even with the opt-in; lost transport → 1 with an
+ * unknown submission, distinct from pending. Covers generated write commands,
+ * `gbrain call` and custom mutation commands over a resident-owner socket and
+ * an HTTP thin client. The direct path runs in pending-write-exit-owner.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { once } from 'node:events';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { startPersistenceIpcServer, persistenceSocketPathForConfig, type PersistenceIpcRequest } from '../src/core/persistence/ipc.ts';
+import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
+import { MIGRATIONS_RUNNING_EXIT_CODE, PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';
+import { describeMigrationFailure } from '../src/commands/upgrade.ts';
+
+const BRAIN = '10000000-0000-4000-8000-000000000001';
+const ID = '20000000-0000-4000-8000-000000000001';
+const CLI = join(import.meta.dir, '../src/cli.ts');
+const dirs: string[] = [];
+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });
+
+type Outcome = 'committed' | 'pending' | 'pending_once' | 'failed' | 'closing' | 'silent';
+
+async function spawnCli(dir: string, args: string[], env: Record<string, string | undefined> = {}, stdin?: string) {
+ const childEnv: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host',
+ GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_WRITE_WAIT_MS: undefined, GBRAIN_ACCEPT_PENDING: undefined, ...env };
+ for (const name of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SOURCE']) delete childEnv[name];
+ const child = Bun.spawn([process.execPath, CLI, ...args], { cwd: dir, env: childEnv, stdin: stdin === undefined ? 'ignore' : new Blob([stdin]),
+ stdout: 'pipe', stderr: 'pipe' });
+ const watchdog = setTimeout(() => child.kill('SIGKILL'), 25_000);
+ try {
+ const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
+ return { stdout, stderr, code };
+ } finally { clearTimeout(watchdog); }
+}
+
+function pendingError(requestId: string) {
+ const error = new OperationError('write_pending', 'The write is accepted and is still pending.', 'Poll get_write_request.');
+ error.writeRequest = { request_id: requestId, state: 'running', retry_after_ms: 100 };
+ error.writeError = 'write_pending';
+ return error;
+}
+
+/** A resident owner socket whose answer per call is scripted. */
+async function withOwner(outcome: Outcome, run: (dir: string, calls: PersistenceIpcRequest[]) => Promise<void>) {
+ const dir = mkdtempSync(join(tmpdir(), 'gb-pending-exit-'));
+ dirs.push(dir);
+ const databasePath = join(dir, 'db');
+ const config = { engine: 'pglite' as const, database_path: databasePath };
+ mkdirSync(join(dir, '.gbrain', 'persistence'), { recursive: true });
+ mkdirSync(databasePath, { recursive: true });
+ const lock = await acquireLock(databasePath);
+ const metadataPath = lock.lockPath ?? join(databasePath, '.gbrain-lock', 'lock');
+ writeFileSync(metadataPath, JSON.stringify({ ...JSON.parse(readFileSync(metadataPath, 'utf8')), subcommand: 'serve' }));
+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify(config));
+ writeFileSync(join(dir, '.gbrain', 'persistence', `${BRAIN}.cli.json`), JSON.stringify({ id: BRAIN, credential: 'a'.repeat(64), lane: 'cli' }), { mode: 0o600 });
+ const calls: PersistenceIpcRequest[] = [];
+ const binding = await startPersistenceIpcServer(persistenceSocketPathForConfig(config)!, {
+ brainId: BRAIN,
+ dispatch: async request => {
+ calls.push(request);
+ const requestId = request.params.request_id as string;
+ if (outcome === 'silent') return new Promise(() => {});
+ if (outcome === 'closing') throw new OperationError('unavailable', 'The persistence owner is closing. Retry the same request_id after restart.');
+ if (outcome === 'pending' || outcome === 'pending_once' && calls.length === 1) throw pendingError(requestId);
+ if (outcome === 'failed') {
+ const error = new OperationError('revision_conflict', 'The page changed.', 'Read the page again.');
+ error.writeRequest = { request_id: requestId, state: 'conflict', retry_after_ms: null };
+ error.writeError = 'revision_conflict';
+ throw error;
+ }
+ const receipt = { request_id: requestId, state: 'committed', retry_after_ms: null };
+ return { ...receipt, slug: request.params.slug ?? 'inbox/example', status: 'created_or_updated', write_request: receipt };
+ },
+ });
+ try { await run(dir, calls); }
+ finally {
+ if (binding) { const closed = once(binding.server, 'close'); binding.close(); await closed; }
+ await releaseLock(lock);
+ }
+}
+
+const COMMANDS: Array<[string, (dir: string) => string[], string?]> = [
+ ['generated put', () => ['put', 'notes/example', '--request-id', ID, '--json'], '---\ntitle: Example\n---\n\nBody.\n'],
+ ['gbrain call', () => ['call', 'put_page', JSON.stringify({ slug: 'notes/example', content: 'Body.', request_id: ID })]],
+ ['custom capture', dir => { writeFileSync(join(dir, 'in.md'), '# Example\n'); return ['capture', '--file', join(dir, 'in.md'), '--request-id', ID, '--json']; }],
+];
+
+describe('resident owner: pending-write exit codes', () => {
+ for (const [label, args, stdin] of COMMANDS) {
+ test(`${label}: committed 0, pending ${PENDING_WRITE_EXIT_CODE}, opt-in 0, failure 1`, async () => {
+ const cases: Array<[Outcome, string[], Record<string, string>, number]> = [
+ ['committed', [], {}, 0],
+ ['pending', [], { GBRAIN_WRITE_WAIT_MS: '0' }, PENDING_WRITE_EXIT_CODE],
+ ['pending', ['--accept-pending'], { GBRAIN_WRITE_WAIT_MS: '0' }, 0],
+ ['pending', [], { GBRAIN_WRITE_WAIT_MS: '0', GBRAIN_ACCEPT_PENDING: '1' }, 0],
+ ['pending', ['--no-accept-pending'], { GBRAIN_WRITE_WAIT_MS: '0', GBRAIN_ACCEPT_PENDING: '1' }, PENDING_WRITE_EXIT_CODE],
+ ['failed', ['--accept-pending'], {}, 1],
+ ['closing', ['--accept-pending'], { GBRAIN_ACCEPT_PENDING: '1' }, 1],
+ ];
+ for (const [outcome, extra, env, expected] of cases) {
+ await withOwner(outcome, async (dir, calls) => {
+ const result = await spawnCli(dir, [...args(dir), ...extra], env, stdin);
+ expect({ outcome, extra, env, code: result.code, stderr: result.stderr }).toMatchObject({ code: expected });
+ expect(calls).toHaveLength(1);
+ if (outcome === 'pending') {
+ const body = JSON.parse(result.stdout);
+ expect(body.write_request).toMatchObject({ request_id: ID, state: 'running' });
+ expect(body.poll_command).toBe(`gbrain call get_write_request '{"request_id":"${ID}"}'`);
+ }
+ });
+ }
+ }, 120_000);
+ }
+
+ test('the CLI wait travels to the owner and bounds one exchange with admission headroom', async () => {
+ await withOwner('committed', async (dir, calls) => {
+ expect((await spawnCli(dir, ['call', 'put_page', JSON.stringify({ slug: 'notes/a', content: 'A', request_id: ID }), '--wait', '45'])).code).toBe(0);
+ expect((await spawnCli(dir, ['call', 'put_page', JSON.stringify({ slug: 'notes/a', content: 'A', request_id: ID })], { GBRAIN_WRITE_WAIT_MS: '7000' })).code).toBe(0);
+ expect((await spawnCli(dir, ['call', 'put_page', JSON.stringify({ slug: 'notes/a', content: 'A', request_id: ID })])).code).toBe(0);
+ // An explicit --timeout shorter than wait + headroom asks the owner to stop early.
+ expect((await spawnCli(dir, ['call', 'put_page', JSON.stringify({ slug: 'notes/a', content: 'A', request_id: ID }), '--timeout=20s'])).code).toBe(0);
+ const waits = calls.map(call => call.write_wait_ms);
+ expect(waits[0]).toBeGreaterThan(44_000);
+ expect(waits[0]).toBeLessThanOrEqual(45_000);
+ expect(waits[1]).toBeGreaterThan(6_000);
+ expect(waits[1]).toBeLessThanOrEqual(7_000);
+ expect(waits[2]).toBeGreaterThan(29_000);
+ expect(waits[2]).toBeLessThanOrEqual(30_000);
+ expect(waits[3]).toBeLessThanOrEqual(5_000);
+ });
+ }, 60_000);
+
+ test('a pending answer is replayed with the same request_id while the wait lasts', async () => {
+ await withOwner('pending_once', async (dir, calls) => {
+ const result = await spawnCli(dir, ['call', 'put_page', JSON.stringify({ slug: 'notes/a', content: 'A', request_id: ID }), '--wait', '5']);
+ expect({ code: result.code, stderr: result.stderr }).toMatchObject({ code: 0 });
+ expect(JSON.parse(result.stdout).write_request.state).toBe('committed');
+ expect(calls).toHaveLength(2);
+ expect(calls.map(call => call.params.request_id)).toEqual([ID, ID]);
+ });
+ }, 60_000);
+
+ test('a lost response is an unknown submission, not a pending write', async () => {
+ await withOwner('silent', async (dir) => {
+ const result = await spawnCli(dir, ['call', 'put_page', JSON.stringify({ slug: 'notes/a', content: 'A', request_id: ID }), '--timeout=1s', '--accept-pending']);
+ expect(result.code).toBe(1);
+ const body = JSON.parse(result.stdout);
+ expect(body).toMatchObject({ request_id: ID, submission_status: 'unknown' });
+ expect(body).not.toHaveProperty('write_request');
+ });
+ }, 60_000);
+
+ test('a malformed --wait refuses before any write is sent', async () => {
+ await withOwner('committed', async (dir, calls) => {
+ const result = await spawnCli(dir, ['call', 'put_page', '{}', '--wait', 'soon']);
+ expect(result.code).not.toBe(0);
+ expect(result.stderr).toContain('--wait requires a number of seconds');
+ expect(calls).toHaveLength(0);
+ });
+ }, 30_000);
+});
+
+/** A loopback MCP server scripted like the owner fixture (HTTP thin client). */
+async function withThinServer(outcome: Outcome, run: (dir: string, calls: Record<string, unknown>[]) => Promise<void>) {
+ const calls: Record<string, unknown>[] = [];
+ const server = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request): Promise<Response> {
+ const path = new URL(request.url).pathname;
+ const base = `http://127.0.0.1:${server.port}`;
+ if (path === '/.well-known/oauth-authorization-server') return Response.json({ issuer: base, token_endpoint: `${base}/token` });
+ if (path === '/token') return Response.json({ access_token: 'fixture', token_type: 'bearer', expires_in: 3600, scope: 'read write' });
+ if (path !== '/mcp' || request.method !== 'POST') return new Response(null, { status: 405 });
+ const body = await request.json() as any;
+ if (body.id === undefined) return new Response(null, { status: 202 });
+ if (body.method === 'initialize') return Response.json({ jsonrpc: '2.0', id: body.id, result: {
+ protocolVersion: body.params.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'fixture', version: '1' } } });
+ const args = body.params.arguments as Record<string, unknown>;
+ calls.push(args);
+ const receipt = (state: string) => ({ request_id: args.request_id, state, retry_after_ms: state === 'running' ? 100 : null });
+ const error = (envelope: Record<string, unknown>) => Response.json({ jsonrpc: '2.0', id: body.id,
+ result: { isError: true, content: [{ type: 'text', text: JSON.stringify(envelope) }] } });
+ if (outcome === 'pending' || outcome === 'pending_once' && calls.length === 1) return error({ error: 'write_pending',
+ message: 'The write is accepted and is still pending.', write_error: 'write_pending', write_request: receipt('running') });
+ if (outcome === 'failed') return error({ error: 'revision_conflict', message: 'The page changed.', write_error: 'revision_conflict', write_request: receipt('conflict') });
+ if (outcome === 'closing') return error({ error: 'unavailable', message: 'The persistence owner is closing.' });
+ const committed = receipt('committed');
+ return Response.json({ jsonrpc: '2.0', id: body.id, result: { content: [{ type: 'text',
+ text: JSON.stringify({ ...committed, slug: args.slug ?? 'inbox/example', status: 'created_or_updated', write_request: committed }) }] } });
+ } });
+ const dir = mkdtempSync(join(tmpdir(), 'gb-pending-thin-'));
+ dirs.push(dir);
+ mkdirSync(join(dir, '.gbrain'));
+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', remote_mcp: {
+ issuer_url: `http://127.0.0.1:${server.port}`, mcp_url: `http://127.0.0.1:${server.port}/mcp`,
+ oauth_client_id: 'fixture', oauth_client_secret: 'fixture' } }));
+ try { await run(dir, calls); } finally { await server.stop(true); }
+}
+
+describe('HTTP thin client: pending-write exit codes', () => {
+ const thin: Array<[string, string[], string?]> = [
+ ['generated put', ['put', 'notes/example', '--json'], '---\ntitle: Example\n---\n\nBody.\n'],
+ ['custom capture', ['capture', 'An example note', '--json']],
+ ['custom takes add', ['takes', 'add', 'notes/example', '--claim', 'Example', '--kind', 'take', '--who', 'world', '--json']],
+ ];
+ for (const [label, args, stdin] of thin) {
+ test(`${label}: committed 0, pending ${PENDING_WRITE_EXIT_CODE}, opt-in 0, failure 1, refusal 1`, async () => {
+ const cases: Array<[Outcome, string[], Record<string, string>, number]> = [
+ ['committed', [], {}, 0],
+ ['pending', ['--wait', '0'], {}, PENDING_WRITE_EXIT_CODE],
+ ['pending', ['--wait', '0', '--accept-pending'], {}, 0],
+ ['failed', ['--accept-pending'], {}, 1],
+ ['closing', [], { GBRAIN_ACCEPT_PENDING: '1' }, 1],
+ ];
+ for (const [outcome, extra, env, expected] of cases) {
+ await withThinServer(outcome, async (dir, calls) => {
+ const result = await spawnCli(dir, [...args, ...extra], env, stdin);
+ expect({ outcome, extra, code: result.code, stderr: result.stderr }).toMatchObject({ code: expected });
+ expect(calls).toHaveLength(1);
+ });
+ }
+ }, 120_000);
+ }
+
+ test('the CLI wait outlasts the server wait by replaying the same request_id', async () => {
+ await withThinServer('pending_once', async (dir, calls) => {
+ const result = await spawnCli(dir, ['capture', 'An example note', '--json', '--wait', '5']);
+ expect({ code: result.code, stderr: result.stderr }).toMatchObject({ code: 0 });
+ expect(calls).toHaveLength(2);
+ expect(calls[0].request_id).toBe(calls[1].request_id);
+ });
+ }, 60_000);
+});
+
+test('a pending post-upgrade write is not reported as a migration-lock conflict (O-ENG-1)', async () => {
+ expect(PENDING_WRITE_EXIT_CODE).not.toBe(MIGRATIONS_RUNNING_EXIT_CODE);
+ expect(await describeMigrationFailure({ status: MIGRATIONS_RUNNING_EXIT_CODE }, '')).toContain('in another apply-migrations');
+ expect(await describeMigrationFailure({ status: PENDING_WRITE_EXIT_CODE }, '')).not.toContain('in another apply-migrations');
+});
diff --git a/test/persistence-cli-delegation.test.ts b/test/persistence-cli-delegation.test.ts
index 2212fe4fe0..473d012f0b 100644
--- a/test/persistence-cli-delegation.test.ts
+++ b/test/persistence-cli-delegation.test.ts
@@ -11,6 +11,7 @@ import type { BrainEngine } from '../src/core/engine.ts';
import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';
import { OperationError } from '../src/core/ops/contract.ts';
import { parseTakesMutation } from '../src/commands/takes-mutation.ts';
+import { PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';
const BRAIN = '10000000-0000-4000-8000-000000000001';
const ID = '20000000-0000-4000-8000-000000000001';
@@ -184,10 +185,10 @@ describe('CLI-only persistence delegation before engine connection', () => {
await withOwner(async (dir, calls) => {
const child = Bun.spawn([process.execPath, join(import.meta.dir, '../src/cli.ts'), 'takes', 'update', 'test/pending',
'--row', '1', '--weight', '0.8', '--request-id', ID, '--json'], {
- cwd: dir, env: { ...process.env, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0' }, stdout: 'pipe', stderr: 'pipe',
+ cwd: dir, env: { ...process.env, GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_WRITE_WAIT_MS: '0' }, stdout: 'pipe', stderr: 'pipe',
});
const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);
- expect(code).toBe(1);
+ expect(code).toBe(PENDING_WRITE_EXIT_CODE);
expect(JSON.parse(stdout).write_request).toMatchObject({ request_id: ID, state: 'queued' });
expect(stderr).toContain(`--request-id ${ID}`);
expect(stdout + stderr).not.toContain('Updated take');
diff --git a/test/thin-client-write-errors.serial.test.ts b/test/thin-client-write-errors.serial.test.ts
index c9d54c2f0c..1ed0717fe2 100644
--- a/test/thin-client-write-errors.serial.test.ts
+++ b/test/thin-client-write-errors.serial.test.ts
@@ -2,6 +2,7 @@ import { afterEach, expect, test } from 'bun:test';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
+import { PENDING_WRITE_EXIT_CODE } from '../src/core/exit-codes.ts';
// Real CLI subprocesses against a loopback-only MCP fixture; no datastore or keys.
const roots: string[] = [];
@@ -45,7 +46,8 @@ async function run(mode: 'timeout' | 'pending' | 'conflict' | 'interrupt', json
issuer_url: `http://127.0.0.1:${server.port}`, mcp_url: `http://127.0.0.1:${server.port}/mcp`,
oauth_client_id: 'fixture', oauth_client_secret: 'fixture',
} }));
- const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: root, GBRAIN_BRAIN_ID: 'host', GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0' };
+ // #5232: no client-side replay here; the fixture answers pending forever.
+ const env: Record<string, string | undefined> = { ...process.env, GBRAIN_HOME: root, GBRAIN_BRAIN_ID: 'host', GBRAIN_NO_BANNER: '1', GBRAIN_BACKUP_CHECK: '0', GBRAIN_WRITE_WAIT_MS: '0' };
for (const name of ['DATABASE_URL', 'GBRAIN_DATABASE_URL', 'GBRAIN_SOURCE']) delete env[name];
const child = Bun.spawn([process.execPath, join(import.meta.dir, '../src/cli.ts'), ...command, ...(json ? ['--json'] : []), mode === 'interrupt' ? '--timeout=10s' : '--timeout=500ms'], {
cwd: root, env, stdout: 'pipe', stderr: 'pipe',
@@ -70,7 +72,7 @@ test.each(['timeout', 'interrupt'] as const)('thin CLI %s exposes the generated
test.each(['pending', 'conflict'] as const)('thin CLI renders the frozen %s receipt as JSON', async mode => {
const result = await run(mode);
- expect({ code: result.code, stderr: result.stderr }).toMatchObject({ code: 1 });
+ expect({ code: result.code, stderr: result.stderr }).toMatchObject({ code: mode === 'pending' ? PENDING_WRITE_EXIT_CODE : 1 });
const body = JSON.parse(result.stdout);
expect(body).toMatchObject({ error: mode === 'conflict' ? 'invalid_params' : 'unavailable', protocol_version: 1,
write_error: mode === 'conflict' ? 'revision_conflict' : 'write_pending',
@@ -80,14 +82,14 @@ test.each(['pending', 'conflict'] as const)('thin CLI renders the frozen %s rece
test('human thin CLI errors retain the request UUID too', async () => {
const result = await run('pending', false);
- expect(result.code).toBe(1);
+ expect(result.code).toBe(PENDING_WRITE_EXIT_CODE);
expect(result.stdout).toBe('');
expect(result.stderr).toContain(`Request: ${result.args!.request_id}`);
}, 15_000);
test.each(['timeout', 'pending'] as const)('thin takes %s preserves the same structured retry identity as page writes', async mode => {
const result = await run(mode, true, ['takes', 'add', 'page', '--claim', 'Example preference', '--kind', 'take', '--who', 'world']);
- expect({ code: result.code, stderr: result.stderr }).toMatchObject({ code: 1 });
+ expect({ code: result.code, stderr: result.stderr }).toMatchObject({ code: mode === 'pending' ? PENDING_WRITE_EXIT_CODE : 1 });
const body = JSON.parse(result.stdout);
expect(body.request_id).toBe(result.args!.request_id);
if (mode === 'timeout') {
@@ -105,7 +107,7 @@ test.each([
const requestId = '31000000-0000-4000-8000-000000000001';
const revision = '32000000-0000-4000-8000-000000000001';
const result = await run('pending', true, ['takes', verb, 'page', ...options, '--request-id', requestId, '--expected-revision', revision]);
- expect(result.code).toBe(1);
+ expect(result.code).toBe(PENDING_WRITE_EXIT_CODE);
expect(result.args).toMatchObject({ request_id: requestId, expected_revision: revision });
expect(JSON.parse(result.stdout).write_request).toMatchObject({ request_id: requestId, state: 'queued' });
}, 15_000);