ไธบ AI Agent ๆ้ ็ๅคง่็บง่ฎฐๅฟ็ณป็ป
่ฎฉ Agent ๅไบบไธๆ ท่ฎฐไฝ ยท ้ๅฟ ยท ๅๆ ยท ๆจ็
Features โข Architecture โข Installation โข Quick Start โข Memory Categories โข Recall Strategies โข API โข License
Unified knowledge graph + vector memory system for AI agents.
Merges graph-memory with memory-lancedb-pro into an 8-category system with intelligent decay and reflection.
brain-memory simulates human brain memory mechanisms:
| ๐งฌ Human Mechanism | โก Code Implementation |
|---|---|
| Short-term โ Long-term | Working Memory โ Knowledge Graph persistence |
| Forgetting Curve | Weibull decay model (3-tier + dynamic acceleration) |
| Knowledge Association | Personalized PageRank + Community detection |
| Reflection | Turn reflection (lightweight) + Session reflection (deep) |
| Inductive Reasoning | 4-type reasoning engine (path / implicit / pattern / contradiction) |
profile / preferences / entities / events / tasks / skills / cases / patternsโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐ API Layer โ
โ ContextEngine (Unified Facade Interface) โ
โ processTurn โ recall โ performFusion โ reflectOnSession โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐๏ธ Control Layer โ
โ โโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโ โ
โ โ Extractorโ โ Recaller โ โ Fusion โ โReflectionโ โReasoningโ โ
โ โโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโ โ
โ โโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโ โ
โ โ Hybrid โ โ Vector โ โ Rerank โ โAdmission โ โ Working โ โ
โ โ Recall โ โ Recall โ โ er โ โ Control โ โ Memory โ โ
โ โโโโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโ โโโโโโโโโโโโ โโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ โ๏ธ Algorithm Layer โ
โ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโโโโโโโโโ โ
โ โ PageRank โ โ Community โ โ LSH โ โ Temporal โ โ
โ โ (PPR) โ โ Detection โ โ Dedup โ โ Classifier โ โ
โ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ โโโโโโโโโโโโโโ โ
โ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ โ
โ โ Decay โ โ Intent โ โ Query โ โ
โ โ (Weibull) โ โ Analyzer โ โ Expander โ โ
โ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ๐พ Storage Layer โ
โ SQLite: 6 tables + FTS5 + Triggers + 8 indexes (v1.1.0: IStorageAdapter abstraction, supports LanceDB POC) โ
โ bm_nodes โ bm_edges โ bm_vectors โ bm_messages โ
โ bm_communities โ bm_nodes_fts โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
npm install memory-likehuman-pro
Note: The published npm package contains the compiled
dist/output. Source files (src/,test/, etc.) are not included in the npm package.
git clone https://github.com/DylingCreation/brain-memory.git
cd brain-memory
npm install
cd brain-memory
npm install
import { ContextEngine, DEFAULT_CONFIG } from 'memory-likehuman-pro';
const config = {
...DEFAULT_CONFIG,
dbPath: '~/.openclaw/brain-memory.db',
llm: {
apiKey: process.env.LLM_API_KEY,
baseURL: 'https://your-ll-api-endpoint/v1',
model: 'your-model-name'
},
embedding: {
apiKey: process.env.EMBEDDING_API_KEY,
baseURL: 'https://your-embedding-api-endpoint/v1',
model: 'your-embedding-model'
}
};
const engine = new ContextEngine(config);
// ๐ Process conversation turns, extract knowledge
const result = await engine.processTurn({
sessionId: 'session-1',
agentId: 'agent-1',
workspaceId: 'workspace-1',
messages: [{
role: 'user',
content: 'I need to implement a memory system in TypeScript'
}]
});
console.log(`Extracted ${result.extractedNodes.length} nodes, ${result.extractedEdges.length} edges`);
// ๐ Recall relevant memories
const recall = await engine.recall('TypeScript memory system', 'session-1', 'agent-1', 'workspace-1');
console.log(`Recalled ${recall.nodes.length} relevant memories`);
brain-memory is designed as an OpenClaw plugin. Configure it in your OpenClaw config file (default: ~/.openclaw/openclaw.json):
{
"plugins": {
"entries": {
"brain-memory": {
"enabled": true,
"config": {
"llm": {
"apiKey": "your-api-key-here",
"baseURL": "https://your-ll-api-endpoint/v1",
"model": "your-model-name"
},
"embedding": {
"apiKey": "your-embedding-api-key",
"baseURL": "https://your-embedding-api-endpoint/v1",
"model": "your-embedding-model"
},
"engine": "hybrid",
"storage": "sqlite",
"mode": "full",
"dbPath": "~/.openclaw/brain-memory.db"
}
}
}
}
}
Plugin hooks registered automatically:
| ๐ Hook | โฐ Trigger | ๐ฏ Function |
|---|---|---|
message_received |
After user sends a message | Extract knowledge from user messages |
message_sent โจ |
After AI sends a reply | Extract suggestions / code / commitments from AI replies |
before_message_write |
Before AI sends a reply | Inject relevant memories into context |
session_start |
New session starts | Warm up memory cache |
session_end |
Session ends | Run reflection + graph maintenance |
The project includes interactive configuration scripts. These are generic setup tools (not platform-specific) that generate basic LLM/Embedding API config files:
# Interactive config โ generates config.js, .env, llm_client.js
npm run configure
# OpenClaw integration โ writes config into ~/.openclaw/openclaw.json
npm run setup-openclaw
Important: The interactive config scripts only set up core API credentials (LLM endpoint, API key, model name, embedding settings) and run mode (full/lite). They do not configure advanced brain-memory features such as decay parameters, reflection settings, fusion thresholds, or working memory limits. Those must be configured manually in your OpenClaw config file or programmatically via
BmConfig.
Lite mode (
mode: "lite"): Skips LLM reflection and knowledge fusion. Keeps heuristic extraction + vector recall + working memory. Recommended for local models (e.g. qwen3.5:9b via Ollama) to reduce latency.
Quickly check your environment, dependencies, configuration, and database status:
npm run doctor
# or: npx brain-memory-doctor
Checks: Node.js version, dependency installation, LLM/Embedding config, database file/schema version/table stats, WAL/SHM residual files.
brain-memory uses 8 memory categories to cover all valuable conversation information:
| ๐ท๏ธ Category | ๐ Meaning | ๐ก Example |
|---|---|---|
profile |
User identity / role / background | "User is a full-stack engineer" |
preferences |
Likes / dislikes / habits | "User prefers concise replies" |
entities |
Projects / tools / environments | "Project uses SQLite" |
events |
Errors / exceptions that occurred | "Docker port conflict" |
tasks |
Completed tasks / discussion topics | "Implement memory system" |
skills |
Reusable procedures (how-to) | "npm install command" |
cases |
Case experience (success / failure) | "Check port before deploying" |
patterns |
Cross-case abstract patterns | "Checking port before deploy is a general rule" |
| ๐ Mode | ๐ Description | ๐ฏ Use Case |
|---|---|---|
graph (default) |
Knowledge graph + Community + PPR | When relationship context matters |
vector |
Pure vector + BM25 + RRF | Lightweight deployment, no graph dependency |
hybrid |
Graph + vector recall in parallel fusion | Best recall quality |
๐ฏ Precise Path (graph mode):
Query โ Vector search / FTS5 โ Community expansion (distance 2) โ Graph walk (maxDepth) โ PPR ranking โ Time decay โ Return Top N
๐ Generalized Path (graph mode):
Query โ Community vector match โ Community members โ Graph walk (1 layer) โ PPR ranking โ Merge with precise path
๐ Hybrid Fusion:
Graph recall (PPR score) โโโ
โโโโ Min-Max normalization โ RRF fusion โ Sort โ Return
Vector recall (RRF score) โโโ
interface BmConfig {
// ๐ Engine mode: graph(default) | vector | hybrid
engine: 'graph' | 'vector' | 'hybrid';
// ๐ Run mode: full(default) | lite (skips LLM reflection/fusion)
mode: 'full' | 'lite';
engine: 'graph' | 'vector' | 'hybrid';
// ๐พ Storage backend: sqlite(default) | lancedb
storage: 'sqlite' | 'lancedb';
// ๐ Database path
dbPath: string;
// ๐๏ธ Session compression turn count
compactTurnCount: number;
// ๐ Recall settings
recallMaxNodes: number; // default: 6
recallMaxDepth: number; // default: 2
recallStrategy: 'full' | 'summary' | 'adaptive' | 'off';
// ๐ค LLM settings
llm: {
apiKey?: string;
baseURL?: string;
model?: string;
};
// ๐ข Embedding settings
embedding: {
apiKey?: string;
baseURL?: string;
model?: string;
dimensions?: number;
};
// ๐ Dedup threshold
dedupThreshold: number; // default: 0.90
// ๐ PageRank settings
pagerankDamping: number; // default: 0.85
pagerankIterations: number; // default: 20
// โณ Decay settings
decay: {
enabled: boolean; // default: false
recencyHalfLifeDays: number; // default: 30
recencyWeight: number; // default: 0.4
frequencyWeight: number; // default: 0.3
intrinsicWeight: number; // default: 0.3
timeDecayHalfLifeDays: number; // default: 60
betaCore: number; betaWorking: number; betaPeripheral: number;
coreDecayFloor: number; workingDecayFloor: number; peripheralDecayFloor: number;
};
// ๐ Noise filter
noiseFilter: {
enabled: boolean; // default: true
minContentLength: number; // default: 10
};
// ๐ญ Reflection
reflection: {
enabled: boolean; // default: true
turnReflection: boolean; // default: false
sessionReflection: boolean; // default: true
safetyFilter: boolean; // default: true
maxInsights: number; // default: 8
importanceBoost: number; // default: 0.15
minConfidence: number; // default: 0.6
};
// ๐ง Working memory
workingMemory: {
enabled: boolean; // default: true
maxTasks: number; // default: 3
maxDecisions: number; // default: 5
maxConstraints: number; // default: 5
};
// ๐ Knowledge fusion
fusion: {
enabled: boolean; // default: true
similarityThreshold: number; // default: 0.75
minNodes: number; // default: 20
minCommunities: number; // default: 3
};
// ๐งฉ Reasoning
reasoning: {
enabled: boolean; // default: true
maxHops: number; // default: 2
maxConclusions: number; // default: 3
minRecallNodes: number; // default: 3
};
}
The unified context engine โ main entry point for all features.
class ContextEngine {
// ๐ Process conversation turn, extract knowledge
processTurn(params: {
sessionId: string; agentId: string; workspaceId: string;
messages: Array<{ role: string; content: string }>;
}): Promise<{
extractedNodes: BmNode[]; extractedEdges: BmEdge[];
reflections: ReflectionInsight[]; workingMemory: WorkingMemoryState;
}>;
// ๐ Recall relevant memories
recall(query: string, sessionId?: string, agentId?: string, workspaceId?: string): Promise<RecallResult>;
// ๐ Knowledge fusion (merge duplicate nodes)
performFusion(sessionId?: string): Promise<FusionResult>;
// ๐ญ Session reflection
reflectOnSession(sessionId: string, messages: Array<{ role: string; content: string }>): Promise<ReflectionInsight[]>;
// ๐งฉ Reasoning engine
performReasoning(query?: string): Promise<ReasoningConclusion[]>;
// ๐ Maintenance (dedup + PageRank + community detection)
runMaintenance(): Promise<void>;
// ๐ง Working memory context
getWorkingMemoryContext(): string | null;
// ๐ Node search
searchNodes(query: string, limit?: number): BmNode[];
// ๐ Statistics (enhanced in v0.2.0)
getStats(): EngineStats; // nodes by type/status/source, communities, vectors, dbSizeBytes, schemaVersion, uptimeMs, embedCache, queryTimeMs
// ๐ฉบ Health check (new in v0.2.0)
healthCheck(): HealthStatus; // overall status, component status (db/llm/embedding), stats, uptime, schemaVersion
// โ Close database
close(): void;
}
brain-memory uses SQLite with 6 tables + FTS5 full-text index:
| ๐ Table | ๐ Purpose | ๐ Key Fields |
|---|---|---|
bm_nodes |
Memory nodes | id, type, category, name, content, pagerank, importance, scope_* |
bm_edges |
Knowledge edges | from_id, to_id, type, instruction, condition |
bm_vectors |
Vector embeddings | node_id(FK), embedding(BLOB), hash |
bm_messages |
Conversation messages | session_id, turn_index, role, content, extracted |
bm_communities |
Community summaries | id, summary, node_count, embedding |
bm_nodes_fts |
FTS5 index | name, description, content (auto-synced via triggers) |
| ๐ก๏ธ Feature | ๐ Description |
|---|---|
| Parameterized SQL | All DB operations use ? placeholders โ no SQL injection |
| Scope Isolation | Memory isolated by session / agent / workspace with cross-scope authorization |
| Prompt Injection Protection | 6-rule safety filter on reflection content (ignore-instruction / key-leak / role-switch / HTML-inject / role-prefix / disable-safety) |
| Input Validation | Strict validation on node types / edge types / memory categories |
npm test
Comprehensive test coverage (v1.5.0):
# Build the project
npm run build
# Clean build artifacts
npm run clean
# Run linting
npm run lint
# Generate API docs
npm run docs
brain-memory/
โโโ src/ # Source code
โ โโโ store/ # Database operations (CRUD + FTS5 + vectors)
โ โโโ extractor/ # Knowledge extraction (LLM node/edge extraction)
โ โโโ recaller/ # Dual-path recall engine
โ โโโ retriever/ # Hybrid recall / Vector recall / Reranker / Admission control
โ โโโ reasoning/ # Reasoning engine
โ โโโ reflection/ # Reflection system
โ โโโ fusion/ # Knowledge fusion & dedup
โ โโโ decay/ # Weibull forgetting algorithm
โ โโโ scope/ # Multi-scope isolation
โ โโโ temporal/ # Temporal classification (static/dynamic)
โ โโโ noise/ # Noise filtering
โ โโโ working-memory/ # Working memory management
โ โโโ format/ # Context formatting & assembly
โ โโโ engine/ # Core engines (LLM + Embedding + ContextEngine)
โ โโโ graph/ # Graph algorithms (PageRank / Community / Dedup / Maintenance)
โ โโโ preferences/ # Preference slot extraction
โ โโโ session/ # Session compression
โ โโโ plugin/ # OpenClaw plugin interfaces
โ โโโ utils/ # Utilities (JSON / Similarity / Text / XML)
โ
โโโ test/ # Test files
โ โโโ *.test.ts # Unit tests
โ โโโ integration/ # Integration tests
โ
โโโ docs/ # Documentation
โโโ scripts/ # Configuration scripts
โโโ openclaw-*.ts # OpenClaw plugin entry points
โโโ index.ts # Module export entry
,
MIT ยท See CHANGELOG.md for full release history.
Made with โค๏ธ for AI Agents