cm

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CM - CASS Memory System

CM - CASS 记忆系统

Procedural memory for AI coding agents. Transforms scattered sessions into persistent, cross-agent memory. Uses a three-layer cognitive architecture that mirrors human expertise development.
AI编码Agent的过程性记忆系统。将分散的会话转换为持久化的跨Agent记忆。采用模仿人类专业技能发展的三层认知架构。

Why This Exists

设计初衷

AI coding agents accumulate valuable knowledge but it's:
  • Trapped in sessions - Context lost when session ends
  • Agent-specific - Claude doesn't know what Cursor learned
  • Unstructured - Raw logs aren't actionable guidance
  • Subject to collapse - Naive summarization loses critical details
You've solved auth bugs three times this month across different agents. Each time you started from scratch.
CM solves this with cross-agent learning: a pattern discovered in Cursor is immediately available to Claude Code.

AI编码Agent会积累宝贵的知识,但这些知识存在以下问题:
  • 局限于会话内 - 会话结束后上下文丢失
  • Agent专属 - Claude 不知道 Cursor 学到了什么
  • 非结构化 - 原始日志无法直接作为可执行指导
  • 易丢失关键信息 - 简单的摘要会丢失重要细节
你这个月在不同Agent上三次解决了认证bug,但每次都要从头开始。
CM通过跨Agent学习解决了这个问题:在Cursor中发现的模式可以立即为Claude Code所用。

Three-Layer Cognitive Architecture

三层认知架构

┌─────────────────────────────────────────────────────────────────────┐
│                    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                │
└─────────────────────────────────────────────────────────────────────┘
Every agent's sessions feed the shared memory. A pattern discovered in Cursor automatically helps Claude Code on the next session.

┌─────────────────────────────────────────────────────────────────────┐
│                    情景记忆 (cass)                           │
│   来自所有Agent的原始会话日志 —— "事实真相"             │
│   Claude Code │ Codex │ Cursor │ Aider │ PI │ Gemini │ ChatGPT │ ...│
└───────────────────────────┬─────────────────────────────────────────┘
                            │ cass 搜索
┌─────────────────────────────────────────────────────────────────────┐
│                    工作记忆 (Diary)                           │
│   结构化的会话摘要:成果、决策等    │
└───────────────────────────┬─────────────────────────────────────────┘
                            │ 反思 + 整理(自动化)
┌─────────────────────────────────────────────────────────────────────┐
│                    过程性记忆 (Playbook)                     │
│   带有置信度跟踪与衰减的提炼规则                │
└─────────────────────────────────────────────────────────────────────┘
每个Agent的会话都会为共享记忆提供数据。在Cursor中发现的模式自动帮助Claude Code完成下一次会话任务。

The One Command You Need

核心命令

bash
cm context "<your task>" --json
Run this before starting any non-trivial task. Returns:
  • relevantBullets - Rules from playbook scored by task relevance
  • antiPatterns - Things that have caused problems
  • historySnippets - Past sessions (yours and other agents')
  • suggestedCassQueries - Deeper investigation searches
bash
cm context "<你的任务>" --json
在开始任何重要任务前运行此命令。返回内容包括:
  • relevantBullets - 根据任务相关性评分的Playbook规则
  • antiPatterns - 曾导致问题的反模式
  • historySnippets - 过往会话片段(包括你和其他Agent的)
  • suggestedCassQueries - 深入调查的建议搜索词

Filtering History by Source

按来源过滤历史记录

historySnippets[].origin.kind
is
"local"
or
"remote"
. Remote hits include
origin.host
:
json
{
  "historySnippets": [
    {
      "source_path": "~/.claude/sessions/session-001.jsonl",
      "origin": { "kind": "local" }
    },
    {
      "source_path": "/home/user/.codex/sessions/session.jsonl",
      "origin": { "kind": "remote", "host": "workstation" }
    }
  ]
}

historySnippets[].origin.kind
的值为
"local"
"remote"
。远程结果包含
origin.host
字段:
json
{
  "historySnippets": [
    {
      "source_path": "~/.claude/sessions/session-001.jsonl",
      "origin": { "kind": "local" }
    },
    {
      "source_path": "/home/user/.codex/sessions/session.jsonl",
      "origin": { "kind": "remote", "host": "workstation" }
    }
  ]
}

Confidence Decay System

置信度衰减系统

Rules aren't immortal. Confidence decays without revalidation:
MechanismEffect
90-day half-lifeConfidence halves every 90 days without feedback
4x harmful multiplierOne mistake counts 4× as much as one success
Maturity progression
candidate
established
proven
规则并非永久有效。若无重新验证,置信度会逐渐衰减:
机制效果
90天半衰期无反馈情况下,置信度每90天减半
4倍有害权重一次错误的影响相当于4次成功的权重
成熟度递进
候选
已确立
已验证

Score Decay Visualization

分数衰减示例

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
初始分数: 10.0(今日获得10次有用标记)

90天后(半衰期):   5.0
180天后:              2.5
270天后:              1.25
365天后:              0.78

Effective Score Formula

有效分数计算公式

typescript
effectiveScore = decayedHelpful - (4 × decayedHarmful)

// Where decay factor = 0.5 ^ (daysSinceFeedback / 90)
typescript
effectiveScore = decayedHelpful - (4 × decayedHarmful)

// 其中衰减因子 = 0.5 ^ (daysSinceFeedback / 90)

Maturity State Machine

成熟度状态机

  ┌──────────┐       ┌─────────────┐    ┌────────┐
  │ candidate│──────▶│ established │───▶│ proven │
  └──────────┘       └─────────────┘    └────────┘
       │                   │                  │
       │                   │ (harmful >25%)   │
       │                   ▼                  │
       │             ┌─────────────┐          │
       └────────────▶│ deprecated  │◀─────────┘
                     └─────────────┘
Transition Rules:
TransitionCriteria
candidate
established
3+ helpful, harmful ratio <25%
established
proven
10+ helpful, harmful ratio <10%
any
deprecated
Harmful ratio >25% OR explicit deprecation

  ┌──────────┐       ┌─────────────┐    ┌────────┐
  │ 候选规则│──────▶│ 已确立规则 │───▶│ 已验证规则 │
  └──────────┘       └─────────────┘    └────────┘
       │                   │                  │
       │                   │(有害占比>25%)   │
       │                   ▼                  │
       │             ┌─────────────┐          │
       └────────────▶│ 已弃用规则  │◀─────────┘
                     └─────────────┘
转换规则:
转换条件
候选
已确立
3次以上有用标记,有害占比<25%
已确立
已验证
10次以上有用标记,有害占比<10%
任意状态
已弃用
有害占比>25% 或 显式标记弃用

Anti-Pattern Learning

反模式学习

Bad rules don't just get deleted. They become warnings:
"Cache auth tokens for performance"
    ↓ (3 harmful marks)
"PITFALL: Don't cache auth tokens without expiry validation"
When a rule is marked harmful multiple times (>50% harmful ratio with 3+ marks), it's automatically inverted into an anti-pattern.

错误的规则不会被简单删除,而是转换为警告:
"为性能缓存认证令牌"
    ↓(3次有害标记)
"陷阱:不要在未验证过期时间的情况下缓存认证令牌"
当一个规则被多次标记为有害(有害占比>50%且标记数≥3),它会自动转换为反模式。

ACE Pipeline (How Rules Are Created)

ACE流水线(规则创建流程)

Generator → Reflector → Validator → Curator
StageRoleLLM?
GeneratorPre-task context hydration (
cm context
)
No
ReflectorExtract patterns from sessions (
cm reflect
)
Yes
ValidatorEvidence gate against cass historyYes
CuratorDeterministic delta mergeNo
Critical: Curator has NO LLM to prevent context collapse from iterative drift. LLMs propose patterns; deterministic logic manages them.
生成器 → 反思器 → 验证器 → 整理器
阶段职责是否使用LLM?
生成器任务前上下文注入 (
cm context
)
反思器从会话中提取模式 (
cm reflect
)
验证器对照cass历史验证证据
整理器确定性增量合并
关键设计: 整理器不使用LLM,以避免迭代漂移导致的上下文丢失。LLM负责提出模式,确定性逻辑负责管理模式。

Scientific Validation

科学验证

Before a rule joins your playbook, it's validated against cass history:
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
Rules without historical evidence are flagged as candidates until proven.

规则加入Playbook前,会对照cass历史进行验证:
待验证规则:"调试认证问题前务必检查令牌过期时间"
证据验证:在cass中搜索应用此规则的会话
结果:找到5个会话,其中4个成功解决问题 → 接受规则
无历史证据支持的规则会被标记为候选规则,直到被验证有效。

Commands Reference

命令参考

Context Retrieval (Primary Workflow)

上下文检索(核心工作流)

bash
undefined
bash
undefined

THE MAIN COMMAND - run before non-trivial tasks

核心命令 - 重要任务前运行

cm context "implement user authentication" --json
cm context "实现用户认证" --json

Limit results for token budget

限制结果数量以节省Token

cm context "fix bug" --json --limit 5 --no-history
cm context "修复bug" --json --limit 5 --no-history

With workspace filter

按工作区过滤

cm context "refactor" --json --workspace /path/to/project
cm context "重构代码" --json --workspace /path/to/project

Self-documenting explanation

快速入门指南

cm quickstart --json
cm quickstart --json

System health

系统健康检查

cm doctor --json cm doctor --fix # Auto-fix issues
cm doctor --json cm doctor --fix # 自动修复问题

Find similar rules

查找相似规则

cm similar "error handling best practices"
undefined
cm similar "错误处理最佳实践"
undefined

Playbook Management

Playbook管理

bash
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
bash
cm playbook list                              # 列出所有规则
cm playbook get b-8f3a2c                      # 查看规则详情
cm playbook add "始终先运行测试"      # 添加规则
cm playbook add --file rules.json             # 从文件批量添加
cm playbook add --file rules.json --session /path/session.jsonl  # 跟踪规则来源会话
cm playbook remove b-xyz --reason "已过时"  # 删除规则
cm playbook export > backup.yaml              # 导出规则
cm playbook import shared.yaml                # 导入规则
cm playbook bootstrap react                   # 为现有项目应用入门规则

cm top 10                                     # 显示有效分数前十的规则
cm stale --days 60                            # 显示60天内无反馈的规则
cm why b-8f3a2c                               # 查看规则来源
cm stats --json                               # 查看Playbook健康指标

Learning & Feedback

学习与反馈

bash
undefined
bash
undefined

Manual feedback

手动反馈

cm mark b-8f3a2c --helpful cm mark b-xyz789 --harmful --reason "Caused regression" cm undo b-xyz789 # Revert feedback
cm mark b-8f3a2c --helpful cm mark b-xyz789 --harmful --reason "导致回归问题" cm undo b-xyz789 # 撤销反馈

Session outcomes (positional: status, rules)

会话结果(位置参数:状态,规则ID)

cm outcome success b-8f3a2c,b-def456 cm outcome failure b-x7k9p1 --summary "Auth approach failed" cm outcome-apply # Apply to playbook
cm outcome success b-8f3a2c,b-def456 cm outcome failure b-x7k9p1 --summary "认证方案失败" cm outcome-apply # 将结果应用到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
cm reflect --days 7 --json cm reflect --session /path/to/session.jsonl # 处理单个会话 cm reflect --workspace /path/to/project # 处理指定项目的会话

Validation

规则验证

cm validate "Always check null before dereferencing"
cm validate "解引用前务必检查空值"

Audit sessions against rules

对照规则审计会话

cm audit --days 30
cm audit --days 30

Deprecate permanently

永久弃用规则

cm forget b-xyz789 --reason "Superseded by better pattern"
undefined
cm forget b-xyz789 --reason "被更优模式替代"
undefined

Onboarding (Agent-Native)

入门引导(Agent原生支持)

Zero-cost playbook building using your existing agent:
bash
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
利用现有Agent零成本构建Playbook:
bash
cm onboard status                             # 查看入门进度
cm onboard gaps                               # 查看规则分类缺口
cm onboard sample --fill-gaps                 # 优先处理填补缺口的会话
cm onboard sample --agent claude --days 14    # 按Agent/时间过滤会话
cm onboard sample --workspace /path/project   # 按工作区过滤会话
cm onboard sample --include-processed         # 重新分析已处理会话
cm onboard read /path/session.jsonl --template  # 获取丰富上下文用于规则提取
cm onboard mark-done /path/session.jsonl      # 标记会话为已处理
cm onboard reset                              # 重置入门进度

Trauma Guard (Safety System)

创伤防护(安全系统)

bash
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
bash
cm trauma list                                # 查看激活的创伤模式
cm trauma add "DROP TABLE" --description "大规模删除" --severity critical
cm trauma heal t-abc --reason "有意的数据迁移"
cm trauma remove t-abc
cm trauma scan --days 30                      # 扫描近30天的会话寻找创伤模式
cm trauma import shared-traumas.yaml

cm guard --install                            # 安装Claude Code钩子
cm guard --git                                # 安装Git预提交钩子
cm guard --install --git                      # 同时安装两者
cm guard --status                             # 检查钩子安装状态

System Commands

系统命令

bash
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

bash
cm init                                       # 初始化系统
cm init --starter typescript                  # 使用TypeScript模板初始化
cm init --force                               # 重新初始化(自动创建备份)
cm starters                                   # 列出可用模板
cm serve --port 3001                          # 启动MCP服务器
cm usage                                      # 查看LLM成本统计
cm privacy status                             # 查看隐私设置
cm privacy enable                             # 启用跨Agent知识增强
cm privacy disable                            # 禁用跨Agent知识增强
cm project --format agents.md                 # 导出为AGENTS.md格式

Starter Playbooks

入门规则手册

Starting with an empty playbook is daunting. Starters provide curated best practices:
bash
cm starters                    # List available
cm init --starter typescript   # Initialize with starter
cm playbook bootstrap react    # Apply to existing playbook
从零开始构建Playbook难度较大。入门模板提供经过整理的最佳实践:
bash
cm starters                    # 列出可用模板
cm init --starter typescript   # 使用TypeScript模板初始化
cm playbook bootstrap react    # 为现有Playbook应用React模板

Built-in Starters

内置模板

StarterFocusRules
generalUniversal best practices5
typescriptTypeScript/Node.js patterns4
reactReact/Next.js development4
pythonPython/FastAPI/Django4
nodeNode.js/Express services4
rustRust service patterns4
模板聚焦领域规则数量
general通用最佳实践5
typescriptTypeScript/Node.js模式4
reactReact/Next.js开发4
pythonPython/FastAPI/Django4
nodeNode.js/Express服务4
rustRust服务模式4

Custom Starters

自定义模板

Create YAML files in
~/.cass-memory/starters/
:
yaml
undefined
~/.cass-memory/starters/
目录下创建YAML文件:
yaml
undefined

~/.cass-memory/starters/django.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]

---
name: django description: Django Web框架最佳实践 bullets:
  • content: "始终使用Django ORM进行数据库操作" category: database maturity: established tags: [django, orm]

---

Inline Feedback (During Work)

内联反馈(工作中使用)

Leave feedback in code comments. Parsed during reflection:
typescript
// [cass: helpful b-8f3a2c] - this rule saved me from a rabbit hole

// [cass: harmful b-x7k9p1] - this advice was wrong for our use case

在代码注释中添加反馈,会在反思阶段被解析:
typescript
// [cass: helpful b-8f3a2c] - 这个规则帮我避免了走弯路

// [cass: harmful b-x7k9p1] - 这个建议不适用于我们的场景

Agent Protocol

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.
You do NOT need to:
  • Run
    cm reflect
    (automation handles this)
  • Run
    cm mark
    manually (use inline comments)
  • Manually add rules to the playbook

1. 开始:    cm context "<任务>" --json
2. 工作:     遵循规则时引用规则ID(例如:"遵循b-8f3a2c规则...")
3. 反馈:     规则有用或有害时添加内联注释
4. 结束:      完成任务即可,学习过程自动进行
你无需手动执行以下操作:
  • 运行
    cm reflect
    (自动化流程会处理)
  • 手动运行
    cm mark
    (使用内联注释即可)
  • 手动向Playbook添加规则

Gap Analysis Categories

缺口分析分类

CategoryKeywords
debugging
error, fix, bug, trace, stack
testing
test, mock, assert, expect, jest
architecture
design, pattern, module, abstraction
workflow
task, CI/CD, deployment
documentation
comment, README, API doc
integration
API, HTTP, JSON, endpoint
collaboration
review, PR, team
git
branch, merge, commit
security
auth, token, encrypt, permission
performance
optimize, cache, profile
Category Status Thresholds:
StatusRule CountPriority
critical
0 rulesHigh
underrepresented
1-2 rulesMedium
adequate
3-10 rulesLow
well-covered
11+ rulesNone

分类关键词
debugging
error, fix, bug, trace, stack(错误、修复、bug、跟踪、堆栈)
testing
test, mock, assert, expect, jest(测试、模拟、断言、预期、Jest)
architecture
design, pattern, module, abstraction(设计、模式、模块、抽象)
workflow
task, CI/CD, deployment(任务、CI/CD、部署)
documentation
comment, README, API doc(注释、README、API文档)
integration
API, HTTP, JSON, endpoint(API、HTTP、JSON、端点)
collaboration
review, PR, team(评审、PR、团队)
git
branch, merge, commit(分支、合并、提交)
security
auth, token, encrypt, permission(认证、令牌、加密、权限)
performance
optimize, cache, profile(优化、缓存、性能分析)
分类状态阈值:
状态规则数量优先级
critical
(严重缺失)
0条规则
underrepresented
(代表不足)
1-2条规则
adequate
(足够覆盖)
3-10条规则
well-covered
(充分覆盖)
11条以上规则

Trauma Guard: Safety System

创伤防护:安全系统

The "hot stove" principle—learn from past incidents and prevent recurrence.
基于“热炉原则”——从过往事故中学习并防止复发。

How It Works

工作原理

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│
└─────────────────┘         └─────────────────┘         └─────────────────┘
会话历史              创伤注册表              运行时防护
┌─────────────────┐         ┌─────────────────┐         ┌─────────────────┐
│ rm -rf /* (失误)│ ──────▶ │ 模式: rm -rf │ ──────▶ │ 已拦截: 此命令匹配│
│ "抱歉,我犯了个 │ 扫描   │ 严重程度: 致命 │ 钩子   │ 创伤模式"         │
│ 错误..."  │         │ 会话ID: abc123 │         │                 │
└─────────────────┘         └─────────────────┘         └─────────────────┘

Built-in Doom Patterns (20+)

内置危险模式(20+种)

CategoryExamples
Filesystem
rm -rf /
,
rm -rf ~
, recursive deletes
Database
DROP DATABASE
,
TRUNCATE
,
DELETE FROM
without WHERE
Git
git push --force
to main/master,
git reset --hard
Infrastructure
terraform destroy -auto-approve
,
kubectl delete namespace
Cloud
aws s3 rm --recursive
, destructive CloudFormation
分类示例
文件系统
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操作

Pattern Storage

模式存储

ScopeLocationPurpose
Global
~/.cass-memory/traumas.jsonl
Personal patterns
Project
.cass/traumas.jsonl
Commit to repo for team
作用域位置用途
全局
~/.cass-memory/traumas.jsonl
个人创伤模式
项目
.cass/traumas.jsonl
提交到仓库供团队使用

Pattern Lifecycle

模式生命周期

  • Active: Blocks matching commands
  • Healed: Temporarily bypassed (with reason and timestamp)
  • Deleted: Removed (can be re-added)

  • Active(激活): 拦截匹配的命令
  • Healed(已恢复): 临时绕过(需提供原因和时间戳)
  • Deleted(已删除): 移除模式(可重新添加)

MCP Server

MCP服务器

Run as MCP server for agent integration:
bash
undefined
作为MCP服务器运行以实现Agent集成:
bash
undefined

Local-only (recommended)

仅本地访问(推荐)

cm serve --port 3001
cm serve --port 3001

With auth token (for non-loopback)

带认证令牌(非回环访问)

MCP_HTTP_TOKEN="<random>" cm serve --host 0.0.0.0 --port 3001
undefined
MCP_HTTP_TOKEN="<随机字符串>" cm serve --host 0.0.0.0 --port 3001
undefined

Tools Exposed

暴露的工具

ToolPurposeParameters
cm_context
Get rules + history
task, limit?, history?, days?, workspace?
cm_feedback
Record feedback
bulletId, helpful?, harmful?, reason?
cm_outcome
Record session outcome
sessionId, outcome, rulesUsed?
memory_search
Search playbook/cass
query, scope?, limit?, days?
memory_reflect
Trigger reflection
days?, maxSessions?, dryRun?
工具用途参数
cm_context
获取规则 + 历史
task, limit?, history?, days?, workspace?
cm_feedback
记录反馈
bulletId, helpful?, harmful?, reason?
cm_outcome
记录会话结果
sessionId, outcome, rulesUsed?
memory_search
搜索Playbook/cass
query, scope?, limit?, days?
memory_reflect
触发反思
days?, maxSessions?, dryRun?

Resources Exposed

暴露的资源

URIPurpose
cm://playbook
Current playbook state
cm://diary
Recent diary entries
cm://outcomes
Session outcomes
cm://stats
Playbook health metrics
URI用途
cm://playbook
当前Playbook状态
cm://diary
近期日记条目
cm://outcomes
会话结果
cm://stats
Playbook健康指标

Client Configuration

客户端配置

Claude Code (
~/.config/claude/mcp.json
):
json
{
  "mcpServers": {
    "cm": {
      "command": "cm",
      "args": ["serve"]
    }
  }
}

Claude Code(配置文件:
~/.config/claude/mcp.json
):
json
{
  "mcpServers": {
    "cm": {
      "command": "cm",
      "args": ["serve"]
    }
  }
}

Graceful Degradation

优雅降级

ConditionBehavior
No cassPlaybook-only scoring, no history snippets
No playbookEmpty playbook, commands still work
No LLMDeterministic reflection, no semantic enhancement
OfflineCached playbook + local diary

条件行为
无cass仅使用Playbook评分,不提供历史片段
无Playbook使用空Playbook,命令仍可正常运行
无LLM仅使用确定性反思,无语义增强
离线状态使用缓存的Playbook + 本地日记

Output Format

输出格式

All commands support
--json
for machine-readable output.
Design principle: stdout = JSON only; diagnostics go to stderr.
所有命令均支持
--json
参数以获取机器可读输出。
设计原则: stdout仅输出JSON;诊断信息输出到stderr。

Success Response

成功响应

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
}
json
{
  "success": true,
  "task": "修复认证超时bug",
  "relevantBullets": [
    {
      "id": "b-8f3a2c",
      "content": "调试认证问题前务必检查令牌过期时间",
      "effectiveScore": 8.5,
      "maturity": "已验证",
      "relevanceScore": 0.92,
      "reasoning": "从5次成功会话中提取"
    }
  ],
  "antiPatterns": [...],
  "historySnippets": [...],
  "suggestedCassQueries": [...],
  "degraded": null
}

Error Response

错误响应

json
{
  "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"
}
json
{
  "success": false,
  "code": "PLAYBOOK_NOT_FOUND",
  "error": "未找到Playbook文件",
  "hint": "运行 'cm init' 创建新的Playbook",
  "retryable": false,
  "recovery": ["cm init", "cm doctor --fix"],
  "docs": "README.md#故障排查"
}

Exit Codes

退出码

CodeMeaning
1Internal error
2User input/usage
3Configuration
4Filesystem
5Network
6cass error
7LLM/provider error

代码含义
1内部错误
2用户输入/使用错误
3配置错误
4文件系统错误
5网络错误
6cass错误
7LLM/提供商错误

Token Budget Management

Token预算管理

FlagEffect
--limit N
Cap number of rules
--min-score N
Only rules above threshold
--no-history
Skip historical snippets (faster)
--json
Structured output

参数效果
--limit N
限制返回的规则数量
--min-score N
仅返回分数高于阈值的规则
--no-history
跳过历史片段(更快)
--json
结构化输出

Configuration

配置

Config lives at
~/.cass-memory/config.json
(global) and
.cass/config.json
(repo).
Precedence: CLI flags > Repo config > Global config > Defaults
Security: Repo config cannot override sensitive paths or user-level consent settings.
配置文件位于
~/.cass-memory/config.json
(全局)和
.cass/config.json
(仓库级)。
优先级: CLI参数 > 仓库配置 > 全局配置 > 默认值
安全限制: 仓库配置无法覆盖敏感路径或用户级同意设置。

Key Options

关键配置项

json
{
  "provider": "anthropic",
  "model": "claude-sonnet-4-20250514",
  "budget": {
    "dailyLimit": 0.10,
    "monthlyLimit": 2.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"}]
  },
  "semanticSearchEnabled": false,
  "embeddingModel": "Xenova/all-MiniLM-L6-v2",
  "dedupSimilarityThreshold": 0.85
}
json
{
  "provider": "anthropic",
  "model": "claude-sonnet-4-20250514",
  "budget": {
    "dailyLimit": 0.10,
    "monthlyLimit": 2.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"}]
  },
  "semanticSearchEnabled": false,
  "embeddingModel": "Xenova/all-MiniLM-L6-v2",
  "dedupSimilarityThreshold": 0.85
}

Environment Variables

环境变量

VariablePurpose
ANTHROPIC_API_KEY
API key for Anthropic (Claude)
OPENAI_API_KEY
API key for OpenAI
GOOGLE_GENERATIVE_AI_API_KEY
API key for Google Gemini
CASS_PATH
Path to cass binary
CASS_MEMORY_LLM
Set to
none
for LLM-free mode
MCP_HTTP_TOKEN
Auth token for non-loopback MCP server

变量用途
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服务器的认证令牌

Data Locations

数据存储位置

~/.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

~/.cass-memory/                  # 全局(用户级)
├── config.json                  # 配置文件
├── playbook.yaml                # 个人Playbook
├── diary/                       # 会话摘要
├── outcomes/                    # 会话结果
├── traumas.jsonl                # 创伤模式
├── starters/                    # 自定义入门规则手册
├── onboarding-state.json        # 入门引导进度
├── privacy-audit.jsonl          # 跨Agent审计日志
├── processed-sessions.jsonl     # 反思进度
└── usage.jsonl                  # LLM成本跟踪

.cass/                           # 项目级(仓库内)
├── config.json                  # 项目特定配置
├── playbook.yaml                # 项目特定规则
├── traumas.jsonl                # 项目特定模式
└── blocked.yaml                 # 需拦截的反模式

Automating Reflection

自动化反思

Cron Job

Cron定时任务

bash
undefined
bash
undefined

Daily at 2am

每天凌晨2点运行

0 2 * * * /usr/local/bin/cm reflect --days 7 >> ~/.cass-memory/reflect.log 2>&1
undefined
0 2 * * * /usr/local/bin/cm reflect --days 7 >> ~/.cass-memory/reflect.log 2>&1
undefined

Claude Code Hook

Claude Code钩子

.claude/hooks.json
:
json
{
  "post-session": ["cm reflect --days 1"]
}

.claude/hooks.json
json
{
  "post-session": ["cm reflect --days 1"]
}

Privacy & Security

隐私与安全

Local-First Design

本地优先设计

  • All data stays on your machine
  • No cloud sync, no telemetry
  • Cross-agent enrichment is opt-in with explicit consent
  • Audit log for enrichment events
  • 所有数据存储在本地机器
  • 无云同步,无遥测
  • 跨Agent知识增强为可选功能,需明确同意
  • 增强操作有审计日志

Secret Sanitization

敏感信息清理

Before processing, content is sanitized:
  • OpenAI/Anthropic/AWS/Google API keys
  • GitHub tokens
  • JWTs
  • Passwords and secrets in config patterns
处理前会自动清理以下内容:
  • OpenAI/Anthropic/AWS/Google API密钥
  • GitHub令牌
  • JWT令牌
  • 配置模式中的密码和敏感信息

Privacy Controls

隐私控制

bash
cm privacy status    # Check settings
cm privacy enable    # Enable cross-agent enrichment
cm privacy disable   # Disable enrichment

bash
cm privacy status    # 查看隐私设置
cm privacy enable    # 启用跨Agent知识增强
cm privacy disable   # 禁用跨Agent知识增强

Performance Characteristics

性能特征

OperationTypical Latency
cm context
(cached)
50-150ms
cm context
(cold)
200-500ms
cm context
(no cass)
30-80ms
cm reflect
(1 session)
5-15s
cm reflect
(5 sessions)
20-60s
cm playbook list
<50ms
cm similar
(keyword)
20-50ms
cm similar
(semantic)
100-300ms
操作典型延迟
cm context
(缓存命中)
50-150ms
cm context
(缓存未命中)
200-500ms
cm context
(无cass)
30-80ms
cm reflect
(单个会话)
5-15s
cm reflect
(5个会话)
20-60s
cm playbook list
<50ms
cm similar
(关键词搜索)
20-50ms
cm similar
(语义搜索)
100-300ms

LLM Cost Estimates

LLM成本估算

OperationTypical Cost
Reflect (1 session)$0.01-0.05
Reflect (7 days)$0.05-0.20
Validate (1 rule)$0.005-0.01
With default budget ($0.10/day, $2.00/month): ~5-10 sessions/day.

操作典型成本
反思(单个会话)$0.01-0.05
反思(7天会话)$0.05-0.20
验证(单个规则)$0.005-0.01
默认预算($0.10/天,$2.00/月):约每天5-10个会话。

Batch Rule Addition

批量添加规则

After analyzing a session, add multiple rules at once:
bash
undefined
分析会话后,可一次性添加多条规则:
bash
undefined

Create JSON file

创建JSON文件

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
cat > rules.json << 'EOF' [ {"content": "提交前始终运行测试", "category": "testing"}, {"content": "调试认证问题前检查令牌过期时间", "category": "debugging"}, {"content": "避免:在测试中模拟整个模块", "category": "testing"} ] EOF

Add all rules

添加所有规则

cm playbook add --file rules.json
cm playbook add --file rules.json

Track which session they came from

跟踪规则来源会话

cm playbook add --file rules.json --session /path/to/session.jsonl
cm playbook add --file rules.json --session /path/to/session.jsonl

Or pipe from stdin

或从标准输入读取

echo '[{"content": "Rule", "category": "workflow"}]' | cm playbook add --file -

---
echo '[{"content": "新规则", "category": "workflow"}]' | cm playbook add --file -

---

Template Output for Onboarding

入门引导模板输出

--template
provides rich context for rule extraction:
bash
cm onboard read /path/to/session.jsonl --template --json
Returns:
  • metadata: path, workspace, message count, topic hints
  • context: related rules, playbook gaps, suggested focus
  • extractionFormat: schema, categories, examples
  • sessionContent: actual session data

--template
参数为规则提取提供丰富上下文:
bash
cm onboard read /path/to/session.jsonl --template --json
返回内容包括:
  • metadata: 文件路径、工作区、消息数量、主题提示
  • context: 相关规则、Playbook缺口、建议聚焦方向
  • extractionFormat: schema、分类、示例
  • sessionContent: 实际会话数据

Integration with CASS

与CASS的集成

CASS provides episodic memory (raw sessions). CM extracts procedural memory (rules and playbooks).
bash
undefined
CASS提供情景记忆(原始会话)。 CM提取过程性记忆(规则和Playbook)。
bash
undefined

CASS: Search raw sessions

CASS: 搜索原始会话

cass search "authentication timeout" --robot
cass search "认证超时" --robot

CM: Get distilled rules for a task

CM: 获取任务相关的提炼规则

cm context "authentication timeout" --json

---
cm context "认证超时" --json

---

Troubleshooting

故障排查

ErrorSolution
cass not found
Install from cass repo
cass search failed
Run
cass index --full
API key missing
Set
ANTHROPIC_API_KEY
,
OPENAI_API_KEY
, or
GOOGLE_GENERATIVE_AI_API_KEY
Playbook corrupt
Run
cm doctor --fix
Budget exceeded
Check
cm usage
, adjust limits
错误解决方案
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
,调整预算限制

Diagnostic Commands

诊断命令

bash
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
bash
cm doctor --json           # 系统健康检查
cm doctor --fix            # 自动修复问题
cm usage                   # 查看LLM预算状态
cm stats --json            # 查看Playbook健康指标
cm why <bullet-id>         # 查看规则来源

LLM-Free Mode

无LLM模式

bash
CASS_MEMORY_LLM=none cm context "task" --json

bash
CASS_MEMORY_LLM=none cm context "任务" --json

Installation

安装

bash
undefined
bash
undefined

One-liner (recommended)

一键安装(推荐)

Specific version

安装特定版本

install.sh --version v0.2.2 --verify
install.sh --version v0.2.2 --verify

System-wide

系统级安装

install.sh --system --verify
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

---
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

---

Integration with Flywheel

与Flywheel的集成

ToolIntegration
CASSCM reads from cass episodic memory, writes procedural memory
NTMRobot mode integrates with cm for context before agent work
Agent MailRules can reference mail threads as provenance
BVTask context enriched with relevant playbook rules
工具集成方式
CASSCM读取cass的情景记忆,写入过程性记忆
NTM机器人模式在Agent工作前集成cm获取上下文
Agent Mail规则可引用邮件线程作为来源
BV任务上下文通过相关Playbook规则增强