Documentation
¶
Overview ¶
Package retrieve implements atl's per-prompt hybrid knowledge retrieval.
The knowledge loop's write side is automated (learning-capture -> /drain -> wiki + journal + agent knowledge base); #140 closes the read side by letting an agent consult that knowledge per prompt. Retrieval is hybrid: a lexical BM25 index plus this local semantic embedder, RRF-fused to a small top-k.
The embedder turns text into dense vectors with a local ONNX model run through the pure-Go gomlx SimpleGo backend (via knights-analytics/hugot). It needs no native library, so the atl binary still cross-compiles to every release target with CGO_ENABLED=0 — the constraint that ruled out a CGo ONNX runtime. It is a text->vector utility, NOT an LLM: it only surfaces the right knowledge pages to hand the agent; Claude remains the agent.
This file plus model.go is the embedder; the lexical index and fusion land in sibling files.
Index ¶
Constants ¶
const MinSimDefault = 0.25
Query returns the top-k documents for a prompt, fusing a BM25 lexical ranking with a semantic (cosine) ranking via RRF. It embeds the prompt once. When the index carries no vectors (an embedder-less build), it degrades to BM25 only. MinSimDefault is the cosine floor the semantic arm applies, below which a document is treated as "no signal" rather than as a weak match.
Derived, not guessed. Re-measured 2026-08-04 against the FULL 328-doc index after the multilingual embedder swap, 28 probes, top-1 cosine by band:
on-topic English 0.165 … 0.564 (median 0.386) on-topic Turkish 0.322 … 0.542 (median 0.454) off-topic English 0.079 … 0.235 off-topic Turkish 0.103 … 0.480
0.25 is unchanged, and it now does the job it could not do before: ALL 8 on-topic Turkish probes clear it, where under the English-only model Turkish scored ~0.140 and none did.
The bands OVERLAP — lowest on-topic 0.165 sits below highest off-topic 0.480 — so no single threshold separates them cleanly, and the two outliers are the model's limit rather than a tuning error:
- 0.480, a Turkish off-topic probe about climbing knots, matching a page about shipping discipline. The same question asked in English scores 0.235: the model is looser in Turkish, and a threshold cannot tell those apart.
- 0.165, "brownfield onboarding has no path through kickoff", whose answer IS in the corpus. Not a loss in practice — those terms appear in the page, so the lexical arm carries it. The floor gates the semantic arm only; the hybrid is what the user sees.
Raising to 0.30 would drop 2 of 8 on-topic English probes to gain one off-topic rejection — the wrong trade, since silence on a real question is the worse failure. At 0.25: 15 of 16 on-topic probes clear, 11 of 12 off-topic are rejected.
Variables ¶
This section is empty.
Functions ¶
func AcquireBuildLock ¶
AcquireBuildLock takes the index-build lock for a project, returning a release function. ok is false when another build already holds it — the caller should exit quietly, not error: a second build is a duplicate, not a failure.
This exists because the auto-index path had no single-flight guard at all. It throttles how often a build is SPAWNED (10 minutes) but never asked whether one was already running, and that gap only became reachable when the corpus grew past the point where a build outlasts the throttle window: two full rebuilds then run concurrently, each saturating the machine. Measured in the wild at 832% CPU with a second process starting behind it.
The lock is advisory and best-effort by design. Every failure path returns ok=true — if the lock cannot be written, indexing must still happen; a retrieval index that silently stops updating is worse than one built twice.
func EnsureModel ¶
EnsureModel returns the local directory of the default embedding model, downloading and sha256-verifying its files on first use. Idempotent: when every file is already present and verifies, it makes no network call.
func ModelDirIfPresent ¶
ModelDirIfPresent returns the default model's local directory and true only if every file is already present at its expected size — the cheap check (no hash, no network) the retrieval hook uses to decide whether it can run the semantic half without triggering a multi-second download on a prompt.
Types ¶
type Doc ¶
Doc is one indexable knowledge page — a wiki page, a journal entry, or an agent knowledge-base child. Path is its absolute location (read live at query time so injected content is never stale); Title is its display heading; Text is the body used for lexical (BM25) and semantic (embedding) matching.
func WalkCorpus ¶
WalkCorpus reads every Markdown file under each directory (recursively) into a Doc, sorted by path for a stable index. A directory that does not exist is skipped (a project may have no journal yet); an unreadable file is skipped rather than failing the whole walk (retrieval is best-effort). Temp files (name ending in .tmp) and empty files are ignored.
type Embedder ¶
type Embedder struct {
// contains filtered or unexported fields
}
Embedder is a reusable feature-extraction pipeline. Building it compiles the model graph — the cold-start cost — so reuse one Embedder across many Embed calls. It is not safe for concurrent use; hold one per goroutine or serialize.
func NewEmbedder ¶
NewEmbedder builds an embedding pipeline from a model directory holding model.onnx + tokenizer.json + config.json (see EnsureModel, which downloads and verifies them). NewGoSession selects the gomlx SimpleGo backend, keeping the whole path pure-Go; the caller must Close the returned Embedder.
func (*Embedder) Close ¶
Close releases the underlying session. Safe to call on a nil-session Embedder.
type Index ¶
type Index struct {
Version int
Docs []Doc
Vecs [][]float32 // parallel to Docs; empty when the corpus is empty
// contains filtered or unexported fields
}
Index is the persisted retrieval index for one corpus: the documents plus one embedding vector per document. BM25 is rebuilt in memory from the documents on first use and cached for the process's lifetime, so only the documents and their vectors are serialized.
The previous note here said the rebuild costs nothing — "tokenizing tens of pages is sub-millisecond". That was measured against a corpus an order of magnitude smaller: this project alone now indexes 350 documents into a 4.1 MB index, and a comment that under-describes a cost by 10x is exactly what stops the next reader from looking.
func Build ¶
Build indexes docs from scratch — see BuildIncremental, which it delegates to with no prior index.
func BuildIncremental ¶
BuildIncremental indexes docs, producing one vector per document (see embedDoc for how a long document is chunked and pooled), reusing the embedding of any document whose path and text are unchanged from old. That reuse is what makes re-indexing cheap: a drain that touched one page re-embeds only that page (seconds) instead of the whole corpus (minutes). It is best-effort — a document that can't be embedded gets a nil vector and stays lexically searchable. A nil embedder builds a lexical-only index (no vectors) so retrieval works before the model has downloaded, degrading to BM25. This is the cold path — run at drain time, not per query.
func Load ¶
Load reads an index from path. A missing, corrupt, or wrong-version file returns (nil, nil) — "no usable index", since the index is a rebuildable cache and the caller (fail-open) simply skips injection until the next rebuild.
func (*Index) LexicalHits ¶
LexicalHits reports how many documents the lexical arm ranks for a prompt — the signal a caller needs to decide whether a query can reach this corpus at all. Zero means BM25 shares no informative term with any page, which is the permanent state of a query written in a language the corpus is not in.
Exposed rather than inferred from Query's output because the two answer different questions: Query can return results from the semantic arm alone while the lexical arm is empty — which is exactly the non-English case, where retrieval looks alive and is running on one leg.
func (*Index) Query ¶
func (ix *Index) Query(ctx context.Context, prompt string, e *Embedder, k int, minSim float64) ([]Result, error)
Query ranks the corpus against prompt and returns up to k results. minSim is the semantic arm's cosine floor (MinSimDefault unless a caller is measuring); the lexical arm's floor is inherent — BM25 already drops any document sharing no query term. When both arms come back empty the result is empty, which is the point: the retriever must be able to say it has nothing.