Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Merge origin/master (#7131) into capy/wave-b-followups; renumber placeholder migration v263 -> v264

garrytan13ed38951c58
diff --cc docs/architecture/canonical-writers.tsv
index 22c38e9506,0c5046da5c..2174ea2326
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@@ -83,7 -83,6 +83,7 @@@ src/core/facts/proposal-supersede.ts 4
src/core/facts/relink-publish.ts 2 coordinator #5836 facts relink (local CLI only, managed or not): the coordinator mutation relink_facts re-locks each pinned unlinked fact, moves linked rows onto their entity fence positions (and retires exact duplicates expired and detached) ahead of the page's canonical projection in the same publication and records the attempt and conflict-sweep handoff in that transaction.
src/core/persistence/loop-fact-retirement.ts 1 coordinator #5869 loops_close fact retirement (managed or not, local or write-bound remote): the coordinator mutation (operation loops_close, intent retire_loop_fact) expires the commitment fact and strikes its fence row through the entity page publication in one transaction, only when the fact is in the loop's source and no other open loop references it.
src/core/facts/withdrawal-schema.ts 1 schema Migration v174 DDL/backfill expires fact rows that match a folded withdrawal fingerprint; schema installation runs under coordinated activation, which quiesces canonical writers.
- src/core/facts/insert-guard-schema.ts 1 engine_guard The facts_guard_inserted statement trigger (migration v263) stamps a withdrawn claim expired by an UPDATE that runs inside the inserting statement and transaction, only on rows that statement inserted, after taking the source FOR SHARE lock a withdrawal holds FOR UPDATE; the rows already passed managed_writer_guard as that INSERT, so a legacy insert on a managed brain fails before the stamp runs. Database only: it writes no file, and the struck fence row in Markdown stays the inserting publisher's (withdrawn claims are dropped or struck before the file write, as with the per-row trigger it replaces).
++src/core/facts/insert-guard-schema.ts 1 engine_guard The facts_guard_inserted statement trigger (migration v264) stamps a withdrawn claim expired by an UPDATE that runs inside the inserting statement and transaction, only on rows that statement inserted, after taking the source FOR SHARE lock a withdrawal holds FOR UPDATE; the rows already passed managed_writer_guard as that INSERT, so a legacy insert on a managed brain fails before the stamp runs. Database only: it writes no file, and the struck fence row in Markdown stays the inserting publisher's (withdrawn claims are dropped or struck before the file write, as with the per-row trigger it replaces).
src/core/facts/withdrawal.ts 2 coordinator Publication is transaction-scoped under admitted authority, source/page guards and revision checks.
src/core/facts/write-single.ts 2 coordinator Managed brains publish the single fact through the managed_facts_entity intent before the legacy supersession or DB-only insert; those legacy writes run only unmanaged and stay trigger-guarded.
src/core/git-remote.ts 0 filesystem_guard Clone, pull and rebase entry points check the durable root refusal registry.
diff --cc docs/architecture/key-files/core-persistence-continued.md
index 90efc91b9c,1e43bf38d0..25db580116
--- a/docs/architecture/key-files/core-persistence-continued.md
+++ b/docs/architecture/key-files/core-persistence-continued.md
@@@ -8,7 -8,7 +8,7 @@@ The #6188 fence check and fence repair
- `src/core/persistence/{types,params,preconditions,verb-errors}.ts` — public mutation receipt states, error reasons and revision/idempotency parameter contracts. Receipt serialization explicitly selects public fields; queued content and execution credentials stay internal. `frozenVerbWriteError` uses MEMORY_VERBS v1's existing error enum with additive `write_request`/`write_error`; `page_body_segmented` is a write error code, so a verb refused by a segmented target keeps it as `write_error` and canonical code under the frozen `invalid_params` (caller class, not retryable) on both the receipt and the pre-admission path (`runMemoryWrite`). `remember` reads a segmented entity page up to PAGE_MAX_BYTES back whole (`materializedPage`) for its inferred-target checks and fence write; over it, a named or inferred entity refuses before admission with `segmentedRememberRefusal` (fix: remember with `infer_entity: false`), never a silent `NO_ENTITY` (`test/large-pages/segmented-remember-refusal.test.ts`); `committedVerbOutcome` refuses pending or failed receipts. `OperationError` and the thin MCP client preserve this metadata, including when a timeout races an already-received receipt. The registry-safe parameter/schema leaf never imports operation values. Pinned by `test/persistence-write-contracts.test.ts`, `test/mcp-client-hardening.test.ts` and a real HTTP envelope in `test/mcp-client.test.ts`.
- `src/core/persistence/{database-write,manual-links}.ts` — `coordinatedDatabaseWrite` is the managed path for rows with no canonical file; `coordinatedManualLinkWrite` (`add_link` / `remove_link`) and `ontology_propose` (one entity page key) use it. On a managed brain it checks the caller's durable write authority for the authority page (`submissionAuthority`, then `authorizeWrite` FOR SHARE inside the transaction), revalidates the source incarnation and commits inside `withCoordinatedWrite` holding the given page keys (both link endpoints). Unmanaged brains keep the engine calls. Manual edges (`link_source` `manual` or a custom tag) survive re-derivation and republication because automatic reconciliation only replaces derived provenances. Tests: `test/managed-writers-w3.test.ts`, `test/managed-ontology-propose.test.ts`.
- - `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer runs its write (or one bounded batch) in it (the `system-of-record.md` "unattributed" list is empty; derivers pass their taint as `maintenanceTransaction(engine, fn, trust)`, see `trust/taint.ts`). `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer; under `gbrain.fact_withdrawal_stamp`, which only the facts insert guard sets, a facts update of `expired_at`/`valid_until` alone keeps them, migration v263); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.
-- `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer runs its write (or one bounded batch) in it (the `system-of-record.md` "unattributed" list is empty; derivers pass their taint as `maintenanceTransaction(engine, fn, trust)`, see `trust/taint.ts`). `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.
++- `src/core/persistence/{attribution,attribution-schema,context}.ts` — write attribution. `withCoordinatedWrite(engine, sourceIds, fn, attribution)` sets `gbrain.write_sources` and the transaction-local actor (`gbrain.write_request`, `gbrain.write_principal_kind`, `gbrain.write_principal_id`) in one round trip and restores them on exit; a nested scope keeps the outer actor. The argument is required: `requestAttribution(row)` for journaled publication (coordinator, forget), `maintenanceAttribution(engine)` (verified local writer, else the CLI registration, else `application`/`host:<id>`; no request) for derived facts, takes/timeline/link extraction, materialization, concept provenance, connector freshness and verify cleanup, `principalAttribution` for manual links (the caller) and source lifecycle (the topology principal). `withWriteAttribution` sets only the actor, for unmanaged legacy transactions; `maintenanceTransaction(engine, fn)` wraps it in one transaction, and every unmanaged direct writer runs its write (or one bounded batch) in it (the `system-of-record.md` "unattributed" list is empty; derivers pass their taint as `maintenanceTransaction(engine, fn, trust)`, see `trust/taint.ts`). `attribution-schema.ts` (migration `f1_write_attribution`; migration-only like the facts DDL, so columns land last on fresh and upgraded brains) adds nullable columns and BEFORE ROW triggers: `facts`/`takes`/`timeline_entries` carry `write_*` (created_by, immutable once set) and `last_write_*` + `last_written_at` (moved only when a classified content column changes; a NULL actor records an unattributed writer; under `gbrain.fact_withdrawal_stamp`, which only the facts insert guard sets, a facts update of `expired_at`/`valid_until` alone keeps them, migration v264); `pages.revision_*` is stamped when `knowledge_revision` changes; `page_versions.write_*` copies the snapshotted revision's actor and `archived_*` names the archiving write. `write_request_id` is `persistence_requests.id` with no foreign key; all-NULL reads as unrecorded. Every column of the three tables is classified content, projection (embeddings, `takes.updated_at`) or attribution, and a new column must be classified and the function re-created; the writer guard treats attribution-only facts/takes updates as projections. Tests: `test/write-attribution.test.ts`, `test/write-attribution-legacy.test.ts` (writer inventory) and `test/write-attribution-<family>.test.ts` (each routed unmanaged writer path; `write-attribution-timeline-10k.slow.test.ts` checks bounded batches at 10k pages) on PGLite; Postgres direct and PgBouncer through `test/e2e/write-attribution-postgres.test.ts`.
- `src/core/persistence/loop-fact-retirement.ts` — #5869 commitment-fact retirement for closed loops, one coordinator mutation on every brain (operation `loops_close`, intent `retire_loop_fact`, dispatched from `service.ts`): expires the fact and strikes its `## Facts` fence row (context `loop closed: <status>`) through the entity page publication in one transaction; no withdrawal tombstone. The shared rule (also `loopFactDrift`, used by doctor `loop_facts_drift` and `gbrain repair loop-facts`): only a fact in the loop's source that no other open loop references, re-checked under row locks at publication (`shared_with_open_loop`, `source_mismatch` otherwise). `retireLoopFact(ctx, loopId)` submits with the caller's grant and maps a refusal or pending write to `fact_expired: false, retryable: true, reason`. Tests: `test/loops-close-fact.serial.test.ts` (+ Postgres twin).
- `src/core/persistence/connector-authority.ts` -- classifies each Google/GitHub source as `connector_database` (managed, unbound), `bound` or `unmanaged` from `persistence_brain.enabled` and the source binding row. File-lane audits (doctor `undeclared_db_only_pages`, backup coverage) read it so a leftover cache directory at `local_path` is never taken for canonical files. Tests: `test/doctor-silent-death-checks.test.ts`, `test/backup-coverage.serial.test.ts`.
- `src/core/persistence/connector-sync.ts` — managed Google/GitHub API ingestion through source-scoped journaled `connector_v2_import`/`_delete`/`_checkpoint`/`_google_receipts` intents and `managed-connector` checkpoint CAS, not Git cursors. The checkpoint key, admission `configHash`, mid-sweep change check and publication `source_changed` check all use the parsed-config identity from `connector-identity.ts`, so cycle stamps in `sources.config` never rotate them. Unbound connectors use reviewed `connector_database` SQL-only authority; bound connectors retain canonical file publication with guarded root/hash/revision/epoch. Every managed run checks the credential's resolved account against the pin in the connector state row before reading its checkpoint (`assertAccount`), then applies a requested `--reset-checkpoint` (pending writes resolved first, pin kept). Each import or delete is first screened by running `prepareConnectorMutation` on an unadmitted request through the no-op kernel; unchanged items take no admission. An unchanged checkpoint save is skipped and, when it would have stamped freshness, `last_sync_at` is stamped directly inside a lease-asserted coordinated write. Accepted-pending writes are progress: a 30-second total wait budget (writes committing within one second are free), at most one in-flight write per page, outstanding writes kept under the principal's outstanding and intent-byte limits, and `ConnectorWaitBudgetStop` (a `write_pending` error) when the budget is spent. The checkpoint never advances past a pending page; the run records its pending set in the state row, and the next run resolves it first (committed dropped, failed retried automatically through the retry-pointer path without `--retry-failed`, unreached failures after a complete sweep dropped and counted). Retired `managed_connector_*` intents route to `prepareOutdatedConnectorMutation`, which fails them `connector_intent_outdated` (detail `pre_upgrade` before the v176 cutoff). Standalone entry, page reads and submissions authenticate the current source, local grant and canonical owner and settle retained worktree publications before deriving request identity. Explicit `--retry-failed` atomically admits a linked attempt and stores a per-base-request `managed-connector-retry` pointer. Durable connector cursors, retry pointers and state rows survive generic seven-day checkpoint GC. Tests: `test/persistence-connectors.test.ts`, `test/persistence-connector-retry.test.ts`, `test/connector-checkpoint-identity.test.ts`, `test/connector-wave3.test.ts` and `test/helpers/connector-restart.ts` on PGLite and disposable Postgres. #6831: a page import whose content matches a source page purge tombstone is skipped per item instead of ending the run: screened before admission (`carriesPurgedPage`, the guard's content hash, read only when the source has a tombstone), and a `failed`/`purged_content` receipt the guard still produces (a purge that landed mid-run) is skipped wherever it surfaces (the item's wait, `refreshPending`, `resolvePendingSet`): it is dropped from `receipts`, never joins the automatic retry set, has its optimistic pending count taken back, and is counted in `last_run.purged_skipped` and `purged_items`. A replayed purged receipt is re-checked against the live tombstones (`purgedNow`) before `mayRetry`: still purged, it is skipped even under `--retry-failed`; cleared, it gets one automatic retry. A run that ends on any error except `LockStolenError` or an aborted caller signal records `last_failure` (code, else `connector_error`; message, the item and request when the run ended on that item's receipt, `consecutive`); only a complete `finish()` (cursor saved, nothing pending or failed) clears it. Tests: `test/connector-purged-item-6831.test.ts` (+ `test/e2e/` twin).
diff --cc docs/architecture/key-files/core-services-2.md
index 216f746465,2576ab87b6..41b2c266e6
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@@ -18,7 -18,7 +18,7 @@@ Fact and page purge modules (`src/core/
- `src/core/facts/queue.ts:FactsQueue.drainPending` — method `drainPending({timeout?: number}): Promise<{drained, unfinished}>`. Semantically distinct from `shutdown()` (which calls `this.internalAbort.abort()` and would abort the very facts:absorb worker trying to log its post-completion event). Drain lets in-flight finish; only the wait is bounded. Default timeout `1000ms` so commands that don't enqueue facts pay one fast 0ms check before exit. `src/cli.ts` op-dispatch finally block awaits `getFactsQueue().drainPending({timeout: 1000})` BEFORE `engine.disconnect()`. Lazy-import keeps the facts-queue module off the hot path for ops that never touch it. Prevents a trailing `'No database connection'` line after `gbrain capture` (a post-page-write facts:absorb outliving the CLI process). Pinned by `test/facts-queue-drain-pending.test.ts` (4 cases: empty fast-path, in-flight settled without abort, unfinished count on timeout, default timeout = 1000ms).
- - `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason `split_fence_rows`, naming the page and the fence (`test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts`). Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts triggers (per row, or once per statement for the bulk fence insert, v263); they prevent reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (`splitFactsFences`; above `PAGE_MAX_BYTES` it refuses with `page_body_segmented`), so a private row, which never reaches chunks, is found wherever the cut falls.
-- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason `split_fence_rows`, naming the page and the fence (`test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts`). Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts trigger; the trigger prevents insert/update from reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (`splitFactsFences`; above `PAGE_MAX_BYTES` it refuses with `page_body_segmented`), so a private row, which never reaches chunks, is found wherever the cut falls.
++- `src/core/facts/withdrawal.ts` + `withdrawal-schema.ts` + `withdrawal-discovery.ts` — durable withdrawal key is `(source_id, visibility, subject, SHA256(normalized claim))`. `subject` is the forgotten row's `entity_slug`; '*' (all subjects) covers subjectless facts and rows recorded before v169. A withdrawal matches when `subject = '*' OR subject = entity_slug`, so forgetting one entity's claim never touches the same claim about another entity. Fence rows belong to their page's entity: the import overlay, prepared-import check (`preserveWithdrawnFenceRows` / `assertPreparedFactWithdrawals`), snapshot overlay and Markdown export match on the page slug. `updateSlug` (both engines, via `moveSlugBindings`) and the phantom-redirect merge move subjects to the new slug (`MOVE_WITHDRAWAL_SUBJECT_SQL`), so rename and index recreation do not restore a claim. Normalization (`gbrain_fact_normalize`, mirrored in JS by `normalizeLoweredClaim`) folds case, whitespace and an explicit punctuation set, not meaning (migration v174); `+`, `#` and in-word dots are kept ("C++" ≠ "C"); pre-v174 ledger rows keep their exact `gbrain_fact_fingerprint_v1` hash and every ledger match checks both. v174 adds a folded row wherever a fact row still holds the claim text, expires facts that became matching, and builds `idx_facts_withdrawal_fingerprint` (the fingerprint inlines normalization: index builds use a restricted search_path). Discovery (`withdrawal-discovery.ts`) is keyed on claim, subject and fingerprint: SQL shortlists pages and chunks whose lowercased text contains every normalized token of the claim (one `lower(text) LIKE ALL(patterns)` fold per text with `%`, `_` and `\` escaped, #6270; necessary for any match; nothing is normalized in SQL), streams them by keyset, then verifies exactly; a subject-scoped claim reads only its entity's page plus provenance of that entity's facts. There is no source-inventory limit (#5674): refusals come from the matched set (>256 pages, reported with the count and sample slugs), the 10s scan budget, per-batch input limits or matching malformed evidence. One facts fence a forced cut splits is checked as one batch; over 16,384 rows or 8 MiB it refuses with reason `split_fence_rows`, naming the page and the fence (`test/pathological/lp-f-split-fence-withdrawal-capacity.test.ts`). Only an existing withdrawal covering the same subject skips discovery. Only affected page revisions/chunks are invalidated. The source row lock serializes withdrawal with the facts triggers (per row, or once per statement for the bulk fence insert, v264); they prevent reactivating a matching claim. Import and snapshot overlays cover every complete legacy fence, including inactive rows; withdrawal markers precede preserved context and retain earlier expiry dates before hashing/chunking; malformed fences retain their existing diagnostics and the DB trigger still protects derived facts. `writeSingleFact` refuses an identical withdrawn claim for the resolved entity before embedding, using the protocol error envelope. `writeFactsToFence` rechecks each input under the page lock and drops claims withdrawn for the page's entity (reporting `withdrawnSkipped`), and the backstop skips them in phase 1, so a withdrawn claim is never appended to Markdown as an active row (audit B-10). TTL/supersession expiry creates no withdrawal; backfill trusts only explicit `forgotten:` markers; Markdown-only copies do not preserve DB-only withdrawals. Pinned by `test/facts-withdrawal-subject.test.ts`, `test/fact-withdrawal-normalized.test.ts`, `test/withdrawal-bounded-safety.test.ts` (both engines) and the Postgres scale gate `test/e2e/fact-withdrawal-scope-postgres.test.ts`. `recordFactWithdrawal(…, { semanticReview })` also queues a `withdraw` review row in `decide_review_queue` inside the same transaction when `decide.slots.conflict.review_withdraw` is on (unset counts as on; `reviewWithdrawOn`) and the caller did not opt out, and runs every `registerWithdrawalInvalidation` hook in that transaction for projections beyond pages and chunks. `src/core/facts/similar-active.ts` — `similarActiveAfterForget`: after a committed `forget`, up to five active facts with the same source, entity and visibility (world only for remote callers) at cosine >= 0.80 to the withdrawn fact's stored embedding, returned as ids and scores with the overnight review state and a `next` line (zero model calls; pinned by `test/decide/review-withdraw.serial.test.ts`). Segmented affected pages are struck segment by segment through `rewriteLiveSegmentedFences` (a new generation whose flip replaces only the rewritten occurrences' chunks); discovery also scans live manifest rows with `facts_slots`, reading only each slot's bytes, and joins a fence a forced cut split from its slots' bytes (`splitFactsFences`; above `PAGE_MAX_BYTES` it refuses with `page_body_segmented`), so a private row, which never reaches chunks, is found wherever the cut falls.
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (per-model threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims. A fence append refused because the page's facts fence does not parse cleanly rethrows the typed `fenceRefusal` (`invalid_fence` / `target_fence_malformed`). On an unmanaged brain, #6398 (fix wave 13): when the page's file is missing but a source-scoped row exists (live, with a vanished `source_path` file, or tombstoned), `writeFactsToFence` returns `stubGuardBlocked` with audit reason `db_only_page` and the caller records the facts DB-only, so no stub overwrites the DB body or resurrects a deleted page; an unreadable row returns `fenceWriteFailed`; the #4872 page mirror runs only for a body read from a real file. Doctor `stub_guard_24h` (`commands/doctor/checks/local-audits.ts`) counts `unprefixed`, `fallback_resolution` and `db_only_page` separately; `db_only_page` never feeds the WARN threshold. Tests: `test/fence-write-db-only.test.ts`, `test/doctor-stub-guard.test.ts`.
- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
diff --cc docs/architecture/key-files/memory-purge.md
index 4b01e6259a,a1bb99e49c..abbaa85577
--- a/docs/architecture/key-files/memory-purge.md
+++ b/docs/architecture/key-files/memory-purge.md
@@@ -9,8 -9,7 +9,8 @@@ User-facing contract: [expire versus pu
- `src/core/belief/purge.ts` — the purge half of the belief ledger (BELIEF_LEDGER.md 6.5). Every fact or page purge bumps `sources.purge_epoch` (`bumpPurgeEpoch`; an append prepared at an older epoch with `preparedEpoch` refuses `belief_stale_preparation`) and runs three passes inside the purge transaction: `redactPurgedKeys` (the purged keys, by `claim_fp` and page lifetime, keep skeletons: value, value_hash and prior_hash null, `purged`), `redactCarryingFields` (keyset batches of 1000 reading only the carrying fields of fact, take and link events, matched in JS by `quotes` over `claimForms`, never SQL `lower()`/`strpos`: each carrying field from `CARRYING_FIELDS` that quotes a purged claim, plain or fence-escaped, becomes `REDACTION_MARKER(<purge request>)` and is listed in `redacted_fields`; a later event's prior_hash naming the old hash names the new one) with `registerLiveCarriers` (a surviving row whose field quotes the claim enters `belief_redactions` with its field hash, so its next event writes the marker until an explicit owner edit sets a different value: `publicationBeliefOptions` marks `ownerEdit` only on a local `put_page`, `edit_page`, `takes_update` or `takes_resolve` with no internal intent kind, and append still needs `OWNER_TIER_FLOOR`) and, for a fact purge, `registerVersionCarriers` (the retained versions still quoting the claim, registered under the keys the backfill gives them). A claim shorter than 8 characters quotes a field only as a word in spaced scripts (`ceo` does not match `herbaceous`; CJK and markup still match), and `appendDerivedHidden` (one `derived.hidden` per key the derivation walk hid; `readBeliefHistory` then hides that key's earlier events and every backfill event of it). A page purge's claims come from `pagePurgeClaims`: the page's facts and takes, every retained version's fence rows and every claim in its lifetimes' events, unbounded. `releaseSuppressedFields` is the owner release `trust confirm` runs (`belief_redactions.released_hash`); every release, there or in an owner-edit append, appends one `redaction.released` (`redactionReleasedDraft`: fields, purge requests and released hashes, never the text) in the publication `released_by` names. The receipt's `ledger` block reports the counts and `derived_walk`; a truncated walk withholds certification of its coverage interval (`coverage-report.ts`). Purge-verify's ledger report is a JS keyset scan too: a missed carrying field is `incomplete`, another subject's recorded value quoting the claim is `out_of_scope` with `field@key` items. Seam: `__setPurgeRedactionFaultForTests`. Probes: `test/belief-ledger-purge.test.ts` (both engines).
- `src/core/belief/purge-mirror.ts` — the text-free purge mirror `<brain home>/.gbrain/purge-events.jsonl` (0600, fsynced): an `intent` line before the purge commits (`appendPurgeIntent`; request, source and incarnation, scope, fingerprints, content hashes, lifetimes, epoch; never claim text; an unwritable mirror refuses the purge with the typed `purge_mirror_unwritable`, with or without a ledger) and a `committed` line after (`appendPurgeCommitted`, best effort; a page purge writes it from the coordinator's `afterCommit`, so it does not depend on the op handler finishing). `restorePgliteBackup` (`gbrain backup restore --purge-mirror <absolute path>` names a mirror other than the brain home's) replays every committed purge newer than the archive inside its transaction (`replayPurgesInRestore`: tombstones, row removal (a fact-scope replay rewrites page bodies and versions through `rewritePageBodies` / `redactPageVersions`, then runs `purgeSegmentStorage` with each claim's `stagingsHoldingClaim`; a page-scope replay deletes the page through `deletePageWithSegments`, so segment texts that held the purged content go in the replay, as in the purge), the three passes, the derived rows hidden again with `derived.hidden` cause `restore_replay`, one `fact.purged`/`page.purged` with cause `restore_replay`; a page-scope replay matches pages by content hash or lifetime, never by slug alone; an archive from before the ledger, no `belief_events`, replays tombstones and row removal and reports `ledger: 'absent'`; an intent whose request already has tombstones is skipped), records each as `complete`, `partial` (no restored row held the text, or the derivation walk could not run) or `unverified` (intent without committed line, not replayed), returns `purge_replay` in the receipt and adds a reconnect warning unless the state is `none` or `complete`; an unreadable mirror is `unavailable`. `coverage.restored` carries the outcome, which `readRestorePurgeReplay` reads back for the doctor. A Postgres restore runs `gbrain beliefs replay-purges --archived-at <iso> (--purge-mirror <abs path> | --from-url-env <VAR>) [--apply]` (`src/commands/beliefs-replay-purges.ts`; dry run by default: `replayPurges` runs the replay in a transaction that rolls back), whose database source `purgeLinesFromDatabase` rebuilds the intents from every pre-restore tombstone (not bounded by `purged_at`, the purge transaction's start) and skips those the archive already holds. Seam: `__setPurgeReplayFaultForTests`. Probes: `test/belief-ledger-restore.test.ts`; segment storage after a replay: `test/large-pages/purge-replay-segments.test.ts` (both engines).
- `src/core/facts/purge-overlay.ts` — purge mode of the import overlay: `dropPurgedFenceRows` drops facts-fence rows matching `fact_purges` and takes-fence rows matching `take_purges` (the takes fence re-renders with its reservation rows plus the dropped numbers reserved, so a purged number is never reused; pinned by `test/purge-overlay-reservations.test.ts`) (subject = page slug; malformed fences left to the withdrawal diagnostics, which refuse a purged claim inside one). Called first by `preserveWithdrawnFenceRows`, so `import-file.ts` needs no change; the snapshot overlay (`page-state/snapshot.ts`) and export (`export-snapshot.ts`) carry purge tombstones as `PageWithdrawal.purged`, which `overlayWithdrawalBody` drops instead of striking.
- - `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. Since migration v263 `facts_refuse_purged` fires on UPDATE only; the facts insert check runs once per statement in `facts/insert-guard-schema.ts`. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).
- - `src/core/facts/insert-guard-schema.ts` — `FACT_INSERT_GUARD_SQL` (migration v263, #7105): one statement-level `facts_guard_inserted` trigger (`AFTER INSERT ... REFERENCING NEW TABLE AS inserted_facts`, function `gbrain_guard_inserted_facts`) runs the purge refusal, and the withdrawal stamp of deferred inserts, once per statement instead of once per row. It takes `FOR SHARE` on each inserted source row, refuses a statement whose rows match a `fact_purges` tombstone with the same `P0001 purged_content` message and `{table, hash8}` detail (the first matching row in insertion order, whatever its `expired_at`), then stamps inserted active rows still matching `fact_withdrawals` (v2 or v1 fingerprint) with `expired_at = min(withdrawn_at)` and a clamped `valid_until`, by an UPDATE of just those rows, run under the transaction-local `gbrain.fact_withdrawal_stamp` setting (`FACT_WITHDRAWAL_STAMP_SETTING`, reset after the UPDATE) so `gbrain_stamp_write_attribution` keeps the `last_write_*` and `last_written_at` the INSERT stamped or supplied. By default an insert is stamped before it is written by the per-row `facts_preserve_withdrawal_insert` (`BEFORE INSERT ... WHEN (NEW.expired_at IS NULL AND <deferral off>)`, the original function), so `INSERT ... RETURNING` reads the stamp; the bulk fence insert (`engine-sql/facts.ts` `insertFactRows`) sets `gbrain.fact_withdrawal_stamp_deferred` (`FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING`) around its INSERTs, so the WHEN clause, which calls no function, skips the trigger and the statement guard stamps instead. The setting moves the stamp and never skips it: the guard stamps every still-matching active row whoever set it. A ledger with no row for the inserted sources costs one index probe. Transition tables cannot take a column list, so `facts_refuse_purged` and `facts_preserve_withdrawal` stay per-row for UPDATE (`BEFORE UPDATE OF ...`). Differences from the per-row insert guards: (1) a row ON CONFLICT DO NOTHING skips is not checked (it is not written either); (2) a row that another per-row BEFORE trigger (for example `managed_writer_guard`) or a constraint also refuses reports that refusal first; (3) a deferred insert is stamped after its RETURNING, so `INSERT ... RETURNING expired_at, valid_until` (or a CTE reading it in the same query) made under the deferral setting sees a withdrawn row unstamped while storage and every later statement see the stamp (`insertFactRows` returns only ids, slugs and row numbers). Pinned by `test/facts-insert-guards-7105.test.ts` (guard calls and firings per statement, RETURNING with and without deferral, and the same refusals, stamps and attribution as the per-row guards re-installed in a rolled-back transaction, both engines).
-- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).
++- `src/core/facts/purge-schema.ts` — `MEMORY_PURGE_SCHEMA_SQL` (schema.sql fragment: `fact_purges`, `take_purges`, `page_purges` keyed `(source_id, content_hash)`, `derivation_inputs`, `needs_rederive`) and `MEMORY_PURGE_GUARD_SQL` (migration only): `facts_refuse_purged`, `takes_refuse_purged` and `pages_refuse_purged` raise `P0001 purged_content: …` (mapped to typed `purged_content` by `persistence/publication-failure.ts`) instead of skipping the row, whatever `expired_at` says. The pages guard has no column list so it never pins columns. Since migration v264 `facts_refuse_purged` fires on UPDATE only; the facts insert check runs once per statement in `facts/insert-guard-schema.ts`. `FACT_PURGE_LOOKUP_INDEX_SQL` (migration v231, CONCURRENTLY on Postgres) adds `fact_purges_subject_idx` (a page's own tombstones, the '*' lookup by fingerprint) and the partial `fact_purges_all_subjects_idx` (subject '*' only, for the snapshot marker count).
++- `src/core/facts/insert-guard-schema.ts` — `FACT_INSERT_GUARD_SQL` (migration v264, #7105): one statement-level `facts_guard_inserted` trigger (`AFTER INSERT ... REFERENCING NEW TABLE AS inserted_facts`, function `gbrain_guard_inserted_facts`) runs the purge refusal, and the withdrawal stamp of deferred inserts, once per statement instead of once per row. It takes `FOR SHARE` on each inserted source row, refuses a statement whose rows match a `fact_purges` tombstone with the same `P0001 purged_content` message and `{table, hash8}` detail (the first matching row in insertion order, whatever its `expired_at`), then stamps inserted active rows still matching `fact_withdrawals` (v2 or v1 fingerprint) with `expired_at = min(withdrawn_at)` and a clamped `valid_until`, by an UPDATE of just those rows, run under the transaction-local `gbrain.fact_withdrawal_stamp` setting (`FACT_WITHDRAWAL_STAMP_SETTING`, reset after the UPDATE) so `gbrain_stamp_write_attribution` keeps the `last_write_*` and `last_written_at` the INSERT stamped or supplied. By default an insert is stamped before it is written by the per-row `facts_preserve_withdrawal_insert` (`BEFORE INSERT ... WHEN (NEW.expired_at IS NULL AND <deferral off>)`, the original function), so `INSERT ... RETURNING` reads the stamp; the bulk fence insert (`engine-sql/facts.ts` `insertFactRows`) sets `gbrain.fact_withdrawal_stamp_deferred` (`FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING`) around its INSERTs, so the WHEN clause, which calls no function, skips the trigger and the statement guard stamps instead. The setting moves the stamp and never skips it: the guard stamps every still-matching active row whoever set it. A ledger with no row for the inserted sources costs one index probe. Transition tables cannot take a column list, so `facts_refuse_purged` and `facts_preserve_withdrawal` stay per-row for UPDATE (`BEFORE UPDATE OF ...`). Differences from the per-row insert guards: (1) a row ON CONFLICT DO NOTHING skips is not checked (it is not written either); (2) a row that another per-row BEFORE trigger (for example `managed_writer_guard`) or a constraint also refuses reports that refusal first; (3) a deferred insert is stamped after its RETURNING, so `INSERT ... RETURNING expired_at, valid_until` (or a CTE reading it in the same query) made under the deferral setting sees a withdrawn row unstamped while storage and every later statement see the stamp (`insertFactRows` returns only ids, slugs and row numbers). Pinned by `test/facts-insert-guards-7105.test.ts` (guard calls and firings per statement, RETURNING with and without deferral, and the same refusals, stamps and attribution as the per-row guards re-installed in a rolled-back transaction, both engines).
- `src/core/page-state/snapshot.ts` — a page snapshot lists only the page's own `fact_purges` tombstones; subject-'*' ones come back as `PageSnapshot.globalPurges` (count, latest `purged_at`, world-only flag; absent at count 0). `resolveGlobalPurges` turns the marker into purge withdrawals for the fence rows of whatever text is overlaid (stored page, incoming file in `page-prepare.ts`, `overlayCanonicalBodies`), on the caller's query. Reconcile pins/preimages and extract-atoms page-state hashing carry the marker, so a new '*' purge invalidates them and an artifact without it reads stale. Alias resolution: `readPageSnapshot` with `resolveAlias` first runs the exact-slug statement (an exact hit outranks every alias), then, on a miss or for `requireUnambiguous`, one `WITH chosen` statement whose candidates are a UNION ALL of the exact-slug probe and an alias-join probe (`slug_aliases` → `pages` on `(source_id, canonical_slug)`, `p.slug<>$1` keeps the branches disjoint so `count(*) OVER ()` still counts pages). #6281: never `slug=$1 OR EXISTS(alias)`, which read every page of every readable source; `page-snapshot-alias-plan.test.ts` pins fewer than 100 `pages` rows per statement from EXPLAIN on both engines.
- `src/core/facts/derivation-inputs.ts` — `recordDerivationInputs(tx, {table, id, sourceId}, inputs)`: complete derived-row → input edges, written by derivers in the deriving transaction (`write_origin` keeps only a display sample). `derivedRowsFrom` walks edges breadth-first (bounded, reports `truncated`); `hideDerivedRows` expires facts, deactivates takes, soft-deletes pages and upserts `needs_rederive`.
- `src/core/deletion-inventory.ts` — the deletion-target registry: every table with a text, JSON, bytes, array, lexeme or vector column, classed `swept`, `retained_inactive` or `out_of_scope` (`probed_reported` with probe columns, `text_free_ledger`, `secret_material`, `no_memory_text`), plus on-disk stores and out-of-reach residuals. `test/deletion-inventory.test.ts` fails on any unlisted text-bearing column of a fresh schema and pins the AGENTS.md "never promise physical erasure" line.
diff --cc src/core/behavior-change-notice.ts
index 4824af23be,1cb43d132a..d8e39b955e
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@@ -1016,12 -1016,9 +1016,15 @@@ export const BEHAVIOR_CHANGES: Readonly
{ since: '0.60.324.0', text: 'New `append_page` adds text to the end of a page in time proportional to the text added, idempotent by `request_id`; use it for conversation logs instead of re-putting the page. `expected_tail_sha256` (the `tail_sha256` that `get_page` with `body: \'none\'` returns) refuses `tail_changed` when another writer appended first. `gbrain append <slug> [--file f | stdin]` calls it.' },
{ since: '0.60.324.0', text: 'New upload sessions (`begin_page_upload`, `upload_page_part`, `get_page_upload`, `commit_page_upload`, `abort_page_upload`) let remote and thin clients write pages larger than one request, up to the page ceiling; `gbrain put --file` and `gbrain capture --file` use them on remote brains. A session is bound to the principal, source and page that began it (any other caller gets `upload_not_found`), staged bytes count against `persistence.limits` upload quotas (`write_quota_exhausted`), and an idle session expires after an hour. Locally, `gbrain put --file` and `gbrain capture --file` stream a file over 24 MiB straight in.' },
{ since: '0.60.324.0', text: '`edit_page` accepts `within` to restrict a match to a range returned by a window read (`edit_target`), and edits a page stored in segments by rewriting only the segments the match touches instead of reading the whole page back.' },
+ // #7112 (Postgres 15 SQL compatibility, owner-exception error text). `since` is restamped at the merge slot.
+ { since: '0.60.326.0', text: 'Managed sync, put_page, source config updates, archive and restore, and the dream-breaker reset work again on Postgres 15: they used the Postgres 16+ `IS JSON` predicate (and doctor jsonb_integrity and `gbrain repair-jsonb` used `pg_input_is_valid`), a syntax error (42601) on Postgres 15 that failed every managed sync checkpoint. They now use a new `gbrain_try_jsonb(text)` function (migration v263) on every server. The same guard no longer fails a config merge or a dream-breaker reset whose stored text is JSON but not jsonb (a \\u0000 escape); that value now reads as an empty object, like other unparseable text.' },
+ { since: '0.60.326.0', text: 'A write that ends `storage_error` on an unexpected database server error now keeps, owner-side in the receipt, the server message with any quoted value replaced by … (`error_text`; object names stay only in known catalog messages or when the statement names them), the failing statement with every literal, number and comment replaced and never its parameters (`statement`), and the error position; a PL/pgSQL RAISE or ASSERT keeps no text. On the brain host `gbrain write-request <id> --json` now prints the receipt\'s `error_detail`, and the persistence consumer log line adds `error_text=`, `statement=` and `position=`. Remote readers see no new field.' },
+ // Wave B follow-ups lane F2 (#7106: a managed import or sync of a new page over 4 MiB replies at commit). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A managed `gbrain import` or `gbrain sync` of a new page over 4 MiB stored in segments now replies when the write commits, before its search index is built, instead of waiting for that build (which on a loaded host outlasted the 30 s import wait and replied `write_pending`). The import result and the write\'s receipt say `searchable: "pending"` and `projection: "pending"`; the import result also carries the `request_id`, `searchable_retry_after_ms` and `searchable_fix`. Read the receipt again (`gbrain write-request -- <request_id>`, `get_write_request`) at that interval until it says `searchable: true`; search finds the page from then on. The build no longer holds up the source\'s next write either. A new page up to 4 MiB, and an edit of a page stored in segments, is still searchable when its import replies (`searchable: true`). A `put_page` of a new page over 4 MiB, whose receipt already said `searchable: "pending"`, now also replies at commit instead of after the build.' },
+ // Wave B follow-ups lane F3 (#7122 remote append_page mention links). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'A remote `append_page` to the body of a page now adds plain `mentions` links (link source `mcp-remote-mention`) for the `[[wikilinks]]`, markdown links and page paths in the appended text, to existing pages the writer can see inside its grant, as a remote `put_page` does. The post-commit pass reads only the appended text, never the rest of a large page, and never removes a link. `gbrain config set mcp.remote_auto_links off` turns it off.' },
+ // Wave B follow-ups lane F4 (an abandoned lane preparation bars its worktree). `since` is stamped at the merge slot.
+ { since: 'TBD', text: 'During a managed sync that publishes in lanes, a page whose preparation ran past its budget is no longer claimed and prepared again by another lane while the abandoned preparation still runs; that worktree now waits for it, as a sync without lanes always did, until it settles or `persistence.preparation_ceiling_ms` passes. A foreground write to that worktree waits the same way meanwhile. The page keeps its `preparation_deadline` reason until it is claimed again.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --cc src/core/facts/insert-guard-schema.ts
index 401cac89de,0000000000..123f4c44bc
mode 100644,000000..100644
--- a/src/core/facts/insert-guard-schema.ts
+++ b/src/core/facts/insert-guard-schema.ts
@@@ -1,101 -1,0 +1,101 @@@
+/**
+ * Set-based insert guards on facts (#7105). One statement-level AFTER INSERT
+ * trigger reads the statement's inserted rows from a transition table and
+ * applies both insert-time guards once per statement instead of once per row
+ * (the withdrawal stamp only for inserts that defer it, see below):
+ *
+ * - Purge refusal (purge-schema.ts `gbrain_refuse_purged_fact`): an inserted
+ * row whose fingerprint has a fact_purges tombstone for its source,
+ * visibility and subject ('*' or its entity_slug) aborts the statement with
+ * the same P0001 `purged_content` message and `{table, hash8}` detail,
+ * whatever its expired_at. When several rows match, the detail names the
+ * first one in insertion order, as the per-row trigger did.
+ * - Withdrawal preservation (withdrawal-schema.ts
+ * `gbrain_preserve_fact_withdrawal`): an inserted active row matching a
+ * fact_withdrawals row (v2 or v1 fingerprint) is stamped expired_at =
+ * min(withdrawn_at) and valid_until = LEAST(valid_until, withdrawn_at).
+ * By default the per-row BEFORE INSERT trigger facts_preserve_withdrawal_insert
+ * stamps the row before it is written, so `INSERT ... RETURNING` reads the
+ * stamp. An insert made under FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING (the
+ * bulk fence insert in engine-sql/facts.ts, whose RETURNING reads only ids)
+ * skips that trigger through its WHEN clause, which calls no function, and
+ * this guard stamps the rows by an UPDATE of just the matching ones at the
+ * end of the statement. The setting only moves the stamp, never skips it:
+ * the guard stamps every inserted active row still matching, whoever set
+ * it. That UPDATE runs under FACT_WITHDRAWAL_STAMP_SETTING
+ * (attribution-schema.ts), so the row keeps the last_write_* values its
+ * INSERT stamped or supplied, and resets it afterwards. A deferred row's
+ * RETURNING (or a CTE over it) reads it unstamped; the next statement reads
+ * the stamp.
+ *
+ * Both take the per-row guards' lock: FOR SHARE on each inserted source row
+ * before the ledgers are read, so an insert still serializes with a purge or
+ * a withdrawal that holds the source FOR UPDATE. A ledger with no row for the
+ * inserted sources costs one index probe, not a fingerprint per row.
+ *
+ * Transition tables cannot be combined with a column list, so updates keep
+ * the per-row BEFORE UPDATE OF triggers under their old names and functions;
+ * only the insert half moves here. A statement trigger sees only the rows the
+ * statement wrote: a row ON CONFLICT DO NOTHING skipped is not checked (it is
- * not saved either). Installed by migration v263.
++ * not saved either). Installed by migration v264.
+ */
+import { FACT_WITHDRAWAL_STAMP_SETTING } from '../persistence/attribution-schema.ts';
+
+export const FACT_INSERT_GUARD_TRIGGER = 'facts_guard_inserted';
+/** Transaction-local; 'on' defers the withdrawal stamp of the following inserts to facts_guard_inserted. */
+export const FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING = 'gbrain.fact_withdrawal_stamp_deferred';
+export const FACT_INSERT_GUARD_FUNCTION = 'gbrain_guard_inserted_facts';
+
+export const FACT_INSERT_GUARD_SQL = `
+CREATE OR REPLACE FUNCTION gbrain_guard_inserted_facts() RETURNS trigger
+ LANGUAGE plpgsql SET search_path = pg_catalog, public AS $fn$
+ DECLARE purged TEXT; stamp_setting TEXT;
+ BEGIN
+ PERFORM s.id FROM sources s WHERE s.id IN (SELECT i.source_id FROM inserted_facts i) ORDER BY s.id FOR SHARE OF s;
+ IF EXISTS (SELECT 1 FROM fact_purges p WHERE p.source_id IN (SELECT i.source_id FROM inserted_facts i)) THEN
+ WITH n AS MATERIALIZED (
+ SELECT row_number() OVER () AS ord, i.source_id, i.visibility, i.entity_slug, gbrain_fact_fingerprint(i.fact) AS fact_hash
+ FROM inserted_facts i)
+ SELECT n.fact_hash INTO purged FROM n
+ WHERE EXISTS (SELECT 1 FROM fact_purges p WHERE p.source_id = n.source_id AND p.visibility = n.visibility
+ AND p.subject IN ('*', n.entity_slug) AND p.fact_hash = n.fact_hash)
+ ORDER BY n.ord LIMIT 1;
+ IF purged IS NOT NULL THEN
+ RAISE EXCEPTION USING ERRCODE = 'P0001',
+ MESSAGE = 'purged_content: this claim was purged from this source and cannot be saved again',
+ DETAIL = json_build_object('table', 'facts', 'hash8', left(purged, 8))::text;
+ END IF;
+ END IF;
+ IF EXISTS (SELECT 1 FROM fact_withdrawals w WHERE w.source_id IN (SELECT i.source_id FROM inserted_facts i WHERE i.expired_at IS NULL)) THEN
+ stamp_setting := current_setting('${FACT_WITHDRAWAL_STAMP_SETTING}', true);
+ PERFORM set_config('${FACT_WITHDRAWAL_STAMP_SETTING}', 'on', true);
+ WITH n AS MATERIALIZED (
+ SELECT i.id, i.source_id, i.visibility, i.entity_slug,
+ gbrain_fact_fingerprint(i.fact) AS fact_hash, gbrain_fact_fingerprint_v1(i.fact) AS fact_hash_v1
+ FROM inserted_facts i WHERE i.expired_at IS NULL),
+ m AS (
+ SELECT n.id, min(w.withdrawn_at) AS withdrawn_at FROM n JOIN fact_withdrawals w
+ ON w.source_id = n.source_id AND w.visibility = n.visibility
+ AND w.subject IN ('*', n.entity_slug) AND w.fact_hash IN (n.fact_hash, n.fact_hash_v1)
+ GROUP BY n.id)
+ UPDATE facts f SET expired_at = m.withdrawn_at, valid_until = LEAST(COALESCE(f.valid_until, m.withdrawn_at), m.withdrawn_at)
+ FROM m WHERE f.id = m.id;
+ PERFORM set_config('${FACT_WITHDRAWAL_STAMP_SETTING}', COALESCE(stamp_setting, ''), true);
+ END IF;
+ RETURN NULL;
+ END
+ $fn$;
+DROP TRIGGER IF EXISTS facts_guard_inserted ON facts;
+CREATE TRIGGER facts_guard_inserted AFTER INSERT ON facts REFERENCING NEW TABLE AS inserted_facts
+ FOR EACH STATEMENT EXECUTE FUNCTION gbrain_guard_inserted_facts();
+DROP TRIGGER IF EXISTS facts_refuse_purged ON facts;
+CREATE TRIGGER facts_refuse_purged BEFORE UPDATE OF fact, source_id, visibility, entity_slug ON facts
+ FOR EACH ROW EXECUTE FUNCTION gbrain_refuse_purged_fact();
+DROP TRIGGER IF EXISTS facts_preserve_withdrawal ON facts;
+CREATE TRIGGER facts_preserve_withdrawal BEFORE UPDATE OF fact, source_id, visibility, entity_slug, expired_at ON facts
+ FOR EACH ROW EXECUTE FUNCTION gbrain_preserve_fact_withdrawal();
+DROP TRIGGER IF EXISTS facts_preserve_withdrawal_insert ON facts;
+CREATE TRIGGER facts_preserve_withdrawal_insert BEFORE INSERT ON facts FOR EACH ROW
+ WHEN (NEW.expired_at IS NULL AND COALESCE(current_setting('${FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING}', true), '') <> 'on')
+ EXECUTE FUNCTION gbrain_preserve_fact_withdrawal();
+`;
diff --cc src/core/schema-migrations/latest.generated.ts
index 7c10d71c56,7c10d71c56..1f7aa9e1ba
--- a/src/core/schema-migrations/latest.generated.ts
+++ b/src/core/schema-migrations/latest.generated.ts
@@@ -4,4 -4,4 +4,4 @@@
// The highest schema migration version (migrate.ts LATEST_VERSION), importable without
// loading the migrations themselves.
--export const LATEST_SCHEMA_VERSION = 263;
++export const LATEST_SCHEMA_VERSION = 264;
diff --cc src/core/schema-migrations/registry.generated.ts
index 8f8345a134,4d376fcd12..87001c9313
--- a/src/core/schema-migrations/registry.generated.ts
+++ b/src/core/schema-migrations/registry.generated.ts
@@@ -263,7 -263,7 +263,8 @@@ import { v259 } from './v259-ingest-log
import { v260 } from './v260-segmented-page-size-index.ts';
import { v261 } from './v261-persistence-request-transient-retries.ts';
import { v262 } from './v262-commit-notifier.ts';
- import { v263 } from './v263-set-based-fact-insert-guards.ts';
+ import { v263 } from './v263-try-jsonb-function.ts';
++import { v264 } from './v264-set-based-fact-insert-guards.ts';
// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the
// runner sorts by version before applying.
@@@ -526,4 -526,4 +527,5 @@@ export const MIGRATIONS: Migration[] =
v261,
v262,
v263,
++ v264,
];
diff --cc src/core/schema-migrations/v264-set-based-fact-insert-guards.ts
index 6ee757ee0b,0000000000..37d3d517ce
mode 100644,000000..100644
--- a/src/core/schema-migrations/v264-set-based-fact-insert-guards.ts
+++ b/src/core/schema-migrations/v264-set-based-fact-insert-guards.ts
@@@ -1,21 -1,0 +1,21 @@@
+import type { Migration } from './types.ts';
+import { FACT_INSERT_GUARD_SQL } from '../facts/insert-guard-schema.ts';
+import { STAMP_ROW_FUNCTION } from '../persistence/attribution-schema.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.
+//
+// #7105: the facts purge refusal and withdrawal stamp run once per INSERT
+// statement (one AFTER INSERT ... REFERENCING NEW TABLE trigger,
+// facts/insert-guard-schema.ts) instead of once per inserted row. The per-row
+// facts_refuse_purged and facts_preserve_withdrawal triggers keep their
+// functions and now fire on UPDATE only. The write-attribution function is
+// re-created so the guard's withdrawal stamp (an UPDATE under
+// gbrain.fact_withdrawal_stamp) keeps the row's last_write_* values.
+// Function and trigger DDL only: no row changes.
- export const v263: Migration = {
- version: 263,
++export const v264: Migration = {
++ version: 264,
+ name: 'set_based_fact_insert_guards',
+ idempotent: true,
+ sql: `${STAMP_ROW_FUNCTION};\n${FACT_INSERT_GUARD_SQL}`,
+};
diff --cc test/facts-insert-guards-7105.test.ts
index 20545bf3c9,0000000000..add077b3a4
mode 100644,000000..100644
--- a/test/facts-insert-guards-7105.test.ts
+++ b/test/facts-insert-guards-7105.test.ts
@@@ -1,329 -1,0 +1,329 @@@
+/**
+ * #7105: the facts purge refusal and withdrawal stamp run once per INSERT
+ * statement, not once per inserted row (facts/insert-guard-schema.ts,
- * migration v263).
++ * migration v264).
+ *
+ * Protects:
+ * 1. Work count. A 6,000-row bulk insert calls the guard functions once per
+ * statement (12 statements of 500), counted by pg_stat_xact_user_functions
+ * inside the inserting transaction; a managed put of a 6,000-row fence fires
+ * guard triggers once per statement, counted by a twin of every guard
+ * trigger that records each firing. Regression: two per-row BEFORE INSERT
+ * triggers called their functions 12,000 times for 6,000 rows, about 0.75 s
+ * of the publish (the 5 s publish wait in
+ * facts-publication-large-fence-6898 missed under gate load).
+ * 2. Semantics. The same batch, run under the per-row guards (re-installed
+ * from their original SQL inside a rolled-back transaction) and under the
+ * statement guard, ends identically: the same P0001 purged_content refusal
+ * and detail for a batch carrying a purged claim, and the same stamped
+ * expired_at / valid_until for a batch carrying withdrawn rows, and keeps
+ * the last_write_* attribution the INSERT stamped or supplied (the stamp is
+ * an UPDATE under gbrain.fact_withdrawal_stamp). Updates still go through
+ * the per-row guards.
+ * 3. INSERT ... RETURNING (a CTE included) reads a withdrawn row's stamp, as
+ * the per-row guard returned it; only an insert under the deferral setting
+ * the bulk fence insert uses reads it unstamped (the documented edge).
+ * Runs on PGLite, and on Postgres when DATABASE_URL is set
+ * (test/postgres-unit-arms.txt).
+ */
+import { afterAll, beforeAll, expect, test } from 'bun:test';
+import { randomUUID } from 'node:crypto';
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { MEMORY_PURGE_GUARD_SQL } from '../src/core/facts/purge-schema.ts';
+import { FACT_WITHDRAWAL_SCHEMA_STATEMENTS } from '../src/core/facts/withdrawal-schema.ts';
+import { FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING } from '../src/core/facts/insert-guard-schema.ts';
+import { claimWorktree } from '../src/core/persistence/ownership.ts';
+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const SLUG = 'people/alice-example';
+const GUARD_FUNCTIONS = ['gbrain_refuse_purged_fact', 'gbrain_preserve_fact_withdrawal', 'gbrain_guard_inserted_facts'];
+const engines: BrainEngine[] = [];
+const dataDir = mkdtempSync(join(tmpdir(), 'gbrain-facts-guards-7105-db-'));
+let closePostgres: (() => Promise<void>) | undefined;
+
+beforeAll(async () => {
+ const backends = testBackends();
+ if (backends.includes('pglite')) {
+ const engine = new PGLiteEngine();
+ await engine.connect({ database_path: dataDir }); await engine.initSchema(); engines.push(engine);
+ }
+ if (backends.includes('postgres')) {
+ const pg = await isolatedPersistencePostgres(process.env.DATABASE_URL!);
+ engines.push(pg.engine); closePostgres = pg.close;
+ }
+}, 120_000);
+afterAll(async () => {
+ for (const engine of engines) { await disposePersistenceConsumer(engine); await engine.disconnect(); }
+ await closePostgres?.(); rmSync(dataDir, { recursive: true, force: true });
+});
+
+const claim = (i: number) => `Claim ${i} about the widget-co supply chain and its quarterly planning cadence`;
+const T = (iso: string) => new Date(iso);
+const row = (i: number, over: Record<string, unknown> = {}) => ({ fact: claim(i), kind: 'fact' as const, source: 'fixture',
+ visibility: 'private' as const, entity_slug: SLUG as string | null, source_markdown_slug: SLUG, row_num: i, valid_from: T('2020-01-01T00:00:00Z'), ...over });
+
+async function newSource(engine: BrainEngine): Promise<string> {
+ const id = `guards-${randomUUID().slice(0, 8)}`;
+ await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1)', [id]);
+ return id;
+}
+
+const rollback = new Error('rollback');
+/** Runs fn in a transaction that always rolls back; perRow re-installs the original per-row INSERT guards first. */
+async function inRolledBack<T>(engine: BrainEngine, perRow: boolean, fn: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ let out: T | undefined;
+ try {
+ await engine.transaction(async tx => {
+ if (perRow) {
+ await tx.executeRaw('DROP TRIGGER IF EXISTS facts_guard_inserted ON facts');
+ await tx.executeRaw('DROP TRIGGER IF EXISTS facts_preserve_withdrawal_insert ON facts');
+ await tx.runMigration(0, MEMORY_PURGE_GUARD_SQL);
+ for (const statement of FACT_WITHDRAWAL_SCHEMA_STATEMENTS) await tx.executeRaw(statement);
+ }
+ out = await fn(tx);
+ throw rollback;
+ });
+ } catch (error) { if (error !== rollback) throw error; }
+ return out as T;
+}
+
+/** Runs one write under a savepoint and returns 'ok' or the refusal it raised. */
+async function refusal(tx: BrainEngine, write: () => Promise<unknown>): Promise<{ code?: string; message: string; detail?: string } | 'ok'> {
+ await tx.executeRaw('SAVEPOINT guard_attempt');
+ try { await write(); await tx.executeRaw('RELEASE SAVEPOINT guard_attempt'); return 'ok'; } catch (e) {
+ await tx.executeRaw('ROLLBACK TO SAVEPOINT guard_attempt');
+ const err = e as { code?: string; message: string; detail?: string };
+ return { code: err.code, message: err.message, detail: err.detail };
+ }
+}
+
+const iso = (d: unknown) => d == null ? null : new Date(d as string).toISOString();
+
+test('a 6,000-row bulk insert calls the guard functions once per statement, not once per row', async () => {
+ for (const engine of engines) {
+ const sourceId = await newSource(engine);
+ const rows = Array.from({ length: 6000 }, (_, i) => row(i + 1));
+ const calls = await engine.transaction(async tx => {
+ await tx.executeRaw("SET LOCAL track_functions = 'pl'");
+ const read = async () => Object.fromEntries((await tx.executeRaw<{ funcname: string; calls: number }>(
+ 'SELECT funcname, calls::int AS calls FROM pg_stat_xact_user_functions WHERE funcname = ANY($1::text[])', [GUARD_FUNCTIONS]))
+ .map(r => [r.funcname, Number(r.calls)]));
+ const before = await read();
+ expect((await tx.insertFacts(rows, { source_id: sourceId })).inserted).toBe(6000);
+ const after = await read();
+ return Object.fromEntries(GUARD_FUNCTIONS.map(name => [name, (after[name] ?? 0) - (before[name] ?? 0)]));
+ });
+ // 6,000 rows in statements of 500.
+ expect(calls).toEqual({ gbrain_refuse_purged_fact: 0, gbrain_preserve_fact_withdrawal: 0, gbrain_guard_inserted_facts: 12 });
+ }
+}, 120_000);
+
+test('a managed put of a 6,000-row fence fires the guard triggers once per insert statement', async () => {
+ for (const engine of engines) {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-facts-guards-7105-'));
+ const root = join(dir, 'brain'); mkdirSync(root);
+ const sourceId = `guards-${randomUUID().slice(0, 8)}`;
+ const twins: string[] = [];
+ try {
+ await withEnv({ GBRAIN_HOME: join(dir, 'home'), GBRAIN_AUDIT_DIR: join(dir, 'audit') }, async () => {
+ await engine.executeRaw('CREATE TABLE IF NOT EXISTS guard_firings_7105 (trigger_name text, level text)');
+ await engine.executeRaw(`CREATE OR REPLACE FUNCTION count_guard_firing_7105() RETURNS trigger LANGUAGE plpgsql AS $fn$
+ BEGIN INSERT INTO guard_firings_7105 VALUES (TG_ARGV[0], TG_LEVEL); IF TG_LEVEL = 'ROW' THEN RETURN NEW; END IF; RETURN NULL; END $fn$`);
+ const guards = await engine.executeRaw<{ name: string; def: string }>(`SELECT t.tgname AS name, pg_get_triggerdef(t.oid) AS def
+ FROM pg_trigger t JOIN pg_proc p ON p.oid = t.tgfoid
+ WHERE t.tgrelid = 'facts'::regclass AND NOT t.tgisinternal AND p.proname = ANY($1::text[])`, [GUARD_FUNCTIONS]);
+ expect(guards.length).toBeGreaterThan(0);
+ for (const guard of guards) {
+ twins.push(`zz_count_${guard.name}`);
+ await engine.executeRaw(guard.def.replace(`CREATE TRIGGER ${guard.name} `, `CREATE TRIGGER zz_count_${guard.name} `)
+ .replace(/EXECUTE FUNCTION \S+\(\)$/, `EXECUTE FUNCTION count_guard_firing_7105('${guard.name}')`));
+ }
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);
+ await claimWorktree(engine, sourceId, root);
+ await engine.setConfig('sync.write_through', 'true');
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const fence = `## Facts\n\n<!--- gbrain:facts:begin -->
+| # | claim | kind | confidence | visibility | notability | valid_from | valid_until | source | context |
+|---|-------|------|------------|------------|------------|------------|-------------|--------|---------|
+${Array.from({ length: 6000 }, (_, i) => `| ${i + 1} | ${claim(i + 1)} | fact | 1.0 | private | medium | 2020-01-01 | | chat | |`).join('\n')}
+<!--- gbrain:facts:end -->\n`;
+ await submitPageMutation({ engine, sourceId, remote: false, config: { engine: engine.kind, embedding_disabled: true },
+ dryRun: false, logger: { info() {}, warn() {}, error() {} } } as any,
+ { operation: 'put_page', params: { slug: SLUG, content: `---\ntitle: Alice Example\ntype: person\n---\n# Alice Example\n\n${fence}`, request_id: randomUUID() } });
+ const [{ n }] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id=$1', [sourceId]);
+ expect(Number(n)).toBe(6000);
+ const firings = await engine.executeRaw<{ trigger_name: string; level: string; n: number }>(
+ 'SELECT trigger_name, level, count(*)::int AS n FROM guard_firings_7105 GROUP BY 1, 2 ORDER BY 1, 2');
+ // 6,000 fence rows in insert statements of 500; no per-row firing.
+ expect(firings.map(f => [f.trigger_name, f.level, Number(f.n)])).toEqual([['facts_guard_inserted', 'STATEMENT', 12]]);
+ });
+ } finally {
+ await disposePersistenceConsumer(engine);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ for (const twin of twins) await engine.executeRaw(`DROP TRIGGER IF EXISTS ${twin} ON facts`);
+ await engine.executeRaw('DROP TABLE IF EXISTS guard_firings_7105');
+ rmSync(dir, { recursive: true, force: true });
+ }
+ }
+}, 300_000);
+
+test('a batch insert carrying a purged claim is refused exactly as the per-row guard refused it', async () => {
+ for (const engine of engines) {
+ const sourceId = await newSource(engine);
+ const arm = (perRow: boolean) => inRolledBack(engine, perRow, async tx => {
+ const tomb = (i: number, subject: string) => tx.executeRaw(
+ `INSERT INTO fact_purges(source_id, visibility, subject, fact_hash) VALUES ($1, 'private', $2, gbrain_fact_fingerprint($3))`,
+ [sourceId, subject, claim(i)]);
+ await tomb(530, '*'); await tomb(560, SLUG); await tomb(20, 'people/other-example');
+ const fp = async (i: number) => (await tx.executeRaw<{ h: string }>('SELECT gbrain_fact_fingerprint($1) AS h', [claim(i)]))[0]!.h;
+ // 600 rows, two statements: the purged claims are in the second, a withdrawn one in the first.
+ await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash) VALUES ($1, 'private', '*', gbrain_fact_fingerprint($2))`, [sourceId, claim(5)]);
+ const insert = (rows: ReturnType<typeof row>[]) => refusal(tx, () => tx.insertFacts(rows, { source_id: sourceId }));
+ const batch = await insert(Array.from({ length: 600 }, (_, i) => row(i + 1)));
+ const landed = await tx.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM facts WHERE source_id=$1', [sourceId]);
+ const expiredRow = await insert([row(900, { fact: claim(530), expired_at: T('2024-01-01T00:00:00Z') })]);
+ const otherSubject = await insert([row(901, { fact: claim(20) })]);
+ const subjectless = await insert([row(902, { fact: claim(560), entity_slug: null })]);
+ const [{ id }] = await tx.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND row_num=901', [sourceId]);
+ const update = await refusal(tx, () => tx.executeRaw('UPDATE facts SET fact=$1 WHERE id=$2', [claim(530), id]));
+ return { batch, landed: Number(landed[0]!.n), expiredRow, otherSubject, subjectless, update, hash8: (await fp(530)).slice(0, 8) };
+ });
+ const perRow = await arm(true), statement = await arm(false);
+ const refused = { code: 'P0001', message: 'purged_content: this claim was purged from this source and cannot be saved again' };
+ expect(statement.batch).toMatchObject(refused);
+ // The first purged row in insertion order (530, then 560) names the refusal.
+ expect(JSON.parse((statement.batch as { detail: string }).detail)).toEqual({ table: 'facts', hash8: statement.hash8 });
+ expect(statement.landed).toBe(0);
+ expect(statement.expiredRow).toMatchObject({ code: 'P0001', message: refused.message });
+ expect(statement.otherSubject).toBe('ok');
+ expect(statement.subjectless).toBe('ok');
+ expect(statement.update).toMatchObject({ code: 'P0001', message: refused.message });
+ expect(statement).toEqual(perRow);
+ }
+}, 120_000);
+
+test('a batch insert carrying withdrawn rows is stamped exactly as the per-row guard stamped it', async () => {
+ for (const engine of engines) {
+ const sourceId = await newSource(engine);
+ const arm = (perRow: boolean) => inRolledBack(engine, perRow, async tx => {
+ const withdraw = (i: number, subject: string, at: string, opts: { v1?: boolean; visibility?: string } = {}) => tx.executeRaw(
+ `INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash, withdrawn_at)
+ VALUES ($1, $2, $3, ${opts.v1 ? 'gbrain_fact_fingerprint_v1' : 'gbrain_fact_fingerprint'}($4), $5::timestamptz)`,
+ [sourceId, opts.visibility ?? 'private', subject, claim(i), at]);
+ await withdraw(10, '*', '2023-01-01T00:00:00Z');
+ await withdraw(520, SLUG, '2023-02-01T00:00:00Z', { v1: true });
+ await withdraw(30, 'people/other-example', '2023-03-01T00:00:00Z');
+ await withdraw(40, '*', '2023-04-01T00:00:00Z'); await withdraw(40, SLUG, '2023-03-15T00:00:00Z');
+ await withdraw(50, '*', '2023-05-01T00:00:00Z');
+ await withdraw(60, '*', '2023-06-01T00:00:00Z', { visibility: 'world' });
+ await withdraw(70, '*', '2023-07-01T00:00:00Z'); await withdraw(71, SLUG, '2023-07-01T00:00:00Z');
+ const rows = Array.from({ length: 600 }, (_, i) => row(i + 1));
+ rows[9] = row(10, { valid_until: T('2025-01-01T00:00:00Z') });
+ rows[519] = row(520, { valid_until: T('2022-01-01T00:00:00Z') });
+ rows[49] = row(50, { expired_at: T('2024-06-01T00:00:00Z') });
+ rows[69] = row(70, { entity_slug: null }); rows[70] = row(71, { entity_slug: null });
+ expect((await tx.insertFacts(rows, { source_id: sourceId })).inserted).toBe(600);
+ const [{ id }] = await tx.executeRaw<{ id: number }>('SELECT id FROM facts WHERE source_id=$1 AND row_num=100', [sourceId]);
+ await tx.executeRaw('UPDATE facts SET fact=$1 WHERE id=$2', [claim(10), id]);
+ return (await tx.executeRaw<{ row_num: number; fact: string; entity_slug: string | null; expired_at: unknown; valid_until: unknown }>(
+ 'SELECT row_num, fact, entity_slug, expired_at, valid_until FROM facts WHERE source_id=$1 ORDER BY row_num', [sourceId]))
+ .map(r => ({ row_num: Number(r.row_num), fact: r.fact, entity_slug: r.entity_slug, expired_at: iso(r.expired_at), valid_until: iso(r.valid_until) }));
+ });
+ const perRow = await arm(true), statement = await arm(false);
+ const stamped = Object.fromEntries(statement.filter(r => r.expired_at).map(r => [r.row_num, [r.expired_at, r.valid_until]]));
+ expect(stamped).toEqual({
+ 10: ['2023-01-01T00:00:00.000Z', '2023-01-01T00:00:00.000Z'],
+ 40: ['2023-03-15T00:00:00.000Z', '2023-03-15T00:00:00.000Z'],
+ 50: ['2024-06-01T00:00:00.000Z', null],
+ 70: ['2023-07-01T00:00:00.000Z', '2023-07-01T00:00:00.000Z'],
+ 100: ['2023-01-01T00:00:00.000Z', '2023-01-01T00:00:00.000Z'],
+ 520: ['2023-02-01T00:00:00.000Z', '2022-01-01T00:00:00.000Z'],
+ });
+ expect(statement).toEqual(perRow);
+ }
+}, 120_000);
+
+test('a withdrawal stamp keeps the write attribution the INSERT stamped or supplied', async () => {
+ const supplied = '11111111-1111-4111-8111-111111111111', actor = '22222222-2222-4222-8222-222222222222';
+ for (const engine of engines) {
+ const sourceId = await newSource(engine);
+ const arm = (perRow: boolean) => inRolledBack(engine, perRow, async tx => {
+ for (const i of [1, 2]) await tx.executeRaw(
+ `INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash, withdrawn_at) VALUES ($1, 'private', '*', gbrain_fact_fingerprint($2), '2023-01-01T00:00:00Z')`,
+ [sourceId, claim(i)]);
+ const insert = (rows: Array<[number, number, string | null]>) => tx.executeRaw(`INSERT INTO facts (source_id, fact, kind, visibility, source, entity_slug,
+ source_markdown_slug, row_num, valid_from, write_request_id, write_principal_kind, write_principal_id,
+ last_write_request_id, last_write_principal_kind, last_write_principal_id, last_written_at)
+ SELECT $1, r.fact, 'fact', 'private', 'fixture', $2, $2, r.row_num, '2020-01-01T00:00:00Z', r.req::uuid, r.kind, r.principal,
+ r.req::uuid, r.kind, r.principal, r.at::timestamptz
+ FROM jsonb_to_recordset($3::text::jsonb) AS r(fact text, row_num integer, req text, kind text, principal text, at text)`,
+ [sourceId, SLUG, JSON.stringify(rows.map(([i, rowNum, req]) => ({ fact: claim(i), row_num: rowNum, req,
+ kind: req && 'local_cli', principal: req && 'principal-supplied', at: req && '2020-01-01T00:00:00Z' })))]);
+ // Deferred, as the bulk fence insert runs: facts_guard_inserted stamps by UPDATE.
+ await tx.executeRaw(`SELECT set_config('${FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING}', 'on', true)`);
+ // No actor set (an engine copy or backfill): supplied and absent attribution, withdrawn and not.
+ await insert([[1, 1, supplied], [2, 2, null], [3, 3, supplied]]);
+ // An actor set (a coordinated write): the INSERT stamps the actor.
+ await tx.executeRaw(`SELECT set_config('gbrain.write_request', $1, true), set_config('gbrain.write_principal_kind', 'local_cli', true),
+ set_config('gbrain.write_principal_id', 'principal-actor', true)`, [actor]);
+ await insert([[1, 4, null]]);
+ await tx.executeRaw(`SELECT set_config('gbrain.write_request', '', true), set_config('gbrain.write_principal_kind', '', true),
+ set_config('gbrain.write_principal_id', '', true), set_config('${FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING}', '', true)`);
+ // The stamp setting does not outlive the stamp: a later expiry by an unattributed writer moves attribution.
+ await tx.executeRaw(`UPDATE facts SET expired_at = '2024-01-01T00:00:00Z' WHERE source_id = $1 AND row_num = 3`, [sourceId]);
+ return (await tx.executeRaw<Record<string, unknown>>(`SELECT row_num, expired_at, write_request_id::text AS created_req, write_principal_id AS created_by,
+ last_write_request_id::text AS last_req, last_write_principal_kind AS last_kind, last_write_principal_id AS last_by,
+ CASE WHEN last_written_at = now() THEN 'now' ELSE last_written_at::text END AS last_at,
+ current_setting('gbrain.fact_withdrawal_stamp', true) AS setting
+ FROM facts WHERE source_id = $1 ORDER BY row_num`, [sourceId]))
+ .map(r => ({ ...r, row_num: Number(r.row_num), expired_at: iso(r.expired_at), last_at: r.last_at === 'now' || r.last_at == null ? r.last_at : iso(r.last_at),
+ setting: r.setting || null }) as Record<string, unknown>);
+ });
+ const perRow = await arm(true), statement = await arm(false);
+ const suppliedRow = { created_req: supplied, created_by: 'principal-supplied', last_req: supplied, last_kind: 'local_cli', last_by: 'principal-supplied',
+ last_at: '2020-01-01T00:00:00.000Z', setting: null };
+ const none = { created_req: null, created_by: null, last_req: null, last_kind: null, last_by: null, last_at: null, setting: null };
+ expect(statement).toEqual([
+ { row_num: 1, expired_at: '2023-01-01T00:00:00.000Z', ...suppliedRow },
+ { row_num: 2, expired_at: '2023-01-01T00:00:00.000Z', ...none },
+ { row_num: 3, expired_at: '2024-01-01T00:00:00.000Z', ...suppliedRow, last_req: null, last_kind: null, last_by: null, last_at: 'now' },
+ { row_num: 4, expired_at: '2023-01-01T00:00:00.000Z', created_req: actor, created_by: 'principal-actor', last_req: actor, last_kind: 'local_cli',
+ last_by: 'principal-actor', last_at: 'now', setting: null },
+ ]);
+ expect(statement).toEqual(perRow);
+ }
+}, 120_000);
+
+
+test('INSERT ... RETURNING reads the withdrawal stamp; only a deferred insert reads it from the next statement', async () => {
+ for (const engine of engines) {
+ const sourceId = await newSource(engine);
+ const seen = await inRolledBack(engine, false, async tx => {
+ await tx.executeRaw(`INSERT INTO fact_withdrawals(source_id, visibility, subject, fact_hash, withdrawn_at) VALUES ($1, 'private', '*', gbrain_fact_fingerprint($2), '2023-01-01T00:00:00Z')`,
+ [sourceId, claim(1)]);
+ const insert = async () => {
+ const [returned] = await tx.executeRaw<{ id: number; expired_at: unknown }>(`WITH ins AS (INSERT INTO facts (source_id, fact, kind, visibility, source)
+ VALUES ($1, $2, 'fact', 'private', 'fixture') RETURNING id, expired_at) SELECT id, expired_at FROM ins`, [sourceId, claim(1)]);
+ const [stored] = await tx.executeRaw<{ expired_at: unknown }>('SELECT expired_at FROM facts WHERE id = $1', [returned!.id]);
+ return { returned: iso(returned!.expired_at), stored: iso(stored!.expired_at) };
+ };
+ const plain = await insert();
+ await tx.executeRaw(`SELECT set_config('${FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING}', 'on', true)`);
+ const deferred = await insert();
+ await tx.executeRaw(`SELECT set_config('${FACT_WITHDRAWAL_STAMP_DEFERRED_SETTING}', '', true)`);
+ return { plain, deferred };
+ });
+ expect(seen).toEqual({ plain: { returned: '2023-01-01T00:00:00.000Z', stored: '2023-01-01T00:00:00.000Z' },
+ deferred: { returned: null, stored: '2023-01-01T00:00:00.000Z' } });
+ }
+}, 120_000);
+
diff --cc test/fixtures/goldens/catalog/pglite-engine-init-default.json
index 5e58cffe30,582c55accb..90cc50ea7a
--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json
@@@ -528,7 -527,8 +528,8 @@@
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",
- "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",
+ "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
+ "gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"
},
diff --cc test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
index 94f01216cc,c24e21978b..dd1469c4b1
--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json
@@@ -528,7 -527,8 +528,8 @@@
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",
- "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",
+ "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
+ "gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3ffbe1c80104ca23fb2581cfdb67541b31769cc5af9dcd1c8b84f8c3844275f4",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c393710877f69961517a5a820b741b9229ee9e20d045e736b191e8366170fedc"
},
diff --cc test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
index 39825212f3,6a6095e121..acd10f1d6d
--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json
@@@ -528,7 -527,8 +528,8 @@@
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",
- "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",
+ "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
+ "gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"
},
diff --cc test/fixtures/goldens/catalog/postgres-engine-init-default.json
index 8f37e4ee0e,b482e71c74..2029e976cc
--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json
@@@ -531,7 -530,8 +531,8 @@@
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",
- "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",
+ "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
+ "gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
"notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"
diff --cc test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
index 35d60721bb,9ea57a2ebc..ff390b706c
--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json
@@@ -531,7 -530,8 +531,8 @@@
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",
- "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",
+ "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
+ "gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
"notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3ffbe1c80104ca23fb2581cfdb67541b31769cc5af9dcd1c8b84f8c3844275f4",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=c393710877f69961517a5a820b741b9229ee9e20d045e736b191e8366170fedc"
diff --cc test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
index 3ae4535086,dc450522e7..64a892589b
--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json
@@@ -531,7 -530,8 +531,8 @@@
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",
- "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",
+ "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
+ "gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
"notify_minion_job_change()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=17f7c36408688409c80befd0a9ef9314e597d78a195418d1b94426e3d0b662f8",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"
diff --cc test/fixtures/goldens/migrations/records.json
index 8d39c70a10,0d27d340dd..8ba43d1064
--- a/test/fixtures/goldens/migrations/records.json
+++ b/test/fixtures/goldens/migrations/records.json
@@@ -1,6 -1,6 +1,6 @@@
{
"golden": {
-- "count": 258,
++ "count": 259,
"gaps": [
17,
18,
@@@ -72,7 -72,7 +72,7 @@@
"tableRows": "906d2413b13d76a06d5910885e47ed5c544be4ff3a2266e83146715721b24270",
"verifyProjectionStatistics": "0d231b04ecfbc5a4109d6fca9567bf4e8c9e9db6c3fbbb35212e026579ed6f67"
},
-- "latest": 263,
++ "latest": 264,
"records": [
{
"handler": {
@@@ -4176,18 -4176,18 +4176,31 @@@
"verify": "absent",
"version": 262
},
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "try_jsonb_function",
+ "sql": {
+ "length": 241,
+ "sha256": "ca16373eb5df962e15b59ed33ebffd4469d09ee873039600929e1b9145638272"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
+ "version": 263
++ },
+ {
+ "handler": "absent",
+ "idempotent": true,
+ "name": "set_based_fact_insert_guards",
+ "sql": {
+ "length": 8343,
+ "sha256": "d01ea4d8a212485932351ad8473d54ef7d0b65f4d5b59b1ba34e4b63bf20b4bb"
+ },
+ "sqlFor": "absent",
+ "transaction": "absent",
+ "verify": "absent",
- "version": 263
++ "version": 264
}
],
"versions": [
@@@ -4448,7 -4448,7 +4461,8 @@@
260,
261,
262,
-- 263
++ 263,
++ 264
]
},
"normalizer": "migrations-record-v1"
diff --cc test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
index 55172ede77,6e744b2f69..3406bcbcbf
--- a/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
+++ b/test/fixtures/goldens/pglite-upgrade-replay/catalog-after-boot.json
@@@ -528,7 -527,8 +528,8 @@@
"gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216",
"gbrain_stamp_trust_tier()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=4610c2e064a0d34dbb66981dd49f15fb6b0b85407327983cde76b905cd626598",
"gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",
- "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=50e9b0e5bf37eeae6555dd16c8104cb0807be6c05a79e0c82237d45162c21dc2",
+ "gbrain_stamp_write_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=e2dbafe65571fedcadc0441415f58fb5b5209b4c9cefa50e4855f58f0452327c",
+ "gbrain_try_jsonb(input text)": "RETURNS jsonb kind=f lang=plpgsql volatility=i secdef=false config=[search_path=pg_catalog, public] body_sha256=11b96a0400158fcb3dbd84255985cd11e473688c53fff64ebf92602fceccbedf",
"update_chunk_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=b870de46705a62891bb318ecdeca1d0d5ea1f8da9a9a79c4cec6569e515dbdeb",
"update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=f354d9571ef5de74a98cfd1661e09aebca711541cbdd6eb86effa48aae8822cc"
},