Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(doctor,notices): chat_fallback_chain check and the behavior_changes disclosure
garrytan96a0b52a61f5
diff --git a/.github/workflows/persistence-validation.yml b/.github/workflows/persistence-validation.ymlindex f603f30ee1..808525caeb 100644--- a/.github/workflows/persistence-validation.yml+++ b/.github/workflows/persistence-validation.yml@@ -206,6 +206,7 @@ jobs:case "$SHARD" in1) files=(test/attribution-backfill-history.test.ts+ test/behavior-change-notice.test.tstest/colon-slug-windows-5032.test.tstest/decide/conflict-proposals-managed.test.tstest/declared-lineage-visibility.test.tsdiff --git a/src/cli.ts b/src/cli.tsindex ab89fce006..a8396d1fae 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -2879,6 +2879,16 @@ async function completeEngineStartup(engine: BrainEngine): Promise<void> {} catch {// Non-fatal. Pre-v39 brains may not have a usable config table yet.}++ // The one-time behavior-change disclosure on the CLI channel (stderr). `serve`+ // delivers it per MCP channel; `doctor` reads it without marking it shown.+ if (dispatchedCommand !== 'serve' && dispatchedCommand !== 'doctor') {+ try {+ const { takeLocalBehaviorNotice } = await import('./core/behavior-change-notice.ts');+ const notice = await takeLocalBehaviorNotice(engine, 'cli', { cfg: MERGED_CONFIG_BY_ENGINE.get(engine) ?? config });+ if (notice) writeCliNotice(notice);+ } catch { /* a disclosure never breaks a command */ }+ }}/** CLI-only usage examples appended to `gbrain <command> --help`. */diff --git a/src/commands/doctor/checks/behavior-changes.ts b/src/commands/doctor/checks/behavior-changes.tsnew file mode 100644index 0000000000..cc357d8db6--- /dev/null+++ b/src/commands/doctor/checks/behavior-changes.ts@@ -0,0 +1,52 @@+/**+ * `behavior_changes` doctor check: the one-time `behavior_changes` safety+ * notice, readable again (src/core/behavior-change-notice.ts). Read-only: it+ * neither records the brain's baseline nor writes a shown marker, so the+ * notice itself is still delivered once per channel. Always `ok`: the changes+ * are on by design and the fix is the optional chain-removal guidance.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import { loadConfig, type GBrainConfig } from '../../../core/config.ts';+import {+ BEHAVIOR_NOTICE_SINCE,+ behaviorBrainKey,+ behaviorChangesNotice,+ behaviorNoticeShown,+ brainPredatesRelease,+ chainDisclosure,+ currentBrainId,+} from '../../../core/behavior-change-notice.ts';+import type { Check } from '../../doctor.ts';+import { checkError } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';+++export async function checkBehaviorChanges(engine: BrainEngine | null, opts: { cfg?: GBrainConfig | null; brainKey?: string } = {}): Promise<Check> {+ try {+ let cfg = opts.cfg;+ if (cfg === undefined) { try { cfg = loadConfig(); } catch { cfg = null; } }+ const brainKey = opts.brainKey ?? behaviorBrainKey(cfg, await currentBrainId());+ if (!(await brainPredatesRelease(engine, brainKey, { persist: false }))) {+ return { name: 'behavior_changes', status: 'ok', message: `Nothing to disclose: this brain is a fresh install at v${BEHAVIOR_NOTICE_SINCE} or later, so the one-time behavior-change notice does not apply.` };+ }+ const notice = behaviorChangesNotice(await chainDisclosure(engine, cfg));+ return {+ name: 'behavior_changes', status: 'ok', message: notice.why, ...(notice.fix ? { fix: notice.fix } : {}),+ details: { since: BEHAVIOR_NOTICE_SINCE, shown: { cli: behaviorNoticeShown(brainKey, 'cli'), stdio: behaviorNoticeShown(brainKey, 'stdio') } },+ };+ } catch (e) {+ return checkError('behavior_changes', 'read the behavior-change disclosure', e);+ }+}++async function runBehaviorChanges(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ checks.push(await checkBehaviorChanges(connectedEngine(ctx)));+ return checks;+}++export const behaviorChangesEntry: DoctorEntry = {+ name: 'behavior_changes',+ emits: ['behavior_changes'],+ run: runBehaviorChanges,+};diff --git a/src/commands/doctor/checks/chat-fallback.ts b/src/commands/doctor/checks/chat-fallback.tsnew file mode 100644index 0000000000..6cc1ac21e2--- /dev/null+++ b/src/commands/doctor/checks/chat-fallback.ts@@ -0,0 +1,144 @@+/**+ * `chat_fallback_chain` doctor check: which chain `chat()` walks, the config+ * plane it comes from (env `GBRAIN_CHAT_FALLBACK_CHAIN` > config.json > DB),+ * every shadowed value, the providers that receive traffic, and whether it+ * also falls back on refusals (`chat_fallback_on_refusal`).+ *+ * An active, healthy chain is an informational `ok` whose optional `fix` is+ * the per-plane removal guidance (`ask_user` or `tell_user_to_run`, never+ * `run`). A malformed entry or plane value, a provider with no credential+ * present, or an unpriced model under a user-set cost cap is a `warn` with a+ * cause-specific fix. Presence checks only: no network, subprocess or+ * inference call (src/core/ai/chat-fallback-planes.ts).+ *+ * The remote report (`run_doctor`) says only that a chain is configured and+ * how many problems it has; entries and providers stay on the brain host.+ */+import type { BrainEngine } from '../../../core/engine.ts';+import type { Action } from '../../../core/agent-output.ts';+import { loadConfig, loadConfigWithEngine, type GBrainConfig } from '../../../core/config.ts';+import { mergedProviderEnv } from '../../../core/ai/provider-env.ts';+import { loadPricingOverrides } from '../../../core/budget/budget-tracker.ts';+import { noPricingFix, noPricingGuidance } from '../../../core/budget/no-pricing.ts';+import {+ USER_CHAT_CAP_KEYS,+ diagnoseChatFallbackEntry,+ readChatFallbackPlanes,+ type ChatFallbackPlane,+ type ChatFallbackPlanes,+ type EntryDiagnosis,+ CHAT_FALLBACK_PLANE_LABEL as PLANE_LABEL,+ chatFallbackRemovalFix,+} from '../../../core/ai/chat-fallback-planes.ts';+import type { Check } from '../../doctor.ts';+import { checkError, doctorVerify } from '../check-fix.ts';+import { connectedEngine, type DoctorContext, type DoctorEntry } from '../context.ts';++const NAME = 'chat_fallback_chain';+const DOCS = 'docs/guides/chat-fallback.md';++export { chatFallbackRemovalFix };++function credentialFix(d: EntryDiagnosis, plane: ChatFallbackPlane, filePath: string): Action {+ return {+ consent: ['credentials'], actor: 'user', requires_exclusive: false, verify: doctorVerify(NAME), docs: DOCS,+ why: `${d.detail} The chain would hand ${d.entry} a request it cannot authenticate. Provide the credential, or remove the entry (${PLANE_LABEL[plane]}).`,+ user_message: d.provider === 'claude-cli'+ ? `The fallback model ${d.entry} runs through the claude CLI, which is not installed here. Install and log in to Claude Code, or set GBRAIN_CLAUDE_CLI_BIN, or remove that entry.`+ : `The fallback model ${d.entry} needs ${d.credential}. Set it where gbrain runs, or remove that entry from ${plane === 'file' ? filePath : PLANE_LABEL[plane]}.`,+ };+}++async function userCapKeys(engine: BrainEngine | null, cfg: GBrainConfig | null): Promise<string[]> {+ const found: string[] = [];+ for (const key of USER_CHAT_CAP_KEYS) {+ const leaf = key.startsWith('cycle.') ? key.slice('cycle.'.length) : null;+ if (leaf && cfg?.cycle?.[leaf] !== undefined) { found.push(key); continue; }+ if (!engine) continue;+ try { if (await engine.getConfig(key)) found.push(key); } catch { /* unreadable: not a cap */ }+ }+ return found;+}++function chainSummary(planes: ChatFallbackPlanes, diags: EntryDiagnosis[]): Record<string, unknown> {+ return {+ plane: planes.effective?.plane ?? null,+ chain: planes.effective?.chain ?? [],+ providers: [...new Set(diags.map(d => d.provider).filter((p): p is string => !!p))],+ shadowed: planes.shadowed,+ malformed: planes.malformed,+ on_refusal: planes.onRefusal,+ entries: diags,+ };+}++export async function checkChatFallbackChain(engine: BrainEngine | null, opts: { remote?: boolean } = {}): Promise<Check> {+ try {+ const planes = await readChatFallbackPlanes(engine);+ if (!planes.effective && planes.malformed.length === 0) {+ return { name: 'chat_fallback_chain', status: 'ok', message: 'No chat_fallback_chain is set: every chat call uses only its own model.' };+ }+ let cfg: GBrainConfig | null = null;+ try { cfg = loadConfig(); } catch { cfg = null; }+ if (engine && cfg) { try { cfg = await loadConfigWithEngine(engine, cfg) ?? cfg; } catch { /* file/env only */ } }+ const env = mergedProviderEnv(cfg, process.env);+ const pricingOverrides = engine ? await loadPricingOverrides(engine) : undefined;+ const caps = await userCapKeys(engine, cfg);+ const diags = (planes.effective?.chain ?? []).map(entry => diagnoseChatFallbackEntry(entry, { env, pricingOverrides, userCapKeys: caps }));+ const problems = diags.filter(d => d.problem);+ const plane = planes.effective?.plane;++ if (opts.remote) {+ const count = problems.length + planes.malformed.length;+ return {+ name: 'chat_fallback_chain', status: count > 0 ? 'warn' : 'ok',+ message: `A chat fallback chain is configured on the brain host${count > 0 ? ` and has ${count} problem(s)` : ''}. Its entries and the providers it reaches stay on the host; the host operator runs gbrain doctor --only chat_fallback_chain there.`,+ fix: { argv: ['gbrain', 'doctor', '--only', NAME], consent: [], actor: 'host_admin', requires_exclusive: false, docs: DOCS,+ why: 'Lists the chain, its config plane, the providers it reaches and per-plane removal guidance on the brain host; read-only.' },+ };+ }++ const details = chainSummary(planes, diags);+ const where = planes.malformed[0];+ if (where) {+ return { name: 'chat_fallback_chain', status: 'warn', details,+ message: `chat_fallback_chain cannot be read: ${where.error}.${planes.effective ? ` The effective chain comes from ${PLANE_LABEL[planes.effective.plane]}.` : ' No chain is walked while this value is set.'}`,+ fix: chatFallbackRemovalFix(where.plane, planes.filePath, 'Fix the value (provider:model entries, comma-separated or a JSON list) or remove it.') };+ }+ const first = problems[0];+ if (first && plane) {+ const fix = first.problem === 'no_credential' ? credentialFix(first, plane, planes.filePath)+ : first.problem === 'unpriced_under_cap' ? noPricingFix(noPricingGuidance(first.entry, 'chat'), 'cli')+ : chatFallbackRemovalFix(plane, planes.filePath, `Fix or remove the entry "${first.entry}".`);+ return { name: 'chat_fallback_chain', status: 'warn', details, fix,+ message: `chat_fallback_chain has ${problems.length} problem entr${problems.length === 1 ? 'y' : 'ies'}: ${problems.map(p => `${p.entry} (${p.problem})`).join(', ')}. ${first.detail}` };+ }++ const effective = planes.effective!;+ const providers = details.providers as string[];+ const shadowed = planes.shadowed.length+ ? ` Shadowed (ignored while this is set): ${planes.shadowed.map(s => `${s.plane} [${s.chain.join(', ')}]`).join('; ')}.` : '';+ const refusal = planes.onRefusal.value+ ? 'It falls back on errors and on refusals, so content one provider refused is sent to the next (chat_fallback_on_refusal=false stops that).'+ : `It falls back on errors only: chat_fallback_on_refusal=false (${planes.onRefusal.plane}).`;+ return {+ name: 'chat_fallback_chain', status: 'ok', details,+ message: `chat_fallback_chain is active from ${PLANE_LABEL[effective.plane]}: ${effective.chain.join(' -> ')}. Providers that receive traffic when a call's own model fails: ${providers.join(', ')}. ${refusal}${shadowed} Removal is optional; ask the user.`,+ fix: chatFallbackRemovalFix(effective.plane, planes.filePath),+ };+ } catch (e) {+ return checkError('chat_fallback_chain', 'read chat_fallback_chain', e);+ }+}++async function runChatFallbackChain(ctx: DoctorContext): Promise<Check[]> {+ const checks: Check[] = [];+ checks.push(await checkChatFallbackChain(connectedEngine(ctx)));+ return checks;+}++export const chatFallbackChainEntry: DoctorEntry = {+ name: 'chat_fallback_chain',+ emits: ['chat_fallback_chain'],+ run: runChatFallbackChain,+};diff --git a/src/commands/doctor/registry.ts b/src/commands/doctor/registry.tsindex a35e40804e..1e54ec8fef 100644--- a/src/commands/doctor/registry.ts+++ b/src/commands/doctor/registry.ts@@ -93,6 +93,8 @@ import { plannerStatsEntry } from './checks/planner-stats.ts';import { revisionBackfillEntry } from './checks/revision-backfill.ts';import { harnessWiringDoctorEntry } from './checks/harness-wiring.ts';import { agentContractEntry } from './checks/agent-contract.ts';+import { chatFallbackChainEntry } from './checks/chat-fallback.ts';+import { behaviorChangesEntry } from './checks/behavior-changes.ts';import { STOP_DOCTOR, type DoctorContext, type DoctorEntry } from './context.ts';import type { Check } from '../doctor.ts';import { infoCheck } from './check-fix.ts';@@ -129,6 +131,8 @@ export const DOCTOR_CHECK_REGISTRY: readonly DoctorEntry[] = [embeddingQueryPrefixEntry,embeddingColumnRegistryEntry,embeddingEnvOverrideEntry,+ chatFallbackChainEntry,+ behaviorChangesEntry,graphCoverageEntry,orphanRatioEntry,staleMentionsEntry,diff --git a/src/commands/doctor/report-remote.ts b/src/commands/doctor/report-remote.tsindex 80025746ea..f2de89a2df 100644--- a/src/commands/doctor/report-remote.ts+++ b/src/commands/doctor/report-remote.ts@@ -20,6 +20,7 @@ import { resolveHoursEnv } from '../../core/env-number.ts';import { schemaVersionHealth } from '../../core/schema-version-health.ts';import { checkProjectionReadiness } from './checks/projection-readiness.ts';import { remoteUnlinkedFactsCheck } from './checks/unlinked-facts.ts';+import { checkChatFallbackChain } from './checks/chat-fallback.ts';import { resolveExcludePrivatePages } from '../../core/search/private-visibility.ts';import {type Check,@@ -388,6 +389,7 @@ export async function doctorReportRemote(// search.reranker.enabled FIRST so absence-of-failures means different// things when reranker is on vs off.checks.push(await checkRerankerHealth(engine));+ checks.push(await checkChatFallbackChain(engine, { remote: opts.remote !== false }));// 9a. v0.40.4 graph_signals_coverage: when graph_signals is enabled// (via mode bundle default or explicit config override), surfacediff --git a/src/commands/init.ts b/src/commands/init.tsindex 7c42aaa3d0..32cf1542f5 100644--- a/src/commands/init.ts+++ b/src/commands/init.ts@@ -1242,6 +1242,7 @@ export async function initPGLite(opts: {preserveConversionConfig(false);saveConfig(config);if (freshContentDatabase) (await import('./migrations/fresh-install.ts')).recordFreshInstallMigrations();+ if (freshContentDatabase) { const n = await import('../core/behavior-change-notice.ts'); n.stampFreshBrainBaseline(n.behaviorBrainKey(config)); }const contentReceipt = await setupSharedBrainContent({ engine, config, sourceId: await resolveSourceId(engine, undefined), remote: false, dryRun: false, logger: { info: console.error, warn: console.error, error: console.error } }, {...opts.content, fresh: freshContentDatabase,...(process.env.GBRAIN_IN_AGENT_SETUP === '1' && !opts.content?.root ? { root: join(dirname(configPath()), '..', 'memory') } : {}),@@ -1578,6 +1579,7 @@ export async function initPostgresCore(opts: {preserveConversionConfig(false);saveConfig(config);if (freshContentDatabase) (await import('./migrations/fresh-install.ts')).recordFreshInstallMigrations();+ if (freshContentDatabase) { const n = await import('../core/behavior-change-notice.ts'); n.stampFreshBrainBaseline(n.behaviorBrainKey(config)); }const contentReceipt = await setupSharedBrainContent({ engine, config, sourceId: await resolveSourceId(engine, undefined), remote: false, dryRun: false, logger: { info: console.error, warn: console.error, error: console.error } }, { ...opts.content, fresh: freshContentDatabase });if (!opts.jsonOutput) console.error(`[init] Content: ${contentReceipt.root ?? contentReceipt.repository_kind} (${contentReceipt.repository_kind}; ${contentReceipt.status}). ${contentReceipt.pending_actions.join(' ')}`);console.log('Config saved to ~/.gbrain/config.json');diff --git a/src/core/ai/chat-fallback-planes.ts b/src/core/ai/chat-fallback-planes.tsnew file mode 100644index 0000000000..c68d64d17a--- /dev/null+++ b/src/core/ai/chat-fallback-planes.ts@@ -0,0 +1,192 @@+/**+ * Where the effective `chat_fallback_chain` comes from, and what each entry+ * needs, read without any network call, subprocess or inference.+ *+ * `readChatFallbackPlanes` reads the three planes `loadConfig` /+ * `loadConfigWithEngine` merge (env `GBRAIN_CHAT_FALLBACK_CHAIN` > the+ * config.json key > the DB `config` row) and names the winner, every+ * shadowed value and any plane whose value cannot be read as a chain. The+ * same precedence decides `chat_fallback_on_refusal`.+ *+ * `diagnoseChatFallbackEntry` checks one entry by presence only: it parses+ * as `provider:model`, the provider is known and serves chat, the provider's+ * own credential is present (its env keys, a recipe's `authPresent`, or the+ * claude CLI binary for `claude-cli`; never a login probe), and the model is+ * priced when a user-set cost cap would otherwise refuse it.+ *+ * Consumers: the `chat_fallback_chain` doctor check and the one-time+ * `behavior_changes` safety notice.+ */+import { existsSync } from 'node:fs';+import { configPath, isEnvDisabled, loadConfigFileOnly } from '../config.ts';+import { parseDbChatFallbackChain } from '../config-db-merge.ts';+import { normalizeChatFallbackChain } from './chat-fallback.ts';+import { resolveRecipe } from './model-resolver.ts';+import { isModelPriceable, type PricingOverrides } from '../budget/reservation-cost.ts';+import type { Recipe } from './types.ts';+import type { Action } from '../agent-output.ts';++export type ChatFallbackPlane = 'env' | 'file' | 'db';++export const CHAT_FALLBACK_ENV = 'GBRAIN_CHAT_FALLBACK_CHAIN';+export const CHAT_FALLBACK_ON_REFUSAL_ENV = 'GBRAIN_CHAT_FALLBACK_ON_REFUSAL';++/**+ * Config keys that set a USD cap on chat work. A BudgetTracker built from one+ * runs with `capSource: 'user'`, so an unpriced model under it is refused+ * (`no_pricing`) instead of running unmetered.+ */+export const USER_CHAT_CAP_KEYS: readonly string[] = [+ 'cycle.extract_atoms.budget_usd',+ 'facts.drain_budget_usd',+ 'facts.drain_daily_budget_usd',+ 'chronicle.job_budget_usd',+ 'takes.bootstrap_budget_usd',+];++export interface ChatFallbackPlanes {+ /** The chain chat() walks, and the plane it comes from; undefined when no plane sets one. */+ effective?: { plane: ChatFallbackPlane; chain: string[] };+ /** Lower-precedence planes that also set a chain (ignored while the winner is set). */+ shadowed: Array<{ plane: ChatFallbackPlane; chain: string[] }>;+ /** Planes whose value cannot be read as a chain. A malformed file value still shadows the DB plane. */+ malformed: Array<{ plane: ChatFallbackPlane; error: string }>;+ onRefusal: { value: boolean; plane: ChatFallbackPlane | 'default' };+ /** config.json path, for file-plane removal guidance. */+ filePath: string;+}++export interface ConfigReader {+ getConfig(key: string): Promise<string | null | undefined>;+}++/** Read all three planes. `db` null (no engine, `--fast`) reads env and file only. Never throws. */+export async function readChatFallbackPlanes(db: ConfigReader | null): Promise<ChatFallbackPlanes> {+ const out: ChatFallbackPlanes = { shadowed: [], malformed: [], onRefusal: { value: true, plane: 'default' }, filePath: configPath() };+ const set: Array<{ plane: ChatFallbackPlane; chain: string[] }> = [];+ // The first plane that speaks wins, even when its value yields no chain:+ // loadConfig keeps it, so the DB merge never fills in under it.+ let winner: ChatFallbackPlane | null = null;++ const envRaw = process.env[CHAT_FALLBACK_ENV];+ if (envRaw) {+ winner = 'env';+ const chain = normalizeChatFallbackChain(envRaw);+ if (chain) set.push({ plane: 'env', chain });+ else out.malformed.push({ plane: 'env', error: `${CHAT_FALLBACK_ENV} is set but names no model` });+ }++ let file: Record<string, unknown> | null = null;+ try { file = loadConfigFileOnly() as unknown as Record<string, unknown> | null; } catch { file = null; }+ const fileRaw = file?.chat_fallback_chain;+ if (fileRaw !== undefined) {+ winner ??= 'file';+ const chain = normalizeChatFallbackChain(fileRaw);+ if (chain) set.push({ plane: 'file', chain });+ else out.malformed.push({ plane: 'file', error: `chat_fallback_chain in ${out.filePath} is not a list of provider:model strings` });+ }++ let dbRaw: string | null | undefined;+ let dbOnRefusal: string | null | undefined;+ if (db) {+ try { dbRaw = await db.getConfig('chat_fallback_chain'); } catch { dbRaw = undefined; }+ try { dbOnRefusal = await db.getConfig('chat_fallback_on_refusal'); } catch { dbOnRefusal = undefined; }+ }+ if (dbRaw) {+ const parsed = parseDbChatFallbackChain(dbRaw);+ if (parsed.chain) { winner ??= 'db'; set.push({ plane: 'db', chain: parsed.chain }); }+ else if (parsed.error) out.malformed.push({ plane: 'db', error: `the DB chat_fallback_chain value ${parsed.error}` });+ }++ out.effective = set.find(s => s.plane === winner);+ out.shadowed = set.filter(s => s.plane !== winner);++ const envRefusal = process.env[CHAT_FALLBACK_ON_REFUSAL_ENV]?.trim();+ const fileRefusal = file?.chat_fallback_on_refusal;+ if (envRefusal) out.onRefusal = { value: !isEnvDisabled(envRefusal), plane: 'env' };+ else if (typeof fileRefusal === 'boolean') out.onRefusal = { value: fileRefusal, plane: 'file' };+ else if (dbOnRefusal === 'true' || dbOnRefusal === 'false') out.onRefusal = { value: dbOnRefusal === 'true', plane: 'db' };+ return out;+}++export type EntryProblem = 'malformed' | 'unknown_provider' | 'no_chat' | 'no_credential' | 'unpriced_under_cap';++export interface EntryDiagnosis {+ entry: string;+ provider?: string;+ /** What the provider authenticates with (env key names or the claude CLI binary); never a value. */+ credential?: string;+ problem?: EntryProblem;+ detail?: string;+}++function claudeCliBinaryPresent(env: Record<string, string | undefined>): boolean {+ const bin = env.GBRAIN_CLAUDE_CLI_BIN ?? process.env.GBRAIN_CLAUDE_CLI_BIN ?? 'claude';+ if (bin.includes('/')) return existsSync(bin);+ try { return !!Bun.which(bin, { PATH: process.env.PATH ?? '' }); } catch { return false; }+}++function credentialOf(recipe: Recipe, env: Record<string, string | undefined>): { present: boolean; how: string } {+ if (recipe.implementation === 'claude-cli') {+ return { present: claudeCliBinaryPresent(env), how: 'the claude CLI binary on PATH or GBRAIN_CLAUDE_CLI_BIN (it keeps its own login)' };+ }+ const required = recipe.auth_env?.required ?? [];+ const how = required.length ? required.join(', ') : 'no credential (local endpoint)';+ if (recipe.authPresent) return { present: recipe.authPresent(env), how };+ return { present: required.every(k => !!env[k]), how };+}++/** One entry, by presence only. `env` is the merged provider env (`mergedProviderEnv`). */+export function diagnoseChatFallbackEntry(+ entry: string,+ ctx: { env: Record<string, string | undefined>; pricingOverrides?: PricingOverrides; userCapKeys: readonly string[] },+): EntryDiagnosis {+ let resolved: ReturnType<typeof resolveRecipe>;+ try {+ resolved = resolveRecipe(entry);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ return /Unknown provider/.test(msg)+ ? { entry, problem: 'unknown_provider', detail: msg }+ : { entry, problem: 'malformed', detail: `${msg} Entries are provider:model, for example anthropic:claude-sonnet-4-6.` };+ }+ const { recipe } = resolved;+ if (!recipe.touchpoints.chat) return { entry, provider: recipe.id, problem: 'no_chat', detail: `${recipe.name} has no chat models.` };+ const cred = credentialOf(recipe, ctx.env);+ if (!cred.present) return { entry, provider: recipe.id, credential: cred.how, problem: 'no_credential', detail: `${recipe.name} needs ${cred.how}, which is not present.` };+ if (ctx.userCapKeys.length > 0 && !isModelPriceable(entry, 'chat', ctx.pricingOverrides)) {+ return { entry, provider: recipe.id, credential: cred.how, problem: 'unpriced_under_cap',+ detail: `gbrain has no price for ${entry}, and a cost cap the user set (${ctx.userCapKeys.join(', ')}) refuses unpriced models.` };+ }+ return { entry, provider: recipe.id, credential: cred.how };+}++export const CHAT_FALLBACK_PLANE_LABEL: Record<ChatFallbackPlane, string> = {+ env: `the ${CHAT_FALLBACK_ENV} environment variable`,+ file: 'config.json',+ db: 'the brain database (gbrain config set)',+};++/**+ * Per-plane removal guidance. Optional: the user decides. DB: the agent may+ * run `gbrain config unset` after the user agrees (`ask_user`). Env and file:+ * only the user can change them (`tell_user_to_run` / `report`), and a+ * long-lived process keeps the old value until it restarts.+ */+export function chatFallbackRemovalFix(plane: ChatFallbackPlane, filePath: string, reason = 'Removing it makes chat calls use only their own model.'): Action {+ const restart = 'A long-lived process (gbrain serve, autopilot, a worker) keeps the old value until it restarts.';+ const base = { consent: ['destructive' as const], requires_exclusive: false, verify: { argv: ['gbrain', 'doctor', '--only', 'chat_fallback_chain', '--json'] }, docs: 'docs/guides/chat-fallback.md' };+ if (plane === 'db') {+ return { ...base, argv: ['gbrain', 'config', 'unset', 'chat_fallback_chain'], actor: 'agent',+ why: `The chain is stored in the brain database. ${reason} Optional: ask the user first. ${restart}`,+ user_message: 'A chat fallback chain is stored in your brain. Do you want it removed (gbrain config unset chat_fallback_chain)? Chat calls would then use only their own model.' };+ }+ if (plane === 'env') {+ return { ...base, argv: ['unset', CHAT_FALLBACK_ENV], actor: 'user',+ why: `The chain comes from ${CHAT_FALLBACK_ENV}. ${reason} Only the user can remove it from the environment that launches gbrain (shell profile, service unit, MCP client config). ${restart}`,+ user_message: `To remove the chat fallback chain, delete ${CHAT_FALLBACK_ENV} from the environment that starts gbrain, then restart any running gbrain serve or autopilot.` };+ }+ return { ...base, actor: 'user',+ why: `The chain is the chat_fallback_chain key in ${filePath}. ${reason} Only the user edits that file. ${restart}`,+ user_message: `To remove the chat fallback chain, delete the "chat_fallback_chain" key from ${filePath}, then restart any running gbrain serve or autopilot.` };+}diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsnew file mode 100644index 0000000000..b25518823c--- /dev/null+++ b/src/core/behavior-change-notice.ts@@ -0,0 +1,337 @@+/**+ * One-time disclosure of four behavior changes an upgrade turns on (safety+ * notice `behavior_changes`, agent operator contract v1). Disclosure only:+ * every change stays on, nothing waits for an answer, and delivery is never+ * recorded as the user's consent.+ *+ * (a) a non-empty `chat_fallback_chain` is walked on every non-pinned chat+ * call, on errors and (unless `chat_fallback_on_refusal=false`) on+ * refusals: the entries, the providers that receive traffic and the+ * per-plane removal guidance. Only when a chain is set; a remote+ * (HTTP) caller sees only that a chain is configured.+ * (b) managed-brain autopilot lint writes its repairs+ * (`gbrain config set cycle.lint_fix false` opts out).+ * (c) transcript re-ingest makes smaller parts and re-embeds once+ * (`TRANSCRIPT_REINGEST_MULTIPLIER`).+ * (d) the mention linker rebuilds its resume state once.+ *+ * Identity: notice id (`behavior_changes@<BEHAVIOR_NOTICE_SINCE>`) × brain ×+ * channel, plus the authenticated client on HTTP. Eligibility: a brain that+ * predates BEHAVIOR_NOTICE_SINCE. Its baseline (the first gbrain version+ * that saw it, `0` when it already existed) is recorded once under+ * GBRAIN_HOME: `gbrain init` stamps a database it creates with this version;+ * otherwise the first look decides from the recorded upgrade history+ * (`upgrade-state.json` `from` below the release) or the brain's own+ * creation time (its oldest `sources.created_at` more than+ * FRESH_BRAIN_GRACE_MS ago). A fresh install sees no notice.+ *+ * Markers:+ * - CLI and stdio: one file per notice × brain × channel under+ * GBRAIN_HOME/notices/behavior-changes/, created exclusively (`wx`), so+ * concurrent processes deliver it once. A home that cannot be written+ * still gets the notice (once per process).+ * - HTTP: one bounded `config` row in the brain DB+ * (`notices.behavior_changes.http`: the notice id and up to+ * HTTP_SHOWN_CAP client ids, oldest dropped first). No migration: the+ * row reuses the key/value table every brain has.+ * `gbrain doctor --only behavior_changes` reads the disclosure again and+ * writes nothing.+ */+import { createHash } from 'node:crypto';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import type { BrainEngine } from './engine.ts';+import type { Action, Notice } from './agent-output.ts';+import { gbrainPath, type GBrainConfig } from './config.ts';+import { VERSION } from '../version.ts';+import {+ CHAT_FALLBACK_PLANE_LABEL,+ chatFallbackRemovalFix,+ diagnoseChatFallbackEntry,+ readChatFallbackPlanes,+ type ChatFallbackPlane,+} from './ai/chat-fallback-planes.ts';+import { mergedProviderEnv } from './ai/provider-env.ts';++/** The first release that carries this notice. Set once, here, at ship time. */+export const BEHAVIOR_NOTICE_SINCE: string = VERSION;+/** The measured re-ingest multiplier for (c), as prose. */+export const TRANSCRIPT_REINGEST_MULTIPLIER = 'about 6x';+export const BEHAVIOR_NOTICE_CODE = 'behavior_changes';+export const BEHAVIOR_NOTICE_ID = `${BEHAVIOR_NOTICE_CODE}@${BEHAVIOR_NOTICE_SINCE}`;+/** A brain created this recently, with no recorded baseline, counts as a fresh install. */+export const FRESH_BRAIN_GRACE_MS = 60 * 60 * 1000;+export const HTTP_SHOWN_KEY = 'notices.behavior_changes.http';+export const HTTP_SHOWN_CAP = 500;+const CLIENT_ID_MAX = 128;+/** The baseline recorded for a brain that existed before baselines were kept. */+const PREDATES = '0';++export type BehaviorChannel = 'cli' | 'stdio' | 'http';++/** Release order over every numeric segment (`0.60.65.0` style; missing segments are 0). */+export function compareReleases(a: string, b: string): number {+ const pa = a.split('.').map(n => parseInt(n, 10) || 0);+ const pb = b.split('.').map(n => parseInt(n, 10) || 0);+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {+ const d = (pa[i] ?? 0) - (pb[i] ?? 0);+ if (d !== 0) return d < 0 ? -1 : 1;+ }+ return 0;+}++function noticeDir(): string {+ return gbrainPath('notices', 'behavior-changes');+}++const safe = (s: string) => s.replace(/[^A-Za-z0-9_.-]/g, '_');++/** Brain identity under GBRAIN_HOME: the brain id plus a hash of its database location (never the location itself). */+export function behaviorBrainKey(cfg: GBrainConfig | null | undefined, brainId = 'host'): string {+ const location = cfg?.database_url ?? cfg?.database_path ?? '';+ return `${safe(brainId)}-${createHash('sha256').update(location).digest('hex').slice(0, 12)}`;+}++/** The brain id the current process routes to (`--brain`, GBRAIN_BRAIN_ID, .gbrain-mount), `host` when unresolvable. */+export async function currentBrainId(): Promise<string> {+ try {+ const { resolveBrainId } = await import('./brain-resolver.ts');+ const { getCliOptions } = await import('./cli-options.ts');+ return resolveBrainId(getCliOptions().brain);+ } catch {+ return 'host';+ }+}++// ── eligibility ─────────────────────────────────────────────────────────────++const baselinePath = (brainKey: string) => join(noticeDir(), `${brainKey}.baseline`);++function readBaseline(brainKey: string): string | null {+ try {+ const v = readFileSync(baselinePath(brainKey), 'utf8').trim();+ return /^\d+(\.\d+)*$/.test(v) ? v : null;+ } catch {+ return null;+ }+}++/** Record a baseline; `exclusive` keeps an existing one (first writer wins). Never throws. */+function writeBaseline(brainKey: string, since: string, exclusive: boolean): void {+ try {+ mkdirSync(noticeDir(), { recursive: true });+ writeFileSync(baselinePath(brainKey), `${since}\n`, { mode: 0o600, flag: exclusive ? 'wx' : 'w' });+ } catch { /* unwritable home or a concurrent first writer: eligibility is re-derived next time */ }+}++/** `gbrain init` created this brain's database: it is a fresh install at this version. */+export function stampFreshBrainBaseline(brainKey: string): void {+ writeBaseline(brainKey, VERSION, false);+}++/** `gbrain upgrade` recorded an upgrade from a release older than this notice. */+function upgradedAcrossRelease(): boolean {+ try {+ const state = JSON.parse(readFileSync(gbrainPath('upgrade-state.json'), 'utf8')) as { last_upgrade?: { from?: unknown } };+ const from = state.last_upgrade?.from;+ return typeof from === 'string' && compareReleases(from, BEHAVIOR_NOTICE_SINCE) < 0;+ } catch {+ return false;+ }+}++async function brainCreatedBefore(engine: BrainEngine, cutoffMs: number): Promise<boolean> {+ try {+ const rows = await engine.executeRaw<{ at: string | Date | null }>(`SELECT MIN(created_at) AS at FROM sources`);+ const at = rows[0]?.at;+ if (at === null || at === undefined) return false;+ const ms = new Date(at).getTime();+ return Number.isFinite(ms) && ms < cutoffMs;+ } catch {+ return false;+ }+}++/**+ * Does this brain predate BEHAVIOR_NOTICE_SINCE? Reads the recorded baseline;+ * without one, derives it and (when `persist`) records it, so a fresh brain+ * stays fresh after the grace window. `persist: false` (doctor) writes nothing.+ */+export async function brainPredatesRelease(+ engine: BrainEngine | null,+ brainKey: string,+ opts: { persist: boolean; now?: number },+): Promise<boolean> {+ let since = readBaseline(brainKey);+ if (!since) {+ const now = opts.now ?? Date.now();+ const predates = upgradedAcrossRelease() || (engine !== null && await brainCreatedBefore(engine, now - FRESH_BRAIN_GRACE_MS));+ since = predates ? PREDATES : VERSION;+ if (opts.persist) {+ writeBaseline(brainKey, since, true);+ since = readBaseline(brainKey) ?? since;+ }+ }+ return compareReleases(since, BEHAVIOR_NOTICE_SINCE) < 0;+}++// ── content ─────────────────────────────────────────────────────────────────++export interface ChainDisclosure {+ plane: ChatFallbackPlane;+ entries: string[];+ providers: string[];+ onRefusal: boolean;+ filePath: string;+}++/** The effective chain as disclosed to the local owner, or null when no chain is set. Never throws. */+export async function chainDisclosure(engine: BrainEngine | null, cfg: GBrainConfig | null): Promise<ChainDisclosure | null> {+ try {+ const planes = await readChatFallbackPlanes(engine);+ if (!planes.effective) return null;+ const env = mergedProviderEnv(cfg, process.env);+ const providers = [...new Set(planes.effective.chain+ .map(entry => diagnoseChatFallbackEntry(entry, { env, userCapKeys: [] }).provider)+ .filter((p): p is string => !!p))];+ return { plane: planes.effective.plane, entries: planes.effective.chain, providers, onRefusal: planes.onRefusal.value, filePath: planes.filePath };+ } catch {+ return null;+ }+}++const DOCTOR_ARGV = ['gbrain', 'doctor', '--only', BEHAVIOR_NOTICE_CODE, '--json'];++/** The disclosure. `remote` (HTTP) names only that a chain is configured; entries and providers stay on the host. */+export function behaviorChangesNotice(chain: ChainDisclosure | null, opts: { remote?: boolean } = {}): Notice {+ const items: string[] = [];+ if (chain && opts.remote) {+ items.push('A chat fallback chain is configured on this brain host: when a chat call\'s own model fails it is retried on other models. Its entries and providers are visible to the brain host operator in gbrain doctor --only chat_fallback_chain.');+ } else if (chain) {+ items.push(`chat_fallback_chain is live (set in ${CHAT_FALLBACK_PLANE_LABEL[chain.plane]}): when a chat call's own model fails${chain.onRefusal ? ' or refuses' : ''}, gbrain retries it on ${chain.entries.join(', ')}, so ${chain.providers.length ? chain.providers.join(', ') : 'those providers'} receive that traffic. ` ++ (chain.onRefusal+ ? 'It falls back on refusals as well as errors, so content one provider refused is sent to the next; `gbrain config set chat_fallback_on_refusal false` keeps outage fallback only.'+ : 'chat_fallback_on_refusal is false, so it falls back on errors only.') ++ ' Removing the chain is optional; ask the user (gbrain doctor --only chat_fallback_chain has the per-plane steps).');+ }+ items.push('On a managed brain, autopilot\'s lint phase now writes its repairs instead of only reporting them; `gbrain config set cycle.lint_fix false` turns that off.');+ items.push(`Transcript re-ingest now splits transcripts into smaller parts (46,080-byte target, previously about 300 KB), ${TRANSCRIPT_REINGEST_MULTIPLIER} as many parts, and re-embeds each re-ingested transcript once.`);+ items.push('The mention linker rebuilds its gazetteer resume state once, so the first mention-extraction run after upgrading rescans pages.');+ const why = `gbrain v${BEHAVIOR_NOTICE_SINCE} changed ${items.length} behaviors on this brain. All stay on; this is a one-time disclosure, not a request for consent. ` ++ items.map((t, i) => `(${i + 1}) ${t}`).join(' ') ++ ' gbrain doctor --only behavior_changes shows this again.';+ const fix: Action = chain && !opts.remote+ ? chatFallbackRemovalFix(chain.plane, chain.filePath)+ : { argv: DOCTOR_ARGV, consent: [], actor: opts.remote ? 'host_admin' : 'agent', requires_exclusive: false,+ why: 'Shows this disclosure again; read-only.', docs: 'docs/guides/chat-fallback.md' };+ return { code: BEHAVIOR_NOTICE_CODE, kind: 'safety', why, fix };+}++// ── delivery ────────────────────────────────────────────────────────────────++/** notice × brain × channel (× client) already handled in this process: one look per process. */+const handled = new Set<string>();+const HANDLED_MAX = 10_000;++function markHandled(key: string): boolean {+ if (handled.has(key)) return false;+ if (handled.size >= HANDLED_MAX) handled.delete(handled.values().next().value as string);+ handled.add(key);+ return true;+}++/** Test seam: forget this process's looks. */+export function __resetBehaviorNoticeForTests(): void {+ handled.clear();+}++/** Claim the per-channel marker. `unwritable` still delivers (conservative). */+function claimMarker(brainKey: string, channel: 'cli' | 'stdio'): 'claimed' | 'shown' | 'unwritable' {+ const path = join(noticeDir(), `${safe(BEHAVIOR_NOTICE_ID)}.${brainKey}.${channel}.shown`);+ try {+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, `${new Date().toISOString()}\n`, { mode: 0o600, flag: 'wx' });+ return 'claimed';+ } catch (e) {+ return (e as NodeJS.ErrnoException)?.code === 'EEXIST' ? 'shown' : 'unwritable';+ }+}++/** Has this channel's marker been written for this brain? (doctor; read-only) */+export function behaviorNoticeShown(brainKey: string, channel: 'cli' | 'stdio'): boolean {+ try {+ readFileSync(join(noticeDir(), `${safe(BEHAVIOR_NOTICE_ID)}.${brainKey}.${channel}.shown`));+ return true;+ } catch {+ return false;+ }+}++/**+ * CLI and stdio: the notice once per notice × brain × channel, or null.+ * Never throws; a fault returns null and the next call looks again.+ */+export async function takeLocalBehaviorNotice(+ engine: BrainEngine,+ channel: 'cli' | 'stdio',+ opts: { cfg: GBrainConfig | null; brainKey?: string; now?: number },+): Promise<Notice | null> {+ let key = '';+ try {+ const brainKey = opts.brainKey ?? behaviorBrainKey(opts.cfg, await currentBrainId());+ key = `${BEHAVIOR_NOTICE_ID}|${brainKey}|${channel}`;+ if (!markHandled(key)) return null;+ if (!(await brainPredatesRelease(engine, brainKey, { persist: true, now: opts.now }))) return null;+ if (claimMarker(brainKey, channel) === 'shown') return null;+ return behaviorChangesNotice(await chainDisclosure(engine, opts.cfg));+ } catch {+ if (key) handled.delete(key);+ return null;+ }+}++interface HttpShown { id: string; clients: Record<string, string> }++function readHttpShown(raw: string | null): HttpShown {+ try {+ const v = raw ? JSON.parse(raw) as Partial<HttpShown> : null;+ if (v && v.id === BEHAVIOR_NOTICE_ID && v.clients && typeof v.clients === 'object') return { id: v.id, clients: v.clients };+ } catch { /* unreadable: start over */ }+ return { id: BEHAVIOR_NOTICE_ID, clients: {} };+}++/** Add a client, keeping the newest HTTP_SHOWN_CAP. */+export function recordHttpShown(raw: string | null, clientId: string, at: string): string {+ const shown = readHttpShown(raw);+ shown.clients[clientId] = at;+ const kept = Object.entries(shown.clients).sort((a, b) => (a[1] < b[1] ? 1 : a[1] > b[1] ? -1 : 0)).slice(0, HTTP_SHOWN_CAP);+ return JSON.stringify({ id: BEHAVIOR_NOTICE_ID, clients: Object.fromEntries(kept) });+}++/**+ * HTTP: the notice once per authenticated client (remote view: no entries or+ * providers). The per-client record lives in the brain's `config` table; a+ * failed write still delivers. Never throws.+ */+export async function takeHttpBehaviorNotice(+ engine: BrainEngine,+ clientId: string | undefined,+ opts: { cfg: GBrainConfig | null; brainKey?: string; now?: number },+): Promise<Notice | null> {+ if (!clientId) return null;+ const client = clientId.slice(0, CLIENT_ID_MAX);+ let key = '';+ try {+ const brainKey = opts.brainKey ?? behaviorBrainKey(opts.cfg, await currentBrainId());+ key = `${BEHAVIOR_NOTICE_ID}|${brainKey}|http|${client}`;+ if (!markHandled(key)) return null;+ if (!(await brainPredatesRelease(engine, brainKey, { persist: true, now: opts.now }))) return null;+ const raw = await engine.getConfig(HTTP_SHOWN_KEY).catch(() => null);+ if (readHttpShown(raw).clients[client]) return null;+ try { await engine.setConfig(HTTP_SHOWN_KEY, recordHttpShown(raw, client, new Date(opts.now ?? Date.now()).toISOString())); } catch { /* deliver anyway */ }+ return behaviorChangesNotice(await chainDisclosure(engine, opts.cfg), { remote: true });+ } catch {+ if (key) handled.delete(key);+ return null;+ }+}diff --git a/src/core/doctor-categories.ts b/src/core/doctor-categories.tsindex 8fee9e5d4c..db37ef5ece 100644--- a/src/core/doctor-categories.ts+++ b/src/core/doctor-categories.ts@@ -192,6 +192,8 @@ export const SKILL_CHECK_NAMES: ReadonlySet<string> = new Set([* Infrastructure liveness signals. DB, workers, OAuth, RLS, locks, providers.*/export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([+ // The effective chat_fallback_chain, its config plane, the providers it reaches and per-entry readiness.+ 'chat_fallback_chain',// Agent operator wave: is an agent harness wired to this brain (registration read; --only adds the smoke test).'harness_wiring','frontmatter_hook',@@ -283,6 +285,8 @@ export const OPS_CHECK_NAMES: ReadonlySet<string> = new Set([* housekeeping. Default category for unknown names (with stderr warn).*/export const META_CHECK_NAMES: ReadonlySet<string> = new Set([+ // The one-time behavior-change disclosure, readable again here (read-only).+ 'behavior_changes',// Agent operator wave E11: recent agent dead ends from the agent-contract event log.'agent_contract','cycle_phase_scope',diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex ae61881b91..6ed0538c37 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -377,6 +377,8 @@ export const NOTICE_CODES = {surface_env_invalid: { kind: 'info', summary: 'GBRAIN_SURFACE holds a value other than verbs, starter or full; the server ignored it and names the surface it serves.' },features_auto_fix: { kind: 'coaching', summary: 'gbrain features found auto-fixable gaps; the fix is the auto-fix command (it may spend on embeddings).' },post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },+ behavior_changes: { kind: 'safety', summary: 'One-time disclosure of behavior an upgrade turned on (a live chat_fallback_chain, managed-brain lint repairs, smaller transcript parts, a mention-linker rescan); everything stays on, and the fix is optional.' },+ chat_fallback_hop: { kind: 'safety', summary: 'chat_fallback_chain sent a request to another model for the first time in this process; names the failed and the next model.' },facts_drain_first_run: { kind: 'info', summary: 'The automatic facts drain is about to process its first backlog on this brain: the queued page count, the estimated spend, the caps and the opt-out.' },facts_drain_deferred: { kind: 'degraded', summary: 'The automatic facts drain left queued pages waiting (no key, a spend cap, an unpriced model under a user cap); the fix is the next step.' },relational_chain: { kind: 'degraded', summary: 'A typed relationship chain found no complete answer (start page not visible, no typed edges, an empty hop) or hit a cap; the notice names the hop and the next call.' },diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 561f46d01d..f5f678ec67 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -22,6 +22,8 @@ import { logVerbUsage } from '../core/verbs/usage-log.ts';import { localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';import { hiddenToolHint } from './hidden-tool-hint.ts';import { takePostUpgradeMcpNotice } from '../core/post-upgrade-notice.ts';+import { takeHttpBehaviorNotice, takeLocalBehaviorNotice } from '../core/behavior-change-notice.ts';+import { takeChatFallbackHopNotices } from '../core/ai/fallback-hop-queue.ts';import { mcpOnboardingNotices } from '../core/onboard/mcp-onboarding.ts';import { takeFactsDrainNotice } from '../core/facts/drain.ts';import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';@@ -581,6 +583,27 @@ function admitNotices(notices: Notice[], opts: DispatchOpts): Notice[] {}}+/**+ * The one-time `behavior_changes` disclosure (stdio: once per brain; HTTP:+ * once per authenticated client, remote view) and the first+ * `chat_fallback_hop` of this process (stdio only: it names models). Rides+ * success and failure results alike. Never throws.+ */+async function sessionSafetyNotices(engine: BrainEngine, opts: DispatchOpts, config: OperationContext['config']): Promise<Notice[]> {+ const out: Notice[] = [];+ try {+ if (opts.transport === 'stdio' && opts.remote !== false) {+ const behavior = await takeLocalBehaviorNotice(engine, 'stdio', { cfg: config ?? null });+ if (behavior) out.push(behavior);+ out.push(...takeChatFallbackHopNotices());+ } else if (opts.transport === 'http') {+ const behavior = await takeHttpBehaviorNotice(engine, opts.auth?.clientId, { cfg: config ?? null });+ if (behavior) out.push(behavior);+ }+ } catch { /* a notice never breaks a tool call */ }+ return out;+}+/** The one error result path: toAgentError → exactly one content block. */export function errorResult(e: unknown, opts: DispatchOpts, extra: { op?: string; mutating?: boolean; idempotent?: boolean; notices?: Notice[] } = {}): ToolResult {const carried = !!extra.notices?.length && e instanceof OperationError;@@ -913,6 +936,7 @@ export async function dispatchToolCall(if (opts.transport === 'stdio' && opts.remote !== false) { const up = takePostUpgradeMcpNotice(); if (up) notices.push(up); } // F7if (opts.transport === 'stdio' && opts.remote !== false) notices.push(...await mcpOnboardingNotices({ engine, op: name, result, meta: responseMeta, config: ctx.config, render: dispatchRenderContext(opts) }));if (opts.transport === 'stdio' && opts.remote !== false) { const drain = takeFactsDrainNotice(); if (drain) notices.push(drain); } // Lane D facts drain+ notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));const out: ToolResult = toolResultWithNotices(result, admitNotices(notices, opts), dispatchRenderContext(opts));if (evidenceBlocks.length > 0) out.content.splice(1, 0, ...evidenceBlocks.map(text => ({ type: 'text' as const, text })));if (opts.transport === 'stdio') {@@ -947,6 +971,7 @@ export async function dispatchToolCall(// access errors, uncaught throws — goes through the one total normaliser,// which redacts raw messages, keeps verbs on their frozen v1 codes, and// never tells a mutating op with an unknown outcome to retry.+ notices.push(...await sessionSafetyNotices(engine, opts, ctx.config));return errorResult(e, opts, { op: name, mutating: op.mutating === true, idempotent: op.idempotent === true, notices: admitNotices(notices, opts) });}}diff --git a/test/behavior-change-notice-cli.test.ts b/test/behavior-change-notice-cli.test.tsnew file mode 100644index 0000000000..4014cfe4b9--- /dev/null+++ b/test/behavior-change-notice-cli.test.ts@@ -0,0 +1,66 @@+/**+ * The `behavior_changes` notice on the real CLI (fix wave lane B3, W-A3).+ *+ * Protects: `gbrain init` stamps the database it creates as a fresh install,+ * so later commands stay silent; a brain with no recorded baseline that was+ * created before the grace window (a `bun install -g` upgrade with no+ * upgrade-state.json) gets the disclosure on stderr once, on the first+ * command (an [AGENT] block off a TTY), and never again; `gbrain doctor`+ * shows it without consuming it.+ * Fails when: init stops stamping, the CLI startup hook stops delivering or+ * marking, or doctor writes the marker.+ * Seams: the real `src/cli.ts` in a subprocess with a throwaway HOME; the+ * brain's age is set by editing `sources.created_at` between commands.+ */+import { describe, expect, test } from 'bun:test';+import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runCli } from './helpers/cli-spawn.ts';++const BLOCK = 'why: [behavior_changes]';+const env = { GBRAIN_CHAT_FALLBACK_CHAIN: undefined, GBRAIN_NO_ONBOARD_NUDGE: '1' };++async function ageBrain(dataDir: string): Promise<void> {+ const engine = new PGLiteEngine();+ await engine.connect({ database_path: dataDir });+ try {+ await engine.executeRaw(`UPDATE sources SET created_at = now() - interval '3 days'`);+ } finally {+ await engine.disconnect();+ }+}++describe('behavior_changes on the CLI', () => {+ test('init marks a fresh install; an older unrecorded brain gets the notice once; doctor only reads it', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-behavior-cli-'));+ const opts = { home, cwd: home, timeoutMs: 120_000, env };+ const init = await runCli(['init', '--pglite', '--no-embedding', '--json'], opts);+ expect(init.exitCode).toBe(0);+ const dir = join(home, '.gbrain', 'notices', 'behavior-changes');+ const baselines = readdirSync(dir).filter(f => f.endsWith('.baseline'));+ expect(baselines).toHaveLength(1);++ const dataDir = join(home, '.gbrain', 'brain.pglite');+ expect(existsSync(dataDir)).toBe(true);+ await ageBrain(dataDir);+ const fresh = await runCli(['list', '--limit', '1'], opts);+ expect(fresh.exitCode).toBe(0);+ expect(fresh.stderr).not.toContain(BLOCK);++ // The same brain as an upgrader sees it: no baseline was ever recorded.+ rmSync(join(dir, baselines[0]!));+ const doctor = await runCli(['doctor', '--only', 'behavior_changes', '--json'], opts);+ expect(doctor.stdout).toContain('one-time disclosure');+ expect(doctor.stderr).not.toContain(BLOCK);+ expect(readdirSync(dir).some(f => f.endsWith('.shown'))).toBe(false);++ const first = await runCli(['list', '--limit', '1'], opts);+ expect(first.exitCode).toBe(0);+ expect(first.stderr).toContain(BLOCK);+ expect(first.stderr).toContain('cycle.lint_fix false');+ const second = await runCli(['list', '--limit', '1'], opts);+ expect(second.stderr).not.toContain(BLOCK);+ }, 300_000);+});diff --git a/test/behavior-change-notice.test.ts b/test/behavior-change-notice.test.tsnew file mode 100644index 0000000000..d73547860c--- /dev/null+++ b/test/behavior-change-notice.test.ts@@ -0,0 +1,292 @@+/**+ * The one-time `behavior_changes` safety notice (fix wave lane B3, W-A3).+ *+ * Protects: an existing brain (recorded upgrade from an older release, an+ * older recorded baseline, or a brain created before the grace window with no+ * upgrade history) gets the disclosure once per notice × brain × channel, and+ * once per authenticated client over HTTP; a fresh install never does, even+ * after the grace window; markers survive a restart; a home that cannot be+ * written still delivers (once per process); concurrent processes deliver it+ * once; the chain section appears only when a chain is set, and the HTTP view+ * never names entries or providers; failed tool responses carry it; doctor+ * reads it without recording anything.+ * Fails when: eligibility, marker identity, the HTTP per-client store, the+ * remote redaction or dispatch delivery regress.+ * Seams: per-test GBRAIN_HOME; `__resetBehaviorNoticeForTests` stands in for a+ * new process; PGLite always, Postgres when DATABASE_URL is set.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import type { BrainEngine } from '../src/core/engine.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import {+ BEHAVIOR_NOTICE_ID,+ BEHAVIOR_NOTICE_SINCE,+ HTTP_SHOWN_CAP,+ HTTP_SHOWN_KEY,+ __resetBehaviorNoticeForTests,+ behaviorBrainKey,+ recordHttpShown,+ takeHttpBehaviorNotice,+ takeLocalBehaviorNotice,+} from '../src/core/behavior-change-notice.ts';+import { checkBehaviorChanges } from '../src/commands/doctor/checks/behavior-changes.ts';+import { dispatchToolCall } from '../src/mcp/dispatch.ts';+import { NoticeLedger, __resetProcessNoticeLedgerForTests } from '../src/core/notice-ledger.ts';+import { _resetDbPlaneMergeMemoForTests } from '../src/core/config-db-merge.ts';+import type { GBrainConfig } from '../src/core/config.ts';+import { withEnv } from './helpers/with-env.ts';+import { requirePostgresTestDatabase, testBackends } from './helpers/test-backends.ts';+import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';++const DAY = 24 * 60 * 60 * 1000;+const NO_CHAIN = { GBRAIN_CHAT_FALLBACK_CHAIN: undefined, GBRAIN_CHAT_FALLBACK_ON_REFUSAL: undefined };+const freshHome = () => mkdtempSync(join(tmpdir(), 'gbrain-behavior-home-'));+const noticeDir = (home: string) => join(home, '.gbrain', 'notices', 'behavior-changes');+let seq = 0;+const config = (): GBrainConfig => ({ engine: 'pglite', database_path: join(tmpdir(), `behavior-brain-${process.pid}-${++seq}`) } as GBrainConfig);++async function setCreated(engine: BrainEngine, agoMs: number): Promise<void> {+ await engine.executeRaw(`UPDATE sources SET created_at = $1::timestamptz`, [new Date(Date.now() - agoMs).toISOString()]);+}++function noticeBlocks(res: { content: Array<{ text: string }> }): string[] {+ return res.content.map(c => c.text).filter(t => t.startsWith('[gbrain notice behavior_changes kind=safety]'));+}++for (const backend of testBackends()) {+ describe(`${backend}: behavior_changes notice`, () => {+ let engine: BrainEngine;+ let close: () => Promise<void>;+ beforeAll(async () => {+ if (backend === 'postgres') {+ const pg = await isolatedPersistencePostgres(requirePostgresTestDatabase());+ engine = pg.engine;+ close = pg.close;+ } else {+ const pglite = new PGLiteEngine();+ await pglite.connect({});+ await pglite.initSchema();+ engine = pglite;+ close = () => pglite.disconnect();+ }+ }, 120_000);+ afterAll(async () => { await close(); });+ beforeEach(async () => {+ __resetBehaviorNoticeForTests();+ __resetProcessNoticeLedgerForTests();+ _resetDbPlaneMergeMemoForTests();+ await engine.unsetConfig(HTTP_SHOWN_KEY);+ await engine.unsetConfig('chat_fallback_chain');+ await setCreated(engine, 0);+ });++ test('a fresh install sees nothing, and stays fresh after the grace window', async () => {+ const home = freshHome();+ await withEnv({ GBRAIN_HOME: home, ...NO_CHAIN }, async () => {+ expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'fresh' })).toBeNull();+ expect(readFileSync(join(noticeDir(home), 'fresh.baseline'), 'utf8').trim()).toBe(BEHAVIOR_NOTICE_SINCE);+ await setCreated(engine, 2 * DAY);+ __resetBehaviorNoticeForTests();+ expect(await takeLocalBehaviorNotice(engine, 'stdio', { cfg: null, brainKey: 'fresh' })).toBeNull();+ });+ });++ test('an existing brain with no upgrade history sees it once per channel, and a restart does not repeat it', async () => {+ await setCreated(engine, 2 * DAY);+ await withEnv({ GBRAIN_HOME: freshHome(), ...NO_CHAIN }, async () => {+ const first = await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'old' });+ expect(first?.code).toBe('behavior_changes');+ expect(first?.kind).toBe('safety');+ expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'old' })).toBeNull();+ __resetBehaviorNoticeForTests();+ expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'old' })).toBeNull();+ expect((await takeLocalBehaviorNotice(engine, 'stdio', { cfg: null, brainKey: 'old' }))?.code).toBe('behavior_changes');+ expect(await takeLocalBehaviorNotice(engine, 'stdio', { cfg: null, brainKey: 'old' })).toBeNull();+ });+ });++ test('a skipped-release install still sees it: upgrade history from an older release, or an older recorded baseline', async () => {+ const home = freshHome();+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'upgrade-state.json'), JSON.stringify({ last_upgrade: { from: '0.50.0.0', to: '99.0.0.0' } }));+ await withEnv({ GBRAIN_HOME: home, ...NO_CHAIN }, async () => {+ expect((await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'upgraded' }))?.code).toBe('behavior_changes');+ });+ const baselineHome = freshHome();+ mkdirSync(noticeDir(baselineHome), { recursive: true });+ writeFileSync(join(noticeDir(baselineHome), 'older.baseline'), '0.59.0.0\n');+ writeFileSync(join(noticeDir(baselineHome), 'current.baseline'), `${BEHAVIOR_NOTICE_SINCE}\n`);+ await withEnv({ GBRAIN_HOME: baselineHome, ...NO_CHAIN }, async () => {+ expect((await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'older' }))?.code).toBe('behavior_changes');+ expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'current' })).toBeNull();+ });+ });++ test('each brain gets its own disclosure', async () => {+ await setCreated(engine, 2 * DAY);+ await withEnv({ GBRAIN_HOME: freshHome(), ...NO_CHAIN }, async () => {+ const a = behaviorBrainKey(config());+ const b = behaviorBrainKey(config());+ expect(a).not.toBe(b);+ expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: a })).not.toBeNull();+ expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: b })).not.toBeNull();+ });+ });++ test('the chain section appears only when a chain is set, with entries, providers and refusal behavior', async () => {+ await setCreated(engine, 2 * DAY);+ await withEnv({ GBRAIN_HOME: freshHome(), ...NO_CHAIN }, async () => {+ const plain = (await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'no-chain' }))!;+ expect(plain.why).not.toContain('chat_fallback_chain is live');+ expect(plain.why).toContain('cycle.lint_fix false');+ expect(plain.why).toContain('about 6x');+ expect(plain.why).toContain('mention linker');+ expect(plain.why).toContain('not a request for consent');+ expect(plain.fix?.argv).toEqual(['gbrain', 'doctor', '--only', 'behavior_changes', '--json']);+ });+ await withEnv({ GBRAIN_HOME: freshHome(), GBRAIN_CHAT_FALLBACK_CHAIN: 'openai:gpt-5.6-luna', GBRAIN_CHAT_FALLBACK_ON_REFUSAL: undefined, OPENAI_API_KEY: 'fake-openai' }, async () => {+ const chained = (await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'chain' }))!;+ expect(chained.why).toContain('chat_fallback_chain is live');+ expect(chained.why).toContain('openai:gpt-5.6-luna');+ expect(chained.why).toContain('so openai receive');+ expect(chained.why).toContain('on refusals as well as errors');+ expect(chained.fix?.argv).toEqual(['unset', 'GBRAIN_CHAT_FALLBACK_CHAIN']);+ expect(chained.fix?.actor).toBe('user');+ });+ await withEnv({ GBRAIN_HOME: freshHome(), GBRAIN_CHAT_FALLBACK_CHAIN: 'openai:gpt-5.6-luna', GBRAIN_CHAT_FALLBACK_ON_REFUSAL: 'false', OPENAI_API_KEY: 'fake-openai' }, async () => {+ expect((await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'chain-no-refusal' }))!.why).toContain('falls back on errors only');+ });+ });++ test('a home that cannot be written still gets the notice, once per process', async () => {+ await setCreated(engine, 2 * DAY);+ const blocker = join(freshHome(), 'not-a-dir');+ writeFileSync(blocker, 'x');+ await withEnv({ GBRAIN_HOME: join(blocker, 'home'), ...NO_CHAIN }, async () => {+ expect(await takeLocalBehaviorNotice(engine, 'stdio', { cfg: null, brainKey: 'ro' })).not.toBeNull();+ expect(await takeLocalBehaviorNotice(engine, 'stdio', { cfg: null, brainKey: 'ro' })).toBeNull();+ __resetBehaviorNoticeForTests();+ expect(await takeLocalBehaviorNotice(engine, 'stdio', { cfg: null, brainKey: 'ro' })).not.toBeNull();+ });+ });++ test('HTTP: once per authenticated client, kept in the brain across restarts, never naming entries or providers', async () => {+ await setCreated(engine, 2 * DAY);+ await withEnv({ GBRAIN_HOME: freshHome(), GBRAIN_CHAT_FALLBACK_CHAIN: 'openai:gpt-5.6-luna', OPENAI_API_KEY: 'fake-openai' }, async () => {+ const a = await takeHttpBehaviorNotice(engine, 'client-a', { cfg: null, brainKey: 'http' });+ expect(a?.code).toBe('behavior_changes');+ expect(a!.why).toContain('A chat fallback chain is configured on this brain host');+ expect(a!.why).not.toContain('gpt-5.6-luna');+ expect(a!.why).not.toContain('openai');+ expect(a!.fix?.actor).toBe('host_admin');+ expect(await takeHttpBehaviorNotice(engine, 'client-a', { cfg: null, brainKey: 'http' })).toBeNull();+ expect(await takeHttpBehaviorNotice(engine, 'client-b', { cfg: null, brainKey: 'http' })).not.toBeNull();+ __resetBehaviorNoticeForTests();+ expect(await takeHttpBehaviorNotice(engine, 'client-a', { cfg: null, brainKey: 'http' })).toBeNull();+ expect(await takeHttpBehaviorNotice(engine, undefined, { cfg: null, brainKey: 'http' })).toBeNull();+ const stored = JSON.parse((await engine.getConfig(HTTP_SHOWN_KEY))!);+ expect(stored.id).toBe(BEHAVIOR_NOTICE_ID);+ expect(Object.keys(stored.clients).sort()).toEqual(['client-a', 'client-b']);+ });+ });++ test('HTTP: a store that cannot be written still delivers', async () => {+ await setCreated(engine, 2 * DAY);+ const readOnly = new Proxy(engine, {+ get(target, prop, receiver) {+ if (prop === 'setConfig') return async () => { throw new Error('read-only brain'); };+ const v = Reflect.get(target, prop, receiver);+ return typeof v === 'function' ? v.bind(target) : v;+ },+ });+ await withEnv({ GBRAIN_HOME: freshHome(), ...NO_CHAIN }, async () => {+ expect(await takeHttpBehaviorNotice(readOnly, 'client-ro', { cfg: null, brainKey: 'http-ro' })).not.toBeNull();+ });+ });++ test('doctor shows the disclosure and records nothing', async () => {+ await setCreated(engine, 2 * DAY);+ const home = freshHome();+ await withEnv({ GBRAIN_HOME: home, ...NO_CHAIN }, async () => {+ const c = await checkBehaviorChanges(engine, { cfg: null, brainKey: 'doctor' });+ expect(c.status).toBe('ok');+ expect(c.message).toContain('one-time disclosure');+ expect(c.details).toMatchObject({ shown: { cli: false, stdio: false } });+ expect(existsSync(noticeDir(home))).toBe(false);+ expect(await takeLocalBehaviorNotice(engine, 'cli', { cfg: null, brainKey: 'doctor' })).not.toBeNull();+ expect((await checkBehaviorChanges(engine, { cfg: null, brainKey: 'doctor' })).details).toMatchObject({ shown: { cli: true, stdio: false } });+ });+ });++ test('stdio dispatch: the first tool result carries it, later ones do not, and a failed first call carries it too', async () => {+ await setCreated(engine, 2 * DAY);+ await withEnv({ GBRAIN_HOME: freshHome(), ...NO_CHAIN }, async () => {+ const cfg = config();+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default', config: cfg };+ const first = await dispatchToolCall(engine as never, 'list_pages', {}, opts);+ expect(noticeBlocks(first)).toHaveLength(1);+ const second = await dispatchToolCall(engine as never, 'list_pages', {}, opts);+ expect(noticeBlocks(second)).toHaveLength(0);++ __resetProcessNoticeLedgerForTests();+ const failCfg = config();+ const failed = await dispatchToolCall(engine as never, 'get_page', { slug: 'missing/acme-example' }, { ...opts, config: failCfg });+ expect(failed.isError).toBe(true);+ const envelope = JSON.parse(failed.content[0]!.text) as { notices?: Array<{ code: string }> };+ expect(envelope.notices?.map(n => n.code)).toContain('behavior_changes');+ const after = await dispatchToolCall(engine as never, 'list_pages', {}, { ...opts, config: failCfg });+ expect(noticeBlocks(after)).toHaveLength(0);+ });+ }, 60_000);++ test('HTTP dispatch: each client gets it on its first tool result', async () => {+ await setCreated(engine, 2 * DAY);+ await withEnv({ GBRAIN_HOME: freshHome(), ...NO_CHAIN }, async () => {+ const cfg = config();+ const ledger = new NoticeLedger();+ const httpOpts = (clientId: string) => ({ remote: true, transport: 'http' as const, sourceId: 'default', config: cfg, noticeLedger: ledger,+ auth: { token: 't', clientId, clientName: clientId, scopes: ['read'], expiresAt: Date.now() / 1000 + 3600 } as never });+ expect(noticeBlocks(await dispatchToolCall(engine as never, 'list_pages', {}, httpOpts('http-a')))).toHaveLength(1);+ expect(noticeBlocks(await dispatchToolCall(engine as never, 'list_pages', {}, httpOpts('http-a')))).toHaveLength(0);+ expect(noticeBlocks(await dispatchToolCall(engine as never, 'list_pages', {}, httpOpts('http-b')))).toHaveLength(1);+ });+ }, 60_000);+ });+}++describe('HTTP per-client store', () => {+ test('keeps the newest HTTP_SHOWN_CAP clients and resets for a new notice id', () => {+ let raw: string | null = JSON.stringify({ id: '[email protected]', clients: { stale: '2020-01-01T00:00:00.000Z' } });+ for (let i = 0; i < HTTP_SHOWN_CAP + 25; i++) raw = recordHttpShown(raw, `client-${i}`, new Date(Date.UTC(2026, 0, 1, 0, 0, i)).toISOString());+ const stored = JSON.parse(raw!) as { id: string; clients: Record<string, string> };+ expect(stored.id).toBe(BEHAVIOR_NOTICE_ID);+ expect(Object.keys(stored.clients)).toHaveLength(HTTP_SHOWN_CAP);+ expect(stored.clients.stale).toBeUndefined();+ expect(stored.clients['client-0']).toBeUndefined();+ expect(stored.clients[`client-${HTTP_SHOWN_CAP + 24}`]).toBeDefined();+ });+});++describe('concurrent initializations', () => {+ test('processes racing on one brain and channel deliver it exactly once', async () => {+ const home = freshHome();+ const script = join(home, 'race.ts');+ const modulePath = join(import.meta.dir, '..', 'src', 'core', 'behavior-change-notice.ts');+ writeFileSync(script, `+ const { takeLocalBehaviorNotice } = await import(${JSON.stringify(modulePath)});+ const old = new Date(Date.now() - 3 * 86400000).toISOString();+ const engine = { executeRaw: async () => [{ at: old }], getConfig: async () => null };+ const n = await takeLocalBehaviorNotice(engine, 'stdio', { cfg: null, brainKey: 'race' });+ console.log(JSON.stringify({ delivered: n !== null }));+ `);+ const env = { ...process.env, GBRAIN_HOME: home, GBRAIN_CHAT_FALLBACK_CHAIN: '' } as Record<string, string>;+ const procs = Array.from({ length: 6 }, () => Bun.spawn(['bun', script], { env, stdout: 'pipe', stderr: 'pipe' }));+ const outs = await Promise.all(procs.map(async p => { await p.exited; return new Response(p.stdout).text(); }));+ const delivered = outs.map(o => JSON.parse(o.trim().split('\n').pop()!).delivered as boolean);+ expect(delivered.filter(Boolean)).toHaveLength(1);+ expect(readFileSync(join(noticeDir(home), 'race.baseline'), 'utf8').trim()).toBe('0');+ }, 60_000);+});diff --git a/test/doctor-chat-fallback-chain.test.ts b/test/doctor-chat-fallback-chain.test.tsnew file mode 100644index 0000000000..428cf0b8fc--- /dev/null+++ b/test/doctor-chat-fallback-chain.test.ts@@ -0,0 +1,190 @@+/**+ * `chat_fallback_chain` doctor check (fix wave lane B3, W-B3).+ *+ * Protects: doctor reports the effective chain, the plane that wins (env >+ * config.json > DB), shadowed values, the providers that receive traffic and+ * whether refusals fall back; an active chain is an informational `ok` whose+ * removal guidance is never `next: run` (DB: ask_user; env: tell_user_to_run;+ * file: names the path and key); malformed entries or plane values, missing+ * provider credentials and unpriced models under a user-set cap are `warn`+ * with a cause-specific fix; the remote report hides entries and providers;+ * the check is in the local registry, `--only` and the remote report; it makes+ * no network or subprocess call.+ * Fails when: any of those diagnoses, plane decisions or redactions regress.+ * Seams: a real PGLite brain (DB plane), a throwaway GBRAIN_HOME (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 { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { checkChatFallbackChain } from '../src/commands/doctor/checks/chat-fallback.ts';+import { finalizeCheckFixes } from '../src/commands/doctor/check-fix.ts';+import { doctorCheckNames, onlyNeedsEngine } from '../src/commands/doctor/registry.ts';+import { doctorReportRemote } from '../src/commands/doctor/report-remote.ts';+import { _resetDbPlaneMergeMemoForTests } from '../src/core/config-db-merge.ts';+import { withEnv } from './helpers/with-env.ts';++const FALLBACK = 'openai:gpt-5.6-luna';+const SECOND = 'deepseek:deepseek-v4-flash';++let engine: PGLiteEngine;+let fetchSpy: ReturnType<typeof spyOn>;+let spawnSpy: ReturnType<typeof spyOn>;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); }, 120_000);+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ for (const k of ['chat_fallback_chain', 'chat_fallback_on_refusal', 'facts.drain_budget_usd', 'pricing.overrides']) await engine.unsetConfig(k);+ _resetDbPlaneMergeMemoForTests();+ fetchSpy = spyOn(globalThis, 'fetch');+ spawnSpy = spyOn(Bun, 'spawn');+});+afterEach(() => {+ expect(fetchSpy).not.toHaveBeenCalled();+ expect(spawnSpy).not.toHaveBeenCalled();+ fetchSpy.mockRestore();+ spawnSpy.mockRestore();+});++function home(file: Record<string, unknown> = {}): string {+ const dir = mkdtempSync(join(tmpdir(), 'gbrain-doctor-chain-'));+ mkdirSync(join(dir, '.gbrain'), { recursive: true });+ writeFileSync(join(dir, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', database_path: join(dir, 'brain.pglite'), ...file }));+ return dir;+}++const ENV_BASE = {+ GBRAIN_CHAT_FALLBACK_CHAIN: undefined, GBRAIN_CHAT_FALLBACK_ON_REFUSAL: undefined, DATABASE_URL: undefined, GBRAIN_DATABASE_URL: undefined,+ OPENAI_API_KEY: 'fake-openai', DEEPSEEK_API_KEY: 'fake-deepseek', ANTHROPIC_API_KEY: undefined, GBRAIN_CLAUDE_CLI_BIN: undefined,+};++async function run(env: Record<string, string | undefined>, file: Record<string, unknown> = {}, remote = false) {+ return withEnv({ ...ENV_BASE, GBRAIN_HOME: home(file), ...env }, async () => {+ const [check] = finalizeCheckFixes([await checkChatFallbackChain(engine, { remote })]);+ return check!;+ });+}++describe('chat_fallback_chain doctor check', () => {+ test('no chain anywhere is a plain ok', async () => {+ const c = await run({});+ expect(c.status).toBe('ok');+ expect(c.message).toContain('No chat_fallback_chain is set');+ expect(c.fix).toBeUndefined();+ });++ test('a DB chain is an informational ok: entries, providers, refusal fallback, ask_user removal', async () => {+ await engine.setConfig('chat_fallback_chain', `${FALLBACK}, ${SECOND}`);+ const c = await run({});+ expect(c.status).toBe('ok');+ expect(c.message).toContain(`${FALLBACK} -> ${SECOND}`);+ expect(c.message).toContain('the brain database');+ expect(c.message).toContain('openai, deepseek');+ expect(c.message).toContain('on refusals');+ expect(c.details).toMatchObject({ plane: 'db', chain: [FALLBACK, SECOND], providers: ['openai', 'deepseek'], on_refusal: { value: true, plane: 'default' } });+ const fix = c.fix as { argv: string[]; next: string; consent: string[] };+ expect(fix.argv).toEqual(['gbrain', 'config', 'unset', 'chat_fallback_chain']);+ expect(fix.next).toBe('ask_user');+ });++ test('env wins over the DB, the DB value is reported shadowed, and env removal is the user\'s (restart named)', async () => {+ await engine.setConfig('chat_fallback_chain', SECOND);+ const c = await run({ GBRAIN_CHAT_FALLBACK_CHAIN: FALLBACK });+ expect(c.status).toBe('ok');+ expect(c.details).toMatchObject({ plane: 'env', chain: [FALLBACK], shadowed: [{ plane: 'db', chain: [SECOND] }] });+ expect(c.message).toContain('Shadowed');+ const fix = c.fix as { argv: string[]; next: string; why: string };+ expect(fix.argv).toEqual(['unset', 'GBRAIN_CHAT_FALLBACK_CHAIN']);+ expect(fix.next).toBe('tell_user_to_run');+ expect(fix.why).toContain('restarts');+ });++ test('config.json wins over the DB and the guidance names the file and key, never run', async () => {+ await engine.setConfig('chat_fallback_chain', SECOND);+ const c = await run({}, { chat_fallback_chain: [FALLBACK], chat_fallback_on_refusal: false });+ expect(c.details).toMatchObject({ plane: 'file', chain: [FALLBACK], shadowed: [{ plane: 'db', chain: [SECOND] }], on_refusal: { value: false, plane: 'file' } });+ expect(c.message).toContain('errors only');+ const fix = c.fix as { next: string; user_message: string };+ expect(fix.next).not.toBe('run');+ expect(fix.user_message).toContain('"chat_fallback_chain"');+ expect(fix.user_message).toContain('config.json');+ });++ test('a bare model name is a malformed entry', async () => {+ await engine.setConfig('chat_fallback_chain', `${FALLBACK}, gpt-5`);+ const c = await run({});+ expect(c.status).toBe('warn');+ expect(c.message).toContain('gpt-5 (malformed)');+ expect((c.fix as { next: string }).next).toBe('ask_user');+ });++ test('an unknown provider is named as such', async () => {+ await engine.setConfig('chat_fallback_chain', 'acme-example:model-1');+ const c = await run({});+ expect(c.status).toBe('warn');+ expect(c.message).toContain('unknown_provider');+ });++ test('a DB value that is not valid JSON says it cannot be read', async () => {+ await engine.setConfig('chat_fallback_chain', '["openai:gpt-5.6-luna"');+ const c = await run({});+ expect(c.status).toBe('warn');+ expect(c.message).toContain('cannot be read');+ expect(c.message).toContain('not valid JSON');+ });++ test('a provider with no credential present gets a credential fix', async () => {+ await engine.setConfig('chat_fallback_chain', 'anthropic:claude-sonnet-4-6');+ const c = await run({});+ expect(c.status).toBe('warn');+ expect(c.message).toContain('no_credential');+ expect(c.message).toContain('ANTHROPIC_API_KEY');+ expect((c.fix as { consent: string[] }).consent).toEqual(['credentials']);+ });++ test('claude-cli checks for its binary, not a login probe', async () => {+ await engine.setConfig('chat_fallback_chain', 'claude-cli:claude-sonnet-4-6');+ const c = await run({ GBRAIN_CLAUDE_CLI_BIN: '/nonexistent/claude-example' });+ expect(c.status).toBe('warn');+ expect(c.message).toContain('claude CLI binary');+ });++ test('an unpriced model under a user-set cap gets the pricing registration fix; without a cap it is ok', async () => {+ await engine.setConfig('chat_fallback_chain', 'openai:acme-unpriced-model');+ expect((await run({})).status).toBe('ok');+ await engine.setConfig('facts.drain_budget_usd', '2');+ const c = await run({});+ expect(c.status).toBe('warn');+ expect(c.message).toContain('unpriced_under_cap');+ expect((c.fix as { argv: string[] }).argv.slice(0, 4)).toEqual(['gbrain', 'pricing', 'set', 'openai:acme-unpriced-model']);+ });++ test('the remote view says a chain is configured without entries or providers', async () => {+ await engine.setConfig('chat_fallback_chain', `${FALLBACK}, ${SECOND}`);+ const c = await run({}, {}, true);+ expect(c.status).toBe('ok');+ expect(c.message).toContain('A chat fallback chain is configured');+ expect(c.message).not.toContain('gpt-5.6-luna');+ expect(c.message).not.toContain('openai');+ expect(c.details).toBeUndefined();+ expect((c.fix as { actor: string }).actor).toBe('host_admin');+ });+});++describe('registration', () => {+ test('the local registry and --only know the check, and --only connects the brain so the DB plane is read', () => {+ expect(doctorCheckNames().has('chat_fallback_chain')).toBe(true);+ expect(onlyNeedsEngine(new Set(['chat_fallback_chain']))).toBe(true);+ expect(onlyNeedsEngine(new Set(['behavior_changes']))).toBe(true);+ });++ test('the remote report carries the check, redacted', async () => {+ await engine.setConfig('chat_fallback_chain', FALLBACK);+ await withEnv({ ...ENV_BASE, GBRAIN_HOME: home() }, async () => {+ const report = await doctorReportRemote(engine, { remote: true });+ const c = report.checks.find(x => x.name === 'chat_fallback_chain');+ expect(c?.message).toContain('A chat fallback chain is configured');+ expect(JSON.stringify(c)).not.toContain('gpt-5.6-luna');+ });+ }, 60_000);+});diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 64abe9b339..1a3096a258 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -554,6 +554,18 @@"name": "embedding_migration_state","status": "ok"},+ {+ "category": "ops",+ "message": "No chat_fallback_chain is set: every chat call uses only its own model.",+ "name": "chat_fallback_chain",+ "status": "ok"+ },+ {+ "category": "meta",+ "message": "Nothing to disclose: this brain is a fresh install at v<version> or later, so the one-time behavior-change notice does not apply.",+ "name": "behavior_changes",+ "status": "ok"+ },{"category": "brain","message": "No entity pages — graph_coverage not applicable (markdown-only brain)",diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 847e082ccc..6ae70a0fb0 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -642,6 +642,18 @@"name": "embedding_migration_state","status": "ok"},+ {+ "category": "ops",+ "message": "No chat_fallback_chain is set: every chat call uses only its own model.",+ "name": "chat_fallback_chain",+ "status": "ok"+ },+ {+ "category": "meta",+ "message": "Nothing to disclose: this brain is a fresh install at v<version> or later, so the one-time behavior-change notice does not apply.",+ "name": "behavior_changes",+ "status": "ok"+ },{"category": "brain","message": "No entity pages — graph_coverage not applicable (markdown-only brain)",diff --git a/test/fixtures/goldens/doctor/registry-build-checks.json b/test/fixtures/goldens/doctor/registry-build-checks.jsonindex 1168f97e33..5e45e119d5 100644--- a/test/fixtures/goldens/doctor/registry-build-checks.json+++ b/test/fixtures/goldens/doctor/registry-build-checks.json@@ -329,6 +329,14 @@"category": "brain","name": "embedding_migration_state"},+ {+ "category": "ops",+ "name": "chat_fallback_chain"+ },+ {+ "category": "meta",+ "name": "behavior_changes"+ },{"category": "brain","name": "graph_coverage"diff --git a/test/fixtures/goldens/doctor/registry-report-remote.json b/test/fixtures/goldens/doctor/registry-report-remote.jsonindex 3fd71e577f..eeefefa308 100644--- a/test/fixtures/goldens/doctor/registry-report-remote.json+++ b/test/fixtures/goldens/doctor/registry-report-remote.json@@ -133,6 +133,10 @@"category": "ops","name": "reranker_health"},+ {+ "category": "ops",+ "name": "chat_fallback_chain"+ },{"category": "brain","name": "graph_signals_coverage"