cass-memory
!Platform !Runtime !Status !License
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.
One-liner install (Linux/macOS):
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/cass_memory_system/main/install.sh?$(date +%s)" \
| bash -s -- --easy-mode --verify
Or via package managers:
# macOS/Linux (Homebrew)
brew install dicklesworthstone/tap/cm
Windows (Scoop)
scoop bucket add dicklesworthstone https://github.com/Dicklesworthstone/scoop-bucket
scoop install dicklesworthstone/cm
🤖 Agent Quickstart (JSON)
Always use --json in agent contexts. stdout = data, stderr = diagnostics, exit 0 = success.
# 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
- How It Works
- Key Features
- For AI Agents
- Installation
- CLI Reference
- The ACE Pipeline
- Data Models
- Scoring Algorithm
- Configuration
- MCP Server
- Architecture & Engineering
- Deep Dive: Core Algorithms
- Privacy & Security
- Trauma Guard: Safety System
- Performance Characteristics
- Starter Playbooks
- Extensibility
- Troubleshooting
- Design Philosophy
- Comparison with Alternatives
- 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:
- Trapped in sessions — Each session ends, context is lost forever
- Agent-specific — Claude Code doesn't know what Cursor learned yesterday
- Unstructured — Raw conversation logs aren't actionable as guidance
- Subject to collapse — Naive summarization loses critical nuances and details
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
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
cass-memory unifies all this collective intelligence into a single, searchable, actionable knowledge base.
The One Command You Need
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:
# 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:
cm context "fix the auth timeout bug" --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:
{
"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:
// [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:
# 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
Use the same workspace that supplied the rules
cm outcome success b-8f3a2c --workspace ~/code/api --summary "Fixed auth bug"
cm outcome-apply --workspace ~/code/api
The CLI saves the outcome before applying feedback. --workspace defaults to the
current directory; pass the same project used for context retrieval. Each new
record retains its workspace, event ID, and the playbook owning each rule, so
replaying the log from another directory cannot redirect feedback. Replaying an
event applies it at most once per rule. An ID that was unknown when recorded does
not later credit an unrelated rule created with that ID.
Recovered legacy files may contain distinct rules sharing an ID. mark and
outcome application reject feedback for an ambiguous ID within its owning
playbook. Outcome batches check every requested destination before changing any
feedback. Assign distinct IDs deliberately, then retry the recorded outcome;
the original rules and feedback remain intact. A unique repository rule can
still override the same ID in the global playbook.
If the configured global playbook changes before a recorded outcome is applied, select its original playbook explicitly:
cm outcome-apply --workspace ~/code/api --playbook ~/memory/original-playbook.yaml --json
The selected path comes from your command or user configuration. Paths recorded
inside repository outcome logs do not grant permission to write other global
playbooks. Default replay applies records for the configured owner and reports
other owners as a partial failure, including the applied count and
skippedOwners. Explicit --playbook replay selects that owner, reports other
groups as skipped, and fails if no loaded records match. Legacy records without
global ownership continue to use the selected playbook and recorded workspace.
An unavailable or corrupt original playbook remains an error; feedback does not
fall back to a different rule with the same ID. Replaying completed events is
safe because their original event IDs are retained.
Automatic reflection saves prepared outcomes with the session's processed marker. If outcome logging or feedback fails, the next non-dry reflection using that processed log retries the pending work, even when there are no new sessions. The retry uses the original event and does not call the reflector again. Partial feedback application and interrupted acknowledgements can be retried safely; errors remain visible while work is pending. This recovery covers outcome delivery after curation; it is not a transaction spanning all playbook and processed-log writes.
New transcript-backed automatic outcomes also retain the source records that mentioned each rule. Reprocessing those records through a different workspace's processed log does not add confidence again, even if the inferred verdict changes. Appended records can provide new evidence. Each applied grading batch with new evidence contributes one event; the keys track record consumption, not a universal event count independent of how sessions were batched. This protection is prospective: older events lack the provenance needed to identify overlaps. Automatic confidence changes abstain when structured source records are unavailable; explicit inline feedback and manual outcomes still work.
What NOT to Do
You do NOT need to:
- Run
cm reflect(automation handles this) - Run
cm markmanually (use inline comments instead) - Manually add rules to the playbook
- Worry about the learning pipeline
Ready-to-Paste Blurb for AGENTS.md / CLAUDE.md
## 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 status2. Get sessions to analyze (filtered by gaps in your playbook)
cm onboard sample --fill-gaps3. Read a session with rich context
cm onboard read /path/to/session.jsonl --template4. 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.json5. Mark session as processed
cm onboard mark-done /path/to/session.jsonlBefore starting complex tasks, retrieve relevant context:bash
cm context "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
- START: Run
cm context "<task>" --json before non-trivial work
- WORK: Reference rule IDs when following them (e.g., "Following b-8f3a2c...")
- FEEDBACK: Leave inline comments when rules help/hurt:
- // [cass: helpful b-xyz] - reason
- // [cass: harmful b-xyz] - reason
- 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
# 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, tracingtesting— Unit tests, mocks, assertions, coveragearchitecture— Design patterns, module structure, abstractionsworkflow— Task management, CI/CD, deploymentdocumentation— Comments, READMEs, API docsintegration— APIs, HTTP, JSON parsing, endpointscollaboration— Code review, PRs, team coordinationgit— Version control, branching, mergingsecurity— Auth, encryption, vulnerability preventionperformance— Optimization, caching, profiling
critical | 0 rules | High |
| underrepresented | 1-2 rules | Medium |
| adequate | 3-10 rules | Low |
| well-covered | 11+ rules | None |
# 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
{
"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:
# 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:
# 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:
cm onboard read /path/to/session.jsonl --template --json
Template output includes:
{
"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": {
"schema": {"content": "string", "category": "string"},
"categories": ["debugging", "testing", "architecture", ...],
"examples": [...]
},
"sessionContent": "..."
}
Template features:
- Topic hints: Categories detected from session content using keyword matching
- Related rules: Existing playbook rules similar to the session content (via semantic search if enabled)
- Playbook gaps: Categories with missing or few rules
- Suggested focus: AI-generated guidance on what to prioritize based on gaps and detected topics
- Examples: Sample rules showing proper format for each category
Gap-Targeted Sampling Algorithm
When using --fill-gaps, the sampling algorithm prioritizes sessions likely to contain patterns for underrepresented categories:
1. Analyze playbook → Identify critical/underrepresented categories
- Generate search queries from category keywords:
- "security" → "security auth token"
- "performance" → "performance optimize cache"
- Search cass with gap-targeted queries
- Score each session against gaps:
- Session matches critical category: +3 points
- Session matches underrepresented category: +2 points
- Session matches adequate category: +1 point
- Sort sessions by gap score (highest first)
- Filter out already-processed sessions
- Return top N sessions
Category keyword detection uses a lightweight approach (no external APIs required):
// Example: detecting categories from text
const CATEGORY_KEYWORDS = {
debugging: ["debug", "error", "fix", "bug", "trace", "stack", ...],
testing: ["test", "mock", "assert", "expect", "jest", "vitest", ...],
security: ["security", "auth", "token", "encrypt", "permission", ...],
// ... more categories
};
// Count keyword matches → category with most matches wins
Targeted Sampling Options
Filter sessions by various criteria to focus on specific areas:
# Filter by workspace/project
cm onboard sample --workspace /Users/x/my-project
Filter by agent
cm onboard sample --agent claude
cm onboard sample --agent cursor
Filter by recency
cm onboard sample --days 30
Combine filters
cm onboard sample --agent claude --days 14 --workspace /Users/x/api-project
Include already-processed sessions (for re-analysis)
cm onboard sample --include-processed
Adjust sample size
cm onboard sample --limit 20
Onboarding Workflow for Agents
Recommended protocol for AI agents doing onboarding:
## Onboarding Protocol
Phase 1: Assessment
- Run
cm onboard status --json to check current progress
- Run
cm onboard gaps --json to see category distribution
- Decide target: ~20 rules across diverse categories for a good initial playbook
Phase 2: Session Analysis Loop
For each session until target reached:
cm onboard sample --fill-gaps --json → get prioritized sessions
cm onboard read <path> --template --json → get session with context
- Analyze session content, identify 2-5 reusable patterns
- Format as rules following extraction guidelines
cm playbook add --file rules.json --session <path> → add rules
- Repeat with next session
Phase 3: Verification
cm onboard status → verify progress
cm onboard gaps → check remaining gaps
cm stats --json → verify playbook health
Why Agent-Native Onboarding?
- Zero additional cost: Uses the AI agent you're already paying for
- Better analysis: Your agent understands your codebase context
- Resumable: Progress persists across sessions
- Gap-aware: Automatically prioritizes underrepresented categories
- Batch-friendly: Add multiple rules efficiently
- Self-documenting: Template output guides extraction
📦 Installation
One-Liner (Recommended)
Recommended: Homebrew (macOS/Linux)
brew install dicklesworthstone/tap/cm
This method provides:
- Automatic updates via
brew upgrade - Dependency management
- Easy uninstall via
brew uninstall
Windows: Scoop
scoop bucket add dicklesworthstone https://github.com/Dicklesworthstone/scoop-bucket
scoop install dicklesworthstone/cm
Alternative: Install Script
Linux/macOS:
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/cass_memory_system/main/install.sh?$(date +%s)" \
| bash -s -- --easy-mode --verify
Direct Downloads:
- Linux x64
- Linux ARM64 (releases after v0.2.14; e.g. Linux containers on Apple Silicon, Graviton)
- macOS Apple Silicon
- macOS Intel
- Windows x64
Installer Options
# Full options
install.sh [--version vX.Y.Z] [--dest DIR] [--system] [--easy-mode] [--verify]
[--from-source] [--artifact-url URL] [--checksum HEX]
[--checksum-url URL] [--quiet]
Examples
install.sh --version v0.6.0 --verify # Specific version
install.sh --system --verify # Install to /usr/local/bin (requires sudo)
install.sh --from-source --version v0.6.0 # Build that release from source (requires bun)
| Flag | Effect |
|------|--------|
| --version | Install a specific release, including source builds (default: latest) |
| --dest DIR | Install to custom directory (default: ~/.local/bin) |
| --system | Install to /usr/local/bin (requires sudo) |
| --easy-mode | Non-interactive, auto-configure PATH |
| --verify | Run self-test after install |
| --from-source | Build the selected release with its frozen Bun lockfile |
| --artifact-url URL | Download this exact custom artifact; failure does not fall back to repository source |
| --checksum HEX | Require this 64-character SHA256 digest before installing a downloaded artifact |
| --checksum-url URL | Require a valid SHA256 digest from this URL and verify the downloaded artifact |
| --quiet | Suppress output |
Installer Robustness
The installer is designed for reliability:
- No API rate limits: Uses GitHub redirect detection instead of API calls, avoiding the 60 requests/hour unauthenticated limit
- Checksum verification: Downloads release
.sha256sidecars. An explicit checksum or checksum URL is mandatory: missing data, malformed digests, missing verification tools, and mismatches stop installation. Without an explicit requirement, unavailable sidecars or tools retain the existing warning-only behavior. - Concurrent install protection: Lock file prevents multiple installers from running simultaneously
- Version-preserving fallbacks: If a standard release binary cannot be used, builds the same selected release from source. A missing source ref fails instead of substituting
main. - Cross-platform checksums: Uses
sha256sumon Linux,shasum -a 256on macOS
ARTIFACT_URL, CHECKSUM, and CHECKSUM_URL environment variables enforce the same requirements as their command-line options.
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
Prerequisites
- cass CLI: The episodic memory layer. Install from cass repo
- LLM API Key (optional): For AI-powered reflection. Set
ANTHROPIC_API_KEY,OPENAI_API_KEY, orGOOGLE_GENERATIVE_AI_API_KEY
Building cass from source requires rustup + nightly. The cass source tree's
.cargo/config.tomlunconditionally passes the nightly-only-Z threadsrustflag,
and its rust-toolchain.toml pins a nightly channel that only a rustup proxy will
honor. A non-rustup Rust (e.g. Homebrew'scargo/rustc) fails before compilation
with `the optionZis only accepted on the nightly compiler. If you need to
build a cass fix from source (e.g. a commit not yet in a stable release), install
rustup and run rustup toolchain install nightly first.
cm doctor reports whether cass is missing entirely or merely has an unavailable
lexical index (fix the latter with cass index --full).
Verify Installation
cm --version
cm doctor --json
Initial Setup
# Initialize (creates global config and playbook)
cm init
Or with a starter playbook for common patterns
cm init --starter typescript # or: react, python, go
cm starters # list available starters
Automating Reflection
The key to the system is automated reflection. Set up a cron job or hook:
# Daily reflection on recent sessions
cm reflect --days 7 --json
Only one project's sessions, only some agents
cm reflect --workspace ~/code/api --agent claude,codex --json
Via cron (runs at 2am daily)
0 2 * /usr/local/bin/cm reflect --days 7 >> ~/.cass-memory/reflect.log 2>&1
If session discovery or processing fails, cm reflect exits nonzero and its
JSON envelope has success: false with error.code: "REFLECTION_FAILED".
Successful work from other sessions remains committed and is reported in data,
alongside sessionsProcessed, deltasGenerated, and errors. Dry runs report
failures the same way while retaining proposed deltas. Ordinary diagnostic
warnings do not make an otherwise successful run fail. Scheduled jobs can check
the process exit status; failed sessions remain eligible for a later retry.
Reflection checks destructive proposals against the rules the model actually read. If a rule was corrected, removed, repinned, or moved to another scope while the model was running, that session fails without applying its proposals or advancing its processing watermark. Other sessions can still commit. Retry the affected session against the current rules; concurrent feedback and confidence updates are retained and do not by themselves invalidate a proposal.
Reflection also recovers interrupted storage commits. Before replacing any
playbook, it persists the exact prepared changes and their session watermarks.
If the process stops between playbook writes or before the processing ledger is
acknowledged, rerun the command: recovery finishes those prepared changes without
calling the model again or counting the sessions twice. JSON reports this work
in recoveredCommits, separately from newly processed sessions. A recovery run
then returns; the next invocation can process new sessions. Pending automatic
outcomes retain their original identities and are delivered after recovery.
If automatic outcome delivery fails after the commit is complete, its queue
remains discoverable by later reflection runs using the same global playbook,
including runs launched from a different workspace. Each retry reports unresolved
storage errors through the normal failure result and retries the original outcome
IDs and feedback destinations. Once storage is repaired, delivery resumes without
applying feedback twice. JSON includes completed delivery in autoOutcome, even
when no new sessions were processed. A dry run does not deliver or acknowledge
queued outcomes.
If an older compacted ledger no longer identifies which global playbook owns a
queued outcome, reflection reports that ambiguity and preserves the queue for
inspection.
Discovery inspects at most 1,024 directory entries and 64 MiB of ledger data per
scan. Each global playbook's queue index holds up to 256 ledger paths within
1 MiB. Ledger writers atomically compact obsolete history before an append
would exceed 64 MiB, retaining current session watermarks, commit receipts,
owner information, and pending outcomes. New commits check both ledger and
index capacity before publishing recovery intent or replacing playbooks.
Repository playbooks retain the fixed 16 MiB ceiling. The global playbook uses
its independently authorized trusted local limits.
Reflection checks each prospective playbook before publishing replacements. A
capacity failure leaves the last readable state in place, preserves retry work,
and reports failure. It does not silently remove candidates or feedback to make
room. cm doctor warns when expanded values, the largest array, or expanded
text/key bytes reach 90% of the selected limit. Review the explicit
retired-rule archive or trusted-limit recovery options.
Before publishing a reflection commit, cm also rechecks the destinations of queued feedback under their writer locks. If archival or another writer changed or removed a feedback target while the proposal was being prepared, publication fails and the session remains retryable. It does not acknowledge feedback for a rule that disappeared during the model call.
Recovery preserves subsequent feedback on files already committed. Normal playbook writes, embedding repair, and initialization refuse to change a target whose prepared replacement is still pending. Run reflection with the original global playbook to recover that transaction, then retry the requested operation. Edits to already-applied targets retain the receipt needed for recovery; resets that would discard it wait until the processing ledger has acknowledged the commit. Forget and undo check before changing their separate blocklists.
If an external editor changes an uncommitted destination, recovery retains both
versions and refuses to overwrite the newer data. The error identifies the
affected file; resolve that conflict before retrying. Keep the pending manifest
and its stage directory under ~/.cass-memory/reflections/commits/ until recovery succeeds.
--dry-run reports a pending commit and leaves it untouched. Each staged
playbook is validated against its destination's input limits; a commit is bounded to 64 target files,
256 MiB of staged data, and a 16 MiB manifest.
Each session uses its source project's applicable rules and reflection policy.
Inline feedback, replacements, deprecations, and merges retain that ownership
through curation. Linked worktrees use their local playbook when present and
otherwise fall back to the main worktree's playbook, while keeping the session
workspace's policy. The source project's additional redaction patterns apply
before diary or reflector requests. Automatically discovered sessions without
workspace provenance use global rules only. For an explicitly named session,
--workspace supplies a fallback; otherwise its launch directory is the fallback.
For Claude Code and Gemini CLI, opt into automatic reflection for your user. Finished sessions across your projects are reflected in the background using your configured LLM provider and budget:
cm hook install # Claude Code, your user across projects
cm hook install --agent gemini # Gemini CLI, your user across projects
cm hook install --global # Explicit user scope (the default)
cm hook status # Show user and shared project installations
cm hook uninstall # Remove your Claude Code user hook
cm hook uninstall --agent gemini # Remove your Gemini user hook
User settings are ~/.claude/settings.json (or $CLAUDE_CONFIG_DIR/settings.json) and ~/.gemini/settings.json. Reflection sends session content to the configured provider, subject to the usual privacy and budget settings. Installing the default hook does not change shared repository settings.
Use cm hook install --project [--agent gemini] only when you intend to share the hook through the repository's .claude/settings.json or .gemini/settings.json. Committing that file enables the hook for teammates who load those settings; the default shared command requires cm on their PATH. cm hook uninstall --project [--agent gemini] removes shared installations, including those created by older versions. Status lists both scopes, and removing cm's hook preserves unrelated hooks and matcher settings.
This adds a SessionEnd hook that runs cm hook session-end. It reads the transcript path from the hook payload and starts cm reflect --session detached, so the agent never waits on it. Output goes to ~/.cass-memory/hooks.log. It skips sessions cm itself started as its LLM (detected by transcript folder and by an environment marker the hook inherits, so it also covers Gemini's hashed folders), and sessions that end inside a background reflect, so it cannot loop. Codex has no session-end event, only a per-turn Stop, so it is not offered; use the --transcript entry point below from a wrapper. Reflection keeps your usual budget limits and processed-session tracking, so re-running a session costs nothing.
For other agents, call the same entry point from a wrapper script or the agent's own end-of-session hook:
cm hook session-end --transcript ~/.codex/sessions/2026/10/06/rollout.jsonl
Long sessions: reflect often. The diary step reads at most diaryMaxInputChars (default 50,000) characters of a transcript: the start, the end, and error/correction lines picked from the middle (see Reflection Settings). A session that goes on for hours can be much longer than that. cm reflect remembers how far into each session it got, and when a session has grown it reflects only the new part. Running it often (from a hook, or cron every 30–60 minutes) therefore keeps each new part small enough to be read in full. Raising diaryMaxInputChars is the other option when your model has the context for it.
Should agents write their own lessons? They don't need to. cm is built so that a separate reflection step pulls lessons out of the transcript, and the working agent can just finish its task. If your agents do end with a list such as Lessons for memory: ..., that is fine input: the diary step reads it like any other text in the transcript, as long as it falls inside the window above (the end of a session always does). Treat such lists as hints for the diary, not as rules: cm still checks candidate rules against history and feedback before trusting them.
🛠️ CLI Reference
Quick Reference Table
| Command | Purpose | Agent Use |
|---------|---------|-----------|
| cm context " | Get rules + history for task | Primary |
| cm quickstart --json | Self-documentation | Setup |
| cm robot-docs [topic] | Machine-readable docs: commands, examples, exit codes, JSON schemas | Integration |
| cm doctor --json | System health check | Diagnostics |
| cm playbook list | Show all rules | Inspection |
| cm similar " | Find similar rules | Search |
| cm stats --json | Playbook metrics | Analytics |
| cm trauma list | Show dangerous patterns | Safety |
| cm guard --install [--user] | Install the safety hook (project or every project) | Safety |
Error Output & Exit Codes
When --json (or --format json) is enabled, errors are printed to stdout as a single JSON object:
{
"success": false,
"error": "…",
"code": "…",
"exitCode": 2,
"recovery": ["…", "…"],
"cause": "…",
"docs": "README.md#-troubleshooting",
"hint": "…",
"details": {}
}
Exit codes are categorized for scripting:
- 1
internal (bug / unexpected) - 2
user input / usage - 3
configuration - 4
filesystem - 5
network - 6
cass - 7
LLM/provider
Agent Commands (Primary Workflow)
# Get context before starting a task (THE MAIN COMMAND)
cm context "implement user authentication" --json
Select a project's rules and explicit applicability selectors
cm context "review Python changes" --workspace ~/code/api --language python --task-type review --json
Rules only, without the cass history search (fast enough for prompt hooks)
cm context "fix the login bug" --history 0 --json
Self-documenting explanation of the system
cm quickstart --json
Find rules similar to a query
cm similar "error handling best practices"
Machine-readable CLI docs (JSON): all topics, or one of
guide | commands | examples | exit-codes | schemas
cm robot-docs
cm robot-docs schemas
cm robot-docs always prints one JSON document to stdout (data.schemaVersion, data.version, data.topics). commands is read from the live CLI definition, so it lists exactly the commands, arguments and options this build accepts. schemas gives JSON Schema (draft-07) for the JSON envelope (success and error) and for the data of context, quickstart and onboard status; the schemas are open, so ignore fields you don't know.
cm context --workspace selects the repository playbook, repository configuration,
history, and context-log location for that project. In a linked worktree, an
existing local playbook takes precedence; otherwise the main worktree's playbook
is used. Context logging and outcome feedback follow that same playbook owner.
Use --language, --framework, and --task-type to filter rules with the
corresponding named scope before ranking. Values match the rule's scopeKey
exactly after trimming whitespace. A supplied selector excludes other values and
rules missing that selector; global and applicable workspace rules remain
eligible. Omitting a selector keeps all values for that scope eligible, and does
not infer the language or framework from the task text. JSON output retains
scope and scopeKey so callers can inspect applicability.
Playbook Commands (Inspect & Manage Rules)
# List all active rules
cm playbook list
Get detailed info for a specific rule
cm playbook get b-8f3a2c
Add a new rule manually
cm playbook add "Always run tests before committing"
Remove/deprecate a rule
cm playbook remove b-xyz789 --reason "No longer applicable"
Export playbook for backup or sharing
cm playbook export > playbook-backup.yaml
Import playbook from file. Rules matching an existing one by text (exact,
or near-identical wording) merge their feedback into it instead of becoming
duplicates; direct instruction conflicts are reported for review.
cm playbook import shared-playbook.yaml
Restore loading of a trusted global playbook above the default resource limits
cm playbook repair --recover-limits --dry-run --json
cm playbook repair --recover-limits --json
Remove only derived inline embeddings from a trusted legacy playbook
cm playbook repair --strip-embeddings --dry-run --json
cm playbook repair --strip-embeddings --json
Move reviewed, unpinned retired rules out of active state, keeping a complete snapshot
cm playbook archive --retired --dry-run --json
cm playbook archive --retired --json
Review directly opposing instructions and their matched clause evidence
cm playbook conflicts --json
Strip feedback that came from cm's own LLM subprocess transcripts (or any
session path pattern), recount helpful/harmful, re-derive maturity.
Backs up each playbook first; bullets left without genuine support are
reported, and deprecated only with --deprecate-orphans.
cm playbook scrub --cm-subprocess-calls --dry-run --json
cm playbook scrub --from-sessions "/old-project/" --deprecate-orphans
Show top N most effective rules
cm top 10
Find rules without recent feedback (stale)
cm stale --days 60
Show why a rule exists (provenance)
cm why b-8f3a2c
Get playbook health metrics
cm stats --json
Learning Commands (Feedback & Reflection)
# Process recent sessions into rules (usually automated)
cm reflect --days 7 --json
Manual feedback on a rule
cm mark b-8f3a2c --helpful
cm mark b-xyz789 --harmful --reason "Caused regression"
Attribute feedback to the same project used for context retrieval
cm mark b-8f3a2c --helpful --workspace ~/code/api
Record session outcome (positional: status, rules)
cm outcome success b-8f3a2c,b-def456
cm outcome failure b-x7k9p1 --summary "Auth approach failed"
cm outcome success b-8f3a2c --workspace ~/code/api
Apply recorded outcomes to playbook
cm outcome-apply --workspace ~/code/api
Validate a proposed rule against history
cm validate "Always check null before dereferencing"
Deprecate a rule permanently
cm forget b-xyz789 --reason "Superseded by better pattern"
Revert a curation decision
cm undo b-xyz789
Check sessions for rule violations
cm audit --days 30
System Commands (Setup & Diagnostics)
``bash
Initialize configuration and playbook
cm init cm init --starter typescript # With starter template cm starters # List available startersCheck system health
cm doctor --json cm doctor --fix # Auto-fix issuesCheck for / install a newer release
cm update --check # Exit code 0 = up to date, 1 = update available cm update # Re-runs the documented install script (interactive only)Export rules for AGENTS.md
cm project --format agents.mdShow LLM cost and usage statistics
cm usageRun MCP HTTP server for agent integration (default: 127.0.0.1:8765)
cm servePrivacy controls
cm privacy status cm privacy enable # Enable cross-agent enrichment cm pri... (README truncated for length)