Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a write naming no expected_revision for an existing page is revision_required, not revision_conflict (#5385)
garrytan708500ea12e2
diff --git a/docs/architecture/key-files/core-persistence.md b/docs/architecture/key-files/core-persistence.mdindex cf40cdac99..86a856b020 100644--- a/docs/architecture/key-files/core-persistence.md+++ b/docs/architecture/key-files/core-persistence.md@@ -56,6 +56,6 @@ Connector ingestion, item holds, checkpoint validation and the single-write fast- `src/core/persistence/unbound-source.ts` — #5254 policy for a Postgres page write to a filesystem source (`local_path`, or `sync.repo_path` for `default`) with default write-through and no worktree binding. `submitPageMutation` refuses `owner_unavailable` with `detail: unbound_source`, a `docs` pointer to `write-refusals.md#unbound-sources-on-postgres`, and a hint naming the filled `sources writer status`/`writer claim ... --admin-intent writer_claim --expected-state <admin_state>` bind command (host path only for trusted local callers) and, for `put_page` to a page without `source_path`, `gbrain config set persistence.unbound_write database_only`. That key (`refuse` default, validated by `config set`; any other stored value refuses) lets such a `put_page` admit with `databaseOnlyReason: 'unbound_source'`. Publication rechecks inside its transaction, after `authorizeStoredRequest` share-locks the source row, that the source is still unbound and the page still has no `source_path` (else `owner_unavailable`/`unbound_source`, hint rebuilt from the persisted message by `writeResponse`), then stamps `pages.database_only_reason='unbound_source'` (migration 177). After binding, `prepareFileTarget` keeps a stamped page with no file database-only (receipt `write_through.skipped: unbound_source` with a warning) and managed sync refuses to import a file at its path (`source_changed`, diagnostic reason `unbound_source`). PGLite keeps auto-claiming. Tests: `test/e2e/unbound-source-postgres.test.ts`, `test/persistence-unbound-source.test.ts`. See [persistence stalls](persistence-stalls.md).-- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot; exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.+- `src/core/persistence/{semantic,semantic-pages}.ts` — revision-bound semantic tag/timeline merges through the journal. Supported merges reprepare against a newer snapshot (`mayReprepare`: `revision_conflict` or, #5385 [R13], `revision_required`, both only when the caller named no `expected_revision`); exact timeline replay leaves canonical bytes, revision, versions and structured rows unchanged. The public timeline handler resolves durable replay before page-existence preflight, retaining original outcomes after page purge or recreation; fresh writes preserve same-source diagnostics. `page-state/projections.ts` completes sanitized text and page search vectors together, and installs delayed embeddings with UPDATE-only revision/chunk/text/index-context checks. New vectors receive the full provider:model captured before provider execution, and a runtime model switch invalidates the prepared indexing context. Metadata updates preserve the sanitized vector. Tests: `persistence-semantic-pages.test.ts`, `page-projection-concurrency.test.ts`.- `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).diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.mdindex ffa6d562fc..09d4039a25 100644--- a/docs/architecture/key-files/core-services-2.md+++ b/docs/architecture/key-files/core-services-2.md@@ -51,7 +51,7 @@ Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`- `src/core/ops/sources.ts` — `sources_remove` is confined to the caller's WRITE authority via `assertSourceInCallerWriteScope(ctx, id)` (context.ts): an untrusted caller may hard-remove only its own write source; a federated read grant naming a source does not make it removable; any other id answers `OperationError('not_found', 'Unknown source: <id>')`, byte-identical to a nonexistent source so the error is not an existence oracle. `sources_status` keeps the read-scope helper (`assertSourceInCallerScope`), so a federated grant can still diagnose a source it cannot remove. Trusted local CLI keeps the full operator view. Over HTTP every client carries a write source (registration default `default`) and its own `oauth_clients.source_id` row FK-RESTRICTs removing that source, so hard removal is effectively an operator action (`gbrain sources remove`); a source a remote `sources_admin` caller just created via `sources_add` stays outside its authority until the operator rescopes the client. There is no `sources_archive` op — archive lives in the CLI (`gbrain sources archive`). Pinned by `test/sources-mcp.test.ts` (federated-read-only id → not_found while status still answers; write-source id → removed; unbound → any; local → any; `remote: undefined` fail-closed) and `test/e2e/sources-remote-mcp.test.ts` (real server: not_found before AND after a read-grant widen; operator CLI completes; rescoping `--source` moves the authority).-- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: missing revision is create-only, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.+- `src/core/page-state/` — Canonical page concurrency foundation shared by both engines. `schema.ts` (migration 150) adds source incarnation UUIDs, logical page revisions, text-projection revisions, and persistent guards for absent pages. `guards.ts` locks sorted sources then page identities in an existing transaction; a transaction or savepoint never re-acquires a key it holds, which covers absent pages because the only pages INSERT runs after `putPage` takes the same guard (`test/e2e/page-guards-postgres.test.ts`); callers lock sources before authority/request/fact rows. `snapshot.ts` computes the normalized body/timeline fingerprints only for a page with fact withdrawals, page-subject purges or a source '*' purge marker (they feed only the withdrawal overlay), as `page-snapshot-batch.ts` does. `snapshot.ts` reads page/tags/withdrawals in one MVCC statement and applies withdrawals using database-normalized text. `transactions.ts` makes helper transaction APIs compose through savepoints. `versions.ts` records the complete canonical snapshot; `rename-alias.ts` records `slug_aliases(old -> new)` inside both engines' `updateSlug` transaction, repoints aliases that named the old slug and drops one spelled like the new slug; `moveSlugBindings` moves the page's facts (`entity_slug`, `source_markdown_slug`) and `page_aliases` in the same transaction, letting a purged page's leftovers at the new slug yield (`test/rename-slug-alias.test.ts`); `materialize.ts` persists only verified canonical overlay bytes without another logical revision. `types.ts` defines revision preconditions: no revision is create-only (an existing page refuses `revision_required`, #5385, its own code since the omission is the caller's and not a race), a stale revision or a page another writer created where an internal writer asserted none (`expectedRevision: null`) is `revision_conflict`, explicit force overwrites. Plain legacy `putPage` calls keep compatibility until their owning operation adopts the managed write protocol. `projection-schema.ts` (migration 153) invalidates unverified prior projections once and queues durable work; `projections.ts` rebuilds Markdown without a worktree/provider and installs only matching canonical revisions. Embedding installs also compare exact chunk identities/text. Source importers seal code/image projections; all read arms hide unsealed projections.- `src/core/page-state/projections.ts` — captures canonical revision, source incarnation, page identity, the complete raw chunk inventory and resolved indexing inputs before preparing derived work. Embedding reads require a current text seal; healing/rebuild capture can explicitly include unsealed pages. Projection installation compares its originating seal, chunk identities/text/source/completion state, chunker version and indexing context (including stored corpus generation) under the page guard before replacing any row. A same-revision re-chunk may replace the snapshot it actually captured; a delayed older installation cannot discard newer chunks or vectors. Rebuild also rechecks its queued job before capture so a completed job from an old listing stays completed. Chunkless healing sanitizes complete body/timeline fences before splitting, preserving withdrawn history in direct page reads while excluding it from retrieval. Tests: `page-projection-origin.test.ts`, `page-projection-vector-preservation.test.ts` (PGLite and isolated Postgres), `embed-stale-chunkless-pages.serial.test.ts` (public healing entry). Shared `markdown-chunks.ts` and `code-chunks.ts` preserve fenced code and source-language metadata. A preserving rebuild keeps a vector only when its `content_chunks.embedding_input_hash` (`src/core/embedding-input-hash.ts`) equals one recomputed from the current page, or, with no recorded hash, when the page is non-contextual and the legacy model/text-hash checks pass; a contextual chunk without provenance is nulled once. `installPageEmbeddings` records the hash in the vector's UPDATE (the plain re-embed tier by default, or the caller's `built` tier and corpus generation), and `stampEmbeddingInputs` does the same for full imports. `resealSafeChunks` re-seals a page below the safe-chunk fence from its unchanged body with no canonical write; `projectionBelowSafeFence` is its predicate. Tests add `projection-embedding-input-hash.test.ts` and `safe-chunk-reseal.test.ts`. It replaces outgoing code edges without deleting incoming edges to retained chunks and clears backfill watermarks. Failed jobs rotate with a retained diagnostic; successful drain refreshes planner statistics. `rebuildPendingPageProjections(engine, limit, { deadlineMs, now, notAfter, retryCooldown, onFailure })` (#5401) checks an injectable clock between pages, bounds a run to rows queued at or before its start (`notAfter`, cast from text in SQL so microseconds survive the driver), applies the 30 s `rebuild_failed` cooldown for the resident, and treats a lock or snapshot error as that page's failure instead of aborting the batch; `projectionBacklog` returns counts only (pending, failed, oldest age) for the drain command and the resident's `projection_status` IPC reply. A same-revision conflict throws `PageProjectionConflictError` naming the fields that changed (`text_projection_revision`, `chunk_digest`, `indexing_context`), the slug and source; `retryProjectionConflict(attempt)` re-runs an attempt that captures a fresh snapshot at most three more times with jitter, then rethrows (`page_projection_conflict` on the wire). Tests: `page-projection-origin.test.ts` (resident rebuild race, two-writer progress, exhausted-retry CLI/JSON output).- `src/core/page-state/credential-reseal.ts` + `src/core/schema-migrations/v189-pages-credential-projection-pending.ts` + `src/commands/doctor/checks/credential-projection.ts` — the targeted re-chunk of pages indexed before the credential-safe projection. Schema migration v187 (on the first connect after upgrade) sets `text_projection_revision = NULL` on every live markdown/code page whose `compiled_truth` or `timeline` matches `-----(BEGIN|END) [A-Z ]*PRIVATE KEY-----` and upserts a `page_projection_jobs` row (reason `credential_projection`), so the current-text-projection seal withholds their old chunks from every retrieval path, local and remote (code-walk `hydrateChunks` in `search/two-pass.ts` applies the same filter). The marker literal is frozen as shipped. `credentialProjectionPending(engine, sourceIds?)` counts pending pages in active sources as `rebuildable` and `kept` (code pages with no `frontmatter.file` or `source_path`, which wait for their importer). `resealCredentialProjections` re-seals each rebuildable page from its unchanged body through `resealSafeChunks` (the `repair safe-chunks` installer), one page per transaction, with no page write, journal admission or provider call; vectors of unchanged chunk text are kept and re-chunked key chunks wait for `gbrain embed --stale`; a revision conflict counts as superseded, a failure prints the retry command and leaves the page withheld. The doctor check `credential_projection_pending` (a `WAVE_CHECKS` entry, `resolution: 'operator'`, brain category) reports `pages_pending` and `kept_pages` and warns while either is non-zero, naming `gbrain apply-migrations --yes --no-autopilot-install` (no provider calls), then `gbrain embed --stale`, and the re-import for kept code pages; a read error is `warn` with unknown health.diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex 2ccff6d661..37e606ee84 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -2374,7 +2374,7 @@ Reasons: `rename_source_changed`.| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable ||---|---|---|---|---|---|---|-| Review the current policy and supply its expected_policy_epoch before changing disclosure. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |+| The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it. | Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed. | Correct the request using the message above, then retry. Run: gbrain get --source '{source_id}' -- '{slug}' | agent | `repeat the read that failed` | 1 | no |### revision_unavailablediff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex a59a1fc1a7..d8cca115d9 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -85,7 +85,7 @@ a receipt can report has a row here.| Reason | Error code | What it means | Recovery || --- | --- | --- | --- || `writer_pool_capacity` | `writer_pool_capacity` | The canonical owner has no free publication slot right now; the write stays queued. | Wait and poll the receipt (`gbrain write-request <id>`). If it persists, check `gbrain sources writer status <source>`. |-| `revision_required` | `revision_required` | The operation must be bound to a revision you reviewed (for example `--if-version` or `expected_revision`), and none was given. | Preview first, then repeat with the revision the preview printed. |+| `revision_required` | `revision_required` | The operation must be bound to a revision you reviewed (for example `--if-version` or `expected_revision`), and none was given: a `put_page` of a page that already exists without `expected_revision` reports this since #5385 (earlier releases said `revision_conflict`). | Preview first, then repeat with the revision the preview printed. || `revision_conflict` | `revision_conflict` | The page changed after the revision this write was bound to. Nothing was overwritten. | Re-read the page, merge your change, and save with the new revision. || <a id="revision-backfill"></a>`revision_backfill_pending` | `revision_backfill_pending` | The page was written before page revisions existed (an upgrade from below schema v150) and the resumable revision backfill has not reached it, so it has no revision to bind to. Its revision reads as `backfill_pending`, never a UUID. Nothing was written. `gbrain doctor` reports the backfill as `revision_backfill` with the pending count and any failed rows by page. | Resume the backfill on the brain host with `gbrain apply-migrations --force-schema` (it prints its progress; `--yes` alone does not resume it once the schema is current). Rows that used all three attempts are no longer retried: run `gbrain repair orphan-children` to preview orphaned child rows and torn page bodies ([orphan children](repair.md#orphan-children)). || `idempotency_conflict` | `idempotency_conflict` | The `request_id` was already used for a different target, content or protocol. | Use a new `request_id` for a different write; reuse an ID only to replay the same write. |diff --git a/docs/protocol/MEMORY_VERBS_v1.md b/docs/protocol/MEMORY_VERBS_v1.mdindex 827c2a40d5..f098b993a2 100644--- a/docs/protocol/MEMORY_VERBS_v1.md+++ b/docs/protocol/MEMORY_VERBS_v1.md@@ -547,7 +547,11 @@ A pending write is a protocol `unavailable` error with a populated suggestion,`protocol_version: 1`, and optional `write_request` and `write_error` fields.It never returns a success `status` or `expired` value. `write_error` carriesthe detailed concurrency reason without changing the frozen protocol error-enum. A committed receipt retains the original memory-verb success fields.+enum. Its values branch three ways on revisions: `revision_required` (the page+exists and the write named no `expected_revision`: read it and resend),+`revision_conflict` (the named revision is stale: re-read and merge) and+`revision_backfill_pending` (resume the revision backfill). 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.@@ -641,6 +645,7 @@ Refusals name the edit and never include protected text:| `edit_protected_span` | `edit_index=<i>` | The text touches a takes or facts section; use the scoped operations. || `edit_invalid` | `edit_index=<i>` when one edit is malformed | Pass 1 to 50 `{old_text, new_text}` objects with non-empty `old_text`. || `revision_conflict` | `current_revision=<uuid>` | Read the page again, rebuild the edits, resend. |+| `revision_required` | — | The page exists and the call named no `expected_revision` (`put_page`; additive since #5385, formerly reported as `revision_conflict`). Read the page, then resend with its revision, or `force: true` for an intentional overwrite. |```json→ get_page {"slug": "projects/example", "include_content": true}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex c52f2f4a9d..d1312002d7 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -381,6 +381,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.157.0', text: 'A top-level call statement in a JavaScript, TypeScript, TSX, Python or Ruby file (a `describe(...)` / `it(...)` block, `app.use(...)`, `print(helper())`, `RSpec.describe ... do`) is now its own chunk, `symbol_type` `module` and `symbol_name` `__module__`, so the calls inside it get edges: `code-callers helper` lists the test body as `<file-basename>::__module__`. Files with such statements gain chunks, so the next `gbrain sync` walks each source once and re-chunks and re-embeds only its files in those five languages (priced by the cost gate as `grammar_drift`); `gbrain reindex-code` does the same now. Definition-only files keep their chunks and vectors.' },{ since: '0.60.157.0', text: 'The entity counters in `get_health` / `gbrain health` (`entity_page_count`, `link_coverage`, `timeline_coverage`, `most_connected`) and doctor\'s `graph_coverage` and `orphan_ratio` gates now count the page types the active schema pack declares with `primitive: entity` (`yc`, `civic` and `organization` included on gbrain-base; a custom pack\'s own entity types; `person` or `company` only while the pack does not reclassify them), resolved per source when sources carry their own pack. Brains whose entities are pack types move from 0 entities and `null` ratios to real numbers, and a doctor score can drop where coverage is low. A pack that does not load now reports `entity_types_status: pack_unavailable` with 0 entities and a `graph_coverage` warn instead of counting the old hardcoded list.' },{ since: '0.60.157.0', text: 'Dream `synthesize_concepts` now writes one concept page for spellings of a label that differ only by hyphens, underscores or dots (`network-effects`, `network_effects`, `networkeffects`): the spelling that already has a live `concepts/` page wins, otherwise the one most atoms use (a tie goes to the hyphenated form), and the other spellings redirect to it for that run without any page write. Two spellings that both already have live pages (`re-sign` / `resign`, `co-op` / `coop`) are kept apart; merging those stays the human redirect path (`merged_into` / `aliases`). Existing duplicate pages are not merged for you: `details.folded_spellings` on the phase receipt names each fold.' },+ { since: '0.60.157.0', text: 'A `put_page` (or `gbrain put`) of a page that already exists, sent without `expected_revision` or `force`, is now refused with its own code `revision_required` instead of `revision_conflict`; the message, the refusal and the fix (read the page, resend with its revision) are unchanged. A stale `expected_revision` is still `revision_conflict`. A client that switched on `revision_conflict` to decide between "re-read and merge" and "I forgot the precondition" can now branch on the code (#5385).' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex afa8c60013..fddaca2964 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -357,7 +357,7 @@ export const CODES = {response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and revision; resubmit against that revision with a new request_id.", requires_exclusive: false } },- revision_required: { class: 'caller', summary: "Review the current policy and supply its expected_policy_epoch before changing disclosure." },+ revision_required: { class: 'caller', summary: "The target already exists and the write named no revision: supply the expected revision read from the page (or the policy epoch) before replacing it.", why: "Without the revision the write cannot tell an intentional replacement from an overwrite of an edit it never saw; nothing was changed.", fix: { argv: ['gbrain', 'get', '--source', '{source_id}', '--', '{slug}'], mcp: { tool: 'get_page', arguments: { slug: '{slug}', source_id: '{source_id}' } }, consent: [], actor: 'agent', why: "Reads the current page and its revision; resubmit with that expected_revision (or force: true for an intentional overwrite).", requires_exclusive: false } },revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },diff --git a/src/core/page-state/types.ts b/src/core/page-state/types.tsindex 18da5d0902..aac927cf29 100644--- a/src/core/page-state/types.ts+++ b/src/core/page-state/types.ts@@ -2,7 +2,12 @@ import type { GetPageOpts, Page } from '../types.ts';/** Opaque logical revisions are independent of timestamps and filesystem hashes. */export interface PageMutationPrecondition {- expectedRevision?: string;+ /**+ * The revision the caller read, or `null` when it read no page and asserts the page is still absent (an internal+ * writer admitted against an empty slot). Omitted: no precondition was supplied, so an existing page refuses with+ * `revision_required` (#5385) instead of the `revision_conflict` a changed revision gets.+ */+ expectedRevision?: string | null;force?: boolean;}@@ -71,13 +76,21 @@ export interface PageSnapshot {globalPurges?: GlobalPurgeMarker;}+/**+ * The three revision refusals. `expectedRevision` is the caller's precondition: a revision (stale → `revision_conflict`),+ * `null` for an asserted-absent page another writer created (→ `revision_conflict`), or `undefined` when the caller+ * supplied none and the page exists (#5385 → `revision_required`: the caller's omission, not a race, so a client+ * can read the page and resubmit instead of treating it as contention).+ */export class PageRevisionConflictError extends Error {- readonly code: 'revision_conflict' | 'revision_backfill_pending' = 'revision_conflict';- constructor(readonly expectedRevision: string | null, readonly currentRevision: string | null) {+ readonly code: 'revision_conflict' | 'revision_required' | 'revision_backfill_pending';+ constructor(readonly expectedRevision: string | null | undefined, readonly currentRevision: string | null) {super(currentRevision === null ? 'The page no longer exists at the expected revision.'- : expectedRevision === null ? 'The page already exists; an expected revision is required.'+ : expectedRevision === undefined ? 'The page already exists; an expected revision is required.'+ : expectedRevision === null ? 'The page was created after it was read. Read its current revision before retrying.': 'The page changed after it was read. Read its current revision before retrying.');this.name = 'PageRevisionConflictError';+ this.code = expectedRevision === undefined && currentRevision !== null ? 'revision_required' : 'revision_conflict';}}@@ -99,12 +112,12 @@ export class RevisionBackfillPendingError extends PageRevisionConflictError {export function assertPageRevision(snapshot: Pick<PageSnapshot, 'revision'> | null, precondition: PageMutationPrecondition = {}): void {const { expectedRevision, force } = precondition;if (force !== undefined && typeof force !== 'boolean') throw new TypeError('force must be a boolean');- if (expectedRevision !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(expectedRevision)) {+ if (expectedRevision != null && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(expectedRevision)) {throw new TypeError('expectedRevision must be a UUID revision');}if (force && expectedRevision !== undefined) throw new TypeError('force and expectedRevision are mutually exclusive');if (force) return;if (snapshot?.revision === REVISION_BACKFILL_PENDING) throw new RevisionBackfillPendingError(expectedRevision ?? null);const current = snapshot?.revision ?? null;- if (current !== (expectedRevision?.toLowerCase() ?? null)) throw new PageRevisionConflictError(expectedRevision ?? null, current);+ if (current !== (expectedRevision?.toLowerCase() ?? null)) throw new PageRevisionConflictError(expectedRevision, current);}diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 623fe8fee3..a8ca266471 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -131,7 +131,7 @@ function requestError(error: unknown): PublicationFailure {const refusal = databaseRefusal(error);if (refusal) return refusal;const code = (error as { code?: string })?.code;- if (code === 'revision_conflict') {+ if (code === 'revision_conflict' || code === 'revision_required') {return { code, message: error instanceof Error && error.message ? error.message : 'The page changed after the supplied revision was read.' };}// #5216: the row still awaits its revision backfill; the error names the resume command.diff --git a/src/core/persistence/file-repair.ts b/src/core/persistence/file-repair.tsindex 9668ad8a8d..62852392cc 100644--- a/src/core/persistence/file-repair.ts+++ b/src/core/persistence/file-repair.ts@@ -318,7 +318,7 @@ export async function prepareManagedFileRepairMutation(engine: BrainEngine, row:const target = checkFile();const source = { sourceId: row.source_id };const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });- assertPageRevision(snapshot, p.expected_revision ? { expectedRevision: p.expected_revision } : {});+ assertPageRevision(snapshot, { expectedRevision: p.expected_revision ?? null }); // null: admitted against an absent page; still a revision_conflict if one appeared (#5385)if ((snapshot?.page.id ?? null) !== row.page_id || (snapshot?.page.source_path != null && snapshot.page.source_path !== p.sourcePath)) {throw opError('page_identity_changed', 'The repaired path no longer names the previewed page.',`Page ${row.slug} in source ${row.source_id} was replaced, removed, or now maps to a different file than ${p.sourcePath}, so repair request ${row.request_id} published nothing. Preview the repair again.`,diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.tsindex 97f31fec75..900a0ab213 100644--- a/src/core/persistence/import-prepare.ts+++ b/src/core/persistence/import-prepare.ts@@ -177,7 +177,7 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri{ fix: reimportFix(p.inputPath, row.source_id) });const source = { sourceId: row.source_id };const snapshot = screen ? screen.snapshot : await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });- assertPageRevision(snapshot, p.expected_revision ? { expectedRevision: p.expected_revision } : {});+ assertPageRevision(snapshot, { expectedRevision: p.expected_revision ?? null }); // null: admitted against an absent page; still a revision_conflict if one appeared (#5385)if ((snapshot?.page.id ?? null) !== row.page_id || snapshot?.page.source_path && snapshot.page.source_path !== p.sourcePath) {throw opError('page_identity_changed', 'The imported path no longer names the accepted page.',`Page ${row.slug} in source ${row.source_id} was replaced, removed, or now maps to a different file than ${p.sourcePath}, so import request ${row.request_id} published nothing. Read the page before importing the file again.`,diff --git a/src/core/persistence/semantic.ts b/src/core/persistence/semantic.tsindex 18002ad6da..892bff5f5c 100644--- a/src/core/persistence/semantic.ts+++ b/src/core/persistence/semantic.ts@@ -2,8 +2,12 @@ import type { WriteRequest } from './model.ts';export const SEMANTIC_PAGE_OPERATIONS: ReadonlySet<string> = new Set(['add_tag', 'remove_tag', 'add_timeline_entry', 'takes_add', 'takes_update', 'takes_supersede', 'takes_resolve', 'takes_remove', 'remember',]);-/** Recompute only supported merges; caller-supplied stale replacements remain conflicts. */+/**+ * Recompute only supported merges; caller-supplied stale replacements remain conflicts. #5385 [R13]: a merge submitted+ * without `expected_revision` meets the page as it is, so the missing-precondition code `revision_required` is as+ * recomputable as the mid-preparation `revision_conflict`; a stale supplied revision is neither.+ */export function mayReprepare(row: WriteRequest, error: { code?: string }): boolean {- return error.code === 'revision_conflict' && row.intent?.expected_revision === undefined+ return (error.code === 'revision_conflict' || error.code === 'revision_required') && row.intent?.expected_revision === undefined&& (SEMANTIC_PAGE_OPERATIONS.has(row.operation) || row.intent?.force === true);}diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.tsindex 6376ffc71b..698a2803f6 100644--- a/src/core/persistence/sync-prepare.ts+++ b/src/core/persistence/sync-prepare.ts@@ -418,7 +418,7 @@ export async function prepareManagedSyncMutation(unbounded: BrainEngine, row: Wrconst source = { sourceId: row.source_id };enterClaimStep(clock, 'page_snapshot', undefined, 'db');const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });- assertPageRevision(snapshot, p.expected_revision === null ? {} : { expectedRevision: p.expected_revision });+ assertPageRevision(snapshot, { expectedRevision: p.expected_revision }); // null asserts the admitted-absent page is still absent (#5385)const recordedOrigin = moved?.slug === row.slug ? moved.sourcePath : p.sourcePath!;const foreignOrigin = snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recordedOrigin, originScope, snapshot.page.slug);if ((snapshot?.page.id ?? null) !== row.page_id || (p.unownedDeletion ? !foreignOrigin : foreignOrigin)) {diff --git a/test/capture-op.test.ts b/test/capture-op.test.tsindex dbdb4945a5..230a7b78c2 100644--- a/test/capture-op.test.ts+++ b/test/capture-op.test.ts@@ -52,13 +52,15 @@ describe('capture op', () => {expect(page?.frontmatter?.captured_at).toBeDefined();// Same-ID replay retains the accepted target and timestamp. A fresh- // create-only request cannot silently replace that existing target.+ // create-only request cannot silently replace that existing target: since+ // #5385 the refusal is `revision_required` (the page exists and the call+ // named no expected_revision), no longer the stale-revision code.const again = parsed(await dispatchToolCall(engine, 'capture', { content, request_id }, { ...STDIO }));expect(again.slug).toBe(body.slug);expect(again.content_hash).toBe(body.content_hash);const fresh = await dispatchToolCall(engine, 'capture', { content: ` ${content}\r\n` }, { ...STDIO });expect(fresh.isError).toBe(true);- expect(parsed(fresh).write_error).toBe('revision_conflict');+ expect(parsed(fresh).write_error).toBe('revision_required');});test('type routes the default slug prefix (diary → life/diary/)', async () => {diff --git a/test/persistence-revision-conflict-message.test.ts b/test/persistence-revision-conflict-message.test.tsindex 06b7693bc5..a80867d989 100644--- a/test/persistence-revision-conflict-message.test.ts+++ b/test/persistence-revision-conflict-message.test.ts@@ -1,7 +1,8 @@/*** A conflicted coordinated write keeps PageRevisionConflictError's own* message, so a caller that never supplied expected_revision is not told its- * revision went stale (#5659).+ * revision went stale (#5659), and since #5385 it also gets its own code+ * (`revision_required`) while a stale revision stays `revision_conflict`.*/import { afterAll, beforeAll, expect, test } from 'bun:test';import { PGLiteEngine } from '../src/core/pglite-engine.ts';@@ -28,7 +29,8 @@ test('a missing expected_revision and a stale one report different conflicts', aconst missing = await dispatchToolCall(engine, 'put_page', { slug, content: page('second body') }, ctx);expect(missing.isError).toBe(true);- expect(body(missing)).toMatchObject({ write_error: 'revision_conflict',+ // #5385: the missing precondition is the caller's omission, not a race, so it carries its own code.+ expect(body(missing)).toMatchObject({ write_error: 'revision_required',message: 'The page already exists; an expected revision is required.' });const stale = await dispatchToolCall(engine, 'put_page', { slug, content: page('second body'),diff --git a/test/revision-required-5385.test.ts b/test/revision-required-5385.test.tsnew file mode 100644index 0000000000..d17ed3a84f--- /dev/null+++ b/test/revision-required-5385.test.ts@@ -0,0 +1,115 @@+/**+ * #5385 [R13]: a write that names no `expected_revision` for an existing page is `revision_required`, its own code,+ * while a stale supplied revision stays `revision_conflict`.+ *+ * Protects: a client that switches on the code can tell "I forgot the precondition: read the page and resubmit"+ * from "someone else moved the page". The semantic merges (`add_tag`, `remember`, a forced put) submitted without a+ * revision still converge through the coordinator's re-preparation (`mayReprepare` accepts the new code), and a+ * blind stale replacement is still refused and never retried. Internal writers that admitted a page as absent+ * (`expectedRevision: null`) keep `revision_conflict` when another writer created it, so the sync fault classes+ * never see the new code.+ * Fails when: the missing case reports `revision_conflict`, the stale case reports `revision_required`, or a+ * semantic merge without a revision stops converging.+ * Seams: `assertPageRevision`, `mayReprepare`, `dispatchToolCall` on a PGLite brain.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { assertPageRevision, PageRevisionConflictError, REVISION_BACKFILL_PENDING } from '../src/core/page-state/types.ts';+import { mayReprepare } from '../src/core/persistence/semantic.ts';+import { CODES } from '../src/core/error-registry.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';++const REV = '0f6d2f4a-9d6b-4c3e-8a1f-2b7c9d0e1f23';+const OTHER = '11111111-1111-1111-1111-111111111111';+const code = (run: () => void): string => { try { run(); } catch (e) { return (e as PageRevisionConflictError).code; } return 'ok'; };++describe('#5385 assertPageRevision', () => {+ test('no precondition on an existing page is revision_required; a stale or asserted-absent one is revision_conflict', () => {+ expect(code(() => assertPageRevision({ revision: REV }, {}))).toBe('revision_required');+ expect(code(() => assertPageRevision({ revision: REV }))).toBe('revision_required');+ expect(code(() => assertPageRevision({ revision: REV }, { expectedRevision: OTHER }))).toBe('revision_conflict');+ expect(code(() => assertPageRevision({ revision: REV }, { expectedRevision: null }))).toBe('revision_conflict');+ expect(code(() => assertPageRevision(null, { expectedRevision: REV }))).toBe('revision_conflict');+ expect(code(() => assertPageRevision(null, {}))).toBe('ok');+ expect(code(() => assertPageRevision(null, { expectedRevision: null }))).toBe('ok');+ expect(code(() => assertPageRevision({ revision: REV }, { expectedRevision: REV }))).toBe('ok');+ expect(code(() => assertPageRevision({ revision: REV }, { force: true }))).toBe('ok');+ expect(code(() => assertPageRevision({ revision: REVISION_BACKFILL_PENDING }, {}))).toBe('revision_backfill_pending');+ expect(code(() => assertPageRevision({ revision: REVISION_BACKFILL_PENDING }, { expectedRevision: REV }))).toBe('revision_backfill_pending');+ });++ test('each code keeps its own message', () => {+ expect(new PageRevisionConflictError(undefined, REV).message).toBe('The page already exists; an expected revision is required.');+ expect(new PageRevisionConflictError(null, REV).message).toBe('The page was created after it was read. Read its current revision before retrying.');+ expect(new PageRevisionConflictError(OTHER, REV).message).toBe('The page changed after it was read. Read its current revision before retrying.');+ expect(new PageRevisionConflictError(REV, null).message).toBe('The page no longer exists at the expected revision.');+ expect(new PageRevisionConflictError(REV, null).code).toBe('revision_conflict');+ });++ test('the registry names the fix: read the page', () => {+ const entry = CODES.revision_required;+ expect(entry.class).toBe('caller');+ expect(entry.fix?.mcp?.tool).toBe('get_page');+ expect(entry.fix?.argv?.[0]).toBe('gbrain');+ expect(entry.summary).toContain('expected revision');+ });+});++describe('#5385 mayReprepare [R13]', () => {+ const row = (operation: string, intent: Record<string, unknown>) => ({ operation, intent } as unknown as WriteRequest);+ test('a merge without a revision recomputes on either code; a supplied stale revision never does', () => {+ for (const c of ['revision_conflict', 'revision_required']) {+ expect(mayReprepare(row('add_tag', {}), { code: c })).toBe(true);+ expect(mayReprepare(row('remember', { fact: 'x' }), { code: c })).toBe(true);+ expect(mayReprepare(row('put_page', { force: true }), { code: c })).toBe(true);+ expect(mayReprepare(row('add_tag', { expected_revision: OTHER }), { code: c })).toBe(false);+ expect(mayReprepare(row('put_page', {}), { code: c })).toBe(false);+ }+ expect(mayReprepare(row('add_tag', {}), { code: 'revision_backfill_pending' })).toBe(false);+ });+});++describe('#5385 on a PGLite brain through the tool surface', () => {+ let engine: PGLiteEngine;+ const ctx = { remote: true, transport: 'stdio' as const, sourceId: 'default' };+ const page = (body: string) => `---\ntitle: Revision example\ntype: note\n---\n${body}`;+ const body = (result: { content: Array<{ text: string }> }) => JSON.parse(result.content[0].text);+ beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ await engine.setConfig('schema_pack', 'gbrain-base');+ });+ afterAll(async () => { await engine.disconnect(); });++ test('missing → revision_required with the get_page fix; stale → revision_conflict; force and the right revision write', async () => {+ const slug = 'notes/revision-required-example';+ expect((await dispatchToolCall(engine, 'put_page', { slug, content: page('first') }, ctx)).isError ?? false).toBe(false);+ const before = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;++ const missing = body(await dispatchToolCall(engine, 'put_page', { slug, content: page('second') }, ctx));+ expect(missing).toMatchObject({ write_error: 'revision_required' });+ expect(JSON.stringify(missing)).toContain('get_page');++ const stale = body(await dispatchToolCall(engine, 'put_page', { slug, content: page('second'), expected_revision: OTHER }, ctx));+ expect(stale).toMatchObject({ write_error: 'revision_conflict' });+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.revision).toBe(before.revision);++ const forced = await dispatchToolCall(engine, 'put_page', { slug, content: page('forced'), force: true, request_id: randomUUID() }, ctx);+ expect(forced.isError ?? false).toBe(false);+ const after = (await engine.readPageSnapshot(slug, { sourceId: 'default' }))!;+ expect(after.revision).not.toBe(before.revision);+ const bound = await dispatchToolCall(engine, 'put_page', { slug, content: page('third'), expected_revision: after.revision, request_id: randomUUID() }, ctx);+ expect(bound.isError ?? false).toBe(false);+ });++ test('semantic merges without a revision converge on an existing page (the retry path stays open)', async () => {+ const slug = 'notes/revision-required-merge';+ await dispatchToolCall(engine, 'put_page', { slug, content: page('prose') }, ctx);+ const results = await Promise.all(['a', 'b', 'c'].map((tag) => dispatchToolCall(engine, 'add_tag', { slug, tag: `tag-${tag}`, request_id: randomUUID() }, ctx)));+ for (const r of results) expect(r.isError ?? false).toBe(false);+ expect((await engine.readPageSnapshot(slug, { sourceId: 'default' }))!.tags).toEqual(['tag-a', 'tag-b', 'tag-c']);+ });+});