Skip to content

TheCodingDragon0/agent-brain

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🧠 Agent Brain for OpenClaw

The cognitive engine that makes any OpenClaw agent genuinely intelligent.

Auto-activating on every message. Compounds over time. Zero config required.


What Is This?

Agent Brain transforms a reactive chatbot into a cognitive agent with persistent memory, self-learning, reasoning, and knowledge graph capabilities. Install it, and your bot gets smarter with every conversation.

No external dependencies required. Works with pure filesystem. Optionally enhances with Ollama for semantic search and LightRAG for knowledge graphs.

Features

🧠 Core Cognition (Tier 1)

  • Structured Memory — People, projects, decisions, preferences, facts. Organized into clean markdown files with confidence scoring and auto-pruning.
  • Active Learning — Captures corrections, patterns, and discoveries. Promotes what works, decays what doesn't. Your bot learns from its mistakes.
  • Live State — Tracks current focus, active tasks, completed work. Never loses context between sessions.
  • Daily Logs — Automatic activity tracking with streak counting. Know exactly what happened and when.
  • Auto-Maintenance — Pattern promotion, memory decay, file compaction, health scoring. The brain takes care of itself.

💡 Enhanced Reasoning (Tier 2)

  • Session Lifecycle — Start → checkpoint → end → arc history. Full session tracking with duration and activity metrics.
  • Task Decomposition — Break complex tasks into tracked steps with progress monitoring.
  • Self-Evaluation — Score your bot's responses (quality 1-10). Low-quality responses auto-flag for improvement.
  • Decision Logging — Record decisions with options considered, reasoning chains, and outcomes.
  • Intelligence Digests — Daily, weekly, and evolution reports showing exactly how your brain is growing.

🔍 Semantic Recall (Tier 3)

  • Vector Search — Powered by Ollama embeddings (qwen3-embedding:0.6b). Ask "what do I know about X?" and it finds it.
  • Related Discovery — Find semantically similar memories you didn't know were connected.
  • Incremental Updates — Only re-embeds changed files. Fast and efficient.
  • Graceful Fallback — If Ollama isn't running, falls back to text search automatically.

🕸️ Knowledge Graph (Tier 4)

  • Entity-Relationship Graph — Self-contained graph built from memory files. No external database needed.
  • Multi-Hop Queries — "If X mentions Y and Y references Z, what connects them?"
  • Path Finding — Discover how any two entities are connected.
  • Cluster Detection — Find groups of related entities.
  • Visualization — Text-based graph display showing entity connections.

Quick Start

1. Install

# Copy the skill to your OpenClaw workspace
cp -r skills/agent-brain/ ~/.openclaw/workspace/skills/

# Run the installer
python3 skills/agent-brain/scripts/install.py

2. Add to AGENTS.md

Add this to your AGENTS.md (or copy from templates/agents-brain-section.md):

## 🧠 Agent Brain — Cognitive Engine (EVERY MESSAGE)

The brain is always on. Follow this protocol:

### On Session Start (first message only)
1. If `brain/state.json` doesn't exist → run `py skills/agent-brain/scripts/init.py`
2. Read `brain/state.json` — get current focus, active tasks
3. Increment `total_sessions`, set `started_at` to now

### On EVERY Message (silent, <50 tokens)
1. Glance `brain/state.json` — what's the current focus?
2. If message mentions known entity → load `brain/memory/{category}/{slug}.md`
3. Apply known patterns from `brain/learnings/patterns.md`

### After EVERY Response (silent, <100 tokens)
1. Corrected? → append to `brain/learnings/corrections.md`
2. Discovered? → append to `brain/learnings/patterns.md`
3. New entity? → `py memory.py add {cat} {slug} --fact "text"`
4. Activity? → `py logger.py log "did X"`
5. Update `brain/state.json`

### Session Lifecycle
1. First message: `py session.py start`
2. Every ~20 turns: `py session.py checkpoint --turns N`
3. Session end: `py session.py end`

3. Start Chatting

Your bot is now cognitive. It learns, remembers, and improves automatically.


Usage

Master Router

All commands go through one entry point:

python3 skills/agent-brain/brain.py <command>

Commands

Command What It Does
brain.py status Brain snapshot — health, memory, stats
brain.py health Full health check with scoring
brain.py log Today's activity log
brain.py streak Activity streak counter
brain.py digest Daily intelligence digest
brain.py weekly Weekly brain digest
brain.py evolution Brain growth over time
brain.py query "X" Semantic search (or text fallback)
brain.py add people alice --fact "Dev" Add memory
brain.py show people alice Show memory file
brain.py list List all memory
brain.py think "task" Decompose into steps
brain.py evaluate "x" --quality 8 Self-evaluate response
brain.py decide "topic" --option "A" --option "B" --chosen "A" Log decision
brain.py session start Start session tracking
brain.py session end End session + capture arc
brain.py embed Embed all memory (Ollama)
brain.py graph Scan memory relationships
brain.py kg build Build knowledge graph
brain.py kg-viz Visualize knowledge graph
brain.py compact Run maintenance cycle
brain.py doctor Validate and fix setup

Architecture

brain/
├── state.json                    # LIVE: current session state
├── config.json                   # Brain configuration
├── knowledge_graph.json          # Generated entity graph
├── embeddings.json               # Vector embeddings index
├── memory/
│   ├── people/{name}.md          # People, contacts, relationships
│   ├── projects/{name}.md        # Active projects, status
│   ├── decisions/{topic}.md      # Key decisions and reasoning
│   ├── preferences/{domain}.md   # User preferences by domain
│   └── facts/{topic}.md          # General knowledge
├── learnings/
│   ├── corrections.md            # User corrections (last 50)
│   ├── patterns.md               # Recurring patterns (confidence-scored)
│   ├── preferences.md            # Confirmed preferences
│   ├── evaluations.md            # Self-evaluation scores
│   └── reasoning.md              # Reasoning chains
├── log/
│   ├── {YYYY-MM-DD}.md          # Daily activity log
│   └── arcs/{session-id}.md     # Session arc history
└── archive/                      # Cold storage (auto-managed)
    ├── memory/
    └── learnings/

Scripts

Core

Script Purpose
brain.py Master command router
init.py Initialize brain directory
install.py One-command full setup
doctor.py Validate + auto-fix
maintain.py Promote, decay, compact, health
snapshot.py Status reports (text/md/json)

Memory & Learning

Script Purpose
memory.py Memory CRUD + text search
logger.py Daily activity logging + streaks

Reasoning

Script Purpose
think.py Task decomposition, self-eval, decisions
session.py Session lifecycle + arc history

Intelligence

Script Purpose
digest.py Daily/weekly/evolution digests
relate.py Cross-memory relationship mapping
recall.py Semantic vector search (Ollama)
kg.py Knowledge graph + multi-hop reasoning

Memory Format

Every memory file follows a clean, consistent template:

# {Title}
*Created: {date} | Updated: {date}*

## Context
{Why this exists, how it was learned}

## Key Facts
1. {fact} *(date)*
2. {fact} *(date)*

## Related
{Links to other memory files}

---
*Confidence: high|medium|low | Last verified: {date}*

How It Works

Every Message (~50 tokens)

The brain glances at state, loads relevant memory if entities are mentioned, and applies known patterns. Automatic, silent, minimal overhead.

After Every Response (~100 tokens)

Checks for corrections, discovers patterns, logs new entities, updates state. The brain learns from every interaction.

Periodic Maintenance (Cron or manual)

  • Promote — Patterns used 3+ times → confidence increases
  • Decay — Memory unused 30 days → warm flag; 90 days → archive
  • Compact — Corrections over 50 → trim oldest
  • Health — Score 0-100 with issue detection and auto-fix

Weekly Digest

Generates a comprehensive report of what the brain learned, how many sessions ran, what was accomplished, and how the brain is evolving.


Configuration

Edit brain/config.json to customize behavior:

{
  "version": "0.1.0",
  "auto_log": true,
  "auto_learn": true,
  "memory_limits": {
    "hot_entries": 100,
    "warm_file_lines": 200,
    "corrections_retain": 50,
    "patterns_promote_threshold": 3,
    "decay_warm_days": 30,
    "decay_cold_days": 90
  },
  "daily_log": true,
  "cite_sources": true
}

Requirements

  • Python 3.10+ (uses only stdlib — no pip install needed)
  • OpenClaw (any version with skills support)
  • Optional: Ollama with qwen3-embedding:0.6b for semantic search
  • Optional: LightRAG for enhanced knowledge graph

Tier Roadmap

✅ Tier 1: Core Cognition

Structured memory, learning capture, live state, daily logs, auto-maintenance, health monitoring, one-command install.

✅ Tier 2: Enhanced Reasoning

Session lifecycle, task decomposition, self-evaluation, decision logging, digests, relationship detection.

✅ Tier 3: Semantic Recall

Ollama vector embeddings, semantic search, related entity discovery, incremental re-embedding, text fallback.

✅ Tier 4: Knowledge Graph

Self-contained entity-relationship graph, multi-hop queries, path finding, cluster detection, visualization, optional LightRAG.


Rules

  1. Never invent memory — If it's not stored, say so.
  2. Cite sources — "Based on brain/memory/projects/x.md..."
  3. No secrets — Never store passwords, tokens, or credentials.
  4. Ask first — Before storing private third-party information.
  5. Graceful degradation — Reinitialize if corrupt, never fail silently.

License

MIT


Commands Quick Reference

# Setup
python3 brain.py install        # One-command install
python3 brain.py doctor         # Validate setup
python3 brain.py doctor --fix   # Auto-fix issues

# Status
python3 brain.py status         # Brain snapshot
python3 brain.py health         # Health check
python3 brain.py log            # Today's activity
python3 brain.py streak         # Activity streak

# Memory
python3 brain.py add people alice --fact "Backend dev"
python3 brain.py show people alice
python3 brain.py list
python3 brain.py query "who works on backend"

# Reasoning
python3 brain.py think "Build auth system"
python3 brain.py evaluate "Fixed the bug" --quality 9
python3 brain.py decide "Use PostgreSQL" --option "PostgreSQL" --option "MySQL" --chosen "PostgreSQL"

# Sessions
python3 brain.py session start
python3 brain.py session end

# Intelligence
python3 brain.py digest         # Daily digest
python3 brain.py weekly         # Weekly digest
python3 brain.py evolution      # Growth report
python3 brain.py embed          # Generate embeddings
python3 brain.py graph          # Scan relationships

# Knowledge Graph
python3 brain.py kg build       # Build graph
python3 brain.py kg-viz         # Visualize graph
python3 brain.py kg-stats       # Graph statistics
python3 brain.py kg-query "X"   # Query graph

# Maintenance
python3 brain.py compact        # Run maintenance

About

Cognitive engine for OpenClaw agents. Auto-activating memory, learning, reasoning, and knowledge graph. Zero config required.

Resources

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages