Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(init): D2 --json writes one document carrying the first-run decision bundle
garrytan78f12647f429
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.jsonindex 25f096eb97..fe1c911ede 100644--- a/scripts/serial-weights.json+++ b/scripts/serial-weights.json@@ -45,7 +45,7 @@"test/checkpoint-harvest.serial.test.ts": 9,"test/cli-error-render.serial.test.ts": 3,"test/cli-help-without-brain.serial.test.ts": 16,- "test/cli-json-guard.serial.test.ts": 4,+ "test/cli-json-guard.serial.test.ts": 6,"test/cli-util-prompt.serial.test.ts": 3,"test/code-callers-pin.serial.test.ts": 11,"test/code-def-refs-pin.serial.test.ts": 12,diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.jsonindex 5f4568c34e..665fa41338 100644--- a/scripts/ubicloud/weights.json+++ b/scripts/ubicloud/weights.json@@ -320,7 +320,7 @@"serial:test/checkpoint-harvest.serial.test.ts": 4977,"serial:test/cli-error-render.serial.test.ts": 3000,"serial:test/cli-help-without-brain.serial.test.ts": 9329,- "serial:test/cli-json-guard.serial.test.ts": 4000,+ "serial:test/cli-json-guard.serial.test.ts": 6000,"serial:test/cli-util-prompt.serial.test.ts": 2644,"serial:test/code-callers-pin.serial.test.ts": 2975,"serial:test/code-def-refs-pin.serial.test.ts": 5089,diff --git a/src/cli/cli-error.ts b/src/cli/cli-error.tsindex b9d2d39a4c..905f20a8bb 100644--- a/src/cli/cli-error.ts+++ b/src/cli/cli-error.ts@@ -25,6 +25,8 @@ import { findCliCommand } from './command-table.ts';export interface CliErrorWriteOpts {/** Raw argv (defaults to process.argv.slice(2)); decides `--json`. */argv?: readonly string[];+ /** Overrides the argv `--json` probe (in-process callers that parsed their own flags). */+ json?: boolean;/*** A pre-v1 JSON shape this site printed: its keys lead and keep their* values, the envelope adds the rest, and the document stays one line@@ -40,7 +42,7 @@ export function cliCommandOf(argv: readonly string[] = process.argv.slice(2)): s/** Render and write `e`; returns the exit code (the caller exits or sets the verdict). */export function writeCliError(e: unknown, command: string, opts: CliErrorWriteOpts = {}): number {- const json = jsonRequested(opts.argv ?? process.argv.slice(2));+ const json = opts.json ?? jsonRequested(opts.argv ?? process.argv.slice(2));const r = renderCliError(e, { json, command, tty: process.stderr.isTTY === true });let stderr = r.stderr;if (r.stdout !== undefined) {diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 111bf8b309..164d0a5e85 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -128,7 +128,7 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// one-line short-circuit (matches `connect`). Without this, `init` is in CLI_ONLY but not// CLI_ONLY_SELF_HELP, so the dispatcher's generic short-circuit fires and the printInitHelp()// guard in init.ts is dead code.- { name: 'init', phase: 'pre-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/init.ts') },+ { name: 'init', phase: 'pre-connect', thinClient: 'none', selfHelp: true, json: 'document', load: () => import('./commands/init.ts') },{ name: 'bench', phase: 'pre-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/bench.ts') },// selfHelp: v0.37 fix wave (deferred TODO, shipped): reinit-pglite has its own --help in// runReinitPglite. Routing through SELF_HELP avoids the generic short-circuit so thediff --git a/src/commands/init-first-run.ts b/src/commands/init-first-run.tsnew file mode 100644index 0000000000..b438e47406--- /dev/null+++ b/src/commands/init-first-run.ts@@ -0,0 +1,74 @@+/**+ * `gbrain init --json`'s first-run decision bundle (agent contract v1 D2,+ * spec G5): ONE `kind: 'ask'` notice whose `decisions[]` carry what the human+ * output relays through `[AGENT]` lines, plus one `user_message`. Init stays+ * non-blocking (exit 0); the agent relays the message and applies the chosen+ * options' argv.+ *+ * Ownership: Lane G5 owns the bundle's content (adding `writeback` and+ * `skills_scaffold`, the `user_message` wording, the harness smoke follow-up);+ * Lane D ships this seam and the decisions it can build today:+ * `search_mode` (the picker's recommendation and cost matrix) and+ * `harness_wiring` (the A7 readiness fix). Extend `buildInitFirstRunNotices`+ * rather than adding a second notice.+ */+import type { Decision, Notice } from '../core/agent-output.ts';+import type { GBrainConfig } from '../core/config.ts';+import { configReadiness } from '../core/readiness.ts';+import type { SearchMode } from '../core/search/mode.ts';++export interface InitFirstRunInputs {+ /** The search mode init applied and why (from the install-time picker). */+ searchMode?: { mode: SearchMode; reason: string };+ /** The config init saved; harness wiring is read from its config-plane readiness. */+ config?: GBrainConfig | null;+}++const SEARCH_MODE_COST =+ 'Per-query search payload cost at 10K queries/month (Haiku 4.5 / Sonnet 4.6 / Opus 4.7): ' ++ 'conservative $40 / $120 / $200, balanced $100 / $300 / $500, tokenmax $200 / $600 / $1,000 per month.';++function searchModeDecision(applied: { mode: SearchMode; reason: string }): Decision {+ const modes: SearchMode[] = ['conservative', 'balanced', 'tokenmax'];+ return {+ id: 'search_mode',+ question: `Which search mode should this brain use? ${SEARCH_MODE_COST}`,+ options: modes.map(m => ({ id: m, label: m === applied.mode ? `${m} (applied)` : m, argv: ['gbrain', 'config', 'set', 'search.mode', m] })),+ default: applied.mode,+ default_reason: applied.reason,+ };+}++function harnessWiringDecision(config: GBrainConfig): Decision | null {+ const entry = configReadiness(config, { transport: 'cli' }).entries.find(e => e.capability === 'harness_wiring');+ if (!entry?.fix || entry.state === 'ok') return null;+ return {+ id: 'harness_wiring',+ question: entry.fix.user_message ?? entry.why,+ options: [+ { id: 'wire', label: entry.fix.why, ...(entry.fix.argv ? { argv: entry.fix.argv } : {}) },+ { id: 'skip', label: 'Do not register gbrain with an agent harness now.' },+ ],+ default: entry.fix.argv ? 'wire' : 'skip',+ default_reason: entry.why,+ };+}++/** The bundle: empty when there is nothing to decide. */+export function buildInitFirstRunNotices(inputs: InitFirstRunInputs): Notice[] {+ const decisions: Decision[] = [];+ if (inputs.searchMode) decisions.push(searchModeDecision(inputs.searchMode));+ if (inputs.config) {+ const wiring = harnessWiringDecision(inputs.config);+ if (wiring) decisions.push(wiring);+ }+ if (decisions.length === 0) return [];+ const defaults = decisions.map(d => `${d.id}: ${d.default}`).join('; ');+ return [{+ code: 'first_run_decisions',+ kind: 'ask',+ why: 'The brain is ready. These settings were applied with defaults or need the user\'s choice; none blocks using the brain.',+ user_message: `gbrain is installed. Reply 'defaults' to keep the recommended settings (${defaults}), or tell me what to change.`,+ decisions,+ }];+}diff --git a/src/commands/init-json.ts b/src/commands/init-json.tsnew file mode 100644index 0000000000..a9c6b78d53--- /dev/null+++ b/src/commands/init-json.ts@@ -0,0 +1,60 @@+/**+ * `gbrain init --json` result writer (agent contract v1 D2). init has several+ * branches (PGLite, Postgres, thin client, migrate-only, the+ * `--prefer-postgres` ladder) and the ladder wraps an inner init, so the+ * success document is accumulated here and written ONCE through+ * writeStdoutFinal when runInit returns. Error documents keep their legacy+ * one-line keys (`status`, `reason`, …) and gain the v1 envelope through+ * writeCliError. Under the `--json` guard every other stdout write goes to+ * stderr.+ */+import { writeStdoutFinal } from '../core/cli-force-exit.ts';+import { opError } from '../core/ops/contract.ts';+import type { RegistryCode } from '../core/error-registry.ts';+import { writeCliError } from '../cli/cli-error.ts';++let pending: Record<string, unknown> | null = null;++/**+ * Record (merge into) the success document. `replace` starts it over (the+ * ladder's envelope) keeping only the first-run `notices` / `contract_version`.+ */+export function setInitJsonResult(doc: Record<string, unknown>, opts: { replace?: boolean } = {}): void {+ if (!opts.replace) { pending = { ...(pending ?? {}), ...doc }; return; }+ const keep = Object.fromEntries(Object.entries(pending ?? {}).filter(([k]) => k === 'notices' || k === 'contract_version'));+ pending = { ...doc, ...keep };+ deferred = null;+}++/** Write the accumulated success document (one line, as before) and clear it. */+export async function flushInitJsonResult(): Promise<void> {+ if (!pending) return;+ const doc = pending;+ pending = null;+ await writeStdoutFinal(`${JSON.stringify(doc)}\n`);+}++/** An init failure under --json: legacy keys + the v1 envelope on stdout, human lines on stderr. Returns the exit code. */+export function initJsonError(legacy: Record<string, unknown>, code: RegistryCode, message: string, suggestion: string): number {+ pending = null;+ return writeCliError(opError(code, message, suggestion), 'init', { legacy, json: true });+}++let deferred: { legacy: Record<string, unknown>; code: RegistryCode; message: string; suggestion: string } | null = null;++/**+ * A Postgres-core failure: the `--prefer-postgres` ladder treats it as a rung+ * failure and moves on, so it is held until the direct `--url`/`--supabase`+ * wrapper writes it (writeDeferredInitJsonError) or the ladder replaces it.+ */+export function deferInitJsonError(legacy: Record<string, unknown>, code: RegistryCode, message: string, suggestion: string): void {+ deferred = { legacy, code, message, suggestion };+}++/** Write the held failure; returns its exit code, or null when none is held. */+export function writeDeferredInitJsonError(): number | null {+ if (!deferred) return null;+ const d = deferred;+ deferred = null;+ return initJsonError(d.legacy, d.code, d.message, d.suggestion);+}diff --git a/src/commands/init-mode-picker.ts b/src/commands/init-mode-picker.tsindex 97fc9e2dc2..17fbef9128 100644--- a/src/commands/init-mode-picker.ts+++ b/src/commands/init-mode-picker.ts@@ -199,7 +199,7 @@ export function parseModeInput(raw: string): SearchMode | null {*/export async function runModePicker(engine: BrainEngine,- opts: { jsonOutput?: boolean; force?: boolean } = {},+ opts: { jsonOutput?: boolean; force?: boolean; onDecision?: (d: { mode: SearchMode; reason: string }) => void } = {},): Promise<SearchMode> {// Idempotent: don't re-prompt if already chosen, unless --force.if (!opts.force) {@@ -213,6 +213,7 @@ export async function runModePicker(const inputs = await resolveInputs(engine);const rec = recommendModeFor(inputs);+ opts.onDecision?.({ mode: rec.mode, reason: rec.reason });// JSON mode (used by --json init) — apply the recommendation silently// and emit a structured event. No interactive prompt.diff --git a/src/commands/init-prefer-postgres.ts b/src/commands/init-prefer-postgres.tsindex bdb7b8c90a..556b5c5a5c 100644--- a/src/commands/init-prefer-postgres.ts+++ b/src/commands/init-prefer-postgres.ts@@ -402,11 +402,13 @@ export async function runPreferPostgresLadder(o: PreferPostgresOpts): Promise<vo}if (o.jsonOutput) {- console.log(JSON.stringify({+ // D2: the ladder's envelope replaces the inner init's document (written once by runInit).+ const { setInitJsonResult } = await import('./init-json.ts');+ setInitJsonResult({status: 'ok',engine: rung === 'pglite' ? 'pglite' : 'postgres',ladder_rung: rung,url_source: urlSource,- }));+ }, { replace: true });}}diff --git a/src/commands/init.ts b/src/commands/init.tsindex f835e31770..dbcee0859d 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -16,8 +16,19 @@ import { isNewContentDatabase, setupSharedBrainContent, type SharedContentOptionimport { resolveSourceId } from '../core/source-resolver.ts';import type { BrainEngine } from '../core/engine.ts';import { readPrimaryEmbeddingStores, readStoredEmbeddingIdentity } from '../core/stored-embedding-identity.ts';+import { deferInitJsonError, flushInitJsonResult, initJsonError, setInitJsonResult, writeDeferredInitJsonError } from './init-json.ts';+import { buildInitFirstRunNotices } from './init-first-run.ts';+import { renderNotice, cliRenderContext } from '../core/agent-output.ts';+import { exitCodeForCode } from '../core/error-catalogue.ts';+import type { SearchMode as SearchModeName } from '../core/search/mode.ts';+/** D2: `--json` writes exactly one document, after whichever branch ran (see init-json.ts). */export async function runInit(args: string[]) {+ await runInitBranches(args);+ if (args.includes('--json')) await flushInitJsonResult();+}++async function runInitBranches(args: string[]) {// Help guard: cli.ts only routes --help to printOpHelp() for shared-op// commands; CLI_ONLY commands (init, embed, etc.) fall through to their// handler with --help in argv. Without this guard, `gbrain init --help`@@ -41,7 +52,8 @@ export async function runInit(args: string[]) {const isNonInteractive = args.includes('--non-interactive');const isMigrateOnly = args.includes('--migrate-only');const jsonOutput = args.includes('--json');- const fileState = readInitConfigState(jsonOutput);+ const fileState = readInitConfigState(jsonOutput, jsonOutput ? message => process.exit(initJsonError({ status: 'error', reason: 'invalid_existing_config', message },+ 'config_error', message, `Repair or move ${configPath()} aside, then re-run gbrain init.`)) : undefined);const urlIndex = args.indexOf('--url');const manualUrl = urlIndex !== -1 ? args[urlIndex + 1] : null;const keyIndex = args.indexOf('--key');@@ -81,11 +93,9 @@ export async function runInit(args: string[]) {const msg = `Thin-client config already present at ${configPath()} (remote_mcp.mcp_url=${url}).\n` +`Re-init would create a local engine and conflict with the remote MCP setup.\n` +`Use --force to overwrite, or \`gbrain init --mcp-only --force\` to refresh thin-client config.`;- if (jsonOutput) {- console.log(JSON.stringify({ status: 'error', reason: 'thin_client_config_present', mcp_url: url, message: msg }));- } else {- console.error(msg);- }+ if (jsonOutput) process.exit(initJsonError({ status: 'error', reason: 'thin_client_config_present', mcp_url: url, message: msg }, 'config_error', msg,+ 'Pass --force to overwrite, or run `gbrain init --mcp-only --force` to refresh the thin-client config.'));+ console.error(msg);process.exit(1);}@@ -270,13 +280,10 @@ function validateInitFlags(args: string[]) {}function failInitFlag(message: string, jsonOutput: boolean): never {- if (jsonOutput) {- console.log(JSON.stringify({ status: 'error', reason: 'invalid_flag', message }));- } else {- console.error(message);- console.error('Run `gbrain init --help` for supported flags.');- }- process.exit(1);+ if (jsonOutput) process.exit(initJsonError({ status: 'error', reason: 'invalid_flag', message }, 'invalid_params', message, 'Run `gbrain init --help` for supported flags.'));+ console.error(message);+ console.error('Run `gbrain init --help` for supported flags.');+ process.exit(exitCodeForCode('invalid_params'));}interface ResolveAIOptionsArgs {@@ -837,7 +844,7 @@ async function initMigrateOnly(opts: { jsonOutput: boolean }) {try {const result = await runMigrateOnlyCore();if (opts.jsonOutput) {- console.log(JSON.stringify({ status: 'success', engine: result.engine, mode: 'migrate-only' }));+ setInitJsonResult({ status: 'success', engine: result.engine, mode: 'migrate-only' });} else {console.log(`Schema up to date (engine: ${result.engine}).`);}@@ -846,11 +853,9 @@ async function initMigrateOnly(opts: { jsonOutput: boolean }) {if (e instanceof PgliteBusyError) throw e;const isNoConfig = e instanceof MigrateOnlyError && e.message.startsWith('No brain configured');const msg = e instanceof Error ? e.message : String(e);- if (opts.jsonOutput) {- console.log(JSON.stringify({ status: 'error', reason: isNoConfig ? 'no_config' : 'migrate_failed', message: msg }));- } else {- console.error(msg);- }+ if (opts.jsonOutput) process.exit(initJsonError({ status: 'error', reason: isNoConfig ? 'no_config' : 'migrate_failed', message: msg },+ isNoConfig ? 'no_brain' : 'database_error', msg, isNoConfig ? 'Run `gbrain init --pglite --no-embedding` first.' : 'Run `gbrain doctor --json` to see what blocks the schema bring-up.'));+ console.error(msg);process.exit(1);}}@@ -886,12 +891,12 @@ async function initRemoteMcp(opts: {const clientSecret = (arg('--oauth-client-secret') ?? process.env.GBRAIN_REMOTE_CLIENT_SECRET ?? '').trim();function fail(reason: string, message: string, extra: Record<string, unknown> = {}): never {- if (jsonOutput) {- console.log(JSON.stringify({ status: 'error', reason, message, ...extra }));- } else {- console.error(message);- }- process.exit(1);+ const code = reason.startsWith('missing_') ? 'invalid_params' : reason.startsWith('token_') ? 'invalid_token'+ : reason.startsWith('discovery_') || reason.startsWith('mcp_smoke_') ? 'unavailable' : 'config_error';+ if (jsonOutput) process.exit(initJsonError({ status: 'error', reason, message, ...extra }, code, message.split('\n')[0],+ message.split('\n').slice(1).join(' ') || 'Run `gbrain init --help` for the thin-client flags.'));+ console.error(message);+ process.exit(code === 'invalid_params' ? exitCodeForCode(code) : 1);}if (!issuerUrl) fail('missing_issuer_url', '--issuer-url is required (or set GBRAIN_REMOTE_ISSUER_URL). Example: --issuer-url https://brain-host.local:3001');@@ -977,14 +982,14 @@ async function initRemoteMcp(opts: {saveConfig(config);if (jsonOutput) {- console.log(JSON.stringify({+ setInitJsonResult({status: 'success',mode: 'thin-client',issuer_url: config.remote_mcp!.issuer_url,mcp_url: config.remote_mcp!.mcp_url,oauth_client_id: config.remote_mcp!.oauth_client_id,oauth_secret_in_config: 'oauth_client_secret' in config.remote_mcp!,- }));+ });} else {console.log('');console.log('Thin-client mode configured. No local DB.');@@ -1093,9 +1098,7 @@ export async function initPGLite(opts: {});if (!pre.ok) {console.error(`\nRefusing to init: ${pre.error}\n`);- if (opts.jsonOutput) {- console.log(JSON.stringify({ status: 'error', reason: 'preflight_failed', error: pre.error }));- }+ if (opts.jsonOutput) process.exit(initJsonError({ status: 'error', reason: 'preflight_failed', error: pre.error }, 'config_error', pre.error, INIT_EMBEDDING_HINT));process.exit(1);}resolvedDim = pre.dim;@@ -1161,14 +1164,8 @@ export async function initPGLite(opts: {engineKind: 'pglite',databasePath: dbPath,}) + '\n');- if (opts.jsonOutput) {- console.log(JSON.stringify({- status: 'error',- reason: 'embedding_dim_mismatch',- current_dims: existing.dims,- requested_dims: resolvedDim,- }));- }+ if (opts.jsonOutput) process.exit(initJsonError({ status: 'error', reason: 'embedding_dim_mismatch', current_dims: existing.dims, requested_dims: resolvedDim },+ 'embedding_width_mismatch', `The brain's vectors are ${existing.dims}d; the requested model produces ${resolvedDim}d.`, INIT_EMBEDDING_HINT));process.exit(1);}}@@ -1262,12 +1259,13 @@ export async function initPGLite(opts: {// DB config writes are valid. Idempotent: skipped on re-init if already set.// Non-TTY auto-selects; --json emits a structured event.const { runModePicker } = await import('./init-mode-picker.ts');- await runModePicker(engine, { jsonOutput: opts.jsonOutput });+ let searchMode: { mode: SearchModeName; reason: string } | undefined;+ await runModePicker(engine, { jsonOutput: opts.jsonOutput, onDecision: d => { searchMode = d; } });const stats = await engine.getStats();if (opts.jsonOutput) {- console.log(JSON.stringify({ status: 'success', engine: 'pglite', path: dbPath, pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt }));+ setInitJsonResult({ status: 'success', engine: 'pglite', path: dbPath, pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt, ...firstRunNotices(searchMode) });} else if (process.env.GBRAIN_IN_AGENT_SETUP === '1') {printInAgentReady(dbPath);} else {@@ -1307,6 +1305,14 @@ export async function initPGLite(opts: {}}+const INIT_EMBEDDING_HINT = 'Pick an embedding model whose dimensions match (`gbrain init --help`), or pass --no-embedding for a keyless brain.';++/** D2/G5: the first-run decision bundle rendered into init's --json document (`notices`, empty → omitted). */+function firstRunNotices(searchMode: { mode: SearchModeName; reason: string } | undefined): { notices?: unknown[]; contract_version: 1 } {+ const notices = buildInitFirstRunNotices({ searchMode, config: loadConfig() }).map(n => renderNotice(n, cliRenderContext()));+ return { ...(notices.length ? { notices } : {}), contract_version: 1 };+}+/*** MEMORY_VERBS v1 quickstart funnel (E3 + D4B + T1 consent). Printed LAST in* both init epilogues as the ONE primary action. The copy-next block is@@ -1357,7 +1363,7 @@ async function initPostgres(opts: Parameters<typeof initPostgresCore>[0]) {try {await initPostgresCore(opts);} catch (e) {- if (e instanceof InitPostgresFailure) process.exit(1);+ if (e instanceof InitPostgresFailure) process.exit((opts.jsonOutput ? writeDeferredInitJsonError() : null) ?? 1);throw e;}}@@ -1395,9 +1401,7 @@ export async function initPostgresCore(opts: {});if (!pre.ok) {console.error(`\nRefusing to init: ${pre.error}\n`);- if (opts.jsonOutput) {- console.log(JSON.stringify({ status: 'error', reason: 'preflight_failed', error: pre.error }));- }+ if (opts.jsonOutput) deferInitJsonError({ status: 'error', reason: 'preflight_failed', error: pre.error }, 'config_error', pre.error, INIT_EMBEDDING_HINT);throw new InitPostgresFailure('preflight_failed', pre.error);}resolvedDim = pre.dim;@@ -1506,14 +1510,8 @@ export async function initPostgresCore(opts: {source: 'init',engineKind: 'postgres',}) + '\n');- if (opts.jsonOutput) {- console.log(JSON.stringify({- status: 'error',- reason: 'embedding_dim_mismatch',- current_dims: existing.dims,- requested_dims: resolvedDim,- }));- }+ if (opts.jsonOutput) deferInitJsonError({ status: 'error', reason: 'embedding_dim_mismatch', current_dims: existing.dims, requested_dims: resolvedDim },+ 'embedding_width_mismatch', `The brain's vectors are ${existing.dims}d; the requested model produces ${resolvedDim}d.`, INIT_EMBEDDING_HINT);throw new InitPostgresFailure('embedding_dim_mismatch');}}@@ -1600,12 +1598,13 @@ export async function initPostgresCore(opts: {// v0.32.3 search-lite install-time mode picker. Same shape as the// PGLite path above — runs AFTER initSchema, idempotent on re-init.const { runModePicker: runPostgresModePicker } = await import('./init-mode-picker.ts');- await runPostgresModePicker(engine, { jsonOutput: opts.jsonOutput });+ let searchMode: { mode: SearchModeName; reason: string } | undefined;+ await runPostgresModePicker(engine, { jsonOutput: opts.jsonOutput, onDecision: d => { searchMode = d; } });const stats = await engine.getStats();if (opts.jsonOutput) {- console.log(JSON.stringify({ status: 'success', engine: 'postgres', pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt }));+ setInitJsonResult({ status: 'success', engine: 'postgres', pages: stats.page_count, embedding_check: embedCheck, content: contentReceipt, ...firstRunNotices(searchMode) });} else {console.log(`\nBrain ready. ${stats.page_count} pages. Engine: Postgres (Supabase).`);if (stats.page_count > 0) {diff --git a/src/core/agent-install/init-state.ts b/src/core/agent-install/init-state.tsindex aafa7f7ab5..5c29f3cc96 100644--- a/src/core/agent-install/init-state.ts+++ b/src/core/agent-install/init-state.ts@@ -4,10 +4,12 @@ import { dirname, join } from 'node:path';import { configPath, gbrainPath, isThinClient, loadConfigFileOnly } from '../config.ts';import { privateWrite, readFileConfigState } from './state.ts';-export function readInitConfigState(json: boolean) {+/** `onInvalid` lets init's `--json` writer report the refusal (agent contract v1 D2). */+export function readInitConfigState(json: boolean, onInvalid?: (message: string) => never) {const state = readFileConfigState(configPath());if (state.kind === 'invalid') {const message = `Existing configuration at ${configPath()} is unreadable or malformed. Preserve and repair it before initialization; it will not be overwritten.`;+ if (onInvalid) onInvalid(message);if (json) console.log(JSON.stringify({ status: 'error', reason: 'invalid_existing_config', message }));else console.error(message);process.exit(1);diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 9d2be94d65..8be33a73a5 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -288,5 +288,6 @@ export interface NoticeEntry {export const NOTICE_CODES = {backup_coverage: { kind: 'coaching', summary: 'Some knowledge assets have no off-machine backup.' },empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },+ first_run_decisions: { kind: 'ask', summary: 'init finished; the first-run decisions (search mode, harness wiring, …) carry defaults the user may change.' },unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },} as const satisfies Record<string, NoticeEntry>;diff --git a/test/cli-json-guard.serial.test.ts b/test/cli-json-guard.serial.test.tsindex be70b9c31e..39e500b5df 100644--- a/test/cli-json-guard.serial.test.ts+++ b/test/cli-json-guard.serial.test.ts@@ -99,3 +99,63 @@ g.flushThenExit(0);`);expect(r.out).toBe('plain\n');}, 20_000);});++// ── D2: command migrations (real CLI subprocesses, isolated GBRAIN_HOME) ──+import { runCli } from './helpers/cli-spawn.ts';+import { mkdirSync } from 'node:fs';++function onlyDocument(stdout: string): Record<string, unknown> {+ const doc = JSON.parse(stdout);+ expect(typeof doc).toBe('object');+ return doc;+}++describe('D2 command migrations: init', () => {+ test('init --pglite --no-embedding --json: one document carrying the first-run decision bundle', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-json-init-'));+ try {+ const r = await runCli(['init', '--pglite', '--no-embedding', '--json'], { home, cwd: home, timeoutMs: 120_000 });+ expect(r.exitCode).toBe(0);+ const doc = onlyDocument(r.stdout);+ expect(doc).toMatchObject({ status: 'success', engine: 'pglite', contract_version: 1 });+ const bundle = (doc.notices as Array<Record<string, any>>).find(n => n.code === 'first_run_decisions')!;+ expect(bundle).toMatchObject({ kind: 'ask', contract_version: 1 });+ expect(bundle.user_message).toContain("Reply 'defaults'");+ const searchMode = bundle.decisions.find((d: { id: string }) => d.id === 'search_mode');+ expect(searchMode.options.map((o: { id: string }) => o.id)).toEqual(['conservative', 'balanced', 'tokenmax']);+ expect(searchMode.options[0].argv).toEqual(['gbrain', 'config', 'set', 'search.mode', 'conservative']);+ // Progress lines and the picker's event went to stderr.+ expect(r.stderr).toContain('Setting up local brain with PGLite');+ expect(r.stdout).not.toContain('search_mode_picker');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ }, 150_000);++ test('init --json usage failure: legacy one-line keys plus the v1 envelope, exit 2', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-json-init-'));+ try {+ const r = await runCli(['init', '--mcp-only', '--json', '--mcp-url', 'http://127.0.0.1:1/mcp', '--oauth-client-id', 'cid', '--oauth-client-secret', 'cs'], { home, cwd: home });+ expect(r.exitCode).toBe(2);+ expect(r.stdout.trim().split('\n')).toHaveLength(1);+ expect(onlyDocument(r.stdout)).toMatchObject({ status: 'error', reason: 'missing_issuer_url', error: 'invalid_params', code: 'invalid_params', contract_version: 1 });+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });++ test('init --json on a malformed config: config_error document, config untouched', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-json-init-'));+ try {+ mkdirSync(join(home, '.gbrain'));+ writeFileSync(join(home, '.gbrain', 'config.json'), '{broken');+ const r = await runCli(['init', '--pglite', '--json'], { home, cwd: home });+ expect(r.exitCode).toBe(1);+ const doc = onlyDocument(r.stdout);+ expect(doc).toMatchObject({ status: 'error', reason: 'invalid_existing_config', code: 'config_error' });+ expect(typeof doc.suggestion).toBe('string');+ } finally {+ rmSync(home, { recursive: true, force: true });+ }+ });+});diff --git a/test/fixtures/goldens/doctor/json-no-config.json b/test/fixtures/goldens/doctor/json-no-config.jsonindex 7629d96dfc..12a97879e5 100644--- a/test/fixtures/goldens/doctor/json-no-config.json+++ b/test/fixtures/goldens/doctor/json-no-config.json@@ -7,12 +7,41 @@"<home>/skills"],"exit_code": 1,- "report": null,+ "report": {+ "class": "caller",+ "code": "no_brain",+ "contract_version": 1,+ "docs": "https://github.com/garrytan/gbrain/blob/master/docs/guides/error-codes.md#no_brain",+ "docs_cmd": [+ "gbrain",+ "errors",+ "no_brain"+ ],+ "error": "no_brain",+ "fix": {+ "actor": "agent",+ "argv": [+ "gbrain",+ "init",+ "--pglite",+ "--no-embedding"+ ],+ "command": "gbrain init --pglite --no-embedding",+ "consent": [],+ "next": "run",+ "requires_exclusive": false,+ "why": "Creates a local PGLite brain with no API keys; nothing leaves this machine."+ },+ "message": "No brain configured. Run: gbrain init",+ "retryable": false,+ "suggestion": "Run `gbrain init --pglite --no-embedding` for a local keyless brain, or `gbrain init --help` for hosted and Postgres options."+ },"stderr": ["GBRAIN_DB_ACCESS no_url",- "No brain configured. Run: gbrain init"+ "Error [no_brain]: No brain configured. Run: gbrain init",+ "Fix: gbrain init --pglite --no-embedding"],- "stdout": []+ "stdout": "<json>"},"normalizer": "doctor-json-v1"}diff --git a/test/init-mcp-only.test.ts b/test/init-mcp-only.test.tsindex a772a711ae..a0c9519197 100644--- a/test/init-mcp-only.test.ts+++ b/test/init-mcp-only.test.ts@@ -184,50 +184,50 @@ describe('gbrain init --mcp-only — happy path', () => {});describe('gbrain init --mcp-only — required-flag errors', () => {- test('missing --issuer-url exits 1 with clear error', async () => {+ test('missing --issuer-url exits 2 (usage) with clear error', async () => {const r = await run(['init', '--mcp-only', '--json','--mcp-url', `http://127.0.0.1:${port}/mcp`,'--oauth-client-id', 'cid','--oauth-client-secret', 'csecret',]);- expect(r.exitCode).toBe(1);+ expect(r.exitCode).toBe(2); // usage error (agent contract v1 A3)const parsed = JSON.parse(r.stdout.trim().split('\n').pop()!);expect(parsed.reason).toBe('missing_issuer_url');});- test('missing --mcp-url exits 1', async () => {+ test('missing --mcp-url exits 2 (usage)', async () => {const r = await run(['init', '--mcp-only', '--json','--issuer-url', `http://127.0.0.1:${port}`,'--oauth-client-id', 'cid','--oauth-client-secret', 'csecret',]);- expect(r.exitCode).toBe(1);+ expect(r.exitCode).toBe(2); // usage error (agent contract v1 A3)const parsed = JSON.parse(r.stdout.trim().split('\n').pop()!);expect(parsed.reason).toBe('missing_mcp_url');});- test('missing --oauth-client-id exits 1', async () => {+ test('missing --oauth-client-id exits 2 (usage)', async () => {const r = await run(['init', '--mcp-only', '--json','--issuer-url', `http://127.0.0.1:${port}`,'--mcp-url', `http://127.0.0.1:${port}/mcp`,'--oauth-client-secret', 'csecret',]);- expect(r.exitCode).toBe(1);+ expect(r.exitCode).toBe(2); // usage error (agent contract v1 A3)const parsed = JSON.parse(r.stdout.trim().split('\n').pop()!);expect(parsed.reason).toBe('missing_client_id');});- test('missing --oauth-client-secret exits 1', async () => {+ test('missing --oauth-client-secret exits 2 (usage)', async () => {const r = await run(['init', '--mcp-only', '--json','--issuer-url', `http://127.0.0.1:${port}`,'--mcp-url', `http://127.0.0.1:${port}/mcp`,'--oauth-client-id', 'cid',]);- expect(r.exitCode).toBe(1);+ expect(r.exitCode).toBe(2); // usage error (agent contract v1 A3)const parsed = JSON.parse(r.stdout.trim().split('\n').pop()!);expect(parsed.reason).toBe('missing_client_secret');});diff --git a/test/migrate-embeddings-recovery-cli.serial.test.ts b/test/migrate-embeddings-recovery-cli.serial.test.tsindex 98963ab098..55eecd1ec8 100644--- a/test/migrate-embeddings-recovery-cli.serial.test.ts+++ b/test/migrate-embeddings-recovery-cli.serial.test.ts@@ -195,8 +195,8 @@ test('both actual migration CLI routes reject unsupported or malformed controlscwd: home, env, stdout: 'pipe', stderr: 'pipe',});const [stdout, stderr, code] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]);- expect(code).toBe(1);- expect(JSON.parse(stdout)).toMatchObject({ status: 'error', reason: 'invalid_flag' });+ expect(code).toBe(2); // usage error (agent contract v1 A3); legacy keys kept, v1 envelope added+ expect(JSON.parse(stdout)).toMatchObject({ status: 'error', reason: 'invalid_flag', code: 'unknown_flag' });if (['--source', '--slugs'].includes(flag)) expect(stderr).toContain(`unknown flag ${flag}`);else expect(stderr).toContain(flag);expect(stderr).not.toContain('PGLite');