Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): accept any client request_id and echo it as client_request_id
garrytan778f67d6b460
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex 1cd94426fa..f8be27f439 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -61,3 +61,5 @@ Connector ingestion, item holds and checkpoint validation continue in [Core Pers- `src/core/persistence/{source-lifecycle,managed-sources,topology-schema,topology-locks,topology-receipts,topology-clone,topology-clone-model,topology-filesystem,topology-recovery}.ts` — migration 157 coordinates source add/claim/archive/restore/remove/purge/rebind/reclone. Native root locks precede topology/source/grant/counter/request guards; a shared root advances every membership and permanently conflicts accepted old-topology requests. Withdrawal mirrors and running publication must settle first. Administrative UUIDs share the page journal's principal-scoped conflict domain and permanent capacity counters. Directory replacement reserves the configured recovery budget before provider/staging work, records a verified manifest and physical identity, and recovers only known bytes; clone failure retains the original checkout and a replayable failure receipt. Rebinding accepts a fresh candidate with exactly matching canonical content, including deletions. Stored worktree manifests and clone recovery records keep `digest`, `file_count`, `canonical_stamp` and `self_transfer` but no per-file map (#5790), so their size is independent of the worktree; `compactStoredManifest` drops a legacy map on rewrite, and transfer prepare/accept hash under the native lock before their transaction. Large-repo tests: `test/persistence-large-manifest.test.ts` (12k files, both engines via `test/e2e/persistence-large-manifest-postgres.test.ts`) and `test/e2e/persistence-large-manifest-50k.test.ts`. Old root refusal records remain. Metadata deletion retains local storage. Restart recovery rotates a bounded root scan so one conflict cannot starve other roots. Tests: `test/persistence-source-lifecycle.test.ts` on PGLite and guarded isolated Postgres. #6099: manifests are Git-scoped for Git checkouts; see `worktree-manifest.ts` in [managed sync and persistence stalls](persistence-stalls.md).- `src/core/persistence/{worktree-refresh,worktree-refresh-schema}.ts` — `gbrain sources refresh` (F0), the one sanctioned managed Git writer. `persistence_worktree_refreshes` holds one row per refresh with a partial unique index (one active refresh per worktree; its 23505 maps to `refresh_in_progress`). `refreshWorktree` prechecks with no database state (managed, owner host, upstream, no active refresh, no recovery, no unexhausted managed-sync cursor, hardened `git fetch` bounded by `sources.refresh_fetch_timeout_ms`, ancestry, dirty paths intersected with the incoming diff), then: `draining` (inserted under `withTopologyLocks` + `lockTopologyRows`; admission in `journal.ts` refuses `worktree_refreshing` for every request with that `worktree_id`, and `assertManagedSyncAllowed` refuses a managed sync before discovery), poll until no queued/running/recovering request, no queued/running `git`/`withdrawal-mirror` effect and no recovery record remain (else `refresh_drain_timeout`, aborted), `fenced` (both native locks held, rechecked in one transaction; `refreshFenceClear` stops request and effect claims), HEAD verified, dirt rechecked, `git merge --ff-only`, HEAD verified again, then one transaction `merged` + upstream observation + `syncing`; native locks are released and the managed `--no-pull` sync runs per member (only `managed_sync_*` `submit_job` admissions pass during `syncing`); `completed` when every member's `last_commit` is the target, or with `outcome.sync_blocked` when a member sync blocks. A per-worktree `refresh-<worktree>.lock` held for the whole run proves liveness: `resumeWorktreeRefreshes` (called from `recoverSourceTopologies`, so on owner start) touches only interrupted `draining`/`fenced`/`merged` rows whose lock is free and applies the section 1.5 table (draining or fenced at the old HEAD abort; HEAD at the verified target moves to `syncing`; anything else is `recovery_required`, which admission refuses with `refresh_recovery_required`). Admission also completes a `syncing` row whose members all reached the target. `--resume` converges and runs the member syncs; `--abandon` lifts a fence only with HEAD back at the start commit. `gbrain sources writer status` lists active refreshes as `worktree_refreshes` (state, heads, the next command), which the refusal hints point at. Doctor `worktree_refresh_stuck` lists rows active over 15 minutes. CLI body: `src/commands/sources-refresh.ts`; while a resident PGLite owner (`gbrain serve`, stdio MCP) holds the database, `src/commands/sources-refresh-delegate.ts` runs the refresh inside it through the `writer_refresh` administration operation (trusted CLI registration only) and prints the same result or refusal. The consumer's idle probe applies `refreshFenceClear` to effects like the claims, so a fenced worktree's queued effects do not wake it. Tests: `test/persistence-worktree-refresh.test.ts`, `test/persistence-worktree-refresh-restart.test.ts` (child-process crash after merge), Postgres via `test/e2e/worktree-refresh-postgres.test.ts`, owner delegation in `test/persistence-sync-stdio-owner.test.ts`.++- `src/core/persistence/preconditions.ts` — `parseWriteRequestId`, the one place a write op's `request_id` is normalized (F6, Cat 40 Hard): a UUID passes through lowercased, any other id of 1-128 printable ASCII characters maps to its RFC 4122 UUIDv5 under `CLIENT_REQUEST_ID_NAMESPACE` (no operation name, so receipt lookups find a write by the client's string); `clientRequestIdOf` is the string admissions store in `persistence_requests.client_request_id` (v219, outside the intent digest, kept by compaction) and receipts echo as `client_request_id`. Administration writer/deactivation ids keep strict UUID checks. `remember(items)` derives child ids from the root string as sent (`childRequestId`). Tests: `test/persistence-client-request-id.test.ts`, `test/e2e/persistence-client-request-id-postgres.test.ts`.diff --git a/docs/guides/concurrent-writes.md b/docs/guides/concurrent-writes.mdindex 8df59c6fd9..d05f21ec4a 100644--- a/docs/guides/concurrent-writes.md+++ b/docs/guides/concurrent-writes.md@@ -3,6 +3,9 @@Each accepted mutation has a durable request UUID scoped to one brain and oneauthenticated principal. A response distinguishes acceptance from commitment.Keep the UUID and original arguments until the request reaches a terminal state.+A caller may send any `request_id` of 1 to 128 printable ASCII characters; a+non-UUID id maps to a deterministic UUID, receipts echo the original as+`client_request_id`, and the receipt helpers accept either.**Say to your agent:** *"Update this page without overwriting a newer revision;use `get_page` and `put_page`, then check the durable receipt."* Or: *"Inspect my@@ -13,8 +16,8 @@ the setup."*Read an existing page with `get_page` and `include_content: true`. Preserve itscomplete `content`, `revision`, and source. Send the edited complete content to-`put_page` with `expected_revision` equal to that revision and a newly generated-`request_id` UUID. Capture replacements, delete, restore, and version revert also+`put_page` with `expected_revision` equal to that revision and a new+`request_id` (or none). Capture replacements, delete, restore, and version revert alsoaccept the revision precondition. `force: true` is an explicit overwrite choice;it is mutually exclusive with `expected_revision`.diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex bfc1e48b07..6919764436 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -327,15 +327,16 @@ fact, so it goes on its item; passing both `fact` and `items`, or a top-levelEvery item is validated before any is written: one invalid item refuses thewhole 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` 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` (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 andwrites nothing twice.-Response: `{ protocol_version, request_id, items[], saved, failed, partial,+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?, 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 } }`. Hints the+`{ index, request_id, status: "failed", error: { code, message, suggestion? } }`. Hints thesingle-fact response would repeat per item appear once in `hints`. `partial: true` means some items saved and some failed; resendonly the failed items, in a new call with a new `request_id`.@@ -525,7 +526,7 @@ empty list means no close match was found, not that every rewording is gone.#### Durable write receipts (additive)Write receipts distinguish accepted work from committed memory. Their public-shape is `{request_id, state, retry_after_ms, revision?, outcome?, persistence?,+shape is `{request_id, client_request_id?, state, retry_after_ms, revision?, outcome?, persistence?,compacted?, created_at?, updated_at?, diagnostic?}`. States are `queued`, `running`,`recovering`, `committed`, `conflict`, `failed`, and `cancelled`. Terminalreceipts have `retry_after_ms: null`. `persistence.mode` distinguishes a@@ -548,10 +549,19 @@ the detailed concurrency reason without changing the frozen protocol errorenum. A committed receipt retains the original memory-verb success fields.Compaction may remove diagnostics, but must preserve those frozen result fields.-The optional caller-generated UUID `request_id` identifies one write intent.-Retry the same verb with the original arguments and the same ID to recover-its outcome, including on the verbs-only surface. A terminal request is never-executed again. Corrected input requires a new ID. Clients that lose a response+The optional caller-chosen `request_id` identifies one write intent; reuse it+only to retry the same write. Any id of 1 to 128 printable ASCII characters+(0x21 to 0x7E, no spaces) is accepted. A UUID is used as is (lowercased); any+other id maps to a deterministic UUIDv5 under one fixed gbrain namespace, so+`request_id` in every response stays a UUID and the id the caller sent comes+back as `client_request_id`, which is kept for the life of the receipt. The+receipt helpers find a write by either id. Retry the same verb with the original+arguments and the same ID to recover its outcome, including on the verbs-only+surface. A terminal request is never executed again. Corrected input requires a+new ID: reusing an id for a different write is refused with+`idempotency_conflict` ("this request_id was used for a different write; send a+new one or omit it"), which `remember` reports as `invalid_params` with+`write_error: "idempotency_conflict"`. Clients that lose a responsewithout retaining its request ID cannot assume that retrying content is anexactly-once write. A receipt never contains queued content, recovery paths orexecution credentials.diff --git a/llms-full.txt b/llms-full.txtindex b535b364e4..2ee3ab04f4 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -9046,15 +9046,16 @@ fact, so it goes on its item; passing both `fact` and `items`, or a top-levelEvery item is validated before any is written: one invalid item refuses thewhole 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` 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` (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 andwrites nothing twice.-Response: `{ protocol_version, request_id, items[], saved, failed, partial,+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?, 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 } }`. Hints the+`{ index, request_id, status: "failed", error: { code, message, suggestion? } }`. Hints thesingle-fact response would repeat per item appear once in `hints`. `partial: true` means some items saved and some failed; resendonly the failed items, in a new call with a new `request_id`.@@ -9244,7 +9245,7 @@ empty list means no close match was found, not that every rewording is gone.#### Durable write receipts (additive)Write receipts distinguish accepted work from committed memory. Their public-shape is `{request_id, state, retry_after_ms, revision?, outcome?, persistence?,+shape is `{request_id, client_request_id?, state, retry_after_ms, revision?, outcome?, persistence?,compacted?, created_at?, updated_at?, diagnostic?}`. States are `queued`, `running`,`recovering`, `committed`, `conflict`, `failed`, and `cancelled`. Terminalreceipts have `retry_after_ms: null`. `persistence.mode` distinguishes a@@ -9267,10 +9268,19 @@ the detailed concurrency reason without changing the frozen protocol errorenum. A committed receipt retains the original memory-verb success fields.Compaction may remove diagnostics, but must preserve those frozen result fields.-The optional caller-generated UUID `request_id` identifies one write intent.-Retry the same verb with the original arguments and the same ID to recover-its outcome, including on the verbs-only surface. A terminal request is never-executed again. Corrected input requires a new ID. Clients that lose a response+The optional caller-chosen `request_id` identifies one write intent; reuse it+only to retry the same write. Any id of 1 to 128 printable ASCII characters+(0x21 to 0x7E, no spaces) is accepted. A UUID is used as is (lowercased); any+other id maps to a deterministic UUIDv5 under one fixed gbrain namespace, so+`request_id` in every response stays a UUID and the id the caller sent comes+back as `client_request_id`, which is kept for the life of the receipt. The+receipt helpers find a write by either id. Retry the same verb with the original+arguments and the same ID to recover its outcome, including on the verbs-only+surface. A terminal request is never executed again. Corrected input requires a+new ID: reusing an id for a different write is refused with+`idempotency_conflict` ("this request_id was used for a different write; send a+new one or omit it"), which `remember` reports as `invalid_params` with+`write_error: "idempotency_conflict"`. Clients that lose a responsewithout retaining its request ID cannot assume that retrying content is anexactly-once write. A receipt never contains queued content, recovery paths orexecution credentials.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex e7c997d0ed..f16328ff18 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -298,6 +298,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.105.0', text: 'search and query rank a page gbrain generated (frontmatter `dream_generated: true`, type `extract_receipt`) at half its score when the query names an entity and a primary record about it is among the results; such rows carry `provenance: "generated"`. Generated corrections are never demoted. `gbrain config set search.demote_generated false` turns the demotion off.' },{ since: '0.60.105.0', text: 'search now says how many pages match the query\'s keywords (`keyword_total`, up to 10000+) and adds one line after the rows saying they are a ranked top-K. `match: "keyword"` lists every keyword match with `total`, `truncated` and a ready-to-send `next`. An agent-facing `mode` is now refused (it was ignored) with a fix naming `match: "keyword"`, and an offset over 10,000 is refused.' },{ since: '0.60.105.0', text: 'Lean search and query rows now keep `effective_date_source`, and replies with dated rows add one line labeling each `effective_date` as a document, event or fallback (import) date; it is never a contract\'s effective date.' },+ { since: '0.60.105.0', text: '`remember` of a claim that was forgotten is now refused before it is accepted, with `invalid_params` and the message prefix `fact_withdrawn` (it used to be accepted and then fail with "The write did not commit"); a claim forgotten without an entity stays withdrawn for every entity. `replaces` now accepts a fact saved without an entity, so `remember` with `entity` and `replaces` links that fact instead of forgetting it. A failed write receipt names its cause instead of "Inspect its durable request on the source host".' },+ { since: '0.60.105.0', text: 'Write tools accept any `request_id` of 1 to 128 printable ASCII characters instead of refusing a non-UUID. A non-UUID maps to a deterministic UUID: responses keep `request_id` as that UUID and add `client_request_id` with the id that was sent, and `get_write_request`, `list_write_requests` and `cancel_write_request` accept either. Reusing an id for a different write is refused with `idempotency_conflict` (`remember`: `invalid_params` with `write_error: idempotency_conflict`).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex 52d5295fd8..fa635e8cfc 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -2,6 +2,7 @@ import { searchAnswerFeedback } from '../feedback/record.ts';import { parseRelationalPlan } from '../search/relational-plan.ts';import { loadSearchModeConfig, resolveSearchMode } from '../search/mode.ts';import { WRITE_REQUEST_PARAM } from '../persistence/params.ts';+import { parseWriteRequestId } from '../persistence/preconditions.ts';import { deliverEvidence, effectivePlan, resolveEvidencePlan, type DeliveryMeta, type EvidencePlan } from '../search/evidence-delivery.ts';import { randomUUID } from 'node:crypto';import { readHolders } from './context.ts';@@ -120,7 +121,7 @@ const extract_facts: Operation = {const r = await runFactsPipeline(p.turn_text as string, {engine: ctx.engine,operationContext: ctx,- requestId: typeof p.request_id === 'string' ? p.request_id : randomUUID(),+ requestId: parseWriteRequestId(p.request_id) ?? randomUUID(),requestIntent: { ...p, request_id: undefined },sourceId,sessionId: typeof p.session_id === 'string' ? p.session_id : null,diff --git a/src/core/ops/page-batch.ts b/src/core/ops/page-batch.tsindex 0a86325549..b77388d269 100644--- a/src/core/ops/page-batch.ts+++ b/src/core/ops/page-batch.ts@@ -8,7 +8,7 @@ const put_pages: Operation = {name: 'put_pages',idempotent: true,outputRedaction: 'no_stored_text',- description: `Write up to ${PAGE_BATCH_MAX_PAGES} complete Markdown pages (${PAGE_BATCH_MAX_BYTES / 1024 / 1024} MB total) in one call; use instead of put_page for more than 3 pages. Each page replaces its whole page, like put_page. Keep one request_id UUID per batch: replaying the identical call never writes twice, and put_pages with ONLY request_id reports progress without resending content. Waits up to wait_ms (default 25000) for commits; follow the returned \`next\`. Needs put_page permission.`,+ description: `Write up to ${PAGE_BATCH_MAX_PAGES} complete Markdown pages (${PAGE_BATCH_MAX_BYTES / 1024 / 1024} MB total) in one call; use instead of put_page for more than 3 pages. Each page replaces its whole page, like put_page. Keep one request_id per batch: replaying the identical call never writes twice, and put_pages with ONLY request_id reports progress without resending content. Waits up to wait_ms (default 25000) for commits; follow the returned \`next\`. Needs put_page permission.`,params: {pages: {type: 'array', description: `1-${PAGE_BATCH_MAX_PAGES} pages; omit to read the batch status.`,@@ -23,7 +23,7 @@ const put_pages: Operation = {},},},- request_id: { ...WRITE_REQUEST_PARAM, required: true, description: 'Batch UUID; reuse it to replay or poll.' },+ request_id: { ...WRITE_REQUEST_PARAM, required: true, description: 'Batch id; reuse only to replay or poll.' },source_id: PAGE_MUTATION_PARAMS.source_id,wait_ms: { ...WRITE_WAIT_PARAM, description: 'Hold the reply up to this many ms (0-30000, from arrival) for commits. Default 25000. Not part of the write.' },},diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 216bdb4bea..54d4d9494f 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -127,11 +127,11 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: Wfunction requiredRequestId(value: unknown): string {const id = parseWriteRequestId(value);- if (!id) throw opError('invalid_params', 'request_id is required.', 'Pass the request_id (a UUID) from the write\'s receipt; list_write_requests shows recent ones.');+ if (!id) throw opError('invalid_params', 'request_id is required.', 'Pass the request_id you sent with the write, or the one its receipt shows; list_write_requests shows recent ones.');return id;}-const requestParam = { type: 'string' as const, required: true, description: 'The UUID you sent with the write.' };+const requestParam = { type: 'string' as const, required: true, description: 'The id you sent, or the receipt\'s.' };export const persistenceOperations: Operation[] = [{diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex caf9d87d29..a23e63e36f 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -116,7 +116,7 @@ export const GRADUATION_INVENTORY: Inventory = {],}),carry('persistence_local_writers', 'security', 'Local writer credentials (cli/stdio) and revocations.'),- carry('persistence_requests', 'user_data', 'Write requests: idempotency records and outcomes, so replays return the stored outcome.'),+ carry('persistence_requests', 'user_data', 'Write requests: idempotency records and outcomes, so replays return the stored outcome; client_request_id keeps the client\'s original id beside its UUIDv5.'),carry('persistence_source_bindings', 'user_data', 'Source to worktree bindings.'),carry('persistence_topology_changes', 'user_data', 'Topology change journal.'),carry('persistence_worktree_refreshes', 'user_data', 'Worktree refresh journal.'),diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex 9a918610f7..283f352db0 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -33,6 +33,8 @@ export interface WriteAdmission {worktreeId?: string | null;topologyGeneration?: string | number | null;requestId?: string;+ /** F6: the client's non-UUID request_id, stored beside the canonical id and never digested. */+ clientRequestId?: string;/** Normalized caller intent, excluding server-generated timestamp/TTL defaults. */callerIntent: Record<string, unknown>;intent: Record<string, unknown>;@@ -126,8 +128,11 @@ export function intentDigest(a: Pick<WriteAdmission, 'operation' | 'sourceId' |return digest({ operation: a.operation, source_id: a.sourceId, slug: a.slug, intent: a.callerIntent });}export function assertReplayIntent(row: WriteRequest, expectedDigest: string): WriteRequest {- if (row.digest !== expectedDigest) throw new OperationError('idempotency_conflict',- 'This request_id was already accepted with different intent.', 'Replay the original request, or allocate a new request_id for a new intent.');+ if (row.digest !== expectedDigest) throw opError('idempotency_conflict', 'This request_id was used for a different write; send a new one or omit it.',+ 'A request_id is reused only to retry the same write. Send this write again with a new request_id or without one; the earlier write keeps its receipt.',+ { fix: readFix(`Reads the earlier write's receipt (request ${row.request_id}), read-only.`, row.principal_kind === 'local_cli'+ ? { argv: ['gbrain', 'write-request', '--', row.request_id] }+ : { mcp: { tool: 'get_write_request', arguments: { request_id: row.client_request_id ?? row.request_id } } }) });return row;}export async function admitWrite(engine: BrainEngine, input: WriteAdmission, overrides?: Partial<JournalLimits>): Promise<WriteRequest> {@@ -193,12 +198,12 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, overINSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,- admitter_version,admitter_host_id)- VALUES($1,$2,$3::uuid,$4,$5,$6::uuid,$7,$8,$9::uuid,$10,$11,$12::text::jsonb,$13::text::jsonb,$14,$15,$16,$17,$18,$19::uuid)+ admitter_version,admitter_host_id,client_request_id)+ VALUES($1,$2,$3::uuid,$4,$5,$6::uuid,$7,$8,$9::uuid,$10,$11,$12::text::jsonb,$13::text::jsonb,$14,$15,$16,$17,$18,$19::uuid,$21)RETURNING *`, [input.principal.kind, input.principal.id, requestId, input.operation, input.sourceId,input.sourceIncarnation, input.pageId ?? null, input.slug, input.worktreeId ?? null, input.topologyGeneration ?? null,fingerprint, JSON.stringify(input.intent), JSON.stringify(input.authority), bytes, terminalBytes, input.targetKind ?? 'page', input.protocolVersion ?? 1,- stamp.version, stamp.hostId, counters.map(c => c.key)]);+ stamp.version, stamp.hostId, counters.map(c => c.key), input.clientRequestId ?? null]);return row;} };}@@ -262,14 +267,14 @@ export async function admitWriteGroupInTransaction(tx: BrainEngine, inputs: Writconst rows = await tx.executeRaw<WriteRequest>(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,page_id,slug,worktree_id,topology_generation,digest,intent,authority,intent_bytes,terminal_reservation,target_kind,protocol_version,- admitter_version,admitter_host_id)+ admitter_version,admitter_host_id,client_request_id)SELECT $1,$2,(e->>'request_id')::uuid,$3,$4,$5::uuid,(e->>'page_id')::integer,e->>'slug',$6::uuid,$7,e->>'digest',e->'intent',$8::text::jsonb,- (e->>'intent_bytes')::bigint,(e->>'terminal_reservation')::bigint,'page',1,$9,$10::uuid+ (e->>'intent_bytes')::bigint,(e->>'terminal_reservation')::bigint,'page',1,$9,$10::uuid,e->>'client_request_id'FROM jsonb_array_elements($11::text::jsonb) WITH ORDINALITY AS t(e,n) ORDER BY nRETURNING *`, [first.principal.kind, first.principal.id, first.operation, first.sourceId, first.sourceIncarnation, first.worktreeId ?? null,first.topologyGeneration ?? null, JSON.stringify(first.authority), stamp.version, stamp.hostId,JSON.stringify(fresh.map(item => ({ request_id: item.requestId, page_id: item.input.pageId ?? null, slug: item.input.slug, digest: item.fingerprint,- intent: item.input.intent, intent_bytes: item.bytes, terminal_reservation: item.terminalBytes })))]);+ intent: item.input.intent, intent_bytes: item.bytes, terminal_reservation: item.terminalBytes, client_request_id: item.input.clientRequestId ?? null })))]);for (const row of rows) priors.set(row.request_id, row);await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count+$4,intent_bytes=intent_bytes+$2,lifetime_ids=lifetime_ids+$4,terminal_bytes=terminal_bytes+$3 WHERE key=ANY($1::text[])`,@@ -666,7 +671,7 @@ export async function compactWriteReceipts(engine: BrainEngine, retentionDays?:if(unfinished.length) return 0;const [effects]=await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytesFROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);- const retained=Math.min(Number(current.terminal_reservation),jsonBytes(current.authority)+jsonBytes(current.outcome??{})+(current.error_detail?jsonBytes(current.error_detail):0)+Number(effects.bytes)+1024);+ const retained=Math.min(Number(current.terminal_reservation),jsonBytes(current.authority)+jsonBytes(current.outcome??{})+(current.error_detail?jsonBytes(current.error_detail):0)+(current.client_request_id?.length??0)+Number(effects.bytes)+1024);await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2 WHERE id=$1::uuid',[row.id,retained]);for(const key of keys) await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-$2 WHERE key=$1',[key,Number(current.terminal_reservation)-retained]);return 1;@@ -677,7 +682,7 @@ export function receiptFor(row: WriteRequest, facts?: WriteHealthFacts, now = Dareturn {...(row.outcome ?? {}),...(row.outcome ? { outcome: row.outcome } : {}),- request_id: row.request_id, state: row.state,+ request_id: row.request_id, ...(row.client_request_id ? { client_request_id: row.client_request_id } : {}), state: row.state,...writeHealth(row, facts, now),...(row.error_code ? { write_error: row.error_code } : {}),...(row.error_detail ? { write_error_detail: publicFailureDetail(row.error_detail) } : {}),diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.tsindex 1cb492dc5c..e9f01ff95b 100644--- a/src/core/persistence/local-client.ts+++ b/src/core/persistence/local-client.ts@@ -11,6 +11,7 @@ import { resolveSourceIdEngineFree } from '../source-resolver.ts';import { opError, opOwnsSource, OperationError } from '../ops/contract.ts';import { readFix, trustedCliRequired } from '../ops/op-fix.ts';import { parseWriteRequestId } from './preconditions.ts';+import { isWriteRequestId } from './types.ts';import {isPersistenceIpcMutation, isPersistenceIpcOperation, isPersistenceIpcRegistration,persistenceSocketPathForConfig, requestPersistenceCapabilities, requestPersistenceOperation,@@ -59,7 +60,7 @@ export function residentPersistenceConfig(hostConfig: GBrainConfig | null, cwd =/** Reads an existing registration only. Revocation/missing credentials never create a new principal. */export function readPersistenceCliRegistration(brainId: string): PersistenceIpcRegistration {// Capability validation has already constrained this filename component to a UUID.- const id = parseWriteRequestId(brainId);+ const id = isWriteRequestId(brainId) ? brainId.toLowerCase() : undefined;if (!id) {throw opError('permission_denied', 'Missing durable brain identity.','The resident owner reported no durable brain identity, so this CLI cannot select its writer registration. Check the brain\'s persistence state; if an older owner is running, the user restarts it after upgrading.',diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.tsindex c71835a273..bc695913b7 100644--- a/src/core/persistence/memory-mutations.ts+++ b/src/core/persistence/memory-mutations.ts@@ -17,7 +17,7 @@ import { claimWorktree } from './ownership.ts';import { declareDurablePersistence } from './protocol.ts';import { resolveFactWriteTarget } from './fact-write-target.ts';import { WRITER_INSPECTION_HINT } from './admin-intent.ts';-import { parseMutationPrecondition } from './preconditions.ts';+import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';import { withCoordinatedWrite } from './context.ts';import { requestAttribution } from './attribution.ts';import { isTerminal, type WriteRequest } from './model.ts';@@ -56,7 +56,7 @@ async function submission(ctx: OperationContext, operation: string, params: Recoawait authorizeStoredRequest(ctx.engine, prior);assertReplayIntent(prior, intentDigest({ operation, sourceId, slug: prior.slug, callerIntent }));}- return { p, requestId, sourceId, principal, callerIntent, prior };+ return { p, requestId, clientRequestId: clientRequestIdOf(params.request_id), sourceId, principal, callerIntent, prior };}type RememberSource = { incarnation: string; archived: boolean; local_path: string | null; kind: string | null };@@ -145,7 +145,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: RecoregisterMutationPreparer('remember', prepareMemoryMutation);const sub = await submission(ctx, 'remember', params);if (sub.prior) return writeResponse(await waitForWrite(ctx.engine, sub.prior, ctx.config, waitMs ?? ctx.writeWaitMs));- const { p, sourceId, principal, callerIntent, requestId } = sub;+ const { p, sourceId, principal, callerIntent, requestId, clientRequestId } = sub;const [source] = await ctx.engine.executeRaw<RememberSource>("SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);if (!source || source.archived) throw sourceInactive(sourceId);@@ -168,7 +168,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco}await assertFactNotWithdrawn(ctx.engine, sourceId, factIntent);const row = await admitWrite(ctx.engine, { principal, operation: 'remember', sourceId, sourceIncarnation: source.incarnation,- slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent,+ slug, pageId: snapshot?.page.id ?? null, requestId, clientRequestId, callerIntent,// The transport's session (MCP `_meta.session_id`) is recorded on the fact, as extract_facts records// it, so recall's session_id filter finds single facts too. Identity only — never a trust surface.intent: { ...callerIntent, entity_slug: entitySlug, fence, valid_from: new Date().toISOString(), valid_until: validUntil?.toISOString() ?? null,@@ -186,7 +186,7 @@ interface WithdrawalTarget { id: number; entity_slug: string | null; source_markexport async function submitForgetMutation(ctx: OperationContext, operation: 'forget' | 'forget_fact', params: Record<string, unknown>): Promise<Record<string, unknown>> {const sub = await submission(ctx, operation, params);if (sub.prior) return withSimilarActive(ctx, operation, sub.sourceId, sub.p, writeResponse(sub.prior));- const { p, sourceId, principal, callerIntent, requestId } = sub;+ const { p, sourceId, principal, callerIntent, requestId, clientRequestId } = sub;const semanticReview = p.semantic_review !== false;const id = Number(p.id);const rawId = String(p.id).trim();@@ -220,7 +220,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'foenforceClientSlugFence(ctx, slug, operation); enforceSubagentSlugFence(ctx, slug, operation);const authority = await submissionAuthority({ ...ctx, engine: tx }, operation, sourceId, source.incarnation, slug);const row = await admitWriteInTransaction(tx, { principal, operation, sourceId, sourceIncarnation: source.incarnation,- slug, requestId, callerIntent, intent: { ...callerIntent, reason }, authority });+ slug, requestId, clientRequestId, callerIntent, intent: { ...callerIntent, reason }, authority });if (isTerminal(row)) return row;return withCoordinatedWrite(tx, [sourceId], async () => {// Even an expired legacy fact acquires a ledger so a stale import cannotdiff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 3a3e2847ba..58e116bbd2 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -87,6 +87,8 @@ export interface WriteRequest {/** #5974 structured failure (publication-failure.ts); receipts expose only its public view. */error_detail?: Record<string, unknown> | null;blocked_reason: string | null;+ /** F6: the non-UUID request_id the client sent (request_id is its UUIDv5); outside the intent digest, kept through compaction. */+ client_request_id?: string | null;compacted: boolean;publication_started: boolean;created_at: Date | string;diff --git a/src/core/persistence/page-batch.ts b/src/core/persistence/page-batch.tsindex 89a3b27773..4a478501bb 100644--- a/src/core/persistence/page-batch.ts+++ b/src/core/persistence/page-batch.ts@@ -25,7 +25,7 @@ import { isTerminal, type WriteRequest } from './model.ts';import { estimatedRetryAfterMs, waitForWrites, writeResponse } from './service.ts';import { initializeLocalPersistence, pageMutationSource, preparePageAdmission, requestPrincipalForContext, withBatchAdmission } from './page-mutations.ts';import type { PageTypeWarning } from './page-input.ts';-import { parseWriteRequestId } from './preconditions.ts';+import { clientRequestIdOf, parseWriteRequestId } from './preconditions.ts';import { parseWireWriteWaitMs } from './write-wait.ts';export const PAGE_BATCH_MAX_PAGES = 50;@@ -122,7 +122,7 @@ async function batchLinks(ctx: OperationContext, sourceId: string, results: Page...(done.length < effects.length ? { why: 'Mention links from [[wikilinks]] to existing pages are built after commit; read this batch again with put_pages {request_id} to see them settle. Do not add them by hand.' } : {}) };}-function batchReceipt(ctx: OperationContext, batchId: string, sourceId: string, results: PageResult[], links: Record<string, unknown>): Record<string, unknown> {+function batchReceipt(ctx: OperationContext, batchId: string, sourceId: string, results: PageResult[], links: Record<string, unknown>, clientRequestId?: string): Record<string, unknown> {const pages = results.map(pageEntry);const committed = pages.filter(page => page.state === 'committed').length;const pending = pages.filter(page => ['queued', 'running', 'recovering'].includes(String(page.state))).length;@@ -138,7 +138,7 @@ function batchReceipt(ctx: OperationContext, batchId: string, sourceId: string,// #6188 (D12, D21): one `fences_normalized` and one coaching notice for every page whose fence Tier 1 rewrote.const fences = mergeFencesNormalized(pages.flatMap(page => page.fences_normalized ? [page.fences_normalized as FencesNormalized] : []));if (fences) ctx.emitNotice?.(fenceNormalizedNotice(fences));- return { batch_request_id: batchId, source_id: sourceId, state, terminal: pending === 0, counts: { total: pages.length, committed, pending, failed },+ return { batch_request_id: batchId, ...(clientRequestId ? { client_request_id: clientRequestId } : {}), source_id: sourceId, state, terminal: pending === 0, counts: { total: pages.length, committed, pending, failed },...(retryAfterMs !== null ? { retry_after_ms: retryAfterMs } : {}), next, links, pages, ...(fences ? { fences_normalized: fences } : {}) };}@@ -201,7 +201,7 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<striconst batchId = parseWriteRequestId(params.request_id);if (!batchId) {throw invalid('put_pages requires request_id; nothing was written.',- 'Generate one UUID for this batch, pass it as request_id, and keep it: replaying the same call with it never writes twice, and put_pages with only that request_id reports progress.');+ 'Pass one request_id for this batch (any id up to 128 printable characters) and keep it: replaying the same call with it never writes twice, and put_pages with only that request_id reports progress.');}const sourceId = pageMutationSource(ctx, params, 'put_pages');await initializeLocalPersistence(ctx);@@ -218,7 +218,7 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<striconst row = byIndex.get(index);return { index, slug: row?.slug ?? '', ...(row ? { row } : {}) };});- return batchReceipt(ctx, batchId, sourceId, results, await batchLinks(ctx, sourceId, results));+ return batchReceipt(ctx, batchId, sourceId, results, await batchLinks(ctx, sourceId, results), clientRequestIdOf(params.request_id));}const pages = parsePages(params.pages);const existing = await readBatch(ctx, batchId);@@ -261,6 +261,6 @@ export async function submitPageBatch(ctx: OperationContext, params: Record<striconst journaled = results.filter(result => result.row);const settled = await waitForWrites(ctx.engine, journaled.map(result => result.row!), ctx.config, remaining());journaled.forEach((result, position) => { result.row = settled[position]!; });- return batchReceipt(ctx, batchId, sourceId, results, await batchLinks(ctx, sourceId, results));+ return batchReceipt(ctx, batchId, sourceId, results, await batchLinks(ctx, sourceId, results), clientRequestIdOf(params.request_id));}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 814d7ee15c..8972664896 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -22,7 +22,7 @@ import { submissionAuthority, authorizeStoredRequest } from './authority.ts';import { currentVerifiedLocalWriter, localHostId, readLocalWriter, registerLocalWriter, withVerifiedLocalRegistration } from './identity.ts';import type { BrainEngine } from '../engine.ts';import { claimWorktree, getWorktreeBinding, managedPersistenceEnabled } from './ownership.ts';-import { parseMutationPrecondition } from './preconditions.ts';+import { clientRequestIdOf, parseMutationPrecondition } from './preconditions.ts';import { assertPurgeParams } from './purge-params.ts';import type { Principal, WriteRequest } from './model.ts';import { normalizeSubagentPageInput, undeclaredPageTypeWarning, type PageTypeWarning } from './page-input.ts';@@ -328,7 +328,7 @@ export async function preparePageAdmission(ctx: OperationContext,throw colonSlugWindowsRefusal(slug, sourceId);}return { typeWarning, slugAdvisory, admission: { principal, operation: input.operation, sourceId, sourceIncarnation: source.incarnation,- slug, pageId: snapshot?.page.id ?? null, requestId, callerIntent, intent, authority,+ slug, pageId: snapshot?.page.id ?? null, requestId, clientRequestId: input.batch ? undefined : clientRequestIdOf(params.request_id), callerIntent, intent, authority,...(input.operation === 'edit_page' ? { terminalReservation: Math.max(16_384, Buffer.byteLength(JSON.stringify(authority)) + 8192)+ (await import('./page-edit.ts')).EDIT_PAGE_RECEIPT_RESERVE } : {}),worktreeId: writeThrough ? binding?.worktree_id : null, topologyGeneration: writeThrough ? binding?.topology_generation : null } };diff --git a/src/core/persistence/params.ts b/src/core/persistence/params.tsindex 2ad96f7ae8..e9c93b7dcb 100644--- a/src/core/persistence/params.ts+++ b/src/core/persistence/params.ts@@ -16,7 +16,7 @@ import { WRITE_REQUEST_STATES, WRITE_HEALTH_REASONS, WRITE_HEALTH_ASSESSMENTS, W*/export const WRITE_REQUEST_PARAM: ParamDef = {type: 'string',- description: 'UUID; retry with it on timeout.',+ description: 'Optional; reuse only to retry.',};/** #6007: transport-only long-poll; never stored with the write or compared on replay. */diff --git a/src/core/persistence/preconditions.ts b/src/core/persistence/preconditions.tsindex 9a43dfd1c2..a7f0492442 100644--- a/src/core/persistence/preconditions.ts+++ b/src/core/persistence/preconditions.ts@@ -1,13 +1,43 @@+import { createHash } from 'node:crypto';import { OperationError } from '../ops/contract.ts';import { isWriteRequestId, type MutationPrecondition } from './types.ts';+/**+ * F6: the one fixed namespace every non-UUID request_id maps under. It carries no operation name, so a+ * receipt lookup finds a write by the client's original string. Changing it orphans every journaled id.+ */+export const CLIENT_REQUEST_ID_NAMESPACE = '3f6a2c1e-9b47-4d2a-8e5f-7c0b1d9a6e24';+export const CLIENT_REQUEST_ID_MAX = 128;+const PRINTABLE_ASCII = /^[\x21-\x7e]+$/;++/** RFC 4122 UUIDv5 of `name` under CLIENT_REQUEST_ID_NAMESPACE. */+export function clientRequestUuid(name: string): string {+ const h = createHash('sha1').update(Buffer.from(CLIENT_REQUEST_ID_NAMESPACE.replace(/-/g, ''), 'hex')).update(name, 'utf8').digest();+ h[6] = (h[6]! & 0x0f) | 0x50;+ h[8] = (h[8]! & 0x3f) | 0x80;+ const hex = h.subarray(0, 16).toString('hex');+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;+}++/**+ * A write op's request_id at the operation boundary: a UUID passes through (lowercased, as always), any+ * other id of 1-128 printable ASCII characters maps to its deterministic UUIDv5. The result is the+ * journal's canonical request_id; administration ids keep their own strict UUID checks.+ */export function parseWriteRequestId(value: unknown): string | undefined {if (value === undefined) return undefined;- if (!isWriteRequestId(value)) {- throw new OperationError('invalid_params', 'request_id must be a UUID.',- 'Generate a UUID before submitting the write and reuse it for retries of the same request.');+ if (isWriteRequestId(value)) return value.toLowerCase();+ if (typeof value !== 'string' || !value.length || value.length > CLIENT_REQUEST_ID_MAX || !PRINTABLE_ASCII.test(value)) {+ const actual = typeof value === 'string' ? `this one has ${value.length} characters${value.length && value.length <= CLIENT_REQUEST_ID_MAX ? ', including a space or non-ASCII character' : ''}` : `this one is ${value === null ? 'null' : `a ${typeof value}`}`;+ throw new OperationError('invalid_params', `request_id must be 1 to ${CLIENT_REQUEST_ID_MAX} printable ASCII characters with no spaces (${actual}).`,+ 'Omit request_id, or send an id you reuse only to retry the same write, for example "remember-acme-example-1".');}- return value.toLowerCase();+ return clientRequestUuid(value);+}++/** The id the client sent when it is not already a UUID; receipts echo it as `client_request_id`. */+export function clientRequestIdOf(value: unknown): string | undefined {+ return typeof value === 'string' && !isWriteRequestId(value) && parseWriteRequestId(value) ? value : undefined;}/** Syntax only; the coordinator checks the revision under its mutation lock. */diff --git a/src/core/persistence/types.ts b/src/core/persistence/types.tsindex 7378d7435b..d6e38af8eb 100644--- a/src/core/persistence/types.ts+++ b/src/core/persistence/types.ts@@ -38,6 +38,8 @@ export interface WriteDiagnostic {export interface WriteReceipt {request_id: string;+ /** F6: the client's non-UUID request_id when it sent one; request_id is its canonical UUIDv5. */+ client_request_id?: string;state: WriteRequestState;/** Milliseconds until polling is useful; null for terminal outcomes. */retry_after_ms: number | null;@@ -100,6 +102,7 @@ export function isWriteReceipt(value: unknown): value is WriteReceipt {const retry = value.retry_after_ms;if (retry !== null && (typeof retry !== 'number' || !Number.isSafeInteger(retry) || retry < 0)) return false;if (isTerminalWriteState(value.state as WriteRequestState) && retry !== null) return false;+ if (value.client_request_id !== undefined && (typeof value.client_request_id !== 'string' || !value.client_request_id)) return false;if (value.revision !== undefined && (typeof value.revision !== 'string' || !value.revision)) return false;if (value.compacted !== undefined && typeof value.compacted !== 'boolean') return false;if (value.outcome !== undefined && !isRecord(value.outcome)) return false;@@ -131,6 +134,7 @@ export function admittedPendingReceipt(envelope: unknown): WriteReceipt | null {export function publicWriteReceipt(receipt: WriteReceipt): WriteReceipt {return {request_id: receipt.request_id,+ ...(receipt.client_request_id !== undefined ? { client_request_id: receipt.client_request_id } : {}),state: receipt.state,retry_after_ms: receipt.retry_after_ms,...(receipt.revision !== undefined ? { revision: receipt.revision } : {}),diff --git a/src/core/persistence/verb-errors.ts b/src/core/persistence/verb-errors.tsindex ab275e0102..c3c148b321 100644--- a/src/core/persistence/verb-errors.ts+++ b/src/core/persistence/verb-errors.ts@@ -142,6 +142,7 @@ export async function runMemoryWrite<T>(run: () => Promise<T>): Promise<T> {const diagnostic = error.code === 'source_changed' ? writeFailureDiagnostic(error.code, error.message) : null;const frozen = verbError(code,diagnostic?.message ?? error.message,diagnostic?.suggestion ?? error.suggestion ?? 'Inspect writer status before retrying.');if (diagnostic) frozen.detail = diagnostic.reason;+ if (error.code === 'idempotency_conflict' && error.fix) frozen.fix = error.fix;if (isWriteErrorCode(error.code)) frozen.writeError=error.code;throw frozen;}diff --git a/src/core/remember-batch.ts b/src/core/remember-batch.tsindex 3ddeadb026..0a1d56da3d 100644--- a/src/core/remember-batch.ts+++ b/src/core/remember-batch.ts@@ -21,6 +21,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';export const REMEMBER_BATCH_MAX = 20;const ITEM_KEYS = new Set(['fact', 'provenance', 'entity', 'infer_entity', 'kind', 'ttl', 'visibility', 'replaces']);@@ -76,11 +77,14 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,}}if (ctx.dryRun) return { dry_run: true, action: 'remember', items: normalized.length, protocol_version: 1 };- const requestId = typeof p.request_id === 'string' && p.request_id ? p.request_id : randomUUID();+ // F6: child ids derive from the root string the client sent (as before the upgrade), so an accepted batch replays to the same receipts.+ const rootId = typeof p.request_id === 'string' && p.request_id ? p.request_id : randomUUID();+ const requestId = parseWriteRequestId(rootId)!;+ const clientRequestId = clientRequestIdOf(rootId);const results: BatchItemResult[] = [];const hints = new Set<string>();for (const [index, item] of normalized.entries()) {- const child = childRequestId(requestId, index);+ const child = childRequestId(rootId, index);try {const out = await single(ctx, { ...item, request_id: child }) as Record<string, unknown>;// Compact per-item receipt: a batch lands in the agent's context, so it carries what the agent acts on, not the full single-fact envelope.@@ -102,6 +106,7 @@ export async function runRememberBatch(ctx: OperationContext, p: Record<string,return {protocol_version: 1,request_id: requestId,+ ...(clientRequestId ? { client_request_id: clientRequestId } : {}),items: results,saved: results.length - failed,failed,diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex cfca332ad7..400363b174 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -219,6 +219,7 @@ import { v215 } from './v215-facts-attributed-to.ts';import { v216 } from './v216-chronicle-campaign-stamps.ts';import { v217 } from './v217-persistence-request-claim-phase.ts';import { v218 } from './v218-purge-legacy-worktree-manifest-files.ts';+import { v219 } from './v219-persistence-client-request-id.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -436,4 +437,5 @@ export const MIGRATIONS: Migration[] = [v216,v217,v218,+ v219,];diff --git a/src/core/schema-migrations/v219-persistence-client-request-id.ts b/src/core/schema-migrations/v219-persistence-client-request-id.tsnew file mode 100644index 0000000000..af456f4093--- /dev/null+++ b/src/core/schema-migrations/v219-persistence-client-request-id.ts@@ -0,0 +1,18 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(); see docs/ENGINES.md+// ("Canonical schema sources") for when schema.sql or a TS fragment also changes.+//+// F6 (Cat 40 Hard): a write op accepts any opaque request_id and journals the+// deterministic UUIDv5 it maps to. persistence_requests gains client_request_id,+// the string the client sent, stored outside the intent digest so receipts echo+// it after a restart or compaction. Column-only and nullable (NULL when the+// client sent a UUID or nothing); like v198 it is migration-created on PGLite+// and no index references it (lookups map the string to its UUID first).+export const v219: Migration = {+ version: 219,+ name: 'persistence_client_request_id',+ idempotent: true,+ sql: `+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS client_request_id text;`,+};diff --git a/test/e2e/persistence-client-request-id-postgres.test.ts b/test/e2e/persistence-client-request-id-postgres.test.tsnew file mode 100644index 0000000000..dc75694151--- /dev/null+++ b/test/e2e/persistence-client-request-id-postgres.test.ts@@ -0,0 +1,59 @@+/**+ * F6 engine parity on Postgres: migration v219 adds persistence_requests.client_request_id+ * (nullable text) on an upgraded brain, and a write sent with a non-UUID request_id+ * journals its UUIDv5 with the client string, replays, reads by either id, refuses reuse+ * for a different write and keeps the string through compaction. Zero model calls.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { hasDatabase, runMigrationsUpTo, setConfigVersion, setupDB, teardownDB } from './helpers.ts';+import type { PostgresEngine } from '../../src/core/postgres-engine.ts';+import { dispatchToolCall } from '../../src/mcp/dispatch.ts';+import { configureGateway, resetGateway } from '../../src/core/ai/gateway.ts';+import { disposePersistenceConsumer } from '../../src/core/persistence/service.ts';+import { compactWriteReceipts } from '../../src/core/persistence/journal.ts';+import { clientRequestUuid } from '../../src/core/persistence/preconditions.ts';++const RUN = hasDatabase();+const d = RUN ? describe : describe.skip;+let engine: PostgresEngine;++async function call(name: string, params: Record<string, unknown>) {+ const res = await dispatchToolCall(engine, name, params, { remote: true, transport: 'stdio', surface: 'starter', takesHoldersAllowList: ['world'], sourceId: 'default' });+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}+const page = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;++d('client request ids on Postgres', () => {+ beforeAll(async () => { engine = await setupDB(); }, 120_000);+ afterAll(async () => { resetGateway(); await disposePersistenceConsumer(engine); await teardownDB(); });+ beforeEach(() => { configureGateway({ env: {} } as never); });++ test('v219 adds a nullable text column on an upgraded brain', async () => {+ await engine.executeRaw('ALTER TABLE persistence_requests DROP COLUMN IF EXISTS client_request_id');+ await setConfigVersion(215);+ await runMigrationsUpTo(engine, 219);+ const [column] = await engine.executeRaw<{ data_type: string; is_nullable: string }>(+ "SELECT data_type,is_nullable FROM information_schema.columns WHERE table_name='persistence_requests' AND column_name='client_request_id'");+ expect(column).toEqual({ data_type: 'text', is_nullable: 'YES' });+ });++ test('a string id journals its UUIDv5, replays, reads by either id, refuses other intent and survives compaction', async () => {+ const id = `pg-put-notes-${Date.now()}`;+ const uuid = clientRequestUuid(id);+ const first = await call('put_page', { slug: `notes/${id}`, content: page('Postgres one'), request_id: id });+ expect(first.isError).toBe(false);+ expect(first.body).toMatchObject({ request_id: uuid, client_request_id: id, state: 'committed' });+ const replay = await call('put_page', { slug: `notes/${id}`, content: page('Postgres one'), request_id: id });+ expect(replay.body).toMatchObject({ request_id: uuid, client_request_id: id, revision: first.body.revision });+ for (const request_id of [id, uuid]) {+ expect((await call('get_write_request', { request_id })).body).toMatchObject({ request_id: uuid, client_request_id: id, state: 'committed' });+ }+ const reuse = await call('put_page', { slug: `notes/${id}`, content: page('Postgres two'), request_id: uuid });+ expect(reuse.body).toMatchObject({ code: 'idempotency_conflict', message: 'This request_id was used for a different write; send a new one or omit it.' });++ await engine.executeRaw("UPDATE persistence_requests SET completed_at=now()-interval '400 days' WHERE request_id=$1::uuid", [uuid]);+ await engine.executeRaw("UPDATE persistence_effects SET state='committed' WHERE request_id IN (SELECT id FROM persistence_requests WHERE request_id=$1::uuid)", [uuid]);+ expect(await compactWriteReceipts(engine, 1)).toBeGreaterThanOrEqual(1);+ expect((await call('get_write_request', { request_id: id })).body).toMatchObject({ client_request_id: id, compacted: true });+ });+});diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 0b4797f8d3..118c5badbf 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -2576,7 +2576,8 @@"37 consumer_host_id uuid/uuid NULL","38 published_at timestamp with time zone/timestamptz NULL","39 error_detail jsonb/jsonb NULL",- "40 claim_phase jsonb/jsonb NULL"+ "40 claim_phase jsonb/jsonb NULL",+ "41 client_request_id text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex 85f3853052..3332c266ca 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -2576,7 +2576,8 @@"37 consumer_host_id uuid/uuid NULL","38 published_at timestamp with time zone/timestamptz NULL","39 error_detail jsonb/jsonb NULL",- "40 claim_phase jsonb/jsonb NULL"+ "40 claim_phase jsonb/jsonb NULL",+ "41 client_request_id text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex d924bb5400..5588907f6e 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -2572,7 +2572,8 @@"37 consumer_host_id uuid/uuid NULL","38 published_at timestamp with time zone/timestamptz NULL","39 error_detail jsonb/jsonb NULL",- "40 claim_phase jsonb/jsonb NULL"+ "40 claim_phase jsonb/jsonb NULL",+ "41 client_request_id text/text NULL"],"flags": "relkind=r rls=true force_rls=false"},diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 1fd814aa2b..0145581264 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 208759,- "stdoutSha256": "5de3a39404e4ab9c60d0a87de666fadafb6e96795bc53031c1507238e64787ad",+ "stdoutBytes": 208738,+ "stdoutSha256": "f0d7ddb98466882484ff212040f7970e921989f074683aae476be22ad75b2ee0","toolNames": ["remember","entity",@@ -238,7 +238,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"source_id": {@@ -345,7 +345,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"semantic_review": {@@ -462,7 +462,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -524,7 +524,7 @@"type": "boolean"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -636,7 +636,7 @@"type": "boolean"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -731,7 +731,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -833,7 +833,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -855,7 +855,7 @@"scope": "write"},{- "description": "Write up to 50 complete Markdown pages (8 MB total) in one call; use instead of put_page for more than 3 pages. Each page replaces its whole page, like put_page. Keep one request_id UUID per batch: replaying the identical call never writes twice, and put_pages with ONLY request_id reports progress without resending content. Waits up to wait_ms (default 25000) for commits; follow the returned `next`. Needs put_page permission.",+ "description": "Write up to 50 complete Markdown pages (8 MB total) in one call; use instead of put_page for more than 3 pages. Each page replaces its whole page, like put_page. Keep one request_id per batch: replaying the identical call never writes twice, and put_pages with ONLY request_id reports progress without resending content. Waits up to wait_ms (default 25000) for commits; follow the returned `next`. Needs put_page permission.","idempotent": true,"local_only": false,"mutating": true,@@ -904,7 +904,7 @@"type": "array"},"request_id": {- "description": "Batch UUID; reuse it to replay or poll.",+ "description": "Batch id; reuse only to replay or poll.","type": "string"},"source_id": {@@ -936,7 +936,7 @@"schema": {"properties": {"request_id": {- "description": "The UUID you sent with the write.",+ "description": "The id you sent, or the receipt's.","type": "string"}},@@ -993,7 +993,7 @@"schema": {"properties": {"request_id": {- "description": "The UUID you sent with the write.",+ "description": "The id you sent, or the receipt's.","type": "string"}},@@ -1558,7 +1558,7 @@"schema": {"properties": {"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -1593,7 +1593,7 @@"schema": {"properties": {"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -2012,7 +2012,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -2191,7 +2191,7 @@"type": "boolean"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"slug": {@@ -4075,7 +4075,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"since": {@@ -4128,7 +4128,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"row_num": {@@ -4199,7 +4199,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"resolved_by": {@@ -4276,7 +4276,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"row_num": {@@ -4329,7 +4329,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"},"row_num": {@@ -5389,7 +5389,7 @@"type": "boolean"},"request_id": {- "description": "UUID; retry with it on timeout. Managed extraction returns durable receipts; when omitted, each call gets a new UUID. Unmanaged extraction retains its legacy non-journaled behavior.",+ "description": "Optional; reuse only to retry. Managed extraction returns durable receipts; when omitted, each call gets a new UUID. Unmanaged extraction retains its legacy non-journaled behavior.","type": "string"},"session_id": {@@ -5635,7 +5635,7 @@"type": "string"},"request_id": {- "description": "UUID; retry with it on timeout.",+ "description": "Optional; reuse only to retry.","type": "string"}},diff --git a/test/persistence-client-request-id.test.ts b/test/persistence-client-request-id.test.tsnew file mode 100644index 0000000000..882d503178--- /dev/null+++ b/test/persistence-client-request-id.test.ts@@ -0,0 +1,248 @@+/**+ * F6 (Cat 40 Hard): write ids any agent can send. A write op's request_id may be any+ * 1-128 printable ASCII string; a non-UUID maps to a deterministic UUIDv5 under one+ * fixed namespace, responses keep request_id as that UUID and echo the client's string+ * as client_request_id (stored outside the intent digest, kept through restart and+ * compaction), and the receipt helpers accept either id.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';+import { LEGACY_EMBEDDING_CONFIG } from './helpers/legacy-embedding-config.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { compactWriteReceipts } from '../src/core/persistence/journal.ts';+import { childRequestId } from '../src/core/remember-batch.ts';+import { CLIENT_REQUEST_ID_MAX, clientRequestIdOf, clientRequestUuid, parseWriteRequestId } from '../src/core/persistence/preconditions.ts';++const ID = 'remember-acme-example-1';+const ID_UUID = 'ef1eabdc-3cd7-523b-934a-f6e477fe2211';+const CONFLICT = 'This request_id was used for a different write; send a new one or omit it.';+let engine: PGLiteEngine;++async function callOn(target: PGLiteEngine, name: string, params: Record<string, unknown>) {+ // The Cat 40 serve path: `gbrain serve --surface starter` over stdio.+ const res = await dispatchToolCall(target, name, params, { remote: true, transport: 'stdio', surface: 'starter', takesHoldersAllowList: ['world'], sourceId: 'default' });+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}+const call = (name: string, params: Record<string, unknown>) => callOn(engine, name, params);+async function local(name: string, params: Record<string, unknown>) {+ const res = await dispatchToolCall(engine, name, params, { remote: false });+ return { isError: res.isError === true, body: JSON.parse(res.content[0]!.text!) as Record<string, any> };+}+const page = (title: string) => `---\ntitle: ${title}\ntype: note\n---\n# ${title}\n\nBody of ${title}.\n`;+const remember = (fact: string, request_id?: string) =>+ call('remember', { fact, provenance: 'test', entity: 'crm/acme-example', ...(request_id !== undefined ? { request_id } : {}) });++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 60_000);+afterAll(async () => { resetGateway(); await engine.disconnect(); });+beforeEach(async () => {+ await disposePersistenceConsumer(engine);+ await resetPgliteState(engine);+ configureGateway({ ...LEGACY_EMBEDDING_CONFIG, env: {} });+ await local('put_page', { slug: 'crm/acme-example', content: '---\ntitle: Acme Example\ntype: company\n---\n# Acme Example\n\nA company.\n' });+});++describe('request_id normalization', () => {+ test('a non-UUID maps to its RFC 4122 UUIDv5; a UUID passes through; uppercase UUIDs keep their identity', () => {+ expect(parseWriteRequestId(ID)).toBe(ID_UUID);+ expect(parseWriteRequestId('a')).toBe('14c7da2e-51c2-50fc-b390-2d6941235ec7');+ expect(parseWriteRequestId('x'.repeat(CLIENT_REQUEST_ID_MAX))).toBe('ba100e41-aa89-5d75-8d67-4adc9af858a2');+ const uuid = randomUUID();+ expect(parseWriteRequestId(uuid)).toBe(uuid);+ expect(parseWriteRequestId(uuid.toUpperCase())).toBe(uuid);+ expect(clientRequestIdOf(uuid.toUpperCase())).toBeUndefined();+ expect(clientRequestIdOf(ID)).toBe(ID);+ expect(parseWriteRequestId(undefined)).toBeUndefined();+ });++ test('invalid ids name the limits, the actual length and a valid example', () => {+ for (const [value, actual] of [['', 'this one has 0 characters'], ['x'.repeat(129), 'this one has 129 characters'],+ ['two words', 'this one has 9 characters, including a space or non-ASCII character'], ['café-1', 'this one has 6 characters'], [42, 'this one is a number'], [null, 'this one is null']] as const) {+ let error: any;+ try { parseWriteRequestId(value); } catch (e) { error = e; }+ expect(error?.code).toBe('invalid_params');+ expect(error.message).toContain('request_id must be 1 to 128 printable ASCII characters with no spaces');+ expect(error.message).toContain(actual);+ expect(error.suggestion).toContain('"remember-acme-example-1"');+ }+ });++ test('distinct ids never collide in the test set, and no mapped id equals its own input', () => {+ const seen = new Map<string, string>();+ for (let i = 0; i < 20_000; i++) {+ for (const id of [`r${i}`, `R${i}`, `remember-${i}`, `${i}`]) {+ const mapped = clientRequestUuid(id);+ expect(seen.get(mapped) ?? id).toBe(id);+ seen.set(mapped, id);+ }+ }+ expect(seen.size).toBe(80_000);+ });+});++describe('write ops with a client request_id', () => {+ test('the same non-UUID replays to the same receipt; get_write_request finds it by the string and by the UUID', async () => {+ const first = await remember('Alice Example leads procurement at Acme Example.', ID);+ expect(first.isError).toBe(false);+ expect(first.body).toMatchObject({ status: 'inserted', request_id: ID_UUID, client_request_id: ID, state: 'committed' });+ const replay = await remember('Alice Example leads procurement at Acme Example.', ID);+ expect(replay.body).toMatchObject({ id: first.body.id, status: 'inserted', request_id: ID_UUID, client_request_id: ID });+ const [{ n }] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM facts");+ expect(Number(n)).toBe(1);+ for (const request_id of [ID, ID_UUID, ID_UUID.toUpperCase()]) {+ const receipt = await call('get_write_request', { request_id });+ expect(receipt.isError).toBe(false);+ expect(receipt.body).toMatchObject({ request_id: ID_UUID, client_request_id: ID, state: 'committed', operation: 'remember' });+ }+ const listed = await call('list_write_requests', {});+ expect(listed.body.requests.find((r: any) => r.request_id === ID_UUID)).toMatchObject({ client_request_id: ID });+ const [row] = await engine.executeRaw<{ client_request_id: string; intent: Record<string, unknown> }>(+ 'SELECT client_request_id,intent FROM persistence_requests WHERE request_id=$1::uuid', [ID_UUID]);+ expect(row!.client_request_id).toBe(ID);+ expect(JSON.stringify(row!.intent)).not.toContain(ID);+ });++ test('replaying by the canonical UUID returns the same receipt; a UUID sent as such has no client_request_id', async () => {+ const first = await remember('Alice Example prefers async updates.', ID);+ const byUuid = await remember('Alice Example prefers async updates.', ID_UUID);+ expect(byUuid.body).toMatchObject({ id: first.body.id, request_id: ID_UUID, client_request_id: ID });+ const upper = randomUUID().toUpperCase();+ const plain = await remember('Alice Example joined in 2025.', upper);+ expect(plain.body.request_id).toBe(upper.toLowerCase());+ expect(plain.body.client_request_id).toBeUndefined();+ expect((await remember('Alice Example joined in 2025.', upper.toLowerCase())).body.id).toBe(plain.body.id);+ });++ test('reuse for a different write is refused by the string and by the UUID (remember keeps its frozen shape)', async () => {+ await remember('Alice Example works remotely.', ID);+ for (const request_id of [ID, ID_UUID]) {+ const reuse = await remember('Alice Example works from the office.', request_id);+ expect(reuse.isError).toBe(true);+ expect(reuse.body).toMatchObject({ code: 'invalid_params', write_error: 'idempotency_conflict', message: CONFLICT });+ expect(reuse.body.fix).toMatchObject({ next: 'run', mcp: { tool: 'get_write_request', arguments: { request_id: ID } } });+ }+ await call('put_page', { slug: 'notes/reuse', content: page('Reuse one'), request_id: 'page-write-1' });+ const pageReuse = await call('put_page', { slug: 'notes/reuse', content: page('Reuse two'), request_id: 'page-write-1' });+ expect(pageReuse.body).toMatchObject({ code: 'idempotency_conflict', message: CONFLICT });+ expect(pageReuse.body.fix.next).toBe('run');+ });++ test('a lost reply is recovered by replaying with the string or reading by the UUID', async () => {+ const id = 'put-notes-lost-reply';+ const first = await call('put_page', { slug: 'notes/lost', content: page('Lost reply'), request_id: id });+ expect(first.isError).toBe(false);+ expect(first.body).toMatchObject({ request_id: clientRequestUuid(id), client_request_id: id, state: 'committed' });+ const replay = await call('put_page', { slug: 'notes/lost', content: page('Lost reply'), request_id: id });+ expect(replay.body).toMatchObject({ request_id: first.body.request_id, revision: first.body.revision, client_request_id: id });+ expect((await call('get_write_request', { request_id: clientRequestUuid(id) })).body).toMatchObject({ state: 'committed', client_request_id: id });+ });++ test('a pending write is read and cancelled by the string or the UUID', async () => {+ // Hold every claim of notes/pending so the write stays queued.+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION f6_hold_claim() RETURNS trigger AS $$+ BEGIN IF NEW.state = 'running' AND NEW.slug LIKE 'notes/pending%' THEN RETURN NULL; END IF; RETURN NEW; END $$ LANGUAGE plpgsql`);+ await engine.executeRaw('CREATE TRIGGER f6_hold_claim BEFORE UPDATE ON persistence_requests FOR EACH ROW EXECUTE FUNCTION f6_hold_claim()');+ try {+ for (const [slug, id, cancelBy] of [['notes/pending-a', 'pending-by-string', 'string'], ['notes/pending-b', 'pending-by-uuid', 'uuid']] as const) {+ const accepted = await call('put_page', { slug, content: page(slug), request_id: id, wait_ms: 0 });+ expect(accepted.isError).toBe(true);+ expect(accepted.body).toMatchObject({ code: 'write_pending', write_request: { request_id: clientRequestUuid(id), client_request_id: id, state: 'queued' } });+ for (const request_id of [id, clientRequestUuid(id)]) {+ expect((await call('get_write_request', { request_id })).body).toMatchObject({ state: 'queued', client_request_id: id });+ }+ const cancelled = await call('cancel_write_request', { request_id: cancelBy === 'string' ? id : clientRequestUuid(id) });+ expect(cancelled.body).toMatchObject({ request_id: clientRequestUuid(id), client_request_id: id, state: 'cancelled' });+ const replay = await call('put_page', { slug, content: page(slug), request_id: id, wait_ms: 0 });+ expect(replay.body.write_request).toMatchObject({ request_id: clientRequestUuid(id), client_request_id: id, state: 'cancelled' });+ }+ } finally {+ await engine.executeRaw('DROP TRIGGER IF EXISTS f6_hold_claim ON persistence_requests');+ await engine.executeRaw('DROP FUNCTION IF EXISTS f6_hold_claim()');+ }+ });++ test('principals are independent: the same string from two callers is two writes', async () => {+ const id = 'shared-client-id';+ const remote = await call('put_page', { slug: 'notes/remote', content: page('Remote'), request_id: id });+ const cli = await local('put_page', { slug: 'notes/cli', content: page('Cli'), request_id: id });+ expect(remote.isError).toBe(false);+ expect(cli.isError).toBe(false);+ expect(cli.body.request_id).toBe(remote.body.request_id);+ const rows = await engine.executeRaw<{ principal_kind: string; slug: string; client_request_id: string }>(+ 'SELECT principal_kind,slug,client_request_id FROM persistence_requests WHERE request_id=$1::uuid ORDER BY slug', [clientRequestUuid(id)]);+ expect(rows.map(r => [r.slug, r.client_request_id])).toEqual([['notes/cli', id], ['notes/remote', id]]);+ expect(new Set(rows.map(r => r.principal_kind)).size).toBe(2);+ });++ test('compaction keeps client_request_id, and the compacted receipt still replays', async () => {+ const first = await remember('Alice Example signs renewals.', ID);+ await engine.executeRaw("UPDATE persistence_requests SET completed_at=now()-interval '400 days' WHERE request_id=$1::uuid", [ID_UUID]);+ // Keyless brains leave the embedding effect queued; compaction retains receipts with unfinished effects.+ await engine.executeRaw("UPDATE persistence_effects SET state='committed' WHERE request_id=(SELECT id FROM persistence_requests WHERE request_id=$1::uuid)", [ID_UUID]);+ expect(await compactWriteReceipts(engine, 1)).toBeGreaterThanOrEqual(1);+ const receipt = await call('get_write_request', { request_id: ID });+ expect(receipt.body).toMatchObject({ request_id: ID_UUID, client_request_id: ID, compacted: true, state: 'committed' });+ const replay = await remember('Alice Example signs renewals.', ID);+ expect(replay.body).toMatchObject({ id: first.body.id, client_request_id: ID, compacted: true });+ });+});++describe('remember(items) with a non-UUID root', () => {+ test('children derive from the root string, so a batch accepted before the upgrade replays to the same receipts', async () => {+ const root = 'batch-legacy-root';+ const items = [{ fact: 'Alice Example owns the renewal.', provenance: 'test', entity: 'crm/acme-example' },+ { fact: 'Alice Example approves discounts.', provenance: 'test', entity: 'crm/acme-example' }];+ const first = await call('remember', { items, request_id: root });+ expect(first.body).toMatchObject({ request_id: clientRequestUuid(root), client_request_id: root, saved: 2, failed: 0 });+ expect(first.body.items.map((i: any) => i.request_id)).toEqual([childRequestId(root, 0), childRequestId(root, 1)]);+ // What an older server stored: the same child rows, without client_request_id.+ await engine.executeRaw('UPDATE persistence_requests SET client_request_id=NULL');+ const replay = await call('remember', { items, request_id: root });+ expect(replay.body.items).toEqual(first.body.items);+ expect(replay.body).toMatchObject({ request_id: clientRequestUuid(root), client_request_id: root, saved: 2 });+ for (const child of first.body.items) {+ expect((await call('get_write_request', { request_id: child.request_id })).body).toMatchObject({ request_id: child.request_id, state: 'committed' });+ }+ const [{ n }] = await engine.executeRaw<{ n: number }>("SELECT count(*)::int AS n FROM persistence_requests WHERE operation='remember'");+ expect(Number(n)).toBe(2);+ });+});++describe('restart', () => {+ let dir: string;+ let disk: PGLiteEngine | null = null;+ beforeAll(() => { dir = mkdtempSync(join(tmpdir(), 'gbrain-f6-restart-')); });+ async function reopen(): Promise<PGLiteEngine> {+ if (disk) { await disposePersistenceConsumer(disk); await disk.disconnect(); }+ disk = new PGLiteEngine();+ await disk.connect({ database_path: join(dir, 'brain.pglite') } as never);+ await disk.initSchema();+ return disk;+ }+ afterAll(async () => {+ if (disk) { await disposePersistenceConsumer(disk); await disk.disconnect(); }+ rmSync(dir, { recursive: true, force: true });+ });++ test('a write sent with a string id replays after the brain reopens', async () => {+ let brain = await reopen();+ await dispatchToolCall(brain, 'put_page', { slug: 'crm/acme-example', content: '---\ntitle: Acme Example\ntype: company\n---\n# Acme Example\n\nA company.\n' }, { remote: false });+ const fact = { fact: 'Alice Example renews in March.', provenance: 'test', entity: 'crm/acme-example', request_id: ID };+ const first = await callOn(brain, 'remember', fact);+ expect(first.body).toMatchObject({ client_request_id: ID, request_id: ID_UUID });+ brain = await reopen();+ const replay = await callOn(brain, 'remember', fact);+ expect(replay.body).toMatchObject({ id: first.body.id, client_request_id: ID, request_id: ID_UUID });+ expect((await callOn(brain, 'get_write_request', { request_id: ID })).body).toMatchObject({ client_request_id: ID, state: 'committed' });+ }, 60_000);+});diff --git a/test/persistence-receipt-operations.test.ts b/test/persistence-receipt-operations.test.tsindex e27d06bd0a..b78faab5c8 100644--- a/test/persistence-receipt-operations.test.ts+++ b/test/persistence-receipt-operations.test.ts@@ -258,6 +258,10 @@ describe('own-principal write receipt operations', () => {for (const params of [{ limit: 0 }, { limit: 101 }, { limit: 1.5 }, { source_id: '__all__' }, { before: '-1' }, { before: '9999999999999999999' }]) {await expect(call('list_write_requests', params)).rejects.toMatchObject({ code: 'invalid_params' });}- await expect(call('get_write_request', { request_id: '../other' })).rejects.toMatchObject({ code: 'invalid_params' });+ // F6: any 1-128 printable ASCII id is a client request id (mapped to its UUIDv5), so only ids outside that set refuse.+ for (const request_id of ['', 'two words', 'x'.repeat(129), 42]) {+ await expect(call('get_write_request', { request_id })).rejects.toMatchObject({ code: 'invalid_params' });+ }+ await expect(call('get_write_request', { request_id: '../other' })).rejects.toMatchObject({ code: 'not_found' });});});