Knowledge & Graph-RAG
mosaic-knowledge is a pure-Rust, dependency-free, environment-pure engine that is
include_str!-vendored into every generated app that declares a vector_dbs. It ingests
text, code, books, and git repositories; builds a knowledge graph; and answers with
grounded, graph-augmented retrieval. Provider calls (embeddings, re-ranking) happen only
at the app's env seams, never inside the crate. See AI in Mosaic for how
this engine fits alongside the assistant, voice, and MCP surfaces.
Design note. The graph re-ranking (Personalized PageRank) and community detection (Louvain modularity) in this engine are deliberately self-contained, deterministic, Rust implementations — Mosaic vendored the algorithms rather than pulling a graph-DB dependency, keeping the engine embeddable in any generated app with zero infra.
Why a knowledge engine, not just a vector store
A pure vector-similarity search answers "what reads like this query" but loses two things
real retrieval needs: structure (which entities relate to which — a function that
calls another, a document that references another) and multi-step reasoning
(following a few relationships, not matching one chunk). mosaic-knowledge keeps a
vector+BM25 retrieval layer for the first and adds a knowledge graph — symbol/file/
book/concept/entity nodes and uses/calls/imports/cites/mentions edges — for the
second, re-ranked by Personalized PageRank when retrieval.graph: true.
Ingestion tiers
| Tier | What it indexes | How |
|---|---|---|
book / pdf | EPUB / DOCX / PDF | Pure-Rust parsing (zip + roxmltree; pdf-extract), chapter markers, OCR seam (MOAIC_OCR_CMD) for scanned pages. |
code | source files + Cargo.toml/package.json/… | A pure-Rust syntactic heuristic (not tree-sitter): call_sites (ident followed by (, minus defs + keyword blocklist) and import_names (use a::b::c, import, from…import); tuned for Rust/Python, other languages degrade to the name( rule. Adds precise calls/imports edges plus coarse token-intersection uses edges. |
docs | markdown / text | Parent–child chunking — the whole section is the parent, paragraph groups are children. |
| git sources | repositories | Cloned through the git CLI (ADR 0013); delta re-indexing via a per-source relpath → sha256 manifest (ADR 0019); latest-changes analysis (K11, ADR 0035). |
Sources are the declared floor, runtime ceiling: declared sources are immutable at runtime; runtime sources and typed entities can be added without a redeploy (ADR 0014), and everything persists to any backend through the OpenDAL seam (ADR 0015) or an embedded LanceDB (ADR 0024).
Retrieval — modes, fusion, and re-ranking
Mosaic exposes two retrieval modes and one graph signal:
| Setting | What it does | When to use |
|---|---|---|
hybrid (default) | BM25 leg + cosine vector leg, reciprocal-rank fusion (wv/(k+rank_v) + wk/(k+rank_k), k=60, default weights 0.7/0.3), then optional MMR diversity selection over a 3× candidate pool. | The default for a reason — works for most queries without a per-request choice. |
naive | Vector-only, or keyword-only when no embedder is configured. | Baseline/debugging, or a corpus with no meaningful structure. |
retrieval.graph: true | After the base ranking, seed Personalized PageRank (damping 0.85, 50 power iterations) from the graph nodes backing the hits and re-score each hit as (1−w)·score + w·ppr_norm with w = graph_weight (default 0.5). No-op on an empty graph / prose-only corpus. | When retrieval returns relevant-but-not-central items and you want graph centrality to pull the important ones up. |
- Communities: single-pass Louvain modularity optimization + Newman modularity, deterministic. (There is no Leiden implementation — see the gaps below.)
- Cross-encoder re-rank seam (K4): a Cohere-compatible
POST /v1/rerankbehindMOAIC_RERANK_*; fail-soft (a missing/failed call keeps the fused order).
Embeddings
- Default: a deterministic local 256-dim embedder (
embed_local_v2) — no network, reproducible. MOAIC_EMBED_ONNX_MODELloads an ONNX sentence model (K7,MOAIC_ONNXRUNTIME_LIB);MOAIC_EMBED_*points at a hosted OpenAI-compatible embedding API.MOAIC_EMBED_LOCAL=1forces the local embedder.
Typed entities & book concepts (the thesis layer)
- Book concepts (P51, ADR 0047). Each chapter's salient terms (frequency ≥ 3, or
capitalized mid-sentence, or a heading) become
conceptnodes withchapter → conceptmentionsedges — giving PPR signal for prose-only corpora. Capped at 25 per chapter. - Typed entities (P52, ADR 0047). A gazetteer maps typed entities to graph nodes.
Entity types are free-form; the recommended taxonomy is
person, location, topic, doctrine, council, book, sermon, institution, event, concept, other. Matching is deterministic: case-insensitive, word-boundary-anchored, longest-form-wins. - Declared floor, runtime ceiling.
vector_dbs[].entitiesis the immutable floor; the runtime registry (add_entity/remove_entity) adds/removes entities live — persisted inside the collection store (JSON or LanceDB), restored at boot, and reflected in the graph without re-indexing.list_gazetteerreports provenance (declaredvsruntime).
The 23 knowledge tools
Every knowledge capability is exposed both as an MCP tool (on POST /mcp, or via the
stdio app server) and as a REST route under /api/vectordb/{kb}/…:
| Tool | Use for |
|---|---|
search_knowledge | Hybrid BM25+vector search — ranked chunks with context, quote, and a stable locator; optional source scoping. |
read_chunk | Read one chunk by id — exact text + locator for citation. |
list_sources | Declared + runtime sources with stable label and file/chunk counts. |
list_knowledge | Documents per kb: doc id + chunk count. |
list_symbols | Code symbols with file+line locators and detected HTTP endpoints (capped 500). |
list_books | The book library (epub/docx/pdf): title, format, chapters, citations. |
cite | Record a citation; optional from → a cites graph edge. |
query_graph | Query/expand the knowledge graph (a node + a depth). |
find_symbol | Resolve a symbol name → stable id (file::name). |
find_callers | Reverse of uses/calls edges for a symbol. |
get_call_graph | Bounded call neighborhood (uses/contains/serves, depth ≤ 5). |
find_similar_implementation | Vector-search code chunks similar to a symbol's chunk — avoid re-inventing existing behavior. |
find_concept | P51 book-concept lookup + the chapters that mention it. |
find_entity | P52 typed-entity lookup + the chapters that mention it. |
list_entities | Typed entities by salience, optional type filter. |
list_gazetteer | The gazetteer with provenance (declared floor + runtime layer). |
add_entity | Runtime gazetteer add (idempotent; no reindex; survives reboot). |
remove_entity | Runtime gazetteer remove (declared entities are immutable). |
make_report | Export a markdown report quoting chunk ids verbatim + a Sources section. |
repo_profile | A one-call re-implementation brief (DSL counts, LOC, deps, symbols, books) — the entry point of the Reimplementation Playbook. |
knowledge_stats | Deterministic stats: entries, per-source files/lines/pages, git facts, endpoints, DSL entity counts. |
recent_changes | Latest-changes of git work-tree sources (K11, ADR 0035). |
reindex_knowledge | Delta re-walk of declared + runtime sources (ADR 0019). |
Typical agent loop (code): ingest the repository once → before acting, call
find_similar_implementation with a natural-language description of the behavior → if a
match exists, find_symbol + get_call_graph to see its dependency footprint → after the
change, reindex_knowledge (delta) so the graph stays current.
Honest gaps vs. a full GraphRAG stack
Compared to a reference GraphRAG implementation (e.g. EE's ee-knowledge/ee-vectordb,
which this page deliberately mirrors), Mosaic is narrower in a few specific, documented
ways:
| Area | Mosaic today | A full stack would add |
|---|---|---|
| Query modes | hybrid, naive only | Local (entity-anchored expand), Global (community-summary), Mix — explicit per-query strategy selection. |
| Community detection | Single-pass Louvain + Newman modularity | Leiden (well-connected communities, refinement phase) for Global-style answers. |
| Code extraction | Pure-Rust syntactic heuristic (name-based calls/imports) | tree-sitter grammars for name-accurate, per-language symbol/edge extraction. |
| PageRank | Query-personalized (seeded from the query's hits) | User-personalized (seeded from a user profile) for per-user personalization. |
| Entity resolution | Deterministic exact/word-boundary matching | Fuzzy/semantic merging of re-extracted mentions across sources. |
| Vector backends | JSON file, embedded LanceDB, OpenDAL (s3/fs/memory) | Dedicated vector-DB services (Qdrant/Weaviate/pgvector) as first-class backends. |
These are the concrete "ideas to adopt" for Mosaic's AI support — tracked as learn-todos
in the repo's sync/ee.md learning ledger (the A-series assistant gaps + the B-series
agent-architecture items: ReAct planner, orchestrator, A2A, generative UI, MCP
tool-grouping, caller attribution, resources/prompts).