Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(agent-contract): legacy nested error shapes gain sibling code/fix (code-def/refs/callers/callees, brainstorm, cycle phase containment); tag A4/A5 source reads
garrytan258eea26a18d
diff --git a/src/commands/brainstorm.ts b/src/commands/brainstorm.tsindex a0dc79ad00..54c4ef69f9 100644--- a/src/commands/brainstorm.ts+++ b/src/commands/brainstorm.ts@@ -28,6 +28,7 @@ import { serializeMarkdown } from '../core/markdown.ts';import { importFromContent } from '../core/import-file.ts';import { writePageThrough, type WriteThroughResult } from '../core/write-through.ts';import { randomBytes } from 'crypto';+import { legacyNestedErrorDocument } from '../core/agent-output.ts';export interface BrainstormCliArgs {question?: string;@@ -293,7 +294,7 @@ async function runBrainstormCli(if (parsed.json) {// Agents reading --json get the structured envelope (matches// serializeError shape from src/core/errors.ts).- console.log(JSON.stringify({ error: err.envelope }, null, 2));+ console.log(JSON.stringify(legacyNestedErrorDocument(err.envelope), null, 2));} else {console.error(`Error [${err.envelope.code}]: ${err.envelope.message}`);if (err.envelope.hint) console.error(` Hint: ${err.envelope.hint}`);diff --git a/src/commands/code-callees.ts b/src/commands/code-callees.tsindex 48ffbfbce3..99ed17f4b0 100644--- a/src/commands/code-callees.ts+++ b/src/commands/code-callees.ts@@ -18,6 +18,7 @@ import type { BrainEngine } from '../core/engine.ts';import { errorFor, serializeError } from '../core/errors.ts';import { resolveCliCodeScope, positionalArgs, parseFlag } from './code-scope.ts';import { resolveCodeReadiness, readinessHint } from '../core/code-graph-readiness.ts';+import { legacyNestedErrorDocument } from '../core/agent-output.ts';function shouldEmitJson(args: string[]): boolean {if (args.includes('--json')) return true;@@ -36,7 +37,7 @@ export async function runCodeCallees(engine: BrainEngine, args: string[]): Promihint: 'gbrain code-callees <symbol> [--source S | --all-sources] [--limit N] [--json]',});if (shouldEmitJson(args)) {- console.log(JSON.stringify({ error: err.envelope }));+ console.log(JSON.stringify(legacyNestedErrorDocument(err.envelope, ['gbrain', 'code-callees', '--help'])));} else {console.error(err.message);}diff --git a/src/commands/code-callers.ts b/src/commands/code-callers.tsindex 5e8dd727bd..7f8a0072b7 100644--- a/src/commands/code-callers.ts+++ b/src/commands/code-callers.ts@@ -30,6 +30,7 @@ import type { BrainEngine } from '../core/engine.ts';import { errorFor, serializeError } from '../core/errors.ts';import { resolveCliCodeScope, positionalArgs, parseFlag } from './code-scope.ts';import { resolveCodeReadiness, readinessHint } from '../core/code-graph-readiness.ts';+import { legacyNestedErrorDocument } from '../core/agent-output.ts';function shouldEmitJson(args: string[]): boolean {if (args.includes('--json')) return true;@@ -48,7 +49,7 @@ export async function runCodeCallers(engine: BrainEngine, args: string[]): Promihint: 'gbrain code-callers <symbol> [--source S | --all-sources] [--limit N] [--json]',});if (shouldEmitJson(args)) {- console.log(JSON.stringify({ error: err.envelope }));+ console.log(JSON.stringify(legacyNestedErrorDocument(err.envelope, ['gbrain', 'code-callers', '--help'])));} else {console.error(err.message);}diff --git a/src/commands/code-def.ts b/src/commands/code-def.tsindex ec2900dad0..e4e6cebe2b 100644--- a/src/commands/code-def.ts+++ b/src/commands/code-def.ts@@ -40,6 +40,7 @@ export interface CodeDefResult {// small-sibling merging). Re-exported here so existing importers keep their// surface.import { DEF_TYPES } from '../core/chunkers/def-types.ts';+import { legacyNestedErrorDocument } from '../core/agent-output.ts';export { DEF_TYPES };@@ -156,7 +157,7 @@ export async function runCodeDef(engine: BrainEngine, args: string[]): Promise<vhint: 'gbrain code-def <symbol> [--source S | --all-sources] [--lang <language>] [--json]',});if (shouldEmitJson(args)) {- console.log(JSON.stringify({ error: err.envelope }));+ console.log(JSON.stringify(legacyNestedErrorDocument(err.envelope, ['gbrain', 'code-def', '--help'])));} else {console.error(err.message);}diff --git a/src/commands/code-refs.ts b/src/commands/code-refs.tsindex 79ba632511..561dacdfd9 100644--- a/src/commands/code-refs.ts+++ b/src/commands/code-refs.ts@@ -23,6 +23,7 @@ import { errorFor, serializeError } from '../core/errors.ts';import { resolveCodeReadiness, readinessHint } from '../core/code-graph-readiness.ts';import { resolveCliCodeScope, positionalArgs, parseFlag } from './code-scope.ts';import { codeReadFilter, type CodeReadScope } from '../core/code-intel/read-scope.ts';+import { legacyNestedErrorDocument } from '../core/agent-output.ts';export interface CodeRefResult {slug: string;@@ -99,7 +100,7 @@ export async function runCodeRefs(engine: BrainEngine, args: string[]): Promise<hint: 'gbrain code-refs <symbol> [--source S | --all-sources] [--lang <language>] [--json]',});if (shouldEmitJson(args)) {- console.log(JSON.stringify({ error: err.envelope }));+ console.log(JSON.stringify(legacyNestedErrorDocument(err.envelope, ['gbrain', 'code-refs', '--help'])));} else {console.error(err.message);}diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex 1e7b863072..18db0c5711 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -673,6 +673,17 @@ export function withAgentSiblings<T extends Record<string, unknown>>(};}+/**+ * `{ error: StructuredError }` (code-def/code-refs/brainstorm `--json`) with+ * the v1 siblings: canonical `code`, an optional diagnostic `fix`, docs_cmd.+ */+export function legacyNestedErrorDocument(envelope: { code: string }, fixArgv?: string[]): Record<string, unknown> {+ return withAgentSiblings({ error: envelope }, {+ code: canonicalCodeFor(envelope.code),+ ...(fixArgv ? { fix: { argv: fixArgv, consent: [], actor: 'agent' as const, why: 'Shows the arguments this command needs.', requires_exclusive: false } } : {}),+ }, cliRenderContext());+}+/** 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 {diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 1acd691d63..1d38c0d586 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -367,6 +367,10 @@ export interface PhaseResult {summary: string;details: Record<string, unknown>;error?: PhaseError;+ /** Agent contract v1: canonical registry code for `error` (sibling, additive). */+ code?: string;+ /** Agent contract v1: the next step for `error`, rendered (sibling, additive). */+ fix?: import('./agent-output.ts').RenderedAction;}export type CycleStatus = 'ok' | 'clean' | 'partial' | 'skipped' | 'failed';diff --git a/src/core/cycle/phase-containment.ts b/src/core/cycle/phase-containment.tsindex 285639c234..4ddbb23069 100644--- a/src/core/cycle/phase-containment.ts+++ b/src/core/cycle/phase-containment.ts@@ -14,6 +14,7 @@ import { LockStolenError } from '../db-lock.ts';import { BudgetExhausted } from '../budget/budget-tracker.ts';import { withChatCallMeter } from '../ai/chat-usage.ts';import { recordContainedPaidFailure } from './dream-breaker.ts';+import { cliRenderContext, toAgentError, type RenderedAction } from '../agent-output.ts';/** Errors that must stop the whole job instead of failing one phase. */export function isUncontainedPhaseError(error: unknown, signal?: AbortSignal): boolean {@@ -61,8 +62,15 @@ export async function timeContainedPhase<T extends PhaseResult>(containment: Phasummary: `${phase} failed: ${err.message.slice(0, 200)}`,details: { contained: true, paid_model_calls: meter.calls, paid_loop_recorded: paidLoopRecorded },error: { class: err.name || 'Error', code, message: err.message.slice(0, 200) },+ ...phaseErrorSiblings(err, phase),},duration_ms: Math.round(performance.now() - start),};}}++/** Agent contract v1: the nested legacy `error` keeps its shape and gains sibling `code` / `fix`. */+function phaseErrorSiblings(err: Error, phase: string): { code: string; fix?: RenderedAction } {+ const env = toAgentError(err, { transport: 'cli', command: `dream:${phase}`, render: cliRenderContext() });+ return { code: env.code, ...(env.fix ? { fix: env.fix } : {}) };+}diff --git a/test/consent.test.ts b/test/consent.test.tsindex 59dc235061..0d5bbe3230 100644--- a/test/consent.test.ts+++ b/test/consent.test.ts@@ -192,6 +192,7 @@ describe('--non-interactive maps explicitly to effects', () => {});test("the post-upgrade apply-migrations call authorizes exactly apply-migrations' install", async () => {+ // test-reads-source-ok[structural]: the internal upgrade caller's literal argv is the input under test (pinned by upgrade-no-autopilot too).const src = readFileSync(join(import.meta.dir, '..', 'src', 'commands', 'upgrade.ts'), 'utf8');const m = src.match(/runApplyMigrations\(\[([^\]]*?)(?:,\s*\.\.\.|\])/);expect(m).not.toBeNull();diff --git a/test/cycle/regression-pr-wave-r1-r2-r4.test.ts b/test/cycle/regression-pr-wave-r1-r2-r4.test.tsindex 12f2225f72..9b50938565 100644--- a/test/cycle/regression-pr-wave-r1-r2-r4.test.ts+++ b/test/cycle/regression-pr-wave-r1-r2-r4.test.ts@@ -118,6 +118,7 @@ describe('R4 — cross-platform stdin via fd 0 (PR #1325 regression pin)', () =>// reader moved from src/cli.ts to src/core/interaction.ts (agent operator// wave A5); cli.ts keeps a legacy-signature shim, so both are checked.const root = join(import.meta.dir ?? '.', '..', '..', 'src');+ // test-reads-source-ok[structural]: the R4 regression pins the absence of the /dev/stdin read in the CLI shim (moved there by A5).const src = readFileSync(join(root, 'core', 'interaction.ts'), 'utf-8');expect(readFileSync(join(root, 'cli.ts'), 'utf-8')).not.toMatch(/readFileSync\(\s*['"]\/dev\/stdin['"]/);diff --git a/test/test-reads-source-smell.test.ts b/test/test-reads-source-smell.test.tsindex 66edfa126c..1223f6ad68 100644--- a/test/test-reads-source-smell.test.ts+++ b/test/test-reads-source-smell.test.ts@@ -77,7 +77,7 @@ const GRANDFATHERED: Record<string, number> = {'cycle-patterns-deadline-budget.test.ts': 4,'cycle-phase-deadline-drift.test.ts': 2,'cycle/nightly-probe-adapters.test.ts': 5,- 'cycle/regression-pr-wave-r1-r2-r4.test.ts': 2,+ 'cycle/regression-pr-wave-r1-r2-r4.test.ts': 1,'cycle/yield-during-phase-throttle.test.ts': 1,'destructive-guard.test.ts': 1,'doctor-categories.test.ts': 1,