Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(errors): B10 backfill coordinator, effect-git, facts-prepare, effect-retry, page-prepare, effect-recovery
garrytanab08ec6a5483
diff --git a/src/core/persistence/coordinator.ts b/src/core/persistence/coordinator.tsindex 8e166c4c51..a61e007270 100644--- a/src/core/persistence/coordinator.ts+++ b/src/core/persistence/coordinator.ts@@ -1,7 +1,9 @@import { existsSync, mkdirSync, readFileSync, statSync, unlinkSync } from 'node:fs';import { dirname } from 'node:path';import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import type { Action } from '../agent-output.ts';import { pageIdentityError } from './page-identity.ts';import { atomicWriteFileSync, mkdirPrivate } from '../atomic-write.ts';import { flushDirectory } from '../fs-durable.ts';@@ -56,11 +58,34 @@ export interface PublicationHooks {| 'before_restore' | 'restoration_staging_flushed' | 'restoration_file_replaced' | 'restoration_directory_flushed' | 'after_restore', request: WriteRequest, index: number): void;}function fileHash(path: string): string | null { return existsSync(path) ? sha256(readFileSync(path)) : null; }+const ownerStatusFix = (sourceId?: string): Action => readFix(sourceId+ ? `Shows source ${sourceId}'s canonical owner with its pending, failed and recovering write requests, read-only.`+ : 'Shows every source\'s canonical owner with its pending, failed and recovering write requests, read-only.',+ { argv: ['gbrain', 'sources', 'writer', 'status', ...(sourceId ? ['--source', sourceId] : []), '--json'] });+const requestFix = (row: WriteRequest): Action => row.principal_kind === 'local_cli'+ ? readFix(`Reads request ${row.request_id}'s durable receipt: its state and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })+ : ownerStatusFix(row.source_id);+const confinementCheck = 'Inspect the canonical owner before resubmitting anything; how to repair the checkout is the user\'s decision.';+function localEditRefusal(message: string, row: WriteRequest, skill: boolean, when: string): OperationError {+ const review = skill ? `review the edited files of ${row.slug}` : `preview the difference with gbrain sources reconcile ${row.source_id} ${row.slug} --preview on the brain host and apply the resolved preview`;+ return opError('source_changed', message,+ `A canonical file of ${row.slug} in source ${row.source_id} was edited outside gbrain ${when}, so it was not overwritten. Inspect request ${row.request_id} first; once it is final, ${review}, then submit the write again with a new request_id.`,+ { fix: requestFix(row) });+}+function unexpectedRecoveryBytes(message: string, row: WriteRequest, when: string): OperationError {+ return opError('unexpected_file_bytes', message,+ `A canonical file of request ${row.request_id} in source ${row.source_id} ${when} matches neither its prior nor its published bytes, so recovery left it untouched and the worktree stays blocked. Inspect the owner and ask the user which version to keep; do not delete the file to unblock it.`,+ { fix: ownerStatusFix(row.source_id) });+}function publishFile(file: PageMutationFile, stagingPath?: string, afterStagingFlush?: () => void, mode?: number | null): void {- if (!isWriteTargetContained(file.path, file.root)) throw new OperationError('storage_error', 'Canonical file target escapes its source root.');+ if (!isWriteTargetContained(file.path, file.root)) throw opError('storage_error', 'Canonical file target escapes its source root.',+ `The file path resolves outside its source's canonical root (a symlinked directory or a moved checkout), so the file was not written. ${confinementCheck}`,+ { fix: ownerStatusFix() });if (file.publishMode === undefined) mkdirSync(dirname(file.path), { recursive: true });else mkdirPrivate(dirname(file.path), file.root);- if (!isWriteTargetContained(file.path, file.root)) throw new OperationError('storage_error', 'Canonical parent path changed during publication.');+ if (!isWriteTargetContained(file.path, file.root)) throw opError('storage_error', 'Canonical parent path changed during publication.',+ `A directory on the file's path was replaced (for example by a symlink) while gbrain created it, so the file was not written. ${confinementCheck}`,+ { fix: ownerStatusFix() });const openMode = mode ?? file.publishMode;if (file.content === null) {try { unlinkSync(file.path); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }@@ -112,7 +137,9 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prtry {assertMutationProtocol(row);if ((row.target_kind ?? 'page') !== (prepared.target ?? 'page') || (skill ? !!prepared.file || !files.length : prepared.files !== undefined)) {- throw new OperationError('unsupported_mutation_protocol', 'Prepared mutation does not match its accepted target.');+ throw opError('unsupported_mutation_protocol', 'Prepared mutation does not match its accepted target.',+ `Request ${row.request_id} in source ${row.source_id} was prepared for a different target than it was accepted for, so nothing was published. This is an internal mismatch, not a caller error: inspect the request and report it to the user; do not resubmit it unchanged.`,+ { fix: requestFix(row) });}if (skill) await assertSharedSkillPersistence(engine, row.source_id);if (row.worktree_id) {@@ -144,7 +171,9 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr}if (!skill) await assertKnowledgePublicationAllowed(engine, row, prepared.file);if (skill && !prepared.noop) {- if (!binding || !lock) throw new OperationError('storage_error', 'Skill publication requires a canonical owner.');+ if (!binding || !lock) throw opError('storage_error', 'Skill publication requires a canonical owner.',+ `Shared-skill request ${row.request_id} reached publication without this host holding source ${row.source_id}'s canonical worktree, so no skill file was written. Inspect the owner; the skill publishes only on the host that owns the source.`,+ { fix: ownerStatusFix(row.source_id) });const bundle = prepareBundleRecovery(files, binding, row);await prepareRecovery(engine, row, bundle.record, bundle.bytes);recovery = bundle.record;@@ -159,7 +188,9 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, pr}});} else if (prepared.file && !prepared.noop) {- if (!binding || !lock || !isWriteTargetContained(prepared.file.path, prepared.file.root)) throw new OperationError('storage_error', 'Filesystem publication requires a confined canonical owner.');+ if (!binding || !lock || !isWriteTargetContained(prepared.file.path, prepared.file.root)) throw opError('storage_error', 'Filesystem publication requires a confined canonical owner.',+ `This host does not hold source ${row.source_id}'s canonical worktree, or the file of ${row.slug} resolves outside it, so request ${row.request_id} wrote no file. Inspect the owner; the write publishes only on the host that owns the source.`,+ { fix: ownerStatusFix(row.source_id) });const before = existsSync(prepared.file.path) ? readFileSync(prepared.file.path) : null;const record: RecoveryRecord = {version: 1, path: prepared.file.path, root: prepared.file.root,@@ -180,7 +211,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prif ((current?.revision ?? null) !== prepared.observedRevision) {throw new OperationError('revision_conflict', 'The page changed during preparation.', 'Read its current revision and submit the updated intent with a new request_id.');}- throw new OperationError('source_changed', 'The canonical file changed after preparation.');+ throw localEditRefusal('The canonical file changed after preparation.', row, skill, 'after the write was prepared, at an unchanged page revision');}const nextBytes = prepared.file.content === null ? 0 : typeof prepared.file.content === 'string'? Buffer.byteLength(prepared.file.content) : prepared.file.content.byteLength;@@ -195,11 +226,15 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prawait tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");const liveBinding = await guardOwnership(tx, row, hostId);if (prepared.sourceExclusive) await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [row.source_id]);- if (binding && String(liveBinding?.owner_epoch) !== String(binding.owner_epoch)) throw new OperationError('owner_unavailable', 'Owner epoch changed before publication.');+ if (binding && String(liveBinding?.owner_epoch) !== String(binding.owner_epoch)) throw opError('owner_unavailable', 'Owner epoch changed before publication.',+ `Source ${row.source_id}'s canonical owner changed (a transfer or re-claim) after request ${row.request_id} was prepared, so this host published nothing for it. Inspect the owner and the request before resubmitting; do not claim or transfer the source to push this write through.`,+ { fix: ownerStatusFix(row.source_id) });await authorizeStoredRequest(tx, row, true);await lockCounters(tx, ['brain', principalKey(requestPrincipal(row)), ...(row.worktree_id ? [`worktree:${row.worktree_id}`] : [])]);const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);- if (!current || current.execution_token !== row.execution_token || current.state !== 'running') throw new OperationError('write_claim_lost', 'Execution claim changed before publication.');+ if (!current || current.execution_token !== row.execution_token || current.state !== 'running') throw opError('write_claim_lost', 'Execution claim changed before publication.',+ `Another worker took over request ${row.request_id} (its execution claim expired or was reassigned) before this attempt published, so this attempt wrote nothing and the current holder decides the outcome. Inspect the request rather than resubmitting it.`,+ { fix: requestFix(row) });if (skill) await assertSharedSkillPersistence(tx, row.source_id);else {await assertKnowledgePublicationAllowed(tx, row, prepared.file);@@ -219,7 +254,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prif (recovery) {const records = recoveryFiles(recovery);for (const record of records) if ((skill ? bundleFileHash(record) : fileHash(record.path)) !== record.beforeHash) {- throw new OperationError('source_changed', 'The canonical file changed during preparation.');+ throw localEditRefusal('The canonical file changed during preparation.', row, skill, 'while the write was being prepared');}await tx.executeRaw('UPDATE persistence_requests SET publication_started=true WHERE id=$1::uuid', [row.id]);await hooks.boundary?.('before_publication', row);@@ -229,7 +264,7 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prfor (let index = 0; index < files.length; index++) {hooks.fileBoundary?.('before_file', row, index);const record = records[index];- if ((skill ? bundleFileHash(record) : fileHash(record.path)) !== record.beforeHash) throw new OperationError('source_changed', 'The canonical file changed before publication.');+ if ((skill ? bundleFileHash(record) : fileHash(record.path)) !== record.beforeHash) throw localEditRefusal('The canonical file changed before publication.', row, skill, 'just before publication');if (skill) publishStagedBundleFile(record, phase => hooks.fileBoundary?.(phase, row, index));else publishFile(files[index], record.staging?.publication?.path, () => {hooks.stagingFlushed?.(row);@@ -288,11 +323,15 @@ export async function publishMutation(engine: BrainEngine, row: WriteRequest, prexport async function recoverPublication(engine: BrainEngine, id: string, hostId = localHostId(), alreadyLocked = false,terminalError?: { code: string; message: string }, capacityAlreadyHeld = false, hooks: PublicationHooks = {}): Promise<WriteRequest> {let row = await getWriteRequestById(engine, id);- if (!row) throw new OperationError('not_found', 'Write request not found.');+ if (!row) throw opError('not_found', 'Write request not found.',+ 'The write request is no longer in the journal (it was compacted or never existed), so there is nothing to recover. Inspect the canonical owners for requests that still need recovery.',+ { fix: ownerStatusFix() });if (!row.recovery) return row;assertMutationProtocol(row);const binding = await getWorktreeBinding(engine, row.source_id, hostId);- if (!binding || binding.owner_host_id !== hostId) throw new OperationError('owner_unavailable', 'Recovery requires the canonical owner.');+ if (!binding || binding.owner_host_id !== hostId) throw opError('owner_unavailable', 'Recovery requires the canonical owner.',+ `Request ${row.request_id} in source ${row.source_id} holds a publication recovery record that only the host owning the source's canonical worktree can finish, and this host does not own it. Inspect the owner; its resident writer finishes the recovery.`,+ { fix: ownerStatusFix(row.source_id) });const lock = alreadyLocked ? null : await acquireWorktree(binding, 0, undefined, engine);if (!alreadyLocked && !lock) return row;const releaseCapacity = capacityAlreadyHeld ? null : tryAcquirePublicationCapacity(engine);@@ -313,14 +352,18 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdconst records = recoveryFiles(current.recovery);if (current.recovery.version === 2) {const owner = await guardOwnership(tx, current, hostId);- if (!owner) throw new OperationError('owner_unavailable', 'Skill recovery requires its canonical owner.');+ if (!owner) throw opError('owner_unavailable', 'Skill recovery requires its canonical owner.',+ `This host no longer holds source ${current.source_id}'s current owner epoch, so shared-skill request ${current.request_id} stays recovering until its owner finishes it. Inspect the owner; its resident writer finishes the recovery.`,+ { fix: ownerStatusFix(current.source_id) });assertBundleRecoveryBinding(current.recovery, owner, current.execution_token);}- for (const record of records) if (!isWriteTargetContained(record.path, record.root) || !binding.local_path || !isWriteTargetContained(record.path, binding.local_path)) throw new OperationError('recovery_required', 'Recovery file binding is no longer confined to this owner.');+ for (const record of records) if (!isWriteTargetContained(record.path, record.root) || !binding.local_path || !isWriteTargetContained(record.path, binding.local_path)) throw opError('recovery_required', 'Recovery file binding is no longer confined to this owner.',+ `A recovery file of request ${current.request_id} now resolves outside source ${current.source_id}'s canonical worktree (a moved checkout or a symlink), so recovery stopped without touching it and the request stays recovering. Inspect the owner and tell the user; the checkout must be repaired before recovery can finish.`,+ { fix: ownerStatusFix(current.source_id) });try {if (!isTerminal(current)) for (const record of records) {const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);- if (actual !== record.beforeHash && actual !== record.afterHash) throw new OperationError('unexpected_file_bytes', 'Canonical recovery bytes changed outside publication.');+ if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed outside publication.', current, 'was edited outside gbrain and');}await withFilesystemPublication([...new Set(records.map(record => record.root))], async () => {for (const record of records) cleanupRecoveryStaging(record);@@ -341,7 +384,7 @@ export async function recoverPublication(engine: BrainEngine, id: string, hostIdconst record = records[index];hooks.fileBoundary?.('before_restore', current, index);const actual = current.recovery.version === 2 ? bundleFileHash(record) : fileHash(record.path);- if (actual !== record.beforeHash && actual !== record.afterHash) throw new OperationError('unexpected_file_bytes', 'Canonical recovery bytes changed during restoration.');+ if (actual !== record.beforeHash && actual !== record.afterHash) throw unexpectedRecoveryBytes('Canonical recovery bytes changed during restoration.', current, 'changed while recovery was restoring it and');if (actual === record.afterHash && actual !== record.beforeHash) {await withFilesystemPublication([record.root], async () => {const file = { path: record.path, root: record.root, content: record.before === null ? null : Buffer.from(record.before, 'base64') };diff --git a/src/core/persistence/effect-git.ts b/src/core/persistence/effect-git.tsindex 83debad330..373d559947 100644--- a/src/core/persistence/effect-git.ts+++ b/src/core/persistence/effect-git.ts@@ -1,7 +1,8 @@import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, statSync } from 'node:fs';import { basename, dirname, join, relative, resolve as resolvePath, sep } from 'node:path';import { execFileBounded, isDurabilityHardenedAsync } from '../brain-repo-durability.ts';-import { OperationError } from '../ops/contract.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { persistenceHome } from './identity.ts';import { nativeFileTarget } from './native-file-target.ts';@@ -16,6 +17,15 @@ const LOCK_REFUSAL = /Unable to create '([\s\S]*)': File exists/;*/const canonical = (path: string) => { try { return join(realpathSync(dirname(path)), basename(path)); } catch { return path; } };+const effectStatusFix = readFix('Shows each source\'s canonical owner with its retrying and parked Git effects, read-only.',+ { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] });+const gitFailure = (message: string, cause: string) => opError('git_unavailable', message,+ `${cause} The page write itself is committed; the effect worker tries this Git effect again and parks it after repeated failures. If it keeps failing, check the checkout with git status on the brain host.`,+ { fix: effectStatusFix });+const rootGone = (relativePath: string) => opError('git_target_unsafe', 'The canonical Git root disappeared.',+ `The canonical checkout was moved or deleted while ${relativePath} was being committed, so nothing was committed for it; the page write itself is committed. Inspect the owner and tell the user: Git effects resume only once the checkout is back, and how to restore it is their decision.`,+ { fix: effectStatusFix });+const GIT_ENV = { GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'Never', GIT_GLOB_PATHSPECS: '0', GIT_NOGLOB_PATHSPECS: '0',GIT_ICASE_PATHSPECS: '0', LC_ALL: 'C' };@@ -50,7 +60,8 @@ async function indexLockError(root: string, hooks: string, stderr: string, signaasync function git(root: string, hooks: string, args: string[], signal?: AbortSignal): Promise<{ stdout: string; code: number }> {const { error, stdout, stderr } = await run(root, hooks, args, signal);- if (error && (error.killed || typeof error.code !== 'number')) throw new OperationError('git_unavailable', 'Git execution did not finish within its bounded attempt.');+ if (error && (error.killed || typeof error.code !== 'number')) throw gitFailure('Git execution did not finish within its bounded attempt.',+ 'A git command in the canonical checkout did not finish within 20 seconds or could not start.');const code = error?.code as number ?? 0;if (code !== 0) { const locked = await indexLockError(root, hooks, stderr, signal); if (locked) throw locked; }return { stdout, code };@@ -68,17 +79,17 @@ async function stageTarget(root: string, hooks: string, relativePath: string, siconst path = nativeFileTarget(root, resolvePath(root, relativePath), 'git_target_unsafe');relativePath = relative(root, path).split(sep).join('/');const tracked = await git(root, hooks, ['ls-files', '-z', '--error-unmatch', '--', relativePath], signal);- if (tracked.code !== 0 && tracked.code !== 1) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');+ if (tracked.code !== 0 && tracked.code !== 1) throw gitFailure('Cannot inspect the canonical Git target.', `git ls-files failed for ${relativePath}.`);const changed = await git(root, hooks, ['status', '--porcelain', '--untracked-files=all', '--', relativePath], signal);- if (changed.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');+ if (changed.code !== 0) throw gitFailure('Cannot inspect the canonical Git target.', `git status failed for ${relativePath}.`);if (changed.stdout.trim()) {if (tracked.code === 0 || existsSync(path)) {const add = await git(root, hooks, ['add', '-A', '--', relativePath], signal);- if (add.code !== 0) throw new OperationError('git_unavailable', 'Cannot stage the canonical Git target.');+ if (add.code !== 0) throw gitFailure('Cannot stage the canonical Git target.', `git add failed for ${relativePath}.`);}const diff = await git(root, hooks, ['diff', '--cached', '--quiet', '--', relativePath], signal);if (diff.code === 1) return { path: relativePath, state: 'changed' };- if (diff.code !== 0) throw new OperationError('git_unavailable', 'Cannot compare the canonical Git target.');+ if (diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target.', `git diff --cached failed for ${relativePath}.`);return { path: relativePath, state: 'unchanged' };}if (tracked.code === 0) return { path: relativePath, state: 'unchanged' };@@ -86,18 +97,18 @@ async function stageTarget(root: string, hooks: string, relativePath: string, si'Reconcile the index and worktree spelling before retrying publication.');let parent = dirname(path);while (!existsSync(parent)) {- if (parent === resolvePath(root)) throw new OperationError('git_target_unsafe', 'The canonical Git root disappeared.');+ if (parent === resolvePath(root)) throw rootGone(relativePath);parent = dirname(parent);}const scope = relative(root, parent).split(sep).join('/') || '.';const deleted = await git(root, hooks, ['diff', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);const staged = await git(root, hooks, ['diff', '--cached', '--name-only', '--diff-filter=D', '--no-renames', '-z', '--', scope], signal);- if (deleted.code !== 0 || staged.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect canonical Git deletions.');+ if (deleted.code !== 0 || staged.code !== 0) throw gitFailure('Cannot inspect canonical Git deletions.', `git diff could not list the deletions under ${scope}.`);for (const entry of new Set(`${deleted.stdout}${staged.stdout}`.split('\0').filter(Boolean))) {if (existsSync(join(root, entry))) continue;let missingParent = dirname(nativeFileTarget(root, join(root, entry), 'git_target_unsafe'));while (!existsSync(missingParent)) {- if (missingParent === resolvePath(root)) throw new OperationError('git_target_unsafe', 'The canonical Git root disappeared.');+ if (missingParent === resolvePath(root)) throw rootGone(relativePath);missingParent = dirname(missingParent);}if (missingParent === parent) throw new OperationError('git_target_unsafe', 'The absent target cannot be distinguished from an indexed deletion.',@@ -133,7 +144,7 @@ export async function commitGitTargets(root: string, relativePaths: string[], siconst paths = [...new Set(normalized.values())];const list = async (args: string[]) => {const out = paths.length ? await git(root, hooks, [...args, '--', ...paths], signal) : { stdout: '', code: 0 };- if (out.code !== 0) throw new OperationError('git_unavailable', 'Cannot inspect the canonical Git target.');+ if (out.code !== 0) throw gitFailure('Cannot inspect the canonical Git target.', `git ${args[0]} failed for this group of ${paths.length} file(s).`);return out.stdout;};const tracked = new Set((await list(['ls-files', '-z'])).split('\0').filter(Boolean));@@ -153,9 +164,9 @@ export async function commitGitTargets(root: string, relativePaths: string[], si}if (staged.length) {const add = await git(root, hooks, ['add', '-A', '--', ...new Set(staged)], signal);- if (add.code !== 0) throw new OperationError('git_unavailable', 'Cannot stage the canonical Git target.');+ if (add.code !== 0) throw gitFailure('Cannot stage the canonical Git target.', `git add failed for this group of ${new Set(staged).size} file(s).`);const diff = await git(root, hooks, ['diff', '--cached', '--name-only', '-z', '--no-renames', '--', ...new Set(staged)], signal);- if (diff.code !== 0) throw new OperationError('git_unavailable', 'Cannot compare the canonical Git target.');+ if (diff.code !== 0) throw gitFailure('Cannot compare the canonical Git target.', `git diff --cached failed for this group of ${new Set(staged).size} file(s).`);const indexed = new Set(diff.stdout.split('\0').filter(Boolean));for (const [requested, path] of normalized) {if (!staged.includes(path) || results.has(requested)) continue;@@ -169,7 +180,8 @@ export async function commitGitTargets(root: string, relativePaths: string[], siconst commitPaths = [...new Set(changed.map(c => c.path))];const message = commitPaths.length === 1 ? 'gbrain: persist canonical memory update' : `gbrain: persist ${commitPaths.length} canonical memory updates`;const result = await git(root, hooks, ['commit', '--only', '-m', message, '--', ...commitPaths], signal);- const outcome = result.code === 0 ? { git: 'committed' } : new OperationError('git_unavailable', 'Cannot commit the canonical Git target.');+ const outcome = result.code === 0 ? { git: 'committed' } : gitFailure('Cannot commit the canonical Git target.',+ `git commit failed for ${commitPaths.length} file(s); a missing Git identity (user.name, user.email) in that checkout is one cause to check.`);for (const c of changed) results.set(c.requested, outcome);});return results;@@ -184,7 +196,9 @@ export async function pushGitRoot(root: string, signal?: AbortSignal): Promise<{const merge = await git(root, hooks, ['config', '--get', `branch.${branch.stdout.trim()}.merge`], signal);if (remote.code !== 0 || merge.code !== 0 || !remote.stdout.trim() || remote.stdout.trim() === '.') return { push: 'skipped', reason: 'no_tracking_remote' } as const;const push = await git(root, hooks, ['push', '--', remote.stdout.trim(), `HEAD:${merge.stdout.trim()}`], signal);- if (push.code !== 0) throw new OperationError('git_push_unavailable', 'The canonical commit is durable locally; its push will retry.');+ if (push.code !== 0) throw opError('git_push_unavailable', 'The canonical commit is durable locally; its push will retry.',+ `git push to ${remote.stdout.trim()} failed (network, credentials or a rejected non-fast-forward). Nothing is lost locally and the worker pushes again on a later pass; gbrain never pulls or rebases the checkout. If it keeps failing, check the remote and its credentials with git push on the brain host.`,+ { fix: effectStatusFix });return { push: 'committed' } as const;});}diff --git a/src/core/persistence/effect-recovery.ts b/src/core/persistence/effect-recovery.tsindex 82b68ac0d1..fd6740de84 100644--- a/src/core/persistence/effect-recovery.ts+++ b/src/core/persistence/effect-recovery.ts@@ -1,7 +1,9 @@import { chmodSync, existsSync } from 'node:fs';import { join, resolve } from 'node:path';import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import type { Action } from '../agent-output.ts';import { isWriteTargetContained } from '../path-confine.ts';import { materializePageSnapshot } from '../page-state/materialize.ts';import type { JournalLimits } from './model.ts';@@ -17,33 +19,49 @@ import { assertRecoveryStagingAbsent, cleanupRecoveryStaging, upgradeRecoveryStaimport { declarePersistenceProtocol } from './protocol.ts';import { advanceEffectCursor } from './effect-journal.ts';+const effectStatusFix = (effect: Pick<PersistenceEffect, 'source_id'>): Action => readFix(+ `Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', effect.source_id, '--json'] });+export async function guardEffectSource(tx: BrainEngine, effect: PersistenceEffect, hostId: string): Promise<WorktreeBinding | null> {await declarePersistenceProtocol(tx);if (effect.worktree_id) {const [owner] = await tx.executeRaw<{ owner_host_id: string; state: string }>('SELECT owner_host_id,state FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [effect.worktree_id]);- if (!owner || owner.owner_host_id !== hostId || owner.state !== 'active') throw new OperationError('owner_unavailable', 'The effect requires its active canonical owner.');+ if (!owner || owner.owner_host_id !== hostId || owner.state !== 'active') throw opError('owner_unavailable', 'The effect requires its active canonical owner.',+ `This host is not the active canonical owner of source ${effect.source_id}'s worktree, so its ${effect.kind} effect waits for the owner; the committed write is unaffected. Inspect the owner; the effect runs there.`,+ { fix: effectStatusFix(effect) });}const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR SHARE', [effect.source_id]);- if (!source || source.archived || source.incarnation !== effect.source_incarnation) throw new OperationError('source_changed', 'The effect source was archived or replaced.');+ if (!source || source.archived || source.incarnation !== effect.source_incarnation) throw opError('source_changed', 'The effect source was archived or replaced.',+ `Source ${effect.source_id} was archived, removed or re-created after this ${effect.kind} effect was recorded, so it no longer applies and nothing was done for it. Inspect the source before acting on its old effects.`,+ { fix: effectStatusFix(effect) });const binding = await getWorktreeBinding(tx, effect.source_id, hostId);if (effect.worktree_id && (!binding || binding.worktree_id !== effect.worktree_id || binding.source_incarnation !== effect.source_incarnation)) {- throw new OperationError('source_changed', 'The effect canonical binding changed.');+ throw opError('source_changed', 'The effect canonical binding changed.',+ `Source ${effect.source_id}'s canonical worktree binding changed (a transfer, re-claim or new incarnation) after this ${effect.kind} effect was recorded, so nothing was done for it. Inspect the owner; do not claim or transfer the source to force the effect through.`,+ { fix: effectStatusFix(effect) });}return binding;}async function lockedEffect(tx: BrainEngine, effect: PersistenceEffect): Promise<PersistenceEffect> {const [current] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [effect.id]);- if (!current || current.execution_token !== effect.execution_token || current.state !== 'running') throw new OperationError('write_claim_lost', 'The effect claim changed.');+ if (!current || current.execution_token !== effect.execution_token || current.state !== 'running') throw opError('write_claim_lost', 'The effect claim changed.',+ `Another worker took over this ${effect.kind} effect of source ${effect.source_id} (its claim expired or was reassigned), so this attempt stopped without changing it; the current holder finishes it. Inspect the owner's effects rather than retrying by hand.`,+ { fix: effectStatusFix(effect) });return current;}export async function reserveEffectRecovery(engine: BrainEngine, effect: PersistenceEffect, record: EffectRecovery,bytes: number, hostId: string, overrides?: Partial<JournalLimits>): Promise<void> {const limits = await readJournalLimits(engine, overrides);- if (!effect.worktree_id) throw new OperationError('owner_unavailable', 'Physical mirror recovery requires a worktree.');+ if (!effect.worktree_id) throw opError('owner_unavailable', 'Physical mirror recovery requires a worktree.',+ `This ${effect.kind} effect of source ${effect.source_id} has no canonical worktree, so there is no file to mirror and nothing was reserved; the withdrawal remains committed. Inspect the source's owner binding.`,+ { fix: effectStatusFix(effect) });if (!Number.isSafeInteger(bytes) || bytes < 1 || bytes > limits.brainRecoveryBytes || bytes > limits.worktreeRecoveryBytes) {- throw new OperationError('request_too_large', 'The physical mirror exceeds recovery capacity; the withdrawal remains committed.');+ throw opError('request_too_large', 'The physical mirror exceeds recovery capacity; the withdrawal remains committed.',+ `Mirroring this withdrawal into its file in source ${effect.source_id} needs ${bytes} bytes of recovery space, more than the brain or worktree recovery limit (${Math.min(limits.brainRecoveryBytes, limits.worktreeRecoveryBytes)} bytes), so the file was not touched. Inspect the owner's effects and tell the user; the canonical file still holds the withdrawn text until it is mirrored.`,+ { fix: effectStatusFix(effect) });}await engine.transaction(async tx => {await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");@@ -51,11 +69,15 @@ export async function reserveEffectRecovery(engine: BrainEngine, effect: Persistconst counters = await lockCounters(tx, ['brain', `worktree:${effect.worktree_id}`]);const current = await lockedEffect(tx, effect);if (current.recovery) {- if (digest(current.recovery) !== digest(record)) throw new OperationError('recovery_required', 'The prior mirror publication must be reconciled first.');+ if (digest(current.recovery) !== digest(record)) throw opError('recovery_required', 'The prior mirror publication must be reconciled first.',+ `This effect of source ${effect.source_id} still holds an earlier mirror publication's recovery record, so a new one was not reserved; the worker recovers the earlier one first. Inspect the owner's effects rather than resubmitting anything.`,+ { fix: effectStatusFix(effect) });return;}for (const counter of counters) if (Number(counter.recovery_bytes) + bytes > (counter.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) {- throw new OperationError('queue_capacity', 'Other publications hold the mirror recovery capacity.');+ throw opError('queue_capacity', 'Other publications hold the mirror recovery capacity.',+ `In-flight publications hold the recovery space this mirror of source ${effect.source_id} needs (${bytes} bytes), so nothing was reserved; the worker tries again once they finish. Inspect the owner if it stays blocked.`,+ { fix: effectStatusFix(effect) });}await tx.executeRaw('UPDATE persistence_effects SET recovery=$2::text::jsonb,recovery_bytes=$3,updated_at=now() WHERE id=$1', [effect.id, JSON.stringify(record), bytes]);for (const counter of counters) await tx.executeRaw('UPDATE persistence_counters SET recovery_bytes=recovery_bytes+$2 WHERE key=$1', [counter.key, bytes]);@@ -74,7 +96,9 @@ async function clearRecovery(tx: BrainEngine, effect: PersistenceEffect): Promisexport async function recoverEffectPublication(engine: BrainEngine, effect: PersistenceEffect, hostId: string,hooks: { boundary?: (name: 'before_mirror_file' | 'after_mirror_file' | 'before_mirror_commit') => Promise<void> } = {}): Promise<void> {const releaseCapacity = tryAcquirePublicationCapacity(engine);- if (!releaseCapacity) throw new OperationError('writer_pool_capacity', 'Mirror recovery is waiting for publication capacity.');+ if (!releaseCapacity) throw opError('writer_pool_capacity', 'Mirror recovery is waiting for publication capacity.',+ `Every publication slot of the writer pool is busy, so mirror recovery for source ${effect.source_id} has not started; the worker tries again once a slot frees. Nothing needs resubmitting.`,+ { fix: effectStatusFix(effect) });try {if (effect.recovery && !effect.recovery.staging) await upgradeRecoveryStaging(engine, 'persistence_effects', effect.id, effect.worktree_id!, 'forward');await engine.transaction(async tx => {@@ -88,11 +112,15 @@ export async function recoverEffectPublication(engine: BrainEngine, effect: Pers|| String(binding.owner_epoch) !== record.ownerEpoch || !isWriteTargetContained(record.path, binding.local_path)|| !isWriteTargetContained(record.path, record.root) || !isWriteTargetContained(record.root, binding.local_path)|| resolve(record.root) !== resolve(join(binding.local_path, binding.relative_path))- || sha256(Buffer.from(record.after, 'base64')) !== record.afterHash) throw new OperationError('recovery_required', 'Mirror recovery no longer belongs to this canonical binding.');+ || sha256(Buffer.from(record.after, 'base64')) !== record.afterHash) throw opError('recovery_required', 'Mirror recovery no longer belongs to this canonical binding.',+ `The recorded mirror recovery for page ${record.slug} no longer matches source ${current.source_id}'s current canonical binding (owner epoch, root or file path changed), so recovery left the file untouched and the effect stays blocked. Inspect the owner and tell the user; repairing the binding is their decision.`,+ { fix: effectStatusFix(current) });await withFilesystemPublication([record.root], async () => cleanupRecoveryStaging(record));const actual = persistenceFileHash(record.path);if (actual !== record.beforeHash && actual !== record.afterHash) {- throw new OperationError('unexpected_file_bytes', 'Physical mirror recovery found unexpected bytes; the root remains blocked.');+ throw opError('unexpected_file_bytes', 'Physical mirror recovery found unexpected bytes; the root remains blocked.',+ `The file of page ${record.slug} in source ${current.source_id} holds bytes that match neither its pre-withdrawal nor its mirrored version, so recovery did not overwrite it and the root stays blocked. Inspect the owner and ask the user which version to keep; do not delete the file to unblock it.`,+ { fix: effectStatusFix(current) });}await tx.lockPageKeys([{ sourceId: current.source_id, slug: record.slug }]);const snapshot = await tx.readPageSnapshot(record.slug, { sourceId: current.source_id, includeDeleted: true });diff --git a/src/core/persistence/effect-retry.ts b/src/core/persistence/effect-retry.tsindex 029545322d..bd3d0484e9 100644--- a/src/core/persistence/effect-retry.ts+++ b/src/core/persistence/effect-retry.ts@@ -3,7 +3,9 @@ import { loadConfigWithEngine, type GBrainConfig } from '../config.ts';import { MAX_RATE_LIMIT_RETRIES } from '../embed-retry.ts';import { EmbeddingDisabledError, readContentChunksColumnDim } from '../embedding-dim-check.ts';import { resolveWriteColumnFromConfigRows } from '../search/embedding-column.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { OperationError, opError, type OperationContext } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import type { Action } from '../agent-output.ts';import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './authority.ts';import { existingLocalHostId } from './identity.ts';import { guardEffectSource } from './effect-recovery.ts';@@ -12,6 +14,17 @@ import { PARK_AFTER_FAILURES, type PersistenceEffect } from './effect-model.ts';import type { WriteRequest } from './model.ts';import { targetedWithdrawalEffect, upgradeWithdrawalEffect } from './effect-targets.ts';+const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its blocking, retrying and parked effects, read-only.`,+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });+const previewFix = (sourceId: string, requestId: string): Action => readFix(+ `Previews request ${requestId}'s parked and failed effects in source ${sourceId} and what retry-effects would do, without queuing anything.`,+ { argv: ['gbrain', 'sources', 'writer', 'retry-effects', '--source', sourceId, '--request-id', requestId, '--dry-run', '--json'] });+const receiptFix = (requestId: string): Action => readFix(`Reads request ${requestId}'s receipt: its source, state and effect outcomes, read-only.`,+ { argv: ['gbrain', 'write-request', '--', requestId] });+const unregisteredHost = (sourceId: string, requestId: string) => opError('permission_denied', 'Retry requires the registered local CLI host.',+ `This machine has no registered gbrain host identity, so it cannot authorize another attempt for request ${requestId} in source ${sourceId}; nothing was queued. Run retry-effects on the brain host that owns ${sourceId}; the owner status names it.`,+ { fix: ownerStatusFix(sourceId) });+async function mountedEmbeddingSignature(engine: BrainEngine): Promise<string> {const rows = await engine.executeRaw<{ key: string; value: string }>(`SELECT key,value FROM configWHERE key IN ('embedding_model','embedding_dimensions','search_embedding_column','embedding_columns') ORDER BY key FOR SHARE`);@@ -55,7 +68,7 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,AND kind IN ('git','withdrawal-mirror') AND (data ? 'parked' OR data ? 'retried') ORDER BY kind`, [request.id]);if (!tracked.length) return null;const hostId = existingLocalHostId();- if (!hostId) throw new OperationError('permission_denied', 'Retry requires the registered local CLI host.');+ if (!hostId) throw unregisteredHost(sourceId, requestId);return engine.transaction(async tx => {await authorizeStoredRequest(tx, request, true);const authority = await submissionAuthority({ engine: tx, remote: false, sourceId } as OperationContext,@@ -71,7 +84,9 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,effects.push({ ...summary, state: effect.state, terminal: effect.state === 'committed', action: 'unchanged' });continue;}- if (effect.execution_token !== null || effect.recovery) throw new OperationError('write_claim_lost', 'A parked effect still has a claim or recovery record; inspect it before retrying.');+ if (effect.execution_token !== null || effect.recovery) throw opError('write_claim_lost', 'A parked effect still has a claim or recovery record; inspect it before retrying.',+ `The ${effect.kind} effect of request ${requestId} in source ${sourceId} is still claimed by a worker or holds a recovery record, so nothing was queued. Inspect the owner's effects; once the worker releases it, preview it again with --dry-run.`,+ { fix: ownerStatusFix(sourceId) });if (dryRun) { effects.push({ ...summary, state: 'parked', terminal: true, action: 'would_retry' }); continue; }const { parked: _parked, retry_slugs: retrying = [], failing_target: _target, ...data } = effect.data;const scanning = targetedWithdrawalEffect(effect) || effect.data.source_scan === true;@@ -82,7 +97,9 @@ export async function retryParkedEffects(engine: BrainEngine, sourceId: string,[effect.id, JSON.stringify({ ...data, ...(slugs.length ? { retry_slugs: slugs } : {}), target_failures: PARK_AFTER_FAILURES - 1,...(!scanning && (effect.data.slug ?? effect.data.relative_path) ? { failing_target: effect.data.slug ?? effect.data.relative_path } : {}),retried: (effect.data.retried ?? 0) + 1 })]);- if (!updated) throw new OperationError('write_claim_lost', 'The parked effect changed during retry approval.');+ if (!updated) throw opError('write_claim_lost', 'The parked effect changed during retry approval.',+ `The ${effect.kind} effect of request ${requestId} changed (claimed, retried or settled by the worker) while this approval ran, so the transaction rolled back and nothing was queued. Preview its current state before deciding again.`,+ { fix: previewFix(sourceId, requestId) });effects.push({ ...summary, state: 'queued', terminal: false, action: 'retry_queued' });}const queued = effects.some(effect => effect.action === 'retry_queued');@@ -115,16 +132,20 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: stringpolicy: 'owner' | 'mounted_database' = 'owner'): Promise<Record<string, unknown>> {const requests = await engine.executeRaw<WriteRequest>(`SELECT r.* FROM persistence_requests r WHERE source_id=$1 AND request_id=$2::uuidAND EXISTS (SELECT 1 FROM persistence_effects e WHERE e.request_id=r.id AND e.kind='embedding') LIMIT 2`, [sourceId, requestId]);- if (requests.length !== 1) throw new OperationError('invalid_params', 'The source and request must identify exactly one embedding obligation.');+ if (requests.length !== 1) throw opError('invalid_params', 'The source and request must identify exactly one embedding obligation.',+ `Request ${requestId} in source ${sourceId} has no single embedding effect and no parked Git or withdrawal effect, so nothing was queued. Check that the request_id is the one from the write receipt and that ${sourceId} is the source it was written to.`,+ { fix: receiptFix(requestId) });const request = requests[0];const hostId = existingLocalHostId();- if (!hostId) throw new OperationError('permission_denied', 'Retry requires the registered local CLI host.');+ if (!hostId) throw unregisteredHost(sourceId, requestId);const config = await loadConfigWithEngine(engine, baseConfig);const configuredSignature = config?.embedding_model && config.embedding_dimensions? `${config.embedding_model}:${config.embedding_dimensions}` : null;return engine.transaction(async tx => {const [selected] = await tx.executeRaw<PersistenceEffect>("SELECT * FROM persistence_effects WHERE request_id=$1::uuid AND kind='embedding'", [request.id]);- if (!selected) throw new OperationError('invalid_params', 'The embedding obligation is unavailable.');+ if (!selected) throw opError('invalid_params', 'The embedding obligation is unavailable.',+ `The embedding effect of request ${requestId} in source ${sourceId} disappeared while retry-effects ran (it settled or was compacted), so nothing was queued. Preview the request again.`,+ { fix: previewFix(sourceId, requestId) });if (selected.data.source_scan && selected.data.version === undefined) {if (selected.worktree_id) await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [selected.worktree_id]);await tx.executeRaw('SELECT id FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);@@ -134,10 +155,14 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: stringconst authority = await submissionAuthority({ engine: tx, remote: false, sourceId } as OperationContext,request.operation, sourceId, request.source_incarnation, request.slug);await authorizeWrite(tx, authority, request.operation, request.slug, true);- if (request.state !== 'committed') throw new OperationError('write_pending', 'Only committed canonical requests have retryable embedding obligations.');+ if (request.state !== 'committed') throw opError('write_pending', 'Only committed canonical requests have retryable embedding obligations.',+ `Request ${requestId} in source ${sourceId} is ${request.state}, not committed, so its embedding effect cannot be retried yet and nothing was queued. Read its receipt and wait until it is final; a request that ends failed or in conflict has no embedding to retry.`,+ { fix: receiptFix(requestId) });const [stored] = await tx.executeRaw<PersistenceEffect>('SELECT * FROM persistence_effects WHERE id=$1 FOR UPDATE', [selected.id]);if (!stored || stored.source_id !== sourceId || stored.source_incarnation !== request.source_incarnation || stored.recovery) {- throw new OperationError('source_changed', 'The effect source or recovery state changed.');+ throw opError('source_changed', 'The effect source or recovery state changed.',+ `Source ${sourceId} was archived or replaced, or the embedding effect of request ${requestId} now holds a recovery record, so nothing was queued. Inspect the source's owner and its effects.`,+ { fix: ownerStatusFix(sourceId) });}const effect = await upgradeWithdrawalEffect(tx, stored, hostId, false);const snapshot = await selectedEffectPage(tx, effect);@@ -145,7 +170,10 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: stringconst scanComplete = scanning && !snapshot;if (!scanComplete && (!snapshot || !scanning &&(snapshot.page.deleted_at || snapshot.revision !== effect.revision || snapshot.page.id !== effect.data.page_id))) {- throw new OperationError('revision_conflict', 'The original embedding obligation is superseded; inspect the current page instead.');+ throw opError('revision_conflict', 'The original embedding obligation is superseded; inspect the current page instead.',+ `Page ${request.slug} changed or was deleted after request ${requestId}, so its old embedding obligation is moot and nothing was queued; the newer write carries its own. Read the page as it is now; if its embeddings are missing, preview gbrain repair embedding-effects --source ${sourceId}.`,+ { fix: readFix(`Shows page ${request.slug} in source ${sourceId} as it is now, with its revision.`,+ { argv: ['gbrain', 'get', '--source', sourceId, '--', request.slug] }) });}if (snapshot) {await authorizeWrite(tx, request.authority, request.operation, snapshot.page.slug, true);@@ -157,9 +185,13 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: stringif (effect.state !== 'failed') {if (effect.data.embedding_retry_base !== undefined || effect.state === 'committed') return { ...receipt, state: effect.state, action: 'unchanged',next_action: 'Inspect this same receipt; this command does not authorize another retry cycle.' };- throw new OperationError('effect_not_failed', 'Only a failed, non-running embedding effect can be explicitly retried.');+ throw opError('effect_not_failed', 'Only a failed, non-running embedding effect can be explicitly retried.',+ `The embedding effect of request ${requestId} is ${effect.state}, so the worker still owns it and nothing was queued. Preview it again once it settles; a committed effect needs nothing.`,+ { fix: previewFix(sourceId, requestId) });}- if (effect.execution_token !== null) throw new OperationError('write_claim_lost', 'A failed effect still has an execution claim; inspect it before retrying.');+ if (effect.execution_token !== null) throw opError('write_claim_lost', 'A failed effect still has an execution claim; inspect it before retrying.',+ `The failed embedding effect of request ${requestId} in source ${sourceId} is still claimed by a worker, so nothing was queued. Inspect the owner's effects; once the claim is released, preview it again with --dry-run.`,+ { fix: ownerStatusFix(sourceId) });const signature = policy === 'mounted_database' && !scanComplete ? await mountedEmbeddingSignature(tx) : configuredSignature;if (!signature && !scanComplete) return { ...receipt, state: 'failed', action: 'blocked', reason: 'embedding_unconfigured', next_action: 'Configure embeddings, then inspect this request again.' };const pending = scanComplete || snapshot?.page.deleted_at ? [] : (await readEmbeddingEffectProjection(tx, effect, snapshot!, hostId, signature!)).pending;@@ -183,7 +215,9 @@ export async function retryEmbeddingEffect(engine: BrainEngine, sourceId: stringoutcome=CASE WHEN $4='committed' THEN '{"embedding":"reconciled"}'::jsonb ELSE NULL ENDWHERE id=$1 AND state='failed' AND execution_token IS NULL AND recovery IS NULL AND attempts=$2 AND source_incarnation=$3::uuid RETURNING state`,[effect.id, effect.attempts, effect.source_incarnation, complete ? 'committed' : 'queued', JSON.stringify(effect.data)]);- if (!updated) throw new OperationError('write_claim_lost', 'The embedding obligation changed during retry approval.');+ if (!updated) throw opError('write_claim_lost', 'The embedding obligation changed during retry approval.',+ `The embedding effect of request ${requestId} changed (claimed or settled by the worker) while this approval ran, so the transaction rolled back and nothing was queued. Preview its current state before deciding again.`,+ { fix: previewFix(sourceId, requestId) });return { ...receipt, state: updated.state, action: complete ? 'reconciled' : 'retry_queued', pending_chunks: pending.length,next_action: complete ? 'The existing vectors satisfy this obligation; no provider work was scheduled.' : 'The resident owner may spend up to five attempts only when its selected file configuration and the database policy permit embedding, under existing provider and job budgets. Repeating this command does not renew that allowance.' };});diff --git a/src/core/persistence/facts-prepare.ts b/src/core/persistence/facts-prepare.tsindex 22e1c69876..cef73d31d3 100644--- a/src/core/persistence/facts-prepare.ts+++ b/src/core/persistence/facts-prepare.ts@@ -1,6 +1,9 @@import type { BrainEngine, NewFact } from '../engine.ts';import type { GBrainConfig } from '../config.ts';-import { OperationError } from '../ops/contract.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import type { Action } from '../agent-output.ts';+import type { RegistryCode } from '../error-registry.ts';import { parseFactsFence, upsertFactRow, formatFenceDate, renderFactsTable, replaceOrInsertFactsFence } from '../facts-fence.ts';import { serializePageToMarkdown } from '../markdown.ts';import { assertFactNotWithdrawn, decideSingleFact, type FactCandidate } from '../facts/single-prepare.ts';@@ -15,6 +18,20 @@ import type { WriteRequest } from './model.ts';import type { ManagedFactIntent, FrozenExtractedFact } from './facts-maintenance.ts';import { assertManagedFactsEmbedding } from './facts-maintenance.ts';+const requestFix = (row: WriteRequest): Action => row.principal_kind === 'local_cli'+ ? readFix(`Reads fact request ${row.request_id}'s durable receipt: its state and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })+ : readFix(`Shows source ${row.source_id}'s canonical owner with its pending, failed and recovering requests, read-only.`,+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] });++/**+ * A refused managed fact request. The journal keeps only code and message, so+ * the suggestion stands alone: inspect the request, then extract again.+ */+function factsRefusal(code: RegistryCode, message: string, row: WriteRequest, cause: string,+ next = 'once it is final, run extract_facts again for the same turn with a new request_id.', fix = requestFix(row)): OperationError {+ return opError(code, message, `${cause} Fact request ${row.request_id} in source ${row.source_id} was refused; inspect it first and do not resubmit it, then ${next}`, { fix });+}+/** #5836: an inferred subject dedups exact text only, so a similar fact is never superseded or dropped for it. */function dedupEmbedding(fact: { embedding?: Float32Array | null; entity_inferred?: unknown }): Float32Array | null {return fact.entity_inferred ? null : fact.embedding ?? null;@@ -30,21 +47,25 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst p = row.intent as ManagedFactIntent | null;if (!p || !['managed_facts_entity', 'managed_facts_complete'].includes(p.kind) || row.operation !== 'extract_facts'|| row.authority.slugPrefixes !== null || row.authority.restrictedNamespace || row.authority.delegated) {- throw new OperationError('permission_denied', 'Unsupported fact extraction intent or confined authority.');+ throw factsRefusal('permission_denied', 'Unsupported fact extraction intent or confined authority.', row,+ 'Managed fact extraction runs only for an extract_facts intent under an unconfined writer, and this request is limited to slug prefixes, a restricted namespace or a delegation, or carries another intent.',+ 'record single facts with remember instead, or ask the user to run the extraction from a writer whose grant is not confined.');}const embedded = p.facts?.some(fact => fact.embedding !== null && fact.embedding !== undefined);const validate = async (tx: BrainEngine, lock = false) => {if (embedded) {await assertManagedFactsEmbedding(tx, config, p.embedding, lock);if (p.facts!.some(fact => fact.embedding && (fact.embedding.length !== p.embedding!.dimensions || !fact.embedding.every(Number.isFinite)))) {- throw new OperationError('embedding_configuration', 'Retained fact vectors do not match their embedding signature.');+ throw factsRefusal('embedding_configuration', 'Retained fact vectors do not match their embedding signature.', row,+ `A retained fact vector is not a finite ${p.embedding!.dimensions}-dimension vector of ${p.embedding!.model}, so none of these facts were installed.`);}}if (p.originalRequestId) {const original = await getWriteRequestById(tx, p.originalRequestId);if (!original || original.state !== 'committed' || original.source_id !== row.source_id || original.source_incarnation !== row.source_incarnation|| original.principal_kind !== row.principal_kind || original.principal_id !== row.principal_id) {- throw new OperationError('permission_denied', 'The original fact extraction authority is unavailable.');+ throw factsRefusal('permission_denied', 'The original fact extraction authority is unavailable.', row,+ 'The committed page write that started this extraction is gone, not committed, or belongs to another source or writer, so its authority cannot back these facts.');}await authorizeFactsBackstop(tx, original, true);}@@ -52,13 +73,16 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writawait authorizeWrite(tx, row.authority, 'extract_facts', p.origin.slug);await authorizePageVisibility(tx, row.authority, p.origin.slug);const origin = await tx.readPageSnapshot(p.origin.slug, { sourceId: row.source_id });- if (!origin || origin.page.id !== p.origin.pageId) throw new OperationError('page_identity_changed', 'The source page was removed or replaced during fact extraction.');+ if (!origin || origin.page.id !== p.origin.pageId) throw factsRefusal('page_identity_changed', 'The source page was removed or replaced during fact extraction.', row,+ `Page ${p.origin.slug}, which these facts were extracted from, was deleted or replaced during extraction.`);if (origin.revision !== p.origin.revision) {const own = await tx.executeRaw(`SELECT id FROM persistence_requests WHERE operation='extract_facts' AND source_id=$1AND source_incarnation=$2::uuid AND principal_kind=$3 AND principal_id=$4 AND COALESCE(intent->>'batchKey',outcome->>'batch_key')=$5AND slug=$6 AND state='committed' AND outcome->>'revision'=$7`,[row.source_id, row.source_incarnation, row.principal_kind, row.principal_id, p.batchKey, p.origin.slug, origin.revision]);- if (!own.length) throw new OperationError('revision_conflict', 'The source page changed during fact extraction.');+ if (!own.length) throw factsRefusal('revision_conflict', 'The source page changed during fact extraction.', row,+ `Page ${p.origin.slug} changed after its facts were extracted, so facts from the older text were not published.`,+ `once it is final, run extract_facts again on the current text of ${p.origin.slug} with a new request_id.`);}}};@@ -68,7 +92,9 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writconst children = p.children ?? [];const done = await tx.executeRaw<{ outcome: { inserted?: number; duplicate?: number; fact_ids?: number[] } }>(`SELECT outcome FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_incarnation=$2::uuidAND state='committed' AND COALESCE(intent->>'batchKey',outcome->>'batch_key')=$3 AND operation='extract_facts'`, [children, row.source_incarnation, p.batchKey]);- if (done.length !== children.length) throw new OperationError('revision_conflict', 'Some extracted facts have not committed.');+ if (done.length !== children.length) throw factsRefusal('revision_conflict', 'Some extracted facts have not committed.', row,+ `${children.length - done.length} of the batch's ${children.length} per-entity fact requests have not committed, so the extraction cannot be recorded as complete.`,+ 'once the entity requests are final, run extract_facts again for the same turn with a new request_id only if facts are still missing.');return { status: 'completed', entity_requests: children.length, kind: p.kind, batch_key: p.batchKey, input_digest: p.inputDigest,inserted: done.reduce((sum, item) => sum + Number(item.outcome.inserted ?? 0), 0),duplicate: done.reduce((sum, item) => sum + Number(item.outcome.duplicate ?? 0), 0),@@ -76,18 +102,24 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writ} };const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });if (snapshot?.page.deleted_at || (snapshot?.page.id ?? null) !== row.page_id || (snapshot?.revision ?? null) !== (p.expected_revision ?? null)) {- throw new OperationError('revision_conflict', 'The fact entity changed after extraction admission.');+ throw factsRefusal('revision_conflict', 'The fact entity changed after extraction admission.', row,+ `Entity page ${row.slug} changed or was deleted after these facts were admitted, so none were published.`);}const facts = (p.facts ?? []).map(fact => ({ ...thawFact(fact), embedding_model: fact.embedding ? p.embedding?.model ?? null : null }));// writeSingleFact's opt-in: an unattributed row keeps its fallback entity slug, database-only.const fallback = (fact: { entity_slug: string | null }) => p.attribute_fallback === true && row.slug === 'memory/unattributed'&& fact.entity_slug !== null && fact.entity_slug !== row.slug;if (!facts.length || facts.some(fact => !fallback(fact) && (fact.entity_slug !== null && fact.entity_slug !== row.slug || fact.entity_slug !== null && !snapshot))) {- throw new OperationError('invalid_params', 'The prepared facts do not match their entity.');+ throw factsRefusal('invalid_params', 'The prepared facts do not match their entity.', row,+ `The request holds no facts, or facts attributed to a page other than ${row.slug}, so none were published.`);}let body = snapshot?.page.compiled_truth ?? '';const parsed = parseFactsFence(body);- if (parsed.warnings.length) throw new OperationError('invalid_params', 'The entity facts fence is malformed.');+ if (parsed.warnings.length) throw factsRefusal('invalid_params', 'The entity facts fence is malformed.', row,+ `The ## Facts table on page ${row.slug} does not parse (${parsed.warnings.length} problem(s)), so no fact rows were added to it.`,+ `read ${row.slug}, repair its ## Facts table, and run extract_facts again with a new request_id.`,+ readFix(`Shows page ${row.slug} in source ${row.source_id} with its ## Facts table, read-only.`,+ { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug], mcp: { tool: 'get_page', arguments: { slug: row.slug, source_id: row.source_id } } }));const [maximum] = await engine.executeRaw<{ n: number }>('SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);let nextRow = Math.max(maximum?.n ?? 0, ...parsed.facts.map(fact => fact.rowNum)) + 1;const entries: Array<{ fact: typeof facts[number]; duplicateId: number | null; rowNum?: number; duplicateOf?: number; supersedes?: FactCandidate }> = [];@@ -118,7 +150,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writfor (const entry of entries) {if (entry.rowNum === undefined) continue;const canonical = canonicalFacts.find(fact => fact.row_num === entry.rowNum);- if (!canonical) throw new OperationError('invalid_params', 'An extracted fact could not be represented in its canonical fence.');+ if (!canonical) throw factsRefusal('invalid_params', 'An extracted fact could not be represented in its canonical fence.', row,+ `An extracted fact did not round-trip through the ## Facts table of page ${row.slug}, so none were published.`);entry.fact = { ...entry.fact, ...canonical, kind: canonical.kind ?? entry.fact.kind,visibility: canonical.visibility ?? entry.fact.visibility, entity_slug: row.slug,embedding: entry.fact.embedding, source_session: entry.fact.source_session };@@ -127,7 +160,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (snapshot && entries.some(entry => entry.rowNum !== undefined)) {page = await preparePageMutation(engine, { ...row, intent: { ...p,content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags) } }, config);- if (page.observedRevision !== snapshot.revision) throw new OperationError('revision_conflict', 'The fact entity changed during preparation.');+ if (page.observedRevision !== snapshot.revision) throw factsRefusal('revision_conflict', 'The fact entity changed during preparation.', row,+ `Entity page ${row.slug} changed while its ## Facts table was being prepared, so none of these facts were published.`);}return { observedRevision: snapshot?.revision ?? null, file: page?.file, noop: entries.every(entry => entry.duplicateId !== null || entry.duplicateOf !== undefined),additionalPageKeys, validate: async tx => {@@ -137,7 +171,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writawait assertFactNotWithdrawn(tx, row.source_id, entry.fact);if (entry.duplicateOf !== undefined) continue;const current = await decideSingleFact(tx, row.source_id, entry.fact, dedupEmbedding(entry.fact), entry.fact.embedding_model, entry.fact.source);- if ((current.candidate?.id ?? null) !== (entry.duplicateId ?? entry.supersedes?.id ?? null)) throw new OperationError('revision_conflict', 'The fact deduplication state changed before publication.');+ if ((current.candidate?.id ?? null) !== (entry.duplicateId ?? entry.supersedes?.id ?? null)) throw factsRefusal('revision_conflict', 'The fact deduplication state changed before publication.', row,+ `A matching fact in source ${row.source_id} was added or retired before publication, so the deduplication decision for ${row.slug} is stale and none of these facts were published.`);}}, apply: async tx => {await page?.apply(tx);@@ -149,7 +184,8 @@ export async function prepareManagedFactsMutation(engine: BrainEngine, row: Writif (entry.duplicateId !== null) { ids.push(entry.duplicateId); continue; }if (entry.rowNum !== undefined) {const result = await tx.insertFacts([{ ...entry.fact, row_num: entry.rowNum, source_markdown_slug: row.slug }], { source_id: row.source_id });- if (result.ids.length !== 1) throw new OperationError('storage_error', 'The canonical extracted fact was not indexed.');+ if (result.ids.length !== 1) throw factsRefusal('storage_error', 'The canonical extracted fact was not indexed.', row,+ `A fact row written into the ## Facts table of ${row.slug} was not indexed, so the publication transaction rolled back.`);ids.push(result.ids[0]);} else ids.push((await tx.insertFact(entry.fact, { source_id: row.source_id })).id);inserted++;diff --git a/src/core/persistence/page-prepare.ts b/src/core/persistence/page-prepare.tsindex 7fef44b1d7..74f3fd9e26 100644--- a/src/core/persistence/page-prepare.ts+++ b/src/core/persistence/page-prepare.ts@@ -8,6 +8,9 @@ import type { Page, PageVersion } from '../types.ts';import { importFromContent, type ParsedPage } from '../import-file.ts';import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown, resolveSourceLocalFilePath, type ParseOpts } from '../markdown.ts';import { OperationError, opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import type { Action } from '../agent-output.ts';+import type { RegistryCode } from '../error-registry.ts';import { pageIdentityError, yamlLocator } from './page-identity.ts';import { assertPageRevision, type PageSnapshot } from '../page-state/types.ts';import { isWriteTargetContained } from '../path-confine.ts';@@ -40,6 +43,24 @@ import { applyPageEdits, editDiff, parsePageEdits } from './page-edit.ts';const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';+const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner with its pending, failed and recovering requests, read-only.`,+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });+const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as it is now, with its revision.`,+ { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId } } });++/**+ * A refused page request. The journal keeps only code and message, so the+ * suggestion stands alone: the cause and next step, then the request to+ * inspect before anything is resubmitted.+ */+function pageRefusal(code: RegistryCode, message: string, row: WriteRequest, cause: string, fix?: Action): OperationError {+ return opError(code, message,+ `${cause} Request ${row.request_id} in source ${row.source_id} was refused; inspect it before resubmitting, and use a new request_id for any corrected write.`,+ { fix: fix ?? (row.principal_kind === 'local_cli'+ ? readFix(`Reads request ${row.request_id}'s durable receipt: its state and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })+ : ownerStatusFix(row.source_id)) });+}+/** The parser trims titles, so a stored title differing only in surrounding whitespace is not drift (#5635). */function canonical(page: Pick<Page, 'type' | 'title' | 'compiled_truth' | 'timeline' | 'frontmatter'>, tags: string[]) {return { type: page.type, title: page.title.trim(), compiled_truth: page.compiled_truth, timeline: page.timeline ?? '',@@ -94,7 +115,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequ// its derived path is not its canonical file and is neither written nor removed.if (snapshot && !snapshot.page.source_path && await isUnboundSourcePage(engine, row.source_id, row.slug)) return undefined;const binding = await getWorktreeBinding(engine, row.source_id, hostId);- if (!binding?.local_path) throw new OperationError('owner_unavailable', 'The canonical worktree is unavailable on this host.');+ if (!binding?.local_path) throw opError('owner_unavailable', 'The canonical worktree is unavailable on this host.',+ `This host does not hold source ${row.source_id}'s canonical worktree (or it has no local path), so the file of ${row.slug} was not written. Inspect the owner before resubmitting; the write publishes on the host that owns the source.`,+ { fix: ownerStatusFix(row.source_id) });const root = join(binding.local_path, binding.relative_path);// #5622: a new page captured from a file inside the source is published to that file.const capturedPath = !snapshot && options.capture ? options.capture.path : recordedPathFromFileUri(snapshot?.page.source_uri, root);@@ -106,7 +129,9 @@ export async function prepareFileTarget(engine: BrainEngine, row: Pick<WriteRequthrow colonSlugWindowsRefusal(row.slug, row.source_id);}const path = nativeFileTarget(root, candidate);- if (!isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The canonical file target is outside its registered source.');+ if (!isWriteTargetContained(path, root)) throw opError('source_changed', 'The canonical file target is outside its registered source.',+ `The file of ${row.slug} resolves outside source ${row.source_id}'s registered root (a symlinked directory or a moved checkout), so nothing was written. Inspect the owner before resubmitting; how to repair the checkout is the user's decision.`,+ { fix: ownerStatusFix(row.source_id) });const before = existsSync(path) ? readFileSync(path) : null;if (!before && snapshot && !snapshot.page.deleted_at && !options.allowMissing) {// A declared db_only page has no canonical file by design and publishes to@@ -167,7 +192,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestpreparedIntent?: { content: string; expectedRevision: string; tags?: string[] }, signal?: AbortSignal,options: { allowMissingFile?: boolean } = {}): Promise<PreparedMutation> {signal?.throwIfAborted();- if (!row.intent) throw new OperationError('storage_error', 'A pending write lost its normalized intent.');+ if (!row.intent) throw pageRefusal('storage_error', 'A pending write lost its normalized intent.', row,+ `The request has no stored intent for ${row.slug} (its payload was compacted or never recorded), so it cannot be published and wrote nothing.`);await assertKnowledgePublicationAllowed(engine, row);const p = row.intent;const source = { sourceId: row.source_id };@@ -187,7 +213,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest}if (row.operation === 'delete_page') {assertPurgeParams(p, row.authority.remote);- if (!snapshot) throw new OperationError('page_not_found', 'Page not found.');+ if (!snapshot) throw pageRefusal('page_not_found', 'Page not found.', row,+ `Page ${row.slug} does not exist in source ${row.source_id}, so nothing was deleted. Check the slug and the source.`, pageFix(row.source_id, row.slug));const purge = p.purge === true;const noop = !purge && snapshot.page.deleted_at != null;// Tombstones still own their recorded artifact. Purge always attempts its@@ -212,13 +239,16 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest// explicitly restore a tombstone; legacy versions leave this state unchanged.let targetDeleted = false;if (row.operation === 'restore_page' || row.operation === 'revert_version') {- if (!snapshot) throw new OperationError('page_not_found', 'Page not found.');+ if (!snapshot) throw pageRefusal('page_not_found', 'Page not found.', row,+ `Page ${row.slug} does not exist in source ${row.source_id} (it was purged or never written), so nothing was ${row.operation === 'restore_page' ? 'restored' : 'reverted'}. Check the slug and the source.`,+ pageFix(row.source_id, row.slug));let page = snapshot.page;let tags = snapshot.tags;if (row.operation === 'revert_version') {const [version] = await engine.executeRaw<PageVersion>('SELECT * FROM page_versions WHERE id=$1 AND page_id=$2', [p.version_id, page.id]);- if (!version) throw new OperationError('not_found', 'Version not found for this page.');+ if (!version) throw pageRefusal('not_found', 'Version not found for this page.', row,+ `Version ${String(p.version_id)} is not in the history of page ${row.slug}, so nothing was reverted. List the page's versions (get_versions; CLI: gbrain history) and revert to one of them.`);targetDeleted = version.is_deleted ?? (snapshot.page.deleted_at != null);page = { ...page, compiled_truth: version.compiled_truth, frontmatter: version.frontmatter,...(version.timeline !== null && version.timeline !== undefined ? { timeline: version.timeline } : {}),@@ -283,15 +313,20 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest: 'Check the content and frontmatter, then submit the corrected content with a new request_id.');}const ready = prepared;- if (ready.observedRevision !== observedRevision) throw new OperationError('revision_conflict', 'The page changed during import preparation.');+ if (ready.observedRevision !== observedRevision) throw pageRefusal('revision_conflict', 'The page changed during import preparation.', row,+ `Page ${row.slug} was written by another request while this one was being prepared, so it published nothing. Read the current page and revision, then submit the intended change against it.`,+ pageFix(row.source_id, row.slug));if (ready.slug !== row.slug) {await authorizeWrite(engine, row.authority, row.operation, ready.slug);const duplicate = await engine.readPageSnapshot(ready.slug, { ...source, excludePrivate: row.authority.remote });- if (!duplicate) throw new OperationError('permission_denied', 'The duplicate is not readable by this writer.');+ if (!duplicate) throw pageRefusal('permission_denied', 'The duplicate is not readable by this writer.', row,+ `The content duplicates another page in source ${row.source_id} that this writer cannot read, so nothing was published. Write it under a different slug, or ask the user to make the write from a writer that can read the existing page.`);return { observedRevision, noop: true, additionalPageKeys:[{sourceId:row.source_id,slug:ready.slug}],validate: async tx => {await authorizeWrite(tx,row.authority,row.operation,ready.slug,true);const current=await tx.readPageSnapshot(ready.slug,{...source,excludePrivate:row.authority.remote});- if (!current || current.page.id!==duplicate.page.id || current.revision!==duplicate.revision) throw new OperationError('revision_conflict','The read-only duplicate changed during preparation.');+ if (!current || current.page.id!==duplicate.page.id || current.revision!==duplicate.revision) throw pageRefusal('revision_conflict','The read-only duplicate changed during preparation.', row,+ `Page ${ready.slug}, which this content duplicates, changed while the write was being prepared, so nothing was published. Read it, then submit the write again if it is still needed.`,+ pageFix(row.source_id, ready.slug));},apply: async () => ({ status: 'duplicate', slug: duplicate.page.slug, duplicate_revision: duplicate.revision }) };}@@ -326,7 +361,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequestconst [pinned] = await tx.executeRaw<{ mode: string | null }>(`UPDATE sources SET config=CASE WHEN config->>'slug_root_mode' IS NULLTHEN jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb($2::text)) ELSE config END WHERE id=$1 RETURNING config->>'slug_root_mode' AS mode`,[row.source_id, pinMode]);- if (pinned?.mode !== pinMode) throw new OperationError('revision_conflict', 'The source slug-root mode changed during preparation.');+ if (pinned?.mode !== pinMode) throw pageRefusal('revision_conflict', 'The source slug-root mode changed during preparation.', row,+ `Another write pinned source ${row.source_id}'s slug-root mode while ${row.slug} was being prepared, so this publication rolled back. Once the request is final, submit the write again; it is prepared under the pinned mode.`);}if (provenance) await tx.executeRaw(`UPDATE pages SET source_kind=$3,ingested_via=$4,ingested_at=$5::timestamptzWHERE source_id=$1 AND slug=$2`, [row.source_id, row.slug, provenance.source_kind, provenance.ingested_via, provenance.ingested_at]);@@ -352,6 +388,8 @@ export async function preparePageMutation(engine: BrainEngine, row: WriteRequest}function editLockedPage(row: WriteRequest, snapshot: PageSnapshot | null) {- if (!snapshot || snapshot.page.deleted_at) throw new OperationError('page_not_found', 'Page not found.');+ if (!snapshot || snapshot.page.deleted_at) throw pageRefusal('page_not_found', 'Page not found.', row,+ `Page ${row.slug} does not exist in source ${row.source_id} or is deleted, so the edit changed nothing. If it is soft-deleted, restore it with restore_page; otherwise write it whole with put_page.`,+ pageFix(row.source_id, row.slug));return applyPageEdits(snapshot.page, snapshot.tags, row.authority.remote, parsePageEdits(row.intent?.edits));}