Information Retrieval
Kompile surfaces information through multiple retrieval mechanisms that can be used independently or combined.
NOTE
Local RAG only requires local-runtime (Anserini), not kompile-app. Overlaying local-runtime (kompile install local-runtime) bundles kompile-embedding-anserini (io.anserini:anserini SameDiff dense encoders + Lucene), all 18+ document/source loaders, and .kgraph archive search directly into the CLI/MCP harness. Without any server process, rag_search and knowledge_search run hybrid dense semantic + lexical retrieval (LocalProjectRagSearch + LocalEmbeddingRuntime) with automatic .kgraph graph evidence attachment over <project>/data/crawls/, and semantic_memory automatically upgrades from TF-IDF to dense SameDiff embeddings.
You only need kompile-app when you want server-side RAG middleware (query transformers, neural rerankers), shared multi-user vector/graph stores (pgvector, Chroma, Vespa, Neo4j), or HTTP/SSE endpoints across a team.
Local RAG (local-runtime) vs. Distributed RAG (kompile-app)
| Capability | CLI Harness + local-runtime (no server) | kompile-app (distributed / team server) |
|---|---|---|
| Storage & scope | Project-local <project>/data/crawls/ + .kgraph archives | Shared Lucene/Anserini, pgvector, Chroma, Vespa, and Neo4j across users & hosts |
| Hybrid search | Dense SameDiff embeddings (kompile-embedding-anserini / anserini) + lexical scoring + .kgraph evidence (rag_search, knowledge_search) | HybridOptimizedRetriever (dense + BM25) + cross-index fan-out + Graph RAG |
| Query transforms & rerankers | Direct hybrid retrieval + automatic lexical fallback | HyDE, multi-query, step-back, expansion, compression + RM3/BM25_PRF/Rocchio/CROSS_ENCODER rerankers |
| Access surface | kompile chat, kompile chat --web, kompile mcp-stdio, kompile serve | Multi-user web UI (:8081), REST API, SSE MCP, scheduled/clustered crawls (:8082) |
Retrieval mechanisms at a glance
| Mechanism | What it searches | Access |
|---|---|---|
| Dense vector search | Embedded document chunks | API, MCP, CLI |
| BM25 keyword search | Full-text index (Lucene) | API, MCP, CLI |
| Hybrid search | Dense + keyword combined | API, MCP, CLI |
| Graph RAG | Knowledge graph entities + communities | API, MCP, CLI |
| Code search | Parsed source code entities (ANTLR4) | API, MCP, CLI |
| Semantic memory | Agent conversation history (embedded) | MCP, CLI |
| Transcript search | Agent session transcripts (grep-style) | MCP, CLI |
| Fact sheet scoping | Partition queries by fact sheet | All |
| Cypher passthrough | Direct graph database queries | API, CLI |
| Cross-index search | Unified search across all backends | API, MCP |
The RAG pipeline
When you send a chat message, the KompileRagOrchestratorImpl runs:
Query -> Conversation History -> Query Processor -> Embed
-> Retrieve (Semantic + BM25) -> Merge + Dedup
-> Build Context -> LLM Generation -> Update MemoryStep 1: Query processing
DefaultQueryProcessor handles the query before retrieval:
Intent detection (regex-based):
- FOLLOW_UP: references prior conversation
- CLARIFICATION: asks for more detail
- COMPARISON: compares concepts
- SUMMARIZATION: asks for a summary
Reference resolution: Pronoun patterns trigger resolution from conversation history -- "it", "that", "they" are resolved to specific entities from prior turns.
Step 2: Query transformation
Six transformation strategies are available. Set via kompile.query.transformer.type:
| Strategy | What it does |
|---|---|
passthrough (default) | No transformation -- uses the query as-is |
compression | Compresses verbose queries into their essential information need |
expansion | Adds related terms and synonyms to broaden recall |
hyde | Generates a hypothetical answer document, embeds that instead of the query |
multi-query | Decomposes complex questions into 2-4 sub-questions, retrieves on each |
step-back | Generates an abstract generalization of the question, retrieves on both |
Configuration:
kompile.query.transformer.type=hyde
kompile.query.transformer.enabled=true
kompile.query.transformer.maxQueries=3
kompile.query.transformer.includeOriginal=true
kompile.query.transformer.temperature=0.7
kompile.query.transformer.maxTokens=256HyDE (Hypothetical Document Embedding): Instead of embedding the question, an LLM generates a hypothetical answer, and that answer is embedded. This often retrieves better results because the hypothetical answer is more similar to actual documents than the question is.
Multi-query: For complex questions like "Compare X and Y", the transformer generates sub-questions ("What is X?", "What is Y?", "How do X and Y differ?") and retrieves on each independently.
Step-back: For specific questions like "Why did system X fail on Tuesday?", generates a broader question ("What are common failure modes of system X?") and retrieves on both.
Step 3: Retrieval
The HybridOptimizedRetriever combines dense vector search and BM25 keyword search. Embeddings stay as INDArray through the entire hot path for efficiency.
Retrieval options:
| Parameter | Default | Description |
|---|---|---|
semanticK | 5 | Number of results from vector search |
keywordK | 5 | Number of results from keyword search |
similarityThreshold | 0.5 | Minimum cosine similarity to include |
enableKeywordSearch | true | Include BM25 results |
enableSemanticSearch | true | Include vector results |
deduplicateResults | true | Remove duplicate chunks |
metadataFilters | {} | Filter by metadata key-value pairs |
Convenience constructors:
semanticOnly(k, threshold)-- vector search onlykeywordOnly(k)-- BM25 onlyhybrid(semanticK, keywordK, threshold)-- both
Step 4: Reranking
After retrieval, an optional reranking step re-scores results. Reranking is disabled by default (kompile.reranker.enabled=false).
| Reranker type | Description |
|---|---|
RM3 | Relevance feedback with pseudo-relevance |
BM25_PRF | BM25 pseudo-relevance feedback |
ROCCHIO | Rocchio relevance feedback (alpha/beta/gamma weighting) |
AXIOM | Axiomatic reranking |
SCORE_TIES_ADJUSTER | Break score ties using secondary signals |
CROSS_ENCODER | Neural cross-encoder reranking (SameDiff model) |
RRF | Reciprocal Rank Fusion (merge multiple rankings) |
NORMALIZE | Score normalization |
MMR | Maximal Marginal Relevance (diversify results) |
Configuration:
kompile.reranker.enabled=true
kompile.reranker.type=rm3
kompile.reranker.fbDocs=10
kompile.reranker.fbTerms=10
kompile.reranker.originalQueryWeight=0.5Step 5: Freshness scoring
DocumentFreshnessScorer adjusts retrieval scores based on document age:
adjusted = (1 - freshnessWeight) * rawScore + freshnessWeight * freshnessScoreNewer documents get a boost. Configurable freshnessWeight controls how much recency matters.
Step 6: Context assembly
ContextBuilder formats retrieved chunks into LLM context, respecting a token budget. Multi-vector documents (tables with both full_table_content and text summaries) are handled specially.
Step 7: LLM generation
The assembled context is sent to the configured LLM provider (OpenAI, Anthropic, Gemini, or local SameDiff) along with the conversation history and system prompt.
Dense vector search
Anserini/Lucene backend
The primary vector store uses Apache Lucene via Anserini:
| Setting | Default | Description |
|---|---|---|
indexPath | auto | Path to the Lucene index |
similarityFunction | COSINE | COSINE, EUCLIDEAN, or DOT_PRODUCT |
maxDimensions | 4096 | Maximum embedding dimensions |
quantizeInt8 | false | Quantize to 8-bit integers |
HNSW enabled | false | Use HNSW index (vs flat search) |
HNSW M | 16 | HNSW max connections per node |
HNSW efConstruction | 100 | HNSW construction search width |
memoryBufferSizeMb | 512 | In-memory buffer size |
batchCommitInterval | 10 | Commit every N batches |
maxDocumentsBeforeCommit | 5000 | Force commit after N documents |
Other vector store backends
| Backend | Config value | Description |
|---|---|---|
| Anserini | anserini | Default; Lucene-backed with HNSW option |
| pgvector | pgvector | PostgreSQL pgvector extension |
| Chroma | chroma | Chroma vector database |
| Vespa | vespa | Vespa search engine |
Set via kompile.vectorstore.type in JSON config.
Embedding models
Dense encoders (SameDiff, local):
- BGE base-en-v1.5 (768 dimensions)
- Arctic Embed L
Sparse encoders:
- CosDPR-distil
- SPLADE++ (ed, sd)
Cross-encoder rerankers:
- MS MARCO MiniLM L-6-v2
- MS MARCO MiniLM L-12-v2
- STSB TinyBERT L-4
- mMARCO mMiniLMv2 L12
- QNLI DistilRoBERTa
External embeddings:
- OpenAI embeddings API
- PostgresML
- Sentence-transformers (Python subprocess)
BM25 keyword search
Lucene-based full-text search with BM25 scoring. Available as a standalone retrieval mode or combined with vector search in hybrid mode.
The AnseriniDocumentRetriever provides keyword search. BM25 parameters (k1=0.9, b=0.4) are tunable.
Graph RAG
See Knowledge Graphs for the full Graph RAG documentation. Three search modes:
| Mode | What it does |
|---|---|
| LOCAL | Embed query -> find similar graph nodes -> expand neighborhood -> format context |
| GLOBAL | PageRank top-k -> connected components -> community summaries -> overview |
| HYBRID | Weighted combination: vectorWeight * searchScore + (1-vectorWeight) * (1/hopDistance) |
Graph RAG adds entity descriptions, relationship descriptions, and community summaries to the context alongside vector search results.
Contextual RAG
Anthropic-style chunk enrichment. When enabled, each chunk gets an LLM-generated position description that situates it within the source document ("This chunk is from the introduction of a paper about...").
Disabled by default (enabled=false). Config persisted to ~/.kompile/config/contextual-rag-config.json.
Memory deduplication and compaction
memory action=save does not add a second copy of a memory. When the new memory is a near duplicate of an existing one of the same type, or shares its series name (the name without dates and attempt/run numbers) and vocabulary, the save updates that memory: the new content first, then only the paragraphs the old one adds. A save without a description is indexed by its first line of prose.
To collapse duplicates already on disk, run memory action=compact (MCP or chat tool) or /memory compact [global] [apply] in chat. Without apply it only reports the groups. With apply, each group keeps its newest file and gains the paragraphs the older ones add. The older files are deleted after a backup to memory-backups/compaction-<timestamp>/ beside the memory directory. MEMORY.md is repointed at the survivors, and duplicate and dangling entries are dropped. The ambient gardener reports the same groups.
Compaction only finds lexical duplicates. A rule saved twice in different words needs judgment. The agent merges those with memory action=merge names=["a.md","b.md"] content="<the consolidated memory>", optionally with name, description and memoryType. names takes file names or memory names. The members are backed up the same way. The merged memory takes the first member's place in MEMORY.md, so it stays in its curated section.
Memory reaches more than the main chat turn:
- Subagents start with the parent's selected
MEMORY.mdindexes. Native subagents get them in the system prompt. Vendor-CLI subagents from the MCPtask/multi_task/quorum_tasktools get them as a<memory_context>envelope on their first message. Turn this off with-Dkompile.subagent.memory=false. - After compaction, a checkpoint that summarizes the running turn's own prompt restores that turn's reminders and the current
MEMORY.mdindex. Nothing else would deliver them again before the next user message.
Required workflow memories
Saving a Markdown memory makes it searchable; it does not make it a policy rule. Normal chat injects the bounded MEMORY.md indexes, not every linked file. For workflow guidance that must be present before work, ask the agent in chat (or configure it via /enforcer):
"Require
project:release-rules.mdandglobal:build-rules.mdas mandatory workflow memories and set workflow mode toenforced."
Under the hood, the agent persists workflowRequiredMemories and workflowMode to .kompile/enforcer-config.json via enforcer_config. These updates save configuration cleanly without mutating an already-running turn's frozen policy. A bare filename defaults to project scope; paths and unknown scopes are rejected. /judge workflow status lists the configured memories. Use /judge workflow reload after changing the selection; selected file contents are read fresh at the beginning of each turn.
The standard/headless agentic harness loads these files in full before the first model request. Missing, empty, escaping-symlink, or over-budget files fail the turn before work, rather than silently omitting or truncating policy. The complete selected memory block is limited to 32,000 characters, independently of the normal 6,000-character chat memory envelope. Direct subagents inherit the frozen parent snapshot, including read-only planner children.
In enforced mode, the inline LLM enforcer receives selected memory in a distinct workflow-constraint block for tool, streaming, and final-response review. Only applicable workflow guidance is enforceable; historical facts are not new tasks, and current user instructions and explicit enforcer rules take precedence. Advisory mode loads the files without promoting them into judge constraints; workflow off/global off skips loading. Unselected memory remains advisory.
Host loading is deterministic. Semantic compliance review still depends on the configured LLM judge, its availability, and fallback policy; keyword-only mode does not interpret Markdown rules. This setting does not add a memory gate to external provider passthrough or standalone MCP clients. Memory read/search/recall calls remain available during read-only discovery; write/save/delete actions do not.
Semantic memory
The SemanticMemoryEngine embeds and indexes agent conversation turns for later retrieval. This allows agents to recall information from previous sessions.
How it works:
- Primary encoder: BGE base-en-v1.5 (768-dim dense) via SameDiff
- Fallback: TF-IDF bag-of-words cosine similarity
- Watches
~/.kompile/memory/and~/.claude/projects/directories - Refreshes index every 60 seconds
- Encoder loads asynchronously (non-blocking startup)
Lexical-only memory for lightweight CLI/MCP hosts
Dense memory encoding is enabled by default. To prevent SemanticMemoryEngine from starting its background SameDiff/BGE encoder loader, set KOMPILE_MEMORY_DENSE_ENABLED=false in the host environment (including an MCP client's server env), or pass the JVM system property -Dkompile.memory.dense.enabled=false. An explicitly set system property takes precedence over the environment variable. Only false (case-insensitive, with surrounding whitespace ignored) disables it; unset or other values keep it enabled. The setting is captured when the engine is constructed, so restart the host after changing it.
Disabled mode reports tfidf (dense disabled) and retains the initial memory scan, 60-second refresh, turn indexing, and TF-IDF queries without loading encoder classes, native libraries, or weights through this engine. This is independent of MCP tool profiles and --no-daemon; it does not disable other model runtimes, crawl/RAG embeddings, or explicitly requested pipelines.
MCP tool: semantic_memory
| Action | Description |
|---|---|
search | Find relevant memory entries (top_k=5, threshold=0.15) |
stats | Memory index statistics |
index_turn | Index a new conversation turn |
Transcript search
Cross-agent transcript search that works across 11 agent providers: Claude Code, Cline, Cursor, Aider, Codex, Continue, Gemini, Qwen, Pi, OpenCode, and Kompile itself.
MCP tool: transcript_search
| Action | Description |
|---|---|
list | List transcripts, optionally filtered by session_id prefix and/or agent |
read | Read a specific session by exact ID or unique ID prefix |
search | Grep-style content search, or ID-prefix lookup when no pattern is supplied |
recent | Show recent sessions |
Search supports regex/literal matching, case sensitivity, inverted matching, context lines (before/after), agent filter, session ID filter, files_with_matches mode, and result limits.
For list and search, session_id is a literal, case-sensitive begins-with filter, not a regex or substring — supply the prefix directly with no * needed. For read, an exact ID takes precedence; otherwise the prefix must match exactly one saved session (an ambiguous prefix returns candidate IDs so you can give a longer prefix).
In chat, just ask naturally — the agent translates your request into transcript_search calls:
- "List Codex sessions whose ID starts with
abc123(up to 10)." → filters bysession_idprefix +agent=codex. - "Search session
abc123for the literal wordfailure." → runs targeted content search within matching sessions. - "Read the transcript for session
abc123." → fetches the uniquely matching session.
Code search
ANTLR4-based semantic code search that understands source code structure:
Supported languages: Java, Python, C++, Go, Kotlin, Rust, C#, SPlan
Entity types: CLASS, METHOD, FUNCTION, INTERFACE, FILE, IMPORT, FIELD, ENUM, RECORD
# Search code
kompile code-index search "handleRequest"
# Find entities
kompile code-index find --type=CLASS --name="*Service"
# Find usages
kompile code-index usages "MyClass.myMethod"
# Watch for changes
kompile code-index watchCode graph analysis:
# Find callers of a method
kompile code-index callers "processDocument"
# Impact analysis
kompile code-index impact "VectorStore"
# Dependency graph
kompile code-index deps "RagService"
# Component detection
kompile code-index componentsMCP tools: code_search, code_graph, local_code_index
Fact sheet scoping
Fact sheets partition your knowledge base into named topics. When a factSheetId is set on a query, retrieval is scoped to documents associated with that fact sheet.
kompile fact-sheets list
kompile fact-sheets activate <id>All retrieval mechanisms (vector search, Graph RAG, code search) respect the fact sheet scope.
Unified knowledge search
The UnifiedKnowledgeTool MCP tool (knowledge_search) provides a single entry point that fans out across all available backends:
- Parallel
DocumentRetrieverfutures (vector + keyword) - Graph RAG LOCAL search (if graph is available)
- Merge and deduplicate by chunk ID (highest score wins)
- Sort by score
knowledge_status reports which backends are active and their node counts.
Local and managed RAG search
The CLI's rag_search MCP tool has two explicit execution modes:
- Local stdio (default): resolves the nearest
kompile.project.jsonand searches only that directory'sdata/crawlsknowledge bases. It launches the configured localENCODERmodel as a bounded, reusable embedding subprocess, reads artifacts only from<project>/data/models, and never contacts the model-staging server. Chunk vectors are cached besidechunks.jsonland are invalidated by model-artifact and content fingerprints. If the encoder is not materialized, retrieval degrades to lexical matching and reportsretrievalMode=lexical-fallback. - Explicit remote (
--url): callsPOST /api/knowledge/search, whereUnifiedKnowledgeToolfans out across the managed deployment's document retrievers and graph.
Local parameters are query, optional topic, optional folder-local knowledgeBase, and limit (default 20, maximum 50). A local invocation never enumerates or merges sibling project folders.
RAG tool for agents
The RagToolImpl Spring AI tool exposes RAG search to agents. Features:
- Multi-vector support (tables have both
full_table_contentand text summary) - Truncation with
result_id+fetch_resultpattern for large results - Configurable
ragMaxDocsandragMaxContentCharsviaMcpOptimizationConfig
Note embedding
Fact sheet notes are embedded using the same EmbeddingModel as source documents. Embeddings are stored as comma-separated float strings on the Note entity. Embedding happens asynchronously with automatic retry for pending notes.
Summary: choosing a retrieval strategy
| Use case | Recommended approach |
|---|---|
| General document Q&A | Hybrid search (default) |
| Precise keyword lookup | keywordOnly mode |
| Conceptual similarity | semanticOnly mode |
| Relationship questions | Graph RAG LOCAL |
| Big-picture summaries | Graph RAG GLOBAL |
| Complex multi-part questions | Multi-query transformer + hybrid |
| Specific factual questions | Step-back transformer + hybrid |
| Code navigation | Code search + code graph |
| Cross-session context | Semantic memory |
| Finding past conversations | Transcript search |
| Direct graph exploration | Cypher queries |
Related concepts
- Crawl Jobs — how data enters the system and becomes searchable, including source types, pipeline routing, and adaptive batching
- Knowledge Graphs — the graph system that powers Graph RAG, including entity extraction, Bayesian networks, graph algorithms, and community detection
- Fact Sheets — how active fact sheets scope retrieval and inject curated facts into the context
- Agents — how agents access retrieval through MCP tools (
rag_search,knowledge_search,graph_search,code_search,semantic_memory,transcript_search) - Guardrails and Evaluation — input/output filters that wrap the retrieval pipeline, and the evaluation harness that measures retrieval quality
- Configuration —
model-roles-config.jsonfor embedding and reranking models,feature-flags-config.jsonfor toggling retrieval features