Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
agent contract: company-brain receipt and policy refusals name their own next step
garrytan155f7a04b530
diff --git a/docs/guides/error-codes.md b/docs/guides/error-codes.mdindex f9d0ffea0e..d4864301d7 100644--- a/docs/guides/error-codes.md+++ b/docs/guides/error-codes.md@@ -1003,6 +1003,26 @@ More: [docs/guides/google-connect.md#troubleshooting](../../docs/guides/google-c|---|---|---|---|---|---|---|| A parameter is missing, has the wrong type, or has an invalid value. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 2 | no |+### invalid_receipt++<a id="invalid_receipt"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| A company-source ingestion receipt input failed validation inside gbrain; nothing was written. | The server failed; this is not a caller mistake. | Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guides/company-brain-ingestion.md#resume-and-verify)++### invalid_receipt_transition++<a id="invalid_receipt_transition"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| An ingestion receipt cannot skip a phase or complete while files failed, writes are pending or verification failed. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guides/company-brain-ingestion.md#resume-and-verify)+### invalid_request<a id="invalid_request"></a>@@ -1447,6 +1467,46 @@ More: [docs/guides/repair.md#projection-owner-resident](../../docs/guides/repair|---|---|---|---|---|---|---|| The request was rate-limited; retry after the stated delay. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |+### receipt_conflict++<a id="receipt_conflict"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The ingestion receipt changed since it was read. | A temporary condition (a lock, a pending write, a rate limit); the same request can succeed later. | Wait briefly, then retry the same request (writes: reuse the same request_id). | agent | `repeat the read that failed` | 1 | yes |++More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guides/company-brain-ingestion.md#resume-and-verify)++### receipt_fence_changed++<a id="receipt_fence_changed"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The managed owner, topology or source binding changed while the ingestion ran. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guides/company-brain-ingestion.md#resume-and-verify)++### receipt_fence_required++<a id="receipt_fence_required"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| Ingestion into a managed or bound source needs the worktree owner's fence. | Only the operator of the brain host can change what blocks this. | Only the brain host's operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host. | host_admin | `gbrain doctor --json` | 1 | no |++More: [docs/guides/company-brain-ingestion.md#resume-and-verify](../../docs/guides/company-brain-ingestion.md#resume-and-verify)++### receipt_identity_mismatch++<a id="receipt_identity_mismatch"></a>++| Meaning | Why | Next step | Who acts · consent | Verify | Exit | Retryable |+|---|---|---|---|---|---|---|+| The receipt ID is already bound to different approved ingestion metadata. | The request itself was wrong or no longer matches the brain; nothing was changed. | Correct the request using the message above, then retry. | agent | `repeat the read that failed` | 1 | no |++More: [docs/guides/company-brain-ingestion.md#agent-and-ci-use](../../docs/guides/company-brain-ingestion.md#agent-and-ci-use)+### recovery_required<a id="recovery_required"></a>diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex b1c27623fa..96ed1305e6 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -1,7 +1,5 @@# shrink-only baseline for scripts/check-agent-contract.ts rule suggestionless-operation-error: path<TAB>countsrc/commands/book-mirror.ts 1-src/core/company-brain/policy.ts 2-src/core/company-brain/receipts.ts 1src/core/facts/backstop.ts 1src/core/minions/submission-authority.ts 1src/core/minions/tool-write-identity.ts 1diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.tsindex c8ffc3b257..92e718c75c 100644--- a/scripts/check-agent-contract.ts+++ b/scripts/check-agent-contract.ts@@ -140,14 +140,27 @@ function nullishDefaulted(fn: FnLike, name: string): boolean {interface Funnel { name: string; index: number }export interface FunnelSite { file: string; line: number; funnel: string; texts: string[] | undefined; expr: string }+/** File-level `const NAME = <string literal>` bindings, so a shared suggestion constant counts as literal text. */+function literalConsts(sf: ts.SourceFile): Map<string, string> {+ const out = new Map<string, string>();+ for (const statement of sf.statements) {+ if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;+ for (const d of statement.declarationList.declarations) {+ const t = ts.isIdentifier(d.name) && d.initializer ? flatText(d.initializer, sf) : undefined;+ if (t !== undefined) out.set((d.name as ts.Identifier).text, t);+ }+ }+ return out;+}+/** Literal texts of a suggestion expression (each branch of a conditional); undefined when any branch is not literal. */-function suggestionTexts(n: ts.Expression, sf: ts.SourceFile): string[] | undefined {- if (ts.isParenthesizedExpression(n)) return suggestionTexts(n.expression, sf);+function suggestionTexts(n: ts.Expression, sf: ts.SourceFile, consts: Map<string, string>): string[] | undefined {+ if (ts.isParenthesizedExpression(n)) return suggestionTexts(n.expression, sf, consts);if (ts.isConditionalExpression(n)) {- const a = suggestionTexts(n.whenTrue, sf); const b = suggestionTexts(n.whenFalse, sf);+ const a = suggestionTexts(n.whenTrue, sf, consts); const b = suggestionTexts(n.whenFalse, sf, consts);return a && b ? [...a, ...b] : undefined;}- const t = flatText(n, sf);+ const t = ts.isIdentifier(n) ? consts.get(n.text) : flatText(n, sf);return t === undefined ? undefined : [t];}@@ -197,6 +210,7 @@ function funnelCallSites(sf: ts.SourceFile, path: string): FunnelSite[] {const funnels = fileFunnels(sf);if (!funnels.length) return [];const out: FunnelSite[] = [];+ const consts = literalConsts(sf);const visit = (n: ts.Node) => {if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {for (const f of funnels) {@@ -205,7 +219,7 @@ function funnelCallSites(sf: ts.SourceFile, path: string): FunnelSite[] {if (arg && ts.isIdentifier(arg) && enclosingSuggestionParams(n).has(arg.text)) continue;out.push({file: path, line: sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1, funnel: f.name,- texts: arg ? suggestionTexts(arg, sf) : undefined, expr: arg ? arg.getText(sf) : '',+ texts: arg ? suggestionTexts(arg, sf, consts) : undefined, expr: arg ? arg.getText(sf) : '',});}}diff --git a/src/core/company-brain/policy.ts b/src/core/company-brain/policy.tsindex eb53ca9720..7acc4b77ac 100644--- a/src/core/company-brain/policy.ts+++ b/src/core/company-brain/policy.ts@@ -1,7 +1,8 @@import { isAbsolute, relative, resolve, sep } from 'node:path';import { z } from 'zod';import { validateMountId } from '../brain-registry.ts';-import { OperationError } from '../ops/contract.ts';+import { OperationError, opError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { isWriteRequestId } from '../persistence/types.ts';import { digest } from '../persistence/digest.ts';import { parseSourceConfig } from '../sources-load.ts';@@ -46,7 +47,9 @@ export function companyBrainProfile(config: unknown): CompanyBrainProfile | nullif (source.company_brain === undefined) return null;const parsed = profileSchema.safeParse(source.company_brain);if (!parsed.success || typeof source.federated !== 'boolean' || source.strategy !== 'markdown' || source.slug_root_mode !== 'source-root' || source.kind != null || source.remote_url != null) {- throw new OperationError('profile_incompatible', 'The persisted company profile is invalid. Reinspect and reconnect explicitly; missing policy values are never defaulted.');+ throw opError('profile_incompatible', 'The persisted company profile is invalid. Reinspect and reconnect explicitly; missing policy values are never defaulted.',+ 'The stored company-brain profile of this source fails validation, usually because its config was edited. Do not edit it back by hand: preview the source\'s removal with gbrain sources remove and --dry-run, and only after the user\'s destructive approval remove it, then inspect and connect the checkout again.',+ { docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' });}return parsed.data;}@@ -65,7 +68,11 @@ export function assertCompanyBrainPolicy(profile: CompanyBrainProfile, receipt:if (profile.databaseId !== databaseId || profile.repository.root !== localPath || profile.receiptId !== receipt.id ||companyBrainPolicyFingerprint(profile, receipt.sourceId) !== receipt.policyFingerprint || profile.approvedRevision !== receipt.approvedRevision ||profile.schema.resolved_digest !== receipt.schemaFingerprint || profile.extractorVersion !== receipt.extractorVersion || receipt.profile !== 'company-brain') {- throw new OperationError('profile_incompatible', 'The source policy no longer matches its immutable ingestion approval. Reinspect and reconnect explicitly; v1 cannot reapprove an existing source in place.');+ throw opError('profile_incompatible', 'The source policy no longer matches its immutable ingestion approval. Reinspect and reconnect explicitly; v1 cannot reapprove an existing source in place.',+ `Source ${receipt.sourceId} no longer matches receipt ${receipt.id}'s approval. Preview its removal (read-only); only after the user's destructive approval remove it with --confirm-destructive, then inspect and connect the checkout again, or use a separate checkout and destination.`,+ { docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify',+ fix: readFix(`Previews what removing source ${receipt.sourceId} from brain ${profile.brainId} would change; changes nothing.`,+ { argv: ['gbrain', 'sources', 'remove', receipt.sourceId, '--brain', profile.brainId, '--dry-run'] }) });}}diff --git a/src/core/company-brain/receipts.ts b/src/core/company-brain/receipts.tsindex c7e0c2bd22..26b1dc384e 100644--- a/src/core/company-brain/receipts.ts+++ b/src/core/company-brain/receipts.ts@@ -1,7 +1,9 @@import type { BrainEngine } from '../engine.ts';import { isValidSourceId } from '../source-id.ts';import { isWriteRequestId } from '../persistence/types.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, type OpErrorOpts } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';+import type { RegistryCode } from '../error-registry.ts';export type SourceIngestionPhase = 'ADMITTED' | 'CONTENT' | 'GRAPH' | 'VERIFY' | 'COMPLETE';export type SourceIngestionDiagnostic = 'interrupted' | 'content_incomplete' | 'graph_incomplete' | 'verification_failed' | 'pending_writes' | 'source_changed' | 'checkpoint_missing' | 'operation_failed';@@ -79,27 +81,32 @@ type ReceiptRow = Omit<SourceIngestionReceipt, 'createdAt' | 'updatedAt' | 'compcreatedAt: string | Date; updatedAt: string | Date; completedAt: string | Date | null; discardedAt: string | Date | null;};-function fail(code: string, message: string): never { throw new OperationError(code, message); }+function fail(code: RegistryCode, message: string, suggestion: string, opts: OpErrorOpts = {}): never { throw opError(code, message, suggestion, opts); }+const RESUME_DOCS = 'docs/guides/company-brain-ingestion.md#resume-and-verify';+const statusFix = (sourceId: string) => readFix(`Shows source ${sourceId}'s ingestion receipt and its outstanding phase, read-only.`, { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] });+const ownerFix = (sourceId: string) => readFix(`Shows which host owns source ${sourceId}'s worktree and its topology, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'] });+const resume = (sourceId: string) => `gbrain sync --source ${sourceId} --no-embed --no-pull`;+const internal = 'This is a gbrain bug in the ingestion caller, not a problem with the source; nothing was written. Report it with gbrain --version and the source status.';function iso(value: string | Date): string { return new Date(value).toISOString(); }function receipt(row: ReceiptRow): SourceIngestionReceipt {return { ...row, counts: { ...emptyCounts, ...row.counts }, createdAt: iso(row.createdAt), updatedAt: iso(row.updatedAt),completedAt: row.completedAt === null ? null : iso(row.completedAt), discardedAt: row.discardedAt === null ? null : iso(row.discardedAt) };}function validateScope(scope: SourceIngestionScope): void {- if (!isValidSourceId(scope.sourceId) || !isWriteRequestId(scope.sourceIncarnation)) fail('invalid_receipt', 'A valid source ID and incarnation are required.');+ if (!isValidSourceId(scope.sourceId) || !isWriteRequestId(scope.sourceIncarnation)) fail('invalid_receipt', 'A valid source ID and incarnation are required.', internal);}function validateId(id: string): void {- if (!isWriteRequestId(id)) fail('invalid_receipt', 'Receipt and request IDs must be UUIDs.');+ if (!isWriteRequestId(id)) fail('invalid_receipt', 'Receipt and request IDs must be UUIDs.', internal);}function validatedCounts(counts: Partial<SourceIngestionCounts>): Partial<SourceIngestionCounts> {- if (!counts || typeof counts !== 'object' || Array.isArray(counts)) fail('invalid_receipt', 'Receipt counts must be numeric counters.');+ if (!counts || typeof counts !== 'object' || Array.isArray(counts)) fail('invalid_receipt', 'Receipt counts must be numeric counters.', internal);for (const [key, value] of Object.entries(counts)) {- if (!Object.hasOwn(emptyCounts, key) || !Number.isSafeInteger(value) || value < 0) fail('invalid_receipt', 'Receipt counts must be known nonnegative safe integers.');+ if (!Object.hasOwn(emptyCounts, key) || !Number.isSafeInteger(value) || value < 0) fail('invalid_receipt', 'Receipt counts must be known nonnegative safe integers.', `Counter ${key} is unknown or not a nonnegative integer. ${internal}`);}return counts;}function validatedRequests(ids: string[]): string[] {- if (!Array.isArray(ids) || ids.length > 128) fail('invalid_receipt', 'At most 128 lifecycle request references are permitted.');+ if (!Array.isArray(ids) || ids.length > 128) fail('invalid_receipt', 'At most 128 lifecycle request references are permitted.', internal);ids.forEach(validateId);return [...new Set(ids)].sort();}@@ -110,27 +117,37 @@ function sanitizedDiagnostic(value: unknown): SourceIngestionDiagnostic {async function lockScope(tx: BrainEngine, input: SourceIngestionScope & { fence: SourceIngestionFence }): Promise<void> {validateScope(input);const [brain] = await tx.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1 FOR SHARE');- if (!input.fence || !['managed', 'unmanaged'].includes(input.fence.mode)) fail('receipt_fence_required', 'An explicit ingestion authority fence is required.');- if (brain?.enabled && input.fence.mode !== 'managed') fail('receipt_fence_required', 'Managed ingestion requires its worktree owner and topology fence.');+ if (!input.fence || !['managed', 'unmanaged'].includes(input.fence.mode)) fail('receipt_fence_required', 'An explicit ingestion authority fence is required.', internal, { fix: statusFix(input.sourceId) });+ if (brain?.enabled && input.fence.mode !== 'managed') fail('receipt_fence_required', 'Managed ingestion requires its worktree owner and topology fence.',+ `This brain uses managed persistence: run the connect or ${resume(input.sourceId)} on the host that owns source ${input.sourceId}'s worktree, so the ingestion carries its owner fence.`,+ { fix: ownerFix(input.sourceId), docs: RESUME_DOCS });if (input.fence.mode === 'managed') {const f = input.fence;if (!isWriteRequestId(f.worktreeId) || !isWriteRequestId(f.ownerHostId) || !/^[0-9]+$/.test(String(f.ownerEpoch)) || !/^[0-9]+$/.test(String(f.topologyGeneration))) {- fail('invalid_receipt', 'Invalid managed owner or topology fence.');+ fail('invalid_receipt', 'Invalid managed owner or topology fence.', internal, { fix: ownerFix(input.sourceId) });}const [owner] = await tx.executeRaw(`SELECT id FROM persistence_worktrees WHERE id=$1::uuid AND owner_host_id=$2::uuidAND owner_epoch=$3::bigint AND topology_generation=$4::bigint AND state='active' FOR SHARE`,[f.worktreeId, f.ownerHostId, String(f.ownerEpoch), String(f.topologyGeneration)]);- if (!owner) fail('receipt_fence_changed', 'The managed owner or topology changed.');+ if (!owner) fail('receipt_fence_changed', 'The managed owner or topology changed.',+ `Source ${input.sourceId}'s worktree owner or topology changed (a claim, transfer or activation) while the ingestion ran. Check the owner, then resume with ${resume(input.sourceId)} on that host.`,+ { fix: ownerFix(input.sourceId), docs: RESUME_DOCS });}const [source] = await tx.executeRaw('SELECT id FROM sources WHERE id=$1 AND incarnation=$2::uuid AND NOT archived FOR SHARE', [input.sourceId, input.sourceIncarnation]);- if (!source) fail('source_changed', 'The source is missing, archived, or has a different incarnation.');+ if (!source) fail('source_changed', 'The source is missing, archived, or has a different incarnation.',+ `Source ${input.sourceId} was removed, archived or recreated after this ingestion started. A recreated source needs a new inspect and connect; restore an archived one first with the user's approval.`,+ { fix: readFix('Lists the active source ids and incarnations, read-only.', { argv: ['gbrain', 'sources', 'list', '--json'] }), docs: RESUME_DOCS });const [binding] = await tx.executeRaw<{ worktree_id: string; source_incarnation: string; topology_generation: string | number }>('SELECT worktree_id, source_incarnation, topology_generation FROM persistence_source_bindings WHERE source_id=$1 FOR SHARE', [input.sourceId]);if (input.fence.mode === 'unmanaged') {- if (binding) fail('receipt_fence_required', 'A bound source requires its managed owner and topology fence.');+ if (binding) fail('receipt_fence_required', 'A bound source requires its managed owner and topology fence.',+ `Source ${input.sourceId} is bound to a managed worktree. Run the ingestion through its owner: ${resume(input.sourceId)} on the host that owns it.`,+ { fix: ownerFix(input.sourceId), docs: RESUME_DOCS });} else if (!binding || binding.worktree_id !== input.fence.worktreeId || binding.source_incarnation !== input.sourceIncarnation|| String(binding.topology_generation) !== String(input.fence.topologyGeneration)) {- fail('receipt_fence_changed', 'The managed source binding changed.');+ fail('receipt_fence_changed', 'The managed source binding changed.',+ `Source ${input.sourceId}'s worktree binding changed while the ingestion ran. Check the owner, then resume with ${resume(input.sourceId)} on that host.`,+ { fix: ownerFix(input.sourceId), docs: RESUME_DOCS });}}@@ -156,7 +173,7 @@ export async function beginSourceIngestionReceipt(db: BrainEngine, input: BeginSvalidateId(input.id);if (!/^([a-f0-9]{40}|[a-f0-9]{64})$/.test(input.approvedRevision) || !/^[a-f0-9]{64}$/.test(input.schemaFingerprint) || !/^[a-f0-9]{64}$/.test(input.policyFingerprint)|| !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(input.profile) || !/^[a-zA-Z0-9][a-zA-Z0-9._+:-]{0,127}$/.test(input.extractorVersion)) {- fail('invalid_receipt', 'Receipts require a full approved revision, resolved-schema SHA-256, profile ID, and extractor version.');+ fail('invalid_receipt', 'Receipts require a full approved revision, resolved-schema SHA-256, profile ID, and extractor version.', internal, { fix: statusFix(input.sourceId) });}const requests = validatedRequests(input.lifecycleRequestIds ?? []);return db.transaction(async tx => {@@ -169,7 +186,9 @@ export async function beginSourceIngestionReceipt(db: BrainEngine, input: BeginSconst prior = await getSourceIngestionReceipt(tx, { ...input, receiptId: input.id });if (!prior || prior.approvedRevision !== input.approvedRevision || prior.profile !== input.profile || prior.schemaFingerprint !== input.schemaFingerprint|| prior.extractorVersion !== input.extractorVersion || prior.policyFingerprint !== input.policyFingerprint || requests.some(id => !prior.lifecycleRequestIds.includes(id))) {- fail('receipt_identity_mismatch', 'The receipt ID is already bound to different approved ingestion metadata.');+ fail('receipt_identity_mismatch', 'The receipt ID is already bound to different approved ingestion metadata.',+ `Receipt ${input.id} records a different approval for source ${input.sourceId}. Resume it with its original plan and --request-id, or inspect the checkout again and connect with a new request.`,+ { fix: statusFix(input.sourceId), docs: 'docs/guides/company-brain-ingestion.md#agent-and-ci-use' });}return prior;});@@ -177,12 +196,14 @@ export async function beginSourceIngestionReceipt(db: BrainEngine, input: BeginSasync function mutate(db: BrainEngine, input: SourceIngestionMutation, change: (prior: SourceIngestionReceipt) => SourceIngestionReceipt): Promise<SourceIngestionReceipt> {validateId(input.receiptId);- if (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 1 || !phases.includes(input.expectedPhase)) fail('invalid_receipt', 'An expected receipt revision and phase are required.');+ if (!Number.isSafeInteger(input.expectedRevision) || input.expectedRevision < 1 || !phases.includes(input.expectedPhase)) fail('invalid_receipt', 'An expected receipt revision and phase are required.', internal, { fix: statusFix(input.sourceId) });return db.transaction(async tx => {await lockScope(tx, input);const [row] = await tx.executeRaw<ReceiptRow>(`SELECT ${columns} FROM source_ingestion_receiptsWHERE id=$1::uuid AND source_id=$2 AND source_incarnation=$3::uuid FOR UPDATE`, [input.receiptId, input.sourceId, input.sourceIncarnation]);- if (!row || row.revision !== input.expectedRevision || row.phase !== input.expectedPhase || row.outcome !== 'incomplete') fail('receipt_conflict', 'The receipt revision, phase, or outcome changed. Reload before retrying.');+ if (!row || row.revision !== input.expectedRevision || row.phase !== input.expectedPhase || row.outcome !== 'incomplete') fail('receipt_conflict', 'The receipt revision, phase, or outcome changed. Reload before retrying.',+ `Another run advanced receipt ${input.receiptId} first, or it is no longer incomplete. Read its current state; an incomplete receipt resumes with ${resume(input.sourceId)}.`,+ { fix: statusFix(input.sourceId), docs: RESUME_DOCS });const next = change(receipt(row));const [updated] = await tx.executeRaw<ReceiptRow>(`UPDATE source_ingestion_receipts SET revision=revision+1, phase=$5, outcome=$6,counts=$7::text::jsonb, lifecycle_request_ids=$8::uuid[], checkpoint_refs=$9::text::jsonb, diagnostic=$10, updated_at=now(),@@ -190,7 +211,9 @@ async function mutate(db: BrainEngine, input: SourceIngestionMutation, change: (WHERE id=$1::uuid AND source_id=$2 AND source_incarnation=$3::uuid AND revision=$4 AND phase=$11 AND outcome='incomplete' RETURNING ${columns}`,[input.receiptId, input.sourceId, input.sourceIncarnation, input.expectedRevision, next.phase, next.outcome, JSON.stringify(next.counts),next.lifecycleRequestIds, JSON.stringify(next.checkpointRefs), next.diagnostic, input.expectedPhase]);- if (!updated) fail('receipt_conflict', 'The receipt changed before the update committed.');+ if (!updated) fail('receipt_conflict', 'The receipt changed before the update committed.',+ `Another run changed receipt ${input.receiptId} while this update committed. Read its current state; an incomplete receipt resumes with ${resume(input.sourceId)}.`,+ { fix: statusFix(input.sourceId), docs: RESUME_DOCS });return receipt(updated);});}@@ -203,23 +226,25 @@ export async function transitionSourceIngestionReceipt(db: BrainEngine, input: Sconst counts = validatedCounts(input.counts ?? {});return mutate(db, input, prior => {const delta = phases.indexOf(input.phase) - phases.indexOf(prior.phase);- if (!phases.includes(input.phase) || (input.phase as SourceIngestionPhase) === 'COMPLETE' || delta < 0 || delta > 1) fail('invalid_receipt_transition', 'Advance at most one ingestion phase, or update the current phase.');+ if (!phases.includes(input.phase) || (input.phase as SourceIngestionPhase) === 'COMPLETE' || delta < 0 || delta > 1) fail('invalid_receipt_transition', 'Advance at most one ingestion phase, or update the current phase.',+ `Receipt ${input.receiptId} is at ${prior.phase}; moving to ${input.phase} skips or reverses a phase. ${internal}`, { fix: statusFix(input.sourceId) });return { ...prior, phase: input.phase, counts: { ...prior.counts, ...counts }, diagnostic: null,lifecycleRequestIds: validatedRequests([...prior.lifecycleRequestIds, ...(input.lifecycleRequestIds ?? [])]) };});}export async function linkSourceIngestionCheckpoints(db: BrainEngine, input: SourceIngestionMutation & { checkpoints: SourceIngestionCheckpoint[] }): Promise<SourceIngestionReceipt> {- if (!Array.isArray(input.checkpoints) || input.checkpoints.length > 32) fail('invalid_receipt', 'At most 32 checkpoint references are permitted.');+ if (!Array.isArray(input.checkpoints) || input.checkpoints.length > 32) fail('invalid_receipt', 'At most 32 checkpoint references are permitted.', internal, { fix: statusFix(input.sourceId) });const checkpoints = input.checkpoints.map(ref => {if (!ref || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(ref.op) || !/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/.test(ref.fingerprint)- || !['content', 'manifest', 'managed_cursor', 'graph', 'verify'].includes(ref.kind)) fail('invalid_receipt', 'Checkpoint references must contain only bounded operation identities.');+ || !['content', 'manifest', 'managed_cursor', 'graph', 'verify'].includes(ref.kind)) fail('invalid_receipt', 'Checkpoint references must contain only bounded operation identities.', internal, { fix: statusFix(input.sourceId) });return { op: ref.op, fingerprint: ref.fingerprint, kind: ref.kind };});return mutate(db, input, prior => {const refs = new Map(prior.checkpointRefs.map(ref => [JSON.stringify([ref.op, ref.fingerprint]), ref]));for (const ref of checkpoints) refs.set(JSON.stringify([ref.op, ref.fingerprint]), ref);- if (refs.size > 32) fail('invalid_receipt', 'At most 32 checkpoint references are permitted.');+ if (refs.size > 32) fail('invalid_receipt', 'At most 32 checkpoint references are permitted.',+ `Receipt ${input.receiptId} would hold more than 32 checkpoints. ${internal}`, { fix: statusFix(input.sourceId) });return { ...prior, checkpointRefs: [...refs.values()] };});}@@ -233,7 +258,9 @@ export async function recordSourceIngestionOutcome(db: BrainEngine, input: Sourcconst next = { ...prior, counts: { ...prior.counts, ...counts } };if (input.outcome === 'incomplete') return { ...next, diagnostic: sanitizedDiagnostic(input.diagnostic) };if (input.outcome !== 'complete' || prior.phase !== 'VERIFY' || input.contentCommitted !== true || input.graphCommitted !== true || input.verificationPassed !== true- || next.counts.failedFiles > 0 || next.counts.pendingWrites > 0 || next.counts.verificationFailures > 0) fail('invalid_receipt_transition', 'Completion requires verified content and graph commits with no failed or pending writes.');+ || next.counts.failedFiles > 0 || next.counts.pendingWrites > 0 || next.counts.verificationFailures > 0) fail('invalid_receipt_transition', 'Completion requires verified content and graph commits with no failed or pending writes.',+ `Source ${input.sourceId} still has ${next.counts.failedFiles} failed file(s), ${next.counts.pendingWrites} pending write(s) and ${next.counts.verificationFailures} verification failure(s). Resume with ${resume(input.sourceId)}, which retries graph and verification.`,+ { fix: statusFix(input.sourceId), docs: RESUME_DOCS });return { ...next, phase: 'COMPLETE', outcome: 'complete', diagnostic: null };});}diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 9d0ec6c1f6..dda036e545 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -161,6 +161,8 @@ export const CODES = {invalid_grant_revoked: { class: 'caller', summary: "Google connect credential error: invalid grant revoked.", docs: 'docs/guides/google-connect.md#troubleshooting' },invalid_grant_testing_expiry: { class: 'caller', summary: "Google connect credential error: invalid grant testing expiry.", docs: 'docs/guides/google-connect.md#troubleshooting' },invalid_params: { class: 'caller', summary: "A parameter is missing, has the wrong type, or has an invalid value.", exit: 2 },+ invalid_receipt: { class: 'server', summary: "A company-source ingestion receipt input failed validation inside gbrain; nothing was written.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },+ invalid_receipt_transition: { class: 'caller', summary: "An ingestion receipt cannot skip a phase or complete while files failed, writes are pending or verification failed.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },invalid_request: { class: 'caller', summary: "submit_agent over the local CLI: use `gbrain agent run` instead." },invalid_source: { class: 'caller', summary: "The source argument or source state is invalid for this operation." },invalid_source_pin: { class: 'caller', summary: "The .gbrain-source pin names an invalid source id." },@@ -215,6 +217,10 @@ export const CODES = {publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },queue_capacity: { class: 'retryable', summary: "The bounded queue is full; existing requests keep their place." },rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },+ receipt_conflict: { class: 'retryable', summary: "The ingestion receipt changed since it was read.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },+ receipt_fence_changed: { class: 'caller', summary: "The managed owner, topology or source binding changed while the ingestion ran.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },+ receipt_fence_required: { class: 'host_only', summary: "Ingestion into a managed or bound source needs the worktree owner's fence.", docs: 'docs/guides/company-brain-ingestion.md#resume-and-verify' },+ receipt_identity_mismatch: { class: 'caller', summary: "The receipt ID is already bound to different approved ingestion metadata.", docs: 'docs/guides/company-brain-ingestion.md#agent-and-ci-use' },recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes." },redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },refresh_dirty: { class: 'caller', summary: "The worktree has uncommitted changes." },diff --git a/test/company-brain-policy.test.ts b/test/company-brain-policy.test.tsindex 9981cdffa3..f47a8aaabe 100644--- a/test/company-brain-policy.test.ts+++ b/test/company-brain-policy.test.ts@@ -11,7 +11,9 @@ import { withEnv } from './helpers/with-env.ts';import { inspectCompanyBrain } from '../src/core/company-brain/inspection.ts';import { admitCompanyBrain, previewCompanyBrain } from '../src/core/company-brain/admission.ts';import { connectCompanyBrain, resumeCompanyBrain } from '../src/core/company-brain/runtime.ts';-import { companyBrainProfile, companyBrainPolicyFingerprint } from '../src/core/company-brain/policy.ts';+import { assertCompanyBrainPolicy, companyBrainProfile, companyBrainPolicyFingerprint, type CompanyBrainProfile } from '../src/core/company-brain/policy.ts';+import type { SourceIngestionReceipt } from '../src/core/company-brain/receipts.ts';+import { caught, envelopeFor } from './helpers/agent-envelope.ts';import { performSync } from '../src/commands/sync.ts';import { runSources } from '../src/commands/sources.ts';import { submitEmbedBackfill } from '../src/core/embed-backfill-submit.ts';@@ -179,3 +181,12 @@ for (const managed of [false, true]) describe(`immutable company approval (${man}}), 120_000);});++test('a policy that drifted from its approval previews the removal and never edits the profile', async () => {+ const profile = { brainId: 'company-example', databaseId: randomUUID() } as unknown as CompanyBrainProfile;+ const receipt = { id: randomUUID(), sourceId: 'wiki' } as unknown as SourceIngestionReceipt;+ const env = envelopeFor(await caught(() => assertCompanyBrainPolicy(profile, receipt, randomUUID(), '/checkout')));+ expect(env).toMatchObject({ code: 'profile_incompatible', docs: expect.stringContaining('company-brain-ingestion.md#resume-and-verify'),+ fix: { argv: ['gbrain', 'sources', 'remove', 'wiki', '--brain', 'company-example', '--dry-run'], next: 'run' } });+ expect(() => companyBrainProfile({ company_brain: { version: 2 } })).toThrow(expect.objectContaining({ code: 'profile_incompatible', suggestion: expect.stringContaining('Do not edit it back by hand') }));+});diff --git a/test/helpers/company-brain-receipts.ts b/test/helpers/company-brain-receipts.tsindex beed3633c5..cfb46dfa77 100644--- a/test/helpers/company-brain-receipts.ts+++ b/test/helpers/company-brain-receipts.ts@@ -11,6 +11,7 @@ import {import { SOURCE_INGESTION_RECEIPTS_SCHEMA_SQL } from '../../src/core/company-brain/receipt-schema.ts';import { appendCompleted, clearOpCheckpoint, loadOpCheckpoint, purgeStaleCheckpoints } from '../../src/core/op-checkpoint.ts';import { LINK_EXTRACTOR_VERSION_TS } from '../../src/core/link-extraction.ts';+import { caught, envelopeFor, expectFunnelSuggestions } from './agent-envelope.ts';export function sourceIngestionReceiptTests(label: string, getEngine: () => BrainEngine): void {describe(label, () => {@@ -288,5 +289,22 @@ export function sourceIngestionReceiptTests(label: string, getEngine: () => Braiawait engine.executeRaw('UPDATE persistence_source_bindings SET source_incarnation=$2::uuid WHERE source_id=$1', [input.sourceId, input.sourceIncarnation]);expect((await transitionSourceIngestionReceipt(engine, { ...mutation(r, fence), phase: 'CONTENT' })).phase).toBe('CONTENT');});++ test('receipt refusals name their own next step: the status read, the resume command, the owner check', async () => {+ expectFunnelSuggestions('src/core/company-brain/receipts.ts', 'fail', 20);+ const r = await beginSourceIngestionReceipt(engine, input);+ const stale = envelopeFor(await caught(() => transitionSourceIngestionReceipt(engine, { ...mutation(r), expectedRevision: r.revision + 1, phase: 'CONTENT' })));+ expect(stale).toMatchObject({ code: 'receipt_conflict', fix: { argv: ['gbrain', 'sources', 'status', input.sourceId, '--json'], next: 'run' } });+ expect(stale.suggestion).toContain(`gbrain sync --source ${input.sourceId} --no-embed --no-pull`);+ let advanced = r;+ for (const phase of ['CONTENT', 'GRAPH', 'VERIFY'] as const) advanced = await transitionSourceIngestionReceipt(engine, { ...mutation(advanced), phase });+ const failed = envelopeFor(await caught(() => recordSourceIngestionOutcome(engine, { ...mutation(advanced), outcome: 'complete', contentCommitted: true,+ graphCommitted: true, verificationPassed: true, counts: { failedFiles: 2 } })));+ expect(failed).toMatchObject({ code: 'invalid_receipt_transition', fix: { argv: ['gbrain', 'sources', 'status', input.sourceId, '--json'] } });+ expect(failed.suggestion).toContain('2 failed file(s)');+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');+ const fence = envelopeFor(await caught(() => beginSourceIngestionReceipt(engine, { ...input, id: randomUUID() })));+ expect(fence).toMatchObject({ code: 'receipt_fence_required', fix: { argv: ['gbrain', 'sources', 'writer', 'status', input.sourceId, '--json'] } });+ });});}