Teach your AI once. It remembers forever. It gets smarter over time.
Agent Brain is a modular memory system for AI agents with continuous learning. It stores facts, catches contradictions, learns your habits, ingests external knowledge, tracks what works, learns from mistakes, and adapts to your tone — all in a local SQLite database with real persistence, full-text search, and pluggable storage backends.
Every AI conversation starts from zero. You repeat yourself. It forgets what you taught it. Agent Brain fixes that with a working persistence layer ( scripts/memory.sh) and six cognitive modules that the agent selectively invokes based on what the task actually needs.
--policy fast|balanced|deep) and optional score explainability ( --explain).superseded_by with a pointer to the replacement, preserving full history.Six modules, one orchestrator, pluggable storage.
text
┌──────────────────────────────┐
│ 🧠 ORCHESTRATOR │
│ Dispatches by task type │
└──────────┬───────────────────┘
│
┌────────────┼────────────────────┐
│ Which modules does this need? │
└────────────┼────────────────────┘
│
┌─────────┬───────┼───────┬──────────┬──────────┐
▼ ▼ ▼ ▼ ▼ ▼
┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐
│ARCHIVE│ │GAUGE │ │INGEST│ │SIGNAL│ │RITUAL│ │ VIBE │
│ 📦 │ │ 📊 │ │ 📥 │ │ ⚡ │ │ 🔄 │ │ 🎭 │
│Store │ │Conf. │ │Learn │ │Check │ │Habits│ │ Tone │
└──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘
└─────────┴───────┴────┬───┴────────┴─────────┘
▼
┌──────────────────┐
│ 💾 memory.db │
│ SQLite (default)│
│ or memory.json │
└──────────────────┘
On EVERY user message, the agent runs this sequence:
Step 1: RETRIEVE — Before doing anything, search memory for context relevant to this message.
Extract 2-4 key topic words from the user's message and search:
bash
./scripts/memory.sh get "<topic words>" --policy balanced
How to pick search terms:
User saysSearch queryWhy"Help me set up the API endpoint""api endpoint setup"Core task nouns"Can you refactor the auth module?""auth refactor code"Task + domain"What port does our server run on?""server port config"Question subject"Fix the TypeScript error in checkout""typescript checkout error"Tech + component"Write tests for the payment flow""payment testing workflow"Domain + action
If results come back, use them silently to inform your response. Never say "I remember..." or "According to my memory..." — just apply the knowledge naturally.
If no results, proceed normally. For deterministic orchestration you can run:
bash
./scripts/memory.sh loop "<full user message>"
Step 2: EXTRACT — Scan the user's message for storable facts, preferences, or procedures.
See the Archive module ( modules/archive/SKILL.md) for signal patterns, categories, and examples. Before storing, always check for conflicts:
bash
./scripts/memory.sh conflicts "<content to store>"
# If NO_CONFLICTS → proceed with add
# If POTENTIAL_CONFLICTS → ask user to clarify, or supersede old entry
./scripts/memory.sh add <type> "<content>" <source> "<tags>"
Extraction is silent — never announce "I'm storing this."
Step 3: RESPOND — Answer the user's request, applying any retrieved context.
Step 4: LEARN — If the user corrects you or confirms something worked, record it:
bash
# User says "that's wrong, it's actually X"
./scripts/memory.sh correct <wrong_id> "<right content>" "<reason>"
# User says "that worked great"
./scripts/memory.sh success <id>
User message: "Can you update the database migration? We use Prisma with PostgreSQL."
Agent thinks:
RETRIEVE: Search for relevant context bash
./scripts/memory.sh get "database migration prisma"
Result: [sure] (fact) Project uses Prisma ORM with PostgreSQL — confirmed, proceed with known setup.
EXTRACT: User revealed tech stack info. Check if already stored:
RESPOND: Help with the migration using Prisma + PostgreSQL knowledge.
LEARN: Nothing to correct or confirm yet.
User message: "Actually we switched to Drizzle last month."
Agent thinks:
RETRIEVE: ./scripts/memory.sh get "database orm drizzle" — no results for Drizzle.
EXTRACT: This is a correction. Find the old entry and correct it: bash
./scripts/memory.sh correct <prisma_entry_id> "Project uses Drizzle ORM with PostgreSQL" "Switched from Prisma to Drizzle"
RESPOND: Acknowledge the switch, adjust advice to use Drizzle.
Not every task needs every module. The orchestrator classifies the task and calls only what's relevant:
Task TypeModules UsedAny message (extract facts)Archive (extract + store) + Signal (check conflicts)Answer a questionGauge (confidence) + Archive (retrieve)User seems frustratedVibe (detect) + Archive (adjust style)Ingest a URLIngest + Archive (store extracted knowledge)Repeated workflowRitual (detect pattern) + Archive (store)Check consistencySignal + ArchiveUser corrects youArchive (correct) + Gauge (update confidence)Record what workedArchive (success)Review memory healthArchive (reflect)
Memory lives in memory/memory.db (SQLite, default) or memory/memory.json (legacy).
All operations go through scripts/memory.sh → scripts/brain.py with a pluggable
storage backend.
text
AGENT_BRAIN_BACKEND=sqlite (default) → memory/memory.db
AGENT_BRAIN_BACKEND=json (legacy) → memory/memory.json
Optional SuperMemory mirror on writes ( add, correct):
text
AGENT_BRAIN_SUPERMEMORY_SYNC=auto (default)
AGENT_BRAIN_SUPERMEMORY_SYNC=on (force sync attempt)
AGENT_BRAIN_SUPERMEMORY_SYNC=off (disable sync)
SUPERMEMORY_API_KEY=... (required for auto/on)
SUPERMEMORY_API_URL=... (optional; default https://api.supermemory.ai/v3/documents)
AGENT_BRAIN_SUPERMEMORY_TIMEOUT=8 (optional timeout seconds)
AGENT_BRAIN_SUPERMEMORY_DEBUG=1 (optional sync warnings to stderr)
By default ( auto), Agent Brain only attempts cloud sync if SUPERMEMORY_API_KEY
is available (directly from environment or loaded from the skill-local env file
set by AGENT_BRAIN_ENV_FILE, default ../.env in scripts/memory.sh), so local
persistence remains the default behavior.
The SQLite backend uses WAL mode for concurrent reads, indexes on type/confidence/tags/memory_class,
and handles 10,000+ entries with sub-100ms latency. Existing memory.json files are
automatically migrated to SQLite on first run (original backed up as memory.json.bak).
No fake numeric scores. Four categories derived from entry metadata:
Results are ranked by a hybrid formula:
code.python)AGENT_BRAIN_REMOTE_EMBEDDINGS=on plus AGENT_BRAIN_EMBEDDING_URL and obey AGENT_BRAIN_REMOTE_EMBEDDING_MAX_ENTRIESRetrieved entries are automatically marked as accessed (no manual touch needed).
The learning loop has three signals:
correct): When you're wrong, track what was wrong, what's right, and why. After 3+ corrections on the same tag, the system detects anti-patterns.success): When a memory is applied successfully, record it. At 3+ successes, confidence auto-upgrades to SURE.similar): The agent can manually check for 3+ similar entries and create pattern entries. Anti-pattern detection after 3+ corrections on the same tag IS automatic.Default: memory/memory.db (SQLite). Legacy: memory/memory.json.
FieldTypeDescriptionidUUIDUnique identifiertypestringfact, preference, procedure, pattern, ingested, correction, anti-pattern, policy``memory_classstringepisodic, semantic, procedural, preference, policy``contentstringThe memory contentsourcestringuser, inferred, ingested``source_urlstring?URL for ingested contenttagslistDot-namespaced tags (e.g., code.python)contextstring?When this applies (e.g., "casual conversations")session_idint?Session this was created increatedISO 8601Creation timestamplast_accessedISO 8601Last retrieval timestampaccess_countintTimes retrieved (starts at 1)confidencestringsure, likely, uncertain``superseded_byUUID?Pointer to replacement entrysuccess_countintTimes successfully appliedcorrection_metaobject?For corrections: wrong_entry_id, wrong_claim, right_claim, reason
KeyDescriptionversionSchema version (4)last_decayTimestamp of last decay runsession_counterAuto-incrementing session IDcurrent_sessionActive session (id, context, started)
Decay threshold scales with access count: 30 * (1 + access_count) days.
Decay runs automatically during get and add operations (24-hour cooldown).
Tags support dot notation for namespacing: code.python, style.tone, workflow.git.
Search for code matches both code.python and code.typescript.
Use ./scripts/memory.sh tags to view the tag hierarchy.
These are examples of what users might say and the commands the agent should run:
text
"Remember: <fact>" → add fact "<content>" user "<tags>"
"What do you know about X?" → get "<topic>" --policy balanced
"Process this full message" → loop "<message>"
"Update that info" → supersede <old_id> <new_id>
"Show all memories" → export
text
"That's wrong, it's actually Y" → correct <wrong_id> "<right>" "<reason>"
"That worked well" → success <id>
"What patterns do you see?" → similar "<topic>" (agent creates pattern if 3+ found)
"Any anti-patterns?" → list anti-pattern
text
"Check for conflicts" → conflicts "<content>"
"Memory health?" → reflect
"What needs consolidation?" → consolidate
"What happened recently?" → log
text
"Start session: Frontend work" → session "Frontend work"
Each module has its own SKILL.md in modules/:
ModuleTypeWhat it doesWhen it appliesArchive 📦CodeStore and retrieve memoriesEvery store/retrieve operationGauge 📊GuidelineInterpret confidence levelsWhen returning memory-based answersIngest 📥GuidelineFetch URLs, extract knowledgeUser says "Ingest: URL" (disabled by default)Signal ⚡GuidelineDetect contradictionsAgent calls conflicts before storingRitual 🔄GuidelineSpot repeated behaviorsAgent calls similar after storingVibe 🎭GuidelineRead emotional toneAgent reads tone per-message
Code = implemented in scripts/brain.py with actual commands.
Guideline = behavioral instructions for the agent — no dedicated code, the agent follows these using core commands ( add, get, conflicts, similar, etc.).
memory/memory.db firstAGENT_BRAIN_SUPERMEMORY_SYNC=off)AGENT_BRAIN_PII_MODE=strict)export to dump all memory as JSON, or open the SQLite file directly