Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): B10 backfill persistence worktree-refresh/topology-filesystem/local-client/derived-facts/activation/memory/loop-fact-retirement/administration, proposal-supersede, synthesize-postprocess

garrytan7238724b466d
diff --git a/src/core/cycle/synthesize-postprocess.ts b/src/core/cycle/synthesize-postprocess.ts
index 98e1a926f7..a4edb9bbba 100644
--- a/src/core/cycle/synthesize-postprocess.ts
+++ b/src/core/cycle/synthesize-postprocess.ts
@@ -1,7 +1,9 @@
import type { BrainEngine } from '../engine.ts';
import { throwIfAborted } from '../abort-check.ts';
import { serializePageToMarkdown } from '../markdown.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { authorizeStoredRequest } from '../persistence/authority.ts';
import { digest } from '../persistence/digest.ts';
import { getWriteRequest } from '../persistence/journal.ts';
@@ -16,6 +18,8 @@ import { emptyQuoteVerifyStats, groundSource, isDreamOwnedPage, resolveVerifyPri
interface OutputRef { slug: string; source_id: string; raw_source?: string; seat?: string; first_write_at?: Date; }
interface RetainedOutput { job_id: number | bigint; job_key: string; request: WriteRequest; }
+const writerStatusFix = (sourceId: string, why: string): Action => readFix(why, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+
export async function postprocessManagedSynthesis(
engine: BrainEngine,
authority: MaintenanceAuthority,
@@ -43,13 +47,19 @@ export async function postprocessManagedSynthesis(
let grounded: GroundedSource | undefined;
for (const ref of [...refs].sort((a, b) => (a.raw_source ?? '').localeCompare(b.raw_source ?? ''))) {
throwIfAborted(opts.signal, '[dream] synthesis postprocessing');
- if (ref.source_id !== authority.writer.sourceId) throw new OperationError('source_changed', 'The synthesis output source changed.');
+ if (ref.source_id !== authority.writer.sourceId) {
+ throw opError('source_changed', 'The synthesis output source changed.',
+ `Synthesis output ${ref.slug} belongs to source ${ref.source_id}, not ${authority.writer.sourceId} that this dream cycle writes, so it was not postprocessed. Check source ${authority.writer.sourceId}'s writer status, then run gbrain dream --phase synthesize --source ${authority.writer.sourceId} again.`,
+ { fix: writerStatusFix(authority.writer.sourceId, `Shows source ${authority.writer.sourceId}'s maintenance writer and requests in flight, read-only.`) });
+ }
const output = outputs.find(o => o.request.slug === ref.slug);
const path = output && jobRawSource.get(Number(output.job_id));
const transcript = path ? byPath.get(path) : undefined;
const revision = output?.request.outcome?.revision;
if (!output || !transcript || typeof revision !== 'string') {
- throw new OperationError('recovery_required', 'The synthesis output has no retained transcript and committed revision.');
+ throw opError('recovery_required', 'The synthesis output has no retained transcript and committed revision.',
+ `Synthesis output ${ref.slug} in source ${ref.source_id} has no retained transcript or committed put_page revision${output ? ` (child request ${output.request.request_id})` : ''}, so it cannot be verified. Inspect the writer status before running synthesis again; do not republish the page by hand.`,
+ { fix: writerStatusFix(ref.source_id, `Shows source ${ref.source_id}'s committed and pending maintenance requests, read-only.`) });
}
const finalizedRef = { ...ref, raw_source: path };
const key = digest({ kind: 'synthesis-postprocess-v1', source: authority.writer.sourceIncarnation,
@@ -65,13 +75,17 @@ export async function postprocessManagedSynthesis(
let content: string;
if (prior) {
if (prior.intent?.kind !== 'managed_maintenance_page' || prior.intent.expected_revision !== revision || typeof prior.intent.content !== 'string') {
- throw new OperationError('recovery_required', 'The retained synthesis postprocessing intent is unavailable.');
+ throw opError('recovery_required', 'The retained synthesis postprocessing intent is unavailable.',
+ `Postprocess request ${prior.request_id} for ${ref.slug} in source ${ref.source_id} exists, but its retained intent does not match revision ${revision}. Inspect it in writer status; do not resubmit under a new request.`,
+ { fix: writerStatusFix(ref.source_id, `Shows request ${prior.request_id} and any recovery it holds, read-only.`) });
}
content = prior.intent.content;
} else {
const snapshot = await engine.readPageSnapshot(ref.slug, { sourceId: ref.source_id });
if (!snapshot || snapshot.revision !== revision) {
- throw new OperationError('revision_conflict', 'The synthesis output changed after the child committed.');
+ throw opError('revision_conflict', 'The synthesis output changed after the child committed.',
+ `Page ${ref.slug} in source ${ref.source_id} changed after the synthesis child committed revision ${revision}, so postprocessing left it alone. Review the page; the next synthesis run processes fresh output.`,
+ { fix: readFix(`Shows page ${ref.slug} as it is now, read-only.`, { argv: ['gbrain', 'get', '--source', ref.source_id, '--', ref.slug] }) });
}
const firstDate = snapshot.page.frontmatter.dream_created_cycle_date || snapshot.page.frontmatter.dream_cycle_date || opts.cycleDate;
const since = ref.first_write_at ?? opts.sinceByTranscript.get(transcript.filePath);
diff --git a/src/core/facts/proposal-supersede.ts b/src/core/facts/proposal-supersede.ts
index a72b2ebbe6..ea63f8a194 100644
--- a/src/core/facts/proposal-supersede.ts
+++ b/src/core/facts/proposal-supersede.ts
@@ -26,7 +26,8 @@ import { contentHash } from '../utils.ts';
import { withPageLock } from '../page-lock.ts';
import { assertSourceFilesystemActive, withSourceFilesystemLock } from '../minions/source-filesystem.ts';
import { resolvePageWriteTarget } from '../write-through.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { getProposal, transitionProposal, type ProposalRow } from '../ai/decide/proposals-store.ts';
import { strikeFenceRow, supersededFact } from './forget.ts';
import type { PreparedMutation } from '../persistence/coordinator.ts';
@@ -274,12 +275,16 @@ async function undoUnmanaged(engine: BrainEngine, proposal: ProposalRow): Promis
// Managed path: coordinator mutation `decide_proposal`
// ---------------------------------------------------------------------------
+const proposalsFix = (why: string) => readFix(why, { argv: ['gbrain', 'decide', 'proposals', 'list', '--status', 'all', '--json'] });
+
/** Coordinator preparer: the same plan as the unmanaged path, published by the coordinator as one unit. */
export async function prepareProposalMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig): Promise<PreparedMutation> {
const p = row.intent as { proposal_id?: number; action?: ProposalAction } | null;
const id = Number(p?.proposal_id);
if (row.operation !== DECIDE_PROPOSAL_OPERATION || !Number.isSafeInteger(id) || (p?.action !== 'accept' && p?.action !== 'undo') || row.authority.remote) {
- throw new OperationError('permission_denied', 'Unsupported decide proposal intent.');
+ throw opError('permission_denied', 'Unsupported decide proposal intent.',
+ `Request ${row.request_id} in source ${row.source_id} is not a local accept or undo of a proposal, so the coordinator refused it and nothing changed. Decide proposals from the brain host's CLI with gbrain decide proposals accept or undo.`,
+ { fix: proposalsFix('Lists proposals with their ids and status, read-only.') });
}
const action = p.action;
const proposal = await getProposal(engine, id);
@@ -293,13 +298,19 @@ export async function prepareProposalMutation(engine: BrainEngine, row: WriteReq
const current = await getProposal(tx, id, true);
const [o, n] = await Promise.all([loadPairFact(tx, proposal.old_fact_id, true), loadPairFact(tx, proposal.new_fact_id, true)]);
if (current?.status !== proposal.status || !o || !n || !oldF || !newF || !sameFields(factFields(o), factFields(oldF)) || !sameFields(factFields(n), factFields(newF))) {
- throw new OperationError('revision_conflict', 'The proposal or its facts changed during preparation.');
+ throw opError('revision_conflict', 'The proposal or its facts changed during preparation.',
+ `Proposal ${id} or its facts changed while request ${row.request_id} was prepared, so nothing was applied. Review its current status, then decide it again if it still applies.`,
+ { fix: proposalsFix(`Shows proposal ${id}'s current status, read-only.`) });
}
};
const pageFor = async (body: string): Promise<PreparedMutation | undefined> => {
if (!snapshot) return undefined;
const page = await preparePage(engine, { ...row, intent: { ...row.intent, content: serializePageToMarkdown({ ...snapshot.page, compiled_truth: body }, snapshot.tags), expected_revision: observedRevision, force: false } }, config);
- if (page.observedRevision !== observedRevision) throw new OperationError('revision_conflict', 'The fact page changed during preparation.');
+ if (page.observedRevision !== observedRevision) {
+ throw opError('revision_conflict', 'The fact page changed during preparation.',
+ `Fact page ${row.slug} in source ${row.source_id} changed while proposal ${id} (request ${row.request_id}) was prepared, so nothing was applied. Review the page and the proposal, then decide it again if it still applies.`,
+ { fix: readFix(`Shows page ${row.slug} as it is now, read-only.`, { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug] }) });
+ }
return page;
};
if (action === 'accept') {
@@ -356,7 +367,11 @@ async function submitManaged(engine: BrainEngine, proposal: ProposalRow, action:
await initializeLocalPersistence(ctx as never);
const principal = await requestPrincipalForContext(ctx as never);
const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean }>('SELECT incarnation, archived FROM sources WHERE id = $1', [sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'The proposal source is not active.');
+ if (!source || source.archived) {
+ throw opError('source_changed', 'The proposal source is not active.',
+ `Proposal ${proposal.id} belongs to source ${sourceId}, which is archived or missing, so nothing changed. Restore the source to decide it (the user's call), or reject the proposal.`,
+ { fix: readFix('Lists sources with their archived state, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
+ }
const oldF = await loadPairFact(engine, proposal.old_fact_id);
const slug = oldF?.source_markdown_slug ?? oldF?.entity_slug ?? 'memory/unattributed';
const authority = await submissionAuthority(ctx as never, DECIDE_PROPOSAL_OPERATION, sourceId, source.incarnation, slug);
diff --git a/src/core/persistence/activation.ts b/src/core/persistence/activation.ts
index 778c6f63d3..5e21b3c819 100644
--- a/src/core/persistence/activation.ts
+++ b/src/core/persistence/activation.ts
@@ -1,7 +1,9 @@
import { existsSync, realpathSync } from 'node:fs';
import { join, resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { acquireWorktree, getWorktreeBinding, type WorktreeBinding } from './ownership.ts';
import { localHostId, existingLocalHostId, persistenceHome, registerLocalWriter } from './identity.ts';
import { nativeLockCapability, tryAcquireNativeLock, type NativeLockHandle } from './native-lock.ts';
@@ -26,6 +28,9 @@ interface SourceRoot { id: string; incarnation: string; root: string | null; con
const quiescence = () => new OperationError('writer_not_quiesced', 'Managed activation requires all older writers and maintenance jobs to be stopped.',
WRITER_INSPECTION_HINT);
+const writerStatusFix = (why: string, sourceId?: string): Action => readFix(why,
+ { argv: ['gbrain', 'sources', 'writer', 'status', ...(sourceId ? ['--source', sourceId] : []), '--json'] });
+
async function configuredSources(engine: BrainEngine, lock = false): Promise<SourceRoot[]> {
const sources = await engine.executeRaw<{ id: string; incarnation: string; local_path: string | null; kind: string | null }>(
`SELECT id,incarnation,local_path,config->>'kind' AS kind FROM sources WHERE archived=false ORDER BY id${lock ? ' FOR UPDATE' : ''}`);
@@ -57,12 +62,18 @@ async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hos
}
const [owner] = await engine.executeRaw<{ local_path: string; coordination_path: string }>(
'SELECT local_path,coordination_path FROM persistence_host_bindings WHERE worktree_id=$1::uuid AND host_id=$2::uuid', [binding.worktree_id, binding.owner_host_id]);
- if (!owner?.local_path || !owner.coordination_path) throw new OperationError('writer_registration_required', 'The canonical owner registration is incomplete.');
+ if (!owner?.local_path || !owner.coordination_path) {
+ throw opError('writer_registration_required', 'The canonical owner registration is incomplete.',
+ `Source '${source.id}' has an owner without a complete host registration (checkout and coordination paths), so activation stopped and nothing changed. Inspect its writer status; repairing ownership is a deliberate topology change the operator reviews, not routine repair.`,
+ { fix: writerStatusFix(`Shows source ${source.id}'s owner host and registration, read-only.`, source.id) });
+ }
if (binding.owner_host_id === hostId) {
if (source.root && !existsSync(resolve(source.root))) throw sourcePathMissing(source, binding.local_path && join(binding.local_path, binding.relative_path));
if (!binding.local_path || !binding.coordination_path
|| source.root && realpathSync(resolve(source.root)) !== realpathSync(join(binding.local_path, binding.relative_path))) {
- throw new OperationError('source_changed', `Source '${source.id}' no longer matches its registered canonical directory.`);
+ throw opError('source_changed', `Source '${source.id}' no longer matches its registered canonical directory.`,
+ `Source '${source.id}' records ${source.root ?? 'no path'}, but its registered canonical directory is ${binding.local_path ? join(binding.local_path, binding.relative_path) : 'incomplete'}, so activation stopped and nothing changed. Inspect its writer status and ask the user which directory is canonical before changing either.`,
+ { fix: writerStatusFix(`Shows source ${source.id}'s registered canonical directory, read-only.`, source.id) });
}
}
bindings.push(binding);
@@ -73,10 +84,18 @@ async function validatedBindings(engine: BrainEngine, sources: SourceRoot[], hos
/** Explicit coordinated-upgrade boundary. Refusal records become durable before enabled does. */
export async function activatePersistence(engine: BrainEngine, opts: { confirmQuiesced?: boolean; dryRun?: boolean; expectedState?: string; cleanupDeadLocalLocks?: boolean } = {}): Promise<ActivationReport> {
if (opts.confirmQuiesced !== true) throw quiescence();
- if (Number(await engine.getConfig('version')) < 157) throw new OperationError('writer_upgrade_required', 'Apply the canonical writer guard, outbox, and source lifecycle migrations before activation.');
+ if (Number(await engine.getConfig('version')) < 157) {
+ throw opError('writer_upgrade_required', 'Apply the canonical writer guard, outbox, and source lifecycle migrations before activation.',
+ 'This brain\'s schema predates managed persistence. List the pending migrations, ask the user to approve applying them, then rerun gbrain sources writer activate --confirm-quiesced --dry-run.',
+ { fix: { argv: ['gbrain', 'apply-migrations', '--dry-run', '--json'], consent: [], actor: 'agent', why: 'Lists the pending migrations without applying them.', requires_exclusive: false } });
+ }
const native = await nativeLockCapability();
const probe = await tryAcquireNativeLock(join(persistenceHome(), 'locks', 'activation-probe.lock'));
- if (!probe) throw new OperationError('writer_lock_unavailable', 'Another activation probe is running.');
+ if (!probe) {
+ throw opError('writer_lock_unavailable', 'Another activation probe is running.',
+ 'Another activation is running on this host and this attempt changed nothing. Let it finish, check the writer status, then rerun with --dry-run before activating.',
+ { fix: writerStatusFix('Shows whether managed persistence is now enabled and which owners are active, read-only.') });
+ }
await probe.release();
const [brain] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
if (brain?.enabled && opts.expectedState === undefined) {
@@ -122,7 +141,9 @@ export async function activatePersistence(engine: BrainEngine, opts: { confirmQu
const identity = (rows: WorktreeBinding[]) => JSON.stringify(rows.map(row => [row.source_id,row.source_incarnation,row.worktree_id,row.owner_host_id,
String(row.owner_epoch),String(row.topology_generation),row.relative_path,row.local_path,row.coordination_path]));
if (identity(bindings) !== identity(initial) || JSON.stringify(currentSources) !== JSON.stringify(sources)) {
- throw new OperationError('source_changed', 'Source ownership changed during activation; inspect writer status and retry.');
+ throw opError('source_changed', 'Source ownership changed during activation; inspect writer status and retry.',
+ 'Sources or their owners changed while activation ran, so it rolled back and nothing was activated. Inspect the writer status, then rerun gbrain sources writer activate --confirm-quiesced --dry-run before activating again.',
+ { fix: writerStatusFix('Shows the current sources, owners and registrations, read-only.') });
}
// Block fresh legacy lease admission for the duration of this commit.
// Even an expired row needs explicit inspection/removal; TTL is not proof
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index b6d846fd35..d8ccac259c 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -3,7 +3,7 @@ import { isAbsolute, join } from 'node:path';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { UNSUPPORTED_MANAGED_BULK_WRITERS } from './maintenance.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError, OperationError } from '../ops/contract.ts';
import { isValidSourceId } from '../source-id.ts';
import { assertValidSlugPrefixes } from '../grants/encoding.ts';
import { isWriteRequestId } from './types.ts';
@@ -17,11 +17,12 @@ import { writerOnboardingPreflight } from './onboarding.ts';
import { assertWriterAdminUnlocked, readWriterAdminLock, setWriterAdminLock } from './admin-lock.ts';
import { listBlockingEffects } from './blocking-effects.ts';
import { listWriterVersions } from './writer-versions.ts';
-import { trustedCliRequired } from '../ops/op-fix.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
-const invalid = (message: string) => new OperationError('invalid_params', message);
+const invalid = (message: string, suggestion = 'Correct that parameter and run the command again; gbrain sources writer --help and gbrain auth local-writer --help list each option and its accepted values.') =>
+ opError('invalid_params', message, suggestion);
function source(value: unknown): string {
- if (typeof value !== 'string' || !isValidSourceId(value)) throw invalid('An explicit active source ID is required.');
+ if (typeof value !== 'string' || !isValidSourceId(value)) throw invalid('An explicit active source ID is required.', 'Name the source explicitly with its id; gbrain sources list --json shows the active sources.');
return value;
}
function path(value: unknown): string {
@@ -80,7 +81,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
if (operation === 'writer_reconcile_backups') return (await import('./reconcile.ts')).runReconcileBackups(engine, params);
if (operation === 'company_brain_preview' || operation === 'company_brain_connect' || operation === 'company_brain_resume') {
const writer = currentVerifiedLocalWriter();
- if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw new OperationError('permission_denied', 'Company source administration requires an authenticated local CLI registration.');
+ if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw trustedCliRequired('Company source administration requires an authenticated local CLI registration.');
keys(params, ['brain_id', 'source_id', 'path', 'plan', 'request_id']);
if (typeof params.brain_id !== 'string' || !params.brain_id.trim()) throw invalid('An explicit brain_id is required.');
const destination = { brainId: params.brain_id, sourceId: source(params.source_id), remote: false };
@@ -113,7 +114,8 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
if (operation === 'writer_retry_effects') {
keys(params, ['source_id', 'request_id', 'dry_run']);
if (params.dry_run !== undefined && typeof params.dry_run !== 'boolean') throw invalid('dry_run must be a boolean.');
- if (!isWriteRequestId(params.request_id)) throw invalid('A valid original write request UUID is required.');
+ if (!isWriteRequestId(params.request_id)) throw invalid('A valid original write request UUID is required.',
+ 'Pass --request-id with the original write\'s request id (a UUID); gbrain sources writer status for that source lists blocked effects with their request ids.');
return (await import('./effect-retry.ts')).retryRequestEffects(engine, source(params.source_id), params.request_id, params.dry_run === true, config, embeddingRetryPolicy);
}
if (operation === 'source_add' || operation === 'source_lifecycle') {
@@ -158,7 +160,10 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
const { nativeLockCapability, tryAcquireNativeLock } = await import('./native-lock.ts');
const capability = await nativeLockCapability();
const lock = await tryAcquireNativeLock(join(persistenceHome(), 'locks', 'admin-status-probe.lock'));
- if (!lock) throw new OperationError('writer_lock_unavailable', 'The native lock probe is busy.');
+ if (!lock) {
+ throw opError('writer_lock_unavailable', 'The native lock probe is busy.',
+ 'Another writer status probe or activation holds the native probe lock on this host. Run the status again without --probe, or probe again once the other command finishes; both are read-only.');
+ }
await lock.release();
native = { ...capability, acquired: true, released: lock.released };
}
@@ -233,7 +238,11 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
if (params.self_transfer !== undefined && typeof params.self_transfer !== 'boolean') throw invalid('self_transfer must be a boolean.');
if (params.dry_run) {
const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
- if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) throw new OperationError('permission_denied', 'Only the current owner can prepare a transfer.');
+ if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) {
+ throw opError('permission_denied', 'Only the current owner can prepare a transfer.',
+ `This host is not source ${sourceId}'s current owner. Run the transfer prepare on the owner host that writer status names; a transfer is a deliberate topology change the operator reviews.`,
+ { fix: readFix(`Shows which host owns source ${sourceId}, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] }) });
+ }
const { manifest } = await prepareWriterTransfer(engine, sourceId, existingLocalHostId()!, undefined, { selfTransfer: params.self_transfer === true, dryRun: true });
return { dry_run: true, action: operation, binding, manifest: { digest: manifest.digest, file_count: manifest.file_count } };
}
diff --git a/src/core/persistence/derived-facts.ts b/src/core/persistence/derived-facts.ts
index f742fb1090..875f457b52 100644
--- a/src/core/persistence/derived-facts.ts
+++ b/src/core/persistence/derived-facts.ts
@@ -1,5 +1,7 @@
import type { BrainEngine, NewFact } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { currentSubmissionAuthority } from '../minions/submission-authority.ts';
import { withCoordinatedWrite } from './context.ts';
import { maintenanceAttribution } from './attribution.ts';
@@ -7,6 +9,8 @@ import { currentVerifiedLocalWriter } from './identity.ts';
import { managedPersistenceEnabled } from './ownership.ts';
import { assertPersistenceAccepting } from './service.ts';
+const sourcesFix = (sourceId: string): Action => readFix(`Lists sources with their archived state, including ${sourceId}.`, { argv: ['gbrain', 'sources', 'list', '--json'] });
+
/**
* Database-only fact rows derived from page text (the fence reconcile, the
* conversation fact index) never touch a canonical file, so a managed brain
@@ -19,10 +23,14 @@ export async function managedDerivedFactsPreflight(engine: BrainEngine, sourceId
assertPersistenceAccepting(engine);
const job = currentSubmissionAuthority();
if (job && job.kind !== 'application' || currentVerifiedLocalWriter()?.remote) {
- throw new OperationError('permission_denied', 'Managed fact maintenance requires a local writer; remote maintenance jobs are not supported.');
+ throw trustedCliRequired('Managed fact maintenance requires a local writer; remote maintenance jobs are not supported.');
}
const [source] = await engine.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1', [sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'The fact maintenance source is not active.');
+ if (!source || source.archived) {
+ throw opError('source_changed', 'The fact maintenance source is not active.',
+ `Source ${sourceId} is archived or missing, so its facts were not maintained and no model was called. Restore the source first if it should be maintained.`,
+ { fix: sourcesFix(sourceId) });
+ }
return true;
}
@@ -36,7 +44,11 @@ export async function withDerivedFactsWrite<T>(engine: BrainEngine, sourceId: st
const attribution = await maintenanceAttribution(engine);
return engine.transaction(tx => withCoordinatedWrite(tx, [sourceId], async () => {
const [source] = await tx.executeRaw<{ archived: boolean }>('SELECT archived FROM sources WHERE id=$1 FOR SHARE', [sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'The fact maintenance source changed during extraction; nothing was written.');
+ if (!source || source.archived) {
+ throw opError('source_changed', 'The fact maintenance source changed during extraction; nothing was written.',
+ `Source ${sourceId} was archived or removed while its facts were extracted, so nothing was written. Restore the source before maintaining its facts again.`,
+ { fix: sourcesFix(sourceId) });
+ }
await tx.lockPageKeys(slugs.map(slug => ({ sourceId, slug })));
return fn(tx);
}, attribution));
@@ -52,7 +64,10 @@ export async function writeDerivedFacts<T>(engine: BrainEngine, sourceId: string
if (!await managedPersistenceEnabled(engine)) return fn(engine);
return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {
const [page] = await tx.executeRaw('SELECT id FROM pages WHERE source_id=$1 AND slug=$2 AND deleted_at IS NULL', [sourceId, slug]);
- if (!page) throw new OperationError('page_not_found', 'The page was deleted during fact extraction; nothing was written.');
+ if (!page) {
+ throw opError('page_not_found', 'The page was deleted during fact extraction; nothing was written.',
+ `Page ${slug} in source ${sourceId} was deleted while its facts were extracted, so nothing was written. No action is needed unless the page should still exist.`);
+ }
return fn(tx);
});
}
@@ -72,7 +87,8 @@ export async function replaceDerivedFactsForPage(engine: BrainEngine, sourceId:
}): Promise<{ deleted: number; inserted: number }> {
return withDerivedFactsWrite(engine, sourceId, [slug], async tx => {
if (!await input.isCurrent(tx)) {
- throw new OperationError('revision_conflict', 'The page changed during fact extraction; its prior facts were kept.');
+ throw opError('revision_conflict', 'The page changed during fact extraction; its prior facts were kept.',
+ `Page ${slug} in source ${sourceId} changed while its facts were extracted, so its prior facts were kept. The next fact maintenance pass extracts from the current page.`);
}
const [deleted] = await tx.executeRaw<{ count: string }>(
`WITH del AS (DELETE FROM facts WHERE source_id=$1 AND source_markdown_slug=$2 AND source LIKE $3 RETURNING 1)
diff --git a/src/core/persistence/local-client.ts b/src/core/persistence/local-client.ts
index e43b3bdde1..b50737f1c4 100644
--- a/src/core/persistence/local-client.ts
+++ b/src/core/persistence/local-client.ts
@@ -6,9 +6,10 @@ import { configDir, type GBrainConfig } from '../config.ts';
import { resolveBrainId } from '../brain-resolver.ts';
import { getCliOptions } from '../cli-options.ts';
import { loadMounts, type MountEntry } from '../brain-registry.ts';
-import { inspectLockHolder } from '../pglite-lock.ts';
+import { inspectLockHolder, type LockHolderInfo } from '../pglite-lock.ts';
import { resolveSourceIdEngineFree } from '../source-resolver.ts';
-import { OperationError } from '../ops/contract.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { parseWriteRequestId } from './preconditions.ts';
import {
isPersistenceIpcMutation, isPersistenceIpcOperation, isPersistenceIpcRegistration,
@@ -19,6 +20,13 @@ import {
import type { PersistenceAdminOperation } from './admin-contract.ts';
import { currentCliWriteWait, replayWhilePending, writeExchangeBudget } from './write-wait.ts';
+function noDiscoveryPath(message: string, holder: LockHolderInfo, brainId?: string): OperationError {
+ const who = holder.pid ? `process ${holder.pid}${holder.subcommand ? ` (gbrain ${holder.subcommand})` : ''}` : 'another process';
+ return opError('owner_unavailable', message,
+ `${who} holds ${brainId ? `brain ${brainId}'s` : 'this brain\'s'} PGLite lock but publishes no persistence socket, usually an older gbrain serve. Ask the user to stop or upgrade that process, then run the command again; nothing was sent to it.`,
+ { fix: readFix('Shows the brain\'s lock holder and persistence state, read-only.', { argv: ['gbrain', 'doctor', ...(brainId ? ['--brain', brainId] : []), '--json'] }) });
+}
+
/** The brain axis must be resolved before inspecting any host lock/socket. */
export function persistenceConfigForBrain(
hostConfig: GBrainConfig | null,
@@ -27,7 +35,11 @@ export function persistenceConfigForBrain(
): GBrainConfig | null {
if (brainId === 'host') return hostConfig;
const mount = mounts.find(candidate => candidate.id === brainId || candidate.alias === brainId);
- if (!mount || mount.enabled === false) throw new OperationError('invalid_params', `Brain '${brainId}' is not an enabled mount.`);
+ if (!mount || mount.enabled === false) {
+ throw opError('invalid_params', `Brain '${brainId}' is not an enabled mount.`,
+ 'Pass --brain host or the id or alias of an enabled mount; re-enabling a disabled mount is the user\'s call.',
+ { fix: readFix('Lists mounted brains with their ids, aliases and enabled state.', { argv: ['gbrain', 'mounts', 'list', '--json'] }) });
+ }
return { engine: mount.engine, database_path: mount.database_path, database_url: mount.database_url } as GBrainConfig;
}
@@ -48,13 +60,17 @@ export function residentPersistenceConfig(hostConfig: GBrainConfig | null, cwd =
export function readPersistenceCliRegistration(brainId: string): PersistenceIpcRegistration {
// Capability validation has already constrained this filename component to a UUID.
const id = parseWriteRequestId(brainId);
- if (!id) throw new OperationError('permission_denied', 'Missing durable brain identity.');
+ if (!id) {
+ throw opError('permission_denied', 'Missing durable brain identity.',
+ 'The resident owner reported no durable brain identity, so this CLI cannot select its writer registration. Check the brain\'s persistence state; if an older owner is running, the user restarts it after upgrading.',
+ { fix: readFix('Shows the brain\'s persistence identity and lock holder, read-only.', { argv: ['gbrain', 'doctor', '--json'] }) });
+ }
let value: unknown;
try { value = JSON.parse(readFileSync(join(configDir(), 'persistence', `${id}.cli.json`), 'utf8')); }
catch { throw new OperationError('permission_denied', 'This CLI has no readable durable writer registration for the selected brain.',
'Register or explicitly regrant the CLI writer on this brain, then retry the same request ID.'); }
if (!isPersistenceIpcRegistration(value) || value.lane !== 'cli') {
- throw new OperationError('permission_denied', 'The local CLI writer registration is invalid.');
+ throw trustedCliRequired('The local CLI writer registration is invalid.');
}
return value;
}
@@ -70,7 +86,7 @@ export async function maybeDelegateLocalAdministration(
const holder = inspectLockHolder(config.database_path);
if (!holder.held) return { handled: false };
const socketPath = persistenceSocketPathForConfig(config);
- if (!socketPath) throw new OperationError('owner_unavailable', 'The PGLite owner has no persistence discovery path.');
+ if (!socketPath) throw noDiscoveryPath('The PGLite owner has no persistence discovery path.', holder);
const capability = await requestPersistenceCapabilities(socketPath);
if (!capability.administration?.includes(operation)) throw new OperationError('owner_unavailable',
'The running owner does not support this local administration command.', 'Upgrade and restart the owner before administering this brain.');
@@ -105,7 +121,7 @@ export async function maybeDelegateLocalOperation(
const holder = inspectLockHolder(config.database_path);
if (!holder.held) return { handled: false };
const socketPath = persistenceSocketPathForConfig(config);
- if (!socketPath) throw new OperationError('owner_unavailable', 'The selected PGLite owner has no persistence discovery path.');
+ if (!socketPath) throw noDiscoveryPath('The selected PGLite owner has no persistence discovery path.', holder, brainId);
// Takes' source is claim provenance, independent of the CLI source routing axis.
const sourceInParams = options.source === undefined && !operation.startsWith('takes_');
diff --git a/src/core/persistence/loop-fact-retirement.ts b/src/core/persistence/loop-fact-retirement.ts
index a4ae8d112d..89b169d9d9 100644
--- a/src/core/persistence/loop-fact-retirement.ts
+++ b/src/core/persistence/loop-fact-retirement.ts
@@ -24,7 +24,8 @@
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { OperationError, type OperationContext } from '../ops/contract.ts';
+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { serializePageToMarkdown } from '../markdown.ts';
import { formatFenceDate, type ParsedFact } from '../facts-fence.ts';
import { strikeFenceRow } from '../facts/forget.ts';
@@ -79,6 +80,12 @@ function heldReason(state: LoopFactState): 'loop_not_found' | 'no_fact' | 'fact_
const stateKey = (s: LoopFactState) => JSON.stringify([s.loop?.status, s.loop?.fact_id, s.fact?.source_id, s.fact?.expired_at, s.fact?.row_num, s.fact?.source_markdown_slug, s.shared]);
+function retirementRefusal(code: 'invalid_params' | 'revision_conflict', message: string, row: WriteRequest, what: string): OperationError {
+ return opError(code, message,
+ `${what} Request ${row.request_id} on ${row.slug} in source ${row.source_id} did not retire the loop's commitment fact; nothing was published. Preview the remaining loop-fact drift; applying that preview (--apply --expect with its hash) is a separate step the user approves.`,
+ { fix: readFix('Previews commitment facts still active for closed loops, without changing anything.', { argv: ['gbrain', 'repair', 'loop-facts', '--source', row.source_id, '--json'] }) });
+}
+
/** A closed loop's fence row: struck, valid until today, with the close recorded in its context. */
function closedLoopRow(fact: ParsedFact, today: string, status: string): ParsedFact {
const context = [`loop closed: ${status}`, fact.context?.trim()].filter(Boolean).join(' | ');
@@ -91,7 +98,7 @@ export async function prepareLoopFactRetirement(engine: BrainEngine, row: WriteR
const intent = row.intent as { kind?: string; loop_id?: number } | null;
const loopId = Number(intent?.loop_id);
if (row.operation !== LOOP_FACT_RETIREMENT_OPERATION || intent?.kind !== LOOP_FACT_RETIREMENT_KIND || !Number.isSafeInteger(loopId)) {
- throw new OperationError('invalid_params', 'Unsupported loop fact retirement intent.');
+ throw retirementRefusal('invalid_params', 'Unsupported loop fact retirement intent.', row, 'The request does not carry a loop fact retirement intent.');
}
const state = await loopFactState(engine, loopId);
const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });
@@ -104,17 +111,17 @@ export async function prepareLoopFactRetirement(engine: BrainEngine, row: WriteR
const page = struck !== null ? await (await import('./page-prepare.ts')).preparePageMutation(engine, { ...row, intent: {
content: serializePageToMarkdown({ ...snapshot!.page, compiled_truth: struck }, snapshot!.tags), expected_revision: observedRevision, force: false,
} }, config) : undefined;
- if (page && page.observedRevision !== observedRevision) throw new OperationError('revision_conflict', 'The fact page changed during preparation.');
+ if (page && page.observedRevision !== observedRevision) throw retirementRefusal('revision_conflict', 'The fact page changed during preparation.', row, 'The entity page changed while the retirement was prepared.');
const validate = async (tx: BrainEngine) => {
if (stateKey(await loopFactState(tx, loopId, true)) !== stateKey(state)) {
- throw new OperationError('revision_conflict', 'The loop or its commitment fact changed during preparation.');
+ throw retirementRefusal('revision_conflict', 'The loop or its commitment fact changed during preparation.', row, `Loop ${loopId} or its commitment fact changed while the retirement was prepared.`);
}
await page?.validate?.(tx);
};
const apply = async (tx: BrainEngine): Promise<Record<string, unknown>> => {
const expired = await tx.executeRaw(`UPDATE facts SET expired_at=now(), valid_until=LEAST(COALESCE(valid_until, now()), now())
WHERE id=$1 AND source_id=$2 AND expired_at IS NULL RETURNING id`, [fact.id, fact.source_id]);
- if (expired.length !== 1) throw new OperationError('revision_conflict', 'The commitment fact changed during publication.');
+ if (expired.length !== 1) throw retirementRefusal('revision_conflict', 'The commitment fact changed during publication.', row, `Fact ${fact.id} changed during publication, so the transaction rolled back.`);
const published = page ? await page.apply(tx) : {};
return { ...published, fact_expired: true, retryable: false, fence_struck: page !== undefined, fact_id: fact.id, loop_id: loopId };
};
diff --git a/src/core/persistence/memory-mutations.ts b/src/core/persistence/memory-mutations.ts
index e19d0924ae..ea9f77a556 100644
--- a/src/core/persistence/memory-mutations.ts
+++ b/src/core/persistence/memory-mutations.ts
@@ -1,6 +1,7 @@
import { randomUUID } from 'node:crypto';
import type { OperationContext } from '../ops/contract.ts';
-import { OperationError, verbError } from '../ops/contract.ts';
+import { opError, OperationError, verbError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { enforceClientSlugFence, enforceSubagentSlugFence, validatePageSlug } from '../ops/context.ts';
import { isNullLikeEntity } from '../facts/write-single.ts';
import { isFactWithdrawn, recordFactWithdrawal, type WithdrawalCommit } from '../facts/withdrawal.ts';
@@ -24,6 +25,12 @@ import { retryWriteAdmission } from './admission-retry.ts';
export { prepareMemoryMutation } from './memory-prepare.ts';
/** Only semantic appends without an explicit caller revision can be recomputed. */
+function sourceInactive(sourceId: string): OperationError {
+ return opError('source_changed', 'The write source is not active.',
+ `Source ${sourceId} is archived or missing, so nothing was saved. Write to an active source, or ask the user to restore ${sourceId}.`,
+ { fix: readFix('Lists sources with their archived state, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'], mcp: { tool: 'sources_list', arguments: {} } }) });
+}
+
export function isSemanticMemoryMutation(row: WriteRequest): boolean {
return row.operation === 'remember' && row.intent?.expected_revision === undefined;
}
@@ -35,7 +42,8 @@ async function submission(ctx: OperationContext, operation: string, params: Reco
const requestId = typeof p.request_id === 'string' ? p.request_id : randomUUID();
const sourceId = typeof p.source_id === 'string' ? p.source_id : ctx.sourceId ?? 'default';
if (ctx.remote !== false && sourceId !== (ctx.auth?.sourceId ?? ctx.sourceId ?? 'default')) {
- throw new OperationError('permission_denied', 'This source is outside the current write grant.');
+ throw opError('permission_denied', 'This source is outside the current write grant.',
+ `This connection may write only to source ${ctx.auth?.sourceId ?? ctx.sourceId ?? 'default'}. Omit source_id to write there, or ask the brain host's operator to grant source ${sourceId}.`);
}
await initializeLocalPersistence(ctx);
const principal = await requestPrincipalForContext(ctx);
@@ -70,7 +78,8 @@ async function planRememberTarget(ctx: OperationContext, sourceId: string, sourc
const snapshot = await ctx.engine.readPageSnapshot(slug, { sourceId, includeDeleted: true });
if (snapshot && (snapshot.page.deleted_at || ctx.remote !== false &&
!await ctx.engine.readPageSnapshot(slug, { sourceId, excludePrivate: authority.excludePrivate }))) {
- throw new OperationError('page_not_found', 'The target entity is not writable by this caller.');
+ throw opError('page_not_found', 'The target entity is not writable by this caller.',
+ `Entity page ${slug} in source ${sourceId} is deleted or not visible to this caller, so nothing was saved. Remember the fact against a visible entity, or without an entity (it is then filed under memory/unattributed).`);
}
if (inferred && !snapshot) throw new InferredTargetRejected('NO_ENTITY');
if (inferred && (await isFactWithdrawn(ctx.engine, sourceId, inferred.visibility, inferred.fact, slug)
@@ -138,7 +147,7 @@ export async function submitRememberMutation(ctx: OperationContext, params: Reco
const { p, sourceId, principal, callerIntent, requestId } = sub;
const [source] = await ctx.engine.executeRaw<RememberSource>(
"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 write source is not active.');
+ if (!source || source.archived) throw sourceInactive(sourceId);
const { parseTtlParam } = await import('../ops/facts.ts');
const validUntil = parseTtlParam(p.ttl);
const entity = typeof p.entity === 'string' && !isNullLikeEntity(p.entity) ? p.entity.trim() : null;
@@ -181,7 +190,7 @@ export async function submitForgetMutation(ctx: OperationContext, operation: 'fo
// Do not acquire a shared source lock first and upgrade it after admission.
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', 'The write source is not active.');
+ if (!source || source.archived) throw sourceInactive(sourceId);
// Another same-ID caller may have completed while we waited for the source.
const prior = await getWriteRequest(tx, principal, requestId);
if (prior) {
diff --git a/src/core/persistence/memory-prepare.ts b/src/core/persistence/memory-prepare.ts
index f97ad4f580..458dd9b5d9 100644
--- a/src/core/persistence/memory-prepare.ts
+++ b/src/core/persistence/memory-prepare.ts
@@ -1,6 +1,8 @@
import type { BrainEngine, NewFact } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import { opError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { pageIdentityError } from './page-identity.ts';
import { assertPageRevision } from '../page-state/types.ts';
import { parseFactsFence, renderFactsTable, replaceOrInsertFactsFence, upsertFactRow, formatFenceDate } from '../facts-fence.ts';
@@ -13,7 +15,16 @@ import type { WriteRequest } from './model.ts';
import { appendContextNote, type InferredVia } from '../facts/subject-infer.ts';
import { inferenceNote } from '../facts/subject-infer-write.ts';
-function conflict(): never { throw new OperationError('revision_conflict', 'The memory changed during semantic preparation.'); }
+function receiptFix(row: WriteRequest): Action {
+ return row.principal_kind === 'local_cli'
+ ? readFix(`Reads request ${row.request_id}'s durable receipt: its state and outcome, read-only.`, { argv: ['gbrain', 'write-request', '--', row.request_id] })
+ : readFix(`Shows source ${row.source_id}'s writer and requests in flight, including ${row.request_id}, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', '--source', row.source_id, '--json'] });
+}
+function conflict(row: WriteRequest): never {
+ throw opError('revision_conflict', 'The memory changed during semantic preparation.',
+ `Another write changed the facts or entity page in source ${row.source_id} while remember request ${row.request_id} was prepared, so it did not save. Check that request's receipt; once it shows conflict, nothing was saved and remembering the fact again is safe.`,
+ { fix: receiptFix(row) });
+}
function candidateState(value: Awaited<ReturnType<typeof decideSingleFact>>): string {
const c = value.candidate;
return JSON.stringify([value.status, c?.id, c?.fact, c?.kind, c?.visibility,
@@ -34,7 +45,11 @@ function outcome(id: number, status: 'inserted' | 'duplicate' | 'superseded', en
/** Every retry renders the semantic append from the latest coherent snapshot. */
export async function prepareMemoryMutation(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, signal?: AbortSignal): Promise<PreparedMutation> {
signal?.throwIfAborted();
- if (row.operation !== 'remember' || !row.intent) throw new OperationError('storage_error', 'Unknown memory mutation intent.');
+ if (row.operation !== 'remember' || !row.intent) {
+ throw opError('storage_error', 'Unknown memory mutation intent.',
+ `Request ${row.request_id} in source ${row.source_id} carries no remember intent, so the coordinator cannot apply it and nothing was saved. This is an internal fault: inspect the request, then report it to the user.`,
+ { fix: receiptFix(row) });
+ }
const p = row.intent;
const input: SingleFactIntent = { fact: String(p.fact).trim(), kind: (p.kind ?? 'fact') as SingleFactIntent['kind'],
visibility: (p.visibility ?? 'world') as SingleFactIntent['visibility'], entity_slug: p.entity_slug as string | null };
@@ -53,9 +68,9 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
const decision = await decideSingleFact(engine, row.source_id, input, dedupEmbedding, embedding_model);
const validate = async (tx: BrainEngine) => {
await assertFactNotWithdrawn(tx, row.source_id, input);
- if (embedding && JSON.stringify(await tx.executeRaw(`${embeddingConfigSql} FOR SHARE`)) !== observedEmbeddingConfig) conflict();
+ if (embedding && JSON.stringify(await tx.executeRaw(`${embeddingConfigSql} FOR SHARE`)) !== observedEmbeddingConfig) conflict(row);
const current = await decideSingleFact(tx, row.source_id, input, dedupEmbedding, embedding_model);
- if (candidateState(current) !== candidateState(decision)) conflict();
+ if (candidateState(current) !== candidateState(decision)) conflict(row);
};
if (decision.status === 'duplicate') {
const duplicate = decision.candidate!;
@@ -70,7 +85,11 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
let rowNum: number | undefined;
if (p.fence === true && snapshot) {
const parsed = parseFactsFence(snapshot.page.compiled_truth);
- if (parsed.warnings.length) throw new OperationError('storage_error', 'The entity facts fence is malformed; repair it before appending memory.');
+ if (parsed.warnings.length) {
+ throw opError('storage_error', 'The entity facts fence is malformed; repair it before appending memory.',
+ `The ## Facts table on ${row.slug} in source ${row.source_id} does not parse, so request ${row.request_id} saved nothing. Fix that table on the page (or ask the user to), then remember the fact again.`,
+ { fix: readFix(`Shows page ${row.slug} with its Facts table, read-only.`, { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug] }) });
+ }
const appended = upsertFactRow(snapshot.page.compiled_truth, { claim: input.fact, kind: input.kind, visibility: input.visibility,
confidence: 1, notability: 'medium', validFrom: formatFenceDate(validFrom),
validUntil: validUntil ? formatFenceDate(validUntil) : undefined, source: fact.source, context });
@@ -86,14 +105,18 @@ export async function prepareMemoryMutation(engine: BrainEngine, row: WriteReque
// Reuse the canonical parser/chunker and durable filesystem publication.
// The original caller revision was checked above; this CAS binds this render.
page = await preparePageMutation(engine, { ...row, intent: { ...p, content, expected_revision: observedRevision, force: false } }, config, undefined, signal);
- if (page.observedRevision !== observedRevision) conflict();
+ if (page.observedRevision !== observedRevision) conflict(row);
}
return { observedRevision, file: page?.file, validate: async tx => { await validate(tx); await page?.validate?.(tx); }, apply: async tx => {
await page?.apply(tx);
let id: number;
if (rowNum !== undefined) {
const inserted = await tx.insertFacts([{ ...fact, row_num: rowNum, source_markdown_slug: row.slug }], { source_id: row.source_id }); // gbrain-allow-direct-insert: coordinator atomically publishes the prepared canonical fact fence and its new indexed row
- if (inserted.ids.length !== 1) throw new OperationError('storage_error', 'The new canonical fact row was not indexed.');
+ if (inserted.ids.length !== 1) {
+ throw opError('storage_error', 'The new canonical fact row was not indexed.',
+ `The fact row for request ${row.request_id} in source ${row.source_id} was not indexed, so its transaction rolled back. Inspect the request before remembering again; if it repeats, run gbrain doctor --json and report it to the user.`,
+ { fix: receiptFix(row) });
+ }
id = inserted.ids[0];
} else {
const inserted = await tx.insertFact(fact, { source_id: row.source_id }); // gbrain-allow-direct-insert: journaled source-scoped semantic publication for subjectless or unresolved entity memory
diff --git a/src/core/persistence/topology-filesystem.ts b/src/core/persistence/topology-filesystem.ts
index bb1e45e5ae..cfac03f1b0 100644
--- a/src/core/persistence/topology-filesystem.ts
+++ b/src/core/persistence/topology-filesystem.ts
@@ -3,14 +3,19 @@ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync } fr
import { lstat, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { flushDirectory, flushFile } from '../fs-durable.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { durableSsrfFlags, GIT_ENV, GIT_SSRF_SUBCOMMAND_FLAGS, parseRemoteUrl } from '../git-remote.ts';
import { persistenceHome } from './identity.ts';
export { flushDirectory as flushTopologyDirectory } from '../fs-durable.ts';
+const recoveryFix=(why:string):Action=>readFix(why,{argv:['gbrain','sources','writer','status','--json']});
export function topologyDirectoryIdentity(path:string):{device:string;inode:string;birthNs:string}{
const info=lstatSync(path,{bigint:true});
- if(!info.isDirectory()||info.isSymbolicLink())throw new OperationError('recovery_required','The staging directory was substituted.');
+ if(!info.isDirectory()||info.isSymbolicLink())throw opError('recovery_required','The staging directory was substituted.',
+ `The topology staging path ${path} is no longer the directory gbrain created, so the lifecycle step stopped for recovery. Inspect the pending recovery in writer status; do not delete or recreate the staging directory by hand.`,
+ {fix:recoveryFix('Shows pending lifecycle requests and their recovery records, read-only.')});
return {device:info.dev.toString(),inode:info.ino.toString(),birthNs:info.birthtimeNs.toString()};
}
/** Complete tree accounting includes .git, sparse files, and metadata headroom. */
@@ -22,7 +27,9 @@ export async function topologyDirectoryBytes(root:string,limit=Number.MAX_SAFE_I
let info;
try{info=await lstat(path);}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')continue;throw error;}
bytes+=4096+info.size;
- if(!Number.isSafeInteger(bytes)||bytes>limit)throw new OperationError('request_too_large','The staged checkout exceeds its reserved recovery capacity.');
+ if(!Number.isSafeInteger(bytes)||bytes>limit)throw opError('request_too_large','The staged checkout exceeds its reserved recovery capacity.',
+ `The checkout staged at ${root} is larger than the ${limit} bytes reserved for its recovery. Inspect the pending lifecycle request in writer status; it needs a smaller repository or a larger recovery budget, which is the user's call.`,
+ {fix:recoveryFix('Shows the pending lifecycle request and the recovery capacity it holds, read-only.')});
if(info.isDirectory())for(const entry of await readdir(path))pending.push(join(path,entry));
}
return bytes;
@@ -30,7 +37,9 @@ export async function topologyDirectoryBytes(root:string,limit=Number.MAX_SAFE_I
export function flushTopologyTree(root:string):void{
const visit=(path:string)=>{
const info=lstatSync(path);
- if(info.isSymbolicLink())throw new OperationError('writer_manifest_unsafe','Canonical checkout recovery refuses symbolic links.');
+ if(info.isSymbolicLink())throw opError('writer_manifest_unsafe','Canonical checkout recovery refuses symbolic links.',
+ `The staged checkout contains a symbolic link at ${path}, and canonical recovery never follows links. Replace it with a regular file or directory in the repository, then inspect the pending recovery in writer status.`,
+ {fix:recoveryFix('Shows the pending lifecycle request this staged checkout belongs to, read-only.')});
if(info.isDirectory()){
for(const entry of readdirSync(path))visit(join(path,entry));
flushDirectory(path);
@@ -45,7 +54,9 @@ export function flushTopologyTree(root:string):void{
export async function cloneTopologyCheckout(url:string,destination:string,maxBytes:number,timeoutMs=600_000):Promise<void>{
parseRemoteUrl(url);
if(!existsSync(destination)||!lstatSync(destination).isDirectory()||lstatSync(destination).isSymbolicLink()||readdirSync(destination).length)
- throw new OperationError('recovery_required','The reserved clone staging directory must remain empty before cloning.');
+ throw opError('recovery_required','The reserved clone staging directory must remain empty before cloning.',
+ `The reserved clone directory ${destination} is missing or not empty, so cloning stopped for recovery. Inspect the pending recovery in writer status; recovery owns that directory, so do not clear it by hand.`,
+ {fix:recoveryFix('Shows pending lifecycle requests and their recovery records, read-only.')});
const base=join(persistenceHome(),'empty-hooks');mkdirSync(base,{recursive:true,mode:0o700});
const hooks=mkdtempSync(join(base,'clone-'));
const child=spawn('git',[...durableSsrfFlags(),'-c',`core.hooksPath=${hooks}`, 'clone',...GIT_SSRF_SUBCOMMAND_FLAGS,'--depth=1','--',url,destination],
@@ -68,7 +79,9 @@ export async function cloneTopologyCheckout(url:string,destination:string,maxByt
const monitor=setInterval(()=>{
if(!check)check=topologyDirectoryBytes(destination,maxBytes).then(()=>{}).catch(stop).finally(()=>{check=undefined;});
},50);
- const timer=setTimeout(()=>stop(new OperationError('storage_error','The staged clone exceeded its execution deadline.')),timeoutMs);
+ const timer=setTimeout(()=>stop(opError('storage_error','The staged clone exceeded its execution deadline.',
+ `Cloning into ${destination} ran past ${Math.round(timeoutMs/1000)} seconds and was stopped. Check that the remote is reachable and not unexpectedly large, and inspect the pending lifecycle request in writer status before submitting it again.`,
+ {fix:recoveryFix('Shows the pending lifecycle request and whether it is held for recovery, read-only.')})),timeoutMs);
try{
const code=await new Promise<number|null>((resolve,reject)=>{child.once('error',reject);child.once('exit',resolve);abandon=()=>resolve(null);});
await check;await stopping;
diff --git a/src/core/persistence/worktree-refresh.ts b/src/core/persistence/worktree-refresh.ts
index 96541125c4..fd5276890b 100644
--- a/src/core/persistence/worktree-refresh.ts
+++ b/src/core/persistence/worktree-refresh.ts
@@ -24,7 +24,9 @@ import type { SyncResult } from '../../commands/sync.ts';
import { execFileBounded } from '../brain-repo-durability.ts';
import { loadConfig } from '../config.ts';
import { catalogueError, type CatalogueName } from '../error-catalogue.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import { recordUpstreamObservation } from '../sync-upstream.ts';
import { checkpointRetryCommand } from './checkpoint-validation.ts';
import { localHostId, persistenceHome } from './identity.ts';
@@ -68,6 +70,8 @@ function refusal(name: CatalogueName, cause: string, fix: string, refreshId?: st
if (refreshId) error.detail = `refresh_id=${refreshId}`;
return error;
}
+const writerStatusFix = (why: string, sourceId?: string): Action => readFix(why,
+ { argv: ['gbrain', 'sources', 'writer', 'status', ...(sourceId ? ['--source', sourceId] : []), '--json'] });
const q = (value: string) => /^[A-Za-z0-9_./:@%+=,-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
/** Hardened git: no prompts, no user hooks, untranslated output, bounded. */
@@ -97,7 +101,11 @@ async function isAncestor(git: Git, root: string, ancestor: string, descendant:
/** Uncommitted paths (ignored files excluded) split into those the incoming diff touches and the rest. */
async function dirtyOverlap(git: Git, root: string, from: string, to: string): Promise<{ overlap: string[]; preserved: string[]; incoming: number }> {
const status = await git(['-C', root, 'status', '--porcelain=v1', '-z', '--untracked-files=normal']);
- if (status.code !== 0) throw new OperationError('storage_error', `git status failed in ${root}: ${status.stderr.trim().split('\n')[0]}`);
+ if (status.code !== 0) {
+ throw opError('storage_error', `git status failed in ${root}: ${status.stderr.trim().split('\n')[0]}`,
+ `Git could not read the checkout at ${root}, so the refresh stopped before merging and the checkout was not changed. Fix what git status reports there, check the refresh state, then rerun gbrain sources refresh for that source with --resume or --abandon.`,
+ { fix: writerStatusFix('Shows any refresh holding these sources in draining or fenced state, read-only.') });
+ }
const dirty: string[] = [];
const fields = status.stdout.split('\0');
for (let i = 0; i < fields.length; i++) {
@@ -107,7 +115,11 @@ async function dirtyOverlap(git: Git, root: string, from: string, to: string): P
if (entry[0] === 'R' || entry[0] === 'C') dirty.push(fields[++i]);
}
const diff = await git(['-C', root, 'diff', '--name-only', '-z', '--no-renames', from, to]);
- if (diff.code !== 0) throw new OperationError('storage_error', `git diff failed in ${root}: ${diff.stderr.trim().split('\n')[0]}`);
+ if (diff.code !== 0) {
+ throw opError('storage_error', `git diff failed in ${root}: ${diff.stderr.trim().split('\n')[0]}`,
+ `Git could not compare ${from} with ${to} in ${root}, so the refresh stopped before merging and the checkout was not changed. Make sure both commits exist locally (fetch again if needed), check the refresh state, then rerun gbrain sources refresh for that source with --resume or --abandon.`,
+ { fix: writerStatusFix('Shows any refresh holding these sources in draining or fenced state, read-only.') });
+ }
const incoming = diff.stdout.split('\0').filter(Boolean);
const touches = (path: string) => incoming.some(file => file === path || (path.endsWith('/') && file.startsWith(path)) || path.startsWith(`${file}/`));
const ours = (path: string) => isPhysicalRootMetadata(path.replace(/\/$/, '')) || path === '.gbrain-managed' || path.startsWith('.gbrain-managed/');
@@ -132,7 +144,11 @@ async function readActiveRefresh(engine: BrainEngine, worktreeId: string): Promi
}
async function readRefresh(engine: BrainEngine, id: string): Promise<WorktreeRefreshRow> {
const [row] = await engine.executeRaw<WorktreeRefreshRow>('SELECT * FROM persistence_worktree_refreshes WHERE id=$1::uuid', [id]);
- if (!row) throw new OperationError('not_found', 'The worktree refresh record disappeared.');
+ if (!row) {
+ throw opError('not_found', 'The worktree refresh record disappeared.',
+ `Refresh ${id}'s record is gone, so another process finished or removed it. Check the writer status before refreshing again.`,
+ { fix: writerStatusFix('Shows the current refresh and drain state of every managed source, read-only.') });
+ }
return row;
}
/** Conditional transition: returns false when another process already moved the row. */
@@ -254,7 +270,11 @@ async function headOf(git: Git, root: string): Promise<string | null> { return r
async function bookkeeping(engine: BrainEngine, row: WorktreeRefreshRow): Promise<void> {
await engine.transaction(async tx => {
await tx.executeRaw("SELECT set_config('synchronous_commit','on',true)");
- if (!await transition(tx, row, ['fenced', 'merged', 'recovery_required'], 'merged')) throw new OperationError('source_changed', 'The refresh record changed under its own lock.');
+ if (!await transition(tx, row, ['fenced', 'merged', 'recovery_required'], 'merged')) {
+ throw opError('source_changed', 'The refresh record changed under its own lock.',
+ `Another process moved refresh ${row.id} for ${row.source_ids.join(', ')} while this one held its lock, so this run stopped after the merge without recording it. Check the writer status, then converge with gbrain sources refresh ${row.source_ids[0]} --resume, which adopts only a HEAD it can verify.`,
+ { fix: writerStatusFix(`Shows refresh ${row.id}'s state and the member sources' heads, read-only.`, row.source_ids[0]) });
+ }
await tx.executeRaw(`UPDATE sources SET upstream_checked_at=now(),upstream_commit=$2,upstream_behind=0 WHERE id=ANY($1::text[])`, [row.source_ids, row.target_head]);
await transition(tx, row, ['merged'], 'syncing');
});
@@ -272,7 +292,8 @@ async function syncMembers(engine: BrainEngine, git: Git, row: WorktreeRefreshRo
let result: SyncResult;
try { result = await performManagedSync(engine, { sourceId, noPull: true }); }
catch (error) {
- const failure = error instanceof OperationError ? error : new OperationError('storage_error', error instanceof Error ? error.message : String(error));
+ const failure = error instanceof OperationError ? error : opError('storage_error', error instanceof Error ? error.message : String(error),
+ `The managed sync of source ${sourceId} failed during refresh ${row.id}. Check its writer status, fix the cause, then resume with gbrain sync --source ${sourceId} --no-pull --retry-failed.`);
blocked.push({ source_id: sourceId, code: failure.code, message: failure.message, resume: `gbrain sync --source ${sourceId} --no-pull --retry-failed` });
status = 'blocked';
break;