Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(errors): B10 backfill source-reconcile, source-lifecycle, prepared-maintenance, reconcile-{backup,merge,audit,state}, reconcile
garrytan972756d33783
diff --git a/src/commands/source-reconcile.ts b/src/commands/source-reconcile.tsindex 20b27ffde3..045289c346 100644--- a/src/commands/source-reconcile.ts+++ b/src/commands/source-reconcile.ts@@ -7,7 +7,8 @@ import { flushDirectory } from '../core/fs-durable.ts';import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';import { isThinClient, loadConfig, toEngineConfig } from '../core/config.ts';import { loadMounts } from '../core/brain-registry.ts';-import { OperationError } from '../core/ops/contract.ts';+import { OperationError, opError } from '../core/ops/contract.ts';+import { readFix, trustedCliRequired } from '../core/ops/op-fix.ts';import { isValidSourceId } from '../core/source-id.ts';import { validateSlug } from '../core/utils.ts';import { runPersistenceAdministration } from '../core/persistence/administration.ts';@@ -69,51 +70,72 @@ export function parseReconcileArgs(args: string[]): ReconcileCliArgs {if (!token.startsWith('-')) { positional.push(token); continue; }const equal = token.indexOf('=');const flag = equal < 0 ? token : token.slice(0, equal);- if (flags.has(flag)) throw new OperationError('invalid_params', `Duplicate option ${flag}.`);+ if (flags.has(flag)) throw opError('invalid_params', `Duplicate option ${flag}.`, `Pass ${flag} once, then rerun the command.`);if (boolean.has(flag)) {- if (equal >= 0) throw new OperationError('invalid_params', `${flag} does not accept a value.`);+ if (equal >= 0) throw opError('invalid_params', `${flag} does not accept a value.`, `Use ${flag} on its own, without =value, then rerun the command.`);flags.set(flag, true);continue;}- if (!values.has(flag)) throw new OperationError('invalid_params', `Unknown reconciliation option: ${flag}.`);+ if (!values.has(flag)) throw opError('invalid_params', `Unknown reconciliation option: ${flag}.`,+ 'Reconciliation accepts --brain, --preview, --out, --from, --decisions, --apply, --request-id, --audit, --backups, --remove-backup, --limit, --after and --json; the help in fix shows which forms combine.',+ { fix: readFix('Lists every reconciliation form and its options.', { argv: ['gbrain', 'sources', 'reconcile', '--help'] }) });const value = equal >= 0 ? token.slice(equal + 1) : args[++i];- if (!value || value.startsWith('-') || value.includes('\0')) throw new OperationError('invalid_params', `${flag} requires a value.`);+ if (!value || value.startsWith('-') || value.includes('\0')) throw opError('invalid_params', `${flag} requires a value.`,+ `Give ${flag} its value as the next argument or as ${flag}=value; a value cannot start with '-'.`);flags.set(flag, value);}const [source, slug] = positional;- if (!isValidSourceId(source)) throw new OperationError('invalid_params', 'Reconciliation requires one explicit source ID.');+ if (!isValidSourceId(source)) throw opError('invalid_params', 'Reconciliation requires one explicit source ID.',+ 'Pass the source ID as the first argument, before the page slug; the command in fix lists registered source IDs.',+ { fix: readFix('Lists the registered sources and their IDs.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });const audit = flags.has('--audit');const backups = flags.has('--backups') || flags.has('--remove-backup');- if (positional.length !== (audit ? 1 : 2)) throw new OperationError('invalid_params', audit- ? 'Audit requires one source and no page slug.' : 'Reconciliation requires one source and one exact page slug.');+ if (positional.length !== (audit ? 1 : 2)) throw opError('invalid_params', audit+ ? 'Audit requires one source and no page slug.' : 'Reconciliation requires one source and one exact page slug.',+ `An audit takes only the source (${source}); preview, apply and backups take the source and exactly one page slug. Rerun with the matching arguments.`);if (slug !== undefined) {- try { validateSlug(slug); } catch { throw new OperationError('invalid_params', 'Invalid page slug.'); }- if (/[?*]/.test(slug)) throw new OperationError('invalid_params', 'Reconciliation does not accept page patterns.');+ try { validateSlug(slug); } catch {+ throw opError('invalid_params', 'Invalid page slug.',+ "Pass the page's exact stored slug: no leading '/', '..' segments, backslashes, URL-encoded separators or control characters.");+ }+ if (/[?*]/.test(slug)) throw opError('invalid_params', 'Reconciliation does not accept page patterns.',+ `Reconcile one page at a time by its exact slug; an --audit run for source ${source} lists the pages that need it.`);}const applying = flags.has('--apply');if (applying && ['--preview', '--from', '--decisions', '--out', '--audit', '--backups', '--remove-backup'].some(flag => flags.has(flag))) {- throw new OperationError('invalid_params', 'Apply cannot be combined with preview, decisions, output, or audit options.');+ throw opError('invalid_params', 'Apply cannot be combined with preview, decisions, output, or audit options.',+ 'Run apply on its own: the resolved preview file after --apply, --request-id and --brain only. Make or resolve previews in a separate command first.');}- if (!applying && flags.has('--request-id')) throw new OperationError('invalid_params', '--request-id is only valid with --apply.');- if (applying && !isWriteRequestId(flags.get('--request-id'))) throw new OperationError('invalid_params', 'Apply requires an explicit UUID --request-id.');- if (flags.has('--decisions') && !flags.has('--from')) throw new OperationError('invalid_params', '--decisions requires --from.');- if (!audit && !flags.has('--backups') && (flags.has('--limit') || flags.has('--after'))) throw new OperationError('invalid_params', '--limit and --after are only valid with --audit or --backups.');- if (audit && ['--preview', '--out', '--from', '--decisions'].some(flag => flags.has(flag))) throw new OperationError('invalid_params', 'Audit cannot create or resolve a page preview.');+ if (!applying && flags.has('--request-id')) throw opError('invalid_params', '--request-id is only valid with --apply.',+ 'Drop --request-id: previews, audits and backup listings change nothing and take no request ID.');+ if (applying && !isWriteRequestId(flags.get('--request-id'))) throw opError('invalid_params', 'Apply requires an explicit UUID --request-id.',+ 'Add --request-id with a new UUID for a first apply. After a lost response or a pending receipt, reuse the same request_id with the same arguments instead of a new one.');+ if (flags.has('--decisions') && !flags.has('--from')) throw opError('invalid_params', '--decisions requires --from.',+ 'Add --from with the preview file the decisions resolve, and --out with a new file for the resolved preview.');+ if (!audit && !flags.has('--backups') && (flags.has('--limit') || flags.has('--after'))) throw opError('invalid_params', '--limit and --after are only valid with --audit or --backups.',+ 'Drop --limit and --after, or use them with --audit (source only) or --backups (one page).');+ if (audit && ['--preview', '--out', '--from', '--decisions'].some(flag => flags.has(flag))) throw opError('invalid_params', 'Audit cannot create or resolve a page preview.',+ 'Run the audit without --preview, --out, --from or --decisions, then preview a page it lists in a separate command.');if (backups && ['--preview', '--out', '--from', '--decisions', '--apply', '--audit'].some(flag => flags.has(flag)) || flags.has('--backups') && flags.has('--remove-backup')) {- throw new OperationError('invalid_params', 'Backup administration cannot be combined with preview, apply, audit, or another backup action.');+ throw opError('invalid_params', 'Backup administration cannot be combined with preview, apply, audit, or another backup action.',+ 'Run --backups (list) or --remove-backup (delete one reference) on its own, with only --brain, --limit, --after and --json.');}const brain = flags.get('--brain') as string | undefined;- if (brain !== undefined && !isValidSourceId(brain)) throw new OperationError('invalid_params', 'Invalid brain ID.');+ if (brain !== undefined && !isValidSourceId(brain)) throw opError('invalid_params', 'Invalid brain ID.',+ 'Pass --brain host for the local brain, or the ID of a mounted brain; the command in fix lists mounted brain IDs.',+ { fix: readFix('Lists the mounted brains and their IDs.', { argv: ['gbrain', 'mounts', 'list', '--json'] }) });const params: Record<string, unknown> = { source_id: source, ...(slug ? { slug } : {}) };if (backups) {params.action = flags.has('--backups') ? 'list' : 'remove';if (flags.has('--remove-backup')) params.backup_reference = flags.get('--remove-backup');- if (flags.has('--after') && !isWriteRequestId(flags.get('--after'))) throw new OperationError('invalid_params', 'Backup pagination requires a request UUID cursor.');+ if (flags.has('--after') && !isWriteRequestId(flags.get('--after'))) throw opError('invalid_params', 'Backup pagination requires a request UUID cursor.',+ 'Pass --after exactly as the previous backup listing returned its cursor (a request UUID), or omit it to start from the newest backup.');}if (applying) params.request_id = flags.get('--request-id');if (flags.has('--limit')) {const limit = Number(flags.get('--limit'));- if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw new OperationError('invalid_params', 'Audit limit must be an integer from 1 to 100.');+ if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw opError('invalid_params', 'Audit limit must be an integer from 1 to 100.',+ 'Pass --limit as a whole number from 1 to 100, or omit it for the default page size.');params.limit = limit;}if (flags.has('--after')) params.after = flags.get('--after');@@ -127,17 +149,24 @@ export function readReconcileJson(path: string): unknown {let fd: number | undefined;try {const target = resolve(path);- if (!lstatSync(target).isFile()) throw new OperationError('invalid_params', 'Reconciliation input must be a regular JSON file, not a symbolic link.');+ if (!lstatSync(target).isFile()) throw opError('invalid_params', 'Reconciliation input must be a regular JSON file, not a symbolic link.',+ 'Pass the path of the preview or decisions file itself, not a symbolic link to it.');fd = openSync(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);const stat = fstatSync(fd);- if (!stat.isFile() || stat.size > PERSISTENCE_IPC_MAX_BYTES - 65536) throw new OperationError('invalid_params', 'Reconciliation input must be a bounded regular JSON file.');+ if (!stat.isFile() || stat.size > PERSISTENCE_IPC_MAX_BYTES - 65536) throw opError('invalid_params', 'Reconciliation input must be a bounded regular JSON file.',+ `Pass the regular preview file written by --out, or a decisions file under ${PERSISTENCE_IPC_MAX_BYTES - 65536} bytes.`);const content = readFileSync(fd);- if (content.byteLength > PERSISTENCE_IPC_MAX_BYTES - 65536) throw new OperationError('invalid_params', 'Reconciliation input exceeds the transport limit.');+ if (content.byteLength > PERSISTENCE_IPC_MAX_BYTES - 65536) throw opError('invalid_params', 'Reconciliation input exceeds the transport limit.',+ `Keep the input under ${PERSISTENCE_IPC_MAX_BYTES - 65536} bytes: pass the preview file written by --out unchanged, and only the decisions it needs.`);try { return JSON.parse(content.toString('utf8')); }- catch { throw new OperationError('invalid_params', 'Reconciliation input is not valid JSON.'); }+ catch {+ throw opError('invalid_params', 'Reconciliation input is not valid JSON.',+ 'Pass the preview file written by --out unchanged, or a decisions file holding one JSON document; validate it with a JSON parser before rerunning.');+ }} catch (error) {if (error instanceof OperationError) throw error;- throw new OperationError('invalid_params', 'Cannot read the reconciliation input as a regular JSON file.');+ throw opError('invalid_params', 'Cannot read the reconciliation input as a regular JSON file.',+ 'Check that the file exists, is a regular file and is readable by this user, then rerun with its path.');} finally { if (fd !== undefined) closeSync(fd); }}@@ -150,7 +179,8 @@ export function writeReconcilePreview(path: string, preview: unknown): void {const target = join(directory, basename(requested));assertManagedFilesystemWrite(target);const content = JSON.stringify(preview, null, 2) + '\n';- if (Buffer.byteLength(content) > PERSISTENCE_IPC_MAX_BYTES - 65536) throw new OperationError('invalid_params', 'The preview exceeds the artifact size limit.');+ if (Buffer.byteLength(content) > PERSISTENCE_IPC_MAX_BYTES - 65536) throw opError('invalid_params', 'The preview exceeds the artifact size limit.',+ `Nothing changed. This page's preview is over the ${PERSISTENCE_IPC_MAX_BYTES - 65536}-byte artifact limit, so it cannot be resolved through reconcile; tell the user the page needs a manual edit of its canonical file.`);temporary = join(directory, `.${basename(target)}.${randomUUID()}.tmp`);fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);writeFileSync(fd, content);@@ -162,7 +192,8 @@ export function writeReconcilePreview(path: string, preview: unknown): void {flushDirectory(directory);} catch (error) {if (error instanceof OperationError) throw error;- throw new OperationError('storage_error', 'Cannot create the private preview file. Use an existing directory outside the canonical worktree and a new filename.');+ throw opError('storage_error', 'Cannot create the private preview file. Use an existing directory outside the canonical worktree and a new filename.',+ 'Nothing changed in the brain. Pass --out a new filename in an existing writable directory outside the source checkout; it never replaces an existing file.');} finally {if (fd !== undefined) closeSync(fd);if (temporary) {@@ -177,10 +208,14 @@ export async function runReconcileCli(args: string[], connected?: BrainEngine):try {const parsed = parseReconcileArgs(args);const brain = parsed.brain ?? getCliOptions().brain;- if (!brain) throw new OperationError('invalid_params', 'Select the brain explicitly with --brain <id> (use --brain host for the local brain).');+ if (!brain) throw opError('invalid_params', 'Select the brain explicitly with --brain <id> (use --brain host for the local brain).',+ 'Add --brain host to reconcile the local brain, or --brain with a mounted brain ID from the command in fix.',+ { fix: readFix('Lists the mounted brains and their IDs.', { argv: ['gbrain', 'mounts', 'list', '--json'] }) });const config = persistenceConfigForBrain(loadConfig(), brain, brain === 'host' ? [] : loadMounts());- if (!config) throw new OperationError('invalid_params', 'The selected brain has no configuration.');- if (isThinClient(config)) throw new OperationError('permission_denied', 'Reconciliation runs on the canonical host using its existing trusted CLI registration. A remote token cannot repair files.');+ if (!config) throw opError('invalid_params', 'The selected brain has no configuration.',+ `Brain '${brain}' is not configured on this machine. Use --brain host for the local brain, or a mounted brain ID from the command in fix.`,+ { fix: readFix('Lists the mounted brains and their IDs.', { argv: ['gbrain', 'mounts', 'list', '--json'] }) });+ if (isThinClient(config)) throw trustedCliRequired('Reconciliation runs on the canonical host using its existing trusted CLI registration. A remote token cannot repair files.');if (parsed.input) parsed.params[parsed.operation === 'writer_reconcile_apply' ? 'preview' : 'from'] = readReconcileJson(parsed.input);if (parsed.decisions) parsed.params.decisions = readReconcileJson(parsed.decisions);if (parsed.output) parsed.params.output_path = resolve(parsed.output);@@ -201,7 +236,13 @@ export async function runReconcileCli(args: string[], connected?: BrainEngine):}const { preview, ...summary } = result;if (parsed.output) {- if (!preview) throw new OperationError('storage_error', 'The owner did not return the requested preview.');+ if (!preview) {+ const sourceId = String(parsed.params.source_id);+ throw opError('storage_error', 'The owner did not return the requested preview.',+ `Nothing was written; a preview never changes canonical content. Check the owner of source ${sourceId} with the command in fix, then rerun the preview.`,+ { fix: readFix('Shows the canonical owner and any pending recovery for this source.',+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--brain', brain, '--json'] }) });+ }writeReconcilePreview(parsed.output, preview);summary.preview_file = resolve(parsed.output);}diff --git a/src/core/persistence/prepared-maintenance.ts b/src/core/persistence/prepared-maintenance.tsindex 557bd29765..43cb67cc50 100644--- a/src/core/persistence/prepared-maintenance.ts+++ b/src/core/persistence/prepared-maintenance.ts@@ -2,7 +2,9 @@ import { realpathSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine, FactRow } from '../engine.ts';import { loadConfig, type GBrainConfig } from '../config.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { opError, type OperationContext } from '../ops/contract.ts';+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';+import type { Action } from '../agent-output.ts';import { currentSubmissionAuthority } from '../minions/submission-authority.ts';import { serializePageToMarkdown } from '../markdown.ts';import { parseFactsFence } from '../facts-fence.ts';@@ -29,6 +31,16 @@ export interface MaintenanceAuthority {wait?: MaintenanceWriteWait;}+function ownerStatusFix(sourceId: string): Action {+ return readFix('Shows the source\'s canonical binding, owner host and any pending recovery.',+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });+}++function receiptFix(row: WriteRequest): Action {+ return readFix('The receipt is the record of what this maintenance request did; read it before planning another.',+ { argv: ['gbrain', 'write-request', '--', row.id] });+}+function maintenanceRequestId(value: unknown): string {const key = digest(value);return `${key.slice(0, 8)}-${key.slice(8, 12)}-4${key.slice(13, 16)}-a${key.slice(17, 20)}-${key.slice(20, 32)}`;@@ -41,15 +53,19 @@ export async function maintenancePreflight(engine: BrainEngine, sourceId: stringconst job = currentSubmissionAuthority();const verified = currentVerifiedLocalWriter();if (job && job.kind !== 'application' || verified?.remote) {- throw new OperationError('permission_denied', 'Managed maintenance requires a registered local CLI writer; remote maintenance jobs are not supported.');+ throw trustedCliRequired('Managed maintenance requires a registered local CLI writer; remote maintenance jobs are not supported.');}if (!verified) await registerLocalWriter(engine, 'cli');const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>("SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);- if (!source || source.archived) throw new OperationError('source_changed', 'The maintenance source is not active.');+ if (!source || source.archived) throw opError('source_changed', 'The maintenance source is not active.',+ `Source '${sourceId}' is missing or archived, so maintenance submitted nothing. Check it with the command in fix; restore an archived source with gbrain sources restore ${sourceId} before running maintenance on it.`,+ { fix: readFix('Lists registered sources, archived ones included.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });const writer = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext,'submit_job', sourceId, source.incarnation, 'maintenance');- if (writer.slugPrefixes !== null) throw new OperationError('permission_denied', 'Managed maintenance requires a source-wide grant.');+ if (writer.slugPrefixes !== null) throw opError('permission_denied', 'Managed maintenance requires a source-wide grant.',+ `The CLI writer registration is limited to slug prefixes, but maintenance on '${sourceId}' writes anywhere in the source. Review the grant with the command in fix; widening it is the user's decision.`,+ { fix: readFix('Shows the CLI writer registration and its source, operation and slug-prefix grant.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });const binding = await getWorktreeBinding(engine, sourceId);// An unbound Google or GitHub source publishes database-only, exactly as its own connector sync does// (its local_path is the connector's state directory, not a canonical checkout).@@ -62,10 +78,14 @@ export async function maintenancePreflight(engine: BrainEngine, sourceId: stringif (writeThrough && (root || configuredRoot || binding)) {if (!binding || binding.source_incarnation !== source.incarnation || binding.owner_host_id !== localHostId() ||binding.state !== 'active' || !binding.local_path || !binding.coordination_path) {- throw new OperationError('owner_unavailable', 'The maintenance source needs an active canonical owner before model work.');+ throw opError('owner_unavailable', 'The maintenance source needs an active canonical owner before model work.',+ `Source '${sourceId}' has no active canonical owner on this host, so no model work ran. Inspect the owner with the command in fix and run maintenance on the host it names; do not claim or transfer ownership just to run maintenance.`,+ { fix: ownerStatusFix(sourceId) });}if (root && realpathSync(root) !== realpathSync(join(binding.local_path, binding.relative_path))) {- throw new OperationError('source_changed', 'The maintenance directory is not the canonical source root.');+ throw opError('source_changed', 'The maintenance directory is not the canonical source root.',+ `Run maintenance for '${sourceId}' against its registered canonical root (the command in fix shows it), or without a directory argument; nothing was submitted.`,+ { fix: ownerStatusFix(sourceId) });}await nativeLockCapability();assertPhysicalRoot(binding.local_path, { worktreeId: binding.worktree_id, coordinationPath: binding.coordination_path });@@ -79,11 +99,13 @@ async function validateMaintenance(engine: BrainEngine, authority: MaintenanceAuconst [source] = await engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1', [authority.writer.sourceId]);if (!source || source.archived || source.incarnation !== authority.writer.sourceIncarnation) {- throw new OperationError('source_changed', 'The accepted maintenance source changed.');+ throw opError('source_changed', 'The accepted maintenance source changed.',+ `Source '${authority.writer.sourceId}' was archived or replaced after maintenance started, so nothing more was submitted for it. Check it with the command in fix, then run the maintenance command again so it preflights the current source.`,+ { fix: readFix('Lists registered sources, archived ones included.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });}// A connector preflighted as unbound publishes database-only; one claimed since then must use its owner.if (authority.writer.databaseOnlyReason === 'connector_database' && await getWorktreeBinding(engine, authority.writer.sourceId)) {- throw new OperationError('source_changed', 'The connector source gained a canonical owner after maintenance preflight.', 'Rerun the maintenance command.');+ throw opError('source_changed', 'The connector source gained a canonical owner after maintenance preflight.', 'Rerun the maintenance command.');}await authorizeWrite(engine, authority.writer, 'submit_job', slug);await authorizePageVisibility(engine, authority.writer, slug);@@ -100,8 +122,10 @@ async function submitMaintenance(engine: BrainEngine, authority: MaintenanceAuthreturn writeResponse(wait.observe(await waitForWrite(engine, prior, loadConfig() ?? { engine: engine.kind }, wait.ms())));}const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId, includeDeleted: true });- if (snapshot?.page.deleted_at) throw new OperationError('page_not_found', 'Maintenance cannot restore a deleted page.');- if ((snapshot?.revision ?? null) !== intent.expected_revision) throw new OperationError('revision_conflict', 'The maintenance target changed before admission.');+ if (snapshot?.page.deleted_at) throw opError('page_not_found', 'Maintenance cannot restore a deleted page.',+ `Page ${slug} in '${authority.writer.sourceId}' was deleted after maintenance read it, and maintenance never recreates deleted pages; nothing was submitted. Run maintenance again to plan from the current pages.`);+ if ((snapshot?.revision ?? null) !== intent.expected_revision) throw opError('revision_conflict', 'The maintenance target changed before admission.',+ `Page ${slug} in '${authority.writer.sourceId}' changed after maintenance read it; nothing was submitted. Run maintenance again so it works from the current revision.`);const row = await admitWrite(engine, { principal: authority.writer.principal, requestId, operation: 'submit_job',sourceId: authority.writer.sourceId, sourceIncarnation: authority.writer.sourceIncarnation, slug,pageId: snapshot?.page.id ?? null, authority: authority.writer, callerIntent: intent, intent,@@ -140,7 +164,9 @@ export async function submitDatabaseMaintenanceIntent(engine: BrainEngine, authoexport async function stampMaintenancePage(engine: BrainEngine, authority: MaintenanceAuthority, slug: string,cycleDate: string, rawSource?: string, rawTraceExemptReason?: string, seat?: string): Promise<void> {const snapshot = await engine.readPageSnapshot(slug, { sourceId: authority.writer.sourceId });- if (!snapshot) throw new OperationError('page_not_found', 'A maintenance output page disappeared.');+ if (!snapshot) throw opError('page_not_found', 'A maintenance output page disappeared.',+ `Output page ${slug} in '${authority.writer.sourceId}' no longer exists, so it was not stamped. Confirm with the command in fix, then run maintenance again to regenerate it if it is still wanted.`,+ { fix: readFix('Shows whether the page exists in this source now.', { argv: ['gbrain', 'get', '--source', authority.writer.sourceId, '--', slug] }) });const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || cycleDate;const page = { ...snapshot.page, frontmatter: { ...snapshot.page.frontmatter, dream_generated: true,dream_cycle_date: firstDate, dream_created_cycle_date: firstDate, ...(rawSource ? { raw_source: rawSource } : {}),@@ -152,10 +178,13 @@ export async function stampMaintenancePage(engine: BrainEngine, authority: Maintexport async function verifyMaintenanceOutputs(engine: BrainEngine, authority: MaintenanceAuthority,refs: Array<{ slug: string; source_id: string }>): Promise<number> {for (const ref of refs) {- if (ref.source_id !== authority.writer.sourceId) throw new OperationError('permission_denied', 'A maintenance output belongs to another source.');+ if (ref.source_id !== authority.writer.sourceId) throw opError('permission_denied', 'A maintenance output belongs to another source.',+ `Output ${ref.slug} is in source '${ref.source_id}', but this maintenance run is authorized only for '${authority.writer.sourceId}'; outputs were not verified. Run maintenance separately per source, and report this to the user if it repeats, since a phase must only emit pages in its own source.`);await validateMaintenance(engine, authority, ref.slug);const snapshot = await engine.readPageSnapshot(ref.slug, { sourceId: ref.source_id });- if (!snapshot) throw new OperationError('page_not_found', 'A maintenance output page disappeared.');+ if (!snapshot) throw opError('page_not_found', 'A maintenance output page disappeared.',+ `Output page ${ref.slug} in '${ref.source_id}' no longer exists, so it was not verified. Confirm with the command in fix, then run maintenance again to regenerate it if it is still wanted.`,+ { fix: readFix('Shows whether the page exists in this source now.', { argv: ['gbrain', 'get', '--source', ref.source_id, '--', ref.slug] }) });if (authority.binding) await prepareFileTarget(engine, { source_id: ref.source_id, slug: ref.slug,worktree_id: authority.binding.worktree_id }, snapshot, serializePageToMarkdown(snapshot.page, snapshot.tags));}@@ -185,20 +214,23 @@ export async function submitMaintenanceConsolidation(engine: BrainEngine, authorconst sourceId = authority.writer.sourceId;const facts = await readFacts(engine, sourceId, cluster.map(f => f.id));if (facts.length !== cluster.length || facts.some(f => f.value.visibility !== 'world' || f.value.expired_at || f.value.consolidated_at)) {- throw new OperationError('revision_conflict', 'The consolidation facts are no longer eligible.');+ throw opError('revision_conflict', 'The consolidation facts are no longer eligible.',+ `Facts on ${slug} in '${sourceId}' were expired, consolidated or made private after clustering; nothing was submitted. The next consolidate run re-clusters the current facts.`);}for (const fact of facts) {const observed = cluster.find(f => f.id === fact.id)!;if (fact.value.fact !== observed.fact || fact.value.entity_slug !== slug || fact.value.confidence !== observed.confidence ||fact.value.source !== observed.source || fact.value.source_session !== observed.source_session ||Date.parse(String(fact.value.valid_from)) !== observed.valid_from.getTime()) {- throw new OperationError('revision_conflict', 'The consolidation input changed after clustering.');+ throw opError('revision_conflict', 'The consolidation input changed after clustering.',+ `A fact on ${slug} in '${sourceId}' was edited after clustering; nothing was submitted. The next consolidate run re-clusters the current facts.`);}}const pages: EvidencePage[] = [];for (const pageSlug of [...new Set([slug, ...facts.map(f => f.value.source_markdown_slug).filter((s): s is string => typeof s === 'string' && !!s)])].sort()) {const snapshot = await engine.readPageSnapshot(pageSlug, { sourceId, excludePrivate: true });- if (!snapshot) throw new OperationError('page_not_found', 'The consolidation evidence page is unavailable.');+ if (!snapshot) throw opError('page_not_found', 'The consolidation evidence page is unavailable.',+ `Evidence page ${pageSlug} in '${sourceId}' was deleted or made private after clustering; nothing was submitted. The next consolidate run re-clusters without it.`);pages.push({ slug: pageSlug, revision: snapshot.revision, id: snapshot.page.id });}const target = pages.find(p => p.slug === slug)!;@@ -233,9 +265,13 @@ export async function submitFactFenceAdoption(engine: BrainEngine, authority: Maasync function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {const p = row.intent!;const facts = p.facts as FactFenceAssignment[];- if (p.source_incarnation !== row.source_incarnation) throw new OperationError('source_changed', 'The fact adoption source changed.');+ if (p.source_incarnation !== row.source_incarnation) throw opError('source_changed', 'The fact adoption source changed.',+ `Source ${row.source_id} was replaced after fact-fence adoption request ${row.id} for ${row.slug} was accepted, so nothing was published. Read the receipt with gbrain write-request -- ${row.id}; the next fact backfill run plans against the current source.`,+ { fix: receiptFix(row) });if (new Set(facts.map(f => f.id)).size !== facts.length || new Set(facts.map(f => f.row_num)).size !== facts.length) {- throw new OperationError('invalid_params', 'A fact adoption assigns one fact or fence position twice.');+ throw opError('invalid_params', 'A fact adoption assigns one fact or fence position twice.',+ `Fact-fence adoption request ${row.id} for ${row.slug} in ${row.source_id} was refused before publication; nothing changed. The plan itself is malformed, so report the request ID to the user rather than running the same backfill again.`,+ { fix: receiptFix(row) });}const fence = new Map(parseFactsFence(p.content as string).facts.map(f => [f.rowNum, f]));const check = async (db: BrainEngine, lock: boolean) => {@@ -244,16 +280,22 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,const fact = current.find(f => f.id === assignment.id);if (!fact || digest(fact.value) !== assignment.hash || fact.value.entity_slug !== row.slug|| fact.value.row_num !== null || fact.value.expired_at !== null) {- throw new OperationError('revision_conflict', 'A legacy fact changed, was already adopted or moved to another owner before adoption.');+ throw opError('revision_conflict', 'A legacy fact changed, was already adopted or moved to another owner before adoption.',+ `A legacy fact on ${row.slug} in ${row.source_id} changed before fact-fence adoption request ${row.id} published; nothing was written. The next fact backfill run re-reads the facts and plans a fresh request.`,+ { fix: receiptFix(row) });}const cell = fence.get(assignment.row_num);if (!cell?.active || cell.claim !== fact.value.fact || cell.visibility !== fact.value.visibility) {- throw new OperationError('invalid_params', 'The adopted fence row does not render its legacy fact.');+ throw opError('invalid_params', 'The adopted fence row does not render its legacy fact.',+ `Fact-fence adoption request ${row.id} for ${row.slug} in ${row.source_id} was refused before publication; nothing changed. The rendered fence does not match the facts it adopts, so report the request ID to the user rather than running the same backfill again.`,+ { fix: receiptFix(row) });}}const occupied = await db.executeRaw(`SELECT id FROM facts WHERE source_id=$1 AND source_markdown_slug=$2AND row_num=ANY($3::integer[])${lock ? ' FOR UPDATE' : ''}`, [row.source_id, row.slug, facts.map(f => f.row_num)]);- if (occupied.length) throw new OperationError('revision_conflict', 'An adopted fence position is already owned by another fact.');+ if (occupied.length) throw opError('revision_conflict', 'An adopted fence position is already owned by another fact.',+ `Another fact took a fence row on ${row.slug} in ${row.source_id} before adoption request ${row.id} published; nothing was written. The next fact backfill run plans from the current fence.`,+ { fix: receiptFix(row) });};await check(engine, false);const prepared = await preparePageMutation(engine, { ...row, intent: { kind: 'managed_maintenance_page', content: p.content,@@ -265,7 +307,9 @@ async function prepareFactFenceAdoption(engine: BrainEngine, row: WriteRequest,FROM jsonb_to_recordset($3::text::jsonb) AS a(id integer,row_num integer)WHERE f.source_id=$1 AND f.id=a.id AND f.row_num IS NULL RETURNING f.id`,[row.source_id, row.slug, JSON.stringify(facts.map(({ id, row_num }) => ({ id, row_num })))]);- if (adopted.length !== facts.length) throw new OperationError('revision_conflict', 'A legacy fact was adopted by another run.');+ if (adopted.length !== facts.length) throw opError('revision_conflict', 'A legacy fact was adopted by another run.',+ `Another run adopted a legacy fact on ${row.slug} in ${row.source_id} while request ${row.id} was publishing, so its transaction rolled back. Read the receipt with gbrain write-request -- ${row.id} for the final state before planning any new adoption.`,+ { fix: receiptFix(row) });const outcome = await applyPreservingTakeResolutions(tx, row.page_id, prepared);return { ...outcome, facts_adopted: facts.length };} };@@ -288,7 +332,7 @@ export async function applyPreservingTakeResolutions(tx: BrainEngine, pageId: nu}export async function prepareMaintenanceMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {- if (row.authority.remote) throw new OperationError('permission_denied', 'Remote maintenance publication is not supported.');+ if (row.authority.remote) throw trustedCliRequired('Remote maintenance publication is not supported.');if (row.intent?.kind === 'managed_maintenance_restore_extractor_facts') return (await import('../repair/extractor-facts.ts')).prepareExtractorFactsRestore(engine, row);if (row.intent?.kind === 'managed_maintenance_expire_captured_facts') return (await import('../repair/captured-facts.ts')).prepareCapturedFactsExpiry(engine, row);if (row.intent?.kind === 'managed_maintenance_timeline_extract') return (await import('../../commands/extract-timeline-db.ts')).prepareTimelineExtract(engine, row);@@ -312,7 +356,9 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Writeif (row.intent?.kind === 'managed_maintenance_phantom_merge') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomMerge(engine, row, config);if (row.intent?.kind === 'managed_maintenance_phantom_delete') return (await import('../cycle/phantom-redirect-managed.ts')).preparePhantomDelete(engine, row, config);if (row.intent?.kind === 'managed_maintenance_retire_stale_atoms') return (await import('../repair/stale-atoms.ts')).prepareStaleAtomRetirement(engine, row, config);- if (row.intent?.kind !== 'managed_maintenance_consolidate') throw new OperationError('invalid_params', 'Unsupported maintenance request.');+ if (row.intent?.kind !== 'managed_maintenance_consolidate') throw opError('invalid_params', 'Unsupported maintenance request.',+ `Request ${row.id} for ${row.slug} in ${row.source_id} carries a maintenance kind this gbrain version does not publish (likely queued by a newer release); nothing changed. Upgrade gbrain on the brain host, and read the receipt before submitting anything new.`,+ { fix: receiptFix(row) });const p = row.intent;const facts = p.facts as FactSnapshot[];const pages = p.pages as EvidencePage[];@@ -322,7 +368,9 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Writereturn { observedRevision: p.expected_revision as string, noop: true, validate: async tx => {const [current] = await tx.executeRaw<{ active: boolean; resolved_at: unknown }>('SELECT active,resolved_at FROM takes WHERE id=$1 AND page_id=$2', [existing.id, row.page_id]);- if (!current || current.active && !current.resolved_at) throw new OperationError('revision_conflict', 'The retired take changed during preparation.');+ if (!current || current.active && !current.resolved_at) throw opError('revision_conflict', 'The retired take changed during preparation.',+ `The take for this consolidation on ${row.slug} in ${row.source_id} was reactivated while request ${row.id} was being prepared; nothing was written. The next consolidate run re-reads the take.`,+ { fix: receiptFix(row) });}, apply: async () => ({ status: 'skipped', reason: 'retired_take', noop: true,facts_consolidated: 0, takes_written: 0, take_id: Number(existing.id) }) };}@@ -335,19 +383,25 @@ export async function prepareMaintenanceMutation(engine: BrainEngine, row: Writefor (const page of pages) {const current = await tx.readPageSnapshot(page.slug, { sourceId: row.source_id, excludePrivate: true });if (!current || current.page.id !== page.id || current.revision !== page.revision) {- throw new OperationError('revision_conflict', 'A consolidation evidence page changed.');+ throw opError('revision_conflict', 'A consolidation evidence page changed.',+ `Evidence page ${page.slug} in ${row.source_id} changed while consolidation request ${row.id} was being prepared; nothing was written. The next consolidate run re-clusters from the current pages.`,+ { fix: receiptFix(row) });}}const current = await readFacts(tx, row.source_id, facts.map(f => f.id), true);if (digest(current) !== digest(facts) || current.some(f => f.value.visibility !== 'world' || f.value.expired_at || f.value.consolidated_at ||f.value.valid_until && Date.parse(String(f.value.valid_until)) <= Date.now())) {- throw new OperationError('revision_conflict', 'The consolidation evidence changed.');+ throw opError('revision_conflict', 'The consolidation evidence changed.',+ `Facts behind consolidation request ${row.id} on ${row.slug} in ${row.source_id} changed or expired before it published; nothing was written. The next consolidate run re-clusters the current facts.`,+ { fix: receiptFix(row) });}}, apply: async tx => {const outcome = await prepared.apply(tx);const [take] = await tx.executeRaw<{ id: number }>("SELECT id FROM takes WHERE page_id=$1 AND claim=$2 AND kind='fact' AND holder='self' ORDER BY id LIMIT 1", [row.page_id, p.claim]);- if (!take) throw new OperationError('storage_error', 'The consolidated take did not commit.');+ if (!take) throw opError('storage_error', 'The consolidated take did not commit.',+ `Consolidation request ${row.id} on ${row.slug} in ${row.source_id} did not find its take inside the publication transaction, so the transaction rolled back. Read the receipt with gbrain write-request -- ${row.id} and check the owner with gbrain sources writer status --source ${row.source_id} --json before any new consolidation.`,+ { fix: receiptFix(row) });for (const fact of facts) await tx.consolidateFact(fact.id, take.id);const chronological = [...facts].sort((a, b) => Date.parse(String(a.value.valid_from)) - Date.parse(String(b.value.valid_from)) || a.id - b.id);for (let i = 0; i < chronological.length - 1; i++) {diff --git a/src/core/persistence/reconcile-audit.ts b/src/core/persistence/reconcile-audit.tsindex 162060af04..18e3a68d42 100644--- a/src/core/persistence/reconcile-audit.ts+++ b/src/core/persistence/reconcile-audit.ts@@ -1,7 +1,7 @@import { statSync } from 'node:fs';import { join } from 'node:path';import type { BrainEngine } from '../engine.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { OperationError, opError, type OperationContext } from '../ops/contract.ts';import { isValidSourceId } from '../source-id.ts';import { validateSlug } from '../utils.ts';import { resolveSourceLocalFilePath } from '../markdown.ts';@@ -11,7 +11,7 @@ import { submissionAuthority } from './authority.ts';import { currentVerifiedLocalWriter, existingLocalHostId, readLocalWriter, verifyLocalWriter } from './identity.ts';import { getWorktreeBinding } from './ownership.ts';import { prepareFileTarget } from './page-prepare.ts';-import { trustedCliRequired } from '../ops/op-fix.ts';+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';export interface ReconcileAuditReport extends Record<string, unknown> {source_id: string;@@ -28,16 +28,24 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: stringoptions: { limit?: number; after?: string } = {}): Promise<ReconcileAuditReport> {const limit = options.limit ?? 25;if (!isValidSourceId(sourceId) || !Number.isInteger(limit) || limit < 1 || limit > 100) {- throw new OperationError('invalid_params', 'Audit requires an explicit source and a limit from 1 to 100.');+ throw opError('invalid_params', 'Audit requires an explicit source and a limit from 1 to 100.',+ 'Pass one registered source ID and a limit from 1 to 100 (default 25); the command in fix lists source IDs.',+ { fix: readFix('Lists the registered sources and their IDs.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });}if (options.after !== undefined) {- if (typeof options.after !== 'string') throw new OperationError('invalid_params', 'The audit cursor must be a page slug.');- try { validateSlug(options.after); } catch { throw new OperationError('invalid_params', 'The audit cursor must be a valid page slug.'); }+ if (typeof options.after !== 'string') throw opError('invalid_params', 'The audit cursor must be a page slug.',+ "Pass --after exactly as the previous audit's next_after slug, or omit it to start from the first page.");+ try { validateSlug(options.after); } catch {+ throw opError('invalid_params', 'The audit cursor must be a valid page slug.',+ "Pass --after exactly as the previous audit's next_after slug, or omit it to start from the first page.");+ }}const hostId = existingLocalHostId();const binding = hostId ? await getWorktreeBinding(engine, sourceId, hostId) : null;if (!binding?.local_path || binding.owner_host_id !== hostId || binding.state !== 'active') {- throw new OperationError('owner_unavailable', 'Read-only drift auditing must run on the active canonical owner.');+ throw opError('owner_unavailable', 'Read-only drift auditing must run on the active canonical owner.',+ `Run the audit of '${sourceId}' on the host that owns its checkout; the command in fix names it. Do not claim or transfer ownership just to audit.`,+ { fix: readFix('Shows the canonical binding and owner host of this source.', { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });}const root = join(binding.local_path, binding.relative_path);const rows = await engine.executeRaw<{ slug: string; bytes: number }>(`SELECT slug,@@ -50,20 +58,25 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: stringfor (const candidate of rows.slice(0, limit)) {report.inspected++;try {- if (Number(candidate.bytes) > 5_000_000) throw new OperationError('invalid_params', 'The page exceeds the bounded audit size.');+ if (Number(candidate.bytes) > 5_000_000) throw opError('invalid_params', 'The page exceeds the bounded audit size.',+ `Page ${candidate.slug} is over 5 MB in the database, so the audit skipped it; inspect it on the canonical host.`);const snapshot = await engine.readPageSnapshot(candidate.slug, { sourceId });- if (!snapshot || snapshot.sourceIncarnation !== binding.source_incarnation) throw new OperationError('page_identity_changed', 'The page identity changed during the audit.');+ if (!snapshot || snapshot.sourceIncarnation !== binding.source_incarnation) throw opError('page_identity_changed', 'The page identity changed during the audit.',+ `Page ${candidate.slug} was deleted or its source replaced while the audit ran; run the audit again from this slug.`);const capturedPath = recordedPathFromFileUri(snapshot.page.source_uri, root);const path = resolveSourceLocalFilePath(root, snapshot.page.source_path, candidate.slug, mode)?? (capturedPath ? join(root, capturedPath) : join(root, `${candidate.slug}.md`));- if (!isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The canonical path is not confined.');+ if (!isWriteTargetContained(path, root)) throw opError('source_changed', 'The canonical path is not confined.',+ `Page ${candidate.slug} records a file outside the source checkout; preview it with sources reconcile before any write.`);let size = 0;try {const stat = statSync(path);- if (!stat.isFile()) throw new OperationError('invalid_params', 'The canonical target is not a regular file.');+ if (!stat.isFile()) throw opError('invalid_params', 'The canonical target is not a regular file.',+ `The file for page ${candidate.slug} is not a regular file; inspect it on the canonical host.`);size = stat.size;} catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }- if (size > 5_000_000) throw new OperationError('invalid_params', 'The file exceeds the bounded audit size.');+ if (size > 5_000_000) throw opError('invalid_params', 'The file exceeds the bounded audit size.',+ `The file for page ${candidate.slug} is over 5 MB, so the audit skipped it; inspect it on the canonical host.`);await prepareFileTarget(engine, { source_id: sourceId, worktree_id: binding.worktree_id, slug: candidate.slug }, snapshot, null, hostId!);} catch (error) {const reason = error instanceof OperationError ? error.code : 'storage_error';@@ -80,17 +93,22 @@ export async function auditCanonicalSource(engine: BrainEngine, sourceId: stringexport async function runReconcileAudit(engine: BrainEngine, params: Record<string, unknown>): Promise<ReconcileAuditReport> {if (Object.keys(params).some(key => !['source_id', 'limit', 'after'].includes(key)) || !isValidSourceId(params.source_id)) {- throw new OperationError('invalid_params', 'Audit accepts only source_id, limit, and after.');+ throw opError('invalid_params', 'Audit accepts only source_id, limit, and after.',+ 'Pass a registered source_id, and optionally limit (1 to 100) and after (the previous next_after slug), with no other fields.');}const writer = currentVerifiedLocalWriter() ?? await verifyLocalWriter(engine, await readLocalWriter(engine, 'cli'));if (writer.remote || writer.principal.kind !== 'local_cli' || writer.grant.slugPrefixes !== null) {throw trustedCliRequired('A whole-source audit requires the existing trusted CLI grant without a slug-prefix restriction.');}if (!writer.grant.sourceIds.includes('*') && !writer.grant.sourceIds.includes(params.source_id)) {- throw new OperationError('permission_denied', 'The current CLI grant excludes this source.');+ throw opError('permission_denied', 'The current CLI grant excludes this source.',+ `The CLI writer registration does not cover source '${params.source_id}'. Review its grant with the command in fix; widening it is the user's decision.`,+ { fix: readFix('Shows the CLI writer registration and the sources it grants.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });}const [source] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1 AND NOT archived', [params.source_id]);- if (!source) throw new OperationError('source_changed', 'The selected source is unavailable.');+ if (!source) throw opError('source_changed', 'The selected source is unavailable.',+ `Source '${params.source_id}' is missing or archived. Check it with the command in fix, and restore an archived source before auditing it.`,+ { fix: readFix('Lists registered sources, archived ones included.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });await submissionAuthority({ engine, remote: false, sourceId: params.source_id } as OperationContext,'put_page', params.source_id, source.incarnation, '__reconciliation_audit__');const report = await auditCanonicalSource(engine, params.source_id, { limit: params.limit as number | undefined, after: params.after as string | undefined });diff --git a/src/core/persistence/reconcile-backup.ts b/src/core/persistence/reconcile-backup.tsindex 2385447e1d..471a1e6bd4 100644--- a/src/core/persistence/reconcile-backup.ts+++ b/src/core/persistence/reconcile-backup.ts@@ -4,7 +4,9 @@ import { dirname, isAbsolute, join } from 'node:path';import type { BrainEngine } from '../engine.ts';import { configDir } from '../config.ts';import { flushDirectory } from '../fs-durable.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 { canonicalFilesystemPath } from './root-registry.ts';import { containsPath } from './ownership.ts';import { acquireNativeLock } from './native-lock.ts';@@ -19,29 +21,36 @@ import { authorizeStoredRequest } from './authority.ts';const backupPattern = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}\.[a-f0-9]{64}\.json$/;const backupReference = (brain: string, principal: Principal, requestId: string) => `${requestId}.${digest({ brain, principal, requestId })}.json`;const backupDirectory = () => join(canonicalFilesystemPath(configDir()), 'reconciliation-previews');+const receiptFix = (requestId: string): Action => readFix('The receipt shows whether this reconcile request is still pending, recovering or terminal.',+ { argv: ['gbrain', 'write-request', '--', requestId] });const privatePermissions = (stat: Stats) => process.platform === 'win32' ||(stat.mode & 0o077) === 0 && (typeof process.getuid !== 'function' || stat.uid === process.getuid());export async function assertReconcileOutputPath(engine: BrainEngine, sourceId: string, path: string): Promise<void> {- if (!isAbsolute(path) || path.includes('\0')) throw new OperationError('invalid_params', 'The private preview output must be an absolute local path.');+ if (!isAbsolute(path) || path.includes('\0')) throw opError('invalid_params', 'The private preview output must be an absolute local path.',+ 'Pass the preview output as an absolute path to a new file outside every source checkout, then run the preview again.');const roots = await engine.executeRaw<{ local_path: string }>(`SELECT local_path FROM sources WHERE local_path IS NOT NULLUNION SELECT local_path FROM persistence_host_bindings WHERE local_path IS NOT NULL`);const resolved = canonicalFilesystemPath(path);if (roots.some(row => containsPath(canonicalFilesystemPath(row.local_path), resolved))) {- throw new OperationError('permission_denied', 'Private reconciliation artifacts must be stored outside every canonical source and worktree.');+ throw opError('permission_denied', 'Private reconciliation artifacts must be stored outside every canonical source and worktree.',+ `Nothing was written. Put the preview output outside every source checkout (the command in fix lists their paths); if no --out was given, the gbrain config directory itself sits inside a checkout and the user must move it.`,+ { fix: readFix('Lists every registered source with its local checkout path.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });}}function privateDirectory(path: string): void {if (!existsSync(path)) { mkdirSync(path, { mode: 0o700, recursive: true }); flushDirectory(dirname(path)); }const stat = lstatSync(path);if (!stat.isDirectory() || stat.isSymbolicLink() || !privatePermissions(stat)) {- throw new OperationError('permission_denied', 'The reconciliation backup directory must be private, owned, and free of symlinks.');+ throw opError('permission_denied', 'The reconciliation backup directory must be private, owned, and free of symlinks.',+ 'Nothing was changed. Ask the user to make reconciliation-previews under the gbrain config directory a real directory owned by them with mode 0700 (not a symlink), then run the same command again.');}}export async function assertReconcileSize(engine: BrainEngine, artifact: ReconcileArtifact): Promise<void> {const limits = await readJournalLimits(engine);if (jsonBytes(artifact) + 65536 > Math.min(PERSISTENCE_IPC_MAX_BYTES, limits.principalIntentBytes, limits.brainIntentBytes, limits.worktreeRecoveryBytes, limits.brainRecoveryBytes)) {- throw new OperationError('request_too_large', 'The complete reconciliation artifact exceeds the configured request/recovery capacity.');+ throw opError('request_too_large', 'The complete reconciliation artifact exceeds the configured request/recovery capacity.',+ `Nothing changed. The preview for ${artifact.preconditions.slug} in ${artifact.preconditions.source_id}, with both originals, is larger than the journal's request and recovery limits; tell the user the page needs a manual edit of its canonical file.`);}}export async function retainReconcileBackup(engine: BrainEngine, artifact: ReconcileArtifact, principal: Principal, requestId: string): Promise<string> {@@ -49,7 +58,8 @@ export async function retainReconcileBackup(engine: BrainEngine, artifact: Reconawait assertReconcileOutputPath(engine, artifact.preconditions.source_id, directory);privateDirectory(directory);const lock = await acquireNativeLock(join(directory, '.capacity.lock'), { timeoutMs: 5000 });- if (!lock) throw new OperationError('writer_lock_unavailable', 'Reconciliation backup capacity is busy.');+ if (!lock) throw opError('writer_lock_unavailable', 'Reconciliation backup capacity is busy.',+ `Another reconciliation holds the backup lock and nothing was admitted. Wait a few seconds, then run the same apply again with the same request_id (${requestId}).`);try {privateDirectory(directory);const limits = await readJournalLimits(engine);@@ -59,7 +69,8 @@ export async function retainReconcileBackup(engine: BrainEngine, artifact: Reconif (existsSync(path)) {const stat = lstatSync(path);if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat) || readFileSync(path, 'utf8') !== value) {- throw new OperationError('idempotency_conflict', 'A different or unsafe retained backup already owns this request ID.');+ throw opError('idempotency_conflict', 'A different or unsafe retained backup already owns this request ID.',+ `Request ID ${requestId} already has a retained backup for a different preview, so nothing was admitted. Apply this preview with a new request ID; reuse ${requestId} only with the exact preview it was first used with.`);}return reference;}@@ -67,7 +78,10 @@ export async function retainReconcileBackup(engine: BrainEngine, artifact: Reconfor (const name of readdirSync(directory)) {if (name === '.capacity.lock') continue;const stat = lstatSync(join(directory, name));- if (!stat.isFile() || stat.isSymbolicLink()) throw new OperationError('storage_error', 'Unexpected content in the private reconciliation backup directory.');+ if (!stat.isFile() || stat.isSymbolicLink()) {+ throw opError('storage_error', 'Unexpected content in the private reconciliation backup directory.',+ `Nothing was admitted. Ask the user to move the non-file entry out of reconciliation-previews under the gbrain config directory, then run the same apply again with the same request_id (${requestId}).`);+ }count++; bytes += stat.size;}if (count + 1 > limits.brainLifetimeIds || bytes + Buffer.byteLength(value) > limits.brainRecoveryBytes) throw capacityError('retained reconciliation backups');@@ -80,7 +94,8 @@ export async function retainReconcileBackup(engine: BrainEngine, artifact: Recon} finally { await lock.release(); }}export function verifyReconcileBackup(reference: string, artifact: ReconcileArtifact): void {- if (!backupPattern.test(reference)) throw new OperationError('storage_error', 'Invalid reconciliation backup reference.');+ if (!backupPattern.test(reference)) throw opError('storage_error', 'Invalid reconciliation backup reference.',+ 'This accepted reconcile request carries a malformed backup reference, so it was not published. Read its receipt with gbrain write-request and its request ID before making a fresh preview; do not resubmit it.');try {const directory = backupDirectory();privateDirectory(directory);@@ -88,7 +103,9 @@ export function verifyReconcileBackup(reference: string, artifact: ReconcileArtiif (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat) ||digest(JSON.parse(readFileSync(path, 'utf8')).preview) !== digest(artifact)) throw new Error('backup changed');} catch {- throw new OperationError('storage_error', 'The retained reconciliation preimages are missing or changed.');+ throw opError('storage_error', 'The retained reconciliation preimages are missing or changed.',+ `The private backup of the originals for request ${reference.slice(0, 36)} is missing or was edited, so the request was not published. Read its receipt with gbrain write-request -- ${reference.slice(0, 36)}; leave files under reconciliation-previews alone, and make a fresh preview with a new request ID if the page still needs reconciling.`,+ { fix: receiptFix(reference.slice(0, 36)) });}}@@ -113,7 +130,10 @@ export async function manageReconcileBackups(engine: BrainEngine, authority: Wriif (existsSync(path)) {privateDirectory(directory);const stat = lstatSync(path);- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat)) throw new OperationError('storage_error', 'A retained backup is not a private ordinary file.');+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat)) {+ throw opError('storage_error', 'A retained backup is not a private ordinary file.',+ `Nothing was changed. The backup for request ${row.request_id} is a link or readable by others; ask the user to restore it as a private regular file (mode 0600) before listing again.`);+ }bytes = stat.size;}backups.push({ backup_reference: reference, request_id: row.request_id, state: row.state, retained: bytes !== null, bytes,@@ -124,30 +144,41 @@ export async function manageReconcileBackups(engine: BrainEngine, authority: Wricapacity: { max_retained_bytes: limits.brainRecoveryBytes, max_retained_count: limits.brainLifetimeIds } };}const reference = params.backup_reference!;- if (!backupPattern.test(reference)) throw new OperationError('invalid_params', 'An exact private backup reference is required.');+ if (!backupPattern.test(reference)) throw opError('invalid_params', 'An exact private backup reference is required.',+ `Pass the exact backup_reference that a --backups listing of ${slug} in ${authority.sourceId} returned.`);const requestId = reference.slice(0, 36);- if (reference !== backupReference(brain.brain_id, principal, requestId)) throw new OperationError('permission_denied', 'The backup reference belongs to another caller or brain.');+ if (reference !== backupReference(brain.brain_id, principal, requestId)) throw opError('permission_denied', 'The backup reference belongs to another caller or brain.',+ `Use a backup_reference from a --backups listing of ${slug} in ${authority.sourceId} made by this CLI registration on this brain; nothing was removed.`);await assertReconcileOutputPath(engine, authority.sourceId, directory);privateDirectory(directory);const lock = await acquireNativeLock(join(directory, '.capacity.lock'), { timeoutMs: 5000 });- if (!lock) throw new OperationError('writer_lock_unavailable', 'Reconciliation backup capacity is busy.');+ if (!lock) throw opError('writer_lock_unavailable', 'Reconciliation backup capacity is busy.',+ 'Another reconciliation holds the backup lock and nothing was removed. Wait a few seconds, then run the same removal again.');try {return await engine.transaction(async tx => {const [row] = await tx.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2AND source_id=$3 AND slug=$4 AND request_id=$5::uuid AND operation='put_page' FOR UPDATE`,[principal.kind, principal.id, authority.sourceId, slug, requestId]);- if (!row) throw new OperationError('permission_denied', 'No caller-bound accepted request authorizes removal of this backup.');+ if (!row) throw opError('permission_denied', 'No caller-bound accepted request authorizes removal of this backup.',+ `Request ${requestId} is not an apply this CLI registration made for ${slug} in ${authority.sourceId}, so nothing was removed. List the removable backups of this page with --backups.`);await authorizeStoredRequest(tx, row, true);- if (!isTerminal(row) || row.recovery !== null) throw new OperationError('recovery_required', 'The backup still protects a nonterminal or recovering request.');+ if (!isTerminal(row) || row.recovery !== null) throw opError('recovery_required', 'The backup still protects a nonterminal or recovering request.',+ `Request ${requestId} is still pending or recovering and its backup protects the originals, so nothing was removed. Read the receipt with gbrain write-request -- ${requestId}; remove the backup only once it is terminal.`,+ { fix: receiptFix(requestId) });const path = join(directory, reference);if (!existsSync(path)) return { removed: false, backup_reference: reference, request_id: row.request_id };privateDirectory(directory);const stat = lstatSync(path);- if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat)) throw new OperationError('storage_error', 'The backup is not a private ordinary file.');+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || !privatePermissions(stat)) {+ throw opError('storage_error', 'The backup is not a private ordinary file.',+ `Nothing was removed. The backup for request ${requestId} is a link or readable by others; ask the user to inspect it. The receipt and page are unaffected.`);+ }const stored = JSON.parse(readFileSync(path, 'utf8')) as { preview: ReconcileArtifact; principal: Principal; request_id: string };if (stored.request_id !== row.request_id || digest(stored.principal) !== digest(principal) ||intentDigest({ operation: 'put_page', sourceId: row.source_id, slug: row.slug, callerIntent: { kind: 'canonical_reconcile', preview: stored.preview } }) !== row.digest) {- throw new OperationError('storage_error', 'The retained backup does not match its immutable request.');+ throw opError('storage_error', 'The retained backup does not match its immutable request.',+ `Nothing was removed. The backup file for request ${requestId} does not match the request it protects; keep it, tell the user, and read the receipt with gbrain write-request -- ${requestId}.`,+ { fix: receiptFix(requestId) });}unlinkSync(path); flushDirectory(directory);return { removed: true, backup_reference: reference, request_id: row.request_id, bytes: stat.size };diff --git a/src/core/persistence/reconcile-merge.ts b/src/core/persistence/reconcile-merge.tsindex 7a992516b8..f89f31a6fb 100644--- a/src/core/persistence/reconcile-merge.ts+++ b/src/core/persistence/reconcile-merge.ts@@ -1,6 +1,7 @@import type { ParsedPage } from '../import-file.ts';import type { Page } from '../types.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { digest, stableJson } from './digest.ts';import { RECONCILE_SAFETY_KEYS } from './reconcile-safety.ts';@@ -22,7 +23,8 @@ function object(value: unknown): value is Record<string, unknown> { return valueexport function validateReconcileJson(value: unknown, allowDates = false): void {let nodes = 0;const visit = (item: unknown, depth: number) => {- if (++nodes > 100_000 || depth > 64) throw new OperationError('request_too_large', 'Reconciliation JSON exceeds the structural limit.');+ if (++nodes > 100_000 || depth > 64) throw opError('request_too_large', 'Reconciliation JSON exceeds the structural limit.',+ 'Keep reconciliation JSON under 100,000 values and 64 levels of nesting: pass the preview file written by --out unchanged, with only the decisions it needs.');if (allowDates && item instanceof Date && Number.isFinite(item.getTime())) return;if (item === null || typeof item === 'string' || typeof item === 'boolean' || typeof item === 'number' && Number.isFinite(item)) return;if (Array.isArray(item)) { for (const child of item) visit(child, depth + 1); return; }@@ -30,17 +32,20 @@ export function validateReconcileJson(value: unknown, allowDates = false): voidfor (const child of Object.values(item)) visit(child, depth + 1);return;}- throw new OperationError('invalid_params', 'Reconciliation values must be finite JSON data.');+ throw opError('invalid_params', 'Reconciliation values must be finite JSON data.',+ 'Use only JSON strings, finite numbers, booleans, null, arrays and plain objects in decisions and set_value values.');};visit(value, 0);}export function strictReconcileKeys(value: unknown, allowed: string[], required = allowed): asserts value is Record<string, unknown> {if (!object(value) || Object.keys(value).some(k => !allowed.includes(k)) || required.some(k => !Object.hasOwn(value, k))) {- throw new OperationError('invalid_params', 'Unsupported or missing reconciliation fields.');+ throw opError('invalid_params', 'Unsupported or missing reconciliation fields.',+ 'Pass the preview file written by --out unchanged, and give each decision only path, action and, for set_value, value.');}}function pointer(path: string): string[] {- if (!path.startsWith('/') || /~(?![01])/u.test(path)) throw new OperationError('invalid_params', 'Decisions require escaped JSON Pointer paths.');+ if (!path.startsWith('/') || /~(?![01])/u.test(path)) throw opError('invalid_params', 'Decisions require escaped JSON Pointer paths.',+ "Write each decision path as a JSON Pointer from the preview's conflict_paths (for example /frontmatter/title), escaping '~' as ~0 and '/' inside a key as ~1.");return path.slice(1).split('/').map(k => k.replace(/~1/g, '/').replace(/~0/g, '~'));}function escaped(key: string): string { return key.replace(/~/g, '~0').replace(/\//g, '~1'); }@@ -48,22 +53,29 @@ export function protectedReconcileKey(key: string): boolean {return protectedKeys.has(key);}export function reconcileDecisions(value: unknown): ReconcileDecision[] {- if (!Array.isArray(value) || value.length > 1000) throw new OperationError('invalid_params', 'decisions must be a bounded array.');+ if (!Array.isArray(value) || value.length > 1000) throw opError('invalid_params', 'decisions must be a bounded array.',+ 'Pass decisions as one JSON array of at most 1000 decision objects.');const decisions = value.map(item => {strictReconcileKeys(item, ['path', 'action', 'value'], ['path', 'action']);if (typeof item.path !== 'string' || !['take_file', 'take_database', 'set_value', 'delete'].includes(String(item.action)) ||- (item.action === 'set_value') !== Object.hasOwn(item, 'value')) throw new OperationError('invalid_params', 'Invalid reconciliation decision.');+ (item.action === 'set_value') !== Object.hasOwn(item, 'value')) {+ throw opError('invalid_params', 'Invalid reconciliation decision.',+ 'Give each decision a string path and an action of take_file, take_database, delete, or set_value with a value; only set_value carries a value.');+ }const parts = pointer(item.path);if (parts[0] === 'tags' || parts[0] === 'frontmatter' && (parts.length === 1 || protectedReconcileKey(parts[1]))) {- throw new OperationError('permission_denied', 'Reconciliation decisions cannot change protected metadata or remove tags.');+ throw opError('permission_denied', 'Reconciliation decisions cannot change protected metadata or remove tags.',+ 'Drop decisions on tags and on protected frontmatter keys (provenance, trust, source and scan fields): reconcile keeps those from the database and unions tags. Decide only the conflict_paths the preview lists.');}- if (item.action === 'delete' && parts[0] !== 'frontmatter') throw new OperationError('invalid_params', 'Only ordinary metadata fields support explicit deletion.');+ if (item.action === 'delete' && parts[0] !== 'frontmatter') throw opError('invalid_params', 'Only ordinary metadata fields support explicit deletion.',+ 'Use delete only on paths under /frontmatter; for title, type, compiled_truth or timeline choose take_file, take_database or set_value.');if (item.action === 'set_value') validateReconcileJson(item.value);return item as unknown as ReconcileDecision;}).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);for (let i = 0; i < decisions.length; i++) for (let j = 0; j < i; j++) {if (decisions[i].path === decisions[j].path || decisions[i].path.startsWith(`${decisions[j].path}/`) || decisions[j].path.startsWith(`${decisions[i].path}/`)) {- throw new OperationError('invalid_params', 'Duplicate or overlapping reconciliation decisions.');+ throw opError('invalid_params', 'Duplicate or overlapping reconciliation decisions.',+ 'Give each path exactly one decision, and do not decide both a field and a path inside it.');}}return decisions;@@ -73,7 +85,9 @@ export function mergeReconcile(file: ParsedPage, database: ParsedPage, decisionsconst chosen = new Map(reconcileDecisions(decisions).map(d => [d.path, d]));const extractionStatus = file.frontmatter.provenance === 'auto-extracted' || database.frontmatter.provenance === 'auto-extracted';if (extractionStatus && [...chosen.keys()].some(path => path === '/frontmatter/status' || path.startsWith('/frontmatter/status/'))) {- throw new OperationError('permission_denied', 'Extraction review status requires the scoped review workflow.');+ throw opError('permission_denied', 'Extraction review status requires the scoped review workflow.',+ "Drop the /frontmatter/status decision: an auto-extracted page's review status changes only through extraction review. The command in fix lists pending stubs; gbrain extraction-review promotes or rejects them.",+ { fix: readFix('Lists the unverified auto-extracted stubs awaiting review, with their slugs.', { argv: ['gbrain', 'extraction-pending'] }) });}const used = new Set<string>(), conflicts: ReconcileConflict[] = [], protectedPaths: string[] = [], scanPaths: string[] = [];const absent = Symbol('absent');@@ -90,7 +104,8 @@ export function mergeReconcile(file: ParsedPage, database: ParsedPage, decisionsif (decision.action === 'delete') return absent;if (decision.action === 'set_value') return decision.value;const selected = decision.action === 'take_file' ? left : right;- if (selected === absent) throw new OperationError('invalid_params', 'The chosen side has no value; use an explicit delete decision.');+ if (selected === absent) throw opError('invalid_params', 'The chosen side has no value; use an explicit delete decision.',+ `The ${decision.action === 'take_file' ? 'file' : 'database'} side has nothing at ${path}. Use delete for that path to drop it, or set_value with the value to keep.`);return selected;}if (left === absent) {@@ -113,9 +128,11 @@ export function mergeReconcile(file: ParsedPage, database: ParsedPage, decisions};const tags = [...new Set([...file.tags, ...database.tags])].sort();const result = merge({ ...file, tags }, { ...database, tags }, '') as ParsedPage;- if ([...chosen.keys()].some(path => !used.has(path))) throw new OperationError('invalid_params', 'A decision names an unknown field path.');+ if ([...chosen.keys()].some(path => !used.has(path))) throw opError('invalid_params', 'A decision names an unknown field path.',+ "Decide only paths the preview lists in conflict_paths (or fields present on either side); remove decisions whose path matches neither.");if (['title', 'type', 'compiled_truth', 'timeline'].some(key => typeof result[key as keyof ParsedPage] !== 'string') || !object(result.frontmatter)) {- throw new OperationError('invalid_params', 'Resolved content has invalid canonical field types.');+ throw opError('invalid_params', 'Resolved content has invalid canonical field types.',+ 'Keep title, type, compiled_truth and timeline as strings and frontmatter as an object in set_value decisions, then resolve the preview again.');}return { result, conflicts, protectedPaths, scanPaths };}diff --git a/src/core/persistence/reconcile-state.ts b/src/core/persistence/reconcile-state.tsindex 7a0763b8c8..c3cafd5542 100644--- a/src/core/persistence/reconcile-state.ts+++ b/src/core/persistence/reconcile-state.ts@@ -6,7 +6,8 @@ import { loadConfig, loadConfigWithEngine } from '../config.ts';import { loadOperatorLiterals } from '../content-sanity-literals.ts';import { parseMarkdown, resolveSourceLocalFilePath } from '../markdown.ts';import { parseDataFrontmatter } from '../data-frontmatter.ts';-import { OperationError } from '../ops/contract.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import type { PageSnapshot } from '../page-state/types.ts';import { isWriteTargetContained } from '../path-confine.ts';import { recordedPathFromFileUri, scannerSlugRootMode } from '../write-through.ts';@@ -75,7 +76,9 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,}const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });- if (!snapshot || snapshot.page.deleted_at) throw new OperationError('page_not_found', 'Reconciliation requires an existing live page; use the separate restore workflow for deleted pages.');+ if (!snapshot || snapshot.page.deleted_at) throw opError('page_not_found', 'Reconciliation requires an existing live page; use the separate restore workflow for deleted pages.',+ `Page ${slug} in '${sourceId}' is deleted or missing; nothing changed. If it was deleted by mistake, restore it (gbrain restore, within the 72-hour window) and then preview it again.`,+ { fix: readFix('Shows whether the page exists or is soft-deleted in this source.', { argv: ['gbrain', 'get', '--source', sourceId, '--include-deleted', '--', slug] }) });if (binding.source_incarnation !== snapshot.sourceIncarnation) staleReconcile('source binding incarnation');const [storedPage] = await engine.executeRaw<Record<string, unknown>>(`SELECT id,source_id,slug,type,title,compiled_truth,timeline,frontmatter,content_hash,source_path,source_kind,source_uri,ingested_via,ingested_at,knowledge_revision,deleted_at FROM pages WHERE id=$1 AND source_id=$2`, [snapshot.page.id, sourceId]);@@ -87,17 +90,23 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,database_only_reason: await isUnboundSourcePage(engine, sourceId, slug) ? 'unbound_source' : null }) ? slugDerivedOrigin(root, slug, mode) : null;const origin = derived ? 'slug_derived' : 'recorded';const path = recordedPath ?? derived?.path ?? null;- if (!path || !isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The page has no unambiguous confined recorded Markdown origin.');+ if (!path || !isWriteTargetContained(path, root)) throw opError('source_changed', 'The page has no unambiguous confined recorded Markdown origin.',+ `Page ${slug} in '${sourceId}' records no Markdown file inside the source checkout, so there is nothing to reconcile it against; nothing changed. Check its recorded source path with the command in fix.`,+ { fix: readFix('Shows the page and its recorded source path.', { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] }) });let size: number;try {const info = lstatSync(path);if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) throw new Error('not an ordinary file');size = info.size;- } catch { throw new OperationError('source_changed', 'The recorded canonical file is missing or is not an ordinary file; repair does not restore files.'); }+ } catch {+ throw opError('source_changed', 'The recorded canonical file is missing or is not an ordinary file; repair does not restore files.',+ `Nothing changed. Restore the canonical file of ${slug} in '${sourceId}' as a regular file (for example from git), then preview the page again.`);+ }const { readJournalLimits } = await import('./limits.ts');const limits = await readJournalLimits(engine);if (size > Math.min(limits.principalIntentBytes, limits.brainIntentBytes, limits.worktreeRecoveryBytes)) {- throw new OperationError('request_too_large', 'The canonical file exceeds reconciliation capacity.');+ throw opError('request_too_large', 'The canonical file exceeds reconciliation capacity.',+ `Nothing changed. The canonical file of ${slug} in '${sourceId}' is larger than the journal's request and recovery limits; tell the user the page needs a manual edit of that file.`);}const fileName = basename(path), uriName = pathToFileURL(path).pathname.split('/').pop()!;const candidates = await engine.executeRaw<{ slug: string; source_path: string | null; source_uri: string | null }>(@@ -116,19 +125,26 @@ export async function readReconcileState(engine: BrainEngine, sourceId: string,try { canonicalCandidate = realpathSync(candidatePath); }catch (error) {if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;- throw new OperationError('source_changed', 'A candidate canonical file origin could not be verified.');+ throw opError('source_changed', 'A candidate canonical file origin could not be verified.',+ `Nothing changed. Page ${candidate.slug} in '${sourceId}' records a file that could not be resolved; check that the source checkout is readable, then preview ${slug} again.`);}- if (canonicalCandidate === canonicalPath) throw new OperationError('source_changed', 'Several pages claim the recorded canonical file.');+ if (canonicalCandidate === canonicalPath) throw opError('source_changed', 'Several pages claim the recorded canonical file.',+ `Nothing changed. Pages ${slug} and ${candidate.slug} in '${sourceId}' both record the same file, so reconcile cannot tell which owns it; decide with the user which page owns the file before reconciling either.`);}const raw = readFileSync(path), text = raw.toString('utf8');- if (!Buffer.from(text).equals(raw)) throw new OperationError('invalid_params', 'The canonical file must contain valid UTF-8.');+ if (!Buffer.from(text).equals(raw)) throw opError('invalid_params', 'The canonical file must contain valid UTF-8.',+ `Nothing changed. Re-save the canonical file of ${slug} in '${sourceId}' as UTF-8, then preview the page again.`);try { parseDataFrontmatter(text); }- catch { throw new OperationError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.'); }+ catch {+ throw opError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.',+ `Nothing changed. Fix the frontmatter of the canonical file of ${slug} in '${sourceId}' (quote values containing ': ', close the --- block), then preview the page again.`);+ }// Preserve a terminal .md in the page key while parsing the canonical Markdown.const parsed = parseMarkdown(text, `${slug}.md`, { validate: true, expectedSlug: slug });const errors = parsed.errors?.filter(e => !['MISSING_OPEN', 'MISSING_CLOSE', 'EMPTY_FRONTMATTER'].includes(e.code)) ?? [];if (errors.length || parsed.errors?.some(e => e.code === 'MISSING_CLOSE') || parsed.slug !== slug) {- throw new OperationError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.');+ throw opError('invalid_params', 'Canonical file metadata cannot be parsed losslessly; repair its syntax before previewing.',+ `Nothing changed. Fix the frontmatter of the canonical file of ${slug} in '${sourceId}' (close the --- block, keep its slug), then preview the page again.`);}const pins: ReconcilePins = { brain_id: brain.brain_id, source_id: sourceId, source_incarnation: snapshot.sourceIncarnation, slug,page_id: snapshot.page.id, worktree_id: binding.worktree_id, binding_digest: digest({ binding, root, path: canonicalPath }), owner_epoch: String(binding.owner_epoch),@@ -163,12 +179,16 @@ export function validateReconcileArtifact(value: unknown): ReconcileArtifact {digest(value.result) !== value.result_digest || typeof value.preconditions.assessment_at !== 'string' ||!Number.isFinite(Date.parse(value.preconditions.assessment_at)) || !Number.isSafeInteger(value.preconditions.page_id) ||Object.entries(value.preconditions).some(([key, v]) => key !== 'page_id' && typeof v !== 'string')) {- throw new OperationError('invalid_params', 'Malformed or modified reconciliation artifact.');+ throw opError('invalid_params', 'Malformed or modified reconciliation artifact.',+ 'Pass the preview file exactly as reconcile wrote it with --out; change it only through --decisions. If it was edited, make a fresh preview.');}for (const key of ['brain_id', 'source_incarnation', 'worktree_id', 'revision']) requireUuid(value.preconditions[key] as string);requireUuid(value.preview_id as string);for (const key of ['binding_digest', 'raw_file_hash', 'policy_digest', 'withdrawals_digest']) {- if (!/^[a-f0-9]{64}$/.test(value.preconditions[key] as string)) throw new OperationError('invalid_params', 'Invalid reconciliation fingerprint.');+ if (!/^[a-f0-9]{64}$/.test(value.preconditions[key] as string)) {+ throw opError('invalid_params', 'Invalid reconciliation fingerprint.',+ 'Pass the preview file exactly as reconcile wrote it with --out; if it was edited, make a fresh preview.');+ }}for (const conflict of value.conflicts as unknown[]) strictReconcileKeys(conflict, ['path', 'file', 'database']);for (const withdrawal of value.preimages.database.withdrawals as unknown[]) strictReconcileKeys(withdrawal, ['visibility', 'fact_hash', 'withdrawn_at']);diff --git a/src/core/persistence/reconcile.ts b/src/core/persistence/reconcile.tsindex d894b9c529..edfd47679f 100644--- a/src/core/persistence/reconcile.ts+++ b/src/core/persistence/reconcile.ts@@ -1,7 +1,7 @@import { randomUUID } from 'node:crypto';import type { BrainEngine } from '../engine.ts';import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../config.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { OperationError, opError, type OperationContext } from '../ops/contract.ts';import { validatePageSlug, slugUnderBoundPrefixes } from '../ops/context.ts';import { isValidSourceId } from '../source-id.ts';import { submissionAuthority, authorizeStoredRequest } from './authority.ts';@@ -16,28 +16,38 @@ import { assertReconcileOutputPath, assertReconcileSize, manageReconcileBackups,import type { LocalGrant } from './identity.ts';import { isTerminal } from './model.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { trustedCliRequired } from '../ops/op-fix.ts';+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';+import type { Action } from '../agent-output.ts';export { assertReconcileOutputPath } from './reconcile-backup.ts';export type { ReconcileArtifact } from './reconcile-state.ts';+function grantFix(): Action {+ return readFix('Shows the CLI writer registration and its sources, operations and slug-prefix grant.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] });+}async function authorize(engine: BrainEngine, sourceId: unknown, slug: unknown) {const verified = currentVerifiedLocalWriter();if (!verified || verified.remote || verified.principal.kind !== 'local_cli') throw trustedCliRequired('Reconciliation requires a verified trusted local CLI caller.');- if (typeof sourceId !== 'string' || !isValidSourceId(sourceId) || typeof slug !== 'string' || !slug) throw new OperationError('invalid_params', 'One explicit source ID and page slug are required.');+ if (typeof sourceId !== 'string' || !isValidSourceId(sourceId) || typeof slug !== 'string' || !slug) throw opError('invalid_params', 'One explicit source ID and page slug are required.',+ 'Pass the source ID and the exact page slug as the first two arguments of gbrain sources reconcile.');validatePageSlug(slug);- if (/[?*]/.test(slug)) throw new OperationError('invalid_params', 'Reconciliation requires an exact page slug, not a pattern.');+ if (/[?*]/.test(slug)) throw opError('invalid_params', 'Reconciliation requires an exact page slug, not a pattern.',+ `Reconcile one page at a time by its exact slug; an --audit run for source ${sourceId} lists the pages that drifted.`);const permitted = (grant: LocalGrant) => (grant.sourceIds.includes('*') || grant.sourceIds.includes(sourceId)) &&grant.scopes.includes('write') && (grant.operations === null || grant.operations.includes('put_page')) &&(grant.slugPrefixes === null || slugUnderBoundPrefixes(grant.slugPrefixes, slug));- if (!permitted(verified.grant)) throw new OperationError('permission_denied', 'Reconciliation exceeds the original CLI grant.');+ if (!permitted(verified.grant)) throw opError('permission_denied', 'Reconciliation exceeds the original CLI grant.',+ `The CLI writer registration does not grant put_page on ${slug} in '${sourceId}'. Review its grant with the command in fix; widening it is the user's decision.`, { fix: grantFix() });const [writer] = await engine.executeRaw<{ grant_ceiling: LocalGrant; revoked_at: unknown; lane: string }>('SELECT grant_ceiling,revoked_at,lane FROM persistence_local_writers WHERE id=$1::uuid', [verified.principal.id]);if (!writer || writer.revoked_at !== null || writer.lane !== 'cli' || !permitted(writer.grant_ceiling)) {- throw new OperationError('permission_denied', 'Reconciliation exceeds the current CLI grant.');+ throw opError('permission_denied', 'Reconciliation exceeds the current CLI grant.',+ `The current CLI writer registration is revoked or no longer grants put_page on ${slug} in '${sourceId}'. Review it with the command in fix; widening or re-registering it is the user's decision.`, { fix: grantFix() });}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 explicit source is missing or archived.');+ if (!source || source.archived) throw opError('source_changed', 'The explicit source is missing or archived.',+ `Source '${sourceId}' is missing or archived. Check it with the command in fix, and restore an archived source before reconciling its pages.`,+ { fix: readFix('Lists registered sources, archived ones included.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });const authority = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext, 'put_page', sourceId, source.incarnation, slug);return { sourceId, slug, authority };}@@ -57,12 +67,15 @@ export async function runReconcilePreview(engine: BrainEngine, params: Record<ststrictReconcileKeys(params, ['source_id', 'slug', 'from', 'decisions', 'output_path'], ['source_id', 'slug']);const { sourceId, slug } = await authorize(engine, params.source_id, params.slug);if (params.output_path !== undefined) {- if (typeof params.output_path !== 'string') throw new OperationError('invalid_params', 'output_path must be an absolute private file path.');+ if (typeof params.output_path !== 'string') throw opError('invalid_params', 'output_path must be an absolute private file path.',+ 'Pass output_path (CLI: --out) as an absolute path to a new file outside every source checkout.');await assertReconcileOutputPath(engine, sourceId, params.output_path);}const from = params.from === undefined ? undefined : validateReconcileArtifact(params.from);- if (params.decisions !== undefined && !from) throw new OperationError('invalid_params', 'Decisions require the previous private preview artifact.');- if (from && (from.preconditions.source_id !== sourceId || from.preconditions.slug !== slug)) throw new OperationError('invalid_params', 'The previous preview names a different page.');+ if (params.decisions !== undefined && !from) throw opError('invalid_params', 'Decisions require the previous private preview artifact.',+ 'Pass the preview being resolved along with the decisions (CLI: --from with the preview file written by --out).');+ if (from && (from.preconditions.source_id !== sourceId || from.preconditions.slug !== slug)) throw opError('invalid_params', 'The previous preview names a different page.',+ `Use the preview made for ${slug} in '${sourceId}', or run the command with the source and slug that preview file names.`);const state = await readReconcileState(engine, sourceId, slug, from?.preconditions.assessment_at);if (from) assertPreimages(from, state);const decisions = reconcileDecisions(params.decisions ?? from?.decisions ?? []);@@ -87,7 +100,8 @@ export async function runReconcileApply(engine: BrainEngine, params: Record<striartifact.decisions = reconcileDecisions(artifact.decisions);const requestId = requireUuid(params.request_id as string);if (artifact.preconditions.source_id !== sourceId || artifact.preconditions.slug !== slug || artifact.status !== 'ready' || artifact.conflicts.length) {- throw new OperationError('invalid_params', 'Apply requires a ready preview for this exact source and page.');+ throw opError('invalid_params', 'Apply requires a ready preview for this exact source and page.',+ `Nothing was submitted. Resolve every conflict first (preview with --from and --decisions until status is ready), then apply that resolved preview for ${slug} in '${sourceId}'.`);}const callerIntent = { kind: 'canonical_reconcile', preview: artifact };const expectedDigest = intentDigest({ operation: 'put_page', sourceId, slug, callerIntent });@@ -135,7 +149,8 @@ export async function runReconcileBackups(engine: BrainEngine, params: Record<st(typeof params.backup_reference !== 'string' || params.after !== undefined || params.limit !== undefined) ||params.action === 'list' && params.backup_reference !== undefined || params.limit !== undefined &&(!Number.isSafeInteger(params.limit) || Number(params.limit) < 1 || Number(params.limit) > 100)) {- throw new OperationError('invalid_params', 'Invalid exact-page backup administration parameters.');+ throw opError('invalid_params', 'Invalid exact-page backup administration parameters.',+ 'List backups with --backups (optional --limit 1 to 100 and --after cursor), or remove one with --remove-backup and its exact reference and no other options.');}try {return await manageReconcileBackups(engine, authority, slug, { action: params.action as 'list' | 'remove',diff --git a/src/core/persistence/source-lifecycle.ts b/src/core/persistence/source-lifecycle.tsindex e498aefe7d..4e9f992400 100644--- a/src/core/persistence/source-lifecycle.ts+++ b/src/core/persistence/source-lifecycle.ts@@ -3,7 +3,9 @@ import { randomUUID } from 'node:crypto';import { existsSync, mkdirSync, realpathSync, statSync } from 'node:fs';import { dirname, isAbsolute, join, relative, resolve, sep } 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 { catalogueError } from '../error-catalogue.ts';import { isValidSourceId } from '../source-id.ts';import { EXPIRED_ARCHIVE_SQL } from '../source-delete.ts';@@ -38,10 +40,20 @@ export interface SourceLifecycleInput {}interface SourceState {id:string;incarnation:string;archived:boolean;local_path:string|null;config:Record<string,unknown>;name:string;last_commit:string|null;}+function sourcesListFix():Action{+ return readFix('Lists every registered source (archived ones included) with its ID and local path.',{argv:['gbrain','sources','list','--json']});+}+function ownerStatusFix(sourceId:string):Action{+ return readFix('Shows the canonical binding, owner host, incarnation and any pending recovery; read it before deciding on a topology change.',+ {argv:['gbrain','sources','writer','status','--source',sourceId,'--json']});+}+function localRoot(path:string,create=false):{source:string;worktree:string}{- if(!isAbsolute(path)||path.includes('\0')) throw new OperationError('invalid_params','Source path must be an absolute directory on this host.');+ if(!isAbsolute(path)||path.includes('\0')) throw opError('invalid_params','Source path must be an absolute directory on this host.',+ 'Pass the source directory as an absolute path on the brain host, then rerun the command; nothing was changed.');const source=create?canonicalFilesystemPath(resolve(path)):realpathSync(resolve(path));- if(existsSync(source)&&!statSync(source).isDirectory()) throw new OperationError('invalid_params','Source path must be a directory.');+ if(existsSync(source)&&!statSync(source).isDirectory()) throw opError('invalid_params','Source path must be a directory.',+ 'The path names a file. Pass the directory that holds the source content, then rerun the command; nothing was changed.');let worktree=source;let ancestor=source;while(!existsSync(ancestor))ancestor=dirname(ancestor);try{worktree=realpathSync(discoverGitRoot(ancestor));}catch{/* directory source */}@@ -53,11 +65,15 @@ export async function installTopologyBinding(tx:BrainEngine,sourceId:string,incaFROM persistence_source_bindings b JOIN persistence_host_bindings h ON h.worktree_id=b.worktree_id AND h.host_id=$1::uuidWHERE b.source_id<>$2`,[localHostId(),sourceId]);const sourcePath=nativeFilesystemPath(root.source);- if(others.some(other=>{const path=nativeFilesystemPath(join(other.local_path,other.relative_path));return containsPath(path,sourcePath)||containsPath(sourcePath,path);}))- throw new OperationError('overlapping_path','Sources cannot claim overlapping canonical directories.');+ const overlap=others.find(other=>{const path=nativeFilesystemPath(join(other.local_path,other.relative_path));return containsPath(path,sourcePath)||containsPath(sourcePath,path);});+ if(overlap) throw opError('overlapping_path','Sources cannot claim overlapping canonical directories.',+ `Source '${sourceId}' would nest inside or around source '${overlap.source_id}'. Choose a directory outside that source's checkout; nothing was changed.`,+ {fix:ownerStatusFix(overlap.source_id)});const compatible=bindings.find(binding=>binding.local_path && containsPath(binding.local_path,root.worktree));const overlapping=bindings.find(binding=>binding.local_path && containsPath(root.worktree,binding.local_path));- if(overlapping&&!compatible) throw new OperationError('topology_change_required','The proposed root encloses another registered worktree. Rebind those sources explicitly first.');+ if(overlapping&&!compatible) throw opError('topology_change_required','The proposed root encloses another registered worktree. Rebind those sources explicitly first.',+ `The directory for '${sourceId}' contains the checkout of source '${overlapping.source_id}'. Move that source first with gbrain sources set-path ${overlapping.source_id} and its verified new directory (a topology change the user decides), or choose a directory that does not enclose it.`,+ {fix:ownerStatusFix(overlapping.source_id)});const worktree=compatible?.local_path??root.worktree;const physical=await claimPhysicalRoot(tx,worktree,{hostId:localHostId(),...(compatible?{worktreeId:compatible.worktree_id,coordinationPath:compatible.coordination_path!}:{})});@@ -92,30 +108,42 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLbefore(tx: BrainEngine): Promise<void>;after(tx: BrainEngine, incarnation: string): Promise<void>;}):Promise<Record<string,unknown>>{- if(!['add','claim','archive','restore','remove','purge','rebind','reclone'].includes(input.operation)) throw new OperationError('invalid_params','Unknown source lifecycle operation.');- for(const key of ['dryRun','refederate','confirmDestructive','createDirectory','expiredOnly','requireGitContent'] as const) if(input[key]!==undefined&&typeof input[key]!=='boolean') throw new OperationError('invalid_params',`${key} must be a boolean.`);- for(const key of ['path','name','expectedIncarnation','requestId','remoteUrl'] as const) if(input[key]!==undefined&&(typeof input[key]!=='string'||input[key]!.length>8192)) throw new OperationError('invalid_params',`${key} must be a bounded string.`);- if(input.config!==undefined&&(!input.config||Array.isArray(input.config)||typeof input.config!=='object'||Buffer.byteLength(JSON.stringify(input.config))>8192)) throw new OperationError('invalid_params','Source configuration must be a bounded object.');- if(!isValidSourceId(input.sourceId)) throw new OperationError('invalid_params','A valid explicit source ID is required.');+ if(!['add','claim','archive','restore','remove','purge','rebind','reclone'].includes(input.operation)) throw opError('invalid_params','Unknown source lifecycle operation.',+ 'Use one of: add, claim, archive, restore, remove, purge, rebind, reclone.');+ for(const key of ['dryRun','refederate','confirmDestructive','createDirectory','expiredOnly','requireGitContent'] as const) if(input[key]!==undefined&&typeof input[key]!=='boolean') throw opError('invalid_params',`${key} must be a boolean.`,`Pass ${key} as true or false, or omit it.`);+ for(const key of ['path','name','expectedIncarnation','requestId','remoteUrl'] as const) if(input[key]!==undefined&&(typeof input[key]!=='string'||input[key]!.length>8192)) throw opError('invalid_params',`${key} must be a bounded string.`,`Pass ${key} as a string of at most 8192 characters, or omit it.`);+ if(input.config!==undefined&&(!input.config||Array.isArray(input.config)||typeof input.config!=='object'||Buffer.byteLength(JSON.stringify(input.config))>8192)) throw opError('invalid_params','Source configuration must be a bounded object.',+ 'Pass the source configuration as one JSON object whose serialized form is at most 8192 bytes.');+ if(!isValidSourceId(input.sourceId)) throw opError('invalid_params','A valid explicit source ID is required.',+ 'Name the source by its ID: lowercase letters, digits and inner hyphens, at most 32 characters. The command in fix lists registered IDs.',{fix:sourcesListFix()});const requestId=input.requestId??randomUUID();if(!isWriteRequestId(requestId) || input.expectedIncarnation!==undefined&&!isWriteRequestId(input.expectedIncarnation))- throw new OperationError('invalid_params','request_id and expected_incarnation must be UUIDs.');- if(['remove','purge','archive'].includes(input.operation)&&input.sourceId==='default') throw new OperationError('invalid_params','The default source cannot be removed or archived.');+ throw opError('invalid_params','request_id and expected_incarnation must be UUIDs.',+ `Omit request_id to get a generated one or pass a UUID; expected_incarnation is the source_incarnation the command in fix reports for '${input.sourceId}'.`,+ {fix:ownerStatusFix(input.sourceId)});+ if(['remove','purge','archive'].includes(input.operation)&&input.sourceId==='default') throw opError('invalid_params','The default source cannot be removed or archived.',+ `The default source holds the brain's primary pages and always stays registered. ${input.operation} a named source instead; the command in fix lists them.`,{fix:sourcesListFix()});const principal=await topologyPrincipal(engine);const intent={...input,requestId:undefined,dryRun:undefined,automaticClaim:undefined};const prior=await priorTopologyChange(engine,principal,requestId,intent);if(prior) return topologyReceipt(prior);if(input.requireGitContent&&input.path&&(!isInsideGitRepo(input.path)||!hasTrackedContent(input.path)))- throw new OperationError('not_a_git_repo','The source path must contain committed Git content. Use --force to register an ordinary directory.');+ throw opError('not_a_git_repo','The source path must contain committed Git content. Use --force to register an ordinary directory.',+ `Commit the content in that directory with git first, or, if '${input.sourceId}' is meant to be a plain directory, rerun the add with --force; nothing was registered.`);if(input.operation==='reclone'||input.operation==='add'&&input.remoteUrl){const {runManagedSourceClone}=await import('./topology-clone.ts');return runManagedSourceClone(engine,input,principal,requestId,intent);}const root=input.path?localRoot(input.path,input.operation==='add'&&input.createDirectory):undefined;- if(['rebind','claim'].includes(input.operation)&&!root) throw new OperationError('invalid_params','The source operation requires its canonical path.');+ if(['rebind','claim'].includes(input.operation)&&!root) throw opError('invalid_params','The source operation requires its canonical path.',+ `Pass the canonical directory for '${input.sourceId}' (the one the command in fix reports, or its verified successor), then rerun the ${input.operation}.`,+ {fix:ownerStatusFix(input.sourceId)});const [before]=await engine.executeRaw<SourceState>('SELECT id,incarnation,archived,local_path,config,name,last_commit FROM sources WHERE id=$1',[input.sourceId]);- if(input.operation!=='add'&&!before) throw new OperationError('not_found','Source not found.');- if(input.expectedIncarnation&&input.expectedIncarnation!==before?.incarnation) throw new OperationError('source_changed','The source was replaced.');+ if(input.operation!=='add'&&!before) throw opError('not_found','Source not found.',+ `No source '${input.sourceId}' is registered on this brain. Check the ID against the command in fix, which lists archived sources too.`,{fix:sourcesListFix()});+ if(input.expectedIncarnation&&input.expectedIncarnation!==before?.incarnation) throw opError('source_changed','The source was replaced.',+ `Source '${input.sourceId}' was removed and re-added after expected_incarnation was read, so nothing was changed. Read its current incarnation with the command in fix and confirm the ${input.operation} still applies before running it again.`,+ {fix:ownerStatusFix(input.sourceId)});if(input.dryRun) return {dry_run:true,operation:input.operation,source_id:input.sourceId,source_incarnation:before?.incarnation??null,path:root?.source??before?.local_path??null};return withTopologyLocks(engine,input.sourceId,async bindings=>{// Hash canonical bytes while holding native exclusion, without a database@@ -141,20 +169,32 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLif(source)source.config=parseSourceConfig(source.config);const repeated=await priorTopologyChange(tx,principal,requestId,intent);if(repeated){await lockTopologyPrincipal(tx,principal);return topologyReceipt(repeated);}- if((source?.incarnation??null)!==(before?.incarnation??null)) throw new OperationError('source_changed','The source changed during lifecycle preparation.');+ if((source?.incarnation??null)!==(before?.incarnation??null)) throw opError('source_changed','The source changed during lifecycle preparation.',+ `Source '${input.sourceId}' was replaced while this ${input.operation} was being prepared; the transaction rolled back and nothing changed. Check its current state with the command in fix before running the ${input.operation} again.`,+ {fix:ownerStatusFix(input.sourceId)});if(admission) await admission.before(tx);- if(input.operation==='add'&&source&&(!root||source.local_path!==null)) throw new OperationError('source_id_taken','Source ID is already registered.');- if(input.operation==='purge'&&!input.expiredOnly&&!source?.archived) throw new OperationError('invalid_params','Only an archived source can be purged.');- if(['remove','purge'].includes(input.operation)&&!input.confirmDestructive) throw new OperationError('invalid_params','Source removal requires explicit destructive confirmation.');+ if(input.operation==='add'&&source&&(!root||source.local_path!==null)) throw opError('source_id_taken','Source ID is already registered.',+ `A source named '${input.sourceId}' already exists; nothing was added. Pick a different ID, or inspect the existing source with the command in fix.`,{fix:sourcesListFix()});+ if(input.operation==='purge'&&!input.expiredOnly&&!source?.archived) throw opError('invalid_params','Only an archived source can be purged.',+ `Source '${input.sourceId}' is active. Purge only follows an archive: gbrain sources archive ${input.sourceId} first, and confirm the purge with the user because it deletes the source's pages.`,{fix:sourcesListFix()});+ if(['remove','purge'].includes(input.operation)&&!input.confirmDestructive) throw opError('invalid_params','Source removal requires explicit destructive confirmation.',+ `Nothing was changed. ${input.operation} deletes the pages of source '${input.sourceId}' from the brain (its files stay on disk); ask the user, and only with their agreement run the command in fix.`,+ {fix:{argv:['gbrain','sources',input.operation,input.sourceId,'--confirm-destructive'],preview_argv:['gbrain','sources',input.operation,input.sourceId,'--dry-run'],+ consent:['destructive'],actor:'agent',requires_exclusive:false,+ why:`Deletes every page of source '${input.sourceId}' from the brain database; local storage is retained.`,+ user_message:`Removing source '${input.sourceId}' deletes its pages from the brain. Its files on disk stay. Do you want to go ahead?`}});if(missingCheckout) await assertRetirableWithoutCheckout(tx,input.sourceId,missingCheckout);const worktrees=bindings.map(binding=>binding.worktree_id);const currentBinding=bindings.find(binding=>binding.source_id===input.sourceId);const sameBinding=!!root&&!!currentBinding?.local_path&¤tBinding.local_path===root.worktree&&nativeFilesystemPath(join(currentBinding.local_path,currentBinding.relative_path))===nativeFilesystemPath(root.source);if(input.operation==='claim'&¤tBinding&&!sameBinding)- throw new OperationError('writer_transfer_required','The source already has a different canonical binding. Use rebind or verified ownership transfer.');+ throw opError('writer_transfer_required','The source already has a different canonical binding. Use rebind or verified ownership transfer.',+ `Source '${input.sourceId}' is already bound to another directory or host; nothing was claimed. Inspect the binding with the command in fix. Moving it (gbrain sources set-path on this host, or a writer transfer between hosts) is a topology change for the user to decide.`,+ {fix:ownerStatusFix(input.sourceId)});if(input.operation==='claim'&&!currentBinding&&source?.local_path&&realpathSync(source.local_path)!==root!.source)- throw new OperationError('source_changed','The requested claim path differs from the configured source root.');+ throw opError('source_changed','The requested claim path differs from the configured source root.',+ `Claim '${input.sourceId}' at the local_path the command in fix reports, or move it to the new directory with gbrain sources set-path ${input.sourceId}; nothing was claimed.`,{fix:sourcesListFix()});const expired=input.expiredOnly?await tx.executeRaw(`SELECT id FROM sources WHERE id=$1 AND ${EXPIRED_ARCHIVE_SQL}`,[input.sourceId]):null;const noop=expired?.length===0 || input.operation==='archive'&&source?.archived || input.operation==='restore'&&!source?.archived|| input.operation==='claim'&&!!currentBinding || input.operation==='rebind'&&sameBinding;@@ -170,11 +210,17 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLconst binding=bindings.find(value=>value.source_id===input.sourceId);if(!binding&&source?.local_path===null)throw new OperationError('writer_registration_required','This source has no canonical filesystem binding.',WRITER_INSPECTION_HINT);- if(!binding?.local_path || !existsSync(binding.local_path)) throw new OperationError('recovery_required','The original checkout is unavailable; recover its last verified manifest before rebinding.');- if(manifests.get(binding.local_path)!.digest!==manifests.get(root!.worktree)!.digest) throw new OperationError('writer_manifest_mismatch','The new checkout differs from the current canonical manifest, including deletions.');+ if(!binding?.local_path || !existsSync(binding.local_path)) throw opError('recovery_required','The original checkout is unavailable; recover its last verified manifest before rebinding.',+ `Nothing was rebound. Restore the original checkout of '${input.sourceId}' at the path the command in fix reports, with its last verified contents, then rerun set-path.`,+ {fix:ownerStatusFix(input.sourceId)});+ if(manifests.get(binding.local_path)!.digest!==manifests.get(root!.worktree)!.digest) throw opError('writer_manifest_mismatch','The new checkout differs from the current canonical manifest, including deletions.',+ `Nothing was rebound. Make the new directory an exact copy of the current checkout of '${input.sourceId}' (same files, nothing extra or missing), then rerun set-path.`,+ {fix:ownerStatusFix(input.sourceId)});}const ownedSourcePath=currentBinding?.local_path?join(currentBinding.local_path,currentBinding.relative_path):source?.local_path;- if(input.operation==='restore'&&ownedSourcePath&&!existsSync(ownedSourcePath)) throw new OperationError('recovery_required','Restore requires the verified canonical checkout. Reclone it before restoring the source.');+ if(input.operation==='restore'&&ownedSourcePath&&!existsSync(ownedSourcePath)) throw opError('recovery_required','Restore requires the verified canonical checkout. Reclone it before restoring the source.',+ `Nothing was restored. Recreate the checkout of '${input.sourceId}' with gbrain sources reclone ${input.sourceId}, then run gbrain sources restore ${input.sourceId} again.`,+ {fix:ownerStatusFix(input.sourceId)});await refreshManagedFilesystemRoots(tx,managedFilesystemDatastorePath(engine));await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");const result=await withCoordinatedWrite(tx,sources,async()=>{@@ -195,8 +241,10 @@ export async function runManagedSourceLifecycle(engine:BrainEngine,input:SourceLawait tx.executeRaw('UPDATE sources SET local_path=$2 WHERE id=$1',[input.sourceId,root!.source]);const id=await installTopologyBinding(tx,input.sourceId,incarnation,root!,bindings);if(!worktrees.includes(id))worktrees.push(id);}else{- const refs=await tx.executeRaw('SELECT client_id FROM oauth_clients WHERE source_id=$1 LIMIT 1',[input.sourceId]);- if(refs.length) throw new OperationError('source_referenced','OAuth clients still reference this source. Revoke and remove those registrations first.');+ const refs=await tx.executeRaw<{client_id:string}>('SELECT client_id FROM oauth_clients WHERE source_id=$1 LIMIT 1',[input.sourceId]);+ if(refs.length) throw opError('source_referenced','OAuth clients still reference this source. Revoke and remove those registrations first.',+ `Nothing was removed. OAuth client ${refs[0].client_id} (and possibly others) is bound to '${input.sourceId}'; list them with the command in fix and ask the user before revoking any, since revoking disconnects that client.`,+ {fix:readFix('Lists OAuth clients with the source each is bound to.',{argv:['gbrain','auth','clients','--json']})});const [impact]=await tx.executeRaw<{count:string}>('SELECT count(*)::text AS count FROM pages WHERE source_id=$1',[input.sourceId]);pagesDeleted=Number(impact.count);await tx.executeRaw('DELETE FROM sources WHERE id=$1 AND incarnation=$2::uuid',[input.sourceId,incarnation]);