Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): B10 backfill atom-maintenance, effects, import-prepare, ownership, topology-recovery, topology-clone, facts-maintenance

garrytand2848c0b7072
diff --git a/src/core/persistence/atom-maintenance.ts b/src/core/persistence/atom-maintenance.ts
index 0f7d26277f..004c60a50b 100644
--- a/src/core/persistence/atom-maintenance.ts
+++ b/src/core/persistence/atom-maintenance.ts
@@ -2,8 +2,10 @@ import { readFileSync } from 'node:fs';
import type { BrainEngine, LinkBatchInput } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import type { OperationContext } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
import { acceptedPendingReceipt } from './accepted-pending.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { authorizeStoredRequest, authorizeWrite, submissionAuthority } from './authority.ts';
import { currentVerifiedLocalWriter, localHostId, registerLocalWriter } from './identity.ts';
@@ -53,6 +55,20 @@ export interface AtomIntent extends Record<string, unknown> {
expectedCheckpoint?: unknown;
}
+const ownerStatusFix = (sourceId: string): Action => readFix(
+ `Shows source ${sourceId}'s canonical owner, its state and any write in flight, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+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 type and revision.`,
+ { argv: ['gbrain', 'get', '--source', sourceId, '--', slug] });
+
/**
* The managed atom write target of a source and the owner refusal its session raises (null when it can run).
* An unbound connector source is database-only by design (connector_database), like its connector sync:
@@ -83,37 +99,56 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,
assertPersistenceAccepting(engine);
const caller = currentSubmissionAuthority();
if (caller && caller.kind !== 'application' || currentVerifiedLocalWriter()?.remote) {
- throw new OperationError('permission_denied', 'Atom extraction cannot mutate a managed brain through an untrusted caller; a trusted local, source-wide writer is required.');
+ throw opError('permission_denied', 'Atom extraction cannot mutate a managed brain through an untrusted caller; a trusted local, source-wide writer is required.',
+ `Run atom extraction for source ${sourceId} from the gbrain CLI in a terminal on the brain host; MCP and delegated callers cannot publish atoms. Nothing was extracted.`,
+ { reason: 'trusted_cli_required', fix: { ...drainFix(sourceId), actor: 'user',
+ user_message: 'Atom extraction has to run from a terminal on the machine that hosts this brain. Please run the command shown there; it calls the configured LLM.' } });
}
const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(
"SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'The atom source is unavailable.');
+ if (!source || source.archived) throw opError('source_changed', 'The atom source is unavailable.',
+ `Source ${sourceId} is missing or archived, so no atoms were extracted. Check the registered sources and run extraction against an active one (or restore ${sourceId} first).`,
+ { fix: readFix('Lists the registered sources with their archived state, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
if (!currentVerifiedLocalWriter()) await registerLocalWriter(engine, 'cli');
const authority = await submissionAuthority({ engine, remote: false, sourceId } as OperationContext,
'submit_job', sourceId, source.incarnation, '__managed_atom_complete__');
if (authority.slugPrefixes || authority.restrictedNamespace || authority.delegated) {
- throw new OperationError('permission_denied', 'Atom maintenance requires a source-wide grant.');
+ throw opError('permission_denied', 'Atom maintenance requires a source-wide grant.',
+ `This host's CLI writer registration is limited to slug prefixes, a restricted namespace or a delegation, so it cannot publish atoms across source ${sourceId}. Review the registration; widening it is the user's decision.`,
+ { fix: readFix('Shows the CLI writer registrations and their grants, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });
}
await authorizeWrite(engine, authority, 'put_page', 'atoms/preflight');
await authorizeWrite(engine, authority, 'delete_page', 'atoms/preflight');
const { binding, writeThrough, connectorDatabase, refusal } = await atomOwnerTarget(engine, sourceId, source);
- if (refusal) throw new OperationError('owner_unavailable', refusal);
+ if (refusal) throw opError('owner_unavailable', refusal,
+ `No extraction was started for source ${sourceId}. Check its canonical owner: run atom extraction on the host that owns the checkout, or have the user claim the checkout on this host with gbrain sources writer claim.`,
+ { fix: ownerStatusFix(sourceId) });
if (writeThrough && binding) {
- if (!await probeWorktreeWriter(binding, engine)) throw new OperationError('writer_lock_unavailable', 'The canonical atom writer is busy; no extraction was started.');
+ if (!await probeWorktreeWriter(binding, engine)) throw opError('writer_lock_unavailable', 'The canonical atom writer is busy; no extraction was started.',
+ `Another write holds source ${sourceId}'s canonical writer. Nothing was started, so run the atom drain again once the owner status shows it idle.`,
+ { fix: ownerStatusFix(sourceId) });
}
if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';
else if (connectorDatabase) authority.databaseOnlyReason = 'connector_database';
else if (!binding) authority.databaseOnlyReason = 'no_repo_configured';
const session: ManagedAtomSession = { sourceId, incarnation: source.incarnation, authority, binding: writeThrough ? binding : null, config: { engine: engine.kind } as GBrainConfig, wait };
if (retry) {
- if (!retry.retryId || retry.retryId.length > 128) throw new OperationError('invalid_params', 'A bounded explicit atom retry identity is required.');
+ if (!retry.retryId || retry.retryId.length > 128) throw opError('invalid_params', 'A bounded explicit atom retry identity is required.',
+ `Submit the atom retry for request ${retry.requestId} as an extract-atoms-drain job; the job supplies its own bounded retry identity. Nothing was started.`,
+ { fix: { argv: ['gbrain', 'jobs', 'submit', 'extract-atoms-drain', '--params', JSON.stringify({ sourceId, retryRequestId: retry.requestId })],
+ consent: ['paid'], actor: 'agent', requires_exclusive: false,
+ why: 'Queues one reviewed retry of the retained atom batch; extraction calls the configured LLM.' } });
const prior = await getWriteRequest(engine, authority.principal, requireUuid(retry.requestId));
if (!prior || prior.operation !== 'submit_job' || prior.source_id !== sourceId || prior.source_incarnation !== source.incarnation) {
- throw new OperationError('not_found', 'No retained atom batch belongs to this writer, source and request.');
+ throw opError('not_found', 'No retained atom batch belongs to this writer, source and request.',
+ `Request ${retry.requestId} is not an atom batch this CLI writer accepted for source ${sourceId}. Read the receipt to see which operation and source it belongs to; nothing was retried.`,
+ { fix: receiptFix(retry.requestId) });
}
await authorizeStoredRequest(engine, prior);
if (prior.compacted && !prior.intent) expiredAtomReceipt(prior);
- if (!String(prior.intent?.kind).startsWith('managed_atom_')) throw new OperationError('not_found', 'No retained atom batch belongs to this writer, source and request.');
+ if (!String(prior.intent?.kind).startsWith('managed_atom_')) throw opError('not_found', 'No retained atom batch belongs to this writer, source and request.',
+ `Request ${retry.requestId} in source ${sourceId} is a ${prior.operation} request, not an atom batch, so atom retry does not apply. Read its receipt instead; nothing was retried.`,
+ { fix: receiptFix(retry.requestId) });
const p = prior.intent as AtomIntent;
const rows = await atomBatchRows(engine, session, p.runKey);
for (let i = 0; i < rows.length; i++) {
@@ -123,7 +158,9 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,
}
const expired = rows.find(row => row.compacted && !row.intent);
if (expired) expiredAtomReceipt(expired);
- if (!rows.some(row => row.state !== 'committed' || row.outcome?.failure)) throw new OperationError('invalid_params', 'This atom batch already completed successfully.');
+ if (!rows.some(row => row.state !== 'committed' || row.outcome?.failure)) throw opError('invalid_params', 'This atom batch already completed successfully.',
+ `Every request in atom batch ${retry.requestId} for source ${sourceId} committed without a failure, so there is nothing to retry. Its receipt shows the outcome; new content is extracted by the regular atom drain.`,
+ { fix: receiptFix(retry.requestId) });
const checkpointKey = p.checkpointKey ?? p.runKey;
const [checkpoint] = await engine.executeRaw<{ completed_keys: unknown }>("SELECT completed_keys FROM op_checkpoints WHERE op='managed-atoms' AND fingerprint=$1", [checkpointKey]);
session.retry = { runKey: digest([checkpointKey, prior.id, retry.retryId]), checkpointKey,
@@ -135,13 +172,17 @@ export async function managedAtomSession(engine: BrainEngine, sourceId: string,
export async function readAtomOrigin(engine: BrainEngine, session: ManagedAtomSession,
item: { kind: 'page'; slug: string; content: string; contentHash: string } | { kind: 'transcript'; filePath: string; content: string; contentHash: string }): Promise<AtomOrigin> {
if (item.kind === 'transcript') {
- if (sha256(readFileSync(item.filePath)) !== sha256(item.content)) throw new OperationError('source_changed', 'The atom transcript changed before extraction.');
+ if (sha256(readFileSync(item.filePath)) !== sha256(item.content)) throw opError('source_changed', 'The atom transcript changed before extraction.',
+ `The transcript was edited while source ${session.sourceId}'s atom extraction read it; nothing was extracted from it. Run the drain again to extract the current file.`,
+ { fix: drainFix(session.sourceId) });
return { kind: item.kind, locator: item.filePath, contentHash: item.contentHash, textHash: sha256(item.content), pageId: null, revision: null,
visibility: effectiveVisibility({ kind: 'transcript' }) };
}
const snapshot = await engine.readPageSnapshot(item.slug, { sourceId: session.sourceId });
if (!snapshot || snapshot.sourceIncarnation !== session.incarnation || snapshot.page.content_hash !== item.contentHash || snapshot.page.compiled_truth !== item.content) {
- throw new OperationError('revision_conflict', 'The atom input changed before extraction.');
+ throw opError('revision_conflict', 'The atom input changed before extraction.',
+ `Page ${item.slug} in source ${session.sourceId} changed while its atoms were being prepared; nothing was extracted from it. Run the drain again to extract the current revision.`,
+ { fix: drainFix(session.sourceId) });
}
const generation = await atomGeneration(engine, snapshot.page.id, item.contentHash);
return { kind: item.kind, locator: item.slug, contentHash: item.contentHash, textHash: sha256(item.content), pageId: snapshot.page.id,
@@ -206,7 +247,9 @@ export function atomRetryInputKey(session: ManagedAtomSession, origin: AtomOrigi
function runKey(session: ManagedAtomSession, origin: AtomOrigin): string {
if (session.retry) {
- if (atomRetryInputKey(session, session.retry.origin) !== atomRetryInputKey(session, origin)) throw new OperationError('source_changed', 'The atom retry input no longer matches its accepted source snapshot.');
+ if (atomRetryInputKey(session, session.retry.origin) !== atomRetryInputKey(session, origin)) throw opError('source_changed', 'The atom retry input no longer matches its accepted source snapshot.',
+ `${origin.kind === 'page' ? `Page ${origin.locator}` : 'The transcript'} in source ${session.sourceId} changed after the reviewed atom batch was accepted, so the retry cannot replay it. Nothing was retried; the regular drain extracts the current content as a new run.`,
+ { fix: drainFix(session.sourceId) });
return session.retry.runKey;
}
// A database-only connector run is its own run: once an owner claims the source, the owner's
@@ -225,7 +268,9 @@ async function atomBatchRows(engine: BrainEngine, session: ManagedAtomSession, k
const completion = await getWriteRequest(engine, session.authority.principal, completionId);
if (completion && (completion.operation !== 'submit_job' || completion.source_id !== session.sourceId ||
completion.source_incarnation !== session.incarnation || completion.slug !== '__managed_atom_complete__')) {
- throw new OperationError('idempotency_conflict', 'The atom completion request ID belongs to another accepted operation.');
+ throw opError('idempotency_conflict', 'The atom completion request ID belongs to another accepted operation.',
+ `Atom completion request ${completionId} is already held by a ${completion.operation} request for ${completion.slug} in source ${completion.source_id}; nothing was admitted. Read that receipt and report the collision to the user with it rather than resubmitting.`,
+ { fix: receiptFix(completionId) });
}
const children = (completion?.intent as AtomIntent | null)?.children ?? [];
return engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE source_id=$1 AND source_incarnation=$2::uuid
@@ -270,7 +315,9 @@ export async function resumeManagedAtoms(engine: BrainEngine, session: ManagedAt
writeResponse(completed);
if (completed.outcome?.failure) malformedAtomReceipt(completed);
}
- if (!rows.some(row => row.request_id === atomRequestId(key, '__managed_atom_complete__'))) throw new OperationError('storage_error', 'The accepted atom batch has no completion receipt.');
+ if (!rows.some(row => row.request_id === atomRequestId(key, '__managed_atom_complete__'))) throw opError('storage_error', 'The accepted atom batch has no completion receipt.',
+ `Source ${session.sourceId}'s atom pages were accepted but the batch's completion was never journaled, so its outcome is unconfirmed. Inspect the accepted request ${rows[0].request_id} and the owner before resubmitting anything.`,
+ { fix: receiptFix(rows[0].request_id) });
return true;
}
@@ -290,11 +337,15 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
const snapshot = await engine.readPageSnapshot(atom.slug, { sourceId: session.sourceId, includeDeleted: true });
if (snapshot && ((snapshot.page.deleted_at && !snapshot.page.frontmatter.retired_by) || snapshot.page.type !== 'atom' ||
(origin.kind === 'page' ? snapshot.page.frontmatter.source_slug !== origin.locator : snapshot.page.frontmatter.source_path !== origin.locator))) {
- throw new OperationError('page_identity_changed', 'The atom target belongs to another origin or was removed.');
+ throw opError('page_identity_changed', 'The atom target belongs to another origin or was removed.',
+ `Atom slug ${atom.slug} in source ${session.sourceId} is held by a page this extraction does not own (another origin, a non-atom page or a deleted page); nothing was admitted. Read that page; whether to move or remove it is the user's decision.`,
+ { fix: pageFix(session.sourceId, atom.slug) });
}
const target = atom.expectedTarget ?? { pageId: snapshot?.page.id ?? null, revision: snapshot?.revision ?? null };
if ((snapshot?.page.id ?? null) !== target.pageId || (snapshot?.revision ?? null) !== target.revision) {
- throw new OperationError('page_identity_changed', 'The reviewed atom retry target changed before admission.');
+ throw opError('page_identity_changed', 'The reviewed atom retry target changed before admission.',
+ `Atom page ${atom.slug} in source ${session.sourceId} changed after the retry was reviewed; nothing was admitted. Read its current revision; the regular drain extracts against it as a new run.`,
+ { fix: pageFix(session.sourceId, atom.slug) });
}
inputs.push({ slug: atom.slug, pageId: target.pageId, intent: { kind: 'managed_atom_page', runKey: key, origin,
...(session.retry ? { checkpointKey: session.retry.checkpointKey, expectedCheckpoint: session.retry.expectedCheckpoint } : {}),
@@ -353,20 +404,28 @@ export async function publishManagedAtoms(engine: BrainEngine, session: ManagedA
export async function prepareManagedAtomMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as AtomIntent | null;
if (!p || !['managed_atom_page', 'managed_atom_delete', 'managed_atom_complete'].includes(p.kind) || !p.origin || row.authority.remote) {
- throw new OperationError('permission_denied', 'Unsupported atom maintenance intent.');
+ throw opError('permission_denied', 'Unsupported atom maintenance intent.',
+ `Request ${row.request_id} in source ${row.source_id} is not an atom maintenance intent the trusted local writer can publish, so the coordinator refused it before any change. Atom extraction runs only from the gbrain CLI on the brain host; inspect the owner before resubmitting anything.`,
+ { fix: ownerStatusFix(row.source_id) });
}
const validate = async (tx: BrainEngine) => {
// A connector preflighted as unbound publishes database-only; one claimed since then must use its owner.
if (row.authority.databaseOnlyReason === 'connector_database' && await getWorktreeBinding(tx, row.source_id)) {
- throw new OperationError('source_changed', 'The connector source gained a canonical owner after atom preflight; the next run extracts through its owner.');
+ throw opError('source_changed', 'The connector source gained a canonical owner after atom preflight; the next run extracts through its owner.',
+ `Connector source ${row.source_id} was claimed by a canonical owner after this database-only atom run started; request ${row.request_id} changed nothing. Run the atom drain on the owning host.`,
+ { fix: ownerStatusFix(row.source_id) });
}
if (p.origin.kind === 'transcript') {
- if (sha256(readFileSync(p.origin.locator)) !== p.origin.textHash) throw new OperationError('source_changed', 'The accepted atom transcript changed.');
+ if (sha256(readFileSync(p.origin.locator)) !== p.origin.textHash) throw opError('source_changed', 'The accepted atom transcript changed.',
+ `The transcript behind atom request ${row.request_id} in source ${row.source_id} was edited after acceptance, so the request published nothing. Run the atom drain again to extract the current file.`,
+ { fix: drainFix(row.source_id) });
} else {
await authorizeWrite(tx, row.authority, 'submit_job', p.origin.locator);
const snapshot = await tx.readPageSnapshot(p.origin.locator, { sourceId: row.source_id });
if (!snapshot || snapshot.page.id !== p.origin.pageId || snapshot.revision !== p.origin.revision || snapshot.page.content_hash !== p.origin.contentHash) {
- throw new OperationError('revision_conflict', 'The accepted atom source page changed.');
+ throw opError('revision_conflict', 'The accepted atom source page changed.',
+ `Page ${p.origin.locator} in source ${row.source_id} changed after atom request ${row.request_id} was accepted, so the request published nothing. Run the atom drain again to extract the current revision.`,
+ { fix: drainFix(row.source_id) });
}
}
};
@@ -406,10 +465,14 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
AND atom.knowledge_revision::text=r.outcome->>'revision' AND atom.deleted_at IS NULL)
OR (COALESCE(r.intent->>'kind',r.outcome->>'atom_kind')='managed_atom_delete'
AND atom.id=r.page_id AND atom.deleted_at IS NOT NULL))`, [children, row.source_incarnation, p.runKey]);
- if (committed.length !== children.length) throw new OperationError('revision_conflict', 'The atom batch is not fully committed.');
+ if (committed.length !== children.length) throw opError('revision_conflict', 'The atom batch is not fully committed.',
+ `Some atom pages in batch ${row.request_id} for source ${row.source_id} did not commit or changed afterwards, so the batch was not marked complete. Read the batch receipt; the next atom drain extracts the source again.`,
+ { fix: receiptFix(row.request_id) });
if (p.origin.kind === 'page') {
const snapshot = await tx.readPageSnapshot(p.origin.locator, { sourceId: row.source_id });
- if (!snapshot) throw new OperationError('revision_conflict', 'The accepted atom source page changed.');
+ if (!snapshot) throw opError('revision_conflict', 'The accepted atom source page changed.',
+ `Page ${p.origin.locator} in source ${row.source_id} is gone since atom batch ${row.request_id} was accepted, so the batch was not marked complete. Read the page to confirm; nothing more is extracted from a removed page.`,
+ { fix: pageFix(row.source_id, p.origin.locator) });
await writeAtomPageState(tx, row.source_id, { slug: p.origin.locator, content: snapshot.page.compiled_truth,
contentHash: p.origin.contentHash, identity: { pageId: p.origin.pageId!, sourceIncarnation: row.source_incarnation,
revision: p.origin.revision! } }, p.failure ? 'failure' : 'complete');
@@ -423,7 +486,9 @@ export async function prepareManagedAtomMutation(engine: BrainEngine, row: Write
ON CONFLICT(op,fingerprint) DO UPDATE SET completed_keys=EXCLUDED.completed_keys,updated_at=now()
WHERE op_checkpoints.completed_keys=$3::text::jsonb RETURNING fingerprint`,
[p.checkpointKey, checkpoint, p.expectedCheckpoint === null ? null : JSON.stringify(p.expectedCheckpoint)]);
- if (!advanced.length) throw new OperationError('revision_conflict', 'The reviewed atom retry checkpoint changed.');
+ if (!advanced.length) throw opError('revision_conflict', 'The reviewed atom retry checkpoint changed.',
+ `Another atom run completed source ${row.source_id}'s reviewed checkpoint after retry ${row.request_id} was accepted, so the retry was not recorded. Read the retry receipt; the later run's atoms stand.`,
+ { fix: receiptFix(row.request_id) });
}
return { status: p.failure ? 'failed' : 'completed',
atoms: committed.filter(child => child.kind === 'managed_atom_page').length,
diff --git a/src/core/persistence/effects.ts b/src/core/persistence/effects.ts
index e6b848b33b..4669544033 100644
--- a/src/core/persistence/effects.ts
+++ b/src/core/persistence/effects.ts
@@ -6,7 +6,9 @@ import type { BrainEngine } from '../engine.ts';
import { PERSISTENCE_PROTOCOL_PREDICATE } from './protocol.ts';
import type { GBrainConfig } from '../config.ts';
import type { PageSnapshot } from '../page-state/types.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 { serializePageToMarkdown } from '../markdown.ts';
import { isWriteTargetContained } from '../path-confine.ts';
import { materializePageSnapshot } from '../page-state/materialize.ts';
@@ -37,6 +39,21 @@ import { selectEffectRecoveries } from './effect-recovery-scan.ts';
import { nativeFileTarget } from './native-file-target.ts';
import { sourceMirrorReadOnly } from './mirror-read-only.ts';
+const effectStatusFix = (effect: Pick<PersistenceEffect, 'source_id'>): Action => readFix(
+ `Shows source ${effect.source_id}'s canonical owner with its blocking, retrying and parked effects, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', effect.source_id, '--json'] });
+const embeddingsFix = (): Action => readFix('Reports whether this brain has a usable embedding provider, model and dimensions, read-only.',
+ { argv: ['gbrain', 'doctor', '--only', 'embeddings', '--json'] });
+const writerBusy = (effect: Pick<PersistenceEffect, 'source_id'>) => opError('writer_busy', 'The canonical worktree is busy.',
+ `Another write holds source ${effect.source_id}'s canonical worktree. The committed write is unaffected and the effect worker tries this effect again shortly; nothing needs resubmitting.`,
+ { fix: effectStatusFix(effect) });
+const recoveryFirst = (effect: Pick<PersistenceEffect, 'source_id'>) => opError('recovery_required', 'Canonical publication recovery must finish first.',
+ `An earlier publication in source ${effect.source_id}'s worktree is still being recovered, so this effect waits; the worker resumes it once recovery completes. Inspect the owner rather than resubmitting writes.`,
+ { fix: effectStatusFix(effect) });
+const gitTargetEscaped = (effect: Pick<PersistenceEffect, 'source_id'>) => opError('source_changed', 'The Git target escaped its registered source.',
+ `The effect's file path resolves outside source ${effect.source_id}'s registered root (a symlink or a moved checkout), so nothing was committed for it. Inspect the owner; the user decides how to repair the checkout.`,
+ { fix: effectStatusFix(effect) });
+
export interface EffectWorkerOptions {
hostId: string;
limit?: number;
@@ -86,7 +103,9 @@ async function materializeAndAdvance(engine: BrainEngine, effect: PersistenceEff
await guardEffectSource(tx, effect, hostId);
await tx.lockPageKeys([{ sourceId: effect.source_id, slug: snapshot.page.slug }]);
const current = await tx.readPageSnapshot(snapshot.page.slug, { sourceId: effect.source_id, includeDeleted: true });
- if (current?.revision !== snapshot.revision || current.page.id !== snapshot.page.id) throw new OperationError('revision_conflict', 'The withdrawal page changed during preparation.');
+ if (current?.revision !== snapshot.revision || current.page.id !== snapshot.page.id) throw opError('revision_conflict', 'The withdrawal page changed during preparation.',
+ `Page ${snapshot.page.slug} in source ${effect.source_id} changed while its withdrawal was materializing; the effect worker picks up the new revision on its next pass. Nothing needs resubmitting.`,
+ { fix: effectStatusFix(effect) });
await materializePageSnapshot(tx, current);
if (skipped) await recordSkippedTarget(tx, effect, { slug: current.page.slug, reason: skipped });
await finishPage(tx, effect, current);
@@ -121,7 +140,9 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin
const snapshot = await selectedEffectPage(engine, effect);
if (!snapshot) { await completeEffect(engine, effect); return; }
attempt.target = snapshot.page.slug;
- if (snapshot.sourceIncarnation !== effect.source_incarnation) throw new OperationError('source_changed', 'The mirror source was replaced.');
+ if (snapshot.sourceIncarnation !== effect.source_incarnation) throw opError('source_changed', 'The mirror source was replaced.',
+ `Source ${effect.source_id} was replaced after this withdrawal mirror was queued, so the effect ends without writing; the new source has its own effects. Check the owner if files still look stale.`,
+ { fix: effectStatusFix(effect) });
if (isMetafilePage(snapshot)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId, 'metafile'); return; }
const content = serializePageToMarkdown(snapshot.page, snapshot.tags);
let file: Awaited<ReturnType<typeof prepareFileTarget>>;
@@ -154,14 +175,16 @@ async function mirrorPage(engine: BrainEngine, effect: PersistenceEffect, bindin
*/
async function singleFileGitTarget(engine: BrainEngine, effect: PersistenceEffect, binding: WorktreeBinding & { local_path: string },
attempt: EffectAttempt): Promise<string | null> {
- if (!effect.data.relative_path) throw new OperationError('storage_error', 'The Git effect lost its target.');
+ if (!effect.data.relative_path) throw opError('storage_error', 'The Git effect lost its target.',
+ `The Git effect queued by request ${effect.request_id} in source ${effect.source_id} has no recorded file path, so nothing was committed to Git; the page write itself is committed. Inspect the owner's effects before resubmitting anything.`,
+ { fix: effectStatusFix(effect) });
attempt.target = effect.data.slug ?? effect.data.relative_path;
const sourceRoot = join(binding.local_path, binding.relative_path);
let path = join(binding.local_path, effect.data.relative_path);
- if (!isWriteTargetContained(path, sourceRoot)) throw new OperationError('source_changed', 'The Git target escaped its registered source.');
+ if (!isWriteTargetContained(path, sourceRoot)) throw gitTargetEscaped(effect);
path = nativeFileTarget(binding.local_path, path, 'git_target_unsafe');
if (persistenceFileHash(path) !== effect.data.expected_hash) { await completeEffect(engine, effect, { git: 'superseded' }); return null; }
- if (!isWriteTargetContained(path, sourceRoot)) throw new OperationError('source_changed', 'The Git target escaped its registered source.');
+ if (!isWriteTargetContained(path, sourceRoot)) throw gitTargetEscaped(effect);
// Declared db_only content stays out of Git. Its gitignored local cache file
// is invisible to `git status`, so publishing it would be refused as unsafe.
// An invalid gbrain.yml (logged by the loader) publishes as before.
@@ -201,11 +224,13 @@ async function gitPage(engine: BrainEngine, effect: PersistenceEffect, binding:
await skip('file_database_drift');
return;
}
- if (!file) throw new OperationError('source_changed', 'The Git binding changed.');
+ if (!file) throw opError('source_changed', 'The Git binding changed.',
+ `Source ${effect.source_id} lost or changed its canonical checkout while this Git effect ran, so page ${snapshot.page.slug} was not committed. Check the owner; the effect resumes once the binding is active again.`,
+ { fix: effectStatusFix(effect) });
const path = file.path;
if (!existsSync(path)) { await materializeAndAdvance(engine, effect, snapshot, opts.hostId); return; }
if (snapshot.page.deleted_at && existsSync(path)) { await finishPage(engine, effect, snapshot, { reason: 'deleted_page_file_present' }); return; }
- if (!isWriteTargetContained(path, join(root, binding.relative_path))) throw new OperationError('source_changed', 'The Git target escaped its registered source.');
+ if (!isWriteTargetContained(path, join(root, binding.relative_path))) throw gitTargetEscaped(effect);
if (isSourceDbOnlySlug(join(root, binding.relative_path), snapshot.page.slug, 'not_db_only')) {
await finishPage(engine, effect, snapshot, { git: 'skipped', reason: 'db_only' });
return;
@@ -221,7 +246,9 @@ export async function readEmbeddingEffectProjection(engine: BrainEngine, effect:
await guardEffectSource(tx, effect, hostId);
const prepared = await readProjectionSnapshot(tx, snapshot.page.slug, effect.source_id);
if (!prepared || prepared.snapshot.revision !== snapshot.revision || prepared.snapshot.page.id !== snapshot.page.id) {
- throw new OperationError('projection_pending', 'The current text projection is not ready.');
+ throw opError('projection_pending', 'The current text projection is not ready.',
+ `Page ${snapshot.page.slug} in source ${effect.source_id} has no current text chunks for revision ${snapshot.revision} yet; the effect worker embeds it once the projection lands. Nothing needs resubmitting.`,
+ { fix: effectStatusFix(effect) });
}
const column = prepared.embeddingColumn;
const completion = await tx.executeRaw<{ id: number; complete: boolean }>(`SELECT cc.id,
@@ -242,7 +269,9 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return;
}
const signature = opts.embedding?.signature ?? currentEmbeddingSignature();
- if (!signature) throw new OperationError('embedding_unconfigured', 'Configure an embedding provider before explicitly retrying.');
+ if (!signature) throw opError('embedding_unconfigured', 'Configure an embedding provider before explicitly retrying.',
+ `Page ${snapshot.page.slug} in source ${effect.source_id} was saved but cannot be embedded: this brain has no embedding provider. Pages and keyword search keep working; check embedding readiness and ask the user before configuring a paid provider.`,
+ { fix: embeddingsFix() });
const { prepared, pending } = await readEmbeddingEffectProjection(engine, effect, snapshot, opts.hostId, signature, opts.embedding?.model);
if (pending.length) {
await assertEmbeddingEffectEnabled(engine, config);
@@ -255,7 +284,9 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
const signal = opts.signal ? AbortSignal.any([opts.signal, lease.signal]) : lease.signal;
let renewing: Promise<void> | undefined;
const renew = () => renewPersistenceEffectClaim({ executeRaw: engine.executeRawDirect.bind(engine) }, effect).then(live => {
- if (!live) lease.abort(new OperationError('write_claim_lost', 'The embedding claim changed.'));
+ if (!live) lease.abort(opError('write_claim_lost', 'The embedding claim changed.',
+ `Another worker took over the embedding of ${snapshot.page.slug} in source ${effect.source_id}; this attempt stops without installing vectors and the owning claim finishes it.`,
+ { fix: effectStatusFix(effect) }));
}).catch(error => { lease.abort(embeddingStorageFailure(error)); });
const interval = setInterval(() => {
if (!renewing && !signal.aborted) renewing = renew().finally(() => { renewing = undefined; });
@@ -283,12 +314,16 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
}
signal.throwIfAborted();
if (vectors.length !== pending.length || pending.some((_, index) => !vectors[index]?.length && !refused?.failures.some(f => f.index === index))) {
- throw new OperationError('embedding_unavailable', 'The provider returned an incomplete embedding batch.');
+ throw opError('embedding_unavailable', 'The provider returned an incomplete embedding batch.',
+ `No vectors were installed for ${snapshot.page.slug} in source ${effect.source_id}; the effect worker tries again with backoff up to its attempt limit. If it keeps failing, check the embedding provider.`,
+ { fix: embeddingsFix() });
}
const installed = await engine.transaction(async tx => {
await guardEffectSource(tx, effect, opts.hostId);
const [claim] = await tx.executeRaw<PersistenceEffect>('SELECT state,execution_token FROM persistence_effects WHERE id=$1 FOR UPDATE', [effect.id]);
- if (claim?.state !== 'running' || claim.execution_token !== effect.execution_token) throw new OperationError('write_claim_lost', 'The embedding claim changed.');
+ if (claim?.state !== 'running' || claim.execution_token !== effect.execution_token) throw opError('write_claim_lost', 'The embedding claim changed.',
+ `Another worker took over the embedding of ${snapshot.page.slug} in source ${effect.source_id}; this attempt installed nothing and the owning claim finishes it.`,
+ { fix: effectStatusFix(effect) });
await tx.executeRaw("SELECT key FROM config WHERE key='embedding_disabled' FOR SHARE");
await assertEmbeddingEffectEnabled(tx, config);
signal.throwIfAborted();
@@ -316,7 +351,9 @@ async function embedPage(engine: BrainEngine, config: GBrainConfig, effect: Pers
return;
}
if (!installed) {
- if (targetedWithdrawalEffect(effect) || effect.data.source_scan) throw new OperationError('revision_conflict', 'The page changed while embedding.');
+ if (targetedWithdrawalEffect(effect) || effect.data.source_scan) throw opError('revision_conflict', 'The page changed while embedding.',
+ `Page ${snapshot.page.slug} in source ${effect.source_id} changed while its vectors were computed, so none were installed; the scan embeds the new revision on its next pass.`,
+ { fix: effectStatusFix(effect) });
await completeEffect(engine, effect, { embedding: 'superseded', reason: 'revision_changed' }); return;
}
return;
@@ -328,14 +365,18 @@ export async function assertEmbeddingEffectEnabled(engine: BrainEngine, config:
assertEmbeddingEnabled(config);
const disabled = await engine.getConfig('embedding_disabled').catch(error => { throw embeddingStorageFailure(error); });
if (disabled !== null && disabled !== 'true' && disabled !== 'false') {
- throw new OperationError('embedding_configuration', 'Selected brain embedding_disabled must be true or false.');
+ throw opError('embedding_configuration', 'Selected brain embedding_disabled must be true or false.',
+ `The brain's embedding_disabled setting is neither true nor false, so embedding is paused. Read it, then have the user set it to true or false with gbrain config set embedding_disabled.`,
+ { fix: readFix('Shows the stored embedding_disabled value and the plane it comes from, read-only.', { argv: ['gbrain', 'config', 'get', 'embedding_disabled'] }) });
}
assertEmbeddingEnabled({ engine: engine.kind, ...config, embedding_disabled: disabled === 'true' });
}
function embeddingStorageFailure(error: unknown): unknown {
return transientDatabaseFailure(error)
- ? new OperationError('embedding_storage_unavailable', 'Embedding policy or claim storage is temporarily unavailable.') : error;
+ ? opError('embedding_storage_unavailable', 'Embedding policy or claim storage is temporarily unavailable.',
+ 'The database did not answer an embedding policy or claim read; no vectors were installed and the effect worker tries again with backoff. If it persists, check database health.',
+ { fix: readFix('Checks the brain database connection and schema health, read-only.', { argv: ['gbrain', 'doctor', '--json'] }) }) : error;
}
async function recordFailure(engine: BrainEngine, effect: PersistenceEffect, error: unknown, signal?: AbortSignal, target?: string): Promise<void> {
@@ -446,16 +487,18 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
const recordOnly = effect.kind === 'git' && hardened === false && !targetedWithdrawalEffect(effect) && !effect.data.source_scan;
try {
if (effect.worktree_id && !['embedding', 'facts-backstop'].includes(effect.kind)) {
- if (!binding) throw new OperationError('owner_unavailable', 'The canonical effect owner is unavailable.');
+ if (!binding) throw opError('owner_unavailable', 'The canonical effect owner is unavailable.',
+ `This host does not hold source ${effect.source_id}'s canonical worktree, so its ${effect.kind} effect waits for the owner. Check which host owns the source; the effect runs there.`,
+ { fix: effectStatusFix(effect) });
lock = await acquireWorktree(binding, 0, undefined, engine);
- if (!lock) throw new OperationError('writer_busy', 'The canonical worktree is busy.');
+ if (!lock) throw writerBusy(effect);
if (recordOnly) { await lock.release(); lock = null; }
}
await engine.transaction(async tx => {
await guardEffectSource(tx, effect, opts.hostId);
if (effect.worktree_id) {
const blocked = await tx.executeRaw('SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [effect.worktree_id]);
- if (blocked.length) throw new OperationError('recovery_required', 'Canonical publication recovery must finish first.');
+ if (blocked.length) throw recoveryFirst(effect);
}
});
effect = await upgradeWithdrawalEffect(engine, effect, opts.hostId);
@@ -496,7 +539,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;
try {
lock = await acquireWorktree(binding, 0, undefined, engine);
- if (!lock) throw new OperationError('writer_busy', 'The canonical worktree is busy.');
+ if (!lock) throw writerBusy(effects[0]!);
} catch (error) {
for (const effect of effects) await recordFailure(engine, effect, error, opts.signal);
return;
@@ -510,10 +553,12 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
const own = await engine.transaction(async tx => {
const guarded = await guardEffectSource(tx, effect, opts.hostId);
const blocked = await tx.executeRaw('SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [effect.worktree_id]);
- if (blocked.length) throw new OperationError('recovery_required', 'Canonical publication recovery must finish first.');
+ if (blocked.length) throw recoveryFirst(effect);
return guarded;
});
- if (!own?.local_path || own.local_path !== binding.local_path) throw new OperationError('source_changed', 'The effect canonical binding changed.');
+ if (!own?.local_path || own.local_path !== binding.local_path) throw opError('source_changed', 'The effect canonical binding changed.',
+ `Source ${effect.source_id}'s canonical checkout no longer matches the worktree this Git group is committing, so its file was left out. Check the owner; the effect resumes under the current binding.`,
+ { fix: effectStatusFix(effect) });
const path = await singleFileGitTarget(engine, effect, { ...own, local_path: own.local_path }, attempt);
if (path !== null) targets.push({ effect, path, attempt });
} catch (error) { await recordFailure(engine, effect, error, opts.signal, attempt.target); }
@@ -569,7 +614,7 @@ export async function runPersistenceEffects(engine: BrainEngine, config: GBrainC
let lock: Awaited<ReturnType<typeof acquireWorktree>> = null;
try {
lock = await acquireWorktree(binding, 0, undefined, engine);
- if (!lock) throw new OperationError('writer_busy', 'The canonical worktree is busy.');
+ if (!lock) throw writerBusy(items[0]!.effect);
pushed = await pushGitRoot(root, opts.signal);
} catch (error) { failure = error; } finally { await lock?.release(); }
for (const { effect, git, target } of items) {
diff --git a/src/core/persistence/facts-maintenance.ts b/src/core/persistence/facts-maintenance.ts
index dfe66bf635..8f954558b6 100644
--- a/src/core/persistence/facts-maintenance.ts
+++ b/src/core/persistence/facts-maintenance.ts
@@ -5,7 +5,9 @@ import type { FactsBackstopCtx } from '../facts/backstop.ts';
import { ENTITY_HINTS_CAP, type ExtractedFact, type FactEmbeddingSignature } from '../facts/extract.ts';
import { readFactsEmbeddingDim } from '../embedding-dim-check.ts';
import type { OperationContext } from '../ops/contract.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { hostFix, opTransport, readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { resolveEntitySlugWithSource } from '../entities/resolve.ts';
import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';
import { inferenceNote } from '../facts/subject-infer-write.ts';
@@ -51,6 +53,15 @@ export interface ManagedFactsSession {
embedding?: FactEmbeddingSignature | null;
}
+const receiptFix = (requestId: string): Action => readFix('Reads the fact request\'s durable receipt: its operation, state and outcome, read-only.',
+ { argv: ['gbrain', 'write-request', '--', requestId], mcp: { tool: 'get_write_request', arguments: { request_id: requestId } } });
+const pageFix = (sourceId: string, slug: string): Action => readFix(`Shows page ${slug} in source ${sourceId} as it is now, with its revision.`,
+ { argv: ['gbrain', 'get', '--source', sourceId, '--', slug], mcp: { tool: 'get_page', arguments: { slug, source_id: sourceId } } });
+const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner, its state and any write in flight, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+const embeddingsFix = (): Action => readFix('Reports the brain\'s embedding model, dimensions and vector columns, read-only.',
+ { argv: ['gbrain', 'doctor', '--only', 'embeddings', '--json'] });
+
function managedFactRequestId(batchKey: string, slug: string): string {
const hex = digest([batchKey, slug]);
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-8${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
@@ -62,7 +73,9 @@ async function validateManagedFactsCompletion(engine: BrainEngine, session: Mana
if (prior.operation !== 'extract_facts' || prior.slug !== '__managed_facts_complete__'
|| prior.source_id !== session.authority.sourceId || prior.source_incarnation !== session.authority.sourceIncarnation
|| inputDigest !== undefined && inputDigest !== session.inputDigest) {
- throw new OperationError('idempotency_conflict', 'This request ID already belongs to another operation or extraction input.');
+ throw opError('idempotency_conflict', 'This request ID already belongs to another operation or extraction input.',
+ `Request ${prior.request_id} was already accepted for a different operation or extraction input, so nothing was admitted. Give this extraction a new request_id; read the receipt to see what the original request did.`,
+ { fix: receiptFix(prior.request_id) });
}
if (prior.compacted && !prior.intent && isTerminal(prior) && prior.state !== 'committed') {
const error = new OperationError('facts_payload_expired', 'The accepted fact extraction failed and its retained payload has expired.',
@@ -70,7 +83,9 @@ async function validateManagedFactsCompletion(engine: BrainEngine, session: Mana
error.writeRequest = receiptFor(prior);
throw error;
}
- if (inputDigest !== session.inputDigest) throw new OperationError('idempotency_conflict', 'The retained fact request cannot verify this extraction input.');
+ if (inputDigest !== session.inputDigest) throw opError('idempotency_conflict', 'The retained fact request cannot verify this extraction input.',
+ `Request ${prior.request_id} no longer retains the input digest needed to prove it matches this extraction, so nothing was admitted. Read its receipt; a new extraction needs a new request_id.`,
+ { fix: receiptFix(prior.request_id) });
}
export async function resolveManagedFactsEmbedding(engine: BrainEngine, config: GBrainConfig,
@@ -79,18 +94,24 @@ export async function resolveManagedFactsEmbedding(engine: BrainEngine, config:
WHERE key IN ('embedding_model','embedding_dimensions','embedding_disabled') ORDER BY key${lock ? ' FOR SHARE' : ''}`);
const values = Object.fromEntries(rows.map(row => [row.key, row.value]));
if (values.embedding_disabled !== undefined && values.embedding_disabled !== 'true' && values.embedding_disabled !== 'false') {
- throw new OperationError('embedding_configuration', 'Selected brain embedding_disabled must be true or false.');
+ throw opError('embedding_configuration', 'Selected brain embedding_disabled must be true or false.',
+ 'The brain\'s embedding_disabled setting is neither true nor false, so fact extraction stopped before admission. Read it, then have the user set it to true or false with gbrain config set embedding_disabled.',
+ { fix: readFix('Shows the stored embedding_disabled value and the plane it comes from, read-only.', { argv: ['gbrain', 'config', 'get', 'embedding_disabled'] }) });
}
if (config.embedding_disabled || values.embedding_disabled === 'true') return null;
const model = values.embedding_model;
if (!model) return null;
const dimensions = /^[1-9]\d*$/.test(values.embedding_dimensions ?? '') ? Number(values.embedding_dimensions) : null;
if (!/^[^\s:]+:[^\s]+$/.test(model) || !dimensions || !Number.isSafeInteger(dimensions)) {
- throw new OperationError('embedding_configuration', 'The selected brain has no verifiable facts embedding model and dimensions.');
+ throw opError('embedding_configuration', 'The selected brain has no verifiable facts embedding model and dimensions.',
+ `The brain's embedding_model (${JSON.stringify(model)}) is not provider:model or embedding_dimensions is not a positive integer, so fact extraction stopped before admission. Check embedding readiness; correcting the configuration is the user's decision.`,
+ { fix: embeddingsFix() });
}
const shape = await readFactsEmbeddingDim(engine);
if (!shape.exists || !shape.columnType || shape.dims !== dimensions) {
- throw new OperationError('embedding_configuration', 'The selected brain facts embedding provenance does not match its vector column.');
+ throw opError('embedding_configuration', 'The selected brain facts embedding provenance does not match its vector column.',
+ `The facts vector column ${shape.exists ? `holds ${shape.dims ?? 'unknown'}-dimension vectors` : 'is missing'}, but ${model} is configured for ${dimensions}, so fact extraction stopped before admission. Check embedding readiness and show the user the mismatch.`,
+ { fix: embeddingsFix() });
}
return { model, dimensions };
}
@@ -99,7 +120,9 @@ export async function assertManagedFactsEmbedding(engine: BrainEngine, config: G
expected: FactEmbeddingSignature | null | undefined, lock = false): Promise<void> {
const current = await resolveManagedFactsEmbedding(engine, config, lock);
if (!expected || !current || expected.model !== current.model || expected.dimensions !== current.dimensions) {
- throw new OperationError('embedding_configuration', 'The selected brain facts embedding policy or model changed; retained vectors cannot be installed.');
+ throw opError('embedding_configuration', 'The selected brain facts embedding policy or model changed; retained vectors cannot be installed.',
+ `The facts embedding changed from ${expected ? `${expected.model} (${expected.dimensions})` : 'none'} to ${current ? `${current.model} (${current.dimensions})` : 'none'} after the facts were embedded, so nothing was admitted. Run the extraction again (the same request_id is safe: nothing was accepted) to embed under the current model.`,
+ { fix: embeddingsFix() });
}
}
@@ -110,13 +133,17 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
assertPersistenceAccepting(engine);
const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string | null; kind: string | null }>(
"SELECT incarnation,archived,local_path,config->>'kind' AS kind FROM sources WHERE id=$1", [ctx.sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'The fact extraction source is unavailable.');
+ if (!source || source.archived) throw opError('source_changed', 'The fact extraction source is unavailable.',
+ `Source ${ctx.sourceId} is missing or archived, so no facts were extracted. Extract into an active source, or restore ${ctx.sourceId} first (the user's decision).`,
+ { fix: readFix('Lists the registered sources with their archived state, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
let authority: WriteAuthority;
let origin: ManagedFactOrigin | null = null;
if (ctx.persistenceRequestId) {
const original = await getWriteRequestById(engine, requireUuid(ctx.persistenceRequestId));
if (!original || original.state !== 'committed' || original.source_id !== ctx.sourceId || original.source_incarnation !== source.incarnation || original.slug !== input.pageSlug) {
- throw new OperationError('permission_denied', 'Fact extraction requires its original committed page authority.');
+ throw opError('permission_denied', 'Fact extraction requires its original committed page authority.',
+ `The page write that triggered fact extraction for ${input.pageSlug ?? 'this turn'} in source ${ctx.sourceId} is not a committed write of that page, so nothing was extracted. Read the write's receipt; facts are extracted only after it commits.`,
+ original ? { fix: receiptFix(original.request_id) } : {});
}
await authorizeFactsBackstop(engine, original);
authority = structuredClone(original.authority);
@@ -126,16 +153,23 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
const verified = currentVerifiedLocalWriter();
const job = currentSubmissionAuthority();
if (job && job.kind !== 'application' || ctx.remote !== false && !verified && job?.kind !== 'application') {
- throw new OperationError('writer_coordinator_required', 'Managed facts require the original operation or durable job authority before extraction.');
+ throw opError('writer_coordinator_required', 'Managed facts require the original operation or durable job authority before extraction.',
+ `Fact extraction for source ${ctx.sourceId} ran outside an operation or durable job, so it has no authority to publish; nothing was extracted. Submit it as the extract_facts operation (an MCP tool call, or gbrain call extract_facts on the brain host).`);
}
operation = { engine, remote: verified?.remote ?? false, sourceId: ctx.sourceId, config: { engine: engine.kind } } as OperationContext;
}
- if (operation.engine !== engine || operation.sourceId && operation.sourceId !== ctx.sourceId) throw new OperationError('permission_denied', 'The extraction context does not match its source.');
+ if (operation.engine !== engine || operation.sourceId && operation.sourceId !== ctx.sourceId) throw opError('permission_denied', 'The extraction context does not match its source.',
+ `The calling operation targets ${operation.sourceId ? `source ${operation.sourceId}` : 'another brain'}, but extraction was asked to write into source ${ctx.sourceId}; nothing was extracted. Run the extraction with the same source as its operation.`);
await initializeLocalPersistence(operation);
authority = await submissionAuthority(operation, 'extract_facts', ctx.sourceId, source.incarnation, input.pageSlug ?? 'memory/unattributed');
}
if (authority.slugPrefixes !== null || authority.restrictedNamespace || authority.delegated) {
- throw new OperationError('permission_denied', 'Multi-entity fact extraction requires an unconfined source grant.');
+ throw opError('permission_denied', 'Multi-entity fact extraction requires an unconfined source grant.',
+ `This writer's grant on source ${ctx.sourceId} is limited to slug prefixes, a restricted namespace or a delegation, so it cannot write facts across entities; nothing was extracted. Save a single fact inside the grant with remember, or ask the brain host's operator for a source-wide grant.`,
+ { fix: ctx.operationContext
+ ? hostFix(ctx.operationContext, opTransport(ctx.operationContext) === 'http' ? ['gbrain', 'auth', 'clients', '--json'] : ['gbrain', 'auth', 'local-writer', 'list', '--json'],
+ 'Shows the connection\'s current grant so the operator can decide whether to widen it to the whole source.')
+ : readFix('Shows the CLI writer registrations and their grants, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });
}
await authorizeWrite(engine, authority, 'extract_facts', input.pageSlug ?? 'memory/unattributed');
for (const hint of ctx.entityHints?.slice(0, ENTITY_HINTS_CAP) ?? []) {
@@ -149,12 +183,16 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
await authorizePageVisibility(engine, authority, input.pageSlug);
const snapshot = await engine.readPageSnapshot(input.pageSlug, { sourceId: ctx.sourceId });
if (!snapshot || snapshot.sourceIncarnation !== source.incarnation || snapshot.page.compiled_truth !== input.turnText) {
- throw new OperationError('revision_conflict', 'The source page changed before fact extraction.');
+ throw opError('revision_conflict', 'The source page changed before fact extraction.',
+ `Page ${input.pageSlug} in source ${ctx.sourceId} no longer holds the text being extracted, so nothing was extracted. Read the current page and extract from its current text.`,
+ { fix: pageFix(ctx.sourceId, input.pageSlug) });
}
origin = { slug: input.pageSlug, pageId: snapshot.page.id, revision: snapshot.revision };
if (ctx.persistenceRequestId) {
const original = (await getWriteRequestById(engine, ctx.persistenceRequestId))!;
- if (original.outcome?.revision !== snapshot.revision) throw new OperationError('revision_conflict', 'The original page write has been superseded.');
+ if (original.outcome?.revision !== snapshot.revision) throw opError('revision_conflict', 'The original page write has been superseded.',
+ `A newer write replaced page ${input.pageSlug} in source ${ctx.sourceId} after request ${original.request_id} committed, so facts are not extracted from the superseded revision. Nothing needs resubmitting: the newer revision's write runs its own extraction.`,
+ { fix: pageFix(ctx.sourceId, input.pageSlug) });
}
}
const binding = await getWorktreeBinding(engine, ctx.sourceId);
@@ -162,11 +200,17 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
const writeThrough = !/^(false|0|off|no)$/i.test(await engine.getConfig('sync.write_through') ?? 'true');
// An unbound connector source is database-only by design (connector_database), like its connector sync.
const connectorDatabase = writeThrough && !binding && isConnectorSourceKind(source.kind);
- if (writeThrough && root && !binding && !connectorDatabase) throw new OperationError('owner_unavailable', 'The fact source has no canonical owner; extraction has not started.');
+ if (writeThrough && root && !binding && !connectorDatabase) throw opError('owner_unavailable', 'The fact source has no canonical owner; extraction has not started.',
+ `Source ${ctx.sourceId} has a checkout but no canonical owner, so facts cannot be written through to it. Check writer status; claiming the checkout is the user's decision on the brain host.`,
+ { fix: ownerStatusFix(ctx.sourceId) });
if (writeThrough && binding) {
- if (binding.state !== 'active' || !binding.owner_host_id) throw new OperationError('owner_unavailable', 'The canonical fact writer is unavailable; extraction has not started.');
+ if (binding.state !== 'active' || !binding.owner_host_id) throw opError('owner_unavailable', 'The canonical fact writer is unavailable; extraction has not started.',
+ `Source ${ctx.sourceId}'s canonical worktree is ${binding.state}, not active, so facts cannot be published yet. Check writer status and extract again once the owner is active.`,
+ { fix: ownerStatusFix(ctx.sourceId) });
if (binding.owner_host_id === localHostId()) {
- if (!await probeWorktreeWriter(binding, engine)) throw new OperationError('writer_lock_unavailable', 'The canonical fact writer is busy; extraction has not started.');
+ if (!await probeWorktreeWriter(binding, engine)) throw opError('writer_lock_unavailable', 'The canonical fact writer is busy; extraction has not started.',
+ `Another write holds source ${ctx.sourceId}'s canonical writer. Nothing was admitted, so run the extraction again once the writer is idle (the same request_id is safe).`,
+ { fix: ownerStatusFix(ctx.sourceId) });
}
}
if (!writeThrough) authority.databaseOnlyReason = 'disabled_by_config';
@@ -188,7 +232,9 @@ export async function prepareManagedFactsSession(ctx: FactsBackstopCtx,
async function collectManagedFacts(engine: BrainEngine, session: ManagedFactsSession, rows: WriteRequest[]): Promise<ManagedFactsResult> {
const result: ManagedFactsResult = { inserted: 0, duplicate: 0, superseded: 0, fact_ids: [], entity_slugs: [], write_requests: [] };
for (const row of rows) {
- if ((row.intent?.inputDigest ?? row.outcome?.input_digest) !== session.inputDigest) throw new OperationError('idempotency_conflict', 'The fact request ID was already used with different extraction input.');
+ if ((row.intent?.inputDigest ?? row.outcome?.input_digest) !== session.inputDigest) throw opError('idempotency_conflict', 'The fact request ID was already used with different extraction input.',
+ `Request ${row.request_id} in source ${row.source_id} was accepted for different extraction input, so this extraction was not merged into it. Give this extraction a new request_id; read the receipt to see the original.`,
+ { fix: receiptFix(row.request_id) });
await authorizeStoredRequest(engine, row);
const finished = await waitForWrite(engine, row, session.config);
writeResponse(finished);
@@ -212,7 +258,9 @@ export async function resumeManagedFacts(engine: BrainEngine, session: ManagedFa
session.authority.principal.kind, session.authority.principal.id, session.batchKey, session.completionRequestId]);
if (!rows.length) return null;
const completion = rows.find(row => row.request_id === session.completionRequestId);
- if (!completion) throw new OperationError('storage_error', 'The accepted facts batch has no completion receipt.');
+ if (!completion) throw opError('storage_error', 'The accepted facts batch has no completion receipt.',
+ `Facts batch requests were accepted in source ${session.authority.sourceId} but their completion request ${session.completionRequestId} was never journaled, so the outcome is unconfirmed. Inspect accepted request ${rows[0].request_id} before resubmitting anything.`,
+ { fix: receiptFix(rows[0].request_id) });
await validateManagedFactsCompletion(engine, session, completion);
return collectManagedFacts(engine, session, rows);
}
@@ -244,7 +292,9 @@ export async function publishManagedFacts(engine: BrainEngine, session: ManagedF
const inputs: Array<{ slug: string; pageId: number | null; intent: ManagedFactIntent }> = [];
for (const [slug, group] of groups) {
const snapshot = await engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
- if (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug === slug) && !snapshot) throw new OperationError('page_identity_changed', 'The resolved fact entity was removed.');
+ if (snapshot?.page.deleted_at || group.some(fact => fact.entity_slug === slug) && !snapshot) throw opError('page_identity_changed', 'The resolved fact entity was removed.',
+ `Entity page ${slug} in source ${sourceId} was deleted after the facts were resolved to it, so nothing was admitted. Run the extraction again (the same request_id is safe: nothing was accepted); it resolves entities against the current pages.`,
+ { fix: pageFix(sourceId, slug) });
inputs.push({ slug, pageId: snapshot?.page.id ?? null, intent: { kind: 'managed_facts_entity', batchKey: session.batchKey,
inputDigest: session.inputDigest, origin: session.origin, originalRequestId: session.originalRequestId,
embedding: session.embedding ?? null, ...(options.supersede ? { supersede: true as const } : {}),
diff --git a/src/core/persistence/import-prepare.ts b/src/core/persistence/import-prepare.ts
index a3060af394..10da646aca 100644
--- a/src/core/persistence/import-prepare.ts
+++ b/src/core/persistence/import-prepare.ts
@@ -22,7 +22,8 @@ import { prepareCanonicalProjections } from './canonical-projections.ts';
import type { PreparedContentImport } from './prepared-import.ts';
import type { PreparedMutation } from './coordinator.ts';
import type { WriteRequest } from './model.ts';
-import { trustedCliRequired } from '../ops/op-fix.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
export type ImportPack = { page_types: ReadonlyArray<{ name: string; path_prefixes: ReadonlyArray<string>; aliases?: ReadonlyArray<string> }> };
export interface ManagedImportIntent extends Record<string, unknown> {
@@ -31,26 +32,40 @@ export interface ManagedImportIntent extends Record<string, unknown> {
ownerEpoch: string; expected_revision?: string; noEmbed: boolean; activePack?: ImportPack;
}
+const reimportFix = (inputPath: string, sourceId: string): Action => ({
+ argv: ['gbrain', 'import', inputPath, '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Re-reads the file as it is now and imports it into source ${sourceId} under a new request through its canonical owner.`,
+});
+const receiptFix = (row: WriteRequest): Action => readFix('Reads the import request\'s durable receipt: its state and recorded error, read-only.',
+ { argv: ['gbrain', 'write-request', '--', row.request_id] });
+const ownerStatusFix = (sourceId: string): Action => readFix(`Shows source ${sourceId}'s canonical owner and its state, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+
export function readImportBytes(path: string): Buffer {
if (realpathSync(path) !== resolve(path) || !lstatSync(path).isFile()) {
- throw new OperationError('source_changed', 'Managed import refuses symlinked files or ancestors. Use the real source path.');
+ throw opError('source_changed', 'Managed import refuses symlinked files or ancestors. Use the real source path.',
+ `${path} is a symlink or sits under one, so it was not imported. Import the file at its real location (or copy it into the source) instead.`);
}
const maxBytes = isImageFilePath(path) ? MAX_IMAGE_BYTES : MAX_FILE_SIZE;
- if (lstatSync(path).size > maxBytes) throw new OperationError('invalid_params', `File too large (max ${maxBytes} bytes).`);
+ if (lstatSync(path).size > maxBytes) throw opError('invalid_params', `File too large (max ${maxBytes} bytes).`,
+ `${basename(path)} is over the ${maxBytes}-byte import limit and was not imported. Split it into smaller files or leave it out of the import.`);
return readFileSync(path);
}
export function managedImportContent(sourcePath: string, bytes: Buffer, activePack?: ImportPack): { slug: string; content: string } {
if (isAbsolute(sourcePath) || sourcePath.split(/[\\/]/).some(part => part === '..') || hasMalformedPathSegment(sourcePath)) {
- throw new OperationError('invalid_params', 'The import path must be a well-formed source-relative path.');
+ throw opError('invalid_params', 'The import path must be a well-formed source-relative path.',
+ `${JSON.stringify(sourcePath)} is absolute, climbs out with "..", or has a malformed segment, so it was not imported. Rename the file or import it from inside the source root.`);
}
if (isReservedSkillBundlePath(sourcePath)) {
- throw new OperationError('skill_bundle_required', 'Import cannot publish skill paths. Use the shared skill publisher.');
+ throw opError('skill_bundle_required', 'Import cannot publish skill paths. Use the shared skill publisher.',
+ `${sourcePath} is a reserved skill path, so import skipped it. Publish skills with put_skill (CLI: gbrain put-skill) and the catalog expected_revision; skill text imported as knowledge is never published as instructions.`);
}
if (isImageFilePath(sourcePath)) return { slug: sourcePath.replaceAll('\\', '/').toLowerCase(), content: bytes.toString('base64') };
let content = bytes.toString('utf8').replace(/^\uFEFF/, '');
if (isCodeFilePath(sourcePath)) return { slug: slugifyCodePath(sourcePath), content };
- if (!/\.mdx?$/i.test(sourcePath)) throw new OperationError('invalid_params', 'Managed import supports Markdown, code and supported image files.');
+ if (!/\.mdx?$/i.test(sourcePath)) throw opError('invalid_params', 'Managed import supports Markdown, code and supported image files.',
+ `${sourcePath} is not a Markdown (.md, .mdx), code or supported image file, so it was not imported. Convert it to Markdown or leave it out.`);
const original = parseMarkdown(content, sourcePath, { validate: true });
const invalid = original.errors?.find(error => error.code === 'YAML_PARSE');
if (invalid) {
@@ -61,16 +76,24 @@ export function managedImportContent(sourcePath: string, bytes: Buffer, activePa
const parsed = parseMarkdown(content, sourcePath, { validate: true, ...(activePack ? { activePack } : {}) });
const expected = slugifyPath(sourcePath);
if (expected && parsed.slug !== expected && slugifyPath(parsed.slug) !== expected) {
- throw new OperationError('invalid_params', `Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expected}".`);
+ throw opError('invalid_params', `Frontmatter slug "${parsed.slug}" does not match path-derived slug "${expected}".`,
+ `In ${sourcePath}, set the frontmatter slug to "${expected}" or remove it (the path decides the slug), or move the file to the path that matches "${parsed.slug}", then import again.`);
}
const slug = parsed.slug || expected;
- if (!slug) throw new OperationError('invalid_params', 'The filename produces no usable slug; add a slug in frontmatter.');
+ if (!slug) throw opError('invalid_params', 'The filename produces no usable slug; add a slug in frontmatter.',
+ `Rename ${sourcePath} to a name with letters or digits, or add a slug: line to its frontmatter, then import again.`);
return { slug, content };
}
export async function assertImportPaths(engine: BrainEngine, sourceId: string, root: string, input: string, target: string): Promise<void> {
- if (await getCompanyBrainProfile(engine, sourceId)) throw new OperationError('profile_incompatible', 'Company-brain sources require approved committed ingestion and never accept ordinary import writeback.');
- if (!isWriteTargetContained(target, root)) throw new OperationError('source_changed', 'The import target escapes its canonical source root.');
+ if (await getCompanyBrainProfile(engine, sourceId)) throw opError('profile_incompatible', 'Company-brain sources require approved committed ingestion and never accept ordinary import writeback.',
+ `Source ${sourceId} ingests only committed content under its approved company-brain profile. Commit the file to that source's repository and sync it, or import it into a different source.`,
+ { fix: { argv: ['gbrain', 'sync', '--no-pull', '--source', sourceId], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Imports source ${sourceId}'s committed checkout through its approved ingestion; uncommitted files are not read.`,
+ verify: { argv: ['gbrain', 'sources', 'status', '--json'] } } });
+ if (!isWriteTargetContained(target, root)) throw opError('source_changed', 'The import target escapes its canonical source root.',
+ `The file would land outside source ${sourceId}'s canonical root (a symlinked directory or a path with ".."), so nothing was imported. Import it from a real path inside the source.`,
+ { fix: ownerStatusFix(sourceId) });
const sources = await engine.executeRaw<{ id: string; local_path: string | null; worktree_path: string | null; relative_path: string | null }>(
`SELECT s.id,s.local_path,h.local_path AS worktree_path,b.relative_path FROM sources s
LEFT JOIN persistence_source_bindings b ON b.source_id=s.id AND b.source_incarnation=s.incarnation
@@ -84,7 +107,10 @@ export async function assertImportPaths(engine: BrainEngine, sourceId: string, r
for (const path of [input, target]) {
const rel = relative(other, path);
if (rel === '' || !isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`)) {
- throw new OperationError('source_changed', 'The import path belongs to a different registered source. Select that source explicitly.');
+ throw opError('source_changed', 'The import path belongs to a different registered source. Select that source explicitly.',
+ `${path === input ? 'The file' : 'Its target'} sits inside source ${source.id}'s root, not ${sourceId}'s; nothing was imported. Import it into ${source.id} with --source ${source.id}.`,
+ { fix: { argv: ['gbrain', 'import', input, '--source', source.id], consent: [], actor: 'agent', requires_exclusive: false,
+ why: `Imports the file into source ${source.id}, which owns its path.` } });
}
}
}
@@ -95,32 +121,49 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
const p = row.intent as ManagedImportIntent | null;
if (row.authority.remote || row.principal_kind !== 'local_cli') throw trustedCliRequired('Filesystem import requires a trusted local CLI writer.');
if (!p || p.kind !== 'managed_file_import' || typeof p.content !== 'string' || typeof p.inputPath !== 'string' || typeof p.sourcePath !== 'string') {
- throw new OperationError('invalid_params', 'The durable file import intent is incomplete.');
+ throw opError('invalid_params', 'The durable file import intent is incomplete.',
+ `Import request ${row.request_id} in source ${row.source_id} has no complete file intent, so it published nothing. Read its receipt, then import the file again with gbrain import --source ${row.source_id}.`,
+ { fix: receiptFix(row) });
}
const binding = await getWorktreeBinding(engine, row.source_id);
- if (!row.worktree_id || !binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw new OperationError('owner_unavailable', 'Managed file import requires its accepted canonical owner.');
+ if (!row.worktree_id || !binding?.local_path || String(binding.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'Managed file import requires its accepted canonical owner.',
+ `Source ${row.source_id}'s canonical owner changed or went away after import request ${row.request_id} was accepted, so it published nothing. Check the owner, then import ${p.sourcePath} again on the host that owns the source.`,
+ { fix: ownerStatusFix(row.source_id) });
const root = join(binding.local_path, binding.relative_path);
const physicalPath = p.path ?? p.sourcePath;
if (isAbsolute(physicalPath) || physicalPath.split(/[\\/]/).some(part => part === '..') || /(^|[\\/])skills([\\/]|$)/i.test(physicalPath)) {
- throw new OperationError('invalid_params', 'The canonical import path must be source-relative knowledge, not a skill path.');
+ throw opError('invalid_params', 'The canonical import path must be source-relative knowledge, not a skill path.',
+ `Import request ${row.request_id} targets ${JSON.stringify(physicalPath)} in source ${row.source_id}, which is absolute, climbs out with "..", or is a skill path; it published nothing. Import knowledge files from inside the source root and publish skills with put_skill.`,
+ { fix: receiptFix(row) });
}
const path = resolve(root, physicalPath);
const checkPaths = async (tx: BrainEngine) => {
const current = await getWorktreeBinding(tx, row.source_id);
- if (!current || current.worktree_id !== row.worktree_id || String(current.owner_epoch) !== p.ownerEpoch) throw new OperationError('owner_unavailable', 'The import owner changed.');
+ if (!current || current.worktree_id !== row.worktree_id || String(current.owner_epoch) !== p.ownerEpoch) throw opError('owner_unavailable', 'The import owner changed.',
+ `Source ${row.source_id}'s canonical owner changed while import request ${row.request_id} was prepared, so it published nothing. Check the owner, then import ${p.sourcePath} again on the host that owns the source.`,
+ { fix: ownerStatusFix(row.source_id) });
await assertImportPaths(tx, row.source_id, root, p.inputPath, path);
await assertKnowledgePublicationAllowed(tx, row, { root, path });
- if (sha256(readImportBytes(p.inputPath)) !== p.inputHash) throw new OperationError('source_changed', 'The input file changed after import admission.');
- if ((existsSync(path) ? sha256(readImportBytes(path)) : null) !== p.targetHash) throw new OperationError('source_changed', 'The canonical file changed after import admission.');
+ if (sha256(readImportBytes(p.inputPath)) !== p.inputHash) throw opError('source_changed', 'The input file changed after import admission.',
+ `${p.sourcePath} was edited after import request ${row.request_id} was accepted, so the request published nothing. Import it again to publish the current bytes.`,
+ { fix: reimportFix(p.inputPath, row.source_id) });
+ if ((existsSync(path) ? sha256(readImportBytes(path)) : null) !== p.targetHash) throw opError('source_changed', 'The canonical file changed after import admission.',
+ `The canonical copy of ${p.sourcePath} in source ${row.source_id} changed after import request ${row.request_id} was accepted, so it was not overwritten. Review that file, then import again if the import should still replace it.`,
+ { fix: reimportFix(p.inputPath, row.source_id) });
};
await checkPaths(engine);
const normalized = managedImportContent(p.sourcePath, readImportBytes(p.inputPath), p.activePack);
- if (normalized.slug !== row.slug || normalized.content !== p.content) throw new OperationError('source_changed', 'The frozen file identity no longer matches the import.');
+ if (normalized.slug !== row.slug || normalized.content !== p.content) throw opError('source_changed', 'The frozen file identity no longer matches the import.',
+ `${p.sourcePath} now normalizes to different content or slug than import request ${row.request_id} accepted for ${row.slug}, so it published nothing. Import it again to publish the current file.`,
+ { fix: reimportFix(p.inputPath, row.source_id) });
const source = { sourceId: row.source_id };
const snapshot = await engine.readPageSnapshot(row.slug, { ...source, includeDeleted: true });
assertPageRevision(snapshot, p.expected_revision ? { expectedRevision: p.expected_revision } : {});
if ((snapshot?.page.id ?? null) !== row.page_id || snapshot?.page.source_path && snapshot.page.source_path !== p.sourcePath) {
- throw new OperationError('page_identity_changed', 'The imported path no longer names the accepted page.');
+ throw opError('page_identity_changed', 'The imported path no longer names the accepted page.',
+ `Page ${row.slug} in source ${row.source_id} was replaced, removed, or now maps to a different file than ${p.sourcePath}, so import request ${row.request_id} published nothing. Read the page before importing the file again.`,
+ { fix: readFix(`Shows which page holds ${row.slug} in source ${row.source_id} now, with its source path and revision.`,
+ { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug] }) });
}
let prepared: (Omit<PreparedContentImport, 'parsedPage'> & { parsedPage?: PreparedContentImport['parsedPage'] }) | undefined;
const prepare = async (value: NonNullable<typeof prepared>) => { prepared = value; return value.result; };
@@ -133,10 +176,16 @@ export async function prepareManagedImportMutation(engine: BrainEngine, row: Wri
? await importCodeFile(engine, p.sourcePath, p.content, { ...source, noEmbed: true, prepare })
: await importFromContent(engine, row.slug, p.content, { ...source, noEmbed: true, remote: false, prepare,
activePack: p.activePack, sourcePath: p.sourcePath, filename: basename(p.sourcePath, '.md'), allowEmptyOverwrite: true });
- if (!prepared) throw new OperationError('invalid_params', result.error ?? 'The file could not be prepared.');
+ if (!prepared) throw opError('invalid_params', result.error ?? 'The file could not be prepared.',
+ `${p.sourcePath} was rejected while preparing import request ${row.request_id} for source ${row.source_id}; nothing was published. Fix the file content or frontmatter named in the message, then import it again.`,
+ { fix: reimportFix(p.inputPath, row.source_id) });
const ready = prepared;
- if (ready.slug !== row.slug || ready.observedRevision !== (snapshot?.revision ?? null)) throw new OperationError('revision_conflict', 'The import identity changed during preparation.');
- if (!image && !ready.parsedPage) throw new OperationError('invalid_params', 'The text import lost its prepared page.');
+ if (ready.slug !== row.slug || ready.observedRevision !== (snapshot?.revision ?? null)) throw opError('revision_conflict', 'The import identity changed during preparation.',
+ `Page ${row.slug} in source ${row.source_id} changed while import request ${row.request_id} was prepared, so it published nothing. Import ${p.sourcePath} again against the current page.`,
+ { fix: reimportFix(p.inputPath, row.source_id) });
+ if (!image && !ready.parsedPage) throw opError('invalid_params', 'The text import lost its prepared page.',
+ `Preparing ${p.sourcePath} for import request ${row.request_id} in source ${row.source_id} produced no page, so nothing was published. Read the receipt and report it to the user if importing the file again fails the same way.`,
+ { fix: receiptFix(row) });
const tags = [...new Set([...(snapshot?.tags ?? []), ...(ready.parsedPage?.tags ?? [])])].sort();
const rendered = imageBytes ?? (code ? p.content : serializePageToMarkdown({
...(snapshot?.page ?? { id: 0, source_id: row.source_id, created_at: new Date(), updated_at: new Date() }), ...ready.parsedPage,
diff --git a/src/core/persistence/ownership.ts b/src/core/persistence/ownership.ts
index 6c932cb1e5..966f42e56b 100644
--- a/src/core/persistence/ownership.ts
+++ b/src/core/persistence/ownership.ts
@@ -2,7 +2,9 @@ import { randomUUID } from 'node:crypto';
import { lstatSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { discoverGitRoot } from '../sync-git.ts';
import { cliOptsToProgressOptions, getCliOptions } from '../cli-options.ts';
import { createProgress, type ProgressOptions } from '../progress.ts';
@@ -18,6 +20,10 @@ import { assertWriterAdminState } from './admin-intent.ts';
import { assertWriterAdminUnlocked } from './admin-lock.ts';
import { inspectPhysicalRootRecovery, repairPhysicalRoot, type PhysicalRootRecovery } from './physical-root-recovery.ts';
+const writerStatusFix = (sourceId: string): Action => readFix(
+ `Shows source ${sourceId}'s owner host, epoch, worktree state, admin_state and any publication still recovering, read-only.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+
export interface WorktreeBinding {
worktree_id: string;
source_id: string;
@@ -51,7 +57,9 @@ export async function getWorktreeBinding(engine: SqlEngine, sourceId: string, ho
export async function claimWorktree(engine: BrainEngine, sourceId: string, path: string, hostId = localHostId(), expectedAdminState?: string,
options: { automatic?: boolean } = {}): Promise<WorktreeBinding> {
if(await managedPersistenceEnabled(engine)) {
- if(hostId!==localHostId()) throw new OperationError('permission_denied','A source can be claimed only by the local registered host.');
+ if(hostId!==localHostId()) throw opError('permission_denied','A source can be claimed only by the local registered host.',
+ `Source ${sourceId} can only be claimed from the host that will own its checkout; nothing was claimed. Run the claim in a terminal on that host after reviewing writer status there.`,
+ { fix: writerStatusFix(sourceId) });
const { runManagedSourceLifecycle }=await import('./source-lifecycle.ts');
await runManagedSourceLifecycle(engine,{operation:'claim',sourceId,path,expectedAdminState,automaticClaim:options.automatic});
return (await getWorktreeBinding(engine,sourceId,hostId))!;
@@ -72,7 +80,9 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:
const candidateId = existingPhysical?.worktreeId ?? randomUUID();
const lockPath = existingPhysical?.coordinationPath ?? canonicalFilesystemPath(join(persistenceHome(), 'locks', `${candidateId}.lock`));
const probe = await tryAcquireNativeLock(lockPath);
- if (!probe) throw new OperationError('writer_lock_unavailable', 'Cannot acquire the new worktree coordination lock.');
+ if (!probe) throw opError('writer_lock_unavailable', 'Cannot acquire the new worktree coordination lock.',
+ `Another gbrain process holds the coordination lock for this checkout, so source ${sourceId} was not claimed. Check writer status and run the claim again once that process has finished.`,
+ { fix: writerStatusFix(sourceId) });
await probe.release();
await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
@@ -80,7 +90,9 @@ export async function claimWorktree(engine: BrainEngine, sourceId: string, path:
await assertWriterAdminState(tx, expectedAdminState);
if (!options.automatic) await assertWriterAdminUnlocked(tx);
const [source] = await tx.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation,archived FROM sources WHERE id=$1 FOR UPDATE', [sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'Only an active registered source can claim a worktree.');
+ if (!source || source.archived) throw opError('source_changed', 'Only an active registered source can claim a worktree.',
+ `Source ${sourceId} is missing or archived, so it cannot own a checkout; nothing was claimed. Check the registered sources; restoring an archived source is the user's decision.`,
+ { fix: readFix('Lists the registered sources with their archived state, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
const current = await getWorktreeBinding(tx, sourceId, hostId);
if (current) {
if (current.source_incarnation !== source.incarnation || current.owner_host_id !== hostId || current.local_path !== root) {
@@ -162,7 +174,9 @@ export async function guardOwnership(tx: SqlEngine, row: WriteRequest, hostId: s
const binding = await getWorktreeBinding(tx, row.source_id, hostId);
if (!owner || !binding || binding.worktree_id !== row.worktree_id || binding.source_incarnation !== row.source_incarnation ||
owner.owner_host_id !== hostId || owner.state !== 'active' || String(binding.topology_generation) !== String(row.topology_generation)) {
- throw new OperationError('owner_unavailable', 'The accepted worktree ownership or source topology changed.');
+ throw opError('owner_unavailable', 'The accepted worktree ownership or source topology changed.',
+ `Source ${row.source_id}'s owner, epoch or topology changed after request ${row.request_id} was accepted, so this host did not publish it. Inspect the owner and the request's receipt (on the channel that submitted it) before resubmitting anything.`,
+ { fix: writerStatusFix(row.source_id) });
}
return binding;
}
@@ -187,7 +201,8 @@ export function worktreeManifest(root: string, opts: { progress?: ProgressOption
for (const name of readdirSync(dir).sort()) {
if (name === '.git' || name === '.gbrain-managed' || isPhysicalRootMetadata(name)) continue;
const path = join(dir, name), info = lstatSync(path);
- if (info.isSymbolicLink()) throw new OperationError('writer_manifest_unsafe', 'Canonical worktree transfer requires a symlink-free manifest.');
+ if (info.isSymbolicLink()) throw opError('writer_manifest_unsafe', 'Canonical worktree transfer requires a symlink-free manifest.',
+ `${relative(canonical, path).split(sep).join('/')} in the checkout is a symlink, so no manifest was recorded. Ask the user to replace it with a real file or directory (or remove it), then run the transfer step again.`);
if (info.isDirectory()) visit(path);
else if (info.isFile()) paths.push(path);
}
@@ -218,10 +233,16 @@ export function compactStoredManifest<T extends { digest: string; files?: Record
export async function prepareWriterTransfer(engine: BrainEngine, sourceId: string, hostId = localHostId(), expectedAdminState?: string,
opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<{ worktree_id: string; owner_epoch: string; manifest: StoredWorktreeManifest }> {
const binding = await getWorktreeBinding(engine, sourceId, hostId);
- if (!binding || binding.owner_host_id !== hostId || !binding.local_path) throw new OperationError('permission_denied', 'Only the current owner can prepare this transfer.');
- if (!binding.coordination_path) throw new OperationError('recovery_required', 'The recorded coordination path is missing.');
+ if (!binding || binding.owner_host_id !== hostId || !binding.local_path) throw opError('permission_denied', 'Only the current owner can prepare this transfer.',
+ `This host does not own source ${sourceId}'s checkout, so nothing was prepared. Check which host owns it; transfer preparation runs in a terminal on that host.`,
+ { fix: writerStatusFix(sourceId) });
+ if (!binding.coordination_path) throw opError('recovery_required', 'The recorded coordination path is missing.',
+ `Source ${sourceId}'s host binding has no coordination lock path, so no transfer was prepared. Inspect writer status and show it to the user; repairing the binding is a deliberate topology change (docs/architecture/topologies.md).`,
+ { fix: writerStatusFix(sourceId) });
const lock = opts.selfTransfer ? await acquireNativeLock(binding.coordination_path, { timeoutMs: 5000 }) : await acquireWorktree(binding, 5000);
- if (!lock) throw new OperationError('write_pending', 'The worktree is busy; retry transfer preparation.');
+ if (!lock) throw opError('write_pending', 'The worktree is busy; retry transfer preparation.',
+ `A write still holds source ${sourceId}'s worktree lock, so nothing was prepared. Wait until writer status shows no write in flight, then run transfer prepare again.`,
+ { fix: writerStatusFix(sourceId) });
try {
// The native lock already excludes writers, so hash before checking out a
// connection. A hashing failure surfaces after the root checks below, as before.
@@ -232,12 +253,18 @@ export async function prepareWriterTransfer(engine: BrainEngine, sourceId: strin
await assertWriterAdminUnlocked(tx);
const [owner] = await tx.executeRaw<{ owner_host_id: string; owner_epoch: string; state: string }>('SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [binding.worktree_id]);
const current = await getWorktreeBinding(tx, sourceId, hostId);
- if (!owner || owner.owner_host_id !== hostId || JSON.stringify(current) !== JSON.stringify(binding)) throw new OperationError('owner_unavailable', 'Ownership changed during transfer.');
- if (owner.state !== 'active' && owner.state !== 'draining') throw new OperationError('writer_transfer_conflict', 'Finish publication recovery before preparing a transfer.');
+ if (!owner || owner.owner_host_id !== hostId || JSON.stringify(current) !== JSON.stringify(binding)) throw opError('owner_unavailable', 'Ownership changed during transfer.',
+ `Source ${sourceId}'s owner or binding changed while the transfer was being prepared, so nothing was recorded. Inspect writer status again before deciding on any transfer.`,
+ { fix: writerStatusFix(sourceId) });
+ if (owner.state !== 'active' && owner.state !== 'draining') throw opError('writer_transfer_conflict', 'Finish publication recovery before preparing a transfer.',
+ `Source ${sourceId}'s worktree is in state ${owner.state}, not active, so no transfer was prepared. Let the owner finish publication recovery (writer status shows it), then prepare again.`,
+ { fix: writerStatusFix(sourceId) });
const pending = await tx.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND
(state IN ('running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [binding.worktree_id]);
const mirrors = await tx.executeRaw('SELECT id FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [binding.worktree_id]);
- if (pending.length || mirrors.length) throw new OperationError('recovery_required', 'Resolve outstanding publication before transfer.');
+ if (pending.length || mirrors.length) throw opError('recovery_required', 'Resolve outstanding publication before transfer.',
+ `Source ${sourceId}'s worktree still has a write or mirror effect publishing or recovering, so no transfer was prepared. Inspect writer status and wait for it to settle on the owner before preparing again.`,
+ { fix: writerStatusFix(sourceId) });
const [brain] = await tx.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
const recovery = opts.selfTransfer ? inspectPhysicalRootRecovery(binding.local_path!, { brainId: brain.brain_id,
worktreeId: binding.worktree_id, hostId, coordinationPath: binding.coordination_path! }) : undefined;
@@ -253,26 +280,44 @@ export async function acceptWriterTransfer(engine: BrainEngine, sourceId: string
opts: { selfTransfer?: boolean; dryRun?: boolean } = {}): Promise<void> {
const root = realpathSync(resolve(path));
const binding = await getWorktreeBinding(engine, sourceId, hostId);
- if (!binding) throw new OperationError('not_found', 'Source has no worktree owner.');
- if (opts.selfTransfer && binding.owner_host_id !== hostId) throw new OperationError('permission_denied', 'Self-transfer requires the current owner host.');
- if (opts.selfTransfer && root !== binding.local_path) throw new OperationError('source_changed', 'Self-transfer must target the recorded canonical path.');
+ if (!binding) throw opError('not_found', 'Source has no worktree owner.',
+ `Source ${sourceId} has no canonical owner to transfer from, so nothing was accepted. Check writer status; a source without an owner is claimed, not transferred, and claiming is the user's decision.`,
+ { fix: writerStatusFix(sourceId) });
+ if (opts.selfTransfer && binding.owner_host_id !== hostId) throw opError('permission_denied', 'Self-transfer requires the current owner host.',
+ `This host does not own source ${sourceId}, so a self-transfer cannot run here; nothing was accepted. Run it on the owner host, or accept an ordinary transfer prepared by the owner.`,
+ { fix: writerStatusFix(sourceId) });
+ if (opts.selfTransfer && root !== binding.local_path) throw opError('source_changed', 'Self-transfer must target the recorded canonical path.',
+ `A self-transfer of source ${sourceId} only repairs its recorded checkout, so nothing was accepted. Pass --path ${binding.local_path ?? 'with the recorded canonical path from writer status'} instead.`,
+ { fix: writerStatusFix(sourceId) });
const coordination = opts.selfTransfer ? binding.coordination_path : readPhysicalRootReservation(root)?.coordinationPath ?? join(persistenceHome(), 'locks', `${binding.worktree_id}.lock`);
- if (!coordination) throw new OperationError('recovery_required', 'The recorded coordination path is missing.');
+ if (!coordination) throw opError('recovery_required', 'The recorded coordination path is missing.',
+ `Source ${sourceId}'s host binding has no coordination lock path, so no transfer was accepted. Inspect writer status and show it to the user; repairing the binding is a deliberate topology change (docs/architecture/topologies.md).`,
+ { fix: writerStatusFix(sourceId) });
const lock = await acquireNativeLock(coordination, { timeoutMs: 5000 });
- if (!lock) throw new OperationError('write_pending', 'Successor worktree is busy.');
+ if (!lock) throw opError('write_pending', 'Successor worktree is busy.',
+ `Another gbrain process holds the successor checkout's coordination lock, so source ${sourceId}'s transfer was not accepted. Run transfer accept again once that process has finished.`,
+ { fix: writerStatusFix(sourceId) });
try {
if (worktreeManifest(root, { progress: humanManifestProgress() }).digest !== expectedManifest)
- throw new OperationError('writer_manifest_mismatch', 'Successor checkout differs from the recorded canonical manifest.');
+ throw opError('writer_manifest_mismatch', 'Successor checkout differs from the recorded canonical manifest.',
+ `The checkout at ${root} does not hash to manifest ${expectedManifest} that the owner recorded for source ${sourceId}; nothing was accepted. Bring it to exactly the prepared content (same files, no extras or deletions), then accept again.`,
+ { fix: writerStatusFix(sourceId) });
await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await assertWriterAdminState(tx, expectedAdminState);
await assertWriterAdminUnlocked(tx);
const [owner] = await tx.executeRaw<{ owner_epoch: string; state: string; manifest: { digest: string; self_transfer?: PhysicalRootRecovery } }>('SELECT owner_epoch,state,manifest FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE', [binding.worktree_id]);
- if (!owner || owner.state !== 'draining' || String(owner.owner_epoch) !== expectedEpoch || owner.manifest?.digest !== expectedManifest) throw new OperationError('writer_transfer_conflict', 'Transfer preparation or epoch changed.');
- if (!!owner.manifest.self_transfer !== !!opts.selfTransfer || JSON.stringify(await getWorktreeBinding(tx, sourceId, hostId)) !== JSON.stringify(binding)) throw new OperationError('writer_transfer_conflict', 'The prepared transfer mode or binding changed.');
+ if (!owner || owner.state !== 'draining' || String(owner.owner_epoch) !== expectedEpoch || owner.manifest?.digest !== expectedManifest) throw opError('writer_transfer_conflict', 'Transfer preparation or epoch changed.',
+ `Source ${sourceId} is no longer prepared at epoch ${expectedEpoch} with manifest ${expectedManifest}, so nothing was accepted. Read writer status and use the epoch and manifest of the current preparation, or have the owner prepare again.`,
+ { fix: writerStatusFix(sourceId) });
+ if (!!owner.manifest.self_transfer !== !!opts.selfTransfer || JSON.stringify(await getWorktreeBinding(tx, sourceId, hostId)) !== JSON.stringify(binding)) throw opError('writer_transfer_conflict', 'The prepared transfer mode or binding changed.',
+ `Source ${sourceId} was prepared ${owner.manifest.self_transfer ? 'as' : 'without'} a self-transfer, or its binding changed since then, so nothing was accepted. Accept with the same --self-transfer choice used at prepare, after re-reading writer status.`,
+ { fix: writerStatusFix(sourceId) });
const pending = await tx.executeRaw(`SELECT id FROM persistence_requests WHERE worktree_id=$1::uuid AND (state IN ('running','recovering') OR recovery IS NOT NULL) LIMIT 1`, [binding.worktree_id]);
const mirrors = await tx.executeRaw('SELECT id FROM persistence_effects WHERE worktree_id=$1::uuid AND recovery IS NOT NULL LIMIT 1', [binding.worktree_id]);
- if (pending.length || mirrors.length) throw new OperationError('recovery_required', 'Transfer state changed; prepare again.');
+ if (pending.length || mirrors.length) throw opError('recovery_required', 'Transfer state changed; prepare again.',
+ `A write or mirror effect started publishing in source ${sourceId}'s worktree after preparation, so nothing was accepted. Wait for writer status to show it settled, then have the owner prepare the transfer again.`,
+ { fix: writerStatusFix(sourceId) });
if (opts.selfTransfer) repairPhysicalRoot(root, owner.manifest.self_transfer!, { hostId, worktreeId: binding.worktree_id, coordinationPath: coordination }, opts.dryRun);
else if (!opts.dryRun) await preparePhysicalRootTransfer(tx, root, { hostId, worktreeId: binding.worktree_id, coordinationPath: coordination, expectedEpoch });
if (opts.dryRun) return;
diff --git a/src/core/persistence/topology-clone.ts b/src/core/persistence/topology-clone.ts
index 4600c6e17d..e8be80470e 100644
--- a/src/core/persistence/topology-clone.ts
+++ b/src/core/persistence/topology-clone.ts
@@ -3,7 +3,9 @@ import { randomUUID } from 'node:crypto';
import { existsSync, mkdirSync, realpathSync } from 'node:fs';
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { parseRemoteUrl } from '../git-remote.ts';
import { isOwnedClone } from '../sources-ops.ts';
import { parseSourceConfig } from '../sources-load.ts';
@@ -21,6 +23,13 @@ import { cloneTopologyCheckout, flushTopologyDirectory, flushTopologyTree, topol
import { finishTopologyClone } from './topology-recovery.ts';
import { reservePhysicalRoot, preparePhysicalRootReplacement, readPhysicalRootReservation } from './physical-root.ts';
+const writerStatusFix=(sourceId?:string):Action=>readFix(
+ sourceId?`Shows source ${sourceId}'s owner host, worktree path and state, read-only.`:'Shows every canonical worktree binding, its path, owner and state, read-only.',
+ {argv:['gbrain','sources','writer','status',...(sourceId?['--source',sourceId]:[]),'--json']});
+const sourcesListFix=():Action=>readFix('Lists the registered sources with their paths and archived state, read-only.',{argv:['gbrain','sources','list','--json']});
+const recoveryCapacityFix=():Action=>readFix('Shows the configured per-worktree recovery capacity in bytes, read-only.',
+ {argv:['gbrain','config','get','persistence.limits.worktree_recovery_bytes']});
+
/** Provider seam only for deterministic storage-boundary tests. */
export interface CloneLifecycleHooks {
clone?:(url:string,stage:string,budget:number)=>Promise<void>;
@@ -31,32 +40,56 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
const [source]=await engine.executeRaw<{incarnation:string;config:Record<string,unknown>;last_commit:string|null;local_path:string|null}>(
'SELECT incarnation,config,last_commit,local_path FROM sources WHERE id=$1',[input.sourceId]);
if(source)source.config=parseSourceConfig(source.config);
- if(input.operation==='add'&&source)throw new OperationError('source_id_taken','Source ID is already registered.');
- if(input.operation==='reclone'&&!source)throw new OperationError('not_found','Source not found.');
- if(input.expectedIncarnation&&input.expectedIncarnation!==source?.incarnation)throw new OperationError('source_changed','The source was replaced.');
+ if(input.operation==='add'&&source)throw opError('source_id_taken','Source ID is already registered.',
+ `Source ${input.sourceId} already exists, so nothing was cloned. Choose a different source id, or use gbrain sources reclone ${input.sourceId} to replace its managed checkout.`,
+ {fix:sourcesListFix()});
+ if(input.operation==='reclone'&&!source)throw opError('not_found','Source not found.',
+ `No source ${input.sourceId} is registered, so there is nothing to reclone. Check the registered sources; a new clone is created with gbrain sources add and --url.`,
+ {fix:sourcesListFix()});
+ if(input.expectedIncarnation&&input.expectedIncarnation!==source?.incarnation)throw opError('source_changed','The source was replaced.',
+ `Source ${input.sourceId} is ${source?`now incarnation ${source.incarnation}`:'no longer registered'}, not the expected ${input.expectedIncarnation}; nothing was cloned. Re-read the source and confirm the ${input.operation} still applies before passing the current incarnation.`,
+ {fix:writerStatusFix(input.sourceId)});
const binding=input.operation==='reclone'?await getWorktreeBinding(engine,input.sourceId):null;
if(input.operation==='reclone'&&(!binding?.local_path||binding.owner_host_id!==localHostId()||binding.relative_path!==''))
- throw new OperationError('owner_unavailable','Reclone must run on the owner of the complete canonical worktree.');
- if(input.operation==='reclone'&&(!source||!isOwnedClone({id:input.sourceId,local_path:source.local_path,config:source.config})))throw new OperationError('unmanaged_path','Reclone only replaces a checkout created and managed by GBrain.');
+ throw opError('owner_unavailable','Reclone must run on the owner of the complete canonical worktree.',
+ `This host does not own source ${input.sourceId}'s whole canonical worktree (it is unclaimed, owned elsewhere, or a subdirectory of a shared root), so nothing was recloned. Check the owner and run the reclone on that host.`,
+ {fix:writerStatusFix(input.sourceId)});
+ if(input.operation==='reclone'&&(!source||!isOwnedClone({id:input.sourceId,local_path:source.local_path,config:source.config})))throw opError('unmanaged_path','Reclone only replaces a checkout created and managed by GBrain.',
+ `Source ${input.sourceId}'s checkout was not cloned by gbrain, so reclone will not replace it; nothing changed. Update that checkout with git directly, or ask the user before converting it into a managed clone.`,
+ {fix:sourcesListFix()});
const url=input.remoteUrl??source?.config.remote_url;
- if(typeof url!=='string')throw new OperationError('invalid_params','A configured HTTPS clone URL is required.');
+ if(typeof url!=='string')throw opError('invalid_params','A configured HTTPS clone URL is required.',
+ input.operation==='add'?`Pass the repository's HTTPS URL with --url to clone source ${input.sourceId}; nothing was cloned.`
+ :`Source ${input.sourceId} has no configured remote URL, so it cannot be recloned; nothing changed. Only a source added from --url can be recloned.`);
parseRemoteUrl(url);
if(input.operation==='reclone'&&input.remoteUrl!==undefined&&input.remoteUrl!==source?.config.remote_url)
- throw new OperationError('source_changed',"Reclone must use the source's configured remote URL.");
+ throw opError('source_changed',"Reclone must use the source's configured remote URL.",
+ `Run gbrain sources reclone ${input.sourceId} without --url; reclone always uses the remote URL recorded for the source. Nothing was recloned.`);
const requested=binding?.local_path??input.path;
- if(typeof requested!=='string'||!isAbsolute(requested)||requested.includes('\0'))throw new OperationError('invalid_params','Clone destination must be an absolute path on the owner.');
+ if(typeof requested!=='string'||!isAbsolute(requested)||requested.includes('\0'))throw opError('invalid_params','Clone destination must be an absolute path on the owner.',
+ `Pass --path as an absolute directory on this host for source ${input.sourceId} (for example under the home directory); nothing was cloned.`);
const target=canonicalFilesystemPath(resolve(requested));
- if(input.operation==='add'&&existsSync(target))throw new OperationError('source_changed','Clone destination already exists. Register its existing path explicitly.');
+ if(input.operation==='add'&&existsSync(target))throw opError('source_changed','Clone destination already exists. Register its existing path explicitly.',
+ `${target} already exists, so it was not cloned over. Register that directory as source ${input.sourceId} if it is the intended checkout, or pass a new --path.`,
+ {fix:{argv:['gbrain','sources','add',input.sourceId,'--path',target,'--json'],consent:[],actor:'agent',requires_exclusive:false,
+ why:`Registers the existing directory as source ${input.sourceId} without cloning or overwriting it.`,
+ verify:{argv:['gbrain','sources','list','--json']}}});
if(input.dryRun)return {dry_run:true,operation:input.operation,source_id:input.sourceId,path:target,source_incarnation:source?.incarnation??null};
return withTopologyLocks(engine,input.sourceId,async bindings=>{
- if(input.operation==='add'&&bindings.some(binding=>!binding.unbound||binding.local_path!==target))throw new OperationError('overlapping_path','A new clone cannot replace or nest inside an existing canonical worktree.');
+ if(input.operation==='add'&&bindings.some(binding=>!binding.unbound||binding.local_path!==target))throw opError('overlapping_path','A new clone cannot replace or nest inside an existing canonical worktree.',
+ `${target} is, contains, or sits inside another source's canonical worktree, so source ${input.sourceId} was not cloned. Pass a --path outside every registered worktree.`,
+ {fix:writerStatusFix()});
const currentBinding=bindings.find(value=>value.source_id===input.sourceId);
- if(input.operation==='reclone'&&(!currentBinding||currentBinding.worktree_id!==binding!.worktree_id))throw new OperationError('source_changed','The canonical clone binding changed.');
+ if(input.operation==='reclone'&&(!currentBinding||currentBinding.worktree_id!==binding!.worktree_id))throw opError('source_changed','The canonical clone binding changed.',
+ `Source ${input.sourceId}'s canonical worktree changed while the reclone took its locks, so nothing was recloned. Re-read the owner, then run the reclone again if it still applies.`,
+ {fix:writerStatusFix(input.sourceId)});
const reservedIdentity=readPhysicalRootReservation(target);
const worktreeId=currentBinding?.worktree_id??reservedIdentity?.worktreeId??randomUUID();
const coordination=currentBinding?.coordination_path??reservedIdentity?.coordinationPath??join(persistenceHome(),'locks',`${worktreeId}.lock`);
let newLock:NativeLockHandle|null=null;
- if(!bindings.some(binding=>binding.worktree_id===worktreeId)){newLock=await acquireNativeLock(coordination!,{timeoutMs:5000});if(!newLock)throw new OperationError('writer_lock_unavailable','The new clone coordination lock is busy.');}
+ if(!bindings.some(binding=>binding.worktree_id===worktreeId)){newLock=await acquireNativeLock(coordination!,{timeoutMs:5000});if(!newLock)throw opError('writer_lock_unavailable','The new clone coordination lock is busy.',
+ `Another gbrain process holds the coordination lock for ${target}, so source ${input.sourceId} was not cloned. Run the command again once that process has finished.`,
+ {fix:writerStatusFix()});}
let accepted:TopologyChange|undefined;
try{
const before=existsSync(target)?worktreeManifest(target,{progress:humanManifestProgress()}):null;
@@ -75,25 +108,33 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
'SELECT local_path,coordination_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[worktreeId,localHostId()]);
if(preparedOwner.owner_host_id!==localHostId()||preparedOwner.state!=='active'||members.length
||host?.local_path!==target||host.coordination_path!==coordination)
- throw new OperationError('recovery_required','The reserved checkout is still bound, recovering, or has a different physical identity.');
+ throw opError('recovery_required','The reserved checkout is still bound, recovering, or has a different physical identity.',
+ `${target} is reserved by worktree ${worktreeId}, which is still bound to a source, recovering, or owned elsewhere, so source ${input.sourceId} was not cloned. Show the user the writer status; an interrupted clone there must finish recovery first.`,
+ {fix:writerStatusFix()});
}
const sources=await lockTopologyRows(tx,input.sourceId,bindings);
const [current]=await tx.executeRaw<{incarnation:string;last_commit:string|null;config:unknown}>('SELECT incarnation,last_commit,config FROM sources WHERE id=$1',[input.sourceId]);
const replay=await priorTopologyChange(tx,principal,requestId,intent);if(replay)return replay;
if((current?.incarnation??null)!==(source?.incarnation??null)||current?.last_commit!==source?.last_commit
- ||current&&parseSourceConfig(current.config).remote_url!==source?.config.remote_url)throw new OperationError('source_changed','The source changed before clone admission.');
+ ||current&&parseSourceConfig(current.config).remote_url!==source?.config.remote_url)throw opError('source_changed','The source changed before clone admission.',
+ `Source ${input.sourceId} was added, replaced, synced or repointed while the ${input.operation} was being admitted, so nothing was recorded. Re-read the source, then run the command again if it still applies.`,
+ {fix:writerStatusFix(input.sourceId)});
const invalidated=await settleTopologyRequests(tx,sources,bindings.map(row=>row.worktree_id),principal);
const incarnation=source?.incarnation??randomUUID();
let canonicalStamp=currentBinding?await topologyCanonicalStamp(tx,worktreeId):'';
const [owner]=currentBinding?await tx.executeRaw<{manifest:TopologyCloneRecovery['manifest']}>('SELECT manifest FROM persistence_worktrees WHERE id=$1::uuid',[worktreeId]):[];
const manifest=before?{...before,canonical_stamp:canonicalStamp}:owner?.manifest?compactStoredManifest(owner.manifest):null;
if(input.operation==='reclone'&&(!manifest||manifest.canonical_stamp!==canonicalStamp))
- throw new OperationError('recovery_required','The missing checkout has no current verified canonical manifest. Recover it from a verified checkpoint before recloning.');
+ throw opError('recovery_required','The missing checkout has no current verified canonical manifest. Recover it from a verified checkpoint before recloning.',
+ `Source ${input.sourceId} has no manifest matching its current canonical content, so a fresh clone could not be verified and nothing was recloned. Show the user the writer status; restoring the checkout from a verified copy is their decision (docs/architecture/topologies.md).`,
+ {fix:writerStatusFix(input.sourceId)});
const recovery:TopologyCloneRecovery={version:1,kind:'clone',phase:'reserved',operation:input.operation as 'add'|'reclone',sourceId:input.sourceId,
incarnation,worktreeId,ownerHostId:localHostId(),ownerEpoch:String(currentBinding?.owner_epoch??preparedOwner?.owner_epoch??1),target,stage,aside,
beforeHash:before?.digest??null,afterHash:null,manifest,canonicalStamp,checkpoint:source?.last_commit??null,sourceRemoteUrl:source?.config.remote_url as string??null,input,cloneBudget:0};
recovery.cloneBudget=reserved-oldBytes-Buffer.byteLength(JSON.stringify(recovery))-65_536;
- if(recovery.cloneBudget<65_536)throw new OperationError('request_too_large','The old checkout leaves insufficient configured recovery space for a staged clone.');
+ if(recovery.cloneBudget<65_536)throw opError('request_too_large','The old checkout leaves insufficient configured recovery space for a staged clone.',
+ `The current checkout of source ${input.sourceId} (${oldBytes} bytes) uses nearly all of the ${reserved}-byte recovery capacity, so nothing was cloned. Ask the user to raise persistence.limits.worktree_recovery_bytes and persistence.limits.brain_recovery_bytes (more disk reserved for recovery), then run the ${input.operation} again.`,
+ {fix:recoveryCapacityFix()});
if(!currentBinding){
if(preparedOwner)await tx.executeRaw("UPDATE persistence_worktrees SET state='recovering' WHERE id=$1::uuid",[worktreeId]);
else await tx.executeRaw("INSERT INTO persistence_worktrees(id,owner_host_id,owner_epoch,state) VALUES($1::uuid,$2::uuid,1,'recovering')",[worktreeId,localHostId()]);
@@ -115,7 +156,9 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await reservePhysicalRoot(tx,target,{hostId:localHostId(),worktreeId,coordinationPath:coordination!});
});
- if(existsSync(recovery.stage))throw new OperationError('recovery_required','The recorded staging path is already occupied.');
+ if(existsSync(recovery.stage))throw opError('recovery_required','The recorded staging path is already occupied.',
+ `Staging directory ${recovery.stage} already exists, so source ${input.sourceId}'s clone stopped without touching it and is rolled back. Show the user that path; lifecycle request ${requestId}'s receipt records the failure.`,
+ {fix:writerStatusFix(input.sourceId)});
mkdirSync(recovery.stage,{mode:0o700});flushTopologyDirectory(dirname(recovery.stage));
recovery.stageIdentity=topologyDirectoryIdentity(recovery.stage);
await topologyTransaction(engine,async tx=>{
@@ -125,11 +168,15 @@ export async function runManagedSourceClone(engine:BrainEngine,input:SourceLifec
await (hooks.clone??cloneTopologyCheckout)(url,recovery.stage,recovery.cloneBudget);
const stageBytes=await topologyDirectoryBytes(recovery.stage,recovery.cloneBudget);
const candidate=worktreeManifest(recovery.stage,{progress:humanManifestProgress()});
- if(recovery.manifest&&candidate.digest!==recovery.manifest.digest)throw new OperationError('writer_manifest_mismatch','The cloned checkout differs from the verified canonical manifest, including deletions.');
+ if(recovery.manifest&&candidate.digest!==recovery.manifest.digest)throw opError('writer_manifest_mismatch','The cloned checkout differs from the verified canonical manifest, including deletions.',
+ `A fresh clone from the remote does not match source ${input.sourceId}'s canonical content exactly (including deletions), so the clone is rolled back and the original kept. Make sure every canonical commit is pushed to the remote, then run gbrain sources reclone ${input.sourceId} again under a new request id.`,
+ {fix:writerStatusFix(input.sourceId)});
flushTopologyTree(recovery.stage);flushTopologyDirectory(dirname(recovery.stage));
recovery.afterHash=candidate.digest;recovery.phase='prepared';recovery.manifest={...candidate,canonical_stamp:recovery.canonicalStamp};
if(oldBytes+stageBytes+Buffer.byteLength(JSON.stringify(recovery))+65_536>Number(admission.recovery_bytes))
- throw new OperationError('request_too_large','The complete staged clone and recovery metadata exceed the reserved capacity.');
+ throw opError('request_too_large','The complete staged clone and recovery metadata exceed the reserved capacity.',
+ `The cloned repository (${stageBytes} bytes) plus the old checkout exceed the ${admission.recovery_bytes}-byte recovery reservation, so the clone is rolled back. Ask the user to raise persistence.limits.worktree_recovery_bytes and persistence.limits.brain_recovery_bytes, then run the ${input.operation} again under a new request id.`,
+ {fix:recoveryCapacityFix()});
await topologyTransaction(engine,async tx=>{
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
await preparePhysicalRootReplacement(tx,recovery.stage,target,{hostId:localHostId(),worktreeId,coordinationPath:coordination!});
diff --git a/src/core/persistence/topology-recovery.ts b/src/core/persistence/topology-recovery.ts
index 9d8c1bedc0..a7fd265122 100644
--- a/src/core/persistence/topology-recovery.ts
+++ b/src/core/persistence/topology-recovery.ts
@@ -2,7 +2,9 @@ import { topologyTransaction } from './topology-transaction.ts';
import { existsSync, lstatSync, renameSync, rmSync } from 'node:fs';
import { basename, dirname, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import { OperationError, opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
import { parseSourceConfig } from '../sources-load.ts';
import { canonicalFilesystemPath } from './root-registry.ts';
import { managedFilesystemDatastorePath, refreshManagedFilesystemRoots, withFilesystemPublication } from './filesystem-guard.ts';
@@ -19,9 +21,20 @@ import { assertPhysicalRoot } from './physical-root.ts';
import { assertPhysicalRootStamp, readPhysicalRootReservation } from './physical-root-record.ts';
import { resumeWorktreeRefreshes } from './worktree-refresh.ts';
+const cloneStatusFix=(sourceId:string):Action=>readFix(
+ `Shows source ${sourceId}'s owner, worktree state (recovering while a clone is unresolved) and blocking effects, read-only.`,
+ {argv:['gbrain','sources','writer','status','--source',sourceId,'--json']});
+/** A clone recovery that found bytes it cannot account for: it stops, keeps everything, and the owner re-checks on each pass. */
+function retainedClone(message:string,record:TopologyCloneRecovery,detail:string):OperationError{
+ return opError('recovery_required',message,
+ `${detail} Recovery of source ${record.sourceId}'s ${record.operation} stopped without moving or deleting anything, and the owner re-checks it on every recovery pass. Show the user the writer status and these paths; never delete them to force progress (docs/architecture/topologies.md, "Supported managed work and explicit repair").`,
+ {why:`Checkout ${record.target}, staging ${record.stage}, retained original ${record.aside}.`,fix:cloneStatusFix(record.sourceId)});
+}
async function readChange(engine:BrainEngine,id:string):Promise<TopologyChange>{
const [row]=await engine.executeRaw<TopologyChange>('SELECT * FROM persistence_topology_changes WHERE id=$1::uuid',[id]);
- if(!row)throw new OperationError('not_found','Source lifecycle request not found.');
+ if(!row)throw opError('not_found','Source lifecycle request not found.',
+ `No source lifecycle request ${id} is recorded on this brain, so there is nothing to recover. Check writer status for the source's current state instead.`,
+ {fix:readFix('Shows every source binding, worktree state and blocking effect on this brain, read-only.',{argv:['gbrain','sources','writer','status','--json']})});
return row;
}
function matchesCloneStage(target:string,stage:string):boolean{
@@ -34,25 +47,30 @@ function validateRecord(record:TopologyCloneRecovery):void{
||!matchesCloneStage(record.target,record.stage)
||!record.aside.startsWith(`${record.target}.gbrain-old-`)||!/[a-f0-9-]{36}$/.test(record.aside)
||canonicalFilesystemPath(record.target)!==record.target||canonicalFilesystemPath(record.stage)!==record.stage||canonicalFilesystemPath(record.aside)!==record.aside)
- throw new OperationError('recovery_required','The recorded clone paths no longer belong to this owner.');
+ throw retainedClone('The recorded clone paths no longer belong to this owner.',record,
+ `The recovery record names paths or an owner host that this host (${localHostId()}) cannot vouch for.`);
}
function treeHash(path:string):string|null{
if(!existsSync(path))return null;
- if(lstatSync(path).isSymbolicLink())throw new OperationError('recovery_required','Recovery refuses a substituted symbolic link.');
+ if(lstatSync(path).isSymbolicLink())throw opError('recovery_required','Recovery refuses a substituted symbolic link.',
+ `${path} was replaced by a symbolic link, so clone recovery stopped without following or removing it. Show the user the path; the owner re-checks it on every recovery pass and stays blocked until the link is replaced by the recorded directory (docs/architecture/topologies.md).`);
return worktreeManifest(path).digest;
}
function assertRetainedRoot(record:TopologyCloneRecovery,path:string):void{
const reservation=readPhysicalRootReservation(record.target);
- if(!reservation||reservation.worktreeId!==record.worktreeId)throw new OperationError('recovery_required','The retained checkout identity cannot be verified.');
+ if(!reservation||reservation.worktreeId!==record.worktreeId)throw retainedClone('The retained checkout identity cannot be verified.',record,
+ `${path} carries no physical-root reservation for worktree ${record.worktreeId}.`);
assertPhysicalRootStamp(path,reservation);
}
function assertStagingOwned(record:TopologyCloneRecovery):void{
if(!existsSync(record.stage))return;
const current=topologyDirectoryIdentity(record.stage),expected=record.stageIdentity;
if(!expected||current.device!==expected.device||current.inode!==expected.inode||current.birthNs!==expected.birthNs)
- throw new OperationError('recovery_required','Unexpected staging directory identity; recovery retained its bytes.');
+ throw retainedClone('Unexpected staging directory identity; recovery retained its bytes.',record,
+ `The staging directory ${record.stage} is not the one this clone created (device/inode differ).`);
if(record.afterHash!==null){
- if(treeHash(record.stage)!==record.afterHash)throw new OperationError('recovery_required','Unexpected staged clone bytes; recovery retained them.');
+ if(treeHash(record.stage)!==record.afterHash)throw retainedClone('Unexpected staged clone bytes; recovery retained them.',record,
+ `The staged clone at ${record.stage} no longer matches the bytes this clone wrote.`);
assertRetainedRoot(record,record.stage);
}
}
@@ -65,7 +83,8 @@ async function guard(tx:BrainEngine,row:TopologyChange,record:TopologyCloneRecov
const [owner]=await tx.executeRaw<{owner_host_id:string;owner_epoch:string;state:string}>('SELECT owner_host_id,owner_epoch,state FROM persistence_worktrees WHERE id=$1::uuid FOR UPDATE',[record.worktreeId]);
const [host]=await tx.executeRaw<{local_path:string}>('SELECT local_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid',[record.worktreeId,localHostId()]);
if(!owner||owner.owner_host_id!==record.ownerHostId||String(owner.owner_epoch)!==record.ownerEpoch||owner.state!=='recovering'||host?.local_path!==record.target)
- throw new OperationError('recovery_required','Ownership changed while the clone needed recovery.');
+ throw retainedClone('Ownership changed while the clone needed recovery.',record,
+ `Worktree ${record.worktreeId} no longer has owner epoch ${record.ownerEpoch} on this host in the recovering state.`);
const members=await tx.executeRaw<{source_id:string}>('SELECT source_id FROM persistence_source_bindings WHERE worktree_id=$1::uuid ORDER BY source_id',[record.worktreeId]);
const sources=[...new Set([record.sourceId,...members.map(value=>value.source_id)])].sort();
await tx.executeRaw('SELECT id FROM sources WHERE id=ANY($1::text[]) ORDER BY id FOR UPDATE',[sources]);
@@ -95,14 +114,17 @@ async function abortClone(engine:BrainEngine,row:TopologyChange,record:TopologyC
if(target!==null)assertPhysicalRoot(record.target,{worktreeId:record.worktreeId});
if(aside!==null){
assertRetainedRoot(record,record.aside);
- if(aside!==record.beforeHash||target!==null&&target!==record.afterHash)throw new OperationError('recovery_required','Unexpected clone recovery bytes; nothing was overwritten.');
+ if(aside!==record.beforeHash||target!==null&&target!==record.afterHash)throw retainedClone('Unexpected clone recovery bytes; nothing was overwritten.',record,
+ 'The retained original or the checkout holds bytes this clone did not record, so restoring the original was not attempted.');
removeOwnedStage(record);
if(target!==null){renameSync(record.target,record.stage);flushTopologyDirectory(dirname(record.target));}
renameSync(record.aside,record.target);flushTopologyDirectory(dirname(record.target));
}else if(record.beforeHash===null){
- if(target!==null&&target!==record.afterHash)throw new OperationError('recovery_required','Unexpected bytes occupy the interrupted clone destination.');
+ if(target!==null&&target!==record.afterHash)throw retainedClone('Unexpected bytes occupy the interrupted clone destination.',record,
+ `${record.target} holds content this clone did not write.`);
if(target!==null){removeOwnedStage(record);renameSync(record.target,record.stage);flushTopologyDirectory(dirname(record.target));}
- }else if(target!==record.beforeHash)throw new OperationError('recovery_required','The original checkout cannot be proven intact.');
+ }else if(target!==record.beforeHash)throw retainedClone('The original checkout cannot be proven intact.',record,
+ `${record.target} no longer matches the original checkout recorded before the clone.`);
removeOwnedStage(record);
if(record.beforeHash!==null)assertPhysicalRoot(record.target,{worktreeId:record.worktreeId});
if(existsSync(dirname(record.target)))flushTopologyDirectory(dirname(record.target));
@@ -125,9 +147,13 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Clo
const [source]=await tx.executeRaw<{incarnation:string;last_commit:string|null;config:unknown}>('SELECT incarnation,last_commit,config FROM sources WHERE id=$1',[record.sourceId]);
if(record.operation==='add'?!!source:!source||source.incarnation!==record.incarnation||source.last_commit!==record.checkpoint
||record.operation==='reclone'&&(parseSourceConfig(source?.config).remote_url??null)!==record.sourceRemoteUrl)
- throw new OperationError('source_changed','The source identity/checkpoint changed while cloning.');
+ throw opError('source_changed','The source identity/checkpoint changed while cloning.',
+ `Source ${record.sourceId} was added, replaced, synced or repointed while its ${record.operation} cloned, so the clone is rolled back and the original checkout kept. Check writer status, then run the ${record.operation} again under a new request id if it is still wanted.`,
+ {fix:cloneStatusFix(record.sourceId)});
if(record.operation==='reclone'&&await topologyCanonicalStamp(tx,record.worktreeId)!==record.canonicalStamp)
- throw new OperationError('source_changed','The logical source changed while cloning; retry after its mirrors finish.');
+ throw opError('source_changed','The logical source changed while cloning; retry after its mirrors finish.',
+ `Pages in source ${record.sourceId} changed while it recloned, so the clone is rolled back and the original checkout kept. Wait until writer status shows no blocking effects for ${record.sourceId}, then run gbrain sources reclone ${record.sourceId} again under a new request id.`,
+ {fix:cloneStatusFix(record.sourceId)});
await settleTopologyRequests(tx,sources,[record.worktreeId],row.principal_id);
assertStagingOwned(record);
const stage=treeHash(record.stage),target=treeHash(record.target),aside=treeHash(record.aside);
@@ -135,13 +161,17 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Clo
assertRetainedRoot(record,record.stage);
if(aside!==null)assertRetainedRoot(record,record.aside);
if(target!==null)assertPhysicalRoot(record.target,{worktreeId:record.worktreeId});
- if(stage!==record.afterHash||aside!==null&&aside!==record.beforeHash)throw new OperationError('recovery_required','Staged clone bytes changed.');
+ if(stage!==record.afterHash||aside!==null&&aside!==record.beforeHash)throw retainedClone('Staged clone bytes changed.',record,
+ 'The staged clone or the retained original changed after the clone verified them.');
if(target!==null){
- if(target!==record.beforeHash||aside!==null)throw new OperationError('recovery_required','The active checkout changed during clone preparation.');
+ if(target!==record.beforeHash||aside!==null)throw retainedClone('The active checkout changed during clone preparation.',record,
+ `${record.target} was edited after the clone recorded it, so it was not swapped out.`);
renameSync(record.target,record.aside);flushTopologyDirectory(dirname(record.target));await hooks.boundary?.('old_moved');
- }else if(record.beforeHash!==null&&aside!==record.beforeHash)throw new OperationError('recovery_required','The old checkout is missing from both recorded paths.');
+ }else if(record.beforeHash!==null&&aside!==record.beforeHash)throw retainedClone('The old checkout is missing from both recorded paths.',record,
+ 'The original checkout is at neither the checkout path nor the retained path.');
renameSync(record.stage,record.target);flushTopologyDirectory(dirname(record.target));await hooks.boundary?.('new_moved');
- }else if(target!==record.afterHash)throw new OperationError('recovery_required','Neither a verified stage nor the published clone is present.');
+ }else if(target!==record.afterHash)throw retainedClone('Neither a verified stage nor the published clone is present.',record,
+ 'Neither the staging directory nor the checkout holds the verified clone.');
assertPhysicalRoot(record.target,{worktreeId:record.worktreeId});
await tx.executeRaw("SELECT set_config('gbrain.topology_change','on',true)");
await withCoordinatedWrite(tx,sources,async()=>{
@@ -168,10 +198,13 @@ export async function finishTopologyClone(engine:BrainEngine,id:string,hooks:Clo
}
}
assertPhysicalRoot(record.target,{worktreeId:record.worktreeId});
- if(treeHash(record.target)!==record.afterHash)throw new OperationError('recovery_required','The committed clone changed before recovery cleanup.');
+ if(treeHash(record.target)!==record.afterHash)throw retainedClone('The committed clone changed before recovery cleanup.',record,
+ `The clone is committed, but ${record.target} changed before its cleanup ran.`);
const aside=treeHash(record.aside);
- if(aside!==null&&aside!==record.beforeHash)throw new OperationError('recovery_required','The retained old checkout changed; cleanup requires inspection.');
- if(existsSync(record.stage))throw new OperationError('recovery_required','Unexpected staging bytes remain after clone commitment.');
+ if(aside!==null&&aside!==record.beforeHash)throw retainedClone('The retained old checkout changed; cleanup requires inspection.',record,
+ `The clone is committed, but the retained original at ${record.aside} changed, so it was not removed.`);
+ if(existsSync(record.stage))throw retainedClone('Unexpected staging bytes remain after clone commitment.',record,
+ `The clone is committed, but ${record.stage} still exists.`);
if(aside!==null){assertRetainedRoot(record,record.aside);rmSync(record.aside,{recursive:true,force:true});}
flushTopologyDirectory(dirname(record.target));
await topologyTransaction(engine,async tx=>{await guard(tx,row,record);await releaseReservation(tx,row,record,'committed');});