Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
Retry hints name the id each write tool replays by; attested QM forget keeps not_found
garrytan6b09edaf1c0f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e77b2a5a95..a5ce24cdf8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,11 +12,11 @@ identifiers and attribution are available in the pre-removal Git revision## [Unreleased]-**A team member's `forget` now says who can withdraw a fact, instead of answering that the fact does not exist.** A remote credential bound to a member, the brain owner's included, withdraws only the facts on its own member page. When it tried to forget a fact it can read but that lives elsewhere (one it saved with `share: true`, or a teammate's shared fact), it got `not_found`, so its agent believed the fact was gone while every reader still recalled it. It is now refused with a reply saying the brain host withdraws it with `gbrain forget <id>`, and the fact stays. A fact the caller cannot read still answers `not_found`, so the reply never confirms a hidden fact exists. The docs that said `remember` defaults to `world` now say that a member-bound credential saves privately on its member page unless it passes `share: true`. Reported by @andreineacsu (#9101).+**A team member's `forget` now says who can withdraw a fact, instead of answering that the fact does not exist.** A remote credential bound to a member, the brain owner's included, withdraws only the facts on its own member page. When it tried to forget a fact it can read but that lives elsewhere (one it saved with `share: true`, or a teammate's shared fact), it got `not_found`, so its agent believed the fact was gone while every reader still recalled it. It is now refused with a reply saying the brain host withdraws it with `gbrain forget <id>`, and the fact stays. A fact the caller cannot read still answers `not_found`, so the reply never confirms a hidden fact exists. An attested QM call (`x-qm-actor`) is unchanged and still answers `not_found` for any fact off the person's page, as QM's published contract says. The docs that said `remember` defaults to `world` now say that a member-bound credential saves privately on its member page unless it passes `share: true`. Reported by @andreineacsu (#9101).**An agent that passes `source` to `remember` is now pointed at `provenance`.** The `remember` description said "provenance (required: source)", and agents read that as a parameter named `source`. The call was refused, and since v0.60.635.0 the refusal suggested `source_id`, the write source, which is not what the agent meant. In the nightly write evals, that one refusal caused every failed refresh-barrier episode on master. The description now says "provenance (required)", and an unknown `source` on `remember` suggests `provenance`.-**A write that a refresh holds back now says which request_id to retry with.** While `gbrain sources refresh` is updating a checkout, a write to it is refused as `worktree_refreshing`, and the refusal said "Retry the same request_id". A write sent without a `request_id` had no id to reuse, so an agent's retry went out as a new request. The refusal now names the request_id it was refused under, a new one when the call sent none, and over MCP its `fix.mcp` is the exact call to repeat with that id after `retry_after_ms`. Nothing is recorded for the refused call, as before. The retry commits under that id, and reusing the id later for a different write is refused (`idempotency_conflict`) like any reused id. A database-only (repo-less) source is never held back.+**A write that a refresh holds back now says which request_id to retry with.** While `gbrain sources refresh` is updating a checkout, a write to it is refused as `worktree_refreshing`, and the refusal said "Retry the same request_id". A write sent without a `request_id` had no id to reuse, so an agent's retry went out as a new request. The refusal now names the request_id it was refused under, a new one when the call sent none, and over MCP its `fix.mcp` is the exact call to repeat with that id after `retry_after_ms`. A refused batch (`put_pages`, or `remember` with `items`) names the batch's own request_id, and `memory_write`, which replays by its `idempotency_key`, is told that key instead. Nothing is recorded for the refused call, as before. The retry commits under that id, and reusing the id later for a different write is refused (`idempotency_conflict`) like any reused id. A database-only (repo-less) source is never held back.**GPT-6.1 Sol's recorded-time page reads and typed graph chains now get answers instead of refusals, and two regressions that shipped without a test now have one.** Sol fills in every optional argument of a tool call. A `get_page` with `known_as_of` (the page as the brain had recorded it at an instant) arrived beside `include_content: true`, `include_timeline_entries: true`, a one-line `lines` window, `view: "read"` and the rest, and gbrain refused the whole call because a recorded-time read does not serve those arguments. A `traverse_graph` with `hops` arrived beside `depth`, `link_type` and `direction`, and was refused the same way. Sol does not follow the refusal's fix, so in a replay of its recorded calls 178 of 651 `get_page` and `traverse_graph` calls failed on arguments alone. Both calls now run: a recorded-time read returns the whole page as recorded, a chain walks its hops, and the response's `set_aside` names each argument that was ignored and why. `body: outline` or `window` with `known_as_of` still refuses, because that names a read mode the ledger cannot serve.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex d1d4950f93..b3d7820576 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -1515,8 +1515,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;{ since: '0.60.655.0', id: 'memory_propose_held_writes_gst1158', text: 'New attested operation `memory_propose` (add it to `--attest-ops`): QM proposes one timeline entry or link on a shared page for the person it serves, and nothing is written until the brain owner runs `gbrain memory-proposals approve <request_id>` (`list`, `show`, `deny --reason`). `get_write_request` and `cancel_write_request` read and withdraw the proposal; an approved one becomes an ordinary write under the same request id. Held text stays in the `memory_proposals` table, out of git, export, search and recall. Proposals expire after `proposals.ttl_hours` (168), at most 10 wait per person and 50 per credential, and closed ones are deleted after `proposals.retention_days` (30). `gbrain doctor` (`memory_proposals_pending`) and `gbrain status` show the queue.' },{ since: '0.60.655.0', id: 'member_email_link_gst1158', text: 'A member can carry an operator-declared email: `gbrain access member add <id> --email <addr>` or `gbrain access member set <id> --email <addr>|none`, shown by `member list`, stored lower-case and unique per brain, and cleared when the member is removed. `gbrain access member link --email <addr> --qm <id>` (and `gbrain mcp admin link --email`, `member-add --email`, `member-set` over the owner session) links the one member that declares it, exactly as linking by member id does; an unknown email is `not_found` and creates nothing. No OAuth token, attested call or MCP tool can set an email or make a link.' },{ since: '0.60.655.0', id: 'qm_admin_http_gst1094', text: 'The brain owner can now manage the attest right, members and canonical-id links over the running server: `gbrain mcp admin attest <client> --attest-actor qm|none [--attest-ops <list>]`, `member-add`, `member-disable`, `member-enable`, `members`, `link <member> --qm <id>`, `unlink --qm <id>` and `links`, backed by `/admin/api/access/attest`, `/admin/api/access/members` and `/admin/api/access/member-links`. These routes take the owner session only (never an OAuth token or an MCP tool), refuse what the local `gbrain auth rescope` and `gbrain access member` commands refuse, preview with `--dry-run` where those do, and log each applied change as `access_admin`. Removing a member stays a brain-host command.' },- { since: 'TBD', id: 'member_forget_names_host_9101', text: 'A remote credential bound to a member, the brain owner\'s included, that runs `forget` or `forget_fact` on a fact it can read but that is not on its own member page (a fact it saved with `share: true`, or a teammate\'s shared fact) is now refused with a reply saying the brain host withdraws it with `gbrain forget <id>` (`scope_denied` from `forget`, `permission_denied` from `forget_fact`). It used to answer `not_found` (`fact_not_found`), as if the fact it had just saved did not exist. A fact the caller cannot read still answers `not_found`, and nothing is withdrawn either way.' },- { since: 'TBD', id: 'refresh_fence_retry_id_gst2353', text: 'A write refused `worktree_refreshing` (a `gbrain sources refresh` is updating its checkout) now names the request_id to retry with in its message, a new one when the call sent none, and over MCP its `fix.mcp` is the same call with that `request_id` (`next: wait` after `retry_after_ms`). The message used to say "Retry the same request_id" even when the call had none. Nothing is recorded for the refused call; the retry commits under that id, and a later write reusing it with different content is refused `idempotency_conflict`.' },+ { since: 'TBD', id: 'member_forget_names_host_9101', text: 'A remote credential bound to a member, the brain owner\'s included, that runs `forget` or `forget_fact` on a fact it can read but that is not on its own member page (a fact it saved with `share: true`, or a teammate\'s shared fact) is now refused with a reply saying the brain host withdraws it with `gbrain forget <id>` (`scope_denied` from `forget`, `permission_denied` from `forget_fact`). It used to answer `not_found` (`fact_not_found`), as if the fact it had just saved did not exist. A fact the caller cannot read still answers `not_found`, and nothing is withdrawn either way. An attested QM call (`x-qm-actor`) is unchanged: any fact off the person\'s page answers `not_found`, as QM contract v3 states.' },+ { since: 'TBD', id: 'refresh_fence_retry_id_gst2353', text: 'A write refused `worktree_refreshing` (a `gbrain sources refresh` is updating its checkout) now names the request_id to retry with in its message, a new one when the call sent none, and over MCP its `fix.mcp` is the same call with that `request_id` (`next: wait` after `retry_after_ms`). A batch (`put_pages`, `remember` with `items`) names the batch\'s own request_id; `memory_write`, which takes no request_id, names its `idempotency_key` and its `fix.mcp` is the same call. The message used to say "Retry the same request_id" even when the call had none. Nothing is recorded for the refused call; the retry commits under that id, and a later write reusing it with different content is refused `idempotency_conflict`.' },{ since: 'TBD', id: 'recorded_read_view_args_gst2214', text: 'get_page with known_as_of beside arguments that shape a current read (lines, bytes, around_chunk_id, cursor, section, grep, context, include_content, include_timeline_entries, view, max_bytes and the like) now reads the whole page as recorded instead of refusing with invalid_params; the response\'s set_aside names what was ignored. body outline or window, or include_quarantined true, with known_as_of still refuses. traverse_graph with hops likewise walks the chain and sets depth, link_type and direction aside instead of refusing.' },];diff --git a/src/core/ops/qm-memory.ts b/src/core/ops/qm-memory.tsindex eab60a87f5..491eb9c215 100644--- a/src/core/ops/qm-memory.ts+++ b/src/core/ops/qm-memory.ts@@ -313,6 +313,14 @@ const memory_write: Operation = {saved.push({ request_id: item.request_id, ...(out?.id !== undefined ? { fact_id: String(out.id) } : {}) });} catch (e) {if (e instanceof OperationError && e.writeError === 'write_pending') { saved.push({ request_id: item.request_id, pending: true }); continue; }+ // memory_write takes no request_id: a retryable refusal names the idempotency_key that replays this write.+ if (e instanceof OperationError && e.requestId === item.request_id) {+ const theirs = `request_id ${item.request_id}`, own = `idempotency_key ${key}`;+ e.message = e.message.replaceAll(theirs, () => own);+ e.suggestion = e.suggestion?.replaceAll(theirs, () => own);+ if (e.fix) e.fix = { ...e.fix, why: e.fix.why.replaceAll(theirs, () => own) };+ e.requestId = undefined;+ }if (e instanceof OperationError && index > 0) e.message = `facts[${index}]: ${e.message} The ${index} fact(s) before it were saved; the same idempotency_key replays them.`;throw e;}diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex ce09bf57ed..910df2bec1 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -25,7 +25,7 @@ import type { WriteRequest } from './model.ts';import { prepareMemoryMutation } from './memory-prepare.ts';import { readForgetTarget, refuseForgetReachingOtherCopies } from './forget-prepare.ts';import { UNATTRIBUTED_MEMORY_SLUG } from '../facts/extract-from-fence.ts';-import { callerIsOwner, privateProvenanceFilterUnderPolicy, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';+import { callerIsOwner, currentCallerAccess, privateProvenanceFilterUnderPolicy, resolveExcludePrivatePages, withFolderRestricted } from '../search/private-visibility.ts';import { projectionEligibleSql } from '../eligibility/sql.ts';import { resolveReadEligibility } from '../eligibility/policy.ts';import { callerMember, factVisibilitySql, memberFactAdmitSql, memberFactPage, memberPageIsOwn, memberPageNotOwned, memberPageSlug, scopePageIsShared, scopePageNotShared, SCOPE_PAGE_SLUG } from '../access/member-facts.ts';@@ -329,6 +329,8 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foconst ownPage = member ? memberPageSlug(member) : null;if (ownPage && !(await ctx.engine.executeRaw(`SELECT 1 FROM facts WHERE id=$1 AND source_id=$2 AND ${memberFactAdmitSql('facts')}`, [id, sourceId])).length) {// #9101: a fact the caller reads (one it shared, or a teammate's shared fact) is refused by name; a fact it cannot read stays not_found.+ // An attested QM actor keeps not_found for every fact off its page, as QM memory-provider contract v3 states.+ if (currentCallerAccess().actor) throw missing();const readable = callerIsOwner() ? 'TRUE' : factVisibilitySql('facts', ['world']);const eligible = projectionEligibleSql('facts', 'facts', await resolveReadEligibility(ctx));const reads = (await ctx.engine.executeRaw(`SELECT 1 FROM facts WHERE id=$1 AND source_id=$2 AND ${readable} AND ${eligible}${excludePrivate ? ` AND ${privateProvenanceFilterUnderPolicy('facts')}` : ''}`, [id, sourceId])).length > 0;diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.tsindex d180104a75..3ae5a15b89 100644--- a/src/core/persistence/page-batch.ts+++ b/src/core/persistence/page-batch.ts@@ -307,9 +307,9 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<stri}if (error instanceof OperationError && error.code === 'worktree_refreshing' && error.requestId) {const child = error.requestId, own = String(params.request_id);- error.message = error.message.replaceAll(child, own);- error.suggestion = error.suggestion?.replaceAll(child, own);- if (error.fix) error.fix = { ...error.fix, why: error.fix.why.replaceAll(child, own) };+ error.message = error.message.replaceAll(child, () => own);+ error.suggestion = error.suggestion?.replaceAll(child, () => own);+ if (error.fix) error.fix = { ...error.fix, why: error.fix.why.replaceAll(child, () => own) };error.requestId = own;}throw error;diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.tsindex ac5ea2fdd4..35356c9f53 100644--- a/src/core/remember-batch.ts+++ b/src/core/remember-batch.ts@@ -134,6 +134,15 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,// unknown) keeps the per-item envelope so its child request_id is never lost.if (failures.length && failed === results.length && failures.every(f => !f.error.writeRequest && f.error.writeError !== 'write_outcome_unknown')) {const [{ index, error }] = failures as [{ index: number; error: OperationError }];+ // A fence refusal names the batch's request_id, never an item's derived id: a retry under an item's id derives new+ // item ids, so retrying it and the batch's own id would save every item twice.+ if (error.requestId === childRequestId(rootId, index)) {+ const child = error.requestId;+ error.message = error.message.replaceAll(child, () => rootId);+ error.suggestion = error.suggestion?.replaceAll(child, () => rootId);+ if (error.fix) error.fix = { ...error.fix, why: error.fix.why.replaceAll(child, () => rootId) };+ error.requestId = rootId;+ }error.message = `items[${index}]: ${error.message} None of the ${results.length} item(s) was saved.`;throw error;}diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 72a40ef7e3..f307a3d97b 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -11,7 +11,7 @@ import { affectsRecall } from '../core/types.ts';import type { BrainEngine } from '../core/engine.ts';import { operations, OperationError, enforceBoundClientOpAllowList, opError } from '../core/operations.ts';import type { OperationContext, AuthInfo } from '../core/operations.ts';-import type { OperationMeta } from '../core/ops/contract.ts';+import type { Operation, OperationMeta } from '../core/ops/contract.ts';import { loadConfig } from '../core/config.ts';import { withRequestConfigSnapshot, withoutRequestConfigSnapshot } from '../core/config-snapshot.ts';import { withCallerAccess } from '../core/search/private-visibility.ts';@@ -743,6 +743,17 @@ async function hiddenContentNotices(engine: BrainEngine, name: string, result: u}}+/**+ * GST-2353: a refusal safe to retry carries the call to repeat (next: wait) in the id parameter the tool takes: its+ * request_id with the id it was refused under, or the same arguments when the tool replays by its idempotency_key.+ */+function attachRetryCall(op: Pick<Operation, 'mutating' | 'params'>, name: string, params: Record<string, unknown>, e: unknown): void {+ if (!op.mutating || !(e instanceof OperationError) || e.retryable !== true || !e.fix || e.fix.mcp) return;+ const retry = op.params.request_id ? (e.requestId ? { ...params, request_id: e.requestId } : null)+ : op.params.idempotency_key && typeof params.idempotency_key === 'string' ? params : null;+ if (retry) e.fix = { ...e.fix, mcp: { tool: name, arguments: retry } };+}+/** A refusal a grant explains: a missing scope or an operation outside the grant's snapshot or fence. */function refusedByGrant(e: unknown): boolean {return e instanceof OperationError && (e.code === 'insufficient_scope' || e.code === 'permission_denied');@@ -1385,10 +1396,7 @@ async function dispatchResolvedCall(// never tells a mutating op with an unknown outcome to retry.notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));notices.push(...await grantBlockedNotices(engine, opts, refusedByGrant(e)));- // GST-2353: a refusal safe to retry under its request id carries the call to repeat, that id included (next: wait).- if (op.mutating && e instanceof OperationError && e.retryable === true && e.requestId && e.fix && !e.fix.mcp) {- e.fix = { ...e.fix, mcp: { tool: name, arguments: { ...safeParams, request_id: e.requestId } } };- }+ attachRetryCall(op, name, safeParams, e);return deferredWriteResult(e, notices, opts) ?? errorResult(e, opts, { op: name, mutating: op.mutating === true, idempotent: op.idempotent === true, notices: admitNotices(notices, opts) });}}diff --git a/test/qm-memory-tools.test.ts b/test/qm-memory-tools.test.tsindex ef8266998f..3c3b72bf47 100644--- a/test/qm-memory-tools.test.ts+++ b/test/qm-memory-tools.test.ts@@ -694,7 +694,7 @@ for (const kind of testBackends()) {}}, 60_000);- test('attested and member-bound forget judge ownership first: a fact off the caller\'s own member page is not_found and files no owner proposal', async () => {+ test('attested and member-bound forget judge ownership first: a fact off the caller\'s own member page is not_found to the attested person, refused by name to a member credential that reads it (#9101), and files no owner proposal', async () => {await engine.insertFact({ fact: 'Acme harbor charter is confirmed canaryconfirmed', kind: 'fact', entity_slug: ACME, source: 'test', visibility: 'world' }, { source_id: SRC });const [confirmed] = await factRows('canaryconfirmed');await engine.transaction(tx => withTrustPromotion(tx, 'user_confirmed', () => tx.executeRaw("UPDATE facts SET trust_tier = 'user_confirmed' WHERE id = $1", [confirmed!.id])));@@ -708,7 +708,8 @@ for (const kind of testBackends()) {for (const as of [alice, { token: 'bob' }] as Who[]) {for (const [op, id] of [['forget', String(confirmed!.id)], ['forget_fact', Number(confirmed!.id)]] as const) {const out = await call(as, op, { id });- expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code: op === 'forget' ? 'not_found' : 'fact_not_found' });+ const code = as === alice ? (op === 'forget' ? 'not_found' : 'fact_not_found') : (op === 'forget' ? 'scope_denied' : 'permission_denied');+ expect({ isError: out.isError, code: out.json.code }).toEqual({ isError: true, code });}}expect(await proposals()).toBe(start);diff --git a/test/refresh-fence-retry-id-gst2353.test.ts b/test/refresh-fence-retry-id-gst2353.test.tsindex 0202ffba67..ee53a6dab5 100644--- a/test/refresh-fence-retry-id-gst2353.test.ts+++ b/test/refresh-fence-retry-id-gst2353.test.ts@@ -7,7 +7,9 @@* (the call to repeat, next: wait), and its message names that id instead of an id* the caller never had; nothing is journaled for the refused call; the retry with fix.mcp's arguments commits under that* id; a later call with that id and a changed payload is refused idempotency_conflict like any reused id; a caller's own- * request_id is the one echoed; a database-only (repo-less) source is never fenced.+ * request_id is the one echoed; a refused put_pages or remember items[] batch names the batch's own request_id (never an+ * item's derived id, so a retry writes each item once), verbatim even with $& or $' in it; memory_write, which takes no+ * request_id, is told its idempotency_key and its fix.mcp is accepted; a database-only (repo-less) source is never fenced.* Regression it catches: master answered "Retry the same request_id in about 2 s." with no id anywhere in the refusal.* Seams: the real refresh state machine paused at its drained boundary (worktree-refresh-fixture), MCP dispatch as a remote* stdio caller, PGLite and Postgres.@@ -21,6 +23,10 @@ import { refreshWorktree } from '../src/core/persistence/worktree-refresh.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 { GBrainOAuthProvider } from '../src/core/oauth-provider.ts';+import { sqlQueryForEngine } from '../src/core/sql-query.ts';+import { addMember, bindCredential } from '../src/core/access/members.ts';+import { linkMember } from '../src/core/access/actor.ts';import { page, withRefreshFixture, type RefreshFixture } from './helpers/worktree-refresh-fixture.ts';const backends = testBackends();@@ -131,6 +137,80 @@ test('put_pages names its own request_id, never a page\'s internal id, in the feexpect(done.body.counts).toMatchObject({ total: 2, failed: 0 });}), 180_000);+test('a batch request_id with replacement patterns ($&, $\') is named verbatim in the fence refusal', () => each(async f => {+ _setRefreshFenceWaitForTests(0);+ const id = "fenced-$&-$'-batch";+ const args = { request_id: id, pages: [{ slug: 'notes/fenced-pattern', content: page('Fenced pattern', 'refused during the refresh') }] };+ await duringRefresh(f, async () => {+ const out = await call(f, 'put_pages', args);+ expect(out.body).toMatchObject({ code: 'worktree_refreshing', retryable: true });+ expect(out.body.message).toContain(`request_id ${id}`);+ expect(out.body.fix.why).toContain(`request_id ${id}`);+ expect(out.body.fix.mcp).toEqual({ tool: 'put_pages', arguments: args });+ });+}), 180_000);++test('remember with items[] names the batch request_id, never an item\'s, when the fence refuses the whole batch; each item is saved once', () => each(async f => {+ await withEntity(f);+ _setRefreshFenceWaitForTests(0);+ const args = { request_id: 'fenced-remember-batch-1', provenance: 'test', items: [+ { fact: 'alice-example plays the oboe canarybatchfence', entity: 'people/alice-example' },+ { fact: 'alice-example sings alto canarybatchfence', entity: 'people/alice-example' }] };+ let retry: { tool: string; arguments: Record<string, unknown> } | undefined;+ await duringRefresh(f, async () => {+ const before = await f.requestCount();+ const out = await call(f, 'remember', args);+ expect(out.body).toMatchObject({ code: 'worktree_refreshing', retryable: true });+ expect(out.body.fix.mcp).toEqual({ tool: 'remember', arguments: args });+ expect(out.body.message).toContain('request_id fenced-remember-batch-1');+ expect(await f.requestCount()).toBe(before);+ retry = out.body.fix.mcp;+ });+ const requestsBefore = await f.requestCount();+ const done = await call(f, retry!.tool, retry!.arguments);+ expect(done.isError ? done.body : 'ok').toBe('ok');+ const again = await call(f, 'remember', args);+ expect(again.isError ? again.body : 'ok').toBe('ok');+ expect(await f.requestCount() - requestsBefore).toBe(2);+ const rows = await f.engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact LIKE '%canarybatchfence%'");+ expect(rows[0]!.n).toBe(2);+}), 180_000);++test('memory_write is told to retry with its idempotency_key: the fix.mcp it returns is accepted and writes the fact once', () => each(async f => {+ const provider = new GBrainOAuthProvider({ sql: sqlQueryForEngine(f.engine), transaction: fn => f.engine.transaction(tx => fn(sqlQueryForEngine(tx))) });+ await addMember(f.engine, 'alice-example');+ const client = await provider.registerClientManual('fence-qm-' + crypto.randomUUID().slice(0, 8), ['client_credentials'], 'read write', [], f.alpha);+ await bindCredential(f.engine, { kind: 'client', id: client.clientId }, { attestActor: 'qm', attestOps: ['get_write_request', 'memory_recall', 'memory_write'] });+ await linkMember(f.engine, 'alice-example', 'qm', 'U0FENCE');+ const token = (await provider.exchangeClientCredentials(client.clientId, client.clientSecret ?? '')).access_token;+ const qm = async (params: Record<string, unknown>) => {+ const result = await dispatchToolCall(f.engine, 'memory_write', { ...params }, { remote: true, transport: 'http', sourceId: f.alpha, admissionOrigin: 'interactive',+ auth: await provider.verifyAccessToken(token) as never, actor: { header: 'U0FENCE' } });+ let body: Record<string, any> = {};+ try { body = JSON.parse(result.content[0]!.text); } catch { body = { text: result.content[0]!.text }; }+ return { isError: result.isError === true, body, structured: result.structuredContent as Record<string, any> | undefined };+ };+ _setRefreshFenceWaitForTests(0);+ const args = { idempotency_key: 'fenced-qm-key-1', facts: [{ fact: 'Alice keeps the pier key canaryqmfence', provenance: 'turn 1' }] };+ let retry: { tool: string; arguments: Record<string, unknown> } | undefined;+ await duringRefresh(f, async () => {+ const out = await qm(args);+ expect(out.isError).toBe(true);+ const body = out.structured?.error ?? out.body;+ expect(body.code).toBe('worktree_refreshing');+ expect(body.fix.mcp).toEqual({ tool: 'memory_write', arguments: args });+ expect(body.message).toContain('idempotency_key fenced-qm-key-1');+ expect(body.message).not.toContain('request_id');+ retry = body.fix.mcp;+ });+ const done = await qm(retry!.arguments);+ expect(done.isError ? done.body : 'ok').toBe('ok');+ const again = await qm(args);+ expect(again.isError ? again.body : 'ok').toBe('ok');+ const rows = await f.engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts WHERE fact LIKE '%canaryqmfence%'");+ expect(rows[0]!.n).toBe(1);+}), 180_000);+test('a database-only (repo-less) source is never fenced: remember without request_id commits during the refresh', () => each(async f => {_setRefreshFenceWaitForTests(0);await duringRefresh(f, async () => {