Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

agent contract: defaulted-suggestion and generic-suggestion scanner rules; administration refusals name their own next step

garrytan47f8460c7868
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
index 9114720d3d..521ac5b935 100644
--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv
@@ -4,12 +4,9 @@ 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/persistence-admin.ts 11
src/commands/recall.ts 3
src/commands/reindex-code-delegate.ts 5
src/commands/repair.ts 6
-src/commands/sources-lifecycle-args.ts 1
-src/commands/sources-lifecycle.ts 2
src/commands/sync-persistence-delegate.ts 4
src/commands/takes-mutation.ts 1
src/core/company-brain/policy.ts 2
diff --git a/scripts/check-agent-contract.ts b/scripts/check-agent-contract.ts
index 0df1900963..c8ffc3b257 100644
--- a/scripts/check-agent-contract.ts
+++ b/scripts/check-agent-contract.ts
@@ -26,6 +26,11 @@
* an op's `cliOnly.argv` template is exempt: cliOnlyRefusal declares its inputs)
* retry-on-mutating "retry" advice in an error raised by a mutating, non-idempotent op handler
* (say "inspect state before resubmitting"; retry only with the same request identity)
+ * defaulted-suggestion a function that builds an error (opError, new OperationError, usageError, invalidParam,
+ * hostOnlyError) from a suggestion/hint parameter that has a default, is optional or is
+ * `??`-defaulted: each call site names its own next step (never baselined)
+ * generic-suggestion a suggestion whose whole text is boilerplate ("see --help", "try again", "check your
+ * input"), at an error constructor or a funnel call site; name the exact usage (never baselined)
* unregistered-code a literal error code thrown in src/ missing from src/core/error-registry.ts (never baselined)
* code-naming a registry code that is not snake_case or carries a transport prefix (never baselined)
*
@@ -44,7 +49,7 @@ export type Rule =
| 'suggestionless-operation-error' | 'throw-new-error-in-ops' | 'hand-built-command' | 'legacy-advice-key'
| 'interactive-io' | 'yes-rerun-string' | 'stdio-inherit' | 'marker-literal' | 'verify-not-read-only'
| 'flag-in-mcp-text' | 'in-scope-placeholder' | 'retry-on-mutating'
- | 'unregistered-code' | 'code-naming';
+ | 'defaulted-suggestion' | 'generic-suggestion' | 'unregistered-code' | 'code-naming';
export const BASELINED_RULES: readonly Rule[] = [
'suggestionless-operation-error', 'throw-new-error-in-ops', 'hand-built-command', 'legacy-advice-key',
@@ -85,6 +90,137 @@ const PLACEHOLDER_RE = /<(?:source|source[-_]id|slug|id|request[-_]id|client[-_]
const RETRY_RE = /\bretry\b/i;
const SAFE_RETRY_RE = /(?:do not|don't|never) retry|same request_id|same request identity/i;
+const SUGGESTION_PARAM = /(?:suggestion|hint)$/i;
+const SUGGESTION_SINK = /^(opError|OperationError|usageError|invalidParam|hostOnlyError)$/;
+const SUGGESTION_ARG: Readonly<Record<string, number>> = { opError: 2, OperationError: 2, verbError: 2, usageError: 1 };
+const GENERIC_SUGGESTION: readonly RegExp[] = [
+ /^(?:please )?(?:see|check|read|consult|run|use)(?: with)?(?: the)? (?:gbrain(?: [a-z][a-z0-9-]*)* )?--help(?: (?:output|for usage|for details|for options))?$/,
+ /^(?:please )?(?:check|verify|fix|correct|review) (?:your|the) (?:input|arguments|parameters|params|request|options)$/,
+ /^(?:please )?(?:try again|retry)(?: later)?$/,
+ /^(?:please )?(?:see|check|read) (?:the )?(?:docs|documentation)$/,
+];
+
+/** True when a suggestion names no next step: empty, or only a generic denylist phrase. */
+export function isGenericSuggestion(text: string): boolean {
+ const t = text.replace(/[`'"]/g, '').replace(/\s+/g, ' ').trim().toLowerCase().replace(/[.!]+$/, '');
+ return t === '' || GENERIC_SUGGESTION.some(re => re.test(t));
+}
+
+type FnLike = ts.FunctionDeclaration | ts.FunctionExpression | ts.ArrowFunction;
+const isFnLike = (n: ts.Node): n is FnLike => ts.isFunctionDeclaration(n) || ts.isFunctionExpression(n) || ts.isArrowFunction(n);
+
+function fnName(fn: FnLike): string | undefined {
+ if (ts.isFunctionDeclaration(fn)) return fn.name?.text;
+ return ts.isVariableDeclaration(fn.parent) && ts.isIdentifier(fn.parent.name) ? fn.parent.name.text : undefined;
+}
+
+/** Error-constructor calls in a function body (the `defaulted-suggestion` sinks). */
+function sinkCalls(fn: FnLike, sf: ts.SourceFile): Array<ts.CallExpression | ts.NewExpression> {
+ const out: Array<ts.CallExpression | ts.NewExpression> = [];
+ const visit = (n: ts.Node) => {
+ if ((ts.isCallExpression(n) || ts.isNewExpression(n)) && SUGGESTION_SINK.test(n.expression.getText(sf))) out.push(n);
+ ts.forEachChild(n, visit);
+ };
+ if (fn.body) visit(fn.body);
+ return out;
+}
+
+function nullishDefaulted(fn: FnLike, name: string): boolean {
+ let found = false;
+ const visit = (n: ts.Node) => {
+ if (ts.isBinaryExpression(n) && n.operatorToken.kind === ts.SyntaxKind.QuestionQuestionToken
+ && ts.isIdentifier(n.left) && n.left.text === name) found = true;
+ if (!found) ts.forEachChild(n, visit);
+ };
+ if (fn.body) visit(fn.body);
+ return found;
+}
+
+/** A file-local function that forwards one of its parameters as an error's suggestion. */
+interface Funnel { name: string; index: number }
+export interface FunnelSite { file: string; line: number; funnel: string; texts: string[] | undefined; expr: string }
+
+/** Literal texts of a suggestion expression (each branch of a conditional); undefined when any branch is not literal. */
+function suggestionTexts(n: ts.Expression, sf: ts.SourceFile): string[] | undefined {
+ if (ts.isParenthesizedExpression(n)) return suggestionTexts(n.expression, sf);
+ if (ts.isConditionalExpression(n)) {
+ const a = suggestionTexts(n.whenTrue, sf); const b = suggestionTexts(n.whenFalse, sf);
+ return a && b ? [...a, ...b] : undefined;
+ }
+ const t = flatText(n, sf);
+ return t === undefined ? undefined : [t];
+}
+
+function fileFunnels(sf: ts.SourceFile): Funnel[] {
+ const fns: FnLike[] = [];
+ const collect = (n: ts.Node) => { if (isFnLike(n)) fns.push(n); ts.forEachChild(n, collect); };
+ collect(sf);
+ const out: Funnel[] = [];
+ const forwards = (fn: FnLike, param: string): boolean => {
+ let found = false;
+ const visit = (n: ts.Node) => {
+ if (found) return;
+ if (ts.isCallExpression(n) || ts.isNewExpression(n)) {
+ const callee = n.expression.getText(sf);
+ const args = n.arguments ?? [];
+ if (SUGGESTION_SINK.test(callee) && args.some(a => ts.isIdentifier(a) && a.text === param)) found = true;
+ for (const f of out) if (f.name === callee && ts.isIdentifier(args[f.index] ?? n) && (args[f.index] as ts.Identifier).text === param) found = true;
+ }
+ ts.forEachChild(n, visit);
+ };
+ if (fn.body) visit(fn.body);
+ return found;
+ };
+ for (let grew = true; grew;) {
+ grew = false;
+ for (const fn of fns) {
+ const name = fnName(fn);
+ if (!name) continue;
+ fn.parameters.forEach((p, index) => {
+ if (!ts.isIdentifier(p.name) || !SUGGESTION_PARAM.test(p.name.text) || out.some(f => f.name === name && f.index === index)) return;
+ if (forwards(fn, p.name.text)) { out.push({ name, index }); grew = true; }
+ });
+ }
+ }
+ return out;
+}
+
+/** The suggestion parameter names of the function enclosing `n` (a forwarding call is not a call site). */
+function enclosingSuggestionParams(n: ts.Node): Set<string> {
+ for (let p = n.parent; p; p = p.parent) {
+ if (isFnLike(p)) return new Set(p.parameters.flatMap(q => ts.isIdentifier(q.name) && SUGGESTION_PARAM.test(q.name.text) ? [q.name.text] : []));
+ }
+ return new Set();
+}
+
+function funnelCallSites(sf: ts.SourceFile, path: string): FunnelSite[] {
+ const funnels = fileFunnels(sf);
+ if (!funnels.length) return [];
+ const out: FunnelSite[] = [];
+ const visit = (n: ts.Node) => {
+ if (ts.isCallExpression(n) && ts.isIdentifier(n.expression)) {
+ for (const f of funnels) {
+ if (f.name !== n.expression.text) continue;
+ const arg = n.arguments[f.index];
+ if (arg && ts.isIdentifier(arg) && enclosingSuggestionParams(n).has(arg.text)) continue;
+ out.push({
+ file: path, line: sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1, funnel: f.name,
+ texts: arg ? suggestionTexts(arg, sf) : undefined, expr: arg ? arg.getText(sf) : '',
+ });
+ }
+ }
+ ts.forEachChild(n, visit);
+ };
+ visit(sf);
+ return out;
+}
+
+/** Every call site of a suggestion-forwarding funnel (`invalid`, `fail`, `usage`, …) under src/, or in the named files. */
+export function funnelSites(files?: readonly string[], root: string = ROOT): FunnelSite[] {
+ const paths = files ? files.map(f => join(root, f)) : tsFiles(join(root, 'src'));
+ return paths.flatMap(file => funnelCallSites(ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.Latest, true), rel(file)));
+}
+
/** Text args of an error constructor call: message (1) and suggestion (2); hostOnlyError's message is arg 2. */
function errorTextArgs(n: ts.CallExpression | ts.NewExpression, sf: ts.SourceFile): ts.Expression[] {
const callee = n.expression.getText(sf);
@@ -219,6 +355,17 @@ export function scan(root: string = ROOT): Hit[] {
const args = n.arguments ?? [];
if (args.length < 3 || args[2]!.getText(sf) === 'undefined') add('suggestionless-operation-error', n);
}
+ if (isFnLike(n) && sinkCalls(n, sf).length) {
+ for (const p of n.parameters) {
+ if (!ts.isIdentifier(p.name) || !SUGGESTION_PARAM.test(p.name.text)) continue;
+ if (p.initializer || p.questionToken || nullishDefaulted(n, p.name.text)) add('defaulted-suggestion', p);
+ }
+ }
+ if ((ts.isCallExpression(n) || ts.isNewExpression(n)) && SUGGESTION_ARG[n.expression.getText(sf)] !== undefined) {
+ const arg = (n.arguments ?? [])[SUGGESTION_ARG[n.expression.getText(sf)]!];
+ const t = arg ? flatText(arg, sf) : undefined;
+ if (t !== undefined && isGenericSuggestion(t)) add('generic-suggestion', arg!);
+ }
if ((ts.isCallExpression(n) || ts.isNewExpression(n)) && ERROR_CALLEE.test(n.expression.getText(sf))) {
const texts = errorTextArgs(n, sf);
for (const arg of texts) {
@@ -276,6 +423,11 @@ export function scan(root: string = ROOT): Hit[] {
ts.forEachChild(n, visit);
};
visit(sf);
+ for (const site of funnelCallSites(sf, path)) {
+ if (site.texts?.some(isGenericSuggestion)) {
+ hits.push({ rule: 'generic-suggestion', file: path, line: site.line, text: `${site.funnel}(…, ${site.expr.slice(0, 100)})` });
+ }
+ }
if (registry) {
for (const { code, line } of collectThrownCodes(sf)) {
if (!registry.has(code)) hits.push({ rule: 'unregistered-code', file: path, line, text: code });
@@ -324,6 +476,8 @@ function main(): number {
const failures: string[] = [];
for (const h of hits) {
if (h.rule === 'unregistered-code') failures.push(`${h.file}:${h.line} [unregistered-code] '${h.text}' is thrown but not registered — add a row to src/core/error-registry.ts, then bun run build:error-codes`);
+ if (h.rule === 'defaulted-suggestion') failures.push(`${h.file}:${h.line} [defaulted-suggestion] ${h.text}: a default suggestion lets call sites skip their next step — make it required and pass one at every call site`);
+ if (h.rule === 'generic-suggestion') failures.push(`${h.file}:${h.line} [generic-suggestion] ${h.text}: name the exact next step (the flag usage, the command, the value to pass), not a generic phrase`);
if (h.rule === 'code-naming') failures.push(`[code-naming] registry code '${h.text}' must be snake_case with no transport prefix`);
}
for (const rule of BASELINED_RULES) {
diff --git a/src/commands/embeddings.ts b/src/commands/embeddings.ts
index b766cc0ee7..86aeb3d69f 100644
--- a/src/commands/embeddings.ts
+++ b/src/commands/embeddings.ts
@@ -50,7 +50,9 @@ function parseEnableArgs(args: string[]): EnableOpts {
throw opError('invalid_params', `Unknown option '${a}' for gbrain embeddings enable.`, 'Run `gbrain embeddings --help` for the accepted options.');
}
const value = args[++i];
- if (!value || value.startsWith('-')) throw opError('invalid_params', `${a} requires a value.`, 'Run `gbrain embeddings --help`.');
+ if (!value || value.startsWith('-')) throw opError('invalid_params', `${a} requires a value.`, a === '--embedding-model'
+ ? 'Pass the model as provider:model, e.g. `gbrain embeddings enable --embedding-model openai:text-embedding-3-small`.'
+ : 'Pass the vector width as a positive integer, e.g. `--embedding-dimensions 1536`, or omit the flag to keep the brain\'s width.');
if (a === '--embedding-model') model = value;
else if (/^\d+$/.test(value) && Number(value) > 0) dims = Number(value);
else throw opError('invalid_params', '--embedding-dimensions must be a positive integer.', 'Pass the width of the brain\'s vector column, or omit it to use that width.');
@@ -147,7 +149,7 @@ export async function runEmbeddings(args: string[]): Promise<void> {
}
const json = args.includes('--json');
try {
- if (sub !== 'enable') throw opError('invalid_params', `Unknown embeddings subcommand '${sub}'.`, 'Run `gbrain embeddings --help`.');
+ if (sub !== 'enable') throw opError('invalid_params', `Unknown embeddings subcommand '${sub}'.`, 'The only subcommand is enable: `gbrain embeddings enable --embedding-model <provider:model>`.');
const result = await enable(parseEnableArgs(rest));
const next = (result.next_command as string[]).join(' ');
await writeStdoutFinal(json ? `${JSON.stringify(result, null, 2)}\n`
diff --git a/src/commands/eval-gate.ts b/src/commands/eval-gate.ts
index 025284b02f..39ff8b3f6d 100644
--- a/src/commands/eval-gate.ts
+++ b/src/commands/eval-gate.ts
@@ -461,11 +461,12 @@ export async function runEvalGate(engine: BrainEngine, args: string[]): Promise<
}
const json = jsonRequested(args);
- const usage: (message: string, suggestion?: string) => never = (message, suggestion = 'Example: gbrain eval gate --qrels Y.qrels.json --json') =>
+ const usage: (message: string, suggestion: string) => never = (message, suggestion) =>
process.exit(writeCliRefusal(usageError(message, suggestion), 'eval', { json }));
if (!opts.baseline && !opts.qrels) {
printHelp();
- usage('Error: at least one of --baseline or --qrels must be set');
+ usage('Error: at least one of --baseline or --qrels must be set',
+ 'Pass --qrels with a qrels fixture for the correctness gate (gbrain eval gate --qrels Y.qrels.json --json), --baseline with a published baseline for the regression gate, or both.');
}
if (opts.baseline && !existsSync(opts.baseline)) usage(`Error: baseline file not found: ${opts.baseline}`, 'Pass an existing --baseline file (write one with `gbrain bench publish`).');
diff --git a/src/commands/persistence-admin.ts b/src/commands/persistence-admin.ts
index 1386d80275..28afdc0fdf 100644
--- a/src/commands/persistence-admin.ts
+++ b/src/commands/persistence-admin.ts
@@ -3,10 +3,11 @@ import { resolve } from 'node:path';
import type { BrainEngine } from '../core/engine.ts';
import { getCliOptions } from '../core/cli-options.ts';
import { finishCliTeardown, setCliExitVerdict, writeStdoutFinal } from '../core/cli-force-exit.ts';
-import { isThinClient, loadConfig, toEngineConfig } from '../core/config.ts';
+import { isThinClient, loadConfig, toEngineConfig, type GBrainConfig } from '../core/config.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { loadMounts } from '../core/brain-registry.ts';
-import { OperationError } from '../core/ops/contract.ts';
+import { opError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
import { maybeDelegateLocalAdministration, persistenceConfigForBrain } from '../core/persistence/local-client.ts';
import { runPersistenceAdministration } from '../core/persistence/administration.ts';
import type { PersistenceAdminOperation } from '../core/persistence/admin-contract.ts';
@@ -87,7 +88,31 @@ in private local files. CLI is the trusted administration lane; stdio stays remo
A revoked CLI cannot replace itself through a running owner. Stop that owner and
explicitly register --replace locally to authorize a new principal.`;
+/**
+ * The brain-host preconditions of every local administration command: a
+ * configured brain, reached locally (an ordinary remote token is not
+ * administration authority).
+ */
+export function adminHostConfig<T extends GBrainConfig>(config: T | null | undefined, brainId: string, what: string, command: string): T {
+ if (!config) throw opError('invalid_params', 'No brain is configured. Run gbrain init first.',
+ `No brain ${brainId} is configured under this GBRAIN_HOME. Run the command on the brain host with its GBRAIN_HOME; creating a brain here with gbrain init is the user's decision.`,
+ { fix: readFix('Reports which config and brain this machine resolves, read-only.', { argv: ['gbrain', 'doctor', '--json'] }) });
+ if (isThinClient(config)) throw opError('permission_denied', `${what} runs locally on the selected brain host; an ordinary remote token is not administration authority.`,
+ `This install reaches brain ${brainId} through a remote token. Ask the user to run the same gbrain ${command} command in a terminal on the machine that hosts the brain.`,
+ { fix: { argv: ['gbrain', 'whoami', '--json'], consent: [], actor: 'agent', why: 'Shows which remote brain and principal this install uses, read-only.', requires_exclusive: false,
+ user_message: `${what} has to run on the machine that hosts this brain. Please run the same command in a terminal there.` } });
+ return config;
+}
+
type Group = 'writer' | 'local-writer';
+const GROUP_ARGV: Record<Group, string[]> = { writer: ['gbrain', 'sources', 'writer'], 'local-writer': ['gbrain', 'auth', 'local-writer'] };
+const BARE_FLAGS = ['--json', '--dry-run', '--replace', '--probe', '--confirm-quiesced', '--self-transfer', '--cleanup-dead-local-locks', '--shared-skills'];
+/** A CLI usage refusal: the exact usage in the suggestion, the group's help as the read-only fix. */
+function invalid(group: Group, message: string, suggestion: string) {
+ return opError('invalid_params', message, suggestion, {
+ fix: readFix(`Prints every ${GROUP_ARGV[group].slice(1).join(' ')} form with its flags.`, { argv: [...GROUP_ARGV[group], '--help'] }),
+ });
+}
export function parsePersistenceAdminArgs(group: Group, args: string[]): {
operation: PersistenceAdminOperation; params: Record<string, unknown>; brain?: string; json: boolean;
} {
@@ -107,17 +132,19 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
if (!token.startsWith('-')) { positional.push(token); continue; }
const equal = token.indexOf('=');
const flag = equal < 0 ? token : token.slice(0, equal);
- if (seen.has(flag)) throw new OperationError('invalid_params', `Duplicate option ${flag}.`);
+ if (seen.has(flag)) throw invalid(group, `Duplicate option ${flag}.`, `Pass ${flag} once; for a list, give one comma-separated value (e.g. --scopes read,write).`);
seen.add(flag);
- if (['--json', '--dry-run', '--replace', '--probe', '--confirm-quiesced', '--self-transfer', '--cleanup-dead-local-locks', '--shared-skills'].includes(flag)) {
- if (equal >= 0) throw new OperationError('invalid_params', `${flag} does not accept a value.`);
+ if (BARE_FLAGS.includes(flag)) {
+ if (equal >= 0) throw invalid(group, `${flag} does not accept a value.`, `Write ${flag} on its own (no =value); leave it out to keep it off.`);
if (flag === '--json') json = true;
else params[flag.slice(2).replaceAll('-', '_')] = true;
continue;
}
- if (flag !== '--brain' && !values[flag]) throw new OperationError('invalid_params', `Unknown administration option: ${flag}.`);
+ if (flag !== '--brain' && !values[flag]) throw invalid(group, `Unknown administration option: ${flag}.`,
+ `Remove ${flag}; the accepted options are --brain, ${Object.keys(values).join(', ')} and the bare flags ${BARE_FLAGS.join(', ')}.`);
const value = equal >= 0 ? token.slice(equal + 1) : args[++i];
- if (value === undefined || value.startsWith('--')) throw new OperationError('invalid_params', `${flag} requires a value.`);
+ if (value === undefined || value.startsWith('--')) throw invalid(group, `${flag} requires a value.`,
+ `Give ${flag} its value right after it, as ${flag} <value> or ${flag}=<value>.`);
if (flag === '--brain') { brain = value; continue; }
const key = values[flag];
params[key] = arrays.has(key) ? value.split(',').map(part => part.trim()).filter(Boolean)
@@ -135,12 +162,15 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
else if (verb === 'unlock') operation = 'writer_unlock';
else if (verb === 'transfer') {
const phase = positional.shift();
- if (phase !== 'prepare' && phase !== 'accept') throw new OperationError('invalid_params', 'Transfer requires prepare or accept.');
+ if (phase !== 'prepare' && phase !== 'accept') throw invalid(group, 'Transfer requires prepare or accept.',
+ 'Run gbrain sources writer transfer prepare on the current owner host first, then gbrain sources writer transfer accept on the successor with the epoch and manifest prepare printed.');
operation = phase === 'prepare' ? 'writer_transfer_prepare' : 'writer_transfer_accept';
- } else throw new OperationError('invalid_params', 'Writer administration requires status, retry-effects, claim, activate, deactivate, transfer, lock, or unlock.');
+ } else throw invalid(group, 'Writer administration requires status, retry-effects, claim, activate, deactivate, transfer, lock, or unlock.',
+ `Name the action after gbrain sources writer${verb ? ` instead of ${verb}` : ''}; start with gbrain sources writer status --json, which changes nothing.`);
const source = positional.shift();
if (source !== undefined) {
- if (params.source_id !== undefined) throw new OperationError('invalid_params', 'Specify the source once.');
+ if (params.source_id !== undefined) throw invalid(group, 'Specify the source once.',
+ `Name the source either as the argument after the action or with --source, not both (here ${source} and ${String(params.source_id)}).`);
params.source_id = source;
}
} else {
@@ -148,9 +178,11 @@ export function parsePersistenceAdminArgs(group: Group, args: string[]): {
if (verb === 'list') operation = 'local_writer_list';
else if (verb === 'register') { operation = 'local_writer_register'; params.lane = positional.shift(); }
else if (verb === 'revoke') { operation = 'local_writer_revoke'; params.id = positional.shift(); }
- else throw new OperationError('invalid_params', 'Local writer administration requires list, register, or revoke.');
+ else throw invalid(group, 'Local writer administration requires list, register, or revoke.',
+ `Name the action after gbrain auth local-writer${verb ? ` instead of ${verb}` : ''}: list (read-only), register cli|stdio, or revoke followed by a writer id from list.`);
}
- if (positional.length) throw new OperationError('invalid_params', `Unexpected argument: ${positional[0]}.`);
+ if (positional.length) throw invalid(group, `Unexpected argument: ${positional[0]}.`,
+ `Remove ${positional[0]}; this action takes at most one positional argument, and every other value goes after its flag.`);
return { operation, params, brain, json };
}
@@ -163,9 +195,8 @@ export async function runPersistenceAdminCli(group: Group, args: string[], conne
try {
const parsed = parsePersistenceAdminArgs(group, args);
const brainId = resolveBrainId(parsed.brain ?? getCliOptions().brain);
- const config = persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts());
- if (!config) throw new OperationError('invalid_params', 'No brain is configured. Run gbrain init first.');
- if (isThinClient(config)) throw new OperationError('permission_denied', 'Writer administration runs locally on the selected brain host; an ordinary remote token is not administration authority.');
+ const config = adminHostConfig(persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts()), brainId,
+ 'Writer administration', GROUP_ARGV[group].slice(1).join(' '));
const delegated = connected ? { handled: false as const } : await maybeDelegateLocalAdministration(parsed.operation, parsed.params, config,
{ timeoutMs: getCliOptions().timeoutMs ?? undefined });
let result: unknown;
diff --git a/src/commands/sources-lifecycle-args.ts b/src/commands/sources-lifecycle-args.ts
index 88a0a669ae..35920f61ae 100644
--- a/src/commands/sources-lifecycle-args.ts
+++ b/src/commands/sources-lifecycle-args.ts
@@ -1,7 +1,8 @@
/** Parse trusted source administration before connecting to the selected datastore. */
import { randomUUID } from 'node:crypto';
import { resolve } from 'node:path';
-import { OperationError } from '../core/ops/contract.ts';
+import { opError } from '../core/ops/contract.ts';
+import { readFix } from '../core/ops/op-fix.ts';
import { isValidSourceId } from '../core/source-id.ts';
import { msysToNativePath } from '../core/path-confine.ts';
import { isWriteRequestId } from '../core/persistence/types.ts';
@@ -13,7 +14,6 @@ export const SOURCE_LIFECYCLE_COMMANDS = ['add', 'remove', 'archive', 'restore',
export function isSourceLifecycleCommand(value: string): boolean {
return (SOURCE_LIFECYCLE_COMMANDS as readonly string[]).includes(value);
}
-const invalid = (message: string) => new OperationError('invalid_params', message);
const absolute = (value: string) => resolve(msysToNativePath(value));
export interface ParsedSourceLifecycle {
@@ -26,7 +26,11 @@ export interface ParsedSourceLifecycle {
export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUID()): ParsedSourceLifecycle {
const [verb, ...rest] = args;
- if (!isSourceLifecycleCommand(verb)) throw invalid('Unknown source lifecycle command.');
+ const known = isSourceLifecycleCommand(verb);
+ const invalid = (message: string, suggestion: string) => opError('invalid_params', message, suggestion, {
+ fix: readFix(`Prints the managed source administration forms and their options.`, { argv: ['gbrain', 'sources', ...(known ? [verb] : []), '--help'] }),
+ });
+ if (!known) throw invalid('Unknown source lifecycle command.', `Use one of gbrain sources ${SOURCE_LIFECYCLE_COMMANDS.join(', ')}.`);
const values = new Map<string, string>();
const flags = new Set<string>();
const positionals: string[] = [];
@@ -38,26 +42,29 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
for (let i = 0; i < rest.length; i++) {
const token = rest[i];
if (!token.startsWith('-')) { positionals.push(token); continue; }
- if (!token.startsWith('--')) throw invalid(`Unknown option: ${token}.`);
+ if (!token.startsWith('--')) throw invalid(`Unknown option: ${token}.`, `Write options in long form with two dashes (e.g. --dry-run); sources ${verb} has no short options.`);
const equal = token.indexOf('=');
const key = token.slice(2, equal < 0 ? undefined : equal);
- if (flags.has(key) || values.has(key)) throw invalid(`Duplicate option --${key}.`);
+ if (flags.has(key) || values.has(key)) throw invalid(`Duplicate option --${key}.`, `Pass --${key} once, with the one value you mean.`);
if (booleans.has(key)) {
- if (equal >= 0) throw invalid(`--${key} does not accept a value.`);
+ if (equal >= 0) throw invalid(`--${key} does not accept a value.`, `Write --${key} on its own, without =value; leave it out to keep it off.`);
flags.add(key); continue;
}
- if (!valued.has(key)) throw invalid(`Unknown option --${key}.`);
+ if (!valued.has(key)) throw invalid(`Unknown option --${key}.`, `Remove --${key}; gbrain sources ${verb} --help lists the options sources ${verb} accepts.`);
const value = equal < 0 ? rest[++i] : token.slice(equal + 1);
- if (value === undefined || value === '' || value.startsWith('--')) throw invalid(`--${key} requires a value.`);
+ if (value === undefined || value === '' || value.startsWith('--')) throw invalid(`--${key} requires a value.`, `Give --${key} its value right after it, as --${key} VALUE or --${key}=VALUE.`);
values.set(key, value);
}
const id = positionals.shift();
- if (!id && verb === 'purge') throw invalid('Managed purge requires an explicit archived source ID. Run sources archived, then sources purge <id> --confirm-destructive.');
- if (!id || !isValidSourceId(id)) throw invalid('An explicit valid source ID is required.');
+ if (!id && verb === 'purge') throw invalid('Managed purge requires an explicit archived source ID. Run sources archived, then sources purge <id> --confirm-destructive.',
+ 'Run gbrain sources archived --json to list the archived source ids, then gbrain sources purge with that id and --confirm-destructive after the user confirms.');
+ if (!id || !isValidSourceId(id)) throw invalid('An explicit valid source ID is required.',
+ `Name the source id right after sources ${verb}: 1-32 lowercase letters, digits and inner hyphens, e.g. gbrain sources ${verb} notes.`);
const requestId = values.get('request-id') ?? generatedId;
const incarnation = values.get('expected-incarnation');
if (!isWriteRequestId(requestId) || incarnation !== undefined && !isWriteRequestId(incarnation)) {
- throw invalid('--request-id and --expected-incarnation must be UUIDs.');
+ throw invalid('--request-id and --expected-incarnation must be UUIDs.',
+ `Pass --request-id and --expected-incarnation as UUIDs exactly as an earlier sources ${verb} printed them; omit --request-id to start a new request.`);
}
const dryRun = flags.has('dry-run');
const params: Record<string, unknown> = { action: verb === 'set-path' ? 'rebind' : verb,
@@ -68,16 +75,20 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
: new Set([...common, ...(verb === 'set-path' ? ['path', 'force'] : []),
...(['remove', 'purge'].includes(verb) ? ['yes', 'confirm-destructive', 'keep-storage'] : []),
...(verb === 'restore' ? ['no-federate', 'refederate'] : [])]);
- for (const key of [...values.keys(), ...flags]) if (!allowed.has(key)) throw invalid(`--${key} does not apply to sources ${verb}.`);
+ for (const key of [...values.keys(), ...flags]) if (!allowed.has(key)) throw invalid(`--${key} does not apply to sources ${verb}.`,
+ `Remove --${key}; sources ${verb} accepts ${[...allowed].map(name => `--${name}`).join(', ')}.`);
if (verb === 'set-path') {
- if (positionals.length && values.has('path')) throw invalid('Specify the set-path target once.');
+ if (positionals.length && values.has('path')) throw invalid('Specify the set-path target once.',
+ `Give the successor directory once: gbrain sources set-path ${id} DIRECTORY, or --path DIRECTORY, not both.`);
const target = positionals.shift() ?? values.get('path');
- if (!target) throw invalid('set-path requires the verified successor directory.');
+ if (!target) throw invalid('set-path requires the verified successor directory.',
+ `Pass the directory that now holds source ${id}'s checkout: gbrain sources set-path ${id} DIRECTORY (--clear clears a connector source's stale local_path).`);
params.path = absolute(target);
}
- if (positionals.length) throw invalid(`Unexpected argument: ${positionals[0]}.`);
+ if (positionals.length) throw invalid(`Unexpected argument: ${positionals[0]}.`, `Remove ${positionals[0]}; sources ${verb} takes only the source id${verb === 'set-path' ? ' and the directory' : ''} as arguments.`);
if (verb === 'restore') {
- if (flags.has('no-federate') && flags.has('refederate')) throw invalid('Choose one federation setting.');
+ if (flags.has('no-federate') && flags.has('refederate')) throw invalid('Choose one federation setting.',
+ 'Pass either --no-federate or --refederate, not both; restore refederates by default.');
params.refederate = !flags.has('no-federate');
}
if (verb === 'remove' || verb === 'purge') {
@@ -86,22 +97,28 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
}
if (verb !== 'add') return { operation: 'source_lifecycle', params, brain: values.get('brain'), legacyOnly: false, json: flags.has('json') };
- if (flags.has('federated') && flags.has('no-federated')) throw invalid('Choose one federation setting.');
+ if (flags.has('federated') && flags.has('no-federated')) throw invalid('Choose one federation setting.', 'Pass either --federated or --no-federated, not both.');
const kind = values.get('kind');
- if (kind !== undefined && !['google', 'github'].includes(kind)) throw invalid('Source kind must be github or google.');
- if ([values.has('path'), values.has('url'), kind !== undefined].filter(Boolean).length > 1) throw invalid('--path, --url and --kind are mutually exclusive.');
- const kindOptions = ['account', 'access', 'token-command', 'services', 'history-days', 'calendar-id', 'scope', 'repos', 'dir', 'app-id', 'app-pem', 'app-install', 'token-env'];
- for (const key of kindOptions) if (values.has(key) && !kind) throw invalid(`--${key} requires --kind github or google.`);
- for (const key of ['account', 'access', 'token-command', 'services', 'history-days', 'calendar-id']) {
- if (values.has(key) && kind !== 'google') throw invalid(`--${key} requires --kind google.`);
+ if (kind !== undefined && !['google', 'github'].includes(kind)) throw invalid('Source kind must be github or google.',
+ 'Pass --kind github or --kind google; a directory or Git remote source uses --path or --url instead of --kind.');
+ if ([values.has('path'), values.has('url'), kind !== undefined].filter(Boolean).length > 1) throw invalid('--path, --url and --kind are mutually exclusive.',
+ 'Give exactly one of --path (a local directory), --url (an https Git remote) or --kind (github or google).');
+ const googleOnly = ['account', 'access', 'token-command', 'services', 'history-days', 'calendar-id'];
+ const githubOnly = ['scope', 'repos', 'app-id', 'app-pem', 'app-install'];
+ const kindOptions = [...googleOnly, ...githubOnly, 'dir', 'token-env'];
+ for (const key of kindOptions) if (values.has(key) && !kind) throw invalid(`--${key} requires --kind github or google.`,
+ `Add ${googleOnly.includes(key) ? '--kind google' : githubOnly.includes(key) ? '--kind github' : '--kind github or --kind google'} for --${key}, or remove --${key}.`);
+ for (const key of googleOnly) {
+ if (values.has(key) && kind !== 'google') throw invalid(`--${key} requires --kind google.`, `--${key} configures a Google source: use --kind google, or remove --${key} from this ${kind} source.`);
}
- for (const key of ['scope', 'repos', 'app-id', 'app-pem', 'app-install']) {
- if (values.has(key) && kind !== 'github') throw invalid(`--${key} requires --kind github.`);
+ for (const key of githubOnly) {
+ if (values.has(key) && kind !== 'github') throw invalid(`--${key} requires --kind github.`, `--${key} configures a GitHub source: use --kind github, or remove --${key} from this ${kind} source.`);
}
const number = (key: string, fallback?: number): number | undefined => {
if (!values.has(key)) return fallback;
const value = Number(values.get(key));
- if (!Number.isSafeInteger(value) || value <= 0) throw invalid(`--${key} must be a positive integer.`);
+ if (!Number.isSafeInteger(value) || value <= 0) throw invalid(`--${key} must be a positive integer.`,
+ `Pass --${key} as a positive whole number, e.g. --${key} ${key === 'history-days' ? 90 : 123456}.`);
return value;
};
const opts: AddSourceOpts = { id, requestId, expectedIncarnation: incarnation,
@@ -112,9 +129,11 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
const scope = values.get('scope') ?? 'auto';
const repos = (values.get('repos') ?? '').split(',').map(value => value.trim()).filter(Boolean);
if (!['auto', 'repos'].includes(scope) || scope === 'repos' && !repos.length || repos.some(repo => !isValidRepoName(repo))) {
- throw invalid('GitHub scope must be auto or repos; repos requires valid owner/name entries.');
+ throw invalid('GitHub scope must be auto or repos; repos requires valid owner/name entries.',
+ 'Pass --scope auto, or --scope repos with --repos as comma-separated owner/name entries (e.g. --repos acme-example/notes).');
}
- if (values.has('app-id') !== values.has('app-pem')) throw invalid('--app-id and --app-pem are required together.');
+ if (values.has('app-id') !== values.has('app-pem')) throw invalid('--app-id and --app-pem are required together.',
+ `Pass both --app-id and --app-pem for a GitHub App, or neither to authenticate with --token-env (default GH_TOKEN).`);
opts.github = { tokenEnv: values.get('token-env') ?? 'GH_TOKEN', handle: '', scope: scope as 'auto' | 'repos', repos,
dir: absolute(values.get('dir') ?? defaultCloneDir(`${id}-github`)), involvement: true,
appId: number('app-id'), appPemPath: values.has('app-pem') ? absolute(values.get('app-pem')!) : undefined,
@@ -124,10 +143,12 @@ export function parseSourceLifecycleArgs(args: string[], generatedId = randomUUI
const account = values.get('account')?.trim().toLowerCase();
const services = (values.get('services') ?? 'gmail,calendar,contacts').split(',').map(value => value.trim().toLowerCase()).filter(Boolean);
const access = values.get('access') ?? 'vault';
- if (!account || !services.length || services.some(service => !(ALL_GOOGLE_SERVICES as readonly string[]).includes(service))) throw invalid('Google requires --account and valid --services.');
+ if (!account || !services.length || services.some(service => !(ALL_GOOGLE_SERVICES as readonly string[]).includes(service))) throw invalid('Google requires --account and valid --services.',
+ `Pass --account with the Google account email and --services as a comma-separated subset of ${ALL_GOOGLE_SERVICES.join(',')}.`);
if (!['vault', 'command', 'env'].includes(access) || access === 'command' && !values.has('token-command')
|| access === 'env' && !values.has('token-env') || access === 'vault' && (values.has('token-command') || values.has('token-env'))) {
- throw invalid('Google access must be vault, command with --token-command, or env with --token-env.');
+ throw invalid('Google access must be vault, command with --token-command, or env with --token-env.',
+ 'Use --access vault (the default, with no token flags), --access command with --token-command, or --access env with --token-env.');
}
opts.google = { account, services, historyDays: number('history-days', 90)!, calendarId: values.get('calendar-id') ?? DEFAULT_CALENDAR_ID,
dir: absolute(values.get('dir') ?? defaultCloneDir(`${id}-google`)), access: access as 'vault' | 'command' | 'env',
diff --git a/src/commands/sources-lifecycle.ts b/src/commands/sources-lifecycle.ts
index a5dbc08445..83823ef7ba 100644
--- a/src/commands/sources-lifecycle.ts
+++ b/src/commands/sources-lifecycle.ts
@@ -2,7 +2,7 @@
import type { BrainEngine } from '../core/engine.ts';
import { OperationError } from '../core/ops/contract.ts';
import { getCliOptions } from '../core/cli-options.ts';
-import { isThinClient, loadConfig } from '../core/config.ts';
+import { loadConfig } from '../core/config.ts';
import { resolveBrainId } from '../core/brain-resolver.ts';
import { loadMounts } from '../core/brain-registry.ts';
import { writeStdoutFinal, setCliExitVerdict } from '../core/cli-force-exit.ts';
@@ -12,6 +12,7 @@ import { managedPersistenceEnabled } from '../core/persistence/ownership.ts';
import { assertTopologyCommitted } from '../core/persistence/managed-sources.ts';
import { parseSourceLifecycleArgs, type ParsedSourceLifecycle } from './sources-lifecycle-args.ts';
import { reportPersistenceCliError } from './persistence-delegate.ts';
+import { adminHostConfig } from './persistence-admin.ts';
export const SOURCE_LIFECYCLE_HELP = `Managed source administration:
gbrain sources add <id> [--path <directory> | --url <https-url> | --kind github|google]
@@ -63,9 +64,8 @@ export async function runSourceLifecycleCli(args: string[], getEngine: () => Pro
try { parsed = parseSourceLifecycleArgs(args); } catch (error) { parseError = error; }
// Global CLI routing has already consumed --brain; parsing retains it for direct callers too.
const brainId = resolveBrainId(parsed?.brain ?? getCliOptions().brain);
- const config = persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts());
- if (!config) throw new OperationError('invalid_params', 'No brain is configured. Run gbrain init first.');
- if (isThinClient(config)) throw new OperationError('permission_denied', 'Source administration runs locally on the selected brain host; an ordinary remote token is not administration authority.');
+ const config = adminHostConfig(persistenceConfigForBrain(loadConfig(), brainId, brainId === 'host' ? [] : loadMounts()), brainId,
+ 'Source administration', `sources ${args[0] ?? ''}`.trim());
if (args[0] === 'set-path' && args.includes('--clear')) {
const { runSetPath } = await import('./sources-set-path.ts');
await runSetPath(await getEngine(), args.slice(1));
diff --git a/src/core/persistence/administration.ts b/src/core/persistence/administration.ts
index d8ccac259c..febfcff40f 100644
--- a/src/core/persistence/administration.ts
+++ b/src/core/persistence/administration.ts
@@ -18,48 +18,70 @@ import { assertWriterAdminUnlocked, readWriterAdminLock, setWriterAdminLock } fr
import { listBlockingEffects } from './blocking-effects.ts';
import { listWriterVersions } from './writer-versions.ts';
import { readFix, trustedCliRequired } from '../ops/op-fix.ts';
+import type { Action } from '../agent-output.ts';
-const invalid = (message: string, suggestion = 'Correct that parameter and run the command again; gbrain sources writer --help and gbrain auth local-writer --help list each option and its accepted values.') =>
- opError('invalid_params', message, suggestion);
+const invalid = (message: string, suggestion: string, fix?: Action) =>
+ opError('invalid_params', message, suggestion, fix ? { fix } : {});
+const sourcesListFix = (why: string) => readFix(why, { argv: ['gbrain', 'sources', 'list', '--json'] });
+const writerListFix = readFix('Lists the local writer registrations and their ids, read-only.', { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'] });
+const LIST_EXAMPLES: Record<string, string> = { source_ids: 'default,notes', scopes: 'read,write', allowed_operations: 'search,get_page', slug_prefixes: 'people/,companies/' };
+const cliFlag = (key: string) => `--${key.replaceAll('_', '-')}`;
function source(value: unknown): string {
- if (typeof value !== 'string' || !isValidSourceId(value)) throw invalid('An explicit active source ID is required.', 'Name the source explicitly with its id; gbrain sources list --json shows the active sources.');
+ if (typeof value !== 'string' || !isValidSourceId(value)) throw invalid('An explicit active source ID is required.', 'Name the source explicitly with its id; gbrain sources list --json shows the active sources.',
+ sourcesListFix('Lists the active source ids, read-only.'));
return value;
}
function path(value: unknown): string {
- if (typeof value !== 'string' || !isAbsolute(value) || value.includes('\0')) throw invalid('path must be an absolute directory path on this host.');
+ if (typeof value !== 'string' || !isAbsolute(value) || value.includes('\0')) throw invalid('path must be an absolute directory path on this host.',
+ 'Pass --path with an absolute directory on this host, e.g. --path /srv/brain/notes; a relative path or one containing a NUL byte is refused.');
return value;
}
-function uuid(value: unknown): string {
- if (!isWriteRequestId(value)) throw invalid('A valid local writer UUID is required.');
+function uuid(value: unknown, message: string, suggestion: string, fix?: Action): string {
+ if (!isWriteRequestId(value)) throw invalid(message, suggestion, fix);
return value;
}
function strings(value: unknown, key: string): string[] {
- if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || !item)) throw invalid(`${key} must be an array of non-empty strings.`);
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || !item)) throw invalid(`${key} must be an array of non-empty strings.`,
+ `Pass ${cliFlag(key)} as a comma-separated list with no empty entries, e.g. ${cliFlag(key)} ${LIST_EXAMPLES[key] ?? 'a,b'}.`);
return [...new Set(value)];
}
+function bool(params: Record<string, unknown>, key: string): void {
+ if (params[key] !== undefined && typeof params[key] !== 'boolean') throw invalid(`${key} must be a boolean.`,
+ `Send ${key} as a JSON boolean (true or false); on the CLI it is the bare flag ${cliFlag(key)}, which takes no value.`);
+}
function keys(params: Record<string, unknown>, allowed: string[]) {
const unknown = Object.keys(params).filter(key => !allowed.includes(key));
- if (unknown.length) throw invalid(`Unsupported administration parameters: ${unknown.join(', ')}.`);
- if (params.dry_run !== undefined && typeof params.dry_run !== 'boolean') throw invalid('dry_run must be a boolean.');
+ if (unknown.length) throw invalid(`Unsupported administration parameters: ${unknown.join(', ')}.`,
+ `Remove ${unknown.join(', ')}; this operation accepts ${allowed.length ? allowed.join(', ') : 'no parameters'}. A caller on another gbrain version sends the parameters of its own version: run the same gbrain version on both sides.`);
+ bool(params, 'dry_run');
}
async function registrationGrant(engine: BrainEngine, params: Record<string, unknown>): Promise<LocalGrant> {
const sourceIds = params.source_ids === undefined ? ['*'] : strings(params.source_ids, 'source_ids');
- if (!sourceIds.length || sourceIds.includes('*') && sourceIds.length !== 1 || sourceIds.some(id => id !== '*' && !isValidSourceId(id))) throw invalid('source_ids must name active sources, or contain only "*".');
+ if (!sourceIds.length || sourceIds.includes('*') && sourceIds.length !== 1 || sourceIds.some(id => id !== '*' && !isValidSourceId(id))) throw invalid('source_ids must name active sources, or contain only "*".',
+ 'Pass --source-ids as a comma-separated list of active source ids, or omit it to grant every source; "*" cannot be combined with ids.',
+ sourcesListFix('Lists the active source ids a grant can name, read-only.'));
if (!sourceIds.includes('*')) {
const rows = await engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id=ANY($1::text[]) AND NOT archived', [sourceIds]);
- if (rows.length !== sourceIds.length) throw invalid('Every source_ids entry must name an active source.');
+ const missing = sourceIds.filter(id => !rows.some(row => row.id === id));
+ if (missing.length) throw invalid('Every source_ids entry must name an active source.',
+ `${missing.join(', ')} ${missing.length === 1 ? 'is' : 'are'} not an active source on this brain: drop ${missing.length === 1 ? 'it' : 'them'} from --source-ids, or add or restore the source first.`,
+ sourcesListFix('Lists the active source ids a grant can name, read-only.'));
}
const scopes = params.scopes === undefined ? ['read', 'write'] : strings(params.scopes, 'scopes');
- if (!scopes.length || scopes.some(scope => !['read', 'write', 'skill_editor', 'skills_member_self'].includes(scope))) throw invalid('Local writer scopes may contain read, write, skill_editor and skills_member_self only.');
+ if (!scopes.length || scopes.some(scope => !['read', 'write', 'skill_editor', 'skills_member_self'].includes(scope))) throw invalid('Local writer scopes may contain read, write, skill_editor and skills_member_self only.',
+ 'Pass --scopes as a comma-separated subset of read, write, skill_editor and skills_member_self, e.g. --scopes read,write.');
const operations = params.allowed_operations === undefined ? null : strings(params.allowed_operations, 'allowed_operations');
if (scopes.some(scope => scope === 'skill_editor' || scope === 'skills_member_self') && !operations?.length) {
- throw invalid('Shared-skill capabilities require an explicit nonempty allowed_operations snapshot.');
+ throw invalid('Shared-skill capabilities require an explicit nonempty allowed_operations snapshot.',
+ 'Add --allowed-operations with the exact comma-separated operations this lane may call, or drop skill_editor and skills_member_self from --scopes.');
}
if (operations) {
const { operations: registry } = await import('../operations.ts');
- if (operations.some(name => !registry.some(op => op.name === name && !op.localOnly && operationScopesAllowed(scopes, op)))) {
- throw invalid('allowed_operations must name public operations within the requested read/write scope.');
+ const outside = operations.filter(name => !registry.some(op => op.name === name && !op.localOnly && operationScopesAllowed(scopes, op)));
+ if (outside.length) {
+ throw invalid('allowed_operations must name public operations within the requested read/write scope.',
+ `Remove ${outside.join(', ')} from --allowed-operations, or widen --scopes (now ${scopes.join(',')}) to the scope each needs; local-only operations can never be granted.`);
}
}
const slugPrefixes = params.slug_prefixes === undefined ? null : strings(params.slug_prefixes, 'slug_prefixes');
@@ -73,6 +95,9 @@ export const CLAIM_BEFORE_ACTIVATION_NOTICE = 'Persistence is not activated. Aft
+ 'file-writing maintenance) refuse while the checkout is managed. Stop older writers, review gbrain sources writer status, '
+ 'then activate deliberately.';
+const transferStatusFix = (sourceId: string) =>
+ readFix(`Shows source ${sourceId}'s owner binding and prepared transfer, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', sourceId, '--json'] });
+
export async function runPersistenceAdministration(engine: BrainEngine, operation: PersistenceAdminOperation,
params: Record<string, unknown>, config?: GBrainConfig, embeddingRetryPolicy: 'owner' | 'mounted_database' = 'owner'): Promise<Record<string, unknown>> {
if (operation === 'writer_reconcile_preview') return (await import('./reconcile.ts')).runReconcilePreview(engine, params);
@@ -83,12 +108,14 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
const writer = currentVerifiedLocalWriter();
if (!writer || writer.remote || writer.principal.kind !== 'local_cli') throw trustedCliRequired('Company source administration requires an authenticated local CLI registration.');
keys(params, ['brain_id', 'source_id', 'path', 'plan', 'request_id']);
- if (typeof params.brain_id !== 'string' || !params.brain_id.trim()) throw invalid('An explicit brain_id is required.');
+ if (typeof params.brain_id !== 'string' || !params.brain_id.trim()) throw invalid('An explicit brain_id is required.',
+ 'Name the destination brain with --brain on gbrain sources connect (host, or a mounted brain id); gbrain mounts list --json shows the mounted brains.');
const destination = { brainId: params.brain_id, sourceId: source(params.source_id), remote: false };
const runtime = await import('../company-brain/runtime.ts');
if (operation === 'company_brain_resume') return { ...await runtime.resumeCompanyBrain(engine, destination) };
const input = { ...destination, path: path(params.path), plan: params.plan as import('../company-brain/types.ts').CompanyBrainPlan,
- ...(params.request_id === undefined ? {} : { requestId: uuid(params.request_id) }) };
+ ...(params.request_id === undefined ? {} : { requestId: uuid(params.request_id, 'A valid connect request UUID is required.',
+ 'Pass --request-id with the UUID the earlier connect preview printed, or omit it to start a new connect request.') }) };
if (operation === 'company_brain_preview') return { ...await runtime.previewCompanyBrain(engine, input) };
return { ...await runtime.connectCompanyBrain(engine, input) };
}
@@ -113,9 +140,11 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
if (operation === 'writer_embed_facts') return (await import('./embed-facts-administration.ts')).runAuthenticatedFactEmbedding(engine, params, config);
if (operation === 'writer_retry_effects') {
keys(params, ['source_id', 'request_id', 'dry_run']);
- if (params.dry_run !== undefined && typeof params.dry_run !== 'boolean') throw invalid('dry_run must be a boolean.');
if (!isWriteRequestId(params.request_id)) throw invalid('A valid original write request UUID is required.',
- 'Pass --request-id with the original write\'s request id (a UUID); gbrain sources writer status for that source lists blocked effects with their request ids.');
+ 'Pass --request-id with the original write\'s request id (a UUID); gbrain sources writer status for that source lists blocked effects with their request ids.',
+ typeof params.source_id === 'string' && isValidSourceId(params.source_id)
+ ? readFix(`Lists source ${params.source_id}'s blocked effects with their request ids, read-only.`, { argv: ['gbrain', 'sources', 'writer', 'status', params.source_id, '--json'] })
+ : undefined);
return (await import('./effect-retry.ts')).retryRequestEffects(engine, source(params.source_id), params.request_id, params.dry_run === true, config, embeddingRetryPolicy);
}
if (operation === 'source_add' || operation === 'source_lifecycle') {
@@ -128,11 +157,13 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
keys(params, ['options', 'request_id', 'dry_run', 'legacy_hardening']);
if (params.legacy_hardening !== undefined) throw new OperationError('writer_coordinator_required',
'Source creation cannot install legacy Git hardening on a managed worktree.', 'Create the source without --pat-file.');
- if (!params.options || typeof params.options !== 'object' || Array.isArray(params.options)) throw invalid('Source add requires typed options.');
+ if (!params.options || typeof params.options !== 'object' || Array.isArray(params.options)) throw invalid('Source add requires typed options.',
+ 'Add the source with gbrain sources add, which builds the typed options; a resident-proxy caller sends params.options as a JSON object.');
const { managedSourceAddInput } = await import('./managed-sources.ts');
const { runManagedSourceLifecycle } = await import('./source-lifecycle.ts');
const options = params.options as import('../sources-ops.ts').AddSourceOpts;
- if (options.requestId !== params.request_id || !isWriteRequestId(params.request_id)) throw invalid('Source add request identity must match its options.');
+ if (options.requestId !== params.request_id || !isWriteRequestId(params.request_id)) throw invalid('Source add request identity must match its options.',
+ 'Send one UUID as both params.request_id and options.requestId; gbrain sources add sets both from one request id, so run the add through it.');
return runManagedSourceLifecycle(engine, { ...managedSourceAddInput(options), dryRun: params.dry_run === true });
}
if(operation==='source_lifecycle') {
@@ -147,7 +178,7 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
}
if (operation === 'writer_status') {
keys(params, ['source_id', 'probe']);
- if (params.probe !== undefined && typeof params.probe !== 'boolean') throw invalid('probe must be a boolean.');
+ bool(params, 'probe');
const adminState = await writerAdminState(engine);
const diagnostics = await writerDiagnostics(engine);
const bindings = await engine.executeRaw(`SELECT b.source_id,b.source_incarnation,b.worktree_id,b.relative_path,b.topology_generation::text AS topology_generation,
@@ -196,9 +227,11 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
}
if (operation === 'writer_activate') {
keys(params, ['confirm_quiesced', 'dry_run', 'shared_skills', 'admin_intent', 'expected_state', 'cleanup_dead_local_locks']);
- if (params.cleanup_dead_local_locks !== undefined && typeof params.cleanup_dead_local_locks !== 'boolean') throw invalid('cleanup_dead_local_locks must be a boolean.');
- if (params.confirm_quiesced !== true) throw invalid('Activation requires --confirm-quiesced after upgrading and stopping older writers on every host.');
- if (params.shared_skills !== undefined && typeof params.shared_skills !== 'boolean') throw invalid('shared_skills must be a boolean.');
+ bool(params, 'cleanup_dead_local_locks');
+ if (params.confirm_quiesced !== true) throw invalid('Activation requires --confirm-quiesced after upgrading and stopping older writers on every host.',
+ 'Upgrade and stop older writers on every host, review gbrain sources writer status --json, then run gbrain sources writer activate --confirm-quiesced with --admin-intent writer_activate and --expected-state set to the admin_state that status printed.',
+ readFix('Shows writer topology, blocking effects and the admin_state activation must name, read-only.', { argv: ['gbrain', 'sources', 'writer', 'status', '--json'] }));
+ bool(params, 'shared_skills');
const expectedState = await requireWriterAdminIntent(engine, operation, params);
if (params.shared_skills === true) {
const { activateSharedSkillPersistence } = await import('./skill-activation.ts');
@@ -211,7 +244,9 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
...(params.dry_run ? { dry_run: true, action: operation } : {}) };
}
if (operation === 'writer_deactivate') {
- if (params.source_id !== undefined) throw invalid('Deactivate is brain-wide: it converts every source of this brain back to classic mode. Omit the <source> argument.');
+ if (params.source_id !== undefined) throw invalid('Deactivate is brain-wide: it converts every source of this brain back to classic mode. Omit the <source> argument.',
+ 'Run gbrain sources writer deactivate with no source; --dry-run first lists every source it converts and each blocker.',
+ readFix('Previews the brain-wide deactivation and its blockers; changes nothing.', { argv: ['gbrain', 'sources', 'writer', 'deactivate', '--dry-run', '--json'] }));
keys(params, ['dry_run', 'admin_intent', 'expected_state', 'request_id']);
const { deactivatePersistence } = await import('./deactivation.ts');
if (params.dry_run === true) {
@@ -230,12 +265,13 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
error.suggestion = `The current admin_state is ${await writerAdminState(engine)}. Review gbrain sources writer status --json, then rerun with --expected-state <that admin_state>.`;
throw error;
}
- return { ...await deactivatePersistence(engine, { expectedState, requestId: params.request_id === undefined ? undefined : uuid(params.request_id) }) };
+ return { ...await deactivatePersistence(engine, { expectedState, requestId: params.request_id === undefined ? undefined
+ : uuid(params.request_id, 'A valid deactivation request UUID is required.', 'Pass --request-id as a UUID, or omit it and gbrain generates one.') }) };
}
if (operation === 'writer_transfer_prepare') {
keys(params, ['source_id', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer']);
const sourceId = source(params.source_id);
- if (params.self_transfer !== undefined && typeof params.self_transfer !== 'boolean') throw invalid('self_transfer must be a boolean.');
+ bool(params, 'self_transfer');
if (params.dry_run) {
const binding = await getWorktreeBinding(engine, sourceId, existingLocalHostId());
if (!binding || binding.owner_host_id !== existingLocalHostId() || !binding.local_path) {
@@ -253,11 +289,13 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
}
if (operation === 'writer_transfer_accept') {
keys(params, ['source_id', 'path', 'expected_epoch', 'manifest', 'dry_run', 'admin_intent', 'expected_state', 'self_transfer']);
- if (params.self_transfer !== undefined && typeof params.self_transfer !== 'boolean') throw invalid('self_transfer must be a boolean.');
+ bool(params, 'self_transfer');
const sourceId = source(params.source_id), root = path(params.path);
if (typeof params.expected_epoch !== 'string' || !/^[1-9]\d{0,18}$/.test(params.expected_epoch)
- || BigInt(params.expected_epoch) > 9_223_372_036_854_775_807n) throw invalid('expected_epoch must be the prepared positive owner epoch.');
- if (typeof params.manifest !== 'string' || !/^[a-f0-9]{64}$/.test(params.manifest)) throw invalid('manifest must be the prepared SHA-256 manifest digest.');
+ || BigInt(params.expected_epoch) > 9_223_372_036_854_775_807n) throw invalid('expected_epoch must be the prepared positive owner epoch.',
+ `Pass --expected-epoch with the owner_epoch that gbrain sources writer transfer prepare ${sourceId} printed (a positive integer).`, transferStatusFix(sourceId));
+ if (typeof params.manifest !== 'string' || !/^[a-f0-9]{64}$/.test(params.manifest)) throw invalid('manifest must be the prepared SHA-256 manifest digest.',
+ `Pass --manifest with the 64-character manifest digest that gbrain sources writer transfer prepare ${sourceId} printed.`, transferStatusFix(sourceId));
if (params.dry_run && params.self_transfer === true) await acceptWriterTransfer(engine, sourceId, root, params.expected_epoch, params.manifest, existingLocalHostId()!, undefined, { selfTransfer: true, dryRun: true });
if (params.dry_run) return { dry_run: true, action: operation, source_id: sourceId, current: await getWorktreeBinding(engine, sourceId, existingLocalHostId()),
manifest_matches: worktreeManifest(root, { progress: humanManifestProgress() }).digest === params.manifest, expected_epoch: params.expected_epoch };
@@ -268,16 +306,19 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
if (operation === 'local_writer_list') {
keys(params, ['limit', 'before']);
const limit = params.limit ?? 100;
- if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > 1000) throw invalid('limit must be an integer from 1 to 1000.');
- const before = params.before === undefined ? null : uuid(params.before);
+ if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > 1000) throw invalid('limit must be an integer from 1 to 1000.',
+ 'Pass --limit as an integer from 1 to 1000, e.g. gbrain auth local-writer list --limit 100.');
+ const before = params.before === undefined ? null : uuid(params.before, 'A valid local writer UUID is required.',
+ 'Pass --before with the next value the previous gbrain auth local-writer list page printed (a writer UUID).', writerListFix);
const rows = await engine.executeRaw<{ id: string }>(`SELECT id,lane,grant_ceiling,revoked_at,created_at FROM persistence_local_writers
WHERE ($1::uuid IS NULL OR id<$1::uuid) ORDER BY id DESC LIMIT $2`, [before, limit + 1]);
return { writers: rows.slice(0, limit), next: rows.length > limit ? rows[limit - 1].id : null };
}
if (operation === 'local_writer_register') {
keys(params, ['lane', 'source_ids', 'scopes', 'allowed_operations', 'slug_prefixes', 'replace', 'dry_run']);
- if (params.lane !== 'cli' && params.lane !== 'stdio') throw invalid('lane must be cli or stdio.');
- if (params.replace !== undefined && typeof params.replace !== 'boolean') throw invalid('replace must be a boolean.');
+ if (params.lane !== 'cli' && params.lane !== 'stdio') throw invalid('lane must be cli or stdio.',
+ 'Name the lane right after register: gbrain auth local-writer register cli (trusted administration) or gbrain auth local-writer register stdio (MCP over stdio).');
+ bool(params, 'replace');
const grant = await registrationGrant(engine, params);
// Register is idempotent. Changing an existing ceiling is an explicit replacement.
if (!params.replace) {
@@ -298,9 +339,11 @@ export async function runPersistenceAdministration(engine: BrainEngine, operatio
// Credentials remain in the private local file, never in output or on the socket.
return { registered: true, id: local.id, lane: local.lane, grant, replaced: params.replace === true };
}
- if (operation !== 'local_writer_revoke') throw invalid('Unknown local administration operation.');
+ if (operation !== 'local_writer_revoke') throw invalid('Unknown local administration operation.',
+ `This brain host does not know ${operation}: run the same gbrain version on the caller and the host (gbrain --version on both).`);
keys(params, ['id', 'dry_run']);
- const id = uuid(params.id);
+ const id = uuid(params.id, 'A valid local writer UUID is required.',
+ 'Pass the id of the writer to revoke exactly as gbrain auth local-writer list --json prints it (a UUID).', writerListFix);
if (params.dry_run) return { dry_run: true, action: 'local_writer_revoke', id };
return { id, revoked: await revokeLocalWriter(engine, id) };
}
diff --git a/test/eval-gate.test.ts b/test/eval-gate.test.ts
index 9569aaecdd..b9c6bc55ad 100644
--- a/test/eval-gate.test.ts
+++ b/test/eval-gate.test.ts
@@ -21,6 +21,7 @@ import { join } from 'node:path';
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
import { resetPgliteState } from './helpers/reset-pglite.ts';
import { runEvalGate } from '../src/commands/eval-gate.ts';
+import { expectFunnelSuggestions } from './helpers/agent-envelope.ts';
import {
BASELINE_FILE_SCHEMA_VERSION,
DEFAULT_THRESHOLDS,
@@ -121,6 +122,11 @@ function withExitCapture<T>(fn: () => Promise<T>): Promise<{ exitCode: number |
}
describe('eval gate: usage errors', () => {
+ test('every usage() refusal names its own next step', () => {
+ expectFunnelSuggestions('src/commands/eval-gate.ts', 'usage', 7);
+ });
+
+
test('no flags → exit 2 with usage error', async () => {
const out = await withExitCapture(() => runEvalGate(engine, []));
expect(out.exitCode).toBe(2);
diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-optional-hint/src/core/error-registry.ts b/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-optional-hint/src/core/error-registry.ts
new file mode 100644
index 0000000000..b70481c8a7
--- /dev/null
+++ b/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-optional-hint/src/core/error-registry.ts
@@ -0,0 +1,3 @@
+export const CODES = {
+ invalid_params: { class: 'caller', summary: 'x' },
+} as const;
diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-optional-hint/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-optional-hint/src/core/ops/sample.ts
new file mode 100644
index 0000000000..91330ab24e
--- /dev/null
+++ b/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-optional-hint/src/core/ops/sample.ts
@@ -0,0 +1,4 @@
+declare class OperationError extends Error { constructor(...args: unknown[]); }
+export function fail(code: string, message: string, nextHint?: string): never {
+ throw new OperationError(code, message, nextHint ?? 'Pass a slug.');
+}
diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-suggestion/src/core/error-registry.ts b/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-suggestion/src/core/error-registry.ts
new file mode 100644
index 0000000000..b70481c8a7
--- /dev/null
+++ b/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-suggestion/src/core/error-registry.ts
@@ -0,0 +1,3 @@
+export const CODES = {
+ invalid_params: { class: 'caller', summary: 'x' },
+} as const;
diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-suggestion/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-suggestion/src/core/ops/sample.ts
new file mode 100644
index 0000000000..a690e96439
--- /dev/null
+++ b/test/fixtures/guards/check-agent-contract.ts/bad-defaulted-suggestion/src/core/ops/sample.ts
@@ -0,0 +1,3 @@
+declare function opError(...args: unknown[]): Error;
+const invalid = (message: string, suggestion = 'Correct that parameter.') => opError('invalid_params', message, suggestion);
+export function f() { throw invalid('Bad input.'); }
diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-generic-funnel/src/core/error-registry.ts b/test/fixtures/guards/check-agent-contract.ts/bad-generic-funnel/src/core/error-registry.ts
new file mode 100644
index 0000000000..b70481c8a7
--- /dev/null
+++ b/test/fixtures/guards/check-agent-contract.ts/bad-generic-funnel/src/core/error-registry.ts
@@ -0,0 +1,3 @@
+export const CODES = {
+ invalid_params: { class: 'caller', summary: 'x' },
+} as const;
diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-generic-funnel/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/bad-generic-funnel/src/core/ops/sample.ts
new file mode 100644
index 0000000000..a9a005c765
--- /dev/null
+++ b/test/fixtures/guards/check-agent-contract.ts/bad-generic-funnel/src/core/ops/sample.ts
@@ -0,0 +1,3 @@
+declare function opError(...args: unknown[]): Error;
+const invalid = (message: string, suggestion: string) => opError('invalid_params', message, suggestion);
+export function f() { throw invalid('Bad input.', 'Check your input.'); }
diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-generic-suggestion/src/core/error-registry.ts b/test/fixtures/guards/check-agent-contract.ts/bad-generic-suggestion/src/core/error-registry.ts
new file mode 100644
index 0000000000..b70481c8a7
--- /dev/null
+++ b/test/fixtures/guards/check-agent-contract.ts/bad-generic-suggestion/src/core/error-registry.ts
@@ -0,0 +1,3 @@
+export const CODES = {
+ invalid_params: { class: 'caller', summary: 'x' },
+} as const;
diff --git a/test/fixtures/guards/check-agent-contract.ts/bad-generic-suggestion/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/bad-generic-suggestion/src/core/ops/sample.ts
new file mode 100644
index 0000000000..c25211b54b
--- /dev/null
+++ b/test/fixtures/guards/check-agent-contract.ts/bad-generic-suggestion/src/core/ops/sample.ts
@@ -0,0 +1,2 @@
+declare function opError(...args: unknown[]): Error;
+export function f() { throw opError('invalid_params', 'Bad input.', 'Run `gbrain repair --help`.'); }
diff --git a/test/fixtures/guards/check-agent-contract.ts/good/src/core/ops/sample.ts b/test/fixtures/guards/check-agent-contract.ts/good/src/core/ops/sample.ts
index 5f91dbb55c..adc2cf400a 100644
--- a/test/fixtures/guards/check-agent-contract.ts/good/src/core/ops/sample.ts
+++ b/test/fixtures/guards/check-agent-contract.ts/good/src/core/ops/sample.ts
@@ -3,3 +3,5 @@ export function f() { throw opError('invalid_params', 'Bad input.', 'Pass a slug
export const inputFix = { argv: ['gbrain', 'pricing', 'set', '<model>'], inputs: [{ name: 'model', how: 'h' }], consent: [], actor: 'agent', why: 'w', requires_exclusive: false };
export const op = { name: 'put_x', mutating: true, idempotent: true, handler: async () => { throw opError('invalid_params', 'Failed.', 'Retry with the same request_id; run `gbrain sync --no-pull` first.'); } };
export const cliOnlyOp = { name: 'inspect_x', cliOnly: { argv: ['gbrain', 'sources', 'inspect', '<path>'] }, handler: async () => null };
+const invalid = (message: string, suggestion: string) => opError('invalid_params', message, suggestion);
+export function g() { throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive integer, e.g. gbrain repair --limit 50; see gbrain repair --help for the other flags.'); }
diff --git a/test/helpers/agent-envelope.ts b/test/helpers/agent-envelope.ts
new file mode 100644
index 0000000000..521148da72
--- /dev/null
+++ b/test/helpers/agent-envelope.ts
@@ -0,0 +1,27 @@
+import { expect } from 'bun:test';
+import { toAgentError, type AgentEnvelope, type RenderContext } from '../../src/core/agent-output.ts';
+import { funnelSites, isGenericSuggestion } from '../../scripts/check-agent-contract.ts';
+
+/** The envelope a caller on `transport` sees for a thrown error (nothing preapproved). */
+export function envelopeFor(error: unknown, transport: RenderContext['transport'] = 'cli', callable: readonly string[] = []): AgentEnvelope {
+ const render: RenderContext = { transport, isCallable: tool => callable.includes(tool), preapproved: () => false };
+ return toAgentError(error, { transport, render });
+}
+
+/** The error a refusal throws (sync or async), so the test can render it. */
+export async function caught(run: () => unknown): Promise<unknown> {
+ try { await run(); } catch (error) { return error; }
+ throw new Error('expected a refusal, but the call succeeded');
+}
+
+/**
+ * Every call site of a file-local suggestion funnel (scanner site list) names
+ * its own next step: a literal suggestion on every branch, none of them empty
+ * or a generic denylist phrase.
+ */
+export function expectFunnelSuggestions(file: string, funnel: string, atLeast: number): void {
+ const sites = funnelSites([file]).filter(site => site.funnel === funnel);
+ expect(sites.length).toBeGreaterThanOrEqual(atLeast);
+ const weak = sites.filter(site => !site.texts?.length || site.texts.some(isGenericSuggestion)).map(site => `${site.file}:${site.line} ${site.expr}`);
+ expect(weak).toEqual([]);
+}
diff --git a/test/persistence-administration.test.ts b/test/persistence-administration.test.ts
index df2872b4de..a6d4bdfe75 100644
--- a/test/persistence-administration.test.ts
+++ b/test/persistence-administration.test.ts
@@ -16,6 +16,7 @@ import { acquireLock, releaseLock } from '../src/core/pglite-lock.ts';
import { parsePersistenceAdminArgs } from '../src/commands/persistence-admin.ts';
import { withEnv } from './helpers/with-env.ts';
import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
+import { caught, envelopeFor, expectFunnelSuggestions } from './helpers/agent-envelope.ts';
let engine: PGLiteEngine;
let brainId: string;
@@ -170,3 +171,50 @@ describe('local writer administration', () => {
expect(() => parsePersistenceAdminArgs('writer', ['transfer', 'steal', 'default'])).toThrow('prepare or accept');
});
});
+
+describe('administration refusals name their own next step', () => {
+ test('every invalid() and uuid() call site carries a site-specific suggestion', () => {
+ expectFunnelSuggestions('src/core/persistence/administration.ts', 'invalid', 15);
+ expectFunnelSuggestions('src/core/persistence/administration.ts', 'uuid', 4);
+ expectFunnelSuggestions('src/commands/persistence-admin.ts', 'invalid', 8);
+ });
+
+ test('a grant naming an inactive source names it and reads the source list', () => isolated(async () => {
+ const env = envelopeFor(await caught(() => runPersistenceAdministration(engine, 'local_writer_register', { lane: 'stdio', source_ids: ['missing-source'] })));
+ expect(env).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'sources', 'list', '--json'], next: 'run' } });
+ expect(env.suggestion).toContain('missing-source');
+ }));
+
+ test('a grant outside its scope names the operations to remove', () => isolated(async () => {
+ const env = envelopeFor(await caught(() => runPersistenceAdministration(engine, 'local_writer_register', { lane: 'stdio', allowed_operations: ['writer_status'] })));
+ expect(env.code).toBe('invalid_params');
+ expect(env.suggestion).toContain('Remove writer_status from --allowed-operations');
+ }));
+
+ test('activation without --confirm-quiesced points at the reviewed status', () => isolated(async () => {
+ const env = envelopeFor(await caught(() => runPersistenceAdministration(engine, 'writer_activate', {})));
+ expect(env).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'sources', 'writer', 'status', '--json'], next: 'run' } });
+ expect(env.suggestion).toContain('--admin-intent writer_activate');
+ }));
+
+ test('deactivate with a source previews the brain-wide change instead', () => isolated(async () => {
+ const env = envelopeFor(await caught(() => runPersistenceAdministration(engine, 'writer_deactivate', { source_id: 'default' })));
+ expect(env).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'sources', 'writer', 'deactivate', '--dry-run', '--json'], next: 'run' } });
+ }));
+
+ test('revoke with a malformed id reads the writer list; a non-boolean flag names its CLI form', () => isolated(async () => {
+ const revoke = envelopeFor(await caught(() => runPersistenceAdministration(engine, 'local_writer_revoke', { id: 'nope' })));
+ expect(revoke).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'auth', 'local-writer', 'list', '--json'], next: 'run' } });
+ const dryRun = envelopeFor(await caught(() => runPersistenceAdministration(engine, 'local_writer_revoke', { id: 'nope', dry_run: 'yes' })));
+ expect(dryRun.suggestion).toContain('--dry-run');
+ }));
+
+ test('CLI usage refusals name the exact usage and offer the group help', async () => {
+ const duplicate = envelopeFor(await caught(() => parsePersistenceAdminArgs('writer', ['claim', 'default', '--source', 'other'])));
+ expect(duplicate).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'sources', 'writer', '--help'], next: 'run' } });
+ expect(duplicate.suggestion).toContain('default and other');
+ const unknown = envelopeFor(await caught(() => parsePersistenceAdminArgs('local-writer', ['list', '--force'])));
+ expect(unknown).toMatchObject({ fix: { argv: ['gbrain', 'auth', 'local-writer', '--help'] } });
+ expect(unknown.suggestion).toContain('Remove --force');
+ });
+});
diff --git a/test/persistence-source-cli.test.ts b/test/persistence-source-cli.test.ts
index 3461c0bf9c..ed8bd1bafa 100644
--- a/test/persistence-source-cli.test.ts
+++ b/test/persistence-source-cli.test.ts
@@ -15,6 +15,7 @@ import { submitPageMutation } from '../src/core/persistence/page-mutations.ts';
import { submitRememberMutation } from '../src/core/persistence/memory-mutations.ts';
import { runPersistenceAdministration } from '../src/core/persistence/administration.ts';
import { reviewedWriterIntent } from './helpers/writer-admin-intent.ts';
+import { caught, envelopeFor, expectFunnelSuggestions } from './helpers/agent-envelope.ts';
let diskEngine: PGLiteEngine;
beforeAll(() => { diskEngine = new PGLiteEngine(); });
@@ -41,6 +42,15 @@ describe('source lifecycle CLI', () => {
expect(() => parseSourceLifecycleArgs(['add', 'example', '--kind', 'google', '--account', '[email protected]', '--access', 'command'])).toThrow('access');
});
+ test('usage refusals name their own next step and offer the verb help', async () => {
+ expectFunnelSuggestions('src/commands/sources-lifecycle-args.ts', 'invalid', 20);
+ const misplaced = envelopeFor(await caught(() => parseSourceLifecycleArgs(['archive', 'example', '--force'])));
+ expect(misplaced).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'sources', 'archive', '--help'], next: 'run' } });
+ expect(misplaced.suggestion).toContain('Remove --force; sources archive accepts');
+ const githubOnly = envelopeFor(await caught(() => parseSourceLifecycleArgs(['add', 'example', '--repos', 'acme-example/notes'])));
+ expect(githubOnly.suggestion).toContain('Add --kind github for --repos');
+ });
+
test('actual CLI source writes use the resident owner, replay after deletion, and share page request identity', async () => {
const dir = mkdtempSync(join(tmpdir(), 'gbrain-source-cli-'));
await withEnv({ GBRAIN_HOME: dir, GBRAIN_BRAIN_ID: 'host', GBRAIN_SOURCE: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined }, async () => {