@cloudcode-hans

Metacognitive Memory

L0~L6 six-layer cognitive memory system plugin for OpenClaw — pure sql.js WASM SQLite, zero native dependencies, cross-device portable

当前版本
v1.0.0
code-plugin社区source-linked

Metacognitive Memory — OpenClaw Plugin

L0~L6 six-layer cognitive memory system for OpenClaw agents. Pure sql.js WASM SQLite — zero native dependencies, cross-device portable, single-file portable.

OpenClaw Plugin sql.js WASM License: MIT


Why

OpenClaw agents start fresh every session. This plugin gives them a long-term, structured memory that mirrors how humans consolidate experience:

LayerNameWhat it storesWhat it's for
L0Raw CaptureUnprocessed conversation turns (role + content)Verbatim journal, the "what actually happened"
L1ExtractionTyped memories (preference / fact / decision / context / instruction) with dedup hashDistilled, reusable knowledge
L2Scene BlocksNarrative scenes (project / decision / interaction / error / growth) with background & resultCoherent episodes you can recall later
L3Cognitive GraphEntities + relations (person / project / supplier / decision / event / concept)Cross-session knowledge graph
L4Goal TreeHierarchical goals with status, blocker, priority, parent/childMulti-step plan tracking
L5Knowledge BaseVerified facts with domain, confidence, tagsSearchable, citation-ready facts
L6Self-ModelErrors, capability categories, self-diagnostics"How am I doing?" reports

Each layer is exposed as an independent tool (20 in total) so the agent can compose memory operations just like any other tool call.


Features

  • Zero native dependenciessql.js is a WASM-compiled SQLite, runs anywhere Node.js runs
  • Cross-device portable — copy the single .db file between machines and your memory travels
  • Automatic L0 capture — registers message:received, message:sent, session:patch hooks so every conversation is journaled without any extra calls
  • 20 independent tools — one per memory operation, no monolithic "remember" tool
  • Configurable extractioneveryNConversations and idleTimeoutSeconds tune when L1 fires
  • Self-diagnosticl6_self_check returns a JSON summary of error counts and capability categories
  • Per-session isolation — every row is scoped by session_id so multi-agent workloads don't mix

One-shot install (ClawHub)

# 1. Install
openclaw plugins install metacognitive-memory

# 2. Enable + register the memory slot + grant hook policy.
#    Edit ~/.openclaw/openclaw.json:
{
  "plugins": {
    "slots": {
      "memory": "metacognitive-memory"
    },
    "entries": {
      "metacognitive-memory": {
        "enabled": true,
        "hooks": {
          "allowPromptInjection": true,
          "allowConversationAccess": true
        },
        "config": {
          "stateDir": "~/.openclaw/state/metacognitive-memory",
          "everyNConversations": 3,
          "idleTimeoutSeconds": 60
        }
      }
    }
  }
}
# 3. Restart the gateway and verify
openclaw gateway restart
openclaw plugins inspect metacognitive-memory

Expected: Status: loaded, Origin: config, Registered 20 tools + 3 hooks in ~/.openclaw/logs/openclaw.log.

From source (developer / local link)

git clone <this-repo>
cd metacognitive-memory-plugin
npm install
npm run build                       # tsc → dist/
openclaw plugins install . --link  # link instead of copy; restart picks up source edits

The --link flag means dist/ edits are picked up after a gateway restart — no need to re-install.


Hook policy — why these flags matter

The two flags in entries.metacognitive-memory.hooks are not optional if you want automatic L0 capture:

  • allowConversationAccess: true — required. The plugin reads the raw inbound/outbound message bodies from message:received / message:sent events. Without it, those hooks are blocked by core's safety gate and the database stays empty.
  • allowPromptInjection: true — optional but recommended. Lets the plugin mutate prompts through typed hooks (e.g. injecting recalled context). Safe for this plugin because it only injects, never replaces.

If you'd rather not auto-capture, set allowConversationAccess: false — the 20 tools still work, you just have to call l0_capture yourself.


Configuration reference

Pass under plugins.entries.metacognitive-memory.config:

KeyTypeDefaultDescription
stateDirstringOpenClaw state dirWhere the SQLite file lives. Must be writable.
everyNConversationsnumber3Triggers L1 extraction every N captured turns
idleTimeoutSecondsnumber60Triggers L1 extraction after N seconds of inactivity

The values are read by the plugin at startup; restart the gateway to apply changes.


Storage layout

<stateDir>/
└── .metacognitive_memory/
    └── memory.db            # single-file SQLite, portable

Tables:

TableLayerPurpose
memory_l0_rawL0Raw captures (session_id, role, content, timestamp)
memory_l1_extractedL1Extracted typed memories (with dedup_hash)
memory_l2_scenesL2Scene blocks
kg_entity / kg_relationL3Knowledge graph
goalL4Goal tree (self-referential parent_id)
knowledge_factL5Verified facts (with full-text search)
self_model / error_logL6Self-diagnostics

Backup = copy memory.db. The plugin auto-saves on every write.

The .metacognitive_memory subdirectory is intentional — it lets multiple plugins share a parent stateDir without colliding.


Tools reference

All 20 tools take session_id as the primary key. L4 and L5 also expose id-based update/verify tools.

L0 — Raw Capture

ToolParameters (besides session_id)
l0_capturerole (user/assistant/system/tool), content, optional tool_name / tool_result
l0_listoptional limit (default 50)

L1 — Extraction

ToolParameters
l1_extractoptional max_memories (default 30)
l1_listoptional memory_type filter, limit

L2 — Scene Blocks

ToolParameters
l2_create_scenescene_type (project/decision/interaction/error/growth), title, optional background / decision / result
l2_list_scenesoptional scene_type filter, limit

L3 — Cognitive Graph

ToolParameters
l3_update_graph(none) — rebuilds from L1
l3_list_entitiesoptional entity_type filter
l3_list_relationsoptional from_entity_id filter

L4 — Goal Tree

ToolParameters
l4_create_goaltitle, optional description / parent_id / priority
l4_treereturns full recursive tree
l4_update_goalgoal_id, optional status / blocker / priority
l4_delete_goalgoal_id — cascades to children

L5 — Knowledge Base

ToolParameters
l5_add_factdomain, fact_text, optional confidence / tags[]
l5_searchquery, optional limit
l5_verify_factfact_id
l5_list_factsoptional domain filter
l5_delete_factfact_id

L6 — Self-Model

ToolParameters
l6_log_errorerror_type (sql/config/logic/tool/recall), summary, optional detail / stack_trace
l6_self_checkreturns { errorStats, capCategories, recentErrors }

Validation workflow

After install, run these to confirm everything works:

# 1. Plugin loaded
openclaw plugins inspect metacognitive-memory
#   → Status: loaded

# 2. Gateway registered tools
openclaw gateway restart
grep "metacognitive-memory" ~/.openclaw/logs/openclaw.log | tail
#   → "[metacognitive-memory] Registered 20 tools + 3 hooks"

# 3. DB is created on first call
ls -la ~/.openclaw/state/metacognitive-memory/.metacognitive_memory/memory.db

# 4. Quick end-to-end smoke test from a node REPL
node -e "
import('metacognitive-memory-plugin').then(async (m) => {
  const core = new m.MetaCore({ stateDir: '~/.openclaw/state/metacognitive-memory/.metacognitive_memory' });
  await core.initialize();
  const id = core.l0Capture({ sessionId: 'smoke', role: 'user', content: 'hello' });
  console.log('L0 row:', id);
  console.log('L0 list:', core.l0List('smoke').length, 'rows');
  await core.close();
});
"

Common pitfalls

SymptomCauseFix
0 tools registeredHook policy blocks allowConversationAccessSet both allowPromptInjection and allowConversationAccess to true
stateDir ignoredPath doesn't exist or isn't writablePre-create it; check permissions
Empty databasemessage:received hook never firedConfirm stateDir is set; check ~/.openclaw/logs/openclaw.log for [metacognitive-memory] lines
Conflict with active-memory / memory-core / memory-wikiMemory slot already takenSet plugins.slots.memory to metacognitive-memory (or "none" to disable) — see OpenClaw memory slots
EACCES on memory.dbMultiple gateway processes on the same stateDirPick one owner; or set a per-process stateDir

Architecture

metacognitive-memory-plugin/
├── openclaw.plugin.json     # manifest: 20 contract tool names + configSchema
├── package.json             # npm + openclaw.extensions + peer dep
├── tsconfig.json            # portable: no absolute paths
├── src/
│   ├── index.ts             # default entry: definePluginEntry + 20 tools + 3 hooks
│   ├── plugin-entry.ts      # alt entry with the same surface (used by some loaders)
│   ├── core/
│   │   ├── types.ts         # L0~L6 shared types
│   │   ├── meta-core.ts     # L0~L6 orchestration facade
│   │   └── store.ts         # sql.js SQLite store (schema + queries)
│   ├── adapters/openclaw/
│   │   └── host-adapter.ts  # stateDir resolution (config → runtime → default)
│   └── types/
│       └── openclaw-plugin-sdk.d.ts   # ambient shim for `openclaw/plugin-sdk/core`
└── dist/                    # build output (npm `files` includes this)

Data flow

message:received ─┐
message:sent     ─┼─→ l0Capture ─→ memory_l0_raw
session:patch    ─┘
                                  │
                          everyNConversations / idleTimeout
                                  │
                                  ▼
                            l1Extract ─→ memory_l1_extracted
                                  │
                  ┌───────────────┼───────────────┐
                  ▼               ▼               ▼
            l2CreateScene   l3UpdateGraph   l5AddFact
                  │               │               │
                  ▼               ▼               ▼
        memory_l2_scenes  kg_entity/kg_rel  knowledge_fact
                                  │
                                  ▼
                            l4CreateGoal ─→ goal
                                  │
                                  ▼
                       l6_log_error / l6_self_check
                                  │
                                  ▼
                            error_log

Development

npm install              # one-time
npm run build            # tsc → dist/
npm run build:watch      # rebuild on save

# Type-check only
npx tsc --project tsconfig.json --noEmit

# Validate the dist entry OpenClaw will load
openclaw plugins validate --entry ./dist/index.js

# Run unit tests
npm test

To work on a live OpenClaw instance:

openclaw plugins install . --link   # link mode
# ...edit src/...
npm run build                       # rebuild dist/
openclaw gateway restart            # pick up new dist/

Memory type reference

L1 Memory Types: preference · fact · decision · context · instruction

L2 Scene Types: project · decision · interaction · error · growth

L3 Entity Types: person · project · supplier · decision · event · concept

L4 Goal Status: pending · in_progress · blocked · done · cancelled

L6 Error Types: sql_error · config_error · logic_error · tool_error · recall_error


Compatibility

  • OpenClaw >= 2026.5.17
  • Node.js >= 22.16.0 (sql.js WASM requires modern Node)
  • No native build step; works on Windows / macOS / Linux identically

License

MIT

源码与版本

源码仓库

cloudcode-hans/metacognitive-memory-plugin

打开仓库

源码提交

e6e35a7b3c4d8f5a1b2c3d4e5f607a8b9c0d1e2f

查看提交

安装命令

openclaw plugins install clawhub:@cloudcode-hans/metacognitive-memory

元数据

  • 包名: @cloudcode-hans/metacognitive-memory
  • 创建时间: 2026/06/08
  • 更新时间: 2026/06/08
  • 执行代码:
  • 源码标签: e6e35a7b3c4d8f5a1b2c3d4e5f607a8b9c0d1e2f

兼容性

  • 构建于 OpenClaw: 2026.6.1
  • 插件 API 范围: >=2026.5.17
  • 标签: latest
  • 文件数: 36