Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): B10 backfill topology-locks, ipc, identity, takes-prepare, sync-run, journal, bundle-files, atom-retry, sync-authority, reconcile-prepare, projection-reindex

garrytanb497029ed274
diff --git a/src/core/persistence/atom-retry.ts b/src/core/persistence/atom-retry.ts
index dc2ecc2618..008993ee52 100644
--- a/src/core/persistence/atom-retry.ts
+++ b/src/core/persistence/atom-retry.ts
@@ -1,15 +1,28 @@
import { readFileSync } from 'node:fs';
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { atomRetryInputKey, managedAtomSession, publishManagedAtoms, readAtomOrigin, resumeManagedAtoms, type AtomIntent, type ManagedAtomRetirement } from './atom-maintenance.ts';
import { isWriteReceipt } from './types.ts';
+const receiptFix = (requestId: string): Action => readFix('Reads the atom request\'s durable receipt: its state, outcome and error, read-only.',
+ { argv: ['gbrain', 'write-request', '--', requestId] });
+const drainFix = (sourceId: string): Action => ({
+ argv: ['gbrain', 'dream', '--drain', '--source', sourceId, '--json'], consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: `Re-reads source ${sourceId}'s current content and extracts its atom backlog under a new run; extraction calls the configured LLM.`,
+});
+const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows which page holds ${slug} in source ${sourceId} now, with its revision, read-only.`,
+ { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });
+
export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: string, requestId: string, retryId: string): Promise<Record<string, unknown>> {
const { withRefreshingLock } = await import('../db-lock.ts');
const { cycleLockIdFor } = await import('../cycle.ts');
return withRefreshingLock(engine, cycleLockIdFor(sourceId), async () => {
const session = await managedAtomSession(engine, sourceId, { requestId, retryId });
- if (!session?.retry) throw new OperationError('invalid_params', 'Explicit atom retry requires a managed source.');
+ if (!session?.retry) throw opError('invalid_params', 'Explicit atom retry requires a managed source.',
+ `Source ${sourceId} is not under managed persistence, so retained atom batch ${requestId} cannot be retried there; nothing was started. Run the ordinary atom drain for the source instead (it calls the configured LLM, so confirm the spend).`,
+ { fix: drainFix(sourceId) });
const retry = session.retry;
const origin = retry.origin;
const item = origin.kind === 'page'
@@ -18,7 +31,9 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strin
const current = await readAtomOrigin(engine, session, item);
// The retry runs against the current origin (its revision and visibility);
// only a change to the input the run key covers refuses it.
- if (atomRetryInputKey(session, current) !== atomRetryInputKey(session, origin)) throw new OperationError('source_changed', 'The original atom input changed; this retry cannot reuse it.');
+ if (atomRetryInputKey(session, current) !== atomRetryInputKey(session, origin)) throw opError('source_changed', 'The original atom input changed; this retry cannot reuse it.',
+ `The ${origin.kind} that atom request ${requestId} extracted from in source ${sourceId} has changed since, so its retained batch no longer applies; nothing was started. Run a fresh atom drain, which extracts from the current content.`,
+ { fix: drainFix(sourceId) });
if (await resumeManagedAtoms(engine, session, current)) return { status: 'completed', replayed: true, model_rerun: false };
const checkpoint = retry.expectedCheckpoint as Array<{ failure?: string }> | null;
if (checkpoint && !checkpoint[0]?.failure) return { status: 'completed', replayed: true, model_rerun: false };
@@ -30,12 +45,18 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strin
const p = row.intent as AtomIntent;
const target = await engine.readPageSnapshot(row.slug, { sourceId, includeDeleted: true });
const revision = row.state === 'committed' ? row.outcome?.revision : p.expected_revision ?? null;
- if (typeof revision !== 'string' && (row.state === 'committed' || revision !== null)) throw new OperationError('storage_error', 'The retained atom publication revision is unavailable.');
+ if (typeof revision !== 'string' && (row.state === 'committed' || revision !== null)) throw opError('storage_error', 'The retained atom publication revision is unavailable.',
+ `The receipt of atom page ${row.slug} (request ${row.request_id}) no longer records the revision it published against, so the retry cannot republish it; nothing was published. Read the batch's receipt, then run a fresh atom drain for source ${sourceId}.`,
+ { fix: receiptFix(requestId) });
const pageId = row.state === 'committed' ? row.page_id ?? target?.page.id ?? null : row.page_id;
if ((target?.page.id ?? null) !== pageId || (target?.revision ?? null) !== revision) {
- throw new OperationError('page_identity_changed', 'An atom target changed independently of the failed publication.');
+ throw opError('page_identity_changed', 'An atom target changed independently of the failed publication.',
+ `Atom page ${row.slug} in source ${sourceId} was edited, created, deleted or replaced after request ${requestId} failed, so republishing would overwrite that change; nothing was published. Read the page, then run a fresh atom drain if its atoms still need extracting.`,
+ { fix: pageFix(sourceId, row.slug) });
}
- if (typeof p.content !== 'string') throw new OperationError('storage_error', 'The retained atom publication content is unavailable.');
+ if (typeof p.content !== 'string') throw opError('storage_error', 'The retained atom publication content is unavailable.',
+ `The receipt of atom page ${row.slug} (request ${row.request_id}) no longer holds its content (the retained payload expired), so the retry cannot republish it; nothing was published. Read the batch's receipt, then run a fresh atom drain for source ${sourceId}.`,
+ { fix: receiptFix(requestId) });
atoms.push({ slug: row.slug, content: p.content, links: p.links ?? [], expectedTarget: { pageId, revision } });
}
const retirements: ManagedAtomRetirement[] = [];
@@ -45,14 +66,18 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strin
const revision = row.state === 'committed' ? row.outcome?.revision : p.expected_revision;
if (typeof revision !== 'string' || row.page_id === null || !target ||
target.page.id !== row.page_id || target.revision !== revision || Boolean(target.page.deleted_at) !== (row.state === 'committed')) {
- throw new OperationError('page_identity_changed', 'An atom retirement target changed independently of the failed publication.');
+ throw opError('page_identity_changed', 'An atom retirement target changed independently of the failed publication.',
+ `Atom page ${row.slug} in source ${sourceId}, which request ${requestId} was retiring, was edited, restored or replaced after the failure, so retiring it now would discard that change; nothing was published. Read the page and decide with the user whether it should still be retired.`,
+ { fix: pageFix(sourceId, row.slug) });
}
retirements.push({ slug: row.slug, pageId: row.page_id, revision });
}
const receipts = await publishManagedAtoms(engine, session, current, atoms, undefined, retirements);
return { status: 'completed', model_rerun: false, write_requests: receipts };
}
- if (!retry.rows.some(row => row.outcome?.failure)) throw new OperationError('invalid_params', 'This failed batch has no malformed extraction to retry.');
+ if (!retry.rows.some(row => row.outcome?.failure)) throw opError('invalid_params', 'This failed batch has no malformed extraction to retry.',
+ `Atom batch ${requestId} in source ${sourceId} did not fail on malformed model output, so a model rerun cannot fix it; nothing was started. Read its receipt for the recorded error and fix that cause instead.`,
+ { fix: receiptFix(requestId) });
const { runPhaseExtractAtoms } = await import('../cycle/extract-atoms.ts');
const result = await runPhaseExtractAtoms(engine, { sourceId, _managedRetry: { requestId, retryId },
_pages: item.kind === 'page' ? [item] : [], _transcripts: item.kind === 'transcript' ? [item] : [] });
@@ -60,7 +85,12 @@ export async function retryManagedAtomBatch(engine: BrainEngine, sourceId: strin
const receipts = Array.isArray(result.details?.write_requests) ? result.details.write_requests.filter(isWriteReceipt) : [];
const receipt = receipts.at(-1);
const pending = receipt && ['queued', 'running', 'recovering'].includes(receipt.state);
- const error = new OperationError(pending ? 'write_pending' : 'extraction_failed', 'The explicit atom retry did not complete; inspect its retained receipt before approving another attempt.');
+ const inspected = receipt?.request_id ?? requestId;
+ const error = opError(pending ? 'write_pending' : 'extraction_failed', 'The explicit atom retry did not complete; inspect its retained receipt before approving another attempt.',
+ pending
+ ? `The retry's atom write ${inspected} in source ${sourceId} is still queued or running and may still commit. Inspect its receipt and wait for it to settle; do not approve another attempt meanwhile.`
+ : `The retry of atom batch ${requestId} in source ${sourceId} ran the model again and failed. Read the receipt for the recorded error before asking the user to approve another paid attempt.`,
+ { fix: receiptFix(inspected) });
if (receipt) error.writeRequest = receipt;
throw error;
}
diff --git a/src/core/persistence/bundle-files.ts b/src/core/persistence/bundle-files.ts
index 110c6f8bb9..81166c4795 100644
--- a/src/core/persistence/bundle-files.ts
+++ b/src/core/persistence/bundle-files.ts
@@ -1,7 +1,9 @@
import { closeSync, constants, fchmodSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readSync, realpathSync, renameSync, unlinkSync, writeSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
import { flushDirectory, sameFileMode } from '../fs-durable.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { sha256 } from './digest.ts';
import type { BundleRecoveryRecord, FileRecoveryRecord, WriteRequest } from './model.ts';
import type { WorktreeBinding } from './ownership.ts';
@@ -15,8 +17,16 @@ export interface MutationFile {
}
export const BUNDLE_FILE_LIMITS = Object.freeze({ files: 128, fileBytes: 1024 * 1024, totalBytes: 8 * 1024 * 1024, depth: 16 });
+const ownersFix = (): Action => readFix('Shows each source\'s canonical root and owner with any pending or recovering skill publication, read-only.',
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] });
+const requestFix = (row: WriteRequest): Action => row.principal_kind === 'local_cli'
+ ? readFix(`Reads skill request ${row.request_id}'s durable receipt: its state and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })
+ : readFix(`Shows source ${row.source_id}'s owner and its pending or recovering requests, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] });
+
function unsafe(): OperationError {
- return new OperationError('storage_error', 'Skill publication requires bounded regular files without aliases, links, or special files.');
+ return opError('storage_error', 'Skill publication requires bounded regular files without aliases, links, or special files.',
+ `A skill bundle path is a symlink, hard link or special file, sits under a symlinked directory, is deeper than ${BUNDLE_FILE_LIMITS.depth} levels, or holds a file over ${BUNDLE_FILE_LIMITS.fileBytes} bytes, so it was not published or restored. Replace it with a regular file inside the source's canonical root, then publish the skill again as a new request; during recovery the owner keeps the files fenced and re-checks them on each pass.`,
+ { fix: ownersFix() });
}
/**
@@ -79,13 +89,19 @@ export function prepareBundleRecovery(files: MutationFile[], binding: WorktreeBi
for (const path of seen) if (path.startsWith(`${normalized}${sep}`) || normalized.startsWith(`${path}${sep}`)) throw unsafe();
seen.add(normalized);
const nextSize = file.content === null ? 0 : typeof file.content === 'string' ? Buffer.byteLength(file.content) : file.content.byteLength;
- if (nextSize > BUNDLE_FILE_LIMITS.fileBytes) throw new OperationError('request_too_large', 'Skill file exceeds the publication byte limit.');
+ if (nextSize > BUNDLE_FILE_LIMITS.fileBytes) throw opError('request_too_large', 'Skill file exceeds the publication byte limit.',
+ `A file of skill request ${row.request_id} in source ${row.source_id} is over the ${BUNDLE_FILE_LIMITS.fileBytes}-byte per-file limit, so nothing was published. Shrink or split it, then publish the skill again as a new request with a new request_id.`,
+ { fix: requestFix(row) });
const before = readBundleFile(file.path, root);
const beforeHash = before ? sha256(before.bytes) : null;
- if (beforeHash !== file.expectedBeforeHash) throw new OperationError('source_changed', 'A canonical skill file changed after preparation.');
+ if (beforeHash !== file.expectedBeforeHash) throw opError('source_changed', 'A canonical skill file changed after preparation.',
+ `A canonical file of skill request ${row.request_id} in source ${row.source_id} changed on disk after the request was prepared, so nothing was published. Read the skill as it is now and publish again against it with a new request_id.`,
+ { fix: requestFix(row) });
beforeBytes += before?.bytes.byteLength ?? 0;
afterBytes += nextSize;
- if (beforeBytes > BUNDLE_FILE_LIMITS.totalBytes || afterBytes > BUNDLE_FILE_LIMITS.totalBytes) throw new OperationError('request_too_large', 'Skill bundle exceeds the publication byte limit.');
+ if (beforeBytes > BUNDLE_FILE_LIMITS.totalBytes || afterBytes > BUNDLE_FILE_LIMITS.totalBytes) throw opError('request_too_large', 'Skill bundle exceeds the publication byte limit.',
+ `Skill request ${row.request_id} in source ${row.source_id} would hold more than ${BUNDLE_FILE_LIMITS.totalBytes} bytes before or after publication, so nothing was published. Shrink the bundle, then publish it again as a new request with a new request_id.`,
+ { fix: requestFix(row) });
records.push({ version: 1, path: file.path, root,
before: before?.bytes.toString('base64') ?? null, beforeHash,
afterHash: file.content === null ? null : sha256(file.content), mode: before?.mode ?? null,
@@ -104,7 +120,9 @@ export function prepareBundleRecovery(files: MutationFile[], binding: WorktreeBi
}
export function assertBundleRecoveryBinding(record: BundleRecoveryRecord, binding: WorktreeBinding, attempt: string | null): void {
- const refuse = () => new OperationError('recovery_required', 'Skill recovery identity or before-image is invalid; canonical files remain fenced.');
+ const refuse = () => opError('recovery_required', 'Skill recovery identity or before-image is invalid; canonical files remain fenced.',
+ `The recovery record for skill files under ${record.root} does not match this owner (root, owner epoch ${binding.owner_epoch} or claim) or carries a malformed before-image, so recovery stopped and the files stay fenced; nothing was restored or deleted. Show the user the owner status; never delete the files or the record to force progress.`,
+ { fix: ownersFix() });
if (!binding.local_path || record.root !== resolve(binding.local_path, binding.relative_path)
|| record.ownerEpoch !== String(binding.owner_epoch) || record.attempt !== attempt) throw refuse();
const seen = new Set<string>();
@@ -126,7 +144,9 @@ export function bundleFileHash(record: FileRecoveryRecord): string | null {
const current = readBundleFile(record.path, record.root);
const hash = current ? sha256(current.bytes) : null;
const expectedMode = hash === record.beforeHash ? record.mode : record.afterMode ?? record.mode;
- if (current && expectedMode !== null && !sameFileMode(current.mode, expectedMode)) throw new OperationError('unexpected_file_bytes', 'A canonical skill file mode changed outside publication.');
+ if (current && expectedMode !== null && !sameFileMode(current.mode, expectedMode)) throw opError('unexpected_file_bytes', 'A canonical skill file mode changed outside publication.',
+ `The permissions of ${record.path} changed outside skill publication, so it was neither published nor restored and stays fenced. Show the user the path; restoring its mode (${expectedMode.toString(8)}) is their decision, and the owner re-checks it on its next recovery pass.`,
+ { fix: ownersFix() });
return hash;
}
@@ -151,7 +171,9 @@ export function stageBundleFile(file: MutationFile, record: FileRecoveryRecord):
let offset = 0;
while (offset < content.byteLength) {
const written = writeSync(fd, content, offset, content.byteLength - offset);
- if (written <= 0) throw new OperationError('storage_error', 'Skill staging did not write the complete file.');
+ if (written <= 0) throw opError('storage_error', 'Skill staging did not write the complete file.',
+ `Staging ${file.path} stopped writing before the file was complete (a full disk or a failing volume), so it was not published; the canonical file is unchanged. Check free space on that volume, then inspect the request's receipt before publishing again.`,
+ { fix: ownersFix() });
offset += written;
}
const mode = record.afterMode ?? record.mode;
@@ -162,7 +184,9 @@ export function stageBundleFile(file: MutationFile, record: FileRecoveryRecord):
}
export function publishStagedBundleFile(record: FileRecoveryRecord, boundary?: (phase: 'file_replaced' | 'directory_flushed') => void): void {
- if (bundleFileHash(record) !== record.beforeHash) throw new OperationError('source_changed', 'The canonical skill file changed before publication.');
+ if (bundleFileHash(record) !== record.beforeHash) throw opError('source_changed', 'The canonical skill file changed before publication.',
+ `${record.path} no longer holds the bytes recorded for this skill publication (it was edited outside it), so it was not replaced. Read the skill as it is now and publish again against it with a new request_id; during recovery the owner re-checks it on each pass.`,
+ { fix: ownersFix() });
if (record.afterHash === null) {
if (record.beforeHash === null) return;
unlinkSync(record.path);
diff --git a/src/core/persistence/identity.ts b/src/core/persistence/identity.ts
index 0f0625a673..63bebc74a0 100644
--- a/src/core/persistence/identity.ts
+++ b/src/core/persistence/identity.ts
@@ -5,7 +5,8 @@ import { join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import { configDir } from '../config.ts';
import { flushDirectory } from '../fs-durable.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { sha256 } from './digest.ts';
import type { Principal, SqlEngine } from './model.ts';
import { acquireNativeLock } from './native-lock.ts';
@@ -21,6 +22,17 @@ export async function withVerifiedLocalRegistration<T>(engine: SqlEngine, regist
const writer = await verifyLocalWriter(engine, registration);
return verifiedLocalWriter.run(writer, () => run(writer));
}
+const registrationsFix = () => readFix('Lists this brain\'s local writer registrations with lane, grant and revocation state, read-only.',
+ { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] });
+const doctorFix = (why: string) => readFix(why, { argv: ['gbrain', 'doctor', '--json'] });
+function invalidIdentityFile(message: string, path: string, what: string): OperationError {
+ return opError('writer_identity_invalid', message,
+ `${path} is not a valid ${what} document, so gbrain cannot use it; nothing was changed. Do not delete or regenerate it to force progress: a new identity orphans the ownership and pending writes recorded for the old one. Show the user the path; restoring it from a backup is their decision.`,
+ { fix: doctorFix('Checks this installation\'s persistence identity and owner state without changing anything.') });
+}
+const credentialMismatch = (path: string, id: string, lane: string) => opError('permission_denied', 'Local writer credential does not match this registration.',
+ `The private credential in ${path} does not match registration ${id} in this brain's database (the file was copied from another brain or host, or the database was restored), so nothing was registered. Do not overwrite either side: show the user the path; moving the file aside and running gbrain auth local-writer register ${lane} for a new principal is their decision.`,
+ { fix: registrationsFix() });
const defaultGrant = (): LocalGrant => ({ sourceIds: ['*'], operations: null, scopes: ['read', 'write'], slugPrefixes: null });
export function persistenceHome(): string { return join(configDir(), 'persistence'); }
@@ -41,20 +53,23 @@ function privateJson<T>(path: string, create: () => T): T {
} finally { closeSync(fd); unlinkSync(temporary); }
}
export function localHostId(): string {
- const value = privateJson<{ version: number; id: string }>(join(persistenceHome(), 'host.json'), () => ({ version: 1, id: randomUUID() }));
- if (value.version !== 1 || typeof value.id !== 'string') throw new OperationError('writer_identity_invalid', 'The local writer identity is invalid.');
+ const path = join(persistenceHome(), 'host.json');
+ const value = privateJson<{ version: number; id: string }>(path, () => ({ version: 1, id: randomUUID() }));
+ if (value.version !== 1 || typeof value.id !== 'string') throw invalidIdentityFile('The local writer identity is invalid.', path, 'host identity');
return value.id;
}
export function existingLocalHostId(): string | null {
const path = join(persistenceHome(), 'host.json');
if (!existsSync(path)) return null;
const value = JSON.parse(readFileSync(path, 'utf8')) as { version: number; id: string };
- if (value.version !== 1 || typeof value.id !== 'string') throw new OperationError('writer_identity_invalid', 'The local writer identity is invalid.');
+ if (value.version !== 1 || typeof value.id !== 'string') throw invalidIdentityFile('The local writer identity is invalid.', path, 'host identity');
return value.id;
}
async function brainIdentity(engine: SqlEngine): Promise<string> {
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
- if (!brain) throw new OperationError('writer_not_initialized', 'Persistence metadata has not been initialized.');
+ if (!brain) throw opError('writer_not_initialized', 'Persistence metadata has not been initialized.',
+ 'This brain\'s database has no persistence metadata row, which the schema migrations create, so no local writer can be registered or verified; nothing changed. Run gbrain doctor --json on the brain host; if it reports pending migrations, bring the schema current with gbrain apply-migrations, then run the command again.',
+ { fix: doctorFix('Reports the schema version and any pending migrations of this brain, read-only.') });
return brain.brain_id;
}
export async function registerLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', grant = defaultGrant(), replace = false): Promise<LocalRegistration> {
@@ -62,7 +77,9 @@ export async function registerLocalWriter(engine: BrainEngine, lane: 'cli' | 'st
const path = join(persistenceHome(), `${brain}.${lane}.json`);
if (!replace) return ensureLocalWriter(engine, lane, grant, path);
const lock = await acquireNativeLock(join(persistenceHome(), 'locks', `${brain}.${lane}.registration.lock`), { timeoutMs: 5000 });
- if (!lock) throw new OperationError('writer_lock_unavailable', 'Local writer registration is busy.');
+ if (!lock) throw opError('writer_lock_unavailable', 'Local writer registration is busy.',
+ `Another process held the ${lane} writer registration lock of this brain for 5 seconds while registering or replacing it, so nothing changed. Check the registrations with the command in fix, then run the registration again only if it is still needed.`,
+ { fix: registrationsFix() });
try {
if (existsSync(path)) return await rotateLocalWriter(engine, lane, grant, path);
return await ensureLocalWriter(engine, lane, grant, path);
@@ -71,11 +88,11 @@ export async function registerLocalWriter(engine: BrainEngine, lane: 'cli' | 'st
async function ensureLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', grant: LocalGrant, path: string): Promise<LocalRegistration> {
const local = privateJson<LocalRegistration>(path, () => ({ id: randomUUID(), credential: randomBytes(32).toString('hex'), lane }));
- if (local.lane !== lane || typeof local.credential !== 'string' || typeof local.id !== 'string') throw new OperationError('writer_identity_invalid', 'Local writer registration is invalid.');
+ if (local.lane !== lane || typeof local.credential !== 'string' || typeof local.id !== 'string') throw invalidIdentityFile('Local writer registration is invalid.', path, `${lane} writer registration`);
const [existing] = await engine.executeRaw<{ revoked_at: unknown; credential_hash: string; lane: string }>(
'SELECT revoked_at,credential_hash,lane FROM persistence_local_writers WHERE id=$1::uuid', [local.id]);
if (existing?.revoked_at != null) throw new OperationError('permission_denied', 'This local writer registration was revoked.', 'Explicitly register a new writer to authorize future work.');
- if (existing && (existing.lane !== lane || existing.credential_hash !== sha256(local.credential))) throw new OperationError('permission_denied', 'Local writer credential does not match this registration.');
+ if (existing && (existing.lane !== lane || existing.credential_hash !== sha256(local.credential))) throw credentialMismatch(path, local.id, lane);
await engine.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)
VALUES($1::uuid,$2,$3,$4::text::jsonb) ON CONFLICT(id) DO NOTHING`, [local.id, lane, sha256(local.credential), JSON.stringify(grant)]);
return local;
@@ -85,7 +102,7 @@ async function ensureLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', gra
async function rotateLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', grant: LocalGrant, path: string): Promise<LocalRegistration> {
const old = JSON.parse(readFileSync(path, 'utf8')) as LocalRegistration;
if (old.lane !== lane || typeof old.id !== 'string' || typeof old.credential !== 'string') {
- throw new OperationError('writer_identity_invalid', 'Local writer registration is invalid.');
+ throw invalidIdentityFile('Local writer registration is invalid.', path, `${lane} writer registration`);
}
const next: LocalRegistration = { id: randomUUID(), credential: randomBytes(32).toString('hex'), lane };
const pending = `${path}.pending.${next.id}`;
@@ -98,7 +115,7 @@ async function rotateLocalWriter(engine: BrainEngine, lane: 'cli' | 'stdio', gra
const [prior] = await tx.executeRaw<{ credential_hash: string; lane: string }>(
'SELECT credential_hash,lane FROM persistence_local_writers WHERE id=$1::uuid FOR UPDATE', [old.id]);
if (prior && (prior.lane !== lane || prior.credential_hash !== sha256(old.credential))) {
- throw new OperationError('permission_denied', 'Local writer credential does not match this registration.');
+ throw credentialMismatch(path, old.id, lane);
}
await tx.executeRaw(`INSERT INTO persistence_local_writers(id,lane,credential_hash,grant_ceiling)
VALUES($1::uuid,$2,$3,$4::text::jsonb)`, [next.id, lane, sha256(next.credential), JSON.stringify(grant)]);
@@ -130,7 +147,9 @@ export async function verifyLocalWriter(engine: SqlEngine, local: LocalRegistrat
const actual = Buffer.from(sha256(local.credential));
const expected = Buffer.from(row?.credential_hash ?? '');
if (!row || row.revoked_at != null || row.lane !== local.lane || actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
- throw new OperationError('permission_denied', 'Local writer registration is unavailable or revoked.');
+ throw opError('permission_denied', 'Local writer registration is unavailable or revoked.',
+ `Local ${local.lane} writer registration ${local.id} is missing from this brain's database, revoked, or holds a different credential, so this caller is not authorized and nothing ran. Review it with the command in fix; replacing a revoked registration (gbrain auth local-writer register ${local.lane} --replace with the complete intended grant) is the user's decision.`,
+ { fix: registrationsFix() });
}
return { principal: { kind: row.lane === 'cli' ? 'local_cli' : 'local_stdio', id: local.id }, grant: row.grant_ceiling, remote: row.lane !== 'cli' };
}
diff --git a/src/core/persistence/ipc.ts b/src/core/persistence/ipc.ts
index 7f07995645..0dc66a0cfa 100644
--- a/src/core/persistence/ipc.ts
+++ b/src/core/persistence/ipc.ts
@@ -2,7 +2,9 @@
import net, { type Server, type Socket } from 'node:net';
import { chmodSync, lstatSync, unlinkSync } from 'node:fs';
import { isAbsolute } from 'node:path';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { resolveSocketPathForConfig, socketHasLiveListener } from '../context/resolve-ipc.ts';
import { isWriteErrorCode, isWriteReceipt, isWriteRequestId, publicWriteReceipt } from './types.ts';
import { isPersistenceAdminOperation, PERSISTENCE_ADMIN_OPERATIONS, type PersistenceAdminOperation } from './admin-contract.ts';
@@ -144,6 +146,13 @@ function administrationRequest(value: unknown): value is PersistenceIpcAdminRequ
&& isPersistenceIpcRegistration(value.registration) && value.registration.lane === 'cli';
}
+const writerStatusFix = (why: string): Action => readFix(why, { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] });
+const ownerVersionsFix = (): Action => writerStatusFix(
+ 'Shows the running owner, this host and the latest admitter and consumer versions per host, read-only, to spot a CLI and owner on different releases.');
+const clientBug = (message: string): OperationError => opError('invalid_params', message,
+ 'This gbrain build produced a malformed local persistence request, so nothing was sent to the owner. It is a client fault, not a caller mistake: run gbrain doctor --json on this host and report it to the user with the command that failed.',
+ { fix: readFix('Checks this installation and its persistence owner without changing anything.', { argv: ['gbrain', 'doctor', '--json'] }) });
+
function publicError(error: unknown): Record<string, unknown> {
if (error instanceof OperationError) return error.toJSON();
// Never reflect driver errors, SQL, credentials, or private payloads.
@@ -153,7 +162,8 @@ function publicError(error: unknown): Record<string, unknown> {
function responseFrame(value: unknown): string {
const frame = JSON.stringify(value) + '\n';
if (Buffer.byteLength(frame) > PERSISTENCE_IPC_MAX_BYTES) {
- throw new OperationError('response_too_large', 'Persistence response exceeds the local transport limit.');
+ throw opError('response_too_large', 'Persistence response exceeds the local transport limit.',
+ `Nothing larger than ${PERSISTENCE_IPC_MAX_BYTES} bytes crosses the local persistence socket, so this frame was not delivered. A write may still have committed on the owner: inspect it by its request_id (get_write_request, or gbrain write-request on the CLI) before resubmitting; for a read, ask for less (a smaller page, limit or selection).`);
}
return frame;
}
@@ -219,20 +229,30 @@ export async function startPersistenceIpcServer(
return;
}
if (record(request) && exactKeys(request, ['version', 'kind']) && request.version === 1 && request.kind === 'projection_status') {
- if (!provider.projectionStatus) throw new OperationError('unavailable', 'This owner does not report projection status.');
- if (active >= PERSISTENCE_IPC_MAX_CONNECTIONS) throw new OperationError('queue_capacity', 'The persistence listener is at capacity; retry shortly.');
+ if (!provider.projectionStatus) throw opError('unavailable', 'This owner does not report projection status.',
+ 'The running persistence owner predates projection status reporting, so the status could not be read; nothing changed. Restart the owner on this gbrain release, or read the owner state with the command in fix instead.',
+ { fix: ownerVersionsFix() });
+ if (active >= PERSISTENCE_IPC_MAX_CONNECTIONS) throw opError('queue_capacity', 'The persistence listener is at capacity; retry shortly.',
+ `All ${PERSISTENCE_IPC_MAX_CONNECTIONS} local persistence connections are busy. This status read changed nothing, so read it again in a few seconds.`);
active++;
admitted = true;
const status = await provider.projectionStatus();
if (!socket.destroyed) socket.end(responseFrame({ version: 1, ok: true, result: status }));
return;
}
- if (!operationRequest(request) && !administrationRequest(request)) throw new OperationError('invalid_params', 'Invalid persistence request envelope.');
- if (request.brain_id !== provider.brainId) throw new OperationError('source_changed', 'The persistence listener now serves a different brain.');
- if (active >= PERSISTENCE_IPC_MAX_CONNECTIONS) throw new OperationError('queue_capacity', 'The persistence listener is at capacity; retry this request ID.');
+ if (!operationRequest(request) && !administrationRequest(request)) throw opError('invalid_params', 'Invalid persistence request envelope.',
+ 'The owner rejected the request frame as malformed, so nothing was admitted. This usually means the CLI and the running owner are different gbrain releases: compare them with the command in fix, restart the owner on the CLI\'s release, then submit the request again.',
+ { fix: ownerVersionsFix() });
+ if (request.brain_id !== provider.brainId) throw opError('source_changed', 'The persistence listener now serves a different brain.',
+ `This socket's owner serves brain ${provider.brainId}, not the brain ${request.brain_id} the request was built for, so nothing was admitted. Check which brain the command targets (its brain selection) against the owner in fix, then submit the request again.`,
+ { fix: writerStatusFix('Shows the brain this host\'s owner serves and its sources, read-only.') });
+ if (active >= PERSISTENCE_IPC_MAX_CONNECTIONS) throw opError('queue_capacity', 'The persistence listener is at capacity; retry this request ID.',
+ `All ${PERSISTENCE_IPC_MAX_CONNECTIONS} local persistence connections are busy, so this request was not admitted. Submit it again in a few seconds with the same arguments and the same request_id${typeof request.params.request_id === 'string' ? ` (${request.params.request_id})` : ''}; never allocate a replacement ID.`);
active++;
admitted = true;
- if (request.kind === 'administration' && !provider.administer) throw new OperationError('unavailable', 'This owner does not support local administration.');
+ if (request.kind === 'administration' && !provider.administer) throw opError('unavailable', 'This owner does not support local administration.',
+ 'The running persistence owner was started without local administration (an older release or a non-CLI owner), so nothing ran. Restart the owner on this gbrain release, or stop it and run the administration command from the gbrain CLI on this host.',
+ { fix: ownerVersionsFix() });
const result = request.kind === 'administration' ? await provider.administer!(request) : await provider.dispatch(request);
if (!socket.destroyed) socket.end(responseFrame({ version: 1, ok: true, result }));
} catch (error) {
@@ -380,13 +400,13 @@ export async function requestPersistenceProjectionStatus(socketPath: string, tim
}
export async function requestPersistenceOperation(socketPath: string, request: PersistenceIpcRequest, timeoutMs = 30_000): Promise<unknown> {
- if (!operationRequest(request)) throw new OperationError('invalid_params', 'Invalid persistence request envelope.');
+ if (!operationRequest(request)) throw clientBug('Invalid persistence request envelope.');
return exchange(socketPath, request, timeoutMs,
typeof request.params.request_id === 'string' ? request.params.request_id : undefined);
}
export async function requestPersistenceAdministration(socketPath: string, request: PersistenceIpcAdminRequest, timeoutMs = 30_000): Promise<unknown> {
- if (!administrationRequest(request)) throw new OperationError('invalid_params', 'Invalid local administration envelope.');
+ if (!administrationRequest(request)) throw clientBug('Invalid local administration envelope.');
return exchange(socketPath, request, timeoutMs,
typeof request.params.request_id === 'string' ? request.params.request_id : undefined);
}
diff --git a/src/core/persistence/journal.ts b/src/core/persistence/journal.ts
index c004a5d153..f14cc96276 100644
--- a/src/core/persistence/journal.ts
+++ b/src/core/persistence/journal.ts
@@ -1,7 +1,9 @@
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import { assertRecoveryStagingAbsent } from './staging.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { digest, jsonBytes, requireUuid } from './digest.ts';
import { authorizeWrite } from './authority.ts';
import { journalLimitKey, oneYearCapacity, readJournalLimits, readReceiptRetentionDays } from './limits.ts';
@@ -39,6 +41,18 @@ interface Counter {
key: string; outstanding_count: number | string; intent_bytes: number | string;
lifetime_ids: number | string; terminal_bytes: number | string; recovery_bytes: number | string;
}
+/** Read-only: the receipt itself for the local CLI writer's own request; another principal's request is inspected on the owner. */
+function requestInspectFix(row: Pick<WriteRequest, 'request_id' | 'source_id' | 'principal_kind'>): Action {
+ return row.principal_kind === 'local_cli'
+ ? readFix(`Reads request ${row.request_id}'s durable receipt: its state, outcome and recorded error, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })
+ : ownerStatusFix(row.source_id);
+}
+function ownerStatusFix(sourceId: string): Action {
+ return readFix(`Shows source ${sourceId}'s owner and every pending, running or recovering request, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+}
+const lifecycleIdConflict = (requestId: string) => opError('idempotency_conflict', 'This request_id belongs to a source lifecycle operation.',
+ `Request ID ${requestId} is already recorded for a source lifecycle change of this CLI writer, so this page write was not admitted and nothing changed. Submit the page write with a new request_id.`);
export function capacityError(resource: string): OperationError {
return new OperationError('queue_capacity', `Write capacity exhausted: ${resource}.`,
'Inspect writer status and configured persistence limits. Existing requests retain their reserved completion space.');
@@ -93,7 +107,7 @@ export async function assertPageRequestIdentity(engine: SqlEngine, principal: Pr
if (principal.kind !== 'local_cli') return;
const [topology] = await engine.executeRaw('SELECT id FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=$2::uuid',
[principal.id, requireUuid(requestId)]);
- if (topology) throw new OperationError('idempotency_conflict', 'This request_id belongs to a source lifecycle operation.');
+ if (topology) throw lifecycleIdConflict(requestId);
}
export async function getWriteRequestById(engine: SqlEngine, id: string, signal?: AbortSignal): Promise<WriteRequest | null> {
const [row] = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid', [id], { signal });
@@ -136,7 +150,9 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
const binding = await tx.executeRaw(`SELECT source_id FROM persistence_source_bindings WHERE source_id=$1
AND source_incarnation=$2::uuid AND worktree_id=$3::uuid AND topology_generation=$4`,
[input.sourceId, input.sourceIncarnation, input.worktreeId, input.topologyGeneration]);
- if (!binding.length) throw new OperationError('source_changed', 'The source binding changed during admission.');
+ if (!binding.length) throw opError('source_changed', 'The source binding changed during admission.',
+ `Source ${input.sourceId}'s worktree binding changed (a claim, transfer or lifecycle change) while this write was being admitted, so nothing was accepted. Check the owner with the command in fix, then submit the write again; reusing the same request_id is safe because nothing was recorded.`,
+ { fix: ownerStatusFix(input.sourceId) });
}
// Source membership is locked before principal/counter/request guards. A
// deleted/recreated source never receives work accepted for its old identity.
@@ -149,12 +165,14 @@ async function prepareAdmission(engine: BrainEngine, input: WriteAdmission, over
const counters = await lockCounters(tx, ['brain', principalKey(input.principal)]);
if(input.principal.kind==='local_cli') {
const topology=await tx.executeRaw('SELECT id FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=$2::uuid',[input.principal.id,requestId]);
- if(topology.length) throw new OperationError('idempotency_conflict','This request_id belongs to a source lifecycle operation.');
+ if(topology.length) throw lifecycleIdConflict(requestId);
}
const prior = await getWriteRequest(tx, input.principal, requestId);
if (prior) {
if ((prior.target_kind ?? 'page') !== (input.targetKind ?? 'page') || (prior.protocol_version ?? 1) !== (input.protocolVersion ?? 1)) {
- throw new OperationError('idempotency_conflict', 'This request_id belongs to a different mutation target or protocol.');
+ throw opError('idempotency_conflict', 'This request_id belongs to a different mutation target or protocol.',
+ `Request ID ${requestId} was already accepted for a ${prior.target_kind ?? 'page'} write (protocol ${prior.protocol_version ?? 1}), so this ${input.targetKind ?? 'page'} write was not admitted. Read the original request${prior.principal_kind === 'local_cli' ? ' with the command in fix' : ' with get_write_request'} if you meant to replay it; otherwise submit this write with a new request_id.`,
+ prior.principal_kind === 'local_cli' ? { fix: requestInspectFix(prior) } : {});
}
return assertReplayIntent(prior, fingerprint);
}
@@ -283,9 +301,13 @@ export async function prepareRecovery(engine: BrainEngine, row: WriteRequest, re
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true),set_config('lock_timeout','1s',true),set_config('statement_timeout','5s',true)");
const counters = await lockCounters(tx, ['brain', `worktree:${row.worktree_id}`]);
const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
- if (!current || current.execution_token !== row.execution_token || current.state !== 'running') throw new OperationError('write_claim_lost', 'The write execution claim was superseded.');
+ if (!current || current.execution_token !== row.execution_token || current.state !== 'running') throw opError('write_claim_lost', 'The write execution claim was superseded.',
+ `Another owner pass claimed request ${row.request_id} in source ${row.source_id} before this pass recorded its recovery, so this pass stopped without publishing; the current claim finishes or recovers it. Inspect the request with the command in fix instead of resubmitting it.`,
+ { fix: requestInspectFix(row) });
if (current.recovery) {
- if (digest(current.recovery) !== digest(recovery)) throw new OperationError('recovery_required', 'An existing publication must be recovered before preparing another.');
+ if (digest(current.recovery) !== digest(recovery)) throw opError('recovery_required', 'An existing publication must be recovered before preparing another.',
+ `Request ${row.request_id} in source ${row.source_id} already holds a different publication recovery record, so nothing new was written. The owner's recovery pass restores or finishes that publication first; inspect it with the command in fix and do not resubmit the request.`,
+ { fix: requestInspectFix(row) });
return;
}
for (const c of counters) if (Number(c.recovery_bytes) + bytes > (c.key === 'brain' ? limits.brainRecoveryBytes : limits.worktreeRecoveryBytes)) throw capacityError('recovery bytes currently reserved by other requests');
@@ -305,9 +327,13 @@ export async function completeWrite(tx: SqlEngine, row: WriteRequest, state: 'co
const keys = ['brain', principalKey(requestPrincipal(row)), ...(row.worktree_id ? [`worktree:${row.worktree_id}`] : [])];
await lockCounters(tx, keys);
const [current] = await tx.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE id=$1::uuid FOR UPDATE', [row.id]);
- if (!current) throw new OperationError('not_found', 'Write request not found.');
+ if (!current) throw opError('not_found', 'Write request not found.',
+ `The journal row of request ${row.request_id} in source ${row.source_id} disappeared before its completion was recorded, so no outcome was saved. Inspect the source's requests with the command in fix before submitting anything again.`,
+ { fix: ownerStatusFix(row.source_id) });
if (isTerminal(current)) return current;
- if (row.execution_token !== current.execution_token) throw new OperationError('write_claim_lost', 'Write claim changed before completion.');
+ if (row.execution_token !== current.execution_token) throw opError('write_claim_lost', 'Write claim changed before completion.',
+ `Another owner pass claimed request ${row.request_id} in source ${row.source_id} before this pass recorded its outcome, so this pass's completion was discarded; the current claim records the final outcome. Inspect the request with the command in fix instead of resubmitting it.`,
+ { fix: requestInspectFix(row) });
const [effects] = await tx.executeRaw<{bytes:string}>(`SELECT COALESCE(SUM(octet_length(data::text)+octet_length(kind)+1024),0)::text AS bytes
FROM persistence_effects WHERE request_id=$1::uuid`,[row.id]);
if (jsonBytes(outcome) + jsonBytes(current.authority) + 1024 + Buffer.byteLength(error?.message ?? '') + Number(effects.bytes) > Number(current.terminal_reservation)) throw capacityError('terminal result and effects exceed their reserved bounded encoding');
diff --git a/src/core/persistence/projection-reindex.ts b/src/core/persistence/projection-reindex.ts
index 51cf775341..a9110f4190 100644
--- a/src/core/persistence/projection-reindex.ts
+++ b/src/core/persistence/projection-reindex.ts
@@ -1,7 +1,9 @@
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { loadConfig } from '../config.ts';
import { readProjectionSnapshot, preparePageProjection, installPageProjection, installPageEmbeddings } from '../page-state/projections.ts';
import { embedBatchWithBackoff } from '../embed-retry.ts';
@@ -13,12 +15,19 @@ import { waitForWrite, writeResponse } from './service.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
+const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows code page ${slug} in source ${sourceId} as stored now, with its revision, read-only.`,
+ { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });
+const previewFix = (sourceId: string): Action => readFix(`Previews which code pages of source ${sourceId} still need reindexing and the embedding cost, without changing anything.`,
+ { argv: ['gbrain', 'reindex-code', '--source', sourceId, '--dry-run', '--json'] });
+
export async function prepareCodeReindex(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {
- if (row.authority.remote || row.intent?.kind !== 'code_projection_reindex') throw new OperationError('permission_denied', 'Code reindex requires trusted local authority.');
+ if (row.authority.remote || row.intent?.kind !== 'code_projection_reindex') throw trustedCliRequired('Code reindex requires trusted local authority.');
const prepared = await readProjectionSnapshot(engine, row.slug, row.source_id, { allowUnsealed: true });
if (!prepared || prepared.pageKind !== 'code' || prepared.snapshot.revision !== row.intent.expected_revision
|| prepared.snapshot.sourceIncarnation !== row.source_incarnation || prepared.snapshot.page.id !== row.page_id) {
- throw new OperationError('revision_conflict', 'The code projection changed after reindex admission.');
+ throw opError('revision_conflict', 'The code projection changed after reindex admission.',
+ `Code page ${row.slug} in source ${row.source_id} changed or was replaced after reindex request ${row.request_id} was admitted, so nothing was reindexed. Run gbrain reindex-code --source ${row.source_id} again; it reads the current revision.`,
+ { fix: pageFix(row.source_id, row.slug) });
}
const noop = row.intent.force !== true && prepared.snapshot.page.text_projection_revision === prepared.snapshot.revision;
const projection = noop ? undefined : await preparePageProjection(prepared);
@@ -31,11 +40,13 @@ export async function prepareCodeReindex(engine: BrainEngine, row: WriteRequest)
export async function reindexCodeProjection(engine: BrainEngine, slug: string, sourceId: string,
opts: { force?: boolean; noEmbed?: boolean } = {}): Promise<{ status: 'imported' | 'skipped'; chunks: number }> {
const snapshot = await readProjectionSnapshot(engine, slug, sourceId, { allowUnsealed: true });
- if (!snapshot || snapshot.pageKind !== 'code') throw new OperationError('source_changed', 'The selected code page is unavailable.');
+ if (!snapshot || snapshot.pageKind !== 'code') throw opError('source_changed', 'The selected code page is unavailable.',
+ `${slug} in source ${sourceId} is no longer a code page (it was deleted, renamed or replaced after it was selected), so it was not reindexed. The preview in fix lists what still needs reindexing.`,
+ { fix: previewFix(sourceId) });
let result: { status: 'imported' | 'skipped'; chunks: number };
if (await managedPersistenceEnabled(engine)) {
const verified = currentVerifiedLocalWriter();
- if (verified?.remote) throw new OperationError('permission_denied', 'Code reindex requires a local CLI writer.');
+ if (verified?.remote) throw trustedCliRequired('Code reindex requires a local CLI writer.');
if (!verified) await registerLocalWriter(engine, 'cli');
const authority = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext,
'submit_job', sourceId, snapshot.snapshot.sourceIncarnation, slug);
@@ -58,17 +69,23 @@ export async function reindexCodeProjection(engine: BrainEngine, slug: string, s
}
if (!opts.noEmbed && result.status === 'imported') {
const prepared = await readProjectionSnapshot(engine, slug, sourceId);
- if (!prepared) throw new OperationError('revision_conflict', 'Code changed before embedding preparation.');
+ if (!prepared) throw opError('revision_conflict', 'Code changed before embedding preparation.',
+ `Code page ${slug} in source ${sourceId} changed after its text was reindexed, so no vectors were computed; the reindexed text is committed. Run gbrain reindex-code --source ${sourceId} again to embed the current revision.`,
+ { fix: previewFix(sourceId) });
const chunks = prepared.chunks.filter(c => c.embedding_is_null);
if (chunks.length) {
if (prepared.embeddingColumn.embeddingModel && prepared.embeddingColumn.embeddingModel !== prepared.embeddingModel) {
- throw new OperationError('embedding_model_mismatch', 'The configured provider does not match the active embedding column. Text recovery is complete; configure the matching model before embedding.');
+ throw opError('embedding_model_mismatch', 'The configured provider does not match the active embedding column. Text recovery is complete; configure the matching model before embedding.',
+ `This brain's active embedding column holds ${prepared.embeddingColumn.embeddingModel} vectors, but the configured model is ${prepared.embeddingModel ?? 'unset'}, so code page ${slug} in source ${sourceId} was reindexed as text only. Check the embedding setup with the command in fix; choosing the model (or migrating the brain's embeddings) is the user's decision.`,
+ { fix: readFix('Reports the brain\'s embedding provider, model, dimensions and active vector column, read-only.', { argv: ['gbrain', 'doctor', '--only', 'embeddings', '--json'] }) });
}
const vectors = await embedBatchWithBackoff(chunks.map(c => c.chunk_text));
const installed = await installPageEmbeddings(engine, prepared, chunks.map((c, i) => ({
chunk_index: c.chunk_index, chunk_text: c.chunk_text, chunk_source: c.chunk_source,
model: prepared.embeddingModel ?? undefined, embedding: vectors[i] })));
- if (!installed) throw new OperationError('revision_conflict', 'Code changed while embedding; text remains queued or searchable without new vectors.');
+ if (!installed) throw opError('revision_conflict', 'Code changed while embedding; text remains queued or searchable without new vectors.',
+ `Code page ${slug} in source ${sourceId} changed while its vectors were computed, so they were discarded. Run gbrain reindex-code --source ${sourceId} again to embed the current revision.`,
+ { fix: previewFix(sourceId) });
}
}
return result;
diff --git a/src/core/persistence/reconcile-prepare.ts b/src/core/persistence/reconcile-prepare.ts
index 683e0663fd..0c572dd422 100644
--- a/src/core/persistence/reconcile-prepare.ts
+++ b/src/core/persistence/reconcile-prepare.ts
@@ -5,7 +5,9 @@ import type { GBrainConfig } from '../config.ts';
import { importFromContent, type ParsedPage } from '../import-file.ts';
import { parseMarkdown, serializePageToMarkdown } from '../markdown.ts';
import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, restoreHiddenFactRows } from '../facts-fence.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { sealPageTextProjection } from '../page-state/projections.ts';
import { sameCanonicalImport } from '../page-state/import-guard.ts';
import { transferLegacyAtomPageState } from '../cycle/extract-atoms-page-state.ts';
@@ -21,12 +23,20 @@ import { stabilizeSafetyAssessments } from './reconcile-safety.ts';
import { assertReconcilePins, readReconcileState, staleReconcile, validateReconcileArtifact, type ReconcileState } from './reconcile-state.ts';
import { verifyReconcileBackup } from './reconcile-backup.ts';
+const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as stored now, with its revision, read-only.`,
+ { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });
+const receiptFix = (row: WriteRequest): Action => readFix('Reads the reconcile request\'s durable receipt: its state, outcome and recorded error, read-only.',
+ { argv: ['gbrain', 'write-request', '--', row.request_id] });
+const freshPreview = (sourceId: string, slug: string) => `Generate a fresh preview with gbrain sources reconcile ${sourceId} ${slug} --preview (with the same --brain), review it and apply that file; nothing from this attempt was written.`;
+
function preservePrivateFacts(incoming: string, stored: string): string {
const next = parseFactsFence(incoming), prior = parseFactsFence(stored);
- if (next.warnings.length || prior.warnings.length) throw new OperationError('invalid_params', 'Fact fences must parse losslessly before reconciliation.');
+ if (next.warnings.length || prior.warnings.length) throw opError('invalid_params', 'Fact fences must parse losslessly before reconciliation.',
+ 'The ## Facts table of the file or of the stored page has rows that do not parse cleanly, so reconciliation cannot prove its private facts are kept; nothing was written. Repair the malformed rows in the file, then generate a fresh preview and apply it.');
for (const fact of prior.facts.filter(f => f.visibility !== 'world')) {
if (next.facts.some(f => f.claim === fact.claim && (f.visibility !== fact.visibility || f.rowNum === fact.rowNum && digest(f) !== digest(fact)))) {
- throw new OperationError('permission_denied', 'Reconciliation cannot modify protected private facts; use the scoped fact workflow.');
+ throw opError('permission_denied', 'Reconciliation cannot modify protected private facts; use the scoped fact workflow.',
+ 'The reconciled page would edit, renumber or change the visibility of a private fact, which reconcile never does; nothing was written. Keep those fact rows as stored, generate a fresh preview, and change private facts through the fact tools (remember, forget) instead.');
}
}
const merged = restoreHiddenFactRows(next, prior);
@@ -51,7 +61,9 @@ export async function prepareReconcileResult(engine: BrainEngine, state: Reconci
prepareFrontmatter: page => stabilizeSafetyAssessments(page.frontmatter, state.snapshot.page.frontmatter, state.pins.assessment_at),
prepare: async prepared => { ready = prepared; return prepared.result; },
});
- if (!ready || ready.slug !== state.pins.slug) throw new OperationError('invalid_params', imported.error ?? 'Reconciliation cannot change page identity or deduplicate to another page.');
+ if (!ready || ready.slug !== state.pins.slug) throw opError('invalid_params', imported.error ?? 'Reconciliation cannot change page identity or deduplicate to another page.',
+ `The reconciled content of ${state.pins.slug} in source ${state.pins.source_id} does not import as that same page (a changed frontmatter slug or a match to another page), and reconcile never changes page identity. Keep its slug as ${state.pins.slug} in the file. ${freshPreview(state.pins.source_id, state.pins.slug)}`,
+ { fix: pageFix(state.pins.source_id, state.pins.slug) });
if (ready.observedRevision !== state.snapshot.revision) staleReconcile('revision changed during policy assessment');
const resolved = reconcileCanonical(ready.parsedPage, [...new Set([...state.snapshot.tags, ...ready.parsedPage.tags])]);
const project = await prepareCanonicalProjections(engine, resolved, state.pins.slug, state.pins.source_id, state.snapshot, writer);
@@ -60,15 +72,19 @@ export async function prepareReconcileResult(engine: BrainEngine, state: Reconci
export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRequest, _config: GBrainConfig): Promise<PreparedMutation> {
if (row.operation !== 'put_page' || row.intent?.kind !== 'canonical_reconcile' || row.authority.remote !== false || row.authority.principal.kind !== 'local_cli') {
- throw new OperationError('permission_denied', 'Canonical reconciliation requires trusted local administration.');
+ throw trustedCliRequired('Canonical reconciliation requires trusted local administration.');
}
await authorizeStoredRequest(engine, row);
const artifact = validateReconcileArtifact(row.intent.preview);
const reference = row.intent.backup_reference;
- if (typeof reference !== 'string') throw new OperationError('storage_error', 'Reconciliation has no retained preimages.');
+ if (typeof reference !== 'string') throw opError('storage_error', 'Reconciliation has no retained preimages.',
+ `Reconcile request ${row.request_id} for ${row.slug} in source ${row.source_id} carries no backup reference, so it cannot publish without its preimages. ${freshPreview(row.source_id, row.slug)}`,
+ { fix: receiptFix(row) });
verifyReconcileBackup(reference, artifact);
if (artifact.status !== 'ready' || artifact.preconditions.source_id !== row.source_id || artifact.preconditions.slug !== row.slug || artifact.preconditions.page_id !== row.page_id) {
- throw new OperationError('invalid_params', 'The reconciliation artifact does not name the accepted page.');
+ throw opError('invalid_params', 'The reconciliation artifact does not name the accepted page.',
+ `The resolved preview applied by request ${row.request_id} is not ready or names a different source, page or page id than ${row.slug} in source ${row.source_id}. ${freshPreview(row.source_id, row.slug)}`,
+ { fix: receiptFix(row) });
}
const state = await readReconcileState(engine, row.source_id, row.slug, artifact.preconditions.assessment_at);
assertReconcilePins(artifact.preconditions, state.pins);
@@ -101,7 +117,9 @@ export async function prepareReconcileMutation(engine: BrainEngine, row: WriteRe
const scanStateTransferred = final ? await transferLegacyAtomPageState(tx, state.snapshot, final) : false;
const file = parseMarkdown(readFileSync(state.path, 'utf8'), row.slug);
if (!sameCanonicalImport(final, prepared.result) || digest(reconcileCanonical(file, file.tags)) !== artifact.result_digest) {
- throw new OperationError('storage_error', 'Reconciliation canonical readback did not match the reviewed result.');
+ throw opError('storage_error', 'Reconciliation canonical readback did not match the reviewed result.',
+ `After publishing, ${row.slug} in source ${row.source_id} read back differently from the reviewed result, so the database change rolled back and the owner's recovery restores the file. Inspect request ${row.request_id}'s receipt before anything else and do not apply the preview again until it is terminal.`,
+ { fix: receiptFix(row) });
}
return { status: 'reconciled', source_id: row.source_id, slug: row.slug, backup_reference: reference,
result_digest: artifact.result_digest, database_changed: !ready.noop, file_changed: sha256(content) !== state.pins.raw_file_hash,
diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.ts
index a363186b45..fde2ab75f7 100644
--- a/src/core/persistence/sync-authority.ts
+++ b/src/core/persistence/sync-authority.ts
@@ -2,7 +2,9 @@ import { AsyncLocalStorage } from 'node:async_hooks';
import type { SyncOpts } from '../../commands/sync.ts';
import type { BrainEngine } from '../engine.ts';
import type { OperationContext } from '../ops/contract.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { currentSubmissionAuthority, currentJobSignal, authorizeJobExecution, assertCurrentRemoteJobPrincipal, authorityDigest, type RemoteJobAuthority } from '../minions/submission-authority.ts';
import { assertSourceFilesystemActive } from '../minions/source-filesystem.ts';
import { throwIfAborted } from '../abort-check.ts';
@@ -12,10 +14,18 @@ import { currentVerifiedLocalWriter, registerLocalWriter } from './identity.ts';
import type { WriteAuthority } from './model.ts';
const legacyDelegation = new AsyncLocalStorage<boolean>();
+/** The bulk sync of one source, which only the brain host's CLI may run. */
+const hostSyncFix = (sourceId: string, actor: 'user' | 'host_admin'): Action => ({
+ argv: ['gbrain', 'sync', '--no-pull', '--source', sourceId], consent: [], actor, requires_exclusive: false,
+ why: `Bulk filesystem sync of source ${sourceId} runs under the brain host's CLI writer, which reads its registered checkout without git pull.`,
+ user_message: actor === 'user'
+ ? `Syncing source ${sourceId} needs the gbrain CLI. Please run the command shown in a terminal on this machine.`
+ : `Syncing source ${sourceId} needs the gbrain CLI on the machine that hosts the brain. Please ask whoever runs that server to run the command shown.`,
+});
/** A shared-secret caller never gains durable CLI authority across activation. */
export function withLegacySyncDelegation<T>(run: () => T): T { return legacyDelegation.run(true, run); }
function assertDurableSyncCaller(): void {
- if (legacyDelegation.getStore()) throw new OperationError('permission_denied', 'Managed sync requires a durable CLI registration; the shared-secret sync lane cannot supply it.');
+ if (legacyDelegation.getStore()) throw trustedCliRequired('Managed sync requires a durable CLI registration; the shared-secret sync lane cannot supply it.');
}
export interface SyncAuthority { writer: WriteAuthority; remoteJob?: RemoteJobAuthority; remoteData?: Record<string, unknown>; }
@@ -53,7 +63,9 @@ export async function assertManagedSyncActive(engine: BrainEngine, lock = false)
export async function managedSyncAuthority(engine: BrainEngine, sourceId: string, incarnation: string, repoPath: string): Promise<SyncAuthority> {
assertDurableSyncCaller();
const current = currentSubmissionAuthority();
- if (current?.kind === 'remote_agent') throw new OperationError('permission_denied', 'Agent jobs cannot run bulk filesystem sync.');
+ if (current?.kind === 'remote_agent') throw opError('permission_denied', 'Agent jobs cannot run bulk filesystem sync.',
+ `A job submitted by an agent connection cannot read the filesystem checkout of source ${sourceId}, so nothing was synced. The brain host's operator runs the sync with the command in fix.`,
+ { fix: hostSyncFix(sourceId, 'host_admin') });
if (current?.kind === 'remote_generic') {
const data = { repoPath, sourceId, noPull: true, noEmbed: true, noExtract: true, auto_embed_backfill: false };
await authorizeJobExecution(engine, { name: 'sync', data, submission_authority: current });
@@ -64,11 +76,15 @@ export async function managedSyncAuthority(engine: BrainEngine, sourceId: string
}
const verified = currentVerifiedLocalWriter();
// A verified stdio writer retains its own lane and grant, even in the owner process.
- if (verified?.remote) throw new OperationError('permission_denied', 'Bulk sync requires the local CLI or an authenticated source-scoped admin job.');
+ if (verified?.remote) throw opError('permission_denied', 'Bulk sync requires the local CLI or an authenticated source-scoped admin job.',
+ `This stdio MCP writer cannot run bulk filesystem sync of source ${sourceId}, so nothing was synced. The user runs the command in fix in a terminal on this machine.`,
+ { fix: hostSyncFix(sourceId, 'user') });
if (!verified) await registerLocalWriter(engine, 'cli');
const writer = await submissionAuthority({ engine, remote: verified?.remote ?? false, sourceId } as OperationContext,
'submit_job', sourceId, incarnation, '__managed_sync_checkpoint__');
- if (writer.slugPrefixes !== null) throw new OperationError('permission_denied', 'Bulk sync requires a source-wide local grant.');
+ if (writer.slugPrefixes !== null) throw opError('permission_denied', 'Bulk sync requires a source-wide local grant.',
+ `This CLI writer's grant covers only some slug prefixes of source ${sourceId}, and bulk sync can touch any page, so nothing was synced. Review the grant with the command in fix; widening it (gbrain auth local-writer register cli --replace with the complete intended grant) is the user's decision.`,
+ { fix: readFix('Lists the local writer registrations with their sources, operations and slug-prefix grants, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });
return { writer };
}
export async function validateSyncAuthority(engine: BrainEngine, authority: SyncAuthority, slug: string): Promise<void> {
@@ -78,12 +94,16 @@ export async function validateSyncAuthority(engine: BrainEngine, authority: Sync
if (authority.remoteJob.grant.jobName !== 'sync' || authority.remoteJob.grant.sourceId !== authority.writer.sourceId ||
authorityDigest(authority.remoteData) !== authority.remoteJob.payloadHash ||
authorityDigest(authority.remoteJob.principal) !== authorityDigest(authority.writer.principal)) {
- throw new OperationError('permission_denied', 'Sync intent exceeds the original job grant.');
+ throw opError('permission_denied', 'Sync intent exceeds the original job grant.',
+ `The sync of source ${authority.writer.sourceId} no longer matches the job that was approved (its name, source, payload or principal changed), so it stopped before admitting anything more. Submit a new sync job for the source, or have the brain host's operator run the command in fix.`,
+ { fix: hostSyncFix(authority.writer.sourceId, 'host_admin') });
}
await assertCurrentRemoteJobPrincipal(engine, authority.remoteJob);
const [source] = await engine.executeRaw<{ created_at: string }>('SELECT created_at FROM sources WHERE id=$1', [authority.writer.sourceId]);
if (!source || new Date(source.created_at).toISOString() !== authority.remoteJob.grant.sourceCreatedAt) {
- throw new OperationError('source_changed', 'The original sync source was replaced.');
+ throw opError('source_changed', 'The original sync source was replaced.',
+ `Source ${authority.writer.sourceId} was removed and registered again after this sync job was approved, so the job no longer applies and it stopped before admitting anything more. Submit a new sync job for the current source.`,
+ { fix: readFix('Lists the registered sources with their IDs and creation times, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
}
}
@@ -97,6 +117,8 @@ export function validateManagedSyncOptions(opts: SyncOpts): void {
opts.noPull !== true || opts.noEmbed !== true || opts.noExtract !== true ||
Object.entries(opts).some(([key,value]) => value !== undefined && !allowed.has(key)) ||
((opts as Record<string,unknown>).auto_embed_backfill !== undefined && (opts as Record<string,unknown>).auto_embed_backfill !== false)) {
- throw new OperationError('permission_denied', 'Sync options exceed the originally accepted remote job.');
+ throw opError('permission_denied', 'Sync options exceed the originally accepted remote job.',
+ `A remote sync job of source ${current.grant.sourceId} runs only on its registered root with no_pull, no_embed and no_extract set and no other options; this run asked for more, so nothing was synced. Submit the job again with only those options, or have the brain host's operator run the command in fix.`,
+ { fix: hostSyncFix(current.grant.sourceId, 'host_admin') });
}
}
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 652047051f..54f6b0216a 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -2,7 +2,9 @@ import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import { loadConfig } from '../config.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { RegistryCode } from '../error-registry.ts';
import { currentSourceFilesystemSignal } from '../minions/source-filesystem.ts';
import { throwIfAborted } from '../abort-check.ts';
import { digest, sha256 } from './digest.ts';
@@ -23,7 +25,7 @@ import { importAnalyzeEveryPages, maybeRefreshPlannerStats } from '../planner-st
import { recordManagedSyncFailure, clearManagedSyncFailureAfterSuccess, formatManagedSyncFailure, type ManagedSyncFailure } from './sync-failures.ts';
import { writeFailureDiagnostic } from './verb-errors.ts';
import { extractManagedStaleLinks } from './links-maintenance.ts';
-import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointTimeoutHint } from './checkpoint-validation.ts';
+import { CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint } from './checkpoint-validation.ts';
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
import type { WriteRequest } from './model.ts';
import { assertManagedSyncAllowed } from './worktree-refresh.ts';
@@ -52,6 +54,12 @@ interface Cursor extends SyncDiscovery { runId: string; index: number; authority
const OP = 'managed-sync';
type CursorHeader = Omit<Cursor, 'entries' | 'companyPlan'> & { total: number };
const header = ({ entries, companyPlan: _plan, ...value }: Cursor): CursorHeader => ({ ...value, total: entries.length });
+/** A managed sync run stopped before admitting the current entry; the recorded failure lets --retry-failed rediscover. */
+function syncRunRefusal(code: RegistryCode, message: string, retry: Parameters<typeof checkpointRetryCommand>[0], cause: string): OperationError {
+ return opError(code, message, `${cause} Pages committed earlier in this run stay committed. Check the source with the command in fix, then run: ${checkpointRetryCommand(retry)}`,
+ { fix: readFix(`Shows source ${retry.sourceId}'s owner and every pending, failed or recovering request, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', retry.sourceId, '--json'] }) });
+}
class MissingSyncManifest extends OperationError {
constructor(readonly cursor: CursorHeader) { super('storage_error', 'The durable sync manifest is unavailable.'); }
}
@@ -90,7 +98,8 @@ async function saveCursor(engine: BrainEngine, key: string, before: Cursor | nul
await tx.executeRaw('UPDATE op_checkpoints SET updated_at=now() WHERE op=$1 AND fingerprint=$2', [`${OP}-manifest`, next.runId]);
}
const current = await readCursor(tx, key, next);
- if (!current) throw new OperationError('storage_error', 'The durable sync cursor disappeared.');
+ if (!current) throw syncRunRefusal('storage_error', 'The durable sync cursor disappeared.', next,
+ `The durable sync cursor of source ${next.sourceId} vanished inside the transaction that saved it (another run of the source finished or replaced it), so this run stopped.`);
assertActive?.();
return current;
});
@@ -153,6 +162,7 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
run: { syncOptions: SyncCursorOptions; repoPath?: string }): Promise<Pending> {
assertActive();
const entry = cursor.entries[cursor.index];
+ const retry = { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? run.syncOptions, repoPath: run.repoPath };
let slug = '__managed_sync_checkpoint__', pageId: number | null = null, revision: string | null = null;
let content: string | null = null, rawHash: string | null = null;
let lineEndingOnly = false, occupantRebound = false;
@@ -167,7 +177,9 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
if (entry.action === 'import' && cursor.companyPlan) {
const company = currentCompanyBrainSync(cursor.sourceId);
const blob = company?.entries.get(entry.path);
- if (company?.receiptId !== cursor.companyReceiptId || !blob || blob.disposition !== 'included') throw new OperationError('plan_stale', 'The durable cursor does not match its approved content manifest.');
+ if (company?.receiptId !== cursor.companyReceiptId || !blob || blob.disposition !== 'included') throw syncRunRefusal('plan_stale', 'The durable cursor does not match its approved content manifest.',
+ retry,
+ `Source ${cursor.sourceId}'s approved company-brain content manifest no longer includes ${entry.path} for this run (its approval changed, or the file is no longer an included path), so nothing was imported for it. If the approval changed, inspect and approve the repository again first (gbrain sources inspect --help).`);
content = (await readCommittedBlob(cursor.companyPlan.revision!, blob, cursor.companyPlan.limits)).toString('utf8');
assertActive();
} else content = entry.action === 'import' ? readSyncContent(cursor, entry) : null;
@@ -177,21 +189,24 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
const snapshot = await engine.readPageSnapshot(slug, { sourceId: cursor.sourceId, includeDeleted: true });
assertActive();
if (occupant && !await sameContentAtOrigin(engine, cursor, entry, key, snapshot, content!, rawHash, lineEndingOnly)) {
- throw new OperationError('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.');
+ throw syncRunRefusal('page_identity_changed', 'The imported origin no longer identifies exactly the accepted page.', retry,
+ `Page ${slug} was imported from ${entry.path} by another run of source ${cursor.sourceId} with different content after this run enumerated it, so the run stopped before admitting it.`);
}
occupantRebound = occupant !== null;
const moved = entry.renameFrom;
const recorded = moved?.slug === slug ? moved.sourcePath : entry.sourcePath;
const foreignOrigin = snapshot?.page.source_path != null && !sameSyncOrigin(snapshot.page.source_path, recorded, originScope, snapshot.page.slug);
if ((snapshot?.page.id ?? null) !== pageId || (snapshot?.revision ?? null) !== revision || (entry.unownedDeletion ? !foreignOrigin : foreignOrigin)) {
- throw new OperationError('revision_conflict', 'A page changed after this sync cursor was enumerated.');
+ throw syncRunRefusal('revision_conflict', 'A page changed after this sync cursor was enumerated.', retry,
+ `Page ${slug} in source ${cursor.sourceId} was edited, deleted or re-bound after this sync enumerated ${entry.path}, so the run stopped before admitting it.`);
}
if (moved && moved.slug !== slug) {
const previous = await engine.readPageSnapshot(moved.slug, { sourceId: cursor.sourceId, includeDeleted: true });
assertActive();
if (previous?.page.id !== moved.pageId || previous.revision !== moved.revision || previous.page.deleted_at != null ||
previous.page.source_path == null || !sameSyncOrigin(previous.page.source_path, moved.sourcePath, originScope, previous.page.slug)) {
- throw new OperationError('revision_conflict', 'A renamed page changed after this sync cursor was enumerated.');
+ throw syncRunRefusal('revision_conflict', 'A renamed page changed after this sync cursor was enumerated.', retry,
+ `Page ${moved.slug}, which ${entry.path} was renamed from, changed or was deleted after this sync enumerated it, so the run stopped before admitting the rename.`);
}
}
}
@@ -310,7 +325,9 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
assertActive();
if (!unfinished.length && (failed && ['failed', 'conflict', 'cancelled'].includes(failed.state) || !cursor.pending && !cursor.processingOptions)) {
if (cursor.processingOptions && digest(cursor.processingOptions) !== digest(processingOptions)) {
- throw new OperationError('invalid_params', 'The approved company sync must retain its original processing options.');
+ throw syncRunRefusal('invalid_params', 'The approved company sync must retain its original processing options.',
+ { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: frozenRun.repoPath },
+ `The unfinished company-brain sync of source ${cursor.sourceId} was approved with ${SYNC_PROCESSING_KEYS.map(key => `${key}=${cursor!.processingOptions![key]}`).join(', ')}, and its retry must keep exactly those processing options; nothing was retried.`);
}
phase = 'freeze';
const retry = { ...cursor, processingOptions };
@@ -373,7 +390,9 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
if (cursor.incarnation !== context.incarnation || cursor.binding.worktree_id !== context.binding.worktree_id ||
String(cursor.binding.topology_generation) !== String(context.binding.topology_generation) ||
String(cursor.binding.owner_epoch) !== String(context.binding.owner_epoch) || cursor.root !== context.root) {
- throw new OperationError('source_changed', 'The unfinished sync cursor belongs to an older source binding.');
+ throw syncRunRefusal('source_changed', 'The unfinished sync cursor belongs to an older source binding.',
+ { sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: frozenRun.repoPath },
+ `The unfinished sync cursor of source ${cursor.sourceId} was written under an older binding (its owner epoch, topology generation, worktree or root changed since), so this run stopped without importing; the retry rediscovers against the current binding.`);
}
const stored = cursor.processingOptions;
if (stored ? digest(stored) !== digest(processingOptions) : !cursor.pending) {
@@ -478,7 +497,9 @@ export async function performManagedSync(engine: BrainEngine, opts: SyncOpts, sl
}
if (pending.intent.kind === 'managed_sync_checkpoint') {
cursor = (await readCursor(engine, key))!;
- if (!cursor?.done) throw new OperationError('storage_error', 'Committed sync checkpoint lost its cursor.');
+ if (!cursor?.done) throw syncRunRefusal('storage_error', 'Committed sync checkpoint lost its cursor.',
+ { sourceId: context.sourceId, processingOptions: pending.intent.processingOptions, syncOptions: pending.intent.syncOptions ?? syncOptions, repoPath: pending.intent.repoPath ?? frozenRun.repoPath },
+ `The final checkpoint request ${pending.requestId} of this sync committed, but its cursor could not be read back to finish the run.`);
await clearManagedSyncFailureAfterSuccess(engine, key);
if (cursor.counts.added + cursor.counts.modified + cursor.counts.deleted > 0) await refreshProjectionStatistics(engine);
assertActive();
diff --git a/src/core/persistence/takes-prepare.ts b/src/core/persistence/takes-prepare.ts
index 73a2d0be3d..0d263f5f2d 100644
--- a/src/core/persistence/takes-prepare.ts
+++ b/src/core/persistence/takes-prepare.ts
@@ -1,6 +1,8 @@
import type { BrainEngine, TakeBatchInput } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { OperationError, opError, type OperationContext } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { RegistryCode } from '../error-registry.ts';
import { parseTakesFence, upsertTakeRow, supersedeRow, type ParsedTake, type TakeQuality } from '../takes-fence.ts';
import { takesPreparation as edit, TakesWriteError } from '../takes-write.ts';
import { serializePageToMarkdown } from '../markdown.ts';
@@ -31,6 +33,13 @@ export async function normalizeTakesIntent(ctx: OperationContext, params: Record
since_supplied: params.since !== undefined };
}
+/** A refused takes publication: the journal keeps code and message only, so the suggestion stands alone. */
+function takesRefusal(code: RegistryCode, message: string, row: WriteRequest, cause: string): OperationError {
+ return opError(code, message, `${cause} Takes request ${row.request_id} on ${row.slug} in source ${row.source_id} failed before anything was written; correct it and submit it as a new request with a new request_id.`,
+ { fix: readFix(`Shows page ${row.slug} in source ${row.source_id} as it is now, with its takes table and revision, read-only.`,
+ { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug], mcp: { tool: 'get_page', arguments: { slug: row.slug, source_id: row.source_id } } }) });
+}
+
function fail(error: unknown): never {
if (!(error instanceof TakesWriteError)) throw error;
const code = error.code === 'holder_denied' ? 'permission_denied' : error.code === 'row_not_found' ? 'not_found'
@@ -42,14 +51,15 @@ export async function prepareTakesMutation(engine: BrainEngine, row: WriteReques
}
async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
- if (!snapshot || snapshot.page.id !== row.page_id) throw new OperationError('page_identity_changed','The accepted page no longer exists.');
+ if (!snapshot || snapshot.page.id !== row.page_id) throw takesRefusal('page_identity_changed','The accepted page no longer exists.',row,
+ `Page ${row.slug} was deleted or replaced after the takes request was accepted.`);
const p = row.intent!;
if (p.expected_revision !== undefined) assertPageRevision(snapshot,engineMutationPrecondition(parseMutationPrecondition(p)));
const body = serializePageToMarkdown(snapshot.page,snapshot.tags);
const parsed = parseTakesFence(body);
edit.assertFenceRoundTrips(parsed);
for (const key of ['claim','kind','holder','source','evidence','unit','resolved_by']) {
- if (p[key] !== undefined && typeof p[key] !== 'string') throw new OperationError('invalid_params',`${key} must be text.`);
+ if (p[key] !== undefined && typeof p[key] !== 'string') throw takesRefusal('invalid_params',`${key} must be text.`,row,`Its ${key} is not text; pass ${key} as a string.`);
edit.assertSafeCellText(key,p[key] as string | undefined);
}
edit.assertValidWeight(p.weight as number | undefined);
@@ -61,21 +71,24 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
let result: Record<string, unknown>;
let oldRow: number | undefined;
if (row.operation === 'takes_add') {
- if (typeof p.claim !== 'string' || !p.claim.trim() || typeof p.kind !== 'string' || typeof p.holder !== 'string') throw new OperationError('invalid_params','claim, kind and holder are required.');
+ if (typeof p.claim !== 'string' || !p.claim.trim() || typeof p.kind !== 'string' || typeof p.holder !== 'string') throw takesRefusal('invalid_params','claim, kind and holder are required.',row,
+ 'takes_add needs claim, kind and holder as non-empty text.');
edit.assertHolderAllowed(p.holder,holders); requiredHolders.add(p.holder);
const added = upsertTakeRow(body,{claim:p.claim,kind:p.kind,holder:p.holder,weight:p.weight as number ?? 0.5,
source:p.source as string | undefined,sinceDate:p.since as string,active:true});
next=added.body; changed=parseTakesFence(next).takes.filter(t=>t.rowNum===added.rowNum);
result={slug:row.slug,row_num:added.rowNum,holder:p.holder};
} else {
- if (!Number.isSafeInteger(p.row_num) || Number(p.row_num)<1) throw new OperationError('invalid_params','row_num must be a positive integer.');
+ if (!Number.isSafeInteger(p.row_num) || Number(p.row_num)<1) throw takesRefusal('invalid_params','row_num must be a positive integer.',row,
+ `Pass row_num as the take's row number on the page (takes_list with page_slug ${row.slug} lists them).`);
const number=Number(p.row_num);
const target=edit.findFenceRow(parsed.takes,number,holders,row.slug);
requiredHolders.add(target.holder);
if (target.resolvedAt) throw new TakesWriteError('already_resolved','Resolved takes are immutable.');
if (!target.active) throw new TakesWriteError('row_inactive','The take was superseded.');
if (row.operation==='takes_supersede') {
- if (typeof p.claim!=='string' || !p.claim.trim()) throw new OperationError('invalid_params','claim is required.');
+ if (typeof p.claim!=='string' || !p.claim.trim()) throw takesRefusal('invalid_params','claim is required.',row,
+ 'takes_supersede needs the replacement claim as non-empty text.');
const holder=typeof p.holder==='string'?p.holder:target.holder;
edit.assertHolderAllowed(holder,holders); requiredHolders.add(holder);
const superseded=supersedeRow(body,number,{claim:p.claim,kind:p.kind as string ?? target.kind,holder,
@@ -90,13 +103,16 @@ async function prepare(engine: BrainEngine, row: WriteRequest, config: GBrainCon
updated={...target,weight:p.weight as number ?? target.weight,source:p.source as string ?? target.source,
sinceDate:p.since_supplied===true?p.since as string:target.sinceDate};
} else if (row.operation==='takes_resolve') {
- if (!['correct','incorrect','partial','unresolvable'].includes(String(p.quality))) throw new OperationError('invalid_params','Unknown resolution quality.');
- if (p.value!==undefined && (typeof p.value!=='number' || !Number.isFinite(p.value))) throw new OperationError('invalid_params','value must be finite.');
+ if (!['correct','incorrect','partial','unresolvable'].includes(String(p.quality))) throw takesRefusal('invalid_params','Unknown resolution quality.',row,
+ 'Pass quality as one of: correct, incorrect, partial, unresolvable.');
+ if (p.value!==undefined && (typeof p.value!=='number' || !Number.isFinite(p.value))) throw takesRefusal('invalid_params','value must be finite.',row,
+ 'Pass value as a finite number, or omit it.');
updated={...target,resolvedAt:String(p.resolved_at),resolvedQuality:p.quality as TakeQuality,
resolvedOutcome:p.quality==='correct'?true:p.quality==='incorrect'?false:undefined,
resolvedEvidence:p.evidence as string | undefined,resolvedValue:p.value as number | undefined,
resolvedUnit:p.unit as string | undefined,resolvedBy:String(p.resolved_by)};
- } else throw new OperationError('invalid_params','Unsupported takes mutation.');
+ } else throw takesRefusal('invalid_params','Unsupported takes mutation.',row,
+ `${row.operation} is not a takes mutation this release can publish (takes_add, takes_update, takes_supersede or takes_resolve).`);
changed=[updated]; next=edit.replaceFence(body,parsed.takes.map(t=>t.rowNum===number?updated:t));
result={slug:row.slug,row_num:number,...(row.operation==='takes_resolve'?{quality:p.quality,resolved_by:p.resolved_by}:{})};
}
diff --git a/src/core/persistence/topology-locks.ts b/src/core/persistence/topology-locks.ts
index d4cafcb9b0..06d550fada 100644
--- a/src/core/persistence/topology-locks.ts
+++ b/src/core/persistence/topology-locks.ts
@@ -2,7 +2,9 @@ import { join } from 'node:path';
import { existsSync } from 'node:fs';
import { assertPhysicalRoot } from './physical-root.ts';
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { localHostId, persistenceHome, currentVerifiedLocalWriter, readLocalWriter, verifyLocalWriter } from './identity.ts';
import { acquireNativeLock, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
import { containsPath, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
@@ -13,14 +15,20 @@ import { ACTIVE_REFRESH_STATES_SQL } from './worktree-refresh-schema.ts';
export type TopologyBinding=WorktreeBinding & { unbound?:boolean };
+const ownerStatusFix=(sourceId:string):Action=>readFix(
+ `Shows source ${sourceId}'s owner host, worktree state, pending or recovering requests and blocking effects, read-only.`,
+ {argv:['gbrain','sources','writer','status','--source',sourceId,'--json']});
+
export async function topologyPrincipal(engine: BrainEngine): Promise<string> {
const writer = currentVerifiedLocalWriter() ?? await verifyLocalWriter(engine, await readLocalWriter(engine, 'cli'));
- if (writer.remote || writer.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Source lifecycle requires a verified local CLI registration.');
+ if (writer.remote || writer.principal.kind !== 'local_cli') throw trustedCliRequired('Source lifecycle requires a verified local CLI registration.');
return writer.principal.id;
}
export async function lockTopologyPrincipal(engine: BrainEngine, id: string): Promise<void> {
const [writer] = await engine.executeRaw<{ lane: string; revoked_at: unknown }>('SELECT lane,revoked_at FROM persistence_local_writers WHERE id=$1::uuid FOR SHARE', [id]);
- if (!writer || writer.lane !== 'cli' || writer.revoked_at != null) throw new OperationError('permission_denied', 'The administering CLI registration was revoked.');
+ if (!writer || writer.lane !== 'cli' || writer.revoked_at != null) throw opError('permission_denied', 'The administering CLI registration was revoked.',
+ `CLI writer registration ${id}, which started this source lifecycle change, was revoked, so nothing changed. Replacing it is the user's decision: review the registrations with the command in fix; the user stops any running owner and runs gbrain auth local-writer register cli --replace with the complete intended grant, then starts the lifecycle command again.`,
+ {reason:'trusted_cli_required',fix:readFix('Lists the local writer registrations with their lane, grant and revocation state, read-only.',{argv:['gbrain','auth','local-writer','list','--json']})});
}
/** Native locks precede every topology/source/grant/receipt transaction. */
@@ -30,7 +38,9 @@ export async function withTopologyLocks<T>(engine: BrainEngine, sourceId: string
const handles: NativeLockHandle[] = [];
const take = async (path: string) => {
const handle = waitMs===0?await tryAcquireNativeLock(path):await acquireNativeLock(path, { timeoutMs: waitMs });
- if (!handle) throw new OperationError('write_pending', 'A source worktree is busy; retry this lifecycle request with the same request_id.');
+ if (!handle) throw opError('write_pending', 'A source worktree is busy; retry this lifecycle request with the same request_id.',
+ `Another lifecycle change, refresh or publication holds a worktree lock of source ${sourceId}, so this change did not start and nothing changed. Check the source with the command in fix, then run the same lifecycle command again with the same request_id once it is idle.`,
+ {fix:ownerStatusFix(sourceId)});
handles.push(handle);
};
try {
@@ -49,7 +59,9 @@ export async function withTopologyLocks<T>(engine: BrainEngine, sourceId: string
}
}
for (const item of bindings.sort((a,b) => a.worktree_id.localeCompare(b.worktree_id))) {
- if (item.owner_host_id !== localHostId() || !item.coordination_path) throw new OperationError('owner_unavailable', 'Run source lifecycle on the current registered owner.');
+ if (item.owner_host_id !== localHostId() || !item.coordination_path) throw opError('owner_unavailable', 'Run source lifecycle on the current registered owner.',
+ `The worktree holding source ${item.source_id || sourceId} is owned by host ${item.owner_host_id}, not this host (${localHostId()}), or has no coordination path here, so nothing changed. Run the lifecycle command on the owning host; moving ownership is a separate, deliberate writer transfer.`,
+ {fix:ownerStatusFix(sourceId)});
await take(item.coordination_path);
if(item.local_path&&existsSync(item.local_path))assertPhysicalRoot(item.local_path,{worktreeId:item.worktree_id,coordinationPath:item.coordination_path});
}
@@ -68,7 +80,9 @@ export async function lockTopologyRows(tx: BrainEngine, sourceId: string, bindin
const owners = await tx.executeRaw<{ id: string; owner_host_id: string; state: string; owner_epoch:string;topology_generation:string }>(
'SELECT id,owner_host_id,state,owner_epoch,topology_generation FROM persistence_worktrees WHERE id=ANY($1::uuid[]) ORDER BY id FOR UPDATE', [ids]);
if (owners.length !== ids.length || owners.some(row => row.owner_host_id !== localHostId() || row.state !== 'active')) {
- throw new OperationError('recovery_required', 'The affected worktree is draining, recovering, or changed ownership.');
+ throw opError('recovery_required', 'The affected worktree is draining, recovering, or changed ownership.',
+ `A worktree holding source ${sourceId} is draining, recovering, or now owned by another host, so the lifecycle change rolled back and nothing changed. Check its state with the command in fix; once it is active on this host, run the same lifecycle command again with the same request_id.`,
+ {fix:ownerStatusFix(sourceId)});
}
const [refresh] = await tx.executeRaw<{ id: string; state: string; source_ids: string[] }>(`SELECT id,state,source_ids FROM persistence_worktree_refreshes
WHERE worktree_id=ANY($1::uuid[]) AND state IN ${ACTIVE_REFRESH_STATES_SQL} AND ($2::uuid IS NULL OR id<>$2::uuid) LIMIT 1`, [ids, refreshId ?? null]);
@@ -86,14 +100,18 @@ export async function lockTopologyRows(tx: BrainEngine, sourceId: string, bindin
const owner=owners.find(owner=>owner.id===before.worktree_id)!;
if(member||host?.local_path!==before.local_path||host.coordination_path!==before.coordination_path
||String(owner.owner_epoch)!==String(before.owner_epoch)||String(owner.topology_generation)!==String(before.topology_generation))
- throw new OperationError('source_changed','The retained worktree binding changed during lifecycle preparation.');
+ throw opError('source_changed','The retained worktree binding changed during lifecycle preparation.',
+ `The unbound worktree at ${before.local_path} gained a source, moved or changed owner while the lifecycle change of ${sourceId} was prepared, so it rolled back and nothing changed. Check the current bindings with the command in fix, then run the lifecycle command again.`,
+ {fix:ownerStatusFix(sourceId)});
continue;
}
const current = await getWorktreeBinding(tx, before.source_id);
if (!current || current.worktree_id !== before.worktree_id || current.source_incarnation !== before.source_incarnation
|| String(current.owner_epoch) !== String(before.owner_epoch) || String(current.topology_generation) !== String(before.topology_generation)
|| current.local_path !== before.local_path || current.coordination_path !== before.coordination_path) {
- throw new OperationError('source_changed', 'Source membership changed during lifecycle lock acquisition.');
+ throw opError('source_changed', 'Source membership changed during lifecycle lock acquisition.',
+ `The worktree binding of source ${before.source_id} (owner epoch, topology generation or path) changed while the lifecycle change of ${sourceId} waited for its locks, so it rolled back and nothing changed. Check the current bindings with the command in fix, then run the lifecycle command again.`,
+ {fix:ownerStatusFix(sourceId)});
}
}
return sources;
@@ -110,13 +128,21 @@ export async function settleTopologyRequests(tx: BrainEngine, sources: string[],
const requests = await tx.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests
WHERE (source_id=ANY($1::text[]) OR worktree_id=ANY($2::uuid[]))
AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) ORDER BY sequence`, [sources,worktrees]);
- if (requests.some(row => row.state === 'running' || row.state === 'recovering' || row.recovery != null)) {
- throw new OperationError('write_pending', 'Publication must finish or recover before source lifecycle can proceed.');
+ const busy = requests.find(row => row.state === 'running' || row.state === 'recovering' || row.recovery != null);
+ if (busy) {
+ throw opError('write_pending', 'Publication must finish or recover before source lifecycle can proceed.',
+ `Write request ${busy.request_id} in source ${busy.source_id} is still publishing or recovering, so the lifecycle change rolled back and nothing changed. The owner finishes or recovers that write on its own; once the command in fix shows no running or recovering request, run the same lifecycle command again with the same request_id.`,
+ {fix:ownerStatusFix(busy.source_id)});
}
- const [blocked] = await tx.executeRaw(`SELECT id FROM persistence_effects WHERE
+ const [blocked] = await tx.executeRaw<{ id: string; source_id: string | null }>(`SELECT id,source_id FROM persistence_effects WHERE
(source_id=ANY($1::text[]) OR worktree_id=ANY($2::uuid[])) AND
(recovery IS NOT NULL OR state='running' OR (kind='withdrawal-mirror' AND state<>'committed')) LIMIT 1`, [sources,worktrees]);
- if (blocked) throw new OperationError('recovery_required', 'Finish the pending withdrawal mirror and publication effects before changing source topology.');
+ if (blocked) {
+ const source = blocked.source_id ?? sources[0];
+ throw opError('recovery_required', 'Finish the pending withdrawal mirror and publication effects before changing source topology.',
+ `Effect ${blocked.id} on source ${source} (a withdrawal mirror or publication effect) has not finished, so the lifecycle change rolled back and nothing changed. The owner's effect worker settles it; check it with the command in fix, which lists it with its page and request; gbrain sources writer retry-effects re-authorizes a failed or parked one. Then run the same lifecycle command again with the same request_id.`,
+ {fix:ownerStatusFix(source)});
+ }
const pending = requests.filter(row => row.state === 'queued');
// Revocation and publication use the same principal rows. Administrative
// invalidation may terminate revoked work but still respects guard ordering.