Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: review fix-check round (resident-owner recovery contract, explicit wait_ms bounds the fence wait)

garrytan1e56626e061f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 686f49c03e..14bafec8e0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,9 +17,10 @@ identifiers and attribution are available in the pre-removal Git revision
### Itemized changes
- `src/core/error-registry.ts`: registers `worktree_refreshing` (class retryable, actor provider). `src/core/persistence/journal.ts`: the fence refusal carries `retryable: true` and a read-only `gbrain sources writer status --source <id> --json` fix, so the envelope renders `next: wait`. A retried admission whose request was already accepted (its acknowledgement lost before the fence) reconciles to that receipt instead of being refused as not recorded.
-- `src/core/persistence/admission-retry.ts`: `waitOutRefreshFence` re-runs an interactive write's whole admission (250 ms to 2 s backoff, 10 s cap shared by every item of a `remember` batch); nothing is held across a pause and a refused attempt journals nothing. Past the cap the refusal is returned with how long the call waited. Background writes and the managed sync keep their own retries; database-only sources are never fenced. Wired into `admitWrite`, `admitBatch` (`put-pages`) and `forget`.
+- `src/core/persistence/admission-retry.ts`: `waitOutRefreshFence` re-runs an interactive write's whole admission (250 ms to 2 s backoff, 10 s cap shared by every item of a `remember` batch, its clock starting at the first refusal; an explicit `wait_ms` on `put_page` or `put_pages` lowers the cap, so `wait_ms: 0` is refused at once); nothing is held across a pause and a refused attempt journals nothing. Past the cap the refusal is returned with how long the call waited. Background writes and the managed sync keep their own retries; database-only sources are never fenced. Wired into `admitWrite`, `admitBatch` (`put-pages`) and `forget`.
- `src/core/persistence/verb-errors.ts`: `remember` and the other memory verbs keep their frozen `unavailable` code for the fence and add `canonical: worktree_refreshing`, its `detail`, `fix` and `retryable`.
-- `src/core/remember-batch.ts`: a batch whose every item failed throws the first item's error (`items[<i>]: ... None of the <n> item(s) was saved.`); a batch with any failed item (or an item whose outcome is unknown, which keeps its child `request_id`) adds `status: "error"` and the first failed `code`, so the CLI exits 1 and MCP returns `isError` with every item's receipt (`src/mcp/dispatch.ts`). `src/cli/remember-format.ts` prints a batch as `saved X of N fact(s)` with one line per item.
+- `src/core/remember-batch.ts`: a batch whose every item failed throws the first item's error (`items[<i>]: ... None of the <n> item(s) was saved.`); a batch with any failed item (or an item whose outcome is unknown, which keeps its child `request_id`) adds `status: "error"` and the first failed `code`, so the CLI exits 1 and MCP returns `isError` with every item's receipt (`src/mcp/dispatch.ts`). `src/cli/remember-format.ts` prints a batch as `saved X of N fact(s)` with one line per item; a failed item keeps its `canonical` code and `retryable` flag. The batch body survives the resident owner (`src/core/persistence/provider.ts`) and the thin client (`src/core/mcp-client.ts`), and a thin-client CLI exits 1 on it too. A batch error leaves the one-shot MCP notices for the next call.
+- `src/core/persistence/ipc.ts`: an error from the resident owner keeps its canonical code, `detail`, `retryable` and (without a receipt) its fix, so a fenced write through a running `gbrain serve` still reads `worktree_refreshing` with `next: wait`.
- `test/write-refusal-refresh-fence-8621.test.ts` (new) pauses a real refresh at its drained boundary on PGLite and Postgres and covers MCP, the wait, the cap, background writes, a database-only source and the CLI exit codes.
## [0.60.576.0] - 2026-11-05
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index e2c87771f1..539709d960 100644
--- a/docs/guides/write-refusals.md
+++ b/docs/guides/write-refusals.md
@@ -572,7 +572,7 @@ this anchor (`--json` puts them in one object on stdout); the command exits 1.
| <a id="refresh_sync_timeout"></a>`refresh_sync_timeout` | `refresh_sync_timeout` | Reported per source in a refresh's `sync_blocked`, not as a refusal: the source's managed sync committed nothing within its share of the refresh sync budget (each member gets an equal share of what is left; `sources.refresh_sync_budget_ms`, `GBRAIN_REFRESH_SYNC_BUDGET_MS`, default 5 min), for example because no consumer claimed its write. The message names that write and its state. The checkout is at the upstream commit, the refresh completed and released its lock, and the source is behind until its next sync. A sync stopped by the drain's own rules is reported with that stop's code instead (`drain_stalled` and the others). | Run the `resume` command (`gbrain sync --source <source> --no-pull`). If it stalls the same way, check the write it names with `gbrain sources writer status <source> --json`. |
| <a id="refresh_source_changed"></a>`refresh_source_changed` | `refresh_source_changed` | HEAD moved (an outside commit or checkout), or the checkout's ownership or set of sources changed, between the precheck and the merge. Nothing was merged and the fence was lifted. | Retry `gbrain sources refresh <source>`. |
| <a id="refresh_recovery_required"></a>`refresh_recovery_required` | `refresh_recovery_required` | Publication or source recovery is pending on the checkout, or a refresh was interrupted and HEAD is neither the commit it started from nor the verified upstream commit. Writes to the checkout stay refused until it is resolved; gbrain never adopts a HEAD it cannot verify. | `gbrain sources writer status <source>`, then `gbrain sources refresh <source> --resume`. When HEAD is unverified the fix names both ways out: reset to the start commit and run `--abandon`, or reset to the upstream commit and run `--resume`. Resetting is destructive, so ask the user first. |
-| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not journaled. `detail` is `retry_after_ms=1000`. Writes to database-only memory are not affected. An interactive write (CLI, MCP) waits out the fence for up to 10 s before this refusal; a background write is refused at once. The refusal is `retryable`, its `fix.next` is `wait`, and the CLI exits 1; the memory verbs keep their frozen `unavailable` code with `canonical: worktree_refreshing`. | Retry the same request ID after `retry_after_ms`; nothing was recorded, so the retry cannot write twice. `gbrain sources writer status --source <source> --json` shows the refresh. A cycle's sync is retried by the next cycle. |
+| <a id="worktree_refreshing"></a>`worktree_refreshing` | `worktree_refreshing` | A write, or a managed sync started by a cycle or another command, reached a checkout while a refresh is draining or merging it. It was not journaled. `detail` is `retry_after_ms=1000`. Writes to database-only memory are not affected. An interactive write (CLI, MCP) waits out the fence for up to 10 s, or its explicit `wait_ms` if lower, before this refusal; a background write is refused at once. The refusal is `retryable`, its `fix.next` is `wait`, and the CLI exits 1; the memory verbs keep their frozen `unavailable` code with `canonical: worktree_refreshing`. | Retry the same request ID after `retry_after_ms`; nothing was recorded, so the retry cannot write twice. `gbrain sources writer status --source <source> --json` shows the refresh. A cycle's sync is retried by the next cycle. |
A refresh is recorded in `persistence_worktree_refreshes` and survives a crash.
When the owner restarts it finishes the deterministic steps on its own: an
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index b69e09a094..a302c15c37 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -98,10 +98,14 @@ let refreshFenceWaitMs = REFRESH_FENCE_WAIT_MS;
/** Test seam: the wait cap, or null for the default. */
export function _setRefreshFenceWaitForTests(ms: number | null): void { refreshFenceWaitMs = ms ?? REFRESH_FENCE_WAIT_MS; }
-/** One deadline shared by every admission inside it (a remember batch waits once, not once per item). */
-const refreshFenceDeadline = new AsyncLocalStorage<{ until: number }>();
-export function withRefreshFenceBudget<T>(fn: () => Promise<T>): Promise<T> {
- return refreshFenceDeadline.getStore() ? fn() : refreshFenceDeadline.run({ until: performance.now() + refreshFenceWaitMs }, fn);
+/**
+ * One wait budget shared by every admission inside it (a remember batch waits once, not once per item). Its clock starts
+ * at the first fence refusal, so time spent publishing earlier items never uses it. `capMs` lowers it to a caller's
+ * explicit reply deadline (`wait_ms`).
+ */
+const refreshFenceDeadline = new AsyncLocalStorage<{ capMs: number; until?: number }>();
+export function withRefreshFenceBudget<T>(fn: () => Promise<T>, capMs?: number): Promise<T> {
+ return refreshFenceDeadline.getStore() ? fn() : refreshFenceDeadline.run({ capMs: Math.min(refreshFenceWaitMs, capMs ?? Infinity) }, fn);
}
export function isRefreshFenceRefusal(error: unknown): error is OperationError {
@@ -115,21 +119,22 @@ export function isRefreshFenceRefusal(error: unknown): error is OperationError {
export async function waitOutRefreshFence<T>(interactive: boolean, admit: () => Promise<T>): Promise<T> {
if (!interactive) return admit();
return withRefreshFenceBudget(async () => {
- const until = refreshFenceDeadline.getStore()!.until;
- const started = performance.now();
+ const budget = refreshFenceDeadline.getStore()!;
+ let waited = 0;
for (let attempt = 0; ; attempt++) {
try { return await admit(); } catch (error) {
if (!isRefreshFenceRefusal(error)) throw error;
const hinted = Number(/retry_after_ms=(\d+)/.exec(error.detail ?? '')?.[1]);
const pause = Math.min(REFRESH_FENCE_BACKOFF_MS[Math.min(attempt, REFRESH_FENCE_BACKOFF_MS.length - 1)]!,
Number.isFinite(hinted) && hinted > 0 ? Math.max(hinted, REFRESH_FENCE_BACKOFF_MS[0]) : Infinity);
- const remaining = until - performance.now();
- if (remaining < pause) {
- const waited = Math.round(performance.now() - started);
- if (waited > 0) error.message = `${error.message} This call waited ${waited} ms for the refresh to finish.`;
+ budget.until ??= performance.now() + budget.capMs;
+ if (budget.until - performance.now() < pause) {
+ if (waited > 0) error.message = `${error.message} This call waited ${Math.round(waited)} ms for the refresh to finish.`;
throw error;
}
+ const slept = performance.now();
await delay(pause);
+ waited += performance.now() - slept;
}
}
});
diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.ts
index 41f147a0d6..cb3d956372 100644
--- a/src/core/persistence/ipc.ts
+++ b/src/core/persistence/ipc.ts
@@ -342,14 +342,26 @@ export class PersistenceIpcTransportError extends Error {
}
}
+/**
+ * GST-1387: a wire error body's recovery contract (canonical code, detail, retryable, fix) restored onto a rebuilt
+ * OperationError, so a refresh fence stays worktree_refreshing with fix.next wait across the owner hop. A receipt
+ * error's fix is not carried: this side renders it from the receipt for its own principal.
+ */
+export function restoreRecoveryContract(error: OperationError, body: Record<string, unknown>): void {
+ if (typeof body.code === 'string' && body.code !== error.code) error.canonical = body.code as OperationError['canonical'];
+ if (typeof body.detail === 'string') error.detail = body.detail;
+ if (typeof body.retryable === 'boolean') error.retryable = body.retryable;
+ if (record(body.fix) && !body.write_request) { const { next: _next, command: _command, ...fix } = body.fix; error.fix = fix as unknown as Action; }
+}
+
function remoteOperationError(value: unknown): OperationError {
if (!record(value) || typeof value.error !== 'string' || typeof value.message !== 'string') {
throw new Error('Malformed persistence error response.');
}
const error = new OperationError(value.error, value.message, typeof value.suggestion === 'string' ? value.suggestion : undefined,
typeof value.docs === 'string' ? value.docs : undefined);
- if (typeof value.detail === 'string') error.detail = value.detail;
if (typeof value.protocol_version === 'number') error.protocolVersion = value.protocol_version;
+ restoreRecoveryContract(error, value);
if (isWriteReceipt(value.write_request)) error.writeRequest = publicWriteReceipt(value.write_request);
if (isWriteRequestId(value.request_id)) error.requestId = value.request_id;
if (isWriteErrorCode(value.write_error)) error.writeError = value.write_error;
diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.ts
index 5fd1dee94e..967b80fc1f 100644
--- a/src/core/persistence/page-batch.ts
+++ b/src/core/persistence/page-batch.ts
@@ -16,7 +16,7 @@ import type { OperationContext } from '../ops/contract.ts';
import { fenceNormalizedNotice, mergeFencesNormalized, type FencesNormalized } from '../fence-repair/report.ts';
import { OperationError, opError } from '../ops/contract.ts';
import { admitWriteGroupInTransaction, type WriteAdmission } from './journal.ts';
-import { retryWriteAdmission, waitOutRefreshFence } from './admission-retry.ts';
+import { retryWriteAdmission, waitOutRefreshFence, withRefreshFenceBudget } from './admission-retry.ts';
import { resolveAdmissionOrigin } from './admission-origin.ts';
import { declareDurablePersistence } from './protocol.ts';
import { digest } from './digest.ts';
@@ -289,7 +289,7 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<stri
if (admissions.length) {
let admitted: WriteRequest[];
try {
- admitted = await admitBatch(ctx, batchId, admissions.map(entry => entry.admission));
+ admitted = await withRefreshFenceBudget(() => admitBatch(ctx, batchId, admissions.map(entry => entry.admission)), params.wait_ms !== undefined ? remaining() : undefined);
} catch (error) {
if (error instanceof OperationError && error.code === 'queue_capacity') {
throw new OperationError('queue_capacity', `${error.message} No page of batch ${batchId} was admitted (it needs ${admissions.length} new write slots).`,
diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.ts
index c387700446..ef97fa9bdb 100644
--- a/src/core/persistence/page-mutations.ts
+++ b/src/core/persistence/page-mutations.ts
@@ -20,6 +20,7 @@ import { sha256 } from './digest.ts';
import { receiptReservation } from './receipt-bytes.ts';
import { assertPersistenceAccepting, estimatedRetryAfterMs, waiterOnlyOwner, onPersistenceLane, waitForWrite, writeResponse } from './service.ts';
import { parseWireWriteWaitMs } from './write-wait.ts';
+import { withRefreshFenceBudget } from './admission-retry.ts';
import { assertTimelineNotOmitted, isTimelineSection, timelineSectionOf, type TimelineSection } from './timeline-omission.ts';
import { contentOriginTier } from '../trust/tier.ts';
import { PAGE_MAX_BYTES } from '../page-size-policy.ts';
@@ -239,8 +240,9 @@ export async function submitPageMutation(ctx: OperationContext,
if (prepared.prior) return withLiveSearchable(ctx, throwIfHeld(pendingAwareResponse(ctx, await waitForWrite(ctx.engine, prepared.prior, ctx.config, waitMs())), false));
const brainId = cached ? cachedPreadmitBrain(ctx.engine) : undefined;
// Phase 4.4: the admission transaction runs on the warm single-write lane when it is free.
- const admit = (admission: WriteAdmission) => onPersistenceLane(ctx.engine, transaction => admitWrite(ctx.engine, admission, undefined, transaction),
- () => admitWrite(ctx.engine, admission));
+ // GST-1387: an explicit wait_ms also bounds the refresh-fence wait, so wait_ms 0 is refused at once, never held.
+ const admit = (admission: WriteAdmission) => withRefreshFenceBudget(() => onPersistenceLane(ctx.engine, transaction => admitWrite(ctx.engine, admission, undefined, transaction),
+ () => admitWrite(ctx.engine, admission)), wireWaitMs !== undefined ? waitMs() : undefined);
let row: WriteRequest;
try { row = await admit(brainId ? { ...prepared.admission, brainId } : prepared.admission); }
catch (error) {
diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.ts
index 441362768e..71dc4326f2 100644
--- a/src/core/persistence/provider.ts
+++ b/src/core/persistence/provider.ts
@@ -8,7 +8,7 @@ import { dispatchToolCall } from '../../mcp/dispatch.ts';
import { registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';
import { startPersistenceConsumer, assertPersistenceAccepting } from './service.ts';
import { isWriteErrorCode, isWriteReceipt } from './types.ts';
-import { LOCAL_CLI_OWNER_OPERATIONS, type PersistenceIpcProvider } from './ipc.ts';
+import { LOCAL_CLI_OWNER_OPERATIONS, restoreRecoveryContract, type PersistenceIpcProvider } from './ipc.ts';
import { runPersistenceAdministration } from './administration.ts';
import { boundedWriteWaitMs } from './write-wait.ts';
export { residentPersistenceConfig } from './local-client.ts';
@@ -95,6 +95,7 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:
const error = new OperationError(typeof body.error === 'string' ? body.error : 'unavailable',
typeof body.message === 'string' ? body.message : 'The local operation could not complete.',
typeof body.suggestion === 'string' ? body.suggestion : undefined);
+ restoreRecoveryContract(error, body);
if (isWriteReceipt(body.write_request)) error.writeRequest = body.write_request;
if (isWriteErrorCode(body.write_error)) error.writeError = body.write_error;
if (body.protocol_version === 1) error.protocolVersion = 1;
diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.ts
index e6b5aa2d8b..66ccd97bea 100644
--- a/src/core/remember-batch.ts
+++ b/src/core/remember-batch.ts
@@ -115,7 +115,7 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,
continue;
}
failures.push({ index, error: e });
- results.push({ index, request_id: child, status: 'failed', error: { code: e.code, message: e.message, ...(e.writeError ? { write_error: e.writeError } : {}), ...(e.detail ? { detail: e.detail } : {}), ...(e.suggestion ? { suggestion: e.suggestion } : {}), ...(e.withdrawn ? { withdrawn: e.withdrawn } : {}) } });
+ results.push({ index, request_id: child, status: 'failed', error: { code: e.code, message: e.message, ...(e.canonical ? { canonical: e.canonical } : {}), ...(e.retryable !== undefined ? { retryable: e.retryable } : {}), ...(e.writeError ? { write_error: e.writeError } : {}), ...(e.detail ? { detail: e.detail } : {}), ...(e.suggestion ? { suggestion: e.suggestion } : {}), ...(e.withdrawn ? { withdrawn: e.withdrawn } : {}) } });
}
} });
const failed = results.filter(r => r.status === 'failed').length;
diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.ts
index b5439d279b..3fce62c0a3 100644
--- a/src/mcp/dispatch.ts
+++ b/src/mcp/dispatch.ts
@@ -1298,10 +1298,9 @@ async function dispatchResolvedCall(
// GST-1387: a remember batch with a failed item is an MCP error; its body keeps every item's receipt.
const batchError = name === 'remember' && typeof result === 'object' && result !== null && (result as { status?: unknown }).status === 'error' && Array.isArray((result as { items?: unknown }).items);
if (opts.transport === 'stdio' && opts.remote !== false && !batchError) { const up = takePostUpgradeMcpNotice(); if (up) notices.push(up); } // F7
- if (opts.transport === 'stdio' && opts.remote !== false) notices.push(...await mcpOnboardingNotices({ engine, op: name, result, meta: responseMeta, config: ctx.config, render: dispatchRenderContext(opts) }));
+ if (opts.transport === 'stdio' && opts.remote !== false && !batchError) notices.push(...await mcpOnboardingNotices({ engine, op: name, result, meta: responseMeta, config: ctx.config, render: dispatchRenderContext(opts) }));
if (opts.transport === 'stdio' && opts.remote !== false && !batchError) { const drain = takeFactsDrainNotice(); if (drain) notices.push(drain); } // Lane D facts drain
- notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));
- notices.push(...await grantBlockedNotices(engine, opts, false));
+ if (!batchError) notices.push(...await sessionSafetyNotices(engine, opts, ctx.config), ...await grantBlockedNotices(engine, opts, false));
const out: ToolResult = batchError ? toolErrorResult(result as never) : toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));
if (evidenceBlocks.length > 0) out.content.splice(1, 0, ...evidenceBlocks.map(text => ({ type: 'text' as const, text })));
if (opts.transport === 'stdio') {
diff --git a/test/mcp-notice-channels.test.ts b/test/mcp-notice-channels.test.ts
index de5c9db850..3903978ed9 100644
--- a/test/mcp-notice-channels.test.ts
+++ b/test/mcp-notice-channels.test.ts
@@ -282,14 +282,19 @@ describe('F7 coaching reaches agents', () => {
try {
mkdirSync(join(home, '.gbrain'), { recursive: true });
writeFileSync(join(home, '.gbrain', 'upgrade-state.json'), JSON.stringify({ last_upgrade: { from: '0.0.1.0', to: VERSION } }));
+ const { __resetBehaviorNoticeForTests, BEHAVIOR_NOTICE_CODE, takeLocalBehaviorNotice } = await import('../src/core/behavior-change-notice.ts');
+ // A brain older than this release has pending behavior changes, so the stdio behavior notice is due.
+ await engine.executeRaw("UPDATE sources SET created_at = now() - interval '30 days'");
await withEnv({ HOME: home, GBRAIN_HOME: home, GBRAIN_NO_ONBOARD_NUDGE: undefined }, async () => {
__resetPostUpgradeNoticeForTests();
+ __resetBehaviorNoticeForTests();
op.handler = async () => ({ status: 'error', error: 'invalid_params', code: 'invalid_params', message: '1 of 2 item(s) failed.',
items: [{ index: 0, request_id: 'r0', status: 'failed', error: { code: 'invalid_params', message: 'refused' } }, { index: 1, request_id: 'r1', status: 'inserted', id: 7 }],
saved: 1, failed: 1, partial: true });
const res = await dispatchToolCall(engine as any, 'remember', { items: ['alice-example likes tea', 'alice-example likes jazz'], provenance: 'test' }, { remote: true, transport: 'stdio', sourceId: 'default' });
expect(res.isError).toBe(true);
expect(takePostUpgradeMcpNotice()?.code).toBe('post_upgrade');
+ expect((await takeLocalBehaviorNotice(engine as any, 'stdio', { cfg: null }))?.code).toBe(BEHAVIOR_NOTICE_CODE);
});
} finally {
op.handler = original;
diff --git a/test/pending-write-exit-owner.test.ts b/test/pending-write-exit-owner.test.ts
index b5b15bf7d3..929ec43d67 100644
--- a/test/pending-write-exit-owner.test.ts
+++ b/test/pending-write-exit-owner.test.ts
@@ -18,6 +18,9 @@ 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';
+import { operations } from '../src/core/operations.ts';
+import { catalogueError } from '../src/core/error-catalogue.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
const CLI = join(import.meta.dir, '../src/cli.ts');
let dir: string;
@@ -120,6 +123,41 @@ describe('paused writers and the CLI exit contract', () => {
});
}, 180_000);
+ test('#8621 resident owner: a refresh-fence refusal keeps its code, retryable flag and wait fix across the owner hop', async () => {
+ await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {
+ const provider = await createPersistenceIpcProvider(engine, config);
+ const binding = await startPersistenceIpcServer(persistenceSocketPathForConfig(config)!, provider);
+ const op = operations.find(o => o.name === 'put_page')! as { handler: unknown };
+ const original = op.handler;
+ const remember = operations.find(o => o.name === 'remember')! as { handler: unknown };
+ const rememberOriginal = remember.handler;
+ op.handler = async () => {
+ const error = catalogueError('worktree_refreshing', 'Source default\'s checkout is being fast-forwarded by a refresh (syncing); this write was not journaled.',
+ 'Retry the same request_id after retry_after_ms: 1000.');
+ throw Object.assign(error, { detail: 'retry_after_ms=1000', retryable: true, fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json'],
+ consent: [], actor: 'provider', requires_exclusive: false, why: 'A refresh holds this checkout\'s writes; repeat the same call after about 1 s.' } });
+ };
+ try {
+ const put = await cli(['put', 'notes/fenced', '--json'], '---\ntitle: Fenced\n---\nbody\n');
+ expect(put.code).toBe(1);
+ const env = JSON.parse(put.stdout);
+ expect(env).toMatchObject({ code: 'worktree_refreshing', retryable: true, detail: 'retry_after_ms=1000' });
+ expect(env.fix).toMatchObject({ next: 'wait', argv: ['gbrain', 'sources', 'writer', 'status', '--source', 'default', '--json', '--brain', 'host'] });
+ // remember keeps its frozen `error: unavailable`; the canonical code rides beside it.
+ remember.handler = async () => { throw Object.assign(new OperationError('unavailable', 'The checkout is refreshing; this fact was not recorded.'),
+ { canonical: 'worktree_refreshing', detail: 'retry_after_ms=1000', retryable: true, protocolVersion: 1 }); };
+ const fact = await cli(['remember', 'acme-example renewed', '--provenance', 'call notes', '--json']);
+ expect(fact.code).toBe(1);
+ expect(JSON.parse(fact.stdout)).toMatchObject({ error: 'unavailable', code: 'worktree_refreshing', retryable: true, detail: 'retry_after_ms=1000' });
+ } finally {
+ op.handler = original;
+ remember.handler = rememberOriginal;
+ 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();
diff --git a/test/remember-batch.test.ts b/test/remember-batch.test.ts
index e808f781b6..62009fd2ec 100644
--- a/test/remember-batch.test.ts
+++ b/test/remember-batch.test.ts
@@ -120,6 +120,16 @@ describe('remember items[] batch', () => {
expect(out.items[1]).toMatchObject({ request_id: childRequestId(root, 1), status: 'failed', error: { write_error: 'write_outcome_unknown' } });
});
+ test('#8621: a fenced item in a partial batch keeps its canonical code and retryable flag', async () => {
+ const { handler: base } = fakeSingle();
+ const handler = async (c: OperationContext, p: Record<string, unknown>) => {
+ if (p.fact !== 'fenced' || c.dryRun) return base(c, p);
+ throw Object.assign(ve('unavailable', 'The checkout is refreshing.', 'Retry the same request_id.'), { canonical: 'worktree_refreshing', retryable: true, detail: 'retry_after_ms=1000' });
+ };
+ const out = await runRememberBatch(ctx, { provenance: 'p', items: [{ fact: 'ok' }, { fact: 'fenced' }] }, handler, ve) as Record<string, any>;
+ expect(out.items[1].error).toMatchObject({ code: 'unavailable', canonical: 'worktree_refreshing', retryable: true, detail: 'retry_after_ms=1000' });
+ });
+
test('#8621: a batch whose every item failed throws the first item error instead of returning a success envelope', async () => {
const { handler, writes } = fakeSingle({ failWrite: () => true });
let err: unknown;
diff --git a/test/write-refusal-refresh-fence-8621.test.ts b/test/write-refusal-refresh-fence-8621.test.ts
index 155c362b1b..8a27924d10 100644
--- a/test/write-refusal-refresh-fence-8621.test.ts
+++ b/test/write-refusal-refresh-fence-8621.test.ts
@@ -24,7 +24,8 @@ import { refreshWorktree } from '../src/core/persistence/worktree-refresh.ts';
import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { admitWrite, type WriteAdmission } from '../src/core/persistence/journal.ts';
import { admitBatch } from '../src/core/persistence/page-batch.ts';
-import { _setRefreshFenceWaitForTests } from '../src/core/persistence/admission-retry.ts';
+import { _setRefreshFenceWaitForTests, waitOutRefreshFence, withRefreshFenceBudget } from '../src/core/persistence/admission-retry.ts';
+import { OperationError } from '../src/core/ops/contract.ts';
import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
import { testBackends } from './helpers/test-backends.ts';
import { withEnv } from './helpers/with-env.ts';
@@ -118,6 +119,37 @@ test('put_page past the wait cap is refused retryable with fix.next wait and ret
}));
}), 120_000);
+test('an explicit wait_ms bounds the fence wait: put_page and put_pages with wait_ms 0 are refused without waiting', () => each(async f => {
+ _setRefreshFenceWaitForTests(5000);
+ await (await duringRefresh(f, async () => {
+ const before = await f.requestCount();
+ const started = performance.now();
+ const one = await call(f, 'put_page', { slug: 'notes/zero-wait', content: page('Zero wait', 'no fence wait'), wait_ms: 0 });
+ const many = await call(f, 'put_pages', { request_id: crypto.randomUUID(), wait_ms: 0, pages: [{ slug: 'notes/zero-wait-batch', content: page('Zero wait batch', 'no fence wait') }] });
+ expect(performance.now() - started).toBeLessThan(5000);
+ for (const out of [one, many]) {
+ expect(out.isError).toBe(true);
+ expect(out.body.code).toBe('worktree_refreshing');
+ expect(out.body.message).not.toContain('waited');
+ }
+ expect(await f.requestCount()).toBe(before);
+ }));
+}), 120_000);
+
+test('a shared fence budget starts at the first refusal, and the waited note needs a real pause', async () => {
+ const fenced = () => Object.assign(new OperationError('worktree_refreshing' as never, 'The checkout is refreshing.'), { detail: 'retry_after_ms=250' });
+ _setRefreshFenceWaitForTests(300);
+ const admitted = await withRefreshFenceBudget(async () => {
+ await new Promise(resolve => setTimeout(resolve, 400));
+ let tries = 0;
+ return waitOutRefreshFence(true, async () => { if (tries++ === 0) throw fenced(); return 'admitted'; });
+ });
+ expect(admitted).toBe('admitted');
+ _setRefreshFenceWaitForTests(0);
+ const refused = await waitOutRefreshFence(true, async () => { await new Promise(resolve => setTimeout(resolve, 30)); throw fenced(); }).catch(e => e as Error);
+ expect(refused.message).toBe('The checkout is refreshing.');
+});
+
test('an admission retried after its accepted commit lost its ack reconciles to the receipt under a fence, never "not recorded"', () => each(async f => {
_setRefreshFenceWaitForTests(0);
const requestId = crypto.randomUUID();