Repository avatar
AI Tools
v1.3.1
active

locus

io.github.jmiaie/locus

Vectorless RAG over markdown: BM25, temporal knowledge graph and link walking, with provenance.

Documentation

Locus

Retrieval your agent can explain: BM25 and a temporal knowledge graph over your own files, served over MCP. No LLM, GPU, vector database, or runtime dependencies.

PyPI Python versions License: MIT CI Version Zero Dependencies 48 MCP Tools

Quick start  ·  Benchmarks  ·  When to use Locus vs OMPA  ·  Architecture  ·  MCP tools  ·  CLI


Quick start

Thirty seconds, Python 3.11+, nothing else to install. The corpus is three notes on purpose: with one note, BM25 IDF collapses and the CLI prints score=0.0000 even though the note is the hit.

pip install locus-rag     # macOS / Linux: python3 -m pip install locus-rag · Windows: py -3 -m pip install locus-rag

mkdir notes
printf '# Auth\n\nJWT tokens are validated on every request by the gateway.\n' > notes/auth.md
printf '# Billing\n\nInvoices are sent on the first of the month.\n' > notes/billing.md
printf '# Deploy\n\nProduction deploys require a green CI run.\n' > notes/deploy.md
locus index ./notes
locus retrieve "how are JWT tokens validated?"

Those two commands print:

{
  "files": 3,
  "chunks": 3,
  "triples": 0
}

[1] auth.md  score=1.4692  via=bm25
------------------------------------------------------------
Auth

JWT tokens are validated on every request by the gateway.

The check is auth.md and via=bm25. 1.4692 is FTS5's score for this three-note corpus (SQLite 3.45).

Python:

from locus import LocusEngine

engine = LocusEngine(store_path=".locus")
engine.index("./notes")
chunks = engine.retrieve("JWT authentication flow", limit=5)
for chunk in chunks:
    print(f"{chunk.doc_path}  via={chunk.provenance}")
print(engine.explain(chunks[0].chunk_id, query="JWT")["narrative"])

MCP (Claude Desktop, Claude Code, Cursor, Windsurf):

claude mcp add locus -- locus mcp --store /path/to/.locus

Same server: python3 -m locus.mcp.server --store /path/to/.locus (Windows: py -3 -m locus.mcp.server --store C:\path\to\.locus). Tool calls use the --store you configured; a call can still pass store_path.

All 48 MCP tools and the four prompts: docs/tools.md. CLI: CLI reference. A no-dependency walkthrough in a checkout of this repo: pip install -e . then python examples/mcp_sales_demo.py (--keep leaves the temp store).

Why Locus

Most agent-memory libraries call an LLM to extract facts before anything can be searched. Locus indexes the text itself. Results say why they came back (via=bm25, matched terms, linked entities). The default path is local and deterministic.

Sibling library: OMPA is the vault an agent writes memory into. Use Locus for document retrieval; use OMPA for persistent session memory. When to use which.

Benchmarks

On the full LongMemEval-S set (470 questions) Locus reaches R@5 0.977 and MRR@10 0.911 at 2.3 ms per query, with 0 LLM calls. An opt-in dense re-rank plus date-aware ranking lifts MRR to 0.937. Method and caveats: Benchmark Results and benchmarks/README.md.

On a 30-question stratified subset, run in one harness against default open-source libraries (not hosted vendor services; low power):

SystemMRR@10
OMPA0.967
Letta archival API0.957
Locus0.917
Letta agent0.800
mem00.722
LangMem0.606
Graphiti, cosine floor removed / default search0.547 / 0.428

In that run Locus made 0 LLM calls. mem0 made 49 calls per question, LangMem 53 and Graphiti 218 (gpt-4o-mini, upper bounds from gateway logs, including pilot runs). Per-question rows: benchmarks/published/2026-10-24-headtohead/.


Architecture

Locus architecture: agent → interfaces (MCP, CLI, Python, HTTP) → BM25 stage 1 → optional re-rank → results with provenance; SQLite memory layer with temporal KG.

Locus is three layers — memory, retrieval, and interface — with no layer depending upward:

┌─────────────────────────────────────────────────────────────────┐
│  Interface Layer                                                  │
│  ┌────────────────┐  ┌──────────────────┐  ┌─────────────────┐  │
│  │  CLI (locus)   │  │  MCP stdio server│  │  HTTP JSON-RPC  │  │
│  │  42 commands   │  │  48 tools        │  │  POST /rpc      │  │
│  │                │  │  4 prompts       │  │  Bearer token   │  │
│  │                │  │  resources       │  │  CORS opt-in    │  │
│  └────────────────┘  └──────────────────┘  └─────────────────┘  │
├─────────────────────────────────────────────────────────────────┤
│  Retrieval Layer                                                  │
│  BM25Retriever  ·  KGRetriever  ·  LinkWalker                    │
│  StructuralRetriever  ·  RecencyRetriever  ·  LinkPopularity     │
│  ──────────────────────────────────────────────────────────────  │
│  RRF Fusion  ·  QueryClassifier  ·  ContextBulletin              │
│  TokenBudget  ·  LocusCluster (multi-node)                       │
├─────────────────────────────────────────────────────────────────┤
│  Memory Layer                                                     │
│  Corpus         SQLite FTS5 BM25 index, checksum dedup, SQLite   │
│  TemporalKG     Triples + validity windows, traversal, match     │
│  EntityResolver Alias table → canonical entity names            │
│  Chunker        Section-aware (heading boundaries) + word-count  │
└─────────────────────────────────────────────────────────────────┘

All storage is SQLite — no external databases, no servers, no configuration.


Retrieval Pipeline

Locus retrieves in two stages. Stage 1 is always BM25 over a SQLite FTS5 inverted index (stdlib sqlite3, no extra packages). Stage 2 is an optional re-rank of the BM25 candidates with five graph/metadata signals, fused with weighted Reciprocal Rank Fusion.

  Query ──► Stage 1: BM25 (SQLite FTS5)  ──► top-k chunks          mode="bm25"  (default)
                     │
                     └─► candidate pool (rerank_depth=100)
                           ├─ KG            entity expansion + one hop (honours as_of)
                           ├─ Link Walk     wikilinks from the top BM25 hits
                           ├─ Structural    frontmatter date / tag / type
                           ├─ Recency       frontmatter date, newest first
                           └─ Link Popularity  inbound wikilinks
                         weighted RRF (intent-aware, rerank_alpha=0.1) ─► top-k   mode="hybrid"

Why BM25 is the default: on the public BEIR SciFact and NFCorpus test sets the hybrid re-rank did not beat plain BM25 (paired bootstrap, see Benchmark Results), and every larger re-rank weight we tried on the dev splits made nDCG@10 worse. The re-rank stays available for link- and frontmatter-rich vaults: engine.retrieve(q, mode="hybrid"), LocusEngine(retrieval_mode="hybrid"), LOCUS_RETRIEVAL_MODE=hybrid, locus retrieve --mode hybrid, or mode on the locus_retrieve MCP tool. Passing as_of selects hybrid, since the temporal filter acts on KG facts.

Analyzer (how text becomes index terms). The default is porter+english. It lower-cases text, drops the Locus stop-words plus a larger English function-word list, and applies Porter stemming with a pure-stdlib stemmer (locus/memory/stemmer.py). On every Porter-stemmable word in the BEIR corpora it gives the same output as SQLite FTS5's porter tokenizer, apart from one degenerate word. The other analyzers are porter (stemming only) and plain (the pre-2026-10-21 behaviour: no stemming, small stop-word list).

How the analyzer is chosen:

  • Set it with LocusEngine(analyzer=...), LOCUS_ANALYZER=... or locus reindex --analyzer ....
  • A store remembers its analyzer.
  • Asking for a different one re-indexes from the stored chunks; source files are not re-read.
  • Stores created before analyzers existed are re-indexed with the default on first open.

Index-term APIs follow the analyzer:

  • top_terms() and inspect_doc() report stems.
  • get_posting_list("running") is the same as get_posting_list("run").

Use analyzer="plain" to keep exact-token behaviour.

Stage-2 signalWeight (× rerank_alpha)What it captures
KG Entityintent-weightedEntities from the query linked to documents
Link Walkintent-weightedCandidates reachable via wikilinks from the top hits
Structural1.0Frontmatter date ranges, tags, doc types
Recency0.3Newer frontmatter date first
Link Popularity0.2Hub documents cited by many others

Retrieval is read-only: it never writes to the store unless you pass track=True, which records hits in the hot-context bulletin and token budget (the locus_retrieve MCP tool does this by default so locus_hot_context keeps working; pass track: false for a pure read).


Features

Retrieval

  • BM25 on SQLite FTS5 — inverted index, so query cost tracks the matching postings, not the corpus size (100k docs: ~93 ms p50 vs ~19 s before); pure-Python fallback when FTS5 is not compiled in
  • Optional hybrid re-rank — KG, link walk, structural, recency and link popularity over the BM25 candidates, fused via weighted RRF (mode="hybrid")
  • Incremental indexing — changed files replace their chunks, postings and auto-extracted KG triples in place; forget removes them; add_fact facts are never touched
  • Deterministic, read-only retrieval — ties broken by index order; nothing is written unless track=True
  • Section-aware chunking
    • Splits at # heading boundaries; long sections fall back to word windows (400 words, 50 overlap).
    • Opt-in options (stored with the index):
      • chunk_words / overlap_words set the window size and overlap.
      • heading_context prefixes every window with its heading path (Spec > 3.1 > Slabs).
      • boundaries="lines" ends windows at line or paragraph breaks.
    • See Chunking, parent-child and RM3.
  • Parent-child retrieval (retrieve(..., parent="section"|"doc")) — matches small chunks, then returns the enclosing section or document. Each result's spans cite the matched passages by character offset. Opt-in.
  • RM3 query expansion (retrieve(..., expansion="rm3")) — LLM-free pseudo-relevance feedback. Opt-in.
    • NFCorpus: +0.014 nDCG@10 (significant).
    • Neutral elsewhere.
    • About 5–10× BM25 latency.
  • Cross-encoder reranking (optional locus[rerank] extra) — reranks the BM25 top-k with a local MiniLM cross-encoder. NFCorpus +0.018 (significant); about 400 ms/query on CPU. Opt-in.
  • Symlink-safe indexing — directory indexing skips symlinks by default, so it never reads outside the indexed tree. Opt in with follow_symlinks="inside" or True (equivalently --follow-symlinks inside|all, or LOCUS_FOLLOW_SYMLINKS).
  • Temporal retrieval — as_of="2024-01-01" returns only facts valid on that date
  • Query intent routing (hybrid) — auto-classifies kg_first / bm25_first / balanced and shifts re-rank weights
  • Checksum dedup — unchanged files never re-indexed; safe to run index on every startup
  • Metadata filters — restrict results by path glob, frontmatter type, tags (all/any), date range, point-in-time as_of (honours supersedes) and any frontmatter field (eq ne in nin gt gte lt lte contains exists). Available in the API (retrieve(..., filters={...})), the CLI (--path --type --tag --date-from --in-force --meta) and the locus_retrieve MCP tool (filters). Filters never change scores, and the candidate pool deepens until limit matches are found. See Metadata filters.
  • Optional LLM query rewriting — rewrite, multi (RRF merge) and HyDE through any OpenAI-compatible endpoint (locus.llm, locus retrieve --llm multi). Off by default and never imported by the core. With gpt-4o-mini, HyDE reaches NFCorpus nDCG@10 0.359 (+0.030, significant); none of the three is significant on SciFact. Costs about 0.8–2 s and $0.02–0.08 per 1,000 queries. See LLM query transformations.
  • Opt-in structure retrieval — contextual BM25 (a title / heading-path / date line indexed with each chunk), heading-tree constrained BM25, and a bounded retrieve-then-read loop (locus_retrieve_read). All off unless you ask. They do not change the default LongMemEval numbers above. Measured on the bundled harness, a look-alike-section set, a small identifier hop, and BRIGHT pony: Structure-aware retrieval.

Knowledge Graph

  • Prose triple extraction — 14 relation patterns (leads, works_at, is_a, part_of, replaced, depends_on...) auto-run during indexing — no annotation required
  • Entity resolution — alias table maps name variants to canonical entities transparently
  • Contradiction detection — surfaces same-predicate triples with different objects and overlapping validity windows
  • BFS traversal — kg.traverse("Alice", max_depth=2) returns the full entity subgraph
  • Pattern matching — kg.match("*", "works_at", "Acme") finds everyone at Acme; * is a wildcard
  • KG export — GraphML (Gephi/Cytoscape), JSONL (scripting), DOT (Graphviz)

Explainability

engine.explain(chunk_id, query="authentication")
# {
#   "bm25_matched_terms": ["jwt", "authentication"],
#   "kg_matched_entities": ["Alice"],
#   "structural_matches": ["date 2025-02-10 in range Q1 2025"],
#   "kg_context": [{"entity": "Alice", "fact_count": 3, "sample_fact": "Alice --leads--> Auth team"}],
#   "narrative": "Chunk from 'auth.md'. Retrieved because: BM25: terms [jwt,
#                 authentication]; KG: Alice links to document..."
# }

This is structurally impossible with vector search. No cosine score has a "why."

MCP Integration

  • 48 tools spanning retrieval, KG operations, reasoning, bulletin management, cluster, evaluation, export, snapshots, annotations and relevance feedback
  • MCP Resources — all indexed documents browsable as locus://doc/{path}
  • 4 MCP Prompts — live-context templates pre-filled with retrieved knowledge before sending to the model
  • HTTP transport — locus serve binds 127.0.0.1 by default; any other host requires --token <secret>. No CORS headers unless you pass --cors-origin <origin>

Memory Management

  • Tiered bulletin board (Tier 0 Pinned / Tier 1 Hot / Tier 2 Archive) with hit-boost + age-decay scoring
  • Persistent hot tier — bulletin.sqlite3 survives process restarts
  • Soft token budget — WARNING / TREND / CRITICAL alerts; never blocks retrieval
  • File watcher — locus watch ./docs auto-reindexes changes; deletions detected

Operations

  • Health diagnostics — locus doctor checks corpus, KG, bulletin, store size, version
  • Multi-node cluster — cross-corpus RRF fusion with node-prefixed provenance (jarv:bm25)
  • OMPA bridge — imports OMPA vaults (markdown + KG triples; OMPA's source_file maps to Locus source)
  • Evaluation — locus benchmark qa.json measures Recall@K and MRR

Metadata filters

engine.retrieve("slab concrete strength", filters={
    "path": ["specs/*", "rfis/*"],          # glob(s) on the document path (any)
    "exclude_path": "*/archive/*",
    "type": "spec",                          # frontmatter `type` (any of; case-insensitive)
    "tags": ["concrete"], "tags_any": ["mri", "vibration"],
    "date_from": "2026-01-01", "date_to": "2026-06-30",   # frontmatter `date`, inclusive
    "as_of": "2026-02-15",                   # in force on that date: effective/date <= it, not superseded
    "meta": {"status": "Closed", "revision": {"gte": 1}, "spec_section": {"in": ["03 30 00"]}},
})
locus retrieve "slab concrete" --type spec --in-force 2026-02-15 --meta "spec_section=03 30 00"
locus retrieve "roof" --filters '{"path": "change-orders/*", "meta": {"status": {"ne": "Void"}}}'

How filters behave:

  • They act on the source document's path and frontmatter.
  • Tags may be a, b, [a, b] or #a #b. They are split on commas and whitespace.
  • Dates compare as ISO strings.
  • A document that is missing a field the filter needs does not match.

Invalid keys, operators or dates raise ValueError. MCP returns that as an error.

Chunking, parent-child retrieval and RM3 (opt-in)

engine = LocusEngine(".locus", chunking={"chunk_words": 200, "overlap_words": 0,
                                         "heading_context": True, "boundaries": "lines"})
engine.index("docs/")            # chunking is stored with the index; changing it re-chunks on the next index()
hits = engine.retrieve("slab strength", parent="section")   # enclosing sections, best chunk's score
hits[0].spans   # [{"chunk_id": ..., "start": 120, "end": 410, "score": 8.1}, ...] offsets into hits[0].content
engine.retrieve("statin muscle pain", expansion="rm3", rm3={"fb_docs": 10, "fb_terms": 20, "orig_weight": 0.9})
locus index docs/ --chunk-words 200 --overlap-words 0 --heading-context --boundaries lines
locus retrieve "slab strength" --parent section --expand rm3 --raw

All three are measured against the current default in docs/COMPARISON.md. Settings were tuned on dev splits only. None was significantly better without a large latency cost, so all three stay opt-in:

  • Chunking options: no significant change on the BEIR test splits. On LongMemEval R@5 they are slightly worse (not significant).
  • Parent-child retrieval: worth using for what it returns: a full section with cited spans instead of a fragment. With 100-word children it is significantly worse on LongMemEval R@5 (−0.017).
  • RM3: significantly better on NFCorpus (+0.0136 nDCG@10) and neutral on SciFact, LongMemEval and the construction demo. It costs 5–10× BM25 latency, roughly 10–20 ms instead of 2–3 ms.

Cross-encoder reranking (optional extra)

pip install "locus-rag[rerank]" # sentence-transformers + PyTorch; the Locus core stays dependency-free
locus retrieve "statin muscle pain" --rerank --rerank-depth 20
from locus.rerank import CrossEncoderReranker
engine = LocusEngine(".locus", reranker=CrossEncoderReranker(depth=20))   # cross-encoder/ms-marco-MiniLM-L-6-v2, CPU
engine.retrieve("statin muscle pain")                 # BM25 top-20 reranked
engine.retrieve("statin muscle pain", rerank=False)   # plain BM25

Measured result (depth 20 tuned on dev; CPU with 2 threads):

  • Quality: NFCorpus +0.0179 nDCG@10 (significant). SciFact, LongMemEval R@5 and the construction demo are not significantly changed.
  • Cost: about 400 ms per query instead of 2–3 ms, and about 750 MB RSS.

It is opt-in. Use it where a few hundred milliseconds is acceptable, or on a GPU.

The model is downloaded from the Hugging Face Hub on first use; after that, set HF_HUB_OFFLINE=1. Hub telemetry is disabled by default.

Dense re-rank and date-aware ranking (optional, off by default)

pip install "locus-rag[dense]"   # sentence-transformers + PyTorch; only needed for DenseReranker
from locus.dense import DenseReranker
engine = LocusEngine(".locus", reranker=DenseReranker())          # all-MiniLM-L6-v2, CPU, fused with BM25 by RRF
engine.retrieve("can you suggest a hotel for my trip?")             # BM25 + dense
engine.retrieve("can you suggest a hotel for my trip?", rerank=False)  # plain BM25

# Date-aware ranking (stdlib only): documents whose frontmatter `date` falls in the window a query refers to
# ("3 weeks ago", "last Tuesday", "yesterday", "last weekend", "last week", "last month") are boosted.
engine.retrieve("what did I buy two weeks ago?", temporal=True, reference_date="2023-05-30")
LocusEngine(".locus", temporal=True)                                # or make it the engine default
  • Dense re-rank: each candidate document from the BM25 pool (300 chunks) is scored by the best cosine between the query and ~200-word windows of the document. That ranking is fused with the BM25 document ranking by RRF (k=60). Window embeddings are cached per document.
  • DenseReranker(route="advice") fuses only for advice/recommendation-style queries (recommend, suggest, tips, ideas, advice). This option was tuned post hoc on LongMemEval: the rule was written after seeing per-type results there. It is not validated on other data and is not a default.
  • Date-aware ranking recognises point-in-time references only. Duration ranges ("past few months", "last 3 months") are ignored, and so is any window wider than 45 days. Undated documents are never boosted, queries without a time reference are unaffected, and there is no general recency boost.

Measured on LongMemEval-S (470 questions, session-level, paired bootstrap B=10,000; harness, rows and the earlier prototype numbers are in benchmarks/published/2026-11-12-ranking/):

SettingMRR@10ΔMRR vs BM25 [95% CI]Notable
BM25 (default)0.911—
temporal=True0.912+0.001 [−0.008, +0.010], not significanttemporal-reasoning +0.018 (not significant)
DenseReranker()0.934+0.024 [+0.008, +0.040], significantpreference questions 0.572 → 0.793; R_all@5 +0.028 (significant)
DenseReranker() + temporal=True0.937+0.027 [+0.009, +0.045], significanttemporal-reasoning 0.872 → 0.926 (significant)
DenseReranker(route="advice") (post hoc)0.924+0.013 [+0.006, +0.022], significant12 questions better, 0 worse

The first dense query on a new ~48-session corpus embeds every candidate document: about 12 s on 2 CPU threads. Later queries hit the embedding cache and take about 20–60 ms. Results are from one dataset. See the benchmark README for caveats and how they compare with the prototype.

LLM query transformations (optional)

from locus.llm import OpenAICompatibleClient, llm_retrieve
client = OpenAICompatibleClient.from_env()   # OPENROUTER_API_KEY, or OPENAI_API_KEY (+ OPENAI_BASE_URL)
hits = llm_retrieve(engine, "why is the L2 slab thicker?", strategy="multi", client=client, limit=5)
client.usage   # {'calls': 1, 'prompt_tokens': ..., 'completion_tokens': ...}
StrategyWhat it sends
rewriteOne keyword-style rewrite of the query
multi3 alternative queries
hydeA short hypothetical answer passage, used as the query

The original query is always retrieved too, and the lists are merged with RRF (k=60), so a bad rewrite cannot drop the original hits.

Configuration and safeguards:

  • Calls use temperature 0 and are memoised per client.
  • LOCUS_LLM_MODEL picks the model.
  • LOCUS_LLM_MAX_TOKENS_TOTAL caps the total tokens per client.
  • Works with any OpenAI-compatible server, including local ones (vLLM, llama.cpp, Ollama).
  • The core never imports locus.llm and makes no network calls.

Measured 2026-10-23 with openai/gpt-4o-mini via OpenRouter, temperature 0, all BEIR test queries (SciFact n=300, NFCorpus n=323), paired bootstrap B=10,000. Full table and the exact LLM outputs (so the run reproduces without an API key) are in benchmarks/published/2026-10-23-llm/.

StrategySciFact nDCG@10 (Δ)NFCorpus nDCG@10 (Δ)Added p50 latency$ / 1k queries
default (no LLM)0.6810.329–0
rewrite0.689 (+0.008, ns)0.347 (+0.018, sig.)~0.85 s$0.015–0.019
multi (3)0.684 (+0.003, ns)0.350 (+0.021, sig.)~1.1–1.4 s$0.032–0.048
hyde0.689 (+0.008, ns)0.359 (+0.030, sig.)~1.9–2.1 s$0.072–0.076

The transforms help on short, vocabulary-mismatched queries (NFCorpus) and are neutral on long, precise claims (SciFact). LongMemEval results for the transforms are not measured yet. Numbers depend on the model; re-measure with yours.


MCP Tools

The full list of all 48 MCP tools, and the four prompts, is in docs/tools.md.


CLI Reference

locus [--store PATH] COMMAND [args]
CommandDescription
index <path>Index files; --pattern **/*.md; chunking --chunk-words --overlap-words --heading-context --boundaries words|lines; --follow-symlinks no|inside|all (default no)
retrieve <query>Retrieve; --limit 5 --mode bm25|hybrid --as-of 2024-01-01 --track --raw; filters --path --exclude-path --type --tag --any-tag --date-from --date-to --in-force --meta K=V --filters JSON; --expand rm3; --parent section|doc; --llm rewrite|multi|hyde (optional, network)
explain <chunk_id>Explain retrieval; --query "..."
statusCorpus + KG + bulletin + budget stats
session-startWarm context open
wrap-upSession close + bulletin tick
add-fact S P OAdd KG triple; --valid-from --valid-to --source
query-entity <name>KG entity facts; --as-of
add-alias A BRegister alias A → canonical B
contradictions [entity]Find conflicting KG triples
kg-traverse <start>BFS traversal; --depth 2 --direction out
kg-matchPattern match; --subject --predicate --obj --as-of
forget <doc_path>Remove document from corpus
sync <path>Full reindex
reindexRebuild the search index from stored chunks; --backend fts5|legacy
watch <path>Auto-reindex on changes; --interval 5
mcpStart MCP stdio server
serveStart HTTP JSON-RPC server; --host 127.0.0.1 --port 7391 --token --cors-origin
ingest-ompa <vault>Import OMPA vault
benchmark <qa.json>Recall@K + MRR; --k 1,3,5
doctorHealth check report
export-kg <path>Export KG; --format graphml|jsonl|dot

Multi-node Cluster

Locus has first-class support for running multiple named nodes — each indexing a different knowledge domain — with cross-node retrieval fused via RRF.

from locus import LocusCluster

cluster = LocusCluster("cluster.json")
cluster.add_node("docs",    "/vaults/docs/.locus")
cluster.add_node("code",    "/vaults/code/.locus")
cluster.add_node("logs",    "/vaults/logs/.locus")

# Query all three simultaneously
chunks = cluster.retrieve("auth system deployment", limit=5)
for c in chunks:
    print(f"{c.provenance}  {c.doc_path}")
    # docs:bm25     auth/jwt.md
    # code:kg       src/auth/middleware.py.md
    # logs:recency  incidents/2025-02-auth-outage.md

Each result is tagged node_name:signal so you always know which knowledge base contributed which chunk. The registry persists across restarts — add a node once, always available.


Companion stack

Locus is the explainable retrieval layer. Pair it with OMPA when the agent also needs a vault it writes. When to use Locus vs OMPA.

LayerProjectRole
Explainable retrievalLocus (locus-rag)Vectorless RAG — BM25 + temporal KG + link walking, zero GPU, MCP-native
Vault memoryOMPA (PyPI)Vault · palace · temporal KG · agent lifecycle hooks
Compliance productCognitionOSPrivate layer for audit, RBAC, retention and PHI redaction on top of Locus + OMPA. Not a public install.

Keep the public locus API stable when changing this package. CognitionOS is not a public pip package, and it has no public repository.

OMPA Bridge

If you already use OMPA as your agent memory layer, Locus can import your vault directly. OMPA's triples table (source_file column) is mapped onto the Locus KG (source). If the table is missing required columns the import raises OMPASchemaError rather than silently importing nothing.

locus ingest-ompa ~/path/to/ompa-vault --store .locus
from locus.bridge.ompa import OMPABridge
bridge = OMPABridge(engine, vault_path="~/ompa-vault")
result = bridge.ingest()
# {"vault": "...", "chunks_indexed": ..., "triples_imported": ..., "kg_source": ".../.palace/knowledge_graph.sqlite3"}

Markdown files are indexed via the normal pipeline. KG triples from .palace/knowledge_graph.sqlite3 are copied row by row after a schema check. Safe to re-run — checksum dedup prevents duplicate indexing.


Health Diagnostics

locus doctor
Locus Doctor
============================================
[PASS]  corpus               47 docs | 203 chunks | avg 4.3 chunks/doc
[PASS]  knowledge_graph      1847 triples | 312 entities | 2 contradictions
[WARN]  bulletin             Tier 0 (pinned) is full — oldest entries will be demoted
[PASS]  entity_resolver      14 aliases registered
[PASS]  store_size           3.21 MB at .locus
[PASS]  version              Locus v1.3.1

Result: 5 pass  1 warn  0 fail

Benchmark Results

Full LongMemEval-S (470 questions)

SystemR@5 [95% CI]R_all@5MRR@10 [95% CI]Query p50Ingest p50 per historyLLM calls
Locus (BM25, default)0.977 [0.962, 0.989]0.8600.911 [0.889, 0.931]2.3 ms0.22 s0
Locus + DenseReranker + temporal=True (opt-in)0.9790.8770.937 [0.919, 0.955]22 ms warm (see note)same index0
OMPA (hybrid BM25 + MiniLM)0.981 [0.968, 0.992]0.8770.933 [0.913, 0.950]26 ms10.1 s0
MRR@10 by LongMemEval-S question type for Locus default, Locus with DenseReranker and temporal ranking, and OMPA.

Session-level retrieval on the 470 non-abstention questions of longmemeval_s_cleaned.json (about 48 sessions per history). R@5: an answer session is in the top 5. R_all@5: every answer session is in the top 5. 95% CIs are percentile paired bootstrap, B=10,000, seed 20261020. Local all-MiniLM-L6-v2 embeddings where used, CPU only, shared 8-vCPU VM, so latencies are indicative. The opt-in dense re-rank embeds every candidate on the first query of a new history (about 12 s on 2 CPU threads); later queries take about 20–60 ms. Results and scripts: 2026-11-12-lme500/ and 2026-11-12-ranking/.

Where Locus is weakest: preference questions ("Can you suggest a hotel for my trip?") share few words with the session where the preference was stated (MRR 0.572; the dense re-rank fixes most of it), and questions that need several sessions at once (R_all@5 0.736 on multi-session).

Cost and speed against LLM-memory libraries

MRR@10 with 95% CIs on the same 30 LongMemEval-S questions: OMPA 0.967, Letta archival API 0.957, Locus 0.917, Letta agent 0.800, mem0 0.722, LangMem 0.606, Graphiti 0.547 / 0.428.

30-question stratified LongMemEval-S subset (low power); open-source libraries with default settings, not the vendors' managed services. Per-question rows and harness: benchmarks/published/2026-10-24-headtohead/.

LLM calls, LLM cost, ingest time and query latency per question on the same 30 LongMemEval-S questions, log scales. Locus and OMPA make 0 LLM calls.

Same 30-question subset and harness as the summary and the chart above. mem0, LangMem and Graphiti call the LLM at ingest; Letta's agent calls it at query time. Cost and call counts come from our gateway logs and include pilot runs, so they are upper bounds.

About vendors' published numbers

mem0 reports 94.4% on LongMemEval and Zep reports 90.2%. Those are end-to-end answer accuracy: a reader LLM answers from the retrieved memories and a judge LLM grades the answer, with each vendor's own models and managed service. The numbers on this page are retrieval recall and ranking with no reader and no judge. They measure different things and cannot be compared directly: high recall is necessary for a correct answer but does not guarantee one. Sources for every vendor number: published_competitors.md.

At a glance

WhatResultData / nSource
Default retrieval quality (BM25 + porter+english)SciFact nDCG@10 0.681, NFCorpus 0.329, LongMemEval-S R@5 0.977BEIR test (300 / 323 q), LME-S (470 q)2026-10-21-analyzer
Search latency at 100k docsp50 93 ms (was 19.0 s BM25-only / 54.6 s six-signal in 1.0.0)synthetic Zipf corpus, 100 q2026-10-20
Index build / store at 100k docs34 s / 419 MB (was 21.7 min / 1,324 MB)same2026-10-20
RM3 expansion (opt-in)NFCorpus +0.0136 (sig.), neutral elsewhere, 5–10× latencyBEIR test, LME-S, demo2026-10-23-ragpack
Cross-encoder rerank (opt-in extra)NFCorpus +0.0179 (sig.), neutral elsewhere, ~400 ms/querysame2026-10-23-ragpack
LLM HyDE (opt-in, gpt-4o-mini)NFCorpus 0.359 (+0.030, sig.); SciFact +0.008 (ns)BEIR test2026-10-23-llm
Construction demo (synthetic, workflow demo)R@5 0.952 (1.000 on point-in-time questions with as-of)24 docs, 21 qexamples/construction
Head-to-head vs mem0 / LangMem (LLM memory, gpt-4o-mini)LME-S session retrieval, same 30 q: Locus R@5 1.000, MRR 0.917; mem0 R@5 0.933, MRR 0.722 (ΔMRR −0.19, sig.); LangMem R@5 0.767, MRR 0.606 (−0.31, sig.). Locus: no LLM, 3 ms/query; mem0/LangMem: ~4 min + 4–6¢ of LLM per 48-session haystack. Zep (Graphiti OSS, n=30): R@5 0.467, MRR 0.428 (−0.49, sig.; ~$0.39 + 7 min LLM per haystack); Letta 0.16.8 (n=30): agent R@5 0.800, MRR 0.800 (−0.12 vs Locus, ns); its direct archival-search API R@5 1.000, MRR 0.957 (+0.04, ns: tied). Graphiti on Gemini gemini-3.5-flash-lite, minimal reasoning (free tier, $0; different LLM, not directly comparable to the gpt-4o-mini rows): R@5 0.167, MRR 0.167 (−0.75 vs Locus, sig.). Separate high-reasoning re-ingest, gemini-3.5-flash-lite, reasoning high; different LLM setting, not directly comparable (scorecard v8; $0; n=30 unique final rows): default R@5 0.500, MRR 0.467, default search empty 1/30 (minimal was 19/30 empty; a nonempty search is not a correct answer); cosine floor removed R@5 0.633, MRR 0.539. MRR vs gpt-4o-mini p=0.7622 (default) and p=0.9324 (floor removed): no significant difference, which is not evidence of equivalence. MRR vs minimal Gemini p=0.0026 and p=0.0054 (significant). Paired bootstrap B=10,000, seed 20261020.LME-S subset, n=30 (low power)2026-10-24-headtohead

"sig." means the 95% paired-bootstrap CI of the difference excludes 0; "ns" means it does not. Latencies are from a shared 8-vCPU VM and are indicative only.

Details

Every number below is reproducible with the scripts in benchmarks/repro/; methodology, data sources and caveats are in benchmarks/README.md. Measured 2026-10-20 on a shared 8-vCPU / 16 GB Linux VM (Python 3.13, SQLite 3.46.1) — treat latencies as indicative. 95% CIs are seeded bootstrap (B = 10,000) over queries.

Public datasets — BEIR test splits, nDCG@10

SystemSciFact (300 q)NFCorpus (323 q)p50 latency (SciFact / NFCorpus)
Locus default (mode="bm25", FTS5, porter+english analyzer) ¹0.681 [0.638, 0.724]0.329 [0.294, 0.364]2.3 ms / 0.8 ms ²
Locus hybrid (mode="hybrid", porter+english) ¹0.678 [0.635, 0.721]0.328 [0.294, 0.363]7.2 ms / 4.1 ms
Locus BM25, plain analyzer (the 2026-10-20 default)0.668 [0.623, 0.713]0.306 [0.272, 0.341]2.7 ms / 1.2 ms
Locus hybrid, plain analyzer0.669 [0.624, 0.714]0.306 [0.272, 0.341]7.7 ms / 4.6 ms
LlamaIndex BM25Retriever (bm25s, stemmer + stop-words, defaults) ¹0.687 [0.644, 0.730]0.323 [0.288, 0.358]0.5 ms / 0.4 ms
rank_bm25 BM25Okapi (Locus plain tokens)0.664 [0.618, 0.709]0.308 [0.274, 0.343]7.2 ms / 1.6 ms
Locus 1.0.0 six-signal pipeline (before)0.581 [0.538, 0.624]0.284 [0.251, 0.318]878 ms / 404 ms

¹ Measured 2026-10-21 (analyzer change; artefacts in benchmarks/published/2026-10-21-analyzer/). ² Interleaved in-process measurement, same session as plain: 1.23× / 1.01× the plain p50 (SciFact / NFCorpus). Other rows' latencies are from separate sessions.

  • Stemming + stop-words (default since 2026-10-21): vs the plain analyzer, +0.0129 [−0.0064, +0.0325] nDCG@10 on SciFact (not significant), +0.0223 [+0.0119, +0.0335] on NFCorpus and +0.0128 [+0.0021, +0.0255] LongMemEval-S R@5 (0.964 → 0.977, n = 470). The NFCorpus and LongMemEval-S gains are significant. The analyzer was chosen on the dev splits only; k1/b stay at FTS5's 1.2/0.75 (see below).
  • vs LlamaIndex BM25 (bm25s): −0.0059 [−0.0159, +0.0043] on SciFact (not significant), +0.0058 [+0.0010, +0.0115] on NFCorpus (significant) and +0.0064 [−0.0064, +0.0213] on LongMemEval-S (not significant). bm25s is still faster per query.
  • vs rank_bm25: +0.0174 [−0.0020, +0.0378] (SciFact), +0.0206 [+0.0104, +0.0317] (NFCorpus), +0.0043 [−0.0064, +0.0170] (LongMemEval-S).
  • Earlier comparison (plain analyzer) — parity with rank_bm25: paired difference +0.0045 [−0.0015, +0.0111] on SciFact and −0.0017 [−0.0043, +0.0009] on NFCorpus — not significant either way.
  • Hybrid vs BM25: +0.0007 [−0.0056, +0.0080] (SciFact) and −0.0001 [−0.0012, +0.0009] (NFCorpus) — no significant gain, so BM25 is the default. The re-rank weight and depth were chosen on the dev splits only (SciFact train, NFCorpus dev); no larger weight helped there.
  • vs Locus 1.0.0: +0.0872 [+0.0636, +0.1111] (SciFact) and +0.0220 [+0.0138, +0.0305] (NFCorpus) nDCG@10 over the old six-signal default; +0.0278 / +0.0124 over the old BM25-only path (both significant).
  • Monte Carlo, 10 random 2,000-doc SciFact sub-corpora: mean nDCG@10 BM25 0.742 · rank_bm25 0.742 · hybrid 0.736 (hybrid lower in 8 of 10 seeds).

Scaling — synthetic corpus (Zipf vocabulary, known-item queries, 100 queries)

DocsIndex buildStore sizeQuery p50 / p95 (default)Before (1.0.0): build · size · p50
1,0000.24 s4.4 MB1.5 ms / 2.2 ms6.0 s · 13 MB · 207 ms
10,0002.5 s43 MB10.5 ms / 16.3 ms85 s · 130 MB · 1.36 s
100,00034 s419 MB93 ms / 137 ms21.7 min · 1,324 MB · 19.0 s

Query cost grows with the size of the matching posting lists: the synthetic queries include very common words, so FTS5 still scores most of the corpus. p95 at 100k is above 100 ms on this machine.

Determinism and the old wiki claims

The 1.0.0 README reported R@5 0.947 / MRR 0.633 for the six-signal pipeline on the bundled Engineering Wiki benchmark. That did not reproduce (0.867 / 0.594 on 62156b5), and simple-100 gave three different answers across five runs. A 2026-10-20 check of five fresh processes with different PYTHONHASHSEED values was deterministic. That check recorded Engineering Wiki default R@5 1.000 / MRR 0.727, hybrid R@5 1.000 / MRR 0.743, and rank_bm25 R@5 1.000 / MRR 0.760. Those wiki scores do not describe current main.

Re-run on 2026-12-01 with python benchmarks/run.py --no-latency (EngineeringWiki, seed 42, 113 queries, Python 3.12.3). Two runs agreed on every quality field:

Benchmark (benchmarks/run.py)SystemR@5MRR
Engineering Wiki (113 queries, synthetic)Locus default (BM25)0.92040.7233
Locus hybrid0.98230.7618

rank_bm25 was not installed, so it was not re-scored. simple-100 was not re-run; the 2026-10-20 figures were R@5 0.600 / MRR 0.274 for Locus default and hybrid, and 0.590 / 0.271 for rank_bm25.

These corpora are generated by Locus's own code and are small, so treat them as smoke tests rather than evidence. The BEIR and LongMemEval-S numbers above are the ones to quote. LongMemEval-S R@5 0.977 / MRR@10 0.911 / 2.3 ms is a different benchmark and was not part of this re-run.

Benchmarking

Create a QA JSON file and run evaluation against your indexed corpus:

[
  {"query": "how does JWT authentication work?",    "expected_docs": ["auth/jwt.md"]},
  {"query": "incident response runbook",            "expected_docs": ["ops/ir.md"]},
  {"query": "Q1 2025 architecture decisions",       "expected_docs": ["adrs/q1-2025.md"]}
]
locus benchmark qa.json --k 1,3,5
Locus Benchmark
========================================
Queries:  20

Recall@1: 0.650  (13/20)
Recall@3: 0.800  (16/20)
Recall@5: 0.850  (17/20)
MRR:      0.723

Misses (top 5):
  [MISS] "incident response process" expected=['ir.md'] got=['deploy.md', ...]

KG Export & Visualization

locus export-kg knowledge.graphml   # Gephi / Cytoscape / yEd
locus export-kg knowledge.dot       # Graphviz → PNG/PDF
locus export-kg knowledge.jsonl     # scripting / grep
# Render a quick PNG with Graphviz
dot -Tpng knowledge.dot -o knowledge.png

Installation

pip install locus-rag          # macOS / Linux: python3 -m pip install locus-rag · Windows: py -3 -m pip install locus-rag

Locus is also described for the MCP registry in server.json (uvx locus-rag mcp --store PATH). Since 1.1.0 the wheel installs both a locus and a locus-rag console script (same CLI). On 1.0.0, which has only locus, use uvx --from locus-rag locus mcp.

Zero runtime dependencies. Locus uses only Python stdlib: sqlite3, re, pathlib, threading, http.server, hashlib, math, json.

Optional extras:

pip install "locus-rag[ompa]"   # OMPA vault bridge
pip install "locus-rag[dev]"    # pytest, coverage
pip install "locus-rag[bench]"  # rank_bm25 baseline for benchmarks
pip install "locus-rag[rerank]" # optional cross-encoder reranker (sentence-transformers + PyTorch)

Requirements: Python 3.11+

On-prem deployment (container or offline bundle)

Nothing in these targets uploads anything. There is no registry push and no PyPI upload.

make offline-bundle      # dist/locus-offline-<ver>.tar.gz: wheel + sdist + install.sh + SHA256SUMS
make image               # builds locus:local from dist/*.whl (docker, or podman with --format docker)
make image-save          # dist/locus-image-<ver>.tar for air-gapped hosts (docker/podman load -i …)
scripts/container-smoke-test.sh locus:local   # 24 checks, no network needed

Offline bundle. Copy the tarball to the target host and run tar xzf locus-offline-*.tar.gz. Then run ./locus-offline-*/install.sh /path/to/venv/bin/python. It checks the checksums and installs with pip --no-index, which works because Locus has no runtime dependencies.

Image. Based on python:3.12-slim, pinned by digest, about 124 MB. It:

  • runs as uid 10001;
  • works with a read-only root filesystem;
  • has a HEALTHCHECK on /health;
  • stops cleanly on SIGTERM.

The index lives in /data (a volume). Mount source documents read-only at /docs.

HTTP binding. HTTP binds 127.0.0.1 inside the container by default, so a published port is unreachable. For local use, use docker exec or MCP stdio (docker run -i --rm -v locus-data:/data locus:local mcp). For remote use:

  • set LOCUS_HTTP_HOST=0.0.0.0;
  • provide the bearer token as a file or secret through LOCUS_HTTP_TOKEN_FILE;
  • publish the port on the host loopback only, and put TLS in front of it.

Locus refuses to bind a non-loopback address without a token. deploy/docker-compose.yml sets all of this up with a Compose secret, read_only, cap_drop: [ALL], no-new-privileges and memory/pid limits.

The smoke test checks the following with --network=none:

  • the non-root user and the healthcheck;
  • indexing and retrieval on a read-only rootfs;
  • MCP stdio;
  • that the loopback-bound port is unreachable from the host;
  • the refusal to start without a token;
  • 401/403 on a missing or wrong token or a foreign Origin;
  • that the token does not appear in logs or config;
  • clean stop;
  • installing the offline bundle.

Construction demo. examples/construction/ has 24 synthetic project documents: specs with revisions, RFIs, submittals, change orders, permits, a lease and OAC minutes. It also has 21 labelled questions (python examples/construction/demo.py). Results are R@5 0.952 overall, and 1.000 on the point-in-time questions when the as-of view is used. They come from a small fictional set; treat them as a workflow demo, not a benchmark.


Use cases

  • Agent memory over your own files. Index a notes vault, a docs folder or a codebase and give Claude Code, Cursor or Claude Desktop a locus_retrieve tool that explains its answers.
  • Regulated and audited work. explain() shows the matched terms and KG facts behind each result, and retrieval is deterministic, so a reviewer can reproduce it. CognitionOS builds audit, RBAC and retention on top.
  • Point-in-time questions. as_of="2024-01-01" returns only facts valid on that date: spec revisions, change orders, leases, org charts. See the synthetic construction demo.
  • On-prem and air-gapped. No model downloads on the default path; a container image and an offline bundle are described under On-prem deployment.
  • Bigger corpora. About 93 ms p50 per query at 100k documents on one node, or a built-in multi-node cluster.

Roadmap

From docs/ROADMAP.md; dates are not commitments.

  • Next: idempotent re-ingest of OMPA vaults; KG invalidation that follows OMPA; vault-relative provenance; a one-page OMPA + Locus bundle quick start.
  • Later: RRF weights tuned on public dev splits; an optional reduced --profile bundle tool set; reading OMPA's KG in place; HTTP hardening for remote use.
  • Measured headroom: questions that need several sessions at once (R_all@5 0.74–0.77 on multi-session and temporal questions) are the largest remaining gap on LongMemEval-S.
  • Not planned: a runtime vector database inside Locus. Dense scoring stays an opt-in extra.

Contributing

See CONTRIBUTING.md. All contributions welcome — bug reports, feature requests, PRs.

git clone https://github.com/jmiaie/locus
cd locus
pip install -e ".[dev]"
pytest tests/ -v

License

MIT — see LICENSE.


Acknowledgements

Locus is architecturally descended from OMPA (Obsidian-MemPalace-Agnostic), which pioneered the three-layer vault → palace → KG design for agent memory. The tiered bulletin board, temporal KG schema, and session lifecycle patterns are direct adaptations. The OMPA bridge enables seamless import of existing OMPA vaults. CognitionOS is a private compliance layer on top of Locus + OMPA (audit, RBAC, retention), not a public install — see Companion stack.

PYPI
locus-rag
Install Command
pip install locus-rag
Runtime: uvx