Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(errors): B10 backfill persistence long tail, repair preparers, phantom-redirect-managed
garrytan96ffdd181aa3
diff --git a/src/core/cycle/phantom-redirect-managed.ts b/src/core/cycle/phantom-redirect-managed.tsindex a0e0c466a9..9b06987766 100644--- a/src/core/cycle/phantom-redirect-managed.ts+++ b/src/core/cycle/phantom-redirect-managed.ts@@ -19,7 +19,8 @@ import type { GBrainConfig } from '../config.ts';import type { Page } from '../types.ts';import type { PreparedMutation } from '../persistence/coordinator.ts';import type { WriteRequest } from '../persistence/model.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { parseFactsFence } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';import { logPhantomEvent } from '../facts/phantom-audit.ts';@@ -74,7 +75,9 @@ export async function preparePhantomMerge(engine: BrainEngine, row: WriteRequestconst phantomUnchanged = async (db: BrainEngine) => {const phantom = await db.readPageSnapshot(phantomSlug, { sourceId: row.source_id });if (!phantom || phantom.page.id !== phantomId || phantom.revision !== p.phantom_revision || await phantomHasResidue(db, phantom.page)) {- throw new OperationError('revision_conflict', 'The phantom page changed before its redirect.');+ throw opError('revision_conflict', 'The phantom page changed before its redirect.',+ `Phantom page ${phantomSlug} in source ${row.source_id} changed before request ${row.request_id} could redirect it, so nothing was merged. Review the page; the next cycle re-evaluates it.`,+ { fix: readFix(`Shows page ${phantomSlug} as it is now, read-only.`, { argv: ['gbrain', 'get', '--source', row.source_id, '--', phantomSlug] }) });}};await phantomUnchanged(engine);@@ -103,7 +106,9 @@ export async function preparePhantomDelete(engine: BrainEngine, row: WriteRequesconst canonicalSlug = String(row.intent!.canonical_slug);const noTimeline = async (db: BrainEngine) => {if ((await db.executeRaw('SELECT 1 FROM timeline_entries WHERE page_id=$1 LIMIT 1', [row.page_id])).length) {- throw new OperationError('revision_conflict', 'The phantom gained timeline rows after its merge.');+ throw opError('revision_conflict', 'The phantom gained timeline rows after its merge.',+ `Phantom page ${row.slug} in source ${row.source_id} gained timeline entries after its merge, so request ${row.request_id} did not delete it. Review those entries; the next cycle re-evaluates the phantom.`,+ { fix: readFix(`Shows page ${row.slug} with its timeline, read-only.`, { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug] }) });}};await noTimeline(engine);@@ -112,7 +117,10 @@ export async function preparePhantomDelete(engine: BrainEngine, row: WriteRequesvalidate: async tx => { await page.validate?.(tx); await noTimeline(tx); },apply: async tx => {const canonical = await tx.readPageSnapshot(canonicalSlug, { sourceId: row.source_id });- if (!canonical) throw new OperationError('page_not_found', 'The redirect target disappeared before the phantom delete.');+ if (!canonical) {+ throw opError('page_not_found', 'The redirect target disappeared before the phantom delete.',+ `Canonical page ${canonicalSlug} in source ${row.source_id} was deleted before request ${row.request_id} could redirect phantom ${row.slug} to it, so the transaction rolled back and the phantom stays. No manual step is needed; the next cycle re-evaluates it.`);+ }await mergePhantomLinks(tx, Number(row.page_id), canonical.page.id);return page.apply(tx);} };diff --git a/src/core/persistence/authority.ts b/src/core/persistence/authority.tsindex 7d246a3a2f..60ecdab0bf 100644--- a/src/core/persistence/authority.ts+++ b/src/core/persistence/authority.ts@@ -1,6 +1,7 @@import type { BrainEngine } from '../engine.ts';import type { OperationContext } from '../ops/contract.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { slugUnderBoundPrefixes, matchesSlugAllowList, noSourceGrantError } from '../ops/context.ts';import { NO_SOURCES } from '../source-id.ts';import { hasScope } from '../scope.ts';@@ -106,7 +107,11 @@ export async function authorizeWrite(engine: SqlEngine, a: WriteAuthority, operaexport async function authorizeStoredRequest(engine: SqlEngine, row: WriteRequest, lock = false): Promise<void> {const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean }>(`SELECT incarnation,archived FROM sources WHERE id=$1${lock ? ' FOR SHARE' : ''}`, [row.source_id]);- if (!source || source.archived || source.incarnation !== row.source_incarnation) throw new OperationError('source_changed', 'The accepted source is no longer active.');+ if (!source || source.archived || source.incarnation !== row.source_incarnation) {+ throw opError('source_changed', 'The accepted source is no longer active.',+ `Source ${row.source_id} was archived, removed, or recreated after request ${row.request_id} was accepted, so it will not be applied. Check the source's writer status; a new write must target the current source.`,+ { fix: readFix(`Shows source ${row.source_id}'s current registration and requests, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] }) });+ }await authorizeWrite(engine, row.authority, row.operation, row.slug, lock);if (skillWrite(row.operation)) {const affected = (row.authority as WriteAuthority & { skillSlugsUsed?: unknown }).skillSlugsUsed;diff --git a/src/core/persistence/canonical-projections.ts b/src/core/persistence/canonical-projections.tsindex f7e07a3b1f..8232785f6d 100644--- a/src/core/persistence/canonical-projections.ts+++ b/src/core/persistence/canonical-projections.ts@@ -10,7 +10,8 @@ import { extractTimelineFromContent, type ExtractedTimelineEntry } from '../timeimport { sanitizeRemoteBody } from '../remote-body.ts';import { sanitizeForJsonb } from '../batch-rows.ts';import { materializedMarker, materializedMarkerHash, timelineKey, timelineKeyHash } from '../timeline-marker.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';type CanonicalBody = Pick<ParsedPage, 'compiled_truth' | 'timeline'>;@@ -217,16 +218,21 @@ function canonicalTakeRows(body: CanonicalBody): Set<number> {}/** Validate a canonical body and compile its provider-free projections. */+function fenceError(message: string, slug: string, sourceId: string, what: string) {+ return opError('invalid_params', message, `${what} on page ${slug} in source ${sourceId}, so it was not written. Fix the fence in the page body, then write the page again.`,+ { fix: readFix(`Shows page ${slug} with its fences, read-only.`, { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) });+}+export function compileCanonicalProjections(page: ParsedPage, slug: string, sourceId: string) {const fields=[page.compiled_truth,page.timeline ?? ''];for(const field of fields) for(const marker of [FACTS_FENCE_BEGIN,FACTS_FENCE_END,TAKES_FENCE_BEGIN,TAKES_FENCE_END]) {- if(field.split(marker).length>2) throw new OperationError('invalid_params','Each canonical body section must contain at most one facts fence and one takes fence.');+ if(field.split(marker).length>2) throw fenceError('Each canonical body section must contain at most one facts fence and one takes fence.', slug, sourceId, 'A body section repeats a facts or takes fence marker');}const factSets=fields.map(parseFactsFence),takeSets=fields.map(parseTakesFence);- if ([...factSets,...takeSets].some(set=>set.warnings.length)) throw new OperationError('invalid_params','A canonical facts or takes fence cannot be parsed losslessly.');+ if ([...factSets,...takeSets].some(set=>set.warnings.length)) throw fenceError('A canonical facts or takes fence cannot be parsed losslessly.', slug, sourceId, 'A facts or takes table does not parse cleanly');const facts=factSets.flatMap(set=>set.facts),takes=takeSets.flatMap(set=>set.takes);for(const rows of [facts,takes]) if(new Set(rows.map(row=>row.rowNum)).size!==rows.length) {- throw new OperationError('invalid_params','Canonical row numbers must be unique across the entire page.');+ throw fenceError('Canonical row numbers must be unique across the entire page.', slug, sourceId, 'Two facts or takes rows share a row number');}return { factRows: extractFactsFromFenceText(facts,slug,sourceId), takes };}diff --git a/src/core/persistence/checkpoint-validation.ts b/src/core/persistence/checkpoint-validation.tsindex 526e88f971..d43063b712 100644--- a/src/core/persistence/checkpoint-validation.ts+++ b/src/core/persistence/checkpoint-validation.ts@@ -18,7 +18,7 @@* `gbrain write-request` / MCP `get_write_request`.*/import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';import { PERSISTENCE_SYNC_RUN_INDEXES } from './schema.ts';import { docsAnchor } from './connector-errors.ts';import type { SyncProcessingOptions } from './sync-authority.ts';@@ -49,7 +49,9 @@ export async function findIncompleteSyncReceipt(tx: Pick<BrainEngine, 'executeRa} catch (error) {const failure = error as { code?: string; message?: string };if (failure?.code !== '57014' || !/statement timeout/.test(String(failure.message))) throw error;- throw new OperationError(CHECKPOINT_VALIDATION_TIMEOUT, CHECKPOINT_VALIDATION_TIMEOUT_MESSAGE);+ throw opError(CHECKPOINT_VALIDATION_TIMEOUT, CHECKPOINT_VALIDATION_TIMEOUT_MESSAGE,+ `Page writes that sync run ${runId} already committed stay committed; only its checkpoint did not. This usually means the request table lacks its lookup indexes: preview that repair and apply it after the user approves, then sync again.`,+ { fix: { argv: ['gbrain', 'repair', 'request-indexes', '--json'], consent: [], actor: 'agent', why: 'Previews the missing request-table indexes without changing anything.', requires_exclusive: false } });}}diff --git a/src/core/persistence/context.ts b/src/core/persistence/context.tsindex 1a3b6d4a8b..0311e4f36a 100644--- a/src/core/persistence/context.ts+++ b/src/core/persistence/context.ts@@ -1,6 +1,6 @@import { AsyncLocalStorage } from 'node:async_hooks';import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import type { WriteAttribution } from './attribution.ts';interface PublicationContext { brainId: string; sourceIds: ReadonlySet<string>; active: boolean; }@@ -39,7 +39,11 @@ const attributionValues = (outer: string[], attribution: WriteAttribution) => ou*/export async function withCoordinatedWrite<T>(engine: BrainEngine, sourceIds: string[], fn: () => Promise<T>, attribution: WriteAttribution): Promise<T> {const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');- if (!brain) throw new OperationError('writer_not_initialized', 'Persistence identity is missing.');+ if (!brain) {+ throw opError('writer_not_initialized', 'Persistence identity is missing.',+ 'This brain has no persistence identity row, so coordinated writes cannot run and nothing was written. List the pending migrations that create it and ask the user to approve applying them.',+ { fix: { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the pending migrations without applying them.', requires_exclusive: false } });+ }const context: PublicationContext = { brainId: brain.brain_id, sourceIds: new Set(sourceIds), active: true };return withTransactionSettings(engine, ['gbrain.write_sources', ...ATTRIBUTION_SETTINGS],([, ...outer]) => [JSON.stringify(sourceIds), ...attributionValues(outer, attribution)],diff --git a/src/core/persistence/control.ts b/src/core/persistence/control.tsindex db4359cc37..14ed4655b6 100644--- a/src/core/persistence/control.ts+++ b/src/core/persistence/control.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import { authorizeStoredRequest } from './authority.ts';import { completeWrite, getWriteRequest, lockCounters } from './journal.ts';import { isTerminal, principalKey, type Principal, type WriteRequest } from './model.ts';@@ -8,7 +8,7 @@ export async function listWriteRequests(engine: BrainEngine, principal: Principaopts: { sourceId: string; before?: string; limit?: number; slugPrefixes?: string[]; operations?: string[]; slugAllowList?: string[];authorize?: (row: WriteRequest) => Promise<boolean> }): Promise<{ requests: WriteRequest[]; next: string | null }> {const limit = Math.min(100, Math.max(1, Math.floor(opts.limit ?? 25)));- if (opts.before !== undefined && !/^\d+$/.test(opts.before)) throw new OperationError('invalid_params', 'Invalid write request cursor.');+ if (opts.before !== undefined && !/^\d+$/.test(opts.before)) throw opError('invalid_params', 'Invalid write request cursor.', 'Pass the next cursor exactly as the previous page returned it (a numeric sequence), or omit it to start from the newest requests.');// Principal/source restrictions are applied before SQL pagination. Additional// current fences filter candidates without leaking counts or foreign cursors.const visible: WriteRequest[] = [];diff --git a/src/core/persistence/database-write.ts b/src/core/persistence/database-write.tsindex 19d301e516..2011e95228 100644--- a/src/core/persistence/database-write.ts+++ b/src/core/persistence/database-write.ts@@ -1,5 +1,6 @@import type { BrainEngine } from '../engine.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { opError, type OperationContext } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { assertPersistenceAccepting } from './service.ts';import { authorizeWrite, submissionAuthority } from './authority.ts';import { managedPersistenceEnabled } from './ownership.ts';@@ -23,14 +24,20 @@ export async function coordinatedDatabaseWrite<T>(ctx: OperationContext, operaticonst sourceId = ctx.sourceId ?? 'default';const [source] = await ctx.engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1', [sourceId]);- if (!source || source.archived) throw new OperationError('source_changed', 'The write source is not active.');+ if (!source || source.archived) {+ throw opError('source_changed', 'The write source is not active.',+ `Source ${sourceId} is archived or missing, so nothing was written. Write to an active source, or ask the user to restore ${sourceId}.`,+ { fix: readFix('Lists sources with their archived state, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'], mcp: { tool: 'sources_list', arguments: {} } }) });+ }await initializeLocalPersistence(ctx);const authority = await submissionAuthority(ctx, operation, sourceId, source.incarnation, authoritySlug);const value = await ctx.engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {const [current] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);if (!current || current.archived || current.incarnation !== source.incarnation) {- throw new OperationError('source_changed', 'The write source changed before the write.');+ throw opError('source_changed', 'The write source changed before the write.',+ `Source ${sourceId} was archived or recreated before this ${operation} committed, so it rolled back and nothing was written. Check the source, then submit the write again against its current registration.`,+ { fix: readFix('Lists sources with their archived state, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'], mcp: { tool: 'sources_list', arguments: {} } }) });}await authorizeWrite(tx, authority, operation, authoritySlug, true);await tx.lockPageKeys(lockSlugs.map(slug => ({ sourceId, slug })));diff --git a/src/core/persistence/deactivation.ts b/src/core/persistence/deactivation.tsindex 7acf6d65f1..58dfcb3e71 100644--- a/src/core/persistence/deactivation.ts+++ b/src/core/persistence/deactivation.ts@@ -27,7 +27,8 @@ import { existsSync, lstatSync, readFileSync, readdirSync, unlinkSync } from 'noimport { dirname, join, resolve } from 'node:path';import type { BrainEngine } from '../engine.ts';import { configDir } from '../config.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { acquireWorktree, getWorktreeBinding } from './ownership.ts';import { existingLocalHostId } from './identity.ts';import type { NativeLockHandle } from './native-lock.ts';@@ -80,7 +81,11 @@ async function readBrain(engine: BrainEngine, lock = false): Promise<BrainRow> {(to_jsonb(persistence_brain)->>'skill_bundles_enabled')::boolean AS skill_bundles_enabled,(to_jsonb(persistence_brain)->>'writer_protocol_floor')::int AS writer_protocol_floorFROM persistence_brain WHERE singleton=1${lock ? ' FOR UPDATE' : ''}`);- if (!brain) throw new OperationError('writer_not_initialized', 'Persistence identity is missing.');+ if (!brain) {+ throw opError('writer_not_initialized', 'Persistence identity is missing.',+ 'This brain has no persistence identity row, so there is no managed mode to read or deactivate. List the pending migrations that create it and ask the user before applying them.',+ { fix: { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the pending migrations without applying them.', requires_exclusive: false } });+ }return brain;}@@ -204,7 +209,11 @@ export async function deactivatePersistence(engine: BrainEngine, opts: { dryRun?const current = await readBrain(tx, true);await assertWriterAdminState(tx, opts.expectedState);await assertWriterAdminUnlocked(tx);- if (!current.enabled) throw new OperationError('writer_admin_state_changed', 'The brain was deactivated concurrently.');+ if (!current.enabled) {+ throw opError('writer_admin_state_changed', 'The brain was deactivated concurrently.',+ 'Another process already deactivated managed persistence, so this run changed nothing more. Confirm the state in writer status; no further deactivation is needed.',+ { fix: readFix('Shows whether managed persistence is enabled, read-only.', { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] }) });+ }await tx.executeRaw('SELECT id FROM persistence_worktrees ORDER BY id FOR UPDATE');await tx.executeRaw('SELECT id FROM sources ORDER BY id FOR UPDATE');await opts.hooks?.afterLocks?.();diff --git a/src/core/persistence/digest.ts b/src/core/persistence/digest.tsindex a16f052cd3..56f0219083 100644--- a/src/core/persistence/digest.ts+++ b/src/core/persistence/digest.ts@@ -1,6 +1,6 @@import { createHash } from 'node:crypto';import { isWriteRequestId } from './types.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';/** Intent identity includes caller input before timestamps and other generated defaults. */export function stableJson(value: unknown): string {@@ -23,7 +23,7 @@ export function sha256(value: string | Uint8Array): string { return createHash('export function jsonBytes(value: unknown): number { return Buffer.byteLength(stableJson(value), 'utf8'); }export function requireUuid(value: string): string {if (!isWriteRequestId(value)) {- throw new OperationError('invalid_params', 'request_id must be a UUID.');+ throw opError('invalid_params', 'request_id must be a UUID.', 'Pass request_id as a UUID such as 123e4567-e89b-42d3-a456-426614174000, or omit it to get a new one; reuse an id only to replay the same request (same request_id, same intent).');}return value.toLowerCase();}diff --git a/src/core/persistence/embed-facts-administration.ts b/src/core/persistence/embed-facts-administration.tsindex 28be4b0f2d..f66a1e738d 100644--- a/src/core/persistence/embed-facts-administration.ts+++ b/src/core/persistence/embed-facts-administration.ts@@ -2,10 +2,10 @@ import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { embedStaleFacts } from '../embed-facts.ts';import { validateEmbedFactsOptions } from '../embed-facts-options.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';import { EmbeddingDisabledError } from '../embedding-dim-check.ts';import { currentVerifiedLocalWriter } from './identity.ts';-import { trustedCliRequired } from '../ops/op-fix.ts';+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';export async function runAuthenticatedFactEmbedding(engine: BrainEngine, params: Record<string, unknown>, selectedConfig: GBrainConfig | null = null): Promise<Record<string, unknown>> {const verified = currentVerifiedLocalWriter();@@ -13,7 +13,8 @@ export async function runAuthenticatedFactEmbedding(engine: BrainEngine, params:throw trustedCliRequired('Fact embedding repair requires a current trusted CLI registration');}if (Object.keys(params).some(key => key !== 'options')) {- throw new OperationError('invalid_params', 'Fact embedding repair requires typed options');+ throw opError('invalid_params', 'Fact embedding repair requires typed options',+ 'Run the CLI command gbrain embed --stale --facts --source with --dry-run first; it builds the typed options this owner lane accepts.');}const options = validateEmbedFactsOptions(params.options);const controller = new AbortController();@@ -26,7 +27,11 @@ export async function runAuthenticatedFactEmbedding(engine: BrainEngine, params:work = embedStaleFacts(engine, { ...options, signal: controller.signal }, selectedConfig);return { ...await work };} catch (error) {- if (error instanceof EmbeddingDisabledError) throw new OperationError('embedding_disabled', error.message);+ if (error instanceof EmbeddingDisabledError) {+ throw opError('embedding_disabled', error.message,+ 'Embeddings are disabled for this brain, so fact embeddings cannot be repaired and nothing was spent. Enabling an embedding provider is the user\'s decision because it can cost money.',+ { fix: readFix('Reports the brain\'s embedding readiness, read-only.', { argv: ['gbrain', 'doctor', '--only', 'embeddings', '--json'] }) });+ }throw error;} finally { unregister(); }}diff --git a/src/core/persistence/embedding-settlement.ts b/src/core/persistence/embedding-settlement.tsindex 1c2985c662..aaa0da2c3e 100644--- a/src/core/persistence/embedding-settlement.ts+++ b/src/core/persistence/embedding-settlement.ts@@ -26,7 +26,7 @@*/import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import { EmbeddingDisabledError } from '../embedding-dim-check.ts';import { MAX_RATE_LIMIT_RETRIES } from '../embed-retry.ts';import { digest } from './digest.ts';@@ -158,7 +158,10 @@ async function queueRetry(tx: BrainEngine, effect: PersistenceEffect, opts: { drconst grantId = paid && opts.runId ? embeddingGrantId(opts.runId, effect.id) : null;if (grantId && grants.includes(grantId)) return { ...base, reason: 'grant_replayed' };if (opts.dryRun) return { ...base, paid, ...(exhausted ? { reason: 'grant_new_retry_cycle' } : {}) };- if (paid && !grantId) throw new OperationError('invalid_params', 'An embedding retry grant needs a repair run id.');+ if (paid && !grantId) {+ throw opError('invalid_params', 'An embedding retry grant needs a repair run id.',+ 'Paid embedding retries run only through gbrain repair embedding-effects, which supplies the run id. Preview it with gbrain repair embedding-effects --json and apply it after the user approves the cost.');+ }const now = new Date().toISOString();const data = { ...effect.data, repair_requeued_at: now,...(effect.state === 'failed' ? { embedding_attempt_base: effect.attempts, embedding_retry_base: effect.attempts } : {}),diff --git a/src/core/persistence/import-mutations.ts b/src/core/persistence/import-mutations.tsindex cbc79c92e7..7e551cb006 100644--- a/src/core/persistence/import-mutations.ts+++ b/src/core/persistence/import-mutations.ts@@ -4,7 +4,7 @@ import { isAbsolute, join, relative, resolve, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';import { isImageFilePath, type ImportResult } from '../import-file.ts';import { loadConfig } from '../config.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { currentVerifiedLocalWriter, localHostId } from './identity.ts';import { getWorktreeBinding } from './ownership.ts';@@ -15,7 +15,7 @@ import { submissionAuthority } from './authority.ts';import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';import type { WorktreeBinding } from './ownership.ts';import type { PageSnapshot } from '../page-state/types.ts';-import { trustedCliRequired } from '../ops/op-fix.ts';+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';export async function importManagedFile(engine: BrainEngine, filePath: string, sourcePath: string,opts: { sourceId?: string; noEmbed?: boolean; activePack?: ImportPack; signal?: AbortSignal; slugRoot?: string } = {}): Promise<ImportResult> {@@ -25,12 +25,15 @@ export async function importManagedFile(engine: BrainEngine, filePath: string, s}opts.signal?.throwIfAborted();if (isImageFilePath(sourcePath) && process.env.GBRAIN_EMBEDDING_MULTIMODAL !== 'true') {- throw new OperationError('invalid_params', 'Image import requires GBRAIN_EMBEDDING_MULTIMODAL=true.');+ throw opError('invalid_params', 'Image import requires GBRAIN_EMBEDDING_MULTIMODAL=true.',+ `${sourcePath} is an image and multimodal embeddings are off, so it was not imported. Import only text files, or ask the user whether to enable GBRAIN_EMBEDDING_MULTIMODAL=true for the gbrain process (image embeddings can cost money).`);}const sourceId = opts.sourceId ?? 'default';const binding = await getWorktreeBinding(engine, sourceId);if (!binding?.local_path || binding.owner_host_id !== localHostId() || binding.state !== 'active') {- throw new OperationError('owner_unavailable', 'Managed import must run on the active canonical owner for the selected source.');+ throw opError('owner_unavailable', 'Managed import must run on the active canonical owner for the selected source.',+ `This host is not the active owner of source ${sourceId}, so nothing was imported. Run the import on the owner host that writer status names, or wait until its owner is active.`,+ { fix: readFix(`Shows source ${sourceId}'s owner host and state, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });}const root = join(binding.local_path, binding.relative_path);const inputPath = resolve(filePath);diff --git a/src/core/persistence/limits.ts b/src/core/persistence/limits.tsindex 4f2e0a5df4..d3bc03910e 100644--- a/src/core/persistence/limits.ts+++ b/src/core/persistence/limits.ts@@ -1,4 +1,4 @@-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';import { DEFAULT_JOURNAL_LIMITS, type JournalLimits, type SqlEngine } from './model.ts';export const RECEIPT_RETENTION_KEY = 'persistence.receipt_retention_days';@@ -13,7 +13,8 @@ export const JOURNAL_CONFIG_KEYS: readonly string[] = [];export function parseJournalConfigValue(key:string,value:string):number {if(!/^(0|[1-9]\d*)$/.test(value) || !Number.isSafeInteger(Number(value))) {- throw new OperationError('invalid_params',`Invalid ${key}: expected a nonnegative integer.`);+ throw opError('invalid_params',`Invalid ${key}: expected a nonnegative integer.`,+ `Set ${key} to a whole number of 0 or more with gbrain config set ${key} followed by the number, or unset it to use the default.`);}return Number(value);}diff --git a/src/core/persistence/page-visibility.ts b/src/core/persistence/page-visibility.tsindex 62b0a61ce3..8de8361b68 100644--- a/src/core/persistence/page-visibility.ts+++ b/src/core/persistence/page-visibility.ts@@ -1,4 +1,4 @@-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';import { REMOTE_PRIVATE_PAGES_KEY, privatePagesFilterFragment } from '../search/private-visibility.ts';import type { SqlEngine, WriteAuthority } from './model.ts';@@ -15,5 +15,5 @@ export async function authorizePageVisibility(engine: SqlEngine, authority: Writif (!(authority.excludePrivate ?? true) && !await excludesPrivateWrites(engine, true)) return;const rows = await engine.executeRaw(`SELECT 1 FROM pages WHERE source_id=$1 AND slug=$2AND NOT (${privatePagesFilterFragment('pages')}) LIMIT 1`, [authority.sourceId, slug]);- if (rows.length) throw new OperationError('page_not_found', 'Page not found.');+ if (rows.length) throw opError('page_not_found', 'Page not found.', 'This page does not exist or is not visible to this connection, so nothing was written. Write to a different slug, or confirm the slug with a search first.');}diff --git a/src/core/persistence/protected-takes.ts b/src/core/persistence/protected-takes.tsindex 0bdebbd49a..8f94fb5426 100644--- a/src/core/persistence/protected-takes.ts+++ b/src/core/persistence/protected-takes.ts@@ -1,19 +1,21 @@import { TAKES_FENCE_BEGIN, TAKES_FENCE_END } from '../takes-fence.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';function fence(body:string):string|null {const start=body.indexOf(TAKES_FENCE_BEGIN);if(start<0) return null;const end=body.indexOf(TAKES_FENCE_END,start+TAKES_FENCE_BEGIN.length);if(end<0 || body.indexOf(TAKES_FENCE_BEGIN,start+TAKES_FENCE_BEGIN.length)>=0) {- throw new OperationError('invalid_params','The takes fence must be repaired before replacing this page.');+ throw opError('invalid_params','The takes fence must be repaired before replacing this page.',+ 'The stored page has an unclosed or repeated takes fence, so a full replacement could lose takes. Ask the user to repair the fence (one begin and one end marker) in the page, then replace it again.');}return body.slice(start,end+TAKES_FENCE_END.length);}/** Remote full-page reads omit takes; a round trip must preserve their canonical fence. */export function preserveProtectedTakes(incoming:string,stored:string):string {const before=fence(stored),after=fence(incoming);- if(after!==null && after!==before) throw new OperationError('permission_denied','Use the scoped takes operations to mutate a takes fence.');+ if(after!==null && after!==before) throw opError('permission_denied','Use the scoped takes operations to mutate a takes fence.',+ 'Send the page without its takes fence (it is preserved automatically), and change takes with takes_add, takes_update, takes_supersede, or takes_resolve.');if(before===null || after!==null) return incoming;return `${incoming.trimEnd()}\n\n${before}\n`;}diff --git a/src/core/persistence/protocol.ts b/src/core/persistence/protocol.tsindex 69443aeae6..cb3bb77511 100644--- a/src/core/persistence/protocol.ts+++ b/src/core/persistence/protocol.ts@@ -1,5 +1,5 @@import type { SqlEngine, WriteRequest } from './model.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';export async function declarePersistenceProtocol(tx: SqlEngine): Promise<void> {await tx.executeRaw("SELECT set_config('gbrain.persistence_protocol','2',true)");@@ -10,7 +10,8 @@ export const PERSISTENCE_PROTOCOL_PREDICATE = "set_config('gbrain.persistence_prexport function assertMutationProtocol(row: Pick<WriteRequest, 'target_kind' | 'protocol_version'>): void {if (((row.target_kind ?? 'page') === 'page' && (row.protocol_version ?? 1) === 1)|| (row.target_kind === 'skill_bundle' && row.protocol_version === 2)) return;- throw new OperationError('unsupported_mutation_protocol', 'This consumer does not support the request target and protocol version.');+ throw opError('unsupported_mutation_protocol', 'This consumer does not support the request target and protocol version.',+ `This gbrain process cannot apply ${row.target_kind ?? 'page'} requests at protocol ${row.protocol_version ?? 1}, so it left the request untouched. A newer gbrain wrote it: upgrading gbrain on this host (the user's call) lets it be applied.`);}export async function assertSharedSkillPersistence(engine: SqlEngine, sourceId?: string): Promise<void> {diff --git a/src/core/persistence/provider.ts b/src/core/persistence/provider.tsindex a531133164..d4bf4f9fd5 100644--- a/src/core/persistence/provider.ts+++ b/src/core/persistence/provider.ts@@ -1,7 +1,7 @@import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { operations } from '../operations.ts';-import { OperationError, type AuthInfo } from '../ops/contract.ts';+import { opError, OperationError, type AuthInfo } from '../ops/contract.ts';import { hasScope, operationScopesAllowed } from '../scope.ts';import { resolveSourceId } from '../source-resolver.ts';import { dispatchToolCall } from '../../mcp/dispatch.ts';@@ -14,6 +14,10 @@ import { boundedWriteWaitMs } from './write-wait.ts';export { residentPersistenceConfig } from './local-client.ts';import { projectionBacklog } from '../page-state/projections.ts';import { trustedCliRequired } from '../ops/op-fix.ts';+import type { Action } from '../agent-output.ts';++const localWritersFix: Action = { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], consent: [], actor: 'agent',+ why: 'Shows this brain\'s local writer registrations with their grants, read-only.', requires_exclusive: false };/** Resident lifecycle owns the consumer; each connection proves its own durable registration. */export async function createPersistenceIpcProvider(engine: BrainEngine, config: GBrainConfig): Promise<PersistenceIpcProvider> {@@ -28,20 +32,28 @@ export async function createPersistenceIpcProvider(engine: BrainEngine, config:startPersistenceConsumer(engine, config);return { brainId: brain.brain_id, projectionStatus: () => projectionBacklog(engine), dispatch: request => withVerifiedLocalRegistration(engine, request.registration, async verified => {assertPersistenceAccepting(engine);- if (request.brain_id !== brain.brain_id) throw new OperationError('permission_denied', 'This registration belongs to a different brain.');+ if (request.brain_id !== brain.brain_id) {+ throw opError('permission_denied', 'This registration belongs to a different brain.',+ 'The CLI sent a writer registration for another brain to this brain\'s owner. Select the intended brain with --brain; registering this CLI on this brain is a credentials step the user approves.',+ { fix: localWritersFix });+ }const operation = operations.find(op => op.name === request.operation);const localSkillAdministration = !verified.remote && verified.principal.kind === 'local_cli'&& ['get_skill_policy', 'set_skill_policy', 'get_skill_retention', 'prune_skill_revisions', 'retain_skill_revision', 'import_skill_proposal'].includes(request.operation);if (!operation || (!localSkillAdministration && !hasScope(verified.grant.scopes, operation.scope ?? 'read'))|| (verified.remote && !operationScopesAllowed(verified.grant.scopes, operation))|| (verified.grant.operations !== null && !verified.grant.operations.includes(operation.name))) {- throw new OperationError('permission_denied', 'The local writer grant excludes this operation.');+ throw opError('permission_denied', 'The local writer grant excludes this operation.',+ `This CLI's writer grant does not cover ${request.operation}. Review the grant; widening it with gbrain auth local-writer register --replace is a credentials change the user approves.`,+ { fix: localWritersFix });}const sourceId = await resolveSourceId(engine, request.routing.source, request.routing.cwd, { skipLocalSignals: true });const unrestricted = verified.grant.sourceIds.includes('*');const sourceAllowed = (source: unknown) => typeof source === 'string' && (unrestricted || verified.grant.sourceIds.includes(source));if (!sourceAllowed(sourceId) || (request.params.source_id !== undefined && !sourceAllowed(request.params.source_id))) {- throw new OperationError('permission_denied', 'The local writer grant excludes this source.');+ throw opError('permission_denied', 'The local writer grant excludes this source.',+ `This CLI's writer grant does not cover source ${String(request.params.source_id ?? sourceId)}. Use a source the grant lists; widening it is a credentials change the user approves.`,+ { fix: localWritersFix });}// AuthInfo carries server-constructed read/fence ceilings; durable identity// remains in the verifier's async context, never a fabricated OAuth identity.diff --git a/src/core/persistence/reindex-administration.ts b/src/core/persistence/reindex-administration.tsindex f2b6eaf5be..eefc852834 100644--- a/src/core/persistence/reindex-administration.ts+++ b/src/core/persistence/reindex-administration.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import { currentVerifiedLocalWriter } from './identity.ts';import { runReindexCode, type ReindexCodeOpts } from '../../commands/reindex-code.ts';import { trustedCliRequired } from '../ops/op-fix.ts';@@ -7,14 +7,14 @@ import { trustedCliRequired } from '../ops/op-fix.ts';export async function runAuthenticatedCodeReindex(engine: BrainEngine, params: Record<string, unknown>): Promise<Record<string, unknown>> {const verified = currentVerifiedLocalWriter();if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw trustedCliRequired('Code reindex requires a trusted CLI registration.');- if (Object.keys(params).some(k => k !== 'options') || !params.options || typeof params.options !== 'object' || Array.isArray(params.options)) throw new OperationError('invalid_params', 'Code reindex requires typed options.');+ if (Object.keys(params).some(k => k !== 'options') || !params.options || typeof params.options !== 'object' || Array.isArray(params.options)) throw opError('invalid_params', 'Code reindex requires typed options.', 'Run gbrain reindex-code from the CLI (gbrain reindex-code --help lists its flags); it builds the typed options this owner lane accepts.');const options = params.options as Record<string, unknown>;const allowed = ['sourceId', 'dryRun', 'yes', 'json', 'force', 'noEmbed', 'workers', 'maxCostUsd'];if (Object.keys(options).some(k => !allowed.includes(k)) ||['dryRun', 'yes', 'json', 'force', 'noEmbed'].some(k => options[k] !== undefined && typeof options[k] !== 'boolean') ||options.sourceId !== undefined && (typeof options.sourceId !== 'string' || !options.sourceId) ||options.workers !== undefined && (!Number.isInteger(options.workers) || Number(options.workers) < 1 || Number(options.workers) > 64) ||- options.maxCostUsd !== undefined && (typeof options.maxCostUsd !== 'number' || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0)) throw new OperationError('invalid_params', 'Invalid code reindex options.');+ options.maxCostUsd !== undefined && (typeof options.maxCostUsd !== 'number' || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0)) throw opError('invalid_params', 'Invalid code reindex options.', 'Use gbrain reindex-code flags only: --source with a source id, --workers from 1 to 64, and --max-cost-usd above 0; gbrain reindex-code --help lists the rest.');if (!options.noEmbed && !options.dryRun && !options.yes) {throw new OperationError('confirmation_required', 'Explicit embedding consent is required; use --no-embed for keyless recovery.','The CLI asks the user before delegating; run gbrain reindex-code without --yes to get the consent request and relay it to the user.');@@ -22,7 +22,9 @@ export async function runAuthenticatedCodeReindex(engine: BrainEngine, params: Rif (!verified.grant.scopes.includes('write') || verified.grant.operations !== null && !verified.grant.operations.includes('submit_job') ||verified.grant.slugPrefixes !== null || !verified.grant.sourceIds.includes('*') &&(typeof options.sourceId !== 'string' || !verified.grant.sourceIds.includes(options.sourceId))) {- throw new OperationError('permission_denied', 'Code reindex exceeds the CLI source-wide write grant.');+ throw opError('permission_denied', 'Code reindex exceeds the CLI source-wide write grant.',+ 'This CLI\'s writer grant lacks write and submit_job on every selected source without slug limits. Review the grant; widening it with gbrain auth local-writer register --replace is a credentials change the user approves.',+ { fix: { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], consent: [], actor: 'agent', why: 'Shows this brain\'s local writer registrations with their grants, read-only.', requires_exclusive: false } });}const work = runReindexCode(engine, options as ReindexCodeOpts);const unregister = engine.registerBeforeDisconnect(async () => { await work.catch(() => {}); });diff --git a/src/core/persistence/root-registry.ts b/src/core/persistence/root-registry.tsindex b872799673..a24ed3e39a 100644--- a/src/core/persistence/root-registry.ts+++ b/src/core/persistence/root-registry.ts@@ -3,7 +3,7 @@ import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openimport { basename, dirname, isAbsolute, join, resolve } from 'node:path';import { configDir } from '../config.ts';import { flushDirectory } from '../fs-durable.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';export interface ManagedRootRecord {local_path: string;@@ -48,7 +48,8 @@ function markerExists(path: string): boolean {try { lstatSync(path); return true; }catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false;- throw new OperationError('writer_coordinator_required', 'Managed-root marker cannot be inspected.');+ throw opError('writer_coordinator_required', 'Managed-root marker cannot be inspected.',+ `gbrain could not read ${path} (${(error as NodeJS.ErrnoException).code ?? 'unknown error'}), so it cannot tell whether this checkout is managed and refuses the write. Fix the path's permissions for this user, then run the command again.`);}}/** Shared refusal marker helps installations with separate homes. It NEVER grants ownership. */@@ -101,7 +102,10 @@ function resolveFilesystemPath(path: string, realpath: (path: string) => string)* them. Per-root files prevent independent registration from dropping siblings.*/export function recordManagedRoots(brainId: string, records: ManagedRootRecord[], modeEpoch?: number): void {- if (!/^[a-f0-9-]{36}$/i.test(brainId)) throw new OperationError('storage_error', 'Invalid managed-root brain identity.');+ if (!/^[a-f0-9-]{36}$/i.test(brainId)) {+ throw opError('storage_error', 'Invalid managed-root brain identity.',+ 'The managed-root registry was given a brain identity that is not a UUID, so nothing was recorded. This is an internal fault: run gbrain doctor --json and report it to the user.');+ }if (!records.length) return;const directory = registryDirectory(); mkdirSync(directory, { recursive: true, mode: 0o700 }); ensureMode(directory, 0o700);let changed = false;diff --git a/src/core/persistence/semantic-pages.ts b/src/core/persistence/semantic-pages.tsindex e92eb67f24..5a45198ae5 100644--- a/src/core/persistence/semantic-pages.ts+++ b/src/core/persistence/semantic-pages.ts@@ -1,7 +1,7 @@import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import { pageIdentityError } from './page-identity.ts';import { renderTimelineEntry, spliceTimelineBlock } from '../timeline-write-through.ts';import { extractTimelineFromContent } from '../timeline-extract.ts';@@ -44,7 +44,9 @@ export async function prepareSemanticPageMutation(engine: BrainEngine, row: Writconst p = row.intent!;if (p.expected_revision !== undefined) assertPageRevision(snapshot,engineMutationPrecondition(parseMutationPrecondition(p)));if (row.operation === 'add_tag' || row.operation === 'remove_tag') {- if (typeof p.tag !== 'string' || !p.tag.trim()) throw new OperationError('invalid_params', 'A tag must be nonempty.');+ if (typeof p.tag !== 'string' || !p.tag.trim()) {+ throw opError('invalid_params', 'A tag must be nonempty.', `Request ${row.request_id} for ${row.slug} in source ${row.source_id} named an empty tag, so nothing changed. Submit the tag change again with a nonempty tag.`);+ }const tag = p.tag.trim();const tags = row.operation === 'add_tag' ? [...new Set([...snapshot.tags, tag])].sort() : snapshot.tags.filter(value => value !== tag);const prepared = await preparePageMutation(engine, row, config, {@@ -52,10 +54,16 @@ export async function prepareSemanticPageMutation(engine: BrainEngine, row: Writ});return { ...prepared, apply: async tx => ({ ...await prepared.apply(tx), status: 'ok', tag }) };}- if (row.operation !== 'add_timeline_entry') throw new OperationError('writer_coordinator_required', 'This semantic writer has no registered preparation handler.');+ if (row.operation !== 'add_timeline_entry') {+ throw opError('writer_coordinator_required', 'This semantic writer has no registered preparation handler.',+ `Request ${row.request_id} (${row.operation}) in source ${row.source_id} has no preparation handler in this gbrain version, so nothing changed. This is an internal or version-skew fault: report it to the user.`);+ }const entry = { date: String(p.date), summary: String(p.summary), source: String(p.source ?? ''), detail: String(p.detail ?? '') };const rendered = renderTimelineEntry(entry, row.slug);- if (!rendered) throw new OperationError('invalid_params', 'The timeline entry cannot be represented losslessly in Markdown.');+ if (!rendered) {+ throw opError('invalid_params', 'The timeline entry cannot be represented losslessly in Markdown.',+ `Request ${row.request_id}'s timeline entry for ${row.slug} would not read back as the same entry, so nothing changed. Submit it again with a YYYY-MM-DD date and a nonempty single-line summary that has no Markdown list or heading syntax.`);+ }// #5567: a writer that regenerates the page from its own inputs never holds this entry. The materialized// marker makes its preserving render carry the bullet forward instead of deleting it (fix wave 4 audit).const [source] = await engine.executeRaw<{ kind: string | null }>("SELECT config->>'kind' AS kind FROM sources WHERE id=$1", [row.source_id]);diff --git a/src/core/persistence/skill-activation.ts b/src/core/persistence/skill-activation.tsindex c0dfa679b5..8243b29777 100644--- a/src/core/persistence/skill-activation.ts+++ b/src/core/persistence/skill-activation.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import { activatePersistence, type ActivationReport } from './activation.ts';import { existingLocalHostId, localHostId } from './identity.ts';import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';@@ -26,7 +26,11 @@ export async function activateSharedSkillPersistence(engine: BrainEngine,if (!binding || binding.owner_host_id !== hostId || binding.state !== 'active' || !binding.local_path) throw quiescence();bindings.push(binding);}- if (!bindings.length) throw new OperationError('writer_registration_required', 'Shared publication requires a registered canonical source root.');+ if (!bindings.length) {+ throw opError('writer_registration_required', 'Shared publication requires a registered canonical source root.',+ 'No active source has a registered canonical owner, so shared skill publication was not enabled. Check writer status; claiming a source root is a deliberate topology change the operator reviews.',+ { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Shows each source\'s canonical owner and claim, read-only.', requires_exclusive: false } });+ }return bindings;};const initial = await loadBindings(engine);diff --git a/src/core/persistence/staging.ts b/src/core/persistence/staging.tsindex f42478192d..1ef253d335 100644--- a/src/core/persistence/staging.ts+++ b/src/core/persistence/staging.ts@@ -3,7 +3,7 @@ import { dirname } from 'node:path';import { atomicStagingPath, validateAtomicStagingPath } from '../atomic-write.ts';import { flushDirectory } from '../fs-durable.ts';import { isWriteTargetContained } from '../path-confine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import { sha256 } from './digest.ts';import type { BrainEngine } from '../engine.ts';import { readJournalLimits } from './limits.ts';@@ -18,7 +18,9 @@ export function recoveryStagingFile(path: string, bytes: string | Uint8Array): Rreturn { path: atomicStagingPath(path), hash: sha256(bytes), bytes: typeof bytes === 'string' ? Buffer.byteLength(bytes) : bytes.byteLength };}function blocked(): OperationError {- return new OperationError('unexpected_staging_bytes', 'Recovery staging has unexpected bytes or identity; the root and its recovery capacity remain reserved.');+ return opError('unexpected_staging_bytes', 'Recovery staging has unexpected bytes or identity; the root and its recovery capacity remain reserved.',+ 'A recovery staging file changed outside gbrain. Inspect the pending recovery in writer status and tell the user; never delete or edit staging files by hand.',+ { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Shows pending recovery records and the capacity they hold, read-only.', requires_exclusive: false } });}function stages(record: StagedRecovery): RecoveryStagingFile[] {const result = Object.values(record.staging ?? {}).filter((stage): stage is RecoveryStagingFile => !!stage);@@ -97,7 +99,9 @@ export async function upgradeRecoveryStaging(engine: BrainEngine, table: 'persisconst minimum = Buffer.byteLength(JSON.stringify(updated)) + Object.values(staging).reduce((sum, stage) => sum + stage.bytes, 0) + 4096;const extra = Math.max(0, minimum - Number(row.recovery_bytes));for (const counter of counters) if (Number(counter.recovery_bytes) + extra > (counter.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) {- throw new OperationError('queue_capacity', 'Recovery is waiting for capacity to durably record its staging paths.');+ throw opError('queue_capacity', 'Recovery is waiting for capacity to durably record its staging paths.',+ `Recovery needs ${extra} more bytes of the ${counter.key === 'brain' ? 'persistence.limits.brain_recovery_bytes' : 'persistence.limits.worktree_recovery_bytes'} budget to record its staging. Let other recovery settle; raising that limit is the user's call, and recovery records are never removed.`,+ { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', why: 'Shows pending recovery records and the capacity they hold, read-only.', requires_exclusive: false } });}await tx.executeRaw(`UPDATE ${table} SET recovery=$2::text::jsonb,recovery_bytes=recovery_bytes+$3 WHERE id=$1`,[id, JSON.stringify(updated), extra]);diff --git a/src/core/persistence/sync-administration.ts b/src/core/persistence/sync-administration.tsindex e9f260fccc..3bd0d2d573 100644--- a/src/core/persistence/sync-administration.ts+++ b/src/core/persistence/sync-administration.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';import { resolveSourceId } from '../source-resolver.ts';import { currentVerifiedLocalWriter } from './identity.ts';import { submissionAuthority } from './authority.ts';@@ -15,7 +15,9 @@ export async function runAuthenticatedSyncSlice(engine: BrainEngine, params: Recconst wire=validateSyncWireParams(params);const sourceId=await resolveSourceId(engine,wire.options.sourceId??null,wire.cwd,{skipLocalSignals:true});const [source]=await engine.executeRaw<{incarnation:string;archived:boolean}>('SELECT incarnation,archived FROM sources WHERE id=$1',[sourceId]);- if(!source||source.archived)throw new OperationError('source_changed','The selected sync source is unavailable.');+ if(!source||source.archived)throw opError('source_changed','The selected sync source is unavailable.',+ `Source ${sourceId} is archived or missing, so nothing was synced. Choose an active source with --source, or ask the user to restore ${sourceId}.`,+ {fix:{argv:['gbrain','sources','list','--json'],consent:[],actor:'agent',why:'Lists sources with their archived state, read-only.',requires_exclusive:false}});await submissionAuthority({engine,remote:false,sourceId} as OperationContext,'submit_job',sourceId,source.incarnation,'__managed_sync_checkpoint__');const controller=new AbortController();const timer=wire.timeoutSeconds>0?setTimeout(()=>controller.abort(),wire.timeoutSeconds*1000):undefined;diff --git a/src/core/persistence/sync-origin.ts b/src/core/persistence/sync-origin.tsindex 0e5ce221c4..1903cccb28 100644--- a/src/core/persistence/sync-origin.ts+++ b/src/core/persistence/sync-origin.ts@@ -1,7 +1,7 @@import { existsSync, realpathSync } from 'node:fs';import { join, relative, sep } from 'node:path';import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import { resolveSlugForPath } from '../sync.ts';/** The source's position inside its Git repository and the origin form sync records. */@@ -48,7 +48,8 @@ export function syncOriginPath(path: string, platform = process.platform): strinif (!normalized || normalized.includes('\0') || normalized.startsWith('/') ||platform === 'win32' && normalized.split('/').some(part => /[<>:"|?*]|[. ]$/.test(part) || /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part)) ||normalized.split('/').some(part => !part || part === '.' || part === '..')) {- throw new OperationError('page_identity_changed', 'The stored sync origin is not a confined relative path.');+ throw opError('page_identity_changed', 'The stored sync origin is not a confined relative path.',+ `The stored source path ${JSON.stringify(path)} is empty, absolute, or escapes the checkout, so sync refused to use it. Inspect the source's writer status and report it to the user; the page origin must be repaired, not overwritten.`);}return normalized;}@@ -60,7 +61,8 @@ export function assertDistinctSyncOrigins(paths: Iterable<string>, platform = prconst normalized = syncOriginPath(path, platform), key = normalized.toLowerCase();const prior = seen.get(key);if (prior !== undefined && prior !== normalized) {- throw new OperationError('page_identity_changed', 'The sync origins contain ambiguous Windows path spellings.');+ throw opError('page_identity_changed', 'The sync origins contain ambiguous Windows path spellings.',+ `${JSON.stringify(prior)} and ${JSON.stringify(normalized)} differ only by letter case, which Windows treats as one file, so sync refused to choose. Rename one of them in the repository, commit, then sync again.`);}seen.set(key, normalized);}@@ -78,6 +80,8 @@ export async function assertSyncPageOrigin(engine: BrainEngine, sourceId: stringconst pages = rows.filter(page => legacy === null || key(page.source_path) !== key(legacy) || sameSyncOrigin(page.source_path, origin, context, page.slug));if (pages.length > 1 || requireOrigin && pageId !== null && pages.length !== 1 ||pages.some(page => page.id !== pageId || !sameSyncOrigin(page.source_path, origin, context, page.slug))) {- throw new OperationError('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.');+ throw opError('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.',+ `${JSON.stringify(sourcePath)} in source ${sourceId} now maps to a different page or to several pages, so this import was refused. Check the source's writer status before syncing again; do not force the import.`,+ { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', why: `Shows source ${sourceId}'s writer and pending requests, read-only.`, requires_exclusive: false } });}}diff --git a/src/core/persistence/sync-wire.ts b/src/core/persistence/sync-wire.tsindex 6d40d5880d..1c917fb7ee 100644--- a/src/core/persistence/sync-wire.ts+++ b/src/core/persistence/sync-wire.ts@@ -1,6 +1,6 @@import { isAbsolute } from 'node:path';import type { SyncOpts } from '../../commands/sync.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';export const SYNC_BOOLEAN_FLAGS = {'--full':'full','--dry-run':'dryRun','--no-pull':'noPull','--no-embed':'noEmbed','--no-extract':'noExtract',@@ -10,7 +10,8 @@ export const SYNC_BOOLEAN_FLAGS = {export const SYNC_VALUE_FLAGS = { '--source':'sourceId','--repo':'repoPath','--src-subpath':'srcSubpath','--strategy':'strategy','--exclude':'exclude','--include-hidden':'includeHidden' } as const;export interface SyncWireParams { options: SyncOpts; cwd: string; timeoutSeconds: number; }-const invalid = () => new OperationError('invalid_params','Invalid or unsupported local sync options.');+const invalid = () => opError('invalid_params','Invalid or unsupported local sync options.',+ 'Run gbrain sync from the CLI (gbrain sync --help lists its flags); it builds the options this owner lane accepts.');export function validateSyncWireParams(value: Record<string,unknown>): SyncWireParams {if (Object.keys(value).some(k=>!['options','cwd','timeoutSeconds'].includes(k)) || typeof value.cwd!=='string' ||!isAbsolute(value.cwd) || value.cwd.length>32768 || value.cwd.includes('\0') || typeof value.timeoutSeconds!=='number' ||diff --git a/src/core/persistence/unbound-source.ts b/src/core/persistence/unbound-source.tsindex 69cdbfd061..eaf3314ab9 100644--- a/src/core/persistence/unbound-source.ts+++ b/src/core/persistence/unbound-source.ts@@ -1,5 +1,5 @@import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import type { SqlEngine, WriteRequest } from './model.ts';/**@@ -21,7 +21,8 @@ export const UNBOUND_COLLISION_MESSAGE = 'A database-only page written while itsexport function parseUnboundWriteValue(value: string): UnboundWritePolicy {if ((UNBOUND_WRITE_VALUES as readonly string[]).includes(value)) return value as UnboundWritePolicy;- throw new OperationError('invalid_params', `${UNBOUND_WRITE_KEY} must be one of: ${UNBOUND_WRITE_VALUES.join(', ')} (got '${value}').`);+ throw opError('invalid_params', `${UNBOUND_WRITE_KEY} must be one of: ${UNBOUND_WRITE_VALUES.join(', ')} (got '${value}').`,+ `Set it with gbrain config set ${UNBOUND_WRITE_KEY} ${UNBOUND_WRITE_VALUES[0]} (the default) or ${UNBOUND_WRITE_VALUES[1]}.`);}/** A missing or unreadable value keeps the refusal. */diff --git a/src/core/repair/captured-facts.ts b/src/core/repair/captured-facts.tsindex ac23e07426..417d0a5a10 100644--- a/src/core/repair/captured-facts.ts+++ b/src/core/repair/captured-facts.ts@@ -36,7 +36,8 @@import { existsSync, readdirSync, readFileSync, type Dirent } from 'node:fs';import { basename, dirname, join } from 'node:path';import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { parseFactsFence, type ParsedFact } from '../facts-fence.ts';import { strikeFenceRow } from '../facts/forget.ts';import { serializePageToMarkdown } from '../markdown.ts';@@ -322,7 +323,11 @@ async function expireDatabaseRows(engine: BrainEngine, page: CapturedFactsPage,/** Preparer for `managed_maintenance_expire_captured_facts`: expires the named database-only rows of the source. */export async function prepareCapturedFactsExpiry(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {const ids = (row.intent as { fact_ids?: unknown } | null)?.fact_ids;- if (!Array.isArray(ids) || !ids.every(id => Number.isSafeInteger(id))) throw new OperationError('invalid_params', 'The captured facts expiry intent does not name its facts.');+ if (!Array.isArray(ids) || !ids.every(id => Number.isSafeInteger(id))) {+ throw opError('invalid_params', 'The captured facts expiry intent does not name its facts.',+ `Request ${row.request_id} in source ${row.source_id} does not name the facts to expire, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,+ { fix: readFix('Previews the captured-facts repair without changing anything.', { argv: ['gbrain', 'repair', 'captured-facts', '--source', row.source_id, '--json'] }) });+ }const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });await authorizeWrite(engine, row.authority, 'submit_job', row.slug);return { observedRevision: snapshot?.revision ?? null, noop: true,diff --git a/src/core/repair/extractor-facts.ts b/src/core/repair/extractor-facts.tsindex 4e8a4ebcf2..8fb5d979aa 100644--- a/src/core/repair/extractor-facts.ts+++ b/src/core/repair/extractor-facts.ts@@ -49,7 +49,8 @@ import type { BrainEngine } from '../engine.ts';import type { PreparedMutation } from '../persistence/coordinator.ts';import type { WriteRequest } from '../persistence/model.ts';import { VERSION } from '../../version.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { parseFactsFence } from '../facts-fence.ts';import { digest } from '../persistence/digest.ts';import { isTerminal } from '../persistence/model.ts';@@ -64,6 +65,9 @@ import { afterCursor, type RepairHandler, type RepairItem, type RepairItemOutcomexport const EXTRACTOR_FACTS_INTENT = 'managed_maintenance_restore_extractor_facts';export const EXTRACTOR_FACTS_SOURCE_PREFIX = 'cli:extract-conversation-facts';+const extractorPreviewFix = (sourceId: string) => readFix('Previews the extractor-facts repair without changing anything.',+ { argv: ['gbrain', 'repair', 'extractor-facts', '--source', sourceId, '--json'] });+/** The first release whose canonical projection leaves fenceless extractor facts alone. */export const EXTRACTOR_FACTS_FIX_VERSION = '0.60.11.0';@@ -394,10 +398,16 @@ export async function prepareExtractorFactsRestore(engine: BrainEngine, row: Wriconst intent = row.intent as { page?: ExtractorFactsPage; preview_hash?: unknown } | null;const page = intent?.page;if (!page || page.source_id !== row.source_id || page.slug !== row.slug || typeof intent?.preview_hash !== 'string' || !Array.isArray(page.facts)) {- throw new OperationError('invalid_params', 'The extractor facts restore intent does not name its page.');+ throw opError('invalid_params', 'The extractor facts restore intent does not name its page.',+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the page and preview it restores, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,+ { fix: extractorPreviewFix(row.source_id) });}const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });- if (!snapshot || snapshot.page.id !== Number(row.page_id)) throw new OperationError('page_identity_changed', 'The conversation page was deleted or replaced before its facts were restored.');+ if (!snapshot || snapshot.page.id !== Number(row.page_id)) {+ throw opError('page_identity_changed', 'The conversation page was deleted or replaced before its facts were restored.',+ `Conversation page ${row.slug} in source ${row.source_id} was deleted or replaced after the preview, so request ${row.request_id} restored nothing. Preview the repair again; it reflects the current pages.`,+ { fix: extractorPreviewFix(row.source_id) });+ }await authorizeWrite(engine, row.authority, 'submit_job', row.slug);return { observedRevision: snapshot.revision, noop: true,validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },diff --git a/src/core/repair/stale-atoms.ts b/src/core/repair/stale-atoms.tsindex d200d77402..13f2405de7 100644--- a/src/core/repair/stale-atoms.ts+++ b/src/core/repair/stale-atoms.ts@@ -26,7 +26,8 @@ import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import type { PreparedMutation } from '../persistence/coordinator.ts';import type { WriteRequest } from '../persistence/model.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { authorizeWrite } from '../persistence/authority.ts';import { managedPersistenceEnabled } from '../persistence/ownership.ts';import { maintenanceTransaction } from '../persistence/attribution.ts';@@ -195,14 +196,21 @@ async function stampRetirement(tx: BrainEngine, atom: StaleAtom): Promise<void>}/** Preparer for `managed_maintenance_retire_stale_atoms`: rechecks the atom's class under its and its origin's page locks, then retires it. */+const staleAtomsPreviewFix = (sourceId: string) => readFix('Previews the stale-atoms repair without changing anything.',+ { argv: ['gbrain', 'repair', 'stale-atoms', '--source', sourceId, '--json'] });+export async function prepareStaleAtomRetirement(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const atom = row.intent!.atom as StaleAtom;if (!atom || atom.slug !== row.slug || atom.source_id !== row.source_id || atom.id !== Number(row.page_id)) {- throw new OperationError('invalid_params', 'The stale atom retirement intent does not name its atom.');+ throw opError('invalid_params', 'The stale atom retirement intent does not name its atom.',+ `Request ${row.request_id} for ${row.slug} in source ${row.source_id} does not name the atom it retires, so nothing changed. Preview the repair again and apply the new preview after the user approves.`,+ { fix: staleAtomsPreviewFix(row.source_id) });}const unchanged = async (db: BrainEngine) => {if (!sameAtom((await staleAtoms(db, [row.source_id], atom.id))[0], atom)) {- throw new OperationError('revision_conflict', 'The stale atom or its source page changed since the preview.');+ throw opError('revision_conflict', 'The stale atom or its source page changed since the preview.',+ `Atom ${row.slug} in source ${row.source_id} or its source page changed after the preview, so request ${row.request_id} retired nothing. Preview the repair again and apply the new preview after the user approves.`,+ { fix: staleAtomsPreviewFix(row.source_id) });}};await unchanged(engine);