Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): B10 backfill facts relink publication and Gmail attachment repair refusals

garrytanec446df7fc4a
diff --git a/src/core/facts/relink-publish.ts b/src/core/facts/relink-publish.ts
index 029ae843d4..d4164a08f7 100644
--- a/src/core/facts/relink-publish.ts
+++ b/src/core/facts/relink-publish.ts
@@ -23,7 +23,7 @@
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { formatFenceDate, parseFactsFence, upsertFactRow } from '../facts-fence.ts';
import { digest } from '../persistence/digest.ts';
@@ -148,11 +148,18 @@ const classKey = (c: Classified[]) => JSON.stringify(c.map(x => x.action === 'li
export async function prepareRelinkMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const intent = row.intent as unknown as RelinkIntent | null;
+ const rerun = `The next gbrain facts relink --source ${row.source_id} run re-plans from current state; preview it with --dry-run (no model calls, no writes).`;
+ const changed = (message: string) => opError('revision_conflict', message,
+ `${row.slug} or one of its facts changed while relink request ${row.request_id} was being prepared, so nothing was written. ${rerun}`);
if (row.operation !== RELINK_OPERATION || intent?.kind !== 'relink_facts' || !Array.isArray(intent.facts) || row.authority.remote) {
- throw new OperationError('permission_denied', 'Unsupported relink intent.');
+ throw opError('permission_denied', 'Unsupported relink intent.',
+ `Request ${row.request_id} is not a trusted local relink this gbrain version can publish, so nothing was written. Facts relink runs only from gbrain facts relink on the brain host.`);
}
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
- if (!snapshot || snapshot.page.id !== row.page_id) throw new OperationError('page_identity_changed', 'The relink target page changed.');
+ if (!snapshot || snapshot.page.id !== row.page_id) {
+ throw opError('page_identity_changed', 'The relink target page changed.',
+ `${row.slug} in ${row.source_id} was deleted or replaced after relink request ${row.request_id} was accepted, so nothing was written. ${rerun}`);
+ }
const observedRevision = snapshot.revision;
const planned = await classify(engine, row, intent, false);
const byId = new Map(intent.facts.map(f => [f.id, f]));
@@ -162,7 +169,10 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteReque
const rowNums = new Map<number, number>();
if (links.length) {
const parsed = parseFactsFence(body);
- if (parsed.warnings.length) throw new OperationError('invalid_params', 'fence_malformed: the entity facts fence is malformed; repair it before relinking.');
+ if (parsed.warnings.length) {
+ throw opError('invalid_params', 'fence_malformed: the entity facts fence is malformed; repair it before relinking.',
+ `Fix the ## Facts table on ${row.slug} in ${row.source_id} (one header row, then one row per fact), then run gbrain facts relink --source ${row.source_id} again; nothing was written.`);
+ }
const [max] = await engine.executeRaw<{ n: number }>(
'SELECT COALESCE(MAX(row_num),0)::int AS n FROM facts WHERE source_id=$1 AND source_markdown_slug=$2', [row.source_id, row.slug]);
let next = Math.max(Number(max?.n ?? 0), 0, ...parsed.facts.map(f => f.rowNum)) + 1;
@@ -176,11 +186,11 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteReque
const page = links.length ? await (await import('../persistence/page-prepare.ts')).preparePageMutation(engine, { ...row, intent: {
content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags), expected_revision: observedRevision, force: false,
} }, config) : undefined;
- if (page && page.observedRevision !== observedRevision) throw new OperationError('revision_conflict', 'The relink target page changed during preparation.');
+ if (page && page.observedRevision !== observedRevision) throw changed('The relink target page changed during preparation.');
const validate = async (tx: BrainEngine) => {
if (classKey(await classify(tx, row, intent, true)) !== classKey(planned)) {
- throw new OperationError('revision_conflict', 'A relinked fact changed during preparation.');
+ throw changed('A relinked fact changed during preparation.');
}
await page?.validate?.(tx);
};
@@ -195,13 +205,13 @@ export async function prepareRelinkMutation(engine: BrainEngine, row: WriteReque
const rowNum = rowNums.get(c.id)!;
const moved = await tx.executeRaw(`UPDATE facts SET entity_slug=$3, source_markdown_slug=$3, row_num=$4::integer, context=$5 ${guard}`,
[row.source_id, c.id, row.slug, rowNum, appendContextNote(c.value.context as string | null, f.note)]);
- if (moved.length !== 1) throw new OperationError('revision_conflict', 'A relinked fact was moved by another writer.');
+ if (moved.length !== 1) throw changed('A relinked fact was moved by another writer.');
outcome.linked.push({ id: c.id, row_num: rowNum });
} else if (c.action === 'retire') {
const [current] = await tx.executeRaw<{ context: string | null }>('SELECT context FROM facts WHERE source_id=$1 AND id=$2', [row.source_id, c.id]);
const retired = await tx.executeRaw(`UPDATE facts SET entity_slug=$3, expired_at=now(), context=$4 ${guard}`,
[row.source_id, c.id, row.slug, appendContextNote(current?.context ?? null, `${f.note} (duplicate of #${c.duplicateOf})`)]);
- if (retired.length !== 1) throw new OperationError('revision_conflict', 'A relinked fact was moved by another writer.');
+ if (retired.length !== 1) throw changed('A relinked fact was moved by another writer.');
outcome.deduped.push({ id: c.id, duplicate_of: c.duplicateOf });
} else {
outcome.skipped.push({ id: c.id, reason: c.reason });
@@ -249,7 +259,10 @@ export async function submitRelinkGroup(engine: BrainEngine, config: GBrainConfi
const principal = await requestPrincipalForContext(ctx);
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 relink source is not active.');
+ if (!source || source.archived) {
+ throw opError('source_changed', 'The relink source is not active.', `Source ${sourceId} is archived or not registered; run gbrain facts relink with --source set to an active source.`,
+ { fix: { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', why: 'Lists the registered sources and whether each is archived.', requires_exclusive: false } });
+ }
const snapshot = await engine.readPageSnapshot(slug, { sourceId });
if (!snapshot) return { ok: false, reason: 'no_page', message: `${slug} no longer exists` };
const target = await resolveFactWriteTarget(engine, sourceId, source);
diff --git a/src/core/google/attachment-backfill.ts b/src/core/google/attachment-backfill.ts
index efe1d5b72a..40f9442684 100644
--- a/src/core/google/attachment-backfill.ts
+++ b/src/core/google/attachment-backfill.ts
@@ -1,6 +1,7 @@
import type { BrainEngine } from '../engine.ts';
import { withConnectorSync, type ManagedConnectorSync } from '../persistence/connector-sync.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { GmailClient, GoogleCursorExpiredError, type FetchImpl } from './google-clients.ts';
import type { GmailThreadAttachmentReceipts, GoogleSourceConfig, GoogleSourceState } from './types.ts';
import { threadAttachmentReceipts } from './attachment-receipts.ts';
@@ -16,8 +17,16 @@ export async function runGoogleAttachmentBackfill(engine: BrainEngine, sourceId:
return withConnectorSync(engine, sourceId, 'google', cfg, {
sourceId, noEmbed: true, noExtract: true, noSchemaPack: true, signal: opts.signal, retryFailed: opts.retryFailed,
}, async (managed, options) => {
- if (!managed) throw new OperationError('writer_coordinator_required', 'Historical attachment repair requires managed persistence. No metadata was changed.');
- if (!cfg.account || !cfg.services.includes('gmail')) throw new OperationError('invalid_params', 'Select a Gmail source for attachment repair.');
+ if (!managed) {
+ throw opError('writer_coordinator_required', 'Historical attachment repair requires managed persistence. No metadata was changed.',
+ `Source ${sourceId} is not managed by the persistence coordinator, and this repair never enables it. Check the source's writer state; turning on managed persistence is the user's decision.`,
+ { fix: readFix(`Shows source ${sourceId}'s writer and persistence state.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
+ }
+ if (!cfg.account || !cfg.services.includes('gmail')) {
+ throw opError('invalid_params', 'Select a Gmail source for attachment repair.',
+ `Source ${sourceId} is not a connected Gmail source; pass --source with a Google source that syncs Gmail.`,
+ { fix: readFix('Lists the registered sources with their connector kind.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
+ }
let tokens: GoogleAccessProvider;
if (cfg.access === 'command') tokens = new CommandAccessProvider(cfg.tokenCommand ?? '');
else if (cfg.access === 'env') tokens = new EnvAccessProvider(cfg.tokenEnv ?? '');
@@ -32,7 +41,8 @@ export async function runGoogleAttachmentBackfill(engine: BrainEngine, sourceId:
const gmail = new GmailClient(tokens, fetchImpl);
const profile = await gmail.getProfile({ signal: options.signal });
if (profile.emailAddress?.toLowerCase() !== cfg.account) {
- throw new OperationError('source_changed', 'The Gmail credential belongs to a different account. No metadata was changed.');
+ throw opError('source_changed', 'The Gmail credential belongs to a different account. No metadata was changed.',
+ `The stored Google credential signs in as a different mailbox than ${cfg.account}, the account source ${sourceId} was imported from. Ask the user to reconnect Google as ${cfg.account} before repairing attachments.`);
}
await managed.assertAccount({ kind: 'google', email: cfg.account });
const state = managed.state<GoogleSourceState>({ gmail_history_id: null, gmail_backfill_floor_ms: null,
@@ -44,7 +54,8 @@ export async function runGoogleAttachmentBackfill(engine: BrainEngine, sourceId:
export async function backfillGmailAttachments(engine: BrainEngine, managed: ManagedConnectorSync, gmail: GmailClient,
state: GoogleSourceState, account: string, limit = GMAIL_ATTACHMENT_BACKFILL_LIMIT, signal?: AbortSignal) {
if (!Number.isSafeInteger(limit) || limit < 1 || limit > GMAIL_ATTACHMENT_BACKFILL_LIMIT) {
- throw new OperationError('invalid_params', `Attachment backfill limit must be 1-${GMAIL_ATTACHMENT_BACKFILL_LIMIT}.`);
+ throw opError('invalid_params', `Attachment backfill limit must be 1-${GMAIL_ATTACHMENT_BACKFILL_LIMIT}.`,
+ `Pass --limit as a whole number from 1 to ${GMAIL_ATTACHMENT_BACKFILL_LIMIT}, or omit it for ${GMAIL_ATTACHMENT_BACKFILL_LIMIT}.`);
}
let cursor = state.gmail_attachment_backfill;
if (cursor && (cursor.version !== 1 || cursor.account !== account || !Number.isSafeInteger(cursor.afterPageId) ||
@@ -52,7 +63,8 @@ export async function backfillGmailAttachments(engine: BrainEngine, managed: Man
!Number.isSafeInteger(cursor.unavailable ?? 0) || (cursor.unavailable ?? 0) < 0 ||
!Number.isSafeInteger(cursor.unavailableMessages ?? 0) || (cursor.unavailableMessages ?? 0) < 0 ||
cursor.afterPageId < 0 || cursor.throughPageId < cursor.afterPageId)) {
- throw new OperationError('revision_conflict', 'Attachment backfill checkpoint does not match this account. No metadata was changed.');
+ throw opError('revision_conflict', 'Attachment backfill checkpoint does not match this account. No metadata was changed.',
+ `Source ${managed.sourceId}'s saved attachment-repair cursor belongs to another account than ${account} or is malformed. Show the user the source's sync state and ask how to proceed; gbrain will not reset the cursor itself.`);
}
if (!cursor) {
const [row] = await engine.executeRaw<{ id: number | null }>(
@@ -72,13 +84,17 @@ export async function backfillGmailAttachments(engine: BrainEngine, managed: Man
for (const row of rows) {
signal?.throwIfAborted();
if (row.account !== account || typeof row.thread_id !== 'string' || !/^[A-Za-z0-9]{1,128}$/.test(row.thread_id)) {
- throw new OperationError('revision_conflict', 'Historical Gmail page ownership is unknown. Content and the current cursor were preserved.');
+ throw opError('revision_conflict', 'Historical Gmail page ownership is unknown. Content and the current cursor were preserved.',
+ `Page ${row.slug} in ${managed.sourceId} has no thread id for ${account}, so its attachments cannot be matched. Inspect the page and tell the user; the repair stops here so the cursor stays on it.`,
+ { fix: readFix(`Reads ${row.slug}'s frontmatter (account, thread_id).`, { argv: ['gbrain', 'get', '--source', managed.sourceId, '--', row.slug] }) });
}
let fetched: GmailThreadAttachmentReceipts;
try {
const thread = await gmail.getThread(row.thread_id, account, { signal, metadataOnly: true });
if (thread.threadId !== row.thread_id || !thread.messages.length) {
- throw new OperationError('revision_conflict', 'Gmail metadata does not match the historical page. Content and the current cursor were preserved.');
+ throw opError('revision_conflict', 'Gmail metadata does not match the historical page. Content and the current cursor were preserved.',
+ `Gmail returned a different or empty thread for page ${row.slug} in ${managed.sourceId}. Inspect the page and tell the user before repeating the repair; nothing was changed.`,
+ { fix: readFix(`Reads ${row.slug}'s stored thread metadata.`, { argv: ['gbrain', 'get', '--source', managed.sourceId, '--', row.slug] }) });
}
fetched = threadAttachmentReceipts(thread);
} catch (error) {