关于 cm
CM 是面向 AI 编码 Agent 的程序性记忆系统,可将会话历史转化为共享且可复用的指导。它结合手册、基于证据的学习、反馈和安全规则,并可通过 MCP 服务提供记忆能力。
主要功能
- 01检索与任务相关的规则和历史
- 02管理共享手册与反馈
- 03根据会话证据验证规则
- 04追踪置信度衰减和成熟度
- 05将反复有害的模式转为警示
- 06依据记录的风险模式防护命令
适用场景
- 01在编码任务前加载过往指导
- 02在不同 Agent 间共享经验模式
- 03查看手册规则可信度的依据
- 04阻止匹配已记录风险的命令
MCP 相关
CM 可通过 `cm serve` 作为 MCP 服务运行。它提供上下文、反馈、结果、搜索和反思工具,以及手册、日志、结果和统计资源。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ dicklesworthstone/ cass_memory_system --skill cm安装后在 Claude Code 中输入/cm确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
.gitattributesCHANGELOG.md.gitignore.ubsignoreLICENSECONTRIBUTING.mdAGENTS.mdbunfig.tomlbun.lockREADME.md.beads/config.yamldeletions.jsonl.migrated.gitignoreREADME.mdmetadata.jsononboard-v2-plan.md.cass/playbook.yaml.github/workflows/ci.ymlnotify-acfs.ymlrelease.ymlcompeting_proposal_plans/2025-12-07-gemini-gemini_-_direct_access_to_google_ai.md2025-12-07-grok-integrating_cass_into_reflective_workflows_shared_grok_conversation.mdcompeting_proposal_plans/claude_version/AGENTS.mdREADME.mdcass-reflect.tspackage.jsondocs/AGENT_NATIVE_ONBOARDING.mddocs/planning/AGENTS.md.blurbAGENT_FRIENDLINESS_REPORT.mdPLAN_FOR_CASS_MEMORY_SYSTEM.md详细介绍
CM - CASS Memory System
面向 AI 编码 Agent 的程序性记忆。将零散的会话转化为持久化、跨 Agent 的记忆。采用三层认知架构,模拟人类专业能力的发展过程。
为什么需要它
AI 编码 Agent 会积累有价值的知识,但这些知识:
- 困在会话中 - 会话结束时上下文就会丢失
- 仅限特定 Agent - Claude 不知道 Cursor 学到了什么
- 缺乏结构 - 原始日志无法转化为可执行的指导
- 容易坍塌 - 简单的摘要会丢失关键细节
这个月,你已经在不同 Agent 中解决了 3 次身份验证错误。每次都要从头开始。
CM 通过跨 Agent 学习解决这个问题:在 Cursor 中发现的模式会立即提供给 Claude Code 使用。
三层认知架构
┌─────────────────────────────────────────────────────────────────────┐
│ EPISODIC MEMORY (cass) │
│ Raw session logs from all agents — the "ground truth" │
│ Claude Code │ Codex │ Cursor │ Aider │ PI │ Gemini │ ChatGPT │ ...│
└───────────────────────────┬─────────────────────────────────────────┘
│ cass search
▼
┌─────────────────────────────────────────────────────────────────────┐
│ WORKING MEMORY (Diary) │
│ Structured session summaries: accomplishments, decisions, etc. │
└───────────────────────────┬─────────────────────────────────────────┘
│ reflect + curate (automated)
▼
┌─────────────────────────────────────────────────────────────────────┐
│ PROCEDURAL MEMORY (Playbook) │
│ Distilled rules with confidence tracking and decay │
└─────────────────────────────────────────────────────────────────────┘
每个 Agent 的会话都会汇入共享记忆。在 Cursor 中发现的模式会自动帮助 Claude Code 处理下一次会话。
你需要的唯一命令
cm context "<your task>" --json
在开始任何非简单任务前运行此命令。 返回:
- relevantBullets - 根据任务相关性评分的手册规则
- antiPatterns - 曾经导致问题的做法
- historySnippets - 过去的会话(你自己的和其他 Agent 的)
- suggestedCassQueries - 用于深入调查的搜索
按来源筛选历史记录
historySnippets[].origin.kind 的值为 "local" 或 "remote"。远程命中结果包含 origin.host:
{
"historySnippets": [
{
"source_path": "~/.claude/sessions/session-001.jsonl",
"origin": { "kind": "local" }
},
{
"source_path": "/home/user/.codex/sessions/session.jsonl",
"origin": { "kind": "remote", "host": "workstation" }
}
]
}
置信度衰减系统
规则并非永不过时。若不重新验证,置信度就会衰减:
| 机制 | 效果 |
|---|---|
| 90 天半衰期 | 90 天没有反馈,置信度减半 |
| 4 倍有害系数 | 一次错误的权重相当于一次成功的 4 倍 |
| 成熟度进阶 | candidate → established → proven |
分数衰减可视化
Initial score: 10.0 (10 helpful marks today)
After 90 days (half-life): 5.0
After 180 days: 2.5
After 270 days: 1.25
After 365 days: 0.78
有效分数公式
effectiveScore = decayedHelpful - (4 × decayedHarmful)
// Where decay factor = 0.5 ^ (daysSinceFeedback / 90)
成熟度状态机
┌──────────┐ ┌─────────────┐ ┌────────┐
│ candidate│──────▶│ established │───▶│ proven │
└──────────┘ └─────────────┘ └────────┘
│ │ │
│ │ (harmful >25%) │
│ ▼ │
│ ┌─────────────┐ │
└────────────▶│ deprecated │◀─────────┘
└─────────────┘
转换规则:
| 转换 | 条件 |
|---|---|
candidate → established | 至少 3 次有帮助,有害比例 <25% |
established → proven | 至少 10 次有帮助,有害比例 <10% |
any → deprecated | 有害比例 >25% 或明确弃用 |
反模式学习
有害规则不会直接删除,而是会变成警告:
"Cache auth tokens for performance"
↓ (3 harmful marks)
"PITFALL: Don't cache auth tokens without expiry validation"
当一条规则被多次标记为有害(有害比例 >50%,且至少标记 3 次)时,它会自动转化为反模式。
ACE 流水线(规则如何创建)
Generator → Reflector → Validator → Curator
| 阶段 | 职责 | 使用大模型? |
|---|---|---|
| Generator | 任务前上下文填充(cm context) | 否 |
| Reflector | 从会话中提取模式(cm reflect) | 是 |
| Validator | 根据 cass 历史记录进行证据核验 | 是 |
| Curator | 确定性增量合并 | 否 |
重要: Curator 不使用大模型,以防迭代偏移导致上下文坍塌。大模型负责提出模式;确定性逻辑负责管理这些模式。
科学验证
在规则加入你的手册前,会先根据 cass 历史记录进行验证:
Proposed rule: "Always check token expiry before auth debugging"
↓
Evidence gate: Search cass for sessions where this applied
↓
Result: 5 sessions found, 4 successful outcomes → ACCEPT
缺乏历史证据的规则会被标记为候选规则,直到得到证实。
命令参考
上下文检索(主要工作流)
# THE MAIN COMMAND - run before non-trivial tasks
cm context "implement user authentication" --json
# Limit results for token budget
cm context "fix bug" --json --limit 5 --no-history
# With workspace filter
cm context "refactor" --json --workspace /path/to/project
# Self-documenting explanation
cm quickstart --json
# System health
cm doctor --json
cm doctor --fix # Auto-fix issues
# Find similar rules
cm similar "error handling best practices"
手册管理
cm playbook list # All rules
cm playbook get b-8f3a2c # Rule details
cm playbook add "Always run tests first" # Add rule
cm playbook add --file rules.json # Batch add from file
cm playbook add --file rules.json --session /path/session.jsonl # Track source
cm playbook remove b-xyz --reason "Outdated" # Remove
cm playbook export > backup.yaml # Export
cm playbook import shared.yaml # Import
cm playbook bootstrap react # Apply starter to existing
cm top 10 # Top effective rules
cm stale --days 60 # Rules without recent feedback
cm why b-8f3a2c # Rule provenance
cm stats --json # Playbook health metrics
学习与反馈
# Manual feedback
cm mark b-8f3a2c --helpful
cm mark b-xyz789 --harmful --reason "Caused regression"
cm undo b-xyz789 # Revert feedback
# Session outcomes (positional: status, rules)
cm outcome success b-8f3a2c,b-def456
cm outcome failure b-x7k9p1 --summary "Auth approach failed"
cm outcome-apply # Apply to playbook
# Reflection (usually automated)
cm reflect --days 7 --json
cm reflect --session /path/to/session.jsonl # Single session
cm reflect --workspace /path/to/project # Project-specific
# Validation
cm validate "Always check null before dereferencing"
# Audit sessions against rules
cm audit --days 30
# Deprecate permanently
cm forget b-xyz789 --reason "Superseded by better pattern"
入门引导(Agent 原生)
使用现有 Agent 构建手册,零成本:
cm onboard status # Check progress
cm onboard gaps # Category gaps
cm onboard sample --fill-gaps # Prioritized sessions
cm onboard sample --agent claude --days 14 # Filter by agent/time
cm onboard sample --workspace /path/project # Filter by workspace
cm onboard sample --include-processed # Re-analyze sessions
cm onboard read /path/session.jsonl --template # Rich context
cm onboard mark-done /path/session.jsonl # Mark processed
cm onboard reset # Start fresh
Trauma Guard(安全系统)
cm trauma list # Active patterns
cm trauma add "DROP TABLE" --description "Mass deletion" --severity critical
cm trauma heal t-abc --reason "Intentional migration"
cm trauma remove t-abc
cm trauma scan --days 30 # Scan for traumas
cm trauma import shared-traumas.yaml
cm guard --install # Claude Code hook
cm guard --git # Git pre-commit hook
cm guard --install --git # Both
cm guard --status # Check installation
系统命令
cm init # Initialize
cm init --starter typescript # With template
cm init --force # Reinitialize (creates backup)
cm starters # List templates
cm serve --port 3001 # MCP server
cm usage # LLM cost stats
cm privacy status # Privacy settings
cm privacy enable # Enable cross-agent enrichment
cm privacy disable # Disable enrichment
cm project --format agents.md # Export for AGENTS.md
入门手册
从空白手册开始可能让人无从下手。入门手册提供经过筛选的最佳实践:
cm starters # List available
cm init --starter typescript # Initialize with starter
cm playbook bootstrap react # Apply to existing playbook
内置入门手册
| 入门手册 | 侧重点 | 规则数 |
|---|---|---|
| general | 通用最佳实践 | 5 |
| typescript | TypeScript/Node.js 模式 | 4 |
| react | React/Next.js 开发 | 4 |
| python | Python/FastAPI/Django | 4 |
| node | Node.js/Express 服务 | 4 |
| rust | Rust 服务模式 | 4 |
自定义入门模板
在 ~/.cass-memory/starters/ 中创建 YAML 文件:
# ~/.cass-memory/starters/django.yaml
name: django
description: Django web framework best practices
bullets:
- content: "Always use Django's ORM for database operations"
category: database
maturity: established
tags: [django, orm]
行内反馈(工作期间)
在代码注释中留下反馈。反思期间会解析这些注释:
// [cass: helpful b-8f3a2c] - this rule saved me from a rabbit hole
// [cass: harmful b-x7k9p1] - this advice was wrong for our use case
Agent 协议
1. START: cm context "<task>" --json
2. WORK: Reference rule IDs when following them (e.g., "Following b-8f3a2c...")
3. FEEDBACK: Leave inline comments when rules help/hurt
4. END: Just finish. Learning happens automatically.
你无需:
- 运行
cm reflect(自动化会处理) - 手动运行
cm mark(使用行内注释) - 手动向操作手册中添加规则
差距分析类别
| 类别 | 关键词 |
|---|---|
debugging | 错误、修复、缺陷、跟踪、堆栈 |
testing | 测试、模拟、断言、预期、jest |
architecture | 设计、模式、模块、抽象 |
workflow | 任务、CI/CD、部署 |
documentation | 注释、README、API 文档 |
integration | API、HTTP、JSON、端点 |
collaboration | 审查、PR、团队 |
git | 分支、合并、提交 |
security | 身份验证、令牌、加密、权限 |
performance | 优化、缓存、性能分析 |
类别状态阈值:
| 状态 | 规则数量 | 优先级 |
|---|---|---|
critical | 0 条规则 | 高 |
underrepresented | 1-2 条规则 | 中 |
adequate | 3-10 条规则 | 低 |
well-covered | 11+ 条规则 | 无 |
创伤防护:安全系统
“烫手炉灶”原则——从过往事故中吸取教训,防止再次发生。
工作原理
Session History Trauma Registry Runtime Guard
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ rm -rf /* (oops)│ ──────▶ │ Pattern: rm -rf │ ──────▶ │ BLOCKED: This │
│ "sorry, I made │ scan │ Severity: FATAL │ hook │ command matches │
│ a mistake..." │ │ Session: abc123 │ │ a trauma pattern│
└─────────────────┘ └─────────────────┘ └─────────────────┘
内置毁灭性操作模式(20+)
| 类别 | 示例 |
|---|---|
| 文件系统 | rm -rf /、rm -rf ~、递归删除 |
| 数据库 | DROP DATABASE、TRUNCATE、不带 WHERE 的 DELETE FROM |
| Git | 对 main/master 执行 git push --force、git reset --hard |
| 基础设施 | terraform destroy -auto-approve、kubectl delete namespace |
| 云 | aws s3 rm --recursive、破坏性 CloudFormation 操作 |
模式存储
| 范围 | 位置 | 用途 |
|---|---|---|
| 全局 | ~/.cass-memory/traumas.jsonl | 个人模式 |
| 项目 | .cass/traumas.jsonl | 提交到仓库,供团队使用 |
模式生命周期
- 生效中:阻止匹配的命令
- 已愈合:暂时绕过(需提供原因和时间戳)
- 已删除:已移除(可以重新添加)
MCP 服务
作为 MCP 服务运行,以便与 Agent 集成:
# Local-only (recommended)
cm serve --port 3001
# With auth token (for non-loopback)
MCP_HTTP_TOKEN="<random>" cm serve --host 0.0.0.0 --port 3001
暴露的工具
| 工具 | 用途 | 参数 |
|---|---|---|
cm_context | 获取规则和历史记录 | task, limit?, history?, days?, workspace? |
cm_feedback | 记录反馈 | bulletId, helpful?, harmful?, reason? |
cm_outcome | 记录会话结果 | sessionId, outcome, rulesUsed? |
memory_search | 搜索操作手册/cass | query, scope?, limit?, days? |
memory_reflect | 触发反思 | days?, maxSessions?, dryRun? |
暴露的资源
| URI | 用途 |
|---|---|
cm://playbook | 当前操作手册状态 |
cm://diary | 最近的日记条目 |
cm://outcomes | 会话结果 |
cm://stats | 操作手册健康指标 |
客户端配置
Claude Code(~/.config/claude/mcp.json):
{
"mcpServers": {
"cm": {
"command": "cm",
"args": ["serve"]
}
}
}
优雅降级
| 条件 | 行为 |
|---|---|
| 没有 cass | 仅根据操作手册评分,不提供历史记录片段 |
| 没有操作手册 | 操作手册为空,命令仍可正常运行 |
| 没有 LLM | 使用确定性反思,不进行语义增强 |
| 离线 | 使用缓存的操作手册和本地日记 |
输出格式
所有命令都支持 --json,用于生成机器可读的输出。
**设计原则:**标准输出仅包含 JSON;诊断信息写入标准错误。
成功响应
{
"success": true,
"task": "fix the auth timeout bug",
"relevantBullets": [
{
"id": "b-8f3a2c",
"content": "Always check token expiry before auth debugging",
"effectiveScore": 8.5,
"maturity": "proven",
"relevanceScore": 0.92,
"reasoning": "Extracted from 5 successful sessions"
}
],
"antiPatterns": [...],
"historySnippets": [...],
"suggestedCassQueries": [...],
"degraded": null
}
错误响应
{
"success": false,
"code": "PLAYBOOK_NOT_FOUND",
"error": "Playbook file not found",
"hint": "Run 'cm init' to create a new playbook",
"retryable": false,
"recovery": ["cm init", "cm doctor --fix"],
"docs": "README.md#-troubleshooting"
}
退出代码
| 代码 | 含义 |
|---|---|
| 1 | 内部错误 |
| 2 | 用户输入/用法错误 |
| 3 | 配置错误 |
| 4 | 文件系统错误 |
| 5 | 网络错误 |
| 6 | cass 错误 |
| 7 | LLM/提供方错误 |
令牌预算管理
| 标志 | 效果 |
|---|---|
--limit N | 限制规则数量 |
--min-score N | 仅包含高于阈值的规则 |
--no-history | 跳过历史记录片段(速度更快) |
--json | 结构化输出 |
配置
配置位于 ~/.cass-memory/config.json(全局)和 .cass/config.json(仓库)。
**优先级:**命令行标志 > 仓库配置 > 全局配置 > 默认值
**安全性:**仓库配置无法覆盖敏感路径或用户级同意设置。
关键选项
{
"provider": "anthropic",
"model": "claude-sonnet-5",
"budget": {
"dailyLimit": 1.00,
"monthlyLimit": 20.00
},
"scoring": {
"decayHalfLifeDays": 90,
"harmfulMultiplier": 4
},
"maxBulletsInContext": 50,
"maxHistoryInContext": 10,
"sessionLookbackDays": 7,
"crossAgent": {
"enabled": false,
"consentGiven": false,
"auditLog": true
},
"remoteCass": {
"enabled": false,
"hosts": [{"host": "workstation", "label": "work"}]
},
"embeddingModel": "Xenova/all-MiniLM-L6-v2",
"dedupSimilarityThreshold": 0.85
}
上文有意未列出 semanticSearchEnabled:它是三态选项。未设置(默认值)时,只要嵌入后端已能离线生成嵌入向量,语义搜索就会运行——本地模型已缓存,或 embeddingBackend: "ollama" 且守护进程已拉取模型并能正常响应;否则只使用关键词搜索。将其设为 true 或 false,即可固定为相应状态。cm doctor 会报告当前状态,cm context --json 则会通过 semanticError(失败)或 semanticNotice(后端尚未就绪)解释关键词搜索结果。
环境变量
| 变量 | 用途 |
|---|---|
ANTHROPIC_API_KEY | Anthropic(Claude)的 API 密钥 |
OPENAI_API_KEY | OpenAI 的 API 密钥 |
GOOGLE_GENERATIVE_AI_API_KEY | Google Gemini 的 API 密钥 |
CASS_PATH | cass 二进制文件的路径 |
CASS_MEMORY_LLM | 设为 none 可启用无 LLM 模式 |
MCP_HTTP_TOKEN | 用于非回环 MCP 服务的身份验证令牌 |
数据位置
~/.cass-memory/ # Global (user-level)
├── config.json # Configuration
├── playbook.yaml # Personal playbook
├── diary/ # Session summaries
├── outcomes/ # Session outcomes
├── traumas.jsonl # Trauma patterns
├── starters/ # Custom starter playbooks
├── onboarding-state.json # Onboarding progress
├── privacy-audit.jsonl # Cross-agent audit trail
├── processed-sessions.jsonl # Reflection progress
└── usage.jsonl # LLM cost tracking
.cass/ # Project-level (in repo)
├── config.json # Project-specific overrides
├── playbook.yaml # Project-specific rules
├── traumas.jsonl # Project-specific patterns
└── blocked.yaml # Anti-patterns to block
自动化反思
Cron 作业
# Daily at 2am
0 2 * * * /usr/local/bin/cm reflect --days 7 >> ~/.cass-memory/reflect.log 2>&1
Claude Code 钩子
.claude/hooks.json:
{
"post-session": ["cm reflect --days 1"]
}
隐私与安全
本地优先设计
- 所有数据都保留在你的计算机上
- 不进行云同步,不收集遥测数据
- 跨 Agent 增强需选择加入并明确同意
- 记录增强事件的审计日志
秘密信息清理
处理前会清理内容中的以下信息:
- OpenAI/Anthropic/AWS/Google API 密钥
- GitHub 令牌
- JWT
- 配置模式中的密码和秘密信息
隐私控制
cm privacy status # Check settings
cm privacy enable # Enable cross-agent enrichment
cm privacy disable # Disable enrichment
性能特征
| 操作 | 典型延迟 |
|---|---|
cm context(缓存命中) | 50-150ms |
cm context(冷启动) | 200-500ms |
cm context(无 cass) | 30-80ms |
cm reflect(1 个会话) | 5-15s |
cm reflect(5 个会话) | 20-60s |
cm playbook list | <50ms |
cm similar(关键词) | 20-50ms |
cm similar(语义) | 100-300ms |
LLM 成本估算
| 操作 | 典型成本 |
|---|---|
| Reflect(1 个会话) | $0.01-0.05 |
| Reflect(7 天) | $0.05-0.20 |
| Validate(1 条规则) | $0.005-0.01 |
使用默认预算($0.10/天,$2.00/月):约 5-10 个会话/天。
批量添加规则
分析会话后,可一次添加多条规则:
# Create JSON file
cat > rules.json << 'EOF'
[
{"content": "Always run tests before committing", "category": "testing"},
{"content": "Check token expiry before auth debugging", "category": "debugging"},
{"content": "AVOID: Mocking entire modules in tests", "category": "testing"}
]
EOF
# Add all rules
cm playbook add --file rules.json
# Track which session they came from
cm playbook add --file rules.json --session /path/to/session.jsonl
# Or pipe from stdin
echo '[{"content": "Rule", "category": "workflow"}]' | cm playbook add --file -
用于引导入门的模板输出
--template 会提供丰富的上下文,以便提取规则:
cm onboard read /path/to/session.jsonl --template --json
返回内容:
- metadata:路径、工作区、消息数、主题提示
- context:相关规则、操作手册缺漏、建议的关注重点
- extractionFormat:架构、类别、示例
- sessionContent:实际会话数据
与 CASS 集成
CASS 提供情景记忆(原始会话)。 CM 提取程序性记忆(规则和操作手册)。
# CASS: Search raw sessions
cass search "authentication timeout" --robot
# CM: Get distilled rules for a task
cm context "authentication timeout" --json
故障排除
| 错误 | 解决方案 |
|---|---|
cass not found | 从 cass 仓库安装 |
cass search failed | 运行 cass index --full |
API key missing | 设置 ANTHROPIC_API_KEY、OPENAI_API_KEY 或 GOOGLE_GENERATIVE_AI_API_KEY |
Playbook corrupt | 运行 cm doctor --fix |
Budget exceeded | 检查 cm usage,调整限制 |
诊断命令
cm doctor --json # System health
cm doctor --fix # Auto-fix issues
cm usage # LLM budget status
cm stats --json # Playbook health
cm why <bullet-id> # Rule provenance
无 LLM 模式
CASS_MEMORY_LLM=none cm context "task" --json
安装
# One-liner (recommended)
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/cass_memory_system/main/install.sh \
| bash -s -- --easy-mode --verify
# Specific version
install.sh --version v0.2.2 --verify
# System-wide
install.sh --system --verify
# From source
git clone https://github.com/Dicklesworthstone/cass_memory_system.git
cd cass_memory_system
bun install && bun run build
sudo mv ./dist/cass-memory /usr/local/bin/cm
与 Flywheel 集成
| 工具 | 集成方式 |
|---|---|
| CASS | CM 从 cass 情景记忆中读取,并写入程序性记忆 |
| NTM | 机器人模式会在 Agent 开始工作前与 cm 集成以获取上下文 |
| Agent Mail | 规则可将邮件线程作为来源依据 |
| BV | 任务上下文会补充相关的操作手册规则 |