Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(agent-contract): A1 error contract wired through MCP dispatch, serve-http and the thin client
garrytanbd3984fbb00a
diff --git a/src/cli.ts b/src/cli.tsindex 77feb9d737..f7472b8eac 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -35,6 +35,7 @@ import { resolveSourceIdEngineFree } from './core/source-resolver.ts';import { formatVolunteeredPage } from './core/context/volunteer.ts';import type { Operation, OperationContext } from './core/operations.ts';import { currentCliWriteWait } from './core/persistence/write-wait.ts';+import { isScopeErrorCode } from './core/error-catalogue.ts';import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';import { serializeMarkdown } from './core/markdown.ts';import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';@@ -831,7 +832,7 @@ async function runThinClientRouted(}break;case 'tool_error':- if (e.detail?.code === 'missing_scope') {+ if (isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason)) {console.error('Missing OAuth scope on this client.');console.error('On the host, re-register the client with broader scopes:');console.error(' gbrain auth register-client <name> --grant-types client_credentials --scopes read,write,admin');diff --git a/src/commands/serve-http-mcp.ts b/src/commands/serve-http-mcp.tsindex 94261106f0..a0cbeb7388 100644--- a/src/commands/serve-http-mcp.ts+++ b/src/commands/serve-http-mcp.ts@@ -20,7 +20,9 @@ import { createSkillResources } from '../mcp/skill-resources.ts';import { resolveAuthCapabilities } from '../core/harness/capabilities.ts';import { resolveWritebackConfig, ambientOptsFrom } from '../core/facts/writeback-config.ts';import { hasScope, operationScopesAllowed } from '../core/scope.ts';-import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, acceptedPendingReceipt, type ToolResult } from '../mcp/dispatch.ts';+import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult, acceptedPendingReceipt, unknownToolEnvelope, errorResult, dispatchRenderContext, type ToolResult } from '../mcp/dispatch.ts';+import { toAgentError } from '../core/agent-output.ts';+import { opError } from '../core/ops/contract.ts';import { resolveStrictParamsMode } from '../mcp/validate-params.ts';import { buildToolDefs } from '../mcp/tool-defs.ts';import {@@ -403,7 +405,8 @@ async function callMcpTool(ctx: ServeHttpContext, state: McpRequestState, requeserror: errorPayload,timestamp: new Date().toISOString(),});- return { content: [{ type: 'text', text: JSON.stringify({ error: errorPayload }) }], isError: true };+ // Agent contract v1 (A1): the one envelope, not the nested legacy StructuredError.+ return errorResult(e, { remote: true, transport: 'http', auth: authInfo, surface, ...(surfaceAllowedOps ? { allowedOps: surfaceAllowedOps } : {}) }, { op: name });}return recordMcpToolResult(ctx, state, name, toolResult, logParamsObj, broadcastParams);@@ -434,7 +437,9 @@ async function rejectUnknownMcpOperation(ctx: ServeHttpContext, state: McpRequeserror: { code: 'unknown_operation', message: `Unknown: ${name}` },timestamp: new Date().toISOString(),});- return { content: [{ type: 'text', text: JSON.stringify({ error: 'unknown_operation', message: `Unknown: ${name}` }) }], isError: true };+ // Frozen v1 pair: `error: unknown_operation` stays; `code: unknown_tool`.+ return unknownToolEnvelope(name, { remote: true, transport: 'http', auth: authInfo, surface: state.surface,+ ...(state.surfaceAllowedOps ? { allowedOps: state.surfaceAllowedOps } : {}) }, 'unknown_operation');}async function rejectInsufficientMcpScope(@@ -472,17 +477,10 @@ async function rejectInsufficientMcpScope(error: { code: 'insufficient_scope', message: `requires '${requiredScope}'` },timestamp: new Date().toISOString(),});- return {- content: [{- type: 'text',- text: JSON.stringify({- error: 'insufficient_scope',- message: `Operation ${name} requires '${requiredScope}' scope`,- your_scopes: authInfo.scopes,- }),- }],- isError: true,- };+ const denial = opError('insufficient_scope', `Operation ${name} requires '${requiredScope}' scope`,+ `Ask the brain host's operator to grant the '${requiredScope}' scope to this client, then reconnect.`);+ const envelope = toAgentError(denial, { transport: 'http', op: name, render: dispatchRenderContext({ remote: true, transport: 'http', auth: authInfo }) });+ return { content: [{ type: 'text', text: JSON.stringify({ ...envelope, your_scopes: authInfo.scopes }) }], isError: true };}async function recordMcpToolResult(@@ -578,10 +576,7 @@ async function serveMcpRequest(server: Server, req: Request, res: Response): Pro} catch (e) {console.error('MCP request handler error:', e instanceof Error ? e.message : e);if (!res.headersSent) {- res.status(500).json({- error: 'internal_error',- message: e instanceof Error ? e.message : 'Unknown error',- });+ res.status(500).json(toAgentError(e, { transport: 'http', render: dispatchRenderContext({ remote: true, transport: 'http' }) }));}}}diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex ed16ceba2d..262b7d9d40 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -15,7 +15,11 @@ import { join } from 'node:path';import { VERSION } from '../version.ts';import { OperationError } from './ops/contract.ts';import { StructuredAgentError } from './errors.ts';-import { codeEntry, codeClass, codeRetryable, exitCodeForCode } from './error-catalogue.ts';+import { canonicalCodeFor, codeEntry, codeClass, codeRetryable, exitCodeForCode } from './error-catalogue.ts';+import { VERB_NAMES } from './verbs.ts';+import { classifyPgAccessError, formatDbAccessMarker } from './pg-access-classify.ts';+import { redactConnectionInfo } from './audit/redact-connection-info.ts';+import { redactUrlsInText } from './url-redact.ts';import { recordAgentContractEvent } from './agent-contract-log.ts';export const CONTRACT_VERSION = 1 as const;@@ -105,6 +109,8 @@ export interface AgentErrorContext {idempotent?: boolean;outcome?: 'not_started' | 'failed' | 'unknown' | 'committed' | 'pending';render: RenderContext;+ /** Additive: the configured DB url + resolved brain id for the GBRAIN_DB_ACCESS classifier row (a mount never reads as host). */+ db?: { url: string | null; brainId?: string };}export interface CliErrorRender { stdout?: string; stderr?: string; exitCode: number }@@ -371,36 +377,234 @@ export function buildEnvelope(p: EnvelopeParts, ctx: RenderContext): AgentEnvelo};}+const VERB_SET: ReadonlySet<string> = new Set(VERB_NAMES);+const isVerbOp = (ctx: AgentErrorContext) => ctx.op !== undefined && VERB_SET.has(ctx.op);++/** The registry's diagnostic default: doctor on the brain host (MCP run_doctor where callable). */+function diagnosticFix(ctx: AgentErrorContext, why: string): Action {+ const remoteHost = ctx.transport === 'http';+ return {+ argv: ['gbrain', 'doctor', '--json'],+ ...(ctx.render.isCallable('run_doctor') ? { mcp: { tool: 'run_doctor', arguments: {} } } : {}),+ consent: [],+ actor: remoteHost ? 'host_admin' : 'agent',+ why,+ requires_exclusive: false,+ };+}++/**+ * A1 safe-recovery invariant: a mutating op with an unknown or pending+ * outcome is never told to retry. The fix inspects state: the caller's own+ * receipt on its channel, a job's status, or nothing (no receipt → no receipt+ * command; the op's read-side diagnostic stays the fix).+ */+function recoveryFix(p: EnvelopeParts, ctx: AgentErrorContext): Action | undefined {+ const outcomeOpen = ctx.outcome === 'unknown' || ctx.outcome === 'pending';+ if (!ctx.mutating || !outcomeOpen) return undefined;+ const receipt = p.write_request as { request_id?: unknown } | undefined;+ const requestId = typeof receipt?.request_id === 'string' && /^[0-9a-f-]{36}$/i.test(receipt.request_id) ? receipt.request_id : undefined;+ if (!requestId) return undefined;+ const why = 'The write may still commit; its receipt says whether it did. Do not resubmit until the receipt is terminal.';+ if (ctx.transport === 'cli') {+ return { argv: ['gbrain', 'write-request', '--', requestId], consent: [], actor: 'agent', why, requires_exclusive: false };+ }+ return {+ argv: ['gbrain', 'write-request', '--', requestId],+ mcp: { tool: 'get_write_request', arguments: { request_id: requestId } },+ consent: [], actor: 'agent', why, requires_exclusive: false,+ };+}++const REFRESH_REFUSALS: ReadonlySet<string> = new Set([+ 'refresh_not_managed', 'refresh_not_owner', 'refresh_no_upstream', 'fetch_failed', 'refresh_diverged', 'refresh_dirty',+ 'sync_in_progress', 'refresh_in_progress', 'refresh_drain_timeout', 'refresh_source_changed', 'refresh_recovery_required',+ 'worktree_refreshing',+]);++type Row = { match: (e: unknown) => boolean; map: (e: any, ctx: AgentErrorContext) => EnvelopeParts };++/** RemoteMcpError transport reasons (no server envelope) → registry codes. */+const REMOTE_REASON_CODE: Record<string, string> = {+ config: 'config_error', discovery: 'unavailable', auth: 'invalid_token', auth_after_refresh: 'invalid_token',+ 'network:timeout': 'timeout', 'network:aborted': 'interrupted', parse: 'internal_error',+};++const named = (name: string) => (e: unknown) => e instanceof Error && e.name === name;++/** The normaliser table: first matching row wins; the last row is the unknown-throw fallback. */+const ROWS: Row[] = [+ {+ match: e => e instanceof OperationError,+ map: (e: OperationError, ctx) => {+ const j = e.toJSON() as Record<string, unknown>;+ let fix = e.fix;+ if (!fix && REFRESH_REFUSALS.has(e.code) && e.suggestion) {+ const argv = argvFromCommand(e.suggestion);+ if (argv) fix = { argv, consent: [], actor: 'agent', why: e.message, requires_exclusive: false };+ }+ return {+ error: e.code, code: e.canonicalCode, message: e.message, suggestion: e.suggestion,+ reason: e.reason, why: e.why, fix, docs: e.docs, notices: e.notices, detail: e.detail,+ protocol_version: e.protocolVersion === 1 ? 1 : undefined,+ write_request: j.write_request, write_error: e.writeError,+ };+ },+ },+ {+ match: e => e instanceof StructuredAgentError,+ map: (e: StructuredAgentError) => ({+ error: e.envelope.code, code: canonicalCodeFor(e.envelope.code), message: e.envelope.message,+ suggestion: e.envelope.hint, docs: e.envelope.docs_url,+ }),+ },+ {+ match: e => e instanceof Error && (e as { tag?: unknown }).tag === 'BUDGET_EXHAUSTED',+ map: (e: Error & { reason: string; cap: number; pricing?: { model: string; units: string[]; lookup: string; register_command: string } }, ctx) => {+ if (e.reason !== 'no_pricing' || !e.pricing) {+ return { error: 'cost_cap_exceeded', code: 'cost_cap_exceeded', message: e.message, reason: e.reason };+ }+ const argv = argvFromPricing(e.pricing.register_command);+ return {+ error: 'no_pricing', code: 'no_pricing', message: e.message, reason: 'no_pricing',+ suggestion: e.pricing.lookup,+ fix: argv ? {+ argv, consent: [], actor: ctx.transport === 'cli' ? 'agent' : 'host_admin',+ why: 'A cost cap needs a price for every model it covers; registering the rate lets the cap be enforced.',+ requires_exclusive: false,+ inputs: e.pricing.units.map(u => ({ name: u, how: e.pricing!.lookup })),+ } : undefined,+ };+ },+ },+ {+ match: named('RemoteMcpError'),+ map: (e: Error & { reason: string; detail?: Record<string, unknown> }) => {+ const d = e.detail ?? {};+ const wire = typeof d.code === 'string' ? d.code : REMOTE_REASON_CODE[e.reason === 'network' ? `network:${String(d.kind)}` : e.reason] ?? 'unavailable';+ const remoteCode = typeof d.canonical_code === 'string' ? d.canonical_code : canonicalCodeFor(wire);+ return {+ error: wire, code: remoteCode, message: typeof d.message === 'string' ? d.message : e.message,+ suggestion: typeof d.suggestion === 'string' ? d.suggestion : undefined,+ reason: typeof d.reason === 'string' ? d.reason : undefined,+ why: typeof d.why === 'string' ? d.why : undefined,+ docs: typeof d.docs === 'string' ? d.docs : undefined,+ detail: typeof d.server_detail === 'string' ? d.server_detail : undefined,+ protocol_version: d.protocol_version === 1 ? 1 : undefined,+ write_request: d.write_request, write_error: typeof d.write_error === 'string' ? d.write_error : undefined,+ notices: Array.isArray(d.notices) ? d.notices as Notice[] : undefined,+ fix: d.fix && typeof d.fix === 'object' ? d.fix as Action : undefined,+ };+ },+ },+ {+ match: named('CredentialError'),+ map: (e: Error & { code: string; problem: string; cause_text: string; fix: string; doc_url: string }) => ({+ error: e.code, code: e.code, message: e.problem, why: e.cause_text, suggestion: e.fix, docs: e.doc_url,+ }),+ },+ {+ match: e => named('AIConfigError')(e) || named('AITransientError')(e),+ map: (e: Error & { fix?: string }) => ({+ error: 'unavailable', code: 'unavailable', message: e.message,+ reason: e.name === 'AIConfigError' ? 'ai_config' : 'ai_transient',+ suggestion: e.fix, retryable: e.name === 'AITransientError',+ }),+ },+ {+ match: named('GBrainError'),+ map: (e: Error & { problem: string; cause_description: string; fix: string; docs_url?: string }) => ({+ error: 'config_error', code: 'config_error', message: e.problem,+ why: e.cause_description || undefined, suggestion: e.fix, docs: e.docs_url,+ }),+ },+ {+ match: e => !(e instanceof Error) && !!e && typeof e === 'object'+ && typeof (e as Record<string, unknown>).code === 'string' && typeof (e as Record<string, unknown>).message === 'string'+ && typeof (e as Record<string, unknown>).class === 'string',+ map: (e: { class: string; code: string; message: string; hint?: string }) => ({+ error: e.code, code: canonicalCodeFor(e.code), message: e.message, suggestion: e.hint,+ }),+ },+];++function argvFromPricing(command: string): string[] | undefined {+ const s = command.replace(/<([a-z0-9-]+)>/gi, 'PLACEHOLDER_$1');+ const argv = argvFromCommand(s);+ return argv?.map(a => a.replace(/^PLACEHOLDER_(.+)$/, '<$1>'));+}++function dbParts(e: unknown, ctx: AgentErrorContext): EnvelopeParts | undefined {+ const d = classifyPgAccessError(e, { url: ctx.db?.url ?? null, brainId: ctx.db?.brainId });+ if (d.reason === 'unknown') return undefined;+ const verb = isVerbOp(ctx);+ if (d.reason === 'schema_missing') {+ return {+ error: 'unavailable', code: 'unavailable', reason: 'schema_missing', message: d.message,+ suggestion: 'Run gbrain apply-migrations on the brain host, then retry.',+ fix: {+ argv: ['gbrain', 'apply-migrations', '--yes'], consent: [], actor: ctx.transport === 'cli' ? 'agent' : 'host_admin',+ why: 'The code expects a table or column this brain does not have yet.', requires_exclusive: true,+ verify: { argv: ['gbrain', 'doctor', '--json'] },+ },+ ...(verb ? { detail: 'schema_missing', protocol_version: 1 as const } : {}),+ };+ }+ return {+ error: verb ? 'unavailable' : 'database_error', code: verb ? 'unavailable' : 'database_error', reason: d.reason,+ message: d.message, suggestion: `${formatDbAccessMarker(d)}. ${d.remediation} Run: gbrain db-repair`,+ fix: {+ argv: ['gbrain', 'db-repair'], consent: [], actor: ctx.transport === 'cli' ? 'agent' : 'host_admin',+ why: 'db-repair diagnoses the database connection without changing anything.', requires_exclusive: false,+ },+ ...(verb ? { detail: d.reason, protocol_version: 1 as const } : {}),+ };+}++function unknownParts(e: unknown, ctx: AgentErrorContext): EnvelopeParts {+ const raw = e instanceof Error ? e.message : String(e);+ let message = raw;+ try { message = redactUrlsInText(redactConnectionInfo(raw)); } catch { /* keep raw */ }+ const where = ctx.op ?? ctx.command ?? 'this operation';+ const verb = isVerbOp(ctx);+ const resubmit = ctx.mutating ? ' The write may have partly run: inspect state before resubmitting.' : '';+ return {+ error: verb ? 'internal' : 'internal_error', code: verb ? 'internal' : 'internal_error',+ message: redactForTransport(message, ctx.transport),+ suggestion: `Server-side failure in ${where}, not a caller mistake.${resubmit} Run \`gbrain doctor --json\` on the brain host; if it repeats, report it to the user.`,+ fix: diagnosticFix(ctx, 'Doctor checks the brain host for the failing dependency.'),+ ...(verb ? { protocol_version: 1 as const } : {}),+ };+}+function genericEnvelope(e: unknown, ctx: AgentErrorContext): AgentEnvelope {const message = e instanceof Error ? e.message : String(e);const where = ctx.op ?? ctx.command ?? 'this operation';- return buildEnvelope({- error: 'internal_error',- code: 'internal_error',- message: redactForTransport(message, ctx.transport),+ return {+ error: 'internal_error', code: 'internal_error', message: redactForTransport(message, ctx.transport),suggestion: `Server-side failure in ${where}, not a caller mistake. Run \`gbrain doctor --json\` on the brain host; if it repeats, report it to the user.`,- }, ctx.render);+ docs_cmd: ['gbrain', 'errors', 'internal_error'], class: 'server', retryable: false, contract_version: CONTRACT_VERSION,+ };}-/** Total: never throws; on an internal fault returns the prior generic envelope. */+/** Total: never throws; on an internal fault returns the prior generic envelope and logs the class (E11). */export function toAgentError(e: unknown, ctx: AgentErrorContext): AgentEnvelope {try {- if (e instanceof OperationError) {- const j = e.toJSON() as Record<string, unknown>;- const unsafeRetry = ctx.mutating === true && ctx.idempotent !== true;- return buildEnvelope({- ...(unsafeRetry ? { retryable: false } : {}),- error: e.code, code: e.canonicalCode, message: e.message, suggestion: e.suggestion,- reason: e.reason, why: e.why, fix: e.fix, docs: e.docs, notices: e.notices, detail: e.detail,- protocol_version: e.protocolVersion === 1 ? 1 : undefined,- write_request: j.write_request, write_error: e.writeError,- }, ctx.render);+ const row = ROWS.find(r => r.match(e));+ let parts = row ? row.map(e, ctx) : dbParts(e, ctx) ?? unknownParts(e, ctx);+ if (!parts.fix) {+ const recovery = recoveryFix(parts, ctx);+ if (recovery) parts = { ...parts, fix: recovery };}- if (e instanceof StructuredAgentError) {- const env = e.envelope;- return buildEnvelope({ error: env.code, code: env.code, message: env.message, suggestion: env.hint, docs: env.docs_url }, ctx.render);+ if (!parts.fix && (codeClass(parts.code) === 'server' || codeClass(parts.code) === 'unavailable')) {+ parts = { ...parts, fix: diagnosticFix(ctx, 'Doctor reports what is missing or failing on the brain host.') };}- return genericEnvelope(e, ctx);+ if (ctx.mutating === true && ctx.idempotent !== true) parts = { ...parts, retryable: false };+ const env = buildEnvelope(parts, ctx.render);+ if (env.code === 'internal_error' || env.code === 'internal' || !env.suggestion) {+ recordAgentContractEvent({ transport: ctx.transport, op: ctx.op, command: ctx.command, code: env.code, has_suggestion: !!env.suggestion, outcome: ctx.outcome });+ }+ return ctx.transport === 'http' ? redactForTransport(env, 'http') : env;} catch (fault) {recordAgentContractEvent({transport: ctx.transport, op: ctx.op, command: ctx.command, code: 'internal_error',diff --git a/src/core/doctor-remote.ts b/src/core/doctor-remote.tsindex 9569c9359e..ad89153407 100644--- a/src/core/doctor-remote.ts+++ b/src/core/doctor-remote.ts@@ -15,6 +15,7 @@import type { GBrainConfig } from './config.ts';import { discoverOAuth, mintClientCredentialsToken, smokeTestMcp } from './remote-mcp-probe.ts';import { callRemoteTool, RemoteMcpError, unpackToolResult } from './mcp-client.ts';+import { isScopeErrorCode } from './error-catalogue.ts';import { safeCompare, driftLevel, loadPromptState } from './thin-client-upgrade-prompt.ts';import { VERSION } from '../version.ts';@@ -430,7 +431,7 @@ async function probeScopes(config: GBrainConfig): Promise<ScopeProbeResult> {result.read_ok = true;} catch (e) {if (e instanceof RemoteMcpError) {- result.read_error = e.detail?.code === 'missing_scope' ? 'missing_scope' : e.reason;+ result.read_error = isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason) ? 'missing_scope' : e.reason;} else {result.read_error = e instanceof Error ? e.message : String(e);}@@ -443,7 +444,7 @@ async function probeScopes(config: GBrainConfig): Promise<ScopeProbeResult> {result.admin_ok = true;} catch (e) {if (e instanceof RemoteMcpError) {- result.admin_error = e.detail?.code === 'missing_scope' ? 'missing_scope' : e.reason;+ result.admin_error = isScopeErrorCode(e.detail?.code, e.detail?.canonical_code, e.detail?.reason) ? 'missing_scope' : e.reason;} else {result.admin_error = e instanceof Error ? e.message : String(e);}diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.tsindex e220bb3536..e30e9079c3 100644--- a/src/core/error-catalogue.ts+++ b/src/core/error-catalogue.ts@@ -63,6 +63,23 @@ export const ERROR_CATALOGUE = {export type CatalogueName = keyof typeof ERROR_CATALOGUE;+/** Wire constants shared by the server and the thin client (A2). */+export const WIRE_CODES = {+ insufficient_scope: 'insufficient_scope',+ unknown_tool: 'unknown_tool',+ not_found: 'not_found',+} as const;++/**+ * A scope denial in any of its historical spellings: the server's+ * `insufficient_scope`, the thin client's legacy `missing_scope`, or+ * `permission_denied` whose canonical code or reason says scope.+ */+export function isScopeErrorCode(code: string | undefined, canonical?: string, reason?: string): boolean {+ if (code === 'insufficient_scope' || code === 'missing_scope' || canonical === 'insufficient_scope') return true;+ return code === 'permission_denied' && (reason === 'insufficient_scope' || reason === 'missing_scope');+}+/** Named refusals (one code may carry several anchors). Same table as ERROR_CATALOGUE. */export const REFUSALS = ERROR_CATALOGUE;diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 072726a56b..9301dce38c 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -40,9 +40,14 @@ export interface CodeEntry {}export const CODES = {+ access_command_failed: { class: 'caller', summary: "Google connect credential error: access command failed.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ access_denied_test_user: { class: 'host_only', summary: "Google connect credential error: access denied test user.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ access_env_missing: { class: 'caller', summary: "Google connect credential error: access env missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },acknowledgment_unavailable: { class: 'unavailable', summary: "This batch is unknown or outside the retained replay window." },+ admin_policy_enforced: { class: 'host_only', summary: "Google connect credential error: admin policy enforced.", docs: 'docs/guides/google-connect.md#troubleshooting' },ambiguous_id: { class: 'caller', summary: "The legacy id matches multiple readable pages." },ambiguous_skill: { class: 'caller', summary: "This name belongs to multiple authorized sources." },+ api_not_enabled: { class: 'host_only', summary: "Google connect credential error: api not enabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },approval_required: { class: 'consent', summary: "The change needs the owner's explicit approval before it can proceed." },autopilot_job_owned_by_other_brain: { class: 'caller', summary: "The autopilot job is bound to a different brain." },benchmark_duplicate_task_id: { class: 'caller', summary: "Benchmark duplicate task id." },@@ -69,10 +74,15 @@ export const CODES = {catalog_unavailable: { class: 'retryable', summary: "Shared skill storage is not ready on this brain." },checkpoint_missing: { class: 'caller', summary: "The approved source plan is missing; do not restart from a different revision." },checkpoint_validation_timeout: { class: 'retryable', summary: "Validating the managed-sync checkpoint timed out." },+ claim_already_used: { class: 'caller', summary: "Google connect credential error: claim already used.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ client_json_unreadable: { class: 'caller', summary: "Google connect credential error: client json unreadable.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ client_json_wrong_type: { class: 'caller', summary: "Google connect credential error: client json wrong type.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ client_shape_invalid: { class: 'caller', summary: "Google connect credential error: client shape invalid.", docs: 'docs/guides/google-connect.md#troubleshooting' },code_callees_requires_symbol: { class: 'caller', summary: "code-callees requires a symbol name." },code_callers_requires_symbol: { class: 'caller', summary: "code-callers requires a symbol name." },code_def_requires_symbol: { class: 'caller', summary: "code-def requires a symbol name." },code_refs_requires_symbol: { class: 'caller', summary: "code-refs requires a symbol name." },+ code_reused: { class: 'caller', summary: "Google connect credential error: code reused.", docs: 'docs/guides/google-connect.md#troubleshooting' },colon_slug_windows_write_through: { class: 'caller', summary: "A colon slug cannot be written through on Windows." },command_failed: { class: 'server', summary: "The command failed before it wrote its JSON result." },config_error: { class: 'caller', summary: "A required configuration value or directory is missing or invalid." },@@ -82,6 +92,7 @@ export const CODES = {connector_fence_below_timeline: { class: 'caller', summary: "A stored page carries a fence the connector render cannot preserve." },connector_holds_exhausted: { class: 'caller', summary: "The source holds the maximum number of failed items; its cursor did not advance." },connector_intent_outdated: { class: 'caller', summary: "The connector request no longer matches the stored connector intent." },+ consent_timeout: { class: 'consent', summary: "Google connect credential error: consent timeout.", docs: 'docs/guides/google-connect.md#troubleshooting' },cost_cap_exceeded: { class: 'server', summary: "The run reached its cost cap before finishing." },cost_preview_requires_yes: { class: 'consent', summary: "Cost preview requires yes." },d_sel_too_small: { class: 'caller', summary: "The selection split has too few tasks for meaningful validation." },@@ -126,7 +137,11 @@ export const CODES = {internal: { class: 'server', summary: "A memory verb failed on the server; this is not a caller mistake." },internal_error: { class: 'server', summary: "The server failed while running the operation; this is not a caller mistake." },interrupted: { class: 'server', summary: "The operation was interrupted by a signal before it finished.", exit: 130 },+ invalid_client: { class: 'caller', summary: "Google connect credential error: invalid client.", docs: 'docs/guides/google-connect.md#troubleshooting' },invalid_connector_text: { class: 'caller', summary: "Invalid connector text." },+ invalid_grant_clock_skew: { class: 'caller', summary: "Google connect credential error: invalid grant clock skew.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ invalid_grant_revoked: { class: 'caller', summary: "Google connect credential error: invalid grant revoked.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ invalid_grant_testing_expiry: { class: 'caller', summary: "Google connect credential error: invalid grant testing expiry.", docs: 'docs/guides/google-connect.md#troubleshooting' },invalid_params: { class: 'caller', summary: "A parameter is missing, has the wrong type, or has an invalid value.", exit: 2 },invalid_request: { class: 'caller', summary: "submit_agent over the local CLI: use `gbrain agent run` instead." },invalid_source: { class: 'caller', summary: "The source argument or source state is invalid for this operation." },@@ -140,24 +155,29 @@ export const CODES = {lock_busy: { class: 'retryable', summary: "Another process holds the lock this command needs." },managed_pull_skipped: { class: 'retryable', summary: "The managed pull was skipped." },method_not_allowed: { class: 'caller', summary: "The HTTP method is not allowed on this endpoint." },+ missing_source_scope: { class: 'server', summary: "A remote tool call reached dispatch without a resolved source scope; the shared default source is refused." },missing_source_value: { class: 'caller', summary: "A source flag was given without a value." },models_strict_violation: { class: 'caller', summary: "A configured model is not allowed under models strict mode." },no_pricing: { class: 'unavailable', summary: "gbrain has no price for the model, so a user-set cost cap cannot be enforced." },+ no_refresh_token: { class: 'caller', summary: "Google connect credential error: no refresh token.", docs: 'docs/guides/google-connect.md#troubleshooting' },no_routing_eval: { class: 'caller', summary: "The skill has no routing-eval rows to bootstrap a benchmark from." },no_skill_md: { class: 'caller', summary: "The skill directory has no SKILL.md." },no_worker_surface: { class: 'caller', summary: "No worker surface." },not_a_git_repo: { class: 'caller', summary: "The source path must contain committed Git content." },+ not_connected: { class: 'caller', summary: "Google connect credential error: not connected.", docs: 'docs/guides/google-connect.md#troubleshooting' },not_found: { class: 'caller', summary: "The requested resource does not exist or is not visible to this caller.", legacy_error: 'invalid_params' },overlapping_path: { class: 'caller', summary: "Sources cannot claim overlapping canonical directories." },owner_unavailable: { class: 'retryable', summary: "The brain's persistence owner is not reachable right now." },page_identity_changed: { class: 'caller', summary: "The page was deleted or replaced while the operation ran." },page_not_found: { class: 'caller', summary: "No page with that slug exists in the selected source.", legacy_error: 'page_identity_changed' },parse_error: { class: 'caller', summary: "The request body is not valid JSON." },+ pasted_wrong_url: { class: 'caller', summary: "Google connect credential error: pasted wrong url.", docs: 'docs/guides/google-connect.md#troubleshooting' },payload_too_large: { class: 'caller', summary: "The payload exceeds the configured size cap." },pending_writes: { class: 'retryable', summary: "A pending source write prevents verified completion." },permission_denied: { class: 'host_only', summary: "This caller is not authorized for the operation." },plan_output_failed: { class: 'server', summary: "Writing the plan output failed." },plan_stale: { class: 'caller', summary: "The saved plan has no valid repository identity." },+ port_in_use: { class: 'retryable', summary: "Google connect credential error: port in use.", docs: 'docs/guides/google-connect.md#troubleshooting' },preview_changed: { class: 'caller', summary: "The state changed since the approved preview." },profile_incompatible: { class: 'caller', summary: "The stored profile is incompatible with this operation." },projection_owner_resident: { class: 'host_only', summary: "A resident owner holds the projection." },@@ -167,6 +187,7 @@ export const CODES = {queue_capacity: { class: 'retryable', summary: "The bounded queue is full; existing requests keep their place." },rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes." },+ redirect_uri_mismatch: { class: 'caller', summary: "Google connect credential error: redirect uri mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },refresh_dirty: { class: 'caller', summary: "The worktree has uncommitted changes." },refresh_diverged: { class: 'caller', summary: "The worktree diverged from its upstream; a fast-forward is impossible." },refresh_drain_timeout: { class: 'retryable', summary: "In-flight work did not drain before the refresh deadline." },@@ -174,6 +195,9 @@ export const CODES = {refresh_not_managed: { class: 'host_only', summary: "The source is not managed, so it cannot be refreshed." },refresh_not_owner: { class: 'host_only', summary: "This process does not own the worktree it would refresh." },refresh_source_changed: { class: 'caller', summary: "The source changed during the refresh." },+ relay_disabled: { class: 'caller', summary: "Google connect credential error: relay disabled.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ relay_session_expired: { class: 'caller', summary: "Google connect credential error: relay session expired.", docs: 'docs/guides/google-connect.md#troubleshooting' },+ relay_unreachable: { class: 'retryable', summary: "Google connect credential error: relay unreachable.", docs: 'docs/guides/google-connect.md#troubleshooting' },request_already_submitted: { class: 'caller', summary: "This optimizer publication request has already been submitted." },request_too_large: { class: 'caller', summary: "The request exceeds a configured capacity; narrow it." },requirements_changed: { class: 'caller', summary: "The runtime requirements exceed the owner-approved publication policy." },@@ -183,6 +207,7 @@ export const CODES = {revision_required: { class: 'caller', summary: "Review the current policy and supply its expected_policy_epoch before changing disclosure." },revision_unavailable: { class: 'unavailable', summary: "The exact authorized revision is unavailable." },scope_denied: { class: 'host_only', summary: "The connection lacks the scope this memory verb requires." },+ scope_missing: { class: 'caller', summary: "Google connect credential error: scope missing.", docs: 'docs/guides/google-connect.md#troubleshooting' },shared_skills_unavailable: { class: 'unavailable', summary: "The shared-skills operation was refused." },shared_skills_unsupported: { class: 'unavailable', summary: "The server does not expose the shared-skills protocol." },skill_asset_not_found: { class: 'caller', summary: "The requested file is not in the approved revision manifest." },@@ -190,6 +215,7 @@ export const CODES = {skill_candidate_invalid: { class: 'caller', summary: "The optimized candidate changed protected frontmatter or has an empty/invalid body." },skill_not_found: { class: 'caller', summary: "No authorized published skill matches this key." },skill_retention_capacity: { class: 'caller', summary: "Retained skill revisions exceed this source storage budget." },+ source_binding_required: { class: 'caller', summary: "A write needs an explicit source binding on this MCP server (--source-guard)." },source_changed: { class: 'caller', summary: "The source changed during the operation; nothing was committed." },source_id_taken: { class: 'caller', summary: "This source already exists and does not match this exact admitted request." },source_not_ready: { class: 'caller', summary: "A committed source and approved schema are required." },@@ -199,6 +225,7 @@ export const CODES = {source_writeback_required: { class: 'host_only', summary: "Canonical preparation requires a source-content correction; this profile never writes repository files." },split_bad_ratio: { class: 'caller', summary: "Split bad ratio." },split_unparseable: { class: 'caller', summary: "Split unparseable." },+ state_mismatch: { class: 'caller', summary: "Google connect credential error: state mismatch.", docs: 'docs/guides/google-connect.md#troubleshooting' },storage_error: { class: 'server', summary: "Reading or writing durable storage failed." },sync_in_progress: { class: 'retryable', summary: "A sync is running on this source." },take_row_collision: { class: 'caller', summary: "A takes fence row number is already used by a different take that is not in this page's canonical fence." },@@ -217,6 +244,7 @@ export const CODES = {unmanaged_path: { class: 'caller', summary: "Reclone only replaces a checkout created and managed by GBrain." },unsupported_export_data: { class: 'unavailable', summary: "The source contains data this export path cannot carry." },unsupported_mutation_protocol: { class: 'unavailable', summary: "Prepared mutation does not match its accepted target." },+ upstream: { class: 'retryable', summary: "Google connect credential error: upstream.", docs: 'docs/guides/google-connect.md#troubleshooting' },verification_failed: { class: 'server', summary: "Source content or relationships changed during verification." },withdrawal_capacity: { class: 'caller', summary: "Withdrawal capacity." },withdrawal_provenance: { class: 'server', summary: "The withdrawal target manifest is invalid." },@@ -240,6 +268,7 @@ export const CODES = {writer_transfer_conflict: { class: 'caller', summary: "Writer transfer conflict." },writer_transfer_required: { class: 'caller', summary: "Writer transfer required." },writer_upgrade_required: { class: 'host_only', summary: "Apply the canonical writer guard, outbox, and source lifecycle migrations before activation." },+ wrong_account_consented: { class: 'caller', summary: "Google connect credential error: wrong account consented.", docs: 'docs/guides/google-connect.md#troubleshooting' },} as const satisfies Record<string, CodeEntry>;export type RegistryCode = keyof typeof CODES;diff --git a/src/core/mcp-client.ts b/src/core/mcp-client.tsindex 82d9545177..67ec1d63b8 100644--- a/src/core/mcp-client.ts+++ b/src/core/mcp-client.ts@@ -24,6 +24,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';import { StreamableHTTPClientTransport, StreamableHTTPError } from '@modelcontextprotocol/sdk/client/streamableHttp.js';import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';import { anySignal } from './abort-check.ts';+import { canonicalCodeFor } from './error-catalogue.ts';import type { GBrainConfig } from './config.ts';import { discoverOAuth, mintClientCredentialsToken } from './remote-mcp-probe.ts';import { isWriteErrorCode, isWriteReceipt, isWriteRequestId, publicWriteReceipt, type WriteErrorCode, type WriteReceipt } from './persistence/types.ts';@@ -85,6 +86,15 @@ export interface RemoteMcpErrorDetail {protocol_version?: 1;server_detail?: string;docs?: string;+ /** Agent contract v1: canonical registry code (`code`) when it differs from or adds to the wire `error` (kept in `code` above). */+ canonical_code?: string;+ reason?: string;+ why?: string;+ /** Rendered fix as the server sent it (`next` included). */+ fix?: Record<string, unknown>;+ /** Notices from the envelope's `notices` key (error results carry exactly one block). */+ notices?: Array<Record<string, unknown>>;+ contract_version?: 1;}export class RemoteMcpError extends Error {@@ -101,8 +111,10 @@ export class RemoteMcpError extends Error {toJSON() {const detail = this.detail;const unknown = detail?.submission_status === 'unknown';+ const wire = detail?.code ?? 'unavailable';return {- error: detail?.code ?? 'unavailable',+ error: wire,+ code: detail?.canonical_code ?? canonicalCodeFor(wire),message: detail?.message ?? this.message,...(detail?.request_id ? { request_id: detail.request_id } : {}),...(detail?.submission_status ? { submission_status: detail.submission_status } : {}),@@ -114,6 +126,11 @@ export class RemoteMcpError extends Error {...(detail?.docs ? { docs: detail.docs } : {}),...(detail?.write_request ? { write_request: publicWriteReceipt(detail.write_request) } : {}),...(detail?.write_error ? { write_error: detail.write_error } : {}),+ ...(detail?.reason ? { reason: detail.reason } : {}),+ ...(detail?.why ? { why: detail.why } : {}),+ ...(detail?.fix ? { fix: detail.fix } : {}),+ ...(detail?.notices?.length ? { notices: detail.notices } : {}),+ ...(detail?.contract_version === 1 ? { contract_version: 1 } : {}),};}}@@ -210,6 +227,12 @@ export function extractToolErrorDetail(message: string): RemoteMcpErrorDetail {if (envelope.protocol_version === 1) detail.protocol_version = 1;if (typeof envelope.detail === 'string') detail.server_detail = envelope.detail;if (typeof envelope.docs === 'string') detail.docs = envelope.docs;+ if (typeof envelope.code === 'string' && envelope.code !== code) detail.canonical_code = envelope.code;+ if (typeof envelope.reason === 'string') detail.reason = envelope.reason;+ if (typeof envelope.why === 'string') detail.why = envelope.why;+ if (envelope.fix && typeof envelope.fix === 'object' && !Array.isArray(envelope.fix)) detail.fix = envelope.fix as Record<string, unknown>;+ if (Array.isArray(envelope.notices)) detail.notices = envelope.notices.filter(n => n && typeof n === 'object') as Array<Record<string, unknown>>;+ if (envelope.contract_version === 1) detail.contract_version = 1;if (isWriteReceipt(envelope.write_request)) detail.write_request = publicWriteReceipt(envelope.write_request);if (isWriteErrorCode(envelope.write_error)) detail.write_error = envelope.write_error;} catch { /* Older servers can return plain text; preserve existing code extraction. */ }@@ -424,9 +447,10 @@ export async function callRemoteTool(submitted = true;const res = await client.callTool({ name: toolName, arguments: args }, undefined, buildMcpRequestOptions(opts, signal));if (res.isError) {- const message = Array.isArray(res.content)- ? res.content.map((c: unknown) => (c as { text?: string }).text ?? '').join('\n')- : 'unknown tool error';+ // Agent contract v1: the envelope is content[0] alone. A notice+ // block from a newer server never joins the body.+ const first = Array.isArray(res.content) ? (res.content[0] as { text?: unknown } | undefined) : undefined;+ const message = typeof first?.text === 'string' ? first.text : 'unknown tool error';// v0.31.1: extract structured error code (e.g. 'missing_scope') so// the dispatcher can produce a pinpoint hint instead of a generic// "tool error" message.@@ -528,6 +552,33 @@ export function unpackToolResult<T = unknown>(res: unknown): T {}}+/**+ * Agent contract v1 notices on a SUCCESS result: `_meta.gbrain_notices`+ * (rendered) when present, else the prefixed extra text blocks after+ * content[0] (`[gbrain notice <code> kind=<kind>]` first line), for hosts+ * that drop `_meta`. Old servers return none.+ */+export function extractNotices(res: unknown): Array<Record<string, unknown>> {+ const meta = extractResponseMeta(res)?.gbrain_notices;+ if (Array.isArray(meta)) return meta.filter(n => n && typeof n === 'object') as Array<Record<string, unknown>>;+ const content = (res as { content?: unknown[] } | undefined)?.content;+ const out: Array<Record<string, unknown>> = [];+ for (const block of Array.isArray(content) ? content.slice(1) : []) {+ const text = (block as { text?: unknown })?.text;+ if (typeof text !== 'string' || !text.startsWith('[gbrain notice ')) continue;+ const [head, ...rest] = text.split('\n');+ const m = /^\[gbrain notice (\S+) kind=(\S+)\]$/.exec(head);+ if (!m) continue;+ const notice: Record<string, unknown> = { code: m[1], kind: m[2] };+ for (const line of rest) {+ const kv = /^(why|fix|next|user_message): (.*)$/.exec(line);+ if (kv) notice[kv[1]] = kv[2];+ }+ out.push(notice);+ }+ return out;+}+/*** T15/FOV-1: read the response-level `_meta` from a tool-call envelope* (see docs/protocol/MCP_META_CHANNELS.md). Old servers simply lack the@@ -559,7 +610,7 @@ export function ignoredRemoteParams(res: unknown): string[] {for (const block of Array.isArray(content) ? content.slice(1) : []) {const text = (block as { text?: unknown })?.text;if (typeof text !== 'string') continue;- for (const m of text.matchAll(/^warning: unknown parameter "([^"]+)" ignored/gm)) names.add(m[1]);+ for (const m of text.matchAll(/^(?:why: )?warning: unknown parameter "([^"]+)" ignored/gm)) names.add(m[1]);}return [...names];}diff --git a/src/core/operations.ts b/src/core/operations.tsindex 91317915dc..5c16d4f0d5 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -19,7 +19,7 @@ import { withOutputRedaction } from './search/output-redaction.ts';// slugOutsideCallerFence, enforceClientSlugFence, BOUND_CLIENT_META_OPS,// stampEvidenceSafe, maybeCaptureSearch) are deliberately NOT re-exported —// they were never part of this module's surface; import them from ops/context.ts.-export { OperationError, verbError } from './ops/contract.ts';+export { OperationError, verbError, opError } from './ops/contract.ts';export type {ErrorCode,ParamDef,diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 643676c37e..4a0c3899c5 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -8,14 +8,13 @@import { affectsRecall } from '../core/types.ts';import type { BrainEngine } from '../core/engine.ts';-import { operations, OperationError, enforceBoundClientOpAllowList } from '../core/operations.ts';+import { operations, OperationError, enforceBoundClientOpAllowList, opError } from '../core/operations.ts';import type { OperationContext, AuthInfo } from '../core/operations.ts';import { loadConfig } from '../core/config.ts';-import { classifyPgAccessError, formatDbAccessMarker, type PgAccessDiagnosis } from '../core/pg-access-classify.ts';import { resolveBrainId } from '../core/brain-resolver.ts';-import { redactConnectionInfo } from '../core/audit/redact-connection-info.ts';-import { redactUrlsInText } from '../core/url-redact.ts';import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';+import { toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';+import { isCallable } from '../core/ops/callable.ts';import { logVerbUsage } from '../core/verbs/usage-log.ts';import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';import { suggestNearest } from '../core/levenshtein.ts';@@ -91,7 +90,7 @@ export function __resetBackupNoticeForTests(): void {* cli.ts startup rail owns that surface. The hourly recheck latch keeps the* healthy steady state at zero file reads per tool call.*/-function maybeAttachBackupNotice(out: ToolResult, opts: DispatchOpts): void {+function maybeBackupNotice(notices: Notice[], opts: DispatchOpts): void {try {if (backupNoticeShown || opts.remote === false || opts.transport !== 'stdio') return;const now = Date.now();@@ -104,7 +103,10 @@ function maybeAttachBackupNotice(out: ToolResult, opts: DispatchOpts): void {if (!gate.show) return;const text = backupNoticeText(s, 'aggregate');if (!text) return;- out.content.push({ type: 'text', text });+ notices.push({+ code: 'backup_coverage', kind: 'coaching', why: text,+ fix: { argv: ['gbrain', 'backup', 'status'], consent: [], actor: 'user', why: 'Lists each asset without a git remote and its fix command.', requires_exclusive: false },+ });backupNoticeShown = true;gate.record();} catch {@@ -439,22 +441,54 @@ export function requestLogStatusForResult(result: ToolResult): RequestLogStatus* gate state is unknown here, and a suggestion naming a hidden/gated op* would be the exact existence oracle this envelope exists to prevent.*/-function unknownToolEnvelope(name: string, allowedOps?: ReadonlySet<string>): ToolResult {+export function unknownToolEnvelope(name: string, opts: DispatchOpts, legacyError?: 'unknown_operation'): ToolResult {+ const allowedOps = opts.allowedOps;const candidates = operations.filter(op => !op.localOnly && !op.publishGateKey && (allowedOps ? allowedOps.has(op.name) : true)).map(op => op.name);const nearest = suggestNearest(name, candidates);- const envelope = {- error: 'unknown_tool',- message: `Unknown tool: ${name}`,- ...(nearest ? { suggestion: `Did you mean "${nearest}"?` } : {}),- };+ const suggestion = nearest+ ? `Did you mean "${nearest}"?`+ : 'List the tools this connection can call (tools/list) and use one of those names.';+ return errorResult(opError('unknown_tool', legacyError ? `Unknown: ${name}` : `Unknown tool: ${name}`, suggestion,+ legacyError ? { legacy_error: legacyError } : {}), opts);+}++/**+ * Agent contract v1 render context for a dispatch caller: a fix names an MCP+ * tool only when the same predicate behind tools/list says this caller can+ * call it. Preapprovals never apply over MCP (they are a CLI consent path).+ */+export function dispatchRenderContext(opts: DispatchOpts): RenderContext {+ const transport = opts.transport === 'stdio' ? 'stdio' : opts.remote === false ? 'cli' : 'http';+ const surface = opts.surface ?? 'full';+ const byName = new Map(operations.map(op => [op.name, op]));return {- content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }],- isError: true,+ transport,+ surface,+ isCallable: (opName: string) => {+ const op = byName.get(opName);+ return !!op && isCallable(op, {+ transport, surface, scopes: opts.auth?.scopes ?? [], publishGates: {}, allowedOps: opts.allowedOps,+ });+ },+ preapproved: () => false,+ ...(opts.auth?.clientId ? { principal: opts.auth.clientId } : {}),};}+/** The one error result path: toAgentError → exactly one content block. */+export function errorResult(e: unknown, opts: DispatchOpts, extra: { op?: string; mutating?: boolean; idempotent?: boolean; notices?: Notice[] } = {}): ToolResult {+ if (extra.notices?.length && e instanceof OperationError) e.notices = [...(e.notices ?? []), ...extra.notices];+ const render = dispatchRenderContext(opts);+ const envelope = toAgentError(e, {+ transport: render.transport, op: extra.op, mutating: extra.mutating, idempotent: extra.idempotent,+ outcome: extra.mutating ? 'unknown' : 'failed', render,+ db: { url: configuredDbUrlForClassify(), brainId: brainIdForClassify() },+ });+ return toolErrorResult(envelope);+}+const stderrLogger: OperationContext['logger'] = {info: (msg: string) => process.stderr.write(`[info] ${msg}\n`),warn: (msg: string) => process.stderr.write(`[warn] ${msg}\n`),@@ -545,7 +579,7 @@ export async function dispatchToolCall(// on every transport, not just unlisted. Same envelope as unknown ops so// the surface doesn't leak which names exist.if (opts.allowedOps && !opts.allowedOps.has(name)) {- return unknownToolEnvelope(name, opts.allowedOps);+ return unknownToolEnvelope(name, opts);}const op = operations.find(o => o.name === name);@@ -555,7 +589,7 @@ export async function dispatchToolCall(// plain `Error: ...` string here breaks the contract on every// unknown-op path and the resulting test failure looked like a// transport bug.- return unknownToolEnvelope(name, opts.allowedOps);+ return unknownToolEnvelope(name, opts);}// localOnly backstop at the SHARED layer (WP1/D7): localOnly ops reach the@@ -566,7 +600,7 @@ export async function dispatchToolCall(// serve-http path also filters these at list time; the legacy bearer// transport at surface 'full' had no gate at all before this line.if (op.localOnly && opts.transport !== 'stdio') {- return unknownToolEnvelope(name, opts.allowedOps);+ return unknownToolEnvelope(name, opts);}// --source-guard (plugin lanes): fail-closed write routing. A user-global@@ -582,23 +616,17 @@ export async function dispatchToolCall(const sentinelWrite = opts.sourceId === '__all__';if (sentinelWrite || (await sourceGuardBlocksWrite(engine, opts.sourceGuardTier))) {logVerb(false);- const envelope = {- error: 'source_binding_required',- message: sentinelWrite+ const refusal = opError('source_binding_required', sentinelWrite? 'GBRAIN_SOURCE=__all__ is a read-span sentinel, not a write target — a write cannot resolve to "all sources". ' +'Set GBRAIN_SOURCE to a concrete source id for writes.': 'This brain has more than one source to choose from and the MCP server runs with --source-guard: ' +`write/admin operations need an explicit source binding so they cannot land in the wrong source (resolution tier: ${opts.sourceGuardTier}).`,- suggestion:- 'Set GBRAIN_SOURCE=<source-id> in the environment that launches this MCP server ' ++ 'Set GBRAIN_SOURCE=<source-id> in the environment that launches this MCP server ' +'(plugin installs pass it through — the user-global stdio serve binds the source from the env, not a flag). ' +'List sources with `gbrain sources list`. Reads are unaffected.',- ...(isVerb ? { protocol_version: MEMORY_VERBS_VERSION } : {}),- };- return {- content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }],- isError: true,- };+ { fix: { argv: ['gbrain', 'sources', 'list'], consent: [], actor: 'user', why: 'Names the source id to bind with GBRAIN_SOURCE.', requires_exclusive: false } });+ if (isVerb) refusal.protocolVersion = MEMORY_VERBS_VERSION;+ return errorResult(refusal, opts, { op: name });}}@@ -608,18 +636,10 @@ export async function dispatchToolCall(logVerb(false);// [c7] verb validation errors speak the protocol envelope (suggestion +// protocol_version); non-verb ops keep the pre-existing shape untouched.- const envelope = isVerb- ? {- error: 'invalid_params',- message: validationError,- suggestion: 'Check the tool schema — required params and types are declared there.',- protocol_version: MEMORY_VERBS_VERSION,- }- : { error: 'invalid_params', message: validationError };- return {- content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }],- isError: true,- };+ const invalid = new OperationError('invalid_params', validationError,+ isVerb ? 'Check the tool schema — required params and types are declared there.' : undefined);+ if (isVerb) invalid.protocolVersion = MEMORY_VERBS_VERSION;+ return errorResult(invalid, opts, { op: name });}// WP3 strict/warn unknown-argument validation. Runs on the NORMALIZED@@ -643,16 +663,11 @@ export async function dispatchToolCall(? `Unknown parameter "${w.param}" — did you mean "${w.suggestion}"?`: `Unknown parameter "${w.param}".`).join(' ');- const envelope = {- error: 'invalid_params',- message: `${n} unknown parameter${n === 1 ? '' : 's'} not declared in the ${name} tool schema (mcp.strict_params=reject). See suggestion for the submitted name${n === 1 ? '' : 's'}.`,- suggestion,- ...(isVerb ? { protocol_version: MEMORY_VERBS_VERSION } : {}),- };- return {- content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }],- isError: true,- };+ const strict = new OperationError('invalid_params',+ `${n} unknown parameter${n === 1 ? '' : 's'} not declared in the ${name} tool schema (mcp.strict_params=reject). See suggestion for the submitted name${n === 1 ? '' : 's'}.`,+ suggestion);+ if (isVerb) strict.protocolVersion = MEMORY_VERBS_VERSION;+ return errorResult(strict, opts, { op: name });}}@@ -665,10 +680,8 @@ export async function dispatchToolCall(// #1924 / #1371. Trusted local callers (remote === false) keep the// historical fallback via buildOperationContext.if ((opts.remote ?? true) && !opts.sourceId) {- return {- content: [{ type: 'text', text: JSON.stringify({ error: 'missing_source_scope', message: `Remote tool call '${name}' carries no resolved sourceId; refusing the shared 'default' source fallback. Pass an explicit sourceId resolved from the caller's grant.` }, null, 2) }],- isError: true,- };+ return errorResult(new OperationError('missing_source_scope',+ `Remote tool call '${name}' carries no resolved sourceId; refusing the shared 'default' source fallback. Pass an explicit sourceId resolved from the caller's grant.`), opts, { op: name });}const ctx = buildOperationContext(engine, safeParams, opts);@@ -689,6 +702,12 @@ export async function dispatchToolCall(ctx.emitResponseMeta('warnings', unknownParamWarnings);}+ // Agent contract v1 (A6): the model-visible notice channel. Producers call+ // ctx.emitNotice; success renders prefixed extra blocks + _meta.gbrain_notices,+ // failure renders the envelope's `notices` key (one block).+ const notices: Notice[] = [];+ ctx.emitNotice = (n) => { if (n) notices.push(n); };+try {if (ctx.remote !== false && op.requiredScopes?.length) {let scopes = ctx.auth?.scopes;@@ -735,27 +754,26 @@ export async function dispatchToolCall(...(name === 'remember' && typeof r?.status === 'string' ? { remember_status: r.status } : {}),});}- const out: ToolResult = { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };// D8: model-visible loudness for empty retrievals. The body stays a bare- // array (D3 — deployed thin-clients parse content[0] only), and a SECOND- // text block carries the diagnosis the model actually sees. Structured+ // array (D3 — deployed thin-clients parse content[0] only); the diagnosis+ // rides the notice channel (its text kept as the `why:` line). Structured// consumers read the same facts from _meta.retrieval below.if (Array.isArray(result) && result.length === 0 && responseMeta.retrieval) {const block = buildEmptyRetrievalBlock(responseMeta.retrieval);- if (block) out.content.push({ type: 'text', text: block });+ if (block) notices.push({ code: 'empty_retrieval', kind: block.includes('degraded:') ? 'degraded' : 'info', why: block });}- // WP3/D8: warn-mode unknown-param notices ride the same model-visible- // extra-block mechanism, so the grace period actually corrects clients- // (old thin-clients read content[0] only — skew-safe).- if (unknownParamWarnings.length > 0) {- out.content.push({ type: 'text', text: buildUnknownParamWarnBlock(unknownParamWarnings) });+ // WP3/D8: warn-mode unknown-param notices ride the same channel, so the+ // grace period actually corrects clients (old thin-clients read content[0]+ // only — skew-safe). One notice per ignored parameter.+ for (const w of unknownParamWarnings) {+ notices.push({ code: 'unknown_param', kind: 'info', why: buildUnknownParamWarnBlock([w]) });}- // Monthly backup-coverage: one AGGREGATE model-visible block per process- // (counts only — never a local path or source id), riding the same- // extra-block mechanism (content[0] untouched, D3/D8 skew rule). The- // refresher runs on the stdio transport ONLY — the WP1/D7 locality axis- // localOnly ops use; 'http' or an UNSET marker never probes (fail-closed).- maybeAttachBackupNotice(out, opts);+ // Monthly backup-coverage: one AGGREGATE notice per process (counts only —+ // never a local path or source id). The refresher runs on the stdio+ // transport ONLY — the WP1/D7 locality axis localOnly ops use; 'http' or+ // an UNSET marker never probes (fail-closed).+ maybeBackupNotice(notices, opts);+ const out: ToolResult = toolResultWithNotices(result, notices, dispatchRenderContext(opts));if (opts.transport === 'stdio') {maybeRefreshBackupStatusInProcess(engine);}@@ -765,7 +783,7 @@ export async function dispatchToolCall(// failure can never drop the retrieval channel. Per-key merge, never// wholesale assignment. See docs/protocol/MCP_META_CHANNELS.md.if (Object.keys(responseMeta).length > 0) {- out._meta = { ...responseMeta };+ out._meta = { ...(out._meta ?? {}), ...responseMeta };}// v0.31 (eD3 + eE4): best-effort _meta.brain_hot_memory injection.// The hook is wrapped in its own try/catch — any DB blip / cache miss /@@ -784,62 +802,10 @@ export async function dispatchToolCall(} catch (e: unknown) {logVerb(false);if (op.mutating) invalidateHotMemoryForEngine(engine); // a failed write may have committed part of its work- if (e instanceof OperationError) {- return { content: [{ type: 'text', text: JSON.stringify(e.toJSON(), null, 2) }], isError: true };- }- // Non-OperationError (uncaught throws) — wrap in the same shape so- // every error response is JSON-parseable. The pre-v0.31 path emitted- // plain `Error: ${msg}` strings here, which broke any caller that- // tried JSON.parse(content).- const msg = e instanceof Error ? e.message : String(e);- // db-availability loop: raw pg errors used to land here VERBATIM —- // unredacted DSNs/hosts/IPs into agent transcripts, no remediation.- // Redact ALL branches; classify DB-access failures into an envelope the- // bundled skills/db-repair skill literal-matches (GBRAIN_DB_ACCESS).- // Both steps are wrapped: a classifier/redactor bug must degrade to the- // prior generic shape, never a worse error.- let redactedMsg = msg;- let dbDiag: PgAccessDiagnosis | null = null;- try {- redactedMsg = redactUrlsInText(redactConnectionInfo(msg));- const d = classifyPgAccessError(e, { url: configuredDbUrlForClassify(), brainId: brainIdForClassify() });- if (d.reason !== 'unknown') dbDiag = d;- } catch { /* fall through to the generic envelope */ }-- if (dbDiag && dbDiag.reason === 'schema_missing') {- // Mid-operation relation/column errors are usually CODE SKEW, not an- // access failure (and connectEngine already runs pending migrations on- // every connect) — the withRelationGuard treatment, generalized. No- // db-repair marker from this layer; connect-time surfaces own that.- const suggestion = 'Run gbrain apply-migrations on the brain host, then retry.';- const envelope = isVerb- ? { error: 'unavailable', message: dbDiag.message, suggestion, detail: 'schema_missing', protocol_version: MEMORY_VERBS_VERSION }- : { error: 'unavailable', message: dbDiag.message, suggestion };- return { content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }], isError: true };- }-- if (dbDiag) {- const suggestion = `${formatDbAccessMarker(dbDiag)}. ${dbDiag.remediation} Run: gbrain db-repair`;- // Verbs keep the FROZEN v1 code set ('unavailable' + reason in detail);- // non-verb ops get the first real use of the declared 'database_error'.- const envelope = isVerb- ? { error: 'unavailable', message: dbDiag.message, suggestion, detail: dbDiag.reason, protocol_version: MEMORY_VERBS_VERSION }- : { error: 'database_error', message: dbDiag.message, suggestion };- return { content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }], isError: true };- }-- // [c7] verbs speak the protocol envelope even for uncaught throws.- const envelope = isVerb- ? {- error: 'internal',- message: redactedMsg,- suggestion: 'This is a server-side failure, not a caller mistake. Retry once; if it persists, run `gbrain doctor`.',- protocol_version: MEMORY_VERBS_VERSION,- }- : { error: 'internal_error', message: redactedMsg };- return {- content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }],- isError: true,- };+ // Agent contract v1 (A1): every failure — OperationError, classified DB+ // access errors, uncaught throws — goes through the one total normaliser,+ // which redacts raw messages, keeps verbs on their frozen v1 codes, and+ // never tells a mutating op with an unknown outcome to retry.+ return errorResult(e, opts, { op: name, mutating: op.mutating === true, idempotent: op.idempotent === true, notices });}}diff --git a/test/cross-lane-5081-5032.test.ts b/test/cross-lane-5081-5032.test.tsindex d7df880f52..6ea5d91c62 100644--- a/test/cross-lane-5081-5032.test.ts+++ b/test/cross-lane-5081-5032.test.ts@@ -20,6 +20,7 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import { dispatchToolCall, type DispatchOpts } from '../src/mcp/dispatch.ts';import { resolveMcpStdioSourceScope } from '../src/mcp/server.ts';import { withEnv } from './helpers/with-env.ts';+import { docsUrl } from '../src/core/agent-output.ts';const NATIVE_WINDOWS = process.platform === 'win32';const home = mkdtempSync(join(tmpdir(), 'gbrain-5081-5032-'));@@ -83,7 +84,8 @@ describe('ENG-O14 #5081 + #5032', () => {const { isError, body } = await asWindows(() => call('put_page', { slug: 'calendar:planning', content: PAGE('Planning') }));expect(isError).toBe(true);expect(body.error).toBe('colon_slug_windows_write_through');- expect(body.docs).toBe('docs/guides/write-refusals.md#colon_slug_windows_write_through');+ // Agent contract v1: the wire docs value is the absolute, version-pinned URL of the registry anchor.+ expect(body.docs).toBe(docsUrl('docs/guides/write-refusals.md#colon_slug_windows_write_through'));expect(await engine.getPage('calendar:planning', { sourceId: 'work' })).toBeNull();}));diff --git a/test/explicit-read-admission-5081.test.ts b/test/explicit-read-admission-5081.test.tsindex 33285efcb8..09a7a32b6a 100644--- a/test/explicit-read-admission-5081.test.ts+++ b/test/explicit-read-admission-5081.test.ts@@ -30,6 +30,7 @@ import { dispatchToolCall, buildOperationContext, type DispatchOpts } from '../simport { resolveMcpStdioSourceScope } from '../src/mcp/server.ts';import { withEnv } from './helpers/with-env.ts';import { encodeDeepResearchId } from '../src/core/deep-research-id.ts';+import { docsUrl } from '../src/core/agent-output.ts';let engine: PGLiteEngine;let outsideCwd: string;@@ -165,7 +166,8 @@ describe('#5081 — explicit reads from a GBRAIN_SOURCE-bound stdio connection',test('denials carry the docs anchor', async () => {const { body } = await call(await bound(), 'search', { query: MARKER, source_id: 'private' });- expect(body.docs).toBe('docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection');+ // Agent contract v1: the wire docs value is the absolute, version-pinned URL of the anchor.+ expect(body.docs).toBe(docsUrl('docs/guides/multi-source-brains.md#explicit-reads-from-a-bound-agent-connection'));});test('a target that opted out is named as opted out', async () => {diff --git a/test/fixtures/agent-contract/v1/error-with-notices.json b/test/fixtures/agent-contract/v1/error-with-notices.jsonindex 66cbe6f196..fd58172ca0 100644--- a/test/fixtures/agent-contract/v1/error-with-notices.json+++ b/test/fixtures/agent-contract/v1/error-with-notices.json@@ -2,7 +2,7 @@"content": [{"type": "text",- "text": "{\n \"error\": \"unavailable\",\n \"code\": \"unavailable\",\n \"message\": \"Semantic search is unavailable.\",\n \"suggestion\": \"Keyword search still works.\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#unavailable\",\n \"reason\": \"embeddings_disabled\",\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"unavailable\"\n ],\n \"class\": \"unavailable\",\n \"retryable\": false,\n \"notices\": [\n {\n \"code\": \"backup_coverage\",\n \"kind\": \"safety\",\n \"why\": \"Two sources have no backup.\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"backup\",\n \"--json\"\n ],\n \"command\": \"gbrain backup --json\",\n \"consent\": [],\n \"actor\": \"user\",\n \"why\": \"Shows which assets are not backed up.\",\n \"requires_exclusive\": false\n },\n \"user_message\": \"Some of your notes are not backed up. Want me to show you which ones?\",\n \"contract_version\": 1\n }\n ],\n \"contract_version\": 1\n}"+ "text": "{\n \"error\": \"unavailable\",\n \"code\": \"unavailable\",\n \"message\": \"Semantic search is unavailable.\",\n \"suggestion\": \"Keyword search still works. Next: run_doctor {}\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#unavailable\",\n \"reason\": \"embeddings_disabled\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"doctor\",\n \"--json\"\n ],\n \"command\": \"gbrain doctor --json\",\n \"mcp\": {\n \"tool\": \"run_doctor\",\n \"arguments\": {}\n },\n \"consent\": [],\n \"actor\": \"agent\",\n \"why\": \"Doctor reports what is missing or failing on the brain host.\",\n \"requires_exclusive\": false\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"unavailable\"\n ],\n \"class\": \"unavailable\",\n \"retryable\": false,\n \"notices\": [\n {\n \"code\": \"backup_coverage\",\n \"kind\": \"safety\",\n \"why\": \"Two sources have no backup.\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"backup\",\n \"--json\"\n ],\n \"command\": \"gbrain backup --json\",\n \"consent\": [],\n \"actor\": \"user\",\n \"why\": \"Shows which assets are not backed up.\",\n \"requires_exclusive\": false\n },\n \"user_message\": \"Some of your notes are not backed up. Want me to show you which ones?\",\n \"contract_version\": 1\n }\n ],\n \"contract_version\": 1\n}"}],"isError": truediff --git a/test/recall-budget-policy-thin-cli.test.ts b/test/recall-budget-policy-thin-cli.test.tsindex 8856e054e3..f06e2de279 100644--- a/test/recall-budget-policy-thin-cli.test.ts+++ b/test/recall-budget-policy-thin-cli.test.ts@@ -112,7 +112,8 @@ test.each(['query_first', 'facts_first'])('thin %s JSON preserves a remote readdispatch: async () => ({ isError: true, content: [{ type: 'text', text: JSON.stringify(error) }] }),});expect(result.exitCode).toBe(1);- expect(JSON.parse(result.stdout)).toEqual(error);+ // Agent contract v1: legacy keys preserved verbatim; the client adds the canonical `code`.+ expect(JSON.parse(result.stdout)).toEqual({ ...error, code: 'unavailable' });expect(validateAgainstSchema(JSON.parse(result.stdout), ERROR_SCHEMA)).toEqual([]);expect(result.stderr).toContain('Synthetic service unavailable');expect(result.calls).toHaveLength(1);diff --git a/test/serve-http-surface-ceiling.test.ts b/test/serve-http-surface-ceiling.test.tsindex 37f8e840ec..6a2ece8264 100644--- a/test/serve-http-surface-ceiling.test.ts+++ b/test/serve-http-surface-ceiling.test.ts@@ -237,8 +237,11 @@ describe('serve --http --surface verbs ceiling E2E (hermetic PGLite)', () => {// result, never a transport-level error).expect(result.isError).toBe(true);expect(result.content?.[0]?.type).toBe('text');- expect(JSON.parse(result.content[0].text)).toEqual({+ // Agent contract v1: the frozen `error` value stays; `code` is the canonical+ // unknown_tool; the rest of the envelope is additive.+ expect(JSON.parse(result.content[0].text)).toMatchObject({error: 'unknown_operation',+ code: 'unknown_tool',message: 'Unknown: list_pages',});}, 30_000);diff --git a/test/validate-params.test.ts b/test/validate-params.test.tsindex 29155dd800..15e010ca16 100644--- a/test/validate-params.test.ts+++ b/test/validate-params.test.ts@@ -100,8 +100,9 @@ describe('warn mode (default) — accept + _meta.warnings + model-visible block']);// D8 second-block mechanism carries the grace-period notice.expect(out.content.length).toBe(2);+ // Agent contract v1: the block rides the notice channel (prefix line), its text kept as `why:`.expect(out.content[1].text).toBe(- 'warning: unknown parameter "partal" ignored — did you mean "partial"? A future release rejects unknown parameters.',+ '[gbrain notice unknown_param kind=info]\nwhy: warning: unknown parameter "partal" ignored — did you mean "partial"? A future release rejects unknown parameters.',);});@@ -117,7 +118,7 @@ describe('warn mode (default) — accept + _meta.warnings + model-visible block'// Nothing within edit distance → no suggestion key at all.expect('suggestion' in warnings[0]).toBe(false);expect(out.content[1].text).toBe(- 'warning: unknown parameter "totally_unrelated_key" ignored. A future release rejects unknown parameters.',+ '[gbrain notice unknown_param kind=info]\nwhy: warning: unknown parameter "totally_unrelated_key" ignored. A future release rejects unknown parameters.',);});