Canonical page: [Retrieval and the Decider](https://cloudflavor.io/aemon/docs/retrieval/)
Source snapshot: https://github.com/cloudflavor/aemon/blob/a85ee1d024b81c6373acd86379fe12f15c26a7a5/docs/retrieval.md

# Retrieval and the Decider

Two stages, and only the first one is mandatory.

## Stage 1: BM25 over FTS5

FTS5 indexes `entries(body, title, kind)` with Porter stemming, `unicode61` and
`tokenchars '_'`, so `max_connections`, `unwrap_or_else` and `sort_by` stay single
tokens. Ranking is `bm25(entries_fts, 1.0, 5.0, 1.0)` — body weight 1, title weight 5 —
and a strict `AND` query that returns nothing is retried with `OR`.

The lexical score is then re-weighted:

```
relevance = -bm25 × kind × title_coverage × symbol × exact × summary
```

- `kind`: Guide/Manual/Reference ×1.35, error FAQ/changelog/release notes ×0.55.
- `title_coverage`: fraction of query tokens present in the chunk title.
- `symbol`: the anchor-index bonus for `symbol:*` rows.
- `exact`: 1.35× when the longest query token appears verbatim in the body.
- `summary`: neutral (1.0) for enriched chunks; summaries are display-only.

Typical latency is ~10 ms for a single corpus.

## Stage 2: optional model rerank (`--rerank`)

Lexical search cannot bridge "my build is slow" → "build cache", so the model first
rewrites the question into 3–5 keyword queries. The variant pools are merged, and one
listwise call orders the top 12. Expansions and reranks are cached in `expand_cache`
and `rerank_cache`; `--no-cache` bypasses all of it.

Reranking **fuses** with the lexical order (reciprocal-rank, weight 0.8) instead of
replacing it. An unguarded listwise rerank put "Footnotes" first for the numpy query;
RRF would have kept it out of the top slot.

## The decider (`--auto`)

`aemon search "..." --auto` makes one model call that returns a *plan*: which libraries
the question is about, whether the anchor index is useful, whether to expand the query,
whether to rerank, and how wide the candidate pool should be.

It sees the **whole library catalog**, not a BM25 shortlist — a 10-name shortlist is how
"trap errors on exit" chose perl and erlang — plus `~/.config/aemon/stack`
(`$AEMON_STACK`), a list of libraries you actually work with:

```
rust
python
bash
go
typescript
sqlite
postgresql
docker
```

That stack is a *preference*, never a filter, so a wrong guess cannot hide the right
answer. The plan's first library gets a 2.2× relevance boost, alternates 1.5×/1.25×.

Decisions are cached under a key that includes the query, the catalog size and the
stack, so ingesting a library or editing the stack invalidates them. `--decider SPEC`
overrides the routing model for one invocation and wins over `--rerank`; an unavailable
decider falls back to the heuristic plan with a warning on stderr.

```
aemon resolve --auto "<question>"      # the shortlist on its own
aemon search "<question>" --auto
plan: libraries=[docker] intent=concept symbols=false expand=true rerank=true candidates=60
      — Task/diagnostic question about slow docker builds; concept search with expansion and reranking.
```

The same client classifies chunks at ingest time (`aemon prune -d <corpus>`): `content`,
`example`, `nav`, `boilerplate`. Non-content chunks are deleted. Labels are cached in
`prune_state`; a truncated or unparsable answer means *keep*, never delete.

## Consumption: `outline` → `get`

Search is not the only interface. The pattern that keeps token use sane:

```
$ aemon outline "select_related prefetch_related" -d django~6.1
  481666  django  Guides       440  Use `QuerySet.select_related()` and `prefetch_related()`
  479750  django  django.db.models  1414  `prefetch_related(*lookups)`
$ aemon get 481666 --budget 2000
```

`outline` costs ~40 tokens per candidate and leaves the choice to the caller. `get`
returns the **expanded section** — the hit plus the rest of its page around it, labelled
with `###` when it crosses into the next item — which is what actually answers the
question. `search --md` does the same expansion inline (`--no-expand` disables it).

**Context budget is a quality knob**: expanding each hit to ~3 000 characters lifted
judged quality from 81 % to 88 %. `search --md` and `get` default to 2 000; raise it
rather than lower it.

## Measured quality

Fifteen hand-written queries with expected pages (`eval/queries.py`):

| mode | hit@1 | hit@3 | latency |
|---|---|---|---|
| BM25 + heuristics, corpus given | 13/15 (86 %) | 13/15 (86 %) | ~10 ms |
| + expansion + rerank, corpus given | 14/15 (93 %) | 15/15 (100 %) | 0.3–14 s (cached 0.3 s) |
| `hint` (library given), 39 realistic queries | 23/39 (59 %) | 30/39 (77 %) | 0.2 s |
| `--rerank` + hint, same 39 | 30/39 (77 %) | 34/39 (87 %) | 5.6 s |
| `--auto`, no hint, same 39 | **32/39 (82 %)** | **36/39 (92 %)** | 0.6 s |
| `--auto` judged, 64 queries, 3 000-char context | — | **56/64 (88 %)** | 1.8 s |
| same, 1 400-char context | — | 55/64 (86 %) | — |
| same, 700-char context | — | 52/64 (81 %) | — |

Decider accuracy (`eval/decider.py`, 39 question-shaped queries, no hints):

| | before catalog+stack | after |
|---|---|---|
| expected library in the plan | 26/39 (66 %) | **37/39 (94 %)** |
| expected library as first choice | 24/39 (61 %) | **32/39 (82 %)** |
| winning hit from the expected library | 27/39 (69 %) | **30/39 (76 %)** |

`n=15` is small: ±1 query is noise, which is why nothing here replaces the fused
lexical order. After later corpus additions the same bench reads `hint` 26/39 (67 %) /
33/39 (85 %) and `--auto` 31/39 (79 %) / **37/39 (95 %)**.

`--auto` reaches the right *answer* 15/15 but names the library the eval expects only
11/15: several libraries document the same concept (Laravel also documents middleware
ordering, Varnish also documents `max_connections`). Without project context that
ambiguity is irreducible, which is why `aemon resolve` exists — an agent that knows its
stack should pass `-l`, and then hit@1 is 86–93 %.

## Coverage guard

Out-of-corpus questions used to return *neighbours*: `trpc` → FastAPI middleware,
`kafka` → Vert.x. The decider now reports what it cannot cover:

```
$ aemon search "kafka consumer rebalance" --auto
COVERAGE GAP: no corpus for [kafka] — results below are neighbours, not docs for kafka
```

In JSON those are `kind: "gap"` rows with `id: 0`. They are not documents, `get`
refuses them, real hits precede them, and they do not count toward a successful search.

Facade crates (`clap`, `sqlx`) re-export everything from sibling crates; `aemon crate`
follows `<crate>-*` siblings once and files them under the same library, so `-l clap`
reaches `clap_derive`. A library may therefore own several corpora at the same version,
and the default "current version" filter keeps all of them.

## Freshness

`aemon fresh <library>` reports `release`, `built_year`, `age_years` and `stale`.
Staleness means the local ingest year is more than two calendar years old — not that
the upstream release is obsolete. `fresh --check` exits 5 when stale, which is what a
scheduled job should assert on.

## Known gaps

- **No embeddings endpoint** on the available providers, so "semantic" here means
  expansion plus rerank, not vector search.
- **Proc-macro crates** (e.g. `serde_derive`) ship rustdoc JSON with no docs, so
  attribute reference pages are missing; split crates (`ratatui` → `ratatui-core`,
  `ratatui-widgets`) need each sub-crate ingested.
- **Enrichment does not pay for itself yet** — see [ingestion](ingestion.md).
