Skill: guohongbin-git/memory-sync-cn (version 1.0.0)

--- name: memory-sync-cn description: 记忆同步系统 - 自动同步 MEMORY.md 与 CortexGraph，支持遗忘曲线和智能检索 metadata: openclaw: emoji: "🧠" requires: bins: ["cortexgraph", "mcporter"] install: - id: cortexgraph kind: python package: cortexgraph bins: ["cortexgraph"] label: "Install CortexGraph (Python)" - id: mcporter kind: node package: mcporter bins: ["mcporter"] label: "Install mcporter (Node.js)" --- # 记忆同步系统 自动同步 OpenClaw 记忆系统与 CortexGraph（带遗忘曲线）。 ## 架构 ``` MEMORY.md (长期记忆) ↕ CortexGraph (智能层) ↕ memory/YYYY-MM-DD.md (每日日志) ``` ## 同步脚本 ### 1. 导入 MEMORY.md 到 CortexGraph ```bash # 运行同步 ./scripts/sync-memory.sh ``` ### 2. 导入每日日志 ```bash # 同步今天的日志 ./scripts/sync-daily.sh # 同步指定日期 ./scripts/sync-daily.sh 2026-02-18 ``` ### 3. 晋升高价值记忆 ```bash # 查看晋升候选 mcporter call cortexgraph.promote_memory auto_detect=true dry_run=true # 执行晋升 mcporter call cortexgraph.promote_memory auto_detect=true ``` ## CortexGraph 工具 ### 核心操作 ```bash # 保存记忆 mcporter call cortexgraph.save_memory content="..." tags='["tag1"]' entities='["Entity1"]' # 搜索记忆 mcporter call cortexgraph.search_memory query="关键词" top_k=5 # 强化记忆（减缓衰减） mcporter call cortexgraph.touch_memory memory_id="UUID" boost_strength=true # 查看知识图谱 mcporter call cortexgraph.read_graph limit=10 ``` ### 智能分析 ```bash # 分析是否值得记住 mcporter call cortexgraph.analyze_message message="用户说的话" # 分析是否需要搜索 mcporter call cortexgraph.analyze_for_recall message="用户说的话" # 自动回忆 mcporter call cortexgraph.auto_recall_process_message message="用户说的话" ``` ### 维护 ```bash # 垃圾回收（删除低分记忆） mcporter call cortexgraph.gc dry_run=true # 合并相似记忆 mcporter call cortexgraph.consolidate_memories auto_detect=true mode=preview # 生成嵌入向量 mcporter call cortexgraph.backfill_embeddings dry_run=true ``` ## 遗忘曲线算法 CortexGraph 使用 Ebbinghaus 遗忘曲线： ``` score = (use_count)^β × e^(-λ × Δt) × strength ``` - **β** = 0.6（使用频率权重） - **λ** = ln(2) / half_life（衰减常数，默认 3 天） - **strength** = 1.0-2.0（重要性） 记忆会自然衰减，除非： - 被引用（touch_memory） - 被搜索到（auto_recall） - 晋升到长期记忆（promote_memory） ## 配置 编辑 `~/.config/cortexgraph/.env`： ```env # 存储路径 CORTEXGRAPH_STORAGE_PATH=~/.config/cortexgraph/jsonl # 衰减参数 CORTEXGRAPH_DECAY_MODEL=power_law CORTEXGRAPH_PL_HALFLIFE_DAYS=3.0 # 阈值 CORTEXGRAPH_FORGET_THRESHOLD=0.05 CORTEXGRAPH_PROMOTE_THRESHOLD=0.65 # 长期记忆（Obsidian） LTM_VAULT_PATH=~/Documents/Obsidian/Vault ``` ## 使用场景 ### 1. 对话中自动记住 ```bash # 分析消息 mcporter call cortexgraph.analyze_message message="用户说..." # 如果 should_save=true，则保存 ``` ### 2. 对话中自动回忆 ```bash # 分析消息 mcporter call cortexgraph.analyze_for_recall message="用户问..." # 如果 should_search=true，则搜索 ``` ### 3. 定期维护 ```bash # 每周运行 mcporter call cortexgraph.gc mcporter call cortexgraph.consolidate_memories auto_detect=true mode=apply ``` ## 与 OpenClaw 集成 CortexGraph 已通过 mcporter 配置： ```json // ~/.openclaw/workspace/config/mcporter.json { "cortexgraph": { "command": "/home/ghb/.local/bin/cortexgraph", "description": "Temporal memory system for AI with Ebbinghaus forgetting curve" } } ``` ## 最佳实践 1. **重要信息 strength=1.5-2.0**（用户偏好、关键决策） 2. **普通信息 strength=1.0**（日常对话） 3. **临时信息 strength=0.5**（上下文相关） 4. **每周维护**：GC + 合并 + 晋升 5. **每月检查**：调整衰减参数 --- *版本: 1.0.0* *作者: 赚钱小能手*

path: README.md
content: # Memory Sync CN

记忆同步系统 - 自动同步 OpenClaw 记忆系统与 CortexGraph。

## 功能

- 🔄 **双向同步**: MEMORY.md ↔ CortexGraph
- 🧠 **遗忘曲线**: 基于 Ebbinghaus 的智能记忆管理
- 📊 **自动晋升**: 高价值记忆自动升级到长期存储
- 🔍 **智能检索**: 语义搜索 + 衰减评分

## 安装

```bash
# 安装 CortexGraph
uv tool install cortexgraph

# 安装 mcporter
npm install -g mcporter

# 配置 CortexGraph
mcporter config add cortexgraph --command "$(which cortexgraph)"
```

## 使用

### 同步 MEMORY.md

```bash
./scripts/sync-memory.sh
```

### 同步每日日志

```bash
# 今天
./scripts/sync-daily.sh

# 指定日期
./scripts/sync-daily.sh 2026-02-18
```

### 晋升高价值记忆

```bash
./scripts/promote-to-memory-md.sh
```

## CortexGraph 工具

```bash
# 保存记忆
mcporter call cortexgraph.save_memory content="..." tags='["tag1"]'

# 搜索记忆
mcporter call cortexgraph.search_memory query="关键词"

# 强化记忆
mcporter call cortexgraph.touch_memory memory_id="UUID"

# 查看图谱
mcporter call cortexgraph.read_graph
```

## 架构

```
┌─────────────┐
│  MEMORY.md  │ ← 长期记忆（手动维护）
└──────┬──────┘
       │ sync
       ↓
┌─────────────┐
│ CortexGraph │ ← 智能层（自动衰减）
└──────┬──────┘
       │ sync
       ↓
┌─────────────┐
│  daily.log  │ ← 每日日志（自动导入）
└─────────────┘
```

## 配置

编辑 `~/.config/cortexgraph/.env`:

```env
CORTEXGRAPH_STORAGE_PATH=~/.config/cortexgraph/jsonl
CORTEXGRAPH_DECAY_MODEL=power_law
CORTEXGRAPH_PL_HALFLIFE_DAYS=3.0
CORTEXGRAPH_FORGET_THRESHOLD=0.05
CORTEXGRAPH_PROMOTE_THRESHOLD=0.65
```

## 许可证

MIT


path: package.json
content: {
  "name": "memory-sync-cn",
  "version": "1.0.0",
  "description": "记忆同步系统 - 自动同步 MEMORY.md 与 CortexGraph，支持遗忘曲线和智能检索",
  "scripts": {
    "sync": "./scripts/sync-memory.sh",
    "sync:daily": "./scripts/sync-daily.sh",
    "promote": "./scripts/promote-to-memory-md.sh"
  },
  "keywords": ["memory", "cortexgraph", "openclaw", "sync"],
  "author": "money-maker-ai"
}


path: scripts/promote-to-memory-md.sh
content: #!/bin/bash
# promote-to-memory-md.sh - 将 CortexGraph 高分记忆导出到 MEMORY.md
# 用法: ./promote-to-memory-md.sh [--dry-run]

set -e

DRY_RUN="${1:-}"
MEMORY_FILE="$HOME/.openclaw/workspace/MEMORY.md"

echo "🧠 晋升高价值记忆 → MEMORY.md"

# 获取高分记忆（score > 1.5，用得多的）
echo "  📊 查询高分记忆..."

RESULT=$(mcporter call cortexgraph.search_memory \
    query="important preference decision strategy" \
    min_score=0.5 \
    top_k=20 \
    --json 2>/dev/null || echo '{"results":[]}')

# 解析结果
echo "$RESULT" | python3 -c "
import json
import sys

data = json.load(sys.stdin)
results = data.get('results', [])

for r in results:
    content = r.get('content', '')
    score = r.get('score', 0)
    tags = ', '.join(r.get('tags', []))
    use_count = r.get('use_count', 0)
    
    print(f'### 📍 Score: {score:.2f} | Uses: {use_count} | Tags: {tags}')
    print(f'{content}')
    print()
"

echo ""
echo "---"
echo "💡 以上是高价值记忆候选"
echo ""
echo "手动操作："
echo "1. 检查内容是否值得加入 MEMORY.md"
echo "2. 编辑 MEMORY.md 添加相关内容"
echo "3. 运行: mcporter call cortexgraph.promote_memory memory_id=UUID"
echo ""
echo "自动晋升（谨慎）："
if [[ "$DRY_RUN" != "--dry-run" ]]; then
    read -p "是否自动晋升高分记忆? [y/N] " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        mcporter call cortexgraph.promote_memory auto_detect=true
    fi
else
    echo "  [DRY RUN] 跳过自动晋升"
fi


path: scripts/sync-daily.sh
content: #!/bin/bash
# sync-daily.sh - 同步每日日志到 CortexGraph
# 用法: ./sync-daily.sh [YYYY-MM-DD] [--dry-run]

set -e

DATE="${1:-$(date +%Y-%m-%d)}"
DRY_RUN="${2:-}"
MEMORY_DIR="$HOME/.openclaw/workspace/memory"
DAILY_FILE="$MEMORY_DIR/$DATE.md"

echo "🧠 同步每日日志 → CortexGraph"
echo "   日期: $DATE"
echo "   文件: $DAILY_FILE"

if [[ ! -f "$DAILY_FILE" ]]; then
    echo "❌ 日志文件不存在: $DAILY_FILE"
    exit 1
fi

# 读取文件内容
CONTENT=$(cat "$DAILY_FILE")

# 检查是否为空
if [[ -z "${CONTENT// /}" ]]; then
    echo "⚠️  日志为空"
    exit 0
fi

# 转义内容
CONTENT_ESCAPED=$(echo "$CONTENT" | sed 's/"/\\"/g')

# 确定标签
DAY_TAG="daily-$DATE"

echo "  📌 导入每日日志 ($DATE)"

if [[ "$DRY_RUN" != "--dry-run" ]]; then
    mcporter call cortexgraph.save_memory \
        --config ~/.openclaw/workspace/config/mcporter.json \
        content="[$DATE] $CONTENT_ESCAPED" \
        tags='["daily-log","'"$DAY_TAG"'"]' \
        source="memory/$DATE.md" \
        strength=1.0
    echo "✅ 同步完成"
else
    echo "  [DRY RUN] 跳过保存"
    echo "---"
    echo "内容预览:"
    echo "$CONTENT" | head -20
fi


path: scripts/sync-memory.sh
content: #!/bin/bash
# sync-memory.sh - 同步 MEMORY.md 到 CortexGraph
# 用法: ./sync-memory.sh [--dry-run]

set -e

DRY_RUN="${1:-}"
MEMORY_FILE="$HOME/.openclaw/workspace/MEMORY.md"
TAGS='["long-term","memory-md"]'

echo "🧠 同步 MEMORY.md → CortexGraph"
echo "   源文件: $MEMORY_FILE"

if [[ ! -f "$MEMORY_FILE" ]]; then
    echo "❌ MEMORY.md 不存在"
    exit 1
fi

# 解析 MEMORY.md 的主要部分
declare -A SECTIONS
CURRENT_SECTION=""
CURRENT_CONTENT=""

while IFS= read -r line; do
    # 检测标题
    if [[ "$line" =~ ^##\ (.+)$ ]]; then
        # 保存上一个 section
        if [[ -n "$CURRENT_SECTION" && -n "$CURRENT_CONTENT" ]]; then
            SECTIONS["$CURRENT_SECTION"]="$CURRENT_CONTENT"
        fi
        CURRENT_SECTION="${BASH_REMATCH[1]}"
        CURRENT_CONTENT=""
    else
        CURRENT_CONTENT+="$line"$'\n'
    fi
done < "$MEMORY_FILE"

# 保存最后一个 section
if [[ -n "$CURRENT_SECTION" && -n "$CURRENT_CONTENT" ]]; then
    SECTIONS["$CURRENT_SECTION"]="$CURRENT_CONTENT"
fi

echo "📋 发现 ${#SECTIONS[@]} 个 section"

# 导入到 CortexGraph
for section in "${!SECTIONS[@]}"; do
    content="${SECTIONS[$section]}"
    
    # 跳过空内容
    if [[ -z "${content// /}" ]]; then
        continue
    fi
    
    # 清理内容（转义引号）
    content_escaped=$(echo "$content" | sed 's/"/\\"/g' | tr '\n' ' ' | sed 's/  */ /g')
    section_escaped=$(echo "$section" | sed 's/"/\\"/g')
    
    # 确定标签（只允许英文）
    # 映射中文 section 到英文标签
    declare -A SECTION_TAGS
    SECTION_TAGS["关于宏斌"]="about-hongbin"
    SECTION_TAGS["宏斌的硬件"]="hardware"
    SECTION_TAGS["宏斌的 API Keys"]="api-keys"
    SECTION_TAGS["我的身份"]="identity"
    SECTION_TAGS["工作原则"]="principles"
    SECTION_TAGS["搜索优先"]="search-first"
    SECTION_TAGS["发布规范"]="publish-rules"
    SECTION_TAGS["术语定义 💡"]="glossary"
    SECTION_TAGS["已发布 Skills"]="published-skills"
    SECTION_TAGS["已安装的能力增强 Skills"]="installed-skills"
    SECTION_TAGS["待发布 Skills（Rate Limit 后）"]="pending-skills"
    SECTION_TAGS["重要教训"]="lessons"
    SECTION_TAGS["撤回方法"]="withdraw-method"
    SECTION_TAGS["Moltbook 账号"]="moltbook"
    SECTION_TAGS["工作文件位置"]="files"
    SECTION_TAGS["数据驱动策略"]="data-strategy"
    
    # 获取标签，默认用 generic
    section_tag="${SECTION_TAGS[$section]:-section}"

    
    # 确定强度（重要信息更高）
    strength=1.5
    if [[ "$section" =~ "教训" || "$section" =~ "原则" || "$section" =~ "规范" ]]; then
        strength=2.0
    fi
    
    echo "  📌 导入: $section (strength=$strength)"
    
    if [[ "$DRY_RUN" != "--dry-run" ]]; then
        mcporter call cortexgraph.save_memory \
            --config ~/.openclaw/workspace/config/mcporter.json \
            content="$section_escaped: $content_escaped" \
            tags='["memory-md","'"$section_tag"'"]' \
            strength=$strength \
            source="MEMORY.md"
    else
        echo "     [DRY RUN] 跳过保存"
    fi
done

echo "✅ 同步完成"


Security scan verdicts — ClawScan: suspicious | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (HIGH)