Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(ai): chat_fallback_on_refusal and a one-time first-hop notice

garrytan09cf74caa437
diff --git a/src/cli/op-notices.ts b/src/cli/op-notices.ts
index d5d50ec1cc..314a20bab9 100644
--- a/src/cli/op-notices.ts
+++ b/src/cli/op-notices.ts
@@ -10,6 +10,7 @@ import { cliRenderContext, renderNotice, type Notice } from '../core/agent-outpu
import { renderCliNotices } from '../core/agent-markers.ts';
import { isInteractive } from '../core/interaction.ts';
import { processNoticeLedger, mutedNoticeCodes } from '../core/notice-ledger.ts';
+import { takeChatFallbackHopNotices } from '../core/ai/fallback-hop-queue.ts';
let pending: Notice[] = [];
@@ -19,7 +20,7 @@ export function captureOpNotice(n: Notice): void {
/** Drain the captured notices into the result (`--json` objects) and/or a stderr string. */
export function applyCliOpNotices(result: unknown, json: boolean): { result: unknown; stderr?: string } {
- const captured = pending;
+ const captured = [...pending, ...takeChatFallbackHopNotices()];
pending = [];
if (captured.length === 0) return { result };
let admitted = captured;
diff --git a/src/core/ai/build-gateway-config.ts b/src/core/ai/build-gateway-config.ts
index 278596b0c4..039a7054fd 100644
--- a/src/core/ai/build-gateway-config.ts
+++ b/src/core/ai/build-gateway-config.ts
@@ -85,6 +85,7 @@ export function buildGatewayConfig(c: GBrainConfig): AIGatewayConfig {
expansion_model: c.expansion_model,
chat_model: c.chat_model,
chat_fallback_chain: c.chat_fallback_chain,
+ chat_fallback_on_refusal: c.chat_fallback_on_refusal,
base_urls: { ...envBaseUrls, ...(c.provider_base_urls ?? {}) }, // config wins over env
provider_chat_options: c.provider_chat_options,
// #1249 empty-string drop + GEMINI alias applied inside mergedProviderEnv.
diff --git a/src/core/ai/chat-fallback.ts b/src/core/ai/chat-fallback.ts
index a1c51a4dac..27dda7fab0 100644
--- a/src/core/ai/chat-fallback.ts
+++ b/src/core/ai/chat-fallback.ts
@@ -16,6 +16,12 @@
* 'content_filter'), the signal `mapStopReason` derives for this purpose.
* A result a chain entry produced carries `fallbackFrom` (the call's own model),
* so callers that cache or key on model identity can tell it apart.
+ * With `chat_fallback_on_refusal: false` (`onRefusal: false` here) a refusal
+ * ends the walk instead: a structural refusal is returned and a provider
+ * content block (`providerContentBlockReason`) is thrown, so content one
+ * provider refused is never sent to the next one; outages still fall back.
+ * The first hop a process takes queues one `chat_fallback_hop` safety notice
+ * (`fallback-hop-queue.ts`, drained by MCP dispatch and the CLI).
* The chain stops on a gbrain policy refusal (an invocation-guard denial or a
* BudgetTracker `BudgetExhausted`: budget, caps and pricing describe gbrain's
* own accounting, and the next model is billed by the same ledger)
@@ -27,8 +33,11 @@
*/
import type { ChatOpts, ChatResult } from './gateway.ts';
+import type { Notice } from '../agent-output.ts';
import { isAIInvocationPolicyError } from './invocation-guard.ts';
+import { providerContentBlockReason } from './errors.ts';
import { BudgetExhausted } from '../budget/budget-tracker.ts';
+import { queueFirstFallbackHop } from './fallback-hop-queue.ts';
const HOP_REASON_MAX_CHARS = 200;
@@ -52,6 +61,33 @@ export function chatFallbackAttempts(primary: string, chain: readonly string[]):
return attempts;
}
+/** The first fallback hop in this process, as one safety notice: which model failed or refused and which one received the request. */
+export function chatFallbackHopNotice(failed: string, next: string, cause: string, refusal: boolean): Notice {
+ return {
+ code: 'chat_fallback_hop',
+ kind: 'safety',
+ why: `chat_fallback_chain sent a request to another model: ${failed} ${refusal ? `refused it (${cause})` : `failed (${cause})`}, so the request went to ${next}. ` +
+ 'Every later hop in this process logs to stderr only. ' +
+ (refusal
+ ? 'Fallback on refusals sends content one provider refused to the next one; `gbrain config set chat_fallback_on_refusal false` keeps outage fallback and stops that.'
+ : 'Outage fallback is the configured behavior; `gbrain doctor --only chat_fallback_chain` shows the chain, the providers it reaches and how to remove it.'),
+ fix: {
+ argv: ['gbrain', 'doctor', '--only', 'chat_fallback_chain', '--json'], consent: [], actor: 'agent', requires_exclusive: false,
+ why: 'Shows the effective chain, the config plane it comes from and per-plane removal guidance; read-only.',
+ docs: 'docs/guides/chat-fallback.md',
+ },
+ };
+}
+
+function queueFirstHop(failed: string, next: string, cause: string, refusal: boolean): void {
+ queueFirstFallbackHop(() => chatFallbackHopNotice(failed, next, cause, refusal));
+}
+
+export interface ChatFallbackOptions {
+ /** `chat_fallback_on_refusal` (default true): false ends the walk on a refusal instead of sending the content onward. */
+ onRefusal?: boolean;
+}
+
function isStructuralRefusal(result: ChatResult): boolean {
return result.stopReason === 'refusal' || result.stopReason === 'content_filter';
}
@@ -67,7 +103,9 @@ export async function chatWithFallback(
primary: string,
chain: readonly string[],
attempt: (opts: ChatOpts) => Promise<ChatResult>,
+ options: ChatFallbackOptions = {},
): Promise<ChatResult> {
+ const onRefusal = options.onRefusal !== false;
const models = chatFallbackAttempts(primary, chain);
const answered = (result: ChatResult, model: string): ChatResult =>
model === models[0] ? result : { ...result, fallbackFrom: models[0] };
@@ -78,12 +116,18 @@ export async function chatWithFallback(
const next = models[i + 1];
try {
const result = await attempt({ ...opts, model, allowFallback: false });
- if (next === undefined || !isStructuralRefusal(result)) return answered(result, model);
+ if (next === undefined || !isStructuralRefusal(result) || !onRefusal) return answered(result, model);
refused ??= answered(result, model);
console.warn(`[ai.gateway] chat ${result.model} stopped with ${result.stopReason}; trying ${next} from chat_fallback_chain`);
+ queueFirstHop(result.model, next, `stopReason ${result.stopReason}`, true);
} catch (err) {
if (isAIInvocationPolicyError(err) || err instanceof BudgetExhausted || opts.abortSignal?.aborted) throw err;
if (model === models[0]) primaryError = err;
+ const blocked = providerContentBlockReason(err);
+ if (blocked !== undefined && !onRefusal) {
+ console.warn(`[ai.gateway] chat ${model} refused the request (${blocked}); chat_fallback_on_refusal is false, so it is not sent to another model`);
+ throw primaryError ?? err;
+ }
if (next === undefined) {
if (refused) {
console.warn(`[ai.gateway] chat ${model} failed (${hopReason(err)}); returning the earlier refusal from ${refused.model}`);
@@ -95,6 +139,7 @@ export async function chatWithFallback(
throw primaryError ?? err;
}
console.warn(`[ai.gateway] chat ${model} failed (${hopReason(err)}); trying ${next} from chat_fallback_chain`);
+ queueFirstHop(model, next, blocked !== undefined ? `content block ${blocked}` : hopReason(err), blocked !== undefined);
}
}
}
diff --git a/src/core/ai/fallback-hop-queue.ts b/src/core/ai/fallback-hop-queue.ts
new file mode 100644
index 0000000000..0f3407bc2c
--- /dev/null
+++ b/src/core/ai/fallback-hop-queue.ts
@@ -0,0 +1,30 @@
+/**
+ * The process-level queue for the first `chat_fallback_chain` hop's
+ * `chat_fallback_hop` safety notice. `chatWithFallback` queues at most one
+ * per process; MCP dispatch (stdio), the CLI op notice channel and CLI
+ * teardown drain it. No imports beyond a type, so every drain site can load
+ * it cheaply.
+ */
+import type { Notice } from '../agent-output.ts';
+
+let queued = false;
+const pending: Notice[] = [];
+
+/** Queue the first hop's notice; every later call in this process is a no-op. Returns whether it queued. */
+export function queueFirstFallbackHop(build: () => Notice): boolean {
+ if (queued) return false;
+ queued = true;
+ pending.push(build());
+ return true;
+}
+
+/** Drain the queued first-hop notice (at most one per process). */
+export function takeChatFallbackHopNotices(): Notice[] {
+ return pending.splice(0);
+}
+
+/** Test seam: re-arm the once-per-process first-hop notice. */
+export function __resetChatFallbackHopNoticeForTests(): void {
+ queued = false;
+ pending.splice(0);
+}
diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.ts
index 247e3948d1..694de582f4 100644
--- a/src/core/ai/gateway.ts
+++ b/src/core/ai/gateway.ts
@@ -447,6 +447,7 @@ export function configureGateway(config: AIGatewayConfig): void {
expansion_model: config.expansion_model ?? DEFAULT_EXPANSION_MODEL,
chat_model: config.chat_model ?? DEFAULT_CHAT_MODEL,
chat_fallback_chain: normalizeChatFallbackChain(config.chat_fallback_chain),
+ chat_fallback_on_refusal: config.chat_fallback_on_refusal,
// v0.35.0.0+: reranker_model stays undefined when unset — reranker is
// opt-in and pulling DEFAULT_RERANKER_MODEL into every gateway start
// would silently register a third-party model id on brains that never
@@ -3428,7 +3429,9 @@ export function toAISDKTools(tools: ChatToolDef[] | undefined): Record<string, a
export async function chat(opts: ChatOpts): Promise<ChatResult> {
const fallbackChain = opts.allowFallback === false ? undefined : _config?.chat_fallback_chain;
- if (fallbackChain?.length) return chatWithFallback(opts, opts.model ?? getChatModel(), fallbackChain, chat);
+ if (fallbackChain?.length) {
+ return chatWithFallback(opts, opts.model ?? getChatModel(), fallbackChain, chat, { onRefusal: _config?.chat_fallback_on_refusal !== false });
+ }
const tracker = __budgetStore.getStore() ?? null;
const modelStrEarly = opts.model ?? getChatModel();
diff --git a/src/core/ai/types.ts b/src/core/ai/types.ts
index 96d8f1f695..b3a58c327b 100644
--- a/src/core/ai/types.ts
+++ b/src/core/ai/types.ts
@@ -498,6 +498,8 @@ export interface AIGatewayConfig {
* Judge, critic and eval call sites opt out with `allowFallback: false`.
*/
chat_fallback_chain?: string[];
+ /** `false` keeps outage fallback but never sends a refused request to the next chain entry. Default true. */
+ chat_fallback_on_refusal?: boolean;
/** Optional per-provider base URL override (openai-compatible variants). */
base_urls?: Record<string, string>;
/** Optional chat providerOptions overrides keyed by recipe id or "recipe:modelId". */
diff --git a/src/core/cli-force-exit.ts b/src/core/cli-force-exit.ts
index 35e82fee8c..d612500380 100644
--- a/src/core/cli-force-exit.ts
+++ b/src/core/cli-force-exit.ts
@@ -936,6 +936,11 @@ export async function finishCliTeardown(opts: FinishCliTeardownOpts): Promise<vo
`[cli] background-work drain failed during teardown: ${e instanceof Error ? e.message : String(e)} — continuing to disconnect`,
);
}
+ // The first chat_fallback_chain hop of this process, when no op notice channel drained it.
+ try {
+ const hops = (await import('./ai/fallback-hop-queue.ts')).takeChatFallbackHopNotices();
+ if (hops.length > 0) (await import('./interop-notices.ts')).writeCliNotices(hops);
+ } catch { /* a notice never blocks teardown */ }
try {
await opts.engine.disconnect();
} catch (e) {
diff --git a/src/core/config-db-merge.ts b/src/core/config-db-merge.ts
index 1a8dbccdfb..cdc6334155 100644
--- a/src/core/config-db-merge.ts
+++ b/src/core/config-db-merge.ts
@@ -3,7 +3,7 @@
*
* DB-plane values that `gbrain config set` accepted for years, `config get`
* echoed back, and NOTHING read: provider credentials, chat/expansion model
- * pins, the chat fallback chain, and flat `cycle.*` knobs. This module owns
+ * pins, the chat fallback chain and its refusal switch, and flat `cycle.*` knobs. This module owns
* their sparse-merge into the loaded config — called by
* `loadConfigWithEngine()` (src/core/config.ts) after its per-key merges,
* with the same precedence: env > file > DB.
@@ -65,12 +65,34 @@ export interface DbPlaneEngineReader {
): Promise<T[]>;
}
+/**
+ * The DB-plane `chat_fallback_chain` string: the comma-separated form the
+ * GBRAIN_CHAT_FALLBACK_CHAIN env var uses, or a JSON string array. `error`
+ * names why a JSON payload was rejected (doctor reports it); an empty chain
+ * is no chain.
+ */
+export function parseDbChatFallbackChain(raw: string): { chain?: string[]; error?: string } {
+ if (!raw.trim().startsWith('[')) {
+ const chain = raw.split(',').map((s) => s.trim()).filter(Boolean);
+ return chain.length > 0 ? { chain } : {};
+ }
+ try {
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed) || !parsed.every((x) => typeof x === 'string')) return { error: 'is not a JSON array of strings' };
+ const chain = parsed.map((s) => s.trim()).filter(Boolean);
+ return chain.length > 0 ? { chain } : {};
+ } catch (err) {
+ return { error: `is not valid JSON (${(err as Error).message})` };
+ }
+}
+
/** The flat scalar keys the batched read fetches (plus the `cycle.` prefix). */
const DB_MERGED_SCALAR_KEYS: readonly string[] = [
...DB_MERGED_PROVIDER_KEY_FIELDS,
'expansion_model',
'chat_model',
'chat_fallback_chain',
+ 'chat_fallback_on_refusal',
];
const CYCLE_PREFIX = 'cycle.';
@@ -185,26 +207,16 @@ export async function applyDbPlaneReadSideMerge(
if (merged.chat_fallback_chain === undefined) {
const rawChain = values.get('chat_fallback_chain');
if (rawChain !== undefined) {
- let chain: string[] | undefined;
- if (rawChain.trim().startsWith('[')) {
- try {
- const parsed = JSON.parse(rawChain);
- if (Array.isArray(parsed) && parsed.every((x) => typeof x === 'string')) {
- chain = parsed.map((s) => s.trim()).filter(Boolean);
- } else {
- console.warn('[gbrain] config: chat_fallback_chain DB value is not a JSON array of strings; ignoring');
- }
- } catch (err) {
- console.warn(`[gbrain] config: chat_fallback_chain DB value is not valid JSON; ignoring (${(err as Error).message})`);
- }
- } else {
- chain = rawChain.split(',').map((s) => s.trim()).filter(Boolean);
- }
- if (chain !== undefined && chain.length > 0) {
- merged.chat_fallback_chain = chain;
- }
+ const parsed = parseDbChatFallbackChain(rawChain);
+ if (parsed.error) console.warn(`[gbrain] config: chat_fallback_chain DB value ${parsed.error}; ignoring`);
+ if (parsed.chain) merged.chat_fallback_chain = parsed.chain;
}
}
+ // chat_fallback_on_refusal — 'true' / 'false' (strict); any other DB value is ignored.
+ if (merged.chat_fallback_on_refusal === undefined) {
+ const rawOnRefusal = values.get('chat_fallback_on_refusal');
+ if (rawOnRefusal === 'true' || rawOnRefusal === 'false') merged.chat_fallback_on_refusal = rawOnRefusal === 'true';
+ }
// Flat cycle.* merge (#2137/#4297 read-side), fed by the same batched read
// (`key LIKE 'cycle.%'` arm); leaves keep their raw string values (each
diff --git a/src/core/config.ts b/src/core/config.ts
index 10c5140a1b..0e81e1abf9 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -156,6 +156,12 @@ export interface GBrainConfig {
* string. Judge, critic and eval call sites pin their model (allowFallback).
*/
chat_fallback_chain?: string[];
+ /**
+ * `false` keeps `chat_fallback_chain` for outages and errors but never sends
+ * a refused request (structural refusal or provider content block) to the
+ * next entry. Default true. Env `GBRAIN_CHAT_FALLBACK_ON_REFUSAL`, file, DB.
+ */
+ chat_fallback_on_refusal?: boolean;
/** Optional base URL overrides for openai-compatible providers (keyed by recipe id). */
provider_base_urls?: Record<string, string>;
/** Optional chat request providerOptions overrides keyed by recipe id or "recipe:modelId". */
@@ -736,6 +742,9 @@ export function loadConfig(): GBrainConfig | null {
...(process.env.GBRAIN_CHAT_FALLBACK_CHAIN
? { chat_fallback_chain: process.env.GBRAIN_CHAT_FALLBACK_CHAIN.split(',').map(s => s.trim()).filter(Boolean) }
: {}),
+ ...(process.env.GBRAIN_CHAT_FALLBACK_ON_REFUSAL?.trim()
+ ? { chat_fallback_on_refusal: !isEnvDisabled(process.env.GBRAIN_CHAT_FALLBACK_ON_REFUSAL) }
+ : {}),
...(process.env.GBRAIN_EMBEDDING_MULTIMODAL
? { embedding_multimodal: process.env.GBRAIN_EMBEDDING_MULTIMODAL === 'true' }
: {}),
@@ -1229,6 +1238,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
'expansion_model',
'chat_model',
'chat_fallback_chain',
+ 'chat_fallback_on_refusal',
'provider_base_urls',
// Integration gates (file-plane, hook-lane)
'integrations.memorable.enabled',
diff --git a/test/ai/chat-fallback-on-refusal.test.ts b/test/ai/chat-fallback-on-refusal.test.ts
new file mode 100644
index 0000000000..1fa546eb59
--- /dev/null
+++ b/test/ai/chat-fallback-on-refusal.test.ts
@@ -0,0 +1,197 @@
+/**
+ * `chat_fallback_on_refusal` and the first-hop notice (fix wave lane B3).
+ *
+ * Protects: with `chat_fallback_on_refusal=false`, a refused request (a
+ * structural refusal stop reason or a provider content block thrown as an
+ * error) is never sent to the next `chat_fallback_chain` entry, while an
+ * outage still falls back; the key reaches chat() through the real loader on
+ * every plane with env > config.json > DB precedence; the first hop of a
+ * process queues exactly one `chat_fallback_hop` safety notice naming the
+ * failed and the next model.
+ * Fails when: the key is dropped at any hop (config.ts, the DB merge key list,
+ * buildGatewayConfig, configureGateway, chatWithFallback), the precedence is
+ * wrong, or the hop notice fires zero or more than one time per process.
+ * Seams: the generateText transport (no network); a real PGLite brain for the
+ * DB plane; a throwaway GBRAIN_HOME for the file plane.
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
+import { mkdtempSync, mkdirSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { chat, configureGateway, resetGateway, __setGenerateTextTransportForTests, type ChatResult } from '../../src/core/ai/gateway.ts';
+import { chatWithFallback } from '../../src/core/ai/chat-fallback.ts';
+import { takeChatFallbackHopNotices, __resetChatFallbackHopNoticeForTests } from '../../src/core/ai/fallback-hop-queue.ts';
+import { buildGatewayConfig } from '../../src/core/ai/build-gateway-config.ts';
+import { loadConfig, loadConfigWithEngine } from '../../src/core/config.ts';
+import { _resetDbPlaneMergeMemoForTests } from '../../src/core/config-db-merge.ts';
+import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
+import { withEnv } from '../helpers/with-env.ts';
+
+const PRIMARY = 'claude-cli:claude-sonnet-4-6';
+const FALLBACK = 'openai:gpt-5.6-luna';
+
+type Outcome = 'ok' | 'refusal' | 'blocked' | 'outage';
+
+/** A provider content block the way the AI SDK surfaces one: a 200 body whose prompt was blocked. */
+function contentBlock(): Error {
+ return Object.assign(new Error('No output generated: the prompt was blocked'), {
+ responseBody: JSON.stringify({ promptFeedback: { blockReason: 'PROHIBITED_CONTENT' } }),
+ statusCode: 200,
+ });
+}
+
+let attempts: string[] = [];
+function installTransport(outcomes: Record<string, Outcome>): void {
+ __setGenerateTextTransportForTests((async (args: any) => {
+ const modelId: string = args.model.modelId;
+ attempts.push(modelId);
+ const outcome = outcomes[modelId] ?? 'ok';
+ if (outcome === 'blocked') throw contentBlock();
+ if (outcome === 'outage') throw Object.assign(new Error(`${modelId} upstream 503`), { status: 503 });
+ return {
+ content: [{ type: 'text', text: `answer from ${modelId}` }],
+ finishReason: 'stop',
+ usage: { inputTokens: 3, outputTokens: 2 },
+ ...(outcome === 'refusal' ? { providerMetadata: { anthropic: { stopReason: 'refusal' } } } : {}),
+ };
+ }) as any);
+}
+
+const ask = () => chat({ model: PRIMARY, messages: [{ role: 'user', content: 'hello' }] });
+
+let warn: ReturnType<typeof spyOn>;
+beforeEach(() => {
+ resetGateway();
+ attempts = [];
+ __resetChatFallbackHopNoticeForTests();
+ warn = spyOn(console, 'warn').mockImplementation(() => {});
+});
+afterEach(() => {
+ __setGenerateTextTransportForTests(null);
+ warn.mockRestore();
+ resetGateway();
+});
+
+describe('chatWithFallback onRefusal', () => {
+ const result = (model: string, stopReason: ChatResult['stopReason']): ChatResult =>
+ ({ text: `from ${model}`, blocks: [], stopReason, usage: { input_tokens: 1, output_tokens: 1, cache_read_tokens: 0, cache_creation_tokens: 0 }, model, providerId: model.split(':')[0]! });
+
+ test('false returns a structural refusal instead of sending it on', async () => {
+ const seen: string[] = [];
+ const out = await chatWithFallback({ messages: [] }, PRIMARY, [FALLBACK], async (o) => { seen.push(o.model!); return result(o.model!, 'refusal'); }, { onRefusal: false });
+ expect(seen).toEqual([PRIMARY]);
+ expect(out.stopReason).toBe('refusal');
+ expect(out.fallbackFrom).toBeUndefined();
+ });
+
+ test('false throws a provider content block instead of sending it on', async () => {
+ const seen: string[] = [];
+ await expect(chatWithFallback({ messages: [] }, PRIMARY, [FALLBACK], async (o) => { seen.push(o.model!); throw contentBlock(); }, { onRefusal: false }))
+ .rejects.toThrow('blocked');
+ expect(seen).toEqual([PRIMARY]);
+ });
+
+ test('false still falls back on an outage', async () => {
+ const seen: string[] = [];
+ const out = await chatWithFallback({ messages: [] }, PRIMARY, [FALLBACK], async (o) => {
+ seen.push(o.model!);
+ if (o.model === PRIMARY) throw Object.assign(new Error('upstream 503'), { status: 503 });
+ return result(o.model!, 'end');
+ }, { onRefusal: false });
+ expect(seen).toEqual([PRIMARY, FALLBACK]);
+ expect(out.model).toBe(FALLBACK);
+ });
+
+ test('the default (true) keeps falling back on refusals', async () => {
+ const seen: string[] = [];
+ await chatWithFallback({ messages: [] }, PRIMARY, [FALLBACK], async (o) => { seen.push(o.model!); return result(o.model!, o.model === PRIMARY ? 'refusal' : 'end'); });
+ expect(seen).toEqual([PRIMARY, FALLBACK]);
+ });
+});
+
+describe('chat_fallback_on_refusal through the real loader', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);
+ afterAll(async () => { await engine.disconnect(); });
+
+ function home(fileOnRefusal?: boolean): string {
+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-on-refusal-'));
+ mkdirSync(join(dir, '.gbrain'), { recursive: true });
+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify({
+ engine: 'pglite', database_path: join(dir, 'brain.pglite'), chat_model: PRIMARY, chat_fallback_chain: [FALLBACK],
+ ...(fileOnRefusal !== undefined ? { chat_fallback_on_refusal: fileOnRefusal } : {}),
+ }));
+ return dir;
+ }
+
+ interface PlaneCase { name: string; env?: string; file?: boolean; db?: string; fallsBack: boolean }
+ const cases: PlaneCase[] = [
+ { name: 'unset (default true)', fallsBack: true },
+ { name: 'DB false', db: 'false', fallsBack: false },
+ { name: 'config.json false', file: false, fallsBack: false },
+ { name: 'GBRAIN_CHAT_FALLBACK_ON_REFUSAL=false', env: 'false', fallsBack: false },
+ { name: 'env true over config.json false', env: 'true', file: false, fallsBack: true },
+ { name: 'env off over DB true', env: 'off', db: 'true', fallsBack: false },
+ { name: 'config.json true over DB false', file: true, db: 'false', fallsBack: true },
+ ];
+
+ for (const outcome of ['refusal', 'blocked'] as const) {
+ test.each(cases)(`${outcome}: $name`, async ({ env, file, db, fallsBack }) => {
+ if (db === undefined) await engine.unsetConfig('chat_fallback_on_refusal');
+ else await engine.setConfig('chat_fallback_on_refusal', db);
+ _resetDbPlaneMergeMemoForTests();
+ await withEnv({
+ GBRAIN_HOME: home(file), GBRAIN_CHAT_FALLBACK_ON_REFUSAL: env, GBRAIN_CHAT_FALLBACK_CHAIN: undefined,
+ GBRAIN_CHAT_MODEL: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined, OPENAI_API_KEY: 'fake-openai',
+ }, async () => {
+ const merged = await loadConfigWithEngine(engine, loadConfig());
+ configureGateway(buildGatewayConfig(merged!));
+ installTransport({ 'claude-sonnet-4-6': outcome });
+ if (fallsBack) {
+ const out = await ask();
+ expect(out.model).toBe(FALLBACK);
+ expect(attempts).toEqual(['claude-sonnet-4-6', 'gpt-5.6-luna']);
+ } else {
+ if (outcome === 'refusal') expect((await ask()).stopReason).toBe('refusal');
+ else await expect(ask()).rejects.toThrow();
+ expect(attempts).toEqual(['claude-sonnet-4-6']);
+ }
+ });
+ });
+ }
+});
+
+describe('first-hop notice', () => {
+ test('the first hop of a process queues one chat_fallback_hop notice naming both models', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: { OPENAI_API_KEY: 'fake-openai' } });
+ installTransport({ 'claude-sonnet-4-6': 'outage' });
+ await ask();
+ await ask();
+ const queued = takeChatFallbackHopNotices();
+ expect(queued).toHaveLength(1);
+ expect(queued[0]!.code).toBe('chat_fallback_hop');
+ expect(queued[0]!.kind).toBe('safety');
+ expect(queued[0]!.why).toContain(PRIMARY);
+ expect(queued[0]!.why).toContain(FALLBACK);
+ expect(queued[0]!.fix?.argv).toEqual(['gbrain', 'doctor', '--only', 'chat_fallback_chain', '--json']);
+ await ask();
+ expect(takeChatFallbackHopNotices()).toEqual([]);
+ expect(attempts).toEqual(['claude-sonnet-4-6', 'gpt-5.6-luna', 'claude-sonnet-4-6', 'gpt-5.6-luna', 'claude-sonnet-4-6', 'gpt-5.6-luna']);
+ });
+
+ test('a refusal hop says refused content went to the next provider', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: { OPENAI_API_KEY: 'fake-openai' } });
+ installTransport({ 'claude-sonnet-4-6': 'refusal' });
+ await ask();
+ const [notice] = takeChatFallbackHopNotices();
+ expect(notice!.why).toContain('refused it');
+ expect(notice!.why).toContain('chat_fallback_on_refusal false');
+ });
+
+ test('no hop, no notice', async () => {
+ configureGateway({ chat_model: PRIMARY, chat_fallback_chain: [FALLBACK], env: { OPENAI_API_KEY: 'fake-openai' } });
+ installTransport({});
+ await ask();
+ expect(takeChatFallbackHopNotices()).toEqual([]);
+ });
+});