Skip to content

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

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

  1. Typed memories (save, recall, forget, types) — the primary layer. Each memory is an individual Markdown file with YAML frontmatter (name, description, type, optional tags and supersedes) classified into four types:
    • user: user profile, role, and workflow preferences
    • feedback: standing rules, corrections, and "never do X / always do Y" guidance
    • project: ongoing project state, design decisions, and non-obvious codebase facts
    • reference: pointers to external trackers, dashboards, runbooks, and environments Saving a typed memory automatically updates the scope's MEMORY.md index (and rolls older entries into archive index files when the index grows large).
  2. Flat Markdown files (read, write, append, list, search) — raw Markdown notes alongside MEMORY.md for freeform topic files.
  3. Memory knowledge graph (create_entity, create_relation, add_observation, delete_*, read_graph, search_nodes, open_nodes) — implements the standard MCP memory-graph API against graph.jsonl for 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:

text
<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 IncidentStore are placed first inside their own reserved budget so a long MEMORY.md cannot push active warnings out of sight.
  • Smart index selection (4,000-char index budget): When both global and project MEMORY.md exist, global gets a 1,500-char share and project gets the remainder. Instead of blindly slicing mid-file, Kompile selects standing rules / mandates first, then newest entries (up to 240 chars per index line), and points the agent to memory action=recall for 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,400 chars total, 900 chars 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-memory to kompile chat to 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 (--memory opts 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.

MemoryTool maintains a local SQLite FTS5 index (MemorySearchIndex) over each memory directory and blends four signals into a single relevance score (effectiveRecallScore):

text
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 OR hits.
  • Output bounding: recall returns 5 results by default (up to 100), capping each body at 1,800 chars — pass full=true for up to 8,000 chars per memory, or filter with memoryType=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 SameDiff bge-base-en-v1.5 encoder (768-dimensional dense vectors, cosine similarity, default top_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 via semantic_memory action=load_encoder, or opt into startup loading with KOMPILE_MEMORY_DENSE_AUTOSTART=true.
  • Automatic TF-IDF fallback: On slim cli-harness installs — or when KOMPILE_MEMORY_DENSE_ENABLED=false — SemanticMemoryEngine falls 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=recall for a topic relevant to the request (a recall returning zero matches counts; calling save does not substitute for recall).
  • 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 explicit memory action=recall tool call on every turn.
  • Enforced everywhere: Runs inside Kompile's own agentic loop, emulated passthrough, Claude Code's Stop hook (MemoryResponseHook), OpenCode's guard plugin (KOMPILE_MEMORY_MANDATE_STATE), and Antigravity's kompile-memory-mandate-guard hook. Corrections are bounded (2 by default, hard cap 4).
  • Opting out:
    text
    /enforcer memory off
    (or via MCP: enforcer_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:

  1. Superseding on save: Pass supersedes="<old-memory-name>" when saving a new typed memory so updated decisions cleanly replace outdated ones.
  2. 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.md index integrity, and
    • suggest consolidations for review.
  3. Explicit pruning (memory action=prune): Identifies stale memories older than stale_days (default 60 days) in dry-run mode first, and archives/prunes them only when called with apply=true.

Memory vs File Notes vs Progress Reports ​

MechanismScope & LifetimeBest For
memory (save / recall)Global or project-wide; durable across sessionsStanding rules, user preferences, architecture decisions, recurring environment facts
file_notePinned to one indexed source file; survives reindexFile-local invariants and traps surfaced automatically by file_context
progressPer-transcript ring buffer (newest 50 reports)Subagent handoffs and milestone reports (/progress-reports) — throwaway, not durable memory

Next steps ​

Released under the Apache-2.0 License.