Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(ops,mcp): B1 — bare throw new Error in op handlers and src/mcp become opError with codes, suggestions and fixes
garrytand11af2df9b65
diff --git a/scripts/agent-contract-baselines/throw-new-error-in-ops.tsv b/scripts/agent-contract-baselines/throw-new-error-in-ops.tsvindex 25b430951d..b524426d40 100644--- a/scripts/agent-contract-baselines/throw-new-error-in-ops.tsv+++ b/scripts/agent-contract-baselines/throw-new-error-in-ops.tsv@@ -1,11 +1,3 @@# shrink-only baseline for scripts/check-agent-contract.ts rule throw-new-error-in-ops: path<TAB>count-src/core/ops/embedding-migration.ts 1-src/core/ops/image.ts 3-src/core/ops/insights.ts 1-src/core/ops/links.ts 1-src/core/ops/orphans.ts 1src/core/schema-migrations/v039-multimodal-dual-column-v0-27-1.ts 2src/core/schema-migrations/v045-facts-hot-memory-v0-31.ts 1-src/mcp/rate-limit.ts 3-src/mcp/source-preflight.ts 1-src/mcp/surface.ts 3diff --git a/src/core/ops/embedding-migration.ts b/src/core/ops/embedding-migration.tsindex ce8fe38a0f..dd46a289bf 100644--- a/src/core/ops/embedding-migration.ts+++ b/src/core/ops/embedding-migration.ts@@ -11,6 +11,7 @@*/import type { Operation } from './contract.ts';+import { hostOnlyError } from './op-fix.ts';// --- #3390: provider-agnostic embedding migration ---@@ -37,7 +38,11 @@ const migrate_embeddings: Operation = {// reachable from a remote transport even if a future dispatch path// forgets the localOnly filter.if (ctx.remote !== false) {- throw new Error('migrate_embeddings is local-only. Run `gbrain migrate embeddings` on the host.');+ const to = typeof p.to === 'string' && /^[a-z0-9_-]+:[A-Za-z0-9._/-]+$/.test(p.to) ? ['--to', p.to] : [];+ throw hostOnlyError(ctx, 'permission_denied', 'migrate_embeddings is local-only. Run `gbrain migrate embeddings` on the host.',+ ['gbrain', 'migrate', 'embeddings', ...to, '--dry-run'],+ 'Re-embedding rebuilds the vector schema and spends provider money, so only the trusted CLI on the brain host runs it; the dry run prints the plan and cost first.',+ { consent: [] });}// ONE shared orchestrator with the CLI (round-2 #11): locks, retarget// gate, DB-verified skip, heartbeat, and completion bookkeeping arediff --git a/src/core/ops/image.ts b/src/core/ops/image.tsindex 1f0f6b7139..9e8c74f41b 100644--- a/src/core/ops/image.ts+++ b/src/core/ops/image.ts@@ -10,7 +10,7 @@ import { readPolicyOpts } from './context.ts';*/import type { BrainEngine } from '../engine.ts';-import type { Operation } from './contract.ts';+import { opError, type Operation } from './contract.ts';import { resolveRequestedScope } from './context.ts';// --- v0.36 Phase 2: search_by_image (image-as-query) ---@@ -50,17 +50,20 @@ const search_by_image: Operation = {// entry, before any file I/O fires. validateParams catches it too at the// dispatch layer; this is defense-in-depth.if (ctx.remote === true && imagePath) {- throw new Error(- 'permission_denied: image_path is not permitted for remote callers (D18). ' +- 'Use image_url or image_data instead.',- );+ throw opError('permission_denied',+ 'permission_denied: image_path is not permitted for remote callers (D18). Use image_url or image_data instead.',+ 'Pass the image as `image_data` (base64 PNG/JPEG/WebP) or `image_url` (http(s)) instead of `image_path`.');}if (!imagePath && !imageUrl && !imageData) {- throw new Error('search_by_image requires one of: image_path, image_url, image_data');+ throw opError('invalid_params', 'search_by_image requires one of: image_path, image_url, image_data',+ ctx.remote === false+ ? 'Pass one image input: --image-path <file>, --image-url <http(s) URL> or --image-data <base64>.'+ : 'Pass one image input: `image_data` (base64 PNG/JPEG/WebP) or `image_url` (http(s) URL).');}if ([imagePath, imageUrl, imageData].filter(Boolean).length > 1) {- throw new Error('search_by_image accepts only one of: image_path, image_url, image_data');+ throw opError('invalid_params', 'search_by_image accepts only one of: image_path, image_url, image_data',+ 'Pass exactly one image input: drop the others and keep the one that names the image.');}// D23-#6 — remote OAuth clients are charged through the durablediff --git a/src/core/ops/insights.ts b/src/core/ops/insights.tsindex 8f2f8f7a1e..bccb5bc41b 100644--- a/src/core/ops/insights.ts+++ b/src/core/ops/insights.ts@@ -11,6 +11,7 @@import type { Operation } from './contract.ts';import { OperationError } from './contract.ts';+import { invalidParam } from './op-fix.ts';import { sourceScopeOpts, readPolicyOpts } from './context.ts';import {FIND_EXPERTS_DESCRIPTION,@@ -302,7 +303,7 @@ const find_trajectory: Operation = {},handler: async (ctx, p) => {if (typeof p.entity_slug !== 'string' || !p.entity_slug.trim()) {- throw new Error('find_trajectory requires entity_slug (string)');+ throw invalidParam(ctx, 'find_trajectory', 'entity_slug', 'find_trajectory requires entity_slug (string)', { example: 'people/alice-example' });}const metric = typeof p.metric === 'string' ? p.metric : undefined;const kind = (p.kind === 'metric' || p.kind === 'event' || p.kind === 'all')diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex d5bc5519f2..d552f795e6 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -8,7 +8,7 @@ import { coordinatedManualLinkWrite } from '../persistence/manual-links.ts';* '../operations.ts' here (cycle).*/-import { OperationError, type Operation } from './contract.ts';+import { OperationError, opError, type Operation } from './contract.ts';import {assertExplicitSourceLive,enforceClientSlugFence,@@ -89,10 +89,10 @@ const add_link: Operation = {// and forbid forging the reconciliation-managed built-ins.const linkSource = ((p.link_source as string) || 'manual').trim();if (MANAGED_LINK_SOURCES.includes(linkSource)) {- throw new Error(+ throw opError('invalid_params',`link_source '${linkSource}' is reconciliation-managed and cannot be set manually; ` +`use 'manual' (the default) or a custom kebab tag like 'citation-graph'`,- );+ `Omit link_source (defaults to 'manual') or pass a custom kebab tag such as 'citation-graph'; ${MANAGED_LINK_SOURCES.join(', ')} are reserved for reconciliation.`);}// v0.31.8 (D7): single ctx.sourceId scopes both endpoints + origin. Cross-// source link creation is out of scope for this wave; use the engine APIdiff --git a/src/core/ops/orphans.ts b/src/core/ops/orphans.tsindex 4827251b3e..9b09178475 100644--- a/src/core/ops/orphans.ts+++ b/src/core/ops/orphans.ts@@ -5,9 +5,9 @@* in ../operations.ts. Never import from '../operations.ts' here (cycle).*/-import type { Operation } from './contract.ts';import { assertSourceInCallerScope, readPolicyOpts } from './context.ts';-import { OperationError } from './contract.ts';+import { OperationError, type Operation } from './contract.ts';+import { invalidParam } from './op-fix.ts';// --- Orphans ---@@ -47,7 +47,7 @@ const find_orphans: Operation = {// quietly fall back to the default and misreport the orphan set.const mode = p.mode === undefined ? undefined : (p.mode as string);if (mode !== undefined && mode !== 'inbound' && mode !== 'islanded') {- throw new Error(`find_orphans: invalid mode "${mode}" — use 'inbound' or 'islanded'`);+ throw invalidParam(ctx, 'find_orphans', 'mode', 'find_orphans: invalid mode — use \'inbound\' or \'islanded\'', { choices: ['islanded', 'inbound'] });}// v0.41.29.0 (Codex F8): scope by the caller's source (ctx.sourceId /// ctx.auth.allowedSources) via the canonical sourceScopeOpts ladder.diff --git a/src/mcp/rate-limit.ts b/src/mcp/rate-limit.tsindex a8e5644122..c9dd56506a 100644--- a/src/mcp/rate-limit.ts+++ b/src/mcp/rate-limit.ts@@ -49,9 +49,9 @@ export class RateLimiter {private readonly clock: Clock;constructor(opts: RateLimitOpts, clock: Clock = Date.now) {- if (opts.limit <= 0) throw new Error('RateLimiter: limit must be > 0');- if (opts.windowMs <= 0) throw new Error('RateLimiter: windowMs must be > 0');- if (opts.lruCap <= 0) throw new Error('RateLimiter: lruCap must be > 0');+ if (opts.limit <= 0) throw new RangeError('RateLimiter: limit must be > 0');+ if (opts.windowMs <= 0) throw new RangeError('RateLimiter: windowMs must be > 0');+ if (opts.lruCap <= 0) throw new RangeError('RateLimiter: lruCap must be > 0');this.opts = opts;this.clock = clock;}diff --git a/src/mcp/source-preflight.ts b/src/mcp/source-preflight.tsindex b38413b5a9..a84419a40c 100644--- a/src/mcp/source-preflight.ts+++ b/src/mcp/source-preflight.ts@@ -1,6 +1,8 @@import type { BrainEngine } from '../core/engine.ts';import { isValidSourceId, ALL_SOURCES } from '../core/source-id.ts';import { isEngineDegraded } from '../core/degraded-marker.ts';+import { opError } from '../core/ops/contract.ts';+import { readFix } from '../core/ops/op-fix.ts';/*** Stdio-lane preflight: a well-formed `GBRAIN_SOURCE` that names NO active@@ -56,11 +58,13 @@ export async function assertStdioSourceBindable(return;}if (rows.length === 0) {- throw new Error(+ throw opError('unknown_source',`GBRAIN_SOURCE="${env}" is not a registered active source (missing or archived); ` +`refusing to serve a phantom scope (reads would return nothing, writes would fail ` +`on the sources foreign key). Run \`gbrain sources list\`, then set GBRAIN_SOURCE ` +`to a listed id or unset it.`,- );+ 'Set GBRAIN_SOURCE to an id that `gbrain sources list` shows (or unset it) in the environment that launches this MCP server, then restart it.',+ { fix: { ...readFix('Lists the registered sources so GBRAIN_SOURCE can name one.', { argv: ['gbrain', 'sources', 'list'] }), actor: 'user',+ user_message: 'The MCP server is bound to a source that does not exist. Please set GBRAIN_SOURCE to one of the ids `gbrain sources list` prints, or unset it, and restart the server.' } });}}diff --git a/src/mcp/surface.ts b/src/mcp/surface.tsindex 138fa5abed..ec921ece9e 100644--- a/src/mcp/surface.ts+++ b/src/mcp/surface.ts@@ -34,6 +34,7 @@ import type { Operation } from '../core/operations.ts';import type { GBrainConfig } from '../core/config.ts';import type { BrainEngine } from '../core/engine.ts';import { VERB_NAMES } from '../core/verbs.ts';+import { opError } from '../core/ops/contract.ts';import { BRAIN_TOOL_ALLOWLIST } from '../core/minions/tools/brain-allowlist.ts';export type McpSurface = 'verbs' | 'starter' | 'full';@@ -133,10 +134,11 @@ export function parseSurfaceFlag(args: string[]): McpSurface | null {if (idx < 0) return null;const raw = args[idx + 1];if (raw === undefined || raw.startsWith('--')) {- throw new Error(`--surface requires a value: verbs | starter | full`);+ throw opError('invalid_params', `--surface requires a value: verbs | starter | full`, 'Pass --surface verbs, --surface starter or --surface full (default full).');}if (!isMcpSurface(raw)) {- throw new Error(`Unknown --surface "${raw}". Use: verbs (the 7 memory verbs) | starter (the ~20 daily-driver ops) | full (all operations, default)`);+ throw opError('invalid_params', `Unknown --surface "${raw}". Use: verbs (the 7 memory verbs) | starter (the ~20 daily-driver ops) | full (all operations, default)`,+ 'Pass --surface verbs (the 7 memory verbs), --surface starter (the ~20 daily-driver ops) or --surface full (all operations, default).');}return raw;}@@ -157,7 +159,8 @@ export function parseAccessFlag(args: string[]): McpAccess {if (idx < 0) return 'full';const raw = args[idx + 1];if (raw !== 'full' && raw !== 'read-only') {- throw new Error('--access takes read-only or full (default full); see docs/mcp/ADMIN.md#read-only-stdio-serve');+ throw opError('invalid_params', '--access takes read-only or full (default full); see docs/mcp/ADMIN.md#read-only-stdio-serve',+ 'Pass --access read-only or --access full (default full).', { docs: 'docs/mcp/ADMIN.md#read-only-stdio-serve' });}return raw;}