Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(errors): B10 backfill company-brain inspection/profile/demo, company-brain-inspect
garrytan1f414c08d7a1
diff --git a/src/commands/company-brain-inspect.ts b/src/commands/company-brain-inspect.tsindex f199fa2257..ffb25a0e73 100644--- a/src/commands/company-brain-inspect.ts+++ b/src/commands/company-brain-inspect.ts@@ -3,7 +3,7 @@ import { dirname, resolve } from 'node:path';import { inspectCompanyBrain } from '../core/company-brain/inspection.ts';import { COMPANY_BRAIN_PROFILE, type CompanyBrainPlan } from '../core/company-brain/types.ts';import { isThinClient, loadConfig } from '../core/config.ts';-import { OperationError } from '../core/ops/contract.ts';+import { opError, OperationError } from '../core/ops/contract.ts';import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';export const COMPANY_BRAIN_INSPECT_HELP = `Inspect an existing company repository without importing it:@@ -33,28 +33,37 @@ export function parseCompanyBrainInspectionArgs(args: string[]): CompanyBrainInsconst arg = args[i];if (arg === '--json') { result.json = true; continue; }if (!arg.startsWith('-')) {- if (result.path) throw new OperationError('invalid_params', 'Inspect accepts exactly one repository path.');+ if (result.path) {+ throw opError('invalid_params', 'Inspect accepts exactly one repository path.', 'Pass a single repository path (quote a path that contains spaces); inspect each repository separately.');+ }result.path = arg;continue;}const equal = arg.indexOf('=');const flag = equal < 0 ? arg : arg.slice(0, equal);if (!['--profile', '--include', '--exclude', '--out'].includes(flag)) {- throw new OperationError('invalid_params', `Unknown inspect option ${JSON.stringify(flag)}.`);+ throw opError('invalid_params', `Unknown inspect option ${JSON.stringify(flag)}.`,+ 'Inspect accepts --profile company-brain, --include, --exclude, --out, and --json; gbrain sources inspect --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 (!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 (flag === '--profile') {- if (value !== COMPANY_BRAIN_PROFILE || result.profile) throw new OperationError('invalid_params', 'Select --profile company-brain once.');+ if (value !== COMPANY_BRAIN_PROFILE || result.profile) {+ throw opError('invalid_params', 'Select --profile company-brain once.', 'Pass --profile company-brain a single time, or omit it to get a profile recommendation without activating one.');+ }result.profile = COMPANY_BRAIN_PROFILE;} else if (flag === '--include') result.include.push(value);else if (flag === '--exclude') result.exclude.push(value);else {- if (result.out) throw new OperationError('invalid_params', 'Choose one --out file.');+ if (result.out) throw opError('invalid_params', 'Choose one --out file.', `Pass --out once; keep ${result.out} or choose a different single path.`);result.out = value;}}- if (!result.path) throw new OperationError('invalid_params', 'A local repository path is required.');+ if (!result.path) {+ throw opError('invalid_params', 'A local repository path is required.', 'Pass the path of a local Git checkout to inspect, for example: gbrain sources inspect ./company-wiki --profile company-brain --json.');+ }return result;}@@ -86,8 +95,10 @@ export async function runCompanyBrainInspection(args: string[]): Promise<void> {try {const options = parseCompanyBrainInspectionArgs(args);json = options.json;- if (isThinClient(loadConfig())) throw new OperationError('permission_denied',- 'Company repository inspection runs locally on the brain host, not through a thin-client installation.');+ if (isThinClient(loadConfig())) {+ throw opError('permission_denied', 'Company repository inspection runs locally on the brain host, not through a thin-client installation.',+ `This installation is a thin client of a remote brain. Ask the user to run gbrain sources inspect on the machine that hosts the company brain, against a checkout of ${options.path} on that machine.`);+ }const plan = await inspectCompanyBrain(options);if (options.out) {const out = resolve(options.out);@@ -95,9 +106,13 @@ export async function runCompanyBrainInspection(args: string[]): Promise<void> {try {writeFileSync(out, `${JSON.stringify(plan, null, 2)}\n`, { flag: 'wx', mode: 0o600 });} catch (error) {- throw new OperationError('plan_output_failed', (error as NodeJS.ErrnoException).code === 'EEXIST'+ const exists = (error as NodeJS.ErrnoException).code === 'EEXIST';+ throw opError('plan_output_failed', exists? 'The plan output already exists. Choose a new --out path; nothing was overwritten.'- : 'The private plan output could not be written. Check the output directory and retry.');+ : 'The private plan output could not be written. Check the output directory and retry.',+ exists+ ? `${out} already exists and is never overwritten. Rerun the inspection with --out naming a new file, or read the existing plan if it is the one you want.`+ : `Writing ${out} failed (${(error as NodeJS.ErrnoException).code ?? 'unknown error'}). Make sure its directory is writable by this user and has free space, then rerun the inspection; it is read-only.`);}}await writeStdoutFinal(json ? `${JSON.stringify({ schema_version: 1, status: plan.ready ? 'ready' : 'blocked',diff --git a/src/core/company-brain/demo.ts b/src/core/company-brain/demo.tsindex 855eeb2ce2..fab3fff36d 100644--- a/src/core/company-brain/demo.ts+++ b/src/core/company-brain/demo.ts@@ -2,7 +2,8 @@ import { PGLiteEngine } from '../pglite-engine.ts';import { importFromContent } from '../import-file.ts';import { loadResolvedPackByName } from '../schema-pack/load-active.ts';import { reconcileSourceLinks } from '../link-reconciliation.ts';-import { OperationError } from '../ops/contract.ts';+import type { RegistryCode } from '../error-registry.ts';+import { opError, type OperationError } from '../ops/contract.ts';import { COMPANY_BRAIN_SAMPLE } from './sample.ts';export interface CompanyBrainDemoResult {@@ -16,6 +17,11 @@ export interface CompanyBrainDemoResult {answers: Array<{ question: string; answer: string; citations: string[] }>;}+function demoFailure(code: RegistryCode, message: string): OperationError {+ return opError(code, message,+ 'The bundled fictional sample failed in a throwaway in-memory brain, so this is a gbrain packaging or code fault, not a problem with your data. Report it to the user with gbrain --version; no brain was touched.');+}+export async function runCompanyBrainDemo(): Promise<CompanyBrainDemoResult> {const engine = new PGLiteEngine();const sourceId = 'company-demo';@@ -29,10 +35,10 @@ export async function runCompanyBrainDemo(): Promise<CompanyBrainDemoResult> {sourceId, noEmbed: true, remote: false, activePack: pack.manifest,sourcePath: `${page.slug}.md`, ingested_via: 'company-brain-demo',});- if (!['imported', 'skipped'].includes(imported.status)) throw new OperationError('demo_import_failed', 'The fictional page did not import successfully.');+ if (!['imported', 'skipped'].includes(imported.status)) throw demoFailure('demo_import_failed', 'The fictional page did not import successfully.');}const graph = await reconcileSourceLinks(engine, sourceId, { pack: pack.manifest });- if (!graph.ok || !graph.complete || graph.unresolved.length) throw new OperationError('demo_graph_failed', 'The fictional graph did not verify.');+ if (!graph.ok || !graph.complete || graph.unresolved.length) throw demoFailure('demo_graph_failed', 'The fictional graph did not verify.');const customer = 'customers/acme-example';const currentDecision = 'decisions/2026-08-20-focus-3pl';const accountLinks = await engine.getLinks(customer, { sourceId });@@ -41,15 +47,15 @@ export async function runCompanyBrainDemo(): Promise<CompanyBrainDemoResult> {const championSlug = accountLinks.find(link => link.link_type === 'champion')?.to_slug;const olderSlug = decisionLinks.find(link => link.link_type === 'supersedes')?.to_slug;const meetingSlug = decisionLinks.find(link => link.link_type === 'decided_in')?.to_slug;- if (!ownerSlug || !championSlug || !olderSlug || !meetingSlug) throw new OperationError('demo_verification_failed', 'Expected ownership or decision provenance is missing.');+ if (!ownerSlug || !championSlug || !olderSlug || !meetingSlug) throw demoFailure('demo_verification_failed', 'Expected ownership or decision provenance is missing.');const owner = await engine.getPage(ownerSlug, { sourceId });const champion = await engine.getPage(championSlug, { sourceId });const decision = await engine.getPage(currentDecision, { sourceId });- if (!owner || !champion || !decision) throw new OperationError('demo_verification_failed', 'The cited fictional pages could not be read back.');+ if (!owner || !champion || !decision) throw demoFailure('demo_verification_failed', 'The cited fictional pages could not be read back.');const rows = await engine.executeRaw<{ type: string; count: number }>('SELECT type,COUNT(*)::int AS count FROM pages WHERE source_id=$1 AND deleted_at IS NULL GROUP BY type', [sourceId]);const types = Object.fromEntries(rows.map(row => [row.type, Number(row.count)]));const pages = Object.values(types).reduce((a, b) => a + b, 0);- if (pages !== COMPANY_BRAIN_SAMPLE.length || types.product !== 1 || types.company !== 1) throw new OperationError('demo_verification_failed', 'The fictional type distribution did not survive import.');+ if (pages !== COMPANY_BRAIN_SAMPLE.length || types.product !== 1 || types.company !== 1) throw demoFailure('demo_verification_failed', 'The fictional type distribution did not survive import.');const cite = (slug: string) => `${sourceId}::${slug}`;return { schema_version: 1, status: 'complete', fictional: true, profile: 'company-brain', pages, types, links: graph.linksCreated,answers: [diff --git a/src/core/company-brain/inspection.ts b/src/core/company-brain/inspection.tsindex 7b55235fc3..e9c77018f4 100644--- a/src/core/company-brain/inspection.ts+++ b/src/core/company-brain/inspection.ts@@ -6,7 +6,7 @@ import { extractEntityRefs, LINK_EXTRACTOR_VERSION_TS, unwrapWikilink } from '..import { normalizeAliasList } from '../search/alias-normalize.ts';import { buildSourceLocalReferenceIndex, frontmatterReferenceHints } from '../source-local-reference-index.ts';import { slugifyPath } from '../sync.ts';-import { OperationError } from '../ops/contract.ts';+import { opError, OperationError } from '../ops/contract.ts';import { QUARANTINE_KEY } from '../quarantine.ts';import { EMBED_SKIP_KEY } from '../embed-skip.ts';import { loadResolvedPackByName } from '../schema-pack/load-active.ts';@@ -29,22 +29,28 @@ function canonical(value: unknown, maxBytes = COMPANY_BRAIN_MAX_METADATA_BYTES):let nodes = 0;let bytes = 0;const visit = (item: unknown, depth: number): unknown => {- if (++nodes > 2_000_000 || depth > 40) throw new OperationError('request_too_large', 'Metadata is too deeply nested or complex.');+ if (++nodes > 2_000_000 || depth > 40) throw opError('request_too_large', 'Metadata is too deeply nested or complex.',+ 'The plan or page metadata nests deeper than 40 levels or holds more than 2,000,000 values. Simplify the frontmatter or inspect a smaller selection so the plan stays within bounds.');if (item === null || typeof item === 'boolean' || (typeof item === 'number' && Number.isFinite(item))) return item;if (typeof item === 'string') {bytes += Buffer.byteLength(item);- if (bytes > maxBytes) throw new OperationError('request_too_large', 'Metadata exceeds its byte limit.');+ if (bytes > maxBytes) {+ throw opError('request_too_large', 'Metadata exceeds its byte limit.',+ `Metadata text passed its ${maxBytes}-byte limit. Narrow the selection with --include or --exclude on gbrain sources inspect, or split the repository.`);+ }return item;}if (item instanceof Date) return item.toISOString();- if (typeof item !== 'object' || item === null || seen.has(item)) throw new OperationError('invalid_params', 'Metadata must be finite, acyclic JSON data.');+ if (typeof item !== 'object' || item === null || seen.has(item)) throw opError('invalid_params', 'Metadata must be finite, acyclic JSON data.',+ 'Use plain JSON data with no NaN, Infinity, functions, or cycles; pass a plan exactly as gbrain sources inspect --json wrote it.');seen.add(item);let result: unknown;if (Array.isArray(item)) result = item.map(value => visit(value, depth + 1));else {const output: Record<string, unknown> = Object.create(null);for (const key of Object.keys(item).sort()) {- if (key === '__proto__' || key === 'constructor' || key === 'prototype') throw new OperationError('invalid_params', 'Unsafe metadata key.');+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') throw opError('invalid_params', 'Unsafe metadata key.',+ 'Remove __proto__, constructor, and prototype keys from the frontmatter or plan; they are refused to prevent prototype pollution.');bytes += Buffer.byteLength(key);output[key] = visit((item as Record<string, unknown>)[key], depth + 1);}@@ -54,7 +60,10 @@ function canonical(value: unknown, maxBytes = COMPANY_BRAIN_MAX_METADATA_BYTES):return result;};const encoded = JSON.stringify(visit(value, 0));- if (Buffer.byteLength(encoded) > maxBytes) throw new OperationError('request_too_large', 'Metadata exceeds its byte limit; narrow selection.');+ if (Buffer.byteLength(encoded) > maxBytes) {+ throw opError('request_too_large', 'Metadata exceeds its byte limit; narrow selection.',+ `The encoded metadata passed its ${maxBytes}-byte limit. Narrow the selection with --include or --exclude on gbrain sources inspect, or split the repository.`);+ }return encoded;}@@ -70,7 +79,8 @@ function patterns(values: string[] | undefined): string[] {if (values === undefined) return [];if (!Array.isArray(values) || values.length > 256 || values.some(value => typeof value !== 'string' || value.length > 1024 ||!safeRepositoryPath(value.replace(/\/$/, '')) || value.startsWith('!'))) {- throw new OperationError('invalid_params', 'Selection must use bounded repository-relative globs without traversal or negation.');+ throw opError('invalid_params', 'Selection must use bounded repository-relative globs without traversal or negation.',+ 'Pass --include and --exclude as repository-relative globs such as docs/** (no leading /, no . or .. or .git segments, no ! negation, no backslashes), at most 256 patterns of up to 1024 characters each.');}return [...new Set(values.map(value => value.endsWith('/') ? `${value}**` : value))].sort();}@@ -248,7 +258,9 @@ function resolveReferences(plan: CompanyBrainPlan, pack: ResolvedPack | null): v}export async function inspectCompanyBrain(options: InspectCompanyBrainOptions): Promise<CompanyBrainPlan> {- if (options.profile !== undefined && options.profile !== COMPANY_BRAIN_PROFILE) throw new OperationError('invalid_params', 'Only the company-brain profile is supported.');+ if (options.profile !== undefined && options.profile !== COMPANY_BRAIN_PROFILE) {+ throw opError('invalid_params', 'Only the company-brain profile is supported.', 'Pass --profile company-brain or omit --profile; it is the only supported profile.');+ }const limits = inspectionLimits(options.limits);const include = patterns(options.include);const exclude = patterns(options.exclude);@@ -314,7 +326,10 @@ export async function inspectCompanyBrain(options: InspectCompanyBrainOptions):}plan.manifest.push(entry);metadataBytes += Buffer.byteLength(JSON.stringify(entry));- if (metadataBytes > limits.maxMetadataBytes) throw new OperationError('request_too_large', 'Selection metadata exceeds its limit; narrow selection.');+ if (metadataBytes > limits.maxMetadataBytes) {+ throw opError('request_too_large', 'Selection metadata exceeds its limit; narrow selection.',+ `Selection metadata passed ${limits.maxMetadataBytes} bytes. Inspect ${options.path} again with narrower --include globs or more --exclude globs, or split the repository.`);+ }}plan.uncommitted = await inspectUncommitted(plan.revision, entries, path => policy(path) === null && /\.mdx?$/i.test(path), limits);if (plan.uncommitted.some(item => item.eligible)) finding(plan, 'error', 'source_not_ready', 'Eligible files have uncommitted changes; commit or exclude them and inspect again. Only committed bytes were inspected.');diff --git a/src/core/company-brain/profile.ts b/src/core/company-brain/profile.tsindex 2dca43e963..7d10235ce2 100644--- a/src/core/company-brain/profile.ts+++ b/src/core/company-brain/profile.ts@@ -1,7 +1,9 @@import { AsyncLocalStorage } from 'node:async_hooks';import { basename, relative } from 'node:path';import type { BrainEngine } from '../engine.ts';-import { OperationError } from '../ops/contract.ts';+import type { Action } from '../agent-output.ts';+import { opError, OperationError } from '../ops/contract.ts';+import { readFix } from '../ops/op-fix.ts';import { importFromContent } from '../import-file.ts';import { readCommittedBlob } from './revision.ts';import { parseMarkdown } from '../markdown.ts';@@ -13,13 +15,25 @@ import type { SourceIngestionCheckpoint } from './receipts.ts';import { companyBrainProfile, companyBrainPolicyFingerprint, type CompanyBrainProfile } from './policy.ts';export { companyBrainProfile, type CompanyBrainProfile } from './policy.ts';+function statusFix(sourceId: string): Action {+ return readFix(`Shows source ${sourceId}'s registration, ingestion receipt, and outstanding phase.`, { argv: ['gbrain', 'sources', 'status', '--json'] });+}++function resumeCommand(sourceId: string): string {+ return `gbrain sync --source ${sourceId} --no-embed --no-pull`;+}+export async function getCompanyBrainProfile(engine: BrainEngine, sourceId: string): Promise<CompanyBrainProfile | null> {const [source] = await engine.executeRaw<{ config: unknown; incarnation: string }>('SELECT config,incarnation FROM sources WHERE id=$1', [sourceId]);if (!source) return null;const profile = companyBrainProfile(source.config);if (!profile) {const [receipt] = await engine.executeRaw("SELECT id FROM source_ingestion_receipts WHERE source_id=$1 AND source_incarnation=$2::uuid AND profile='company-brain' LIMIT 1", [sourceId, source.incarnation]);- if (receipt) throw new OperationError('profile_incompatible', 'The durable company approval has no source policy. Reconnect explicitly; sync cannot fall back to an unrestricted profile.');+ if (receipt) {+ throw opError('profile_incompatible', 'The durable company approval has no source policy. Reconnect explicitly; sync cannot fall back to an unrestricted profile.',+ `Source ${sourceId} has a company-brain receipt but no stored source policy. Check its status; reconnecting means previewing removal with gbrain sources remove ${sourceId} --dry-run and connecting again, a destructive step the user approves. Do not edit stored policy fields.`,+ { fix: statusFix(sourceId) });+ }}return profile;}@@ -50,7 +64,9 @@ export async function withCompanyBrainSource<T>(engine: BrainEngine, sourceId: sconst profile = source ? companyBrainProfile(source.config) : null;if (!source || source.incarnation !== context.sourceIncarnation || !profile || source.local_path !== profile.repository.root || profile.receiptId !== context.receiptId ||companyBrainPolicyFingerprint(profile, sourceId!) !== context.policyFingerprint) {- throw new OperationError('source_changed', 'The source incarnation or approved ingestion changed before publication.');+ throw opError('source_changed', 'The source incarnation or approved ingestion changed before publication.',+ `Another connect or sync changed source ${sourceId}'s registration or approval while this import ran, so this page was not published. Check the receipt, then resume with ${resumeCommand(sourceId!)}.`,+ { fix: statusFix(sourceId!) });}return run(tx);});@@ -63,16 +79,28 @@ export function softDeleteSyncPages(engine: BrainEngine, slugs: string[], opts:export async function readCompanyBrainPlan(engine: BrainEngine, receiptId: string): Promise<CompanyBrainPlan> {const [row] = await engine.executeRaw<{ completed_keys: CompanyBrainPlan[] }>("SELECT completed_keys FROM op_checkpoints WHERE op='company-brain-plan' AND fingerprint=$1", [receiptId]);- if (!row?.completed_keys?.[0]) throw new OperationError('checkpoint_missing', 'The approved source plan is missing; do not restart from a different revision.');+ if (!row?.completed_keys?.[0]) {+ throw opError('checkpoint_missing', 'The approved source plan is missing; do not restart from a different revision.',+ `Receipt ${receiptId}'s approved plan checkpoint is gone, so gbrain will not resume from another revision. Check the source status; starting over needs a removal preview and a new reviewed connection, which the user approves.`,+ { fix: readFix(`Shows which source holds receipt ${receiptId} and its outstanding phase.`, { argv: ['gbrain', 'sources', 'status', '--json'] }) });+ }return row.completed_keys[0];}export async function importCompanyBrainFile(engine: BrainEngine, filePath: string, sourceId: string) {const context = currentCompanyBrainSync(sourceId);- if (!context?.plan.revision) throw new OperationError('plan_stale', 'An approved committed source plan is required.');+ if (!context?.plan.revision) {+ throw opError('plan_stale', 'An approved committed source plan is required.',+ `This import of source ${sourceId} ran outside an approved company-brain sync. Run ${resumeCommand(sourceId)} so the approved plan governs it.`,+ { fix: statusFix(sourceId) });+ }const path = relative(context.plan.revision.root, filePath).split('\\').join('/');const entry = context.entries.get(path);- if (!entry?.page || entry.disposition !== 'included') throw new OperationError('plan_stale', 'The import path is outside the approved selection.');+ if (!entry?.page || entry.disposition !== 'included') {+ throw opError('plan_stale', 'The import path is outside the approved selection.',+ `${path} is not in source ${sourceId}'s approved selection. Changing the selection needs a new inspection and a separately approved connection.`,+ { fix: statusFix(sourceId) });+ }const content = (await readCommittedBlob(context.plan.revision, entry, context.plan.limits)).toString('utf8');const pack = context.pack;const parsed = parseMarkdown(content, entry.page.slug, { activePack: pack.manifest });@@ -84,10 +112,13 @@ export async function importCompanyBrainFile(engine: BrainEngine, filePath: striprepare: async ready => {const tags = [...(snapshot?.tags ?? []), ...ready.parsedPage.tags];if (digest(canonical(parsed, parsed.tags)) !== digest(canonical(ready.parsedPage, tags))) {- throw new OperationError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.');+ throw opError('source_writeback_required', 'Canonical preparation requires a source-content correction; this profile never writes repository files.',+ `${path} would change when published canonically (for example normalized frontmatter or tags), and this profile never edits repository files. Review the needed correction with the user, commit it, then resume with ${resumeCommand(sourceId)}.`);}if (ready.slug !== entry.page!.slug || ready.observedRevision !== (snapshot?.revision ?? null)) {- throw new OperationError('revision_conflict', 'The approved file no longer names the same page revision.');+ throw opError('revision_conflict', 'The approved file no longer names the same page revision.',+ `Page ${entry.page!.slug} in source ${sourceId} changed after this sync read it, so nothing was published for it. Resume with ${resumeCommand(sourceId)} to import against the current revision.`,+ { fix: statusFix(sourceId) });}const project = await prepareCanonicalProjections(engine, ready.parsedPage, ready.slug, sourceId, snapshot, 'immutable');await withCompanyBrainSource(engine, sourceId, async tx => { await ready.apply(tx); await project(tx); });