Mosaic one model, many lenses

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

TierWhat it indexesHow
book / pdfEPUB / DOCX / PDFPure-Rust parsing (zip + roxmltree; pdf-extract), chapter markers, OCR seam (MOAIC_OCR_CMD) for scanned pages.
codesource 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.
docsmarkdown / textParent–child chunking — the whole section is the parent, paragraph groups are children.
git sourcesrepositoriesCloned 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:

SettingWhat it doesWhen 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.
naiveVector-only, or keyword-only when no embedder is configured.Baseline/debugging, or a corpus with no meaningful structure.
retrieval.graph: trueAfter 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/rerank behind MOAIC_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_MODEL loads an ONNX sentence model (K7, MOAIC_ONNXRUNTIME_LIB); MOAIC_EMBED_* points at a hosted OpenAI-compatible embedding API.
  • MOAIC_EMBED_LOCAL=1 forces 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 concept nodes with chapter → concept mentions edges — 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[].entities is 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_gazetteer reports provenance (declared vs runtime).

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}/…:

ToolUse for
search_knowledgeHybrid BM25+vector search — ranked chunks with context, quote, and a stable locator; optional source scoping.
read_chunkRead one chunk by id — exact text + locator for citation.
list_sourcesDeclared + runtime sources with stable label and file/chunk counts.
list_knowledgeDocuments per kb: doc id + chunk count.
list_symbolsCode symbols with file+line locators and detected HTTP endpoints (capped 500).
list_booksThe book library (epub/docx/pdf): title, format, chapters, citations.
citeRecord a citation; optional from → a cites graph edge.
query_graphQuery/expand the knowledge graph (a node + a depth).
find_symbolResolve a symbol name → stable id (file::name).
find_callersReverse of uses/calls edges for a symbol.
get_call_graphBounded call neighborhood (uses/contains/serves, depth ≤ 5).
find_similar_implementationVector-search code chunks similar to a symbol's chunk — avoid re-inventing existing behavior.
find_conceptP51 book-concept lookup + the chapters that mention it.
find_entityP52 typed-entity lookup + the chapters that mention it.
list_entitiesTyped entities by salience, optional type filter.
list_gazetteerThe gazetteer with provenance (declared floor + runtime layer).
add_entityRuntime gazetteer add (idempotent; no reindex; survives reboot).
remove_entityRuntime gazetteer remove (declared entities are immutable).
make_reportExport a markdown report quoting chunk ids verbatim + a Sources section.
repo_profileA one-call re-implementation brief (DSL counts, LOC, deps, symbols, books) — the entry point of the Reimplementation Playbook.
knowledge_statsDeterministic stats: entries, per-source files/lines/pages, git facts, endpoints, DSL entity counts.
recent_changesLatest-changes of git work-tree sources (K11, ADR 0035).
reindex_knowledgeDelta 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:

AreaMosaic todayA full stack would add
Query modeshybrid, naive onlyLocal (entity-anchored expand), Global (community-summary), Mix — explicit per-query strategy selection.
Community detectionSingle-pass Louvain + Newman modularityLeiden (well-connected communities, refinement phase) for Global-style answers.
Code extractionPure-Rust syntactic heuristic (name-based calls/imports)tree-sitter grammars for name-accurate, per-language symbol/edge extraction.
PageRankQuery-personalized (seeded from the query's hits)User-personalized (seeded from a user profile) for per-user personalization.
Entity resolutionDeterministic exact/word-boundary matchingFuzzy/semantic merging of re-extracted mentions across sources.
Vector backendsJSON 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).