Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(models): reranker doc names the maintainers' GGUF; doctor probe checks the model ranks (#6381)
time-attackf38a1e030bab
diff --git a/docs/ai-providers/llama-server-reranker.md b/docs/ai-providers/llama-server-reranker.mdindex 1e67c548c4..75742801b7 100644--- a/docs/ai-providers/llama-server-reranker.md+++ b/docs/ai-providers/llama-server-reranker.md@@ -12,8 +12,9 @@ One supported local model family:- **Qwen3-Reranker** (0.6B / 4B / 8B) — open-weight cross-encoder. Qwenpublishes official GGUFs for its EMBEDDING models but not for the- rerankers, so pull a community GGUF conversion from HuggingFace (or- convert the official weights yourself) and serve.+ rerankers. Use the llama.cpp maintainers' 0.6B build, or convert the+ official weights yourself (step 2). Some community conversions drop the+ classifier head and score every passage near zero.This recipe is the path override + recipe shape. Any provider whoserequest/response wire matches llama.cpp can use it by just pointing@@ -43,36 +44,45 @@ across releases. The recipe sends to `/v1/rerank`.### 2. Pull a reranker GGUF-For Qwen3-Reranker-4B (quantized Q4_K_M is the sweet spot for CPU),-pull a community GGUF conversion. Qwen ships no official reranker GGUF-repos (the official `Qwen/Qwen3-Reranker-4B` repo carries the raw-weights only), so the conversion below is **community-maintained** —-verify scores against your own eval before trusting it in production:+Default: the llama.cpp maintainers' conversion of Qwen3-Reranker-0.6B+(`ggml-org` on Hugging Face):```bash-# Pick a quant level — Q4_K_M is the usual CPU sweet spot.huggingface-cli download \- mradermacher/Qwen3-Reranker-4B-GGUF Qwen3-Reranker-4B.Q4_K_M.gguf \+ ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF qwen3-reranker-0.6b-q8_0.gguf \--local-dir ./models```-Prefer official provenance? Convert the real `Qwen/Qwen3-Reranker-4B`-weights yourself with llama.cpp's `convert_hf_to_gguf.py`, then quantize.+(`llama-server -hf ggml-org/Qwen3-Reranker-0.6B-Q8_0-GGUF` downloads and+serves it in one step.)++For 4B or 8B there is no maintainers' build. Convert the official+`Qwen/Qwen3-Reranker-4B` (or `-8B`) weights yourself with llama.cpp's+`convert_hf_to_gguf.py`, then quantize with `llama-quantize` (Q4_K_M is the+usual CPU choice).++> **Check a GGUF before you trust it.** A conversion without the+> classifier tensor (`cls.output.weight`) loads and answers, but every+> score is meaningless (around 1e-28 in the llama.cpp issue tracker). List+> the tensors with the dump script in llama.cpp's `gguf-py`+> (`python gguf-py/gguf/scripts/gguf_dump.py ./models/<file>.gguf | grep cls.output`)+> and expect a match. `gbrain models doctor` also catches it (step 5).### 3. Launch llama-server with --reranking AND --alias```bash./build/bin/llama-server \- --model ./models/Qwen3-Reranker-4B.Q4_K_M.gguf \- --alias qwen3-reranker-4b \- --reranking \+ --model ./models/qwen3-reranker-0.6b-q8_0.gguf \+ --alias qwen3-reranker-0.6b \+ --reranking --pooling rank \--port 8081```The `--alias` matters: without it, llama-server's `/v1/models` (and the`model` field rerank requests echo) defaults to the full gguf filepath, which makes the gbrain config string ugly and brittle. With-`--alias qwen3-reranker-4b`, your config string is short and stable.+`--alias qwen3-reranker-0.6b`, your config string is short and stable.+`--pooling rank` selects the reranking head explicitly.`--reranking` and `--embeddings` are mutually exclusive at serverlaunch. If you also run a local embedder via the@@ -88,11 +98,11 @@ match that convention).gbrain config set provider_base_urls.llama-server-reranker http://your-host:8081/v1# Tell search to use this reranker-gbrain config set search.reranker.model llama-server-reranker:qwen3-reranker-4b+gbrain config set search.reranker.model llama-server-reranker:qwen3-reranker-0.6bgbrain config set search.reranker.enabled true```-The `qwen3-reranker-4b` after the colon is your `--alias` value from+The `qwen3-reranker-0.6b` after the colon is your `--alias` value fromstep 3. Any string works as long as it matches your server's alias.Env vars work too as an alternative to the config set above:@@ -107,13 +117,18 @@ export LLAMA_SERVER_RERANKER_API_KEY=your-bearer-token```bashgbrain models doctor-# Expect: ✔ reranker_config llama-server-reranker:qwen3-reranker-4b ok-# ✔ reranker_config llama-server-reranker:qwen3-reranker-4b ok (reachability)+# Expect: ✔ reranker_config llama-server-reranker:qwen3-reranker-0.6b ok+# ✔ reranker_config llama-server-reranker:qwen3-reranker-0.6b ok (reachable; ranks a relevant passage above an unrelated one)gbrain search "some query" --json | jq '.[].rerank_score'# Expect: rerank_score on every row```+The reachability probe sends one question with a relevant and an+unrelated passage. If it reports `config` ("scores an unrelated passage as+high as a relevant one"), the server answers but the model can't rank:+usually a broken conversion. Replace the GGUF (step 2).+If `gbrain models doctor` reports the reachability probe as `network`status, two common causes:@@ -162,7 +177,7 @@ hard-fail when configured for local rerank. Local rerank costselectricity, not API tokens.```bash-GBRAIN_MAX_USD=0.01 gbrain search "..." --reranker llama-server-reranker:qwen3-reranker-4b+GBRAIN_MAX_USD=0.01 gbrain search "..." --reranker llama-server-reranker:qwen3-reranker-0.6b# Works: rerank fires, recorded at $0, cumulative cap untouched.```diff --git a/docs/architecture/key-files/commands-4.md b/docs/architecture/key-files/commands-4.mdindex 0573208a6d..2213711f71 100644--- a/docs/architecture/key-files/commands-4.md+++ b/docs/architecture/key-files/commands-4.md@@ -31,7 +31,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL- `src/commands/migrations/v0_46_3.ts` — idempotent no-op for a retired notification. Returns a complete migration with a skipped notice phase; performs no database, config, provider, vector or pending-work writes. Its feature pitch points to read-only status and explicit-target migration previews.- `src/commands/migrations/v0_60_31.ts` — the security fix wave orchestrated migration (ledger `0.60.31`), two phases. `credential_projection`: runs `runMigrateOnlyCore` first (schema v189 marks the pages; PGLite skips the runner's schema pre-flight), then `resealCredentialProjections`, provider-free and never embedding; a dry run reports the count; any failed page makes the run `partial`, so `gbrain apply-migrations --yes --no-autopilot-install` retries it, and re-sealed pages are no longer pending, so a rerun resumes. `google_file_modes_notice`: `googleFileModesNoticePhase` from `v0_60_31-google-file-modes.ts`. A brain without config completes with the phase skipped. Agent instructions: `skills/migrations/v0.60.31.0.md`.-- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`) derived from `resolveModelDetailed`, so a tier key is attributed before `models.default`. A `Nightly quality probe` block (JSON `nightly_probe`; `schema_version` stays 1) shows the probe's routes from `resolveNightlyProbeModelRoutes`: reader and extractor with their source, and each judge slot labelled `config: models.eval.cross_modal.slot_<x>`, `panel default` or `substitute for <default> (no usable provider)` — the #4636 substitution run with a silent log against this process's gateway. Its `environment_note` says availability, substitutes and key-aware defaults are judged from this process's environment, so a key only in the daemon's `~/.gbrain/env` reads as unavailable. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory `[newer <family> available: <id>] (gbrain config set ...)` hint (JSON: `newer_available`); version parsing lives in `src/core/ai/anthropic-model-ids.ts` (8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default. `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.+- `src/commands/models.ts` — `gbrain models [--json]` read-only routing dashboard: prints tier defaults (`utility`/`reasoning`/`deep`/`subagent`), the resolved value for each (re-walking the resolution chain), every per-task override (14 `PER_TASK_KEYS`, including provider-neutral `models.contextual_synopsis` with legacy-key/env attribution and `models.dream.extract_atoms` which reports via its own caller-specific resolver — `resolveExtractAtomsModel()` in `extract-atoms.ts` — rather than the generic chain, so the report can't diverge from what the phase actually calls), the alias map, and a source-of-truth column (`default` / `config: <key>` / `env: <VAR>`) derived from `resolveModelDetailed`, so a tier key is attributed before `models.default`. A `Nightly quality probe` block (JSON `nightly_probe`; `schema_version` stays 1) shows the probe's routes from `resolveNightlyProbeModelRoutes`: reader and extractor with their source, and each judge slot labelled `config: models.eval.cross_modal.slot_<x>`, `panel default` or `substitute for <default> (no usable provider)` — the #4636 substitution run with a silent log against this process's gateway. Its `environment_note` says availability, substitutes and key-aware defaults are judged from this process's environment, so a key only in the daemon's `~/.gbrain/env` reads as unavailable. A resolved Anthropic haiku/sonnet/opus id older (by major, minor) than the anthropic recipe's newest priced same-family id gets an advisory `[newer <family> available: <id>] (gbrain config set ...)` hint (JSON: `newer_available`); version parsing lives in `src/core/ai/anthropic-model-ids.ts` (8-digit segment is a date, so dated and undated forms compare equal; fable, non-Anthropic, newer-than-recipe and unparseable ids get no hint). The hint never changes a default. `gbrain models doctor [--skip=<provider>] [--json]` fires a 1-token `gateway.chat()` probe against each configured chat + expansion model and classifies failures into `{model_not_found, auth, rate_limit, network, unknown}`. The probe timeout resolves per model via `resolveChatProbeTimeoutMs` — the recipe touchpoint's `default_timeout_ms` when declared, else the flat 5000ms default (mirrors the reranker probe's recipe-default fallback; `claude-cli` declares 30s because its `claude -p` subprocess cold start routinely outruns 5s and would false-fail every run as `unknown`). The reranker reachability probe sends one question with a relevant and an unrelated passage and reports `ok` only when the relevant one scores higher by more than 0.1; equal, inverted or missing scores are `config` with a fix naming `docs/ai-providers/llama-server-reranker.md` step 2 (a broken GGUF conversion answers but ranks at random). Wired into `cli.ts` dispatch + `CLI_ONLY` set. A zero-token `embedding_config` probe runs FIRST, before any chat/expansion probes spend money: `probeEmbeddingConfig()` reads `getEmbeddingModel()` + `getEmbeddingDimensions()` and (for Voyage flexible-dim models) checks `isValidVoyageOutputDim(dims)` against `VOYAGE_VALID_OUTPUT_DIMS`. `ProbeStatus` variant `'config'` + optional `fix?: string` on `ProbeResult` surface a paste-ready `gbrain config set ...` line in human + JSON output; touchpoint label `'embedding_config'` joins `'chat'` and `'expansion'`.- `src/commands/pricing.ts` — `gbrain pricing set <model> --input <usd/1M> --output <usd/1M> | --rate <usd/1M> [--source <url>]`, `pricing list [--json]`, `pricing unset <model>`. Each write reads `pricing.overrides`, changes one entry (keyed by the lowercased model; case variants replaced) and writes it back, so other entries survive; an unreadable stored value is refused, never overwritten. Rates must be non-negative finite numbers; $0 is accepted with a stderr warning. Entries keep the parser schema (`{input, output}` or `pricePerMTok`) with `source` and `set_at` beside them. Trust boundary: CLI-only (never an operation, so MCP cannot reach it) and `thinClient: 'refuse'` in the command table. Pinned by `test/budget/no-pricing-registration.test.ts`.- `src/commands/orphans.ts` — `gbrain orphans` and MCP `find_orphans` share islanded (no live inbound or outbound links) and legacy inbound-only modes. Read policy scopes candidates and excludes private candidates, endpoints and independent origin pages before counting. Cross-source public links still establish reachability by the documented orphan definition. Reporting exclusions (`shouldExcludeFromOrphanReporting`) stay centralized; the scoped live-page denominator excludes the same private/reporting rows. `--source` remains explicit; no new remote privacy parameter. Connector renders (an `email`/`meeting` page whose source `config.kind` is a connector kind) are islanded by construction, so they leave both totals and are reported as `connector_renders_excluded` (`--include-pseudo` keeps them); doctor `orphan_ratio` carries that count in `details` and prints `gbrain extract links --by-mention --source db` (plus `--source-id` when scoped). Pinned by `test/orphan-ratio-connector-renders.test.ts`.diff --git a/src/commands/models.ts b/src/commands/models.tsindex 2af0958de5..7d32326fb3 100644--- a/src/commands/models.ts+++ b/src/commands/models.ts@@ -630,6 +630,14 @@ async function probeRerankerConfig(engine: BrainEngine): Promise<ProbeResult> {* when set — so a CPU-only local reranker's cold-start warmup doesn't* cause the probe to false-fail with `network`/timeout.*/+/** #6381: one relevant and one unrelated passage; a working cross-encoder separates them by a clear margin. */+const RERANK_PROBE = {+ query: 'What is the capital of France?',+ relevant: 'Paris is the capital of France.',+ unrelated: 'Bananas are a yellow fruit.',+} as const;+const RERANK_PROBE_MIN_MARGIN = 0.1;+export async function probeRerankerReachability(engine: BrainEngine, deps: ProbeDeps = {}): Promise<ProbeResult | null> {const modelStr = await resolveLiveRerankerModel(engine);if (!modelStr) return null;@@ -648,18 +656,34 @@ export async function probeRerankerReachability(engine: BrainEngine, deps: Probeconst controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(new Error(`probe timed out after ${probeTimeoutMs}ms`)), probeTimeoutMs);try {- await rerank({+ const results = await rerank({model: modelStr,- query: 'probe',- documents: ['probe document'],+ query: RERANK_PROBE.query,+ documents: [RERANK_PROBE.relevant, RERANK_PROBE.unrelated],signal: controller.signal,timeoutMs: probeTimeoutMs,});+ const relevant = results.find(r => r.index === 0)?.relevanceScore;+ const unrelated = results.find(r => r.index === 1)?.relevanceScore;+ const discriminates = Number.isFinite(relevant) && Number.isFinite(unrelated)+ && (relevant as number) - (unrelated as number) > RERANK_PROBE_MIN_MARGIN;+ if (!discriminates) {+ return {+ model: modelStr,+ touchpoint: 'reranker_config',+ status: 'config',+ message: Number.isFinite(relevant) && Number.isFinite(unrelated)+ ? `reachable, but it scores an unrelated passage as high as a relevant one (${relevant} vs ${unrelated})`+ : 'reachable, but it did not return a score for both probe passages',+ elapsed_ms: Date.now() - start,+ fix: 'The model is likely a broken GGUF conversion; see docs/ai-providers/llama-server-reranker.md step 2.',+ };+ }return {model: modelStr,touchpoint: 'reranker_config',status: 'ok',- message: 'reachable',+ message: 'reachable; ranks a relevant passage above an unrelated one',elapsed_ms: Date.now() - start,};} finally {diff --git a/test/models-doctor-reranker.test.ts b/test/models-doctor-reranker.test.tsindex a404b0bdc1..0a75fb4bf1 100644--- a/test/models-doctor-reranker.test.ts+++ b/test/models-doctor-reranker.test.ts@@ -14,7 +14,7 @@*/import { describe, test, expect, afterEach } from 'bun:test';-import { resolveLiveRerankerModel } from '../src/commands/models.ts';+import { probeRerankerReachability, resolveLiveRerankerModel } from '../src/commands/models.ts';import { configureGateway, resetGateway } from '../src/core/ai/gateway.ts';/**@@ -97,3 +97,34 @@ describe('resolveLiveRerankerModel — divergence fix', () => {expect(resolved).toBe('voyage:rerank-2.5');});});++describe('probeRerankerReachability — discrimination (#6381)', () => {+ const engine = makeEngineStub({ 'search.reranker.model': 'llama-server-reranker:qwen3-reranker-0.6b', 'search.reranker.enabled': 'true' });+ type Rerank = NonNullable<Parameters<typeof probeRerankerReachability>[1]>['rerank'];+ const stub = (scores: Array<{ index: number; relevanceScore: number }>, seen?: { documents?: string[] }): Rerank =>+ (async (input: { documents: string[] }) => { if (seen) seen.documents = input.documents; return scores; }) as unknown as Rerank;++ test('a broken conversion that scores both passages near zero is a config finding with the doc fix', async () => {+ configureGateway({ env: {} });+ const r = await probeRerankerReachability(engine, { rerank: stub([{ index: 0, relevanceScore: 1e-28 }, { index: 1, relevanceScore: 3e-29 }]) });+ expect(r?.status).toBe('config');+ expect(r?.message).toContain('unrelated passage as high as a relevant one');+ expect(r?.fix).toContain('docs/ai-providers/llama-server-reranker.md');+ });++ test('a reranker that ranks the relevant passage clearly higher is ok; the probe sends one relevant and one unrelated passage', async () => {+ configureGateway({ env: {} });+ const seen: { documents?: string[] } = {};+ const r = await probeRerankerReachability(engine, { rerank: stub([{ index: 1, relevanceScore: 0.01 }, { index: 0, relevanceScore: 0.97 }], seen) });+ expect(r?.status).toBe('ok');+ expect(seen.documents).toHaveLength(2);+ });++ test('an inverted ranking and a response missing a passage are config findings', async () => {+ configureGateway({ env: {} });+ expect((await probeRerankerReachability(engine, { rerank: stub([{ index: 0, relevanceScore: 0.1 }, { index: 1, relevanceScore: 0.9 }]) }))?.status).toBe('config');+ const missing = await probeRerankerReachability(engine, { rerank: stub([{ index: 0, relevanceScore: 0.9 }]) });+ expect(missing?.status).toBe('config');+ expect(missing?.message).toContain('did not return a score for both');+ });+});