Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix: refresh-fence write refusals are retryable waits, never success (#8621)

garrytanab3774e98dcd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index af2351b4af..dea782f0aa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ credits are retained; no result has been reassigned to another provider. Origina
identifiers and attribution are available in the pre-removal Git revision
`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).
+## [Unreleased]
+
+**A write a refresh fence refused is never reported as success, and an interactive write waits the fence out.** While `gbrain sources refresh` drains, fast-forwards and syncs a checkout, writes to it are refused `worktree_refreshing`. That refusal was unregistered (class server, `fix: gbrain doctor`), `remember` with `items` whose every item it refused printed `undefined (fact #undefined)` and exited 0, and the same batch over MCP returned `isError: false`. The refusal is now retryable with `fix.next: wait` and `retry_after_ms`, an interactive write retries it with backoff for up to 10 s before refusing, and a batch that saved nothing is an error on every surface (#8621).
+
+### 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`.
+- `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/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 adds `status: "error"`. `src/cli/remember-format.ts` prints a batch as `saved X of N fact(s)` with one line per item.
+- `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.574.0] - 2026-11-04
**A brain opened from settings no longer leaks into the process, or into another brain, when a call forgets its scope.** While an embedded engine is open, an embed, chat, expansion or rerank call that entered no scope now refuses `engine_scope_required` and sends nothing, even if the host configured a process gateway; it decides by scope presence alone. `withLocalScope(fn)` marks a call that belongs to the process gateway, and the CLI, `gbrain serve` and `gbrain jobs` enter it, so they behave exactly as before. `hybridSearch`, the import paths, minion jobs and `POST /mcp` enter their engine's scope themselves. Each embedded engine keeps its own chat-usage sink (it survives `reconnect()`), batch-shrink, no-key and structured-output memory, and alias and remote-privacy policy, and a closed per-call engine is no longer held by the policy sets. A host that reopens a brain per call can pass `settings.cache_namespace` to keep its query embeddings warm. `openEngine` now refuses a settings key it does not know. Everything here is behind `embedded_core`, which is off by default.
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.md
index 0cdc1a9e52..fd270657bf 100644
--- a/docs/guides/error-codes.md
+++ b/docs/guides/error-codes.md
@@ -5095,6 +5095,16 @@ More: [docs/guides/write-refusals.md#visibility_not_applied](../../docs/guides/w
More: [docs/guides/write-refusals.md#worktree_dirty](../../docs/guides/write-refusals.md#worktree_dirty)
+### worktree_refreshing
+
+<a id="worktree_refreshing"></a>
+
+| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |
+|---|---|---|---|---|---|---|
+| A write reached a checkout while `gbrain sources refresh` was draining, fast-forwarding or syncing it, so it was not journaled; nothing was recorded. | A refresh fences every source bound to the checkout until its syncs finish, so no write publishes onto a moving HEAD. An interactive write waits out the fence for up to 10 s before this refusal; a refresh tick can hold it for minutes. | Repeat the same call with the same request_id after retry_after_ms (in detail); nothing was recorded, so the retry cannot write twice. gbrain sources writer status --source <id> --json shows the refresh. | provider | `repeat the read that failed` | 1 | yes |
+
+More: [docs/guides/write-refusals.md#worktree_refreshing](../../docs/guides/write-refusals.md#worktree_refreshing)
+
### write_capacity_backpressure
<a id="write_capacity_backpressure"></a>
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.md
index 9431fe3f84..e2c87771f1 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. | Retry the same request ID after about a second. `gbrain sources writer status <source>` 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 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/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.md
index bf9e4f591a..1d6de27fd2 100644
--- a/docs/protocol/MEMORY_VERBS_v1.md
+++ b/docs/protocol/MEMORY_VERBS_v1.md
@@ -411,18 +411,18 @@ fact, so it goes on its item; passing both `fact` and `items`, or a top-level
Every item is validated before any is written: one invalid item refuses the
whole call with `items[<i>]` in the message. Each item is then saved as its own
-write with a child `request_id` derived from the call's `request_id` (the
-string the caller sent, so a batch accepted by an older server replays to the
-same receipts) and the item index, so replaying the same `request_id` replays each child's outcome and
+write with a child `request_id` derived from the call's `request_id` (as sent, so an
+older server's batch replays to the same receipts) and the item index, so a replay repeats each child's outcome and
writes nothing twice.
Response: `{ protocol_version, request_id, client_request_id?, items[], saved, failed, partial,
hints?, next? }`. Each `items[]` entry is a compact receipt `{ index,
request_id, status, id?, entity_slug?, superseded_fact_id?, warnings?, valid_until?, state? }`
(`state` and `retry_after_ms` only when the write is not yet committed), or
-`{ index, request_id, status: "failed", error: { code, message, suggestion? } }`. Hints the
-single-fact response would repeat per item appear once in `hints`. `partial: true` means some items saved and some failed; resend
-only the failed items, in a new call with a new `request_id`.
+`{ index, request_id, status: "failed", error: { code, message, suggestion? } }`. Per-item hints
+appear once in `hints`. `partial: true`: some items saved; resend
+only the failed ones under a new `request_id`. Any failed item adds `status: "error"` (CLI exit 1,
+MCP `isError`); if none saved, the call fails with the first item's error.
### entity(name) — read, zero LLM, p99 < 100ms
diff --git a/llms-full.txt b/llms-full.txt
index f964ca2b0c..953f27939b 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -8871,18 +8871,18 @@ fact, so it goes on its item; passing both `fact` and `items`, or a top-level
Every item is validated before any is written: one invalid item refuses the
whole call with `items[<i>]` in the message. Each item is then saved as its own
-write with a child `request_id` derived from the call's `request_id` (the
-string the caller sent, so a batch accepted by an older server replays to the
-same receipts) and the item index, so replaying the same `request_id` replays each child's outcome and
+write with a child `request_id` derived from the call's `request_id` (as sent, so an
+older server's batch replays to the same receipts) and the item index, so a replay repeats each child's outcome and
writes nothing twice.
Response: `{ protocol_version, request_id, client_request_id?, items[], saved, failed, partial,
hints?, next? }`. Each `items[]` entry is a compact receipt `{ index,
request_id, status, id?, entity_slug?, superseded_fact_id?, warnings?, valid_until?, state? }`
(`state` and `retry_after_ms` only when the write is not yet committed), or
-`{ index, request_id, status: "failed", error: { code, message, suggestion? } }`. Hints the
-single-fact response would repeat per item appear once in `hints`. `partial: true` means some items saved and some failed; resend
-only the failed items, in a new call with a new `request_id`.
+`{ index, request_id, status: "failed", error: { code, message, suggestion? } }`. Per-item hints
+appear once in `hints`. `partial: true`: some items saved; resend
+only the failed ones under a new `request_id`. Any failed item adds `status: "error"` (CLI exit 1,
+MCP `isError`); if none saved, the call fails with the first item's error.
### entity(name) — read, zero LLM, p99 < 100ms
diff --git a/src/cli/remember-format.ts b/src/cli/remember-format.ts
index f0420ebc89..feab48ac8f 100644
--- a/src/cli/remember-format.ts
+++ b/src/cli/remember-format.ts
@@ -5,6 +5,16 @@
*/
export function formatRememberResult(r: Record<string, any>, params: Record<string, unknown> = {}): string {
if (r.dry_run) return `[dry-run] would remember: ${r.fact}\n`;
+ // GST-1387: a batch (`items`) reports per item; a failed item never reads as saved.
+ if (Array.isArray(r.items)) {
+ const lines = [`saved ${r.saved} of ${r.items.length} fact(s)${r.failed ? `, ${r.failed} failed` : ''}${r.pending ? `, ${r.pending} pending` : ''}`];
+ for (const item of r.items) {
+ lines.push(item.status === 'failed' ? ` items[${item.index}]: failed [${item.error?.code}] ${item.error?.message ?? ''}`
+ : ` items[${item.index}]: ${item.status}${item.id !== undefined ? ` (fact #${item.id})` : ''}${item.entity_slug ? ` entity: ${item.entity_slug}` : ''}`);
+ }
+ if (r.next) lines.push(` next: ${r.next}`);
+ return lines.join('\n') + '\n';
+ }
const lines = [r.status_text || `${r.status} (fact #${r.id})`];
if (r.entity_slug) lines.push(` entity: ${r.entity_slug}${r.entity_inferred ? ' (inferred from mention)' : ''}`);
if (r.valid_until) lines.push(` expires: ${r.valid_until}`);
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index fee274831a..256c3fac09 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1425,6 +1425,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
// GBRA-280 (GBEV-30 re-read) get_page window-selector precedence; release:restamp stamps since at the merge slot.
{ since: '0.60.570.0', id: 'get_page_selector_precedence_gbra280', text: 'get_page given several window selectors now reads one window instead of refusing with invalid_params: cursor, then around_chunk_id, then lines, then bytes, and a cursor that cannot read the page or an around_chunk_id no longer on it gives way to the next. body full, include_content and content_only beside a selector are set aside, so the read stays a window and never returns the whole page. The response\'s window_selector names what applied and what was ignored; a call with one selector is unchanged.' },
{ since: '0.60.574.0', id: 'embedded_scope_required_gbra283', text: 'Experimental embedded engines (`openEngine` with `embedded_core: true`) only; the CLI, `gbrain serve` and mounts are unchanged. While such an engine is open, an embed, chat, expansion or rerank call that entered no scope now refuses `engine_scope_required` (new code) even when the host configured a process gateway with `configureGateway`; before, that configuration let unscoped calls use the process keys, and the refusal was `engine_scope_missing`, which now only means a provider the engine lacks or a closed engine. Wrap such calls in `withEngineScope(engine, fn)`, or `withLocalScope(fn)` for calls that belong to the process gateway (both from `gbrain/engine-open`); `hybridSearch`, the import paths, minion jobs and `POST /mcp` enter their engine\'s scope themselves. `openEngine` also refuses an unknown settings key, top-level or nested, with `engine_settings_invalid` naming the key, where it used to ignore it. An embedded engine\'s chat usage is no longer on the process usage stack and survives `reconnect()`. See docs/ENGINES.md "Upgrading an embedded host".' },
+ // GST-1387 (#8621) refresh-fence refusals; release:restamp stamps since at the merge slot.
+ { since: '0.60.574.0', id: 'refresh_fence_refusal_gst1387', text: 'A write refused because `gbrain sources refresh` is fast-forwarding its checkout (`worktree_refreshing`) is now a registered retryable refusal whose fix is `next: wait` with `retry_after_ms`, instead of class server with `fix: gbrain doctor`; the memory verbs keep `unavailable` and add `canonical: worktree_refreshing`. An interactive CLI or MCP write waits out the fence for up to 10 s before that refusal; a background write is refused at once as before. `remember` with `items` whose every item failed is now refused with the first item\'s error (CLI exit 1, MCP isError) instead of a success envelope with `failed`, and a batch with any failed item adds `status: "error"`, so the CLI exits 1.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
index ecfb7e42ce..18339ed0e6 100644
--- a/src/core/error-registry.ts
+++ b/src/core/error-registry.ts
@@ -863,6 +863,7 @@ export const CODES = {
why: "On a live checkout an agent may be mid-edit on a file the catch-up reaches. The bytes are not committed at HEAD, so sync cannot tell a deliberate local change from a stray one, and importing the pinned version would discard the edit; before #6340 this refusal stopped the whole run.",
docs: 'docs/guides/write-refusals.md#worktree_dirty',
suggestion: 'Commit the file (or restore it), then run gbrain sync unblock --source <id> --apply (it re-screens every held file that is now committed) and the same gbrain sync; a later commit that changes the file re-screens it on its own.' },
+ worktree_refreshing: { class: 'retryable', actor: 'provider', summary: "A write reached a checkout while `gbrain sources refresh` was draining, fast-forwarding or syncing it, so it was not journaled; nothing was recorded.", why: "A refresh fences every source bound to the checkout until its syncs finish, so no write publishes onto a moving HEAD. An interactive write waits out the fence for up to 10 s before this refusal; a refresh tick can hold it for minutes.", docs: 'docs/guides/write-refusals.md#worktree_refreshing', suggestion: 'Repeat the same call with the same request_id after retry_after_ms (in detail); nothing was recorded, so the retry cannot write twice. gbrain sources writer status --source <id> --json shows the refresh.' },
writer_admin_intent_required: { class: 'host_only', summary: "Topology changes require an action-specific --admin-intent and the --expected-state from a reviewed writer status." },
writer_admin_locked: { class: 'host_only', summary: "Writer administration is locked; deactivation was not applied." },
writer_admin_state_changed: { class: 'caller', summary: "Writer topology changed since inspection; the administrative request was not applied." },
diff --git a/src/core/persistence/admission-retry.ts b/src/core/persistence/admission-retry.ts
index e4e103d3b8..b69e09a094 100644
--- a/src/core/persistence/admission-retry.ts
+++ b/src/core/persistence/admission-retry.ts
@@ -1,3 +1,4 @@
+import { AsyncLocalStorage } from 'node:async_hooks';
import { setTimeout as delay } from 'node:timers/promises';
import { markNotAdmitted, OperationError, opError } from '../ops/contract.ts';
import { getCode, isConnectionLoss } from '../retry-matcher.ts';
@@ -84,3 +85,52 @@ export function outstandingCapacityOf(error: OperationError): { outstanding: num
const scope = /\bbrain outstanding\b/.test(error.message) ? 'brain' : /\bprincipal outstanding\b/.test(error.message) ? 'principal' : null;
return { outstanding: match ? Number(match[1]) : null, limit: match ? Number(match[2]) : null, scope };
}
+
+/**
+ * GST-1387: how long an interactive write waits out a refresh fence (`worktree_refreshing`) before it is refused. A
+ * `gbrain sources refresh` tick fences its checkout while it drains, fast-forwards and syncs; a write refused there was
+ * never journaled, so re-running its admission is safe. The cap stays well under a caller's own deadline (the CLI's 30 s
+ * remote timeout); past it the refusal is returned with `fix.next: wait` and its `retry_after_ms`, never a success.
+ */
+export const REFRESH_FENCE_WAIT_MS = 10_000;
+const REFRESH_FENCE_BACKOFF_MS = [250, 500, 1000, 2000] as const;
+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);
+}
+
+export function isRefreshFenceRefusal(error: unknown): error is OperationError {
+ return error instanceof OperationError && error.code === 'worktree_refreshing';
+}
+
+/**
+ * Runs one whole admission (its own transactions), re-running it while a refresh fence refuses it. Only interactive
+ * writes wait: background producers and the managed sync keep their own retry loops. Nothing is held across a pause.
+ */
+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();
+ 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.`;
+ throw error;
+ }
+ await delay(pause);
+ }
+ }
+ });
+}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index c59299e7fa..332eed8a20 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -3,13 +3,13 @@ import { WRITE_SWITCHES, writeSwitchOn } from './switches.ts';
import type { BrainEngine } from '../engine.ts';
import { getCode } from '../retry-matcher.ts';
import { assertRecoveryStagingAbsent } from './staging.ts';
-import { OperationError, opError } from '../ops/contract.ts';
+import { markNotAdmitted, OperationError, opError } from '../ops/contract.ts';
import { readFix } from '../ops/op-fix.ts';
import type { Action } from '../agent-output.ts';
import { digest, jsonBytes, requireUuid } from './digest.ts';
import { authorizeWrite } from './authority.ts';
import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentionDays } from './limits.ts';
-import { outstandingCapacityDetail, retryWriteAdmission } from './admission-retry.ts';
+import { outstandingCapacityDetail, retryWriteAdmission, waitOutRefreshFence } from './admission-retry.ts';
import { PreadmitBrainChanged } from './preadmit-cache.ts';
import { pipelined } from '../page-state/transactions.ts';
import { backgroundPaused, backgroundWorktreeInactive, declaredBackground, readBackgroundPauseShare, resolveAdmissionOrigin, type AdmissionOrigin } from './admission-origin.ts';
@@ -270,11 +270,12 @@ export async function admitWrite(engine: BrainEngine, input: WriteAdmission, ove
// #6355: a lent connection (the consumer's warm lane) whose session dropped is dead for every later attempt, so the
// re-run takes a transaction from the engine's pool after the pool itself is rebuilt.
let run = transaction;
- return retryWriteAdmission(requestId, remaining => run(async tx => {
+ // GST-1387: an interactive write waits out a refresh fence (bounded), re-running its whole admission.
+ return waitOutRefreshFence(resolveAdmissionOrigin(input.origin) === 'interactive', () => retryWriteAdmission(requestId, remaining => run(async tx => {
const brain = await declareDurablePersistence(tx, `${Math.min(100, remaining)}ms`, `${remaining}ms`);
if (input.brainId !== undefined && brain !== input.brainId) throw new PreadmitBrainChanged();
return apply(tx);
- }), undefined, async error => { run = fn => engine.transaction(fn, { pipelineFirst: isPersistenceDeclaration }); await engine.reconnect({ error }); });
+ }), undefined, async error => { run = fn => engine.transaction(fn, { pipelineFirst: isPersistenceDeclaration }); await engine.reconnect({ error }); }));
}
/** Caller owns the transaction and retries its entire unit of work after rollback. */
export async function admitWriteInTransaction(tx: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>): Promise<WriteRequest> {
@@ -624,7 +625,11 @@ async function assertWorktreeNotRefreshing(tx: BrainEngine, input: WriteAdmissio
`Source ${input.sourceId}'s checkout is being fast-forwarded by refresh ${refresh.id} (${refresh.state}); this write was not journaled.`,
`Retry the same request_id after retry_after_ms: 1000. Check progress with gbrain sources writer status ${input.sourceId}.`);
error.detail = 'retry_after_ms=1000';
- throw error;
+ error.retryable = true;
+ // GST-1387: nothing was recorded, so the same call is retried after the delay (actor provider renders next: wait).
+ error.fix = { argv: ['gbrain', 'sources', 'writer', 'status', '--source', input.sourceId, '--json'], consent: [], actor: 'provider', requires_exclusive: false,
+ why: `A refresh of source ${input.sourceId}'s checkout holds its writes until it finishes syncing; this write was not recorded. Repeat the same call with the same request_id after about 1 s (retry_after_ms=1000); this read-only command shows the refresh's progress.` };
+ throw markNotAdmitted(error);
}
/**
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index 1e9dd7c0b3..4f71fe650a 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -28,7 +28,8 @@ import { grantedWriteSource, writeGrantRefusal } from './write-grant.ts';
import { requestAttribution } from './attribution.ts';
import { isTerminal, type WriteRequest } from './model.ts';
import { prepareMemoryMutation } from './memory-prepare.ts';
-import { retryWriteAdmission } from './admission-retry.ts';
+import { retryWriteAdmission, waitOutRefreshFence } from './admission-retry.ts';
+import { resolveAdmissionOrigin } from './admission-origin.ts';
import { privateProvenanceFilterFragment, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';
import { markBeliefCommits } from '../belief/append.ts';
import { callerMember, memberFactAdmitSql, memberFactPage, memberPageIsOwn, memberPageNotOwned, memberPageSlug } from '../access/member-facts.ts';
@@ -350,7 +351,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
// are released before backoff. Admission must not retry a nested savepoint.
let withdrawn: WithdrawalCommit['pages'] = [];
const beliefReport = { appended: 0 };
- const done = await retryWriteAdmission(requestId, remaining => ctx.engine.transaction(async tx => {
+ const done = await waitOutRefreshFence(resolveAdmissionOrigin(ctx.admissionOrigin) === 'interactive', () => retryWriteAdmission(requestId, remaining => ctx.engine.transaction(async tx => {
withdrawn = [];
beliefReport.appended = 0;
await declareDurablePersistence(tx, `${Math.min(1000, remaining)}ms`, `${remaining}ms`);
@@ -396,7 +397,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
: { id, expired: true, path: 'legacy_db', reason: reason ?? 'forgotten' };
return completeWrite(tx, row, 'committed', { ...outcome, persistence: { mode: 'database' } });
}, requestAttribution(row));
- }), undefined, error => ctx.engine.reconnect({ error }));
+ }), undefined, error => ctx.engine.reconnect({ error })));
if (beliefReport.appended && done.state === 'committed') await markBeliefCommits(ctx.engine, [done.id]).catch(() => undefined);
// The commit removed the withdrawn pages' chunks. Rebuild them before
// acknowledging: a CLI process exits without a resident projection worker.
diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.ts
index 4681bf86b3..5fd1dee94e 100644
--- a/src/core/persistence/page-batch.ts
+++ b/src/core/persistence/page-batch.ts
@@ -16,7 +16,8 @@ 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 } from './admission-retry.ts';
+import { retryWriteAdmission, waitOutRefreshFence } from './admission-retry.ts';
+import { resolveAdmissionOrigin } from './admission-origin.ts';
import { declareDurablePersistence } from './protocol.ts';
import { digest } from './digest.ts';
import { queueLinksReconcile } from './effect-journal.ts';
@@ -186,7 +187,7 @@ export async function admitBatch(ctx: OperationContext, batchId: string, admissi
const key = digest([admission.operation, admission.authority]);
groups.set(key, [...(groups.get(key) ?? []), index]);
});
- return retryWriteAdmission(`batch ${batchId}`, remaining => ctx.engine.transaction(async tx => {
+ return waitOutRefreshFence(resolveAdmissionOrigin(admissions[0]?.origin) === 'interactive', () => retryWriteAdmission(`batch ${batchId}`, remaining => ctx.engine.transaction(async tx => {
await declareDurablePersistence(tx, `${Math.min(1000, remaining)}ms`, `${remaining}ms`);
const rows: WriteRequest[] = new Array(admissions.length);
for (const indexes of groups.values()) {
@@ -194,7 +195,7 @@ export async function admitBatch(ctx: OperationContext, batchId: string, admissi
indexes.forEach((index, position) => { rows[index] = admitted[position]!; });
}
return rows;
- }), BATCH_ADMISSION_BUDGET_MS, error => ctx.engine.reconnect({ error }));
+ }), BATCH_ADMISSION_BUDGET_MS, error => ctx.engine.reconnect({ error })));
}
async function prepareAll(caller: OperationContext, batchId: string, sourceId: string, pages: BatchPage[], repeats: Repeats) {
diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.ts
index a6d5a459bf..d04911da7c 100644
--- a/src/core/persistence/verb-errors.ts
+++ b/src/core/persistence/verb-errors.ts
@@ -1,4 +1,4 @@
-import { verbError, opError, OperationError } from '../ops/contract.ts';
+import { markNotAdmitted, verbError, opError, OperationError } from '../ops/contract.ts';
import type { Action } from '../agent-output.ts';
import { isTerminalWriteState, isWriteErrorCode, type WriteErrorCode, type WriteReceipt } from './types.ts';
import { pendingWriteHint } from './health.ts';
@@ -285,6 +285,13 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {
Object.assign(segmented, { canonical: 'page_body_segmented', writeError: 'page_body_segmented', fix: error.fix ?? segmentedRememberFix() });
throw segmented;
}
+ // GST-1387: a refresh fence is a retryable wait, not an outage: the frozen code stays unavailable, and the canonical code,
+ // its retry_after_ms detail and its wait fix ride along so the caller retries the same request_id.
+ if (error.code === 'worktree_refreshing') {
+ const fenced = verbError('unavailable', error.message, error.suggestion ?? 'Retry the same request_id after retry_after_ms.', error.detail);
+ Object.assign(fenced, { canonical: 'worktree_refreshing', docs: error.docs, fix: error.fix, retryable: true });
+ throw markNotAdmitted(fenced);
+ }
const code = ['permission_denied','scope_denied','source_changed','writer_registration_required'].includes(error.code)
? 'scope_denied' : ['revision_required','revision_conflict','idempotency_conflict','invalid_params','page_identity_changed'].includes(error.code)
? 'invalid_params' : 'unavailable';
diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.ts
index f539e20b3c..84d68e4aed 100644
--- a/src/core/remember-batch.ts
+++ b/src/core/remember-batch.ts
@@ -23,6 +23,7 @@ import { createHash, randomUUID } from 'node:crypto';
import type { OperationContext } from './operations.ts';
import { OperationError } from './ops/contract.ts';
import { clientRequestIdOf, parseWriteRequestId } from './persistence/preconditions.ts';
+import { withRefreshFenceBudget } from './persistence/admission-retry.ts';
export const REMEMBER_BATCH_MAX = 20;
const ITEM_KEYS = new Set(['fact', 'provenance', 'entity', 'infer_entity', 'kind', 'ttl', 'visibility', 'content_origin', 'valid_from', 'replaces']);
@@ -88,7 +89,9 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,
const clientRequestId = clientRequestIdOf(rootId);
const results: BatchItemResult[] = [];
const hints = new Set<string>();
- for (const [index, item] of normalized.entries()) {
+ const failures: Array<{ index: number; error: OperationError }> = [];
+ // GST-1387: the items share one refresh-fence wait, so a fenced checkout delays the batch once, not once per item.
+ await withRefreshFenceBudget(async () => { for (const [index, item] of normalized.entries()) {
const child = childRequestId(rootId, index);
try {
const out = await single(ctx, { ...item, request_id: child }) as Record<string, unknown>;
@@ -111,12 +114,21 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,
...(e.writeRequest.target ? { target: e.writeRequest.target } : {}) });
continue;
}
+ failures.push({ index, error: e });
results.push({ index, request_id: child, status: 'failed', error: { code: e.code, message: e.message, ...(e.detail ? { detail: e.detail } : {}), ...(e.suggestion ? { suggestion: e.suggestion } : {}), ...(e.withdrawn ? { withdrawn: e.withdrawn } : {}) } });
}
- }
+ } });
const failed = results.filter(r => r.status === 'failed').length;
const pending = results.filter(r => r.status === 'pending').length;
+ // GST-1387: a batch that saved nothing is a refusal on every surface (CLI exit non-zero, MCP isError), never a success
+ // envelope; its first item's error keeps that item's code and fix.
+ if (failures.length && failed === results.length) {
+ const [{ index, error }] = failures as [{ index: number; error: OperationError }];
+ error.message = `items[${index}]: ${error.message} None of the ${results.length} item(s) was saved.`;
+ throw error;
+ }
return {
+ ...(failed > 0 ? { status: 'error', error: `${failed} of ${results.length} item(s) failed; see items[].error.` } : {}),
protocol_version: 1,
request_id: requestId,
...(clientRequestId ? { client_request_id: clientRequestId } : {}),
diff --git a/test/remember-batch.test.ts b/test/remember-batch.test.ts
index 7a2905d388..3700a45df4 100644
--- a/test/remember-batch.test.ts
+++ b/test/remember-batch.test.ts
@@ -102,6 +102,18 @@ describe('remember items[] batch', () => {
expect(out.partial).toBe(true);
expect(out.items[1].status).toBe('failed');
expect(out.next).toContain('new request_id');
+ // #8621: a partial failure is an in-band error (the CLI exits 1), not a clean success.
+ expect(out).toMatchObject({ status: 'error', saved: 1, failed: 1 });
+ });
+
+ 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;
+ try { await runRememberBatch(ctx, { provenance: 'p', items: [{ fact: 'a' }, { fact: 'b' }] }, handler, ve); } catch (e) { err = e; }
+ expect(err).toBeInstanceOf(OperationError);
+ expect((err as OperationError).code).toBe('internal_error');
+ expect((err as Error).message).toBe('items[0]: boom None of the 2 item(s) was saved.');
+ expect(writes).toHaveLength(0);
});
test('rejects empty, oversized, unknown-field and fact+items calls', async () => {
diff --git a/test/remember-withdrawn-claim.test.ts b/test/remember-withdrawn-claim.test.ts
index af175d555b..a485998eb9 100644
--- a/test/remember-withdrawn-claim.test.ts
+++ b/test/remember-withdrawn-claim.test.ts
@@ -68,8 +68,9 @@ describe('remember after forget of the same claim', () => {
expect(await requestCount()).toBe(before);
const batch = await call('remember', { items: [{ fact: CLAIM, entity: 'crm/acme-example', provenance: 'team update' }] });
- expect(batch.body.failed).toBe(1);
- expect(batch.body.items[0].error).toMatchObject({ code: 'invalid_params', message: FACT_WITHDRAWN_MESSAGE, suggestion: FACT_WITHDRAWN_SUGGESTION });
+ // #8621: a batch that saved nothing is refused with its item's error, never a success envelope.
+ expect(batch.isError).toBe(true);
+ expect(batch.body).toMatchObject({ code: 'invalid_params', message: `items[0]: ${FACT_WITHDRAWN_MESSAGE} None of the 1 item(s) was saved.`, suggestion: FACT_WITHDRAWN_SUGGESTION });
});
test('a withdrawal that lands after admission fails the receipt with fact_withdrawn, readable through get_write_request', async () => {
diff --git a/test/write-refusal-refresh-fence-8621.test.ts b/test/write-refusal-refresh-fence-8621.test.ts
new file mode 100644
index 0000000000..2a2bdcb6d0
--- /dev/null
+++ b/test/write-refusal-refresh-fence-8621.test.ts
@@ -0,0 +1,180 @@
+/**
+ * #8621: a write refused by a refresh fence (`worktree_refreshing`) was reported as success or as an outage.
+ *
+ * Protects: `remember` with `items` whose every item a refresh fence refused is an error on every surface (MCP isError,
+ * CLI exit 1), never a success envelope; the refusal is a registered retryable code whose fix renders `next: wait` with
+ * `retry_after_ms`, through the memory verbs too (frozen `unavailable`, canonical `worktree_refreshing`); an interactive
+ * write waits out a short fence (bounded) and commits, past the cap it is refused and nothing is journaled; background
+ * writes are not delayed; a database-only (repo-less) source is never fenced.
+ * Regression it catches: master returned `{failed: 1}` with isError false and exit 0 (`undefined (fact #undefined)`),
+ * rendered the refusal as class server with `fix: gbrain doctor`, and refused every write at once.
+ * Seams: the real refresh state machine paused at its drained boundary (`hooks.boundary`); the wait cap test seam.
+ */
+import { afterAll, afterEach, beforeAll, expect, test } from 'bun:test';
+import { spawnSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { createEngine } from '../src/core/engine-factory.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { dispatchToolCall } from '../src/mcp/dispatch.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { refreshWorktree } from '../src/core/persistence/worktree-refresh.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { _setRefreshFenceWaitForTests } from '../src/core/persistence/admission-retry.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { page, setupRefreshFixture, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';
+
+const backends = testBackends();
+const engines: BrainEngine[] = [];
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({}); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); if (engine.kind === 'pglite') await engine.disconnect(); }
+ await closePostgres?.();
+});
+afterEach(() => _setRefreshFenceWaitForTests(null));
+
+const each = async (fn: (f: RefreshFixture) => Promise<void>) => { for (const engine of engines) await withRefreshFixture(engine, fn); };
+const PERSON = '---\ntitle: Alice Example\ntype: person\n---\nAlice is a person.\n';
+
+/** An entity page on the managed source, committed and synced through a completed refresh. */
+async function withEntity(f: RefreshFixture): Promise<void> {
+ f.push('alpha/people/alice-example.md', PERSON);
+ expect((await refreshWorktree(f.engine, f.alpha)).status).toBe('completed');
+}
+
+/** Runs `fn` while a real refresh of the checkout is paused at its drained boundary; `release` lets it finish. */
+async function duringRefresh(f: RefreshFixture, fn: (release: () => void) => Promise<void>) {
+ f.push('alpha/two.md', page('Alpha two', 'An upstream observation.'));
+ let release!: () => void; const gate = new Promise<void>(resolve => { release = resolve; });
+ let reached!: () => void; const drained = new Promise<void>(resolve => { reached = resolve; });
+ const refresh = refreshWorktree(f.engine, f.alpha, { hooks: { boundary: async point => { if (point === 'drained') { reached(); await gate; } } } });
+ await drained;
+ try { await fn(release); } catch (error) { release(); await refresh.catch(() => undefined); throw error; }
+ release();
+ return refresh;
+}
+
+async function call(f: RefreshFixture, name: string, params: Record<string, unknown>, sourceId = f.alpha) {
+ const result = await dispatchToolCall(f.engine, name, params, { remote: true, transport: 'stdio', sourceId, admissionOrigin: 'interactive' });
+ return { isError: result.isError === true, body: JSON.parse(result.content[0]!.text) as Record<string, any> };
+}
+
+test('remember items: a batch the fence refused entirely is an MCP error with a wait fix, not a success envelope', () => each(async f => {
+ await withEntity(f);
+ _setRefreshFenceWaitForTests(0);
+ const result = await duringRefresh(f, async () => {
+ const before = await f.requestCount();
+ const out = await call(f, 'remember', { items: [{ fact: 'alice-example likes tea', entity: 'people/alice-example', provenance: 'test' }] });
+ expect(out.isError).toBe(true);
+ expect(out.body).toMatchObject({ error: 'unavailable', code: 'worktree_refreshing', retryable: true, detail: 'retry_after_ms=1000' });
+ expect(out.body.message).toContain('items[0]');
+ expect(out.body.message).toContain('None of the 1 item(s) was saved');
+ expect(out.body.fix.next).toBe('wait');
+ expect(await f.requestCount()).toBe(before);
+ });
+ expect((await result).status).toBe('completed');
+}), 120_000);
+
+test('remember (single) refused by the fence keeps the frozen unavailable code and carries the canonical wait', () => each(async f => {
+ await withEntity(f);
+ _setRefreshFenceWaitForTests(0);
+ await (await duringRefresh(f, async () => {
+ const out = await call(f, 'remember', { fact: 'alice-example likes jazz', entity: 'people/alice-example', provenance: 'test' });
+ expect(out.isError).toBe(true);
+ expect(out.body).toMatchObject({ error: 'unavailable', code: 'worktree_refreshing', class: 'retryable', retryable: true });
+ expect(out.body.fix).toMatchObject({ next: 'wait', argv: ['gbrain', 'sources', 'writer', 'status', '--source', f.alpha, '--json', '--brain', 'host'] });
+ }));
+}), 120_000);
+
+test('put_page past the wait cap is refused retryable with fix.next wait and retry_after_ms, and nothing is journaled', () => each(async f => {
+ _setRefreshFenceWaitForTests(400);
+ await (await duringRefresh(f, async () => {
+ const before = await f.requestCount();
+ const started = performance.now();
+ const out = await call(f, 'put_page', { slug: 'notes/capped', content: page('Capped', 'refused after the cap') });
+ expect(performance.now() - started).toBeGreaterThanOrEqual(250);
+ expect(out.isError).toBe(true);
+ expect(out.body).toMatchObject({ error: 'worktree_refreshing', code: 'worktree_refreshing', class: 'retryable', retryable: true, detail: 'retry_after_ms=1000' });
+ expect(out.body.fix.next).toBe('wait');
+ expect(out.body.message).toContain('waited');
+ expect(await f.requestCount()).toBe(before);
+ }));
+}), 120_000);
+
+test('an interactive write waits out a short refresh fence and commits once the refresh finishes', () => each(async f => {
+ let write: Promise<Record<string, unknown>> | undefined;
+ const refresh = await duringRefresh(f, async release => {
+ write = submitPageMutation({ ...f.ctx(f.alpha), admissionOrigin: 'interactive' },
+ { operation: 'put_page', params: { slug: 'notes/waited', content: page('Waited', 'written after the refresh') } });
+ await new Promise(resolve => setTimeout(resolve, 700));
+ release();
+ });
+ expect((await refresh).status).toBe('completed');
+ const written = await write!;
+ expect((written.write_request as { state?: string } | undefined)?.state ?? written.state).toBe('committed');
+ const [row] = await f.engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [f.alpha, 'notes/waited']);
+ expect(Number(row!.n)).toBe(1);
+}), 120_000);
+
+test('a background write is refused at once (its producer retries), and a database-only source is never fenced', () => each(async f => {
+ await (await duringRefresh(f, async () => {
+ const started = performance.now();
+ const error = await f.put(f.alpha, 'notes/background', page('Background', 'refused')).then(() => null, e => e as { code?: string });
+ expect(error?.code).toBe('worktree_refreshing');
+ expect(performance.now() - started).toBeLessThan(2000);
+ const repoLess = await call(f, 'put_page', { slug: 'notes/repo-less', content: page('Repo-less', 'database only') }, 'default');
+ expect(repoLess.isError).toBe(false);
+ }));
+}), 120_000);
+
+test('CLI: remember --items whose every item the fence refused exits 1; a refused put exits 1 with next wait', async () => {
+ if (!backends.includes('pglite')) return;
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-8621-'));
+ const home = join(dir, 'home');
+ try {
+ mkdirSync(join(home, '.gbrain'), { recursive: true });
+ const cfg = { engine: 'pglite' as const, database_path: join(home, '.gbrain', 'brain.pglite') };
+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify(cfg));
+ const alpha = await withEnv({ GBRAIN_HOME: home }, async () => {
+ const engine = await createEngine(cfg);
+ await engine.connect(cfg); await engine.initSchema();
+ try {
+ const f = await setupRefreshFixture(engine, dir);
+ await withEntity(f);
+ // A refresh left in syncing short of its target fences the checkout for the child processes below.
+ const target = f.push('alpha/two.md', page('Alpha two', 'upstream'));
+ const [w] = await engine.executeRaw<{ e: string }>('SELECT owner_epoch::text AS e FROM persistence_worktrees WHERE id=$1::uuid', [f.worktreeId]);
+ const [b] = await engine.executeRaw<{ g: string }>('SELECT topology_generation::text AS g FROM persistence_source_bindings WHERE source_id=$1', [f.alpha]);
+ await engine.executeRaw(`INSERT INTO persistence_worktree_refreshes (worktree_id,source_ids,principal_id,owner_epoch,topology_generation,state,old_head,target_head,upstream_ref)
+ VALUES($1::uuid,$2::text[],gen_random_uuid(),$3,$4,'syncing',$5,$6,'origin/main')`, [f.worktreeId, [f.alpha, f.beta], w!.e, b!.g, f.head(), target]);
+ return f.alpha;
+ } finally { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ });
+ const run = (args: string[], input?: string) => spawnSync('bun', ['run', 'src/cli.ts', ...args], { cwd: process.cwd(), encoding: 'utf8', input, timeout: 120_000,
+ env: { ...process.env, GBRAIN_HOME: home, DATABASE_URL: '', GBRAIN_DATABASE_URL: '', GBRAIN_SKIP_STARTUP_HOOKS: '1' } });
+ const batch = run(['remember', '--items', JSON.stringify([{ fact: 'alice-example likes tea', entity: 'people/alice-example', provenance: 'test' }]), '--source-id', alpha]);
+ expect(batch.status).toBe(1);
+ expect(batch.stderr).toContain('worktree_refreshing');
+ expect(batch.stdout).not.toContain('undefined');
+ const put = run(['put', 'notes/refused', '--source-id', alpha, '--json'], page('Refused', 'body'));
+ expect(put.status).toBe(1);
+ const env = JSON.parse(put.stdout);
+ expect(env).toMatchObject({ code: 'worktree_refreshing', class: 'retryable', retryable: true });
+ expect(env.fix.next).toBe('wait');
+ } finally { rmSync(dir, { recursive: true, force: true }); }
+}, 240_000);