Retrieval is where memory architectures succeed or fail in practice. A store full of good facts is useless if the query for them is written in the wrong words, if stale rows outrank fresh ones, or if the top results eat the whole context budget before the decisive fact appears. This skill covers retrieval as a pipeline, from rewriting the question through hybrid search, reranking, and packing results into context. It builds on ../memory-recall/SKILL.md, which covers basic query patterns, and adds the strategies that matter once the store is large or the task is hard.
Quick Workflow
- Rewrite the task question into 2 to 4 keyword queries, including synonyms and the nouns the stored entry would contain.
- Run keyword retrieval and embedding retrieval in parallel, then merge by rank, not by raw score.
- Rerank merged results by confidence, recency, and layer, and drop anything below the task's confidence floor.
- If the top results reference other records, follow one hop and rerank again before packing.
- Pack results into the context budget largest value first, and stop as soon as the budget is full.
- Log which queries hit and which missed, so retrieval improves from real misses instead of guesses.
1. Query expansion and rewriting
One query rarely matches how knowledge was stored. Expand before searching, using synonyms, abbreviations, and related terms from the task itself. The expansion below turns a vague task question into queries that match stored wording, and it keeps the expansion explicit so a bad synonym can be spotted and removed.
"""Query expansion: turn one task question into several store queries."""
EXPANSIONS = {
"login": ["auth", "authentication", "credential"],
"scan": ["sweep", "probe", "enumeration"],
"token": ["session", "bearer", "api key"],
}
def expand_queries(question):
words = question.lower().split()
queries = [" ".join(words)]
for word, synonyms in EXPANSIONS.items():
if word in words:
for synonym in synonyms:
queries.append(" ".join(
synonym if w == word else w for w in words))
return queries
# Example: "staging login token expiry" becomes queries covering
# "staging auth token expiry" and "staging authentication session expiry"
Expansion rules that prevent noise:
- Expand nouns and verbs, never stop words. Expanding "the" or "is" adds nothing but false matches.
- Cap expansion at 5 queries. Beyond that, the merged list is mostly duplicates and the reranker has nothing useful left to rank.
- Keep the original query first. If expansion hurts, the original ranking is still visible in the log for comparison.
2. Hybrid retrieval and rank fusion
Keyword search finds exact terms such as hostnames, error codes, and tool names. Embedding search finds paraphrases and concepts. Neither alone is enough, so run both and merge by reciprocal rank fusion, which rewards records that rank well in both lists without requiring comparable raw scores.
"""Hybrid retrieval with reciprocal rank fusion over two ranked lists."""
def reciprocal_rank_fusion(ranked_lists, k=60):
fused = {}
for results in ranked_lists:
for rank, record_id in enumerate(results, start=1):
fused[record_id] = fused.get(record_id, 0.0) + 1.0 / (k + rank)
return sorted(fused.items(), key=lambda item: item[1], reverse=True)
keyword_hits = ["mem_011", "mem_042", "mem_007", "mem_103"]
embedding_hits = ["mem_042", "mem_011", "mem_210", "mem_007"]
merged = reciprocal_rank_fusion([keyword_hits, embedding_hits])
# mem_042 and mem_011 lead because both retrievers ranked them highly.
When only one retriever is available, which is the normal case for a SQLite-backed store, keyword retrieval plus filters is the honest baseline. Do not claim embedding search exists when it does not. Add embeddings as an optional index over the same records, and keep the keyword path working when the index is absent or stale.
3. Reranking by confidence, recency, and layer
Raw retrieval order is a starting point, not a decision. Rerank with the signals that matter for the task, and make the weights explicit so they can be tuned from measured misses rather than argued about. The reranker below is deliberately simple, because a reranker nobody can explain is a reranker nobody can debug.
"""Transparent reranker: confidence, recency, and layer trust."""
from datetime import datetime, timezone
LAYER_TRUST = {"semantic": 1.0, "procedural": 0.9, "episodic": 0.6}
def rerank(records, now=None, half_life_days=90):
now = now or datetime.now(timezone.utc)
scored = []
for record in records:
age_days = (now - record.created).days
recency = 0.5 ** (age_days / half_life_days)
score = (
0.5 * record.confidence
+ 0.3 * recency
+ 0.2 * LAYER_TRUST.get(record.layer, 0.5)
)
scored.append((score, record))
scored.sort(key=lambda item: item[0], reverse=True)
return scored
# A fresh episodic observation can outrank a stale semantic fact here
# only if its confidence is high, which is exactly the case to inspect.
Set the confidence floor per task, not per store. A report draft can tolerate 0.5 confidence leads flagged as leads. An action that changes a system needs 0.8 or higher, or a fresh direct verification. Log every case where reranking changed the top result, because that log is the evidence for tuning the weights.
4. Multi-hop retrieval and context packing
Some questions cannot be answered from one record. A fact references a host, the host references a scan, and the scan references a finding. Follow references one hop, rerank the combined set, and stop. Two hops usually adds noise faster than value, and each hop multiplies the context cost. Packing then decides what actually reaches the agent, largest value first within a fixed token budget.
"""One-hop follow plus budget-aware packing of retrieved records."""
def one_hop_expand(records, store, limit=10):
seen = {r.id for r in records}
extra = []
for record in records:
for source_id in record.sources:
if source_id not in seen and len(extra) < limit:
extra.append(store.fetch(source_id))
seen.add(source_id)
return records + extra
def pack(records, budget_tokens=4000):
packed, used = [], 0
for score, record in records:
cost = record.token_estimate
if used + cost > budget_tokens:
continue
packed.append(record)
used += cost
return packed, used
Packing rules:
- Never truncate a record mid-sentence to fit the budget. Drop the whole record and note the drop, so the reader knows something was left out.
- Keep the query and the packing decision in the task log. A later audit that cannot reproduce what the agent saw cannot judge whether retrieval or reasoning failed.
- If the budget fills before any semantic record appears, the query is wrong, not the budget. Rewrite and rerun instead of raising the budget.
Edge cases
- Retrieval returns nothing. Try synonyms, drop filters, then check whether the knowledge was ever captured. A retrieval miss caused by a capture gap is fixed by capture, not by better ranking.
- Retrieval returns only stale rows. Shorten the recency half-life for fast-changing facts, and verify the top row live before acting.
- Two retrievers disagree completely. Inspect the overlap. Zero overlap usually means the query terms and the stored terms live in different vocabularies, which expansion should have bridged.
- The same record dominates every query. That record is either genuinely central or over-tagged. Check its tags, and split it if it covers several unrelated topics.
- Retrieval is slow on a large store. Add tag and layer filters to every query first, then consider an index. A slow retriever that agents avoid is worse than a fast narrow one they actually use.
Key references
- CWE-200 (Exposure of Sensitive Information to an Unauthorized Actor): why retrieved content needs the same access controls as the store itself.
- SQLite FTS5 documentation: https://sqlite.org/fts5.html
- Python sqlite3 module: https://docs.python.org/3/library/sqlite3.html
- ../memory-recall/SKILL.md and ../memory-consolidation/SKILL.md in this repo.
