Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(notices): degraded_recall shows on every affected call on stdio and CLI
garrytan33528c0c7ad8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 05d91f51be..219c5f98bb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,13 +10,14 @@ credits are retained; no result has been reassigned to another provider. Originaidentifiers and attribution are available in the pre-removal Git revision`6040075c6cb95be5881cc2e1b76ef7d71f4e5d29` (retained on 2026-09-23).-## [Unreleased] - low-hanging fruit wave lane B: leaner search rows (GBRA-81)+## [Unreleased] - low-hanging fruit wave lane B: leaner search rows, degraded_recall on every affected call (GBRA-81)### Itemized changes- **Lean search rows drop `id` where `fetch` is not callable.** Remote `search` and `query` lean rows carry `id` (the deep-research `fetch` key, base64 of `source_id` and `slug`, so a duplicate of two fields already in the row) only when `fetch` is callable on the caller's surface at call time. MCP dispatch threads one `isCallable(op)` predicate into `OperationContext`, built from the same check tools/list uses: the stdio session's surface after any `request_tools` widening, the HTTP client's effective surface and scopes under the server ceiling. `fields: "full"`, `mcp.result_rows: full`, gbrain's thin client and the local CLI are unchanged. On the committed Cat 40 Hard transcripts (served on `starter`, 3,169 `search` calls) a keyless replay (`scripts/replay-lean-row-savings.ts`) saves 9.52% of `search` characters on the starter surface and 1.35% on the full surface, where `id` stays and only score rounding applies.- **Lean-row `score` prints 4 significant digits.** Rounding happens only in `leanRow`, so full rows and trusted local callers keep the raw float; RRF-scale scores are small, so fixed decimals would have collapsed them. Two scores print equal only when they agree to 4 significant digits, and order never inverts.- **`fetch` without an id names both routes.** The refusal says to re-run `search` once `fetch` is callable, or to pass the row's slug (accepted when unambiguous in the caller's read scope).+- **`degraded_recall` shows on every affected call on stdio and the CLI.** Transient degradations (`rerank_failed`, `embed_timeout`, a failed keyword or title arm, every other per-call stage) are no longer deduped per session, so a failure after a different earlier failure, or the same failure after a recovery, always carries its notice. A notice made only of configuration-persistent stages (a keyless brain's `embed_unavailable`, about 600 characters on every search otherwise) carries an unrendered `dedupe_key` of its sorted unique stage/reason pairs, which the notice ledger dedupes on per session and the wire never shows. HTTP stays per call. `docs/protocol/AGENT_OPERATOR_v1.md` now states one rule for stdio, CLI and HTTP.## [0.60.178.0] - 2026-10-12diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex 1a08a04848..fd283f5384 100644--- a/docs/architecture/key-files/agent-contract.md+++ b/docs/architecture/key-files/agent-contract.md@@ -9,7 +9,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `src/core/error-registry.ts` — `CODES`: one row per literal error code thrown in `src/` (class, summary, optional why/reasons/docs/suggestion/diagnostic-only fix/effects/actor/`legacy_error`/`renamed_from`/`exit`/`retryable`); `RegistryCode` is its key union. `NOTICE_CODES`: notice codes with their kind (mute accepts coaching/info only). New codes: add a row, then `bun run build:error-codes`. Completeness is AST-checked by `test/error-catalogue.test.ts` and `scripts/check-agent-contract.ts`.- `src/core/error-docs.ts` — renders registry rows (meaning · why · next step · who acts/consent · verify · exit · retryable) for `docs/guides/error-codes.md` (`scripts/build-error-codes.ts`, `check:error-codes` in verify) and `gbrain errors` (`src/cli/commands/errors.ts`: `<code>`, `--changed`, list; `--json`; unknown code exits 2 with a did-you-mean).- `src/core/agent-contract-log.ts` — E11 seam: `recordAgentContractEvent` appends `{ts, op|command, transport, code, has_suggestion | effects, outcome, fault}` (never params or messages) to `<GBRAIN_HOME>/agent-contract/events.jsonl`, bounded (halved past 1 MiB), synchronous, fail-open. `readAgentContractEvents` feeds doctor's `agent_contract` check (`src/commands/doctor/checks/agent-contract.ts`).-- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`) and, on HTTP, `degraded`/`safety` notices are never deduped; at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute).+- `src/core/notice-ledger.ts` — notice dedupe/budget/mute. `NoticeLedger.tally(audience, key)` counts per-session events (dispatch counts reranker-degraded search/query calls with it and records `_meta.retrieval.rerank_degraded`). `NoticeLedger.admit(notices, {transport, principal, sessionId}, muted)`: stdio uses `processNoticeLedger()`; HTTP passes `ServeHttpContext.noticeLedger` (keyed by principal + transport-resolved session id, 10k keys, 24 h TTL). Per-call codes (`PER_CALL_NOTICE_CODES`: `degraded_recall`, `empty_retrieval`, `unknown_param`, `listing_truncated`, `source_binding_narrowed`, `local_transcripts`, `held_files`, `mention_index`, …) and, on HTTP, `degraded`/`safety` notices are never deduped, except that a notice's unrendered `Notice.dedupe_key` replaces its code as the dedupe identity and dedupes a per-call code once per session per key on stdio/CLI (`degradedRecallNotice` sets it only when every stage/reason pair is configuration-persistent: a keyless brain's `embed_unavailable`; HTTP ignores it for degraded notices; `renderNotice` never copies it); at most 2 coaching notices per session. Mutes apply to coaching/info notices and to `MUTEABLE_ASK_CODES` (only `first_run_decisions`). Mute store `<GBRAIN_HOME>/notices/muted.json`: owner list (global) + per-client lists; `mute_notice` op (`src/core/ops/notices.ts`, write scope; HTTP per client, stdio under the `stdio` audience that dispatch reads on stdio) and `gbrain notices mute|unmute|list` (`src/cli/commands/notices.ts`, owner; `unmuteNoticeForOwner` clears the global and the `stdio` lists, `list` shows both). Tests: `test/notice-ledger.test.ts`, `test/mcp-onboarding.test.ts` (stdio mute across a fresh process, MCP mute → CLI unmute).- `src/core/ops/callable.ts` — `isCallable(op, {transport, surface, scopes, publishGates, allowedOps})`: the one predicate behind stdio `stdioVisibleTools`, serve-http `listMcpTools`, the legacy bearer transport's tools/list, and `dispatchRenderContext` (which tools a fix may name). `publishGatesFromDisabled` converts the gate resolver's disabled-op set. Test: `test/callable-predicate.test.ts` (list ⇔ pre-A2 filters; list ⇔ dispatch on surface/locality).- `src/cli/cli-error.ts` — the CLI's one error writer (D1): `writeCliError`/`exitCliError` render through `renderCliError` (human `Error [code]` / `Fix:` / `Why:` / `Docs:` on stderr; under `--json` one envelope on stdout plus the human lines on stderr) and record the code for the guard's fallback document; a `legacy` shape (unknown flag's `{status, reason:'invalid_flag', message}`, `pglite_busy`'s `next_action`) leads, keeps its values and stays one line. `usageError` (`invalid_params` / `unknown_flag` / `unknown_command`, exit 2), `unknownFlagError` (did-you-mean from the command's curated help flags, else the acceptance registry), `writeFatalCliError` (the `import.meta.main` seam; keeps the `GBRAIN_DB_ACCESS` marker + remediation on human output). Test: `test/cli-error-render.test.ts`.- `src/cli/help/<command>.ts` + `src/cli/help/render.ts` + `src/cli/help/validate.ts` — D3/D4 curated CLI help. Each spec module exports `help: CliHelpSpec` (`summary`, `usage`, `flags: [{name, type: boolean|string|number|enum, values?, desc, consent?}]`, 2–4 `examples`, `end_of_options?`) and is loaded lazily through its command-table record's `help: () => import('./help/<name>.ts')` (literal, so `bun build --compile` bundles it and `gbrain --version` loads none; pinned by `test/cli-command-table.test.ts` and `scripts/check-compile-autoload.sh`). Curated today: doctor, import, serve, apply-migrations, autopilot, status, onboard; every curated flag must be in the generated acceptance registry and `--yes` is listed wherever the handler parses it. `printCuratedHelp` answers `gbrain <cmd> --help`/`-h` first in main()'s help short-circuit, engine-free (human table with type/values/consent; `--help --json` one document `{command, …spec, contract_version}`). `curatedFlagError(command, args)` (called in main() after the unknown-flag check) refuses a missing/non-numeric `number` value or an out-of-set `enum` value with `invalid_params` (exit 2) via `flagValueError`, example value drawn from the spec's examples; `--flag=value` and `--flag value`, stops at a bare `--`; `string` flags (e.g. onboard's `--max-usd off`) are not checked. `unknownFlagError` draws did-you-mean candidates from the curated flags. Tests: `test/cli-help-curated.test.ts`, `test/cli-help-curated-cli.test.ts`.diff --git a/docs/protocol/AGENT_OPERATOR_v1.md b/docs/protocol/AGENT_OPERATOR_v1.mdindex cdf405fcd2..15d976138f 100644--- a/docs/protocol/AGENT_OPERATOR_v1.md+++ b/docs/protocol/AGENT_OPERATOR_v1.md@@ -745,12 +745,20 @@ final document.| `coaching` | the setup limits what the user is trying to do | mention it once, at a natural point; follow `fix.next` if the user wants it || `info` | context for this result | use it; no action needed |-**Dedupe and budget.** On stdio, a notice shows once per server process. HTTP-is stateless, so dedupe is per authenticated client and session, and-`degraded` and `safety` notices ride every affected call. At most 2-`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)-are never deduped.+**Dedupe and budget.** On stdio and the CLI, a notice shows once per process,+except the notices that describe one call's result. HTTP is stateless, so+dedupe is per authenticated client and session, and `degraded` and `safety`+notices ride every affected call. At most 2 `coaching` notices per session.+Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,+`unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)+are never deduped on any transport, with one exception: a `degraded_recall`+whose only stages come from the brain's configuration (`embed_unavailable` on+a keyless brain, which degrades every search the same way) shows once per+stdio or CLI session. A transient degradation (`rerank_failed`,+`embed_timeout`, a failed keyword or title arm, or any other stage) shows on+every affected call, so a failure, a recovery and the same failure again show+the notice twice. A notice missing from a later call never means that call+was healthy: `_meta.retrieval.degraded` records every call's stages.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`renders `next: wait`: repeat the same call (the fix carries it) after the delay@@ -784,7 +792,7 @@ instead.| `behavior_changes` (safety) | the first tool result per brain | the first tool result per authenticated client (names no chain entries or providers) | once, on stderr, on the first command; `gbrain doctor --only behavior_changes` reads it again || `chat_fallback_hop` (safety) | the first fallback hop of the server process | never | the first hop of the command || `backup_coverage` | once per process | never | the CLI startup rail |-| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call | every affected call (redacted) | the command's own notices |+| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call (a keyless brain's configuration-only `degraded_recall`: once per session) | every affected call (redacted) | the command's own notices |HTTP gets no onboarding coaching because the counts are brain-wide (they crosssource-scoped grants) and every remedy runs on the brain host, which a remotediff --git a/llms-full.txt b/llms-full.txtindex d19692b31f..43b59c7a84 100644--- a/llms-full.txt+++ b/llms-full.txt@@ -3951,12 +3951,20 @@ final document.| `coaching` | the setup limits what the user is trying to do | mention it once, at a natural point; follow `fix.next` if the user wants it || `info` | context for this result | use it; no action needed |-**Dedupe and budget.** On stdio, a notice shows once per server process. HTTP-is stateless, so dedupe is per authenticated client and session, and-`degraded` and `safety` notices ride every affected call. At most 2-`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)-are never deduped.+**Dedupe and budget.** On stdio and the CLI, a notice shows once per process,+except the notices that describe one call's result. HTTP is stateless, so+dedupe is per authenticated client and session, and `degraded` and `safety`+notices ride every affected call. At most 2 `coaching` notices per session.+Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,+`unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)+are never deduped on any transport, with one exception: a `degraded_recall`+whose only stages come from the brain's configuration (`embed_unavailable` on+a keyless brain, which degrades every search the same way) shows once per+stdio or CLI session. A transient degradation (`rerank_failed`,+`embed_timeout`, a failed keyword or title arm, or any other stage) shows on+every affected call, so a failure, a recovery and the same failure again show+the notice twice. A notice missing from a later call never means that call+was healthy: `_meta.retrieval.degraded` records every call's stages.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`renders `next: wait`: repeat the same call (the fix carries it) after the delay@@ -3990,7 +3998,7 @@ instead.| `behavior_changes` (safety) | the first tool result per brain | the first tool result per authenticated client (names no chain entries or providers) | once, on stderr, on the first command; `gbrain doctor --only behavior_changes` reads it again || `chat_fallback_hop` (safety) | the first fallback hop of the server process | never | the first hop of the command || `backup_coverage` | once per process | never | the CLI startup rail |-| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call | every affected call (redacted) | the command's own notices |+| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call (a keyless brain's configuration-only `degraded_recall`: once per session) | every affected call (redacted) | the command's own notices |HTTP gets no onboarding coaching because the counts are brain-wide (they crosssource-scoped grants) and every remedy runs on the brain host, which a remotediff --git a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.mdindex 7d4dd9cfb3..4df98392b7 100644--- a/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-coding/skills/conventions/agent-operator-protocol.md@@ -747,12 +747,20 @@ final document.| `coaching` | the setup limits what the user is trying to do | mention it once, at a natural point; follow `fix.next` if the user wants it || `info` | context for this result | use it; no action needed |-**Dedupe and budget.** On stdio, a notice shows once per server process. HTTP-is stateless, so dedupe is per authenticated client and session, and-`degraded` and `safety` notices ride every affected call. At most 2-`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)-are never deduped.+**Dedupe and budget.** On stdio and the CLI, a notice shows once per process,+except the notices that describe one call's result. HTTP is stateless, so+dedupe is per authenticated client and session, and `degraded` and `safety`+notices ride every affected call. At most 2 `coaching` notices per session.+Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,+`unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)+are never deduped on any transport, with one exception: a `degraded_recall`+whose only stages come from the brain's configuration (`embed_unavailable` on+a keyless brain, which degrades every search the same way) shows once per+stdio or CLI session. A transient degradation (`rerank_failed`,+`embed_timeout`, a failed keyword or title arm, or any other stage) shows on+every affected call, so a failure, a recovery and the same failure again show+the notice twice. A notice missing from a later call never means that call+was healthy: `_meta.retrieval.degraded` records every call's stages.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`renders `next: wait`: repeat the same call (the fix carries it) after the delay@@ -786,7 +794,7 @@ instead.| `behavior_changes` (safety) | the first tool result per brain | the first tool result per authenticated client (names no chain entries or providers) | once, on stderr, on the first command; `gbrain doctor --only behavior_changes` reads it again || `chat_fallback_hop` (safety) | the first fallback hop of the server process | never | the first hop of the command || `backup_coverage` | once per process | never | the CLI startup rail |-| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call | every affected call (redacted) | the command's own notices |+| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call (a keyless brain's configuration-only `degraded_recall`: once per session) | every affected call (redacted) | the command's own notices |HTTP gets no onboarding coaching because the counts are brain-wide (they crosssource-scoped grants) and every remedy runs on the brain host, which a remotediff --git a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.mdindex 7d4dd9cfb3..4df98392b7 100644--- a/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md+++ b/plugin-variants/gbrain-daily/skills/conventions/agent-operator-protocol.md@@ -747,12 +747,20 @@ final document.| `coaching` | the setup limits what the user is trying to do | mention it once, at a natural point; follow `fix.next` if the user wants it || `info` | context for this result | use it; no action needed |-**Dedupe and budget.** On stdio, a notice shows once per server process. HTTP-is stateless, so dedupe is per authenticated client and session, and-`degraded` and `safety` notices ride every affected call. At most 2-`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)-are never deduped.+**Dedupe and budget.** On stdio and the CLI, a notice shows once per process,+except the notices that describe one call's result. HTTP is stateless, so+dedupe is per authenticated client and session, and `degraded` and `safety`+notices ride every affected call. At most 2 `coaching` notices per session.+Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,+`unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)+are never deduped on any transport, with one exception: a `degraded_recall`+whose only stages come from the brain's configuration (`embed_unavailable` on+a keyless brain, which degrades every search the same way) shows once per+stdio or CLI session. A transient degradation (`rerank_failed`,+`embed_timeout`, a failed keyword or title arm, or any other stage) shows on+every affected call, so a failure, a recovery and the same failure again show+the notice twice. A notice missing from a later call never means that call+was healthy: `_meta.retrieval.degraded` records every call's stages.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`renders `next: wait`: repeat the same call (the fix carries it) after the delay@@ -786,7 +794,7 @@ instead.| `behavior_changes` (safety) | the first tool result per brain | the first tool result per authenticated client (names no chain entries or providers) | once, on stderr, on the first command; `gbrain doctor --only behavior_changes` reads it again || `chat_fallback_hop` (safety) | the first fallback hop of the server process | never | the first hop of the command || `backup_coverage` | once per process | never | the CLI startup rail |-| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call | every affected call (redacted) | the command's own notices |+| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call (a keyless brain's configuration-only `degraded_recall`: once per session) | every affected call (redacted) | the command's own notices |HTTP gets no onboarding coaching because the counts are brain-wide (they crosssource-scoped grants) and every remedy runs on the brain host, which a remotediff --git a/plugin/skills/conventions/agent-operator-protocol.md b/plugin/skills/conventions/agent-operator-protocol.mdindex 7d4dd9cfb3..4df98392b7 100644--- a/plugin/skills/conventions/agent-operator-protocol.md+++ b/plugin/skills/conventions/agent-operator-protocol.md@@ -747,12 +747,20 @@ final document.| `coaching` | the setup limits what the user is trying to do | mention it once, at a natural point; follow `fix.next` if the user wants it || `info` | context for this result | use it; no action needed |-**Dedupe and budget.** On stdio, a notice shows once per server process. HTTP-is stateless, so dedupe is per authenticated client and session, and-`degraded` and `safety` notices ride every affected call. At most 2-`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)-are never deduped.+**Dedupe and budget.** On stdio and the CLI, a notice shows once per process,+except the notices that describe one call's result. HTTP is stateless, so+dedupe is per authenticated client and session, and `degraded` and `safety`+notices ride every affected call. At most 2 `coaching` notices per session.+Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,+`unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)+are never deduped on any transport, with one exception: a `degraded_recall`+whose only stages come from the brain's configuration (`embed_unavailable` on+a keyless brain, which degrades every search the same way) shows once per+stdio or CLI session. A transient degradation (`rerank_failed`,+`embed_timeout`, a failed keyword or title arm, or any other stage) shows on+every affected call, so a failure, a recovery and the same failure again show+the notice twice. A notice missing from a later call never means that call+was healthy: `_meta.retrieval.degraded` records every call's stages.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`renders `next: wait`: repeat the same call (the fix carries it) after the delay@@ -786,7 +794,7 @@ instead.| `behavior_changes` (safety) | the first tool result per brain | the first tool result per authenticated client (names no chain entries or providers) | once, on stderr, on the first command; `gbrain doctor --only behavior_changes` reads it again || `chat_fallback_hop` (safety) | the first fallback hop of the server process | never | the first hop of the command || `backup_coverage` | once per process | never | the CLI startup rail |-| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call | every affected call (redacted) | the command's own notices |+| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call (a keyless brain's configuration-only `degraded_recall`: once per session) | every affected call (redacted) | the command's own notices |HTTP gets no onboarding coaching because the counts are brain-wide (they crosssource-scoped grants) and every remedy runs on the brain host, which a remotediff --git a/skills/conventions/agent-operator-protocol.md b/skills/conventions/agent-operator-protocol.mdindex 7d4dd9cfb3..4df98392b7 100644--- a/skills/conventions/agent-operator-protocol.md+++ b/skills/conventions/agent-operator-protocol.md@@ -747,12 +747,20 @@ final document.| `coaching` | the setup limits what the user is trying to do | mention it once, at a natural point; follow `fix.next` if the user wants it || `info` | context for this result | use it; no action needed |-**Dedupe and budget.** On stdio, a notice shows once per server process. HTTP-is stateless, so dedupe is per authenticated client and session, and-`degraded` and `safety` notices ride every affected call. At most 2-`coaching` notices per session. Notices that describe one call's result-(`empty_retrieval`, `unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)-are never deduped.+**Dedupe and budget.** On stdio and the CLI, a notice shows once per process,+except the notices that describe one call's result. HTTP is stateless, so+dedupe is per authenticated client and session, and `degraded` and `safety`+notices ride every affected call. At most 2 `coaching` notices per session.+Notices that describe one call's result (`degraded_recall`, `empty_retrieval`,+`unknown_param`, `listing_truncated`, `delta_incomplete`, `facts_unembedded`)+are never deduped on any transport, with one exception: a `degraded_recall`+whose only stages come from the brain's configuration (`embed_unavailable` on+a keyless brain, which degrades every search the same way) shows once per+stdio or CLI session. A transient degradation (`rerank_failed`,+`embed_timeout`, a failed keyword or title arm, or any other stage) shows on+every affected call, so a failure, a recovery and the same failure again show+the notice twice. A notice missing from a later call never means that call+was healthy: `_meta.retrieval.degraded` records every call's stages.**Degraded retry hint.** A `degraded` notice whose fix has `actor: provider`renders `next: wait`: repeat the same call (the fix carries it) after the delay@@ -786,7 +794,7 @@ instead.| `behavior_changes` (safety) | the first tool result per brain | the first tool result per authenticated client (names no chain entries or providers) | once, on stderr, on the first command; `gbrain doctor --only behavior_changes` reads it again || `chat_fallback_hop` (safety) | the first fallback hop of the server process | never | the first hop of the command || `backup_coverage` | once per process | never | the CLI startup rail |-| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call | every affected call (redacted) | the command's own notices |+| `degraded_recall`, `empty_retrieval`, `source_binding_narrowed` and the other per-call notices | every affected call (a keyless brain's configuration-only `degraded_recall`: once per session) | every affected call (redacted) | the command's own notices |HTTP gets no onboarding coaching because the counts are brain-wide (they crosssource-scoped grants) and every remedy runs on the brain host, which a remotediff --git a/skills/skills.lock.json b/skills/skills.lock.jsonindex 412e3d7230..8a26a1d24b 100644--- a/skills/skills.lock.json+++ b/skills/skills.lock.json@@ -44,7 +44,7 @@"concept-synthesis/routing-eval.jsonl": "96dbd7d9c1b606e9e06262d0c06282399741e2bccb8eeb7b9ca88c20f44cda0e","context-audit/SKILL.md": "6d786629d40544ddaab4f4e6e333569d270bcb8b581589dc16fb9f8bcb4f6207","context-audit/routing-eval.jsonl": "fb1832e24cc1b04163a74c5cde72bca53050a66246ca902e1a5f40303f52b5ab",- "conventions/agent-operator-protocol.md": "d22b616c90d84d7035cf2c56ed2c59d361b06a0499f548ae21e81bd23823efce",+ "conventions/agent-operator-protocol.md": "3fbd096433e83a428a5db4e65aa786d1f6dc7eb2ccea757810aee04bdb5ec0a1","conventions/brain-first.md": "d9b18321150830d38586f5bd23ce9de735f08ac3b54d7ac63bc3184a61e17ef1","conventions/brain-routing.md": "392998d9a109b330c9225af4ca5c8798b0ff02eba4d441c93fdb7c263687d0c6","conventions/calibration.md": "500dc26bd7c8400f50dc4c16fd83f1a588f3e7e68c59050a21fd8a0f69e4d198",diff --git a/src/core/agent-output.ts b/src/core/agent-output.tsindex 251ecaa4ae..cfc7bc39e1 100644--- a/src/core/agent-output.ts+++ b/src/core/agent-output.ts@@ -76,6 +76,13 @@ export interface Notice {fix?: Action;user_message?: string;decisions?: Decision[];+ /**+ * Unrendered: the NoticeLedger's dedupe identity. A per-call code carrying+ * one is deduped per session under `code` + this key instead of riding+ * every call; any code carrying one dedupes under it instead of `code`+ * alone. renderNotice never copies it, so it never reaches the wire.+ */+ dedupe_key?: string;}export interface RenderedNotice extends Omit<Notice, 'fix'> { fix?: RenderedAction; contract_version: 1 }diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.tsindex 3fdeab2c41..46c4a06592 100644--- a/src/core/behavior-change-notice.ts+++ b/src/core/behavior-change-notice.ts@@ -469,6 +469,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }{ since: '0.60.177.0', text: 'A brain whose persistence mode cannot be read (no `persistence_brain` row, more than one, or an `enabled` value that is not a boolean) now refuses every write, sync, connector run, activation and maintenance step that depends on it with `storage_error` (`detail: persistence_mode_unknown`, fix: `gbrain sources writer status --probe --json`) instead of treating the brain as unmanaged and writing around the owner; only a well-formed `enabled: false` row selects the unmanaged path. A managed `gbrain sync --full` tree walk no longer soft-deletes a page it imported from an untracked working-tree file: a page whose stored import provenance is the working tree, or is unknown, is kept while its file is still present (`working_tree_kept` in the result), and a page imported from a Git blob still follows Git. A soft deletion is not harmless (recall stops at once and the purge lifecycle follows), so this applies on the next sync without opt-in. A first sync, a `--full` sync or one commit that alone exceeds the 100,000-entry / 16 MiB cursor bound now completes in path slices (every import slice, then bounded deletion slices, pinned at one target; the slice cursor is checkpointed with each slice and `last_commit` moves only when the whole target settles) instead of refusing with `request_too_large`; a scheduled sync takes one slice per run and `gbrain sync --drain` takes them all. One file whose manifest entry alone exceeds the byte bound still refuses by name.' },// Low-hanging fruit wave lane B (GBRA-81, items 2 and 3). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.{ since: '0.60.178.0', text: 'Lean `search` and `query` rows (remote callers) now carry `id`, the `fetch` key, only when the connection can call `fetch` at that moment: a `full` surface, a stdio session `request_tools` widened, or an HTTP client whose surface and scopes include it. On `starter` and `verbs` connections, `fetch` was never callable, so the row\'s `slug` and `source_id` identify the page; `fields: "full"` returns every field, `id` included, and the `mcp.result_rows: full` host setting does so for every remote caller. Lean-row `score` now prints 4 significant digits. The local CLI and gbrain\'s thin client keep full rows, unchanged. `fetch` called without an id now says to re-run `search` once `fetch` is callable, or to pass the row\'s slug.' },+ { since: '0.60.178.0', text: 'On stdio MCP and the CLI, the `degraded_recall` notice now shows on every call a transient degradation affects (`rerank_failed`, `embed_timeout`, a failed keyword or title arm, and every other per-call stage); it used to show once per session, so a rerank failure after an earlier embedding timeout returned fused-order results with no notice. A keyless brain whose only degradation is `embed_unavailable` still shows it once per session. HTTP is unchanged: every affected call. `_meta.retrieval.degraded` still records every call\'s stages.' },];/** The newest disclosed change's release: the notice id moves only when a release adds rows. */diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex 374549ff84..d051c61df5 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -62,6 +62,16 @@ export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidancefacts_embedding_column_missing: { why: 'the facts table has no embedding column, so saved facts were ranked by word overlap alone', fix: 'doctor' },};+/**+ * Stage/reason pairs that come from the brain's configuration, not from this+ * call: a keyless install (`--no-embedding`, or no embedding provider)+ * degrades every search the same way, so its notice shows once per session.+ * Every other recall stage is transient and rides each affected call.+ */+const CONFIGURATION_PERSISTENT_STAGES: ReadonlySet<string> = new Set([+ 'embed_unavailable:embedding_disabled', 'embed_unavailable:no_provider', 'keyword_only_no_embedding_provider:',+]);+const NOT_ABSENCE = 'Treat a thin or empty result as "not found with a degraded search", never as "the brain has nothing on this".';/** Why each `rerank_failed` reason happened (closed vocabulary: RerankFailedReason). */@@ -129,6 +139,8 @@ function embeddingsFix(cfg: GBrainConfig | null | undefined, transport: 'stdio'/*** One `degraded_recall` notice for the recall-affecting stages of this call; null when none applies.+ * It rides every affected call, except when all its stage/reason pairs are configuration-persistent:+ * then it carries an unrendered `dedupe_key` (the sorted unique pairs) and shows once per session.* A `rerank_failed` stage names its reason, the fallback (fused order) and, when the caller counts them* (`rerankDegradedCalls`), this session's reranker-degraded calls; its fix follows the reason (`retry`* is the call to repeat after a transient failure) when no other stage needs a fix.@@ -142,6 +154,8 @@ export function degradedRecallNotice(.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 pairs = [...new Set(entries.filter(s => names.includes(s.stage as RecallStage)).map(s => `${s.stage}:${s.reason ?? ''}`))].sort();+ const persistent = pairs.every(p => CONFIGURATION_PERSISTENT_STAGES.has(p));const rerank = names.includes('rerank_failed') ? rerankReason(entries.find(s => s.stage === 'rerank_failed')?.reason) : undefined;const labels = names.map(n => (n === 'rerank_failed' ? `rerank_failed: ${rerank}` : n));const whys = names.map(n => (n === 'rerank_failed'@@ -161,6 +175,7 @@ export function degradedRecallNotice(why: `Recall was degraded (${labels.join(', ')}): ${whys.join('; ')}. ${NOT_ABSENCE}${choice}`,...(fix ? { fix } : {}),...(fix?.user_message ? { user_message: fix.user_message } : {}),+ ...(persistent ? { dedupe_key: pairs.join('|') } : {}),};}diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex d92b4f2639..8183fdc7d9 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -8,6 +8,11 @@* principal. Bounded: 10k keys, 24 h TTL.* - `degraded` and `safety` notices are never deduped on HTTP (attached to* every affected call). At most 2 `coaching` notices per session.+ * - A notice's unrendered `dedupe_key` replaces its code as the dedupe+ * identity, and turns a per-call code into a once-per-session one:+ * `degraded_recall` rides every affected call, except a notice made only of+ * configuration-persistent stages (a keyless brain's `embed_unavailable`),+ * which shows once per session per distinct key.* - Mute applies to `coaching` and `info` only: globally for the local owner* (`gbrain notices mute <code>`), per client on remote transports* (`mute_notice`). Persisted under GBRAIN_HOME.@@ -20,10 +25,10 @@ import type { Notice, Transport } from './agent-output.ts';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. *//** The one muteable `ask`: an unanswered first-run bundle must stay dismissible. Every other ask always shows. */export const MUTEABLE_ASK_CODES: ReadonlySet<string> = new Set(['first_run_decisions']);-export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout', 'facts_unembedded']);+/** Notices that describe THIS call's result (never deduped unless the notice carries a `dedupe_key`): the diagnosis must ride every affected call. */+export const PER_CALL_NOTICE_CODES: ReadonlySet<string> = new Set(['degraded_recall', 'empty_retrieval', 'unknown_param', 'listing_truncated', 'former_relationships_hidden', 'source_binding_narrowed', 'local_transcripts', 'held_files', 'relational_chain', 'mention_index', 'delta_incomplete', 'identity_siblings_capped', 'alias_fanout', 'facts_unembedded']);export interface NoticeAudience {transport: Transport;@@ -68,9 +73,9 @@ export class NoticeLedger {const session = this.session(audience);for (const n of notices) {if ((n.kind === 'coaching' || n.kind === 'info' || MUTEABLE_ASK_CODES.has(n.code)) && muted.has(n.code)) continue;- const always = PER_CALL_NOTICE_CODES.has(n.code)+ const always = (PER_CALL_NOTICE_CODES.has(n.code) && n.dedupe_key === undefined)|| (audience.transport === 'http' && (n.kind === 'degraded' || n.kind === 'safety'));- const key = `${session}|${n.code}`;+ const key = n.dedupe_key === undefined ? `${session}|${n.code}` : `${session}|${n.code}|${n.dedupe_key}`;if (!always && this.seen.has(key)) continue;if (n.kind === 'coaching') {const used = this.coaching.get(session)?.count ?? 0;diff --git a/test/mcp-notice-channels.test.ts b/test/mcp-notice-channels.test.tsindex 01bf0a276c..71c9a5d6f2 100644--- a/test/mcp-notice-channels.test.ts+++ b/test/mcp-notice-channels.test.ts@@ -17,6 +17,8 @@ import {chatKeyFix, keylessThinkNotice, thinkNotSavedNotice, degradedDedupNotice,} from '../src/core/interop-notices.ts';import { withEnv } from './helpers/with-env.ts';+import { importFromContent } from '../src/core/import-file.ts';+import { serializeMarkdown } from '../src/core/markdown.ts';import type { GBrainConfig } from '../src/core/config.ts';let engine: PGLiteEngine;@@ -92,10 +94,34 @@ 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' });}+ /** A page that is indexed and safety-checked, so a keyless search's only degradation is the configuration-persistent embed_unavailable. */+ async function importPage() {+ await importFromContent(engine, 'notes/alpha', serializeMarkdown({}, 'Alpha body about widgets.', '', { type: 'note', title: 'Alpha', tags: [] }), { noEmbed: true, forceRechunk: true });+ }+ const noticeBlocks = (res: { content: Array<{ text: string }> }) => res.content.filter(c => c.text.startsWith('[gbrain notice degraded_recall'));++ test('stdio: two keyless searches show one degraded_recall notice; a transient stage on the same search rides every call', async () => {+ await withEnv(NO_KEYS, async () => {+ await importPage();+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default', config: keylessUnchosen, noticeLedger: new (await import('../src/core/notice-ledger.ts')).NoticeLedger() };+ const first = await dispatchToolCall(engine as any, 'search', { query: 'widgets' }, opts);+ const degraded = (first._meta?.retrieval as { degraded?: Array<{ stage: string; reason?: string }> }).degraded;+ expect(degraded).toEqual([{ stage: 'embed_unavailable', reason: 'no_provider' }]);+ expect(JSON.parse(first.content[0].text).length).toBeGreaterThan(0);+ expect(noticeBlocks(first)).toHaveLength(1);+ const second = await dispatchToolCall(engine as any, 'search', { query: 'widgets' }, opts);+ expect(noticeBlocks(second)).toHaveLength(0);+ // keyword_zero (no match for these terms) is this call's own state: the notice rides each such call.+ for (let i = 0; i < 2; i++) {+ const miss = await dispatchToolCall(engine as any, 'search', { query: 'zeppelin' }, opts);+ expect(noticeBlocks(miss)[0]?.text).toContain('keyword_zero');+ }+ });+ }, 60_000);test('stdio: content[0] unchanged, a prefixed degraded block + _meta.gbrain_notices, once per session', async () => {await withEnv(NO_KEYS, async () => {- await seedPage();+ await importPage();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();diff --git a/test/notice-ledger.test.ts b/test/notice-ledger.test.tsindex f3e6822f92..4b37a077a4 100644--- a/test/notice-ledger.test.ts+++ b/test/notice-ledger.test.ts@@ -29,6 +29,30 @@ describe('NoticeLedger', () => {expect(l.admit([n('tip', 'info')], { ...s1, principal: 'client-b' })).toHaveLength(1);});+ test('degraded_recall rides every call on stdio and CLI; a dedupe_key dedupes it per session per key; HTTP ignores the key', () => {+ const d = (dedupe_key?: string): Notice => ({ ...n('degraded_recall', 'degraded'), ...(dedupe_key ? { dedupe_key } : {}) });+ for (const transport of ['stdio', 'cli'] as const) {+ const l = new NoticeLedger();+ const a = { transport };+ for (let i = 0; i < 3; i++) expect(l.admit([d()], a)).toHaveLength(1);+ expect(l.admit([d('embed_unavailable:no_provider')], a)).toHaveLength(1);+ expect(l.admit([d('embed_unavailable:no_provider')], a)).toHaveLength(0);+ expect(l.admit([d('embed_unavailable:embedding_disabled')], a)).toHaveLength(1);+ expect(l.admit([d()], a)).toHaveLength(1);+ expect(l.admit([d('embed_unavailable:no_provider')], { transport, sessionId: 'other' })).toHaveLength(1);+ }+ const http = new NoticeLedger();+ for (let i = 0; i < 3; i++) expect(http.admit([d('embed_unavailable:no_provider')], { transport: 'http', principal: 'p' })).toHaveLength(1);+ });++ test('a dedupe_key on a non-per-call code dedupes under the key instead of the code', () => {+ const l = new NoticeLedger();+ const a = { transport: 'stdio' as const };+ expect(l.admit([{ ...n('tip', 'info'), dedupe_key: 'a' }], a)).toHaveLength(1);+ expect(l.admit([{ ...n('tip', 'info'), dedupe_key: 'a' }], a)).toHaveLength(0);+ expect(l.admit([{ ...n('tip', 'info'), dedupe_key: 'b' }], a)).toHaveLength(1);+ });+test('at most 2 coaching notices per session', () => {const l = new NoticeLedger();const a = { transport: 'http' as const, principal: 'p' };diff --git a/test/rerank-degraded-notice.serial.test.ts b/test/rerank-degraded-notice.serial.test.tsindex cfd1a5e37d..72bdcf17e9 100644--- a/test/rerank-degraded-notice.serial.test.ts+++ b/test/rerank-degraded-notice.serial.test.ts@@ -5,6 +5,12 @@* operator contract; every affected call's `_meta.retrieval` records the same* without `fields: "full"`.*+ * Low-hanging-fruit item 3: a transient degradation (rerank_failed,+ * embed_timeout, a failed keyword or title arm) shows on every affected call+ * on stdio too; only a configuration-persistent `embed_unavailable` (a+ * keyless brain) shows once per session, keyed by an unrendered+ * `dedupe_key` that never reaches the wire. HTTP stays per call.+ ** Drives the REAL dispatch path (dispatchToolCall → search op handler) with* hybridSearchCached mocked to report the degradation.*@@ -20,13 +26,15 @@ import { DEGRADED_REASONS } from '../src/core/types.ts';import type { RerankFailedReason } from '../src/core/search/rerank.ts';let nextReason: string | undefined = 'unreachable';+/** When set, the stages the next search reports instead of `rerank_failed: nextReason`. */+let nextDegraded: Array<{ stage: string; reason?: string }> | undefined;mock.module('../src/core/search/hybrid.ts', () => ({...realHybrid,hybridSearchCached: async (_engine: unknown, _query: string, opts: { onMeta?: (m: unknown) => void }) => {opts.onMeta?.({vector_enabled: true, expansion_applied: false, detail_resolved: null, retrieved_count: 1,- degraded: nextReason === undefined ? [] : [{ stage: 'rerank_failed', reason: nextReason }],+ degraded: nextDegraded ?? (nextReason === undefined ? [] : [{ stage: 'rerank_failed', reason: nextReason }]),});return [{ page_id: 1, source_id: 'default', slug: 'notes/a', title: 'A', type: 'note', chunk_text: 'a text', score: 1 }];},@@ -110,7 +118,7 @@ describe('rerank_failed notice per reason', () => {});describe('dispatch: per-call meta and session count', () => {- test('stdio: the notice shows once with the count, every call meta records reason, fallback and the running count', async () => {+ test('stdio: the notice rides every affected call with the running count, and every call meta records reason, fallback and count', async () => {const noticeLedger = new NoticeLedger();nextReason = 'unreachable';const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default', noticeLedger };@@ -119,10 +127,10 @@ describe('dispatch: per-call meta and session count', () => {const metas = outs.map(o => (o._meta as Record<string, any>).retrieval);expect(metas.map(m => m.rerank_degraded)).toEqual([1, 2, 3].map(n => ({ reason: 'unreachable', fallback: 'fused_order', calls_this_session: n })));expect(metas.every(m => m.degraded.some((d: { stage: string; reason: string }) => d.stage === 'rerank_failed' && d.reason === 'unreachable'))).toBe(true);- expect(noticeBlock(outs[0])).toContain('rerank_failed: unreachable');- expect(noticeBlock(outs[0])).toContain('reranker-degraded calls this session: 1');- expect(noticeBlock(outs[1])).toBeUndefined();- expect(noticeBlock(outs[2])).toBeUndefined();+ for (const [i, out] of outs.entries()) {+ expect(noticeBlock(out)).toContain('rerank_failed: unreachable');+ expect(noticeBlock(out)).toContain(`reranker-degraded calls this session: ${i + 1}`);+ }});test('HTTP: the notice rides every affected call with the session running count; a healthy call adds nothing', async () => {@@ -144,3 +152,77 @@ describe('dispatch: per-call meta and session count', () => {expect((other._meta as Record<string, any>).retrieval.rerank_degraded.calls_this_session).toBe(1);});});++describe('degraded_recall dedupe: transient per call, configuration-persistent once per session', () => {+ const stdio = () => ({ remote: true, transport: 'stdio' as const, sourceId: 'default', noticeLedger: new NoticeLedger() });+ const search = (opts: Record<string, unknown>, degraded: Array<{ stage: string; reason?: string }>) => {+ nextDegraded = degraded;+ return dispatchToolCall(engineStub, 'search', { query: 'which account' }, opts as never);+ };+ const KEYLESS = [{ stage: 'embed_unavailable', reason: 'no_provider' }];++ test('stdio: embed_timeout then a rerank failure shows two notices', async () => {+ const opts = stdio();+ try {+ const first = await search(opts, [{ stage: 'embed_timeout', reason: 'timeout' }]);+ const second = await search(opts, [{ stage: 'rerank_failed', reason: 'timeout' }]);+ expect(noticeBlock(first)).toContain('embed_timeout');+ expect(noticeBlock(second)).toContain('rerank_failed: timeout');+ } finally { nextDegraded = undefined; }+ });++ test('stdio: failure, recovery, then the same failure shows the notice both times', async () => {+ const opts = stdio();+ try {+ const failed = await search(opts, [{ stage: 'keyword_arm_failed', reason: 'provider_error' }]);+ const healthy = await search(opts, []);+ const again = await search(opts, [{ stage: 'keyword_arm_failed', reason: 'provider_error' }]);+ expect(noticeBlock(failed)).toContain('keyword_arm_failed');+ expect(noticeBlock(healthy)).toBeUndefined();+ expect(noticeBlock(again)).toContain('keyword_arm_failed');+ const title = await search(opts, [{ stage: 'title_arm_failed', reason: 'timeout' }]);+ expect(noticeBlock(await search(opts, [{ stage: 'title_arm_failed', reason: 'timeout' }]))).toContain('title_arm_failed');+ expect(noticeBlock(title)).toContain('title_arm_failed');+ } finally { nextDegraded = undefined; }+ });++ test('stdio: two keyless searches show one notice; a transient failure on top still shows', async () => {+ const opts = stdio();+ try {+ const first = await search(opts, KEYLESS);+ const second = await search(opts, KEYLESS);+ expect(noticeBlock(first)).toContain('embed_unavailable');+ expect(noticeBlock(second)).toBeUndefined();+ const mixed = await search(opts, [...KEYLESS, { stage: 'rerank_failed', reason: 'timeout' }]);+ expect(noticeBlock(mixed)).toContain('rerank_failed: timeout');+ expect(noticeBlock(await search(opts, KEYLESS))).toBeUndefined();+ } finally { nextDegraded = undefined; }+ });++ test('HTTP stays per call, keyless included', async () => {+ const opts = { remote: true, transport: 'http' as const, sourceId: 'default', noticeLedger: new NoticeLedger(), auth: { clientId: 'client-a', scopes: ['read'] }, sessionId: 's1' };+ try {+ for (let i = 0; i < 2; i++) expect(noticeBlock(await search(opts, KEYLESS))).toContain('embed_unavailable');+ for (let i = 0; i < 2; i++) expect(noticeBlock(await search(opts, [{ stage: 'embed_timeout', reason: 'timeout' }]))).toContain('embed_timeout');+ } finally { nextDegraded = undefined; }+ });++ test('dedupe_key is built from sorted unique stage/reason pairs, only for configuration-persistent stages, and never reaches the wire', async () => {+ expect(degradedRecallNotice([{ stage: 'embed_unavailable', reason: 'no_provider' }, { stage: 'embed_unavailable', reason: 'no_provider' }], { transport: 'stdio' })!.dedupe_key)+ .toBe('embed_unavailable:no_provider');+ expect(degradedRecallNotice([{ stage: 'embed_unavailable', reason: 'no_provider' }, { stage: 'embed_unavailable', reason: 'embedding_disabled' }], { transport: 'stdio' })!.dedupe_key)+ .toBe('embed_unavailable:embedding_disabled|embed_unavailable:no_provider');+ expect(degradedRecallNotice(['keyword_only_no_embedding_provider'], { transport: 'stdio' })!.dedupe_key).toBe('keyword_only_no_embedding_provider:');+ for (const transient of [+ [{ stage: 'embed_unavailable', reason: 'provider_error' }], [{ stage: 'embed_timeout', reason: 'timeout' }], [{ stage: 'rerank_failed', reason: 'auth' }],+ [{ stage: 'keyword_arm_failed', reason: 'timeout' }], [{ stage: 'title_arm_failed' }], [...KEYLESS, { stage: 'rerank_failed', reason: 'timeout' }], ['embed_unavailable'],+ ]) expect(degradedRecallNotice(transient, { transport: 'stdio' })!.dedupe_key, JSON.stringify(transient)).toBeUndefined();+ const opts = stdio();+ try {+ const out = await search(opts, KEYLESS);+ expect(noticeBlock(out)).toBeDefined();+ expect(JSON.stringify(out)).not.toContain('dedupe_key');+ expect(JSON.stringify(out)).not.toContain('embed_unavailable:no_provider');+ } finally { nextDegraded = undefined; }+ });+});