Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(persistence): keep a bounded identity for owner exceptions and allow-list public failure detail (#5929)
garrytan93de6fbd94cd
diff --git a/docs/ENGINES.md b/docs/ENGINES.mdindex 2f1d87585e..456ef14b9c 100644--- a/docs/ENGINES.md+++ b/docs/ENGINES.md@@ -651,7 +651,14 @@ checkpoint did not advance. The message names both errors (redacted, at mostthe SQLSTATE (for example `53300` when a pooler's client limit is reached),a write-error code, `storage_error`, or `deadline_exceeded` when the phaseoverran its five-second budget. `message` is the redacted error text, one line,-at most 200 characters. Connection-wait evidence follows on Postgres:+at most 200 characters. When an unexpected exception in the owner failed a+write (`storage_error` "Publication failed (TypeError in owner build 0.60.x)"),+the line also carries `class=`, `errno=` and `frame=` (the top gbrain source+frame, repo-relative, for example `src/core/persistence/page-prepare.ts:120`):+the owner diagnostics the receipt points at. The stored receipt keeps the same+identifiers (never the error message) owner-side in `error_detail`, with the+build that ran the attempt; `gbrain write-request <id>` names an owner on+another build than the CLI (`owner_build`) and the restart to run. Connection-wait evidence follows on Postgres:`first_conn_ms` is the time from phase start until the phase obtained aconnection; `checkout=not_observed conn_wait_ms=<n>` means it had not obtainedone after `n` milliseconds (a saturated pool or pooler, not a slow query); anddiff --git a/docs/architecture/key-files/canonical-reconciliation.md b/docs/architecture/key-files/canonical-reconciliation.mdindex 206402a2d8..0ff84da49b 100644--- a/docs/architecture/key-files/canonical-reconciliation.md+++ b/docs/architecture/key-files/canonical-reconciliation.md@@ -6,7 +6,7 @@- `src/core/persistence/reconcile-additive.ts` (#5974) — pure structural drift classifier over the complete file/database delta: inserted whole lines (two-pointer subsequence, CRLF-normalized; fence, heading and table insertions excluded) are `suggested`; an append-only `contacts` list, an allowlisted activity date moving forward, and one-sided ordinary fields are `auto`; policy/privacy/identity/tag changes and everything else are `review`. `--auto-additive` previews write `take_file` only for `auto` (and `suggested` with `--accept-suggested`), recorded as format-2 `auto_decisions` with an evidence digest that apply and owner preparation recheck. `--audit --classify` reports per-page verdicts and counts, never values.-- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`.+- `src/core/persistence/publication-failure.ts` (#5974) — maps a P0001 from the managed-writer guard (which raises TABLE/SCHEMA, `managed_writer_guard:<branch>` and a JSON DETAIL) or another trigger to a bounded `error_detail` (origin, raiser, table, op, branch, relationship, stage, plus owner-only source ids and the attempt's build/host). Receipts expose only `publicFailureDetail`; `sources writer status` lists the full detail under `recent_failures`. #5929: `ownerExceptionFailure` (the coordinator `requestError` fallback) keeps an unexpected exception's class, errno and top `src/...:line` frame as `origin: owner_exception` (never its message), so `withAttempt` stamps the build; `publicFailureDetail` is an allow-list (origin, sqlstate, raiser, table, op, branch, relationship, stage, fence), so `error_class`/`errno`/`frame`, `sources` and `attempt` stay owner-only; `ownerBuildMismatch` drives the local `owner_build` receipt field (`ops/persistence.ts`) and the submit-time why/fix (`page-mutations.ts`), and `ownerExceptionLogText` the consumer log line.- `src/core/cycle/extract-atoms-page-state.ts` — derived page scan/failure state keyed by source incarnation, stable page identity and content hash. Compare-and-swap stamps never update canonical frontmatter. Reviewed reconciliation can carry matching state across removal of legacy bookkeeping fields. Atom item completion still waits for all atoms and provenance links; managed extraction uses journaled publication and a durable completion receipt after trusted local source-wide authority checks and, for filesystem publication, owner preflight.diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 93725278c9..5bd6d91159 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -263,6 +263,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.0.0-wave11', text: '`gbrain repair failed-writes` now replays subagent and restricted-namespace writes (they were all refused "via subagent requires ctx.subagentId"), under the original writer\'s stored authority re-checked against its live grant; replayed writes are attributed to that original writer.' },{ since: '0.0.0-wave11', text: 'Inline `[Source: ..., date]` citations no longer file an adjacent HTML comment (such as `<!-- AUTO:slack END -->`) as a timeline entry, and a timeline row carrying comment markup is never written back into a page (it would duplicate a section END marker); `gbrain repair timeline-comments --source <id>` previews and cleans rows and bullets stored before this release.' },{ since: '0.0.0-wave11', text: 'On a managed brain, `gbrain files upload-raw` of a small file now refuses before creating anything (it used to leave an empty `.raw/` directory); configure a storage backend and use `gbrain files upload <file> --page <slug>`.' },+ { since: '0.0.0-wave11', text: 'A managed write that fails on an unexpected owner exception now reports `storage_error` "Publication failed (<ErrorClass> in owner build <version>)" instead of a bare message, the owner log line names the class and source frame, and `gbrain write-request <id>` (`owner_build`) says when the owner that ran it is on another build than the CLI and needs a restart.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 7a782beae0..216bdb4bea 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -110,9 +110,12 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: Wconst intent = row.intent as Pick<import('../persistence/sync-prepare.ts').SyncIntent, 'processingOptions' | 'syncOptions' | 'repoPath'> | null;const checkpoint = row.error_code === CHECKPOINT_VALIDATION_TIMEOUT ? await checkpointTimeoutHint(ctx.engine, { requestId: row.request_id, sourceId: row.source_id,processingOptions: intent?.processingOptions, syncOptions: intent?.syncOptions, repoPath: intent?.repoPath }) : null;+ // #5929: a trusted local reader learns when the owner that ran the attempt is on another build.+ const mismatch = ctx.remote === false ? (await import('../persistence/publication-failure.ts')).ownerBuildMismatch(row.error_detail, (await import('../../version.ts')).VERSION) : null;return {...publicWriteReceipt(receiptFor(row, facts)),operation: row.operation, source_id: row.source_id, slug: row.slug,+ ...(mismatch ? { owner_build: mismatch } : {}),...(isWriteErrorCode(row.error_code) ? { write_error: row.error_code, write_error_message: writeFailureDiagnostic(row.error_code, row.error_message).message } : {}),...(checkpoint ? { detail: checkpoint.detail, suggestion: checkpoint.suggestion, docs: checkpoint.docs } : {}),effects: (await publicEffectsForRequest(ctx.engine, row.id)).map(effect => {diff --git a/src/core/persistence/consumer.ts b/src/core/persistence/consumer.tsindex 193b88df4e..49b39bad90 100644--- a/src/core/persistence/consumer.ts+++ b/src/core/persistence/consumer.ts@@ -6,6 +6,7 @@ import { localHostId } from './identity.ts';import { executeClaimedGroup, PAGE_BATCH_GROUP_MAX } from './group-publish.ts';import { CLAIM_LOST, DEFAULT_CLAIM_LEASE_TIMING, endLostLease, startClaimLease, type ClaimLeaseTiming } from './claim-lease.ts';import { isTerminal, type WriteRequest } from './model.ts';+import { ownerExceptionLogText } from './publication-failure.ts';import { refreshManagedFilesystemRoots } from './filesystem-guard.ts';import { PROJECTION_RETRY_READY_SQL, rebuildPendingPageProjections } from '../page-state/projections.ts';import { publicationConcurrency } from './pool-capacity.ts';@@ -31,6 +32,12 @@ const PROCESS_STARTED_AT = new Date(performance.timeOrigin);const phaseScope = new AsyncLocalStorage<{ observation: PhaseObservation; startedAt: number }>();/** #5233: one-line, redacted, length-capped error text for the consumer's stderr line. */+/** #5929: the failed receipt's message plus, for an owner exception, its class, errno and gbrain frame (this log is owner-side). */+function failureLogText(row: WriteRequest): string | undefined {+ const extra = ownerExceptionLogText(row.error_detail);+ return row.error_message || extra ? `${row.error_message ?? ''}${extra}`.replaceAll('"', "'") : undefined;+}+function errorDetail(error: unknown): string | undefined {const message = (error as { message?: unknown } | null)?.message;if (typeof message !== 'string' || !message.trim()) return undefined;@@ -558,7 +565,7 @@ export class PersistenceConsumer {preparationActive = false;await faultPoint('consumer:prepared', { requestId: row.request_id, sourceId: row.source_id, operation: row.operation });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 === 'failed') this.log('publication', done.error_code ?? 'storage_error', failureLogText(done));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);}@@ -572,7 +579,7 @@ export class PersistenceConsumer {const current = await getWriteRequestById(this.engine, row.id);if (current && !isTerminal(current) && current.execution_token === row.execution_token && !current.recovery) {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);+ if (done.state === 'failed') this.log(preparationActive ? 'preparation' : 'publication', done.error_code ?? 'storage_error', failureLogText(done));return this.settled(done);}throw error;diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex e0edbaa6d6..f427230bd9 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -31,7 +31,7 @@ import { assertMutationProtocol, assertSharedSkillPersistence, declareDurablePerimport { 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';+import { databaseRefusal, ownerExceptionFailure, withAttempt, type PublicationFailure, type PublicationFailureDetail, type PublicationStage } from './publication-failure.ts';import { fenceFailureDetail } from '../fence-repair/refusal.ts';import { faultPoint, withFaultPoints } from './fault-points.ts';@@ -126,7 +126,7 @@ function requestError(error: unknown): PublicationFailure {}// #5216: the row still awaits its revision backfill; the error names the resume command.if (code === 'revision_backfill_pending' && error instanceof Error) return { code, message: error.message };- return { code: 'storage_error', message: `Publication failed${code ? ` (${code})` : ''}. Inspect owner diagnostics.` };+ return ownerExceptionFailure(error);}function conflictCode(code: string): boolean { return ['revision_required','revision_conflict','revision_backfill_pending','source_changed','page_identity_changed'].includes(code); }export function transientDatabaseFailure(error: unknown): boolean {diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex cab275cd9d..da82f2e5d2 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -4,6 +4,8 @@ import { realpathSync } from 'node:fs';import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { OperationContext } from '../ops/contract.ts';import { OperationError } from '../ops/contract.ts';+import { VERSION } from '../../version.ts';+import { ownerBuildMismatch } from './publication-failure.ts';import { enforceClientSlugFence, enforceSubagentSlugFence, normalizeSlugPrefix, parseSourceIdParam, requireWritablePage, validatePageSlug } from '../ops/context.ts';import { suffixedSlugAdmission } from './suffixed-slug.ts';import { defaultSlug, detectBinaryNullByte, explicitCaptureType, mergeCaptureFrontmatter, normalizeForHash } from '../capture-content.ts';@@ -135,7 +137,12 @@ async function resolveCaptureFile(ctx: OperationContext, sourceId: string, p: Re}function pendingAwareResponse(ctx: OperationContext, row: WriteRequest): Record<string, unknown> {- return writeResponse(row, { retryAfterMs: estimatedRetryAfterMs(ctx.engine, 1) });+ try { return writeResponse(row, { retryAfterMs: estimatedRetryAfterMs(ctx.engine, 1) }); } catch (error) {+ // #5929: a trusted local caller is told when an owner on another build ran the failed attempt.+ const mismatch = ctx.remote === false && error instanceof OperationError ? ownerBuildMismatch(row.error_detail, VERSION) : null;+ if (mismatch) { error.why = mismatch.why; error.fix = mismatch.fix; }+ throw error;+ }}/** #6188 (D21): a write whose fence Tier 1 rewrote carries one `fence_normalized` coaching notice. */diff --git a/src/core/persistence/publication-failure.ts b/src/core/persistence/publication-failure.tsindex b6a57dafe5..e548bb56d2 100644--- a/src/core/persistence/publication-failure.ts+++ b/src/core/persistence/publication-failure.ts@@ -1,6 +1,7 @@import { OperationError } from '../ops/contract.ts';import { writerStamp } from './writer-versions.ts';import type { FenceFailureDetail } from '../fence-repair/refusal.ts';+import type { Action } from '../agent-output.ts';/*** #5974: a database refusal during preparation or publication becomes a@@ -25,7 +26,15 @@ export interface PublicationFailureDetail {}/** #6188: a typed fence refusal's location (`fence-repair/refusal.ts`), plus the attempt stamp. */export type FenceRefusalDetail = FenceFailureDetail & Pick<PublicationFailureDetail, 'stage' | 'attempt'>;-export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail }+/**+ * #5929: an unexpected exception in the owner. Fixed identifiers only, never+ * the message, SQL or values: the error class, its errno and the top gbrain+ * source frame (repo-relative). All three are owner-only.+ */+export interface OwnerExceptionDetail extends Pick<PublicationFailureDetail, 'stage' | 'attempt'> {+ origin: 'owner_exception'; error_class?: string; errno?: string; frame?: string;+}+export interface PublicationFailure { code: string; message: string; detail?: PublicationFailureDetail | FenceRefusalDetail | OwnerExceptionDetail }const IDENT = /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/;const ident = (value: unknown) => typeof value === 'string' && IDENT.test(value) ? value : undefined;@@ -72,6 +81,54 @@ export function databaseRefusal(error: unknown): PublicationFailure | null {detail: { origin: raiser ? 'database_trigger' : 'database', sqlstate, ...(raiser ? { raiser } : {}), ...(table ? { table } : {}) } };}+const ERRNO = /^[A-Za-z0-9_]{1,40}$/;++/** The top stack frame inside gbrain's own `src/`, as `src/<path>.ts:<line>`; never an absolute path. */+function gbrainFrame(stack: unknown): string | undefined {+ if (typeof stack !== 'string') return undefined;+ for (const line of stack.split('\n').slice(1)) {+ if (line.includes('node_modules')) continue;+ const match = /.*[\/\\(\s](src[\/\\][\w./\\-]+?\.ts):(\d+)/.exec(line);+ if (match) return `${match[1]!.replace(/\\/g, '/')}:${match[2]}`;+ }+ return undefined;+}++/** #5929: the bounded identity of an unexpected owner exception, with a message naming only the class, errno and owner build. */+export function ownerExceptionFailure(error: unknown): PublicationFailure {+ const e = (error && typeof error === 'object' ? error : {}) as { constructor?: { name?: unknown }; code?: unknown; errno?: unknown; stack?: unknown };+ const errorClass = ident(e.constructor?.name);+ const raw = typeof e.code === 'string' ? e.code : typeof e.errno === 'number' ? String(e.errno) : undefined;+ const errno = raw && ERRNO.test(raw) ? raw : undefined;+ const frame = gbrainFrame(e.stack);+ const what = [errorClass, errno].filter(Boolean).join(' ');+ return { code: 'storage_error', message: `Publication failed (${what ? `${what} in ` : ''}owner build ${writerStamp().version}). Inspect owner diagnostics.`,+ detail: { origin: 'owner_exception', ...(errorClass ? { error_class: errorClass } : {}), ...(errno ? { errno } : {}), ...(frame ? { frame } : {}) } };+}++/** Owner-side text for the consumer log: the class and frame of an owner exception, else nothing. */+export function ownerExceptionLogText(detail: unknown): string {+ const d = detail as Partial<OwnerExceptionDetail> | null;+ if (!d || d.origin !== 'owner_exception') return '';+ return [d.error_class ? ` class=${d.error_class}` : '', d.errno ? ` errno=${d.errno}` : '', d.frame ? ` frame=${d.frame}` : ''].join('');+}++/**+ * #5929: when the owner that ran a failed attempt is on another build than+ * this CLI (a long-running `gbrain serve` started before an upgrade), say so+ * with the restart step. Owner-only: the attempt stamp is never public.+ */+export function ownerBuildMismatch(detail: unknown, cliVersion: string): { owner: string; cli: string; why: string; fix: Action } | null {+ const owner = (detail as Partial<PublicationFailureDetail> | null)?.attempt?.consumer_version;+ if (typeof owner !== 'string' || !owner || owner === cliVersion) return null;+ return { owner, cli: cliVersion,+ why: `The owner process that ran this attempt is on gbrain ${owner}; this CLI is ${cliVersion}. Long-running \`gbrain serve\` processes (and autopilot or sync jobs) started before the upgrade still own writes and run the old code.`,+ fix: { consent: [], actor: 'user', requires_exclusive: false,+ why: 'Restart every gbrain serve, autopilot and sync process on the brain host so the owner runs this build, then submit the write again with a new request_id.',+ user_message: `Restart the gbrain serve (and autopilot) processes on the brain host: they are on ${owner}, this CLI is ${cliVersion}.`,+ verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--probe', '--json'] } } };+}+/** Stamps which build, host and stage ran the failed attempt. */export function withAttempt(failure: PublicationFailure, stage: PublicationStage): PublicationFailure {if (!failure.detail) return failure;@@ -85,9 +142,12 @@ export function withAttempt(failure: PublicationFailure, stage: PublicationStage* reason and problem classes; its row numbers stay owner-side (they can* number rows a remote caller never saw).*/+const PUBLIC_DETAIL_KEYS: ReadonlySet<string> = new Set(['origin', 'sqlstate', 'raiser', 'table', 'op', 'branch', 'relationship', 'stage', 'fence']);+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;+ // #5929: an allow-list, so a key added to a stored detail is owner-only unless it is listed here.+ const rest = Object.fromEntries(Object.entries(detail).filter(([key]) => PUBLIC_DETAIL_KEYS.has(key)));if ((rest as { origin?: unknown }).origin === 'fence') {const { rows: _rows, issues, ...fence } = ((rest as unknown as FenceFailureDetail).fence ?? {}) as FenceFailureDetail['fence'];const publicIssues = Array.isArray(issues) ? issues.map(({ row: _row, ...issue }) => issue) : undefined;diff --git a/test/publication-failure-owner-exception.test.ts b/test/publication-failure-owner-exception.test.tsnew file mode 100644index 0000000000..fb032bd3c3--- /dev/null+++ b/test/publication-failure-owner-exception.test.ts@@ -0,0 +1,107 @@+/**+ * #5929: an unexpected exception inside the owner's preparation or publication+ * keeps a bounded identity (class, errno, repo-relative top gbrain frame, never+ * its message), so the attempt is stamped with the owner's build; remote+ * receipts expose only the allow-listed public keys; `gbrain write-request`+ * names an owner/CLI build mismatch with a restart fix.+ */+import { afterAll, beforeAll, describe, 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 { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { operationsByName } from '../src/core/operations.ts';+import { OperationError } from '../src/core/ops/contract.ts';+import { installFaultHook } from '../src/core/persistence/fault-points.ts';+import { receiptFor } from '../src/core/persistence/journal.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { claimWorktree } from '../src/core/persistence/ownership.ts';+import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';+import { publicFailureDetail } from '../src/core/persistence/publication-failure.ts';+import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';+import { VERSION } from '../src/version.ts';+import { withEnv } from './helpers/with-env.ts';++let engine: PGLiteEngine;+const dir = mkdtempSync(join(tmpdir(), 'gbrain-owner-exception-'));+const sourceId = `owner-exc-${randomUUID().slice(0, 8)}`;+const logger = { info() {}, warn() {}, error() {} };+const ctx = () => ({ engine, sourceId, remote: false, config: { engine: 'pglite', embedding_disabled: true }, dryRun: false, logger }) as never;++beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ const root = join(dir, 'brain'); mkdirSync(root);+ await engine.executeRaw('INSERT INTO sources(id,name,local_path) VALUES($1,$1,$2)', [sourceId, root]);+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, () => claimWorktree(engine, sourceId, root));+}, 60_000);+afterAll(async () => { installFaultHook(undefined); await disposePersistenceConsumer(engine); await engine.disconnect(); rmSync(dir, { recursive: true, force: true }); });++async function failingWrite(error: Error): Promise<{ thrown: OperationError; row: WriteRequest }> {+ const slug = `notes/${randomUUID().slice(0, 8)}`;+ const requestId = randomUUID();+ installFaultHook(async point => { if (point === 'consumer:prepared') throw error; });+ let thrown: unknown;+ try {+ await withEnv({ GBRAIN_HOME: join(dir, 'home') }, () => submitPageMutation(ctx(), { operation: 'put_page',+ params: { slug, content: '---\ntype: note\ntitle: Example\n---\nBody.\n', request_id: requestId } }));+ } catch (e) { thrown = e; } finally { installFaultHook(undefined); }+ const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE request_id=$1::uuid', [requestId]);+ return { thrown: thrown as OperationError, row };+}++describe('#5929 owner exceptions keep a bounded identity', () => {+ test('a TypeError is stored with its class and repo-relative frame, the attempt is stamped, and its message never leaves the owner', async () => {+ // As thrown inside gbrain: a dependency frame first, then gbrain's own source under an absolute checkout path.+ const error = Object.assign(new TypeError('cannot read secret-value of undefined'), { stack: [+ 'TypeError: cannot read secret-value of undefined',+ ' at parse (/home/alice-example/.bun/install/global/node_modules/yaml/dist/index.js:10:3)',+ ' at preparePageMutation (/home/alice-example/gbrain/src/core/persistence/page-prepare.ts:120:15)',+ ' at run (/home/alice-example/gbrain/src/core/persistence/consumer.ts:540:9)'].join('\n') });+ const { thrown, row } = await failingWrite(error);+ expect(thrown).toBeInstanceOf(OperationError);+ expect(thrown.code).toBe('storage_error');+ expect(row.error_code).toBe('storage_error');+ expect(row.error_message).toBe(`Publication failed (TypeError in owner build ${VERSION}). Inspect owner diagnostics.`);+ const detail = row.error_detail as Record<string, any>;+ expect(detail).toMatchObject({ origin: 'owner_exception', error_class: 'TypeError', stage: 'publication', attempt: { consumer_version: VERSION } });+ expect(detail.frame).toBe('src/core/persistence/page-prepare.ts:120');+ expect(JSON.stringify(row)).not.toContain('secret-value');+ expect(JSON.stringify(row)).not.toContain('alice-example');+ });++ test('an errno-bearing error keeps the errno', async () => {+ const { row } = await failingWrite(Object.assign(new Error('no space left on /home/alice-example/brain'), { code: 'ENOSPC' }));+ expect(row.error_detail).toMatchObject({ origin: 'owner_exception', error_class: 'Error', errno: 'ENOSPC' });+ expect(row.error_message).toBe(`Publication failed (Error ENOSPC in owner build ${VERSION}). Inspect owner diagnostics.`);+ expect(JSON.stringify(row)).not.toContain('alice-example');+ });++ test('the receipt any caller reads carries none of the owner-only fields', async () => {+ const { row } = await failingWrite(new RangeError('bad offset'));+ const receipt = receiptFor(row) as Record<string, any>;+ expect(receipt.write_error_detail).toEqual({ origin: 'owner_exception', stage: 'publication' });+ });++ test('the public view of today\'s detail shapes is unchanged', () => {+ const guard = { origin: 'database_guard', sqlstate: 'P0001', raiser: 'gbrain_require_managed_writer', table: 'tags', branch: 'source_scope', op: 'INSERT',+ relationship: 'different_source', sources: { target: 'a', old: null, allowed: ['b'] }, stage: 'publication', attempt: { consumer_version: '0.60.1.0', consumer_host_id: 'h' } };+ expect(JSON.stringify(publicFailureDetail(guard))).toBe(JSON.stringify({ origin: 'database_guard', sqlstate: 'P0001', raiser: 'gbrain_require_managed_writer',+ table: 'tags', branch: 'source_scope', op: 'INSERT', relationship: 'different_source', stage: 'publication' }));+ const fence = { origin: 'fence', fence: { version: 1, fence: 'facts', section: 'body', reason: 'malformed_row', rows: [3], issues: [{ row: 3, column: 'kind', problem: 'invalid_enum' }] },+ stage: 'preparation', attempt: { consumer_version: '0.60.1.0', consumer_host_id: 'h' } };+ expect(JSON.stringify(publicFailureDetail(fence))).toBe(JSON.stringify({ origin: 'fence', fence: { version: 1, fence: 'facts', section: 'body', reason: 'malformed_row',+ issues: [{ column: 'kind', problem: 'invalid_enum' }] }, stage: 'preparation' }));+ expect(publicFailureDetail({ origin: 'database', sqlstate: 'P0001', surprise: 'leak' })).toEqual({ origin: 'database', sqlstate: 'P0001' });+ });++ test('write-request names an owner build that differs from this CLI, with a restart fix', async () => {+ const { row } = await failingWrite(new TypeError('stale owner'));+ await engine.executeRaw(`UPDATE persistence_requests SET error_detail=jsonb_set(error_detail,'{attempt,consumer_version}','"0.60.1.0"') WHERE id=$1::uuid`, [row.id]);+ const receipt = await withEnv({ GBRAIN_HOME: join(dir, 'home') }, () =>+ operationsByName.get_write_request.handler(ctx(), { request_id: row.request_id })) as Record<string, any>;+ expect(receipt.owner_build).toMatchObject({ owner: '0.60.1.0', cli: VERSION });+ expect(receipt.owner_build.why).toContain('gbrain serve');+ expect(receipt.owner_build.fix).toMatchObject({ actor: 'user', verify: { argv: ['gbrain', 'sources', 'writer', 'status', '--probe', '--json'] } });+ });+});