Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
agent contract: repair, forget, capture, takes and timeline refusals name their own next step
garrytanae6ff3d35e65
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex 2f47c1bdfb..4b6b3ddec5 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -1,10 +1,5 @@# shrink-only baseline for scripts/check-agent-contract.ts rule suggestionless-operation-error: path<TAB>countsrc/commands/book-mirror.ts 1-src/commands/capture.ts 4-src/commands/extract-timeline-db.ts 2-src/commands/recall.ts 3-src/commands/repair.ts 6-src/commands/takes-mutation.ts 1src/core/company-brain/policy.ts 2src/core/company-brain/receipts.ts 1src/core/facts/backstop.ts 1diff --git a/src/commands/capture.ts b/src/commands/capture.tsindex 7f83ae242b..8ed4ea775f 100644--- a/src/commands/capture.ts+++ b/src/commands/capture.ts@@ -37,7 +37,7 @@ import type { BrainEngine } from '../core/engine.ts';import { loadConfig, isThinClient } from '../core/config.ts';import { callRemoteTool, unpackToolResult, RemoteMcpError } from '../core/mcp-client.ts';import { computeContentHash } from '../core/ingestion/types.ts';-import { operations, OperationError } from '../core/operations.ts';+import { operations, opError } from '../core/operations.ts';import type { OperationContext } from '../core/operations.ts';import { resolveSourceWithTier } from '../core/source-resolver.ts';// Pure content helpers moved to core (shared with the capture MCP op — the@@ -95,7 +95,9 @@ function parseArgs(args: string[]): RunOpts | { help: true; positional: string |const mutationFlag = /^--(request-id|expected-revision)(?:=(.*))?$/.exec(a);if (mutationFlag) {const value = mutationFlag[2] ?? args[++i];- if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${mutationFlag[1]} requires a UUID.`);+ if (!value || value.startsWith('--')) throw opError('invalid_params', `${mutationFlag[1]} requires a UUID.`, mutationFlag[1] === 'request-id'+ ? 'Give --request-id the UUID an earlier attempt of this capture printed (it replays that request), or omit it and gbrain generates one.'+ : 'Give --expected-revision the revision gbrain get --json returned for the page, or omit it to capture without a revision check.');if (mutationFlag[1] === 'request-id') opts.request_id = value;else opts.expected_revision = value;continue;@@ -126,7 +128,9 @@ function parseArgs(args: string[]): RunOpts | { help: true; positional: string |if (a === '--where') { const v = args[++i]; if (v) opts.where = v; continue; }if (a === '--kind') { const v = args[++i]; if (v) opts.kind = v; continue; }if (a === '--depth') { const v = args[++i]; if (v) opts.depth = v; continue; }- if (a.startsWith('--')) throw new OperationError('invalid_params', `Unsupported capture option '${a}'.`);+ if (a.startsWith('--')) throw opError('invalid_params', `Unsupported capture option '${a.split('=')[0]}'.`,+ `Remove ${a.split('=')[0]}; gbrain capture accepts --file, --stdin, --slug, --type, --source, --who, --what, --where, --kind, --depth, --request-id, --expected-revision, --force, --json and --quiet.`,+ { fix: { argv: ['gbrain', 'capture', '--help'], consent: [], actor: 'agent', why: 'Prints the capture forms and flags.', requires_exclusive: false } });positional.push(a);}if (positional.length > 0) {@@ -393,11 +397,15 @@ export async function runCapture(engine: BrainEngine | null, args: string[], optif (delegated.handled) result = delegated.result as Record<string, unknown>;else {if (!engine && options.getEngine) engine = await options.getEngine();- if (!engine) throw new OperationError('owner_unavailable', 'Capture requires a connected engine or a local persistence owner.');+ if (!engine) throw opError('owner_unavailable', 'Capture requires a connected engine or a local persistence owner.',+ 'Run gbrain capture from the CLI on the brain host, where it opens the brain itself or hands the capture to a running gbrain serve.',+ { fix: { argv: ['gbrain', 'doctor', '--json'], consent: [], actor: 'agent', why: 'Shows whether this machine resolves a brain and whether a serve owns it, read-only.', requires_exclusive: false } });const resolved = await resolveSourceWithTier(engine, parsed.source ?? null);resolvedSourceId = resolved.source_id;const captureOp = operations.find(operation => operation.name === 'capture');- if (!captureOp) throw new OperationError('unavailable', 'The capture operation is missing; upgrade this installation.');+ if (!captureOp) throw opError('unavailable', 'The capture operation is missing; upgrade this installation.',+ 'This gbrain build has no capture operation. Check for an update and, with the user\'s go-ahead, run gbrain upgrade, then capture again.',+ { fix: { argv: ['gbrain', 'check-update', '--json'], consent: [], actor: 'agent', why: 'Reports whether a newer gbrain is available, read-only.', requires_exclusive: false } });const ctx: OperationContext = {engine, config: cfg ?? { engine: 'pglite' }, sourceId: resolvedSourceId,remote: false, dryRun: false, writeWaitMs: currentCliWriteWait().waitMs,diff --git a/src/commands/extract-timeline-db.ts b/src/commands/extract-timeline-db.tsindex 1584d71c0a..3948328a75 100644--- a/src/commands/extract-timeline-db.ts+++ b/src/commands/extract-timeline-db.ts@@ -28,7 +28,8 @@ import { getWriteRequest } from '../core/persistence/journal.ts';import { isTerminal, type WriteRequest } from '../core/persistence/model.ts';import { digest } from '../core/persistence/digest.ts';import type { PreparedMutation } from '../core/persistence/coordinator.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 { createProgress } from '../core/progress.ts';import { getCliOptions, cliOptsToProgressOptions } from '../core/cli-options.ts';import { filterRefsSince } from './extract.ts';@@ -253,16 +254,22 @@ async function publishPageTimeline(engine: BrainEngine, authority: MaintenanceAu}/** Preparer for `managed_maintenance_timeline_extract`: a database-only publication on the page key. */+function timelinePageChanged(row: WriteRequest, message: string): OperationError {+ return opError('page_identity_changed', message,+ `Page ${row.slug} in source ${row.source_id} changed before its queued timeline extraction ran, so this page was skipped. Read the page that holds the slug now; gbrain extract timeline --source db --source-id ${row.source_id} extracts it again under a new request.`,+ { fix: readFix(`Shows which page holds ${row.slug} now and its revision.`, { argv: ['gbrain', 'get', '--source', row.source_id, '--', row.slug], mcp: { tool: 'get_page', arguments: { slug: row.slug, source_id: row.source_id } } }) });+}+export async function prepareTimelineExtract(engine: BrainEngine, row: WriteRequest): Promise<PreparedMutation> {const snapshot = await engine.readPageSnapshot(row.slug, { sourceId: row.source_id });- if (!snapshot || snapshot.page.id !== Number(row.page_id)) throw new OperationError('page_identity_changed', 'The page was deleted or replaced before its timeline was extracted.');+ if (!snapshot || snapshot.page.id !== Number(row.page_id)) throw timelinePageChanged(row, 'The page was deleted or replaced before its timeline was extracted.');await authorizeWrite(engine, row.authority, 'submit_job', row.slug);const inferDates = (row.intent as { infer_dates?: unknown } | null)?.infer_dates === true;return { observedRevision: snapshot.revision, noop: true,validate: async tx => { await authorizeWrite(tx, row.authority, 'submit_job', row.slug); },apply: async tx => {const current = await tx.readPageSnapshot(row.slug, { sourceId: row.source_id });- if (!current) throw new OperationError('page_identity_changed', 'The page disappeared before its timeline was extracted.');+ if (!current) throw timelinePageChanged(row, 'The page disappeared before its timeline was extracted.');return { status: 'completed', added: await writePageTimeline(tx, current.page, row.slug, row.source_id, inferDates) };} };}diff --git a/src/commands/recall.ts b/src/commands/recall.tsindex ec2ef96f0f..1ed219974a 100644--- a/src/commands/recall.ts+++ b/src/commands/recall.ts@@ -832,16 +832,18 @@ export async function runForget(engine: BrainEngine | (() => Promise<BrainEngine? args[sourceIndex].slice('--source='.length) : args[sourceIndex + 1];const { parseWriteRequestId } = await import('../core/persistence/preconditions.ts');const { randomUUID } = await import('node:crypto');- const { OperationError, operations } = await import('../core/operations.ts');+ const { opError, operations } = await import('../core/operations.ts');const { reportPersistenceCliError } = await import('./persistence-delegate.ts');const json = args.includes('--json');let requestId: string;try {if (requestIndex >= 0 && (!requestValue || requestValue.startsWith('--'))) {- throw new OperationError('invalid_params', '--request-id requires a UUID.');+ throw opError('invalid_params', '--request-id requires a UUID.',+ `Give --request-id the UUID an earlier attempt of this forget printed, or omit it and gbrain forget ${id} generates one.`);}if (sourceIndex >= 0 && (!sourceValue || sourceValue.startsWith('--'))) {- throw new OperationError('invalid_params', '--source requires a source ID.');+ throw opError('invalid_params', '--source requires a source ID.', `Give --source the id of the source that holds fact ${id}, e.g. --source default, or omit it to use the default source.`,+ { fix: { argv: ['gbrain', 'sources', 'list', '--json'], consent: [], actor: 'agent', why: 'Lists the source ids, read-only.', requires_exclusive: false } });}requestId = parseWriteRequestId(requestValue) ?? randomUUID();} catch (error) {@@ -857,7 +859,10 @@ export async function runForget(engine: BrainEngine | (() => Promise<BrainEngineconst cfg = loadConfig();if (isThinClient(cfg)) {try {- if (sourceValue) throw new OperationError('invalid_params', '--source cannot override the remote memory writer grant.');+ if (sourceValue) throw opError('invalid_params', '--source cannot override the remote memory writer grant.',+ 'Drop --source: on a remote brain the connection\'s memory writer grant decides the source.',+ { fix: { argv: ['gbrain', 'forget', String(id), ...(reason !== undefined ? ['--reason', reason] : []), '--request-id', requestId], consent: [], actor: 'agent',+ requires_exclusive: false, why: `The same forget of fact ${id} without --source, under the same request id.` } });const raw = await callRemoteTool(cfg!, 'forget', params, { timeoutMs: 30_000 });const result = unpackToolResult<{ id: string; expired: boolean }>(raw);if (json) console.log(JSON.stringify(result, null, 2));diff --git a/src/commands/repair.ts b/src/commands/repair.tsindex 107c4a6371..5de0ee4b7f 100644--- a/src/commands/repair.ts+++ b/src/commands/repair.ts@@ -13,7 +13,8 @@import type { BrainEngine } from '../core/engine.ts';import { setCliExitVerdict } from '../core/cli-force-exit.ts';import { clearHealthMemo } from '../core/health-memo.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 { REPAIR_KINDS, resolveRepairScope, type RepairKind, type RepairResult } from '../core/repair/core.ts';import { consentGate, engineConsentEnv } from '../core/consent-cli.ts';import { AUTO_REPAIR_REGISTRY, EXPLICIT_REPAIR_REGISTRY, REPAIR_REGISTRY, explicitRepairNotices, repairMaySpend, repairPreviewCommand, repairRunner, repairSpec } from '../core/repair/registry.ts';@@ -71,6 +72,10 @@ const BOOLEAN_FLAGS = new Set(['--apply', '--all', '--json', '--no-embed', '--inconst VALUE_FLAGS = new Set(['--source', '--limit', '--expect', '--only', '--skip']);/** Flags only `gbrain repair frontmatter` accepts. */const FRONTMATTER_FLAGS = ['--only', '--skip', '--diff', '--yes'] as const;+const VALUE_EXAMPLES: Record<string, string> = { '--source': 'default', '--limit': '50', '--expect': 'PLAN_HASH', '--only': 'notes/a.md', '--skip': 'notes/a.md' };+/** A usage refusal whose fix is the read-only preview (gbrain repair without --apply writes nothing). */+const invalid = (message: string, suggestion: string, preview: string[] = ['gbrain', 'repair', '--json']) => opError('invalid_params', message, suggestion,+ { fix: readFix('Previews the repair; without --apply it writes nothing.', { argv: preview }) });interface RepairArgs { kind?: string; apply: boolean; all: boolean; json: boolean; noEmbed: boolean; includeAmbiguous: boolean; diff: boolean; yes: boolean;source?: string; limit?: string; expect?: string; only: string[]; skip: string[] }@@ -92,7 +97,7 @@ export function parseRepairArgs(args: string[]): RepairArgs {`To cap paid repair work, preview gbrain doctor --remediation-plan --json, then after the user agrees run: gbrain doctor --remediate --yes --include-repairs --max-usd ${cap && !cap.startsWith('-') ? cap : '<n>'} --expect <plan_hash> (plan_hash from the preview)`);}if (BOOLEAN_FLAGS.has(flag)) {- if (equal >= 0) throw new OperationError('invalid_params', `${flag} does not accept a value.`);+ if (equal >= 0) throw invalid(`${flag} does not accept a value.`, `Write ${flag} on its own, without =value; leave it out to keep it off.`);if (flag === '--apply') parsed.apply = true;else if (flag === '--all') parsed.all = true;else if (flag === '--json') parsed.json = true;@@ -102,9 +107,9 @@ export function parseRepairArgs(args: string[]): RepairArgs {else parsed.noEmbed = true;continue;}- if (!VALUE_FLAGS.has(flag)) throw new OperationError('invalid_params', `Unknown option ${flag} for gbrain repair.`, 'Run gbrain repair --help for the accepted options.');+ if (!VALUE_FLAGS.has(flag)) throw invalid(`Unknown option ${flag} for gbrain repair.`, `Remove ${flag}; gbrain repair accepts ${[...BOOLEAN_FLAGS, ...VALUE_FLAGS].join(', ')}.`);const value = equal >= 0 ? token.slice(equal + 1) : args[++i];- if (!value || value.startsWith('--')) throw new OperationError('invalid_params', `${flag} requires a value.`);+ if (!value || value.startsWith('--')) throw invalid(`${flag} requires a value.`, `Give ${flag} its value right after it, e.g. ${flag} ${VALUE_EXAMPLES[flag]}${flag === '--expect' ? ' (the plan_hash the preview printed)' : ''}.`);if (flag === '--source') parsed.source = value;else if (flag === '--expect') parsed.expect = value;else if (flag === '--only') parsed.only.push(value);@@ -114,7 +119,9 @@ export function parseRepairArgs(args: string[]): RepairArgs {if (positional.length > 1) throw new OperationError('invalid_params', `Unexpected argument '${positional[1]}'; gbrain repair takes at most one kind.`,`Kinds: ${REPAIR_KINDS.join(', ')}.`);parsed.kind = positional[0];- if (used.has('--yes') && parsed.kind !== 'frontmatter') throw new OperationError('invalid_params', '`--yes` is not accepted by gbrain repair; pass --apply to write.');+ if (used.has('--yes') && parsed.kind !== 'frontmatter') throw invalid('`--yes` is not accepted by gbrain repair; pass --apply to write.',+ `Preview first with gbrain repair${parsed.kind ? ` ${parsed.kind}` : ''}, then run the same command with --apply instead of --yes.`,+ ['gbrain', 'repair', ...(parsed.kind ? [parsed.kind] : []), ...(parsed.source ? ['--source', parsed.source] : []), '--json']);const frontmatterOnly = [...used].find(flag => flag !== '--yes');if (frontmatterOnly && parsed.kind !== 'frontmatter') throw new OperationError('invalid_params', `${frontmatterOnly} applies only to gbrain repair frontmatter.`,`Preview it by name: gbrain repair frontmatter${parsed.source ? ` --source ${parsed.source}` : ''}`);@@ -155,12 +162,15 @@ export async function runRepairCommand(engine: BrainEngine, args: string[]): Proif (args.includes('--help') || args.includes('-h')) { console.log(REPAIR_HELP); return; }const { kind, apply, all, json, noEmbed, includeAmbiguous, source, expect, only, skip, diff, limit: limitText } = parseRepairArgs(args);const limit = limitText === undefined ? undefined : Number(limitText);- if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw new OperationError('invalid_params', '--limit must be a positive integer.');+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1)) throw invalid('--limit must be a positive integer.', 'Pass --limit as a positive whole number, e.g. --limit 50, or omit it to repair every item.');if (kind && !REPAIR_KINDS.includes(kind as RepairKind)) {throw new OperationError('invalid_params', `Unknown repair kind '${kind}'.`, `Kinds: ${REPAIR_KINDS.join(', ')}.`);}- if (kind && all) throw new OperationError('invalid_params', 'Pass either a kind or --all, not both.');- if (!kind && apply && !all) throw new OperationError('invalid_params', 'Name a kind or pass --all with --apply.');+ if (kind && all) throw invalid('Pass either a kind or --all, not both.', `Drop --all to repair only ${kind}, or drop ${kind} to run every automatic kind.`,+ ['gbrain', 'repair', kind, ...(source ? ['--source', source] : []), '--json']);+ if (!kind && apply && !all) throw invalid('Name a kind or pass --all with --apply.',+ 'Review the preview of every automatic kind, then apply one by name (gbrain repair KIND --apply) or all of them with --all --apply.',+ ['gbrain', 'repair', ...(source ? ['--source', source] : []), '--json']);const kinds: RepairKind[] = kind ? [kind as RepairKind] : AUTO_REPAIR_REGISTRY.map(spec => spec.kind);const explicitKindsNotRun = kind ? [] : explicitRepairNotices({ source });const scope = await resolveRepairScope(engine, source);diff --git a/src/commands/takes-mutation.ts b/src/commands/takes-mutation.tsindex 28899fbc6c..63bfc570b3 100644--- a/src/commands/takes-mutation.ts+++ b/src/commands/takes-mutation.ts@@ -4,7 +4,9 @@ import { resolve } from 'node:path';import type { BrainEngine } from '../core/engine.ts';import { getCliOptions } from '../core/cli-options.ts';import { isThinClient, loadConfig, type GBrainConfig } from '../core/config.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 type { Action } from '../core/agent-output.ts';import { parseMutationPrecondition } from '../core/persistence/preconditions.ts';import { isWriteReceipt } from '../core/persistence/types.ts';import { currentCliWriteWait } from '../core/persistence/write-wait.ts';@@ -17,11 +19,17 @@ import { reportPersistenceCliError } from './persistence-delegate.ts';const names = ['add', 'update', 'supersede', 'resolve'] as const;export type TakesMutation = typeof names[number];export function isTakesMutation(value: string): value is TakesMutation { return (names as readonly string[]).includes(value); }-const invalid = (message: string) => new OperationError('invalid_params', message);+const USAGE_FIX = readFix('Prints every gbrain takes form with its flags.', { argv: ['gbrain', 'takes', '--help'] });+const invalid = (message: string, suggestion: string, fix: Action = USAGE_FIX) => opError('invalid_params', message, suggestion, { fix });+const REQUIRED_USAGE: Record<TakesMutation, string> = {+ add: '--claim "..." --kind fact|take|bet|hunch --who HOLDER', update: '--row N', supersede: '--row N --claim "..."', resolve: '--row N --quality correct|incorrect|partial',+};export function parseTakesMutation(args: string[]): { operation: `takes_${TakesMutation}`; params: Record<string, unknown>; sourceId?: string; json: boolean } {const [sub, slug, ...rest] = args;- if (!isTakesMutation(sub) || !slug || slug.startsWith('-')) throw invalid('Usage: gbrain takes add|update|supersede|resolve <slug> [options].');+ if (!isTakesMutation(sub) || !slug || slug.startsWith('-')) throw invalid('Usage: gbrain takes add|update|supersede|resolve <slug> [options].',+ isTakesMutation(sub) ? `Name the page slug right after takes ${sub}: gbrain takes ${sub} people/alice-example ${REQUIRED_USAGE[sub]}.`+ : 'Start with the mutation and the page slug, e.g. gbrain takes add people/alice-example --claim "..." --kind take --who alice-example.');const params: Record<string, unknown> = { slug };let sourceId: string | undefined, json = false;const fields: Record<string, string> = { '--claim': 'claim', '--kind': 'kind', '--who': 'holder', '--weight': 'weight',@@ -32,21 +40,24 @@ export function parseTakesMutation(args: string[]): { operation: `takes_${TakesMfor (let i = 0; i < rest.length; i++) {const raw = rest[i], equal = raw.indexOf('=');const flag = equal < 0 ? raw : raw.slice(0, equal);- if (seen.has(flag)) throw invalid(`Duplicate option ${flag}.`);+ if (seen.has(flag)) throw invalid(`Duplicate option ${flag}.`, `Pass ${flag} once, with the one value you mean.`);seen.add(flag);if (flag === '--json' || flag === '--force') {- if (equal >= 0) throw invalid(`${flag} does not accept a value.`);+ if (equal >= 0) throw invalid(`${flag} does not accept a value.`, `Write ${flag} on its own, without =value.`);if (flag === '--json') json = true; else params.force = true;continue;}const key = fields[flag];- if (!key) throw invalid(`Unsupported takes mutation option: ${flag}.`);+ if (!key) throw invalid(`Unsupported takes mutation option: ${flag}.`,+ `Remove ${flag}; takes ${sub} accepts ${Object.keys(fields).join(', ')}, --json and --force.`);const value = equal >= 0 ? raw.slice(equal + 1) : rest[++i];- if (value === undefined || value.startsWith('--')) throw invalid(`${flag} requires a value.`);+ if (value === undefined || value.startsWith('--')) throw invalid(`${flag} requires a value.`, `Give ${flag} its value right after it, as ${flag} VALUE or ${flag}=VALUE.`);if (key === 'source_id') { sourceId = value; continue; }if (['weight', 'value', 'row_num'].includes(key)) {const number = Number(value);- if (!value.trim() || !Number.isFinite(number) || key === 'row_num' && (!Number.isSafeInteger(number) || number < 1)) throw invalid(`${flag} requires ${key === 'row_num' ? 'a positive integer' : 'a finite number'}.`);+ if (!value.trim() || !Number.isFinite(number) || key === 'row_num' && (!Number.isSafeInteger(number) || number < 1)) throw invalid(`${flag} requires ${key === 'row_num' ? 'a positive integer' : 'a finite number'}.`,+ key === 'row_num' ? `Pass --row as the take's row number from gbrain takes ${slug} --json, e.g. --row 2.` : `Pass ${flag} as a plain number, e.g. ${flag} ${key === 'weight' ? '0.7' : '1000'}.`,+ key === 'row_num' ? readFix(`Lists ${slug}'s takes with their row numbers, read-only.`, { argv: ['gbrain', 'takes', slug, '--json'] }) : USAGE_FIX);params[key] = number;} else params[key] = key === 'local_dir' ? resolve(value) : value;}@@ -55,20 +66,29 @@ export function parseTakesMutation(args: string[]): { operation: `takes_${TakesM: sub === 'update' ? ['row_num', 'weight', 'source', 'since']: sub === 'supersede' ? ['row_num', 'claim', 'kind', 'holder', 'weight', 'source', 'since']: ['row_num', 'quality', 'outcome', 'evidence', 'source', 'value', 'unit', 'resolved_by'];- for (const key of Object.keys(params)) if (![...common, ...allowed].includes(key)) throw invalid(`${key} is not supported by takes ${sub}.`);+ const flagOf = (key: string) => Object.keys(fields).find(flag => fields[flag] === key) ?? `--${key}`;+ for (const key of Object.keys(params)) if (![...common, ...allowed].includes(key)) throw invalid(`${key} is not supported by takes ${sub}.`,+ `Remove ${flagOf(key)}; takes ${sub} takes ${allowed.map(flagOf).join(', ')} (plus --request-id, --expected-revision, --force and --dir).`);for (const key of sub === 'add' ? ['claim', 'kind', 'holder'] : sub === 'supersede' ? ['row_num', 'claim'] : ['row_num']) {- if (params[key] === undefined || params[key] === '') throw invalid(`Missing ${key === 'holder' ? '--who' : key === 'row_num' ? '--row' : `--${key}`}.`);+ if (params[key] === undefined || params[key] === '') throw invalid(`Missing ${key === 'holder' ? '--who' : key === 'row_num' ? '--row' : `--${key}`}.`,+ `takes ${sub} needs ${REQUIRED_USAGE[sub]}: gbrain takes ${sub} ${slug} ${REQUIRED_USAGE[sub]}.`,+ key === 'row_num' ? readFix(`Lists ${slug}'s takes with their row numbers, read-only.`, { argv: ['gbrain', 'takes', slug, '--json'] }) : USAGE_FIX);}- if (params.kind !== undefined && !['fact', 'take', 'bet', 'hunch'].includes(String(params.kind))) throw invalid('Invalid --kind. Expected fact, take, bet, or hunch.');+ if (params.kind !== undefined && !['fact', 'take', 'bet', 'hunch'].includes(String(params.kind))) throw invalid('Invalid --kind. Expected fact, take, bet, or hunch.',+ 'Pass --kind as fact, take, bet or hunch, e.g. --kind take.');if (sub === 'resolve') {- if (params.quality !== undefined && params.outcome !== undefined) throw invalid('--quality and --outcome are mutually exclusive.');+ if (params.quality !== undefined && params.outcome !== undefined) throw invalid('--quality and --outcome are mutually exclusive.',+ 'Pass only --quality correct|incorrect|partial|unresolvable; --outcome is its older true/false alias.');if (params.outcome !== undefined) {- if (params.outcome !== 'true' && params.outcome !== 'false') throw invalid('--outcome must be true or false.');+ if (params.outcome !== 'true' && params.outcome !== 'false') throw invalid('--outcome must be true or false.',+ 'Pass --quality correct|incorrect|partial|unresolvable instead (or --outcome true|false).');params.quality = params.outcome === 'true' ? 'correct' : 'incorrect';delete params.outcome;}- if (!['correct', 'incorrect', 'partial', 'unresolvable'].includes(String(params.quality))) throw invalid('--quality requires correct, incorrect, partial, or unresolvable.');- if (params.evidence !== undefined && params.source !== undefined && params.evidence !== params.source) throw invalid('--evidence and --source specify different evidence; use one.');+ if (!['correct', 'incorrect', 'partial', 'unresolvable'].includes(String(params.quality))) throw invalid('--quality requires correct, incorrect, partial, or unresolvable.',+ `Pass --quality as correct, incorrect, partial or unresolvable, e.g. gbrain takes resolve ${slug} --row ${String(params.row_num ?? 1)} --quality correct.`);+ if (params.evidence !== undefined && params.source !== undefined && params.evidence !== params.source) throw invalid('--evidence and --source specify different evidence; use one.',+ 'Keep --evidence and drop --source (on resolve both name the evidence), or give them the same value.');if (params.evidence === undefined && params.source !== undefined) params.evidence = params.source;delete params.source;}@@ -87,7 +107,11 @@ export async function runTakesMutation(engine: BrainEngine | (() => Promise<Brailet result: Record<string, unknown>;if (isThinClient(config)) {if (args.some(arg => arg === '--outcome' || arg.startsWith('--outcome='))) console.error('[deprecated] --outcome is the v0.28 alias for --quality. Prefer --quality correct|incorrect|partial in new scripts.');- if (cli.brain || parsed.sourceId || params.local_dir !== undefined) throw invalid('--brain, --source-id, and --dir require a local brain host; the remote credential selects its source.');+ if (cli.brain || parsed.sourceId || params.local_dir !== undefined) throw invalid('--brain, --source-id, and --dir require a local brain host; the remote credential selects its source.',+ 'Drop --brain, --source-id and --dir on this thin client: the remote connection\'s credential selects the brain and source.',+ { argv: ['gbrain', 'takes', ...args.filter((arg, index) => !['--brain', '--source-id', '--dir'].some(flag => arg === flag || arg.startsWith(`${flag}=`)+ || (args[index - 1] === flag))) ], consent: [], actor: 'agent', requires_exclusive: false,+ why: 'The same takes mutation without the local-host flags; the remote credential picks its source.' });result = unpackToolResult(await callRemoteTool(config!, operation, params, { timeoutMs: cli.timeoutMs ?? 30_000, writeWaitMs: currentCliWriteWait().waitMs }));} else {const delegated = await maybeDelegateLocalOperation(operation, params, config, {diff --git a/test/capture-runcapture.test.ts b/test/capture-runcapture.test.tsindex b5d3d2e71f..22ad01caf8 100644--- a/test/capture-runcapture.test.ts+++ b/test/capture-runcapture.test.ts@@ -22,6 +22,7 @@import { describe, test, expect } from 'bun:test';import { __testing as captureTesting } from '../src/commands/capture.ts';import { computeContentHash } from '../src/core/ingestion/types.ts';+import { caught, envelopeFor } from './helpers/agent-envelope.ts';const { detectBinaryNullByte, detectBinarySignature, normalizeForHash, maybeRewriteSourceFkError } = captureTesting;@@ -247,3 +248,17 @@ describe('A2 — maybeRewriteSourceFkError (friendly FK violation hint)', () =>expect(hint).toContain("source 'foo'");});});++describe('capture argument refusals name their own next step', () => {+ test('an unsupported option lists the accepted flags, offers the help and never echoes its value', async () => {+ const env = envelopeFor(await caught(() => captureTesting.parseArgs(['--token=synthetic-credential-value', 'note'])));+ expect(env).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'capture', '--help'], next: 'run' } });+ expect(env.suggestion).toContain('Remove --token; gbrain capture accepts --file');+ expect(JSON.stringify(env)).not.toContain('synthetic-credential-value');+ });++ test('a mutation flag without a UUID names where the value comes from', async () => {+ expect(envelopeFor(await caught(() => captureTesting.parseArgs(['--expected-revision']))).suggestion).toContain('gbrain get --json');+ expect(envelopeFor(await caught(() => captureTesting.parseArgs(['--request-id', '--json']))).suggestion).toContain('replays that request');+ });+});diff --git a/test/extract-timeline-db-managed.test.ts b/test/extract-timeline-db-managed.test.tsindex 8214da16a4..ec8587d49d 100644--- a/test/extract-timeline-db-managed.test.ts+++ b/test/extract-timeline-db-managed.test.ts@@ -2,8 +2,21 @@* #5904 probe (E28): `extract timeline --source db` on a managed PGLite brain.* Postgres arm: test/e2e/extract-timeline-db-postgres.test.ts.*/-import { test } from 'bun:test';+import { expect, test } from 'bun:test';+import type { BrainEngine } from '../src/core/engine.ts';+import type { WriteRequest } from '../src/core/persistence/model.ts';+import { prepareTimelineExtract } from '../src/commands/extract-timeline-db.ts';+import { caught, envelopeFor } from './helpers/agent-envelope.ts';import { managedTimelineDbRefusalExitsNonZero, managedTimelineDbWritesThroughCoordinator } from './helpers/extract-timeline-db-scenarios.ts';test('managed extract timeline --source db writes the missing rows through the coordinator', () => managedTimelineDbWritesThroughCoordinator(), 120_000);test('a refused timeline write says nothing was written and exits non-zero', () => managedTimelineDbRefusalExitsNonZero(), 120_000);++test('a page replaced before its queued extraction reads the current page, on the CLI and over MCP', async () => {+ const engine = { readPageSnapshot: async () => null } as unknown as BrainEngine;+ const row = { slug: 'people/alice-example', source_id: 'notes', page_id: '7' } as unknown as WriteRequest;+ const error = await caught(() => prepareTimelineExtract(engine, row));+ expect(envelopeFor(error)).toMatchObject({ code: 'page_identity_changed',+ fix: { argv: ['gbrain', 'get', '--source', 'notes', '--', 'people/alice-example'], next: 'run' } });+ expect(envelopeFor(error, 'stdio', ['get_page']).fix).toMatchObject({ mcp: { tool: 'get_page', arguments: { slug: 'people/alice-example', source_id: 'notes' } }, next: 'run' });+});diff --git a/test/repair-flags.test.ts b/test/repair-flags.test.tsindex 96039e3504..5f99d6fdb1 100644--- a/test/repair-flags.test.ts+++ b/test/repair-flags.test.ts@@ -14,6 +14,7 @@ import { REPAIR_KINDS } from '../src/core/repair/core.ts';import { REPAIR_HELP, runRepairCommand } from '../src/commands/repair.ts';import { AUTO_REPAIR_REGISTRY } from '../src/core/repair/registry.ts';import { withEnv } from './helpers/with-env.ts';+import { envelopeFor, expectFunnelSuggestions } from './helpers/agent-envelope.ts';let engine: PGLiteEngine;const home = mkdtempSync(join(tmpdir(), 'gbrain-repair-flags-'));@@ -69,6 +70,20 @@ describe('gbrain repair flags', () => {expect(error.message).toContain('extra');});+ test('usage refusals name the exact usage and offer the read-only preview', async () => {+ expectFunnelSuggestions('src/commands/repair.ts', 'invalid', 7);+ const both = envelopeFor(await refusal(['timeline', '--all']));+ expect(both).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'repair', 'timeline', '--json'], next: 'run' } });+ expect(both.suggestion).toContain('Drop --all to repair only timeline');+ const yes = envelopeFor(await refusal(['timeline', '--yes']));+ expect(yes).toMatchObject({ fix: { argv: ['gbrain', 'repair', 'timeline', '--json'] } });+ expect(yes.suggestion).toContain('--apply instead of --yes');+ const limit = envelopeFor(await refusal(['timeline', '--limit', '0']));+ expect(limit.suggestion).toContain('--limit 50');+ const applyAll = envelopeFor(await refusal(['--apply']));+ expect(applyAll).toMatchObject({ fix: { argv: ['gbrain', 'repair', '--json'], next: 'run' } });+ });+test('help names every registered kind', () => {for (const kind of REPAIR_KINDS) expect(REPAIR_HELP).toContain(` ${kind}`);});diff --git a/test/takes-mutation-refusals.test.ts b/test/takes-mutation-refusals.test.tsnew file mode 100644index 0000000000..b025d8e036--- /dev/null+++ b/test/takes-mutation-refusals.test.ts@@ -0,0 +1,26 @@+import { describe, expect, test } from 'bun:test';+import { parseTakesMutation } from '../src/commands/takes-mutation.ts';+import { caught, envelopeFor, expectFunnelSuggestions } from './helpers/agent-envelope.ts';++describe('takes mutation refusals name their own next step', () => {+ test('every invalid() call site carries a site-specific suggestion', () => {+ expectFunnelSuggestions('src/commands/takes-mutation.ts', 'invalid', 14);+ });++ test('a missing row points at the page takes listing', async () => {+ const env = envelopeFor(await caught(() => parseTakesMutation(['update', 'people/alice-example', '--weight', '0.7'])));+ expect(env).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'takes', 'people/alice-example', '--json'], next: 'run' } });+ expect(env.suggestion).toContain('gbrain takes update people/alice-example --row N');+ });++ test('a flag another mutation owns names the flags this one takes and offers the help', async () => {+ const env = envelopeFor(await caught(() => parseTakesMutation(['update', 'people/alice-example', '--row', '2', '--claim', 'x'])));+ expect(env).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'takes', '--help'], next: 'run' } });+ expect(env.suggestion).toContain('Remove --claim; takes update takes --row, --weight, --source, --since');+ });++ test('an invalid quality shows the resolve usage for this row', async () => {+ const env = envelopeFor(await caught(() => parseTakesMutation(['resolve', 'people/alice-example', '--row', '3', '--quality', 'maybe'])));+ expect(env.suggestion).toContain('gbrain takes resolve people/alice-example --row 3 --quality correct');+ });+});diff --git a/test/thin-client-routing-audit.test.ts b/test/thin-client-routing-audit.test.tsindex 1b3cd9725e..280dceadfd 100644--- a/test/thin-client-routing-audit.test.ts+++ b/test/thin-client-routing-audit.test.ts@@ -18,6 +18,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';import { tmpdir } from 'node:os';import { join } from 'node:path';import * as mcpClient from '../src/core/mcp-client.ts';+import * as cliForceExit from '../src/core/cli-force-exit.ts';import { runForget } from '../src/commands/recall.ts';import { runJobs } from '../src/commands/jobs.ts';import { withEnv } from './helpers/with-env.ts';@@ -77,6 +78,20 @@ describe('thin-client routing audit — ROUTE additions call the remote op', ()expect(out).toContain('Forgot fact id=42');});+ test('gbrain forget --source on a thin client is refused with the same forget minus --source as the fix', async () => {+ const requestId = '0190c6d2-1111-7000-8000-000000000042';+ const docs: string[] = [];+ const final = spyOn(cliForceExit, 'writeStdoutFinal').mockImplementation(async (doc: string) => { docs.push(doc); });+ try {+ await thinClient(() => runForget(async () => { throw new Error('local engine opened'); },+ ['42', '--source', 'notes', '--request-id', requestId, '--json']));+ } finally { final.mockRestore(); }+ expect(calls).toEqual([]);+ const envelope = JSON.parse(docs.join(''));+ expect(envelope).toMatchObject({ code: 'invalid_params', fix: { argv: ['gbrain', 'forget', '42', '--request-id', requestId], next: 'run' } });+ expect(envelope.suggestion).toContain('Drop --source');+ });+test('gbrain jobs list calls list_jobs with the parsed filters', async () => {reply = [job];const { out } = await thinClient(() => runJobs(null, ['list', '--status', 'completed', '--queue', 'default', '--limit', '5', '--json']));