Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(agent-contract): A0 frozen interfaces for the agent operator wave

garrytan644d14cac0b5
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 09fa913cd5..52011d6e06 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -80,6 +80,10 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/core/ingestion/sources/file-watcher.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
{ path: 'src/core/ingestion/sources/gstack-learnings.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
{ path: 'src/core/ingestion/sources/inbox-folder.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/guides/data-ingestion.md promises the inbox folder)' },
+ { path: 'src/core/consent.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (C1/C2 command handlers) land on the collector' },
+ { path: 'src/core/interaction.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (A5 prompt shims, C5 readers) land on the collector' },
+ { path: 'src/core/ops/callable.ts', reason: 'held: agent operator wave A0 freeze; tools/list + dispatch wiring lands in A2 on the collector' },
+ { path: 'src/core/readiness.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (E/F readiness producers) land on the collector' },
{ path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' },
];
diff --git a/src/cli/command-table.ts b/src/cli/command-table.ts
index fcc627fecf..7085a76e0e 100644
--- a/src/cli/command-table.ts
+++ b/src/cli/command-table.ts
@@ -34,6 +34,7 @@
*/
import type { GBrainConfig } from '../core/config.ts';
import type { BrainEngine } from '../core/engine.ts';
+import type { Effect, Notice } from '../core/agent-output.ts';
export type CliPhase = 'pre-connect' | 'pre-connect-own-engine' | 'post-connect';
export type CliThinClientMode = 'none' | 'refuse' | 'route-then-refuse';
@@ -45,6 +46,27 @@ export interface CliDispatchContext {
SELECTED_CONFIG_BY_ENGINE: Pick<WeakMap<BrainEngine, GBrainConfig>, 'get'>;
/** import.meta.url of src/cli.ts, for paths the moved bodies resolved relative to it. */
cliModuleUrl: string;
+ /** Agent contract v1 (A6): CLI notice channel (TTY stderr lines, non-TTY `[AGENT]` block, `--json` `notices`). */
+ emitNotice?: (n: Notice) => void;
+}
+
+/** One curated flag in a lazy help module (D3). */
+export interface CliHelpFlag {
+ name: string;
+ type: 'boolean' | 'string' | 'number' | 'enum';
+ values?: readonly string[];
+ desc: string;
+ /** Effects the flag authorizes or triggers (e.g. `--yes` on paid work). */
+ consent?: readonly Effect[];
+}
+
+/** Curated help spec loaded lazily from `src/cli/help/<command>.ts` (D3). */
+export interface CliHelpSpec {
+ summary: string;
+ usage: string;
+ flags: readonly CliHelpFlag[];
+ examples: readonly string[];
+ end_of_options?: true;
}
export interface PreConnectCommandModule {
@@ -62,6 +84,16 @@ interface CliCommandBase {
selfHelp?: true;
/** Skip the startup update check and mark children (member of STARTUP_HOOK_SKIP_COMMANDS). */
skipStartupHooks?: true;
+ /** Agent contract v1 (D2): the command's `--json` output contract; turns the stdout guard on. */
+ json?: 'document' | 'ndjson';
+ /** The whole invocation, startup included, is read-only (eligible as a `fix.verify`). */
+ read_only?: true;
+ /** A4: consent-gated command; connects probe-only until consent is granted. */
+ startup?: 'observational';
+ /** Honours a bare `--` as end of options (positionals after it are never flags). */
+ end_of_options?: true;
+ /** D3: lazy curated help module. */
+ help?: () => Promise<{ help: CliHelpSpec }>;
}
export type CliCommandRecord =
diff --git a/src/core/agent-output.ts b/src/core/agent-output.ts
new file mode 100644
index 0000000000..359d63ed29
--- /dev/null
+++ b/src/core/agent-output.ts
@@ -0,0 +1,476 @@
+/**
+ * Agent operator contract v1 (docs/designs/AGENT_OPERATOR_WAVE.md, A0/A1/A6).
+ *
+ * One `Action` (`fix`) for every failure, refusal, degradation and
+ * recommendation; one error envelope (`AgentEnvelope`) for CLI `--json`, MCP
+ * `isError` results and HTTP bodies; one notice wire format. `next` and the
+ * shell `command` are computed here at render time and never stored.
+ *
+ * Everything an agent reads is built from static registry templates plus
+ * interpolated ids that pass through `inertText()`: newlines and marker
+ * tokens are neutralised so a page title can never forge an instruction.
+ */
+import { existsSync } from 'node:fs';
+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';
+
+export const CONTRACT_VERSION = 1 as const;
+
+export type Effect = 'paid' | 'destructive' | 'credentials' | 'egress' | 'persistent_install';
+export type Actor = 'agent' | 'user' | 'host_admin' | 'provider';
+export type Next = 'run' | 'ask_user' | 'tell_user_to_run' | 'wait' | 'report';
+export type Transport = 'cli' | 'stdio' | 'http';
+export type Surface = 'verbs' | 'starter' | 'full';
+export type ErrorClass = 'caller' | 'consent' | 'retryable' | 'unavailable' | 'server' | 'host_only';
+
+export interface McpCall { tool: string; arguments: Record<string, unknown> }
+
+/** A value the agent must obtain before running (e.g. a model's price). argv holds `<name>` only for these. */
+export interface ActionInput { name: string; how: string }
+
+/** Stored/constructed form. Never carries `next` or `command`: both are computed at render time. */
+export interface Action {
+ argv?: string[];
+ mcp?: McpCall;
+ consent: Effect[];
+ actor: Actor;
+ why: string;
+ user_message?: string;
+ verify?: { argv?: string[]; mcp?: McpCall };
+ docs?: string;
+ requires_exclusive: boolean;
+ inputs?: ActionInput[];
+ plan_hash?: string;
+ preview_argv?: string[];
+ then?: Action;
+}
+
+/** Wire form: what an agent reads. */
+export interface RenderedAction extends Omit<Action, 'then' | 'docs'> {
+ command?: string;
+ next: Next;
+ docs?: string;
+ then?: RenderedAction;
+}
+
+export type NoticeKind = 'safety' | 'degraded' | 'coaching' | 'ask' | 'info';
+export interface DecisionOption { id: string; label: string; argv?: string[] }
+export interface Decision { id: string; question: string; options: DecisionOption[]; default: string; default_reason: string }
+
+export interface Notice {
+ code: string;
+ kind: NoticeKind;
+ why: string;
+ fix?: Action;
+ user_message?: string;
+ decisions?: Decision[];
+}
+export interface RenderedNotice extends Omit<Notice, 'fix'> { fix?: RenderedAction; contract_version: 1 }
+
+/** The one error envelope (CLI --json document, MCP isError content[0], HTTP bodies). */
+export interface AgentEnvelope {
+ error: string;
+ code: string;
+ reason?: string;
+ message: string;
+ suggestion: string;
+ why?: string;
+ fix?: RenderedAction;
+ docs?: string;
+ docs_cmd: string[];
+ class: ErrorClass;
+ retryable: boolean;
+ notices?: RenderedNotice[];
+ contract_version: 1;
+ detail?: string; protocol_version?: 1; write_request?: unknown; write_error?: string;
+}
+
+export interface RenderContext {
+ transport: Transport;
+ surface?: Surface;
+ isCallable(opName: string): boolean;
+ preapproved(effects: Effect[], estUsd?: number | null): boolean;
+ principal?: string;
+}
+
+export interface AgentErrorContext {
+ transport: Transport;
+ op?: string;
+ command?: string;
+ mutating?: boolean;
+ idempotent?: boolean;
+ outcome?: 'not_started' | 'failed' | 'unknown' | 'committed' | 'pending';
+ render: RenderContext;
+}
+
+export interface CliErrorRender { stdout?: string; stderr?: string; exitCode: number }
+
+/** Attached to OperationContext (MCP) and the CLI dispatch context. */
+export interface NoticeSink { emitNotice(n: Notice): void }
+
+// ── render context defaults ────────────────────────────────────────────────
+
+/** The trusted local CLI: no MCP tool is callable from a shell, nothing is preapproved unless A4 says so. */
+export function cliRenderContext(overrides: Partial<RenderContext> = {}): RenderContext {
+ return { transport: 'cli', isCallable: () => false, preapproved: () => false, ...overrides };
+}
+
+// ── text safety ────────────────────────────────────────────────────────────
+
+const MARKER_RE = /\[(\/?)(AGENT|SHOW USER|gbrain notice)/gi;
+const MAX_INLINE = 2_000;
+
+/**
+ * Neutralise interpolated text for any agent-visible channel: newlines become
+ * spaces and marker tokens lose their opening bracket, so `[/SHOW USER]` in a
+ * page title renders as `(/SHOW USER]` and cannot close or open a block.
+ */
+export function inertText(value: string, max: number = MAX_INLINE): string {
+ const flat = value.replace(/\r\n|\r|\n|\u2028|\u2029/g, ' ').replace(MARKER_RE, '($1$2');
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
+}
+
+const SAFE_SHELL = /^[A-Za-z0-9_@%+=:,./-]+$/;
+
+/** POSIX shell quoting; the only way a human `command` string is built. */
+export function shellQuote(argv: readonly string[]): string {
+ return argv.map(arg => {
+ if (arg === '') return "''";
+ if (SAFE_SHELL.test(arg)) return arg;
+ return `'${inertText(arg).replace(/'/g, `'\\''`)}'`;
+ }).join(' ');
+}
+
+/**
+ * Split a literal shell command that a legacy site stored as a string (F0's
+ * refusal `fix`, a `suggestion` that is exactly one command) into argv. Only
+ * `gbrain …` commands made of plain or single-quoted words qualify; anything
+ * with pipes, substitutions or placeholders returns undefined (prose stays prose).
+ */
+export function argvFromCommand(command: string): string[] | undefined {
+ const s = command.trim().replace(/^`|`$/g, '');
+ if (!s.startsWith('gbrain ') && s !== 'gbrain') return undefined;
+ const out: string[] = [];
+ const re = /\s*(?:'([^']*)'|([^\s'"`$|;&<>()\\]+))/y;
+ let i = 0;
+ while (i < s.length) {
+ re.lastIndex = i;
+ const m = re.exec(s);
+ if (!m) return undefined;
+ out.push(m[1] ?? m[2]);
+ i = re.lastIndex;
+ while (i < s.length && s[i] === ' ') i++;
+ }
+ return out.length ? out : undefined;
+}
+
+/** `no_pull: true` on MCP, `--no-pull` on the CLI. */
+export function paramRef(ctx: { transport: Transport }, param: string): string {
+ return ctx.transport === 'cli' ? `--${param.replace(/_/g, '-')}` : `${param}: true`;
+}
+
+// ── docs URLs ──────────────────────────────────────────────────────────────
+
+const REPO_BLOB = 'https://github.com/garrytan/gbrain/blob';
+let docsRefOverride: string | null = null;
+
+/** Test seam: pin the ref docsUrl() uses (null restores detection). */
+export function __setDocsRefForTests(ref: string | null): void { docsRefOverride = ref; }
+
+function docsRef(): string {
+ if (docsRefOverride !== null) return docsRefOverride;
+ const root = join(import.meta.dir, '..', '..');
+ return existsSync(join(root, '.git')) ? 'master' : `v${VERSION}`;
+}
+
+/**
+ * Absolute docs URL for a repo-relative anchor (`docs/guides/x.md#y`).
+ * Published package → the `v<VERSION>` tag; source checkout → `master`;
+ * `LLMS_REPO_BASE` (fork override, same knob as build:llms) wins.
+ */
+export function docsUrl(anchor: string): string {
+ if (/^https?:\/\//.test(anchor)) return anchor;
+ const path = anchor.replace(/^\.?\//, '');
+ const forkBase = process.env.LLMS_REPO_BASE?.replace(/\/+$/, '');
+ return forkBase ? `${forkBase}/${path}` : `${REPO_BLOB}/${docsRef()}/${path}`;
+}
+
+// ── next + rendering ───────────────────────────────────────────────────────
+
+/** The published decision table (first matching row wins). */
+export function deriveNext(a: Action, ctx: RenderContext): Next {
+ const callableMcp = a.mcp !== undefined && ctx.isCallable(a.mcp.tool);
+ if (!a.argv?.length && !callableMcp) return 'report';
+ if (a.actor === 'provider') return 'wait';
+ if (a.actor === 'user' || a.actor === 'host_admin') return 'tell_user_to_run';
+ if (ctx.transport !== 'cli' && !callableMcp) return 'tell_user_to_run';
+ if (a.consent.length > 0 && (a.consent.includes('destructive') || !ctx.preapproved(a.consent))) return 'ask_user';
+ return 'run';
+}
+
+function renderVerify(v: Action['verify'], ctx: RenderContext): RenderedAction['verify'] {
+ if (!v) return undefined;
+ const mcp = v.mcp && ctx.isCallable(v.mcp.tool) ? v.mcp : undefined;
+ if (!v.argv && !mcp) return undefined;
+ return { ...(v.argv ? { argv: v.argv } : {}), ...(mcp ? { mcp } : {}) };
+}
+
+/** Render an Action for the caller's surface. Key order is part of the v1 goldens. */
+export function renderAction(a: Action, ctx: RenderContext): RenderedAction {
+ const mcp = a.mcp && ctx.isCallable(a.mcp.tool) ? a.mcp : undefined;
+ const cliOnlyOnMcp = ctx.transport !== 'cli' && !mcp && a.actor === 'agent' && !!a.argv?.length;
+ const actor: Actor = cliOnlyOnMcp ? (ctx.transport === 'http' ? 'host_admin' : 'user') : a.actor;
+ const effective: Action = { ...a, mcp, actor };
+ const verify = renderVerify(a.verify, ctx);
+ const out: RenderedAction = {
+ ...(a.argv ? { argv: a.argv, command: shellQuote(a.argv) } : {}),
+ ...(mcp ? { mcp } : {}),
+ consent: a.consent,
+ actor,
+ next: deriveNext(effective, ctx),
+ why: inertText(a.why),
+ ...(a.user_message !== undefined ? { user_message: inertText(a.user_message) } : {}),
+ ...(verify ? { verify } : {}),
+ ...(a.docs ? { docs: docsUrl(a.docs) } : {}),
+ requires_exclusive: a.requires_exclusive,
+ ...(a.inputs?.length ? { inputs: a.inputs } : {}),
+ ...(a.plan_hash ? { plan_hash: a.plan_hash } : {}),
+ ...(a.preview_argv ? { preview_argv: a.preview_argv } : {}),
+ ...(a.then ? { then: renderAction(a.then, ctx) } : {}),
+ };
+ return out;
+}
+
+export function renderNotice(n: Notice, ctx: RenderContext): RenderedNotice {
+ return {
+ code: n.code,
+ kind: n.kind,
+ why: inertText(n.why),
+ ...(n.fix ? { fix: renderAction(n.fix, ctx) } : {}),
+ ...(n.user_message !== undefined ? { user_message: inertText(n.user_message) } : {}),
+ ...(n.decisions?.length ? { decisions: n.decisions } : {}),
+ contract_version: CONTRACT_VERSION,
+ };
+}
+
+export const NOTICE_PREFIX = '[gbrain notice ';
+const NOTICE_KIND_ORDER: readonly NoticeKind[] = ['safety', 'degraded', 'ask', 'coaching', 'info'];
+
+/** Stable order for notice blocks: safety, degraded, ask, coaching, info. */
+export function orderNotices<T extends { kind: NoticeKind }>(notices: readonly T[]): T[] {
+ return [...notices].sort((a, b) => NOTICE_KIND_ORDER.indexOf(a.kind) - NOTICE_KIND_ORDER.indexOf(b.kind));
+}
+
+function renderedStep(fix: RenderedAction): string | undefined {
+ if (fix.mcp) return `${fix.mcp.tool} ${JSON.stringify(fix.mcp.arguments)}`;
+ return fix.command;
+}
+
+/** The MCP extra text block for one notice. First line is the fixed prefix clients key on. */
+export function noticeBlock(n: RenderedNotice): string {
+ const lines = [`${NOTICE_PREFIX}${n.code} kind=${n.kind}]`, `why: ${n.why}`];
+ if (n.fix) {
+ const step = renderedStep(n.fix);
+ if (step) lines.push(`fix: ${step}`);
+ lines.push(`next: ${n.fix.next}`);
+ }
+ if (n.user_message) lines.push(`user_message: ${n.user_message}`);
+ for (const d of n.decisions ?? []) {
+ lines.push(`decision ${d.id}: ${inertText(d.question)} (default: ${d.default})`);
+ }
+ return lines.join('\n');
+}
+
+// ── HTTP view ──────────────────────────────────────────────────────────────
+
+const HTTP_DROP_KEYS = new Set(['pid', 'lock_owner', 'path', 'data_dir', 'database_path', 'asset']);
+const ABS_PATH_RE = /(?:^|(?<=[\s'"`(=]))(?:\/(?:home|Users|root|tmp|var|private|opt|srv|mnt|etc)\/[^\s'"`)]*|[A-Za-z]:\\[^\s'"`)]*|~\/[^\s'"`)]*)/g;
+const PID_RE = /\b(PID|pid)\s*[:=]?\s*\d+/g;
+const KEY_NAME_RE = /\b[A-Z][A-Z0-9]*_(?:API_KEY|TOKEN|SECRET)\b/g;
+
+function redactString(s: string): string {
+ return s.replace(ABS_PATH_RE, '<path>').replace(PID_RE, '$1 <redacted>').replace(KEY_NAME_RE, '<provider key>');
+}
+
+/** One transport-keyed redaction pass: http strips local paths, PIDs, key names and host posture keys. */
+export function redactForTransport<T>(value: T, transport: Transport): T {
+ if (transport !== 'http') return value;
+ const walk = (v: unknown): unknown => {
+ if (typeof v === 'string') return redactString(v);
+ if (Array.isArray(v)) return v.map(walk);
+ if (v && typeof v === 'object') {
+ const out: Record<string, unknown> = {};
+ for (const [k, val] of Object.entries(v as Record<string, unknown>)) {
+ if (HTTP_DROP_KEYS.has(k)) continue;
+ out[k] = walk(val);
+ }
+ return out;
+ }
+ return v;
+ };
+ return walk(value) as T;
+}
+
+// ── envelope ───────────────────────────────────────────────────────────────
+
+/** Fields a normaliser row extracts before the shared envelope assembly. */
+export interface EnvelopeParts {
+ error: string;
+ code: string;
+ message: string;
+ suggestion?: string;
+ reason?: string;
+ why?: string;
+ fix?: Action;
+ docs?: string;
+ notices?: Notice[];
+ detail?: string;
+ protocol_version?: 1;
+ write_request?: unknown;
+ write_error?: string;
+ retryable?: boolean;
+}
+
+function appendFixToSuggestion(suggestion: string, fix: RenderedAction | undefined): string {
+ if (!fix) return suggestion;
+ const step = renderedStep(fix);
+ if (!step || suggestion.includes(step)) return suggestion;
+ const prose = suggestion.trim();
+ return prose ? `${prose.replace(/[.\s]*$/, '.')} Next: ${step}` : `Next: ${step}`;
+}
+
+/** Assemble the envelope from normalised parts. Legacy keys first, in their historical order. */
+export function buildEnvelope(p: EnvelopeParts, ctx: RenderContext): AgentEnvelope {
+ const entry = codeEntry(p.code);
+ const fix = p.fix ? renderAction(p.fix, ctx) : undefined;
+ const suggestion = appendFixToSuggestion(p.suggestion ?? entry?.suggestion ?? '', fix);
+ const docs = p.docs ?? entry?.docs ?? `docs/guides/error-codes.md#${p.code}`;
+ const notices = p.notices?.length ? orderNotices(p.notices).map(n => renderNotice(n, ctx)) : undefined;
+ return {
+ error: p.error,
+ code: p.code,
+ message: p.message,
+ suggestion,
+ docs: docsUrl(docs),
+ ...(p.detail !== undefined ? { detail: p.detail } : {}),
+ ...(p.protocol_version !== undefined ? { protocol_version: p.protocol_version } : {}),
+ ...(p.write_request !== undefined ? { write_request: p.write_request } : {}),
+ ...(p.write_error !== undefined ? { write_error: p.write_error } : {}),
+ ...(p.reason !== undefined ? { reason: p.reason } : {}),
+ ...(p.why !== undefined ? { why: p.why } : {}),
+ ...(fix ? { fix } : {}),
+ docs_cmd: ['gbrain', 'errors', p.code],
+ class: codeClass(p.code),
+ retryable: p.retryable ?? codeRetryable(p.code),
+ ...(notices ? { notices } : {}),
+ contract_version: CONTRACT_VERSION,
+ };
+}
+
+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),
+ 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);
+}
+
+/** Total: never throws; on an internal fault returns the prior generic envelope. */
+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);
+ }
+ 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);
+ }
+ return genericEnvelope(e, ctx);
+ } catch {
+ return genericEnvelope(e, ctx);
+ }
+}
+
+/** Pure: callers write the strings. TTY order: `Error [code]: msg` / `Fix:` / `Why:` / `Docs:`. */
+export function renderCliError(e: unknown, opts: { json: boolean; command: string; tty: boolean }): CliErrorRender {
+ const env = toAgentError(e, { transport: 'cli', command: opts.command, render: cliRenderContext() });
+ const exitCode = exitCodeForCode(env.code);
+ if (opts.json) return { stdout: `${JSON.stringify(env, null, 2)}\n`, exitCode };
+ const lines = [`Error [${env.code}]: ${env.message}`];
+ lines.push(`Fix: ${env.fix?.command ?? env.suggestion}`);
+ if (env.why) lines.push(`Why: ${env.why}`);
+ if (env.docs) lines.push(`Docs: ${env.docs}`);
+ return { stderr: `${lines.join('\n')}\n`, exitCode };
+}
+
+// ── wire builders shared by dispatch, the CLI and the goldens ──────────────
+
+export interface ToolResultShape {
+ content: { type: 'text'; text: string }[];
+ isError?: boolean;
+ _meta?: Record<string, unknown>;
+}
+
+/**
+ * MCP success result: `content[0]` is exactly the pre-v1 body (bare arrays
+ * included); each notice is one extra prefixed text block, mirrored rendered
+ * under `_meta.gbrain_notices`.
+ */
+export function toolResultWithNotices(result: unknown, notices: readonly Notice[], ctx: RenderContext): ToolResultShape {
+ const out: ToolResultShape = { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
+ if (notices.length === 0) return out;
+ const rendered = orderNotices(notices).map(n => redactForTransport(renderNotice(n, ctx), ctx.transport));
+ for (const n of rendered) out.content.push({ type: 'text', text: noticeBlock(n) });
+ out._meta = { gbrain_notices: rendered };
+ return out;
+}
+
+/** MCP error result: exactly one content block holding the envelope. */
+export function toolErrorResult(envelope: AgentEnvelope): ToolResultShape {
+ return { content: [{ type: 'text', text: JSON.stringify(envelope, null, 2) }], isError: true };
+}
+
+/**
+ * Legacy nested error shapes (`{ error: { class, code, message, hint } }`
+ * from code-def/code-refs, phase containment) keep their nesting and gain the
+ * v1 sibling keys.
+ */
+export function withAgentSiblings<T extends Record<string, unknown>>(
+ legacy: T,
+ parts: { code: string; fix?: Action },
+ ctx: RenderContext,
+): T & { code: string; fix?: RenderedAction; docs_cmd: string[]; contract_version: 1 } {
+ return {
+ ...legacy,
+ code: parts.code,
+ ...(parts.fix ? { fix: renderAction(parts.fix, ctx) } : {}),
+ docs_cmd: ['gbrain', 'errors', parts.code],
+ contract_version: CONTRACT_VERSION,
+ };
+}
+
+/** The `--json` exit-time fallback document: a non-zero exit that wrote no final document. */
+export function fallbackJsonDocument(exitCode: number, lastCode?: string): Record<string, unknown> {
+ return {
+ error: 'command_failed',
+ code: lastCode ?? 'command_failed',
+ message: `The command exited with status ${exitCode} without writing its JSON result.`,
+ suggestion: 'Re-run without --json to read the error on stderr, or run `gbrain doctor --json`.',
+ exit_code: exitCode,
+ contract_version: CONTRACT_VERSION,
+ };
+}
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index ab991d5e8b..c565f6cfec 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -54,6 +54,7 @@
*/
import { writeSync } from 'node:fs';
+import { spawn, type ChildProcess, type SpawnOptions } from 'node:child_process';
import { formatWithOptions } from 'node:util';
import {
drainAllBackgroundWorkForCliExit,
@@ -680,7 +681,8 @@ function chainStdoutWrite(data: string | Uint8Array, encoding?: BufferEncoding):
* later than the native writer fired it, never earlier), boolean return
* (always true: the chain owns backpressure, and flushThenExit awaits it).
*/
-export function installStdoutPipeDelivery(): void {
+export function installStdoutPipeDelivery(opts: { json?: 'document' | 'ndjson' } = {}): void {
+ void opts;
if (stdoutInterposed) return;
if (process.stdout.isTTY) return;
stdoutInterposed = true;
@@ -755,6 +757,32 @@ export async function writeStdoutFinal(output: string): Promise<void> {
await chainStdoutWrite(output);
}
+/**
+ * Agent contract v1 (A0/D2): `--json` (or `--json=true`) appears before a
+ * bare `--` end-of-options marker.
+ */
+export function jsonRequested(argv: readonly string[]): boolean {
+ for (const a of argv) {
+ if (a === '--') return false;
+ if (a === '--json' || a === '--json=true') return true;
+ }
+ return false;
+}
+
+/** One NDJSON line on fd 1 (the only stdout path for `json: 'ndjson'` commands under the guard). */
+export async function writeNdjsonLine(line: unknown): Promise<void> {
+ await chainStdoutWrite(`${JSON.stringify(line)}\n`);
+}
+
+/**
+ * Spawn a child CLI process. Under the `--json` guard the child's stdout is
+ * piped to this process's stderr so it can never corrupt the JSON document;
+ * otherwise stdio is inherited. The one sanctioned `stdio: 'inherit'` site.
+ */
+export function spawnCliChild(cmd: string, args: readonly string[], opts: SpawnOptions = {}): ChildProcess {
+ return spawn(cmd, [...args], { stdio: 'inherit', ...opts });
+}
+
export interface FinishCliTeardownOpts {
/** Engine to disconnect. A disconnect throw is warned + swallowed (D3). */
engine: { disconnect(): Promise<void> };
diff --git a/src/core/consent.ts b/src/core/consent.ts
new file mode 100644
index 0000000000..6a8aa07981
--- /dev/null
+++ b/src/core/consent.ts
@@ -0,0 +1,111 @@
+/**
+ * Consent primitive (agent operator contract v1, A4). CLI command handlers
+ * call `requireConsent()` before paid, destructive, credential, egress or
+ * persistent-install work. It resolves with the Authorization that covers the
+ * request or throws `confirmation_required` (exit 3) carrying the consent
+ * payload. Core library paths never prompt: they take an Authorization.
+ *
+ * Consent honesty: an agent can always pass `--yes`. This gate forces a stop
+ * and supplies relay text; it cannot prove a human agreed.
+ */
+import { CONTRACT_VERSION, renderAction, shellQuote, type Action, type Actor, type Effect, type RenderContext, type RenderedAction } from './agent-output.ts';
+import { opError } from './ops/contract.ts';
+
+export type CapSource = 'derived' | 'default' | 'user';
+
+export interface Authorization {
+ consented_effects: Effect[];
+ /** null only when no paid effect. */
+ cap_usd: number | null;
+ cap_source: CapSource | null;
+ via: 'yes' | 'max_usd' | 'tokenmax' | 'preapproval' | 'apply_flag' | 'non_interactive_flag' | 'tty_prompt';
+ /** destructive: binds the persisted approved selection. */
+ approval_token?: string;
+}
+
+export interface ConsentRequest {
+ command: string;
+ effects: Effect[];
+ actor: Actor;
+ what: string; why: string; risk: string;
+ user_message: string;
+ /** The exact command that runs once approved. */
+ argv: string[];
+ preview_argv?: string[];
+ est_usd?: number | null;
+ plan_hash?: string;
+ /** destructive: persisted with the approval (A4 destructive rail). */
+ selection?: unknown;
+ /** Raw argv, for --yes/--max-usd/--expect/--apply/--trust/--non-interactive. */
+ args: readonly string[];
+}
+
+/** CLI command handlers only. Resolves with the authorization or throws OperationError('confirmation_required'). */
+export async function requireConsent(req: ConsentRequest): Promise<Authorization> {
+ if (req.effects.length === 0) return { consented_effects: [], cap_usd: null, cap_source: null, via: 'yes' };
+ if (req.args.includes('--yes')) {
+ return { consented_effects: [...req.effects], cap_usd: null, cap_source: null, via: 'yes' };
+ }
+ throw opError('confirmation_required', `${req.what} needs the user's approval before it runs; nothing was changed.`,
+ req.user_message, { why: req.why });
+}
+
+/** The exit-3 `--json` document (and the data behind the human `[AGENT]` block). */
+export interface ConfirmationPayload {
+ status: 'confirmation_required';
+ error: 'confirmation_required';
+ code: 'confirmation_required';
+ message: string;
+ suggestion: string;
+ effects: Effect[];
+ actor: Actor;
+ why: string;
+ risk: string;
+ est_usd: number | null;
+ user_message: string;
+ fix: RenderedAction;
+ preview: { argv: string[]; command: string } | null;
+ plan_hash?: string;
+ preapprove_argv?: string[];
+ docs_cmd: string[];
+ contract_version: 1;
+}
+
+/**
+ * Destructive approvals bind the plan: the approved command already carries
+ * `--yes --expect <plan_hash>`. Paid payloads offer a per-run preapproval;
+ * destructive ones never do.
+ */
+export function confirmationPayload(req: ConsentRequest, ctx: RenderContext): ConfirmationPayload {
+ const destructive = req.effects.includes('destructive');
+ const argv = [...req.argv];
+ if (!argv.includes('--yes')) argv.push('--yes');
+ if (destructive && req.plan_hash && !argv.includes('--expect')) argv.push('--expect', req.plan_hash);
+ const fix: Action = {
+ argv, consent: [...req.effects], actor: req.actor, why: req.why, user_message: req.user_message,
+ requires_exclusive: false,
+ ...(req.preview_argv ? { preview_argv: req.preview_argv } : {}),
+ ...(req.plan_hash ? { plan_hash: req.plan_hash } : {}),
+ };
+ const rendered = renderAction(fix, ctx);
+ const paid = req.effects.includes('paid');
+ return {
+ status: 'confirmation_required',
+ error: 'confirmation_required',
+ code: 'confirmation_required',
+ message: `${req.what} needs the user's approval before it runs; nothing was changed.`,
+ suggestion: `Ask the user: ${req.user_message} If they agree, run: ${rendered.command}`,
+ effects: [...req.effects],
+ actor: req.actor,
+ why: req.why,
+ risk: req.risk,
+ est_usd: req.est_usd ?? null,
+ user_message: req.user_message,
+ fix: rendered,
+ preview: req.preview_argv ? { argv: req.preview_argv, command: shellQuote(req.preview_argv) } : null,
+ ...(req.plan_hash ? { plan_hash: req.plan_hash } : {}),
+ ...(paid && !destructive ? { preapprove_argv: ['gbrain', 'config', 'set', 'consent.preapprove.paid.max_usd_per_run', '<usd>'] } : {}),
+ docs_cmd: ['gbrain', 'errors', 'confirmation_required'],
+ contract_version: CONTRACT_VERSION,
+ };
+}
diff --git a/src/core/error-catalogue.ts b/src/core/error-catalogue.ts
index 1bbde5ae97..e220bb3536 100644
--- a/src/core/error-catalogue.ts
+++ b/src/core/error-catalogue.ts
@@ -19,6 +19,10 @@
*/
import { OperationError } from './ops/contract.ts';
import { StructuredAgentError, buildError } from './errors.ts';
+import { CODES, type CodeEntry, type RegistryCode } from './error-registry.ts';
+import type { ErrorClass } from './agent-output.ts';
+
+export { CODES, type CodeEntry, type RegistryCode } from './error-registry.ts';
export interface CatalogueEntry {
/** Stable machine-readable code on the wire. */
@@ -59,6 +63,65 @@ export const ERROR_CATALOGUE = {
export type CatalogueName = keyof typeof ERROR_CATALOGUE;
+/** Named refusals (one code may carry several anchors). Same table as ERROR_CATALOGUE. */
+export const REFUSALS = ERROR_CATALOGUE;
+
+const CLASS_SUGGESTION: Record<ErrorClass, string> = {
+ caller: 'Correct the request using the message above, then retry.',
+ consent: 'Stop and ask the user; re-run only with the authorization the message names.',
+ retryable: 'Wait briefly, then retry the same request (writes: reuse the same request_id).',
+ unavailable: 'A required capability is not available on this brain. Run `gbrain doctor --json` to see what is missing.',
+ server: 'Server-side failure, not a caller mistake. Run `gbrain doctor --json` on the brain host; if it repeats, report it to the user.',
+ host_only: 'Only the brain host\'s operator can resolve this. Tell the user the message and run `gbrain doctor --json` on the brain host.',
+};
+
+const REFUSAL_DOCS_BY_CODE: ReadonlyMap<string, string> = new Map(
+ Object.entries(ERROR_CATALOGUE).filter(([name, e]) => name === e.code).map(([, e]) => [e.code, e.docs]),
+);
+
+/** Legacy wire values that are not themselves registered codes map to their canonical code. */
+const CANONICAL_BY_LEGACY: ReadonlyMap<string, string> = new Map(
+ Object.entries(CODES as Record<string, CodeEntry>)
+ .filter(([, e]) => e.legacy_error !== undefined && !(e.legacy_error in CODES))
+ .map(([code, e]) => [e.legacy_error!, code]),
+);
+
+export function isRegistryCode(code: string): code is RegistryCode {
+ return Object.prototype.hasOwnProperty.call(CODES, code);
+}
+
+/** The registry entry with defaults applied (docs anchor, suggestion), or undefined for an unregistered code. */
+export function codeEntry(code: string): (CodeEntry & { docs: string; suggestion: string }) | undefined {
+ if (!isRegistryCode(code)) return undefined;
+ const e = CODES[code] as CodeEntry;
+ return {
+ ...e,
+ docs: e.docs ?? REFUSAL_DOCS_BY_CODE.get(code) ?? `docs/guides/error-codes.md#${code}`,
+ suggestion: e.suggestion ?? CLASS_SUGGESTION[e.class],
+ };
+}
+
+/** Canonical registry code for a wire `error` value (identity unless the value is a frozen legacy alias). */
+export function canonicalCodeFor(wire: string): string {
+ return CANONICAL_BY_LEGACY.get(wire) ?? wire;
+}
+
+/** An unregistered code is a server fault by construction (the AST test keeps that set empty). */
+export function codeClass(code: string): ErrorClass {
+ return isRegistryCode(code) ? (CODES[code] as CodeEntry).class : 'server';
+}
+
+export function codeRetryable(code: string): boolean {
+ if (!isRegistryCode(code)) return false;
+ const e = CODES[code] as CodeEntry;
+ return e.retryable ?? e.class === 'retryable';
+}
+
+/** CLI exit code for an error code (A3 table): entry override, else 1. */
+export function exitCodeForCode(code: string): number {
+ return isRegistryCode(code) ? (CODES[code] as CodeEntry).exit ?? 1 : 1;
+}
+
/**
* An `OperationError` for a catalogue entry. `message` is one sentence; `hint`
* is the exact command to run next, filled with real values.
diff --git a/src/core/error-registry.ts b/src/core/error-registry.ts
new file mode 100644
index 0000000000..072726a56b
--- /dev/null
+++ b/src/core/error-registry.ts
@@ -0,0 +1,245 @@
+/**
+ * The error code registry (agent operator contract v1, A2). Every literal
+ * code thrown in `src/` has one entry here: its class (which derives the CLI
+ * exit code and `retryable`), a one-sentence meaning, and optionally a
+ * default suggestion, a default fix (diagnostic reads only), reasons, a docs
+ * anchor and the frozen legacy wire value. `docs/guides/error-codes.md` is
+ * generated from this table (`bun run build:error-codes`), and
+ * `test/error-catalogue.test.ts` walks the source AST so an unregistered code
+ * fails CI.
+ *
+ * Adding a code: add one entry (snake_case, no transport prefix), then run
+ * `bun run build:error-codes`. Entries default their docs to
+ * `docs/guides/error-codes.md#<code>`.
+ */
+import type { Action, Actor, Effect, ErrorClass } from './agent-output.ts';
+
+export interface CodeEntry {
+ class: ErrorClass;
+ /** What happened, one sentence. */
+ summary: string;
+ /** Why it happens / what it protects. */
+ why?: string;
+ /** Closed vocabulary for `reason` when one code covers several causes. */
+ reasons?: readonly string[];
+ /** Repo-relative anchor; default `docs/guides/error-codes.md#<code>`. */
+ docs?: string;
+ /** Default prose suggestion when a site supplies none. */
+ suggestion?: string;
+ /** Default fix template: read-only diagnostics only (scanner-checked). */
+ fix?: Action;
+ effects?: readonly Effect[];
+ actor?: Actor;
+ /** The code this one replaced (documented in error-codes.md "Renamed in this release"). */
+ renamed_from?: string;
+ /** Frozen v1 `error` wire value some sites keep for this canonical code. */
+ legacy_error?: string;
+ /** CLI exit code; default derives from class (1). */
+ exit?: number;
+ retryable?: boolean;
+}
+
+export const CODES = {
+ acknowledgment_unavailable: { class: 'unavailable', summary: "This batch is unknown or outside the retained replay window." },
+ ambiguous_id: { class: 'caller', summary: "The legacy id matches multiple readable pages." },
+ ambiguous_skill: { class: 'caller', summary: "This name belongs to multiple authorized sources." },
+ 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." },
+ benchmark_empty: { class: 'caller', summary: "The benchmark file has no tasks." },
+ benchmark_exists: { class: 'caller', summary: "A benchmark already exists at the target path." },
+ benchmark_judge_llm_no_rubric: { class: 'caller', summary: "Benchmark judge llm no rubric." },
+ benchmark_judge_qrels_no_expected: { class: 'caller', summary: "Benchmark judge qrels no expected." },
+ benchmark_judge_rule_no_checks: { class: 'caller', summary: "Benchmark judge rule no checks." },
+ benchmark_judge_unknown_kind: { class: 'caller', summary: "Benchmark judge unknown kind." },
+ benchmark_malformed: { class: 'caller', summary: "A benchmark row is not valid JSON." },
+ benchmark_missing_judge: { class: 'caller', summary: "Benchmark missing judge." },
+ benchmark_missing_task: { class: 'caller', summary: "Benchmark missing task." },
+ benchmark_missing_task_id: { class: 'caller', summary: "Benchmark missing task id." },
+ benchmark_not_found: { class: 'caller', summary: "The benchmark file cannot be read." },
+ benchmark_rule_check_bad_arg: { class: 'caller', summary: "Benchmark rule check bad arg." },
+ benchmark_rule_check_malformed: { class: 'caller', summary: "Benchmark rule check malformed." },
+ benchmark_rule_check_unknown_op: { class: 'caller', summary: "Benchmark rule check unknown op." },
+ bootstrap_empty: { class: 'caller', summary: "The benchmark bootstrap produced no tasks." },
+ bootstrap_pending_review: { class: 'caller', summary: "The bootstrapped benchmark awaits human review." },
+ bridge_ownership_conflict: { class: 'caller', summary: "The private local CLI registration is invalid." },
+ bucket_not_found: { class: 'unavailable', summary: "The configured storage bucket does not exist." },
+ budget_unsatisfiable: { class: 'unavailable', summary: "Reserved by MEMORY_VERBS v1; never returned." },
+ cancelled: { class: 'caller', summary: "The write was cancelled before it committed." },
+ 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." },
+ 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." },
+ 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." },
+ confirmation_required: { class: 'consent', summary: "The command needs the user's authorization before it runs; nothing was changed.", exit: 3 },
+ conflicting_source_scope: { class: 'caller', summary: "--source and --all-sources were both given." },
+ connector_account_changed: { class: 'caller', summary: "The connector credential resolves to a different account than the source is pinned to." },
+ 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." },
+ 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." },
+ database_error: { class: 'server', summary: "The brain database could not be reached or refused the operation." },
+ demo_graph_failed: { class: 'server', summary: "The fictional graph did not verify." },
+ demo_import_failed: { class: 'server', summary: "The fictional page did not import successfully." },
+ demo_verification_failed: { class: 'server', summary: "Expected ownership or decision provenance is missing." },
+ derived_cap_exhausted: { class: 'server', summary: "Paid work stopped at the cost cap derived from its estimate; the run is resumable." },
+ destination_not_ready: { class: 'host_only', summary: "The destination brain is not initialized for this operation." },
+ dirty_tree: { class: 'caller', summary: "Commit or stash canonical skill edits before optimization." },
+ effect_not_failed: { class: 'caller', summary: "Only a failed, non-running embedding effect can be explicitly retried." },
+ embedding_auth_failed: { class: 'unavailable', summary: "The embedding provider rejected the credentials." },
+ embedding_budget_below_worst_case: { class: 'unavailable', summary: "The embedding migration cap is below its worst-case cost; nothing was changed." },
+ embedding_configuration: { class: 'host_only', summary: "The brain's embedding configuration is invalid." },
+ embedding_disabled: { class: 'unavailable', summary: "Embeddings are disabled on this brain." },
+ embedding_failed: { class: 'server', summary: "Computing embeddings for the content failed." },
+ embedding_model_mismatch: { class: 'unavailable', summary: "The configured provider does not match the active embedding column." },
+ embedding_plane_split: { class: 'unavailable', summary: "Embedding plane split." },
+ embedding_storage_unavailable: { class: 'retryable', summary: "Embedding policy or claim storage is temporarily unavailable." },
+ embedding_unavailable: { class: 'unavailable', summary: "The provider returned an incomplete embedding batch." },
+ embedding_unconfigured: { class: 'host_only', summary: "The selected brain has no verifiable text embedding model and dimensions." },
+ export_limit: { class: 'caller', summary: "This migration is bounded to 5,000 active pages per source; split or use a reviewed bulk export." },
+ extraction_failed: { class: 'server', summary: "The accepted atom extraction produced malformed output." },
+ extractor_identity_mismatch: { class: 'server', summary: "The approved extractor differs from the installed extractor; this receipt cannot resume or admit another revision." },
+ fact_already_expired: { class: 'caller', summary: "The fact had already expired before this write." },
+ fact_not_found: { class: 'caller', summary: "Fact not found." },
+ facts_absorb_write_refused: { class: 'caller', summary: "Facts absorb refused the write." },
+ facts_payload_expired: { class: 'server', summary: "The accepted fact extraction failed and its retained payload has expired." },
+ fetch_failed: { class: 'retryable', summary: "Fetching the upstream failed." },
+ full_resync_required: { class: 'retryable', summary: "The catalog cursor is invalid or expired." },
+ git_index_locked: { class: 'retryable', summary: "Another Git process holds the canonical checkout index lock." },
+ git_index_stale: { class: 'caller', summary: "Git index stale." },
+ git_push_unavailable: { class: 'retryable', summary: "The canonical commit is durable locally; its push will retry." },
+ git_target_unsafe: { class: 'caller', summary: "Git cannot identify the existing canonical file by its native spelling." },
+ git_unavailable: { class: 'retryable', summary: "A git command did not complete." },
+ graph_incomplete: { class: 'server', summary: "Source relationship reconciliation is incomplete." },
+ held_out_overlaps_benchmark: { class: 'caller', summary: "Held out overlaps benchmark." },
+ held_out_required_for_bundled: { class: 'caller', summary: "Held out required for bundled." },
+ idempotency_conflict: { class: 'caller', summary: "The request_id already belongs to a different accepted operation." },
+ independent_principal_required: { class: 'consent', summary: "This local CLI principal already owns another source/destination for this harness." },
+ insufficient_scope: { class: 'host_only', summary: "The connection lacks the OAuth scope the operation requires.", legacy_error: 'permission_denied' },
+ 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_connector_text: { class: 'caller', summary: "Invalid connector text." },
+ 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." },
+ invalid_source_pin: { class: 'caller', summary: "The .gbrain-source pin names an invalid source id." },
+ invalid_source_uri: { class: 'caller', summary: "The page has a stored file source_uri that cannot be resolved to a local filesystem path." },
+ invalid_token: { class: 'host_only', summary: "The bearer token is missing, invalid, or revoked." },
+ invalid_write_wait: { class: 'caller', summary: "Invalid write wait." },
+ legacy_job_selection_invalid: { class: 'caller', summary: "The legacy job selection is invalid." },
+ legacy_jobs_active: { class: 'caller', summary: "Legacy jobs are still active." },
+ local_conflict: { class: 'caller', summary: "A local file or registration conflicts with the requested change." },
+ 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_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_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_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." },
+ 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." },
+ 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." },
+ projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },
+ provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },
+ publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },
+ 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." },
+ 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." },
+ refresh_no_upstream: { class: 'caller', summary: "The worktree has no upstream to refresh from." },
+ 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." },
+ 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." },
+ response_too_large: { class: 'caller', summary: "Persistence response exceeds the local transport limit." },
+ resume_spec_mismatch: { class: 'caller', summary: "Resume spec mismatch." },
+ revision_conflict: { class: 'caller', summary: "The target changed since it was read; the expected revision no longer matches." },
+ 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." },
+ 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." },
+ skill_bundle_required: { class: 'caller', summary: "Import cannot publish skill paths." },
+ 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_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." },
+ source_profile_no_backfill: { class: 'unavailable', summary: "This source profile disables automatic embedding backfill." },
+ source_referenced: { class: 'caller', summary: "OAuth clients still reference this source." },
+ source_root_conflict: { class: 'caller', summary: "Multiple active sources alias this canonical skill root; resolve ownership before publishing." },
+ 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." },
+ 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." },
+ target_escape: { class: 'caller', summary: "The skill target must remain within its selected root." },
+ timeout: { class: 'retryable', summary: "The operation did not finish within its time bound.", exit: 124 },
+ topology_change_required: { class: 'host_only', summary: "Adding this source would replace or overlap another owner root." },
+ unavailable: { class: 'unavailable', summary: "A required dependency or capability cannot serve this request." },
+ unexpected_file_bytes: { class: 'server', summary: "A canonical skill file mode changed outside publication." },
+ unexpected_staging_bytes: { class: 'server', summary: "Recovery staging has unexpected bytes or identity; the root and its recovery capacity remain reserved." },
+ unknown: { class: 'server', summary: "An unclassified failure (legacy StructuredError fallback code)." },
+ unknown_flag: { class: 'caller', summary: "The command does not accept one of the flags passed.", exit: 2 },
+ unknown_method: { class: 'caller', summary: "The JSON-RPC method is not supported." },
+ unknown_source: { class: 'caller', summary: "The named source is not registered or is archived." },
+ unknown_tool: { class: 'caller', summary: "The named tool does not exist or is not callable on this connection.", legacy_error: 'unknown_operation' },
+ unknown_transport: { class: 'unavailable', summary: "The caller's transport could not be identified." },
+ 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." },
+ 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." },
+ write_claim_lost: { class: 'retryable', summary: "Execution claim changed before publication." },
+ write_pending: { class: 'retryable', summary: "The write was accepted and is still pending; it may commit later.", exit: 10 },
+ writer_admin_intent_required: { class: 'host_only', summary: "Topology changes require an action-specific --admin-intent and the --expected-state from a reviewed writer status." },
+ writer_admin_locked: { class: 'host_only', summary: "Writer administration is locked; deactivation was not applied." },
+ writer_admin_state_changed: { class: 'caller', summary: "Writer topology changed since inspection; the administrative request was not applied." },
+ writer_busy: { class: 'retryable', summary: "The canonical worktree is busy with another write." },
+ writer_coordinator_required: { class: 'host_only', summary: "The operation needs managed persistence (a writer coordinator) on the brain host." },
+ writer_identity_invalid: { class: 'host_only', summary: "The local writer identity is invalid." },
+ writer_identity_publish_failed: { class: 'host_only', summary: "The replacement writer is durable but its credential file could not be published." },
+ writer_lock_unavailable: { class: 'retryable', summary: "Another activation probe is running." },
+ writer_manifest_mismatch: { class: 'caller', summary: "Successor checkout differs from the recorded canonical manifest." },
+ writer_manifest_unsafe: { class: 'caller', summary: "Canonical worktree transfer requires a symlink-free manifest." },
+ writer_not_initialized: { class: 'host_only', summary: "Persistence identity is missing." },
+ writer_not_quiesced: { class: 'host_only', summary: "Older writers or maintenance jobs are still running." },
+ writer_pool_capacity: { class: 'retryable', summary: "Mirror recovery is waiting for publication capacity." },
+ writer_registration_required: { class: 'host_only', summary: "Writer registration required." },
+ writer_regrant_required: { class: 'host_only', summary: "This lane already has a different grant." },
+ 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." },
+} as const satisfies Record<string, CodeEntry>;
+
+export type RegistryCode = keyof typeof CODES;
diff --git a/src/core/interaction.ts b/src/core/interaction.ts
new file mode 100644
index 0000000000..b1979a161e
--- /dev/null
+++ b/src/core/interaction.ts
@@ -0,0 +1,79 @@
+/**
+ * Interaction primitive (agent operator contract v1, A5): whether a human can
+ * answer a prompt, prompt reads that treat EOF/timeout as a decline, and
+ * bounded payload reads from stdin. Neither GBRAIN_INTERACTIVE nor
+ * GBRAIN_NON_INTERACTIVE implies consent.
+ */
+
+export interface InteractiveProbe {
+ env?: NodeJS.ProcessEnv;
+ stdinIsTTY?: boolean; stdoutIsTTY?: boolean;
+}
+
+/** Process-scoped markers only: a variable set inside an agent's child process, never a user-level home dir. */
+const AGENT_MARKERS = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'OPENCODE', 'OPENCODE_PID'] as const;
+
+/** The first agent-process marker present in env, or null. Never CODEX_HOME (a human's shell sets it). */
+export function agentProcessMarker(env: NodeJS.ProcessEnv = process.env): string | null {
+ for (const k of AGENT_MARKERS) if (env[k]) return k;
+ return null;
+}
+
+const truthy = (v: string | undefined) => v !== undefined && v !== '' && v !== '0' && v.toLowerCase() !== 'false';
+
+export function isInteractive(probe: InteractiveProbe = {}): boolean {
+ const env = probe.env ?? process.env;
+ const stdinTTY = probe.stdinIsTTY ?? process.stdin.isTTY === true;
+ const stdoutTTY = probe.stdoutIsTTY ?? process.stdout.isTTY === true;
+ if (!stdinTTY || !stdoutTTY) return false;
+ if (truthy(env.GBRAIN_INTERACTIVE)) return true;
+ if (truthy(env.GBRAIN_NON_INTERACTIVE)) return false;
+ if (truthy(env.CI)) return false;
+ return agentProcessMarker(env) === null;
+}
+
+export type LineRead = { kind: 'line'; text: string } | { kind: 'eof' } | { kind: 'timeout' };
+
+/** Prompt read: stderr prompt; EOF/timeout = decline. Returns {kind:'eof'} at once when !isInteractive(). */
+export async function readLine(opts: { prompt: string; timeoutMs?: number }): Promise<LineRead> {
+ if (!isInteractive()) return { kind: 'eof' };
+ const timeoutMs = opts.timeoutMs ?? 300_000;
+ return new Promise(resolve => {
+ process.stderr.write(opts.prompt);
+ process.stdin.setEncoding('utf-8');
+ let buf = '';
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ const done = (r: LineRead) => {
+ process.stdin.removeListener('data', onData);
+ process.stdin.removeListener('end', onEnd);
+ if (timer) clearTimeout(timer);
+ process.stdin.pause();
+ resolve(r);
+ };
+ const onData = (chunk: string | Buffer) => {
+ buf += chunk.toString();
+ const nl = buf.indexOf('\n');
+ if (nl >= 0) done({ kind: 'line', text: buf.slice(0, nl).replace(/\r$/, '').trim() });
+ };
+ const onEnd = () => done(buf ? { kind: 'line', text: buf.trim() } : { kind: 'eof' });
+ if (timeoutMs > 0) timer = setTimeout(() => done({ kind: 'timeout' }), timeoutMs);
+ process.stdin.on('data', onData);
+ process.stdin.once('end', onEnd);
+ process.stdin.resume();
+ });
+}
+
+export type StdinRead =
+ | { kind: 'data'; text: string }
+ | { kind: 'empty' }
+ | { kind: 'timeout'; phase: 'first_byte' | 'inactivity'; bytes: number }
+ | { kind: 'cancelled'; bytes: number }
+ | { kind: 'error'; error: Error; bytes: number };
+
+/** Payload read: first-byte timeout 30 s (stderr notice at 5 s), 60 s inactivity reset on progress, no total time cap. */
+export async function readStdinBounded(opts: { firstByteMs?: number; inactivityMs?: number; maxBytes?: number; signal?: AbortSignal } = {}): Promise<StdinRead> {
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk as Buffer));
+ const text = Buffer.concat(chunks).toString('utf8');
+ return text.length ? { kind: 'data', text } : { kind: 'empty' };
+}
diff --git a/src/core/ops/callable.ts b/src/core/ops/callable.ts
new file mode 100644
index 0000000000..a969f1d654
--- /dev/null
+++ b/src/core/ops/callable.ts
@@ -0,0 +1,33 @@
+/**
+ * The one callability predicate (agent operator contract v1, A2): tools/list
+ * on stdio and HTTP and dispatch all ask the same question, and fixes/notices
+ * name an MCP tool only when it answers true for the caller
+ * (`RenderContext.isCallable`). Pure: the caller resolves its own scopes,
+ * publish gates and bound-tool allow-set first.
+ */
+import type { Operation } from './contract.ts';
+import type { Surface, Transport } from '../agent-output.ts';
+import { operationScopesAllowed } from '../scope.ts';
+import { filterOpsForSurface } from '../../mcp/surface.ts';
+
+export interface CallableContext {
+ transport: Transport;
+ surface: Surface;
+ /** Verified scopes for this connection (HTTP token / stdio registration grant). Ignored on cli. */
+ scopes: readonly string[];
+ /** Resolved publish gates keyed by `Operation.publishGateKey`; a missing key is off (fail-closed). */
+ publishGates: Record<string, boolean>;
+ /** Extra fail-closed allow-set (read-only stdio, bound-client tool list). */
+ allowedOps?: ReadonlySet<string>;
+}
+
+/** The one predicate behind tools/list AND dispatch. */
+export function isCallable(op: Operation, ctx: CallableContext): boolean {
+ if (ctx.allowedOps && !ctx.allowedOps.has(op.name)) return false;
+ if (filterOpsForSurface([op], ctx.surface).length === 0) return false;
+ if (ctx.transport === 'cli') return true;
+ if (op.localOnly && ctx.transport !== 'stdio') return false;
+ if (op.publishGateKey && ctx.publishGates[op.publishGateKey] !== true) return false;
+ if (ctx.transport === 'http') return operationScopesAllowed(ctx.scopes, op);
+ return !op.requiredScopes?.length || operationScopesAllowed(ctx.scopes, op);
+}
diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.ts
index 88378f01c6..90e197df58 100644
--- a/src/core/ops/contract.ts
+++ b/src/core/ops/contract.ts
@@ -10,6 +10,8 @@ import type { BrainEngine } from '../engine.ts';
import type { GBrainConfig } from '../config.ts';
import { MEMORY_VERBS_VERSION } from '../verbs.ts';
import { publicWriteReceipt, type WriteErrorCode, type WriteReceipt } from '../persistence/types.ts';
+import { cliRenderContext, renderAction, renderNotice, CONTRACT_VERSION, type Action, type Notice } from '../agent-output.ts';
+import { canonicalCodeFor, type RegistryCode } from '../error-catalogue.ts';
// --- Types ---
@@ -60,6 +62,21 @@ export class OperationError extends Error {
public protocolVersion?: number;
public writeRequest?: WriteReceipt;
public writeError?: WriteErrorCode;
+ /** Agent contract v1 (A1): which cause, when one code covers several. */
+ public reason?: string;
+ /** Agent contract v1: why it happened, for the agent to explain and weigh. */
+ public why?: string;
+ /** Agent contract v1: the one next step. Rendered (`next`, `command`) only at serialization. */
+ public fix?: Action;
+ /** Agent contract v1: advice that rides the error (rendered into the envelope's `notices`). */
+ public notices?: Notice[];
+ /** Set to 1 by opError(); toJSON() emits `contract_version` only when set. */
+ public contractVersion?: 1;
+ /**
+ * Canonical registry code when this site keeps a frozen legacy `error`
+ * value (A1 frozen pairs, e.g. `error: invalid_params`, `code: not_found`).
+ */
+ public canonical?: RegistryCode;
constructor(
public code: ErrorCode,
@@ -71,9 +88,27 @@ export class OperationError extends Error {
this.name = 'OperationError';
}
+ /** The canonical registry code (`code` on the wire); `this.code` stays the frozen `error` value. */
+ get canonicalCode(): string {
+ return this.canonical ?? canonicalCodeFor(this.code);
+ }
+
+ /**
+ * The explicit escape from opError()'s required suggestion: a refusal whose
+ * next step genuinely cannot be named at the throw site. `reason` is
+ * required so the registry default fix can still be selected.
+ */
+ static bare(code: RegistryCode, message: string, reason: string): OperationError {
+ const e = new OperationError(code, message);
+ e.reason = reason;
+ e.contractVersion = CONTRACT_VERSION;
+ return e;
+ }
+
toJSON() {
return {
error: this.code,
+ code: this.canonicalCode,
message: this.message,
suggestion: this.suggestion,
docs: this.docs,
@@ -81,10 +116,45 @@ export class OperationError extends Error {
protocol_version: this.protocolVersion,
...(this.writeRequest ? { write_request: publicWriteReceipt(this.writeRequest) } : {}),
...(this.writeError ? { write_error: this.writeError } : {}),
+ ...(this.reason !== undefined ? { reason: this.reason } : {}),
+ ...(this.why !== undefined ? { why: this.why } : {}),
+ ...(this.fix ? { fix: renderAction(this.fix, cliRenderContext()) } : {}),
+ ...(this.notices?.length ? { notices: this.notices.map(n => renderNotice(n, cliRenderContext())) } : {}),
+ ...(this.contractVersion !== undefined ? { contract_version: this.contractVersion } : {}),
};
}
}
+export interface OpErrorOpts {
+ reason?: string;
+ why?: string;
+ fix?: Action;
+ docs?: string;
+ detail?: string;
+ /**
+ * The frozen v1 `error` wire value when this site historically threw a
+ * different code (A1 frozen pairs). `error` keeps this value; `code` is the
+ * canonical registry code passed to opError().
+ */
+ legacy_error?: string;
+}
+
+/**
+ * Agent contract v1 error constructor (mirrors verbError): `suggestion` is
+ * positional and required. Use `OperationError.bare()` only when no next step
+ * can be named at the throw site.
+ */
+export function opError(code: RegistryCode, message: string, suggestion: string, opts: OpErrorOpts = {}): OperationError {
+ const e = new OperationError(opts.legacy_error ?? code, message, suggestion, opts.docs);
+ if (opts.legacy_error !== undefined) e.canonical = code;
+ if (opts.reason !== undefined) e.reason = opts.reason;
+ if (opts.why !== undefined) e.why = opts.why;
+ if (opts.fix !== undefined) e.fix = opts.fix;
+ if (opts.detail !== undefined) e.detail = opts.detail;
+ e.contractVersion = CONTRACT_VERSION;
+ return e;
+}
+
/**
* CLI→MCP gap-closure wave (ENG-E2) — shared relation-missing guard for the
* telemetry ops (get_job_stats, cache_stats, search_stats, search_tune).
@@ -334,6 +404,13 @@ export interface OperationContext {
* which render the same meta directly; emissions are always optional-chained.
*/
emitResponseMeta?: (key: string, value: unknown) => void;
+ /**
+ * Agent contract v1 (A6): model-visible advice. MCP dispatch renders each
+ * notice as a prefixed extra text block plus `_meta.gbrain_notices` on
+ * success, and into the error envelope's `notices` key on failure. Unset
+ * on callers that have no notice channel; producers call it optionally.
+ */
+ emitNotice?: (n: Notice) => void;
/**
* WP4 (D2): the SERVER surface ceiling for this transport (force-clamped),
* threaded by the MCP dispatch layer. Consumed by `request_tools`: the
@@ -542,6 +619,13 @@ export interface Operation {
handler: (ctx: OperationContext, params: Record<string, unknown>) => Promise<unknown>;
outputRedaction: OutputRedactionPolicy;
mutating?: boolean;
+ /**
+ * Agent contract v1 (A2): repeating the call with the same arguments (and,
+ * for journaled writes, the same request identity) has the same effect as
+ * calling it once. Drives `idempotentHint` and whether an unknown-outcome
+ * failure may say `retryable: true`.
+ */
+ idempotent?: boolean;
/**
* Capability scope required to invoke this op over an authenticated
* transport. v0.28 added `sources_admin` (manage federated sources) and
diff --git a/src/core/readiness.ts b/src/core/readiness.ts
new file mode 100644
index 0000000000..2f81f78de7
--- /dev/null
+++ b/src/core/readiness.ts
@@ -0,0 +1,63 @@
+/**
+ * Capability readiness (agent operator contract v1, A7): one place that says
+ * what this install can do, why not, and the fix. Two tiers:
+ *
+ * - config plane (`configReadiness`): synchronous, memoized, in-memory config
+ * only; the one file read allowed is a memoized `peekLock()` for lock_owner.
+ * Used by MCP initialize, whoami and write receipts.
+ * - probed tier (`probedReadiness`): worker, backup, migrations; bounded,
+ * cached, never `getStats`/`getHealth`. Used by doctor and
+ * `gbrain://capabilities`.
+ */
+import type { GBrainConfig } from './config.ts';
+import type { BrainEngine } from './engine.ts';
+import type { Action, Transport } from './agent-output.ts';
+
+export type ReadinessState = 'ok' | 'disabled_by_choice' | 'not_applicable' | 'missing' | 'degraded' | 'unknown';
+export type CapabilityId =
+ | 'embeddings' | 'chat_llm' | 'worker' | 'writeback' | 'backup' | 'tool_surface'
+ | 'sync' | 'migrations' | 'harness_wiring';
+
+export interface ReadinessEntry {
+ capability: CapabilityId;
+ state: ReadinessState;
+ /** Closed vocabulary per capability. */
+ reason: string;
+ why: string;
+ fix?: Action;
+ tier: 'config' | 'probed';
+ /** backup: which asset. */
+ asset?: string;
+ /** false → stripped from the HTTP view. */
+ http_visible: boolean;
+}
+
+export interface LockOwner { pid: number; transport: 'stdio' | 'http'; started_at?: string; is_self: boolean }
+export interface ConfigReadiness { entries: ReadinessEntry[]; lock_owner: LockOwner | null }
+
+/** Probe cache for the probed tier (process-wide on stdio/CLI; one per ServeHttpContext on HTTP). */
+export interface ReadinessCache {
+ get(key: string): { at: number; value: ReadinessEntry[] } | undefined;
+ set(key: string, value: { at: number; value: ReadinessEntry[] }): void;
+}
+
+export function configReadiness(cfg: GBrainConfig, ctx: { transport: Transport }): ConfigReadiness {
+ void cfg; void ctx;
+ return { entries: [], lock_owner: null };
+}
+
+export async function probedReadiness(engine: BrainEngine, opts: { cache?: ReadinessCache } = {}): Promise<ReadinessEntry[]> {
+ void engine; void opts;
+ return [];
+}
+
+export function embeddingEnablement(cfg: GBrainConfig): Action {
+ void cfg;
+ return {
+ argv: ['gbrain', 'doctor', '--json'],
+ consent: [],
+ actor: 'agent',
+ why: 'Embeddings are not configured on this brain.',
+ requires_exclusive: false,
+ };
+}
diff --git a/test/agent-contract-a0.test.ts b/test/agent-contract-a0.test.ts
new file mode 100644
index 0000000000..1b4f212dc3
--- /dev/null
+++ b/test/agent-contract-a0.test.ts
@@ -0,0 +1,48 @@
+/**
+ * A0 frozen-interface smoke (docs/designs/AGENT_OPERATOR_WAVE.md): the
+ * primitives every lane codes against exist with their frozen shapes.
+ * Behavioural tables live in the per-primitive tests.
+ */
+import { describe, expect, test } from 'bun:test';
+import { agentProcessMarker, isInteractive } from '../src/core/interaction.ts';
+import { isCallable } from '../src/core/ops/callable.ts';
+import { configReadiness, embeddingEnablement } from '../src/core/readiness.ts';
+import { jsonRequested } from '../src/core/cli-force-exit.ts';
+import { operations } from '../src/core/operations.ts';
+import type { GBrainConfig } from '../src/core/config.ts';
+
+describe('A0 interfaces', () => {
+ test('isInteractive needs two TTYs and no agent marker; CODEX_HOME is not a marker', () => {
+ expect(isInteractive({ env: {}, stdinIsTTY: true, stdoutIsTTY: true })).toBe(true);
+ expect(isInteractive({ env: {}, stdinIsTTY: false, stdoutIsTTY: true })).toBe(false);
+ expect(isInteractive({ env: { CLAUDECODE: '1' }, stdinIsTTY: true, stdoutIsTTY: true })).toBe(false);
+ expect(isInteractive({ env: { CODEX_HOME: '/x' }, stdinIsTTY: true, stdoutIsTTY: true })).toBe(true);
+ expect(agentProcessMarker({ CODEX_HOME: '/x' })).toBeNull();
+ expect(isInteractive({ env: { CLAUDECODE: '1', GBRAIN_INTERACTIVE: '1' }, stdinIsTTY: true, stdoutIsTTY: true })).toBe(true);
+ });
+
+ test('jsonRequested stops at a bare --', () => {
+ expect(jsonRequested(['doctor', '--json'])).toBe(true);
+ expect(jsonRequested(['doctor', '--json=true'])).toBe(true);
+ expect(jsonRequested(['get', '--', '--json'])).toBe(false);
+ expect(jsonRequested(['doctor'])).toBe(false);
+ });
+
+ test('isCallable: verbs surface admits only verbs; http drops localOnly', () => {
+ const recall = operations.find(o => o.name === 'recall')!;
+ const local = operations.find(o => o.localOnly)!;
+ const base = { scopes: ['read', 'write'], publishGates: {} };
+ expect(isCallable(recall, { ...base, transport: 'stdio', surface: 'verbs' })).toBe(true);
+ expect(isCallable(local, { ...base, transport: 'http', surface: 'full' })).toBe(false);
+ expect(isCallable(local, { ...base, transport: 'stdio', surface: 'full' })).toBe(local.publishGateKey === undefined);
+ });
+
+ test('readiness entry points have their frozen shapes', () => {
+ const cfg = { engine: 'pglite' } as GBrainConfig;
+ const r = configReadiness(cfg, { transport: 'cli' });
+ expect(Array.isArray(r.entries)).toBe(true);
+ expect(r).toHaveProperty('lock_owner');
+ const fix = embeddingEnablement(cfg);
+ expect(typeof fix.requires_exclusive).toBe('boolean');
+ });
+});
diff --git a/test/agent-contract-goldens.test.ts b/test/agent-contract-goldens.test.ts
new file mode 100644
index 0000000000..ff312cf312
--- /dev/null
+++ b/test/agent-contract-goldens.test.ts
@@ -0,0 +1,193 @@
+/**
+ * Agent operator contract v1 goldens (docs/designs/AGENT_OPERATOR_WAVE.md A0).
+ *
+ * The files under test/fixtures/agent-contract/v1/ freeze the wire shapes
+ * every lane codes against and that old-client/new-server pairs run against.
+ * Fixtures never contain `next` (computed at render time, never stored): the
+ * normaliser strips it from the produced value and this file pins it
+ * separately. Docs URLs are stored as `{{DOCS_BASE}}/…`.
+ *
+ * Regenerate: GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/agent-contract-goldens.test.ts
+ */
+import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
+import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
+import { join } from 'node:path';
+import {
+ __setDocsRefForTests, docsUrl, fallbackJsonDocument, noticeBlock, renderNotice, toAgentError,
+ toolErrorResult, toolResultWithNotices, withAgentSiblings, type Notice, type RenderContext,
+} from '../src/core/agent-output.ts';
+import { opError, OperationError } from '../src/core/ops/contract.ts';
+import { confirmationPayload } from '../src/core/consent.ts';
+import { withEnv } from './helpers/with-env.ts';
+
+const DIR = join(import.meta.dir, 'fixtures', 'agent-contract', 'v1');
+const UPDATE = process.env.GBRAIN_TEST_UPDATE_GOLDENS === '1';
+
+const stdio: RenderContext = {
+ transport: 'stdio',
+ surface: 'full',
+ isCallable: (op) => op !== 'get_health',
+ preapproved: () => false,
+};
+const http: RenderContext = { ...stdio, transport: 'http', principal: 'client-example' };
+const cli: RenderContext = { transport: 'cli', isCallable: () => false, preapproved: () => false };
+
+let base = '';
+beforeAll(() => { __setDocsRefForTests('master'); base = docsUrl('').replace(/\/$/, ''); });
+afterAll(() => { __setDocsRefForTests(null); });
+
+function stripNext(v: unknown): unknown {
+ if (Array.isArray(v)) return v.map(stripNext);
+ if (v && typeof v === 'object') {
+ return Object.fromEntries(Object.entries(v as Record<string, unknown>)
+ .filter(([k]) => k !== 'next').map(([k, x]) => [k, stripNext(x)]));
+ }
+ if (typeof v === 'string') {
+ if (v.startsWith('{')) {
+ try { return JSON.stringify(stripNext(JSON.parse(v)), null, 2); } catch { /* not JSON */ }
+ }
+ return v.split(base).join('{{DOCS_BASE}}').replace(/^next: [a-z_]+$/m, 'next: {{next}}');
+ }
+ return v;
+}
+
+function normalise(v: unknown): unknown {
+ const s = stripNext(v);
+ return typeof s === 'string' ? s : JSON.parse(JSON.stringify(s));
+}
+
+function golden(name: string, actual: unknown): void {
+ const path = join(DIR, name);
+ const value = normalise(actual);
+ const text = typeof value === 'string' ? `${value}\n` : `${JSON.stringify(value, null, 2)}\n`;
+ if (UPDATE) { mkdirSync(DIR, { recursive: true }); writeFileSync(path, text); }
+ expect(text).toBe(readFileSync(path, 'utf8'));
+}
+
+const doctorFix = {
+ argv: ['gbrain', 'doctor', '--json'],
+ consent: [] as [],
+ actor: 'agent' as const,
+ why: 'Doctor reports which capability is missing and how to enable it.',
+ requires_exclusive: false,
+};
+
+const noResultsNotice: Notice = {
+ code: 'empty_retrieval',
+ kind: 'info',
+ why: 'No pages matched. Search ran keyword-only because embeddings are not configured.',
+ fix: doctorFix,
+ user_message: 'I found no notes on that topic. Your brain searches keywords only right now.',
+};
+
+const safetyNotice: Notice = {
+ code: 'backup_coverage',
+ kind: 'safety',
+ why: 'Two sources have no backup.',
+ fix: { ...doctorFix, argv: ['gbrain', 'backup', '--json'], why: 'Shows which assets are not backed up.' },
+ user_message: 'Some of your notes are not backed up. Want me to show you which ones?',
+};
+
+describe('agent contract v1 goldens', () => {
+ test('object result: content[0] is the bare body, no notices', () => {
+ golden('object-result.json', toolResultWithNotices({ slug: 'notes/alpha-example', title: 'Alpha example' }, [], stdio));
+ });
+
+ test('bare-array result: content[0] stays a bare array; notices ride extra blocks and _meta', () => {
+ const r = toolResultWithNotices([], [noResultsNotice], stdio);
+ expect(JSON.parse(r.content[0].text)).toEqual([]);
+ expect(r.content[1].text.startsWith('[gbrain notice empty_retrieval kind=info]')).toBe(true);
+ golden('bare-array-result.json', r);
+ });
+
+ test('error with fix (MCP, tool callable)', () => {
+ const e = opError('invalid_params', "Unknown sort 'bogus'.", 'Use one of: updated, created, title.', {
+ fix: {
+ argv: ['gbrain', 'list', '--sort', 'updated'],
+ mcp: { tool: 'list_pages', arguments: { sort: 'updated' } },
+ consent: [], actor: 'agent', why: 'updated is the default sort.', requires_exclusive: false,
+ verify: { mcp: { tool: 'list_pages', arguments: { sort: 'updated', limit: 1 } } },
+ },
+ });
+ const env = toAgentError(e, { transport: 'stdio', op: 'list_pages', render: stdio });
+ expect(env.fix?.next).toBe('run');
+ golden('error-with-fix.json', toolErrorResult(env));
+ });
+
+ test('error with notices: one block, notices inside the envelope', () => {
+ const e = opError('unavailable', 'Semantic search is unavailable.', 'Keyword search still works.', { reason: 'embeddings_disabled' });
+ e.notices = [safetyNotice];
+ const r = toolErrorResult(toAgentError(e, { transport: 'stdio', op: 'query', render: stdio }));
+ expect(r.content).toHaveLength(1);
+ golden('error-with-notices.json', r);
+ });
+
+ test('nested legacy error keeps nesting and gains sibling code/fix', () => {
+ const legacy = { error: { class: 'UsageError', code: 'code_def_requires_symbol', message: 'code-def requires a symbol name', hint: 'gbrain code-def <symbol> [--json]' } };
+ golden('nested-legacy-error.json', withAgentSiblings(legacy, {
+ code: 'code_def_requires_symbol',
+ fix: { argv: ['gbrain', 'code-def', '--help'], consent: [], actor: 'agent', why: 'Shows the required symbol argument.', requires_exclusive: false },
+ }, cli));
+ });
+
+ test('receipt-bearing error keeps write_request and points at the receipt, not a retry', () => {
+ const e = opError('write_pending', 'The write was accepted and is still pending.', 'Inspect the receipt before resubmitting.', {
+ fix: {
+ mcp: { tool: 'get_write_request', arguments: { request_id: '11111111-2222-4333-8444-555555555555' } },
+ consent: [], actor: 'agent', why: 'The receipt says whether the write committed.', requires_exclusive: false,
+ },
+ });
+ e.writeRequest = { request_id: '11111111-2222-4333-8444-555555555555', state: 'queued', retry_after_ms: 2000 } as OperationError['writeRequest'];
+ e.writeError = 'write_pending';
+ golden('receipt-error.json', toolErrorResult(toAgentError(e, { transport: 'stdio', op: 'put_page', mutating: true, outcome: 'pending', render: stdio })));
+ });
+
+ test('legacy frozen error value with the new canonical code', () => {
+ const e = opError('unknown_tool', 'Unknown: list_pagez', 'Call request_tools to see the tools this connection can call.', { legacy_error: 'unknown_operation' });
+ const env = toAgentError(e, { transport: 'http', render: http });
+ expect(env.error).toBe('unknown_operation');
+ expect(env.code).toBe('unknown_tool');
+ golden('legacy-error-value.json', toolErrorResult(env));
+ });
+
+ test('confirmation_required payload', () => {
+ golden('confirmation-required.json', confirmationPayload({
+ command: 'doctor',
+ effects: ['paid'],
+ actor: 'agent',
+ what: 'doctor --remediate',
+ why: 'Remediation re-embeds 120 stale pages through the configured provider.',
+ risk: 'Spends up to the cap on embedding calls; no data is deleted.',
+ user_message: 'Fixing your brain\'s health will cost about $0.40 in embedding calls. OK to proceed?',
+ argv: ['gbrain', 'doctor', '--remediate', '--max-usd', '0.60'],
+ preview_argv: ['gbrain', 'doctor', '--remediation-plan', '--json'],
+ est_usd: 0.4,
+ args: ['--remediate'],
+ }, cli));
+ });
+
+ test('notice block text', () => {
+ golden('notice-block.txt', noticeBlock(renderNotice(noResultsNotice, stdio)));
+ });
+
+ test('--json exit-time fallback document', () => {
+ golden('json-fallback.json', fallbackJsonDocument(1));
+ });
+});
+
+describe('deriveNext pins for the goldens (next is never stored)', () => {
+ test('notice fix runs on stdio, error fix runs, consent asks', () => {
+ expect(renderNotice(noResultsNotice, stdio).fix?.next).toBe('tell_user_to_run');
+ const p = confirmationPayload({
+ command: 'x', effects: ['paid'], actor: 'agent', what: 'x', why: 'w', risk: 'r', user_message: 'u',
+ argv: ['gbrain', 'x'], args: [],
+ }, cli);
+ expect(p.fix.next).toBe('ask_user');
+ });
+
+ test('LLMS_REPO_BASE fork override', async () => {
+ await withEnv({ LLMS_REPO_BASE: 'https://raw.githubusercontent.com/fork-org/gbrain/main/' }, () => {
+ expect(docsUrl('docs/guides/error-codes.md#x')).toBe('https://raw.githubusercontent.com/fork-org/gbrain/main/docs/guides/error-codes.md#x');
+ });
+ });
+});
diff --git a/test/fixtures/agent-contract/v1/README.md b/test/fixtures/agent-contract/v1/README.md
new file mode 100644
index 0000000000..993c4213d6
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/README.md
@@ -0,0 +1,12 @@
+# Agent operator contract v1 goldens
+
+Frozen wire shapes for `docs/protocol/AGENT_OPERATOR_v1.md` (spec:
+`docs/designs/AGENT_OPERATOR_WAVE.md`, A0). Produced and checked by
+`test/agent-contract-goldens.test.ts`; regenerate with
+`GBRAIN_TEST_UPDATE_GOLDENS=1`.
+
+- Fixtures never contain `next`: it is computed at render time from the
+ effects, actor, transport, callability and preapprovals. Conformance tests
+ recompute it.
+- Docs URLs are stored as `{{DOCS_BASE}}/…` (the version-pinned base).
+- `notice-block.txt` stores `next: {{next}}` for the same reason.
diff --git a/test/fixtures/agent-contract/v1/bare-array-result.json b/test/fixtures/agent-contract/v1/bare-array-result.json
new file mode 100644
index 0000000000..7f931e3006
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/bare-array-result.json
@@ -0,0 +1,35 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "[]"
+ },
+ {
+ "type": "text",
+ "text": "[gbrain notice empty_retrieval kind=info]\nwhy: No pages matched. Search ran keyword-only because embeddings are not configured.\nfix: gbrain doctor --json\nnext: {{next}}\nuser_message: I found no notes on that topic. Your brain searches keywords only right now."
+ }
+ ],
+ "_meta": {
+ "gbrain_notices": [
+ {
+ "code": "empty_retrieval",
+ "kind": "info",
+ "why": "No pages matched. Search ran keyword-only because embeddings are not configured.",
+ "fix": {
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--json"
+ ],
+ "command": "gbrain doctor --json",
+ "consent": [],
+ "actor": "user",
+ "why": "Doctor reports which capability is missing and how to enable it.",
+ "requires_exclusive": false
+ },
+ "user_message": "I found no notes on that topic. Your brain searches keywords only right now.",
+ "contract_version": 1
+ }
+ ]
+ }
+}
diff --git a/test/fixtures/agent-contract/v1/confirmation-required.json b/test/fixtures/agent-contract/v1/confirmation-required.json
new file mode 100644
index 0000000000..34e0f511cb
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/confirmation-required.json
@@ -0,0 +1,61 @@
+{
+ "status": "confirmation_required",
+ "error": "confirmation_required",
+ "code": "confirmation_required",
+ "message": "doctor --remediate needs the user's approval before it runs; nothing was changed.",
+ "suggestion": "Ask the user: Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed? If they agree, run: gbrain doctor --remediate --max-usd 0.60 --yes",
+ "effects": [
+ "paid"
+ ],
+ "actor": "agent",
+ "why": "Remediation re-embeds 120 stale pages through the configured provider.",
+ "risk": "Spends up to the cap on embedding calls; no data is deleted.",
+ "est_usd": 0.4,
+ "user_message": "Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed?",
+ "fix": {
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--remediate",
+ "--max-usd",
+ "0.60",
+ "--yes"
+ ],
+ "command": "gbrain doctor --remediate --max-usd 0.60 --yes",
+ "consent": [
+ "paid"
+ ],
+ "actor": "agent",
+ "why": "Remediation re-embeds 120 stale pages through the configured provider.",
+ "user_message": "Fixing your brain's health will cost about $0.40 in embedding calls. OK to proceed?",
+ "requires_exclusive": false,
+ "preview_argv": [
+ "gbrain",
+ "doctor",
+ "--remediation-plan",
+ "--json"
+ ]
+ },
+ "preview": {
+ "argv": [
+ "gbrain",
+ "doctor",
+ "--remediation-plan",
+ "--json"
+ ],
+ "command": "gbrain doctor --remediation-plan --json"
+ },
+ "preapprove_argv": [
+ "gbrain",
+ "config",
+ "set",
+ "consent.preapprove.paid.max_usd_per_run",
+ "<usd>"
+ ],
+ "docs_cmd": [
+ "gbrain",
+ "errors",
+ "confirmation_required"
+ ],
+ "contract_version": 1
+}
diff --git a/test/fixtures/agent-contract/v1/error-with-fix.json b/test/fixtures/agent-contract/v1/error-with-fix.json
new file mode 100644
index 0000000000..b1bf8435e7
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/error-with-fix.json
@@ -0,0 +1,9 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "{\n \"error\": \"invalid_params\",\n \"code\": \"invalid_params\",\n \"message\": \"Unknown sort 'bogus'.\",\n \"suggestion\": \"Use one of: updated, created, title. Next: list_pages {\\\"sort\\\":\\\"updated\\\"}\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#invalid_params\",\n \"fix\": {\n \"argv\": [\n \"gbrain\",\n \"list\",\n \"--sort\",\n \"updated\"\n ],\n \"command\": \"gbrain list --sort updated\",\n \"mcp\": {\n \"tool\": \"list_pages\",\n \"arguments\": {\n \"sort\": \"updated\"\n }\n },\n \"consent\": [],\n \"actor\": \"agent\",\n \"why\": \"updated is the default sort.\",\n \"verify\": {\n \"mcp\": {\n \"tool\": \"list_pages\",\n \"arguments\": {\n \"sort\": \"updated\",\n \"limit\": 1\n }\n }\n },\n \"requires_exclusive\": false\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"invalid_params\"\n ],\n \"class\": \"caller\",\n \"retryable\": false,\n \"contract_version\": 1\n}"
+ }
+ ],
+ "isError": true
+}
diff --git a/test/fixtures/agent-contract/v1/error-with-notices.json b/test/fixtures/agent-contract/v1/error-with-notices.json
new file mode 100644
index 0000000000..66cbe6f196
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/error-with-notices.json
@@ -0,0 +1,9 @@
+{
+ "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}"
+ }
+ ],
+ "isError": true
+}
diff --git a/test/fixtures/agent-contract/v1/json-fallback.json b/test/fixtures/agent-contract/v1/json-fallback.json
new file mode 100644
index 0000000000..3e15a21561
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/json-fallback.json
@@ -0,0 +1,8 @@
+{
+ "error": "command_failed",
+ "code": "command_failed",
+ "message": "The command exited with status 1 without writing its JSON result.",
+ "suggestion": "Re-run without --json to read the error on stderr, or run `gbrain doctor --json`.",
+ "exit_code": 1,
+ "contract_version": 1
+}
diff --git a/test/fixtures/agent-contract/v1/legacy-error-value.json b/test/fixtures/agent-contract/v1/legacy-error-value.json
new file mode 100644
index 0000000000..96334f7304
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/legacy-error-value.json
@@ -0,0 +1,9 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "{\n \"error\": \"unknown_operation\",\n \"code\": \"unknown_tool\",\n \"message\": \"Unknown: list_pagez\",\n \"suggestion\": \"Call request_tools to see the tools this connection can call.\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#unknown_tool\",\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"unknown_tool\"\n ],\n \"class\": \"caller\",\n \"retryable\": false,\n \"contract_version\": 1\n}"
+ }
+ ],
+ "isError": true
+}
diff --git a/test/fixtures/agent-contract/v1/nested-legacy-error.json b/test/fixtures/agent-contract/v1/nested-legacy-error.json
new file mode 100644
index 0000000000..00cd2cd7c8
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/nested-legacy-error.json
@@ -0,0 +1,27 @@
+{
+ "error": {
+ "class": "UsageError",
+ "code": "code_def_requires_symbol",
+ "message": "code-def requires a symbol name",
+ "hint": "gbrain code-def <symbol> [--json]"
+ },
+ "code": "code_def_requires_symbol",
+ "fix": {
+ "argv": [
+ "gbrain",
+ "code-def",
+ "--help"
+ ],
+ "command": "gbrain code-def --help",
+ "consent": [],
+ "actor": "agent",
+ "why": "Shows the required symbol argument.",
+ "requires_exclusive": false
+ },
+ "docs_cmd": [
+ "gbrain",
+ "errors",
+ "code_def_requires_symbol"
+ ],
+ "contract_version": 1
+}
diff --git a/test/fixtures/agent-contract/v1/notice-block.txt b/test/fixtures/agent-contract/v1/notice-block.txt
new file mode 100644
index 0000000000..705927dc6f
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/notice-block.txt
@@ -0,0 +1,5 @@
+[gbrain notice empty_retrieval kind=info]
+why: No pages matched. Search ran keyword-only because embeddings are not configured.
+fix: gbrain doctor --json
+next: {{next}}
+user_message: I found no notes on that topic. Your brain searches keywords only right now.
diff --git a/test/fixtures/agent-contract/v1/object-result.json b/test/fixtures/agent-contract/v1/object-result.json
new file mode 100644
index 0000000000..3445510d5c
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/object-result.json
@@ -0,0 +1,8 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "{\n \"slug\": \"notes/alpha-example\",\n \"title\": \"Alpha example\"\n}"
+ }
+ ]
+}
diff --git a/test/fixtures/agent-contract/v1/receipt-error.json b/test/fixtures/agent-contract/v1/receipt-error.json
new file mode 100644
index 0000000000..f63578a062
--- /dev/null
+++ b/test/fixtures/agent-contract/v1/receipt-error.json
@@ -0,0 +1,9 @@
+{
+ "content": [
+ {
+ "type": "text",
+ "text": "{\n \"error\": \"write_pending\",\n \"code\": \"write_pending\",\n \"message\": \"The write was accepted and is still pending.\",\n \"suggestion\": \"Inspect the receipt before resubmitting. Next: get_write_request {\\\"request_id\\\":\\\"11111111-2222-4333-8444-555555555555\\\"}\",\n \"docs\": \"{{DOCS_BASE}}/docs/guides/error-codes.md#write_pending\",\n \"write_request\": {\n \"request_id\": \"11111111-2222-4333-8444-555555555555\",\n \"state\": \"queued\",\n \"retry_after_ms\": 2000\n },\n \"write_error\": \"write_pending\",\n \"fix\": {\n \"mcp\": {\n \"tool\": \"get_write_request\",\n \"arguments\": {\n \"request_id\": \"11111111-2222-4333-8444-555555555555\"\n }\n },\n \"consent\": [],\n \"actor\": \"agent\",\n \"why\": \"The receipt says whether the write committed.\",\n \"requires_exclusive\": false\n },\n \"docs_cmd\": [\n \"gbrain\",\n \"errors\",\n \"write_pending\"\n ],\n \"class\": \"retryable\",\n \"retryable\": false,\n \"contract_version\": 1\n}"
+ }
+ ],
+ "isError": true
+}
diff --git a/test/persistence-write-contracts.test.ts b/test/persistence-write-contracts.test.ts
index 33c8236e95..4c1d743712 100644
--- a/test/persistence-write-contracts.test.ts
+++ b/test/persistence-write-contracts.test.ts
@@ -100,7 +100,7 @@ describe('public write receipts', () => {
test('non-write errors retain the existing wire shape', () => {
expect(JSON.parse(JSON.stringify(new OperationError('invalid_params', 'Bad input.'))))
- .toEqual({ error: 'invalid_params', message: 'Bad input.' });
+ .toEqual({ error: 'invalid_params', code: 'invalid_params', message: 'Bad input.' });
});
test('receipt parsing refuses invented completion states and unsafe polling intervals', () => {
diff --git a/test/timeline-date-errors.test.ts b/test/timeline-date-errors.test.ts
index 50ca81ff27..cec57fc000 100644
--- a/test/timeline-date-errors.test.ts
+++ b/test/timeline-date-errors.test.ts
@@ -141,7 +141,9 @@ describe('add_timeline_entry rejects invalid dates as invalid_params', () => {
}, OPTS);
expect(result.isError).toBe(true);
- expect(payload(result)).toEqual({ error: 'invalid_params', message });
+ // Agent contract v1: legacy keys keep their values; `code` (and the other
+ // v1 envelope keys) are additive.
+ expect(payload(result)).toMatchObject({ error: 'invalid_params', code: 'invalid_params', message });
expect(await pageState(REJECTED_SLUG)).toEqual(rejectedBaseline);
});
});