Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(errors): B10 backfill company-brain revision/admission/runtime, company-brain-connect, brain-resident-locate, google-attachments

garrytand5083c6f5440
diff --git a/src/commands/company-brain-connect.ts b/src/commands/company-brain-connect.ts
index 6a6232e718..3c13e472e5 100644
--- a/src/commands/company-brain-connect.ts
+++ b/src/commands/company-brain-connect.ts
@@ -2,12 +2,15 @@ import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs
import { randomUUID } from 'node:crypto';
import { isInteractive, readLine } from '../core/interaction.ts';
import { CONFIRMATION_REQUIRED_EXIT_CODE } from '../core/exit-codes.ts';
+import type { Action } from '../core/agent-output.ts';
import type { BrainEngine } from '../core/engine.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { isThinClient, loadConfig } from '../core/config.ts';
import { loadMounts } from '../core/brain-registry.ts';
import { isValidSourceId } from '../core/source-id.ts';
-import { OperationError } from '../core/ops/contract.ts';
+import type { RegistryCode } from '../core/error-registry.ts';
+import { opError, OperationError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
import { inspectCompanyBrain, validateCompanyBrainPlan } from '../core/company-brain/inspection.ts';
import { COMPANY_BRAIN_MAX_METADATA_BYTES, COMPANY_BRAIN_PROFILE, type CompanyBrainPlan } from '../core/company-brain/types.ts';
import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
@@ -42,6 +45,12 @@ export interface CompanyBrainConnectArgs {
requestId: string;
}
+const CONNECT_OPTIONS = '--brain, --source, --profile company-brain, --include, --exclude, --plan, --request-id, --yes, and --json';
+
+function mountsFix(): Action {
+ return readFix('Lists the mounted brains and their ids.', { argv: ['gbrain', 'mounts', 'list', '--json'] });
+}
+
export function parseCompanyBrainConnectArgs(args: string[], explicitBrain: string | null): CompanyBrainConnectArgs {
const options: CompanyBrainConnectArgs = { brainId: explicitBrain ?? '', sourceId: '', include: [], exclude: [], json: false, yes: false, requestId: randomUUID() };
const seen = new Set<string>();
@@ -50,18 +59,24 @@ export function parseCompanyBrainConnectArgs(args: string[], explicitBrain: stri
if (arg === '--json') { options.json = true; continue; }
if (arg === '--yes') { options.yes = true; continue; }
if (!arg.startsWith('-')) {
- if (options.path) throw new OperationError('invalid_params', 'Connect accepts exactly one repository path.');
+ if (options.path) throw opError('invalid_params', 'Connect accepts exactly one repository path.',
+ 'Pass a single repository path (quote a path that contains spaces), or a saved plan with --plan instead of a path.');
options.path = arg;
continue;
}
const equal = arg.indexOf('=');
const flag = equal < 0 ? arg : arg.slice(0, equal);
if (!['--source', '--profile', '--include', '--exclude', '--plan', '--request-id'].includes(flag)) {
- throw new OperationError('invalid_params', `Unknown connect option ${JSON.stringify(flag)}.`);
+ throw opError('invalid_params', `Unknown connect option ${JSON.stringify(flag)}.`,
+ `Connect accepts ${CONNECT_OPTIONS}; gbrain sources connect --help lists them.`);
}
const value = equal < 0 ? args[++i] : arg.slice(equal + 1);
- if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${flag} requires a value.`);
- if (seen.has(flag) && flag !== '--include' && flag !== '--exclude') throw new OperationError('invalid_params', `Pass ${flag} only once.`);
+ if (!value || value.startsWith('--')) {
+ throw opError('invalid_params', `${flag} requires a value.`, `Follow ${flag} with its value, or write ${flag}=value; a value cannot start with --.`);
+ }
+ if (seen.has(flag) && flag !== '--include' && flag !== '--exclude') {
+ throw opError('invalid_params', `Pass ${flag} only once.`, `Remove the repeated ${flag}; only --include and --exclude may repeat.`);
+ }
seen.add(flag);
if (flag === '--source') options.sourceId = value;
else if (flag === '--plan') options.planFile = value;
@@ -69,16 +84,29 @@ export function parseCompanyBrainConnectArgs(args: string[], explicitBrain: stri
else if (flag === '--include') options.include.push(value);
else if (flag === '--exclude') options.exclude.push(value);
else {
- if (value !== COMPANY_BRAIN_PROFILE) throw new OperationError('invalid_params', 'Only --profile company-brain is supported.');
+ if (value !== COMPANY_BRAIN_PROFILE) {
+ throw opError('invalid_params', 'Only --profile company-brain is supported.', 'Pass --profile company-brain or omit --profile; it is the only supported profile.');
+ }
options.profile = COMPANY_BRAIN_PROFILE;
}
}
if (!/^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/.test(options.brainId) || !isValidSourceId(options.sourceId)) {
- throw new OperationError('invalid_params', 'Connect requires explicit valid --brain and --source destinations. Ambient routing is not used.');
+ throw opError('invalid_params', 'Connect requires explicit valid --brain and --source destinations. Ambient routing is not used.',
+ 'Pass --brain with a mounted brain id (lowercase letters, digits, hyphens) and --source with a new lowercase source id, both explicitly.',
+ { fix: mountsFix() });
+ }
+ if (Boolean(options.path) === Boolean(options.planFile)) {
+ throw opError('invalid_params', 'Provide one repository path or --plan file, not both.',
+ 'Pass exactly one of: the repository path, or --plan with the file gbrain sources inspect --json --out wrote.');
+ }
+ if (options.planFile && (options.include.length || options.exclude.length)) {
+ throw opError('invalid_params', 'A saved plan fixes its selection. Inspect again to change include/exclude rules.',
+ `Drop --include/--exclude to connect ${options.planFile} as reviewed, or run gbrain sources inspect again with the new rules and --out to write a new plan.`);
+ }
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(options.requestId)) {
+ throw opError('invalid_params', '--request-id must be a UUID.',
+ 'Pass the request ID that the earlier connect printed as "Request:" (a UUID) to resume it, or omit --request-id to start a new request.');
}
- if (Boolean(options.path) === Boolean(options.planFile)) throw new OperationError('invalid_params', 'Provide one repository path or --plan file, not both.');
- if (options.planFile && (options.include.length || options.exclude.length)) throw new OperationError('invalid_params', 'A saved plan fixes its selection. Inspect again to change include/exclude rules.');
- if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(options.requestId)) throw new OperationError('invalid_params', '--request-id must be a UUID.');
return options;
}
@@ -94,15 +122,23 @@ async function connectionPlan(options: CompanyBrainConnectArgs): Promise<Company
if (Buffer.byteLength(text) > COMPANY_BRAIN_MAX_METADATA_BYTES) throw new Error();
saved = JSON.parse(text);
} catch {
- throw new OperationError('invalid_params', 'The plan must be a readable, bounded regular JSON file. Inspect the repository again.');
+ throw opError('invalid_params', 'The plan must be a readable, bounded regular JSON file. Inspect the repository again.',
+ `${options.planFile} must be a regular JSON file (not a symlink) under ${COMPANY_BRAIN_MAX_METADATA_BYTES} bytes, as written by gbrain sources inspect --profile company-brain --json --out. Inspect the repository again to write a fresh plan file.`);
} finally {
if (fd !== undefined) closeSync(fd);
}
if (saved && typeof saved === 'object' && 'plan' in saved) saved = (saved as { plan: unknown }).plan;
const path = (saved as Partial<CompanyBrainPlan> | null)?.revision?.root;
- if (typeof path !== 'string') throw new OperationError('plan_stale', 'The saved plan has no valid repository identity. Inspect again.');
+ if (typeof path !== 'string') {
+ throw opError('plan_stale', 'The saved plan has no valid repository identity. Inspect again.',
+ `${options.planFile} has no repository identity. Inspect the repository again with gbrain sources inspect --profile company-brain --json --out and connect the new plan file.`);
+ }
const validated = await validateCompanyBrainPlan(saved, { path, profile: options.profile, mode: 'apply' });
- if (!validated.valid || !validated.plan) throw new OperationError(validated.code, 'The saved plan is stale or not ready. Inspect the repository again.');
+ if (!validated.valid || !validated.plan) {
+ throw opError(validated.code as RegistryCode, 'The saved plan is stale or not ready. Inspect the repository again.',
+ `The checkout at ${path} no longer matches ${options.planFile}, or the plan has blocking findings. Inspect it again, review the new plan, and connect that one.`,
+ { fix: readFix('A fresh read-only inspection shows what the checkout holds now.', { argv: ['gbrain', 'sources', 'inspect', path, '--profile', 'company-brain', '--json'] }) });
+ }
return validated.plan;
}
@@ -115,8 +151,15 @@ export async function runCompanyBrainConnect(args: string[], connectEngine: () =
try {
options = parseCompanyBrainConnectArgs(args, getCliOptions().brain);
const config = persistenceConfigForBrain(loadConfig(), options.brainId, options.brainId === 'host' ? [] : loadMounts());
- if (!config) throw new OperationError('destination_not_ready', 'The destination must already be initialized. Set up a separate company brain first.');
- if (isThinClient(config)) throw new OperationError('permission_denied', 'Connect runs on the company brain host; an ordinary remote token is not administration authority.');
+ if (!config) {
+ throw opError('destination_not_ready', 'The destination must already be initialized. Set up a separate company brain first.',
+ `Brain ${options.brainId} is not initialized on this machine. Check the mounted brains; creating a company brain is a separate step the user approves, and connect never initializes one.`,
+ { fix: mountsFix() });
+ }
+ if (isThinClient(config)) {
+ throw opError('permission_denied', 'Connect runs on the company brain host; an ordinary remote token is not administration authority.',
+ `Brain ${options.brainId} is reached through a remote token here. Ask the user to run gbrain sources inspect and gbrain sources connect on the machine that hosts it, against a checkout on that machine.`);
+ }
const plan = await connectionPlan(options);
if (!plan.ready || !plan.revision) {
if (json) await emit({ schema_version: 1, status: 'blocked', code: 'source_not_ready', plan });
@@ -152,7 +195,11 @@ export async function runCompanyBrainConnect(args: string[], connectEngine: () =
if (delegated.handled) {
const connected = await maybeDelegateLocalAdministration('company_brain_connect', { ...params, request_id: options.requestId }, config,
{ timeoutMs: getCliOptions().timeoutMs ?? undefined });
- if (!connected.handled) throw new OperationError('owner_unavailable', 'The resident owner changed after preview. Retry with the same request ID.');
+ if (!connected.handled) {
+ throw opError('owner_unavailable', 'The resident owner changed after preview. Retry with the same request ID.',
+ `Check source ${options.sourceId}'s status first; then rerun this connect with --request-id ${options.requestId} and the same destination and plan (same request_id), which replays the approved request instead of creating another source.`,
+ { fix: readFix(`Shows whether request ${options.requestId} already registered source ${options.sourceId}.`, { argv: ['gbrain', 'sources', 'status', '--brain', options.brainId, '--json'] }) });
+ }
result = connected.result as Record<string, unknown>;
} else {
const { connectCompanyBrain } = await import('../core/company-brain/runtime.ts');
diff --git a/src/commands/google-attachments.ts b/src/commands/google-attachments.ts
index 105aa95842..32ff3f6a05 100644
--- a/src/commands/google-attachments.ts
+++ b/src/commands/google-attachments.ts
@@ -6,7 +6,8 @@ import { resolveBrainId } from '../core/brain-resolver.ts';
import { loadMounts } from '../core/brain-registry.ts';
import { persistenceConfigForBrain } from '../core/persistence/local-client.ts';
import { readLocalWriter, withVerifiedLocalRegistration } from '../core/persistence/identity.ts';
-import { OperationError } from '../core/ops/contract.ts';
+import { opError, OperationError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
import { isValidSourceId } from '../core/source-id.ts';
import { parseGoogleSourceConfig, runGoogleAttachmentBackfill } from '../core/google/google-source.ts';
import type { FetchImpl } from '../core/google/google-clients.ts';
@@ -30,27 +31,51 @@ Run on the canonical host with the selected PGLite brain idle; remote delegation
See docs/guides/google-connect.md#attachment-receipts-and-historical-repair`;
export function parseGoogleAttachmentsArgs(args: string[]) {
- if (args[0] !== 'backfill') throw new OperationError('invalid_params', 'Select the attachment backfill subcommand.');
+ if (args[0] !== 'backfill') {
+ throw opError('invalid_params', 'Select the attachment backfill subcommand.',
+ 'Use gbrain google attachments backfill with --source naming the Google source; it previews without --yes.');
+ }
const flags = new Map<string, string | true>();
for (let i = 1; i < args.length; i++) {
const [flag, inline] = args[i].split(/=(.*)/s);
- if (!['--source', '--brain', '--limit', '--yes', '--json', '--retry-failed'].includes(flag) || flags.has(flag)) throw new OperationError('invalid_params', 'Unknown or duplicate attachment repair option.');
+ if (!['--source', '--brain', '--limit', '--yes', '--json', '--retry-failed'].includes(flag) || flags.has(flag)) {
+ throw opError('invalid_params', 'Unknown or duplicate attachment repair option.',
+ 'Backfill accepts --source, --brain, --limit, --yes, --json, and --retry-failed, each at most once.');
+ }
if (['--yes', '--json', '--retry-failed'].includes(flag)) {
- if (inline !== undefined) throw new OperationError('invalid_params', 'Boolean attachment repair options do not accept values.');
+ if (inline !== undefined) {
+ throw opError('invalid_params', 'Boolean attachment repair options do not accept values.', 'Write --yes, --json, and --retry-failed without =value.');
+ }
flags.set(flag, true);
} else {
const value = inline ?? args[++i];
- if (!value || value.startsWith('-') || value.includes('\0')) throw new OperationError('invalid_params', 'An attachment repair option needs a value.');
+ if (!value || value.startsWith('-') || value.includes('\0')) {
+ throw opError('invalid_params', 'An attachment repair option needs a value.',
+ `Follow ${flag} with its value, or write ${flag}=value; a value cannot start with '-'.`);
+ }
flags.set(flag, value);
}
}
const sourceId = flags.get('--source');
- if (!isValidSourceId(sourceId)) throw new OperationError('invalid_params', 'Select one explicit valid Google source ID.');
+ if (!isValidSourceId(sourceId)) {
+ throw opError('invalid_params', 'Select one explicit valid Google source ID.',
+ 'Pass --source with the id of the Google source to repair; source list shows the ids.',
+ { fix: readFix('Lists registered sources and their ids.', { argv: ['gbrain', 'sources', 'list', '--json'] }) });
+ }
const limit = flags.has('--limit') ? Number(flags.get('--limit')) : 25;
- if (!Number.isSafeInteger(limit) || limit < 1 || limit > 25) throw new OperationError('invalid_params', 'Attachment repair limit must be 1-25.');
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 25) {
+ throw opError('invalid_params', 'Attachment repair limit must be 1-25.', 'Pass --limit as a whole number from 1 to 25, or omit it to use 25.');
+ }
const brain = flags.get('--brain') as string | undefined;
- if (brain && !isValidSourceId(brain)) throw new OperationError('invalid_params', 'Select a valid brain ID.');
- if (flags.has('--retry-failed') && !flags.has('--yes')) throw new OperationError('invalid_params', '--retry-failed requires --yes.');
+ if (brain && !isValidSourceId(brain)) {
+ throw opError('invalid_params', 'Select a valid brain ID.', 'Pass --brain with host or a mounted brain id (lowercase letters, digits, hyphens).',
+ { fix: readFix('Lists the mounted brains and their ids.', { argv: ['gbrain', 'mounts', 'list', '--json'] }) });
+ }
+ if (flags.has('--retry-failed') && !flags.has('--yes')) {
+ throw opError('invalid_params', '--retry-failed requires --yes.',
+ `Preview source ${sourceId} without --retry-failed first. --retry-failed applies a batch that re-attempts terminal failed receipts, so pair it with --yes only after the user approves that batch.`,
+ { fix: readFix(`Previews source ${sourceId}'s attachment repair without contacting Google or writing.`, { argv: ['gbrain', 'google', 'attachments', 'backfill', '--source', sourceId, ...(brain ? ['--brain', brain] : []), '--json'] }) });
+ }
return { sourceId, limit, brain, yes: flags.has('--yes'), json: flags.has('--json'), retryFailed: flags.has('--retry-failed') };
}
@@ -62,7 +87,13 @@ export async function runGoogleAttachments(args: string[], connected?: BrainEngi
const parsed = parseGoogleAttachmentsArgs(args);
const brain = resolveBrainId(parsed.brain ?? getCliOptions().brain);
const config = persistenceConfigForBrain(loadConfig(), brain, brain === 'host' ? [] : loadMounts());
- if (!connected && (!config || isThinClient(config))) throw new OperationError('permission_denied', 'Attachment repair requires the configured canonical host, not a remote token.');
+ if (!connected && (!config || isThinClient(config))) {
+ throw opError('permission_denied', 'Attachment repair requires the configured canonical host, not a remote token.',
+ `Brain ${brain} is not a local brain on this machine. Ask the user to run the repair on the machine that hosts it; a remote token cannot repair attachments.`,
+ { fix: { argv: ['gbrain', 'google', 'attachments', 'backfill', '--source', parsed.sourceId, '--brain', brain, '--json'], consent: [], actor: 'user', requires_exclusive: false,
+ why: 'Previews the repair on the canonical host without contacting Google or writing.',
+ user_message: `Attachment repair for source ${parsed.sourceId} has to run on the machine that hosts brain ${brain}. Please run the command shown there.` } });
+ }
if (!connected) {
const { createEngine } = await import('../core/engine-factory.ts');
owned = await createEngine(toEngineConfig(config!));
@@ -72,9 +103,17 @@ export async function runGoogleAttachments(args: string[], connected?: BrainEngi
const registration = await readLocalWriter(engine, 'cli');
const result = await withVerifiedLocalRegistration(engine, registration, async () => {
const [source] = await engine.executeRaw<{ config: Record<string, unknown>; incarnation: string; local_path: string | null; archived: boolean }>('SELECT config,incarnation,local_path,archived FROM sources WHERE id=$1', [parsed.sourceId]);
- if (!source || source.archived || source.config.kind !== 'google') throw new OperationError('invalid_params', 'Select an active Google source.');
+ if (!source || source.archived || source.config.kind !== 'google') {
+ throw opError('invalid_params', 'Select an active Google source.',
+ `Source ${parsed.sourceId} is missing, archived, or not a Google source in brain ${brain}. List the sources and pass the active Google one with --source.`,
+ { fix: readFix(`Lists brain ${brain}'s sources with their kinds.`, { argv: ['gbrain', 'sources', 'list', '--brain', brain, '--json'] }) });
+ }
const [mode] = await engine.executeRaw<{ enabled: boolean }>('SELECT enabled FROM persistence_brain WHERE singleton=1');
- if (!mode?.enabled) throw new OperationError('writer_coordinator_required', 'Attachment repair requires already-enabled managed persistence.');
+ if (!mode?.enabled) {
+ throw opError('writer_coordinator_required', 'Attachment repair requires already-enabled managed persistence.',
+ `Brain ${brain} does not run managed persistence, and this repair never enables it. Ordinary ingestion of source ${parsed.sourceId} keeps working; enabling managed persistence is a separate decision for the user.`,
+ { fix: readFix(`Shows brain ${brain}'s persistence and writer state.`, { argv: ['gbrain', 'doctor', '--brain', brain, '--json'] }) });
+ }
await managedSyncAuthority(engine, parsed.sourceId, source.incarnation, source.local_path ?? '');
const cfg = parseGoogleSourceConfig(source.config, source.local_path ?? '');
if (!parsed.yes) {
diff --git a/src/core/company-brain/admission.ts b/src/core/company-brain/admission.ts
index 84327939b9..1f3e6ceccc 100644
--- a/src/core/company-brain/admission.ts
+++ b/src/core/company-brain/admission.ts
@@ -1,7 +1,10 @@
import { randomUUID } from 'node:crypto';
import { resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import type { RegistryCode } from '../error-registry.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
import { isValidSourceId } from '../source-id.ts';
import { assertNoOverlappingPath } from '../sources-ops.ts';
import { checkApprovedSchemaForEngine } from '../schema-pack/engine-resolution.ts';
@@ -15,9 +18,46 @@ import { priorTopologyChange, recordTopologyChange } from '../persistence/topolo
import { runManagedSourceLifecycle } from '../persistence/source-lifecycle.ts';
import { validateCompanyBrainPlan } from './inspection.ts';
import { beginSourceIngestionReceipt, getSourceIngestionReceipt, linkSourceIngestionCheckpoints, type SourceIngestionFence } from './receipts.ts';
-import type { CompanyBrainPlan } from './types.ts';
+import type { CompanyBrainPlan, PlanValidationResult } from './types.ts';
import { companyBrainProfile, companyBrainPolicyFingerprint, companyBrainRepository, assertCompanyBrainPolicy, assertCompanyBrainExtractor, isCompanyBrainId } from './policy.ts';
+export function reinspectFix(path: string): Action {
+ return readFix('A fresh read-only inspection shows what the checkout holds now and produces a plan you can review and connect.',
+ { argv: ['gbrain', 'sources', 'inspect', resolve(path), '--profile', 'company-brain', '--json'] });
+}
+
+export function sourceStatusFix(brainId: string, why: string): Action {
+ return readFix(why, { argv: ['gbrain', 'sources', 'status', '--brain', brainId, '--json'] });
+}
+
+export function ownerStatusFix(sourceId: string): Action {
+ return readFix(`Shows which host owns source ${sourceId} and whether its owner is active; the company sync runs only there.`,
+ { argv: ['gbrain', 'sources', 'writer', 'status', '--source', sourceId, '--json'] });
+}
+
+function planNotReady(code: PlanValidationResult['code'], message: string, path: string): OperationError {
+ return opError(code as RegistryCode, message,
+ `Inspect ${resolve(path)} again, resolve any error findings, and connect only the new reviewed plan; a changed or stale plan is never re-approved silently.`,
+ { fix: reinspectFix(path) });
+}
+
+function requestIdError(): OperationError {
+ return opError('invalid_params', 'requestId must be a UUID.',
+ 'Pass the request ID printed as "Request:" by the earlier connect (a UUID) to resume that request, or omit it to start a new one.');
+}
+
+function brainUninitialized(message: string, brainId: string): OperationError {
+ return opError('destination_not_ready', message,
+ `Brain ${brainId} has no persistence identity yet. Check it with gbrain doctor; initializing or migrating a brain is a separate step the user approves, and connect never does it.`,
+ { fix: readFix(`Shows brain ${brainId}'s schema and migration state without changing it.`, { argv: ['gbrain', 'doctor', '--brain', brainId, '--json'] }) });
+}
+
+function sourceTaken(message: string, input: CompanyBrainDestination): OperationError {
+ return opError('source_id_taken', message,
+ `Source ${input.sourceId} already exists in brain ${input.brainId}. If it is this company source, resume it with gbrain sync --brain ${input.brainId} --source ${input.sourceId} --no-embed --no-pull (or repeat connect with its original --request-id); otherwise choose a new --source id.`,
+ { fix: sourceStatusFix(input.brainId, `Shows source ${input.sourceId}'s registration and ingestion receipt so you can tell whether it is the company source to resume.`) });
+}
+
export interface CompanyBrainDestination {
brainId: string;
sourceId: string;
@@ -31,7 +71,8 @@ export interface CompanyBrainConnectInput extends CompanyBrainDestination {
export function unwrapCompanyBrainPlan(value: unknown): CompanyBrainPlan {
if (value && typeof value === 'object' && 'plan' in value) value = (value as { plan: unknown }).plan;
if (!value || typeof value !== 'object' || Array.isArray(value) || !('plan_digest' in value)) {
- throw new OperationError('plan_stale', 'A raw inspection plan or inspection envelope with plan is required.');
+ throw opError('plan_stale', 'A raw inspection plan or inspection envelope with plan is required.',
+ 'Pass the JSON that gbrain sources inspect --profile company-brain --json writes (the raw plan, or its envelope with a plan key); inspect the repository again if the file is not one.');
}
return value as CompanyBrainPlan;
}
@@ -51,10 +92,12 @@ export interface CompanyBrainPreview {
export function assertCompanyBrainCaller(input: CompanyBrainDestination): void {
const authority = currentSubmissionAuthority();
if (input.remote !== false || currentVerifiedLocalWriter()?.remote || authority?.kind === 'remote_agent' || authority?.kind === 'remote_generic') {
- throw new OperationError('permission_denied', 'Company source administration requires an explicitly trusted local caller.');
+ throw trustedCliRequired('Company source administration requires an explicitly trusted local caller.');
}
if (!isCompanyBrainId(input.brainId) || !isValidSourceId(input.sourceId)) {
- throw new OperationError('destination_not_ready', 'An explicitly selected initialized brain and source ID are required.');
+ throw opError('destination_not_ready', 'An explicitly selected initialized brain and source ID are required.',
+ 'Name the destination explicitly: --brain takes a mounted brain id of lowercase letters, digits, and hyphens, and --source a lowercase source id; ambient routing is never used.',
+ { fix: readFix('Lists the mounted brains and their ids.', { argv: ['gbrain', 'mounts', 'list', '--json'] }) });
}
}
@@ -62,7 +105,9 @@ export async function ingestionFence(engine: BrainEngine, sourceId: string): Pro
if (!await managedPersistenceEnabled(engine)) return { mode: 'unmanaged' };
const binding = await getWorktreeBinding(engine, sourceId);
if (!binding?.owner_host_id || binding.owner_host_id !== localHostId() || binding.state !== 'active' || !binding.local_path) {
- throw new OperationError('owner_unavailable', 'The managed source must run on its active registered local owner.');
+ throw opError('owner_unavailable', 'The managed source must run on its active registered local owner.',
+ `Source ${sourceId} is managed and this host is not its active owner. Check the owner, then run the command on that host or wait until its owner is active again.`,
+ { fix: ownerStatusFix(sourceId) });
}
return { mode: 'managed', worktreeId: binding.worktree_id, ownerHostId: binding.owner_host_id,
ownerEpoch: String(binding.owner_epoch), topologyGeneration: String(binding.topology_generation) };
@@ -78,14 +123,17 @@ async function assertIngestionStorage(engine: BrainEngine): Promise<void> {
function admissionConfig(input: CompanyBrainConnectInput, requestId: string, databaseId: string) {
const plan = input.plan;
- if (!plan.revision || !plan.schema) throw new OperationError('source_not_ready', 'A committed source and approved schema are required.');
+ if (!plan.revision || !plan.schema) throw planNotReady('source_not_ready', 'A committed source and approved schema are required.', input.path);
const policy = { version: 1, profile: 'company-brain', brainId: input.brainId, databaseId, receiptId: requestId,
repository: companyBrainRepository(plan.revision), planDigest: plan.plan_digest, selection: plan.selection, limits: plan.limits,
schema: plan.schema, extractorVersion: plan.extractor_version, approvedRevision: plan.revision.commit,
committedOnly: true, noPull: true, noEmbed: true, noBackfill: true, noWriteback: true };
const config = { federated: false, strategy: 'markdown', slug_root_mode: 'source-root', company_brain: policy };
const profile = companyBrainProfile(config)!;
- if (Buffer.byteLength(JSON.stringify(config)) > 8192) throw new OperationError('request_too_large', 'The approved selection exceeds source policy capacity; narrow the selection.');
+ if (Buffer.byteLength(JSON.stringify(config)) > 8192) {
+ throw opError('request_too_large', 'The approved selection exceeds source policy capacity; narrow the selection.',
+ `The stored source policy is capped at 8192 bytes. Inspect ${resolve(input.path)} again with fewer, broader --include and --exclude globs, then connect that plan.`);
+ }
return { profile, config };
}
@@ -101,7 +149,7 @@ async function approvedReplay(engine: BrainEngine, input: CompanyBrainConnectInp
const [source] = await engine.executeRaw<{ incarnation: string; archived: boolean; local_path: string; config: unknown }>(
'SELECT incarnation,archived,local_path,config FROM sources WHERE id=$1', [input.sourceId]);
if (!source) return null;
- const collision = () => new OperationError('source_id_taken', 'This source already exists and does not match this exact admitted request. Use sync to resume it.');
+ const collision = () => sourceTaken('This source already exists and does not match this exact admitted request. Use sync to resume it.', input);
if (!input.requestId || !isWriteRequestId(input.requestId) || source.archived) throw collision();
if (!input.plan.revision || resolve(input.path) !== source.local_path || input.plan.revision.root !== source.local_path) throw collision();
const principal = await topologyPrincipal(engine);
@@ -125,15 +173,17 @@ async function approvedReplay(engine: BrainEngine, input: CompanyBrainConnectInp
export async function checkCompanyBrainDestination(engine: BrainEngine, input: CompanyBrainConnectInput, newSource = true): Promise<CompanyBrainPreview> {
assertCompanyBrainCaller(input);
await assertIngestionStorage(engine);
- if (!input.plan.ready || !input.plan.revision || !input.plan.schema) throw new OperationError('source_not_ready', 'The inspected source is not ready to connect.');
+ if (!input.plan.ready || !input.plan.revision || !input.plan.schema) throw planNotReady('source_not_ready', 'The inspected source is not ready to connect.', input.path);
const [brain] = await engine.executeRaw<{ brain_id: string; enabled: boolean }>('SELECT brain_id,enabled FROM persistence_brain WHERE singleton=1');
- if (!brain) throw new OperationError('destination_not_ready', 'Initialize the selected brain before connecting a source.');
+ if (!brain) throw brainUninitialized('Initialize the selected brain before connecting a source.', input.brainId);
if (newSource && (await engine.executeRaw('SELECT id FROM sources WHERE id=$1', [input.sourceId])).length) {
- throw new OperationError('source_id_taken', 'Connect requires a new source. Resume the existing source through sync.');
+ throw sourceTaken('Connect requires a new source. Resume the existing source through sync.', input);
}
const requirements = input.plan.audience_requirements;
if (requirements.some(value => !['internal', 'public', 'world'].includes(value))) {
- throw new OperationError('destination_not_ready', 'The source requires a narrower audience policy; no access grants will be inferred or changed.');
+ throw opError('destination_not_ready', 'The source requires a narrower audience policy; no access grants will be inferred or changed.',
+ `Some pages declare an audience narrower than internal. Exclude them by inspecting ${resolve(input.path)} again with --exclude globs, or ask the user to map them through a separately approved access design.`,
+ { fix: reinspectFix(input.path) });
}
const schema = input.plan.schema;
const checked = await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },
@@ -141,7 +191,11 @@ export async function checkCompanyBrainDestination(engine: BrainEngine, input: C
if (checked.binding) {
const [page] = await engine.executeRaw('SELECT id FROM pages LIMIT 1');
const [profile] = await engine.executeRaw("SELECT id FROM sources WHERE config->'company_brain' IS NOT NULL LIMIT 1");
- if (page || profile) throw new OperationError('destination_not_ready', 'An occupied brain must already use the exact company schema. Mixed-schema admission is not supported.');
+ if (page || profile) {
+ throw opError('destination_not_ready', 'An occupied brain must already use the exact company schema. Mixed-schema admission is not supported.',
+ `Brain ${input.brainId} already holds pages under a different schema. Connect into a dedicated company brain instead; creating one is a separate step the user approves.`,
+ { fix: sourceStatusFix(input.brainId, `Shows what brain ${input.brainId} already holds.`) });
+ }
}
const [broad] = await engine.executeRaw<{ count: string }>(
`SELECT count(*)::text AS count FROM (
@@ -158,11 +212,11 @@ export async function checkCompanyBrainDestination(engine: BrainEngine, input: C
export async function previewCompanyBrain(engine: BrainEngine, input: CompanyBrainConnectInput): Promise<CompanyBrainPreview> {
input = { ...input, plan: unwrapCompanyBrainPlan(input.plan) };
assertCompanyBrainCaller(input);
- if (input.requestId !== undefined && !isWriteRequestId(input.requestId)) throw new OperationError('invalid_params', 'requestId must be a UUID.');
+ if (input.requestId !== undefined && !isWriteRequestId(input.requestId)) throw requestIdError();
await assertIngestionStorage(engine);
const replay = await approvedReplay(engine, input);
const checked = await validateCompanyBrainPlan(input.plan, { path: input.path, mode: replay ? 'resume' : 'apply' });
- if (!checked.valid) throw new OperationError(checked.code, 'The source no longer matches its approved inspection plan.');
+ if (!checked.valid) throw planNotReady(checked.code, 'The source no longer matches its approved inspection plan.', input.path);
return { ...await checkCompanyBrainDestination(engine, input, !replay), ...(replay ? { replayed: true as const, receiptId: replay.receiptId } : {}) };
}
@@ -171,26 +225,34 @@ export async function admitCompanyBrain(engine: BrainEngine, input: CompanyBrain
assertCompanyBrainCaller(input);
await assertIngestionStorage(engine);
const requestId = input.requestId ?? randomUUID();
- if (!isWriteRequestId(requestId)) throw new OperationError('invalid_params', 'requestId must be a UUID.');
+ if (!isWriteRequestId(requestId)) throw requestIdError();
const replay = await approvedReplay(engine, { ...input, requestId });
if (replay) {
const validation = await validateCompanyBrainPlan(input.plan, { path: input.path, mode: 'resume' });
- if (!validation.valid) throw new OperationError(validation.code, 'The admitted request no longer matches its approved repository identity.');
+ if (!validation.valid) {
+ throw opError(validation.code as RegistryCode, 'The admitted request no longer matches its approved repository identity.',
+ `Request ${requestId} already admitted source ${input.sourceId}, but the checkout no longer matches its approved commit. Check the receipt; resume with gbrain sync --brain ${input.brainId} --source ${input.sourceId} --no-embed --no-pull once that commit is present again. gbrain never substitutes current HEAD.`,
+ { fix: sourceStatusFix(input.brainId, `Shows source ${input.sourceId}'s ingestion receipt and outstanding phase.`) });
+ }
return replay;
}
- if (!input.plan.revision || !input.plan.schema) throw new OperationError('source_not_ready', 'A committed source and approved schema are required.');
+ if (!input.plan.revision || !input.plan.schema) throw planNotReady('source_not_ready', 'A committed source and approved schema are required.', input.path);
const plan = input.plan;
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
- if (!brain) throw new OperationError('destination_not_ready', 'Initialize the explicitly selected brain first.');
+ if (!brain) throw brainUninitialized('Initialize the explicitly selected brain first.', input.brainId);
const { profile, config } = admissionConfig(input, requestId, brain.brain_id);
assertCompanyBrainExtractor(profile.extractorVersion, input);
await registerLocalWriter(engine, 'cli');
const before = async (tx: BrainEngine) => {
await tx.executeRaw("SELECT key FROM config WHERE key='schema_pack' FOR UPDATE");
const preview = await checkCompanyBrainDestination(tx, input);
- if (preview.databaseId !== profile.databaseId) throw new OperationError('source_changed', 'The selected database identity changed during admission.');
+ if (preview.databaseId !== profile.databaseId) {
+ throw opError('source_changed', 'The selected database identity changed during admission.',
+ `Brain ${input.brainId} now resolves to a different database than the one previewed, so nothing was admitted. Check it with gbrain doctor, then preview the connect again before approving.`,
+ { fix: readFix(`Shows which database brain ${input.brainId} resolves to now.`, { argv: ['gbrain', 'doctor', '--brain', input.brainId, '--json'] }) });
+ }
const validation = await validateCompanyBrainPlan(plan, { path: input.path, mode: 'apply' });
- if (!validation.valid) throw new OperationError(validation.code, 'The source changed before admission; inspect it again.');
+ if (!validation.valid) throw planNotReady(validation.code, 'The source changed before admission; inspect it again.', input.path);
await assertNoOverlappingPath(tx, input.sourceId, plan.revision!.root);
if (preview.schemaBinding) await tx.setConfig('schema_pack', preview.schemaBinding);
};
diff --git a/src/core/company-brain/revision.ts b/src/core/company-brain/revision.ts
index 9b4f600fd2..4cc9e1df46 100644
--- a/src/core/company-brain/revision.ts
+++ b/src/core/company-brain/revision.ts
@@ -2,18 +2,24 @@ import { spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
import { constants, existsSync, lstatSync, openSync, fstatSync, readSync, closeSync, realpathSync } from 'node:fs';
import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import { opError } from '../ops/contract.ts';
import {
COMPANY_BRAIN_MAX_ENTRIES, COMPANY_BRAIN_MAX_FILE_BYTES, COMPANY_BRAIN_MAX_METADATA_BYTES,
type CommittedEntry, type InspectionLimits, type RevisionIdentity, type UncommittedEntry,
} from './types.ts';
+function inspectAgain(root: string, why: string, extra: string[] = []): Action {
+ return { argv: ['gbrain', 'sources', 'inspect', root, '--profile', 'company-brain', ...extra, '--json'], consent: [], actor: 'agent', why, requires_exclusive: false };
+}
+
export function inspectionLimits(input: InspectionLimits = {}): Required<InspectionLimits> {
const defaults = { maxEntries: COMPANY_BRAIN_MAX_ENTRIES, maxMetadataBytes: COMPANY_BRAIN_MAX_METADATA_BYTES, maxFileBytes: COMPANY_BRAIN_MAX_FILE_BYTES };
for (const key of Object.keys(defaults) as (keyof InspectionLimits)[]) {
const value = input[key] ?? defaults[key];
if (!Number.isSafeInteger(value) || value < 1 || value > defaults[key]) {
- throw new OperationError('invalid_params', 'Inspection limits must be positive integers no larger than the built-in limits.');
+ throw opError('invalid_params', 'Inspection limits must be positive integers no larger than the built-in limits.',
+ `Omit the limits to use the built-ins, or pass positive integers no larger than maxEntries ${COMPANY_BRAIN_MAX_ENTRIES}, maxMetadataBytes ${COMPANY_BRAIN_MAX_METADATA_BYTES}, and maxFileBytes ${COMPANY_BRAIN_MAX_FILE_BYTES}.`);
}
defaults[key] = value;
}
@@ -42,14 +48,16 @@ async function gitRead(root: string, args: string[], maxBytes: number, onChunk?:
let bytes = 0;
let failure: Error | undefined;
const timer = setTimeout(() => {
- failure = new OperationError('invalid_source', 'Git inspection timed out; narrow the repository and retry.');
+ failure = opError('invalid_source', 'Git inspection timed out; narrow the repository and retry.',
+ `A local Git read in ${root} ran past its 30-second limit. Inspect a smaller checkout (a separate repository or sparse clone holding only the Markdown to import); the inspection is read-only, so rerunning it once after other disk activity settles is safe.`);
child.kill('SIGKILL');
}, 30_000);
child.stdout.on('data', (chunk: Buffer) => {
if (failure) return;
bytes += chunk.length;
if (bytes > maxBytes) {
- failure = new OperationError('request_too_large', 'Inspection exceeds its bounded metadata or file limit; partition the repository or narrow selection.');
+ failure = opError('request_too_large', 'Inspection exceeds its bounded metadata or file limit; partition the repository or narrow selection.',
+ `Git output from ${root} passed its ${maxBytes}-byte cap. Split the content into a smaller checkout and inspect that path, or exclude the oversized files with --exclude on gbrain sources inspect.`);
child.kill('SIGKILL');
return;
}
@@ -57,11 +65,13 @@ async function gitRead(root: string, args: string[], maxBytes: number, onChunk?:
catch (error) { failure = error as Error; child.kill('SIGKILL'); }
});
child.stderr.resume();
- child.on('error', () => { failure = new OperationError('invalid_source', 'Git is unavailable for local inspection.'); });
+ child.on('error', () => { failure = opError('invalid_source', 'Git is unavailable for local inspection.',
+ 'Install Git and make sure `git` is on the PATH of the gbrain process, then run the inspection again; company sources are read only through local Git.'); });
child.on('close', code => {
clearTimeout(timer);
if (failure) reject(failure);
- else if (code !== 0) reject(new OperationError('invalid_source', 'The local Git revision is unavailable or invalid; inspect a committed checkout.'));
+ else if (code !== 0) reject(opError('invalid_source', 'The local Git revision is unavailable or invalid; inspect a committed checkout.',
+ `Git could not read ${root} at the requested revision. Confirm it is a Git checkout with at least one commit and that an approved commit still exists locally (no fetch is attempted), then inspect it again with gbrain sources inspect.`));
else accept(Buffer.concat(chunks));
});
});
@@ -76,39 +86,57 @@ async function gitRecords(root: string, args: string[], limits: Required<Inspect
for (;;) {
const end = pending.indexOf(0, offset);
if (end < 0) break;
- if (++count > limits.maxEntries) throw new OperationError('request_too_large', 'Inspection exceeds the entry limit; partition the repository.');
+ if (++count > limits.maxEntries) throw opError('request_too_large', 'Inspection exceeds the entry limit; partition the repository.',
+ `The checkout at ${root} lists more than ${limits.maxEntries} Git entries. Split it into smaller checkouts and inspect each one separately.`);
let record: string;
try { record = new TextDecoder('utf-8', { fatal: true }).decode(pending.subarray(offset, end)); }
- catch { throw new OperationError('invalid_source', 'Git contains a path that is not valid UTF-8.'); }
+ catch {
+ throw opError('invalid_source', 'Git contains a path that is not valid UTF-8.',
+ `Rename the file whose name is not valid UTF-8 in ${root}, commit the rename, then inspect again; plans cannot represent that path.`);
+ }
visit(record);
offset = end + 1;
}
pending = pending.subarray(offset);
});
- if (pending.length) throw new OperationError('invalid_source', 'Git returned an incomplete inventory.');
+ if (pending.length) {
+ throw opError('invalid_source', 'Git returned an incomplete inventory.',
+ `Git's listing of ${root} ended mid-record, usually because the checkout changed during the read. Let other Git activity finish, then inspect again; inspection is read-only.`);
+ }
}
export async function resolveCommittedRevision(path: string, revision?: string): Promise<RevisionIdentity> {
const root = resolve(path);
try {
if (realpathSync(root) !== root || !lstatSync(root).isDirectory() || /[\x00-\x1f\x7f]/.test(root)) throw new Error();
- } catch { throw new OperationError('invalid_source', 'Inspect a real local directory without symlink components.'); }
+ } catch {
+ throw opError('invalid_source', 'Inspect a real local directory without symlink components.',
+ `Pass the checkout's real path to gbrain sources inspect: ${root} must be an existing directory reached without symlinks or control characters.`);
+ }
if (revision !== undefined && !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(revision)) {
- throw new OperationError('invalid_source', 'An approved revision must be a full Git commit object ID.');
+ throw opError('invalid_source', 'An approved revision must be a full Git commit object ID.',
+ 'Use the full 40- or 64-character commit ID recorded in the approved plan (plan.revision.commit), not a branch name or abbreviated hash.');
}
const text = async (args: string[]) => (await gitRead(root, args, 64 * 1024)).toString('utf8').replace(/\n$/, '');
const gitRoot = await text(['rev-parse', '--show-toplevel']);
const gitDir = await text(['rev-parse', '--absolute-git-dir']);
if (realpathSync(gitRoot) !== gitRoot || realpathSync(gitDir) !== gitDir) {
- throw new OperationError('invalid_source', 'The Git directory or checkout resolves through a symlink.');
+ throw opError('invalid_source', 'The Git directory or checkout resolves through a symlink.',
+ `The checkout at ${gitRoot} or its Git directory ${gitDir} is reached through a symlink. Clone or move it to a real path without symlinks, then inspect that path.`);
}
const scope = relative(gitRoot, root).split(sep).join('/');
- if (scope && !safeRepositoryPath(scope)) throw new OperationError('invalid_source', 'The source directory is outside its Git checkout.');
+ if (scope && !safeRepositoryPath(scope)) {
+ throw opError('invalid_source', 'The source directory is outside its Git checkout.',
+ `Inspect ${gitRoot} or a directory inside it whose relative path has no '.', '..', or .git components.`);
+ }
const commit = await text(['rev-parse', '--verify', '--end-of-options', `${revision ?? 'HEAD'}^{commit}`]);
const tree = await text(['rev-parse', '--verify', '--end-of-options', `${commit}^{tree}`]);
const objectFormat = await text(['rev-parse', '--show-object-format']);
if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit) || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(tree) ||
- (objectFormat !== 'sha1' && objectFormat !== 'sha256')) throw new OperationError('invalid_source', 'Unsupported Git object identity.');
+ (objectFormat !== 'sha1' && objectFormat !== 'sha256')) {
+ throw opError('invalid_source', 'Unsupported Git object identity.',
+ `Git reported a commit, tree, or object format for ${gitRoot} that gbrain cannot verify. Inspect a SHA-1 or SHA-256 repository checked out at a normal commit.`);
+ }
const rootStat = lstatSync(root, { bigint: true });
const gitStat = lstatSync(gitDir, { bigint: true });
return { root, git_root: gitRoot, git_dir: gitDir, scope, commit, tree, object_format: objectFormat,
@@ -121,11 +149,17 @@ export async function inventoryCommittedRevision(revision: RevisionIdentity, inp
await gitRecords(revision.git_root, ['ls-tree', '-r', '-l', '-z', '--full-tree', revision.tree], limits, record => {
const tab = record.indexOf('\t');
const match = /^(\d{6}) (blob|commit) ([a-f0-9]{40,64}) +(-|\d+)$/.exec(record.slice(0, tab));
- if (tab < 0 || !match) throw new OperationError('invalid_source', 'Git returned an invalid tree entry.');
+ if (tab < 0 || !match) {
+ throw opError('invalid_source', 'Git returned an invalid tree entry.',
+ `Git listed a tree entry in ${revision.git_root} that gbrain cannot parse. Check the repository with git fsck, then inspect it again.`);
+ }
const path = record.slice(tab + 1);
if (revision.scope && !path.startsWith(`${revision.scope}/`)) return;
const bytes = match[4] === '-' ? null : Number(match[4]);
- if (bytes !== null && !Number.isSafeInteger(bytes)) throw new OperationError('request_too_large', 'Git blob size exceeds supported bounds.');
+ if (bytes !== null && !Number.isSafeInteger(bytes)) {
+ throw opError('request_too_large', 'Git blob size exceeds supported bounds.',
+ `A blob in ${revision.git_root} reports a size beyond safe integer bounds. Remove it from the repository or inspect a checkout without it.`);
+ }
entries.push({ path: revision.scope ? path.slice(revision.scope.length + 1) : path,
mode: match[1]!, object_type: match[2] as 'blob' | 'commit', object_id: match[3]!, bytes });
});
@@ -136,20 +170,32 @@ export async function readCommittedBlob(revision: RevisionIdentity, entry: Commi
const limits = inspectionLimits(input);
if (!safeRepositoryPath(entry.path) || !/^100(?:644|755)$/.test(entry.mode) || entry.object_type !== 'blob' ||
!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(entry.object_id)) {
- throw new OperationError('invalid_source', 'Only safe committed regular blobs can be read.');
+ throw opError('invalid_source', 'Only safe committed regular blobs can be read.',
+ `Only committed regular files at safe repository paths are readable. Inspect ${revision.root} again so the plan lists only eligible files.`,
+ { fix: inspectAgain(revision.root, 'A fresh read-only inspection rebuilds the manifest from verified committed blobs.') });
+ }
+ if (entry.bytes === null || entry.bytes > limits.maxFileBytes) {
+ throw opError('request_too_large', 'Markdown exceeds the import file limit; split it into smaller files.',
+ `${entry.path} is larger than the ${limits.maxFileBytes}-byte file limit. Split it into smaller files and commit them, or exclude it, then inspect again.`,
+ { fix: inspectAgain(revision.root, 'Previews the plan without the oversized file; inspection is read-only.', [`--exclude=${entry.path}`]) });
}
- if (entry.bytes === null || entry.bytes > limits.maxFileBytes) throw new OperationError('request_too_large', 'Markdown exceeds the import file limit; split it into smaller files.');
const gitPath = revision.scope ? `${revision.scope}/${entry.path}` : entry.path;
const treeEntry = (await gitRead(revision.git_root,
['ls-tree', '-r', '-l', '-z', '--full-tree', revision.tree, '--', `:(literal)${gitPath}`], 64 * 1024)).toString('utf8');
const separator = treeEntry.indexOf('\t');
const expected = `${entry.mode} blob ${entry.object_id} ${entry.bytes}`;
if (separator < 0 || treeEntry.slice(0, separator).replace(/ +/g, ' ') !== expected || treeEntry.slice(separator + 1) !== `${gitPath}\0`) {
- throw new OperationError('invalid_source', 'The blob does not belong to the approved revision and path.');
+ throw opError('invalid_source', 'The blob does not belong to the approved revision and path.',
+ `${entry.path} at approved commit ${revision.commit} is not in the checkout at ${revision.root} as planned. Inspect the checkout again; gbrain never substitutes current HEAD for an approved commit, so a missing commit needs a new reviewed plan.`,
+ { fix: inspectAgain(revision.root, 'Shows what the checkout holds now without changing the brain or the repository.') });
}
const result = await gitRead(revision.git_root, ['cat-file', 'blob', entry.object_id], limits.maxFileBytes);
const hash = createHash(revision.object_format).update(`blob ${result.length}\0`).update(result).digest('hex');
- if (result.length !== entry.bytes || hash !== entry.object_id) throw new OperationError('invalid_source', 'The approved committed blob identity does not match its bytes.');
+ if (result.length !== entry.bytes || hash !== entry.object_id) {
+ throw opError('invalid_source', 'The approved committed blob identity does not match its bytes.',
+ `Git returned bytes for ${entry.path} that do not hash to ${entry.object_id}, so the object store in ${revision.git_root} may be damaged. Check it with git fsck, then inspect ${revision.root} again.`,
+ { fix: inspectAgain(revision.root, 'Re-reads and re-verifies every committed blob without changing the brain or the repository.') });
+ }
return result;
}
@@ -187,7 +233,10 @@ export async function inspectUncommitted(revision: RevisionIdentity, entries: Co
await gitRecords(revision.git_root, ['ls-files', '--stage', '-z'], limits, record => {
const tab = record.indexOf('\t');
const match = /^(\d{6}) ([a-f0-9]{40,64}) ([0-3])$/.exec(record.slice(0, tab));
- if (!match) throw new OperationError('invalid_source', 'Git returned an invalid index entry.');
+ if (!match) {
+ throw opError('invalid_source', 'Git returned an invalid index entry.',
+ `Git listed an index entry in ${revision.git_root} that gbrain cannot parse. Check the index with git status and git fsck, then inspect ${revision.root} again.`);
+ }
const path = local(record.slice(tab + 1));
if (path !== null) index.set(path, { oid: match[2]!, mode: match[1]!, stage: match[3]! });
});
@@ -213,7 +262,8 @@ export async function inspectUncommitted(revision: RevisionIdentity, entries: Co
});
const result = [...dirty.values()].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
if (result.length > limits.maxEntries || Buffer.byteLength(JSON.stringify(result)) > limits.maxMetadataBytes) {
- throw new OperationError('request_too_large', 'Uncommitted inventory exceeds inspection limits; narrow the repository.');
+ throw opError('request_too_large', 'Uncommitted inventory exceeds inspection limits; narrow the repository.',
+ `The checkout at ${revision.root} has more uncommitted or untracked files than the limits allow (${limits.maxEntries} entries, ${limits.maxMetadataBytes} metadata bytes). Commit, remove, or git-ignore them, then inspect again.`);
}
return result;
}
diff --git a/src/core/company-brain/runtime.ts b/src/core/company-brain/runtime.ts
index 661e98fcbd..56c1bb0f26 100644
--- a/src/core/company-brain/runtime.ts
+++ b/src/core/company-brain/runtime.ts
@@ -2,7 +2,10 @@ import { randomUUID } from 'node:crypto';
import { realpathSync } from 'node:fs';
import { resolve } from 'node:path';
import type { BrainEngine } from '../engine.ts';
-import { OperationError } from '../ops/contract.ts';
+import type { Action } from '../agent-output.ts';
+import type { RegistryCode } from '../error-registry.ts';
+import { opError, OperationError } from '../ops/contract.ts';
+import { readFix } from '../ops/op-fix.ts';
import type { SyncOpts, SyncResult } from '../../commands/sync.ts';
import { performSync } from '../../commands/sync.ts';
import { checkApprovedSchemaForEngine } from '../schema-pack/engine-resolution.ts';
@@ -12,7 +15,7 @@ import { companyBrainGraphStamp, verifyCompanyBrain } from './verification.ts';
import { loadLinkPageMetadata } from '../link-reconciliation.ts';
import { digest } from '../persistence/digest.ts';
import { assertCompanyBrainPolicy, assertCompanyBrainExtractor, companyBrainPolicyFingerprint, companyBrainRepository } from './policy.ts';
-import { admitCompanyBrain, assertCompanyBrainCaller, checkCompanyBrainDestination, ingestionFence,
+import { admitCompanyBrain, assertCompanyBrainCaller, checkCompanyBrainDestination, ingestionFence, ownerStatusFix, reinspectFix, sourceStatusFix,
type CompanyBrainConnectInput, type CompanyBrainDestination } from './admission.ts';
import { companyBrainProfile, getCompanyBrainProfile, readCompanyBrainPlan, withCompanyBrainSync } from './profile.ts';
import type { CompanyBrainSyncContext } from './profile.ts';
@@ -31,6 +34,15 @@ export interface CompanyBrainResult {
evidence?: CompanyBrainEvidence;
}
+function resumeFix(input: CompanyBrainDestination, why: string): Action {
+ return { argv: ['gbrain', 'sync', '--brain', input.brainId, '--source', input.sourceId, '--no-embed', '--no-pull'], consent: [], actor: 'agent', why, requires_exclusive: false,
+ verify: { argv: ['gbrain', 'sources', 'status', '--brain', input.brainId, '--json'] } };
+}
+
+function resumeCommand(input: CompanyBrainDestination): string {
+ return `gbrain sync --brain ${input.brainId} --source ${input.sourceId} --no-embed --no-pull`;
+}
+
export async function connectCompanyBrain(engine: BrainEngine, input: CompanyBrainConnectInput): Promise<CompanyBrainResult> {
const admitted = await admitCompanyBrain(engine, input);
return resumeCompanyBrain(engine, input, {}, admitted);
@@ -40,7 +52,9 @@ export async function resumeCompanyBrain(engine: BrainEngine, input: CompanyBrai
assertCompanyBrainCaller(input);
if (opts.workingTree || opts.noSchemaPack || opts.includeGitignored || opts.skipFailed || opts.srcSubpath ||
opts.strategy && opts.strategy !== 'markdown' || opts.exclude?.length || opts.includeHidden?.length) {
- throw new OperationError('profile_incompatible', 'The connected source uses its approved committed selection and schema; inspect a new selection instead of overriding its sync policy.');
+ throw opError('profile_incompatible', 'The connected source uses its approved committed selection and schema; inspect a new selection instead of overriding its sync policy.',
+ `Run ${resumeCommand(input)} without working-tree, schema-pack, ignored-file, skip-failed, strategy, exclude, or subpath overrides. A different selection needs a new inspection and a separately approved connection.`,
+ { fix: resumeFix(input, `Syncs source ${input.sourceId} with its approved committed selection and schema.`) });
}
return withRefreshingLock(engine, `company-brain:${input.sourceId}`, signal => execute(engine, input, { ...opts,
signal: opts.signal ? AbortSignal.any([opts.signal, signal]) : signal }, expected));
@@ -49,13 +63,35 @@ export async function resumeCompanyBrain(engine: BrainEngine, input: CompanyBrai
async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts: SyncOpts, expected?: Awaited<ReturnType<typeof admitCompanyBrain>>): Promise<CompanyBrainResult> {
const [source] = await engine.executeRaw<{ incarnation: string; local_path: string; archived: boolean; config: unknown }>(
'SELECT incarnation,local_path,archived,config FROM sources WHERE id=$1', [input.sourceId]);
- if (!source || source.archived) throw new OperationError('source_changed', 'The connected source is unavailable.');
- if (opts.repoPath && realpathSync(resolve(opts.repoPath)) !== source.local_path) throw new OperationError('source_changed', 'The requested path does not match the approved source.');
+ if (!source || source.archived) {
+ throw opError('source_changed', 'The connected source is unavailable.',
+ `Source ${input.sourceId} is not registered or is archived in brain ${input.brainId}. Check its status; an archived source must be restored, and a removed one connected again after review.`,
+ { fix: sourceStatusFix(input.brainId, `Shows whether source ${input.sourceId} is registered, archived, or missing.`) });
+ }
+ if (opts.repoPath && realpathSync(resolve(opts.repoPath)) !== source.local_path) {
+ throw opError('source_changed', 'The requested path does not match the approved source.',
+ `Source ${input.sourceId} is approved for the checkout at ${source.local_path}. Sync it without a different repository path.`,
+ { fix: resumeFix(input, `Syncs source ${input.sourceId} from its approved checkout.`) });
+ }
let profile = companyBrainProfile(source.config);
- if (!profile || profile.brainId !== input.brainId) throw new OperationError('destination_not_ready', 'The source does not belong to this approved company destination.');
- if (expected && (source.incarnation !== expected.sourceIncarnation || profile.receiptId !== expected.receiptId)) throw new OperationError('source_changed', 'The admitted source or receipt changed before execution.');
+ if (!profile || profile.brainId !== input.brainId) {
+ throw opError('destination_not_ready', 'The source does not belong to this approved company destination.',
+ profile
+ ? `Source ${input.sourceId} was approved for brain ${profile.brainId}, not ${input.brainId}. Run the sync with --brain ${profile.brainId}.`
+ : `Source ${input.sourceId} has no company-brain approval in brain ${input.brainId}. Check its status; ordinary sources sync without the company workflow.`,
+ { fix: sourceStatusFix(input.brainId, `Shows source ${input.sourceId}'s registration and any ingestion receipt.`) });
+ }
+ if (expected && (source.incarnation !== expected.sourceIncarnation || profile.receiptId !== expected.receiptId)) {
+ throw opError('source_changed', 'The admitted source or receipt changed before execution.',
+ `Request ${expected.receiptId} admitted source ${input.sourceId}, but its registration or receipt changed before indexing started. Inspect the receipt before doing anything else; do not reconnect over it.`,
+ { fix: sourceStatusFix(input.brainId, `Shows source ${input.sourceId}'s current receipt so you can tell which request owns it.`) });
+ }
let receipt = await getSourceIngestionReceipt(engine, { sourceId: input.sourceId, sourceIncarnation: source.incarnation, receiptId: profile.receiptId });
- if (!receipt || receipt.outcome === 'discarded') throw new OperationError('checkpoint_missing', 'The active source receipt is missing or discarded.');
+ if (!receipt || receipt.outcome === 'discarded') {
+ throw opError('checkpoint_missing', 'The active source receipt is missing or discarded.',
+ `Source ${input.sourceId} has no active ingestion receipt, so gbrain will not resume from a different revision. Check its status; starting over means previewing removal with gbrain sources remove ${input.sourceId} --brain ${input.brainId} --dry-run and reconnecting, a destructive step the user approves.`,
+ { fix: sourceStatusFix(input.brainId, `Shows source ${input.sourceId}'s receipt state (missing, discarded, or incomplete).`) });
+ }
const [brain] = await engine.executeRaw<{ brain_id: string }>('SELECT brain_id FROM persistence_brain WHERE singleton=1');
assertCompanyBrainPolicy(profile, receipt, brain?.brain_id, source.local_path);
assertCompanyBrainExtractor(receipt.extractorVersion, input);
@@ -65,13 +101,23 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
: await readCompanyBrainPlan(engine, receipt.id);
if (receipt.outcome !== 'complete') {
if (plan.plan_digest !== profile.planDigest || plan.revision?.commit !== receipt.approvedRevision || plan.schema?.resolved_digest !== receipt.schemaFingerprint) {
- throw new OperationError('plan_stale', 'The stored plan does not match the active ingestion receipt.');
+ throw opError('plan_stale', 'The stored plan does not match the active ingestion receipt.',
+ `Source ${input.sourceId}'s stored plan disagrees with receipt ${receipt.id}. Check the receipt and inspect ${source.local_path} again; do not edit stored approval fields to make them match.`,
+ { fix: sourceStatusFix(input.brainId, `Shows receipt ${receipt.id}'s approved revision and outstanding phase.`) });
}
const validation = await validateCompanyBrainPlan(plan, { path: source.local_path, mode: 'resume' });
- if (!validation.valid) throw new OperationError(validation.code, 'The approved source or schema changed; inspect it before resuming.');
+ if (!validation.valid) {
+ throw opError(validation.code as RegistryCode, 'The approved source or schema changed; inspect it before resuming.',
+ `The checkout at ${source.local_path} no longer matches approved commit ${receipt.approvedRevision} or its schema. Inspect it; gbrain never substitutes current HEAD, so a missing commit or changed schema needs a new reviewed connection.`,
+ { fix: reinspectFix(source.local_path) });
+ }
}
const schema = profile.schema;
- if (plan.revision && digest(companyBrainRepository(plan.revision)) !== digest(profile.repository)) throw new OperationError('source_changed', 'The approved repository identity changed; reconnect explicitly.');
+ if (plan.revision && digest(companyBrainRepository(plan.revision)) !== digest(profile.repository)) {
+ throw opError('source_changed', 'The approved repository identity changed; reconnect explicitly.',
+ `The checkout at ${source.local_path} is no longer the repository approved for source ${input.sourceId}. Restore the original checkout, or preview removal with gbrain sources remove ${input.sourceId} --brain ${input.brainId} --dry-run and reconnect once the user approves.`,
+ { fix: sourceStatusFix(input.brainId, `Shows source ${input.sourceId}'s approved revision and receipt.`) });
+ }
const { pack } = await checkApprovedSchemaForEngine(engine, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest },
{ sourceId: input.sourceId, remote: false });
const fence = await ingestionFence(engine, input.sourceId);
@@ -79,7 +125,11 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
expectedRevision: receipt!.revision, expectedPhase: receipt!.phase, fence });
if (receipt.outcome === 'complete') {
const fresh = plan;
- if (!fresh.ready) throw new OperationError('source_not_ready', 'The current committed source is not ready; inspect its findings before syncing.');
+ if (!fresh.ready) {
+ throw opError('source_not_ready', 'The current committed source is not ready; inspect its findings before syncing.',
+ `The latest commit in ${source.local_path} has blocking findings. Inspect it, fix or exclude what it reports and commit, then sync source ${input.sourceId} again; the last verified import stays in place.`,
+ { fix: reinspectFix(source.local_path) });
+ }
if (fresh.revision!.commit === receipt.approvedRevision && !opts.full) return { ok: true, code: 'complete', receipt,
evidence: await readCompanyBrainEvidence(engine, input.sourceId) };
await checkCompanyBrainDestination(engine, { ...input, path: source.local_path, plan: fresh }, false);
@@ -87,7 +137,11 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
await engine.transaction(async tx => {
await tx.executeRaw('SELECT singleton FROM persistence_brain WHERE singleton=1 FOR UPDATE');
const [current] = await tx.executeRaw<{ config: unknown; local_path: string }>('SELECT config,local_path FROM sources WHERE id=$1 AND incarnation=$2::uuid AND NOT archived FOR UPDATE', [input.sourceId, source.incarnation]);
- if (!current || companyBrainProfile(current.config)?.receiptId !== receipt!.id) throw new OperationError('source_changed', 'The source approval changed.');
+ if (!current || companyBrainProfile(current.config)?.receiptId !== receipt!.id) {
+ throw opError('source_changed', 'The source approval changed.',
+ `Another connect or sync changed source ${input.sourceId}'s approval while this sync ran, and this step rolled back. Check the receipt, then run ${resumeCommand(input)} again.`,
+ { fix: sourceStatusFix(input.brainId, `Shows which receipt now owns source ${input.sourceId}.`) });
+ }
assertCompanyBrainPolicy(companyBrainProfile(current.config)!, receipt!, brain.brain_id, current.local_path);
assertCompanyBrainExtractor(receipt!.extractorVersion, input);
const nextId = randomUUID();
@@ -130,7 +184,11 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
while (graphPhase === 'VERIFY' || cursor?.completed_keys[1] !== 'complete') {
opts.signal?.throwIfAborted();
const graph = await reconcileSourceLinks(engine, input.sourceId, { pack: pack.manifest, afterSlug, limit: 250, expectedSourceIncarnation: source.incarnation });
- if (!graph.ok || graph.failures.length) throw new OperationError('graph_incomplete', 'Source relationship reconciliation is incomplete.');
+ if (!graph.ok || graph.failures.length) {
+ throw opError('graph_incomplete', 'Source relationship reconciliation is incomplete.',
+ `Resume with ${resumeCommand(input)}; graph reconciliation continues from receipt ${receipt.id}'s checkpoint.`,
+ { fix: resumeFix(input, `Resumes source ${input.sourceId}'s graph phase from its checkpoint.`) });
+ }
const counts = receipt.counts;
receipt = await engine.transaction(async tx => {
const next = await transitionSourceIngestionReceipt(tx, { ...mutation(), phase: graphPhase, counts: {
@@ -140,7 +198,11 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
return next;
});
if (graph.complete) break;
- if (!graph.nextAfterSlug || graph.nextAfterSlug === afterSlug) throw new OperationError('graph_incomplete', 'Graph reconciliation did not advance.');
+ if (!graph.nextAfterSlug || graph.nextAfterSlug === afterSlug) {
+ throw opError('graph_incomplete', 'Graph reconciliation did not advance.',
+ `Check source ${input.sourceId}'s receipt, then resume with ${resumeCommand(input)}; if it stalls at the same point again, run gbrain doctor --brain ${input.brainId} --json and report it to the user.`,
+ { fix: sourceStatusFix(input.brainId, `Shows receipt ${receipt.id}'s graph counts and outstanding phase.`) });
+ }
afterSlug = graph.nextAfterSlug;
}
receipt = await transitionSourceIngestionReceipt(engine, { ...mutation(), phase: 'VERIFY' });
@@ -162,10 +224,16 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
await checkApprovedSchemaForEngine(tx, { name: schema.name, identity: schema.identity, resolvedManifestHash: schema.resolved_digest }, { sourceId: input.sourceId, remote: false });
await tx.lockPageKeys(verified.metadata.map(page => ({ sourceId: input.sourceId, slug: page.slug })));
if (digest(await loadLinkPageMetadata(tx, input.sourceId)) !== digest(verified.metadata) || await companyBrainGraphStamp(tx, input.sourceId) !== verified.graphStamp) {
- throw new OperationError('verification_failed', 'Source content or relationships changed during verification.');
+ throw opError('verification_failed', 'Source content or relationships changed during verification.',
+ `Another write touched source ${input.sourceId} while it was being verified, so completion was not recorded. Resume with ${resumeCommand(input)} to verify again.`,
+ { fix: resumeFix(input, `Re-runs verification for source ${input.sourceId} against its approved commit.`) });
}
const [pending] = await tx.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering') LIMIT 1", [input.sourceId]);
- if (pending) throw new OperationError('pending_writes', 'A pending source write prevents verified completion.');
+ if (pending) {
+ throw opError('pending_writes', 'A pending source write prevents verified completion.',
+ `Source ${input.sourceId} has a queued or running write. Check the source's writer, let the write finish, then resume with ${resumeCommand(input)}.`,
+ { fix: ownerStatusFix(input.sourceId) });
+ }
evidence = await readCompanyBrainEvidence(tx, input.sourceId);
return recordSourceIngestionOutcome(tx, { ...mutation(), outcome: 'complete', contentCommitted: true, graphCommitted: true, verificationPassed: true,
counts: { verificationFailures: 0, pendingWrites: 0, graphPages: verified.metadata.length, links: verified.links, unresolvedLinks: verified.unresolvedLinks } });
@@ -181,7 +249,11 @@ async function execute(engine: BrainEngine, input: CompanyBrainDestination, opts
export async function performCompanyBrainSync(engine: BrainEngine, opts: SyncOpts): Promise<SyncResult> {
const profile = await getCompanyBrainProfile(engine, opts.sourceId!);
- if (!profile) throw new OperationError('profile_incompatible', 'The source company profile is missing.');
+ if (!profile) {
+ throw opError('profile_incompatible', 'The source company profile is missing.',
+ `Source ${opts.sourceId} has no company-brain approval, so it cannot be synced as a company source. Check its registration in source status.`,
+ { fix: readFix(`Shows source ${opts.sourceId}'s registration and any ingestion receipt.`, { argv: ['gbrain', 'sources', 'status', '--json'] }) });
+ }
const result = await resumeCompanyBrain(engine, { brainId: profile.brainId, sourceId: opts.sourceId!, remote: false }, opts);
return { fromCommit: null, toCommit: result.receipt.approvedRevision,
added: 0, modified: 0, deleted: 0, renamed: 0, chunksCreated: 0, embedded: 0, pagesAffected: [], ...result.sync,
diff --git a/src/core/skillpack/brain-resident-locate.ts b/src/core/skillpack/brain-resident-locate.ts
index b34f2b423c..4a6f8ec6b6 100644
--- a/src/core/skillpack/brain-resident-locate.ts
+++ b/src/core/skillpack/brain-resident-locate.ts
@@ -22,9 +22,11 @@ import { loadAllSources } from '../sources-load.ts';
import { loadSkillpackManifest } from './manifest-v1.ts';
import { loadState, findEntry } from './state.ts';
import { MAX_SKILL_MD_BYTES } from '../skill-catalog.ts';
+import type { Action } from '../agent-output.ts';
import type { BrainEngine } from '../engine.ts';
-import { OperationError, type OperationContext } from '../operations.ts';
+import { opError, type OperationContext } from '../operations.ts';
import { sourceScopeOpts } from '../operations.ts';
+import { hostFix, readFix } from '../ops/op-fix.ts';
export interface ResidentPackSkill {
slug: string;
@@ -161,6 +163,10 @@ export async function loadResidentPacksForServer(ctx: OperationContext): Promise
return { packs };
}
+function listPacksFix(why: string): Action {
+ return readFix(why, { argv: ['gbrain', 'brain-skillpack'], mcp: { tool: 'list_brain_skillpack', arguments: {} } });
+}
+
export interface ResidentSkillDetail {
source_id: string;
pack_name: string;
@@ -185,40 +191,51 @@ export async function getResidentSkillDetail(
slug: string,
): Promise<ResidentSkillDetail> {
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(slug)) {
- throw new OperationError('invalid_params', `Invalid skill slug: ${JSON.stringify(slug)}`);
+ throw opError('invalid_params', `Invalid skill slug: ${JSON.stringify(slug)}`,
+ 'Pass the skill slug exactly as list_brain_skillpack returns it: lowercase letters, digits, and hyphens, at most 64 characters.',
+ { fix: listPacksFix('Lists every brain-resident pack with its source id and skill slugs.') });
}
// Respect source scoping: a scoped caller can only reach its own sources.
const scope = sourceScopeOpts(ctx);
- if (scope.sourceIds && !scope.sourceIds.includes(sourceId)) {
- throw new OperationError('not_found', `Source not in scope: ${sourceId}`);
- }
- if (scope.sourceId && scope.sourceId !== sourceId) {
- throw new OperationError('not_found', `Source not in scope: ${sourceId}`);
+ if ((scope.sourceIds && !scope.sourceIds.includes(sourceId)) || (scope.sourceId && scope.sourceId !== sourceId)) {
+ throw opError('not_found', `Source not in scope: ${sourceId}`,
+ `This connection cannot read source ${sourceId}. List the packs it can see and use one of their source ids.`,
+ { fix: listPacksFix('Lists only the brain-resident packs on sources this connection may read.') });
}
let sources;
try {
sources = await loadAllSources(ctx.engine);
} catch {
- throw new OperationError('storage_error', 'Could not enumerate sources.');
+ throw opError('storage_error', 'Could not enumerate sources.',
+ 'The brain could not read its sources table; this is a server-side storage failure, not a caller mistake. Run the doctor check on the brain host; if it repeats, report it to the user.',
+ { fix: hostFix(ctx, ['gbrain', 'doctor', '--json'], 'Checks the brain\'s database connection and schema.') });
}
const src = sources.find((s) => s.id === sourceId);
if (!src || !src.local_path) {
- throw new OperationError('not_found', `Source ${sourceId} has no local path.`);
+ throw opError('not_found', `Source ${sourceId} has no local path.`,
+ `Source ${sourceId} is not registered or has no local checkout on the brain host, so it ships no brain-resident pack here. List the packs this brain does ship.`,
+ { fix: listPacksFix('Lists the sources that ship a brain-resident pack.') });
}
const packRoot = src.local_path;
let manifest;
try {
manifest = loadSkillpackManifest(packRoot);
} catch {
- throw new OperationError('not_found', `Source ${sourceId} has no valid skillpack.`);
+ throw opError('not_found', `Source ${sourceId} has no valid skillpack.`,
+ `Source ${sourceId}'s skillpack.json is missing or invalid, so its pack cannot load. List the packs that do load; tell the user if they expected this source to ship one.`,
+ { fix: listPacksFix('Lists the brain-resident packs that load successfully.') });
}
if (manifest.brain_resident !== true) {
- throw new OperationError('not_found', `Source ${sourceId} does not ship a brain-resident pack.`);
+ throw opError('not_found', `Source ${sourceId} does not ship a brain-resident pack.`,
+ `Source ${sourceId}'s skillpack is not marked brain_resident, so it is not served here. List the packs this brain does serve.`,
+ { fix: listPacksFix('Lists the sources that ship a brain-resident pack.') });
}
const skillDir = `skills/${slug}`;
if (!manifest.skills.includes(skillDir)) {
- throw new OperationError('not_found', `Skill "${slug}" not in pack ${manifest.name}.`);
+ throw opError('not_found', `Skill "${slug}" not in pack ${manifest.name}.`,
+ `Pack ${manifest.name} on source ${sourceId} has no skill ${slug}. List its skills and pass one of the slugs it returns.`,
+ { fix: listPacksFix(`Lists pack ${manifest.name}'s skill slugs.`) });
}
// Confinement: realpath the resolved SKILL.md and require it stays under the
@@ -230,16 +247,22 @@ export async function getResidentSkillDetail(
realRoot = realpathSync(packRoot);
realFile = realpathSync(skillMd);
} catch {
- throw new OperationError('not_found', `SKILL.md missing for ${slug} in ${sourceId}.`);
+ throw opError('not_found', `SKILL.md missing for ${slug} in ${sourceId}.`,
+ `Pack ${manifest.name} lists skill ${slug}, but its SKILL.md is missing on the brain host. Tell the user the pack is incomplete so its maintainer can add the file.`);
}
const rel = relative(realRoot, realFile);
if (rel.startsWith('..') || resolve(realRoot, rel) !== realFile) {
- throw new OperationError('storage_error', 'Skill path escaped the pack root.');
+ throw opError('storage_error', 'Skill path escaped the pack root.',
+ `Skill ${slug} in source ${sourceId} resolves outside its pack root (a symlink or '..'), so it was refused. Do not retry; tell the user so the pack's maintainer replaces it with a regular file inside the pack.`);
}
const st = statSync(realFile);
- if (!st.isFile()) throw new OperationError('storage_error', 'Resolved skill path is not a file.');
+ if (!st.isFile()) {
+ throw opError('storage_error', 'Resolved skill path is not a file.',
+ `Skill ${slug}'s SKILL.md in source ${sourceId} is not a regular file. Tell the user so the pack's maintainer can fix the pack.`);
+ }
if (st.size > MAX_SKILL_MD_BYTES) {
- throw new OperationError('storage_error', `SKILL.md exceeds ${MAX_SKILL_MD_BYTES} bytes.`);
+ throw opError('storage_error', `SKILL.md exceeds ${MAX_SKILL_MD_BYTES} bytes.`,
+ `Skill ${slug}'s SKILL.md in source ${sourceId} is larger than the ${MAX_SKILL_MD_BYTES}-byte limit and cannot be served. Tell the user so the pack's maintainer can shorten it.`);
}
const body = readFileSync(realFile, 'utf-8');