Persistent Memory: Storage, Injection & Search
Kompile treats memory as a first-class, cross-agent subsystem rather than an ad-hoc scratchpad. Every agent running inside Kompile — whether native Standard Chat, Claude Code, Codex, Antigravity (agy), or OpenCode — shares the same structured memory store, the same pre-turn auto-injection pipeline, and the same search and recall engines.
1. How memory is stored (scopes & layers)
Kompile keeps memory in two plain-text scopes on disk (human-readable, git-friendly, never locked in a proprietary blob):
| Scope | Location | What Belongs Here |
|---|---|---|
| Global | ~/.kompile/memory/ | User-wide preferences, standing rules, tool conventions, and cross-repo knowledge |
| Project | .kompile/memory/ | Repository architecture decisions, test/build workarounds, debugging findings, and project references |
Inside each scope, Kompile's memory tool supports three complementary layers:
- Typed memories (
save,recall,forget,types) — the primary layer. Each memory is an individual Markdown file with YAML frontmatter (name,description,type, optionaltagsandsupersedes) classified into four types:user: user profile, role, and workflow preferencesfeedback: standing rules, corrections, and "never do X / always do Y" guidanceproject: ongoing project state, design decisions, and non-obvious codebase factsreference: pointers to external trackers, dashboards, runbooks, and environments Saving a typed memory automatically updates the scope'sMEMORY.mdindex (and rolls older entries into archive index files when the index grows large).
- Flat Markdown files (
read,write,append,list,search) — raw Markdown notes alongsideMEMORY.mdfor freeform topic files. - Memory knowledge graph (
create_entity,create_relation,add_observation,delete_*,read_graph,search_nodes,open_nodes) — implements the standard MCP memory-graph API againstgraph.jsonlfor structured entity/relation facts.
NOTE
Cross-agent portability: memory action=search searches across project and global Kompile memory plus Claude, Codex, Gemini/AGY, Qwen, and OpenCode project memory directories together (and optionally paired peers via include_peers=true or remote harness sources via include_sources=true). On Antigravity (agy), kompile-brain-guard intentionally blocks direct reads/writes to ~/.gemini/antigravity-cli/brain so all durable knowledge stays unified in Kompile's memory store.
2. Where memory is used: pre-turn <memory_context> auto-injection
You don't have to remember to remind an agent about project conventions on every prompt. Before each user turn — across interactive chat, headless runs, and managed passthrough — ChatMemory.buildMemoryContext(query) builds a bounded <memory_context> envelope and prepends it to the turn in a fixed priority order:
<memory_context>
1. [Relevant incidents — warn-only historical evidence] (IncidentStore — bounded leading block)
2. [Persistent memory] (Global + Project MEMORY.md indexes)
3. [Task-relevant memories] (Top 3 query-matched typed memories)
4. [Previous conversations] (Past transcript hits, if budget allows)
5. [Retrieved documents] (Connected RAG hits, if budget allows)
</memory_context>How budgets & selection prevent context bloat
- Incidents never get buried: Open project incidents from
IncidentStoreare placed first inside their own reserved budget so a longMEMORY.mdcannot push active warnings out of sight. - Smart index selection (
4,000-char index budget): When both global and projectMEMORY.mdexist, global gets a1,500-char share and project gets the remainder. Instead of blindly slicing mid-file, Kompile selects standing rules / mandates first, then newest entries (up to240chars per index line), and points the agent tomemory action=recallfor the rest. - Automatic per-turn task recall: Kompile automatically runs a lightweight query extracted from your current prompt (stripping stop words) and injects up to 3 matching typed memories (
2,400chars total,900chars per body) under[Task-relevant memories]. - Prompt-cache-friendly deduplication (
MemoryContextProjection): Across multi-turn HTTP requests, Kompile strips exact repeated[Persistent memory]blocks from older user turns on the wire — retaining only the newest identical snapshot while preserving retrieved evidence — so long chats don't pay repeatedly for duplicate index headers. - Compaction reload (
NativeCompactionReload): When native CLI agents (agy acp,claude) compact their conversation window, Kompile automatically re-delivers the memory files and skills that session already loaded. - Controlling injection: Pass
--no-memorytokompile chatto disable injection for a session. Subagents inherit memory by default (-Dkompile.subagent.memory=true), while packaged Kompile Spins disable global memory injection by default so personas start cleanly (--memoryopts back in).
3. How memory search & recall work
Kompile provides two complementary search engines depending on whether you need fast ranked keyword/recency recall or vector similarity search.
Engine 1: Ranked SQLite FTS5 + BM25 (memory action=recall & action=search)
MemoryTool maintains a local SQLite FTS5 index (MemorySearchIndex) over each memory directory and blends four signals into a single relevance score (effectiveRecallScore):
effectiveScore = BM25
* (1 / (1 + ageDays / 60)) # 60-day recency decay
* (1.15 if type in {feedback, user} else 1.0) # standing-rule type boost
* (1 + min(0.20, 0.04 * ln(1 + timesRecalled))) # usage boost- Why this ranking works well in practice:
- Standing corrections (
feedback) and user preferences (user) get a 1.15× boost over transient notes. - Smooth 60-day half-life recency decay favors recent architecture decisions without erasing evergreen rules.
- Frequently recalled memories earn up to a +20% usage boost, and ties break newest-modified first.
- Multi-word prompts are guarded against noisy single-common-word FTS5
ORhits.
- Standing corrections (
- Output bounding:
recallreturns5results by default (up to100), capping each body at1,800chars — passfull=truefor up to8,000chars per memory, or filter withmemoryType=feedback|project|user|reference.
Engine 2: Semantic Vector Search (SemanticMemoryEngine & semantic_memory)
For conceptual queries where exact keywords don't match, semantic_memory searches across memory files, indexed conversation turns (action=index_turn), and memory-graph entries:
- With
local-runtime: Uses Kompile's SameDiffbge-base-en-v1.5encoder (768-dimensional dense vectors, cosine similarity, defaulttop_k=5,threshold=0.15). To keep CLI startup instant, the GPU/ND4J dense encoder does not auto-start at boot by default — load it on demand viasemantic_memory action=load_encoder, or opt into startup loading withKOMPILE_MEMORY_DENSE_AUTOSTART=true. - Automatic TF-IDF fallback: On slim
cli-harnessinstalls — or whenKOMPILE_MEMORY_DENSE_ENABLED=false—SemanticMemoryEnginefalls back seamlessly to lock-free TF-IDF cosine similarity with zero native library load.
4. Enforcing memory recall (MemoryResponseMandate)
Even with <memory_context> auto-injection, agents sometimes skip checking deeper memories before making an assumption. Kompile includes a deterministic turn-end memory mandate (MemoryResponseMandate, ON by default — no LLM judge required):
- What it enforces: Before delivering a final response, the agent must complete a successful
memory action=recallfor a topic relevant to the request (a recall returning zero matches counts; callingsavedoes not substitute forrecall). - Two modes:
SMART(default): Automatically skips redundant tool recall when the host already injected matching[Task-relevant memories]for this turn, or on short user continuations ("yes","proceed","lgtm","run tests", etc.).EVERY_TURN: Requires an explicitmemory action=recalltool call on every turn.
- Enforced everywhere: Runs inside Kompile's own agentic loop, emulated passthrough, Claude Code's
Stophook (MemoryResponseHook), OpenCode's guard plugin (KOMPILE_MEMORY_MANDATE_STATE), and Antigravity'skompile-memory-mandate-guardhook. Corrections are bounded (2by default, hard cap4). - Opting out:text(or via MCP:
/enforcer memory offenforcer_config action=set field=memory_before_response value=false).
5. Keeping memory clean: gardening, superseding & pruning
Long-lived repositories accumulate hundreds of memories over months. Kompile prevents stale or contradictory memories from degrading recall in three ways:
- Superseding on save: Pass
supersedes="<old-memory-name>"when saving a new typed memory so updated decisions cleanly replace outdated ones. - Ambient Memory Gardener (
AmbientMemoryGardener/ambient_garden): A background maintenance service (runs every 30 minutes after a 5-minute startup delay, or on demand) that scans the memory directory to:- detect near-duplicate memory files,
- flag stale entries unmodified for 90+ days,
- surface conflicting/contradictory memories,
- verify
MEMORY.mdindex integrity, and - suggest consolidations for review.
- Explicit pruning (
memory action=prune): Identifies stale memories older thanstale_days(default60days) in dry-run mode first, and archives/prunes them only when called withapply=true.
Memory vs File Notes vs Progress Reports
| Mechanism | Scope & Lifetime | Best For |
|---|---|---|
memory (save / recall) | Global or project-wide; durable across sessions | Standing rules, user preferences, architecture decisions, recurring environment facts |
file_note | Pinned to one indexed source file; survives reindex | File-local invariants and traps surfaced automatically by file_context |
progress | Per-transcript ring buffer (newest 50 reports) | Subagent handoffs and milestone reports (/progress-reports) — throwaway, not durable memory |
Next steps
- Why Kompile Is Opinionated — how memory fits alongside the Enforcer, Judge, Subagents, and Auditing
- The Enforcer — configuring
/enforcer memoryand other deterministic guardrails - File Context, Notes & Activity — file-scoped notes (
file_note) vs project memory - Embeddings, Serving & Pipelines — running
bge-base-en-v1.5dense memory embeddings onlocal-runtime