← 返回 Skills 市场
dobrinalexandru

Agent Brain

作者 Alex Dobrin · GitHub ↗ · v1.0.10
cross-platform ⚠ suspicious
83
总下载
0
收藏
0
当前安装
9
版本数
在 OpenClaw 中安装
/install agent-brain
功能描述
Local-first persistent memory for AI agents with SQLite storage, orchestrated retrieve/extract loops, hybrid retrieval, contradiction checks, correction lear...
使用说明 (SKILL.md)

Agent Brain 🧠

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.

Why this exists

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.

What makes this different

  • Production-grade storage. SQLite with WAL mode and indexed queries. Handles 10,000+ entries without breaking a sweat. JSON backend available as fallback.
  • Pluggable backends. Storage abstraction layer means you can swap SQLite for Postgres, Supabase, or any other backend — the command interface stays the same.
  • Continuous learning. Corrections track what was wrong, what's right, and why. Successes reinforce what works. Anti-patterns emerge from repeated mistakes.
  • Selective dispatch, not a linear pipeline. The orchestrator picks the 1-3 modules relevant to each task. Storing a fact doesn't need Vibe. Reading tone doesn't need Archive.
  • Active fact extraction. The agent scans every message for storable information — identity, tech stack, preferences, workflows, project context — without being asked.
  • Honest confidence. No fake 0.0-1.0 scores. Four categories (SURE / LIKELY / UNCERTAIN / UNKNOWN) derived from actual metadata — source type, access count, age.
  • Hybrid retrieval. Results ranked with lexical + semantic scoring (--policy fast|balanced|deep) and optional score explainability (--explain).
  • Supersede, don't delete. Old facts aren't destroyed. They're marked superseded_by with a pointer to the replacement, preserving full history.
  • Decay is mechanical. Entries scale their decay threshold by access count. Heavily-used knowledge persists longer. Unused knowledge fades.

Architecture

Six modules, one orchestrator, pluggable storage.

          ┌──────────────────────────────┐
          │       🧠 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  │
                └──────────────────┘

How It Works

Per-Message Flow

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:

./scripts/memory.sh get "\x3Ctopic words>" --policy balanced

How to pick search terms:

User says Search query Why
"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:

./scripts/memory.sh loop "\x3Cfull 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:

./scripts/memory.sh conflicts "\x3Ccontent to store>"
# If NO_CONFLICTS → proceed with add
# If POTENTIAL_CONFLICTS → ask user to clarify, or supersede old entry
./scripts/memory.sh add \x3Ctype> "\x3Ccontent>" \x3Csource> "\x3Ctags>"

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:

# User says "that's wrong, it's actually X"
./scripts/memory.sh correct \x3Cwrong_id> "\x3Cright content>" "\x3Creason>"

# User says "that worked great"
./scripts/memory.sh success \x3Cid>

Full Example

User message: "Can you update the database migration? We use Prisma with PostgreSQL."

Agent thinks:

  1. RETRIEVE: Search for relevant context

    ./scripts/memory.sh get "database migration prisma"
    

    Result: [sure] (fact) Project uses Prisma ORM with PostgreSQL — confirmed, proceed with known setup.

  2. EXTRACT: User revealed tech stack info. Check if already stored:

    • "We use Prisma with PostgreSQL" — already in memory (retrieved above), skip.
  3. RESPOND: Help with the migration using Prisma + PostgreSQL knowledge.

  4. LEARN: Nothing to correct or confirm yet.

User message: "Actually we switched to Drizzle last month."

Agent thinks:

  1. RETRIEVE: ./scripts/memory.sh get "database orm drizzle" — no results for Drizzle.

  2. EXTRACT: This is a correction. Find the old entry and correct it:

    ./scripts/memory.sh correct \x3Cprisma_entry_id> "Project uses Drizzle ORM with PostgreSQL" "Switched from Prisma to Drizzle"
    
  3. RESPOND: Acknowledge the switch, adjust advice to use Drizzle.

Selective Dispatch

Not every task needs every module. The orchestrator classifies the task and calls only what's relevant:

Task Type Modules Used
Any message (extract facts) Archive (extract + store) + Signal (check conflicts)
Answer a question Gauge (confidence) + Archive (retrieve)
User seems frustrated Vibe (detect) + Archive (adjust style)
Ingest a URL Ingest + Archive (store extracted knowledge)
Repeated workflow Ritual (detect pattern) + Archive (store)
Check consistency Signal + Archive
User corrects you Archive (correct) + Gauge (update confidence)
Record what worked Archive (success)
Review memory health Archive (reflect)

Persistence

Memory lives in memory/memory.db (SQLite, default) or memory/memory.json (legacy). All operations go through scripts/memory.shscripts/brain.py with a pluggable storage backend.

AGENT_BRAIN_BACKEND=sqlite  (default) → memory/memory.db
AGENT_BRAIN_BACKEND=json    (legacy)  → memory/memory.json

Optional SuperMemory mirror on writes (add, correct):

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

Confidence

No fake numeric scores. Four categories derived from entry metadata:

  • SURE: Well-established fact, stated multiple times or 3+ successes
  • LIKELY: Stated once, no contradictions
  • UNCERTAIN: Inferred, not directly stated
  • UNKNOWN: No relevant memory exists

Retrieval

Results are ranked by a hybrid formula:

  • Keyword match (40%) — meaningful words, stopwords filtered
  • Tag overlap (25%) — supports namespaced tags (e.g., code.python)
  • Confidence (15%) — higher confidence entries rank higher
  • Recency (10%) — recently accessed entries get a boost
  • Access frequency (10%) — frequently used knowledge ranks higher
  • Semantic similarity (policy dependent) — local semantic vectors by default; optional remote embeddings require AGENT_BRAIN_REMOTE_EMBEDDINGS=on plus AGENT_BRAIN_EMBEDDING_URL and obey AGENT_BRAIN_REMOTE_EMBEDDING_MAX_ENTRIES

Retrieved entries are automatically marked as accessed (no manual touch needed).

Continuous Learning

The learning loop has three signals:

  1. Corrections (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.
  2. Successes (success): When a memory is applied successfully, record it. At 3+ successes, confidence auto-upgrades to SURE.
  3. Patterns (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.

Storage

Default: memory/memory.db (SQLite). Legacy: memory/memory.json.

Entry Schema

Field Type Description
id UUID Unique identifier
type string fact, preference, procedure, pattern, ingested, correction, anti-pattern, policy
memory_class string episodic, semantic, procedural, preference, policy
content string The memory content
source string user, inferred, ingested
source_url string? URL for ingested content
tags list Dot-namespaced tags (e.g., code.python)
context string? When this applies (e.g., "casual conversations")
session_id int? Session this was created in
created ISO 8601 Creation timestamp
last_accessed ISO 8601 Last retrieval timestamp
access_count int Times retrieved (starts at 1)
confidence string sure, likely, uncertain
superseded_by UUID? Pointer to replacement entry
success_count int Times successfully applied
correction_meta object? For corrections: wrong_entry_id, wrong_claim, right_claim, reason

Meta Fields

Key Description
version Schema version (4)
last_decay Timestamp of last decay run
session_counter Auto-incrementing session ID
current_session Active session (id, context, started)

Decay

Decay threshold scales with access count: 30 * (1 + access_count) days.

  • An entry accessed once decays after 60 days
  • An entry accessed 5 times decays after 180 days
  • Heavily-used knowledge persists longer mechanically

Decay runs automatically during get and add operations (24-hour cooldown).

Tags

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.

Natural Language → Commands

These are examples of what users might say and the commands the agent should run:

Core

"Remember: \x3Cfact>"              → add fact "\x3Ccontent>" user "\x3Ctags>"
"What do you know about X?"     → get "\x3Ctopic>" --policy balanced
"Process this full message"     → loop "\x3Cmessage>"
"Update that info"              → supersede \x3Cold_id> \x3Cnew_id>
"Show all memories"             → export

Learning

"That's wrong, it's actually Y" → correct \x3Cwrong_id> "\x3Cright>" "\x3Creason>"
"That worked well"               → success \x3Cid>
"What patterns do you see?"      → similar "\x3Ctopic>" (agent creates pattern if 3+ found)
"Any anti-patterns?"             → list anti-pattern

Meta

"Check for conflicts"           → conflicts "\x3Ccontent>"
"Memory health?"                → reflect
"What needs consolidation?"     → consolidate
"What happened recently?"       → log

Sessions

"Start session: Frontend work"  → session "Frontend work"

Modules

Each module has its own SKILL.md in modules/:

Module Type What it does When it applies
Archive 📦 Code Store and retrieve memories Every store/retrieve operation
Gauge 📊 Guideline Interpret confidence levels When returning memory-based answers
Ingest 📥 Guideline Fetch URLs, extract knowledge User says "Ingest: URL" (disabled by default)
Signal Guideline Detect contradictions Agent calls conflicts before storing
Ritual 🔄 Guideline Spot repeated behaviors Agent calls similar after storing
Vibe 🎭 Guideline Read emotional tone Agent 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.).

Security

  • Local-first by default. All data is written to memory/memory.db first
  • Optional cloud mirror. SuperMemory sync is best-effort and can be disabled (AGENT_BRAIN_SUPERMEMORY_SYNC=off)
  • PII guardrail. Sensitive-looking secrets are refused by default (AGENT_BRAIN_PII_MODE=strict)
  • Ingest disabled by default. URL fetching requires explicit opt-in (SSRF risk)
  • Inspectable. Use export to dump all memory as JSON, or open the SQLite file directly
  • WAL mode. SQLite's Write-Ahead Logging prevents corruption from concurrent access
  • Auto-migration. v2/v3 JSON/SQLite data is migrated to schema v4 automatically, with backup for JSON migration
安全使用建议
This skill appears to do what it claims (local persistent memory) but has privacy-sensitive behavior and a couple of small inconsistencies you should consider before installing: - Review the actual scripts (memory.sh and any code that does ingestion or remote calls) before enabling or giving it any persistent access. Ensure memory directory location and file permissions are acceptable. - It relies on local tools (bash, python3, SQLite); the skill metadata doesn't list these as required — make sure your runtime provides them. - By default ingest is disabled, and remote embeddings/mirroring are opt-in. Do NOT set AGENT_BRAIN_EMBEDDING_URL, AGENT_BRAIN_REMOTE_EMBEDDINGS, or any SuperMemory sync env vars unless you trust the external endpoint and understand what data might be sent. - The agent is instructed to silently store extracted facts from every message. If you care about privacy, limit automatic extraction (or require explicit user confirmation before storing), enable strict PII mode, and consider encrypting or restricting access to memory.db and backups. - If you want higher assurance, run the included test suite in an isolated environment to observe behavior, and audit memory.sh for any references to sourcing external env files or unexpected network calls. If you are unsure, treat this as sensitive: the functionality is coherent, but the storage and silent capture behavior makes it privacy-sensitive rather than obviously benign.
功能分析
Type: OpenClaw Skill Name: agent-brain Version: 1.0.10 The skill bundle is classified as suspicious primarily due to a Server-Side Request Forgery (SSRF) vulnerability in `scripts/brain.py`. While `modules/ingest/SKILL.md` explicitly details robust URL validation to prevent SSRF for the 'ingest' functionality, the `remote_semantic_vector` function in `scripts/brain.py` performs network requests to `AGENT_BRAIN_EMBEDDING_URL` without implementing these crucial validation checks. This discrepancy creates a significant flaw that could allow an attacker to make requests to internal network resources if they can control the `AGENT_BRAIN_EMBEDDING_URL` environment variable. Other potential risks, such as shell injection from agent instructions in `SKILL.md`, are largely mitigated by `scripts/brain.py`'s use of parameterized queries and direct Python file operations. The optional cloud synchronization to `https://api.supermemory.ai/v3/documents` is a documented feature with PII guardrails, not malicious exfiltration.
能力评估
Purpose & Capability
The name/description match the provided scripts and SKILL.md: this is a local SQLite/JSON-backed memory system with retrieval, extraction, conflict checks, and optional remote mirroring. Implementation files (scripts/, sqlite_store.py, json_store.py, etc.) implement the documented features. Minor mismatch: the package does not declare required runtime binaries (the scripts and tests use bash and python3 and the SQLite backend requires sqlite support), but requires.env is empty; that's an omission rather than evidence of malicious intent.
Instruction Scope
SKILL.md instructs the agent to scan EVERY user message, extract identity/project/tech stack/preferences, and silently store those facts in memory (never announce 'I'm storing this'). While consistent with a memory system, this is privacy-sensitive behavior: it will capture PII and project context unless carefully constrained. The document prohibits storing passwords/keys and marks ingest disabled by default, but the agent-level instruction to run the per-message loop and silently persist extracted content is significant scope and should be accepted only with awareness. The ingest module permits fetching user-provided URLs (with validation) — fetches would send page content to the agent/runtime for extraction.
Install Mechanism
No install spec (no network downloads or package installs) — the skill is delivered as scripts and documentation only. This is low install risk. However, the included scripts will run locally and expect standard tooling (bash, python3, sqlite library), which are not listed as explicit requirements.
Credentials
The skill declares no required credentials and operates on local files (memory.db / memory.json). _meta.json contains optional env keys (AGENT_BRAIN_SUPERMEMORY_SYNC, AGENT_BRAIN_PII_MODE) and the code/test reference optional variables for remote embeddings (AGENT_BRAIN_EMBEDDING_URL, AGENT_BRAIN_REMOTE_EMBEDDINGS). Those are opt-in, but if enabled they could cause memory contents or derived embeddings to be sent to external services. No unexplained secret or unrelated credential requests are present.
Persistence & Privilege
The skill creates and maintains persistent local storage (memory.db / memory.json) and is intended to be invoked on every message by the agent. It does not declare always:true and does not modify other skills. The primary risk is data persistence: stored memories may include PII or project secrets if the agent's extraction rules or user confirmations are lax. Optional SuperMemory/remote sync features could make data leave the host if enabled.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install agent-brain
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /agent-brain 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.10
**Major upgrade: Adds a production-ready SQLite backend, modular orchestration, hybrid retrieval, and correction learning with real persistence.** - Introduced new script-based architecture (`scripts/`) for orchestration, storage, benchmarking, and validation. - Swapped single-file JSON storage for SQLite by default (with pluggable backend support). - Modularized core functionality: retrieval, extraction, contradiction detection, correction, and learning now handled by distinct modules. - Expanded documentation to cover architecture, usage examples, selective dispatch, persistent storage, and backend configuration. - Deprecated legacy `memory/index.json`; all memory operations now routed via `scripts/memory.sh` and `scripts/brain.py`. - Laid groundwork for advanced features (hybrid search policies, history-preserving updates, optional cloud sync).
v1.0.9
- Updated storage model: Now uses local-only memory by default, with no automatic cloud sync. - SuperMemory (cloud sync) is now optional and opt-in, with clear instructions for enabling. - Clarified security: all data stays local unless explicitly configured otherwise. - Revised documentation to reflect storage and security changes. - Minor improvements to module and feature descriptions for clarity.
v1.0.8
- Major documentation rewrite for clarity and onboarding - Added dual storage support details (local and optional cloud sync with SuperMemory) - More prominent feature and benefit overview - New visual diagram explaining modules and memory flow - Streamlined command and security sections - Ingest module usage and risks clarified
v1.0.7
- Improved documentation with clearer module explanations and practical examples. - Added a table summarizing what each module does and example usage. - Expanded command list with usage hints for each function. - Clarified how to enable the optional, security-sensitive "Ingest" module. - Updated tone to be more user-friendly and instructional.
v1.0.5
- Updated description to clarify "local memory system" for agents. - Added "Vibe" feature for tone detection. - Made Ingest module disabled by default for improved security; instructions to enable now included. - Provided clearer security warnings and enablement steps for URL ingestion. - Minor clarifications and formatting improvements to documentation.
v1.0.4
- Updated skill description for clarity and simplicity. - Streamlined module list: focuses on Archive, Signal, Gauge, and Ritual. - Added prominent security warning regarding web_fetch and SSRF risks. - Refined usage and disabling instructions. - Updated command list to match simplified feature set.
v1.0.3
- Overhauled security: disables autonomous model invocation; only runs with explicit user commands. - Now requires user-provided URLs for web data ingestion (no automatic web fetch). - Updated metadata fields and requirements for improved transparency. - Memory remains local and can be cleared by deleting the memory folder. - Added sample user commands for knowledge ingestion and fact storage.
v1.0.1
- No changes made in this version. - Content in all files remains identical to the previous release.
v1.0.0
Major update: Agent skill replaced with an integrated, modular "agent-brain" system. - Introduces 6 cognitive modules: archive, ingest, vibe, gauge, signal, and ritual. - Removes previous focus on agent voice, personality, and boundaries; shifts to continuous learning and memory. - Skill now runs autonomously, dispatching only relevant modules per task to optimize operation. - Enhances privacy—no data leaves your machine; memory stored locally in the memory directory. - Consolidates all core functions into one installable skill with clear structure and usage instructions.
元数据
Slug agent-brain
版本 1.0.10
许可证
累计安装 0
当前安装数 0
历史版本数 9
常见问题

Agent Brain 是什么?

Local-first persistent memory for AI agents with SQLite storage, orchestrated retrieve/extract loops, hybrid retrieval, contradiction checks, correction lear... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 83 次。

如何安装 Agent Brain?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install agent-brain」即可一键安装,无需额外配置。

Agent Brain 是免费的吗?

是的,Agent Brain 完全免费(开源免费),可自由下载、安装和使用。

Agent Brain 支持哪些平台?

Agent Brain 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Agent Brain?

由 Alex Dobrin(@dobrinalexandru)开发并维护,当前版本 v1.0.10。

💬 留言讨论