Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): B10 backfill connector-sync, sync-prepare, connector-google-receipts, sync-discovery

garrytan8e6d63792195
diff --git a/src/core/persistence/connector-google-receipts.ts b/src/core/persistence/connector-google-receipts.ts
index 575444dd01..b5cc17805b 100644
--- a/src/core/persistence/connector-google-receipts.ts
+++ b/src/core/persistence/connector-google-receipts.ts
@@ -2,7 +2,7 @@ import type { BrainEngine } from '../engine.ts';
import type { PageSnapshot } from '../page-state/types.ts';
import type { WriteRequest } from './model.ts';
import type { PreparedMutation } from './coordinator.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError, type OperationError } from '../ops/contract.ts';
import { digest } from './digest.ts';
import { contentHash } from '../utils.ts';
import { serializePageToMarkdown } from '../markdown.ts';
@@ -12,6 +12,26 @@ import type { GmailThreadAttachmentReceipts } from '../google/types.ts';
export type GoogleReceipts = GmailThreadAttachmentReceipts;
+/** A receipt patch refused on ownership or bounds: permanent for this page, so the next step is reading it, never repeating the repair. */
+function receiptOwnershipRefusal(message: string, snapshot: PageSnapshot | null, cause: string): OperationError {
+ const page = snapshot?.page;
+ if (!page) return opError('revision_conflict', message, `${cause} The page is missing, so there is nothing to repair; repeating the repair does not change this.`);
+ return opError('revision_conflict', message, `${cause} Page ${page.slug} in ${page.source_id} was left untouched and repeating the repair does not change this; `
+ + 'read its frontmatter and tell the user if its attachment metadata needs a manual fix.', {
+ fix: { argv: ['gbrain', 'get', '--source', page.source_id, '--', page.slug], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows the frontmatter the attachment repair refused to change.' },
+ });
+}
+
+/** The Gmail page moved under an admitted receipt patch: the receipt is read first, then the repair re-reads the current page. */
+function receiptRaceRefusal(message: string, row: WriteRequest): OperationError {
+ return opError('revision_conflict', message, `Page ${row.slug} in ${row.source_id} changed while its attachment receipts were being patched, so request ${row.request_id} was refused and the content was preserved. `
+ + `Read its receipt first (gbrain write-request -- ${row.request_id}); once it is final, gbrain google attachments backfill --source ${row.source_id} --retry-failed re-reads the current page.`, {
+ fix: { argv: ['gbrain', 'write-request', '--', row.request_id], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The receipt confirms whether the metadata patch published before anything is resubmitted.' },
+ });
+}
+
/** `account` is the parsed connector account (connector-identity.ts), never read from raw source config. */
export function ownedGoogleReceipts(snapshot: PageSnapshot | null, account: string, receipts: GoogleReceipts): GoogleReceipts {
const page = snapshot?.page;
@@ -23,12 +43,14 @@ export function ownedGoogleReceipts(snapshot: PageSnapshot | null, account: stri
new Set(fm.message_ids).size !== fm.message_ids.length || receipts.version !== 1 || !Array.isArray(receipts.messages) ||
(receipts.unavailable !== undefined && receipts.unavailable !== 'thread_not_found') ||
(!receipts.messages.length && !receipts.unavailable) || receipts.messages.length > 512 || Buffer.byteLength(JSON.stringify(receipts)) > 131_072) {
- throw new OperationError('revision_conflict', 'Historical Gmail receipt ownership is unknown or metadata exceeds the repair bound. Content was preserved.');
+ throw receiptOwnershipRefusal('Historical Gmail receipt ownership is unknown or metadata exceeds the repair bound. Content was preserved.', snapshot,
+ 'The page is not a connector-owned email of this Google account and thread, or its receipts exceed the repair bound (512 messages, 128 KiB).');
}
const prior = fm.gmail_attachment_receipts as GoogleReceipts | undefined;
if (prior !== undefined && (prior?.version !== 1 || prior.account !== receipts.account || prior.threadId !== receipts.threadId || !Array.isArray(prior.messages) ||
prior.messages.length > 512 || Buffer.byteLength(JSON.stringify(prior)) > 131_072)) {
- throw new OperationError('revision_conflict', 'The attachment metadata field is not connector-owned. Content was preserved.');
+ throw receiptOwnershipRefusal('The attachment metadata field is not connector-owned. Content was preserved.', snapshot,
+ 'The existing gmail_attachment_receipts field was not written by this connector for this account and thread.');
}
const messageIds = fm.message_ids as string[];
for (const entries of [receipts.messages, prior?.messages ?? []]) {
@@ -37,15 +59,18 @@ export function ownedGoogleReceipts(snapshot: PageSnapshot | null, account: stri
(m.unavailable !== undefined && !['thread_not_found', 'message_not_found'].includes(m.unavailable)) ||
!['not_inspected', 'incomplete', 'none', 'present'].includes(m.inspection?.state) || !Array.isArray(m.inspection.attachments) ||
m.inspection.attachments.some(a => !a || a.account !== receipts.account || a.messageId !== m.messageId || a.fetched !== false || a.indexed !== false))) {
- throw new OperationError('revision_conflict', 'Gmail receipt identity or ownership is unknown. Content was preserved.');
+ throw receiptOwnershipRefusal('Gmail receipt identity or ownership is unknown. Content was preserved.', snapshot,
+ 'A message receipt is duplicated, malformed, or names attachments of another account or message.');
}
}
if (prior?.messages.some(m => !messageIds.includes(m.messageId))) {
- throw new OperationError('revision_conflict', 'Existing Gmail receipts do not match the historical message identities. Content was preserved.');
+ throw receiptOwnershipRefusal('Existing Gmail receipts do not match the historical message identities. Content was preserved.', snapshot,
+ 'The stored receipts name messages that are not in the page\'s message_ids.');
}
if (!receipts.unavailable && messageIds.some(id => !receipts.messages.some(m => m.messageId === id)) &&
receipts.messages.some(m => m.inspection.state === 'incomplete' || m.inspection.state === 'not_inspected')) {
- throw new OperationError('revision_conflict', 'Incomplete Gmail metadata cannot establish disappearance. Content was preserved.');
+ throw receiptOwnershipRefusal('Incomplete Gmail metadata cannot establish disappearance. Content was preserved.', snapshot,
+ 'Gmail returned incomplete metadata, so a missing message cannot be recorded as gone.');
}
const selected = messageIds.map(messageId => {
const incoming = receipts.messages.find(m => m.messageId === messageId);
@@ -57,7 +82,8 @@ export function ownedGoogleReceipts(snapshot: PageSnapshot | null, account: stri
const merged = { ...prior, ...receipts, messages: selected };
if (!receipts.unavailable) delete merged.unavailable;
if (Buffer.byteLength(JSON.stringify(merged)) > 131_072) {
- throw new OperationError('revision_conflict', 'Preserved Gmail receipts exceed the repair bound. Content was preserved.');
+ throw receiptOwnershipRefusal('Preserved Gmail receipts exceed the repair bound. Content was preserved.', snapshot,
+ 'The merged receipts would exceed the 128 KiB repair bound.');
}
return merged;
}
@@ -72,7 +98,7 @@ export async function prepareGoogleReceiptPatch(engine: BrainEngine, row: WriteR
const target = await prepareFileTarget(engine, row, current, serializePageToMarkdown(page, current.tags));
const file = target && { ...target, publishMode: 0o600 };
const projection = noop ? null : await readProjectionSnapshot(engine, row.slug, row.source_id, { allowUnsealed: true });
- if (!noop && (!projection || projection.snapshot.revision !== current.revision)) throw new OperationError('revision_conflict', 'The Gmail page changed during receipt preparation.');
+ if (!noop && (!projection || projection.snapshot.revision !== current.revision)) throw receiptRaceRefusal('The Gmail page changed during receipt preparation.', row);
const chunks = projection ? await preparePageProjection(projection) : null;
return { observedRevision: current.revision, sourceExclusive: true, deferEmbedding: true, noop, file,
apply: async tx => {
@@ -80,15 +106,15 @@ export async function prepareGoogleReceiptPatch(engine: BrainEngine, row: WriteR
const liveProjection = await readProjectionSnapshot(tx, row.slug, row.source_id, { allowUnsealed: true });
if (!liveProjection || liveProjection.indexingContext !== projection!.indexingContext ||
digest(liveProjection.chunks) !== digest(projection!.chunks)) {
- throw new OperationError('revision_conflict', 'The Gmail projection changed during receipt preparation.');
+ throw receiptRaceRefusal('The Gmail projection changed during receipt preparation.', row);
}
await tx.createVersion(row.slug, { sourceId: row.source_id });
const changed = await tx.executeRaw(`UPDATE pages SET frontmatter=jsonb_set(frontmatter,'{gmail_attachment_receipts}',$3::text::jsonb),content_hash=$4,updated_at=now()
WHERE source_id=$1 AND slug=$2 AND id=$5 AND knowledge_revision=$6::uuid AND deleted_at IS NULL RETURNING id`,
[row.source_id, row.slug, JSON.stringify(receipts), contentHash({ ...page, tags: current.tags }), current.page.id, current.revision]);
- if (changed.length !== 1) throw new OperationError('revision_conflict', 'The Gmail page changed before metadata publication.');
+ if (changed.length !== 1) throw receiptRaceRefusal('The Gmail page changed before metadata publication.', row);
const next = await readProjectionSnapshot(tx, row.slug, row.source_id, { allowUnsealed: true });
- if (!next || !chunks) throw new OperationError('revision_conflict', 'The Gmail receipt projection is unavailable.');
+ if (!next || !chunks) throw receiptRaceRefusal('The Gmail receipt projection is unavailable.', row);
await installPageProjection(tx, next, chunks.chunks, { seal: true, preserveEmbeddings: true, code: chunks.code });
}
return { status: noop ? 'skipped' : 'updated', slug: row.slug, source_id: row.source_id, noop, attachment_metadata_only: true };
diff --git a/src/core/persistence/connector-sync.ts b/src/core/persistence/connector-sync.ts
index 4cc793b20d..2e4acf0c62 100644
--- a/src/core/persistence/connector-sync.ts
+++ b/src/core/persistence/connector-sync.ts
@@ -8,7 +8,9 @@ import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { slugifyPath } from '../sync.ts';
import type { Page } from '../types.ts';
import { isWriteTargetContained } from '../path-confine.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import type { RegistryCode } from '../error-registry.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
@@ -31,7 +33,7 @@ import { LockStolenError, syncLockId, withRefreshingLock, type DbLockHandle } fr
import { ownedGoogleReceipts, prepareGoogleReceiptPatch, type GoogleReceipts } from './connector-google-receipts.ts';
import { connectorCheckpointKey, connectorIdentity, type ConnectorIdentity, type ConnectorKind } from './connector-identity.ts';
import { readManagedConnectorState, recordConnectorSyncAttempt, sameConnectorAccount, writeManagedConnectorState, type ConnectorAccount, type ConnectorPendingEntry, type ConnectorRunCounts, type ConnectorState } from './connector-state.ts';
-import { connectorAccountChanged, connectorFenceHint, docsAnchor, CONNECTOR_INTENT_OUTDATED_OLD_HOST, CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE } from './connector-errors.ts';
+import { connectorAccountChanged, connectorFenceHint, docsAnchor, receiptDeliveredHint, CONNECTOR_INTENT_OUTDATED_OLD_HOST, CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE } from './connector-errors.ts';
import { inspectUnchanged, screeningRequest } from './noop-kernel.ts';
import { conceptPreservationHold, preserveCanonicalFences } from '../cycle/concept-publication.ts';
import { FACTS_FENCE_BEGIN } from '../facts-fence.ts';
@@ -108,13 +110,43 @@ interface ConnectorIntent extends Record<string, unknown> {
fileBeforeHash: string | null;
}
+/** Read-only: the owner's view of a source's binding, queue and blocking receipts. */
+function ownerStatusFix(sourceId: string, why: string): Action {
+ return { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', why, requires_exclusive: false };
+}
+
+/** Read-only: one connector write receipt; connector writes run under the local CLI writer, so the CLI reads its own receipt. */
+function receiptFix(requestId: string, why: string): Action {
+ return { argv: ['gbrain', 'write-request', '--', requestId], consent: [], actor: 'agent', why, requires_exclusive: false };
+}
+
+/** The next run of a connector source's sync: it resolves the recorded pending set before it sweeps. */
+function connectorSyncFix(sourceId: string, why: string): Action {
+ return { argv: ['gbrain', 'sync', '--source', sourceId], consent: [], actor: 'agent', why, requires_exclusive: false };
+}
+
+/**
+ * Publishing an admitted connector item was refused. The coordinator keeps
+ * only code and message, so the suggestion stands alone: read the receipt,
+ * then re-attempt the item explicitly once the cause is fixed.
+ */
+function connectorPublicationRefusal(code: RegistryCode, message: string, row: WriteRequest, cause: string): OperationError {
+ return opError(code, message, `${cause} Read receipt ${row.request_id} first (gbrain write-request -- ${row.request_id}); once it is final and the cause is fixed, `
+ + `gbrain sync --source ${row.source_id} --retry-failed re-attempts the item under a new request ID.`,
+ { fix: receiptFix(row.request_id, 'The receipt records whether this connector write published anything; nothing is resubmitted until it is final.') });
+}
+
/** The connector binding's owner and incarnation checks; returns the paths they prove present. */
function checkedConnectorBinding(sourceId: string, source: ConnectorSource, binding: WorktreeBinding) {
if (binding.owner_host_id !== localHostId() || !binding.local_path || !binding.coordination_path) {
- throw new OperationError('owner_unavailable', 'The connector canonical owner is unavailable on this host.');
+ throw opError('owner_unavailable', 'The connector canonical owner is unavailable on this host.',
+ `Source ${sourceId} is owned by another host or its worktree binding is incomplete; run its connector sync on the owner host that gbrain sources writer status --source ${sourceId} --json names.`,
+ { fix: ownerStatusFix(sourceId, 'Shows which host owns the source and whether its binding records a local and coordination path.') });
}
if (binding.source_id !== sourceId || binding.source_incarnation !== source.incarnation || !source.local_path) {
- throw new OperationError('source_changed', 'The connector source does not match its canonical binding.');
+ throw opError('source_changed', 'The connector source does not match its canonical binding.',
+ `The canonical binding of ${sourceId} belongs to another source incarnation, or the source has no local path. Inspect the binding before syncing ${sourceId} again; nothing was written.`,
+ { fix: ownerStatusFix(sourceId, 'Shows the binding\'s source incarnation and recorded paths next to the source registration.') });
}
return { localPath: binding.local_path, coordinationPath: binding.coordination_path, sourcePath: source.local_path };
}
@@ -132,7 +164,9 @@ function connectorBindingRoot(sourceId: string, source: ConnectorSource, binding
}
return root;
} catch {
- throw new OperationError('source_changed', 'The connector directory no longer matches its canonical source root.');
+ throw opError('source_changed', 'The connector directory no longer matches its canonical source root.',
+ `The directory configured for ${sourceId} (g_dir, gh_dir or the source path) no longer resolves to the owner's recorded canonical root. Restore that directory, then run gbrain sync --source ${sourceId}; nothing was written.`,
+ { fix: ownerStatusFix(sourceId, 'Shows the canonical root the owner recorded, to compare with the configured connector directory.') });
}
}
@@ -161,7 +195,9 @@ async function connectorFileTarget(engine: BrainEngine, row: Pick<WriteRequest,
snapshot: PageSnapshot | null, content: string | null, sourcePath: string | null, root: string | null): Promise<PreparedMutation['file']> {
if (!row.worktree_id || snapshot || !sourcePath || !root) return prepareFileTarget(engine, row, snapshot, content);
const path = resolve(root, sourcePath);
- if (!isWriteTargetContained(path, root)) throw new OperationError('source_changed', 'The canonical file target is outside its registered source.');
+ if (!isWriteTargetContained(path, root)) throw opError('source_changed', 'The canonical file target is outside its registered source.',
+ `The file for ${row.slug} would resolve outside the registered root of ${row.source_id}, so nothing was written. Check the root with gbrain sources writer status --source ${row.source_id} --json before syncing again.`,
+ { fix: ownerStatusFix(row.source_id, 'Shows the registered canonical root the connector file must stay inside.') });
const before = persistenceFileHash(path);
if (before && content !== null && before !== sha256(content)) {
throw new OperationError('source_changed', 'An unindexed file already occupies the canonical page path.', 'Import the file before replacing it.');
@@ -177,16 +213,27 @@ export async function beginConnectorSync(engine: BrainEngine, sourceId: string,
validateManagedSyncOptions(opts);
if (opts.dryRun || opts.skipFailed || opts.srcSubpath || opts.exclude?.length || opts.includeHidden?.length ||
opts.includeGitignored || opts.workingTree || opts.strategy === 'code' || connector === 'google' && opts.githubItem) {
- throw new OperationError('invalid_params', 'Managed connector sync does not support dry runs, Git file filters, or --skip-failed.');
+ throw opError('invalid_params', 'Managed connector sync does not support dry runs, Git file filters, or --skip-failed.',
+ `Run gbrain sync --source ${sourceId} without --dry-run, --skip-failed, --src-subpath, --exclude, --include-hidden, --include-gitignored, --working-tree or --strategy code; a connector imports provider items, not Git files. Nothing was synced.`,
+ { fix: connectorSyncFix(sourceId, 'The plain connector sync is the supported managed run; it keeps every pending-write and checkpoint guard.') });
}
const caller = currentSubmissionAuthority();
- if (caller && caller.kind !== 'application') throw new OperationError('permission_denied', 'Connector sync requires a trusted local CLI writer; remote jobs cannot acquire connector credentials.');
+ if (caller && caller.kind !== 'application') throw opError('permission_denied', 'Connector sync requires a trusted local CLI writer; remote jobs cannot acquire connector credentials.',
+ `Connector credentials stay on the brain host, so ${sourceId} syncs only from the gbrain CLI there: gbrain sync --source ${sourceId}. Ask the brain host's operator to run it.`,
+ { fix: { ...connectorSyncFix(sourceId, 'Only the trusted local CLI on the brain host can read connector credentials.'), actor: 'host_admin',
+ user_message: `The ${connector} connector source ${sourceId} has to sync on the machine that hosts the brain. Please ask whoever runs it to run the command shown there.` } });
const [source] = await engine.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'The connector source is not active.');
- if (source.config.kind !== connector) throw new OperationError('writer_coordinator_required', 'Managed connector sync requires a registered connector source; legacy filesystem calls are unsupported.');
+ if (!source || source.archived) throw opError('source_changed', 'The connector source is not active.',
+ `Source ${sourceId} is missing or archived, so nothing was synced. Check it in gbrain sources list --json; an archived connector source syncs again only after gbrain sources restore ${sourceId}.`,
+ { fix: { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', why: 'Lists every source with its archived state.', requires_exclusive: false } });
+ if (source.config.kind !== connector) throw opError('writer_coordinator_required', 'Managed connector sync requires a registered connector source; legacy filesystem calls are unsupported.',
+ `Source ${sourceId} is not registered as a ${connector} connector source. Run gbrain sync --source ${sourceId}, which dispatches to the importer its registration names.`,
+ { fix: connectorSyncFix(sourceId, 'The sync command routes a source to its registered connector or filesystem importer.') });
const identity = connectorIdentity(connector, source.config, source.local_path);
if (digest(identity.config) !== digest(suppliedConfig) || opts.sourceId !== undefined && opts.sourceId !== sourceId) {
- throw new OperationError('source_changed', 'Connector options do not match the registered source.');
+ throw opError('source_changed', 'Connector options do not match the registered source.',
+ `The connector options supplied for ${sourceId} differ from its registered configuration, so nothing was synced. Run gbrain sync --source ${sourceId}, which reads the registered configuration itself.`,
+ { fix: connectorSyncFix(sourceId, 'The sync command loads the source\'s registered connector configuration instead of caller-supplied options.') });
}
const authority = await managedSyncAuthority(engine, sourceId, source.incarnation, source.local_path ?? '');
const binding = await getWorktreeBinding(engine, sourceId);
@@ -222,7 +269,9 @@ export async function withConnectorSync<T>(engine: BrainEngine, sourceId: string
const combined = opts.signal ? AbortSignal.any([opts.signal, signal]) : signal;
const options = { ...opts, signal: combined };
const session = await beginConnectorSync(engine, sourceId, connector, config, options, { handle, signal: combined });
- if (!session) throw new OperationError('source_changed', 'The managed connector mode changed before the sweep.');
+ if (!session) throw opError('source_changed', 'The managed connector mode changed before the sweep.',
+ `Managed persistence was switched while the sync of ${sourceId} started, so nothing was swept. Check the mode with gbrain sources writer status --source ${sourceId} --json, then run gbrain sync --source ${sourceId}.`,
+ { fix: ownerStatusFix(sourceId, 'Shows whether managed persistence is active for this brain and source.') });
// Only a validated, authorized sweep opens the autopilot dispatch gate (#5673); the
// session keeps the stamp in the state row it writes back.
await recordConnectorSyncAttempt(engine, sourceId);
@@ -396,13 +445,17 @@ export class ManagedConnectorSync {
const [source] = await engine.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [this.sourceId]);
if (!source || source.archived || source.incarnation !== this.source.incarnation || source.local_path !== this.source.local_path ||
source.config.kind !== this.connector || connectorIdentity(this.connector, source.config, source.local_path).digest !== this.identity.digest) {
- throw new OperationError('source_changed', 'The connector source changed during the sweep.');
+ throw opError('source_changed', 'The connector source changed during the sweep.',
+ `The configuration, path or incarnation of ${this.sourceId} changed while this sweep ran; writes it already admitted keep their receipts. Inspect the source on the owner before running gbrain sync --source ${this.sourceId} again.`,
+ { fix: ownerStatusFix(this.sourceId, 'Shows the current registration and every pending or blocked receipt of the source.') });
}
const binding = await getWorktreeBinding(engine, this.sourceId);
if ((binding?.worktree_id ?? null) !== (this.binding?.worktree_id ?? null) ||
String(binding?.owner_epoch) !== String(this.binding?.owner_epoch) ||
connectorBindingRoot(this.sourceId, source, binding) !== this.canonicalRoot) {
- throw new OperationError('source_changed', 'The connector ownership changed during the sweep.');
+ throw opError('source_changed', 'The connector ownership changed during the sweep.',
+ `The owner binding or canonical root of ${this.sourceId} changed while this sweep ran; writes it already admitted keep their receipts. Inspect the owner before running gbrain sync --source ${this.sourceId} again.`,
+ { fix: ownerStatusFix(this.sourceId, 'Shows the current owner, epoch and canonical root of the source.') });
}
return binding;
}
@@ -415,7 +468,10 @@ export class ManagedConnectorSync {
}
private async authorizeRetryReceipt(engine: BrainEngine, row: WriteRequest): Promise<void> {
if (row.source_id !== this.sourceId || row.principal_kind !== this.authority.writer.principal.kind || row.principal_id !== this.authority.writer.principal.id) {
- throw new OperationError('write_pending', 'Other accepted work must drain before connector retry approval.');
+ throw opError('write_pending', 'Other accepted work must drain before connector retry approval.',
+ `Request ${row.request_id} of another writer or source is still ahead of the connector retry for ${this.sourceId}; nothing was re-approved. `
+ + `Inspect it with gbrain sources writer status --source ${row.source_id} --json and let it finish before the next run of the same connector sync.`,
+ { fix: ownerStatusFix(row.source_id, 'Shows the accepted request that blocks the retry and whether it is still running or needs recovery.') });
}
await authorizeStoredRequest(engine, row);
}
@@ -423,8 +479,11 @@ export class ManagedConnectorSync {
const row = await this.retryBlocker(engine);
if (!row) return;
await this.authorizeRetryReceipt(engine, row);
- const error = new OperationError(row.recovery || isTerminal(row) ? 'recovery_required' : 'write_pending',
- 'Accepted work must finish before connector retry approval.');
+ const error = opError(row.recovery || isTerminal(row) ? 'recovery_required' : 'write_pending',
+ 'Accepted work must finish before connector retry approval.',
+ `Request ${row.request_id} for ${row.slug} in ${row.source_id} is ${row.state}${row.recovery ? ' and needs recovery' : ''}; nothing was re-approved. `
+ + `Read its receipt with gbrain write-request -- ${row.request_id} and do not resubmit it; once it is final, run the same connector sync for ${this.sourceId} again.`,
+ { fix: receiptFix(row.request_id, 'The receipt says whether the blocking write committed, failed or still needs recovery.') });
error.writeRequest = receiptFor(row);
error.writeError = row.recovery || isTerminal(row) ? 'recovery_required' : 'write_pending';
throw error;
@@ -465,7 +524,10 @@ export class ManagedConnectorSync {
throw error;
}
state<T>(empty: T): T {
- if (this.resetRequested) throw new OperationError('storage_error', 'A requested checkpoint reset runs after the connector account check, before the checkpoint is read.');
+ if (this.resetRequested) throw opError('storage_error', 'A requested checkpoint reset runs after the connector account check, before the checkpoint is read.',
+ `The ${this.connector} connector read its checkpoint before the account check that applies the reset, so nothing was reset or synced for ${this.sourceId}. `
+ + 'This is a gbrain bug, not a caller mistake: report it to the user with gbrain doctor --json output.',
+ { fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Doctor output identifies the installed version and brain state for the bug report.', requires_exclusive: false } });
return structuredClone((this.checkpoint[0] as { state?: T } | undefined)?.state ?? empty);
}
async page(slug: string) {
@@ -490,7 +552,9 @@ export class ManagedConnectorSync {
return done.pending || done.row.outcome?.noop !== true;
}
async patchGoogleReceipts(slug: string, receipts: GoogleReceipts, pageId: number): Promise<GoogleReceipts> {
- if (this.connector !== 'google') throw new OperationError('invalid_params', 'Attachment repair requires a Google source.');
+ if (this.connector !== 'google') throw opError('invalid_params', 'Attachment repair requires a Google source.',
+ `Source ${this.sourceId} is a ${this.connector} connector; Gmail attachment repair runs only on a Google source with Gmail. Pick one from gbrain sources list --json, then run gbrain google attachments backfill --source with its id.`,
+ { fix: { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', why: 'Lists every source with its connector kind.', requires_exclusive: false } });
const done = await this.submit('connector_v2_google_receipts', slug, null, { googleReceipts: receipts, googlePageId: pageId, noEmbed: true });
return (done.row!.intent as ConnectorIntent).googleReceipts!;
}
@@ -702,14 +766,18 @@ export class ManagedConnectorSync {
await this.recover(slug);
const snapshot = await this.engine.readPageSnapshot(slug, { sourceId: this.sourceId, includeDeleted: true });
if (kind === 'connector_v2_google_receipts') {
- if (!snapshot || snapshot.page.id !== extra.googlePageId) throw new OperationError('page_identity_changed', 'The historical Gmail page was deleted or recreated.');
+ if (!snapshot || snapshot.page.id !== extra.googlePageId) throw opError('page_identity_changed', 'The historical Gmail page was deleted or recreated.',
+ `Page ${slug} in ${this.sourceId} was deleted or recreated after the attachment repair read it, so its receipts were not patched. Read the current page, then run gbrain google attachments backfill --source ${this.sourceId} again.`,
+ { fix: { argv: ['gbrain', 'get', '--source', this.sourceId, '--', slug], consent: [], actor: 'agent', why: 'Shows whether the page exists now and which page id it carries.', requires_exclusive: false } });
extra.googleReceipts = ownedGoogleReceipts(snapshot, (this.identity.config as GoogleSourceConfig).account, extra.googleReceipts!);
sourcePath = snapshot!.page.source_path!;
}
const file = kind === 'connector_v2_checkpoint' ? undefined : await connectorFileTarget(this.engine,
{ source_id: this.sourceId, worktree_id: this.binding?.worktree_id ?? null, slug }, snapshot, extra.content ?? null, sourcePath, this.canonicalRoot);
if (file && sourcePath && resolve(file.path) !== resolve(this.canonicalRoot!, sourcePath)) {
- throw new OperationError('source_changed', 'The connector source path no longer names its canonical file.');
+ throw opError('source_changed', 'The connector source path no longer names its canonical file.',
+ `The recorded path of ${slug} no longer resolves to its canonical file under the root of ${this.sourceId}, so nothing was submitted. Inspect the root and binding before running gbrain sync --source ${this.sourceId} again.`,
+ { fix: ownerStatusFix(this.sourceId, 'Shows the canonical root the connector file path must resolve under.') });
}
const intent: ConnectorIntent = { kind, connector: this.connector, sourceRoot: this.source.local_path,
configHash: this.identity.digest, syncAuthority: this.authority, expected_revision: snapshot?.revision ?? null,
@@ -739,7 +807,9 @@ export class ManagedConnectorSync {
if (row) {
await authorizeStoredRequest(engine, row);
assertReplayIntent(row, intentDigest(input));
- } else if (retry && !retry.pending) throw new OperationError('storage_error', 'The approved connector retry receipt is unavailable.');
+ } else if (retry && !retry.pending) throw opError('storage_error', 'The approved connector retry receipt is unavailable.',
+ `The retry approved for ${slug} in ${this.sourceId} points at request ${retry.requestId}, which no longer exists; nothing was admitted. Inspect the source's receipts, then re-approve held items with gbrain sources retry-held ${this.sourceId}.`,
+ { fix: ownerStatusFix(this.sourceId, 'Shows the source\'s receipts and any retained recovery before a retry is approved again.') });
return { retry, input, row };
};
const automatic = this.autoRetry.has(baseRequestId);
@@ -754,7 +824,9 @@ export class ManagedConnectorSync {
try {
if (this.binding && !lock) {
await this.refuseRetryBlocker(this.engine);
- throw new OperationError('write_pending', 'The canonical owner is busy; retry approval has not changed.');
+ throw opError('write_pending', 'The canonical owner is busy; retry approval has not changed.',
+ `The owner of ${this.sourceId} is busy, so the failed write ${failedRow.request_id} for ${slug} was not re-approved and nothing new was admitted. Check the owner's queue; the next run of the same connector sync re-attempts it once the owner is free.`,
+ { fix: ownerStatusFix(this.sourceId, 'Shows what the canonical owner is running and what is queued behind it.') });
}
row = await this.engine.transaction(async tx => {
if (this.binding) await tx.executeRaw('SELECT id FROM persistence_worktrees WHERE id=$1::uuid FOR SHARE', [this.binding.worktree_id]);
@@ -762,13 +834,17 @@ export class ManagedConnectorSync {
await this.validate(tx, slug);
await authorizeWrite(tx, this.authority.writer, 'submit_job', slug, true);
const current = await selected(tx);
- if (!current.row) throw new OperationError('storage_error', 'The failed connector receipt is unavailable.');
+ if (!current.row) throw opError('storage_error', 'The failed connector receipt is unavailable.',
+ `Failed request ${failedRow.request_id} for ${slug} in ${this.sourceId} disappeared before its retry was approved; nothing was admitted. Inspect the source's receipts before running the same connector sync again.`,
+ { fix: ownerStatusFix(this.sourceId, 'Shows the source\'s current receipts and recovery state.') });
await authorizeStoredRequest(tx, current.row, true);
if (!mayRetry(current.row)) return current.row;
await this.refuseRetryBlocker(tx);
const [checkpoint] = await tx.executeRaw<{ completed_keys: unknown[] }>(
"SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1 FOR UPDATE", [this.checkpointKey]);
- if (digest(checkpoint?.completed_keys ?? []) !== digest(this.checkpoint)) throw new OperationError('revision_conflict', 'The connector cursor changed before retry approval.');
+ if (digest(checkpoint?.completed_keys ?? []) !== digest(this.checkpoint)) throw opError('revision_conflict', 'The connector cursor changed before retry approval.',
+ `Another run moved the connector cursor of ${this.sourceId} while this one re-approved ${slug}; nothing was admitted. Run gbrain sync --source ${this.sourceId} to continue from the new cursor.`,
+ { fix: connectorSyncFix(this.sourceId, 'A new run reads the current cursor and resolves the recorded pending set first.') });
const attempt = (current.retry?.attempt ?? 0) + 1;
const retry: ConnectorRetry = { checkpointKey: this.checkpointKey,
principalId: principal.id, principalKind: principal.kind, baseRequestId, retryOf: current.row.request_id, attempt,
@@ -845,38 +921,49 @@ export class ManagedConnectorSync {
export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
const p = row.intent as ConnectorIntent | null;
if (!p || !CONNECTOR_V2_KINDS.includes(p.kind) ||
- p.syncAuthority.writer.remote || p.syncAuthority.remoteJob) throw new OperationError('permission_denied', 'Unsupported connector authority.');
+ p.syncAuthority.writer.remote || p.syncAuthority.remoteJob) throw connectorPublicationRefusal('permission_denied', 'Unsupported connector authority.', row,
+ 'The request does not carry a local connector writer\'s authority; only the trusted local CLI publishes connector content.');
if (!row.worktree_id && (row.authority.databaseOnlyReason !== 'connector_database' || p.syncAuthority.writer.databaseOnlyReason !== 'connector_database') ||
row.worktree_id && (row.authority.databaseOnlyReason !== undefined || p.syncAuthority.writer.databaseOnlyReason !== undefined)) {
- throw new OperationError('permission_denied', 'Connector database-only authority does not match its binding.');
+ throw connectorPublicationRefusal('permission_denied', 'Connector database-only authority does not match its binding.', row,
+ `The request's database-only authority no longer matches whether ${row.source_id} has a worktree binding (the source was bound or unbound after admission).`);
}
const validate = async (tx: BrainEngine) => {
await validateSyncAuthority(tx, p.syncAuthority, row.slug);
const [source] = await tx.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [row.source_id]);
if (!source || source.archived || source.incarnation !== row.source_incarnation || source.config.kind !== p.connector ||
connectorIdentity(p.connector, source.config, source.local_path).digest !== p.configHash || source.local_path !== p.sourceRoot) {
- throw new OperationError('source_changed', 'The connector configuration changed after admission.');
+ throw connectorPublicationRefusal('source_changed', 'The connector configuration changed after admission.', row,
+ `The connector configuration, path or incarnation of ${row.source_id} changed after this write was admitted.`);
}
const binding = await getWorktreeBinding(tx, row.source_id);
if ((binding?.worktree_id ?? null) !== row.worktree_id || (binding ? String(binding.owner_epoch) : null) !== p.ownerEpoch) {
- throw new OperationError('source_changed', 'The connector ownership binding changed after admission.');
+ throw connectorPublicationRefusal('source_changed', 'The connector ownership binding changed after admission.', row,
+ `The owner binding of ${row.source_id} changed after this write was admitted.`);
}
- if (connectorBindingRoot(row.source_id, source, binding) !== p.canonicalRoot) throw new OperationError('source_changed', 'The connector canonical root changed after admission.');
+ if (connectorBindingRoot(row.source_id, source, binding) !== p.canonicalRoot) throw connectorPublicationRefusal('source_changed', 'The connector canonical root changed after admission.', row,
+ `The canonical root of ${row.source_id} changed after this write was admitted.`);
if (p.filePath !== null && (!p.canonicalRoot || !isWriteTargetContained(p.filePath, p.canonicalRoot) || persistenceFileHash(p.filePath) !== p.fileBeforeHash)) {
- throw new OperationError('source_changed', 'The connector canonical file changed after admission.');
+ throw connectorPublicationRefusal('source_changed', 'The connector canonical file changed after admission.', row,
+ `The canonical file of ${row.slug} in ${row.source_id} changed on disk after this write was admitted.`);
}
if (p.kind !== 'connector_v2_checkpoint') {
const [checkpoint] = await tx.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1", [p.checkpointKey]);
- if (digest(cursorOnly(checkpoint?.completed_keys)) !== digest(cursorOnly(p.checkpointBefore))) throw new OperationError('revision_conflict', 'The connector checkpoint changed before publication.');
+ if (digest(cursorOnly(checkpoint?.completed_keys)) !== digest(cursorOnly(p.checkpointBefore))) throw connectorPublicationRefusal('revision_conflict', 'The connector checkpoint changed before publication.', row,
+ `Another run moved the connector cursor of ${row.source_id} before this write published.`);
}
};
await validate(engine);
if (p.kind === 'connector_v2_checkpoint') return { observedRevision: null, sourceExclusive: true, validate, apply: async tx => {
const [current] = await tx.executeRaw<{ completed_keys: unknown[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-connector' AND fingerprint=$1 FOR UPDATE", [p.checkpointKey]);
- if (digest(current?.completed_keys ?? []) !== digest(p.checkpointBefore)) throw new OperationError('revision_conflict', 'The connector checkpoint changed during the sweep.');
+ if (digest(current?.completed_keys ?? []) !== digest(p.checkpointBefore)) throw opError('revision_conflict', 'The connector checkpoint changed during the sweep.',
+ `Another run moved the connector cursor of ${row.source_id} during this sweep, so checkpoint request ${row.request_id} was refused and the cursor stayed where that run left it. Read the receipt; the next gbrain sync --source ${row.source_id} saves the cursor again.`,
+ { fix: receiptFix(row.request_id, 'The receipt confirms the checkpoint save did not commit.') });
const receipts = p.receipts ?? [];
const committed = await tx.executeRaw<{ id: string }>("SELECT id FROM persistence_requests WHERE id=ANY($1::uuid[]) AND source_id=$2 AND source_incarnation=$3::uuid AND state='committed'", [receipts, row.source_id, row.source_incarnation]);
- if (committed.length !== new Set(receipts).size) throw new OperationError('write_pending', 'A connector page receipt has not committed.');
+ if (committed.length !== new Set(receipts).size) throw opError('write_pending', 'A connector page receipt has not committed.',
+ `A page write that checkpoint request ${row.request_id} depends on has not committed, so the cursor of ${row.source_id} did not advance. Read the receipt; the next gbrain sync --source ${row.source_id} waits for the pending page writes before it saves the cursor again.`,
+ { fix: receiptFix(row.request_id, 'The receipt confirms the checkpoint save did not commit.') });
await tx.executeRaw(`INSERT INTO op_checkpoints(op,fingerprint,completed_keys) VALUES('managed-connector',$1,$2::text::jsonb)
ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()`, [p.checkpointKey, JSON.stringify(p.checkpointAfter)]);
if (p.fresh) await tx.executeRaw('UPDATE sources SET last_sync_at=now(),newest_content_at=COALESCE($3::timestamptz,newest_content_at) WHERE id=$1 AND incarnation=$2::uuid',
@@ -886,7 +973,8 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id, includeDeleted: true });
if ((snapshot?.revision ?? null) !== p.expected_revision || (snapshot?.page.id ?? null) !== row.page_id ||
snapshot?.page.source_path != null && snapshot.page.source_path !== p.sourcePath) {
- throw new OperationError('revision_conflict', 'The connector page changed after admission.');
+ throw connectorPublicationRefusal('revision_conflict', 'The connector page changed after admission.', row,
+ `Page ${row.slug} in ${row.source_id} changed after this connector write was admitted.`);
}
const deleteFile = p.kind === 'connector_v2_delete' ? await prepareFileTarget(engine, row, snapshot, null) : undefined;
if (p.kind === 'connector_v2_delete') return { observedRevision: snapshot?.revision ?? null, sourceExclusive: true, validate,
@@ -899,7 +987,8 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };
} };
if (p.kind === 'connector_v2_google_receipts') {
- if (p.connector !== 'google' || !p.googleReceipts) throw new OperationError('invalid_params', 'Invalid Google attachment receipt mutation.');
+ if (p.connector !== 'google' || !p.googleReceipts) throw connectorPublicationRefusal('invalid_params', 'Invalid Google attachment receipt mutation.', row,
+ 'The request is not an attachment-receipt patch for a Google source.');
const [source] = await engine.executeRaw<ConnectorSource>('SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [row.source_id]);
const account = (connectorIdentity('google', source.config, source.local_path).config as GoogleSourceConfig).account;
const prepared = await prepareGoogleReceiptPatch(engine, row, snapshot, account, p.googleReceipts);
@@ -907,11 +996,13 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
}
if (!p.sourcePath || typeof p.content !== 'string' || slugifyPath(p.sourcePath) !== row.slug ||
p.sourcePath.split('/').some(part => !part || part === '.' || part === '..') || p.sourcePath.includes('\\')) {
- throw new OperationError('invalid_params', 'The connector import path is invalid.');
+ throw connectorPublicationRefusal('invalid_params', 'The connector import path is invalid.', row,
+ `The recorded source path is empty, escapes the source, or does not map to ${row.slug}.`);
}
const activePack = p.noSchemaPack ? undefined : (await loadActivePackForEngine(engine, { remote: false, sourceId: row.source_id }).catch(() => null))?.manifest;
const parsed = parseMarkdown(p.content, row.slug, { activePack });
- if (parsed.slug !== row.slug) throw new OperationError('invalid_params', 'The connector content changes its page identity.');
+ if (parsed.slug !== row.slug) throw connectorPublicationRefusal('invalid_params', 'The connector content changes its page identity.', row,
+ `The provider content's frontmatter names a slug other than ${row.slug}.`);
// #5567: carry materialized and database-only timeline rows forward into the connector render.
const carried = await materializeTimeline(engine, parsed, row.slug, snapshot, 'preserving');
// Facts and takes fences added on the brain (remember, loop extraction) are not part of the provider's render;
@@ -935,16 +1026,19 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
if (snapshot?.page.frontmatter.visibility === 'private') page.frontmatter.visibility = 'private';
},
prepare: async value => { prepared = value; return value.result; } });
- if (!prepared || prepared.slug !== row.slug) throw new OperationError('revision_conflict', result.error ?? 'A different page owns this connector content.');
+ if (!prepared || prepared.slug !== row.slug) throw connectorPublicationRefusal('revision_conflict', result.error ?? 'A different page owns this connector content.', row,
+ `Another page already owns this connector content's identity, so ${row.slug} was not written.`);
const ready = prepared;
- if (ready.observedRevision !== (snapshot?.revision ?? null)) throw new OperationError('revision_conflict', 'The connector page changed during preparation.');
+ if (ready.observedRevision !== (snapshot?.revision ?? null)) throw connectorPublicationRefusal('revision_conflict', 'The connector page changed during preparation.', row,
+ `Page ${row.slug} in ${row.source_id} changed while this connector write was being prepared.`);
const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, snapshot, 'preserving');
const tags = [...new Set([...(snapshot?.tags ?? []), ...ready.parsedPage.tags])].sort();
const page: Page = { ...(snapshot?.page ?? { id: 0, slug: row.slug, source_id: row.source_id, created_at: new Date(row.created_at), updated_at: new Date(row.created_at) }), ...ready.parsedPage };
const target = await connectorFileTarget(engine, row, snapshot, serializePageToMarkdown(page, tags), p.sourcePath, p.canonicalRoot);
// Google pages hold private mail: derived here from the stored connector, never submitted, so request ids are unchanged.
const file = target && p.connector === 'google' ? { ...target, publishMode: 0o600 } : target;
- if (file && (file.path !== p.filePath || file.expectedBeforeHash !== p.fileBeforeHash)) throw new OperationError('source_changed', 'The connector canonical file changed during preparation.');
+ if (file && (file.path !== p.filePath || file.expectedBeforeHash !== p.fileBeforeHash)) throw connectorPublicationRefusal('source_changed', 'The connector canonical file changed during preparation.', row,
+ `The canonical file of ${row.slug} in ${row.source_id} changed on disk while this connector write was being prepared.`);
return { observedRevision: ready.observedRevision, sourceExclusive: true,
validate: async tx => { await validate(tx); await ready.validate(tx); },
file, ...databaseOnlyPublication(row, file), noop: ready.noop, deferEmbedding: p.noEmbed, apply: async tx => {
@@ -966,7 +1060,13 @@ export async function prepareConnectorMutation(engine: BrainEngine, row: WriteRe
export async function prepareOutdatedConnectorMutation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
const cutoff = await readConnectorV2Cutoff(engine);
const preUpgrade = cutoff !== null && new Date(row.created_at).getTime() < new Date(cutoff).getTime();
- throw new OperationError('connector_intent_outdated', preUpgrade ? CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE : CONNECTOR_INTENT_OUTDATED_OLD_HOST);
+ const message = preUpgrade ? CONNECTOR_INTENT_OUTDATED_PRE_UPGRADE : CONNECTOR_INTENT_OUTDATED_OLD_HOST;
+ const hint = receiptDeliveredHint({ error_code: 'connector_intent_outdated', error_message: message, source_id: row.source_id })!;
+ throw opError('connector_intent_outdated', message, hint.suggestion, { docs: hint.docs, ...(hint.detail ? { detail: hint.detail } : {}),
+ fix: preUpgrade ? connectorSyncFix(row.source_id, 'The item is fetched again under a new request ID; no host upgrade is needed.')
+ : { argv: ['gbrain', 'upgrade'], consent: [], actor: 'user', requires_exclusive: false,
+ why: `A host running an older gbrain admitted this connector write for ${row.source_id} in the retired format.`,
+ user_message: `Please run the command shown on the host that runs connector jobs for ${row.source_id}, then sync it again.` } });
}
/** `connector_fence_below_timeline`: the item is counted toward a hold; the repair moves the fence above the sentinel. */
diff --git a/src/core/persistence/sync-discovery.ts b/src/core/persistence/sync-discovery.ts
index 8798d36b35..2a797947c8 100644
--- a/src/core/persistence/sync-discovery.ts
+++ b/src/core/persistence/sync-discovery.ts
@@ -5,6 +5,8 @@ import type { BrainEngine } from '../engine.ts';
import type { SyncOpts } from '../../commands/sync.ts';
import { parseMarkdown } from '../markdown.ts';
import { OperationError, opError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import type { RegistryCode } from '../error-registry.ts';
import { buildDetachedWorkingTreeManifest, computeSyncDelta } from '../sync-delta.ts';
import { isSyncable, isCodeFilePath, matchesAnyGlob, resolveSlugForPath } from '../sync.ts';
import { resolveSlugRootMode } from '../sync-anchor.ts';
@@ -39,19 +41,40 @@ export function syncGit(root: string, args: string[]): string {
return execFileSync('git', ['-c', 'core.quotepath=false', '-C', root, ...args],
{ encoding: 'utf8', timeout: 30_000, maxBuffer: 32 * 1024 ** 2, stdio: ['ignore', 'pipe', 'pipe'] });
}
+/**
+ * A sync file or root failed a confinement or identity check. These helpers
+ * know no source id, so the read-only fix lists every registered root.
+ */
+function syncTargetRefusal(code: RegistryCode, message: string, cause: string): OperationError {
+ return opError(code, message, `${cause} Nothing was written for it. Inspect the source on its owner (gbrain sources writer status --json lists every registered root), `
+ + 'fix the checkout there, then sync that source again; do not bypass the check or change ownership to force it.', {
+ fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows each source\'s registered root and owner to compare with the checkout.' },
+ });
+}
+/** The supported managed sync run of one source: local HEAD, no git pull, every guard kept. */
+function managedSyncFix(sourceId: string, why: string): Action {
+ return { argv: ['gbrain', 'sync', '--no-pull', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false, why,
+ verify: { argv: ['gbrain', 'sources', 'status', sourceId] } };
+}
export function readSyncFile(root: string, path: string): Buffer | null {
- if (realpathSync(root) !== resolve(root)) throw new OperationError('source_changed', 'The registered source root was replaced by a symlink.');
+ if (realpathSync(root) !== resolve(root)) throw syncTargetRefusal('source_changed', 'The registered source root was replaced by a symlink.',
+ `The registered root holding ${path} is now a symlink.`);
const absolute = resolve(root, path);
- if (!isWriteTargetContained(absolute, root)) throw new OperationError('source_changed', 'Sync file escaped its registered root.');
+ if (!isWriteTargetContained(absolute, root)) throw syncTargetRefusal('source_changed', 'Sync file escaped its registered root.',
+ `${path} resolves outside its registered source root.`);
try {
// Reject symlink components, including ones targeting another path inside the root.
let current = root;
for (const part of relative(root, absolute).split(sep)) {
current = join(current, part);
- if (lstatSync(current).isSymbolicLink()) throw new OperationError('source_changed', 'Sync cannot publish through a symlink.');
+ if (lstatSync(current).isSymbolicLink()) throw syncTargetRefusal('source_changed', 'Sync cannot publish through a symlink.',
+ `A component of ${path} is a symlink; sync reads and publishes only real files inside the root.`);
}
- if (!lstatSync(absolute).isFile()) throw new OperationError('source_changed', 'Sync target is not a regular file.');
- if (lstatSync(absolute).size > 10 * 1024 ** 2) throw new OperationError('request_too_large', 'Sync file exceeds the bounded import size.');
+ if (!lstatSync(absolute).isFile()) throw syncTargetRefusal('source_changed', 'Sync target is not a regular file.',
+ `${path} is not a regular file.`);
+ if (lstatSync(absolute).size > 10 * 1024 ** 2) throw opError('request_too_large', 'Sync file exceeds the bounded import size.',
+ `${path} is larger than the 10 MiB sync import bound, so nothing was imported from it. Shrink or split the file, or add it to the sync.exclude config, then sync its source again.`);
return readFileSync(absolute);
} catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; throw error; }
}
@@ -59,7 +82,8 @@ export const syncRawHash = (root: string, path: string): string | null => { cons
export function assertConfiguredSyncRoot(root: string, configuredRoot: string | null): void {
if (configuredRoot === null) return;
try { if (realpathSync.native(resolve(configuredRoot)) === realpathSync.native(root) && realpathSync(root) === root) return; } catch {}
- throw new OperationError('source_changed', 'The configured source directory no longer matches the accepted sync owner.');
+ throw syncTargetRefusal('source_changed', 'The configured source directory no longer matches the accepted sync owner.',
+ 'The configured directory of this source no longer resolves to the owner\'s registered root (it moved, was re-pointed, or became a symlink).');
}
function syncGitPath(context: Pick<SyncDiscovery, 'root' | 'gitRoot'>, path: string): string {
return relative(realpathSync.native(context.gitRoot), resolve(realpathSync.native(context.root), path)).split(sep).join('/');
@@ -69,12 +93,14 @@ export function assertSyncEntryOrigin(context: Pick<SyncDiscovery, 'root' | 'git
const gitPath = syncGitPath(context, entry.path);
const expected = context.slugMode === 'source-root' ? relative(context.root, resolve(context.root, entry.path)).split(sep).join('/') : gitPath;
const origin = syncOriginPath(entry.sourcePath);
- if (origin !== syncOriginPath(expected)) throw new OperationError('page_identity_changed', 'The sync path does not match its accepted origin.');
+ if (origin !== syncOriginPath(expected)) throw syncTargetRefusal('page_identity_changed', 'The sync path does not match its accepted origin.',
+ `${entry.path} no longer maps to its recorded origin ${entry.sourcePath} under this source's root.`);
if (entry.action !== 'delete') return;
if (typeof entry.working !== 'boolean') throw new OperationError('page_identity_changed', 'The legacy deletion does not identify its Git or working-tree origin.',
'Inspect the source identity, then explicitly retry failed sync discovery; the accepted request has not been rewritten.');
if (entry.working === true) {
- if (readSyncFile(context.root, entry.path) !== null) throw new OperationError('source_changed', 'The working-tree deletion no longer exists.');
+ if (readSyncFile(context.root, entry.path) !== null) throw syncTargetRefusal('source_changed', 'The working-tree deletion no longer exists.',
+ `${entry.path} is back in the working tree after its deletion was recorded, so the deletion was not applied.`);
return;
}
let tree = context.target;
@@ -95,9 +121,7 @@ export function assertSyncEntryOrigin(context: Pick<SyncDiscovery, 'root' | 'git
/** A managed-sync `writer_coordinator_required` refusal whose fix is the supported `gbrain sync --no-pull --source <id>` run. */
function managedSyncRefusal(sourceId: string, message: string, suggestion: string): OperationError {
return opError('writer_coordinator_required', message, suggestion, {
- fix: { argv: ['gbrain', 'sync', '--no-pull', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
- why: 'A managed brain syncs its registered checkout through the persistence coordinator: it imports local HEAD without git pull and keeps every ignored-file and failed-receipt guard.',
- verify: { argv: ['gbrain', 'sources', 'status', sourceId] } },
+ fix: managedSyncFix(sourceId, 'A managed brain syncs its registered checkout through the persistence coordinator: it imports local HEAD without git pull and keeps every ignored-file and failed-receipt guard.'),
});
}
/** Validate the current owner and source without enumerating a new manifest. */
@@ -113,16 +137,27 @@ export async function resolveManagedSyncContext(engine: BrainEngine, opts: SyncO
const binding = await getWorktreeBinding(engine, sourceId);
if (!source || source.archived || !binding || binding.source_incarnation !== source.incarnation ||
binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {
- throw new OperationError('owner_unavailable', 'Sync must run on the active registered worktree owner.');
+ throw opError('owner_unavailable', 'Sync must run on the active registered worktree owner.',
+ `Source ${sourceId} is archived, re-registered, or not bound to an active worktree owned by this host. Run its sync on the owner host that gbrain sources writer status --source ${sourceId} --json names; do not claim or transfer the source to make this host the owner.`,
+ { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows the owning host, binding state and incarnation of the source.' } });
}
const registeredRoot = resolve(binding.local_path, binding.relative_path);
const root = realpathSync(registeredRoot);
- if (root !== registeredRoot) throw new OperationError('source_changed', 'The registered source root identity changed.');
+ if (root !== registeredRoot) throw opError('source_changed', 'The registered source root identity changed.',
+ `The registered root of ${sourceId} now resolves somewhere else (a symlink or a moved directory), so nothing was synced. Restore the directory on the owner, then run gbrain sync --no-pull --source ${sourceId}.`,
+ { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows the root the owner registered, to compare with the directory on disk.' } });
assertConfiguredSyncRoot(root, source.local_path);
const gitRoot = realpathSync(syncGit(root, ['rev-parse', '--show-toplevel']).trim());
const requested = realpathSync(opts.srcSubpath ? resolve(opts.repoPath ?? gitRoot, opts.srcSubpath) : opts.repoPath ?? root);
- if (realpathSync.native(requested) !== realpathSync.native(root) || !isWriteTargetContained(realpathSync.native(root), realpathSync.native(gitRoot))) throw new OperationError('source_changed', 'Sync path does not match this source binding.');
- if (source.config?.kind != null) throw new OperationError('writer_coordinator_required', 'Connector sync requires its dedicated coordinator.');
+ if (realpathSync.native(requested) !== realpathSync.native(root) || !isWriteTargetContained(realpathSync.native(root), realpathSync.native(gitRoot))) throw opError('source_changed', 'Sync path does not match this source binding.',
+ `The repository path or source subpath given for ${sourceId} does not resolve to its registered root. Run gbrain sync --no-pull --source ${sourceId} without --repo or --src-subpath so it uses the registered root.`,
+ { fix: managedSyncFix(sourceId, 'Without a path override, sync reads the registered root of the source.') });
+ if (source.config?.kind != null) throw opError('writer_coordinator_required', 'Connector sync requires its dedicated coordinator.',
+ `Source ${sourceId} is a connector source, so the Git sync path does not apply. Run gbrain sync --source ${sourceId} without --repo, --src-subpath or other Git options; it dispatches to the connector.`,
+ { fix: { argv: ['gbrain', 'sync', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The sync command routes a connector source to its own coordinator.' } });
return { binding, root, gitRoot, sourceId, incarnation: source.incarnation, source };
}
export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, context?: ManagedSyncContext): Promise<SyncDiscovery> {
@@ -172,7 +207,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
};
const storable = <T extends { source_path: string | null }>(page: T) => page.source_path === null || !isWindowsColonTarget(page.source_path);
const put = (path: string, action: SyncEntry['action'], working = false) => {
- if (process.platform === 'win32' && path.includes('\\')) throw new OperationError('page_identity_changed', 'Git paths containing literal backslashes are not safe Windows sync targets.');
+ if (process.platform === 'win32' && path.includes('\\')) throw opError('page_identity_changed', 'Git paths containing literal backslashes are not safe Windows sync targets.',
+ `${path} in ${sourceId} has a literal backslash in its name, which Windows cannot store; nothing was synced. Rename it on a macOS or Linux checkout and commit, then run gbrain sync --no-pull --source ${sourceId}.`);
if (refuse(path, action)) return;
if (eligible(path)) entries.set(path, { path: relative(nativeRoot, join(nativeGitRoot, path)).split(sep).join('/'), sourcePath: sourcePath(path), action, working });
};
@@ -228,8 +264,11 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
}
}
const selected = [...entries.values()].sort((a, b) => a.action.localeCompare(b.action) || a.path.localeCompare(b.path));
- if (selected.some(e => !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path))) throw new OperationError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.');
- if (selected.length > 100_000 || Buffer.byteLength(JSON.stringify(selected)) > 16 * 1024 ** 2) throw new OperationError('request_too_large', 'Sync discovery exceeds the bounded cursor size.');
+ const unsupported = selected.find(e => !/\.mdx?$/i.test(e.path) && !isCodeFilePath(e.path));
+ if (unsupported) throw opError('writer_coordinator_required', 'Managed image sync requires a prepared importer; this sync was refused before any page write.',
+ `Managed sync of ${sourceId} imports only Markdown and code files, and this run selected others (for example ${unsupported.path}). Exclude them with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);
+ if (selected.length > 100_000 || Buffer.byteLength(JSON.stringify(selected)) > 16 * 1024 ** 2) throw opError('request_too_large', 'Sync discovery exceeds the bounded cursor size.',
+ `This sync of ${sourceId} selected ${selected.length} entries, above the 100,000-entry and 16 MiB cursor bound; nothing was written. Narrow it with --exclude or the sync.exclude config, then run gbrain sync --no-pull --source ${sourceId}.`);
const discovered: SyncDiscovery = { ...(refused.size ? { fileRefusals: [...refused.values()] } : {}), binding: { ...binding, owner_epoch: String(binding.owner_epoch), topology_generation: String(binding.topology_generation) }, root, gitRoot, sourceId, incarnation, from: source.last_commit, target, entries: selected, slugMode, ...(company ? { companyPlan: company.plan } : {}) };
// Freeze all logical identities in one database statement, before yielding
// between pages. A later interactive edit must conflict with this scan.
@@ -249,10 +288,14 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
const legacy = legacySyncOrigin(originScope, syncOriginPath(entry.sourcePath));
const origins = [...byPath.get(syncOriginPath(entry.sourcePath)) ?? [],
...(legacy ? byPath.get(legacy) ?? [] : []).filter(page => sameSyncOrigin(page.source_path!, entry.sourcePath, originScope, page.slug))];
- if (origins.length > 1) throw new OperationError('page_identity_changed', 'Several pages claim the same imported origin.');
+ if (origins.length > 1) throw opError('page_identity_changed', 'Several pages claim the same imported origin.',
+ `Pages ${origins.map(page => page.slug).join(', ')} in ${sourceId} all record ${entry.sourcePath} as their origin; nothing was written. Keep one, remove or re-point the others, then run gbrain sync --no-pull --source ${sourceId}.`,
+ { fix: { argv: ['gbrain', 'get', '--source', sourceId, '--', origins[0]!.slug], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows one of the pages that claim the origin, to decide which one keeps it.' } });
let slug = entry.slug ?? origins[0]?.slug ?? resolveSlugForPath(entry.sourcePath);
if (!slug && entry.action === 'import') slug = parseMarkdown(readSyncContent(discovered, entry), '').slug;
- if (!slug) throw new OperationError('invalid_params', 'The imported file has no usable page slug.');
+ if (!slug) throw opError('invalid_params', 'The imported file has no usable page slug.',
+ `${entry.sourcePath} in ${sourceId} yields no page slug from its path or frontmatter; nothing was written. Rename the file or set a frontmatter slug and commit, then run gbrain sync --no-pull --source ${sourceId}.`);
if (!company && entry.action === 'import' && !origins.length && !isCodeFilePath(entry.sourcePath)) {
entry.slug = slug;
claims.set(slug, [...(claims.get(slug) ?? []), entry]);
@@ -288,7 +331,8 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
? recorded.slice(prefix.length) : recorded;
const respelled = holderOrigin !== null && !holderOrigin.includes('\\') && deletions.has(holderOrigin);
const spellings = [...(holderOrigin === null || respelled ? [] : [holderOrigin]), ...candidates.map(entry => syncOriginPath(entry.sourcePath))].map(spelling);
- if (new Set(spellings).size !== spellings.length) throw new OperationError('page_identity_changed', 'Sync origins for one slug differ only by case or separator spelling.');
+ if (new Set(spellings).size !== spellings.length) throw opError('page_identity_changed', 'Sync origins for one slug differ only by case or separator spelling.',
+ `Files mapping to page ${slug} in ${sourceId} differ only by case or separator spelling (${candidates.slice(0, 3).map(entry => entry.sourcePath).join(', ')}); nothing was written. Keep one spelling, rename or remove the others and commit, then run gbrain sync --no-pull --source ${sourceId}.`);
// A live page keeps its slug while its own file is still in the tree; the newcomer is the collision.
const kept = holder && !deleted.has(holder.id) && holderOrigin !== null && !deletions.has(holderOrigin) ? holderOrigin : null;
const winner = kept === null ? candidates.find(entry => /\.mdx?$/i.test(entry.sourcePath) && entry.sourcePath.replace(/\.mdx?$/i, '') === slug) ?? candidates[0] : null;
@@ -329,7 +373,9 @@ export async function discoverManagedSync(engine: BrainEngine, opts: SyncOpts, c
export function readSyncContent(discovery: SyncDiscovery, entry: SyncEntry): string {
if (entry.working) {
const bytes = readSyncFile(discovery.root, entry.path);
- if (bytes === null) throw new OperationError('source_changed', 'The discovered working-tree file disappeared.');
+ if (bytes === null) throw opError('source_changed', 'The discovered working-tree file disappeared.',
+ `${entry.path} left the working tree of ${discovery.sourceId} between discovery and import, so nothing was imported from it. Run gbrain sync --no-pull --source ${discovery.sourceId} to rediscover the tree.`,
+ { fix: managedSyncFix(discovery.sourceId, 'A new discovery reads the working tree as it is now.') });
return bytes.toString('utf8');
}
return syncGit(discovery.gitRoot, ['show', `${discovery.target}:${syncGitPath(discovery, entry.path)}`]);
diff --git a/src/core/persistence/sync-prepare.ts b/src/core/persistence/sync-prepare.ts
index 2e843525ea..91bb8754f3 100644
--- a/src/core/persistence/sync-prepare.ts
+++ b/src/core/persistence/sync-prepare.ts
@@ -3,7 +3,9 @@ import { basename, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { Page } from '../types.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import type { RegistryCode } from '../error-registry.ts';
import { importFromContent, importCodeFile } from '../import-file.ts';
import { parseMarkdown, resolveParsedSubtype, serializePageToMarkdown } from '../markdown.ts';
import { resolveSlugForPath, slugifyPath, isCodeFilePath } from '../sync.ts';
@@ -28,7 +30,7 @@ import type { CompanyBrainPlan } from '../company-brain/types.ts';
import { companyBrainProfile } from '../company-brain/profile.ts';
import { companyBrainPolicyFingerprint } from '../company-brain/policy.ts';
import { isUnboundSourcePage, UNBOUND_COLLISION_MESSAGE } from './unbound-source.ts';
-import { findIncompleteSyncReceipt } from './checkpoint-validation.ts';
+import { checkpointRetryCommand, findIncompleteSyncReceipt } from './checkpoint-validation.ts';
import { frontmatterSlugConflictMessage } from './verb-errors.ts';
import { CHUNKER_VERSION } from '../chunkers/code.ts';
@@ -53,10 +55,36 @@ export interface SyncIntent extends Record<string, unknown> {
syncAuthority: SyncAuthority; cursorKey: string; runId: string; index: number;
from: string | null; target: string; total: number; slugMode: 'git-root' | 'source-root';
}
+/**
+ * Read-only: the receipt itself for the local CLI writer's own request;
+ * another principal's request is inspected on the owner instead.
+ */
+function syncInspectFix(row: WriteRequest, requestId: string, owner: boolean): Action {
+ return owner || row.principal_kind !== 'local_cli'
+ ? { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows the source\'s owner, cursor and every pending, failed or recovering receipt without changing anything.' }
+ : { argv: ['gbrain', 'write-request', '--', requestId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'The receipt records whether this sync write published anything; nothing is resubmitted until it is final.' };
+}
+
+/**
+ * Publishing an accepted managed-sync request was refused. The coordinator
+ * keeps only code and message, so the suggestion stands alone: inspect the
+ * request, then rerun the exact failed-run command once the cause is fixed.
+ */
+function syncPublicationRefusal(code: RegistryCode, message: string, row: WriteRequest, p: SyncIntent | null, cause: string, inspectOwner = false): OperationError {
+ const fix = syncInspectFix(row, row.request_id, inspectOwner);
+ const rerun = checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p?.processingOptions, syncOptions: p?.syncOptions, repoPath: p?.repoPath });
+ return opError(code, message, `${cause} Request ${row.request_id} in ${row.source_id} was refused; inspect it first (${fix.argv!.join(' ')}) and do not resubmit it. `
+ + `Once it is final and the cause is fixed, run: ${rerun}`, { fix });
+}
+
export async function prepareManagedSyncMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as SyncIntent | null;
- if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw new OperationError('invalid_params', 'Unsupported internal sync intent.');
- if (p.unownedDeletion && p.kind !== 'managed_sync_delete') throw new OperationError('invalid_params', 'Only a deletion can record an unowned path.');
+ if (!p || !['managed_sync_import', 'managed_sync_delete', 'managed_sync_checkpoint'].includes(p.kind)) throw syncPublicationRefusal('invalid_params', 'Unsupported internal sync intent.', row, p,
+ 'The request does not carry a managed sync intent this release can publish.');
+ if (p.unownedDeletion && p.kind !== 'managed_sync_delete') throw syncPublicationRefusal('invalid_params', 'Only a deletion can record an unowned path.', row, p,
+ 'Its intent records an unowned path on something other than a deletion.');
const originPageId = p.unownedDeletion ? null : row.page_id;
await assertManagedSyncActive(engine);
if (p.kind !== 'managed_sync_delete' && (!p.processingOptions ||
@@ -66,7 +94,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
}
await validateSyncAuthority(engine, p.syncAuthority, row.slug);
const binding = await getWorktreeBinding(engine, row.source_id);
- if (!binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw new OperationError('owner_unavailable', 'The accepted sync owner changed.');
+ if (!binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner changed.', row, p,
+ `The canonical owner of ${row.source_id} changed, or lost its local path, after this sync was admitted. Do not claim or transfer the source to repair content.`, true);
const root = join(binding.local_path, binding.relative_path);
const [configuredSource] = await engine.executeRaw<{ local_path: string | null }>('SELECT local_path FROM sources WHERE id=$1', [row.source_id]);
assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
@@ -76,7 +105,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
let originContext: Parameters<typeof assertSyncEntryOrigin>[0] | undefined;
let originScope: SyncOriginScope | undefined;
if (p.kind !== 'managed_sync_checkpoint') {
- if (typeof p.path !== 'string' || typeof p.sourcePath !== 'string') throw new OperationError('storage_error', 'The accepted sync origin is missing.');
+ if (typeof p.path !== 'string' || typeof p.sourcePath !== 'string') throw syncPublicationRefusal('storage_error', 'The accepted sync origin is missing.', row, p,
+ 'The stored intent has no recorded file path for this page.');
let working = p.working;
if (p.kind === 'managed_sync_delete' && working === undefined) {
const [manifest] = await engine.executeRaw<{ entry: { path: string; sourcePath: string; action: string; working: boolean; pageId?: number | null } }>(
@@ -101,7 +131,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (!moved || moved.slug === row.slug) return;
const previous = await tx.readPageSnapshot(moved.slug, { sourceId: row.source_id, includeDeleted: true });
if (previous?.page.id !== moved.pageId || previous.revision !== moved.revision || previous.page.deleted_at != null) {
- throw new OperationError('revision_conflict', 'The renamed page changed after sync admission.');
+ throw syncPublicationRefusal('revision_conflict', 'The renamed page changed after sync admission.', row, p,
+ `Page ${moved.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);
}
};
const validate = async (tx: BrainEngine) => {
@@ -111,12 +142,15 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
assertConfiguredSyncRoot(root, configuredSource?.local_path ?? null);
const [cursor] = await tx.executeRaw<{ run_id: string; request_id: string | null }>(
"SELECT completed_keys->0->>'runId' AS run_id,completed_keys->0->'pending'->>'requestId' AS request_id FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR SHARE", [p.cursorKey]);
- if (cursor && (cursor.run_id !== p.runId || cursor.request_id !== row.request_id)) throw new OperationError('revision_conflict', 'The accepted sync cursor changed before publication.');
+ if (cursor && (cursor.run_id !== p.runId || cursor.request_id !== row.request_id)) throw syncPublicationRefusal('revision_conflict', 'The accepted sync cursor changed before publication.', row, p,
+ `Another sync run of ${row.source_id} replaced the cursor this request belongs to.`);
const current = await getWorktreeBinding(tx, row.source_id);
- if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw new OperationError('owner_unavailable', 'The accepted sync owner epoch changed.');
+ if (!current || String(current.owner_epoch) !== p.ownerEpoch) throw syncPublicationRefusal('owner_unavailable', 'The accepted sync owner epoch changed.', row, p,
+ `The owner epoch of ${row.source_id} changed after this sync was admitted. Do not claim or transfer the source to repair content.`, true);
if (p.kind !== 'managed_sync_checkpoint') await assertKnowledgePublicationAllowed(tx, row,
p.path === null ? undefined : { root, path: join(root, p.path) });
- if (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw new OperationError('source_changed', 'The imported file changed after sync admission.');
+ if (p.path !== null && syncRawHash(root, p.path) !== p.rawHash) throw syncPublicationRefusal('source_changed', 'The imported file changed after sync admission.', row, p,
+ `The file of ${row.slug} changed on disk after this sync was admitted; review the change and commit it.`);
if (origin && originContext) {
assertSyncEntryOrigin(originContext, origin);
await assertSyncPageOrigin(tx, row.source_id, origin.sourcePath, originPageId, p.kind === 'managed_sync_delete', originScope);
@@ -128,7 +162,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const policy = companyBrainProfile(source?.config);
if (!policy || policy.planDigest !== p.companyApproval.planDigest || policy.extractorVersion !== p.companyApproval.extractorVersion || policy.approvedRevision !== p.target ||
companyBrainPolicyFingerprint(policy, row.source_id) !== p.companyApproval.policyFingerprint) {
- throw new OperationError('source_changed', 'The company source approval changed.');
+ throw syncPublicationRefusal('source_changed', 'The company source approval changed.', row, p,
+ `The approved company-brain plan of ${row.source_id} changed after this sync was admitted, so the run needs the current approval.`);
}
const schema = p.companyApproval.schema;
await checkApprovedSchemaForEngine(tx, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest }, { remote: false, sourceId: row.source_id });
@@ -138,18 +173,24 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const [cursor] = await tx.executeRaw<{ completed_keys: [{ runId: string; index: number; total: number }] }>(
"SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1 FOR UPDATE", [p.cursorKey]);
if (!cursor || cursor.completed_keys[0].runId !== p.runId || cursor.completed_keys[0].index !== p.total || cursor.completed_keys[0].total !== p.total) {
- throw new OperationError('revision_conflict', 'The sync cursor is not fully committed.');
+ throw syncPublicationRefusal('revision_conflict', 'The sync cursor is not fully committed.', row, p,
+ `Not every page write of this sync run has committed, so the checkpoint of ${row.source_id} did not advance.`);
}
const [manifest] = await tx.executeRaw<{ count: number }>("SELECT jsonb_array_length(completed_keys) AS count FROM op_checkpoints WHERE op='managed-sync-manifest' AND fingerprint=$1", [p.runId]);
- if (!manifest || Number(manifest.count) !== p.total) throw new OperationError('storage_error', 'The immutable sync manifest is incomplete.');
+ if (!manifest || Number(manifest.count) !== p.total) throw syncPublicationRefusal('storage_error', 'The immutable sync manifest is incomplete.', row, p,
+ `The immutable manifest of this sync run is incomplete, so the checkpoint of ${row.source_id} did not advance.`);
const incomplete = await findIncompleteSyncReceipt(tx, row.worktree_id!, p.runId);
- if (incomplete) throw new OperationError('recovery_required', `An incomplete page receipt (request ${incomplete}) still blocks the sync checkpoint.`);
+ if (incomplete) throw opError('recovery_required', `An incomplete page receipt (request ${incomplete}) still blocks the sync checkpoint.`,
+ `Page request ${incomplete} of this sync run is still open or needs recovery, so checkpoint request ${row.request_id} of ${row.source_id} did not commit. `
+ + `Inspect request ${incomplete} and let it finish; do not resubmit it. Then run: ${checkpointRetryCommand({ sourceId: row.source_id, processingOptions: p.processingOptions, syncOptions: p.syncOptions, repoPath: p.repoPath })}`,
+ { fix: syncInspectFix(row, incomplete, false) });
// #5522: an overtaken run accepts a source another cursor already checkpointed at this exact target.
const changed = await tx.executeRaw(`UPDATE sources SET last_commit=$3,last_sync_at=now(),config=jsonb_set(${SOURCE_CONFIG_OBJECT_SQL},'{slug_root_mode}',to_jsonb($5::text)),
newest_content_at=(SELECT MAX(updated_at) FROM pages WHERE source_id=$1 AND deleted_at IS NULL)
WHERE id=$1 AND incarnation=$2::uuid AND (last_commit IS NOT DISTINCT FROM $4 OR ($6::boolean AND last_commit=$3))
AND (config->>'slug_root_mode' IS NULL OR config->>'slug_root_mode'=$5) RETURNING id`, [row.source_id, row.source_incarnation, p.target, p.from, p.slugMode, p.overtaken === true]);
- if (!changed.length) throw new OperationError('revision_conflict', 'The source checkpoint changed during this sync.');
+ if (!changed.length) throw syncPublicationRefusal('revision_conflict', 'The source checkpoint changed during this sync.', row, p,
+ `Another sync moved the commit checkpoint of ${row.source_id} while this run published.`);
// #5566: a full walk re-chunked every stale page, so acknowledge the chunker version as the legacy gate does.
if (p.from === null || p.syncOptions?.full === true) await tx.executeRaw('UPDATE sources SET chunker_version=$2 WHERE id=$1', [row.source_id, String(CHUNKER_VERSION)]);
await tx.executeRaw("UPDATE op_checkpoints SET completed_keys=jsonb_set(completed_keys,'{0,done}','true'::jsonb),updated_at=now() WHERE op='managed-sync' AND fingerprint=$1", [p.cursorKey]);
@@ -161,30 +202,37 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const recordedOrigin = moved?.slug === row.slug ? moved.sourcePath : p.sourcePath!;
const foreignOrigin = snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recordedOrigin, originScope, snapshot.page.slug);
if ((snapshot?.page.id ?? null) !== row.page_id || (p.unownedDeletion ? !foreignOrigin : foreignOrigin)) {
- throw new OperationError('page_identity_changed', 'The imported path no longer names the accepted page.');
+ throw syncPublicationRefusal('page_identity_changed', 'The imported path no longer names the accepted page.', row, p,
+ `Page ${row.slug} was recreated, or its recorded origin moved, after this sync was admitted.`);
}
if (p.unownedDeletion) return { observedRevision: snapshot!.revision, noop: true, validate,
apply: async () => ({ status: 'skipped', slug: row.slug, source_id: row.source_id, noop: true, reason: 'unowned_deleted_path' }) };
if (snapshot && snapshot.page.source_path == null && await isUnboundSourcePage(engine, row.source_id, row.slug)) {
- throw new OperationError('source_changed', UNBOUND_COLLISION_MESSAGE);
+ throw syncPublicationRefusal('source_changed', UNBOUND_COLLISION_MESSAGE, row, p,
+ `A canonical file now occupies the path of page ${row.slug}, written while ${row.source_id} was unbound; neither copy was overwritten. Rename or remove the file and commit, or copy what you need into the page first.`);
}
if (p.kind === 'managed_sync_delete') return { observedRevision: snapshot?.revision ?? null, noop: !snapshot || snapshot.page.deleted_at != null,
validate, apply: async tx => {
if (snapshot && snapshot.page.deleted_at == null) { await tx.createVersion(row.slug, source); await tx.softDeletePage(row.slug, source); }
return { status: 'soft_deleted', slug: row.slug, source_id: row.source_id, noop: !snapshot || snapshot.page.deleted_at != null };
} };
- if (typeof p.content !== 'string' || typeof p.sourcePath !== 'string' || typeof p.path !== 'string') throw new OperationError('storage_error', 'The frozen import content is missing.');
+ if (typeof p.content !== 'string' || typeof p.sourcePath !== 'string' || typeof p.path !== 'string') throw syncPublicationRefusal('storage_error', 'The frozen import content is missing.', row, p,
+ 'The stored intent has no frozen file content to import.');
if (isCodeFilePath(p.sourcePath)) {
- if (p.companyApproval) throw new OperationError('profile_incompatible', 'Company source approval permits only committed Markdown content.');
+ if (p.companyApproval) throw syncPublicationRefusal('profile_incompatible', 'Company source approval permits only committed Markdown content.', row, p,
+ `A company-brain source imports only committed Markdown, and ${row.slug} is a code file; remove it from the approved revision.`);
if (snapshot && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && snapshot.page.compiled_truth !== p.content) {
- throw new OperationError('source_changed', 'Newer code file bytes disagree with the pinned import.');
+ throw syncPublicationRefusal('source_changed', 'Newer code file bytes disagree with the pinned import.', row, p,
+ `The working tree holds newer bytes for ${row.slug} than the pinned import; sync did not overwrite them. Preserve the local edit and commit it.`);
}
let prepared: PreparedContentImport | undefined;
const result = await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true,
prepare: async value => { prepared = value; return value.result; } });
- if (!prepared || prepared.slug !== row.slug) throw new OperationError('invalid_params', result.error ?? 'The code file identity could not be prepared.');
+ if (!prepared || prepared.slug !== row.slug) throw syncPublicationRefusal('invalid_params', result.error ?? 'The code file identity could not be prepared.', row, p,
+ `The code file could not be prepared as page ${row.slug}.`);
const ready = prepared;
- if (ready.observedRevision !== (snapshot?.revision ?? null)) throw new OperationError('revision_conflict', 'The code page changed during preparation.');
+ if (ready.observedRevision !== (snapshot?.revision ?? null)) throw syncPublicationRefusal('revision_conflict', 'The code page changed during preparation.', row, p,
+ `Page ${row.slug} changed while this sync was being prepared.`);
return { observedRevision: ready.observedRevision,
validate: async tx => { await validate(tx); await ready.validate(tx); },
noop: ready.noop, deferEmbedding: true, apply: async tx => {
@@ -194,14 +242,17 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
} };
}
const schema = p.companyApproval?.schema;
- if (schema && p.processingOptions?.noSchemaPack) throw new OperationError('profile_incompatible', 'Company source approval requires its pinned schema pack.');
+ if (schema && p.processingOptions?.noSchemaPack) throw syncPublicationRefusal('profile_incompatible', 'Company source approval requires its pinned schema pack.', row,
+ { ...p, processingOptions: { ...p.processingOptions!, noSchemaPack: false } },
+ `A company-brain source imports with its pinned schema pack, so ${row.source_id} cannot sync with --no-schema-pack.`);
const activePack = p.processingOptions?.noSchemaPack ? undefined : schema ? (await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },
{ remote: false, sourceId: row.source_id })).pack.manifest : (await loadActivePackForEngine(engine, { remote: row.authority.remote, sourceId: row.source_id }).catch(() => null))?.manifest;
// A renamed page is prepared where it stands; publication moves it, then re-prepares at the new slug.
const renamed = moved && moved.slug !== row.slug ? moved : undefined;
const base = renamed ? await engine.readPageSnapshot(renamed.slug, { ...source, includeDeleted: true }) : snapshot;
if (renamed && (base?.page.id !== renamed.pageId || base.revision !== renamed.revision || base.page.deleted_at != null)) {
- throw new OperationError('revision_conflict', 'The renamed page changed after sync admission.');
+ throw syncPublicationRefusal('revision_conflict', 'The renamed page changed after sync admission.', row, p,
+ `Page ${renamed.slug}, which this file was renamed from, changed or was deleted after the sync was admitted.`);
}
// row.slug is already resolved; parseMarkdown expects a filename, as in importFromContent.
const parsedInput = parseMarkdown(p.content, `${row.slug}.md`, { activePack });
@@ -210,7 +261,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const retainedRecordedOrigin = snapshot?.page.source_path != null &&
syncOriginPath(snapshot.page.source_path) === syncOriginPath(p.sourcePath) && parsedInput.slug === snapshot.page.slug;
if (expectedSlug && parsedInput.slug !== expectedSlug && slugifyPath(parsedInput.slug) !== expectedSlug && !retainedRecordedOrigin) {
- throw new OperationError('invalid_params', frontmatterSlugConflictMessage(p.sourcePath, parsedInput.slug, expectedSlug));
+ throw syncPublicationRefusal('invalid_params', frontmatterSlugConflictMessage(p.sourcePath, parsedInput.slug, expectedSlug), row, p,
+ 'Correct the frontmatter `slug:` in the file and commit the change.');
}
if (!p.companyApproval && base && !p.lineEndingOnly && p.rawHash !== sha256(p.content) && !sameCanonicalImport(base, parsedInput)) {
// The pinned commit can simply trail the coordinator: a committed page write reaches the
@@ -221,7 +273,8 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
const working = renamed ? null : readSyncFile(root, p.path);
if (!working || sha256(working) !== p.rawHash
|| !sameCanonicalImport(base, parseMarkdown(working.toString('utf8'), `${row.slug}.md`, { activePack }))) {
- throw new OperationError('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.');
+ throw syncPublicationRefusal('source_changed', 'Newer working-tree bytes and the current page disagree with this pinned Git import.', row, p,
+ `The working tree holds newer bytes for ${row.slug} that match neither the pinned import nor the current page; sync did not overwrite them. Preserve the local edit and commit it.`);
}
return { observedRevision: snapshot?.revision ?? null, noop: true, contentUnchanged: true, validate,
apply: async () => ({ status: 'skipped', slug: row.slug, source_id: row.source_id, chunks: 0, noop: true, imported_file: true }) };
@@ -240,13 +293,16 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
filename: basename(p.sourcePath).replace(/\.mdx?$/i, ''), sourcePath: p.sourcePath, allowEmptyOverwrite: true };
const result = await importFromContent(engine, renamed?.slug ?? row.slug, importContent, { ...importOptions,
prepare: async value => { prepared = value; return value.result; } });
- if (!prepared) throw new OperationError('invalid_params', result.error ?? 'The sync file could not be prepared.');
+ if (!prepared) throw syncPublicationRefusal('invalid_params', result.error ?? 'The sync file could not be prepared.', row, p,
+ `The file could not be prepared as page ${row.slug}.`);
const ready = prepared;
- if (ready.observedRevision !== (base?.revision ?? null)) throw new OperationError('revision_conflict', 'The page changed during sync preparation.');
+ if (ready.observedRevision !== (base?.revision ?? null)) throw syncPublicationRefusal('revision_conflict', 'The page changed during sync preparation.', row, p,
+ `Page ${renamed?.slug ?? row.slug} changed while this sync was being prepared.`);
if (ready.slug !== (renamed?.slug ?? row.slug)) {
// Cross-slug dedup must never advance the origin's checkpoint without a
// guarded proof about the other identity. Keep the cursor explicitly blocked.
- throw new OperationError('revision_conflict', 'A different page already owns this file identity; resolve the duplicate before syncing.');
+ throw syncPublicationRefusal('revision_conflict', 'A different page already owns this file identity; resolve the duplicate before syncing.', row, p,
+ `Page ${ready.slug} already holds the content identity of ${renamed?.slug ?? row.slug}; resolve the duplicate pages first.`);
}
const parsed = parseMarkdown(p.content, `${row.slug}.md`, { activePack });
resolveParsedSubtype(parsed, base?.page);
@@ -258,11 +314,13 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
// A move re-infers an implicit type from the new location, as a fresh import there would.
const renamedType = renamed && parsedInput.typeExplicit !== true ? parsedInput.type : undefined;
const overlay = digest(canonical(parsed, parsed.tags)) !== digest(canonical({ ...ready.parsedPage, type: renamedType ?? ready.parsedPage.type }, tags));
- if (overlay && p.companyApproval) throw new OperationError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.');
+ if (overlay && p.companyApproval) throw syncPublicationRefusal('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.', row, p,
+ `The file of ${row.slug} needs a canonical correction, and a company-brain source never rewrites repository files; correct it in the repository and commit.`);
// #5409: a read-only mirror keeps its canonical metadata in the database only; its checkout stays the remote's bytes.
const mirrorReadOnly = overlay && await sourceMirrorReadOnly(engine, row.source_id);
const writeback = overlay && !mirrorReadOnly;
- if (writeback && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw new OperationError('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.');
+ if (writeback && !p.lineEndingOnly && p.rawHash !== sha256(p.content)) throw syncPublicationRefusal('source_changed', 'Canonical sanitization cannot overwrite newer working-tree bytes.', row, p,
+ `The canonical correction for ${row.slug} would overwrite newer working-tree bytes; preserve the local edit and commit it.`);
// A rename projects against the moved page (same id), so its pinned timeline rows carry over.
const project = await prepareCanonicalProjections(engine, ready.parsedPage, row.slug, row.source_id, base, p.companyApproval ? 'immutable' : 'file');
return { observedRevision: snapshot?.revision ?? null,
@@ -278,11 +336,13 @@ export async function prepareManagedSyncMutation(engine: BrainEngine, row: Write
if (renamed) {
// The page moves first, keeping its id, inbound links and history and leaving
// `old -> new` in slug_aliases; the file content is then prepared against it.
- if (await tx.updateSlug(renamed.slug, row.slug, source) !== 1) throw new OperationError('page_identity_changed', 'The renamed page could not move to its new slug.');
+ if (await tx.updateSlug(renamed.slug, row.slug, source) !== 1) throw syncPublicationRefusal('page_identity_changed', 'The renamed page could not move to its new slug.', row, p,
+ `Page ${renamed.slug} could not move to ${row.slug}.`);
if (renamedType) await tx.executeRaw('UPDATE pages SET type=$3 WHERE source_id=$1 AND slug=$2', [row.source_id, row.slug, renamedType]);
let movedImport: PreparedContentImport | undefined;
await importFromContent(tx, row.slug, importContent, { ...importOptions, prepare: async value => { movedImport = value; return value.result; } });
- if (!movedImport || movedImport.slug !== row.slug) throw new OperationError('page_identity_changed', 'The renamed page could not be prepared at its new slug.');
+ if (!movedImport || movedImport.slug !== row.slug) throw syncPublicationRefusal('page_identity_changed', 'The renamed page could not be prepared at its new slug.', row, p,
+ `Page ${renamed.slug} could not be prepared at ${row.slug}.`);
await movedImport.validate(tx);
applied = movedImport;
}