---
name: CASS Memory System
slug: cass-memory-system
category: AI Engineering
description: Procedural memory system for AI coding agents with confidence decay, anti-pattern learning, and cross-agent knowledge transfer. Use before tasks to retrieve relevant rules, anti-patterns, and history.
github: "https://github.com/Dicklesworthstone/cass_memory_system"
language: TypeScript
stars: 396
forks: 46
install: "git clone https://github.com/Dicklesworthstone/cass_memory_system"
added: 2026-07-16T03:20:44.814Z
last_synced: 2026-07-16T03:20:44.814Z
canonical_url: "https://dirskills.com/skills/cass-memory-system"
---

# CASS Memory System

Procedural memory system for AI coding agents with confidence decay, anti-pattern learning, and cross-agent knowledge transfer. Use before tasks to retrieve relevant rules, anti-patterns, and history.

**Install:** `git clone https://github.com/Dicklesworthstone/cass_memory_system`

## README

# cass-memory

<div align="center">
  <img src="cm_illustration.webp" alt="cass-memory - Procedural memory for AI coding agents">
</div>

![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-blue.svg)
![Runtime](https://img.shields.io/badge/runtime-Bun-f472b6.svg)
![Status](https://img.shields.io/badge/status-alpha-purple.svg)
![License](https://img.shields.io/badge/license-MIT-green.svg)

**Procedural memory for AI coding agents.**
Transforms scattered agent sessions into persistent, cross-agent memory—so every agent learns from every other agent's experience.

<div align="center">

**One-liner install (Linux/macOS):**

```bash
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/cass_memory_system/main/install.sh?$(date +%s)" \
  | bash -s -- --easy-mode --verify
```

**Or via package managers:**

```bash
# macOS/Linux (Homebrew)
brew install dicklesworthstone/tap/cm

# Windows (Scoop)
scoop bucket add dicklesworthstone https://github.com/Dicklesworthstone/scoop-bucket
scoop install dicklesworthstone/cm
```

</div>

---

## 🤖 Agent Quickstart (JSON)

**Always use `--json` in agent contexts.** stdout = data, stderr = diagnostics, exit 0 = success.

```bash
# 1) Get task-specific memory before you start
cm context "implement auth rate limiting" --json

# 2) See the minimum viable workflow
cm quickstart --json

# 3) Build the playbook (memory onboarding)
cm onboard status --json
cm onboard sample --fill-gaps --json
cm onboard read /path/to/session.jsonl --template --json
cm onboard mark-done /path/to/session.jsonl
```

## Table of Contents

- [Why This Exists](#-why-this-exists)
- [How It Works](#-how-it-works)
- [Key Features](#-key-features)
- [For AI Agents](#-for-ai-agents-the-most-important-section)
- [Installation](#-installation)
- [CLI Reference](#-cli-reference)
- [The ACE Pipeline](#-the-ace-pipeline)
- [Data Models](#-data-models)
- [Scoring Algorithm](#-scoring-algorithm)
- [Configuration](#-configuration)
- [MCP Server](#-mcp-server)
- [Architecture & Engineering](#-architecture--engineering)
- [Deep Dive: Core Algorithms](#-deep-dive-core-algorithms)
- [Privacy & Security](#-privacy--security)
- [Trauma Guard: Safety System](#-trauma-guard-safety-system)
- [Performance Characteristics](#-performance-characteristics)
- [Starter Playbooks](#-starter-playbooks)
- [Extensibility](#-extensibility-adding-new-components)
- [Troubleshooting](#-troubleshooting)
- [Design Philosophy](#-design-philosophy)
- [Comparison with Alternatives](#-comparison-with-alternatives)
- [Roadmap](#-roadmap)

---

## 💡 Why This Exists

### The Problem

AI coding agents accumulate valuable knowledge through sessions: debugging strategies, code patterns, user preferences, project-specific insights. But this knowledge is:

1. **Trapped in sessions** — Each session ends, context is lost forever
2. **Agent-specific** — Claude Code doesn't know what Cursor learned yesterday
3. **Unstructured** — Raw conversation logs aren't actionable as guidance
4. **Subject to collapse** — Naive summarization loses critical nuances and details

You've solved authentication bugs three times this month across different agents. Each time, you started from scratch because the knowledge from previous sessions was inaccessible.

### The Solution

`cass-memory` implements a **three-layer cognitive architecture** that transforms raw session logs into actionable, confidence-tracked rules:

| Layer | Role | Implementation |
|-------|------|----------------|
| **Episodic Memory** | Raw ground truth from all agents | `cass` search engine |
| **Working Memory** | Structured session summaries | Diary entries |
| **Procedural Memory** | Distilled rules with tracking | Playbook bullets |

This mirrors how human expertise develops: raw experiences (episodic) are consolidated into structured memories (working), which eventually become automatic knowledge (procedural).

### Who Benefits

- **AI Agents**: Get relevant rules and historical context before starting any task
- **Developers**: Build institutional memory that persists across tools and sessions
- **Teams**: Share patterns discovered by any team member's AI assistant
- **Power Users**: Create sophisticated workflows that leverage cross-agent learning

---

## 🔄 How It Works

```
┌─────────────────────────────────────────────────────────────────────┐
│                    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 bridging raw logs to rules           │
│   accomplishments │ decisions │ challenges │ outcomes               │
└───────────────────────────┬─────────────────────────────────────────┘
                            │ reflect + curate (automated)
                            ▼
┌─────────────────────────────────────────────────────────────────────┐
│                    PROCEDURAL MEMORY (Playbook)                     │
│   Distilled rules with confidence tracking                          │
│   Rules │ Anti-patterns │ Feedback │ Decay                          │
└─────────────────────────────────────────────────────────────────────┘
```

Every agent's sessions feed the shared memory. A pattern discovered in Cursor **automatically** helps Claude Code on the next session.

---

## ✨ Key Features

### Cross-Agent Learning

Sessions from all your AI coding agents feed a unified knowledge base:

```
Claude Code session    →  ┐
Cursor session         →  │→  Unified Playbook  →  All agents benefit
Codex session          →  │
Aider session          →  │
PI session             →  ┘
```

A debugging technique discovered in Cursor is immediately available to Claude Code. No manual knowledge transfer required.

### Confidence Decay System

Rules aren't immortal. A rule helpful 8 times in January but never validated since loses confidence over time:

- **90-day half-life**: Confidence halves every 90 days without revalidation
- **4x harmful multiplier**: One mistake counts 4× as much as one success
- **Maturity progression**: `candidate` → `established` → `proven`

This prevents stale rules from polluting your playbook while rewarding consistently helpful guidance.

### 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, it's automatically inverted into an anti-pattern that warns future agents away from the same mistake.

### Scientific Validation

New rules aren't blindly accepted. Before a rule joins your playbook, it's validated against your 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.

### Graceful Degradation

The system works even when components are missing:

| Condition | Behavior |
|-----------|----------|
| No cass | Playbook-only scoring, no history snippets |
| No playbook | Empty playbook, commands still work |
| No LLM | Deterministic reflection, no semantic enhancement |
| Offline | Cached playbook + local diary |

You always get value, even in degraded conditions.

---

## 🤖 For AI Agents: The Most Important Section

`cass-memory` is designed **specifically** for AI coding agents—not just as an afterthought, but as a first-class design goal. When you're an AI agent working on a codebase, cross-agent memory becomes invaluable: rules learned by other agents, context about design decisions, debugging approaches that worked, and institutional memory that would otherwise be lost.

### Why Cross-Agent Memory Matters

Imagine you're Claude Code working on a React authentication bug. With `cass-memory`, you can instantly access:
- Rules extracted from previous Claude sessions about auth patterns
- Debugging strategies discovered by Cursor last week
- Anti-patterns identified when Codex hit the same issue
- Historical context from Aider about the codebase's auth architecture

This cross-pollination of knowledge across different AI agents is transformative. Each agent has different strengths, different context windows, and encounters different problems. `cass-memory` unifies all this collective intelligence into a single, searchable, actionable knowledge base.

### The One Command You Need

```bash
cm context "<your task>" --json
```

**Run this command before starting any non-trivial task.** It returns:
- **Relevant rules** from the playbook (scored by task relevance)
- **Historical context** from past sessions (yours and other agents')
- **Anti-patterns** to avoid (things that have caused problems)
- **Suggested searches** for deeper investigation

### Self-Documenting API

`cass-memory` teaches agents how to use it—no external documentation required:

```bash
# Quick capability check and self-explanation
cm quickstart --json
# → Returns complete explanation of the system and how to use it

# System health and available features
cm doctor --json
# → { checks: [...], recommendations: [...], ... }

# Get relevant context for a task
cm context "implement user authentication" --json
# → { relevantBullets: [...], antiPatterns: [...], historySnippets: [...] }
```

### Structured Output Format

Every command supports `--json` for machine-readable output:

```bash
cm context "fix the auth timeout bug" --json
```

```json
{
  "success": true,
  "task": "fix the auth timeout bug",
  "relevantBullets": [
    {
      "id": "b-8f3a2c",
      "content": "Always check token expiry before other auth debugging",
      "effectiveScore": 8.5,
      "maturity": "proven",
      "relevanceScore": 0.92,
      "reasoning": "Extracted from 5 successful sessions"
    }
  ],
  "antiPatterns": [
    {
      "id": "b-x7k9p1",
      "content": "Don't cache auth tokens without expiry validation",
      "effectiveScore": 3.2
    }
  ],
  "historySnippets": [
    {
      "source_path": "~/.claude/sessions/session-001.jsonl",
      "agent": "claude",
      "origin": { "kind": "local" },
      "snippet": "Fixed timeout by increasing token refresh interval...",
      "score": 0.87
    }
  ],
  "suggestedCassQueries": [
    "cass search 'authentication timeout' --robot --days 30"
  ],
  "degraded": null
}
```

**Design principle**: stdout contains only parseable JSON data; all diagnostics go to stderr.

**Filtering remote vs local history:** `historySnippets[].origin.kind` is `"local"` or `"remote"`; remote hits include `origin.host`.

### Error Handling for Agents

Errors are structured and include recovery hints:

```json
{
  "success": false,
  "code": "PLAYBOOK_NOT_FOUND",
  "error": "Playbook file not found at ~/.cass-memory/playbook.yaml",
  "hint": "Run 'cm init' to create a new playbook",
  "retryable": false
}
```

### Token Budget Management

AI agents have context limits. `cass-memory` provides controls to manage output size:

| Flag | Effect |
|------|--------|
| `--limit N` | Cap number of rules returned |
| `--min-score N` | Only return rules above score threshold |
| `--no-history` | Skip historical snippets (faster, smaller) |
| `--json` | Structured output for parsing |

### Inline Feedback (During Work)

When a rule helps or hurts during your work, leave inline feedback:

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

These comments are automatically parsed during reflection and update rule confidence.

### Session Outcome Recording

After completing a task, record the outcome:

```bash
# Record successful outcome (positional: status, rules)
cm outcome success b-8f3a2c,b-xyz789 --summary "Fixed auth bug"

# Record failure
cm outcome failure b-x7k9p1 --summary "Rule led to wrong approach"

# Apply recorded outcomes to playbook
cm outcome-apply
```

### What NOT to Do

You do NOT need to:
- Run `cm reflect` (automation handles this)
- Run `cm mark` manually (use inline comments instead)
- Manually add rules to the playbook
- Worry about the learning pipeline

The system learns from your sessions automatically. Your job is just to **query context before working**.

### Ready-to-Paste Blurb for AGENTS.md / CLAUDE.md

```markdown
## Memory System: cass-memory

The Cass Memory System (cm) is a tool for giving agents an effective memory based on the ability to quickly search across previous coding agent sessions across an array of different coding agent tools (e.g., Claude Code, Codex, Gemini-CLI, Cursor, etc) and projects (and even across multiple machines, optionally) and then reflect on what they find and learn in new sessions to draw out useful lessons and takeaways; these lessons are then stored and can be queried and retrieved later, much like how human memory works.

The `cm onboard` command guides you through analyzing historical sessions and extracting valuable rules.

### Quick Start

```bash
# 1. Check status and see recommendations
cm onboard status

# 2. Get sessions to analyze (filtered by gaps in your playbook)
cm onboard sample --fill-gaps

# 3. Read a session with rich context
cm onboard read /path/to/session.jsonl --template

# 4. Add extracted rules (one at a time or batch)
cm playbook add "Your rule content" --category "debugging"
# Or batch add:
cm playbook add --file rules.json

# 5. Mark session as processed
cm onboard mark-done /path/to/session.jsonl
```

Before starting complex tasks, retrieve relevant context:

```bash
cm context "<task description>" --json
```

This returns:
- **relevantBullets**: Rules that may help with your task
- **antiPatterns**: Pitfalls to avoid
- **historySnippets**: Past sessions that solved similar problems
- **suggestedCassQueries**: Searches for deeper investigation

### Protocol

1. **START**: Run `cm context "<task>" --json` before non-trivial work
2. **WORK**: Reference rule IDs when following them (e.g., "Following b-8f3a2c...")
3. **FEEDBACK**: Leave inline comments when rules help/hurt:
   - `// [cass: helpful b-xyz] - reason`
   - `// [cass: harmful b-xyz] - reason`
4. **END**: Just finish your work. Learning happens automatically.

### Key Flags

| Flag | Purpose |
|------|---------|
| `--json` | Machine-readable JSON output (required!) |
| `--limit N` | Cap number of rules returned |
| `--no-history` | Skip historical snippets for faster response |

stdout = data only, stderr = diagnostics. Exit 0 = success.
```

---

## 🎓 Agent-Native Onboarding

Building a playbook from scratch can be daunting—but you don't need to spend money on LLM API calls to do it. The **agent-native onboarding** system leverages the AI coding agent you're already paying for (via Claude Max, ChatGPT Pro, Cursor Pro, etc.) to analyze historical sessions and extract rules.

### The Zero-Cost Approach

Traditional approaches to building a playbook might suggest using external LLM APIs to analyze sessions and extract rules. But if you're already running an AI coding agent, **that agent can do the analysis work itself**—at no additional cost.

```
Traditional approach:
  Sessions → External LLM API → Rules → $ cost per session

Agent-native approach:
  Sessions → Your Agent (already paid for) → Rules → $0 additional cost
```

The `cm onboard` command guides your agent through analyzing historical sessions and extracting valuable rules.

### Quick Start

```bash
# 1. Check status and see recommendations
cm onboard status

# 2. Get sessions to analyze (filtered by gaps in your playbook)
cm onboard sample --fill-gaps

# 3. Read a session with rich context
cm onboard read /path/to/session.jsonl --template

# 4. Add extracted rules (one at a time or batch)
cm playbook add "Your rule content" --category "debugging"
# Or batch add:
cm playbook add --file rules.json

# 5. Mark session as processed
cm onboard mark-done /path/to/session.jsonl
```

### Gap Analysis

Not all playbook categories are equally represented. The gap analysis system identifies **underrepresented categories** so you can prioritize which sessions to analyze.

**Categories tracked:**
- `debugging` — Error resolution, bug fixing, tracing
- `testing` — Unit tests, mocks, assertions, coverage
- `architecture` — Design patterns, module structure, abstractions
- `workflow` — Task management, CI/CD, deployment
- `documentation` — Comments, READMEs, API docs
- `integration` — APIs, HTTP, JSON parsing, endpoints
- `collaboration` — Code review, PRs, team coordination
- `git` — Version control, branching, merging
- `security` — Auth, encryption, vulnerability prevention
- `performance` — Optimization, caching, profiling

**Category status thresholds:**
| Status | Rule Count | Priority |
|--------|------------|----------|
| `critical` | 0 rules | High |
| `underrepresented` | 1-2 rules | Medium |
| `adequate` | 3-10 rules | Low |
| `well-covered` | 11+ rules | None |

```bash
# View detailed gap analysis
cm onboard gaps

# Sample sessions prioritized for gap-filling
cm onboard sample --fill-gaps
```

### Progress Tracking

Onboarding progress persists across sessions, so agents can resume where they left off even after context window limits are reached.

**State stored at:** `~/.cass-memory/onboarding-state.json`

```json
{
  "version": 1,
  "startedAt": "2025-01-15T10:30:00Z",
  "lastUpdatedAt": "2025-01-15T14:45:00Z",
  "processedSessions": [
    {
      "path": "/Users/x/.claude/sessions/session-001.jsonl",
      "processedAt": "2025-01-15T11:00:00Z",
      "rulesExtracted": 3
    }
  ],
  "stats": {
    "totalSessionsProcessed": 5,
    "totalRulesExtracted": 12
  }
}
```

Commands for progress management:
```bash
# Check progress
cm onboard status

# Mark a session as done (even if no rules extracted)
cm onboard mark-done /path/to/session.jsonl

# Reset progress to start fresh
cm onboard reset
```

### Batch Rule Addition

After analyzing a session, add multiple rules at once using the batch add feature:

```bash
# Create a JSON file with rules
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 at once
cm playbook add --file rules.json

# Or pipe from another command
echo '[{"content": "Rule from stdin", "category": "workflow"}]' | cm playbook add --file -

# Track which session the rules came from
cm playbook add --file rules.json --session /path/to/session.jsonl
```

The `--session` flag automatically updates onboarding progress, crediting the session with the number of rules extracted.

### Template Output for Rich Context

The `--template` flag provides agents with rich contextual information to guide extraction:

```bash
cm onboard read /path/to/session.jsonl --template --json
```

**Template output includes:**

```json
{
  "metadata": {
    "path": "/path/to/session.jsonl",
    "workspace": "/Users/x/project",
    "messageCount": 127,
    "topicHints": ["debugging", "testing", "git"]
  },
  "context": {
    "relatedRules": [
      {"id": "b-abc123", "content": "...", "similarity": 0.72}
    ],
    "playbookGaps": {
      "critical": ["security", "performance"],
      "underrepresented": ["collaboration"]
    },
    "suggestedFocus": "This session may contain security patterns - you have NO rules in this area!"
  },
  "extractionFormat": {
    "sch
