Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(mcp): degraded-recall and source-binding notices; keyless explanations as info notices (F3, F8, F9)
garrytan2feeee34b3ac
diff --git a/src/cli.ts b/src/cli.tsindex 5061e94c47..f061e8e4cf 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -63,6 +63,7 @@ import {type CliDispatchContext,} from './cli/command-table.ts';import { formatRememberResult } from './cli/remember-format.ts';+import { applyCliOpNotices, captureOpNotice } from './cli/op-notices.ts';// db-availability loop: best-effort brain-id for the GBRAIN_DB_ACCESS marker,// so a MOUNT's DB failure reads as `brain=<id>` instead of masquerading as a@@ -684,12 +685,13 @@ async function runSharedOperation(command: string, subArgs: string[], cliOpts: C// path's return value so renderers see the same shape they'd see on the// routed path. Date → ISO string; bigint → string (postgres.js shape);// Buffer → object. Microsecond-cost; eliminates a whole drift bug class.- const result = normalizeLocalResult(rawResult);+ const { result, stderr: noticeText } = applyCliOpNotices(normalizeLocalResult(rawResult), params.json === true);const output = formatResult(op.name, result, params);// Awaited delivery (#3423): queued stdout writes past 64KiB lose their// tail to a slow pipe reader when the exit grace lapses — see// writeStdoutFinal.if (output) await writeStdoutFinal(output);+ if (noticeText) process.stderr.write(noticeText);// #4488: an op that reports failure IN-BAND (`{status: 'error'}` — e.g.// put_page over unparseable frontmatter) used to print the envelope and// exit 0, so scripts read a never-written page as success. Echo the error@@ -1513,6 +1515,7 @@ export async function makeContext(engine: BrainEngine, params: Record<string, un// T15/FOV-1: capture the retrieval meta for formatResult's empty-result// render (the local-engine twin of the MCP _meta.retrieval channel).emitResponseMeta: captureRetrievalMeta,+ emitNotice: captureOpNotice, // A6/F8: rendered after the result by applyCliOpNotices};}diff --git a/src/cli/op-notices.ts b/src/cli/op-notices.tsnew file mode 100644index 0000000000..d5d50ec1cc--- /dev/null+++ b/src/cli/op-notices.ts@@ -0,0 +1,33 @@+/**+ * CLI notice channel for shared ops run by the local CLI (agent operator+ * contract v1, A6 + F8). Op handlers emit through `ctx.emitNotice`; the CLI+ * renders after the result: `--json` object results carry them under+ * `notices` (array results stay bare, notices go to stderr), human output+ * gets stderr lines on a TTY and an `[AGENT]` block otherwise (stdout is data).+ * One op per CLI process, so module state is safe.+ */+import { cliRenderContext, renderNotice, type Notice } from '../core/agent-output.ts';+import { renderCliNotices } from '../core/agent-markers.ts';+import { isInteractive } from '../core/interaction.ts';+import { processNoticeLedger, mutedNoticeCodes } from '../core/notice-ledger.ts';++let pending: Notice[] = [];++export function captureOpNotice(n: Notice): void {+ pending.push(n);+}++/** 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;+ pending = [];+ if (captured.length === 0) return { result };+ let admitted = captured;+ try { admitted = processNoticeLedger().admit(captured, { transport: 'cli' }, mutedNoticeCodes()); } catch { /* fail-open */ }+ const rendered = admitted.map(n => renderNotice(n, cliRenderContext()));+ if (rendered.length === 0) return { result };+ const isObject = typeof result === 'object' && result !== null && !Array.isArray(result);+ if (json && isObject) return { result: { ...(result as Record<string, unknown>), notices: rendered } };+ const out = renderCliNotices(rendered, { json: false, tty: isInteractive(), stdoutIsData: true });+ return { result, stderr: out.stderr };+}diff --git a/src/commands/think.ts b/src/commands/think.tsindex 006735fa81..85ddc25ca2 100644--- a/src/commands/think.ts+++ b/src/commands/think.ts@@ -11,6 +11,8 @@ import { loadConfig, isThinClient } from '../core/config.ts';import { callRemoteTool, unpackToolResult } from '../core/mcp-client.ts';import { canonicalLookup } from '../core/model-pricing.ts';import { embedQuery } from '../core/embedding.ts';+import { keylessThinkNotice } from '../core/interop-notices.ts';+import { applyCliOpNotices, captureOpNotice } from '../cli/op-notices.ts';function flagValue(args: string[], name: string): string | undefined {const i = args.indexOf(name);@@ -250,16 +252,20 @@ prints what would have been the input (exit 0).result.modelUsed,);+ // F8: keyless-by-design output carries its explanation as an info notice.+ if (result.synthesis_status === 'no_llm') captureOpNotice(keylessThinkNotice());+ const { result: jsonDoc, stderr: noticeText } = applyCliOpNotices({+ ...result,+ cost_usd: costUsd ?? null,+ saved_slug: savedSlug ?? null,+ evidence_inserted: evidenceInserted,+ take_row: takeRow,+ }, json);if (json) {- console.log(JSON.stringify({- ...result,- cost_usd: costUsd ?? null,- saved_slug: savedSlug ?? null,- evidence_inserted: evidenceInserted,- take_row: takeRow,- }, null, 2));+ console.log(JSON.stringify(jsonDoc, null, 2));return;}+ if (noticeText) process.stderr.write(noticeText);// Human-readable outputconsole.log(`# ${question}\n`);diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex f724555ade..fce745acf4 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -286,4 +286,9 @@ export const NOTICE_CODES = {empty_retrieval: { kind: 'info', summary: 'A retrieval returned no results; the notice says whether recall was degraded.' },unknown_param: { kind: 'info', summary: 'The call passed a parameter the tool does not declare; it was ignored.' },listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },+ degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence.' },+ source_binding_narrowed: { kind: 'info', summary: "A GBRAIN_SOURCE / .gbrain-source binding narrowed an unqualified read that came back empty; the fix reads another source explicitly." },+ degraded_dedup: { kind: 'info', summary: 'remember ran without an embedding provider, so only exact duplicates are detected.' },+ synthesis_keyless: { kind: 'info', summary: 'think returned gathered evidence without synthesis because no chat-model key is configured (by design on a keyless brain).' },+ think_not_saved: { kind: 'info', summary: 'think save/take persist only for the local CLI, so this answer was not saved.' },} as const satisfies Record<string, NoticeEntry>;diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsnew file mode 100644index 0000000000..627e7f9e55--- /dev/null+++ b/src/core/interop-notices.ts@@ -0,0 +1,231 @@+/**+ * Lane F notice producers (agent operator contract v1, F3/F8/F9): the+ * model-visible explanations for degraded recall, a source binding that+ * narrowed a read, keyless-by-design answers and the facts the CLI formatter+ * used to invent on its own. Everything here is pure: callers pass the+ * config and the call's result, and emit the returned notices through+ * `ctx.emitNotice` (ops) or dispatch's notice list (MCP). Notices interpolate+ * ids and closed-vocabulary stage names only, never page text.+ */+import type { Action, Notice } from './agent-output.ts';+import type { GBrainConfig } from './config.ts';+import type { ExplicitReadBinding } from './ops/contract.ts';+import { configReadiness } from './readiness.ts';+import { affectsRecall, type DegradedStage } from './types.ts';++// ── degraded recall (F3) ───────────────────────────────────────────────────++type StageFix = 'embeddings' | 'doctor' | null;+interface StageGuidance { why: string; fix: StageFix }++/** Recall-affecting stages: every DEGRADED_STAGES member except the ranking-only ones, plus the verbs' own markers. */+export type RecallStage =+ | Exclude<DegradedStage, 'reranker_skipped'>+ | 'keyword_only_no_embedding_provider' | 'deadline' | 'server_budget';++/**+ * The closed guidance map: what each recall-affecting stage means for the+ * answer, and which fix applies. Pinned exhaustive by its type and by+ * test/mcp-notice-channels.test.ts.+ */+export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidance>> = {+ embed_unavailable: { why: 'semantic (vector) search did not run, so matches phrased differently from the query can be missing', fix: 'embeddings' },+ keyword_only_no_embedding_provider: { why: 'semantic (vector) search did not run, so matches phrased differently from the query can be missing', fix: 'embeddings' },+ embed_timeout: { why: 'the embedding provider timed out, so this call fell back to keyword matching', fix: 'doctor' },+ expansion_failed: { why: 'query expansion failed, so synonym-phrased matches can be missing', fix: 'doctor' },+ expansion_partial: { why: 'some query-expansion variants could not be embedded', fix: 'doctor' },+ rescore_skipped: { why: 'the rescoring pass was skipped', fix: 'doctor' },+ vector_arm_failed: { why: 'the vector retrieval arm failed', fix: 'doctor' },+ keyword_arm_failed: { why: 'the keyword retrieval arm failed', fix: 'doctor' },+ title_arm_failed: { why: 'the title retrieval arm failed', fix: 'doctor' },+ budget_dropped_all: { why: 'the token budget dropped every result; raise the budget parameter to see them', fix: null },+ budget_truncated: { why: 'the token budget cut some results; raise the budget parameter to see more', fix: null },+ keyword_zero: { why: 'keyword matching found nothing for these terms', fix: null },+ cache_prestamp: { why: 'this answer came from a cache entry whose original degradation is unknown', fix: null },+ rerank_passthrough: { why: 'the reranker returned nothing usable, so results keep their fused order', fix: null },+ rerank_failed: { why: 'reranking failed, so results keep their fused order', fix: null },+ keyword_relaxed_carried: { why: 'keyword matching was relaxed to find anything at all', fix: null },+ safe_index_pending: { why: 'some pages in scope are still being safety-indexed for agent readers and are withheld until that finishes', fix: 'doctor' },+ vector_candidates_incomplete: { why: 'vector search hit its candidate limit or deadline, so some semantic matches can be missing', fix: null },+ projection_pending: { why: 'recently written pages are not in the search index yet', fix: 'doctor' },+ projection_status_unknown: { why: 'whether recent writes are in the search index could not be checked', fix: 'doctor' },+ deadline: { why: 'the pack hit its time limit and is partial', fix: null },+ server_budget: { why: 'the server ran out of time budget for this pack', fix: null },+};++const NOT_ABSENCE = 'Treat a thin or empty result as "not found with a degraded search", never as "the brain has nothing on this".';++/** Doctor on the brain host; `run_doctor` where callable (renderAction drops it otherwise). */+export function doctorFix(why: string): Action {+ return { argv: ['gbrain', 'doctor', '--json'], mcp: { tool: 'run_doctor', arguments: {} }, consent: [], actor: 'agent', why, requires_exclusive: false };+}++/**+ * The embeddings fix for a keyword-only call. A brain the user set up keyless+ * (`disabled_by_choice`) gets none: notices never coach on a choice; the why+ * says so and doctor still shows the enable command.+ */+function embeddingsFix(cfg: GBrainConfig | null | undefined, transport: 'stdio' | 'http' | 'cli'): { fix?: Action; byChoice: boolean } {+ if (!cfg) return { fix: doctorFix('Doctor reports why semantic search is unavailable.'), byChoice: false };+ const entry = configReadiness(cfg, { transport }).entries.find(e => e.capability === 'embeddings');+ if (entry?.state === 'disabled_by_choice') return { byChoice: true };+ return { fix: entry && entry.state !== 'ok' && entry.fix ? entry.fix : doctorFix('Embeddings are configured but did not answer; doctor reports the provider failure.'), byChoice: false };+}++/** One `degraded_recall` notice for the recall-affecting stages of this call; null when none applies. */+export function degradedRecallNotice(+ stages: ReadonlyArray<{ stage?: string; reason?: string } | string>,+ opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli' },+): Notice | null {+ const names = [...new Set(stages+ .map(s => (typeof s === 'string' ? { stage: s } : s))+ .filter(s => affectsRecall(s) && (s.stage as string) in DEGRADED_STAGE_GUIDANCE)+ .map(s => s.stage as RecallStage))];+ if (names.length === 0) return null;+ const guidance = names.map(n => DEGRADED_STAGE_GUIDANCE[n]);+ const fixKind: StageFix = guidance.some(g => g.fix === 'embeddings') ? 'embeddings' : guidance.some(g => g.fix === 'doctor') ? 'doctor' : null;+ const emb = fixKind === 'embeddings' ? embeddingsFix(opts.config, opts.transport) : undefined;+ const fix = emb ? emb.fix : fixKind === 'doctor' ? doctorFix('Doctor names the failing retrieval dependency and its fix.') : undefined;+ const choice = emb?.byChoice ? ' This brain was set up keyword-only by the user\'s choice; mention it only if the user asks why something was not found.' : '';+ return {+ code: 'degraded_recall',+ kind: 'degraded',+ why: `Recall was degraded (${names.join(', ')}): ${guidance.map(g => g.why).join('; ')}. ${NOT_ABSENCE}${choice}`,+ ...(fix ? { fix } : {}),+ ...(fix?.user_message ? { user_message: fix.user_message } : {}),+ };+}++// ── source binding narrowed (F3, TODOS #5250) ──────────────────────────────++const BINDING_READ_OPS: ReadonlySet<string> = new Set(['search', 'query', 'recall', 'list_pages']);++function emptyRead(op: string, result: unknown): boolean {+ if (Array.isArray(result)) return result.length === 0;+ if (op !== 'recall' || !result || typeof result !== 'object') return false;+ const r = result as { facts?: unknown[]; results?: unknown[] };+ return (r.facts?.length ?? 0) === 0 && (r.results?.length ?? 0) === 0;+}++/**+ * A stdio connection bound by GBRAIN_SOURCE / `.gbrain-source` whose+ * unqualified read came back empty while other sources are readable: say the+ * binding narrowed it and name the explicit read that widens it.+ */+export function sourceBindingNarrowedNotice(+ op: string, params: Record<string, unknown>, result: unknown, binding: ExplicitReadBinding | undefined,+): Notice | null {+ if (!binding || !BINDING_READ_OPS.has(op) || params.source_id !== undefined || !emptyRead(op, result)) return null;+ const others = binding.sourceIds.filter(id => id !== binding.sourceId);+ const optedOut = binding.optedOut.filter(id => id !== binding.sourceId && !others.includes(id));+ if (others.length === 0 && optedOut.length === 0) return null;+ const { _meta: _ignored, ...args } = params;+ const parts = [+ `This connection is bound to source '${binding.sourceId}' by ${binding.via}, so this unqualified ${op} read only that source and found nothing there.`,+ others.length ? `Also readable with an explicit source_id: ${others.join(', ')}.` : '',+ optedOut.length ? `Not readable from this connection (opted out of federated reads): ${optedOut.join(', ')}.` : '',+ ].filter(Boolean);+ return {+ code: 'source_binding_narrowed',+ kind: 'info',+ why: parts.join(' '),+ ...(others.length ? {+ fix: {+ mcp: { tool: op, arguments: { ...args, source_id: others[0] } },+ consent: [], actor: 'agent' as const, requires_exclusive: false,+ why: `Repeats the read in '${others[0]}'${others.length > 1 ? `; repeat for ${others.slice(1).join(', ')}` : ''}.`,+ },+ } : {}),+ };+}++// ── keyless chat answers (F8/F9) ───────────────────────────────────────────++/**+ * The chat-key fix for synthesize/think on a keyless brain: a key enables+ * paid calls, so the agent asks; both providers are named; the user stores+ * the key themselves (never on a command line); the free fallback is named.+ */+export function chatKeyFix(): Action {+ return {+ argv: ['gbrain', 'providers', 'list'],+ consent: ['credentials', 'paid'],+ actor: 'user',+ why: 'Synthesis needs a chat-model API key, and every synthesized answer is a paid call. Either provider works: Anthropic (ANTHROPIC_API_KEY) or OpenAI (OPENAI_API_KEY). The user adds `NAME=<key>` to the .env file in the gbrain home directory (or exports it for every gbrain process); a key is never passed on a command line. `gbrain providers list` shows what each provider needs. Free fallback meanwhile: recall, search and get_page work without a key, so answer from their results.',+ user_message: 'Synthesized answers need a chat-model API key (Anthropic or OpenAI), and each answer costs a little. Want to add one? Until then I can still answer from your notes directly.',+ verify: { argv: ['gbrain', 'doctor', '--only', 'facts_extraction_health', '--json'] },+ requires_exclusive: false,+ };+}++/** think on a keyless brain: retrieval-only output is by design, not a failure. */+export function keylessThinkNotice(): Notice {+ return {+ code: 'synthesis_keyless',+ kind: 'info',+ why: 'No chat-model key is configured, so think returned the gathered evidence without a synthesized answer (by design on a keyless brain). Answer from the gathered pages yourself (read them with get_page), or ask the user about adding a key.',+ fix: chatKeyFix(),+ };+}++/** think with save/take over MCP: persistence is local-CLI only, so `saved_slug` is null. */+export function thinkNotSavedNotice(): Notice {+ return {+ code: 'think_not_saved',+ kind: 'info',+ why: 'save/take persist only for the local CLI caller, so this answer was not saved (saved_slug: null). To keep it, save the key facts with remember, or ask the user to run `gbrain think --save` with this question on the brain host.',+ };+}++/** remember without an embedding provider: duplicate detection is exact-match only. */+export function degradedDedupNotice(cfg?: GBrainConfig | null): Notice {+ const fix = cfg ? embeddingsFix(cfg, 'stdio').fix : undefined;+ return {+ code: 'degraded_dedup',+ kind: 'info',+ why: 'No embedding provider is configured, so remember detects only exact duplicates; a near-duplicate phrasing of an existing fact inserts a second fact. Recall first when unsure whether a fact is already saved.',+ ...(fix?.consent.length ? { fix } : {}),+ };+}++// ── dispatch producer ──────────────────────────────────────────────────────++const VECTOR_FALLBACK_WARNINGS: ReadonlySet<string> = new Set(['QUESTION_EMBED_FAILED']);++/** Recall-affecting stages of one successful call, from its result and the handler-emitted `retrieval` meta. */+export function recallStagesFor(op: string, result: unknown, meta: Record<string, unknown>, cfg?: GBrainConfig | null): string[] {+ const r = (result && typeof result === 'object' ? result : {}) as Record<string, unknown>;+ if (op === 'search' || op === 'query') {+ const retrieval = meta.retrieval as { degraded?: Array<{ stage?: string; reason?: string }> } | undefined;+ return (retrieval?.degraded ?? []).filter(affectsRecall).map(d => d.stage as string);+ }+ if (op === 'recall') return typeof r.search_degraded === 'string' ? ['keyword_only_no_embedding_provider'] : [];+ if (op === 'context_pack') return typeof r.degraded_reason === 'string' ? [r.degraded_reason] : [];+ if (op === 'think') {+ const warned = Array.isArray(r.warnings) && r.warnings.some(w => VECTOR_FALLBACK_WARNINGS.has(String(w)));+ const keyless = !!cfg && configReadiness(cfg, { transport: 'stdio' }).entries.some(e => e.capability === 'embeddings' && e.state !== 'ok' && e.state !== 'not_applicable');+ return warned || keyless ? ['embed_unavailable'] : [];+ }+ return [];+}++/**+ * The MCP dispatch producer (one call per successful tool call): the+ * `degraded_recall` notice on search/query/recall/think/context_pack and+ * `source_binding_narrowed` on an empty bound stdio read. Never throws.+ */+export function recallInteropNotices(+ op: string, result: unknown, meta: Record<string, unknown>, params: Record<string, unknown>,+ opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli'; binding?: ExplicitReadBinding },+): Notice[] {+ try {+ const out: Notice[] = [];+ const degraded = degradedRecallNotice(recallStagesFor(op, result, meta, opts.config), opts);+ if (degraded) out.push(degraded);+ const narrowed = opts.transport === 'stdio' ? sourceBindingNarrowedNotice(op, params, result, opts.binding) : null;+ if (narrowed) out.push(narrowed);+ return out;+ } catch {+ return [];+ }+}diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex cf6620f573..00baa595bf 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -21,7 +21,7 @@ const MAX_KEYS = 10_000;const TTL_MS = 24 * 60 * 60 * 1000;export const COACHING_BUDGET_PER_SESSION = 2;/** Notices that describe THIS call's result (never deduped): the diagnosis must ride every affected call. */-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated']);+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'source_binding_narrowed']);export interface NoticeAudience {transport: Transport;diff --git a/src/core/ops/takes.ts b/src/core/ops/takes.tsindex 4c74d173e9..721fb70683 100644--- a/src/core/ops/takes.ts+++ b/src/core/ops/takes.ts@@ -283,6 +283,10 @@ const think: Operation = {}}+ // F8: the explanations the CLI formatter prints, as model-visible notices.+ const { keylessThinkNotice, thinkNotSavedNotice } = await import('../interop-notices.ts');+ if (result.synthesis_status === 'no_llm') ctx.emitNotice?.(keylessThinkNotice());+ if (remote && (Boolean(p.save) || Boolean(p.take))) ctx.emitNotice?.(thinkNotSavedNotice());return {...result,// #1698 (#10): the persist-skip signal returns slug '' — map it (and anydiff --git a/src/core/verbs.ts b/src/core/verbs.tsindex 843f2a4511..316201ca51 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -163,7 +163,13 @@ const remember: Operation = {const { submitRememberMutation } = await import('./persistence/memory-mutations.ts');const { runMemoryWrite } = await import('./persistence/verb-errors.ts');- return runMemoryWrite(() => submitRememberMutation(ctx, { ...p, fact, provenance, kind, visibility }));+ const result = await runMemoryWrite(() => submitRememberMutation(ctx, { ...p, fact, provenance, kind, visibility }));+ // F8: the explanation the CLI formatter prints, as a model-visible notice.+ if ((result as { degraded_dedup?: boolean } | null)?.degraded_dedup) {+ const { degradedDedupNotice } = await import('./interop-notices.ts');+ ctx.emitNotice?.(degradedDedupNotice(ctx.config));+ }+ return result;},cliHints: { name: 'remember', positional: ['fact'] },};@@ -283,12 +289,16 @@ const synthesize: Operation = {// unconfigured key routed to the extractive fallback would be masked on// every call and never get fixed.if (result.warnings.includes('NO_ANTHROPIC_API_KEY')) {- throw verbError(+ // F9: a key enables paid calls, so the fix asks; the key never rides a command line.+ const { chatKeyFix } = await import('./interop-notices.ts');+ const e = verbError('unavailable','synthesize needs an LLM and none is configured.',- 'Set an API key (e.g. `gbrain config set anthropic_api_key sk-...` or ANTHROPIC_API_KEY) and retry. recall and entity work without one.',+ 'Ask the user whether to add a chat-model API key (Anthropic or OpenAI; each synthesized answer is a paid call). Meanwhile recall and entity work without one: answer from their results.','chat gateway unconfigured (NO_ANTHROPIC_API_KEY)',);+ e.fix = chatKeyFix();+ throw e;}// Best-effort cost block [E5/m3]: actual tokens when the gateway reporteddiff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex 22592effbc..9ff22b0558 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -17,6 +17,7 @@ import { cliRenderContext, toAgentError, toolErrorResult, toolResultWithNotices,import { isCallable } from '../core/ops/callable.ts';import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger } from '../core/notice-ledger.ts';import { logVerbUsage } from '../core/verbs/usage-log.ts';+import { recallInteropNotices } from '../core/interop-notices.ts';import { sourceGuardBlocksWrite } from '../core/source-resolver.ts';import { suggestNearest } from '../core/levenshtein.ts';import {@@ -801,6 +802,9 @@ export async function dispatchToolCall(for (const w of unknownParamWarnings) {notices.push({ code: 'unknown_param', kind: 'info', why: buildUnknownParamWarnBlock([w]) });}+ // Lane F (F3): degraded recall and a source binding that narrowed an empty read.+ notices.push(...recallInteropNotices(name, result, responseMeta, safeParams,+ { config: ctx.config, transport: dispatchRenderContext(opts).transport, binding: ctx.explicitReadBinding }));// Monthly backup-coverage: one AGGREGATE notice per process (counts only —// never a local path or source id). The refresher runs on the stdio// transport ONLY — the WP1/D7 locality axis localOnly ops use; 'http' ordiff --git a/test/dispatch-response-meta.serial.test.ts b/test/dispatch-response-meta.serial.test.tsindex 3ba2cd6294..ece36a7a10 100644--- a/test/dispatch-response-meta.serial.test.ts+++ b/test/dispatch-response-meta.serial.test.ts@@ -65,8 +65,10 @@ describe('dispatch response meta (WP2/D3/D8)', () => {expect(out.isError).toBeUndefined();// Body block 0 stays the bare array (deployed thin-clients parse only this).expect(JSON.parse(out.content[0].text)).toEqual([]);- // D8: the model-visible diagnosis block.- expect(out.content.length).toBe(2);+ // D8: the model-visible diagnosis block, then F3's degraded_recall notice+ // (agent contract v1: a recall-affecting stage always rides a notice).+ expect(out.content.length).toBe(3);+ expect(out.content[2].text).toStartWith('[gbrain notice degraded_recall kind=degraded]');expect(out.content[1].text).toContain('0 results');expect(out.content[1].text).toContain('retrieved 3');expect(out.content[1].text).toContain('degraded: embed_unavailable');@@ -87,11 +89,13 @@ describe('dispatch response meta (WP2/D3/D8)', () => {expect(retrieval.vector_enabled).toBe(true);});- test('non-empty results → single block, _meta.retrieval still present (D3: on ALL responses)', async () => {+ test('non-empty results → body + degraded_recall notice only, _meta.retrieval still present (D3: on ALL responses)', async () => {nextResults = [{ page_id: 1, source_id: 'default', slug: 'a', chunk_text: 'x' }];nextMeta = DEGRADED_META;const out = await callSearch();- expect(out.content.length).toBe(1);+ // No empty-retrieval block; F3's degraded notice rides every affected HTTP call.+ expect(out.content.length).toBe(2);+ expect(out.content[1].text).toStartWith('[gbrain notice degraded_recall kind=degraded]');const retrieval = (out._meta as Record<string, any>).retrieval;expect(retrieval.returned_count).toBe(1);});diff --git a/test/mcp-backup-nag.serial.test.ts b/test/mcp-backup-nag.serial.test.tsindex c8ef6e643f..6b5c756086 100644--- a/test/mcp-backup-nag.serial.test.ts+++ b/test/mcp-backup-nag.serial.test.ts@@ -111,13 +111,17 @@ type CallOpts = { remote?: boolean; transport?: 'stdio' | 'http' };// Default transport is 'stdio' — the ONLY transport the notice fires on.// Trust-pin tests pass 'http' / undefined explicitly.-function callSearch(opts: CallOpts = {}) {- return dispatchToolCall(engineStub, 'search', { query: 'anything at all' }, {+async function callSearch(opts: CallOpts = {}) {+ const out = await dispatchToolCall(engineStub, 'search', { query: 'anything at all' }, {remote: true,transport: 'stdio',sourceId: 'default',...opts,});+ // F3's degraded_recall notice (this keyless stub searches keyword-only) is+ // orthogonal to the backup block under test; it is pinned in+ // test/mcp-notice-channels.test.ts.+ return { ...out, content: out.content.filter(c => !c.text.startsWith('[gbrain notice degraded_recall ')) };}async function waitFor(pred: () => boolean, ms = 2000): Promise<boolean> {diff --git a/test/mcp-notice-channels.test.ts b/test/mcp-notice-channels.test.tsnew file mode 100644index 0000000000..09b663f912--- /dev/null+++ b/test/mcp-notice-channels.test.ts@@ -0,0 +1,182 @@+/**+ * Lane F notice producers on the MCP channel (agent operator contract v1,+ * F3 / F8 / F9): degraded recall, a source binding that narrowed an empty+ * read, and the keyless explanations. Pins the closed DEGRADED_STAGE_GUIDANCE+ * map, the wire shape (content[0] byte-identical, notices as prefixed extra+ * blocks + `_meta.gbrain_notices`), stdio once-per-session vs HTTP+ * every-call delivery, and the "never coach on a keyless-by-choice brain" rule.+ */+import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { dispatchToolCall, __resetBackupNoticeForTests } from '../src/mcp/dispatch.ts';+import { DEGRADED_STAGES, RANKING_ONLY_DEGRADED_STAGES } from '../src/core/types.ts';+import { NOTICE_CODES } from '../src/core/error-registry.ts';+import {+ DEGRADED_STAGE_GUIDANCE, degradedRecallNotice, sourceBindingNarrowedNotice, recallStagesFor,+ chatKeyFix, keylessThinkNotice, thinkNotSavedNotice, degradedDedupNotice,+} from '../src/core/interop-notices.ts';+import { withEnv } from './helpers/with-env.ts';+import type { GBrainConfig } from '../src/core/config.ts';++let engine: PGLiteEngine;++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+});+afterAll(async () => { await engine.disconnect(); });+beforeEach(async () => {+ await resetPgliteState(engine);+ __resetBackupNoticeForTests();+});++const NO_KEYS = { OPENAI_API_KEY: undefined, ANTHROPIC_API_KEY: undefined, VOYAGE_API_KEY: undefined, GBRAIN_EMBEDDING_MODEL: undefined };+const keylessByChoice = { engine: 'pglite', embedding_disabled: true } as unknown as GBrainConfig;+const keylessUnchosen = { engine: 'pglite' } as unknown as GBrainConfig;++describe('DEGRADED_STAGE_GUIDANCE', () => {+ test('covers every recall-affecting stage and no ranking-only one', () => {+ for (const stage of DEGRADED_STAGES) {+ if (RANKING_ONLY_DEGRADED_STAGES.has(stage)) expect(stage in DEGRADED_STAGE_GUIDANCE).toBe(false);+ else expect(DEGRADED_STAGE_GUIDANCE[stage as keyof typeof DEGRADED_STAGE_GUIDANCE]).toBeDefined();+ }+ });++ test('every Lane F notice code is registered with its kind', () => {+ expect(NOTICE_CODES.degraded_recall.kind).toBe('degraded');+ for (const c of ['source_binding_narrowed', 'degraded_dedup', 'synthesis_keyless', 'think_not_saved', 'listing_truncated'] as const) {+ expect(NOTICE_CODES[c].kind).toBe('info');+ }+ });++ test('ranking-only degradation is no notice; recall-affecting stages are named and say "not absence"', () => {+ expect(degradedRecallNotice([{ stage: 'reranker_skipped' }], { config: keylessUnchosen, transport: 'stdio' })).toBeNull();+ const n = degradedRecallNotice([{ stage: 'expansion_failed', reason: 'timeout' }], { config: keylessUnchosen, transport: 'stdio' })!;+ expect(n.code).toBe('degraded_recall');+ expect(n.kind).toBe('degraded');+ expect(n.why).toContain('expansion_failed');+ expect(n.why).toContain('never as "the brain has nothing on this"');+ expect(n.fix?.argv).toEqual(['gbrain', 'doctor', '--json']);+ });++ test('keyword-only on a brain without a key: the enablement fix asks (credentials + paid)', async () => {+ await withEnv(NO_KEYS, async () => {+ const n = degradedRecallNotice([{ stage: 'embed_unavailable', reason: 'no_provider' }], { config: keylessUnchosen, transport: 'stdio' })!;+ expect(n.fix?.consent).toEqual(['credentials', 'paid']);+ expect(n.user_message).toBeTruthy();+ });+ });++ test('keyless by the user\'s choice: the notice states the limit but never coaches', async () => {+ await withEnv(NO_KEYS, async () => {+ const n = degradedRecallNotice(['keyword_only_no_embedding_provider'], { config: keylessByChoice, transport: 'stdio' })!;+ expect(n.fix).toBeUndefined();+ expect(n.user_message).toBeUndefined();+ expect(n.why).toContain("keyword-only by the user's choice");+ expect(degradedDedupNotice(keylessByChoice).fix).toBeUndefined();+ });+ });++ test('recallStagesFor reads each op\'s own degradation marker', () => {+ expect(recallStagesFor('search', [], { retrieval: { degraded: [{ stage: 'reranker_skipped' }, { stage: 'embed_unavailable' }] } })).toEqual(['embed_unavailable']);+ expect(recallStagesFor('recall', { facts: [], search_degraded: 'keyword_only_no_embedding_provider' }, {})).toEqual(['keyword_only_no_embedding_provider']);+ expect(recallStagesFor('context_pack', { degraded_reason: 'deadline' }, {})).toEqual(['deadline']);+ expect(recallStagesFor('think', { warnings: ['QUESTION_EMBED_FAILED'] }, {})).toEqual(['embed_unavailable']);+ expect(recallStagesFor('get_page', {}, {})).toEqual([]);+ });+});++describe('degraded recall over MCP dispatch (keyless PGLite)', () => {+ async function seedPage() {+ await engine.putPage('notes/alpha', { type: 'note', title: 'Alpha', compiled_truth: 'Alpha body about widgets.', timeline: '', frontmatter: {} }, { sourceId: 'default' });+ }++ test('stdio: content[0] unchanged, a prefixed degraded block + _meta.gbrain_notices, once per session', async () => {+ await withEnv(NO_KEYS, async () => {+ await seedPage();+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default', config: keylessUnchosen };+ const first = await dispatchToolCall(engine as any, 'search', { query: 'widgets' }, opts);+ expect(first.isError).toBeUndefined();+ expect(Array.isArray(JSON.parse(first.content[0].text))).toBe(true);+ const block = first.content.find(c => c.text.startsWith('[gbrain notice degraded_recall kind=degraded]'));+ expect(block).toBeDefined();+ expect(block!.text).toContain('embed_unavailable');+ const meta = first._meta?.gbrain_notices as Array<{ code: string; contract_version: number }>;+ expect(meta.some(n => n.code === 'degraded_recall' && n.contract_version === 1)).toBe(true);+ // Process ledger: the stdio session saw it already.+ const second = await dispatchToolCall(engine as any, 'search', { query: 'widgets' }, opts);+ expect(second.content.some(c => c.text.startsWith('[gbrain notice degraded_recall'))).toBe(false);+ });+ }, 60_000);++ test('HTTP: degraded notices ride every affected call', async () => {+ await withEnv(NO_KEYS, async () => {+ await seedPage();+ const { NoticeLedger } = await import('../src/core/notice-ledger.ts');+ const opts = {+ remote: true, transport: 'http' as const, sourceId: 'default', config: keylessUnchosen, noticeLedger: new NoticeLedger(),+ auth: { token: 't', clientId: 'client-a', clientName: 'a', scopes: ['read'], expiresAt: Date.now() / 1000 + 3600 } as any,+ };+ for (let i = 0; i < 2; i++) {+ const res = await dispatchToolCall(engine as any, 'search', { query: 'widgets' }, opts);+ expect(res.content.some(c => c.text.startsWith('[gbrain notice degraded_recall kind=degraded]'))).toBe(true);+ }+ });+ }, 60_000);+});++describe('source_binding_narrowed', () => {+ const binding = { sourceId: 'work', via: 'GBRAIN_SOURCE' as const, sourceIds: ['work', 'personal'], optedOut: [] };++ test('an empty unqualified bound read names the binding and the explicit read', () => {+ const n = sourceBindingNarrowedNotice('search', { query: 'x' }, [], binding)!;+ expect(n.code).toBe('source_binding_narrowed');+ expect(n.why).toContain("bound to source 'work' by GBRAIN_SOURCE");+ expect(n.fix?.mcp).toEqual({ tool: 'search', arguments: { query: 'x', source_id: 'personal' } });+ });++ test('silent when the read named a source, found something, or nothing else is readable', () => {+ expect(sourceBindingNarrowedNotice('search', { query: 'x', source_id: 'work' }, [], binding)).toBeNull();+ expect(sourceBindingNarrowedNotice('search', { query: 'x' }, [{ slug: 'a' }], binding)).toBeNull();+ expect(sourceBindingNarrowedNotice('search', { query: 'x' }, [], { ...binding, sourceIds: ['work'] })).toBeNull();+ expect(sourceBindingNarrowedNotice('get_page', { slug: 'x' }, [], binding)).toBeNull();+ });++ test('opted-out sources are named without a fix', () => {+ const n = sourceBindingNarrowedNotice('recall', {}, { facts: [] }, { ...binding, sourceIds: ['work'], optedOut: ['private'] })!;+ expect(n.why).toContain('opted out of federated reads): private');+ expect(n.fix).toBeUndefined();+ });++ test('dispatch attaches it to an empty bound stdio read every time (per-call notice)', async () => {+ await withEnv(NO_KEYS, async () => {+ await engine.executeRaw(`INSERT INTO sources (id, name, config) VALUES ('work', 'work', '{}'::jsonb), ('personal', 'personal', '{}'::jsonb) ON CONFLICT DO NOTHING`);+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'work', explicitReadBinding: binding, config: keylessUnchosen };+ for (let i = 0; i < 2; i++) {+ const res = await dispatchToolCall(engine as any, 'list_pages', {}, opts);+ expect(JSON.parse(res.content[0].text)).toEqual([]);+ expect(res.content.some(c => c.text.startsWith('[gbrain notice source_binding_narrowed kind=info]'))).toBe(true);+ }+ });+ }, 60_000);+});++describe('keyless answers ask before spending (F8/F9)', () => {+ test('the chat-key fix names both providers, asks, and never puts a key on a command line', () => {+ const fix = chatKeyFix();+ expect(fix.consent).toEqual(['credentials', 'paid']);+ expect(fix.actor).toBe('user');+ expect(fix.why).toContain('ANTHROPIC_API_KEY');+ expect(fix.why).toContain('OPENAI_API_KEY');+ expect(fix.why).toContain('Free fallback');+ expect(fix.argv?.join(' ')).not.toMatch(/sk-|api_key/);+ });++ test('think keyless + not-saved notices are info and carry their reason', () => {+ expect(keylessThinkNotice().kind).toBe('info');+ expect(keylessThinkNotice().fix?.consent).toEqual(['credentials', 'paid']);+ expect(thinkNotSavedNotice().why).toContain('saved_slug: null');+ });+});