当前位置: 首页 > Skill >

BrainX V5 — The First Brain for OpenClaw

BrainX V5 — The First Brain for OpenClaw

BrainX V5 — The First Brain for OpenClaw

向量记忆引擎,基于 PostgreSQL + pgvector + OpenAI 嵌入。存储、搜索并将上下文记忆注入 LLM 提示,支持自动注入...

0.3.5 2026.11.21 983
获取Skill文件查看使用说明
作 者:沈言 许可证: 更新时间:2026.11.21
本文目录展开

BrainX V5 — The First Brain for OpenClaw

Persistent memory system using vector embeddings for contextual retrieval in AI agents.

37 Features

# Feature Description
1 ✅ Production Active on 32 agent profiles with centralized shared memory (2,400+ memories)
2 🧠 Auto-Learning Learns on its own from every conversation without human intervention
3 💾 Persistent Memory Remembers across sessions — PostgreSQL + pgvector
4 🤝 Shared Memory All agents share the same knowledge pool
5 💉 Automatic Briefing Personalized context injection at each agent startup
6 🔎 Semantic Search Searches by meaning, not exact keywords
7 🏷️ Intelligent Classification Auto-typed: facts, decisions, learnings, gotchas, notes
8 📊 Usage-Based Prioritization Hot/warm/cold tiers — automatic promote/degrade based on access
9 🤝 Cross-Agent Learning Propagates important gotchas and learnings across all agents
10 🔄 Anti-Duplicates Semantic deduplication by cosine similarity with intelligent merge
11 ⚡ Anti-Contradictions Detects contradictory memories and supersedes the obsolete one
12 📋 Session Indexing Searches past conversations (30-day retention)
13 🔒 PII Scrubbing Automatic redaction of sensitive data before storage
14 🔮 Pattern Detection Detects recurring patterns and promotes them automatically
15 🛡️ Disaster Recovery Full backup/restore (DB + configs + hooks + workspaces)
16 ⭐ Quality Scoring Evaluates memory quality and promotes only what deserves to persist
17 ⚙️ Fact Extraction Regex + LLM pipelines capture both operational facts and nuanced learnings
18 📦 Context Packs Weekly project packs and bootstrap topic files for fast situational awareness
19 📈 Telemetry Query logs, injection metrics, and health monitoring built in
20 🧵 Supersede Chains Old memories can be replaced cleanly without losing history
21 🌀 Memory Distillation Consolidates raw logs into higher-signal memories over time
22 🛡️ Pre-Action Advisory Queries past mistakes before high-risk tool execution
23 👤 Agent Profiles Per-agent hook injection: boosts/filters memories by agent role
24 🔀 Cross-Agent Injection Slots Hook reserves 30% of context slots for other agents' memories
25 📊 Metrics Dashboard CLI dashboard with top patterns, memory stats, and usage trends
26 🔧 Doctor & Auto-Fix Schema integrity check + automatic repair of detected issues
27 👍 Memory Feedback Mark memories as useful/useless/incorrect to refine quality
28 🗺️ Trajectory Recording Records problem→solution paths for future reference
29 📝 Learning Details Extended metadata extraction for learnings and gotchas
30 🔄 Lifecycle Management Automatic promotion/degradation of memories by age and usage
31 📥 Workspace Import Imports existing MEMORY.md files from all workspaces into the brain
32 🧪 Eval Dataset Generation Generates evaluation datasets from real memories for quality testing
33 🏗️ Session Snapshots Captures full agent state at session close for analysis
34 🧹 Low-Signal Cleanup Automatic cleanup of low-value, outdated, or redundant memories
35 🔃 Memory Reclassification Reclassifies memories with correct types and categories post-hoc
36 🔄 Auto-Promotion Pipeline Detects high-recurrence patterns and promotes them as rules in workspace files automatically
37 📊 15-Step Daily Pipeline Consolidated daily pipeline: bootstrap, lifecycle, distiller, harvester, bridge, auto-distiller, consolidation, cross-agent, contradiction, md-harvester, error-harvester, auto-promoter, promotion-applier, memory-enforcer, audit

When to Use

✅ USE when:

  • An agent needs to "remember" information from previous sessions
  • You want to give additional context to an LLM about past actions
  • You need semantic search by content
  • You want to store important decisions with metadata

❌ DON'T USE when:

  • Ephemeral information that doesn't need persistence
  • Structured tabular data (use a regular DB)
  • Simple cache (use Redis or in-memory)

Auto-Injection (Hook)

BrainX V5 includes an OpenClaw hook that automatically injects relevant memories when an agent starts.

Production Validation Status

Real validation completed on 2026-03-18:

  • Global hook enabled in ~/.openclaw/openclaw.json
  • Managed hook synced with ~/.openclaw/skills/brainx-v5/hook/ (handler.js re-synced)
  • Active physical database: brainx_v5
  • agent-profiles.json expanded from 10 to 32 profiles (all agents)
  • Cross-agent injection slots (30%) activated in production
  • 20 null embeddings regenerated + 17 duplicate pairs deduped via brainx fix
  • 2 pending migrations applied
  • Doctor: 18/18 passed, 0 warnings
  • Real bootstrap smoke test passed for 10 agents
  • Expected evidence confirmed:
    • <!-- BRAINX:START --> block written into MEMORY.md
    • Updated: timestamp present
    • Fresh row recorded in brainx_pilot_log

If this validation becomes stale, rerun a bootstrap smoke test before assuming runtime is still healthy.

How it works:

  1. agent:bootstrap event → Hook fires automatically
  2. PostgreSQL query → Fetches hot/warm recent memories
  3. Generates file → Creates BRAINX_CONTEXT.md in the workspace
  4. Agent reads → File is loaded as initial context

Configuration:

In ~/.openclaw/openclaw.json:

{
  "hooks": {
    "internal": {
      "enabled": true,
      "entries": {
        "brainx-auto-inject": {
          "enabled": true,
          "limit": 5,
          "tier": "hot+warm",
          "minImportance": 5
        }
      }
    }
  }
}

Per-agent setup:

Add to AGENTS.md in each workspace:

## Every Session

1. Read `SOUL.md`
2. Read `USER.md`
3. Read `brainx.md`
4. Read `BRAINX_CONTEXT.md` ← Auto-injected context

Available Tools

brainx_add_memory

Saves a memory to the vector brain.

Parameters:

  • content (required) — Memory text
  • type (optional) — Type: note, decision, action, learning (default: note)
  • context (optional) — Namespace/scope
  • tier (optional) — Priority: hot, warm, cold, archive (default: warm)
  • importance (optional) — Importance 1-10 (default: 5)
  • tags (optional) — Comma-separated tags
  • agent (optional) — Name of the agent creating the memory

Example:

brainx add --type decision --content "Use embeddings 3-small to reduce costs" --tier hot --importance 9 --tags config,openai

brainx_search

Searches memories by semantic similarity.

Parameters:

  • query (required) — Search text
  • limit (optional) — Number of results (default: 10)
  • minSimilarity (optional) — Threshold 0-1 (default: 0.3)
  • minImportance (optional) — Filter by importance 0-10
  • tier (optional) — Filter by tier
  • context (optional) — Exact context filter

Example:

brainx search --query "API configuration" --limit 5 --minSimilarity 0.5

Returns: JSON with results.

brainx_inject

Gets memories formatted for direct injection into LLM prompts.

Parameters:

  • query (required) — Search text
  • limit (optional) — Number of results (default: 10)
  • minImportance (optional) — Filter by importance
  • tier (optional) — Tier filter (default: hot+warm)
  • context (optional) — Context filter
  • maxCharsPerItem (optional) — Truncate content (default: 2000)

Example:

brainx inject --query "what decisions were made about openai" --limit 3

Returns: Formatted text ready for injection:

[sim:0.82 imp:9 tier:hot type:decision agent:coder ctx:openclaw]
Use embeddings 3-small to reduce costs...

---

[sim:0.71 imp:8 tier:hot type:decision agent:support ctx:brainx]
Create SKILL.md for OpenClaw integration...

brainx_health

Verifies BrainX is operational.

Parameters: none

Example:

brainx health

Returns: PostgreSQL + pgvector connection status.

Backup and Recovery

Create Backup

./scripts/backup-brainx.sh ~/backups

Creates brainx-v5_backup_YYYYMMDD_HHMMSS.tar.gz containing:

  • Full PostgreSQL database (SQL dump)
  • OpenClaw configuration (hooks, .env)
  • Skill files
  • Workspace documentation

Restore Backup

./scripts/restore-brainx.sh backup.tar.gz --force

Fully restores BrainX V5 including:

  • All memories (with embeddings)
  • Hook configuration
  • Environment variables

Full Documentation

See RESILIENCE.md for:

  • Complete disaster scenarios
  • Migration to new VPS
  • Troubleshooting
  • Automatic backup configuration

Configuration

Environment Variables

# Required
DATABASE_URL=postgresql://user:pass@host:5432/brainx_v5
OPENAI_API_KEY=sk-...

# Optional
OPENAI_EMBEDDING_MODEL=text-embedding-3-small
OPENAI_EMBEDDING_DIMENSIONS=1536
BRAINX_INJECT_DEFAULT_TIER=hot+warm
BRAINX_INJECT_MAX_CHARS_PER_ITEM=2000
BRAINX_INJECT_MAX_LINES_PER_ITEM=80

Database Setup

# Schema is in ~/.openclaw/skills/brainx-v5/sql/
# Requires PostgreSQL with pgvector extension

psql $DATABASE_URL -f ~/.openclaw/skills/brainx-v5/sql/v3-schema.sql

Direct Integration

You can also use the unified wrapper that reads the API key from OpenClaw:

cd ~/.openclaw/skills/brainx-v5
./brainx add --type note --content "test"
./brainx search --query "test"
./brainx inject --query "test"
./brainx health

Compatibility: ./brainx-v5 and ./brainx-v5-cli also work as aliases for the main wrapper.

Advisory System (Pre-Action Check)

BrainX includes an advisory system that queries relevant memories, trajectories, and recurring patterns before executing high-risk tools. Helps agents avoid repeating past mistakes.

High-Risk Tools

The following tools automatically trigger advisory checks: exec, deploy, railway, delete, rm, drop, git push, git force-push, migration, cron, message send, email send.

CLI Usage

# Check for advisories before a tool execution
./brainx-v5 advisory --tool exec --args '{"command":"rm -rf /tmp/old"}' --agent coder --json

# Quick check via helper script
./scripts/advisory-check.sh exec '{"command":"rm -rf /tmp/old"}' coder

Agent Integration (Manual)

Since only agent:bootstrap is supported as a hook event, agents should manually call brainx advisory before high-risk tools:

# In agent SKILL.md or AGENTS.md, add:
# Before exec/deploy/delete/migration, run:
cd ~/.openclaw/skills/brainx-v5 && ./scripts/advisory-check.sh <tool> '<args_json>' <agent>

The advisory returns relevant memories, similar past problem→solution paths, and recurring patterns with a confidence score. It's informational — never blocking.

Agent-Aware Hook Injection

The agent:bootstrap hook uses agent profiles (hook/agent-profiles.json) to customize memory injection per agent:

  • coder: Boosts gotcha/error/learning memories; filters by infrastructure/code/deploy/github contexts; excludes notes
  • writer: Boosts decision/learning; filters by content/seo/marketing; excludes errors
  • monitor: Boosts gotcha/error; filters by infrastructure/health/monitoring
  • echo: No filtering (default behavior)

Agents not listed in the profiles file get the default unfiltered injection. Edit hook/agent-profiles.json to add new agent profiles.

Cross-Agent Memory Sharing

The hook reserves ~30% of injection slots for cross-agent memories, ensuring each agent sees relevant learnings from other agents. The cross-agent-learning.js script tags high-importance memories for cross-agent visibility without creating duplicates.

Security & Trust

This skill is flagged with "suspicious patterns" by ClawHub's automated scanner. Here's what each pattern does and why it's necessary:

Pattern File Why
child_process.execFile hook/handler.js Invokes the BrainX CLI to query memories during agent bootstrap. No arbitrary command execution.
process.env access lib/db.js, lib/openai-rag.js, lib/cli.js Reads DATABASE_URL and OPENAI_API_KEY to connect to PostgreSQL and generate embeddings. Standard for any database-backed skill.
fetch('https://api.openai.com') lib/openai-rag.js Calls OpenAI Embeddings API to generate vector representations. Single endpoint, no other network calls.
File read/write hook/handler.js Writes BRAINX_CONTEXT.md and updates MEMORY.md in the agent's workspace during bootstrap injection.

No secrets are stored in code. All credentials come from environment variables. No data leaves the system except embedding requests to OpenAI.

Notes

  • Memories are stored with vector embeddings (1536 dimensions)
  • Search uses cosine similarity
  • inject is the most useful tool for giving context to LLMs
  • Tier hot = fast access, cold/archive = long-term storage
  • Memories are persistent in PostgreSQL (independent of OpenClaw)
  • Auto-injection hook fires on every agent:bootstrap

Feature Status (Tables)

✅ All Operational

Table Function Status
brainx_memories Core: stores memories with embeddings ✅ Active (2,400+)
brainx_query_log Tracks search/inject queries ✅ Active
brainx_pilot_log Tracks auto-inject per agent ✅ Active
brainx_context_packs Pre-generated context packages ✅ Active
brainx_patterns Detects recurring errors/issues ✅ Active
brainx_session_snapshots Captures state at session close ✅ Active
brainx_learning_details Extended metadata for learning/gotcha memories ✅ Active
brainx_trajectories Records problem→solution paths ✅ Active

8/8 tables operational. Population scripts implemented 2026-03-06.

Full Feature Inventory (35)

CLI Core (brainx <cmd>)

# Command Function
1 add Save memory (7 types, 20+ categories, V5 metadata)
2 search Semantic search by cosine similarity
3 inject Formatted memories for LLM prompt injection
4 fact / facts Shortcut to save/list infrastructure facts
5 resolve Mark pattern as resolved/promoted/wont_fix
6 promote-candidates Detect memories eligible for promotion
7 lifecycle-run Degrade/promote memories by age/usage
8 metrics Metrics dashboard and top patterns
9 doctor Full diagnostics (schema, integrity, stats)
10 fix Auto-repair issues detected by doctor
11 feedback Mark memory as useful/useless/incorrect
12 health PostgreSQL + pgvector connection status

Processing Scripts (scripts/)

# Script Function
13 memory-bridge.js Syncs memory between sessions/agents
14 memory-distiller.js Distills sessions into new memories
15 session-harvester.js Harvests info from past sessions
16 session-snapshot.js Captures state at session close
17 pattern-detector.js Detects recurring errors/issues
18 learning-detail-extractor.js Extracts metadata from learnings/gotchas
19 trajectory-recorder.js Records problem→solution paths
20 fact-extractor.js Extracts facts from conversations
21 contradiction-detector.js Detects contradicting memories
22 cross-agent-learning.js Shares learnings between agents
23 quality-scorer.js Scores memory quality
24 context-pack-builder.js Generates pre-built context packages
25 reclassify-memories.js Reclassifies memories with correct types/categories
26 cleanup-low-signal.js Cleans up low-value memories
27 dedup-supersede.js Detects and marks duplicates
28 eval-memory-quality.js Evaluates dataset quality
29 generate-eval-dataset-from-memories.js Generates evaluation dataset
30 memory-feedback.js Per-memory feedback system
31 import-workspace-memory-md.js Imports from workspace MEMORY.md files
32 migrate-v2-to-v3.js Schema migration V2→V3
33 promotion-applier.js Last-mile auto-promotion: distills patterns via LLM and writes rules to workspace files

Hooks and Infrastructure

# Component Function
34 brainx-auto-inject Auto-injection hook at each agent bootstrap
35 backup-brainx.sh Full backup (DB + config + skills)
36 restore-brainx.sh Full restore from backup
37 promotion-applier.js Pipeline step 13: writes promoted patterns to workspace files

V5 Metadata

  • sourceKind — Origin: user_explicit, agent_inference, tool_verified, llm_distilled, etc.
  • sourcePath — Source file/URL
  • confidence — Score 0-1
  • expiresAt — Automatic expiration
  • sensitivity — normal/sensitive/restricted
  • Automatic PII scrubbing (BRAINX_PII_SCRUB_ENABLED)
  • Similarity-based dedup (BRAINX_DEDUPE_SIM_THRESHOLD)

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,018
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,013
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,013
Skill 文件
  • SKILL.md
    • BrainX V5 — The First Brain for OpenClaw
    • 37 Features
    • When to Use
    • Auto-Injection (Hook)
      • Production Validation Status
      • How it works:
      • Configuration:
      • Per-agent setup:
    • Available Tools
      • brainx_add_memory
      • brainx_search
      • brainx_inject
      • brainx_health
    • Backup and Recovery
      • Create Backup
      • Restore Backup
      • Full Documentation
    • Configuration
      • Environment Variables
      • Database Setup
    • Direct Integration
    • Advisory System (Pre-Action Check)
      • High-Risk Tools
      • CLI Usage
      • Agent Integration (Manual)
      • Agent-Aware Hook Injection
      • Cross-Agent Memory Sharing
    • Security & Trust
    • Notes
    • Feature Status (Tables)
      • ✅ All Operational
    • Full Feature Inventory (35)
      • CLI Core (brainx <cmd>)
      • Processing Scripts (scripts/)
      • Hooks and Infrastructure
      • V5 Metadata
  • 项目或源文件

相关 Skill

更多
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。
Traditional Bone Tool Making Basics Traditional Bone Tool Making Basics Use when you need custom, durable, repairable tools like awls, needles, scrapers, harpoons, or fishing hooks made from local animal bones or antlers and comm...
音频混音工具 音频混音工具 名称:Sound Mixing Tool(标识 sound-mixing-tool) 短简介(≤60字):音乐/音效响度精确对齐 + 融合混音工作流:用 ffmpeg 两段式 loudnorm 把多组素材 LUFS 偏差压到 <0.10,再最小干预融合、导出可进引擎的独立分轨。 标签/关键词:音频混音 响度匹配 LUFS ffmpeg 游戏音频 音效设计 Wwise FMOD 分轨导出 后期处理 触发词:混音 · 响度匹配 · LUFS 对齐 · MIX 版本 · 音乐音效分轨 · 融合 · 不打架 · 不能盖住 适用场景 :游戏音频集成、影视短视频配乐、播客后期