360 Secure SkillHub
360 安全技能中心

OpenClaw Memory v4.1

这是面向单用户AI代理的轻量文件型记忆系统,零依赖仅12KB。核心分事件、知识、流程三类记忆,HOT/WARM/COLD/BUFFER四层加载,具备原子写入、自动归档、每周复盘、健康校验等10种机制。适用于AI代理跨会话记忆搭建/优化、防止记忆膨胀等场景,通过Markdown文件读写,无数据库或API依赖。

ciklopentan
ciklopentan
热度 23.40
最近更新 2026-04-05 15:26:51
分类:开发依赖:代码执行 / 读写文件应用场景:代码生成 / 自动化脚本 / 数据处理

安装技能

复制下面的话术发给你的 Agent,它会通过 secure-skills 检索并安装该技能。

执行命令安装此 skill: npx secure-skills-cli add openclaw-memory-v4
Metadata
name
openclaw-memory
description
Lightweight file-based memory system for single-user AI agents. No databases, no APIs — just markdown files with tiered loading, grep tagging, and automatic archival. Use when: (1) setting up agent memory from scratch, (2) improving existing file-based memory, (3) implementing tiered context loading (HOT/WARM/COLD), (4) adding WAL-lite writes, compaction recovery, buffer rotation, or episodic TTL, (5) preventing memory bloat, duplicate facts, or stale knowledge, (6) validating memory health (tags, freshness, invariants), (7) user mentions "memory system", "agent memory", "tiered memory", "episodic memory", "working buffer", "weekly review", "memory archive", "health check", or asks how an AI agent should remember things between sessions. Trigger on: memory setup, long-term memory for agents, context compaction recovery, persistent agent notes, file-based knowledge graph alternative.

OpenClaw Memory v4.1 (2026-04-05)

File-based 3-tier memory for single-user AI agents. ~12KB, 9 files, zero dependencies.

Core Design

3 types, 4 tiers, 10 mechanisms that fit in a terminal.

3 Types

Type What Lives
Episodic What happened memory/episodic/YYYY-MM-DD.md
Semantic What I know memory/semantic/*.md
Procedural How to do things memory/procedural/*.md

4 Tiers

Tier Files When to load
HOT MEMORY.md (≤60 lines) Every session
WARM semantic/*.md, procedural/*.md By context (grep tags)
COLD episodic/, archive/ On query
BUFFER working-buffer.md During active task

Directory Structure

MEMORY.md                          ← HOT, ≤60 lines, always loaded
├── memory/
│   ├── episodic/                  ← COLD, one per day
│   │   └── YYYY-MM-DD.md          ← events, decisions, signals
│   ├── semantic/                  ← WARM, one per domain
│   │   ├── infrastructure.md      ← IP, ports, services
│   │   ├── preferences.md         ← style, rules, habits
│   │   ├── projects.md            ← active projects
│   │   └── decisions.md           ← final decisions with why
│   ├── procedural/                ← WARM, how-to + lessons
│   │   ├── lessons-learned.md     ← post-mortems, anti-patterns
│   │   └── (other how-to files)
│   ├── working-buffer.md          ← BUFFER, active task scratchpad
│   ├── archive/YYYY/MM/           ← episodic >30 days, auto-moved
│   └── scripts/
│       ├── archive-old-episodic.sh ← TTL archiver
│       ├── atomic-write.sh         ← crash-safe file writes
│       └── health-check.sh         ← invariant validation

10 Mechanisms

1. WAL-lite — Files Before Responses

Before answering with important info (decisions, corrections, facts), write to working-buffer.md first. Then reply. Files survive restarts.

Working buffer header format (v4.1+):

# Working Buffer
created: 2026-04-05T14:31:00+08:00
last_active: 2026-04-05T14:31:00+08:00

## Active Task:
- ...

Header enables:

  • Stale detection: If last_active > 2 hours and no current session working on it → abandoned buffer
  • Compaction recovery: Distinguish current task from leftover buffer

2. Compaction Recovery

After session compaction or reset:

  1. Read MEMORY.md
  2. Read episodic for today + yesterday
  3. Read working-buffer.md (if stale, check for pending work)
  4. Resume from file contents

3. Canonical Owner Rule — Principle, Not Mechanism

Each class of fact has exactly one home. Never duplicate:

Fact type Lives in
IP, ports, services semantic/infrastructure.md
Preferences, style, rules semantic/preferences.md
Commands, how-to procedural/*.md
Events, decisions, timeline episodic/YYYY-MM-DD.md
Post-mortems, anti-patterns procedural/lessons-learned.md
Final decisions with rationale semantic/decisions.md

4. Atomic Writes

Prevent corrupted files on crash. Use dd with fsync:

# Via script:
echo "content" | bash scripts/atomic-write.sh /path/to/file.md

# Manual: tmp → fsync → mv
TMP=$(mktemp /path/to/file.md.tmp.XXXX)
dd if="$TMP" of=/path/to/file.md conv=fsync status=none && rm -f "$TMP"
# Or simpler:
cp --force "$TMP" /path/to/file.md && sync
mv is atomic on same filesystem — just ensure file is complete first.

5. Closure Blocks in Episodic

End every episodic note with 4 lines:

Updated: YYYY-MM-DD
Decisions: what was changed
Signal: what I learned about the system
Open: remaining items (or "none")

Decision = what I changed. Signal = what I learned.

6. Episodic TTL

Archive files older than N days into archive/YYYY/MM/:

bash scripts/archive-old-episodic.sh 30   # default 30

7. Buffer Rotation

When working-buffer.md exceeds 80 lines:

  1. Atomically move buffer: mv working-buffer.md "working-buffer.md.rotating"
  2. Append rotated content: cat "working-buffer.md.rotating" >> episodic/$(date +%Y-%m-%d).md
  3. On success: rm -f "working-buffer.md.rotating"
  4. On failure: mv "working-buffer.md.rotating" "working-buffer.md.pending" (preserves data)
  5. Touch new working-buffer.md with timestamp header
  6. Continue

Recovery: If working-buffer.md.pending exists, append it to episodic first. If working-buffer.md.lock exists, remove it.

Rotation is soft — if in the middle of a complex task, defer until session end.

8. Weekly Review (cron, Monday 9:00)

Automated review that:

  1. Reads episodic files from past 7 days
  2. Extracts decisions → semantic/decisions.md
  3. Extracts lessons → procedural/lessons-learned.md
  4. Runs health-check.sh — fix any FAILs
  5. Runs episodic archival (>30 days)
  6. Updates MEMORY.md freshness + open questions
  7. Clears stale working-buffer
  8. Commits all changes

If nothing meaningful changed → skip with "No meaningful changes".

9. Health Check (invariant validation)

Before important operations, run:

bash scripts/health-check.sh

9 checks: tags on line 2, frozen vocabulary, last_verified <30d, buffer <80 lines, open questions ≤5, closure blocks, Active Decisions link integrity, episodic file count, WAL integrity (no orphaned buffer entries). Returns exit code 0 if all pass, 1 if any fail.

10. Grep-Based Tag Discovery

Every WARM file has #tags: on line 2:

grep -rl "qdrant" memory/                         # all files mentioning qdrant
grep -rl "#tags:.*networking" memory/              # files tagged networking
head -2 memory/**/*.md | grep "#tags:"             # discover all tags

Emergency Procedures

If health-check.sh FAIL:

  1. Do not answer complex questions requiring memory-based decisions
  2. Tell user: "Memory integrity check failed"
  3. Fix any FAIL checks before proceeding

Tag Vocabulary (Frozen)

infrastructure: tailscale, tailnet, docker, synapse, matrix, coturn, qdrant, ubuntu, systemd, ufw, fail2ban, samba, ssh, networking, gateway, pm2 preferences: rules, style, workflow, memory, habits projects: audit, skills, security, review procedural: deepseek, puppeteer, benchmark, troubleshooting, tasks, checklist, backup, diagnostics lessons: postmortem, errors, fixes, anti-patterns

Do not invent new tags.

Friction Log

If a task takes >5 minutes of waiting/googling → note it inline with #friction: tag in the working buffer. Weekly review moves recurring friction → lessons-learned.md.

Known Limits (documented, not fixed)

  • No file locking for concurrent writes — Single writer assumed; stagger crons to avoid overlap between cron jobs and main session
  • No auto-promotion: Important signals in old episodic files don't auto-surface to semantic; relies on weekly review to catch them
  • Tag enforcement is trust-based: Health-check validates tags against frozen vocabulary, but doesn't prevent writing new tags

Safety Rules

  • trash > rm — never delete, always move
  • Atomic writes for all file modifications
  • No duplicate facts across files (Canonical Owner)
  • No credentials in episodic notes
  • Commit changes after updates
  • Weekly review validates last_verified dates

Why This Works

  • Text > brain: Files survive restarts. Mental notes don't.
  • Grep > database: No vector DB, no API, no dependency chain.
  • Small context: 60-line MEMORY.md fits in any prompt.
  • Self-maintaining: TTL archival + weekly review + health check + buffer rotation.
  • Hard to break: Atomic writes, canonical owners, frozen tags, invariant checks.

See references/design-rationale.md for the full decision trail from the 4-round AI consultation that shaped this system.