Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

agent contract: owner-delegated CLI refusals and fact backfill name their own next step

garrytan55b22e940876
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 521ac5b935..2f47c1bdfb 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -1,19 +1,12 @@
# shrink-only baseline for scripts/check-agent-contract.ts rule suggestionless-operation-error: path<TAB>count
src/commands/book-mirror.ts 1
src/commands/capture.ts 4
-src/commands/embed-facts-delegate.ts 5
-src/commands/extract-stale-delegate.ts 4
src/commands/extract-timeline-db.ts 2
src/commands/recall.ts 3
-src/commands/reindex-code-delegate.ts 5
src/commands/repair.ts 6
-src/commands/sync-persistence-delegate.ts 4
src/commands/takes-mutation.ts 1
src/core/company-brain/policy.ts 2
src/core/company-brain/receipts.ts 1
-src/core/embed-backfill-submit.ts 1
-src/core/embed-facts-options.ts 1
-src/core/embed-facts.ts 2
src/core/facts/backstop.ts 1
src/core/harness/native-router.ts 1
src/core/minions/submission-authority.ts 1
diff --git a/src/commands/embed-facts-delegate.ts b/src/commands/embed-facts-delegate.ts
index fc3df6bf14..60fa8be550 100644
--- a/src/commands/embed-facts-delegate.ts
+++ b/src/commands/embed-facts-delegate.ts
@@ -7,13 +7,19 @@ import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../
import { PersistenceIpcTransportError } from '../core/persistence/ipc.ts';
import { validateEmbedFactsOptions, type EmbedFactsOptions } from '../core/embed-facts-options.ts';
import type { EmbedFactsResult } from '../core/embed-facts.ts';
-import { OperationError } from '../core/ops/contract.ts';
+import { OperationError, opError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
+const FACT_EMBED_EXAMPLES: Record<string, string> = { '--source': 'default', '--max-cost-usd': '1', '--max-facts': '500', '--batch-size': '50', '--budget-ms': '60000' };
+const invalid = (message: string, suggestion: string) => opError('invalid_params', message, suggestion,
+ { fix: readFix('Prints every gbrain embed form, including fact repair and its flags.', { argv: ['gbrain', 'embed', '--help'] }) });
+
export function parseFactEmbedArgs(args: string[]): EmbedFactsOptions {
if (!args.includes('--stale') || !args.includes('--facts')) {
- throw new OperationError('invalid_params', 'Use embed --stale --facts --source <id> [--dry-run | --yes --max-cost-usd N] [--max-facts N]');
+ throw invalid('Use embed --stale --facts --source <id> [--dry-run | --yes --max-cost-usd N] [--max-facts N]',
+ 'Fact repair takes both --stale and --facts: preview with gbrain embed --stale --facts --source SOURCE --dry-run, then apply with --yes --max-cost-usd N after the user approves the cost.');
}
const options: Record<string, unknown> = {};
const booleans = { '--dry-run': 'dryRun', '--yes': 'yes' } as const;
@@ -24,10 +30,11 @@ export function parseFactEmbedArgs(args: string[]): EmbedFactsOptions {
const boolean = booleans[arg as keyof typeof booleans];
if (boolean) { options[boolean] = true; continue; }
const key = values[arg as keyof typeof values];
- if (!key) throw new OperationError('invalid_params', 'Use embed --stale --facts with only source, preview, approval, and bounded repair options');
+ if (!key) throw invalid('Use embed --stale --facts with only source, preview, approval, and bounded repair options',
+ `Remove ${arg.split('=')[0]}; fact repair accepts --source, --dry-run, --yes, --max-cost-usd, --max-facts, --batch-size, --budget-ms, --json and --quiet.`);
const value = args[++i];
- if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${arg} requires a value`);
- if (options[key] !== undefined) throw new OperationError('invalid_params', `${arg} may be supplied only once`);
+ if (!value || value.startsWith('--')) throw invalid(`${arg} requires a value`, `Give ${arg} its value right after it, e.g. ${arg} ${FACT_EMBED_EXAMPLES[arg]}.`);
+ if (options[key] !== undefined) throw invalid(`${arg} may be supplied only once`, `Pass ${arg} once, with the one value you mean.`);
options[key] = key === 'sourceId' ? value : Number(value);
}
return validateEmbedFactsOptions(options);
@@ -41,7 +48,13 @@ export async function maybeDelegateFactEmbed(hostConfig: GBrainConfig | null, ar
try {
const delegated = await maybeDelegateLocalAdministration('writer_embed_facts', { options }, config,
{ timeoutMs: (options.budgetMs ?? 60_000) + 30_000 });
- if (!delegated.handled) throw new OperationError('owner_unavailable', 'The observed PGLite owner stopped before fact repair admission');
+ if (!delegated.handled) {
+ const paid = options.dryRun !== true;
+ throw opError('owner_unavailable', 'The observed PGLite owner stopped before fact repair admission',
+ `Nothing ran: the running gbrain serve exited before admitting the repair. Run the same command again; it opens the brain directly or delegates to the new owner.${paid ? ' It spends up to the approved --max-cost-usd, as before.' : ''}`,
+ { fix: { argv: ['gbrain', 'embed', ...args], consent: paid ? ['paid'] : [], actor: 'agent', requires_exclusive: false,
+ why: 'The owner stopped before admission, so the same request has not run yet.' } });
+ }
const result = delegated.result as EmbedFactsResult;
await writeStdoutFinal(JSON.stringify(result, null, 2) + '\n');
if (result.failures) setCliExitVerdict(1);
diff --git a/src/commands/extract-stale-delegate.ts b/src/commands/extract-stale-delegate.ts
index abb9f69d88..f558d63325 100644
--- a/src/commands/extract-stale-delegate.ts
+++ b/src/commands/extract-stale-delegate.ts
@@ -4,7 +4,8 @@ import { resolveBrainId } from '../core/brain-resolver.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
import { inspectLockHolder } from '../core/pglite-lock.ts';
-import { OperationError } from '../core/ops/contract.ts';
+import { opError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
import { writeStdoutFinal } from '../core/cli-force-exit.ts';
import { formatManagedStaleExtraction, type ManagedLinkExtraction } from '../core/persistence/links-maintenance.ts';
@@ -15,6 +16,8 @@ export async function maybeDelegateExtractStale(hostConfig: GBrainConfig | null,
const config = persistenceConfigForBrain(hostConfig, brainId, brainId === 'host' ? [] : loadMounts());
if (config?.engine !== 'pglite' || !config.database_path || config.database_url || !inspectLockHolder(config.database_path).held) return false;
const json = args.includes('--json');
+ const invalid = (message: string, suggestion: string) => opError('invalid_params', message, suggestion,
+ { fix: readFix('Prints the gbrain extract forms and flags.', { argv: ['gbrain', 'extract', '--help'] }) });
try {
const params: Record<string, unknown> = {};
for (let i = 0; i < args.length; i++) {
@@ -22,16 +25,19 @@ export async function maybeDelegateExtractStale(hostConfig: GBrainConfig | null,
if (arg === '--dry-run') params.dry_run = true;
else if (arg === '--source-id') {
const value = args[++i];
- if (!value || value.startsWith('-')) throw new OperationError('invalid_params', '--source-id requires a value.');
+ if (!value || value.startsWith('-')) throw invalid('--source-id requires a value.', 'Give --source-id the source to extract, e.g. gbrain extract --stale --source-id default, or omit it to extract every source.');
params.source_id = value;
} else if (arg === '--source') {
- if (args[++i] !== 'db') throw new OperationError('invalid_params', "extract --stale is DB-source only; drop '--source fs'.");
+ if (args[++i] !== 'db') throw invalid("extract --stale is DB-source only; drop '--source fs'.", 'Drop --source fs (or pass --source db); stale extraction reads pages from the database.');
} else if (!['--stale', '--json', '--include-frontmatter', '--catch-up', 'all'].includes(arg)) {
- throw new OperationError('invalid_params', `Unsupported owner-delegated extract --stale option: ${arg}.`);
+ throw invalid(`Unsupported owner-delegated extract --stale option: ${arg.split('=')[0]}.`,
+ `Remove ${arg.split('=')[0]}; while gbrain serve holds the brain, extract --stale accepts --source-id, --dry-run, --json, --include-frontmatter and --catch-up. Stop the serve to use other extract options.`);
}
}
const delegated = await maybeDelegateLocalAdministration('writer_extract_stale', params, config, { timeoutMs: 86_400_000 });
- if (!delegated.handled) throw new OperationError('owner_unavailable', 'The registered owner stopped before extraction. Retry the same command.');
+ if (!delegated.handled) throw opError('owner_unavailable', 'The registered owner stopped before extraction. Retry the same command.',
+ 'Nothing ran: the running gbrain serve exited before admitting the extraction. Run the same command again; it opens the brain directly or delegates to the new owner.',
+ { fix: { argv: ['gbrain', 'extract', ...args], consent: [], actor: 'agent', requires_exclusive: false, why: 'The owner stopped before admission, so the same extraction has not run yet.' } });
const result = delegated.result as ManagedLinkExtraction;
const dryRun = params.dry_run === true;
await writeStdoutFinal(formatManagedStaleExtraction(result, dryRun, json) + '\n');
diff --git a/src/commands/reindex-code-delegate.ts b/src/commands/reindex-code-delegate.ts
index 7ea1f00227..027a88ec7a 100644
--- a/src/commands/reindex-code-delegate.ts
+++ b/src/commands/reindex-code-delegate.ts
@@ -4,13 +4,17 @@ import { resolveBrainId } from '../core/brain-resolver.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
import { inspectLockHolder } from '../core/pglite-lock.ts';
-import { OperationError } from '../core/ops/contract.ts';
+import { opError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
import { setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
import { DEFAULT_PAID_CAP_USD } from '../core/consent.ts';
import { consentGate } from '../core/consent-cli.ts';
import type { ReindexCodeOpts, ReindexCodeResult } from './reindex-code.ts';
+const invalid = (message: string, suggestion: string) => opError('invalid_params', message, suggestion,
+ { fix: readFix('Prints the gbrain reindex-code flags.', { argv: ['gbrain', 'reindex-code', '--help'] }) });
+
export function parseReindexCodeDelegateArgs(args: string[]): ReindexCodeOpts {
const options: ReindexCodeOpts = {};
const booleans = { '--force': 'force', '--no-embed': 'noEmbed', '--dry-run': 'dryRun', '--yes': 'yes', '-y': 'yes', '--json': 'json' } as const;
@@ -18,15 +22,17 @@ export function parseReindexCodeDelegateArgs(args: string[]): ReindexCodeOpts {
const arg = args[i];
const key = booleans[arg as keyof typeof booleans];
if (key) { options[key] = true; continue; }
- if (!['--source', '--workers', '--concurrency', '--max-cost', '--max-cost-usd'].includes(arg)) throw new OperationError('invalid_params', 'Unsupported owner-delegated reindex-code option. Run gbrain reindex-code --help.');
+ if (!['--source', '--workers', '--concurrency', '--max-cost', '--max-cost-usd'].includes(arg)) throw invalid('Unsupported owner-delegated reindex-code option. Run gbrain reindex-code --help.',
+ `Remove ${arg.split('=')[0]}; while gbrain serve holds the brain, reindex-code accepts --source, --workers, --max-cost-usd, --force, --no-embed, --dry-run, --yes and --json.`);
const value = args[++i];
- if (!value || value.startsWith('-')) throw new OperationError('invalid_params', `${arg} requires a value.`);
+ if (!value || value.startsWith('-')) throw invalid(`${arg} requires a value.`,
+ `Give ${arg} its value right after it, e.g. ${arg} ${arg === '--source' ? 'default' : arg === '--workers' || arg === '--concurrency' ? '4' : '2'}.`);
if (arg === '--source') options.sourceId = value;
else if (arg === '--workers' || arg === '--concurrency') {
- if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 64) throw new OperationError('invalid_params', 'workers must be an integer from 1 to 64.');
+ if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 64) throw invalid('workers must be an integer from 1 to 64.', `Pass ${arg} as a whole number from 1 to 64, e.g. ${arg} 4.`);
options.workers = Number(value);
} else {
- if (!Number.isFinite(Number(value)) || Number(value) <= 0) throw new OperationError('invalid_params', 'Owner-delegated reindex requires a positive numeric cost cap.');
+ if (!Number.isFinite(Number(value)) || Number(value) <= 0) throw invalid('Owner-delegated reindex requires a positive numeric cost cap.', `Pass ${arg} as a positive dollar amount, e.g. ${arg} 2, or use --no-embed for the free text-only rebuild.`);
options.maxCostUsd = Number(value);
}
}
@@ -58,7 +64,13 @@ export async function maybeDelegateReindexCode(hostConfig: GBrainConfig | null,
if (options.maxCostUsd === undefined && auth.cap_usd !== null) options.maxCostUsd = auth.cap_usd;
}
const delegated = await maybeDelegateLocalAdministration('writer_reindex_code', { options }, config, { timeoutMs: 86_400_000 });
- if (!delegated.handled) throw new OperationError('owner_unavailable', 'The registered owner stopped before reindex admission. Retry the same command.');
+ if (!delegated.handled) {
+ const paid = !options.noEmbed && !options.dryRun;
+ throw opError('owner_unavailable', 'The registered owner stopped before reindex admission. Retry the same command.',
+ `Nothing ran: the running gbrain serve exited before admitting the reindex. Run the same command again; it opens the brain directly or delegates to the new owner.${paid ? ' Re-embedding stays paid and needs the same approval.' : ''}`,
+ { fix: { argv: ['gbrain', 'reindex-code', ...args], consent: paid ? ['paid'] : [], actor: 'agent', requires_exclusive: false,
+ why: 'The owner stopped before admission, so the same reindex has not run yet.' } });
+ }
const result = delegated.result as ReindexCodeResult;
await writeStdoutFinal(options.json ? JSON.stringify(result) + '\n' :
`reindex-code: ${result.reindexed} reindexed, ${result.skipped} skipped, ${result.failed} failed (${result.codePages} code pages).\n`);
diff --git a/src/commands/sync-persistence-delegate.ts b/src/commands/sync-persistence-delegate.ts
index ca6dc423e1..32a8d75e19 100644
--- a/src/commands/sync-persistence-delegate.ts
+++ b/src/commands/sync-persistence-delegate.ts
@@ -5,7 +5,8 @@ import { loadMounts } from '../core/brain-registry.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { resolveSourceIdEngineFree } from '../core/source-resolver.ts';
import { inspectLockHolder } from '../core/pglite-lock.ts';
-import { OperationError } from '../core/ops/contract.ts';
+import { OperationError, opError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
import { PersistenceIpcTransportError } from '../core/persistence/ipc.ts';
import { SYNC_BOOLEAN_FLAGS, SYNC_VALUE_FLAGS, validateSyncWireParams } from '../core/persistence/sync-wire.ts';
@@ -19,6 +20,9 @@ import { parseDurationSeconds } from '../core/sync-concurrency.ts';
import { runDrain, drainJsonFields, formatDrainSummary, syncOutcome } from '../core/persistence/sync-drain.ts';
import { syncResumeCommand } from '../core/sync-reconcile.ts';
+const invalid=(message:string,suggestion:string)=>opError('invalid_params',message,suggestion,
+ {fix:readFix('Prints the gbrain sync flags.',{argv:['gbrain','sync','--help']})});
+
export async function parsePersistenceSyncArgs(args:string[],cwd=process.cwd()) {
const options:Record<string,unknown>={};
for(let i=0;i<args.length;i++) {
@@ -26,15 +30,18 @@ export async function parsePersistenceSyncArgs(args:string[],cwd=process.cwd())
const boolean=SYNC_BOOLEAN_FLAGS[arg as keyof typeof SYNC_BOOLEAN_FLAGS];
if(boolean){options[boolean]=true;continue;}
if(['--json','--yes','--no-hard-deadline'].includes(arg))continue;
- if(['--timeout','--hard-deadline'].includes(arg)){if(!args[++i]||args[i].startsWith('--'))throw new OperationError('invalid_params',`${arg} requires a value.`);continue;}
+ if(['--timeout','--hard-deadline'].includes(arg)){if(!args[++i]||args[i].startsWith('--'))throw invalid(`${arg} requires a value.`,`Give ${arg} a duration right after it, e.g. ${arg} 10m.`);continue;}
const key=SYNC_VALUE_FLAGS[arg as keyof typeof SYNC_VALUE_FLAGS];
- if(!key)throw new OperationError('invalid_params',`Unsupported owner-delegated sync option: ${arg}.`);
- const value=args[++i];if(!value||value.startsWith('--'))throw new OperationError('invalid_params',`${arg} requires a value.`);
+ if(!key)throw invalid(`Unsupported owner-delegated sync option: ${arg.split('=')[0]}.`,
+ `Remove ${arg.split('=')[0]}; while gbrain serve holds the brain, sync runs inside it and accepts ${[...Object.keys(SYNC_BOOLEAN_FLAGS),...Object.keys(SYNC_VALUE_FLAGS),'--timeout','--hard-deadline','--json','--yes'].join(', ')}.`);
+ const value=args[++i];if(!value||value.startsWith('--'))throw invalid(`${arg} requires a value.`,`Give ${arg} its value right after it, as ${arg} VALUE.`);
if(key==='exclude'||key==='includeHidden')options[key]=[...(options[key] as string[]??[]),value];
else options[key]=key==='repoPath'?resolve(cwd,value):value;
}
const source=resolveSourceIdEngineFree(typeof options.sourceId==='string'?options.sourceId:null,cwd);
- if(source==='__all__')throw new OperationError('invalid_params','Owner-delegated sync requires one explicit source.');
+ if(source==='__all__')throw opError('invalid_params','Owner-delegated sync requires one explicit source.',
+ 'Name one source with --source while gbrain serve holds the brain (repeat the command per source); gbrain sources list --json lists them.',
+ {fix:readFix('Lists the source ids to sync one at a time, read-only.',{argv:['gbrain','sources','list','--json']})});
if(source)options.sourceId=source;
const softTimeout=parseDurationSeconds(args.find((_,i)=>args[i-1]==='--timeout'),'--timeout');
const hardTimeout=await deriveDelegatedTimeoutSeconds(args);
@@ -59,7 +66,8 @@ export async function maybeDelegateSyncToPersistence(hostConfig:GBrainConfig|nul
result=await runDrain({signal:stop.signal,announce:true,pass:async()=>{
const delegated=await maybeDelegateLocalAdministration('writer_sync',{...params,timeoutSeconds:Number.isFinite(deadline)?Math.max(1,Math.ceil((deadline-performance.now())/1000)):params.timeoutSeconds} as unknown as Record<string,unknown>,config,
{timeoutMs:Math.min(86_400_000,Math.max(30_000,deadline-performance.now()+30_000))});
- if(!delegated.handled)throw new OperationError('owner_unavailable','The observed PGLite owner stopped before sync admission.','Retry the same sync options to resume its durable cursor.');
+ if(!delegated.handled)throw opError('owner_unavailable','The observed PGLite owner stopped before sync admission.','Retry the same sync options to resume its durable cursor.',
+ {fix:{argv:['gbrain','sync',...args],consent:[],actor:'agent',requires_exclusive:false,why:'The owner stopped before admission; the same options resume the durable cursor.'}});
return delegated.result as SyncResult;
}});
} finally { if(timer)clearTimeout(timer); }
diff --git a/src/core/embed-backfill-submit.ts b/src/core/embed-backfill-submit.ts
index bdbc99d911..668b02ef8b 100644
--- a/src/core/embed-backfill-submit.ts
+++ b/src/core/embed-backfill-submit.ts
@@ -39,7 +39,8 @@
*/
import type { BrainEngine } from './engine.ts';
import { getCompanyBrainProfile } from './company-brain/profile.ts';
-import { OperationError } from './ops/contract.ts';
+import { opError } from './ops/contract.ts';
+import { readFix } from './ops/op-fix.ts';
import { embedBackfillWorkerSurface } from './minions/embed-backfill-admission.ts';
import { MinionQueue } from './minions/queue.ts';
import { parseUsdLimit, resolveSpendPosture, type SpendPosture } from './spend-posture.ts';
@@ -137,7 +138,10 @@ export async function submitEmbedBackfill(
// a row so the undrainable job cannot also cooldown-block a later attempt.
const surface = embedBackfillWorkerSurface(engine);
if (surface.status === 'no_worker_surface') return surface;
- if (await getCompanyBrainProfile(engine, sourceId)) throw new OperationError('source_profile_no_backfill', 'This source profile disables automatic embedding backfill. Enable enrichment only through a separate explicit action.');
+ if (await getCompanyBrainProfile(engine, sourceId)) throw opError('source_profile_no_backfill', 'This source profile disables automatic embedding backfill. Enable enrichment only through a separate explicit action.',
+ `Source ${sourceId} uses the company-brain import profile, which never queues embedding backfill; keyword search keeps working. Embedding it is a separate action the user approves; do not edit the stored profile.`,
+ { docs: 'docs/guides/company-brain-ingestion.md#what-stays-opt-in',
+ fix: readFix(`Shows source ${sourceId}'s profile and import state, read-only.`, { argv: ['gbrain', 'sources', 'status', sourceId, '--json'] }) });
const now = opts.nowMs ?? Date.now();
const cooldownMin =
diff --git a/src/core/embed-facts-options.ts b/src/core/embed-facts-options.ts
index 72f1db1491..dbef110294 100644
--- a/src/core/embed-facts-options.ts
+++ b/src/core/embed-facts-options.ts
@@ -1,4 +1,4 @@
-import { OperationError } from './ops/contract.ts';
+import { opError } from './ops/contract.ts';
import { isValidSourceId } from './source-id.ts';
export interface EmbedFactsOptions {
@@ -12,25 +12,32 @@ export interface EmbedFactsOptions {
}
export function validateEmbedFactsOptions(value: unknown): EmbedFactsOptions {
- const invalid = (message: string): never => { throw new OperationError('invalid_params', message); };
- if (!value || typeof value !== 'object' || Array.isArray(value)) return invalid('Fact backfill requires typed options');
+ const invalid = (message: string, suggestion: string): never => { throw opError('invalid_params', message, suggestion); };
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return invalid('Fact backfill requires typed options',
+ 'Run fact repair through gbrain embed --stale --facts, which builds the typed options; an owner-proxy caller sends options as a JSON object.');
const options = value as Record<string, unknown>;
const allowed = ['sourceId', 'dryRun', 'yes', 'maxCostUsd', 'maxFacts', 'batchSize', 'budgetMs'];
- if (Object.keys(options).some(key => !allowed.includes(key))) return invalid('Unsupported fact backfill options');
- if (!isValidSourceId(options.sourceId)) return invalid('Fact backfill requires an explicit --source <id>');
+ const extra = Object.keys(options).filter(key => !allowed.includes(key));
+ if (extra.length) return invalid('Unsupported fact backfill options',
+ `Remove ${extra.join(', ')}; fact repair options are ${allowed.join(', ')}. Run the same gbrain version on the caller and the brain host.`);
+ if (!isValidSourceId(options.sourceId)) return invalid('Fact backfill requires an explicit --source <id>',
+ 'Name the source with --source, e.g. gbrain embed --stale --facts --source default --dry-run; gbrain sources list --json lists the source ids.');
for (const flag of ['dryRun', 'yes']) {
- if (options[flag] !== undefined && typeof options[flag] !== 'boolean') return invalid(`${flag} must be a boolean`);
+ if (options[flag] !== undefined && typeof options[flag] !== 'boolean') return invalid(`${flag} must be a boolean`,
+ `Send ${flag} as a JSON boolean; on the CLI it is the bare flag ${flag === 'dryRun' ? '--dry-run' : '--yes'}.`);
}
for (const [key, flag, max] of [
['maxFacts', '--max-facts', 10_000], ['batchSize', '--batch-size', 100], ['budgetMs', '--budget-ms', 3_600_000],
] as const) {
if (options[key] !== undefined && (typeof options[key] !== 'number' || !Number.isSafeInteger(options[key])
- || options[key] < 1 || options[key] > max)) return invalid(`${flag} must be an integer between 1 and ${max}`);
+ || options[key] < 1 || options[key] > max)) return invalid(`${flag} must be an integer between 1 and ${max}`,
+ `Pass ${flag} as a whole number from 1 to ${max}, or omit it for the default.`);
}
const dryRun = options.dryRun === true || options.yes !== true;
if ((options.maxCostUsd !== undefined || !dryRun) && (typeof options.maxCostUsd !== 'number'
|| !Number.isFinite(options.maxCostUsd) || options.maxCostUsd < 0)) {
- return invalid('Fact backfill execution requires --yes and a finite --max-cost-usd >= 0');
+ return invalid('Fact backfill execution requires --yes and a finite --max-cost-usd >= 0',
+ `Preview first with gbrain embed --stale --facts --source ${String(options.sourceId)} --dry-run; to apply, pass --yes with --max-cost-usd set to the dollar cap the user approved (e.g. --max-cost-usd 1).`);
}
return { ...options, dryRun } as unknown as EmbedFactsOptions;
}
diff --git a/src/core/embed-facts.ts b/src/core/embed-facts.ts
index 62ea7a57bf..bba934f42a 100644
--- a/src/core/embed-facts.ts
+++ b/src/core/embed-facts.ts
@@ -10,7 +10,8 @@ import { redactFindings } from './secret-scan.ts';
import { currentVerifiedLocalWriter } from './persistence/identity.ts';
import { submissionAuthority, authorizeWrite } from './persistence/authority.ts';
import type { OperationContext } from './ops/contract.ts';
-import { OperationError } from './ops/contract.ts';
+import { OperationError, opError } from './ops/contract.ts';
+import { readFix } from './ops/op-fix.ts';
import { validateEmbedFactsOptions, type EmbedFactsOptions } from './embed-facts-options.ts';
import { AUDIT_ROW_SOURCES } from './facts/audit-sources.ts';
import { resolveMaxChunkTokens } from './embedding-input-limit.ts';
@@ -55,7 +56,9 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
const verified = currentVerifiedLocalWriter();
if (verified && (verified.remote || verified.principal.kind !== 'local_cli' || verified.grant.slugPrefixes !== null
|| !verified.grant.sourceIds.includes('*') && !verified.grant.sourceIds.includes(opts.sourceId))) {
- throw new OperationError('permission_denied', 'Fact backfill requires a trusted source-wide CLI grant');
+ throw opError('permission_denied', 'Fact backfill requires a trusted source-wide CLI grant',
+ `The registered CLI writer cannot repair every fact of source ${opts.sourceId}: fact repair needs the local CLI lane with no slug prefixes and a grant covering that source. Show the grant to the user; widening it (gbrain auth local-writer register cli --replace) is their decision.`,
+ { fix: readFix('Shows the local writer registrations and their grants, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });
}
const [source] = await engine.executeRaw<{ incarnation: string }>(
'SELECT incarnation::text FROM sources WHERE id=$1 AND archived=false', [opts.sourceId]);
@@ -68,7 +71,9 @@ export async function embedStaleFacts(engine: BrainEngine, opts: EmbedFactsOpts,
const [row] = await target.executeRaw<{ unrestricted_slugs: boolean }>(
`SELECT grant_ceiling->'slugPrefixes' = 'null'::jsonb AS unrestricted_slugs
FROM persistence_local_writers WHERE id=$1::uuid`, [authority.principal.id]);
- if (row?.unrestricted_slugs !== true) throw new OperationError('permission_denied', 'Fact backfill requires a current source-wide CLI grant');
+ if (row?.unrestricted_slugs !== true) throw opError('permission_denied', 'Fact backfill requires a current source-wide CLI grant',
+ `The current CLI writer registration has slug prefixes, so it cannot repair every fact of source ${opts.sourceId}. Show the grant to the user; replacing it with an unprefixed grant is their decision.`,
+ { fix: readFix('Shows the local writer registrations and their grants, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] }) });
};
await authorize(engine);
const model = getEmbeddingModel();
diff --git a/test/company-brain-policy.test.ts b/test/company-brain-policy.test.ts
index 2679934ae7..9981cdffa3 100644
--- a/test/company-brain-policy.test.ts
+++ b/test/company-brain-policy.test.ts
@@ -114,7 +114,8 @@ for (const managed of [false, true]) describe(`immutable company approval (${man
expect(shared.config.federated).toBe(true);
expect(companyBrainPolicyFingerprint(companyBrainProfile(shared.config)!, request.sourceId)).toBe(approval);
if (engine.kind === 'pglite') expect(await submitEmbedBackfill(engine, request.sourceId, { reason: 'federation_flip' })).toMatchObject({ status: 'no_worker_surface' });
- else await expect(submitEmbedBackfill(engine, request.sourceId, { reason: 'federation_flip' })).rejects.toMatchObject({ code: 'source_profile_no_backfill' });
+ else await expect(submitEmbedBackfill(engine, request.sourceId, { reason: 'federation_flip' })).rejects.toMatchObject({ code: 'source_profile_no_backfill',
+ docs: 'docs/guides/company-brain-ingestion.md#what-stays-opt-in', fix: { argv: ['gbrain', 'sources', 'status', request.sourceId, '--json'] } });
const file = join(request.path, 'people/person-01.md');
const content = readFileSync(file, 'utf8') + '\nAn explicitly committed update after sharing.\n';
writeFileSync(file, content); git(request.path, 'add', '.'); git(request.path, 'commit', '-qm', 'Synthetic shared source update');
diff --git a/test/embed-facts-delegate.test.ts b/test/embed-facts-delegate.test.ts
new file mode 100644
index 0000000000..cbb916fd5d
--- /dev/null
+++ b/test/embed-facts-delegate.test.ts
@@ -0,0 +1,36 @@
+import { describe, expect, test } from 'bun:test';
+import { parseFactEmbedArgs } from '../src/commands/embed-facts-delegate.ts';
+import { validateEmbedFactsOptions } from '../src/core/embed-facts-options.ts';
+import { parsePersistenceSyncArgs } from '../src/commands/sync-persistence-delegate.ts';
+import { caught, envelopeFor, expectFunnelSuggestions } from './helpers/agent-envelope.ts';
+
+describe('owner-delegated CLI refusals name their own next step', () => {
+ test('every funnel call site carries a site-specific suggestion', () => {
+ expectFunnelSuggestions('src/commands/embed-facts-delegate.ts', 'invalid', 4);
+ expectFunnelSuggestions('src/core/embed-facts-options.ts', 'invalid', 6);
+ expectFunnelSuggestions('src/commands/extract-stale-delegate.ts', 'invalid', 3);
+ expectFunnelSuggestions('src/commands/sync-persistence-delegate.ts', 'invalid', 3);
+ });
+
+ test('fact repair usage refusals offer the embed help and never echo a flag value', async () => {
+ const unknown = envelopeFor(await caught(() => parseFactEmbedArgs(['--stale', '--facts', '--token=synthetic-credential-value'])));
+ expect(unknown).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'embed', '--help'], next: 'run' } });
+ expect(unknown.suggestion).toContain('Remove --token;');
+ expect(JSON.stringify(unknown)).not.toContain('synthetic-credential-value');
+ const missing = envelopeFor(await caught(() => parseFactEmbedArgs(['--stale', '--facts', '--max-facts'])));
+ expect(missing.suggestion).toContain('--max-facts 500');
+ });
+
+ test('applying fact repair without a cap names the preview and the approved cap', async () => {
+ const env = envelopeFor(await caught(() => validateEmbedFactsOptions({ sourceId: 'notes', yes: true })));
+ expect(env.code).toBe('invalid_params');
+ expect(env.suggestion).toContain('gbrain embed --stale --facts --source notes --dry-run');
+ });
+
+ test('an unsupported delegated sync flag lists the flags the owner accepts', async () => {
+ const env = envelopeFor(await caught(() => parsePersistenceSyncArgs(['--bogus=synthetic-credential-value'])));
+ expect(env).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'sync', '--help'], next: 'run' } });
+ expect(env.suggestion).toContain('--no-pull');
+ expect(JSON.stringify(env)).not.toContain('synthetic-credential-value');
+ });
+});
diff --git a/test/reindex-code-delegate.test.ts b/test/reindex-code-delegate.test.ts
index 70266bfa6e..ca09bedf34 100644
--- a/test/reindex-code-delegate.test.ts
+++ b/test/reindex-code-delegate.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test } from 'bun:test';
import { parseReindexCodeDelegateArgs } from '../src/commands/reindex-code-delegate.ts';
+import { caught, envelopeFor, expectFunnelSuggestions } from './helpers/agent-envelope.ts';
describe('resident code reindex arguments', () => {
test('keyless source-scoped recovery stays explicit', () => {
@@ -15,6 +16,7 @@ describe('resident code reindex arguments', () => {
} catch (error) {
expect(error).toMatchObject({ code: 'invalid_params' });
expect((error as Error).message).not.toContain('synthetic-credential-value');
+ expect(JSON.stringify(envelopeFor(error))).not.toContain('synthetic-credential-value');
}
});
@@ -23,4 +25,11 @@ describe('resident code reindex arguments', () => {
expect(() => parseReindexCodeDelegateArgs(args)).toThrow();
});
}
+
+ test('refusals name the flag usage and offer the reindex-code help', async () => {
+ expectFunnelSuggestions('src/commands/reindex-code-delegate.ts', 'invalid', 4);
+ const env = envelopeFor(await caught(() => parseReindexCodeDelegateArgs(['--workers', '65'])));
+ expect(env).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'reindex-code', '--help'], next: 'run' } });
+ expect(env.suggestion).toContain('--workers 4');
+ });
});