Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ops): B2/B6/B7/B8 for sources, sync, request_tools, skillopt, skills catalog, files, connectors and receipt ops
garrytan32ca7069cea0
diff --git a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv b/scripts/agent-contract-baselines/suggestionless-operation-error.tsvindex c0c17d33ce..c71de35166 100644--- a/scripts/agent-contract-baselines/suggestionless-operation-error.tsv+++ b/scripts/agent-contract-baselines/suggestionless-operation-error.tsv@@ -40,23 +40,15 @@ src/core/minions/submission-authority.ts 1src/core/minions/tool-write-identity.ts 1src/core/ops/attribution.ts 1src/core/ops/code-intel.ts 1-src/core/ops/connectors.ts 3src/core/ops/context.ts 20src/core/ops/extraction.ts 2src/core/ops/facts.ts 1-src/core/ops/files.ts 3src/core/ops/insights.ts 1src/core/ops/jobs.ts 29src/core/ops/loops.ts 9src/core/ops/orphans.ts 1src/core/ops/pages.ts 1-src/core/ops/persistence.ts 4-src/core/ops/request-tools.ts 2src/core/ops/search.ts 2-src/core/ops/skillopt.ts 7-src/core/ops/skills-catalog.ts 3-src/core/ops/sources.ts 4-src/core/ops/sync-status.ts 3src/core/ops/takes.ts 1src/core/ops/timeline.ts 3src/core/ops/transcripts.ts 1diff --git a/src/core/ops/connectors.ts b/src/core/ops/connectors.tsindex 5506396971..e5fee5e862 100644--- a/src/core/ops/connectors.ts+++ b/src/core/ops/connectors.ts@@ -13,7 +13,7 @@*/import type { Operation } from './contract.ts';-import { OperationError } from './contract.ts';+import { hostOnlyError, invalidParam } from './op-fix.ts';import { connectorProviders } from '../connectors/registry.ts';import { credentialMode, resolveCredential } from '../connectors/credentials.ts';import {@@ -46,7 +46,9 @@ const connectors_status: Operation = {},handler: async (ctx, p) => {if (ctx.remote === true) {- throw new OperationError('permission_denied', 'connectors_status is local-only — call via the gbrain CLI.');+ throw hostOnlyError(ctx, 'permission_denied', 'connectors_status is local-only — call via the gbrain CLI.',+ ['gbrain', 'connectors', 'status', ...(p.provider === 'chatgpt' || p.provider === 'claude' ? [p.provider] : [])],+ 'Connector credentials live on the brain host, so only its CLI reads their status.');}const only = typeof p.provider === 'string' ? p.provider : undefined;const providers = connectorProviders.filter((prov) => !only || prov.name === only);@@ -79,7 +81,7 @@ const connector_sync: Operation = {description:'Sync a chat provider\'s conversation history into the brain: list new ' +'conversations since the watermark, fetch them, and ingest as pages under ' +- 'conversations/<provider>/. Incremental by default; --full re-scans. ' ++ 'conversations/<provider>/. Incremental by default; `full: true` re-scans. ' +'Local-only (uses on-disk credentials).',scope: 'write',mutating: true,@@ -92,11 +94,13 @@ const connector_sync: Operation = {},handler: async (ctx, p) => {if (ctx.remote === true) {- throw new OperationError('permission_denied', 'connector_sync is local-only — call via the gbrain CLI.');+ throw hostOnlyError(ctx, 'permission_denied', 'connector_sync is local-only — call via the gbrain CLI.',+ ['gbrain', 'connectors', 'sync', ...(p.provider === 'chatgpt' || p.provider === 'claude' ? [p.provider] : []), '--dry-run'],+ 'Connector syncs use credentials stored on the brain host; the dry run previews how many conversations would import.');}const provider = typeof p.provider === 'string' ? p.provider : '';if (!isConnectorProviderName(provider)) {- throw new OperationError('invalid_params', `unknown connector provider '${provider}' (expected chatgpt|claude)`);+ throw invalidParam(ctx, 'connector_sync', 'provider', 'unknown connector provider (expected chatgpt|claude)', { choices: ['chatgpt', 'claude'] });}return runConnectorSync(ctx.engine, {provider,diff --git a/src/core/ops/files.ts b/src/core/ops/files.tsindex 34369d1368..28023a30e9 100644--- a/src/core/ops/files.ts+++ b/src/core/ops/files.ts@@ -6,7 +6,8 @@*/import type { Operation } from './contract.ts';-import { OperationError } from './contract.ts';+import { opError } from './contract.ts';+import { hostFix, readFix } from './op-fix.ts';import { validateFilename, validatePageSlug, validateUploadPath } from './context.ts';// --- File Operations ---@@ -95,10 +96,13 @@ const file_upload: Operation = {// Typed error BEFORE any insert; git-tracked small files have their own// lane (`gbrain files upload-raw --page <slug>`).if (!ctx.config.storage) {- throw new OperationError(+ const slugOk = pageSlug !== null && /^[a-z0-9][a-z0-9._/-]*$/i.test(pageSlug);+ throw opError('storage_error','No storage backend configured — file_upload would record a files row with no stored bytes.',- 'Configure `storage` in your gbrain config (supabase | s3 | local), or use `gbrain files upload-raw --page <slug>` for git-tracked small files.',+ `Configure \`storage\` in your gbrain config (supabase | s3 | local), or use \`gbrain files upload-raw ${filePath} --page ${slugOk ? pageSlug : '<slug>'}\` for git-tracked small files.`,+ ...(slugOk ? [{ fix: hostFix(ctx, ['gbrain', 'files', 'upload-raw', filePath, '--page', pageSlug!],+ 'With no storage backend, a small file goes into the brain repo next to its page instead (git-tracked, with a .redirect.yaml pointer).') }] : []),);}const { createStorage } = await import('../storage.ts');@@ -122,7 +126,8 @@ const file_upload: Operation = {try {await storage.upload(storagePath, content, mimeType || undefined);} catch (uploadErr) {- throw new OperationError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`);+ throw opError('storage_error', `Upload failed: ${uploadErr instanceof Error ? uploadErr.message : String(uploadErr)}`,+ 'Nothing was recorded. Check the storage backend (credentials, bucket, disk) with `gbrain doctor --json`, then upload again; the upload is keyed by content hash, so repeating it is safe.');}try {@@ -170,13 +175,14 @@ const file_url: Operation = {const sql = sqlQueryForEngine(ctx.engine);const rows = await sql`SELECT storage_path, mime_type, size_bytes FROM files WHERE storage_path = ${p.storage_path as string}`;if (rows.length === 0) {- throw new OperationError('storage_error', `File not found: ${p.storage_path}`);+ throw opError('storage_error', `File not found: ${p.storage_path}`, 'No file row has that storage_path. List stored files (fix) and use a storage_path from that list.',+ { fix: readFix('Lists stored files with their storage_path.', { argv: ['gbrain', 'files', 'list'], mcp: { tool: 'file_list', arguments: {} } }) });}// #4302: resolve a REAL URL from the backend, after confirming the object// is actually there — the old `gbrain:files/<path>` placeholder pointed// at nothing and hid rows whose bytes had vanished.if (!ctx.config.storage) {- throw new OperationError(+ throw opError('storage_error',`No storage backend configured — cannot produce a URL for ${p.storage_path}.`,'Configure `storage` in your gbrain config (supabase | s3 | local).',@@ -186,9 +192,10 @@ const file_url: Operation = {const storage = await createStorage(ctx.config.storage as any);const present = await storage.exists(rows[0].storage_path as string).catch(() => false);if (!present) {- throw new OperationError(+ throw opError('storage_error',`File row exists but the storage backend has no object at ${rows[0].storage_path} — re-upload it.`,+ 'The bytes are missing from storage. Re-upload the original file with file_upload (same path); `gbrain files verify` lists every row in this state.',);}return { storage_path: rows[0].storage_path, url: await storage.getUrl(rows[0].storage_path as string) };diff --git a/src/core/ops/persistence.ts b/src/core/ops/persistence.tsindex 36dc4972cd..dfaf65ddf4 100644--- a/src/core/ops/persistence.ts+++ b/src/core/ops/persistence.ts@@ -1,5 +1,7 @@/** Own-write receipt controls. UUID knowledge alone never grants access. */-import { OperationError, type Operation, type OperationContext } from './contract.ts';+import { OperationError, opError, type Operation, type OperationContext } from './contract.ts';+import { invalidParam, readFix } from './op-fix.ts';+import { isValidSourceId } from '../source-id.ts';import { enforceBoundClientOpAllowList, enforceClientSlugFence, enforceSubagentSlugFence, normalizeSlugPrefix, parseSourceIdParam } from './context.ts';import { hasScope } from '../scope.ts';import { normalizeTokenScopes } from '../legacy-token-scope.ts';@@ -11,9 +13,19 @@ import type { WriteHealthFacts } from '../persistence/health.ts';const RECEIPT_NAMES = ['get_write_request', 'list_write_requests', 'cancel_write_request'] as const;type ReceiptOperation = typeof RECEIPT_NAMES[number];-const denied = () => new OperationError('permission_denied', 'This writer grant does not include the requested receipt operation.',+const denied = () => opError('permission_denied', 'This writer grant does not include the requested receipt operation.','Explicitly regrant the required receipt operation. Existing operation snapshots do not expand during upgrades.');-const missing = () => new OperationError('not_found', 'No accessible write request has that request_id.');+function callerSource(ctx: OperationContext): string | undefined {+ const id = ctx.auth?.sourceId ?? ctx.sourceId;+ return isValidSourceId(id) ? id : undefined;+}+/** Foreign, missing and inaccessible requests share one answer (anti-enumeration); the fix lists the caller's own receipts. */+const missing = (sourceId?: string) => opError('not_found', 'No accessible write request has that request_id.',+ 'Check the request_id; list_write_requests shows the receipts this connection can read in its source, newest first.',+ { fix: readFix('Lists your own write receipts in this source, newest first.', {+ argv: ['gbrain', 'write-requests', ...(sourceId ? ['--source', sourceId] : [])],+ mcp: { tool: 'list_write_requests', arguments: sourceId ? { source_id: sourceId } : {} },+ }) });function operationAllowed(operations: unknown, operation: string): boolean {return operations == null || Array.isArray(operations) && operations.every(value => typeof value === 'string') && operations.includes(operation);@@ -112,7 +124,7 @@ async function publicReceipt(ctx: OperationContext, row: WriteRequest, facts?: Wfunction requiredRequestId(value: unknown): string {const id = parseWriteRequestId(value);- if (!id) throw new OperationError('invalid_params', 'request_id is required.');+ if (!id) throw opError('invalid_params', 'request_id is required.', 'Pass the request_id (a UUID) from the write\'s receipt; list_write_requests shows recent ones.');return id;}@@ -132,7 +144,7 @@ export const persistenceOperations: Operation[] = [const { principal } = await receiptAccess(ctx, 'get_write_request');const { getWriteRequest, writeHealthFacts } = await import('../persistence/journal.ts');const row = await getWriteRequest(ctx.engine, principal, id);- if (!row || !await visible(ctx, row)) throw missing();+ if (!row || !await visible(ctx, row)) throw missing(callerSource(ctx));return publicReceipt(ctx, row, (await writeHealthFacts(ctx.engine, [row])).get(row.id));},},@@ -152,9 +164,9 @@ export const persistenceOperations: Operation[] = [const access = await receiptAccess(ctx, 'list_write_requests');const sourceId = parseSourceIdParam(params.source_id ?? ctx.sourceId, 'list_write_requests') ?? 'default';const limit = params.limit ?? 25;- if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > 100) throw new OperationError('invalid_params', 'limit must be an integer from 1 to 100.');+ if (typeof limit !== 'number' || !Number.isInteger(limit) || limit < 1 || limit > 100) throw invalidParam(ctx, 'list_write_requests', 'limit', 'limit must be an integer from 1 to 100.', { example: 25 });if (params.before !== undefined && (typeof params.before !== 'string' || !/^\d{1,19}$/.test(params.before)- || BigInt(params.before) > 9_223_372_036_854_775_807n)) throw new OperationError('invalid_params', 'Invalid write request cursor.');+ || BigInt(params.before) > 9_223_372_036_854_775_807n)) throw opError('invalid_params', 'Invalid write request cursor.', 'Pass `before` exactly as the previous response\'s `next` value, or omit it to start from the newest receipt.');if (access.sourceIds && !access.sourceIds.includes(sourceId)) return { requests: [], next: null };const { listWriteRequests } = await import('../persistence/control.ts');const slugAllowList = ctx.viaSubagent !== true ? undefined : ctx.allowedSlugPrefixes?.length ? ctx.allowedSlugPrefixes@@ -182,17 +194,17 @@ export const persistenceOperations: Operation[] = [const { principal } = await receiptAccess(ctx, 'cancel_write_request');const { getWriteRequest, writeHealthFacts } = await import('../persistence/journal.ts');const row = await getWriteRequest(ctx.engine, principal, id);- if (!row || !await visible(ctx, row)) throw missing();+ if (!row || !await visible(ctx, row)) throw missing(callerSource(ctx));if (ctx.dryRun) return { dry_run: true, action: 'cancel_write_request', request_id: id, state: row.state };const { cancelWriteRequest } = await import('../persistence/control.ts');const cancelled = await cancelWriteRequest(ctx.engine, principal, id, {authorize: async (engine, current) => {const lockedCtx = { ...ctx, engine };await receiptAccess(lockedCtx, 'cancel_write_request', true);- if (!await visible(lockedCtx, current)) throw missing();+ if (!await visible(lockedCtx, current)) throw missing(callerSource(ctx));},});- if (!cancelled) throw missing();+ if (!cancelled) throw missing(callerSource(ctx));return publicReceipt(ctx, cancelled, (await writeHealthFacts(ctx.engine, [cancelled])).get(cancelled.id));},},diff --git a/src/core/ops/request-tools.ts b/src/core/ops/request-tools.tsindex 72fc8bb141..81cc538046 100644--- a/src/core/ops/request-tools.ts+++ b/src/core/ops/request-tools.ts@@ -21,7 +21,11 @@ import { hasScope, operationScopesAllowed } from '../scope.ts';import { RateLimiter } from '../../mcp/rate-limit.ts';import { writeSurfaceChangeAudit } from '../surface-audit.ts';import type { Operation, OperationContext } from './contract.ts';-import { OperationError } from './contract.ts';+import { OperationError, opError } from './contract.ts';+import { hostFix, invalidParam } from './op-fix.ts';++/** stdio and legacy bearer tokens have no per-client surface row: the server's own start flag decides. */+const NO_CLIENT_SURFACE = 'no per-client surface on this transport; the server surface is set on the host with `gbrain serve --surface <verbs|starter|full>`';import { opAllowedForBoundClient } from './context.ts';// --- WP4 (T9): request_tools — discovery + pull-based per-client unlock ---@@ -150,9 +154,10 @@ const request_tools: Operation = {// together is ambiguous (persist vs descriptor fetch) — reject loudly// rather than silently persisting and ignoring the tools list.if (p.surface !== undefined && p.tools !== undefined) {- throw new OperationError(+ throw opError('invalid_params','pass either {surface} (persist) or {tools} (descriptor fetch), not both.',+ 'Call request_tools once with `tools` to fetch descriptors, and separately with `surface` to change this client\'s tool surface.',);}@@ -162,18 +167,19 @@ const request_tools: Operation = {if (!isMcpSurface(requested)) {// Backstop for direct handler calls — MCP dispatch already rejects// via the enum in validateParams (invalid_params naming the valid set).- throw new OperationError('invalid_params', `surface must be one of: verbs, starter, full (got an unrecognized value)`);+ throw invalidParam(ctx, 'request_tools', 'surface', 'surface must be one of: verbs, starter, full (got an unrecognized value)', { choices: ['verbs', 'starter', 'full'] });}const clientId = ctx.auth?.clientId;if (!clientId) {// stdio has no per-token identity; a surface persist has nowhere to land.- return { persisted: false, reason: 'no per-client surface on this transport; use --surface' };+ return { persisted: false, reason: NO_CLIENT_SURFACE };}if (surfaceWiderThan(requested, ceiling)) {- const e = new OperationError(+ const e = opError('permission_denied',`surface '${requested}' is above this server's ceiling '${ceiling}' (D2: per-client surfaces narrow, never widen).`,- `The operator caps this transport at --surface ${ceiling}; widening requires a server restart with a wider --surface.`,+ `The brain host's operator caps this server at surface '${ceiling}'; a wider surface needs that server restarted with \`gbrain serve --surface ${requested}\`. Tools outside '${ceiling}' stay unavailable on this connection until then.`,+ { fix: hostFix(ctx, ['gbrain', 'serve', '--surface', requested], 'The surface ceiling is a server start flag; only the host that runs the server can widen it.') },);e.detail = `ceiling=${ceiling}`; // amendment 4 key=value denial grammar; ENG-11 assign-afterthrow e;@@ -194,14 +200,16 @@ const request_tools: Operation = {}if (rows.length === 0) {// Legacy bearer tokens carry a clientId that is not an oauth_clients row.- return { persisted: false, reason: 'no per-client surface on this transport; use --surface' };+ return { persisted: false, reason: NO_CLIENT_SURFACE };}const current = rows[0] as { surface?: string | null; surface_set_by?: string | null };const operatorLocked = () => {- const e = new OperationError(+ const e = opError('permission_denied',"this client's surface is operator-pinned and cannot be self-changed (amendment 19).",`Ask the brain operator to change it: gbrain auth rescope-client ${clientId} --surface ${requested}`,+ { fix: hostFix(ctx, ['gbrain', 'auth', 'rescope-client', clientId, '--surface', requested],+ 'The operator pinned this client\'s surface; only the brain host\'s operator can change a pin.') },);e.detail = 'locked_by=operator';return e;@@ -214,7 +222,7 @@ const request_tools: Operation = {}const rl = requestToolsPersistLimiter.check(clientId);if (!rl.allowed) {- throw new OperationError(+ throw opError('rate_limited','surface persistence is rate-limited to ~5 changes per hour per client (D14.5).',`Retry after ~${rl.retryAfter ?? 60}s.`,diff --git a/src/core/ops/skillopt.ts b/src/core/ops/skillopt.tsindex f8038f2c2a..da2eb278eb 100644--- a/src/core/ops/skillopt.ts+++ b/src/core/ops/skillopt.ts@@ -9,7 +9,8 @@*/import type { Operation } from './contract.ts';-import { OperationError } from './contract.ts';+import { opError } from './contract.ts';+import { hostFix, invalidParam, paramUse } from './op-fix.ts';// v0.41.18.0 (A7 + T16, codex finding #5): MCP op for federated / thin-client// brain installs to drive `gbrain onboard --auto` over MCP. Admin scope@@ -79,7 +80,8 @@ const run_onboard: Operation = {// 'auto' and 'auto-with-prompt' modes: require --max-usd per A12 + A20// safety posture (cron-safety; refuses surprise spend).if (maxUsd === undefined) {- throw new OperationError('invalid_params', `mode='${mode}' requires max_usd (cron-safety cap)`);+ throw opError('invalid_params', `mode='${mode}' requires max_usd (cron-safety cap)`,+ `Pass ${paramUse(ctx, 'max_usd', 1)} (a spend cap in USD) with mode '${mode}', or use mode 'check' for a free plan. Spending needs the user's OK: ask before choosing a cap.`);}// Critical T16 + codex #5 security gate: filter out PROTECTED_JOB_NAMES@@ -160,7 +162,7 @@ const run_skillopt: Operation = {// every derived path is contained by construction. Applies to all callers.const skillNameRaw = (p.skill_name as string) ?? '';if (!/^[a-z0-9][a-z0-9-]*$/.test(skillNameRaw)) {- throw new OperationError('invalid_params', `run_skillopt: skill_name must be kebab-case (matching ^[a-z0-9][a-z0-9-]*$); got '${skillNameRaw}'`);+ throw invalidParam(ctx, 'run_skillopt', 'skill_name', 'run_skillopt: skill_name must be kebab-case (matching ^[a-z0-9][a-z0-9-]*$)', { example: 'query' });}if (ctx.remote !== false) {// Remote: enforce per-skill allowlist read from config.@@ -174,7 +176,9 @@ const run_skillopt: Operation = {} catch { /* fall through to deny */ }const skillName = (p.skill_name as string) ?? '';if (!allowed.includes(skillName)) {- throw new OperationError('permission_denied', `run_skillopt: skill '${skillName}' is not in skillopt.allowed_skills allowlist (default deny-all for remote callers)`);+ throw opError('permission_denied', `run_skillopt: skill '${skillName}' is not in skillopt.allowed_skills allowlist (default deny-all for remote callers)`,+ `Remote callers can optimize only skills the brain host's operator allow-lists (skillopt.allowed_skills, deny-all by default); ask them to add '${skillName}', or have the host run the optimizer itself.`,+ { fix: hostFix(ctx, ['gbrain', 'skillopt', skillName], 'Runs the optimizer on the brain host, where no remote allowlist applies.', { consent: ['paid'] }) });}}const { clampRemoteReflectMaxTokens } = await import('../skillopt/output-cap.ts');@@ -182,7 +186,8 @@ const run_skillopt: Operation = {try {reflectMaxTokens = clampRemoteReflectMaxTokens(p.reflect_max_tokens);} catch (err) {- throw new OperationError('invalid_params', `run_skillopt: ${err instanceof Error ? err.message : String(err)}`);+ throw opError('invalid_params', `run_skillopt: ${err instanceof Error ? err.message : String(err)}`,+ 'Lower reflect_max_tokens to the stated cap, or omit it to use the default.');}const { runSkillOpt } = await import('../skillopt/orchestrator.ts');const { autoDetectSkillsDirReadOnly } = await import('../repo-root.ts');@@ -190,7 +195,10 @@ const run_skillopt: Operation = {let sharedSkill: import('../skillopt/types.ts').SkillOptOpts['sharedSkill'];if (p.shared_skill === true) {for (const field of ['source_id', 'source_incarnation', 'pack_id', 'expected_revision', 'request_id']) {- if (typeof p[field] !== 'string' || !p[field]) throw new OperationError('invalid_params', `shared_skill requires ${field}.`);+ if (typeof p[field] !== 'string' || !p[field]) {+ throw opError('invalid_params', `shared_skill requires ${field}.`,+ `With shared_skill: true pass source_id, source_incarnation, pack_id and expected_revision from get_skill, and a fresh request_id (UUID); ${field} is missing.`);+ }}const { assertSkillCapability } = await import('../shared-skills/policy.ts');assertSkillCapability(ctx, 'skill_editor', 'put_skill');@@ -201,7 +209,8 @@ const run_skillopt: Operation = {? await (await import('../shared-skills/optimizer.ts')).sharedOptimizerSkillsDir(ctx, sharedSkill.source_id, sharedSkill.source_incarnation): autoDetectSkillsDirReadOnly(process.cwd()).dir;if (!skillsDir) {- throw new OperationError('config_error', 'run_skillopt: skills directory not found');+ throw opError('config_error', 'run_skillopt: skills directory not found',+ 'The brain host has no skills directory to optimize. Run `gbrain doctor --json` on the host; it reports where gbrain looks for skills.');}const models = await resolveSkillOptModels(ctx.engine);const skillName = p.skill_name as string;@@ -232,7 +241,8 @@ const run_skillopt: Operation = {catch { /* parent also missing; fall back to resolved form */ }}if (real !== rootReal && !real.startsWith(rootReal + nodePath.sep)) {- throw new OperationError('permission_denied', `run_skillopt: ${label} must resolve within the skills directory for remote callers`);+ throw opError('permission_denied', `run_skillopt: ${label} must resolve within the skills directory for remote callers`,+ `Omit ${label} to use the skill's default benchmark, or pass a path inside the skills directory.`);}};confine('benchmark_path', p.benchmark_path as string | undefined);diff --git a/src/core/ops/skills-catalog.ts b/src/core/ops/skills-catalog.tsindex 7d7efbbd5d..bfa2beb253 100644--- a/src/core/ops/skills-catalog.ts+++ b/src/core/ops/skills-catalog.ts@@ -7,7 +7,8 @@*/import type { Operation } from './contract.ts';-import { OperationError } from './contract.ts';+import { opError } from './contract.ts';+import { hostFix, invalidParam } from './op-fix.ts';import {LIST_SKILLS_DESCRIPTION,GET_SKILL_DESCRIPTION,@@ -39,7 +40,7 @@ const list_skills: Operation = {},handler: async (ctx, p) => {if (p.schema_version === 2) return (await import('../shared-skills/catalog.ts')).listSharedSkills(ctx, p);- if (p.schema_version !== undefined && p.schema_version !== 1) throw new OperationError('invalid_params', 'Supported skill catalog schema versions are 1 and 2.');+ if (p.schema_version !== undefined && p.schema_version !== 1) throw invalidParam(ctx, 'list_skills', 'schema_version', 'Supported skill catalog schema versions are 1 and 2.', { choices: ['1', '2'], example: 2 });const compatibility = await import('../shared-skills/compatibility.ts');if (await compatibility.sharedCatalogActive(ctx)) return compatibility.listLegacySharedSkills(ctx, typeof p.section === 'string' ? p.section : undefined);const sc = await import('../skill-catalog.ts');@@ -81,8 +82,8 @@ const get_skill: Operation = {},handler: async (ctx, p) => {if (p.schema_version === 2) return (await import('../shared-skills/catalog.ts')).getSharedSkill(ctx, sharedSkillReadSelector(p));- if (p.expected_brain_id !== undefined) throw new OperationError('invalid_params', 'expected_brain_id requires schema_version 2; it asserts identity and never selects a brain connection.');- if (p.schema_version !== undefined && p.schema_version !== 1) throw new OperationError('invalid_params', 'Supported skill catalog schema versions are 1 and 2.');+ if (p.expected_brain_id !== undefined) throw opError('invalid_params', 'expected_brain_id requires schema_version 2; it asserts identity and never selects a brain connection.', 'Pass schema_version: 2 with expected_brain_id, or drop expected_brain_id.');+ if (p.schema_version !== undefined && p.schema_version !== 1) throw invalidParam(ctx, 'get_skill', 'schema_version', 'Supported skill catalog schema versions are 1 and 2.', { choices: ['1', '2'], example: 2 });const compatibility = await import('../shared-skills/compatibility.ts');if (await compatibility.sharedCatalogActive(ctx)) return compatibility.getLegacySharedSkill(ctx, p.name, typeof p.source_id === 'string' ? p.source_id : undefined);const sc = await import('../skill-catalog.ts');@@ -271,11 +272,13 @@ const advisor: Operation = {if (!enabled) {// Same k=v detail grammar as assertPublishEnabled (WP1): honest// catalogs hide this op at list time; the throw is the backstop.- const err = new OperationError(+ const err = opError('permission_denied','The advisor is not published over MCP by the brain owner, so it is hidden from your ' +'tool catalog. Ask the owner to enable it if you need it.','The owner can enable it with `gbrain config set mcp.publish_advisor true`.',+ { fix: hostFix(ctx, ['gbrain', 'config', 'set', 'mcp.publish_advisor', 'true'],+ 'Publishing the advisor over MCP is the brain owner\'s choice; only the trusted CLI on the brain host changes it.') },);err.detail = 'config_key=mcp.publish_advisor';throw err;diff --git a/src/core/ops/sources.ts b/src/core/ops/sources.tsindex c3679a88e5..575c9361fe 100644--- a/src/core/ops/sources.ts+++ b/src/core/ops/sources.ts@@ -6,13 +6,28 @@* '../operations.ts' here (cycle).*/-import type { Operation } from './contract.ts';-import { OperationError, authTransport } from './contract.ts';+import type { Operation, OperationContext } from './contract.ts';+import { authTransport, opError } from './contract.ts';+import { hostFix, hostOnlyError, paramUse } from './op-fix.ts';+import { isValidSourceId } from '../source-id.ts';import { assertSourceInCallerScope, assertSourceInCallerWriteScope, sourceScopeOpts } from './context.ts';import { resolveAuthCapabilities } from '../harness/capabilities.ts';// --- v0.28: whoami + sources management ---+/** A source id from params, validated for argv; an unsafe id is left out rather than interpolated. */+function sourceIdArg(id: unknown): string[] {+ return isValidSourceId(id) ? [id] : [];+}++/** B6: managed source lifecycle runs only on the verified owner CLI; the refusal names the exact host command. */+function managedLifecycleRefusal(ctx: OperationContext, args: string[]) {+ return hostOnlyError(ctx, 'writer_coordinator_required',+ 'Managed source lifecycle requires the verified owner CLI. An ordinary MCP grant does not confer owner administration authority.',+ ['gbrain', ...args],+ 'With managed persistence on, adding or removing a source changes the brain\'s writer topology, which only its owner CLI may do.');+}+const whoami: Operation = {name: 'whoami',mutating: false,@@ -44,11 +59,12 @@ const whoami: Operation = {return { transport: 'stdio', scopes: [] };}if (!ctx.auth) {- throw new OperationError(+ throw opError('unknown_transport','whoami called over a remote transport that did not thread ctx.auth. ' +'This is a transport bug — every remote call site must populate ctx.auth ' +'or set ctx.remote === false.',+ 'This is a gbrain server bug, not a caller mistake: tell the user, and have `gbrain doctor --json` run on the brain host.',);}// Legacy access_tokens reuse `name` as both clientId and clientName, so the@@ -76,8 +92,8 @@ const sources_add: Operation = {idempotent: false,outputRedaction: 'no_stored_text',description:- 'Register a new source. Supports either --path (existing v0.17 behavior) ' +- 'or --url (v0.28 federated remote-clone path: parses the URL through the ' ++ 'Register a new source. Supports either `path` (existing v0.17 behavior) ' ++ 'or `url` (v0.28 federated remote-clone path: parses the URL through the ' +'SSRF gate, clones into $GBRAIN_HOME/clones/<id>/ via temp-dir + rename ' +'atomicity, and stores remote_url in sources.config). Pre-flight collision ' +'check on id; rollback on either-side failure.',@@ -109,7 +125,7 @@ const sources_add: Operation = {handler: async (ctx, p) => {const { addSource } = await import('../sources-ops.ts');if(ctx.remote!==false&&await (await import('../persistence/ownership.ts')).managedPersistenceEnabled(ctx.engine))- throw new OperationError('writer_coordinator_required','Managed source lifecycle requires the verified owner CLI. An ordinary MCP grant does not confer owner administration authority.');+ throw managedLifecycleRefusal(ctx, ['sources', 'add', ...sourceIdArg(p.id), ...(typeof p.url === 'string' && /^https:\/\/\S+$/.test(p.url) ? ['--url', p.url] : [])]);// v0.28.1 codex finding (CRITICAL + HIGH): a `sources_admin` token over// HTTP MCP must not be able to plant content at arbitrary host paths.@@ -131,11 +147,13 @@ const sources_add: Operation = {const remotePath = isLocal ? (p.path as string | undefined) ?? null : null;const remoteCloneDir = isLocal ? (p.clone_dir as string | undefined) : undefined;if (!isLocal && p.path !== undefined) {- throw new OperationError(+ throw opError('invalid_params','sources_add: path is not honored over MCP (security confinement). ' +- 'Register with --url instead, or run `gbrain sources add --path ...` on the host CLI.',- 'Use --url to register a remote source, or run the command locally with --path.',+ 'Register with `url` instead, or run `gbrain sources add <id> --path <dir>` on the host CLI.',+ `Pass ${paramUse(ctx, 'url', 'https://github.com/owner/repo')} to register a remote Git source, or have the host run the command in fix to register this local directory.`,+ { fix: hostFix(ctx, ['gbrain', 'sources', 'add', ...sourceIdArg(p.id), '--path', String(p.path)],+ 'Local directories can only be registered by the trusted CLI on the brain host (MCP callers cannot plant host paths).') },);}@@ -236,7 +254,7 @@ const sources_remove: Operation = {assertSourceInCallerWriteScope(ctx, p.id as string);const { removeSource } = await import('../sources-ops.ts');if(ctx.remote!==false&&await (await import('../persistence/ownership.ts')).managedPersistenceEnabled(ctx.engine))- throw new OperationError('writer_coordinator_required','Managed source lifecycle requires the verified owner CLI. An ordinary MCP grant does not confer owner administration authority.');+ throw managedLifecycleRefusal(ctx, ['sources', 'remove', ...sourceIdArg(p.id), '--dry-run']);return removeSource(ctx.engine, {id: p.id as string,confirmDestructive: (p.confirm_destructive as boolean) === true,@@ -293,7 +311,11 @@ const sources_inspect: Operation = {localOnly: true,mutating: false,handler: async (ctx, params) => {- if (ctx.remote !== false) throw new OperationError('permission_denied', 'Repository inspection requires the trusted local CLI.');+ if (ctx.remote !== false) {+ throw hostOnlyError(ctx, 'permission_denied', 'Repository inspection requires the trusted local CLI.',+ ['gbrain', 'sources', 'inspect', String(params.path), '--json'],+ 'Inspection reads a local Git checkout, which only the trusted CLI on that machine may do.');+ }const { inspectCompanyBrain } = await import('../company-brain/inspection.ts');return inspectCompanyBrain({ path: params.path as string,profile: params.profile as 'company-brain' | undefined,diff --git a/src/core/ops/sync-status.ts b/src/core/ops/sync-status.tsindex c9eaec37ab..f696fb66cb 100644--- a/src/core/ops/sync-status.ts+++ b/src/core/ops/sync-status.ts@@ -5,8 +5,18 @@* ../operations.ts. Never import from '../operations.ts' here (cycle).*/-import type { Operation } from './contract.ts';-import { OperationError } from './contract.ts';+import type { Operation, OperationContext } from './contract.ts';+import { opError } from './contract.ts';+import { opTransport, readFix } from './op-fix.ts';++/** `gbrain sync --source <id>` on the CLI, `source_id: "<id>"` over MCP. */+function sourceRef(ctx: OperationContext, id: string): string {+ return opTransport(ctx) === 'cli' ? `--source ${id}` : `source_id: "${id}"`;+}++const LIST_SOURCES = readFix('Lists the registered, active source ids sync can target.', {+ argv: ['gbrain', 'sources', 'list'], mcp: { tool: 'sources_list', arguments: {} },+});// --- Sync ---@@ -39,9 +49,11 @@ const sync_brain: Operation = {if (explicit) {const { resolveSourceId, SourceTargetError, ALL_SOURCES } = await import('../source-resolver.ts');if (explicit === ALL_SOURCES) {- throw new OperationError(+ throw opError('invalid_params',`sync_brain targets exactly one source; '${ALL_SOURCES}' is not valid here.`,+ `Pass one registered source id (for example ${sourceRef(ctx, 'default')}); run it once per source to sync several.`,+ { fix: LIST_SOURCES },);}try {@@ -50,7 +62,7 @@ const sync_brain: Operation = {sourceId = await resolveSourceId(ctx.engine, explicit);} catch (e) {if (e instanceof SourceTargetError) {- throw new OperationError('invalid_params', e.message);+ throw opError('invalid_params', e.message, 'Pick a registered, active source id (fix lists them) and pass it explicitly.', { fix: LIST_SOURCES });}throw e;}@@ -61,7 +73,7 @@ const sync_brain: Operation = {derived = await resolveSourceForRepoPath(ctx.engine, repo);} catch (e) {if (e instanceof SourceTargetError) {- throw new OperationError('invalid_params', e.message);+ throw opError('invalid_params', e.message, 'Pick a registered, active source id (fix lists them) and pass it explicitly.', { fix: LIST_SOURCES });}throw e;}@@ -70,12 +82,12 @@ const sync_brain: Operation = {// scope / dotfile context) but `repo` belongs to a different one.// Refuse with a structured error instead of silently picking a side.if (ctx.sourceId && ctx.sourceId !== 'default' && ctx.sourceId !== derived.source_id) {- throw new OperationError(+ throw opError('invalid_params',`repo path resolves to source '${derived.source_id}' (via ${derived.tier}) but the ` +`caller is scoped to source '${ctx.sourceId}'. Pass source_id explicitly to pick one.`,- `Re-run with source_id: '${derived.source_id}' to sync that repo's source, or ` +- `source_id: '${ctx.sourceId}' to force the caller's scope.`,+ `Re-run with ${sourceRef(ctx, derived.source_id)} to sync that repo's source, or ` ++ `${sourceRef(ctx, ctx.sourceId)} to force the caller's scope.`,);}sourceId = derived.source_id;diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex c08fca9bdf..1aee996815 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 229615,- "stdoutSha256": "aaf93740a028c3db9ce963308738d61d0d1b008b249b4cbf6430e1a6fd859630",+ "stdoutBytes": 229621,+ "stdoutSha256": "c8e5f93cf4806fe7e4c6df1544c77779543b3d51023504dcc140383bb690eb1e","toolNames": ["remember","entity",@@ -3988,7 +3988,7 @@"scope": "read"},{- "description": "Register a new source. Supports either --path (existing v0.17 behavior) or --url (v0.28 federated remote-clone path: parses the URL through the SSRF gate, clones into $GBRAIN_HOME/clones/<id>/ via temp-dir + rename atomicity, and stores remote_url in sources.config). Pre-flight collision check on id; rollback on either-side failure.",+ "description": "Register a new source. Supports either `path` (existing v0.17 behavior) or `url` (v0.28 federated remote-clone path: parses the URL through the SSRF gate, clones into $GBRAIN_HOME/clones/<id>/ via temp-dir + rename atomicity, and stores remote_url in sources.config). Pre-flight collision check on id; rollback on either-side failure.","idempotent": false,"local_only": false,"mutating": true,@@ -4330,7 +4330,7 @@"scope": "read"},{- "description": "Sync a chat provider's conversation history into the brain: list new conversations since the watermark, fetch them, and ingest as pages under conversations/<provider>/. Incremental by default; --full re-scans. Local-only (uses on-disk credentials).",+ "description": "Sync a chat provider's conversation history into the brain: list new conversations since the watermark, fetch them, and ingest as pages under conversations/<provider>/. Incremental by default; `full: true` re-scans. Local-only (uses on-disk credentials).","idempotent": false,"local_only": true,"mutating": true,diff --git a/test/ops-error-fixes-g3.test.ts b/test/ops-error-fixes-g3.test.tsnew file mode 100644index 0000000000..1a2762af90--- /dev/null+++ b/test/ops-error-fixes-g3.test.ts@@ -0,0 +1,112 @@+/**+ * Lane B (B2/B6/B7/B8) on the sources / sync / request_tools / skillopt /+ * connectors / receipt / files ops: refusals carry a filled, surface-correct+ * next step, host-only refusals name the exact host command, and MCP text+ * names params, not CLI flags.+ */+import { describe, expect, test } from 'bun:test';+import { operations, type OperationContext } from '../src/core/operations.ts';+import { toAgentError, type Transport } from '../src/core/agent-output.ts';++const op = (name: string) => operations.find(o => o.name === name)!;++function engine(managed = false, rows: unknown[] = []) {+ return {+ kind: 'pglite',+ executeRaw: async (sql: string) => (/persistence_brain/.test(sql) ? [{ enabled: managed }] : rows),+ getConfig: async () => null,+ } as unknown as OperationContext['engine'];+}++function ctx(transport: Transport, over: Partial<OperationContext> = {}): OperationContext {+ return {+ engine: engine(), config: { engine: 'pglite' }, logger: { info() {}, warn() {}, error() {} },+ remote: transport !== 'cli', ...(transport === 'cli' ? {} : { transport }), dryRun: false, sourceId: 'notes',+ ...over,+ } as unknown as OperationContext;+}++async function envelopeOf(name: string, c: OperationContext, params: Record<string, unknown>, callable: string[] = []) {+ const transport: Transport = c.remote === false ? 'cli' : c.transport === 'http' ? 'http' : 'stdio';+ try {+ await op(name).handler(c, params);+ } catch (e) {+ return toAgentError(e, { transport, op: name, render: { transport, isCallable: t => callable.includes(t), preapproved: () => false } });+ }+ throw new Error(`${name} did not throw`);+}++describe('sources ops', () => {+ test('sources_add path over MCP: names `url`, never --url; host fix registers the local directory', async () => {+ const env = await envelopeOf('sources_add', ctx('http'), { id: 'notes', path: '/srv/notes' });+ expect(env.code).toBe('invalid_params');+ expect(env.suggestion).toContain('url: "https://github.com/owner/repo"');+ expect(env.suggestion).not.toMatch(/--url/);+ // The HTTP view never carries host paths (redactForTransport).+ expect(env.fix).toMatchObject({ argv: ['gbrain', 'sources', 'add', 'notes', '--path', '<path>'], actor: 'host_admin', next: 'tell_user_to_run' });+ const stdio = await envelopeOf('sources_add', ctx('stdio'), { id: 'notes', path: '/srv/notes' });+ expect(stdio.fix).toMatchObject({ argv: ['gbrain', 'sources', 'add', 'notes', '--path', '/srv/notes'], actor: 'user', next: 'tell_user_to_run' });+ });++ test('managed lifecycle refusal names the owner CLI command (B6)', async () => {+ const env = await envelopeOf('sources_remove', ctx('stdio', { engine: engine(true) }), { id: 'notes' });+ expect(env).toMatchObject({+ error: 'writer_coordinator_required',+ fix: { argv: ['gbrain', 'sources', 'remove', 'notes', '--dry-run'], actor: 'user', next: 'tell_user_to_run' },+ });+ expect(env.fix?.user_message).toContain('terminal on this machine');+ });++ test('an unsafe source id is never interpolated', async () => {+ const env = await envelopeOf('sources_add', ctx('http', { engine: engine(true) }), { id: '--yes', url: 'https://example.com/x.git' });+ expect(env.fix?.argv).toEqual(['gbrain', 'sources', 'add', '--url', 'https://example.com/x.git']);+ });+});++describe('sync_brain', () => {+ test("'__all__' refusal lists sources and renders the flag per surface", async () => {+ const cli = await envelopeOf('sync_brain', ctx('cli'), { source_id: '__all__' });+ expect(cli.suggestion).toContain('--source default');+ expect(cli.fix).toMatchObject({ argv: ['gbrain', 'sources', 'list'], next: 'run' });+ const mcp = await envelopeOf('sync_brain', ctx('stdio'), { source_id: '__all__' }, ['sources_list']);+ expect(mcp.suggestion).toContain('source_id: "default"');+ expect(mcp.fix).toMatchObject({ mcp: { tool: 'sources_list' }, next: 'run' });+ });+});++describe('request_tools', () => {+ test('an out-of-range surface lists the choices', async () => {+ const env = await envelopeOf('request_tools', ctx('http'), { surface: 'everything' });+ expect(env.suggestion).toContain('one of: verbs, starter, full');+ });++ test('above the ceiling: the host restart command, not a bare --surface', async () => {+ const env = await envelopeOf('request_tools', ctx('http', { surfaceCeiling: 'starter', auth: { clientId: 'gbrain_cl_a', scopes: ['read'], token: 't' } }), { surface: 'full' });+ expect(env).toMatchObject({ error: 'permission_denied', fix: { argv: ['gbrain', 'serve', '--surface', 'full'], actor: 'host_admin' } });+ });+});++describe('skillopt / connectors / receipts / files', () => {+ test('run_onboard auto without max_usd says to ask before spending', async () => {+ const env = await envelopeOf('run_onboard', ctx('http'), { mode: 'auto' });+ expect(env.code).toBe('invalid_params');+ expect(env.suggestion).toContain('max_usd: 1');+ expect(env.suggestion).toContain("user's OK");+ });++ test('connector_sync over MCP names the host command with the provider filled', async () => {+ const env = await envelopeOf('connector_sync', ctx('stdio'), { provider: 'claude' });+ expect(env.fix).toMatchObject({ argv: ['gbrain', 'connectors', 'sync', 'claude', '--dry-run'], actor: 'user', next: 'tell_user_to_run' });+ });++ test('get_write_request not_found points at the caller\'s own receipts', async () => {+ const env = await envelopeOf('get_write_request', ctx('cli'), {});+ expect(env.code).toBe('invalid_params');+ expect(env.suggestion).toContain('request_id');+ });++ test('file_url not found lists stored files', async () => {+ const env = await envelopeOf('file_url', ctx('cli'), { storage_path: 'x/y.png' });+ expect(env.fix).toMatchObject({ argv: ['gbrain', 'files', 'list'], next: 'run' });+ });+});