Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(errors): B10 backfill topology receipts, grandfather, page-mutations, persistence service and managed-sources refusals
garrytancd2c6e353e4d
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex 79aac39de1..9cd547c622 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -54,7 +54,6 @@ src/core/persistence/effect-targets.ts 2src/core/persistence/embed-facts-administration.ts 2src/core/persistence/embedding-settlement.ts 1src/core/persistence/facts-prepare.ts 13-src/core/persistence/grandfather.ts 6src/core/persistence/identity.ts 9src/core/persistence/import-mutations.ts 2src/core/persistence/ipc.ts 9@@ -62,10 +61,8 @@ src/core/persistence/journal.ts 8src/core/persistence/limits.ts 1src/core/persistence/local-client.ts 5src/core/persistence/loop-fact-retirement.ts 4-src/core/persistence/managed-sources.ts 5src/core/persistence/memory-mutations.ts 4src/core/persistence/memory-prepare.ts 4-src/core/persistence/page-mutations.ts 6src/core/persistence/page-prepare.ts 11src/core/persistence/page-visibility.ts 1src/core/persistence/projection-reindex.ts 7@@ -76,7 +73,6 @@ src/core/persistence/reconcile-prepare.ts 7src/core/persistence/reindex-administration.ts 3src/core/persistence/root-registry.ts 2src/core/persistence/semantic-pages.ts 3-src/core/persistence/service.ts 5src/core/persistence/skill-activation.ts 1src/core/persistence/staging.ts 2src/core/persistence/sync-administration.ts 1@@ -87,7 +83,6 @@ src/core/persistence/sync-wire.ts 1src/core/persistence/takes-prepare.ts 8src/core/persistence/topology-filesystem.ts 5src/core/persistence/topology-locks.ts 9-src/core/persistence/topology-receipts.ts 6src/core/persistence/unbound-source.ts 1src/core/persistence/worktree-refresh.ts 5src/core/repair/captured-facts.ts 1diff --git a/src/core/persistence/grandfather.ts b/src/core/persistence/grandfather.tsindex c8d3f4f32a..b889124c23 100644--- a/src/core/persistence/grandfather.ts+++ b/src/core/persistence/grandfather.ts@@ -4,7 +4,7 @@ import type { BrainEngine } from '../engine.ts';import { loadConfig } from '../config.ts';import { contentHash } from '../utils.ts';import { serializePageToMarkdown } from '../markdown.ts';-import { OperationError, type OperationContext } from '../ops/contract.ts';+import { opError, OperationError, type OperationContext } from '../ops/contract.ts';import { assertPageRevision } from '../page-state/types.ts';import { initializeLocalPersistence, requestPrincipalForContext } from './page-mutations.ts';import { submissionAuthority, authorizeStoredRequest } from './authority.ts';@@ -92,28 +92,40 @@ export async function admitCanonicalGrandfather(engine: BrainEngine, selected: Gexport async function prepareGrandfatherMutation(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {if (row.operation !== 'put_page' || row.intent?.kind !== 'managed_grandfather' || row.authority.remote !== false || row.authority.principal.kind !== 'local_cli') {- throw new OperationError('permission_denied', 'Grandfathering requires the trusted canonical migration path.');+ throw opError('permission_denied', 'Grandfathering requires the trusted canonical migration path.',+ `Request ${row.request_id} is not a trusted local grandfather write, so nothing changed. Grandfathering runs only from gbrain apply-migrations on the brain host.`);}await authorizeStoredRequest(engine, row);const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });- if (!snapshot || snapshot.page.id !== row.page_id) throw new OperationError('page_identity_changed', 'The grandfathered page identity changed.');+ if (!snapshot || snapshot.page.id !== row.page_id) {+ throw opError('page_identity_changed', 'The grandfathered page identity changed.',+ `${row.slug} in ${row.source_id} was deleted or replaced after grandfathering was queued, so it was skipped; the next migration run re-plans from current pages.`);+ }assertPageRevision(snapshot, { expectedRevision: row.intent.expected_revision as string });- if (Object.hasOwn(snapshot.page.frontmatter ?? {}, 'validate')) throw new OperationError('revision_conflict', 'A validation decision already exists.');+ if (Object.hasOwn(snapshot.page.frontmatter ?? {}, 'validate')) {+ throw opError('revision_conflict', 'A validation decision already exists.',+ `${row.slug} in ${row.source_id} already records a validate decision, so grandfathering left it unchanged; nothing else is needed.`);+ }if (snapshot.page.frontmatter != null && (typeof snapshot.page.frontmatter !== 'object' || Array.isArray(snapshot.page.frontmatter))) {- throw new OperationError('invalid_params', 'Grandfathering requires valid object frontmatter.');+ throw opError('invalid_params', 'Grandfathering requires valid object frontmatter.',+ `${row.slug} in ${row.source_id} has frontmatter that is not a YAML mapping. Fix the page's frontmatter, then run the migration again.`);}const frontmatter = { ...snapshot.page.frontmatter, validate: false };const hash = contentHash({ ...snapshot.page, frontmatter, tags: snapshot.tags });const file = await prepareFileTarget(engine, row, snapshot, serializePageToMarkdown({ ...snapshot.page, frontmatter }, snapshot.tags));if (file && !['.md', '.mdx'].includes(extname(file.path).toLowerCase())) {- throw new OperationError('invalid_params', 'Non-Markdown artifacts cannot be grandfathered by rewriting their bytes.');+ throw opError('invalid_params', 'Non-Markdown artifacts cannot be grandfathered by rewriting their bytes.',+ `${row.slug} in ${row.source_id} is backed by a non-Markdown file, so grandfathering skips it rather than rewrite its bytes; no action is needed.`);}return { observedRevision: snapshot.revision, file, ...databaseOnlyPublication(row, file), deferEmbedding: true, apply: async tx => {await tx.createVersion(row.slug, { sourceId: row.source_id });const updated = await tx.executeRaw(`UPDATE pages SET frontmatter=jsonb_set(COALESCE(frontmatter,'{}'::jsonb),'{validate}','false'::jsonb),content_hash=$4WHERE id=$1 AND source_id=$2 AND knowledge_revision=$3::uuid AND NOT(COALESCE(frontmatter,'{}'::jsonb)?'validate') RETURNING id`,[row.page_id, row.source_id, snapshot.revision, hash]);- if (updated.length !== 1) throw new OperationError('revision_conflict', 'The validation decision changed before publication.');+ if (updated.length !== 1) {+ throw opError('revision_conflict', 'The validation decision changed before publication.',+ `${row.slug} in ${row.source_id} changed while it was being grandfathered, so the transaction rolled back; the next migration run re-plans from current pages.`);+ }if (snapshot.page.text_projection_revision === snapshot.revision) {await tx.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1 AND source_id=$2', [row.page_id, row.source_id]);}diff --git a/src/core/persistence/managed-sources.ts b/src/core/persistence/managed-sources.tsindex 4e13b348b8..d7dafbc2ab 100644--- a/src/core/persistence/managed-sources.ts+++ b/src/core/persistence/managed-sources.ts@@ -19,12 +19,15 @@ export function assertTopologyCommitted(result:Record<string,unknown>):void{}/** Normalize one caller intent without provider, database or canonical write work. */export function managedSourceAddInput(opts:AddSourceOpts):SourceLifecycleInput{- if(!isValidSourceId(opts.id))throw new OperationError('invalid_params','A valid explicit source ID is required.');+ if(!isValidSourceId(opts.id))throw new OperationError('invalid_params','A valid explicit source ID is required.',+ 'Pass a source id of 1-32 lowercase letters, digits and inner hyphens (for example "notes" or "acme-wiki").');if(opts.remoteUrl&&opts.localPath||opts.github&&opts.google||(opts.github||opts.google)&&(opts.remoteUrl||opts.localPath))- throw new OperationError('invalid_params','Choose exactly one source location: path, remote URL, GitHub, or Google.');- if(opts.cloneDir&&!opts.remoteUrl)throw new OperationError('invalid_params','cloneDir requires a remote URL.');+ throw new OperationError('invalid_params','Choose exactly one source location: path, remote URL, GitHub, or Google.',+ `Add source ${opts.id} with exactly one of a local path, a Git remote URL, a GitHub connector or a Google connector.`);+ if(opts.cloneDir&&!opts.remoteUrl)throw new OperationError('invalid_params','cloneDir requires a remote URL.',+ `Drop the clone directory for source ${opts.id}, or pass it together with the Git remote URL it should clone.`);if(opts.force!==undefined&&typeof opts.force!=='boolean'||opts.federated!=null&&typeof opts.federated!=='boolean')- throw new OperationError('invalid_params','force and federated must be boolean values.');+ throw new OperationError('invalid_params','force and federated must be boolean values.','Pass force and federated as true or false, or omit them.');let path=opts.localPath?resolve(msysToNativePath(opts.localPath)):undefined;let config:Record<string,unknown>=opts.federated==null?{}:{federated:opts.federated};if(opts.remoteUrl){path=resolve(opts.cloneDir??defaultCloneDir(opts.id));config={...config,remote_url:opts.remoteUrl,managed_clone:true};}@@ -49,6 +52,7 @@ export async function addManagedSource(engine:BrainEngine,opts:AddSourceOpts):Prconst result=await runManagedSourceLifecycle(engine,managedSourceAddInput(opts));assertTopologyCommitted(result);const [row]=await engine.executeRaw<SourceRow>('SELECT * FROM sources WHERE id=$1 AND incarnation=$2::uuid',[opts.id,result.source_incarnation]);- if(!row)throw new OperationError('source_changed','The created source was subsequently removed.');+ if(!row)throw new OperationError('source_changed','The created source was subsequently removed.',+ `Source ${opts.id} committed and was then removed by another lifecycle change before it could be read. Check the registered sources before adding it again.`);return row;}diff --git a/src/core/persistence/page-mutations.ts b/src/core/persistence/page-mutations.tsindex 398651b64c..0f4e281a7c 100644--- a/src/core/persistence/page-mutations.ts+++ b/src/core/persistence/page-mutations.ts@@ -40,9 +40,14 @@ export async function initializeLocalPersistence(ctx: OperationContext): Promise/** Validate explicit routing before any admission, including dry-run adapters. */export function pageMutationSource(ctx: OperationContext, params: Record<string, unknown>, operation: string): string {const sourceId = parseSourceIdParam(params.source_id, operation) ?? ctx.sourceId ?? 'default';- if (sourceId === '__all__') throw new OperationError('invalid_params', 'A mutation must target exactly one source.');- if (ctx.remote !== false && sourceId !== (ctx.auth?.sourceId ?? ctx.sourceId ?? 'default')) {- throw new OperationError('permission_denied', 'This source is outside the current write grant.');+ if (sourceId === '__all__') {+ throw new OperationError('invalid_params', 'A mutation must target exactly one source.',+ `Pass source_id as one source (for example ${ctx.sourceId && ctx.sourceId !== '__all__' ? ctx.sourceId : 'default'}); writes never fan out across sources.`);+ }+ const granted = ctx.auth?.sourceId ?? ctx.sourceId ?? 'default';+ if (ctx.remote !== false && sourceId !== granted) {+ throw new OperationError('permission_denied', 'This source is outside the current write grant.',+ `This connection writes only to source ${granted}. Pass source_id ${granted} (or omit it), or ask the brain host's operator to grant write access to ${sourceId}.`);}return sourceId;}@@ -52,7 +57,9 @@ export function pageMutationSource(ctx: OperationContext, params: Record<string,* that file, so only a capture under that slug binds the file as its origin.*/async function resolveCaptureFile(ctx: OperationContext, sourceId: string, p: Record<string, unknown>): Promise<string | null> {- if (Object.hasOwn(p, 'capture_path')) throw new OperationError('invalid_params', 'capture_path is reserved for the capture owner.');+ if (Object.hasOwn(p, 'capture_path')) {+ throw new OperationError('invalid_params', 'capture_path is reserved for the capture owner.', 'Drop capture_path and pass the text as content; gbrain sets the capture path itself.');+ }if (p.local_file === undefined) return null;if (ctx.remote !== false || typeof p.local_file !== 'string' || !isAbsolute(p.local_file)) {throw new OperationError('invalid_params', 'Capture file paths are accepted only from the trusted local CLI.',@@ -81,7 +88,8 @@ export async function submitPageMutation(ctx: OperationContext,if (input.operation === 'put_page' && ['kind', 'preview', 'backup_reference'].some(key => Object.hasOwn(input.params, key))) {if (ctx.remote !== false || input.managedFileImport !== true || input.params.kind !== 'managed_file_import' ||['preview', 'backup_reference'].some(key => Object.hasOwn(input.params, key))) {- throw new OperationError('invalid_params', 'Reserved persistence fields cannot be submitted through put_page. Use trusted local reconciliation administration.');+ throw new OperationError('invalid_params', 'Reserved persistence fields cannot be submitted through put_page. Use trusted local reconciliation administration.',+ 'Drop kind, preview and backup_reference from put_page; reconciling a canonical file runs through gbrain sources reconcile on the brain host.');}}assertPersistenceAccepting(ctx.engine);@@ -104,7 +112,10 @@ export async function submitPageMutation(ctx: OperationContext,if (input.operation === 'delete_page') assertPurgeParams(p, ctx.remote);const [source] = await ctx.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 write source is not active.');+ if (!source || source.archived) {+ throw new OperationError('source_changed', 'The write source is not active.',+ `Source ${sourceId} is archived or not registered, so nothing was written. Write to an active source (sources_list shows them).`);+ }let slug = typeof p.slug === 'string' ? p.slug.toLowerCase() : '';const intent = ['takes_add','takes_update','takes_supersede','takes_resolve'].includes(input.operation)? await (await import('./takes-prepare.ts')).normalizeTakesIntent(ctx,p) : { ...p };@@ -114,7 +125,8 @@ export async function submitPageMutation(ctx: OperationContext,? await undeclaredPageTypeWarning(ctx, { ...intent, slug }, sourceId) : null;if (input.operation === 'capture') {if (typeof p.content !== 'string' || !normalizeForHash(p.content) || detectBinaryNullByte(Buffer.from(p.content)) !== -1) {- throw new OperationError('invalid_params', 'Capture requires nonempty text without binary NUL bytes.');+ throw new OperationError('invalid_params', 'Capture requires nonempty text without binary NUL bytes.',+ 'Pass content as non-empty text; binary files are not captured (store them with file_upload instead).');}const explicitType = explicitCaptureType(p.content, typeof p.type === 'string' ? p.type : undefined);if (explicitType) {diff --git a/src/core/persistence/service.ts b/src/core/persistence/service.tsindex 035b0b4e29..56a320794d 100644--- a/src/core/persistence/service.ts+++ b/src/core/persistence/service.ts@@ -24,12 +24,12 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestassertMutationProtocol(row);const registered = preparers.get(row.operation);if (registered) {- if (registered.target !== (row.target_kind ?? 'page')) throw new OperationError('unsupported_mutation_protocol', 'The registered preparer does not support this mutation target.');+ if (registered.target !== (row.target_kind ?? 'page')) throw new OperationError('unsupported_mutation_protocol', 'The registered preparer does not support this mutation target.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);return registered.prepare(e, row, cfg, signal);}if (row.target_kind === 'skill_bundle') {if (['put_skill', 'delete_skill'].includes(row.operation)) return (await import('../shared-skills/publication.ts')).prepareSharedSkillMutation(e, row, cfg);- throw new OperationError('unsupported_mutation_protocol', 'No compatible skill mutation preparer is registered.');+ throw new OperationError('unsupported_mutation_protocol', 'No compatible skill mutation preparer is registered.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);}if (row.operation === 'submit_job' && String(row.intent?.kind).startsWith('managed_atom_')) return (await import('./atom-maintenance.ts')).prepareManagedAtomMutation(e, row, cfg);if (row.operation === 'extract_facts' && String(row.intent?.kind).startsWith('managed_facts_')) return (await import('./facts-prepare.ts')).prepareManagedFactsMutation(e, row, cfg);@@ -48,12 +48,15 @@ export async function preparePersistedMutation(e: BrainEngine, row: WriteRequestif (['takes_add','takes_update','takes_supersede','takes_resolve'].includes(row.operation)) return (await import('./takes-prepare.ts')).prepareTakesMutation(e,row,cfg);if (['add_tag','remove_tag','add_timeline_entry'].includes(row.operation)) return prepareSemanticPageMutation(e, row, cfg);if (['put_page','capture','delete_page','restore_page','revert_version','edit_page'].includes(row.operation)) return preparePageMutation(e, row, cfg, undefined, signal);- throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.');+ throw new OperationError('unsupported_mutation_protocol', 'No compatible mutation preparer is registered for this operation.', `Request ${row.request_id} (${row.operation}) was accepted by a gbrain version whose preparer this one lacks, so it has not run. Run gbrain upgrade on every host that serves this brain; the request stays journaled and resumes after the upgrade.`);}export function startPersistenceConsumer(engine: BrainEngine, config: GBrainConfig): PersistenceConsumer {const prior = services.get(engine);if (prior) {- if (prior.stopping) throw new OperationError('unavailable', 'The persistence owner is closing.');+ if (prior.stopping) {+ throw new OperationError('unavailable', 'The persistence owner is closing.',+ 'The persistence owner in this process is shutting down; start the command again after it exits. Accepted writes stay journaled and resume on the next owner.');+ }return prior.consumer;}const consumer = new PersistenceConsumer(engine, config, preparePersistedMutation);@@ -98,7 +101,10 @@ export function persistenceConsumerStatus(engine: BrainEngine) {: { state: 'not_running', accepting: false, active_preparations: 0, active_worktrees: 0 };}export function assertPersistenceAccepting(engine: BrainEngine): void {- if (services.get(engine)?.stopping) throw new OperationError('unavailable', 'The persistence owner is closing. Retry the same request_id after restart.');+ if (services.get(engine)?.stopping) {+ throw new OperationError('unavailable', 'The persistence owner is closing. Retry the same request_id after restart.',+ 'Nothing new was accepted. After the owner restarts, resubmit with the same request_id so a write that was already accepted is never applied twice.');+ }}/** The waiter never owns a provider, database connection, or kernel lock. */export async function waitForWrite(engine: BrainEngine, row: WriteRequest, config: GBrainConfig, waitMs = 5000): Promise<WriteRequest> {diff --git a/src/core/persistence/topology-receipts.ts b/src/core/persistence/topology-receipts.tsindex f8cc03b4ba..bcdbc07e9a 100644--- a/src/core/persistence/topology-receipts.ts+++ b/src/core/persistence/topology-receipts.ts@@ -1,8 +1,8 @@import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';import { digest, jsonBytes } from './digest.ts';import { lockCounters } from './journal.ts';-import { readJournalLimits } from './limits.ts';+import { journalLimitKey, readJournalLimits } from './limits.ts';import { principalKey } from './model.ts';export interface TopologyChange {@@ -12,16 +12,19 @@ export interface TopologyChange {}export async function priorTopologyChange(engine:BrainEngine,principal:string,requestId:string,intent:unknown):Promise<TopologyChange|null> {const page=await engine.executeRaw("SELECT id FROM persistence_requests WHERE principal_kind='local_cli' AND principal_id=$1 AND request_id=$2::uuid",[principal,requestId]);- if(page.length) throw new OperationError('idempotency_conflict','This request_id belongs to a page mutation.');+ if(page.length) throw opError('idempotency_conflict','This request_id belongs to a page mutation.',+ `Request ${requestId} already names a page write, so this lifecycle change was not accepted. Submit it with a new request id, or omit the id so gbrain generates one.`);const [prior]=await engine.executeRaw<TopologyChange>('SELECT * FROM persistence_topology_changes WHERE principal_id=$1::uuid AND request_id=$2::uuid',[principal,requestId]);- if(prior && prior.digest!==digest(intent)) throw new OperationError('idempotency_conflict','This lifecycle request_id was accepted with different arguments.');+ if(prior && prior.digest!==digest(intent)) throw opError('idempotency_conflict','This lifecycle request_id was accepted with different arguments.',+ `Request ${requestId} was accepted for a ${prior.operation} of source ${prior.source_id} with other arguments. Reuse it only to resubmit that identical command; give a different change a new request id.`);return prior??null;}export async function recordTopologyChange(tx:BrainEngine, input:{principal:string;requestId:string;intent:unknown;operation:string;sourceId:string;incarnation:string|null;worktrees:string[]},outcome:Record<string,unknown>, recovery:Record<string,unknown>|null=null,recoveryBytes=0):Promise<TopologyChange> {const terminalBytes=16_384;const intentBytes=recovery?jsonBytes(input.intent):0;- if(Buffer.byteLength(JSON.stringify(outcome))+1024>terminalBytes) throw new OperationError('request_too_large','Lifecycle outcome exceeds its retained receipt capacity.');+ if(Buffer.byteLength(JSON.stringify(outcome))+1024>terminalBytes) throw opError('request_too_large','Lifecycle outcome exceeds its retained receipt capacity.',+ `The ${input.operation} of source ${input.sourceId} would record an outcome over ${terminalBytes - 1024} bytes, so nothing was recorded. Report this to the user with the request id ${input.requestId}; it is not a caller mistake.`);const limits=await readJournalLimits(tx);const key=principalKey({kind:'local_cli',id:input.principal});const counters=await lockCounters(tx,['brain',key,...input.worktrees.map(id=>`worktree:${id}`)]);@@ -31,13 +34,16 @@ export async function recordTopologyChange(tx:BrainEngine, input:{principal:striif(!counter.key.startsWith('worktree:')){if(recovery && (Number(counter.outstanding_count)+1>(brain?limits.brainOutstanding:limits.principalOutstanding)||Number(counter.intent_bytes)+intentBytes>(brain?limits.brainIntentBytes:limits.principalIntentBytes)))- throw new OperationError('queue_capacity','Pending lifecycle work exceeds available brain/principal request or intent capacity.');+ throw opError('queue_capacity','Pending lifecycle work exceeds available brain/principal request or intent capacity.',+ `Too much lifecycle work is still pending, so the ${input.operation} of source ${input.sourceId} was not accepted. Let the pending work settle, then submit it again; raising ${journalLimitKey(brain?'brainOutstanding':'principalOutstanding')} is the user's call.`, { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', input.sourceId, '--json'], consent: [], actor: 'agent', why: 'Shows the pending lifecycle and recovery work that holds this capacity.', requires_exclusive: false } });if(Number(counter.lifetime_ids)+1>(brain?limits.brainLifetimeIds:limits.principalLifetimeIds)||Number(counter.terminal_bytes)+terminalBytes>(brain?limits.brainTerminalBytes:limits.principalTerminalBytes))- throw new OperationError('queue_capacity','Permanent lifecycle receipts reached the configured capacity. Increase the quota; existing IDs are retained.');+ throw opError('queue_capacity','Permanent lifecycle receipts reached the configured capacity. Increase the quota; existing IDs are retained.',+ `Retained lifecycle receipts reached ${journalLimitKey(brain?'brainLifetimeIds':'principalLifetimeIds')} or ${journalLimitKey(brain?'brainTerminalBytes':'principalTerminalBytes')}, so the ${input.operation} of source ${input.sourceId} was not accepted. Ask the user whether to raise the quota with gbrain config set; receipts are never evicted.`);}if(recoveryBytes && counter.key!==key && Number(counter.recovery_bytes)+recoveryBytes>(brain?limits.brainRecoveryBytes:limits.worktreeRecoveryBytes))- throw new OperationError('queue_capacity','The lifecycle recovery exceeds available brain/worktree capacity.');+ throw opError('queue_capacity','The lifecycle recovery exceeds available brain/worktree capacity.',+ `Recovery records already use the ${journalLimitKey(brain?'brainRecoveryBytes':'worktreeRecoveryBytes')} budget, so the ${input.operation} of source ${input.sourceId} was not accepted. Let recovery settle first; raising the cap is the user's call and recovery records are never removed.`, { fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--source', input.sourceId, '--json'], consent: [], actor: 'agent', why: 'Shows the pending lifecycle and recovery work that holds this capacity.', requires_exclusive: false } });}const [row]=await tx.executeRaw<TopologyChange>(`INSERT INTO persistence_topology_changes(principal_id,request_id,digest,operation,source_id,source_incarnation,worktree_ids,state,recovery,recovery_bytes,terminal_bytes,outcome,intent_bytes)