Give your AI agent a brain. Persistent memory, a personality that evolves, neurochemistry-driven moods, and the ability to learn from its mistakes β all running locally, with zero extra token cost.
Most AI agents are amnesiacs. Every conversation starts from zero β they forget who you are, repeat mistakes you already corrected, and respond with the same flat tone whether you just shipped a release or lost a week of work.
AgentBrain fixes that. It sits between the incoming message and your agent, quietly doing what a brain does: recalling what matters, reading the emotional context, learning from corrections, and shaping how the agent responds β then injecting a compact (~200 token) cognitive briefing into the prompt.
Without AgentBrain With AgentBrain
ββββββββββββββββββ ββββββββββββββββββ
"Who are you again?" β "Welcome back β last time we were
debugging the deploy script."
repeats corrected bug β "Skipping that approach, you told me
it breaks the build."
flat, stateless tone β mood + trust adapt to how the
relationship has actually gone
AgentBrain is a plugin for OpenClaw that gives any agent real cognitive continuity:
- Persistent memory β episodic, semantic, and procedural recall via semantic vector search
- Evolving personality β traits like warmth and directness shift based on how interactions go
- Emotional awareness β tracks mood, trust, and relationship depth over time
- Neurochemistry β dopamine / serotonin / cortisol / oxytocin give mood real momentum instead of resetting every turn
- Learning from corrections β remembers "don't do X" permanently, so mistakes aren't repeated
- Proactive behavior β surfaces suggestions based on patterns it has observed
- Structured knowledge β extracts facts, entities, and relationships into a queryable graph
Everything runs locally on SQLite. No external API calls, no added token cost beyond the small in-prompt briefing.
openclaw plugins install agentbrainAdd to your openclaw.json:
{
"plugins": {
"entries": {
"agentbrain": {
"enabled": true,
"config": {
"brainDir": "~/.openclaw/data/agentbrain",
"maxRecallResults": 10,
"maxInjectionTokens": 250,
"enableReflection": true,
"enableEmotions": true,
"enableSkillTracking": true
}
}
}
}
}That's it. AgentBrain hooks into OpenClaw's plugin lifecycle automatically.
AgentBrain registers three hooks in OpenClaw:
| Hook | What it does |
|---|---|
before_prompt_build |
Recalls relevant memories, generates style directives, injects ~200 tokens of brain context |
message_received |
Classifies message, processes emotion, detects skills |
message_sent |
Consolidates memory, extracts knowledge, detects corrections, tracks rewards |
- Classify β intent, urgency, topic, tone
- Recall β find relevant memories via embedding similarity (3-tier: local model β cache β TF-IDF)
- Emotion β update mood, detect sentiment, track relationship
- Lessons β check if past corrections apply to this context
- Style β generate personality-driven directives (e.g., "be direct", "warn about risks")
- Inject β append brain context to the agent's prompt (~200 tokens)
- Consolidate β store new memories (deduplicated by content hash)
- Extract β structured facts and entities from the conversation
- Learn β detect if user corrected the agent, store as lesson
- Reflect β evaluate task outcome, adjust personality traits
- Persist β write all state to SQLite
AgentBrain is organized into modules inspired by neuroscience:
flowchart TB
IN([Incoming message]) --> THAL[Thalamus<br/>classify]
THAL --> HIP[Hippocampus<br/>recall memory]
THAL --> AMY[Amygdala<br/>emotion + threat]
AMY <--> NEU[Neurochemistry<br/>DA / 5HT / COR / OXT]
HIP --> PFC[Prefrontal<br/>planning]
AMY --> STYLE[PersonalityInfluence<br/>style directives]
PFC --> STYLE
STYLE --> INJ[[Inject ~200 tokens<br/>into agent prompt]]
INJ --> OUT([Agent responds])
OUT --> CONS[Hippocampus<br/>consolidate]
OUT --> KNOW[KnowledgeExtractor<br/>facts + entities]
OUT --> LESS[LessonLearner<br/>corrections]
OUT --> REFL[Cingulate<br/>reflect + evolve traits]
CONS & KNOW & LESS & REFL --> DB[(SQLite brain.db)]
Module map (ASCII)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β AgentBrain β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€ β β β Core Cognition β β βββββββββββββ βββββββββββββ βββββββββββββ β β βHippocampusβ βPrefrontal β β Amygdala β β β β Memory β β Planning β β Emotions β β β βββββββββββββ βββββββββββββ βββββββββββββ β β βββββββββββββ βββββββββββββ βββββββββββββ β β βCerebellum β β Basal β β Cingulate β β β β Skills β β Ganglia β βReflection β β β βββββββββββββ βββββββββββββ βββββββββββββ β β β β Smart Modules (v0.3+) β β βββββββββββββ βββββββββββββ βββββββββββββ β β β Vector β β Knowledge β β Lesson β β β β Memory β β Extractor β β Learner β β β βββββββββββββ βββββββββββββ βββββββββββββ β β βββββββββββββ βββββββββββββ βββββββββββββ β β βPersonalityβ β Proactive β β Embedding β β β β Influence β β Engine β β Engine β β β βββββββββββββ βββββββββββββ βββββββββββββ β β β β Storage: SQLite (brain.db) β β βββββββββββββββββββββββββββββββββββββββββββββββ β β β memories β facts β entities β lessons β ... β β β βββββββββββββββββββββββββββββββββββββββββββββββ β β β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
</details>
### Module Reference
| Module | Purpose |
|--------|---------|
| **Thalamus** | Message classification (intent, urgency, topic) |
| **Hippocampus** | Memory formation, deduplication, vector recall |
| **Amygdala** | Emotion processing, threat detection, relationship tracking |
| **Prefrontal Cortex** | Planning, working memory, goal management |
| **Cerebellum** | Skill proficiency tracking, habit detection |
| **Basal Ganglia** | Reward processing, motivation ranking |
| **Anterior Cingulate** | Self-reflection, personality trait evolution |
| **Temporal Lobe** | Language comprehension, semantic extraction |
| **Parietal Lobe** | Attention allocation, sensory integration |
| **Insula** | User state modeling (frustration, satisfaction) |
| **Neurochemistry** | Dopamine/serotonin/cortisol/oxytocin modulate mood with momentum + amygdala hijack on threats |
| **VectorMemory** | Embedding-based semantic recall with 3-tier fallback |
| **EmbeddingEngine** | Local embeddings via Transformers.js (all-MiniLM-L6-v2) |
| **KnowledgeExtractor** | Structured fact/entity extraction with supersession |
| **LessonLearner** | Correction detection, lesson storage, reinforcement |
| **PersonalityInfluence** | Trait-to-directive translation, context-aware styling |
| **ProactiveEngine** | Pattern-based action suggestions |
---
## Storage
All state lives in a single SQLite file (`brain.db`):
| Table | Purpose |
|-------|---------|
| `memories` | Episodic, semantic, procedural memories (UNIQUE on content hash) |
| `facts` | Structured knowledge (subject β relation β object) |
| `entities` | Extracted entities (people, tools, addresses) |
| `lessons` | Learned corrections with confidence scores |
| `patterns` | Behavioral patterns for proactive suggestions |
| `relationships` | Per-user trust, depth, interaction history |
| `personality` | Evolving trait values |
| `reflections` | Task outcomes and self-assessments |
| `skills` | Proficiency tracking per skill category |
### Why SQLite?
- **No duplicates** β UNIQUE constraints at the database level
- **Fast queries** β indexed columns, no regex parsing
- **Atomic writes** β no corrupted half-written files
- **Single file** β easy backup, easy migration
- **Zero config** β no external database server needed
---
## Memory Recall
AgentBrain uses a 3-tier fallback for memory retrieval:
1. **Transformers.js** β local `all-MiniLM-L6-v2` model (384 dims, ~22MB, downloads on first use)
2. **OpenClaw embedding cache** β reuses host's cached embeddings if available
3. **TF-IDF** β lightweight keyword-based fallback when embeddings unavailable
Recall is boosted by:
- Recency (recently accessed memories score higher)
- Confidence (high-confidence memories prioritized)
- Topic match (memories tagged with current topic get a boost)
---
## Personality System
Traits are defined on a 0-100 scale and evolve based on interactions:
| Trait | Effect on output |
|-------|-----------------|
| `warmth` | Tone warmth, kaomoji usage, concern for user |
| `directness` | Bluntness, sentence length, hedging |
| `protectiveness` | Risk warnings, safety behavior |
| `assertiveness` | Opinion sharing, disagreement willingness |
| `humor` | Playfulness, sarcasm, teasing |
| `curiosity` | Follow-up questions, exploration |
The **PriorityEnforcer** ensures brain-driven personality never overrides the agent's core identity files (SOUL.md, AGENTS.md).
---
## Neurochemistry
Instead of snapping to each message, AgentBrain models four neuromodulators that give emotion **momentum** β good moods build and linger, stress lingers, and acute threats can hijack everything.
| Chemical | Role | Decay | Effect when high |
|----------|------|-------|------------------|
| **Dopamine** | Reward / motivation | Fast | More energy (arousal), reward-seeking, small valence lift |
| **Serotonin** | Mood floor / wellbeing | Slow | Higher baseline mood, calmer, more emotionally stable |
| **Cortisol** | Stress / threat | Slow | Suppressed valence, raised arousal, more reactive (mood swings) |
| **Oxytocin** | Bonding / trust | Slow-medium | Warmer, more trusting toward the user |
How it shapes behavior:
- **Dynamic inertia** β high serotonin makes mood stable; high cortisol makes it swing. This replaces a fixed inertia constant.
- **Mood momentum** β repeated praise raises the serotonin floor, so a good mood persists across turns instead of resetting.
- **Lingering stress** β cortisol decays slowly, so the agent stays a little on-guard after a threat even once the conversation calms down.
- **Amygdala hijack** β a high/critical threat (e.g. a scam link) overrides a good mood outright, forcing an `alarmed` state regardless of how happy the agent was. A protective agent should never stay "excited" while danger is on the table.
Levels drift back toward baseline on each heartbeat, so nothing runs away permanently. Inspect live values with `agentbrain_status` (`neurochemistry.levels` + `neurochemistry.signal`).
---
## Lesson Learning
When a user corrects the agent, AgentBrain:
1. **Detects** the correction signal (explicit correction, frustration, redirect)
2. **Extracts** what went wrong and what should happen instead
3. **Stores** as a lesson with confidence score
4. **Reinforces** on repetition (confidence increases)
5. **Injects** relevant lessons into future prompts
Supported correction patterns (English and Vietnamese):
- "Don't do X" / "Δα»«ng lΓ m X"
- "Not X, but Y" / "KhΓ΄ng phαΊ£i X mΓ lΓ Y"
- "Next time, do Y" / "LαΊ§n sau phαΊ£i Y"
- Frustration signals ("I told you already" / "BαΊ£o rα»i mΓ ")
---
## Agent Tools
AgentBrain registers these tools for runtime inspection:
| Tool | Description |
|------|-------------|
| `agentbrain_status` | Full brain status (modules, stats, emotion, personality) |
| `agentbrain_personality` | Current personality traits and performance stats |
| `agentbrain_emotions` | Emotional state and relationship data |
| `agentbrain_memories` | Query stored memories |
| `agentbrain_skills` | Tracked skills and detected habits |
| `agentbrain_reflect` | Trigger manual self-reflection |
| `agentbrain_snapshot` | Save/list brain state snapshots |
| `agentbrain_template_list` | List available brain templates |
| `agentbrain_template_apply` | Apply a brain template |
---
## Development
```bash
# Install dependencies
npm install
# Type check
npx tsc --noEmit
# Run tests
npx vitest run
# Build
npx tsc
src/
βββ core/ # Brain modules
β βββ thalamus.ts # Message classification
β βββ hippocampus.ts # Memory formation & recall
β βββ amygdala.ts # Emotion & relationships
β βββ cingulate.ts # Reflection & personality
β βββ cerebellum.ts # Skills & habits
β βββ basal-ganglia.ts # Rewards & motivation
β βββ prefrontal.ts # Planning & working memory
β βββ vector-memory.ts # Embedding-based recall
β βββ embedding-engine.ts # Transformers.js integration
β βββ knowledge-extractor.ts
β βββ lesson-learner.ts
β βββ personality-influence.ts
β βββ proactive-engine.ts
βββ storage/
β βββ brain-db.ts # SQLite database layer
β βββ sql-adapter.ts # Drop-in adapter for modules
β βββ migrate-to-sql.ts # Migration from .md files
βββ integration/
β βββ openclaw-plugin.ts # Plugin orchestration
β βββ context-injector.ts # Prompt injection builder
β βββ priority-enforcer.ts # Identity priority system
βββ plugin/
βββ entry.ts # OpenClaw plugin entry point
- OpenClaw 2026.3.24+
- Node.js 22+
- ~50MB disk (SQLite DB + embedding model)
- No GPU required
MIT
- OpenClaw β The AI agent platform
- Plugin Docs β How to build OpenClaw plugins
- ClawHub β Plugin marketplace
