Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(search): rerank degradation reason, session count and per-reason fix
garrytan8bf4da0de9e7
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.mdindex a78597d77f..ae68a64789 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.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`: `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/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`.@@ -20,7 +20,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-- `test/cli-contract.test.ts` — D5: `--help` contract for every command-table record (exit 0, non-stub, curated flags only, `--yes` shown where parsed) against the shrink-only `test/fixtures/cli-contract/help-baseline.json`, and one success + one failure row per `json`-declared record.- `src/cli/json-guard.ts` — picks the `--json` guard mode for an invocation: on only when `jsonRequested(argv)` and the command-table record declares `json: 'document' | 'ndjson'`; wires the E11 `json_document_missing` hook. The guard itself is `installStdoutPipeDelivery({ json })` in `src/core/cli-force-exit.ts`: stdout writes and console.log/info/debug go to stderr, only `writeStdoutFinal`/`writeNdjsonLine` reach fd 1, a non-zero exit with no document writes the fallback document, `spawnCliChild` pipes child stdout to stderr. Test: `test/cli-json-guard.test.ts`. A record whose subcommands differ in shape declares `jsonSubcommands` (keyed by the first positional after the command; `eval`). `writeCliError` adds `status:'error'` to the envelope under the ndjson guard; `writeCliRefusal` (cli-error.ts) keeps a site's pre-v1 stderr line and writes the envelope under `--json`. D5 (`test/cli-contract.test.ts`) has one row per declaration, `<command> <sub>` included.- `scripts/check-agent-contract.ts` — syntax-only AST scanner (≈2 s) in `bun run verify` and `guards-manifest.tsv` (fixtures `test/fixtures/guards/check-agent-contract.ts/`). Rules: suggestion-less `OperationError`, `throw new Error` in ops/mcp/handlers, hand-built `fix`/`next_action` command strings, legacy advice keys, raw interactive stdin/readline/raw-mode outside `interaction.ts`/`consent.ts`, raw "re-run with --yes" strings outside `consent.ts`, `stdio: 'inherit'` outside `spawnCliChild`, marker literals outside `agent-output.ts`/`agent-markers.ts`, `verify.argv` naming a non-read-only command (read_only command-table records + a static read-only list), plus unregistered codes and code naming (never baselined). Two more never-baselined rules keep every refusal's next step site-specific: `defaulted-suggestion` (a function that builds an error through `opError`, `new OperationError`, `usageError`, `invalidParam` or `hostOnlyError` from a `*suggestion`/`*hint` parameter with a default, an optional marker or a `??` fallback) and `generic-suggestion` (a suggestion whose whole text is a denylisted phrase such as "see --help", "check your input" or "try again", at a constructor or at a call site of a file-local funnel). `funnelSites(files?)` lists every funnel call site (`invalid`, `fail`, `usage`, `deny`, …) with its literal suggestion texts, resolving file-level string constants; `test/helpers/agent-envelope.ts` (`expectFunnelSuggestions`, `envelopeFor`, `caught`) drives the per-funnel table tests in each module's owner test. Per-rule shrink-only baselines in `scripts/agent-contract-baselines/<rule>.tsv`; `--update` lowers them and refuses growth.-- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.+- `src/core/interop-notices.ts` — Lane F notice producers (pure; callers emit). `DEGRADED_STAGE_GUIDANCE` (closed, typed exhaustive over recall-affecting stages + the verbs' markers) → one `degraded_recall` notice (kind degraded: names the stages, says a thin result is not proof of absence; fix = the embeddings enablement or a doctor diagnostic; a `rerank_failed` stage names its reason, the `fused_order` fallback and the session's reranker-degraded call count, and when no other stage needs a fix its fix follows the reason: `timeout`/`rate_limited` repeat the same call after 5/20 s (`actor: provider`, `next: wait`), `auth` is the user's key (credentials), the rest run doctor verified by `reranker_health` (`test/rerank-degraded-notice.serial.test.ts`); none on a brain keyless by choice, whose why says no query text was sent and that `gbrain doctor --json` names the enable command). `embeddingOptedOutFor` reads the opt-out markers (search/query degraded reason `embedding_disabled`, recall `keyword_only_embedding_disabled`, think `QUESTION_EMBED_SKIPPED_EMBEDDING_DISABLED`); `factEmbeddingDisabled` (src/core/embedding-disabled.ts) gates every query and fact embed. `sourceBindingNarrowedNotice` (per-call info: a GBRAIN_SOURCE/.gbrain-source bound stdio read that came back empty while other sources are readable; fix = the explicit `source_id` read). `recallInteropNotices` is dispatch's one producer call. `chatKeyFix` (credentials + paid, both providers, free fallback, never a key on a command line), `keylessThinkNotice`, `thinkNotSavedNotice`, `degradedDedupNotice`, `writeCliNotices` (terminal lines / `[AGENT]` block for non-interactive callers). Test: `test/mcp-notice-channels.test.ts`.- `src/mcp/status-mode.ts` + `src/commands/serve-status.ts` + `src/commands/serve-http-status.ts` + `src/core/serve-http-status-marker.ts` — F4 status-only serve, stdio and `--http`. cli.ts hands over a host-brain `serve` (not `--fail-fast`/`GBRAIN_SERVE_FAIL_FAST=1`) with no config, an unreadable config, a missing or repair-failed brain, or a PGLite lock held by a live holder; `runStatusModeServe` is the one entry point for both transports and logs `serve_status_mode_enter` / `serve_status_mode_recovered` (`reason`, `transport`, `elapsed_ms`) as one-line JSON on stderr. `probeStatus` reads config + `peekLock` only; `reprobe(state, connect)` is the one re-probe (no lock attempt while blocked, `resetReadinessMemo()` before the throw-only connect from `src/core/engine-connect.ts`); a check that must run on every re-probe hooks the `probeAgain` wrapper in `runStatusModeServe`. stdio: a gated lazy engine (`createDegradedEngine` with the configured `kind`, reconnect `statusReconnect`, ≤1 attempt / 5 s inside tool calls) marked with `StatusModeState`; `statusPayload` → `{status, reason, why (lock owner PID/transport, brain path, config path), fix, user_message, decisions, share_http_plan}`. `--http`: `runHttpStatusServe` binds one `node:http` listener with a mutable handler (`/health` 503 + `Retry-After: 5` + `instance`; `/mcp` stateless SDK server with only `gbrain_status`; every other route a 503 `serve_status_only` envelope), each response built from the allowlist in `httpStatusPayload`/`httpStatusEnvelope` with `reason` collapsed to `unavailable`; a single-flight chained 5 s tick runs the re-probe, and on a connect `runServe(..., { adoptServer })` builds the full app and swaps the handler on the same listener; a failed build disconnects the engine and stays status-only (`brain_unopenable`); SIGINT/SIGTERM during a recovery waits for it, then closes once. The marker `GBRAIN_HOME/serve-http-status-<port>.json` `{pid, instance_nonce, brain_id, bind, port, reason, since}` is removed only by its own instance; live = PID alive and written after the last boot (readiness), plus `/health` 503 with the nonce within 500 ms (`verifiedStatusMarkers`, doctor, which deletes dead markers). `statusFix(state, transport)` words the fix for how the server re-checks. A recovered HTTP server answers authenticated `gbrain_status` (read scope, never listed) with `status: recovered`. Tests: `test/serve-status-mode.serial.test.ts` (stdio recover → recall; shared `serve --http`; no brain → init; `--fail-fast`; stdio transition lines; Postgres `--http` keeps the degraded path), `test/serve-http-status-mode.serial.test.ts` (HTTP journey, doctor, thin client, recovery with re-auth, `serve_port_in_use`, no-config recovery, stale marker, single-flight tick, failed build, shutdown during recovery, two-port markers).- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`.diff --git a/docs/architecture/key-files/core-search-1.md b/docs/architecture/key-files/core-search-1.mdindex cd9397a316..30db5e715a 100644--- a/docs/architecture/key-files/core-search-1.md+++ b/docs/architecture/key-files/core-search-1.md@@ -68,6 +68,6 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/core/search/read-policy-sql.ts` — shared internal concrete-page SQL policy (`PageReadScope` in `types.ts`): nonempty federated grants precede scalar source; `excludePrivate` is resolved by `ops/context.ts:readPolicyOpts`, never an MCP override. Optional live-page filtering excludes deleted/quarantined pages and archived sources. Both engines apply policy inside content, version, timeline, graph and identity reads before limits. While page privacy is enforced, history requires both current-page and snapshot visibility. Links/timeline projections independently authorize originating pages.-- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | provider_error`, which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.+- `src/core/search/rerank.ts` — the call-site abstraction. `applyReranker(query, results, opts)` slots between `dedupResults()` and `enforceTokenBudget()` in `src/core/search/hybrid.ts`. Slices `opts.topNIn` (default 30) by current RRF order, caps each document via `capRerankDoc` (`RERANK_MAX_DOC_CHARS=6000` then a measured-ratio shrink to `RERANK_MAX_DOC_TOKENS=1400` — a 2048-ubatch llama-server minus query/template headroom minus a Qwen-tokenizer margin; every cut through `truncateUtf8` so no lone surrogate reaches the JSON body; docs under 1400 chars skip the tokenizer; applies to hosted providers too, so code/CJK chunks at the chunker ceiling lose part of their tail while prose is untouched), sends to `gateway.rerank()`, reorders by `relevanceScore` desc (within a run of exactly equal finite scores the fused input order decides, so provider tie order never leaks; rows never cross a different score), appends the un-reranked tail unchanged (recall protection). Fail-open on every `RerankError.reason`: any error logs via `logRerankFailure` and returns the input array unchanged — except the SKIP class `no_key` (`RerankSkipReason`), which returns the input immediately WITHOUT a per-query audit row (the gateway already wrote the one per-process-per-model row) and fires `opts.onSkip(reason)`; every OTHER thrown failure (HTTP error, network, timeout, budget) is audited and fires `opts.onFailure(reason)` with `RerankFailedReason` `timeout | budget | rate_limited | unreachable | auth | provider_error` (gateway `rate_limit` → `rate_limited`, a transport failure with no HTTP response → `unreachable`, 401/403 → `auth`, 5xx and everything else → `provider_error`; Cat 40 R0, pinned on the real wire by `test/rerank-failure-reason.serial.test.ts`), which `hybrid.ts` stamps as `{stage: 'rerank_failed', reason}` (recall-affecting, like `rerank_passthrough`; the LongMemEval reranker gate and the R1 script count it as un-reranked); `hybrid.ts` passes an `onSkip` that stamps `{stage: 'reranker_skipped', reason}` into `HybridSearchMeta.degraded` (closed vocabulary in `types.ts`), which `--explain` renders as `degraded: reranker_skipped (no_key)` via `formatDegradedSummary` — the only place a silently skipped reranker is visible from the CLI. `types.ts` classifies the stage as ranking-only: `RANKING_ONLY_DEGRADED_STAGES` (= `{reranker_skipped}`) + `affectsRecall(entry)` — consumers that ask "was recall impaired?" filter through it (the CLI `No results.` line in `cli.ts:describeEmptyRetrieval` and the MCP empty-result block in `dispatch.ts:buildEmptyRetrievalBlock` keep saying "clean miss"; the degraded cache-TTL rule below uses the same predicate), while consumers that report what did not run (`--explain`, telemetry, eval rows) keep it; pinned by `test/degraded-stages-recall.test.ts`. `hybridSearchCached` excludes `reranker_skipped` from the short degraded-TTL rule (it is a config state, not a transient limp: a keyless balanced brain keeps the full `cache.ttl_seconds`, and the stored meta still carries the stamp). Stamps `rerank_score` onto reordered items so downstream telemetry sees the new ordering signal. `topNOut: null` is the explicit "don't truncate" signal — semantically distinct from `undefined` ("fall through to mode bundle"). Test seam: `opts.rerankerFn` stubs `gateway.rerank` without the network. Document cap pinned by `test/rerank-doc-cap.test.ts`.- `src/core/search/rrf-page-fusion.ts` — `accumulateRrf(lists)`, the one accumulation step behind `rrfFusion` / `rrfFusionWeighted` in `hybrid.ts`. Votes are keyed on the PAGE `(source_id, slug)`: each list adds `weight / (k + rank)` to a page once, at its best rank, chunks stay distinct rows keyed `(source_id, slug, chunk_id)` with their own vote (`own`) and an OR-propagated `keyword_hit` (`keyword_relaxed` only if every holding list was relaxed), and each page's lead chunk (largest `own`, first-seen on ties — a vector arm in `composeFusionLists` order) scores the page's summed vote while its other chunks score their own vote. Pure. Pinned by `test/search/rrf-page-grain.test.ts`.diff --git a/docs/architecture/key-files/core-utilities-2.md b/docs/architecture/key-files/core-utilities-2.mdindex 4ac8ba4221..7b3aaa07e6 100644--- a/docs/architecture/key-files/core-utilities-2.md+++ b/docs/architecture/key-files/core-utilities-2.md@@ -4,7 +4,7 @@Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.- `src/core/repair/` — `gbrain repair` core. `core.ts`: `resolveRepairScope` (default every active source; prints brain and source ids), `runRepair` (dry run unless `apply`; each item is one revision-bound `put_page` with a deterministic request id (replayed while pending, a new attempt id after a terminal failure), re-decided against current state just before it is applied; a cursor in `op_checkpoints` keyed by kind + scope resumes an interrupted or `--limit` run and is cleared when a scan completes; the same row carries the run id (written before the first applied item and passed to `apply` as `runId`), so a resumed run keeps the id that any authorization it granted is bound to; a kind may return a named per-item outcome (`RepairItemOutcome`), tallied in `outcomes` and `outcome_items`; a `spends: 'llm'` kind's plan reports `llm` (its paid-model estimate, null for an unpriced model under a user-set cap, and what is left under its own daily cap), and its result's `cost` adds `llm_usd` (the estimate on a dry run, the actual spend summed from each item's `llm_usd` on an apply) and `llm_cap_remaining_usd` (the smaller of the daily cap and the run allowance, less the spend), keys other kinds never carry; `maxLlmUsd` is the run's paid-model allowance: each item's `apply` gets what is left as `llmAllowanceUsd`, and once it is used up, or an item's own `llm_usd` estimate exceeds what is left, the run stops `budget_exhausted` before that item, naming spent and allowance, and rerunning the apply command resumes it (a dry run sums the per-item estimates of the items it would apply, so `--limit` lowers it); the core opens no budget tracker; `deadline` (epoch ms) stops the run with `time_budget` before the next item; an item outcome's `stop` ends the run after that item with its reason, message and fix; a kind's `report` hook adds `repaired`, `remaining`, `verification` (or refines `stopped`) once the run ends, and a plan's `scan` is copied to the result; stops before crossing 90% of the brain or principal lifetime-ID / receipt-byte caps with the `gbrain config set` value that finishes; a held writer stops with `gbrain sources writer status <source>`). `timeline.ts`: `scanTimelineHistory` (bounded id-order scan shared with the doctor) and the materialize kind. `visibility.ts`: `planVisibilityRepair`, the tighten-only atom/concept backfill (atoms from `effectiveVisibility` of their origin, concepts from the strictest input over provenance edges and atoms' `concepts:`; no-lineage concepts are counted and left alone). `safe-chunks.ts`: a `publication: 'projection'` kind (no admission, zero lifetime-ID and receipt cost, no capacity stop) that re-seals markdown and code pages below the safe-chunk fence through `resealSafeChunks`, then embeds their NULL chunks unless `--no-embed`; code pages without a recorded path and other page kinds are residuals. The pending count is reported only by the doctor check `safe_index_pending`, which the post-upgrade recovery banner uses. `contextual-mode.ts`: a `publication: 'projection'` kind (#5621) that stamps `contextual_retrieval_mode` + `corpus_generation` on sealed live markdown pages with a NULL mode through `resolveImportContextualMode` (`src/core/import-contextual-mode.ts`, the resolver `importFromContent` also uses, strict source-row read), then under the page guard clears only vectors whose recorded embedding input the stamped convention no longer accepts (the #5553 rule) and re-embeds that page once unless `--no-embed`; unsealed pages are the `unsealed_projection` residual. `connector-checkpoints.ts`: a `publication: 'projection'` bookkeeping kind (#5686, `embeds: false`) that deletes connector checkpoint rows and retry pointers no registered source can load and that are older than 7 days, keeping rows a non-terminal request or recorded pending set references; brain-wide. `request-indexes.ts`: a `publication: 'projection'` brain-wide kind (#5762, `embeds: false`) that builds a missing managed sync request index or drops an INVALID one and rebuilds it through `buildIndexOnline` (`src/core/schema-migrations/helpers.ts`: CONCURRENTLY on Postgres under the session's startup timeouts with no session SET, inline on PGLite, the result re-checked for validity, an index another session is still building is left alone); it clears `persistence_request_indexes`. `orphan-bindings.ts`: a projection bookkeeping kind (#5732) over `persistence/orphan-bindings.ts` that deletes persistence source bindings of a removed source or an earlier incarnation, brain-wide, keeping one a pending request of that incarnation references. `embedding-effects.ts`: a projection kind (#5629/#5734, `embeds: 'effect'`) over `persistence/embedding-settlement.ts`; each stale queued or failed embedding effect of a committed write is `reconciled` (the effect projection verifier passes), `superseded` (page deleted, or a newer revision of the same page owns its own effect), `retry_queued` (stale queued re-queued for the owner; failed granted the retry-effects allowance; an exhausted allowance gets one new bounded cycle under `embeddingGrantId(runId, effect)`, which a resumed run replays) or `blocked` with a reason; every change is a compare-and-set on state, attempts, execution token and recovery, and a changed candidate is `changed_since_preview`. Retry items count the whole retry budget in the embedding estimate. `registry.ts`: `REPAIR_REGISTRY` (one entry per `REPAIR_KINDS` name in `--all` order: handler, help summary, `embeds` — `effect` when the publication's embedding effect re-embeds each page outside the run, `inline` when the kind embeds in-process and honors `--no-embed`, `none` for bookkeeping kinds — `spends: 'llm'` for a kind that may call a paid chat model, and the doctor `checks` it clears), `repairMayEmbed` (embedding spend under the flags) and `repairMaySpend` (that or `spends: 'llm'`), `repairForCheck`, `repairApplyCommand` and `repairRunner`, the one trusted local runner that both `gbrain repair` and doctor remediation use (its `run` takes `maxLlmUsd`; `repairRunner` and `repairSpec` take an optional `registry` of stub specs for tests, and production callers use the registered kinds); a new kind plugs in by adding its name to `REPAIR_KINDS` and one registry entry. A kind with `explicit_only` (`stale-atoms`, `extractor-facts`; the `extractor-facts.ts` stub refuses with `unavailable` until its fix wave 5 lane lands) runs only when named: `AUTO_REPAIR_REGISTRY` is the `--all`, no-kind and remediation set, `explicitRepairNotices` lists the rest as `explicit_kind_required` with `repairPreviewCommand`, and `runRepair` refuses an unnamed explicit-only kind (`explicitKindRequired`), so a supplied remediation step cannot run one. Explicit-only kinds and kinds with `preview_bound` (`fences`, which is not explicit-only and so also runs from `--all`, the remediation run and the maintenance cycle with a bare `--apply`) accept `--expect <hash>`; only explicit-only kinds accept `--include-ambiguous`; `--only`/`--skip`/`--slug` selections, `--no-llm` and `--max-usd` (only `spends: 'llm'` kinds; it only lowers their cap) are passed to `plan` as `RepairPlanOptions` and printed in the apply command; a plan's `preview_hash` is appended to its apply command, and its `listing` (every previewed item with its class) is printed by the dry run. `stale-atoms.ts` (#5770): live page-bound atoms (never `imported_from`, never `source_path`-only) whose source page is gone (`origin_gone`) or whose stripped 16-character `source_hash` differs from a source page that already completed an extraction at its current hash (`origin_changed`; managed evidence is the completed `managed-atoms` checkpoint via `managedAtomCompletedSql`, unmanaged evidence a non-managed atom at that hash). The preview saves the set with `saveApprovedSet`; `--apply --expect <hash>` loads it (`preview_changed` otherwise; `--apply` alone refuses with the filled commands), rechecks each atom (revision, class, origin, evidence) and reports `retired`, `changed_since_preview` or `file_conflict` (an uncoordinated edit of the atom file; its attempt-aware `repairRequestId` lets a later apply retry once the file is fixed). An approved set applies only under the source selection it was previewed with, and the apply's resume cursor is keyed by its approval hash. Managed brains admit one `managed_maintenance_retire_stale_atoms` request per atom bound to its revision (`prepareStaleAtomRetirement`, rechecked under the atom and origin page locks, no live origin needed); unmanaged brains soft-delete in one locked transaction. Both stamp `retired_by: stale-atoms`/`retired_at` and bump the origin page's `managed-atoms-generation` (clearing its page state and completed checkpoints, keeping the current hash for `origin_changed`), so a restored page is extracted again and `publishManagedAtoms` restores the retired atoms. Tests: `test/repair-explicit-only.test.ts`, `test/repair-stale-atoms.test.ts` and `test/journey-atoms-sync-race.test.ts` (PGLite and Postgres). Tests: `test/repair-command.test.ts`, `test/derived-visibility-repair.test.ts`, `test/safe-chunk-reseal.test.ts` (PGLite and Postgres), `test/repair-contextual-mode-5621.serial.test.ts` (PGLite and Postgres), `test/repair-flags.test.ts`, `test/persistence-request-indexes.test.ts`. `attribution-backfill.ts` (Foundations 1, F1b): an automatic `publication: 'projection'` bookkeeping kind (`embeds: 'none'`, no doctor check) that fills NULL write attribution only where exactly one committed request proves it: `pages.revision_*` and `page_versions.write_*` from the page mutation (or fenced `remember`) whose `outcome.revision` is the row's `knowledge_revision` (skipped, duplicate and observe-only requests prove nothing), and `facts.write_*` from the `remember` whose `outcome.id` names the fact with status `inserted` or `superseded`. The preview proofs and each batch run inside a short transaction with `enable_nestloop` off (the journal join on the outcome key has no index, and fresh attribution columns have no statistics), restoring the caller's setting before it ends. Items are batches of up to 1,000 ids per table in (table, id) cursor order; each batch re-runs the proof under `lockPageKeys` for its pages and commits on its own, so an interrupted run resumes after the last committed batch. Unproven NULL rows are the `unrecorded_<table>` residuals. Test: `test/write-attribution-read.test.ts`. `google-file-modes.ts`: an explicit-only (`explicit_only: true`), `publication: 'projection'` filesystem-only kind (`embeds: false`, no admission, no request ids) that plans one item per loose entry from `scanGoogleFileModes` (cursor phase = source index; the item carries root, relative path, kind and old mode) and applies `tightenGoogleEntry` (outcomes `tightened`, `already_private`, `skipped` with a reason); symlink, foreign-owner and wrong-type entries are `skipped_*` residuals. It is last in `REPAIR_KINDS`, so `--all` runs it after `embedding-effects`; registry check `google_file_modes`. Every run re-scans, so a rerun after `--limit` picks up exactly what is still loose.-- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.+- `src/core/rerank-audit.ts` — failure-only JSONL audit at `~/.gbrain/audit/rerank-failures-YYYY-Www.jsonl` (ISO-week rotation, mirrors `src/core/audit-slug-fallback.ts`). Exports `logRerankFailure({reason, model, query_hash, doc_count, error_summary})` + `readRecentRerankFailures(days)`. The `no_key` reason is written ONCE per process per model by the gateway itself (not per query by `applyReranker`): the provider key is absent, so calls are skipped without HTTP and results pass through unreranked; `auth` means key present but rejected; `unreachable` means no HTTP response at all (connection refused, DNS, reset; a stale `provider_base_urls` entry fails every call this way, Cat 40 R0), while `network` stays a provider 5xx. Deliberately no `logRerankSuccess`: writing once per tokenmax search is hot-path I/O churn AND success events leak query volume + timing into a local audit file. `gbrain doctor`'s `reranker_health` check (`doctor/checks/calibration.ts`) resolves enablement + model through `resolveSearchMode(loadSearchModeConfig)` — the plane search reranks with — and `rerankerReadiness` before reading the audit: readiness is evaluated against the DB-merged config plane (`loadConfigWithEngine`, so DB-plane provider keys and `provider_base_urls` self-host overrides count, exactly like the gateway the CLI configures): a brain with NO embedding provider (`isAvailable('embedding')` false on a configured gateway) is `ok` even when not ready — search runs keyword-only there and never reaches `applyReranker`, so there is nothing to fix; otherwise enabled-but-not-ready (key absent / unknown model) warns with the paste-ready fix; only audit rows for the RESOLVED model count (rows for any other model never make the live default warn or send the operator to verify the wrong key); `no_key` skip rows are informational once ready (those processes ran unreranked; a long-lived worker started before the key was added keeps skipping until restarted) and never outlive the fix as a warn; then the auth / payload / budget / unreachable (3+ rows: names the `provider_base_urls.<provider>` key) / transient / unknown ladders on the non-skip rows; disabled → ok (with an enable hint when the default is ready). Query text SHA-256-prefix-hashed (8 hex chars) for privacy. `GBRAIN_AUDIT_DIR` env override honored via the shared `resolveAuditDir()`.- `src/core/repair/extractor-facts.ts` — `gbrain repair extractor-facts` (#5731), explicit-only and preview-bound. `classifyExtractorFacts` (read-only; also the doctor check's count) takes conversation-extractor facts with `expired_at` set and `row_num` NULL and classes each: `excluded` (page missing or deleted, `superseded_by` set, withdrawn, an active same-text fact on the page, or an earlier same-text candidate), `ambiguous` (unmanaged brain; no committed request of the page with `completed_at = expired_at`, compared in SQL as microsecond UTC text, which only a same-transaction completion satisfies on Postgres; a consumer at or above v0.60.11.0; or the page has ever held fence-projected facts) or `evidenced`. The preview lists every candidate, hashes them with the selection (`--include-ambiguous`) and saves one approved item per page (with its request id) through `preview-approval.ts`; the apply loads only that set, skips pages whose request already committed or whose facts are active again, and restores each still-identical fact with a fresh `row_num` above the page's facts and fence rows. Managed brains publish one database-only `managed_maintenance_restore_extractor_facts` request per page (`submitDatabaseMaintenanceIntent`, dispatched by `prepareMaintenanceMutation` to `prepareExtractorFactsRestore`, which reclassifies under the page lock); unmanaged brains run the same restore in one locked transaction. Previews warn, naming the host, when a consumer older than this release published after `writer_version_cutoff`. On PGLite `now()` has millisecond resolution, so the same-transaction rule is millisecond-exact there.- `src/core/repair/captured-facts.ts` — `gbrain repair captured-facts`, explicit-only and preview-bound. `classifyCapturedFacts` (read-only; also the `captured_facts_active` count) takes active capture-lane facts and classes each by its session (`captureSessionId`: `sweep:corpus:<file>` resolves through `corpusFileSessionId`): `evidenced` when a gbrain claude-cli scratch project holds the session's harness transcript or its corpus file sits in `<corpus>.quarantine/`; `ambiguous` (paste candidate) when a retained corpus file of the session holds a paste block and at least 60% of the claim's content words occur there only inside paste blocks; `excluded:legitimate_duplicate` when the claim and entity also have an active row that is not proven suspect. Sessions with no transcript and no corpus file are counted `unclassifiable`. The preview hashes every candidate with the selection (`--include-ambiguous`) and saves one approved item per page through `preview-approval.ts`; the apply reclassifies each fact, expires database-only rows through one database-only `managed_maintenance_expire_captured_facts` request per page on a managed brain (owner-checked by `maintenancePreflight`; `prepareCapturedFactsExpiry`, dispatched from `prepareMaintenanceMutation`) or one transaction on an unmanaged brain, and strikes fenced rows in the page's `## Facts` fence through one revision-bound `put_page`, so the canonical projection expires them and a later page write cannot reactivate them. No withdrawal is recorded, so `remember` can save the same claim again. Pinned by `test/repair-captured-facts.test.ts` (+ Postgres arm).- `src/core/repair/loop-facts.ts` — `gbrain repair loop-facts` (#5869), explicit-only and preview-bound (`--apply --expect <hash>`): candidates are `loopFactDrift` rows (closed `done`/`dropped` loops whose commitment fact is active, in the loop's source and shared with no open loop); each item is rechecked (`changed_since_preview`) and retired through `retireLoopFact`, the same coordinated strike-plus-expire publication `loops_close` uses.diff --git a/docs/protocol/MCP_META_CHANNELS.md b/docs/protocol/MCP_META_CHANNELS.mdindex 95e7df2bd0..95eb27da3a 100644--- a/docs/protocol/MCP_META_CHANNELS.md+++ b/docs/protocol/MCP_META_CHANNELS.md@@ -31,7 +31,7 @@ shape for it.| Key | Producer | Contents ||-----|----------|----------|| `brain_hot_memory` | serve-http `metaHook` (`getBrainHotMemoryMeta`) | Hot-memory facts relevant to the call |-| `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed) |+| `retrieval` | `search`/`query` op handlers | `returned_count`, `retrieved_count`, `vector_enabled`, `expansion_applied`, `cache`, `token_budget`, `degraded[]` (closed stage vocabulary), `rerank_degraded` (on a call whose reranker failed: `{reason, fallback: "fused_order", calls_this_session}`; reason is `timeout`, `budget`, `rate_limited`, `unreachable`, `auth` or `provider_error`; no `fields: "full"` needed), `hint` (non-contractual prose), `rows` (`"lean"` or `"full"`: the row shape of content[0]; reported for remote callers and whenever `fields` is passed) || `warnings` | dispatch strict-params warn mode | `[{code: 'unknown_param', param, suggestion?}]` || `pagination` | `list_pages` op handler | `truncated` (more rows match), `limit` (effective), `clamped_from?` (the caller's limit when capped), `next?` (params for the following page: `{sort, updated_after, updated_after_slug}` under `updated_asc`, else `{offset}`). The model-visible counterpart is the `listing_truncated` notice block (kind `info`, never deduped), whose `fix.mcp` is the next-page call. |diff --git a/scripts/serial-files.tsv b/scripts/serial-files.tsvindex c225d3d7ba..262fea856f 100644--- a/scripts/serial-files.tsv+++ b/scripts/serial-files.tsv@@ -291,6 +291,8 @@ test/remediation-run-extras.serial.test.ts R2 R2: mock.module(../src/core/miniontest/remediation-run-loop.serial.test.ts R2 R2: mock.module(../src/core/minions/queue.ts, ../src/core/minions/wait-for-completion.ts, ../src/core/remediation-checkpoint.ts, ../src/core/ai/gateway.ts) replaces modules for every file in the processtest/remote-privacy-journeys.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; configureGateway changes the process-wide AI gateway; binds local servers/portstest/repair-contextual-mode-5621.serial.test.ts R1 R1: mutates process.env (GBRAIN_HOME)+test/rerank-degraded-notice.serial.test.ts R2 R2: mock.module (hybridSearchCached)+test/rerank-failure-reason.serial.test.ts global-state global-state: configureGateway changes the process-wide AI gateway; binds local servers/ports; R1: mutates process.env (GBRAIN_HOME, GBRAIN_AUDIT_DIR); R3: constructs PGLiteEngine inside a test (disconnected in finally)test/rerank-no-key.serial.test.ts global-state global-state: process-wide test seams __setRerankTransportForTests; configureGateway changes the process-wide AI gatewaytest/schema-cli-database-path.serial.test.ts global-state global-state: R3: constructs PGLiteEngine outside beforeAll; R4: PGLiteEngine without an afterAll disconnecttest/schema-engine-isolation.serial.test.ts global-state global-state: spyOn engine.getConfig, engine.searchKeyword, engine.searchVectordiff --git a/src/commands/doctor/checks/calibration.ts b/src/commands/doctor/checks/calibration.tsindex ef50520a3f..79009df3b6 100644--- a/src/commands/doctor/checks/calibration.ts+++ b/src/commands/doctor/checks/calibration.ts@@ -682,6 +682,17 @@ export async function checkRerankerHealth(engine: BrainEngine, now: Date = new D};}+ // Cat 40 R0: no HTTP response at all is a configuration or network fault+ // (a stale base URL fails every call), not a provider outage.+ const unreachableFails = failures.filter((f) => f.reason === 'unreachable');+ if (unreachableFails.length >= 3) {+ return {+ name: 'reranker_health',+ status: 'warn',+ message: `${unreachableFails.length} reranker call(s) in the last 7 days could not reach the ${model} endpoint (connection refused, DNS or network error), so those searches kept their fused order. Fix: check the reranker base URL (\`provider_base_urls.${model.split(':')[0]}\` in the gbrain config, or the provider default) and that the brain host can reach it, then run \`gbrain models doctor\`.`,+ };+ }+const transientFails = failures.filter((f) => f.reason === 'network' || f.reason === 'timeout' || f.reason === 'rate_limit',);diff --git a/src/core/ai/decide/rerank-adapter.ts b/src/core/ai/decide/rerank-adapter.tsindex 125d88f9cd..21161c878d 100644--- a/src/core/ai/decide/rerank-adapter.ts+++ b/src/core/ai/decide/rerank-adapter.ts@@ -120,7 +120,7 @@ export async function rerankViaDecide(input: RerankInput, deps: RerankViaDecideDif (isAIInvocationPolicyError(error) || error instanceof RerankError) throw error;if (error instanceof DecideError) throw new RerankError(`TypeSafe rerank: ${error.message}`, error.reason === 'rate_limited' ? 'rate_limit' : 'unknown', error.status);if (ctrl.signal.aborted) throw new RerankError('TypeSafe rerank: request aborted', input.signal?.aborted ? 'unknown' : 'timeout');- throw new RerankError('TypeSafe rerank: transport failed', 'network');+ throw new RerankError('TypeSafe rerank: transport failed', 'unreachable');} finally {clearTimeout(timer);input.signal?.removeEventListener('abort', callerAbort);diff --git a/src/core/ai/gateway.ts b/src/core/ai/gateway.tsindex 90a43c8067..c09338e94d 100644--- a/src/core/ai/gateway.ts+++ b/src/core/ai/gateway.ts@@ -4315,7 +4315,8 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {// Timeout via AbortController; merges with caller-supplied signal.const ctrl = new AbortController();const timeoutMs = input.timeoutMs ?? DEFAULT_RERANK_TIMEOUT_MS;- const t = setTimeout(() => ctrl.abort(new Error('rerank timed out')), timeoutMs);+ let timedOut = false;+ const t = setTimeout(() => { timedOut = true; ctrl.abort(new Error('rerank timed out')); }, timeoutMs);if (input.signal) {if (input.signal.aborted) ctrl.abort(input.signal.reason);else input.signal.addEventListener('abort', () => ctrl.abort(input.signal!.reason), { once: true });@@ -4364,7 +4365,7 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {: 'unknown';throw new RerankError(msg, reason, resp.status);}- const json: any = await resp.json();+ const json: any = await resp.json().catch((err: unknown) => { throw timedOut ? err : new RerankError('rerank: malformed response (body is not JSON)', 'unknown'); });// v0.46.3: two response dialects share the item shape {index,// `results[]`, Voyage's REST returns `data[]` ({object: "list", data:// [...]}, live-wire verified 2026-08-15; Voyage's Python SDK renames it@@ -4387,14 +4388,12 @@ export async function rerank(input: RerankInput): Promise<RerankResult[]> {if (isAIInvocationPolicyError(err)) throw err;_rerankRecord(true);if (err instanceof RerankError) throw err;- // AbortError on timeout — classify cleanly.- if (err && typeof err === 'object' && (err as any).name === 'AbortError') {- const msg = (err as Error).message || 'rerank aborted';- throw new RerankError(msg, msg.toLowerCase().includes('timed out') ? 'timeout' : 'unknown');- }- // Network errors (DNS, connection refused, etc.) become network class.+ // fetch rejects with the abort reason itself (a plain Error, not an AbortError), so the flag is the tell.+ if (timedOut) throw new RerankError(`rerank timed out after ${timeoutMs}ms`, 'timeout');+ if (err && typeof err === 'object' && (err as any).name === 'AbortError') throw new RerankError((err as Error).message || 'rerank aborted', 'unknown');+ // No HTTP response at all (connection refused, DNS, reset) is `unreachable`; a provider 5xx is `network`.const msg = err instanceof Error ? err.message : String(err);- throw new RerankError(`rerank: ${msg}`, 'network');+ throw new RerankError(`rerank: ${msg}`, 'unreachable');} finally {clearTimeout(t);tracker?.release(reservation);diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 0d2093ba3a..639fac931c 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -379,7 +379,7 @@ export const NOTICE_CODES = {listing_truncated: { kind: 'info', summary: 'A listing returned a full page and more rows match; the fix is the next-page call.' },former_relationships_hidden: { kind: 'info', summary: 'A graph read returned live relationships only and left out ended ones; the fix repeats the call with status: "all" (or as_of) to see history.' },mention_index: { kind: 'degraded', summary: 'The entity mention index is pending, off, failed or does not cover this page type, so references listed for an entity may be incomplete.' },- degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence.' },+ degraded_recall: { kind: 'degraded', summary: 'A retrieval stage that affects recall did not run; an empty or thin result is not proof of absence. A failed rerank names its reason (timeout, budget, rate_limited, unreachable, auth, provider_error), the fused-order fallback and the session\'s count of reranker-degraded calls; timeout and rate_limited say to repeat the call after a delay, the rest point at doctor\'s reranker_health.' },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.' },local_transcripts: { kind: 'info', summary: 'The brain host keeps recent session transcripts that page reads never return and this connection cannot read; the fix is the CLI read (`gbrain transcripts recent --json`).' },diff --git a/src/core/interop-notices.ts b/src/core/interop-notices.tsindex 1954a9506d..c31b33e67f 100644--- a/src/core/interop-notices.ts+++ b/src/core/interop-notices.ts@@ -14,6 +14,7 @@ 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';+import type { RerankFailedReason } from './search/rerank.ts';import { localTranscriptsFix } from './transcripts.ts';// ── degraded recall (F3) ───────────────────────────────────────────────────@@ -58,6 +59,52 @@ export const DEGRADED_STAGE_GUIDANCE: Readonly<Record<RecallStage, StageGuidanceconst 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). */+const RERANK_REASON_WHY: Readonly<Record<RerankFailedReason, string>> = {+ timeout: 'the reranker did not answer within its timeout',+ budget: 'a spend cap stopped the reranker call',+ rate_limited: 'the reranker provider refused the call for its rate or concurrency limit (HTTP 429)',+ unreachable: 'the reranker endpoint could not be reached (connection refused, DNS or network error; a wrong reranker base URL looks like this)',+ auth: 'the reranker provider rejected its API key (HTTP 401/403)',+ provider_error: 'the reranker provider answered with an error',+};+/** Seconds to wait before repeating the call, for the transient reasons. */+const RERANK_RETRY_AFTER_S: Partial<Record<RerankFailedReason, number>> = { timeout: 5, rate_limited: 20 };+const RERANKER_HEALTH_VERIFY = { argv: ['gbrain', 'doctor', '--only', 'reranker_health', '--json'] };++function rerankReason(reason: string | undefined): RerankFailedReason {+ return reason !== undefined && reason in RERANK_REASON_WHY ? reason as RerankFailedReason : 'provider_error';+}++/**+ * The fix for a failed rerank, per reason: a transient one (timeout, rate+ * limit) repeats the same call after the stated delay (`next: wait`); the+ * rest point at doctor's `reranker_health`, which names the endpoint, key or+ * cap behind the failure. A rejected key is the user's to replace.+ */+function rerankFix(reason: RerankFailedReason, retry?: { op: string; args: Record<string, unknown> }): Action {+ const delay = RERANK_RETRY_AFTER_S[reason];+ if (delay !== undefined && retry) {+ return {+ mcp: { tool: retry.op, arguments: retry.args }, consent: [], actor: 'provider', requires_exclusive: false,+ why: `The results are complete but keep their fused order. If ranking matters, repeat this ${retry.op} call after about ${delay} seconds; if reranking keeps failing, \`gbrain doctor --only reranker_health --json\` on the brain host names the cause.`,+ };+ }+ if (reason === 'auth') {+ return {+ argv: RERANKER_HEALTH_VERIFY.argv, consent: ['credentials'], actor: 'user', requires_exclusive: false, verify: RERANKER_HEALTH_VERIFY,+ why: 'The reranker provider rejected its API key. The user replaces the key in the .env file in the gbrain home directory (never on a command line); doctor confirms the reranker afterwards.',+ user_message: 'Search results are not being reranked because the reranker rejected its API key. Can you check the reranker key (for example VOYAGE_API_KEY) on the brain host?',+ };+ }+ const why = reason === 'unreachable'+ ? "Doctor's reranker_health names the reranker endpoint that could not be reached; the fix is the provider's base URL (provider_base_urls) or the network on the brain host."+ : reason === 'budget'+ ? "Doctor's reranker_health names the spend cap or missing price that stopped reranking; raising a cap is the user's call."+ : "Doctor's reranker_health names the reranker failure and its fix.";+ return { ...doctorFix(why), verify: RERANKER_HEALTH_VERIFY };+}+/** 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 };@@ -75,26 +122,38 @@ function embeddingsFix(cfg: GBrainConfig | null | undefined, transport: 'stdio'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. */+/**+ * One `degraded_recall` notice for the recall-affecting stages of this call; null when none applies.+ * 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.+ */export function degradedRecallNotice(stages: ReadonlyArray<{ stage?: string; reason?: string } | string>,- opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli'; optedOut?: boolean },+ opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli'; optedOut?: boolean; rerankDegradedCalls?: number; retry?: { op: string; args: Record<string, unknown> } },): Notice | null {- const names = [...new Set(stages- .map(s => (typeof s === 'string' ? { stage: s } : s))+ const entries = stages.map(s => (typeof s === 'string' ? { stage: s } : s));+ const names = [...new Set(entries.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 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'+ ? `reranking failed because ${RERANK_REASON_WHY[rerank!]}, so results keep their fused order (fallback: fused_order${opts.rerankDegradedCalls ? `; reranker-degraded calls this session: ${opts.rerankDegradedCalls}` : ''})`+ : DEGRADED_STAGE_GUIDANCE[n].why));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 byChoice = opts.optedOut || stages.some(s => typeof s !== 'string' && s.reason === 'embedding_disabled');+ const byChoice = opts.optedOut || entries.some(s => s.reason === 'embedding_disabled');const emb = fixKind === 'embeddings' ? (byChoice ? { byChoice: true } as { fix?: Action; byChoice: boolean } : 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 fix = emb ? emb.fix+ : fixKind === 'doctor' ? doctorFix('Doctor names the failing retrieval dependency and its fix.')+ : rerank ? rerankFix(rerank, opts.retry) : 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. No query text was sent to an embedding provider. If the user wants semantic search, `gbrain doctor --json` names the enable command; turning it on needs their consent.' : '';return {code: 'degraded_recall',kind: 'degraded',- why: `Recall was degraded (${names.join(', ')}): ${guidance.map(g => g.why).join('; ')}. ${NOT_ABSENCE}${choice}`,+ why: `Recall was degraded (${labels.join(', ')}): ${whys.join('; ')}. ${NOT_ABSENCE}${choice}`,...(fix ? { fix } : {}),...(fix?.user_message ? { user_message: fix.user_message } : {}),};@@ -236,11 +295,14 @@ export function recallStagesFor(op: string, result: unknown, meta: Record<string*/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 },+ opts: { config?: GBrainConfig | null; transport: 'stdio' | 'http' | 'cli'; binding?: ExplicitReadBinding; rerankDegradedCalls?: number },): Notice[] {try {const out: Notice[] = [];- const degraded = degradedRecallNotice(recallStagesFor(op, result, meta, opts.config), { ...opts, optedOut: embeddingOptedOutFor(op, result, meta) });+ const entries = (meta.retrieval as { degraded?: Array<{ stage?: string; reason?: string }> } | undefined)?.degraded ?? [];+ const stages = recallStagesFor(op, result, meta, opts.config).map(stage => entries.find(d => d.stage === stage) ?? stage);+ const { _meta: _ignored, ...args } = params;+ const degraded = degradedRecallNotice(stages, { ...opts, optedOut: embeddingOptedOutFor(op, result, meta), retry: { op, args } });if (degraded) out.push(degraded);const narrowed = opts.transport === 'stdio' ? sourceBindingNarrowedNotice(op, params, result, opts.binding) : null;if (narrowed) out.push(narrowed);diff --git a/src/core/notice-ledger.ts b/src/core/notice-ledger.tsindex a11a7eccd7..6e9ecb5f9b 100644--- a/src/core/notice-ledger.ts+++ b/src/core/notice-ledger.ts@@ -36,6 +36,7 @@ export interface NoticeAudience {export class NoticeLedger {private seen = new Map<string, number>();private coaching = new Map<string, { count: number; at: number }>();+ private tallies = new Map<string, { n: number; at: number }>();constructor(private readonly now: () => number = Date.now) {}@@ -51,6 +52,16 @@ export class NoticeLedger {}}+ /** Count one more `key` event in this audience's session (e.g. a reranker-degraded call) and return the session total. */+ tally(audience: NoticeAudience, key: string): number {+ const k = `${this.session(audience)}|${key}`;+ const n = (this.tallies.get(k)?.n ?? 0) + 1;+ this.tallies.delete(k);+ this.tallies.set(k, { n, at: this.now() });+ this.prune(this.tallies, v => v.at);+ return n;+ }+/** Filter one call's notices: mute, dedupe and the coaching budget. Never throws. */admit(notices: readonly Notice[], audience: NoticeAudience, muted: ReadonlySet<string> = new Set()): Notice[] {const out: Notice[] = [];diff --git a/src/core/rerank-audit.ts b/src/core/rerank-audit.tsindex cd6ba0e66d..f58495ee8e 100644--- a/src/core/rerank-audit.ts+++ b/src/core/rerank-audit.ts@@ -32,6 +32,7 @@ export type RerankFailureReason =| 'no_key'| 'rate_limit'| 'network'+ | 'unreachable'| 'timeout'| 'budget'| 'payload_too_large'diff --git a/src/core/search/rerank.ts b/src/core/search/rerank.tsindex 3eb03ffaf0..d1622e4b40 100644--- a/src/core/search/rerank.ts+++ b/src/core/search/rerank.ts@@ -49,8 +49,17 @@ export interface RerankerOpts {/** The two skip classes (no HTTP call, no per-query audit row). */export type RerankSkipReason = 'no_key';-/** A reranker call that threw (anything but a missing key), as stamped on the wire. */-export type RerankFailedReason = 'timeout' | 'budget' | 'provider_error';+/**+ * A reranker call that threw (anything but a missing key), as stamped on the+ * wire: no answer within the timeout, a spend cap, HTTP 429 (provider rate or+ * concurrency limit), no HTTP response at all (connection refused, DNS — a+ * wrong base URL looks like this), HTTP 401/403, or any other provider error.+ */+export type RerankFailedReason = 'timeout' | 'budget' | 'rate_limited' | 'unreachable' | 'auth' | 'provider_error';++const FAILED_REASON: Partial<Record<RerankFailureReason, RerankFailedReason>> = {+ timeout: 'timeout', budget: 'budget', rate_limit: 'rate_limited', unreachable: 'unreachable', auth: 'auth',+};/** SHA-256 prefix (8 chars) of the query text for privacy-preserving audit. */function hashQuery(query: string): string {@@ -162,7 +171,7 @@ export async function applyReranker(} catch {// Audit logging must never break search.}- const failed: RerankFailedReason = reason === 'timeout' || reason === 'budget' ? reason : 'provider_error';+ const failed = FAILED_REASON[reason] ?? 'provider_error';try { opts.onFailure?.(failed); } catch { /* caller hook must never break search */ }return results;}diff --git a/src/core/types.ts b/src/core/types.tsindex 9e1b1f6860..8825448b89 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -2017,7 +2017,7 @@ export const DEGRADED_REASONS = [// #4648 — rerank_passthrough reasons (mirror RerankPassThroughReason).'empty_result_set','malformed_shape',- 'budget',+ 'budget', 'rate_limited', 'unreachable', 'auth', // rerank_failed reasons (mirror RerankFailedReason)'candidate_budget','iterative_scan_unavailable','egress_denied', // System One: the Jev reranker skipped a query with a candidate from decide.egress.deny_sources@@ -2044,7 +2044,7 @@ export interface DegradedStageEntry {* short degraded TTL lets the next query recover a reranked result set* (master's v0.48.1.0 behavior, kept at the merge). It never reaches the* empty-result copy because a pass-through implies a non-empty batch.- * - `rerank_failed` (the call threw: timeout / provider_error / budget) is transient too.+ * - `rerank_failed` (the call threw: timeout / budget / rate_limited / unreachable / auth / provider_error) is transient too.* - `keyword_relaxed_carried` is recall-shaped by definition (see above).* Pinned by test/degraded-stages-recall.test.ts; a new fail-open stage must be* classified here in the same commit that adds it.diff --git a/src/mcp/dispatch.ts b/src/mcp/dispatch.tsindex f2dcb68ee1..0520200e7d 100644--- a/src/mcp/dispatch.ts+++ b/src/mcp/dispatch.ts@@ -17,7 +17,7 @@ import { VERB_NAMES, MEMORY_VERBS_VERSION } from '../core/verbs.ts';import { cliRenderContext, orderNotices, redactForTransport, renderNotice, toAgentError, toolErrorResult, toolResultWithNotices, type Notice, type RenderContext } from '../core/agent-output.ts';import { cliOnlyRefusal, isCallable } from '../core/ops/callable.ts';import { hostFix, scopeDeniedError } from '../core/ops/op-fix.ts';-import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger } from '../core/notice-ledger.ts';+import { mutedNoticeCodes, processNoticeLedger, __resetProcessNoticeLedgerForTests, type NoticeLedger, type NoticeAudience } from '../core/notice-ledger.ts';import { logVerbUsage } from '../core/verbs/usage-log.ts';import { localTranscriptsNotice, recallInteropNotices, wantsTranscriptHint } from '../core/interop-notices.ts';import { hiddenToolHint } from './hidden-tool-hint.ts';@@ -573,18 +573,40 @@ export function localCallErrorEnvelope(tool: string, e: unknown) {* ServeHttpContext ledger. Session identity is the transport-resolved id only.* Fail-open: a ledger fault delivers every notice.*/+function noticeAudience(opts: DispatchOpts): NoticeAudience {+ return { transport: opts.transport === 'stdio' ? 'stdio' : opts.remote === false ? 'cli' : 'http', principal: opts.auth?.clientId, sessionId: opts.sessionId };+}+function admitNotices(notices: Notice[], opts: DispatchOpts): Notice[] {if (notices.length === 0) return notices;try {- const principal = opts.auth?.clientId;- const transport = opts.transport === 'stdio' ? 'stdio' : opts.remote === false ? 'cli' : 'http';- return (opts.noticeLedger ?? processNoticeLedger()).admit(notices,- { transport, principal, sessionId: opts.sessionId }, mutedNoticeCodes(principal ?? (transport === 'stdio' ? 'stdio' : undefined)));+ const audience = noticeAudience(opts);+ return (opts.noticeLedger ?? processNoticeLedger()).admit(notices, audience,+ mutedNoticeCodes(audience.principal ?? (audience.transport === 'stdio' ? 'stdio' : undefined)));} catch {return notices;}}+/**+ * Cat 40 R0: a search/query whose reranker failed counts toward this+ * session's reranker-degraded calls, and its own `_meta.retrieval` records+ * the reason, the fallback and that count (no `fields: "full"` needed).+ * Returns the session count, or undefined when the reranker did not fail.+ */+function recordRerankDegradation(responseMeta: Record<string, unknown>, opts: DispatchOpts): number | undefined {+ try {+ const retrieval = responseMeta.retrieval as { degraded?: Array<{ stage?: string; reason?: string }> } | undefined;+ const failed = retrieval?.degraded?.find(d => d.stage === 'rerank_failed');+ if (!retrieval || !failed) return undefined;+ const calls = (opts.noticeLedger ?? processNoticeLedger()).tally(noticeAudience(opts), 'rerank_failed');+ responseMeta.retrieval = { ...retrieval, rerank_degraded: { reason: failed.reason ?? 'provider_error', fallback: 'fused_order', calls_this_session: calls } };+ return calls;+ } catch {+ return undefined;+ }+}+/*** The one-time `behavior_changes` disclosure (stdio: once per brain; HTTP:* once per authenticated client, remote view) and the first@@ -930,8 +952,9 @@ export async function dispatchToolCall(notices.push({ code: 'unknown_param', kind: 'info', why: buildUnknownParamWarnBlock([w]) });}// Lane F (F3): degraded recall and a source binding that narrowed an empty read.+ const rerankDegradedCalls = recordRerankDegradation(responseMeta, opts);notices.push(...recallInteropNotices(name, result, responseMeta, safeParams,- { config: ctx.config, transport: dispatchRenderContext(opts).transport, binding: ctx.explicitReadBinding }));+ { config: ctx.config, transport: dispatchRenderContext(opts).transport, binding: ctx.explicitReadBinding, rerankDegradedCalls }));// 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/ai/rerank.test.ts b/test/ai/rerank.test.tsindex 376698a8ce..5942a20e5b 100644--- a/test/ai/rerank.test.ts+++ b/test/ai/rerank.test.ts@@ -13,7 +13,9 @@* - Response parsing: `{results: [{index, relevance_score}]}` →* `RerankResult[]` with `{index, relevanceScore}`.* - Error classification: 401/403 → auth, 429 → rate_limit, 5xx → network,- * other 4xx → unknown; AbortError on timeout → timeout.+ * other 4xx → unknown, no HTTP response (fetch reject) → unreachable; the+ * timeout path is pinned on the real wire in+ * test/rerank-failure-reason.serial.test.ts.* - Pre-flight payload guard: body over `max_payload_bytes` throws* payload_too_large BEFORE any HTTP call (no transport invocation).* - Empty documents → empty result, no HTTP call.@@ -229,7 +231,7 @@ describe('gateway.rerank() — error classification', () => {}});- test('network exception (fetch reject) → network', async () => {+ test('network exception (fetch reject) → unreachable', async () => {__setRerankTransportForTests(async () => {throw new Error('ECONNREFUSED');});@@ -237,7 +239,7 @@ describe('gateway.rerank() — error classification', () => {await rerank({ query: 'q', documents: ['d'] });throw new Error('should have thrown');} catch (err) {- expect((err as RerankError).reason).toBe('network');+ expect((err as RerankError).reason).toBe('unreachable');}});diff --git a/test/doctor-reranker-health.test.ts b/test/doctor-reranker-health.test.tsindex 1c376feb2a..bd00f0e412 100644--- a/test/doctor-reranker-health.test.ts+++ b/test/doctor-reranker-health.test.ts@@ -204,4 +204,17 @@ describe('reranker_health (v0.48.2 readiness-aware)', () => {expect(c.message).toContain('Reranker disabled');});});+ test('Cat 40 R0: repeated unreachable rows (a stale reranker base URL) → warn naming the base-URL key, not a provider outage', async () => {+ await inFreshAudit({ VOYAGE_API_KEY: 'pa-test' }, async () => {+ for (let i = 0; i < 3; i++) {+ logRerankFailure({ model: DEFAULT_RERANKER_MODEL, reason: 'unreachable', query_hash: `0000000${i}`, doc_count: 30, error_summary: 'rerank: Unable to connect' });+ }+ gw({ VOYAGE_API_KEY: 'pa-test' });+ const c = await checkRerankerHealth(engineWith({}));+ expect(c.status).toBe('warn');+ expect(c.message).toContain('could not reach');+ expect(c.message).toContain(`provider_base_urls.${DEFAULT_RERANKER_MODEL.split(':')[0]}`);+ expect(c.message).not.toContain('status page');+ });+ });});diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex c2dedcb432..c21f49470b 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -447,7 +447,7 @@"kind": "variable","name": "DEGRADED_REASONS","signature": [- "readonly [\"no_provider\", \"provider_error\", \"timeout\", \"variant_embed_failed\", \"original_embed_failed\", \"first_result_truncated\", \"no_key\", \"empty_result_set\", \"malformed_shape\", \"budget\", \"candidate_budget\", \"iterative_scan_unavailable\", \"egress_denied\", \"embedding_disabled\"]"+ "readonly [\"no_provider\", \"provider_error\", \"timeout\", \"variant_embed_failed\", \"original_embed_failed\", \"first_result_truncated\", \"no_key\", \"empty_result_set\", \"malformed_shape\", \"budget\", \"rate_limited\", \"unreachable\", \"auth\", \"candidate_budget\", \"iterative_scan_unavailable\", \"egress_denied\", \"embedding_disabled\"]"]},{@@ -461,7 +461,7 @@"kind": "type","name": "DegradedReason","signature": [- "\"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | \"embedding_disabled\""+ "\"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"rate_limited\" | \"unreachable\" | \"auth\" | \"egress_denied\" | \"embedding_disabled\""]},{@@ -474,7 +474,7 @@{"kind": "interface","members": [- "reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | \"embedding_disabled\" | undefined",+ "reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"rate_limited\" | \"unreachable\" | \"auth\" | \"egress_denied\" | \"embedding_disabled\" | undefined","stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\""],"name": "DegradedStageEntry"@@ -1728,7 +1728,7 @@"cause?: unknown","message: string","name: string",- "reason: \"unknown\" | \"timeout\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"payload_too_large\" | \"network\" | \"auth\" | \"rate_limit\"",+ "reason: \"unknown\" | \"timeout\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"unreachable\" | \"auth\" | \"payload_too_large\" | \"network\" | \"rate_limit\"","stack?: string | undefined","status?: number | undefined"],@@ -5748,7 +5748,7 @@"kind": "type","name": "ErrorCode","signature": [- "\"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"+ "\"rate_limited\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | (string & {})"]},{@@ -5834,7 +5834,7 @@{"kind": "class","members": [- "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"rate_limited\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined",+ "canonical?: \"unknown\" | \"projection_pending\" | \"timeout\" | \"rate_limited\" | \"embedding_disabled\" | \"writer_lock_unavailable\" | \"writer_pool_capacity\" | \"owner_unavailable\" | \"recovery_required\" | \"queue_capacity\" | \"revision_required\" | \"revision_conflict\" | \"idempotency_conflict\" | \"source_changed\" | \"write_pending\" | \"storage_error\" | \"cancelled\" | \"permission_denied\" | \"scope_denied\" | \"invalid_params\" | \"not_found\" | \"page_not_found\" | \"page_identity_changed\" | \"write_claim_lost\" | \"request_too_large\" | \"response_too_large\" | \"writer_registration_required\" | \"writer_identity_invalid\" | \"writer_not_initialized\" | \"writer_coordinator_required\" | \"fact_already_expired\" | \"source_writeback_required\" | \"unsupported_mutation_protocol\" | \"writer_upgrade_required\" | \"writer_not_quiesced\" | \"skill_bundle_required\" | \"take_row_collision\" | \"invalid_source_uri\" | \"writer_admin_locked\" | \"connector_account_changed\" | \"connector_intent_outdated\" | \"checkpoint_validation_timeout\" | \"invalid_connector_text\" | \"connector_holds_exhausted\" | \"connector_fence_below_timeline\" | \"core_budget_exceeded\" | \"core_mark_owner_only\" | \"core_remote_edit_refused\" | \"core_delete_owner_only\" | \"embedding_failed\" | \"bucket_not_found\" | \"database_error\" | \"unknown_transport\" | \"extraction_failed\" | \"fact_not_found\" | \"provenance_required\" | \"unavailable\" | \"budget_unsatisfiable\" | \"embedding_budget_below_worst_case\" | \"access_command_failed\" | \"access_denied_test_user\" | \"access_env_missing\" | \"acknowledgment_unavailable\" | \"admin_policy_enforced\" | \"ambiguous_id\" | \"ambiguous_ref\" | \"ambiguous_skill\" | \"answer_not_yours\" | \"answer_pending\" | \"answer_unavailable\" | \"api_not_enabled\" | \"approval_required\" | \"autopilot_job_owned_by_other_brain\" | \"benchmark_duplicate_task_id\" | \"benchmark_empty\" | \"benchmark_exists\" | \"benchmark_judge_llm_no_rubric\" | \"benchmark_judge_qrels_no_expected\" | \"benchmark_judge_rule_no_checks\" | \"benchmark_judge_unknown_kind\" | \"benchmark_malformed\" | \"benchmark_missing_judge\" | \"benchmark_missing_task\" | \"benchmark_missing_task_id\" | \"benchmark_not_found\" | \"benchmark_rule_check_bad_arg\" | \"benchmark_rule_check_malformed\" | \"benchmark_rule_check_unknown_op\" | \"bootstrap_empty\" | \"bootstrap_pending_review\" | \"bridge_ownership_conflict\" | \"cache_quota_exceeded\" | \"catalog_capacity_exceeded\" | \"catalog_unavailable\" | \"changed_since_preview\" | \"chronicle_skipped\" | \"no_pricing\" | \"checkpoint_missing\" | \"claim_already_used\" | \"client_json_unreadable\" | \"client_json_wrong_type\" | \"client_shape_invalid\" | \"code_callees_requires_symbol\" | \"code_callers_requires_symbol\" | \"code_def_requires_symbol\" | \"code_refs_requires_symbol\" | \"code_reused\" | \"colon_slug_windows_write_through\" | \"command_failed\" | \"config_error\" | \"confirmation_required\" | \"conflicting_source_scope\" | \"consent_timeout\" | \"content_rejected\" | \"cost_cap_exceeded\" | \"cost_preview_requires_yes\" | \"cycle_failed\" | \"d_sel_too_small\" | \"delta_cursor_upgrade_required\" | \"demo_graph_failed\" | \"demo_import_failed\" | \"demo_verification_failed\" | \"derived_cap_exhausted\" | \"destination_not_ready\" | \"dirty_tree\" | \"effect_not_failed\" | \"embedding_auth_failed\" | \"embedding_configuration\" | \"embedding_model_mismatch\" | \"embedding_plane_split\" | \"embedding_storage_unavailable\" | \"embedding_unavailable\" | \"embedding_unconfigured\" | \"embedding_width_mismatch\" | \"engine_graduated\" | \"eval_suite_unwired\" | \"export_limit\" | \"extractor_identity_mismatch\" | \"facts_absorb_write_refused\" | \"facts_drain_deferred\" | \"facts_drain_job_failed\" | \"facts_payload_expired\" | \"feedback_disabled\" | \"feedback_not_authorized\" | \"fetch_failed\" | \"fix_not_writable\" | \"file_removed_during_scan\" | \"file_too_large\" | \"follow_approval_required\" | \"frontmatter_slug_conflict\" | \"full_resync_required\" | \"gate_failed\" | \"git_index_locked\" | \"git_index_stale\" | \"git_push_unavailable\" | \"git_target_unsafe\" | \"git_unavailable\" | \"graduation_drain_timeout\" | \"graduation_embedding_dimension_mismatch\" | \"graduation_foreign_host_binding\" | \"graduation_in_progress\" | \"graduation_interrupted\" | \"graduation_rollback_writes_lost\" | \"graduation_source_writer_held\" | \"graduation_split_brain\" | \"graduation_target_auth_failed\" | \"graduation_target_ddl_unreachable\" | \"graduation_target_not_empty\" | \"graduation_target_unsupported\" | \"graduation_unclassified_table\" | \"graduation_unsupported_platform\" | \"graduation_verify_failed\" | \"graph_incomplete\" | \"held_out_overlaps_benchmark\" | \"held_out_required_for_bundled\" | \"independent_principal_required\" | \"insufficient_scope\" | \"internal\" | \"internal_error\" | \"interrupted\" | \"invalid_acknowledgment\" | \"invalid_client\" | \"invalid_fence\" | \"sync_in_progress\" | \"invalid_frontmatter\" | \"invalid_grant_clock_skew\" | \"invalid_grant_revoked\" | \"invalid_grant_testing_expiry\" | \"invalid_rating\" | \"invalid_receipt\" | \"invalid_receipt_transition\" | \"invalid_request\" | \"invalid_source\" | \"invalid_source_pin\" | \"invalid_token\" | \"invalid_write_wait\" | \"legacy_job_selection_invalid\" | \"legacy_jobs_active\" | \"local_conflict\" | \"lock_busy\" | \"managed_pull_skipped\" | \"membership_inactive\" | \"membership_not_found\" | \"method_not_allowed\" | \"migration_failed\" | \"migrations_pending\" | \"migrations_running\" | \"missing_source_scope\" | \"missing_source_value\" | \"models_strict_violation\" | \"no_refresh_token\" | \"no_routing_eval\" | \"no_skill_md\" | \"no_worker\" | \"no_worker_surface\" | \"not_a_git_repo\" | \"not_connected\" | \"no_brain\" | \"overlapping_path\" | \"page_projection_conflict\" | \"parse_error\" | \"parser_regression\" | \"pasted_wrong_url\" | \"payload_too_large\" | \"pending_writes\" | \"pglite_busy\" | \"plan_output_failed\" | \"plan_stale\" | \"port_in_use\" | \"preview_changed\" | \"profile_incompatible\" | \"projection_owner_resident\" | \"publication_pending\" | \"receipt_conflict\" | \"receipt_fence_changed\" | \"receipt_fence_required\" | \"receipt_identity_mismatch\" | \"redirect_uri_mismatch\" | \"ref_not_in_answer\" | \"refresh_dirty\" | \"refresh_diverged\" | \"refresh_drain_timeout\" | \"refresh_no_upstream\" | \"refresh_not_managed\" | \"refresh_not_owner\" | \"refresh_source_changed\" | \"relay_disabled\" | \"relay_session_expired\" | \"relay_unreachable\" | \"rename_held\" | \"request_already_submitted\" | \"requirements_changed\" | \"requires_local_engine\" | \"resume_spec_mismatch\" | \"revision_unavailable\" | \"scope_missing\" | \"serve_port_in_use\" | \"serve_status_only\" | \"shared_skills_unavailable\" | \"shared_skills_unsupported\" | \"skill_asset_not_found\" | \"skill_candidate_invalid\" | \"skill_not_found\" | \"skill_retention_capacity\" | \"skill_unavailable\" | \"source_binding_required\" | \"source_id_taken\" | \"source_not_ready\" | \"source_profile_no_backfill\" | \"source_referenced\" | \"source_root_conflict\" | \"split_bad_ratio\" | \"split_unparseable\" | \"stale_unavailable\" | \"state_mismatch\" | \"sync_not_applicable\" | \"sync_parser_regression\" | \"target_escape\" | \"topology_change_required\" | \"trusted_local_only\" | \"unexpected_file_bytes\" | \"unexpected_staging_bytes\" | \"unknown_command\" | \"unknown_flag\" | \"unknown_method\" | \"unknown_source\" | \"unknown_tool\" | \"unmanaged_path\" | \"unsupported_export_data\" | \"upstream\" | \"verification_failed\" | \"withdrawal_capacity\" | \"withdrawal_provenance\" | \"writer_admin_intent_required\" | \"writer_admin_state_changed\" | \"writer_busy\" | \"writer_identity_publish_failed\" | \"writer_manifest_mismatch\" | \"writer_manifest_unsafe\" | \"writer_regrant_required\" | \"writer_transfer_conflict\" | \"writer_transfer_required\" | \"wrong_account_consented\" | undefined","canonicalCode: string","cause?: unknown","code: ErrorCode",@@ -7788,7 +7788,7 @@"kind": "variable","name": "DEGRADED_REASONS","signature": [- "readonly [\"no_provider\", \"provider_error\", \"timeout\", \"variant_embed_failed\", \"original_embed_failed\", \"first_result_truncated\", \"no_key\", \"empty_result_set\", \"malformed_shape\", \"budget\", \"candidate_budget\", \"iterative_scan_unavailable\", \"egress_denied\", \"embedding_disabled\"]"+ "readonly [\"no_provider\", \"provider_error\", \"timeout\", \"variant_embed_failed\", \"original_embed_failed\", \"first_result_truncated\", \"no_key\", \"empty_result_set\", \"malformed_shape\", \"budget\", \"rate_limited\", \"unreachable\", \"auth\", \"candidate_budget\", \"iterative_scan_unavailable\", \"egress_denied\", \"embedding_disabled\"]"]},{@@ -7802,7 +7802,7 @@"kind": "type","name": "DegradedReason","signature": [- "\"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | \"embedding_disabled\""+ "\"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"rate_limited\" | \"unreachable\" | \"auth\" | \"egress_denied\" | \"embedding_disabled\""]},{@@ -7815,7 +7815,7 @@{"kind": "interface","members": [- "reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"egress_denied\" | \"embedding_disabled\" | undefined",+ "reason?: \"candidate_budget\" | \"iterative_scan_unavailable\" | \"no_provider\" | \"provider_error\" | \"timeout\" | \"variant_embed_failed\" | \"original_embed_failed\" | \"first_result_truncated\" | \"no_key\" | \"empty_result_set\" | \"malformed_shape\" | \"budget\" | \"rate_limited\" | \"unreachable\" | \"auth\" | \"egress_denied\" | \"embedding_disabled\" | undefined","stage: \"embed_unavailable\" | \"embed_timeout\" | \"expansion_failed\" | \"expansion_partial\" | \"rescore_skipped\" | \"vector_arm_failed\" | \"keyword_arm_failed\" | \"title_arm_failed\" | \"budget_dropped_all\" | \"budget_truncated\" | \"keyword_zero\" | \"cache_prestamp\" | \"reranker_skipped\" | \"rerank_passthrough\" | \"rerank_failed\" | \"keyword_relaxed_carried\" | \"safe_index_pending\" | \"vector_candidates_incomplete\" | \"projection_pending\" | \"projection_status_unknown\""],"name": "DegradedStageEntry"diff --git a/test/rerank-degraded-notice.serial.test.ts b/test/rerank-degraded-notice.serial.test.tsnew file mode 100644index 0000000000..adc8f2ffeb--- /dev/null+++ b/test/rerank-degraded-notice.serial.test.ts@@ -0,0 +1,145 @@+/**+ * Cat 40 Hard R0 (DX "Rerank notice"): the `degraded_recall` notice for+ * `rerank_failed` names the reason, the fallback and this session's count of+ * reranker-degraded calls, with a `fix.next` per reason under the agent+ * operator contract; every affected call's `_meta.retrieval` records the same+ * without `fields: "full"`.+ *+ * Drives the REAL dispatch path (dispatchToolCall → search op handler) with+ * hybridSearchCached mocked to report the degradation.+ *+ * Serial: mock.module (isolation guard R2).+ */+import { describe, expect, mock, test } from 'bun:test';+import * as realHybrid from '../src/core/search/hybrid.ts';+import type { BrainEngine } from '../src/core/engine.ts';+import { renderNotice, type RenderContext } from '../src/core/agent-output.ts';+import { degradedRecallNotice } from '../src/core/interop-notices.ts';+import { NoticeLedger } from '../src/core/notice-ledger.ts';+import { DEGRADED_REASONS } from '../src/core/types.ts';+import type { RerankFailedReason } from '../src/core/search/rerank.ts';++let nextReason: string | undefined = 'unreachable';++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 }],+ });+ return [{ page_id: 1, source_id: 'default', slug: 'notes/a', title: 'A', type: 'note', chunk_text: 'a text', score: 1 }];+ },+}));++const { dispatchToolCall } = await import('../src/mcp/dispatch.ts');++const engineStub = {+ getConfig: async () => null,+ executeRaw: async (sql: string) => sql.includes('AS pending') ? [{ pending: false }] : [],+} as unknown as BrainEngine;++const REASONS: RerankFailedReason[] = ['timeout', 'budget', 'rate_limited', 'unreachable', 'auth', 'provider_error'];+const callable: RenderContext = { transport: 'stdio', isCallable: () => true, preapproved: () => false };++function notice(reason: RerankFailedReason, calls = 1) {+ return degradedRecallNotice([{ stage: 'rerank_failed', reason }], {+ transport: 'stdio', rerankDegradedCalls: calls, retry: { op: 'search', args: { query: 'q', limit: 5 } },+ })!;+}++function noticeBlock(out: { content: Array<{ text: string }> }): string | undefined {+ return out.content.map(c => c.text).find(t => t.startsWith('[gbrain notice degraded_recall'));+}++describe('rerank_failed notice per reason', () => {+ test('every reason is a wire reason code (the redactor keeps it)', () => {+ for (const r of REASONS) expect((DEGRADED_REASONS as readonly string[]).includes(r)).toBe(true);+ });++ test('the why names the reason, the fallback and the session count, and keeps the not-absence rule', () => {+ for (const r of REASONS) {+ const n = notice(r, 3);+ expect(n.code).toBe('degraded_recall');+ expect(n.kind).toBe('degraded');+ expect(n.why).toContain(`rerank_failed: ${r}`);+ expect(n.why).toContain('fallback: fused_order');+ expect(n.why).toContain('reranker-degraded calls this session: 3');+ expect(n.why).toContain('never as "the brain has nothing on this"');+ }+ expect(notice('unreachable').why).toContain('could not be reached');+ expect(notice('timeout').why).toContain('did not answer within its timeout');+ expect(notice('rate_limited').why).toContain('HTTP 429');+ });++ test('timeout and rate_limited: next wait, repeating the same call after the stated delay', () => {+ for (const [r, s] of [['timeout', 5], ['rate_limited', 20]] as const) {+ const fix = renderNotice(notice(r), callable).fix!;+ expect(fix.next).toBe('wait');+ expect(fix.mcp).toEqual({ tool: 'search', arguments: { query: 'q', limit: 5 } });+ expect(fix.why).toContain(`after about ${s} seconds`);+ }+ });++ test('unreachable, provider_error and budget: run doctor, verified by reranker_health', () => {+ for (const r of ['unreachable', 'provider_error', 'budget'] as const) {+ const fix = renderNotice(notice(r), callable).fix!;+ expect(fix.next).toBe('run');+ expect(fix.mcp?.tool).toBe('run_doctor');+ expect(fix.verify?.argv).toEqual(['gbrain', 'doctor', '--only', 'reranker_health', '--json']);+ }+ expect(notice('unreachable').fix!.why).toContain('provider_base_urls');+ expect(notice('budget').fix!.why).toContain("the user's call");+ });++ test('auth: the user replaces the key (credentials), never a key on a command line', () => {+ const n = renderNotice(notice('auth'), callable);+ expect(n.fix!.next).toBe('tell_user_to_run');+ expect(n.fix!.consent).toEqual(['credentials']);+ expect(n.fix!.why).toContain('never on a command line');+ expect(n.user_message).toBeDefined();+ });++ test('a missing or unknown reason reads as provider_error; another stage that needs a fix keeps its fix', () => {+ expect(degradedRecallNotice([{ stage: 'rerank_failed' }], { transport: 'stdio' })!.why).toContain('rerank_failed: provider_error');+ const both = degradedRecallNotice([{ stage: 'expansion_failed', reason: 'timeout' }, { stage: 'rerank_failed', reason: 'timeout' }], { transport: 'stdio', retry: { op: 'search', args: {} } })!;+ expect(both.fix?.argv).toEqual(['gbrain', 'doctor', '--json']);+ expect(both.why).toContain('expansion_failed, rerank_failed: timeout');+ });+});++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 () => {+ const noticeLedger = new NoticeLedger();+ nextReason = 'unreachable';+ const opts = { remote: true, transport: 'stdio' as const, sourceId: 'default', noticeLedger };+ const outs = [];+ for (let i = 0; i < 3; i++) outs.push(await dispatchToolCall(engineStub, 'search', { query: 'which account' }, opts));+ 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();+ });++ test('HTTP: the notice rides every affected call with the session running count; a healthy call adds nothing', async () => {+ const noticeLedger = new NoticeLedger();+ const opts = { remote: true, transport: 'http' as const, sourceId: 'default', noticeLedger, auth: { clientId: 'client-a', scopes: ['read'] }, sessionId: 's1' };+ nextReason = 'timeout';+ const first = await dispatchToolCall(engineStub, 'search', { query: 'which account' }, opts as any);+ nextReason = undefined;+ const healthy = await dispatchToolCall(engineStub, 'search', { query: 'which account' }, opts as any);+ nextReason = 'timeout';+ const second = await dispatchToolCall(engineStub, 'search', { query: 'which account' }, opts as any);+ expect(noticeBlock(first)).toContain('reranker-degraded calls this session: 1');+ expect(noticeBlock(first)).toContain('next: wait');+ expect(noticeBlock(healthy)).toBeUndefined();+ expect((healthy._meta as Record<string, any>).retrieval.rerank_degraded).toBeUndefined();+ expect(noticeBlock(second)).toContain('reranker-degraded calls this session: 2');+ expect((second._meta as Record<string, any>).retrieval.rerank_degraded).toEqual({ reason: 'timeout', fallback: 'fused_order', calls_this_session: 2 });+ const other = await dispatchToolCall(engineStub, 'search', { query: 'which account' }, { ...opts, sessionId: 's2' } as any);+ expect((other._meta as Record<string, any>).retrieval.rerank_degraded.calls_this_session).toBe(1);+ });+});diff --git a/test/rerank-failure-reason.serial.test.ts b/test/rerank-failure-reason.serial.test.tsnew file mode 100644index 0000000000..631b6c6c4b--- /dev/null+++ b/test/rerank-failure-reason.serial.test.ts@@ -0,0 +1,155 @@+/**+ * Cat 40 Hard R0: a hard reranker failure carries the reason the gateway can+ * actually tell apart, through the REAL wire path (gateway.rerank over fetch+ * to local servers, no transport seam).+ *+ * The held-out run's slots pointed `provider_base_urls.voyage` at a metering+ * proxy port from an earlier process, so every rerank call got "connection+ * refused" and the wire said only `provider_error`. A timeout said the same:+ * the abort timer's Error reached the catch as a plain Error, not an+ * AbortError, and was filed as a network failure.+ *+ * Serial: configureGateway changes the process-wide AI gateway and the audit+ * dir is set through process.env; binds local ports.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { configureGateway, resetGateway, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { hybridSearch } from '../src/core/search/hybrid.ts';+import { installFixtureChunks } from './helpers/page-projection.ts';+import { applyReranker, type RerankFailedReason } from '../src/core/search/rerank.ts';+import { BudgetExhausted } from '../src/core/budget/budget-tracker.ts';+import { readRecentRerankFailures } from '../src/core/rerank-audit.ts';+import type { SearchResult } from '../src/core/types.ts';+import { withEnv } from './helpers/with-env.ts';++const rows = (): SearchResult[] => ['a', 'b', 'c'].map((s, i) => ({+ slug: `notes/${s}`, page_id: i + 1, title: s, type: 'note', chunk_text: `${s} text`, chunk_source: 'compiled_truth',+ chunk_id: i + 1, chunk_index: 0, score: 1 - i / 10, stale: false,+} as SearchResult));++let server: ReturnType<typeof Bun.serve>;+let deadPort: number;+let auditDir: string;++beforeAll(() => {+ server = Bun.serve({+ port: 0, hostname: '127.0.0.1',+ fetch: async (req) => {+ const status = Number(new URL(req.url).pathname.split('/')[1]);+ if (status === 0) { await Bun.sleep(2_000); return Response.json({ data: [] }); }+ if (status === 200) return Response.json({ data: [{ index: 2, relevance_score: 0.9 }, { index: 0, relevance_score: 0.5 }, { index: 1, relevance_score: 0.1 }] });+ return new Response('{"detail":"no"}', { status });+ },+ });+ const probe = Bun.serve({ port: 0, hostname: '127.0.0.1', fetch: () => new Response('') });+ deadPort = probe.port!;+ probe.stop(true);+ auditDir = mkdtempSync(join(tmpdir(), 'gbrain-rerank-reason-'));+});++afterAll(() => {+ server.stop(true);+ __setEmbedTransportForTests(null);+ resetGateway();+ rmSync(auditDir, { recursive: true, force: true });+});++/** Rerank against `baseUrl` with the real gateway and fetch; returns the reported failure reason (undefined on success). */+async function rerankVia(baseUrl: string, timeoutMs = 2_000): Promise<{ reason?: RerankFailedReason; out: SearchResult[] }> {+ configureGateway({+ embedding_model: 'openai:text-embedding-3-small', embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test', VOYAGE_API_KEY: 'vk-test' },+ base_urls: { voyage: baseUrl },+ } as any);+ let reason: RerankFailedReason | undefined;+ const out = await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, () => applyReranker('which note', rows(), {+ enabled: true, topNIn: 30, topNOut: null, model: 'voyage:rerank-2.5', timeoutMs,+ onFailure: (r) => { reason = r; },+ }));+ return { reason, out };+}++describe('rerank failure reasons on the real wire path', () => {+ test('an unreachable endpoint (connection refused) reports unreachable, not provider_error', async () => {+ const { reason, out } = await rerankVia(`http://127.0.0.1:${deadPort}/v1`);+ expect(reason).toBe('unreachable');+ expect(out.map(r => r.slug)).toEqual(['notes/a', 'notes/b', 'notes/c']);+ });++ test('a call past its timeout reports timeout', async () => {+ const t0 = performance.now();+ const { reason } = await rerankVia(`http://127.0.0.1:${server.port}/0`, 150);+ expect(reason).toBe('timeout');+ expect(performance.now() - t0).toBeLessThan(1_500);+ const row = await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, () => readRecentRerankFailures(1).at(-1));+ expect(row?.reason).toBe('timeout');+ });++ test('HTTP 429 reports rate_limited', async () => {+ expect((await rerankVia(`http://127.0.0.1:${server.port}/429`)).reason).toBe('rate_limited');+ });++ test('HTTP 401 reports auth', async () => {+ expect((await rerankVia(`http://127.0.0.1:${server.port}/401`)).reason).toBe('auth');+ });++ test('HTTP 503 and 400 report provider_error', async () => {+ expect((await rerankVia(`http://127.0.0.1:${server.port}/503`)).reason).toBe('provider_error');+ expect((await rerankVia(`http://127.0.0.1:${server.port}/400`)).reason).toBe('provider_error');+ });++ test('a healthy endpoint reranks and reports no failure', async () => {+ const { reason, out } = await rerankVia(`http://127.0.0.1:${server.port}/200`);+ expect(reason).toBeUndefined();+ expect(out.map(r => r.slug)).toEqual(['notes/c', 'notes/a', 'notes/b']);+ });++ test('a spend cap reports budget', async () => {+ let reason: RerankFailedReason | undefined;+ await withEnv({ GBRAIN_AUDIT_DIR: auditDir }, () => applyReranker('which note', rows(), {+ enabled: true, topNIn: 30, topNOut: null,+ rerankerFn: async () => { throw new BudgetExhausted('spend cap reached', { reason: 'cost', spent: 1, cap: 1 }); },+ onFailure: (r) => { reason = r; },+ }));+ expect(reason).toBe('budget');+ });+});++describe('the held-out run, reproduced: a stale proxied reranker base URL', () => {+ test('hybridSearch with the reranker on and provider_base_urls.voyage on a dead port stamps rerank_failed: unreachable and keeps fused order', async () => {+ const home = mkdtempSync(join(tmpdir(), 'gbrain-rerank-reason-home-'));+ const engine = new PGLiteEngine();+ try {+ await withEnv({ GBRAIN_HOME: home, GBRAIN_AUDIT_DIR: auditDir }, async () => {+ await engine.connect({});+ await engine.initSchema();+ for (const s of ['alpha', 'beta', 'gamma']) {+ await engine.putPage(`notes/${s}`, { type: 'note', title: s, compiled_truth: `shared keyword ${s}` });+ await installFixtureChunks(engine, `notes/${s}`, [{ chunk_index: 0, chunk_text: `shared keyword ${s}`, chunk_source: 'compiled_truth' }]);+ }+ configureGateway({+ embedding_model: 'openai:text-embedding-3-large', embedding_dimensions: 1536,+ env: { OPENAI_API_KEY: 'sk-test', VOYAGE_API_KEY: 'vk-test' },+ base_urls: { voyage: `http://127.0.0.1:${deadPort}/slot0/voyage/v1` },+ } as any);+ __setEmbedTransportForTests(async (args: any) => ({ embeddings: args.values.map(() => Array.from({ length: 1536 }, (_, j) => (j === 0 ? 1 : 0.01))) }) as any);+ let degraded: Array<{ stage: string; reason?: string }> = [];+ const out = await hybridSearch(engine, 'shared keyword', {+ limit: 10,+ reranker: { enabled: true, topNIn: 30, topNOut: null, model: 'voyage:rerank-2.5', timeoutMs: 5_000 },+ onMeta: (m) => { degraded = m.degraded ?? []; },+ });+ expect(out.length).toBe(3);+ expect(out.every(r => r.rerank_score === undefined)).toBe(true);+ expect(degraded).toContainEqual({ stage: 'rerank_failed', reason: 'unreachable' });+ });+ } finally {+ await engine.disconnect();+ rmSync(home, { recursive: true, force: true });+ }+ });+});