Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): a database guard refusal names its table, operation, branch and source relationship instead of an opaque P0001 (#5974)
garrytan98197f55ac87
diff --git a/docs/guides/write-refusals.md b/docs/guides/write-refusals.mdindex 9b382d4db4..6f2ee49d58 100644--- a/docs/guides/write-refusals.md+++ b/docs/guides/write-refusals.md@@ -37,6 +37,7 @@ of making a duplicate.| Reason | Error code | What it means | Recovery || --- | --- | --- | --- || `file_database_drift` | `source_changed` | The page's canonical file and its database copy disagree, usually because the file was edited outside a coordinated write. Neither copy was overwritten. A file with no `type:` line keeps the stored type, and titles compare trimmed, so those alone no longer cause this. | `gbrain sources reconcile <source> <slug> --brain <brain> --preview`, review the preview, resolve it, then `--apply <resolved-preview-file> --request-id <new uuid>`. Retry the original write with a **new** request ID. See [repair a file/database disagreement](concurrent-writes.md#repair-a-filedatabase-disagreement). |+| <a id="writer-coordinator-required"></a>`database_guard` or `database_trigger` | `writer_coordinator_required` (or `storage_error` for another trigger) | A database trigger refused a row while a write was being prepared or published, so nothing was committed and any canonical file already replaced was restored. With `database_guard`, a gbrain process wrote a row its publication does not own (another source, an unresolvable source, or a source checkpoint/topology change outside owner administration). This is a gbrain defect or a version mismatch between gbrain processes sharing the database, not a content conflict. The receipt's `write_error_detail` names the table, operation, guard branch, source relationship and stage; it never contains page text or source names. | On the brain host run `gbrain sources writer status --probe --json`. Its `recent_failures[].error_detail` adds the source ids and the gbrain build and host that ran the attempt (`attempt.consumer_version`). If that build differs from `gbrain --version`, upgrade or restart every gbrain process that shares the database (serve, autopilot, sync jobs), then retry with a **new** request ID. If the builds match, report `error_detail` on the gbrain issue tracker. Never force-write, edit SQL or disable the guard. || `ambiguous_source_path` | `page_identity_changed` | A source registered at a Git subfolder `<sub>` has a page whose stored path `<sub>/<file>` could mean either `<file>` in the source directory (the older Git-root spelling) or `<sub>/<file>` inside a folder of the source that repeats its name, and both files exist. Sync refuses instead of guessing. See [sources in a Git subfolder](multi-source-brains.md#sources-in-a-git-subfolder). | Rename or move one of the two files, commit, then `gbrain sync --source <source> --no-pull --retry-failed`. || `physical_root_device_changed` | `recovery_required` | The checkout's filesystem device number changed while everything else matches, which macOS can do after a reboot. When the owner token, brain, worktree, root, inode and a non-zero birth time all match and the caller can verify database ownership, the write path re-stamps ownership by itself and the write proceeds. This refusal means the automatic re-stamp could not be verified; the suggestion says why. | Do a deliberate self-transfer: `gbrain sources writer status <source>` (note `admin_state`), then `gbrain sources writer transfer prepare <source> --self-transfer --admin-intent writer_transfer_prepare --expected-state <admin_state>`, then `gbrain sources writer transfer accept <source> --path <root> --expected-epoch <epoch> --manifest <digest from prepare> --self-transfer --admin-intent writer_transfer_accept --expected-state <fresh admin_state>`. Retry the original write with the **same** request ID. Never delete ownership marker files. || <a id="embedding_budget_below_worst_case"></a>`embedding_budget_below_worst_case` | `embedding_budget_below_worst_case` | `gbrain migrate embeddings` (or the local `migrate_embeddings` operation) was given a `--max-cost-usd` cap below the migration's worst-case authorization: every planned provider request at its maximum input size, plus any debits a resumed run already holds. The run stopped before any provider request, re-chunk or vector invalidation, so nothing changed. The message and JSON carry `cap_usd`, `worst_case_usd`, `debited_usd` and `required_cap_usd`. | Re-run with the value the `suggestion` names, for example `gbrain migrate embeddings --to <provider:model> --dim <N> --max-cost-usd <required_cap_usd> --yes` (operation: `max_cost_usd`). Preview first with `--dry-run`, which prints the worst-case authorization beside the estimate. Requests settle to reported usage, so actual spend is usually far below the cap. See [embedding migration](embedding-migration.md). |diff --git a/src/core/persistence/connector-errors.ts b/src/core/persistence/connector-errors.tsindex de1053be14..bfe5029d54 100644--- a/src/core/persistence/connector-errors.ts+++ b/src/core/persistence/connector-errors.ts@@ -63,7 +63,15 @@ export function connectorFenceHint(source: string): string {+ `then re-attempt the item: gbrain sources retry-held ${source}`;}-export function receiptDeliveredHint(receipt: { error_code?: string | null; error_message?: string | null; source_id?: string; slug?: string | null; intent?: Record<string, unknown> | null }):+/** #5974: a trigger refusal is a gbrain defect or a writer-version mismatch, not a content conflict. */+export const DATABASE_REFUSAL_HINT = 'This is not a content conflict: a gbrain process wrote a row its publication did not own, so the database refused it and nothing was committed. '+ + 'On the brain host run gbrain sources writer status --probe --json; recent_failures[].error_detail names the table, operation, guard branch, sources, '+ + 'and the gbrain build and host that ran the attempt. If that build differs from gbrain --version, upgrade or restart every gbrain process sharing this database '+ + '(serve, autopilot, sync jobs), then retry with a new request ID. If the builds match, report error_detail (it contains no page text) on the gbrain issue tracker. '+ + 'Do not force-write, edit SQL, or disable the guard; ask the user before changing which hosts own the brain.';++export function receiptDeliveredHint(receipt: { error_code?: string | null; error_message?: string | null; source_id?: string; slug?: string | null; intent?: Record<string, unknown> | null;+ error_detail?: Record<string, unknown> | null }):{ suggestion: string; detail?: string; docs: string } | null {const source = receipt.source_id ?? '<source>';switch (receipt.error_code) {@@ -88,6 +96,13 @@ export function receiptDeliveredHint(receipt: { error_code?: string | null; errosuggestion: `The embedding provider gave no usable vector for some chunks of ${slug}; the other chunks were stored and nothing is retried. `+ `Inspect those chunks' text (empty, whitespace- or symbol-only chunks are the usual cause) or the provider, then run gbrain embed ${slug}${sourceFlag}.` };}+ case 'writer_coordinator_required':+ case 'storage_error': {+ // #5974: a database trigger refused the publication (see publication-failure.ts).+ const origin = receipt.error_detail?.origin;+ if (origin !== 'database_guard' && origin !== 'database_trigger') return null;+ return { detail: String(origin), docs: docsAnchor('writer_coordinator_required'), suggestion: DATABASE_REFUSAL_HINT };+ }case 'connector_fence_below_timeline':return { docs: docsAnchor('connector_fence_below_timeline'), detail: 'fence_not_carried', suggestion: connectorFenceHint(source) };case 'owner_unavailable':diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 189475eb9b..a4ac6b8c27 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -472,6 +472,7 @@ export class PersistenceConsumer {this.preparing.delete(row.id);preparationActive = false;const done = await publishMutation(this.engine, row, prepared, this.hostId);+ if (done.state === 'failed') this.log('publication', done.error_code ?? 'storage_error', done.error_message ?? undefined);if (done.state === 'committed' && row.worktree_id && !String(row.intent?.kind).startsWith('managed_sync_')) {this.foregroundCounts.set(row.worktree_id, this.foregroundCompletions(row.worktree_id) + 1);}@@ -484,7 +485,9 @@ export class PersistenceConsumer {}const current = await getWriteRequestById(this.engine, row.id);if (current && !isTerminal(current) && current.execution_token === row.execution_token && !current.recovery) {- return isTerminal(await finishUnpublishedFailure(this.engine, current, error));+ const done = await finishUnpublishedFailure(this.engine, current, error, preparationActive ? 'preparation' : 'publication');+ if (done.state === 'failed') this.log(preparationActive ? 'preparation' : 'publication', done.error_code ?? 'storage_error', done.error_message ?? undefined);+ return isTerminal(done);}throw error;} finally {diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex cc6b8f2606..157358d331 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -26,6 +26,7 @@ import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistencimport { assertBundleRecoveryBinding, bundleFileHash, prepareBundleRecovery, publishStagedBundleFile, stageBundleFile, type MutationFile } from './bundle-files.ts';import { assertKnowledgePublicationAllowed } from '../shared-skills/knowledge-guard.ts';import { classifyMirrorPage, sourceMirrorReadOnly } from './mirror-read-only.ts';+import { databaseRefusal, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';interface PreparedMutationBase {sourceExclusive?: boolean;@@ -69,8 +70,10 @@ function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingF// Effect recovery uses the same confined durable publication primitive, under// its own recovery record and native root capability.export { fileHash as persistenceFileHash, publishFile as publishPersistenceFile };-function requestError(error: unknown): { code: string; message: string } {+function requestError(error: unknown): PublicationFailure {if (error instanceof OperationError) return { code: error.code, message: error.message };+ const refusal = databaseRefusal(error);+ if (refusal) return refusal;const code = (error as { code?: string })?.code;if (code === 'revision_conflict') {return { code, message: error instanceof Error && error.message ? error.message : 'The page changed after the supplied revision was read.' };@@ -84,8 +87,9 @@ export function transientDatabaseFailure(error: unknown): boolean {return ['40001','40P01','55P03','57014','53300','57P01','57P02','57P03','08000','08003','08006','08001','08004','ECONNRESET','ECONNREFUSED','ETIMEDOUT','CONNECTION_CLOSED','CONNECTION_ENDED'].includes(String((error as {code?:string})?.code));}-export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRequest, error: unknown): Promise<WriteRequest> {- const failure = requestError(error);+export async function finishUnpublishedFailure(engine: BrainEngine, row: WriteRequest, error: unknown,+ stage: PublicationStage = 'publication'): Promise<WriteRequest> {+ const failure = withAttempt(requestError(error), stage);if (mayReprepare(row, failure) || transientDatabaseFailure(error)) {await releaseUnpublishedClaim(engine, row, transientDatabaseFailure(error) ? 'database_contention' : 'revision_changed_repreparing');return (await getWriteRequestById(engine, row.id))!;@@ -265,7 +269,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr// Even a rejected prepare can retain a journal record; do not leave that// record unaccounted or let a sibling publication bypass its recovery.const failure = !transactionBodyCompleted && !mayReprepare(row, requestError(error)) && !transientDatabaseFailure(error)- ? requestError(error) : undefined;+ ? withAttempt(requestError(error), published ? 'after_file_publication' : 'publication') : undefined;try { await markRecovering(engine, row, failure ? 'publication_failed' : published ? 'commit_outcome_uncertain' : 'publication_not_started', failure); }catch { /* database outage: durable recovery record remains discoverable */ }if (lock) {@@ -285,7 +289,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr}export async function recoverPublication(engine: BrainEngine, id: string, hostId = localHostId(), alreadyLocked = false,- terminalError?: { code: string; message: string }, capacityAlreadyHeld = false, hooks: PublicationHooks = {}): Promise<WriteRequest> {+ terminalError?: PublicationFailure, capacityAlreadyHeld = false, hooks: PublicationHooks = {}): Promise<WriteRequest> {let row = await getWriteRequestById(engine, id);if (!row) throw new OperationError('not_found', 'Write request not found.');if (!row.recovery) return row;@@ -359,7 +363,8 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdassertRecoveryStagingAbsent(record);}// Withdrawal is authoritative DB state and is never rolled back here.- const failure = terminalError ?? (current.error_code ? {code:current.error_code,message:current.error_message ?? 'Publication failed before database completion.'} : undefined);+ const failure: PublicationFailure | undefined = terminalError ?? (current.error_code ? {code:current.error_code,message:current.error_message ?? 'Publication failed before database completion.',+ ...(current.error_detail ? { detail: current.error_detail as unknown as PublicationFailureDetail } : {})} : undefined);if (failure) return completeWrite(tx, current, conflictCode(failure.code) ? 'conflict' : 'failed', {}, failure);for (const key of ['brain', `worktree:${current.worktree_id}`]) await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes-$2 WHERE key=$1', [key, Number(current.recovery_bytes)]);const [queued] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state='queued',execution_token=NULL,diff --git a/src/core/persistence/diagnostics.ts b/src/core/persistence/diagnostics.tsindex 6bb1e6189b..c371154227 100644--- a/src/core/persistence/diagnostics.ts+++ b/src/core/persistence/diagnostics.ts@@ -5,6 +5,7 @@ import { publicationConcurrency } from './pool-capacity.ts';import { WRITER_INSPECTION_HINT } from './admin-intent.ts';import { writeHealth } from './health.ts';import type { WriteRequestState } from './types.ts';+import { DATABASE_REFUSAL_HINT } from './connector-errors.ts';export const WRITER_NEXT_ACTIONS: Record<string, string> = {unexpected_staging_bytes: 'Keep the worktree blocked and retain its staging files and recovery capacity. Compare the recorded staging size and hash, then reconcile unexpected bytes explicitly before retrying; never discard unverified staging files.',@@ -23,6 +24,7 @@ export const WRITER_NEXT_ACTIONS: Record<string, string> = {consumer_stopping: 'Restart the resident owner and inspect the same request_id before resubmitting.',source_changed: 'Inspect the source incarnation and worktree binding; queued requests cannot follow a recreated source.',permission_denied: 'Inspect the durable principal and current source, operation, and namespace grants.',+ writer_coordinator_required: DATABASE_REFUSAL_HINT,};export function writerNextAction(reason: string | null | undefined): string {return reason && WRITER_NEXT_ACTIONS[reason] || 'Inspect the sanitized receipt and owner diagnostics before retrying with the same request_id.';@@ -70,11 +72,17 @@ export async function readWriterDiagnostics(engine: BrainEngine) {const effects = await engine.executeRaw(`SELECT e.kind,e.state,COUNT(*)::integer AS count,MIN(r.created_at) AS oldest_atFROM persistence_effects e JOIN persistence_requests r ON r.id=e.request_idWHERE e.state<>'committed' GROUP BY e.kind,e.state ORDER BY e.kind,e.state`);+ // #5974: trusted-admin view of database refusals, including owner-only source ids and the executing build.+ const failures = await engine.executeRaw<{ request_id: string; operation: string; source_id: string; state: WriteRequestState;+ error_code: string | null; error_detail: Record<string, unknown>; completed_at: Date | string | null }>(+ `SELECT request_id,operation,source_id,state,error_code,error_detail,completed_at FROM persistence_requests+ WHERE error_detail IS NOT NULL ORDER BY sequence DESC LIMIT 20`);const limits = await readJournalLimits(engine);const { persistenceConsumerStatus } = await import('./service.ts');const ingress = persistenceConsumerStatus(engine);return { ...brain, sampled_at: new Date().toISOString(), publication_concurrency: publicationConcurrency(engine),ingress, worktrees, counters, queue, effects, limits, capacity: capacityDiagnostics(counters, limits),+ recent_failures: failures.map(row => ({ ...row, next_action: writerNextAction(row.error_code === 'storage_error' ? 'writer_coordinator_required' : row.error_code) })),blockers: blockers.map(row => {const health = writeHealth(row);const advice = writerNextAction(row.blocked_reason ?? row.error_code);diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.tsindex c004a5d153..5952f4b0c0 100644--- a/src/core/persistence/journal.ts+++ b/src/core/persistence/journal.ts@@ -8,6 +8,7 @@ import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentiimport { retryWriteAdmission } from './admission-retry.ts';import { writeHealth, type WriteHealthFacts } from './health.ts';import { writerStamp } from './writer-versions.ts';+import { publicFailureDetail } from './publication-failure.ts';import { catalogueError } from '../error-catalogue.ts';import { ACTIVE_REFRESH_STATES_SQL, refreshFenceClear } from './worktree-refresh-schema.ts';import { assertMutationProtocol, assertSharedSkillPersistence, declarePersistenceProtocol, PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';@@ -297,7 +298,7 @@ export async function prepareRecovery(engine: BrainEngine, row: WriteRequest, re/** In the SAME transaction as page publication. Counters are always before request locks. */export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'committed' | 'conflict' | 'failed' | 'cancelled',- outcome: Record<string, unknown>, error?: { code: string; message: string }): Promise<WriteRequest> {+ outcome: Record<string, unknown>, error?: { code: string; message: string; detail?: unknown }): Promise<WriteRequest> {// Every acknowledged terminal state survives a crash, including cancellation// and pre-publication failures that do not enter the file coordinator.await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");@@ -310,15 +311,16 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'coif (row.execution_token !== current.execution_token) throw new OperationError('write_claim_lost', 'Write claim changed before completion.');const [effects] = await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytesFROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);- if (jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + Number(effects.bytes) > Number(current.terminal_reservation)) throw capacityError('terminal result and effects exceed their reserved bounded encoding');+ if (jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + (error?.detail ? jsonBytes(error.detail) : 0) + Number(effects.bytes) > Number(current.terminal_reservation)) throw capacityError('terminal result and effects exceed their reserved bounded encoding');// Only publication stamps the consumer; failures, cancellations and conflicts leave it unset.const stamp = writerStamp();const [done] = await tx.executeRaw<WriteRequest>(`UPDATE persistence_requests SET state=$2,outcome=$3::text::jsonb,- error_code=$4,error_message=$5,completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,+ error_code=$4,error_message=$5,error_detail=COALESCE($8::text::jsonb,error_detail),completed_at=now(),updated_at=now(),claim_expires_at=NULL,blocked_reason=NULL,consumer_version=CASE WHEN $2='committed' THEN $6 ELSE consumer_version END,consumer_host_id=CASE WHEN $2='committed' THEN $7::uuid ELSE consumer_host_id END,published_at=CASE WHEN $2='committed' THEN now() ELSE published_at END- WHERE id=$1::uuid RETURNING *`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null, stamp.version, stamp.hostId]);+ WHERE id=$1::uuid RETURNING *`, [row.id, state, JSON.stringify(outcome), error?.code ?? null, error?.message ?? null, stamp.version, stamp.hostId,+ error?.detail ? JSON.stringify(error.detail) : null]);await tx.executeRaw(`UPDATE persistence_counters SET outstanding_count=outstanding_count-1,intent_bytes=intent_bytes-$2WHERE key=ANY($1::text[])`, [['brain', principalKey(requestPrincipal(row))], Number(current.intent_bytes)]);// Recovery bytes remain reserved until physical cleanup has been verified.@@ -340,10 +342,12 @@ export async function clearResolvedRecovery(engine: BrainEngine, id: string): Prawait tx.executeRaw('UPDATE persistence_requests SET recovery=NULL,recovery_bytes=0,blocked_reason=NULL WHERE id=$1::uuid', [id]);});}-export async function markRecovering(engine: SqlEngine, row: WriteRequest, reason: string, failure?: {code:string;message:string}): Promise<void> {+export async function markRecovering(engine: SqlEngine, row: WriteRequest, reason: string, failure?: {code:string;message:string;detail?:unknown}): Promise<void> {await engine.executeRaw(`UPDATE persistence_requests SET state='recovering',blocked_reason=$3,updated_at=now(),- error_code=COALESCE(error_code,$4),error_message=COALESCE(error_message,$5)- WHERE id=$1::uuid AND execution_token=$2::uuid AND state IN ('running','recovering') AND ${PERSISTENCE_PROTOCOL_PREDICATE}`, [row.id, row.execution_token, reason, failure?.code ?? null, failure?.message ?? null]);+ error_code=COALESCE(error_code,$4),error_message=COALESCE(error_message,$5),+ error_detail=CASE WHEN error_code IS NULL THEN $6::text::jsonb ELSE error_detail END+ WHERE id=$1::uuid AND execution_token=$2::uuid AND state IN ('running','recovering') AND ${PERSISTENCE_PROTOCOL_PREDICATE}`,+ [row.id, row.execution_token, reason, failure?.code ?? null, failure?.message ?? null, failure?.detail ? JSON.stringify(failure.detail) : null]);}/*** PGLite has no autovacuum. The resident owner reclaims queue churn and keeps@@ -378,7 +382,7 @@ export async function compactWriteReceipts(engine: BrainEngine, retentionDays?:if(unfinished.length) return 0;const [effects]=await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytesFROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);- const retained=Math.min(Number(current.terminal_reservation),jsonBytes(current.authority)+jsonBytes(current.outcome??{})+Number(effects.bytes)+1024);+ const retained=Math.min(Number(current.terminal_reservation),jsonBytes(current.authority)+jsonBytes(current.outcome??{})+(current.error_detail?jsonBytes(current.error_detail):0)+Number(effects.bytes)+1024);await tx.executeRaw('UPDATE persistence_requests SET intent=NULL,compacted=true,error_message=NULL,terminal_reservation=$2 WHERE id=$1::uuid',[row.id,retained]);for(const key of keys) await tx.executeRaw('UPDATE persistence_counters SET terminal_bytes=terminal_bytes-$2 WHERE key=$1',[key,Number(current.terminal_reservation)-retained]);return 1;@@ -392,6 +396,7 @@ export function receiptFor(row: WriteRequest, facts?: WriteHealthFacts, now = Darequest_id: row.request_id, state: row.state,...writeHealth(row, facts, now),...(row.error_code ? { write_error: row.error_code } : {}),+ ...(row.error_detail ? { write_error_detail: publicFailureDetail(row.error_detail) } : {}),...(row.blocked_reason ? { blocked_reason: row.blocked_reason } : {}),...(row.compacted ? { compacted: true } : {}),created_at: new Date(row.created_at).toISOString(), updated_at: new Date(row.updated_at).toISOString(),diff --git a/src/core/persistence/model.ts b/src/core/persistence/model.tsindex 8f230a22f2..6b3858edcc 100644--- a/src/core/persistence/model.ts+++ b/src/core/persistence/model.ts@@ -82,6 +82,8 @@ export interface WriteRequest {outcome: Record<string, unknown> | null;error_code: string | null;error_message: string | null;+ /** #5974 structured failure (publication-failure.ts); receipts expose only its public view. */+ error_detail?: Record<string, unknown> | null;blocked_reason: string | null;compacted: boolean;publication_started: boolean;diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsnew file mode 100644index 0000000000..de5c0ae792--- /dev/null+++ b/src/core/persistence/publication-failure.ts@@ -0,0 +1,84 @@+import { OperationError } from '../ops/contract.ts';+import { writerStamp } from './writer-versions.ts';++/**+ * #5974: a database refusal during preparation or publication becomes a+ * structured, bounded diagnostic instead of an opaque storage_error. Only+ * fixed identifiers are kept: trigger function, table, operation, guard+ * branch and the source relationship. Page text, SQL and row values never are.+ */+export type PublicationStage = 'preparation' | 'publication' | 'after_file_publication';+export interface PublicationFailureDetail {+ origin: 'database_guard' | 'database_trigger' | 'database';+ sqlstate: string;+ raiser?: string;+ table?: string;+ op?: string;+ branch?: string;+ relationship?: string;+ /** Owner-only: source identifiers can name private sources. */+ sources?: { target: string | null; old: string | null; allowed: string[] };+ stage?: PublicationStage;+ /** Owner-only: the build and host that executed the failed attempt. */+ attempt?: { consumer_version: string; consumer_host_id: string | null };+}+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail }++const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;+const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;+const GUARD_PREFIX = 'writer_coordinator_required:';+const RELATIONSHIP_TEXT: Record<string, string> = {+ different_source: 'a row in a source this publication does not own',+ missing_source: 'a row whose source could not be resolved',+ old_source_outside: 'a row moved from a source this publication does not own',+ checkpoint_outside_owner: 'a source sync checkpoint outside owner publication',+ topology_outside_administration: 'a source topology change outside writer administration',+};++function guardDetail(raw: unknown): Pick<PublicationFailureDetail, 'op' | 'relationship' | 'sources'> {+ if (typeof raw !== 'string' || raw.length > 4096) return {};+ let parsed: Record<string, unknown>;+ try { parsed = JSON.parse(raw) as Record<string, unknown>; } catch { return {}; }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};+ const allowed = Array.isArray(parsed.allowed) ? parsed.allowed.map(ident).filter((v): v is string => !!v).slice(0, 32) : [];+ const target = ident(parsed.target_source) ?? null, old = ident(parsed.old_source) ?? null;+ return { op: ident(parsed.op), relationship: ident(parsed.relationship),+ ...(target || old || allowed.length ? { sources: { target, old, allowed } } : {}) };+}++/** Null when the error is not a database refusal this module recognizes. */+export function databaseRefusal(error: unknown): PublicationFailure | null {+ if (error instanceof OperationError || !error || typeof error !== 'object') return null;+ const e = error as Record<string, unknown>;+ const sqlstate = typeof e.code === 'string' && /^[0-9A-Z]{5}$/.test(e.code) ? e.code : null;+ if (sqlstate !== 'P0001') return null;+ const where = typeof e.where === 'string' ? e.where : '';+ const raiser = ident(/PL\/pgSQL function (?:[A-Za-z_][A-Za-z0-9_]*\.)?([A-Za-z_][A-Za-z0-9_]*)[( ]/.exec(where)?.[1]);+ const table = ident(e.table_name ?? e.table);+ const constraint = typeof (e.constraint_name ?? e.constraint) === 'string' ? String(e.constraint_name ?? e.constraint) : '';+ const message = typeof e.message === 'string' ? e.message : '';+ if (message.startsWith(GUARD_PREFIX) || constraint.startsWith('managed_writer_guard')) {+ const branch = constraint.startsWith('managed_writer_guard:') ? ident(constraint.slice('managed_writer_guard:'.length)) : undefined;+ const detail: PublicationFailureDetail = { origin: 'database_guard', sqlstate, raiser: raiser ?? 'gbrain_require_managed_writer',+ ...(table ? { table } : {}), ...(branch ? { branch } : {}), ...guardDetail(e.detail) };+ const what = detail.relationship ? RELATIONSHIP_TEXT[detail.relationship] ?? 'a row outside its allowlist' : 'a row outside its allowlist';+ return { code: 'writer_coordinator_required', detail, message:+ `The managed-writer database guard refused ${detail.op ? `an ${detail.op}` : 'a write'}${table ? ` on ${table}` : ''}: ${what}. Nothing was committed.` };+ }+ return { code: 'storage_error', message: `Publication failed (P0001${raiser ? ` in ${raiser}` : ''}). Inspect owner diagnostics.`,+ detail: { origin: raiser ? 'database_trigger' : 'database', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}) } };+}++/** Stamps which build, host and stage ran the failed attempt. */+export function withAttempt(failure: PublicationFailure, stage: PublicationStage): PublicationFailure {+ if (!failure.detail) return failure;+ const stamp = writerStamp();+ return { ...failure, detail: { ...failure.detail, stage, attempt: { consumer_version: stamp.version, consumer_host_id: stamp.hostId } } };+}++/** The receipt view any caller may read: fixed enums only, no source identifiers, host or build. */+export function publicFailureDetail(detail: unknown): Record<string, unknown> | undefined {+ if (!detail || typeof detail !== 'object' || Array.isArray(detail)) return undefined;+ const { sources: _sources, attempt: _attempt, ...rest } = detail as PublicationFailureDetail;+ return rest as unknown as Record<string, unknown>;+}diff --git a/src/core/persistence/writer-guard-schema.ts b/src/core/persistence/writer-guard-schema.tsindex 574de90dcc..acb99c97ec 100644--- a/src/core/persistence/writer-guard-schema.ts+++ b/src/core/persistence/writer-guard-schema.ts@@ -21,12 +21,16 @@ BEGINIS NOT DISTINCT FROM (OLD.last_commit,OLD.last_sync_at,OLD.newest_content_at) THEN RETURN NEW; END IF;allowed := COALESCE(NULLIF(current_setting('gbrain.write_sources',true),''),'[]')::jsonb;IF NOT (allowed ? NEW.id) THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source checkpoints require canonical owner publication';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source checkpoints require canonical owner publication',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:checkpoint',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship','checkpoint_outside_owner','target_source',NEW.id,'old_source',OLD.id,'allowed',allowed)::text;END IF;RETURN NEW;END IF;IF COALESCE(current_setting('gbrain.topology_change',true),'') <> 'on' THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source topology must be drained and changed through writer administration';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source topology must be drained and changed through writer administration',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:topology',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship','topology_outside_administration','target_source',row_data->>'id','old_source',old_data->>'id')::text;END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;ELSIF TG_TABLE_NAME IN ('facts','takes') AND TG_OP='UPDATE' THEN@@ -47,7 +51,11 @@ BEGINIF target_source IS NULL AND TG_OP='DELETE' THEN RETURN OLD; END IF;allowed := COALESCE(NULLIF(current_setting('gbrain.write_sources',true),''),'[]')::jsonb;IF target_source IS NULL OR NOT (allowed ? target_source) OR (old_source IS NOT NULL AND NOT (allowed ? old_source)) THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: canonical writer must use the persistence coordinator';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: canonical writer must use the persistence coordinator',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:allowlist',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship',CASE WHEN target_source IS NULL THEN 'missing_source'+ WHEN NOT (allowed ? target_source) THEN 'different_source' ELSE 'old_source_outside' END,+ 'target_source',target_source,'old_source',old_source,'allowed',allowed)::text;END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END $fn$;diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 568c882b54..cb006bd6fc 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1220,12 +1220,16 @@ BEGINIS NOT DISTINCT FROM (OLD.last_commit,OLD.last_sync_at,OLD.newest_content_at) THEN RETURN NEW; END IF;allowed := COALESCE(NULLIF(current_setting('gbrain.write_sources',true),''),'[]')::jsonb;IF NOT (allowed ? NEW.id) THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source checkpoints require canonical owner publication';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source checkpoints require canonical owner publication',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:checkpoint',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship','checkpoint_outside_owner','target_source',NEW.id,'old_source',OLD.id,'allowed',allowed)::text;END IF;RETURN NEW;END IF;IF COALESCE(current_setting('gbrain.topology_change',true),'') <> 'on' THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source topology must be drained and changed through writer administration';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source topology must be drained and changed through writer administration',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:topology',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship','topology_outside_administration','target_source',row_data->>'id','old_source',old_data->>'id')::text;END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;ELSIF TG_TABLE_NAME IN ('facts','takes') AND TG_OP='UPDATE' THEN@@ -1246,7 +1250,11 @@ BEGINIF target_source IS NULL AND TG_OP='DELETE' THEN RETURN OLD; END IF;allowed := COALESCE(NULLIF(current_setting('gbrain.write_sources',true),''),'[]')::jsonb;IF target_source IS NULL OR NOT (allowed ? target_source) OR (old_source IS NOT NULL AND NOT (allowed ? old_source)) THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: canonical writer must use the persistence coordinator';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: canonical writer must use the persistence coordinator',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:allowlist',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship',CASE WHEN target_source IS NULL THEN 'missing_source'+ WHEN NOT (allowed ? target_source) THEN 'different_source' ELSE 'old_source_outside' END,+ 'target_source',target_source,'old_source',old_source,'allowed',allowed)::text;END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END \$fn\$;diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 1466eae354..6288d52244 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -1923,12 +1923,16 @@ BEGINIS NOT DISTINCT FROM (OLD.last_commit,OLD.last_sync_at,OLD.newest_content_at) THEN RETURN NEW; END IF;allowed := COALESCE(NULLIF(current_setting('gbrain.write_sources',true),''),'[]')::jsonb;IF NOT (allowed ? NEW.id) THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source checkpoints require canonical owner publication';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source checkpoints require canonical owner publication',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:checkpoint',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship','checkpoint_outside_owner','target_source',NEW.id,'old_source',OLD.id,'allowed',allowed)::text;END IF;RETURN NEW;END IF;IF COALESCE(current_setting('gbrain.topology_change',true),'') <> 'on' THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source topology must be drained and changed through writer administration';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source topology must be drained and changed through writer administration',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:topology',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship','topology_outside_administration','target_source',row_data->>'id','old_source',old_data->>'id')::text;END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;ELSIF TG_TABLE_NAME IN ('facts','takes') AND TG_OP='UPDATE' THEN@@ -1949,7 +1953,11 @@ BEGINIF target_source IS NULL AND TG_OP='DELETE' THEN RETURN OLD; END IF;allowed := COALESCE(NULLIF(current_setting('gbrain.write_sources',true),''),'[]')::jsonb;IF target_source IS NULL OR NOT (allowed ? target_source) OR (old_source IS NOT NULL AND NOT (allowed ? old_source)) THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: canonical writer must use the persistence coordinator';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: canonical writer must use the persistence coordinator',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:allowlist',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship',CASE WHEN target_source IS NULL THEN 'missing_source'+ WHEN NOT (allowed ? target_source) THEN 'different_source' ELSE 'old_source_outside' END,+ 'target_source',target_source,'old_source',old_source,'allowed',allowed)::text;END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END \$fn\$;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex ebc2c73baa..593f50645c 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -197,6 +197,7 @@ import { v193 } from './v193-f1-write-attribution.ts';import { v194 } from './v194-f0-worktree-refreshes.ts';import { v195 } from './v195-f3-access-token-grants.ts';import { v196 } from './v196-f4-planner-stats.ts';+import { v197 } from './v197-publication-failure-detail.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -392,4 +393,5 @@ export const MIGRATIONS: Migration[] = [v194,v195,v196,+ v197,];diff --git a/src/core/schema-migrations/v197-publication-failure-detail.ts b/src/core/schema-migrations/v197-publication-failure-detail.tsnew file mode 100644index 0000000000..4851d85deb--- /dev/null+++ b/src/core/schema-migrations/v197-publication-failure-detail.ts@@ -0,0 +1,21 @@+import type { Migration } from './types.ts';+import { MANAGED_WRITER_GUARD_SQL } from '../persistence/writer-guard-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.+//+// #5974: a refused publication names what refused it. The managed-writer guard+// is re-installed so each RAISE carries TABLE/SCHEMA, a+// CONSTRAINT='managed_writer_guard:<branch>' marker and a JSON DETAIL with the+// operation and source relationship (no row values). persistence_requests gains+// error_detail, the bounded structured failure (publication-failure.ts) that+// survives recovery and compaction. Column-only and nullable; like v178 it is+// migration-created on PGLite and no index references it.+export const v197: Migration = {+ version: 197,+ name: 'publication_failure_detail',+ idempotent: true,+ sql: `+ ALTER TABLE persistence_requests ADD COLUMN IF NOT EXISTS error_detail jsonb;+ ${MANAGED_WRITER_GUARD_SQL}`,+};diff --git a/src/schema.sql b/src/schema.sqlindex 6b0ecdbe51..b1e7f75033 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -1919,12 +1919,16 @@ BEGINIS NOT DISTINCT FROM (OLD.last_commit,OLD.last_sync_at,OLD.newest_content_at) THEN RETURN NEW; END IF;allowed := COALESCE(NULLIF(current_setting('gbrain.write_sources',true),''),'[]')::jsonb;IF NOT (allowed ? NEW.id) THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source checkpoints require canonical owner publication';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source checkpoints require canonical owner publication',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:checkpoint',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship','checkpoint_outside_owner','target_source',NEW.id,'old_source',OLD.id,'allowed',allowed)::text;END IF;RETURN NEW;END IF;IF COALESCE(current_setting('gbrain.topology_change',true),'') <> 'on' THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source topology must be drained and changed through writer administration';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: source topology must be drained and changed through writer administration',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:topology',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship','topology_outside_administration','target_source',row_data->>'id','old_source',old_data->>'id')::text;END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;ELSIF TG_TABLE_NAME IN ('facts','takes') AND TG_OP='UPDATE' THEN@@ -1945,7 +1949,11 @@ BEGINIF target_source IS NULL AND TG_OP='DELETE' THEN RETURN OLD; END IF;allowed := COALESCE(NULLIF(current_setting('gbrain.write_sources',true),''),'[]')::jsonb;IF target_source IS NULL OR NOT (allowed ? target_source) OR (old_source IS NOT NULL AND NOT (allowed ? old_source)) THEN- RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: canonical writer must use the persistence coordinator';+ RAISE EXCEPTION USING ERRCODE='P0001', MESSAGE='writer_coordinator_required: canonical writer must use the persistence coordinator',+ TABLE=TG_TABLE_NAME, SCHEMA=TG_TABLE_SCHEMA, CONSTRAINT='managed_writer_guard:allowlist',+ DETAIL=jsonb_build_object('op',TG_OP,'relationship',CASE WHEN target_source IS NULL THEN 'missing_source'+ WHEN NOT (allowed ? target_source) THEN 'different_source' ELSE 'old_source_outside' END,+ 'target_source',target_source,'old_source',old_source,'allowed',allowed)::text;END IF;IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;END $fn$;diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-default.json b/test/fixtures/goldens/catalog/pglite-engine-init-default.jsonindex 0233c0bd2b..9f9b1f453f 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-default.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-default.json@@ -311,7 +311,7 @@"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f23ed35b3590e5290a8045c1867957a1227d8fbccf6a6ada70e506098c234fc2","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",@@ -2145,7 +2145,8 @@"35 admitter_host_id uuid/uuid NULL","36 consumer_version text/text NULL","37 consumer_host_id uuid/uuid NULL",- "38 published_at timestamp with time zone/timestamptz NULL"+ "38 published_at timestamp with time zone/timestamptz NULL",+ "39 error_detail jsonb/jsonb NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.jsonindex b65f7c72d5..2b71d87416 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-fts-portuguese.json@@ -311,7 +311,7 @@"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f23ed35b3590e5290a8045c1867957a1227d8fbccf6a6ada70e506098c234fc2","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",@@ -2145,7 +2145,8 @@"35 admitter_host_id uuid/uuid NULL","36 consumer_version text/text NULL","37 consumer_host_id uuid/uuid NULL",- "38 published_at timestamp with time zone/timestamptz NULL"+ "38 published_at timestamp with time zone/timestamptz NULL",+ "39 error_detail jsonb/jsonb NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.jsonindex fbe78328cd..47f6f215f3 100644--- a/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-engine-init-high-dims.json@@ -311,7 +311,7 @@"gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_preserve_fact_withdrawal()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=9beb118551a08451a228146373f50f2aa2ce0cfe89937e937d361b33224aa0aa","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f23ed35b3590e5290a8045c1867957a1227d8fbccf6a6ada70e506098c234fc2","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","gbrain_stamp_revision_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=d446ed1145d8bb9c93cb0ca4aa076a5dc7a5fe07b3e79518adaf1b17b0a51216","gbrain_stamp_version_attribution()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=1b28a0e5769198d86490dc20b2aee80b7e6595670428a63ac9c6825cd2a35b10",@@ -2141,7 +2141,8 @@"35 admitter_host_id uuid/uuid NULL","36 consumer_version text/text NULL","37 consumer_host_id uuid/uuid NULL",- "38 published_at timestamp with time zone/timestamptz NULL"+ "38 published_at timestamp with time zone/timestamptz NULL",+ "39 error_detail jsonb/jsonb NULL"],"flags": "relkind=r rls=false force_rls=false"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json b/test/fixtures/goldens/catalog/pglite-schema-blob-default.jsonindex 733de4ec91..cf9e17da42 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-default.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-default.json@@ -242,7 +242,7 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f23ed35b3590e5290a8045c1867957a1227d8fbccf6a6ada70e506098c234fc2","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8e2e253471f22c3e70b2fa2e67ba9162ee3d2c764d175cb5b674db2b907d1e9d"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.jsonindex f7021812e4..855c61a3da 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-fts-portuguese.json@@ -242,7 +242,7 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f23ed35b3590e5290a8045c1867957a1227d8fbccf6a6ada70e506098c234fc2","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=3d98cc6ce4387bd742c1588ddc2133d036c7c5c8c64f7d33d1909c9ae44e73a6"},diff --git a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.jsonindex cf19a7f30b..1d83679dc6 100644--- a/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json+++ b/test/fixtures/goldens/catalog/pglite-schema-blob-high-dims.json@@ -242,7 +242,7 @@"gbrain_guard_skill_publication()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=e854c0d058e75a65c3a90127c5c417380975100e83fc34288f6085e786df10a9","gbrain_lease_shared_skill_delivery()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=5e493c1ac8dce8cb025a736629e563437c4b214744137c302c532c20bf7e7acf","gbrain_queue_page_projection()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=6c544b9c129b6a17dcabeb5ee8d44a2b0e0af9d02ca3fe47c7d7f22ec313042c",- "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=763764b9806792f869d68bb422dcdc0ad3498f975799c55e3823123c5f1fb9a5",+ "gbrain_require_managed_writer()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=f23ed35b3590e5290a8045c1867957a1227d8fbccf6a6ada70e506098c234fc2","gbrain_require_persistence_protocol(required integer)": "RETURNS void kind=f lang=plpgsql volatility=v secdef=false config=[] body_sha256=af07b7fac60dec0a4fe568217931ac449d32f73b3a53a047b3b02a5f59cb5058","update_page_search_vector()": "RETURNS trigger kind=f lang=plpgsql volatility=v secdef=false config=[search_path=pg_catalog, public] body_sha256=8e2e253471f22c3e70b2fa2e67ba9162ee3d2c764d175cb5b674db2b907d1e9d"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 88871a865e..f80055caee 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 191,+ "count": 192,"gaps": [17,18,@@ -28,7 +28,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 196,+ "latest": 197,"records": [{"handler": {@@ -2222,8 +2222,8 @@"idempotent": true,"name": "durable_concurrent_persistence","sql": {- "length": 9186,- "sha256": "21a98206b5bbc4223d0aafcaaaeb674b528eb81df67e3ba2c70bc5ae530f1246"+ "length": 10099,+ "sha256": "0efb22aee75bab0a8bd8c67e9e7b73370a5729b270c7a7d815b2cbc43483fcb3"},"sqlFor": "absent","transaction": "absent",@@ -2287,8 +2287,8 @@"idempotent": true,"name": "managed_alias_and_source_checkpoint_guards","sql": {- "length": 4337,- "sha256": "8866c1c22107bcfbd69ad9b11eb75771fd1c5fbdf96eb580b1e4ed1ba004f531"+ "length": 5250,+ "sha256": "17fd401c0b6172a7c7cd3533e65db534f25d718b4bda4f3b08d85191244486e3"},"sqlFor": "absent","transaction": "absent",@@ -2446,8 +2446,8 @@"idempotent": true,"name": "fact_embedding_identity","sql": {- "length": 4482,- "sha256": "04a5eb5a5338d5b4db9cc2947316b49d6fa3330e776bef81f209a78f7821c56d"+ "length": 5395,+ "sha256": "739cd1a06f34d163fce0baf2e51923fdc590bc05ad1f5448cc50408dc3bf491c"},"sqlFor": "absent","transaction": "absent",@@ -2845,8 +2845,8 @@"idempotent": true,"name": "take_embedding_identity","sql": {- "length": 4482,- "sha256": "c3192c2ababd73606034a0bc4d2b384ef7f42bdf1c2916e7349223d162442549"+ "length": 5395,+ "sha256": "8000426f0aba734fe12c6cda1a9f7419a95eee444b25efab7396c7eabdf2aa5d"},"sqlFor": "absent","transaction": "absent",@@ -2858,8 +2858,8 @@"idempotent": true,"name": "f1_write_attribution","sql": {- "length": 13179,- "sha256": "14a8b29806b434b992d5fa365c1cdb3e55b4e39f144fdd1630c660b8151c410c"+ "length": 14092,+ "sha256": "7668900f69f4873d6312626da009416076284f840ca18d1018d736b974a20faf"},"sqlFor": "absent","transaction": "absent",@@ -2910,6 +2910,19 @@"transaction": "absent","verify": "absent","version": 196+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "publication_failure_detail",+ "sql": {+ "length": 5341,+ "sha256": "ceb9f3bbeb67523178d1c130a5657122941cf06620f17f4bed964c8af394bd04"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 197}],"versions": [@@ -3103,7 +3116,8 @@193,194,195,- 196+ 196,+ 197]},"normalizer": "migrations-record-v1"diff --git a/test/persistence-publication-refusal-5974.test.ts b/test/persistence-publication-refusal-5974.test.tsnew file mode 100644index 0000000000..e7612a92b1--- /dev/null+++ b/test/persistence-publication-refusal-5974.test.ts@@ -0,0 +1,161 @@+/**+ * #5974: a database guard refusal during publication used to surface as an+ * opaque `storage_error: Publication failed (P0001)`. It now names the trigger,+ * table, operation, guard branch and source relationship, records the build and+ * host that ran the attempt, keeps that detail through recovery and+ * compaction, and exposes source identifiers only to the owner diagnostics.+ * Runs on PGLite, and on an isolated Postgres database when DATABASE_URL is set.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { randomUUID } from 'node:crypto';+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import type { OperationContext } from '../src/core/ops/contract.ts';+import { registerLocalWriter } from '../src/core/persistence/identity.ts';+import { submissionAuthority } from '../src/core/persistence/authority.ts';+import { admitWrite, claimNextWrite, compactWriteReceipts, receiptFor, type WriteAdmission } from '../src/core/persistence/journal.ts';+import { publishMutation } from '../src/core/persistence/coordinator.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { databaseRefusal, publicFailureDetail } from '../src/core/persistence/publication-failure.ts';+import { readWriterDiagnostics } from '../src/core/persistence/diagnostics.ts';+import { writeResponse } from '../src/core/persistence/service.ts';+import { DATABASE_REFUSAL_HINT } from '../src/core/persistence/connector-errors.ts';+import { VERSION } from '../src/version.ts';+import { assertSafeE2eDatabaseUrl } from './helpers/db-guard.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const engines: BrainEngine[] = [];+const roots: string[] = [];+let closePostgres: (() => Promise<void>) | undefined;+const sourceId = 'refusal-owned';+const otherSource = 'refusal-other';+const hostId = randomUUID();+const input = (body: string) => ({ type: 'note', title: 'Example', compiled_truth: body, timeline: '', frontmatter: {} });+const ctx = (engine: BrainEngine, source = sourceId): OperationContext => ({ engine, config: { engine: engine.kind }, sourceId: source, remote: false,+ dryRun: false, logger: { info() {}, warn() {}, error() {} } });++beforeAll(async () => {+ const local = new PGLiteEngine();+ await local.connect({}); await local.initSchema(); engines.push(local);+ if (process.env.DATABASE_URL) {+ assertSafeE2eDatabaseUrl(process.env.DATABASE_URL);+ const isolated = await isolatedPersistencePostgres(process.env.DATABASE_URL);+ closePostgres = isolated.close; engines.push(isolated.engine);+ }+ for (const engine of engines) {+ for (const id of [sourceId, otherSource]) await engine.executeRaw('INSERT INTO sources(id,name) VALUES($1,$1) ON CONFLICT DO NOTHING', [id]);+ await registerLocalWriter(engine, 'cli');+ }+}, 120_000);+afterAll(async () => {+ for (const engine of engines) if (engine.kind === 'pglite') await engine.disconnect();+ await closePostgres?.();+ for (const root of roots) rmSync(root, { recursive: true, force: true });+});++async function admission(engine: BrainEngine, slug: string, extra: Partial<WriteAdmission> = {}): Promise<WriteAdmission> {+ const source = extra.sourceId ?? sourceId;+ const [row] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [source]);+ const authority = await submissionAuthority(ctx(engine, source), 'put_page', source, row.incarnation, slug);+ const page = await engine.readPageSnapshot(slug, { sourceId: source, includeDeleted: true });+ return { principal: authority.principal, operation: 'put_page', sourceId: source, sourceIncarnation: row.incarnation, slug,+ pageId: page?.page.id ?? null, requestId: randomUUID(), callerIntent: { content: slug }, intent: { content: slug }, authority, ...extra };+}+async function managed<T>(engine: BrainEngine, fn: () => Promise<T>): Promise<T> {+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ try { return await fn(); } finally { await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1'); }+}++describe('#5974 database refusal diagnostics', () => {+ test('a cross-source write inside publication fails with a structured, redacted diagnostic', async () => {+ for (const engine of engines) await managed(engine, async () => {+ const slug = `cross-${engine.kind}`;+ await admitWrite(engine, await admission(engine, slug));+ const row = (await claimNextWrite(engine, hostId))!;+ const done = await publishMutation(engine, row, { observedRevision: null, apply: async tx => {+ await tx.putPage(slug, input('owned'), { sourceId });+ await tx.putPage(`${slug}-leak`, input('not owned'), { sourceId: otherSource });+ return { status: 'created' };+ } }, hostId);++ expect(done.state).toBe('failed');+ expect(done.error_code).toBe('writer_coordinator_required');+ expect(done.error_message).toBe('The managed-writer database guard refused an INSERT on pages: a row in a source this publication does not own. Nothing was committed.');+ expect(done.error_detail).toMatchObject({ origin: 'database_guard', sqlstate: 'P0001', raiser: 'gbrain_require_managed_writer',+ table: 'pages', op: 'INSERT', branch: 'allowlist', relationship: 'different_source', stage: 'publication',+ sources: { target: otherSource, old: null, allowed: [sourceId] }, attempt: { consumer_version: VERSION } });+ expect(await engine.readPageSnapshot(slug, { sourceId })).toBeNull();+ expect(await engine.readPageSnapshot(`${slug}-leak`, { sourceId: otherSource })).toBeNull();++ const receipt = receiptFor(done) as Record<string, unknown>;+ expect(receipt.write_error).toBe('writer_coordinator_required');+ expect(receipt.write_error_detail).toEqual({ origin: 'database_guard', sqlstate: 'P0001', raiser: 'gbrain_require_managed_writer',+ table: 'pages', op: 'INSERT', branch: 'allowlist', relationship: 'different_source', stage: 'publication' });+ expect(JSON.stringify(receipt)).not.toContain(otherSource);+ try { writeResponse(done); throw new Error('expected a refusal'); }+ catch (error) {+ expect(error).toMatchObject({ code: 'writer_coordinator_required', suggestion: DATABASE_REFUSAL_HINT, detail: 'database_guard' });+ expect(JSON.stringify(error)).not.toContain(otherSource);+ }++ const diagnostics = await readWriterDiagnostics(engine);+ const failure = diagnostics.recent_failures.find(f => f.request_id === done.request_id)!;+ expect(failure.error_detail).toMatchObject({ sources: { target: otherSource, allowed: [sourceId] }, attempt: { consumer_version: VERSION } });+ expect(failure.next_action).toBe(DATABASE_REFUSAL_HINT);++ await engine.executeRaw("UPDATE persistence_requests SET completed_at=now()-interval '400 days' WHERE id=$1::uuid", [done.id]);+ await compactWriteReceipts(engine, 1);+ const [compacted] = await engine.executeRaw<{ compacted: boolean; error_message: string | null; error_detail: unknown }>(+ 'SELECT compacted,error_message,error_detail FROM persistence_requests WHERE id=$1::uuid', [done.id]);+ expect(compacted.compacted).toBe(true);+ expect(compacted.error_message).toBeNull();+ expect(compacted.error_detail).toMatchObject({ table: 'pages', relationship: 'different_source' });+ });+ });++ test('a refusal after the canonical file was replaced restores it and records the stage', async () => {+ for (const engine of engines) {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-refusal-root-')); roots.push(root);+ const fileSource = `refusal-file-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [fileSource, root]);+ const binding = await claimWorktree(engine, fileSource, root, hostId);+ const path = join(root, 'file.md'); writeFileSync(path, 'Before');+ const a = await admission(engine, 'file', { sourceId: fileSource, worktreeId: binding.worktree_id, topologyGeneration: binding.topology_generation });+ await managed(engine, async () => {+ await admitWrite(engine, a);+ const row = (await claimNextWrite(engine, hostId))!;+ const done = await publishMutation(engine, row, { observedRevision: null, file: { path, root, content: 'After' },+ apply: async tx => { await tx.putPage('file-leak', input('not owned'), { sourceId: otherSource }); return {}; } }, hostId);+ expect(done.state).toBe('failed');+ expect(done.recovery).toBeNull();+ expect(readFileSync(path, 'utf8')).toBe('Before');+ expect(done.error_detail).toMatchObject({ origin: 'database_guard', table: 'pages', stage: 'after_file_publication',+ sources: { target: otherSource, allowed: [fileSource] } });+ });+ }+ });++ test('a guarded tag write outside any coordinator names the table and missing allowlist', async () => {+ for (const engine of engines) {+ await engine.putPage('tagged', input('x'), { sourceId });+ const error = await managed(engine, () => engine.addTag('tagged', 'loose', { sourceId }).then(() => null, e => e));+ expect(databaseRefusal(error)).toMatchObject({ code: 'writer_coordinator_required',+ detail: { table: 'tags', op: 'INSERT', branch: 'allowlist', relationship: 'different_source', sources: { target: sourceId, allowed: [] } } });+ }+ });++ test('another P0001 raiser stays storage_error but names its function; other errors are not classified', async () => {+ for (const engine of engines) {+ const error = await engine.executeRaw("DO $$ BEGIN RAISE EXCEPTION 'private page text must not leak'; END $$").then(() => null, e => e);+ const refusal = databaseRefusal(error)!;+ expect(refusal).toMatchObject({ code: 'storage_error', detail: { origin: 'database_trigger', sqlstate: 'P0001', raiser: 'inline_code_block' } });+ expect(JSON.stringify(refusal)).not.toContain('private page text');+ expect(databaseRefusal(Object.assign(new Error('x'), { code: '23505' }))).toBeNull();+ expect(publicFailureDetail({ origin: 'database_guard', sources: { target: 'a' }, attempt: { consumer_version: '1' }, table: 'pages' }))+ .toEqual({ origin: 'database_guard', table: 'pages' });+ }+ });+});diff --git a/test/schema-bootstrap-coverage.test.ts b/test/schema-bootstrap-coverage.test.tsindex 15ac790955..7629c49042 100644--- a/test/schema-bootstrap-coverage.test.ts+++ b/test/schema-bootstrap-coverage.test.ts@@ -1022,6 +1022,10 @@ const COLUMN_EXEMPTIONS = new Set<string>(['persistence_requests.consumer_host_id','persistence_requests.published_at','persistence_brain.writer_version_cutoff',+ // #5974 (migration v197) — structured publication failure detail. Same+ // posture as v178: persistence_requests is migration-created on PGLite, no+ // index references the column, and every reader treats NULL as no detail.+ 'persistence_requests.error_detail',// #5455 (migration v183) — managed mode epoch. persistence_brain is// migration-created on PGLite; no index in either blob references it, and// pre-migration readers go through to_jsonb(persistence_brain)->'mode_epoch'.