Skip to content

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) ​

CapabilityCLI Harness + local-runtime (no server)kompile-app (distributed / team server)
Storage & scopeProject-local <project>/data/crawls/ + .kgraph archivesShared Lucene/Anserini, pgvector, Chroma, Vespa, and Neo4j across users & hosts
Hybrid searchDense 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 & rerankersDirect hybrid retrieval + automatic lexical fallbackHyDE, multi-query, step-back, expansion, compression + RM3/BM25_PRF/Rocchio/CROSS_ENCODER rerankers
Access surfacekompile chat, kompile chat --web, kompile mcp-stdio, kompile serveMulti-user web UI (:8081), REST API, SSE MCP, scheduled/clustered crawls (:8082)

Retrieval mechanisms at a glance ​

MechanismWhat it searchesAccess
Dense vector searchEmbedded document chunksAPI, MCP, CLI
BM25 keyword searchFull-text index (Lucene)API, MCP, CLI
Hybrid searchDense + keyword combinedAPI, MCP, CLI
Graph RAGKnowledge graph entities + communitiesAPI, MCP, CLI
Code searchParsed source code entities (ANTLR4)API, MCP, CLI
Semantic memoryAgent conversation history (embedded)MCP, CLI
Transcript searchAgent session transcripts (grep-style)MCP, CLI
Fact sheet scopingPartition queries by fact sheetAll
Cypher passthroughDirect graph database queriesAPI, CLI
Cross-index searchUnified search across all backendsAPI, 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 Memory

Step 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:

StrategyWhat it does
passthrough (default)No transformation -- uses the query as-is
compressionCompresses verbose queries into their essential information need
expansionAdds related terms and synonyms to broaden recall
hydeGenerates a hypothetical answer document, embeds that instead of the query
multi-queryDecomposes complex questions into 2-4 sub-questions, retrieves on each
step-backGenerates 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=256

HyDE (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:

ParameterDefaultDescription
semanticK5Number of results from vector search
keywordK5Number of results from keyword search
similarityThreshold0.5Minimum cosine similarity to include
enableKeywordSearchtrueInclude BM25 results
enableSemanticSearchtrueInclude vector results
deduplicateResultstrueRemove duplicate chunks
metadataFilters{}Filter by metadata key-value pairs

Convenience constructors:

  • semanticOnly(k, threshold) -- vector search only
  • keywordOnly(k) -- BM25 only
  • hybrid(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 typeDescription
RM3Relevance feedback with pseudo-relevance
BM25_PRFBM25 pseudo-relevance feedback
ROCCHIORocchio relevance feedback (alpha/beta/gamma weighting)
AXIOMAxiomatic reranking
SCORE_TIES_ADJUSTERBreak score ties using secondary signals
CROSS_ENCODERNeural cross-encoder reranking (SameDiff model)
RRFReciprocal Rank Fusion (merge multiple rankings)
NORMALIZEScore normalization
MMRMaximal 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.5

Step 5: Freshness scoring ​

DocumentFreshnessScorer adjusts retrieval scores based on document age:

adjusted = (1 - freshnessWeight) * rawScore + freshnessWeight * freshnessScore

Newer 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.

Anserini/Lucene backend ​

The primary vector store uses Apache Lucene via Anserini:

SettingDefaultDescription
indexPathautoPath to the Lucene index
similarityFunctionCOSINECOSINE, EUCLIDEAN, or DOT_PRODUCT
maxDimensions4096Maximum embedding dimensions
quantizeInt8falseQuantize to 8-bit integers
HNSW enabledfalseUse HNSW index (vs flat search)
HNSW M16HNSW max connections per node
HNSW efConstruction100HNSW construction search width
memoryBufferSizeMb512In-memory buffer size
batchCommitInterval10Commit every N batches
maxDocumentsBeforeCommit5000Force commit after N documents

Other vector store backends ​

BackendConfig valueDescription
AnserinianseriniDefault; Lucene-backed with HNSW option
pgvectorpgvectorPostgreSQL pgvector extension
ChromachromaChroma vector database
VespavespaVespa 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)

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:

ModeWhat it does
LOCALEmbed query -> find similar graph nodes -> expand neighborhood -> format context
GLOBALPageRank top-k -> connected components -> community summaries -> overview
HYBRIDWeighted 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.md indexes. Native subagents get them in the system prompt. Vendor-CLI subagents from the MCP task/multi_task/quorum_task tools 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.md index. 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.md and global:build-rules.md as mandatory workflow memories and set workflow mode to enforced."

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:

  1. Primary encoder: BGE base-en-v1.5 (768-dim dense) via SameDiff
  2. Fallback: TF-IDF bag-of-words cosine similarity
  3. Watches ~/.kompile/memory/ and ~/.claude/projects/ directories
  4. Refreshes index every 60 seconds
  5. 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

ActionDescription
searchFind relevant memory entries (top_k=5, threshold=0.15)
statsMemory index statistics
index_turnIndex a new conversation turn

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

ActionDescription
listList transcripts, optionally filtered by session_id prefix and/or agent
readRead a specific session by exact ID or unique ID prefix
searchGrep-style content search, or ID-prefix lookup when no pattern is supplied
recentShow 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 by session_id prefix + agent=codex.
  • "Search session abc123 for the literal word failure." → runs targeted content search within matching sessions.
  • "Read the transcript for session abc123." → fetches the uniquely matching session.

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

bash
# 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 watch

Code graph analysis:

bash
# 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 components

MCP 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.

bash
kompile fact-sheets list
kompile fact-sheets activate <id>

All retrieval mechanisms (vector search, Graph RAG, code search) respect the fact sheet scope.

The UnifiedKnowledgeTool MCP tool (knowledge_search) provides a single entry point that fans out across all available backends:

  1. Parallel DocumentRetriever futures (vector + keyword)
  2. Graph RAG LOCAL search (if graph is available)
  3. Merge and deduplicate by chunk ID (highest score wins)
  4. Sort by score

knowledge_status reports which backends are active and their node counts.

The CLI's rag_search MCP tool has two explicit execution modes:

  • Local stdio (default): resolves the nearest kompile.project.json and searches only that directory's data/crawls knowledge bases. It launches the configured local ENCODER model as a bounded, reusable embedding subprocess, reads artifacts only from <project>/data/models, and never contacts the model-staging server. Chunk vectors are cached beside chunks.jsonl and are invalidated by model-artifact and content fingerprints. If the encoder is not materialized, retrieval degrades to lexical matching and reports retrievalMode=lexical-fallback.
  • Explicit remote (--url): calls POST /api/knowledge/search, where UnifiedKnowledgeTool fans 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_content and text summary)
  • Truncation with result_id + fetch_result pattern for large results
  • Configurable ragMaxDocs and ragMaxContentChars via McpOptimizationConfig

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 caseRecommended approach
General document Q&AHybrid search (default)
Precise keyword lookupkeywordOnly mode
Conceptual similaritysemanticOnly mode
Relationship questionsGraph RAG LOCAL
Big-picture summariesGraph RAG GLOBAL
Complex multi-part questionsMulti-query transformer + hybrid
Specific factual questionsStep-back transformer + hybrid
Code navigationCode search + code graph
Cross-session contextSemantic memory
Finding past conversationsTranscript search
Direct graph explorationCypher queries

Released under the Apache-2.0 License.