Skip to content
Proyectos

Acerca de

Memoria procedimental para agentes de programación con IA: transforma el historial disperso de las sesiones en una memoria persistente compartida entre agentes, para que todos aprendan unos de otros.

Herramientas de desarrollo

Cómo se miden estas cifras

Crecimiento de estrellas medido

in 24h
+7
in 7 days
+19
in 15 days
+19
in 1 month
Recopilando historial

Cambios netos en períodos que se solapan, no totales diarios. Los datos no disponibles se dejan en blanco. Las estrellas indican interés, no calidad.

README.md

Original

cass-memory

cass-memory - Procedural memory for AI coding agents

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

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 independent sessions explicitly support this instruction → ACTIVE

Rules without historical evidence are flagged as candidates until proven.

Reflection checks other sessions for corroboration and excludes recognizable CM-generated transcripts. Workspace rules use evidence from the source project. Global rules can also use configured remote histories. The evidence gate and model judge the same search results within validationLookbackDays. Automatic verdicts from cm validate --json include the snippets that led to the decision.

For language, framework, and task rules, validation also checks the exact scopeKey that defines where the instruction applies. That selector helps find relevant history; it does not itself prove that a session supports the rule. Evidence from a different or unknown scope is neutral, so Python-only examples cannot corroborate a Rust-specific instruction. A missing or blank selector, or one longer than 1,000 characters, keeps the proposed rule in draft without searching history or calling a model.

Anti-patterns are evaluated as warnings: successful use of a behavior does not corroborate a warning against that behavior, while observed harm or successful avoidance can. Explicit prohibitions such as "Never disable certificate checks" retain their written meaning; marking them as pitfalls does not reverse them.

Newly reflected rules also retain their validation history: the exact instruction evaluated, source session and diary, verdict and reason, and grounded archive citations. Citations keep their original path and line, source/conversation IDs when available, and the actual SSH target for remote evidence. A disabled or skipped check is recorded explicitly; it does not invent a successful validation. Repeated observations are deduplicated and these records add no helpful votes.

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

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 Sets the minimum task relevance on the 0–10 scale (inclusive). Overrides minRelevanceScore and preserves the configured relative relevance floor.
--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

# Grade the rules shown in this session's logged briefing
cm context "Test database migrations" --session migration-check --log-context
cm outcome success --session migration-check

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

For automated submissions, pass a stable --request-id to cm outcome or requestId to MCP cm_outcome. Retry with the same workspace and outcome details after a lost response. The retry returns the original event ID and uses the original rule owners, even if the checkout has since acquired its own playbook. A changed payload or global playbook produces an error. Use a new request ID for each independent observation in a session. A keyed submission also records an empty briefing so a later retry cannot credit rules that appeared after that observation.

After a project or linked worktree gains a local playbook, outcome-apply can still replay events recorded for that checkout in its previous shared log. It fills --limit from the current log first, then looks in the main worktree and global logs for records carrying the checkout's workspace. Use --session to recover a specific session even behind newer events. Use --outcome-id <id> to replay one event from a session. When feedback application fails after an outcome has been recorded, the CLI reports its ID and the exact replay command. In JSON mode, error.details.argv contains the arguments for that command. Replaying the event preserves feedback already saved before the interruption.

Omitting the rule list requires --session. The CLI uses the latest logged briefing for that session and checkout. These inferred citations use the automatic grading policy, including its guard against assigning a failure to a large set of displayed rules. An empty or missing briefing produces a no-effect result.

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.

When original transcript records identify a rule, automatic outcomes, reflector feedback, inline annotations, and duplicate-rule reinforcement share the same evidence accounting. Reprocessing those records through another workspace's log or another grading method does not add confidence again, even if the inferred verdict changes. Inline annotations on separate records retain their distinct judgments, and direct rule feedback takes precedence over duplicate-rule reinforcement. Appended records can provide new evidence, including a later occurrence of identical text. Each applied judgment with new evidence contributes one event; event counts can still depend on how observations were grouped.

cm undo and cm playbook scrub retain opaque retraction markers so replay and playbook import cannot restore the withdrawn events or reuse their recorded evidence. 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 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

## 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" --session /path/to/session.jsonl
# Or batch add:
cm playbook add --file rules.json --session /path/to/session.jsonl

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

Before starting complex tasks, retrieve relevant context:

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" --session /path/to/session.jsonl
# Or batch add:
cm playbook add --file rules.json --session /path/to/session.jsonl

# 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
# 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", "antiPattern": true},
  {"content": "Use a context manager when opening files", "category": "workflow", "scope": "language", "scopeKey": "python"}
]
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 stores the session path on each added rule so cm why can trace its source. Successful single and batch adds accumulate in the session's progress count. Marking the session done preserves that count.

Batch entries can set scope to language, framework, or task with an exact scopeKey. Selectors are trimmed, must be nonempty, and have a 1,000-character limit. Identical text with different selectors remains separate, including when replaying the same extraction session. --check --strict compares potential duplicates within the same applicability and rule interpretation.

Omitting both fields uses the destination default: global, or workspace with --repo. The --repo flag chooses storage; a named rule stored there also stays limited to that repository. Explicit workspace scope requires --repo, and batch entries cannot supply an arbitrary workspace path. Invalid or incomplete scope metadata is reported as an entry error instead of becoming global advice.

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

Reading a session uses its recorded project directory, including local transcript metadata when cass is unavailable or the session is outside the timeline window. The template shows that project's applicable global and repository rules and category gaps. To choose a different project for extraction, pass --workspace /path/to/project. Redaction patterns from both the selected project and the session's source project remain active. Session metadata stays separate from the chosen project context: unknown source workspaces are reported as null, and estimated message counts carry messageCountApproximate: true.

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: Applicable playbook rules similar to the session content, using semantic search when available and keyword relevance when embeddings are disabled or fail. context.relatedRulesMode identifies the method; a successful semantic search with no matches remains empty.
  • 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
2. Generate search queries from category keywords:
   - "security" → "security auth token"
   - "performance" → "performance optimize cache"
3. Search cass with gap-targeted queries
4. Score each session against gaps:
   - Session matches critical category: +3 points
   - Session matches underrepresented category: +2 points
   - Session matches adequate category: +1 point
5. Sort sessions by gap score (highest first)
6. Filter out already-processed sessions
7. 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:

# Inspect another project's rules and gaps from any directory
cm onboard status --workspace /Users/x/my-project --json
cm onboard gaps --workspace /Users/x/my-project --json

# 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

--workspace selects the project's configuration, applicable playbook rules, gap analysis, and sanitization policy, as well as filtering sampled sessions. Workspace-specific status counts include that project's sessions. Without this filter, sampling continues to consider all projects. Progress totals remain global so the same historical session is not analyzed twice. onboard guided, onboard read, and onboard mark-done also accept --workspace; completion markers use that workspace's reflection log when it is supplied.

Local onboarding checks workspace membership against indexed and recorded project metadata. Remote sessions from enabled SSH targets use host-qualified references throughout reading and completion tracking. With --workspace, remote candidates must have an exact indexed workspace match; their paths are never resolved against local files. Candidates that fail these checks are withheld, with remoteSessionsSkipped and warnings in JSON. Session reads retain caller, destination, and all identified local source projects' redactions, and stop if a required policy cannot be read or compiled.

Onboarding Workflow for Agents

Recommended protocol for AI agents doing onboarding:

## Onboarding Protocol

### Phase 1: Assessment
1. Run `cm onboard status --json` to check current progress
2. Run `cm onboard gaps --json` to see category distribution
3. Decide target: ~20 rules across diverse categories for a good initial playbook

### Phase 2: Session Analysis Loop
For each session until target reached:
1. `cm onboard sample --fill-gaps --json` → get prioritized sessions
2. `cm onboard read <path> --template --json` → get session with context
3. Analyze session content, identify 2-5 reusable patterns
4. Format as rules following extraction guidelines
5. `cm playbook add --file rules.json --session <path>` → add rules
6. Repeat with next session

### Phase 3: Verification
1. `cm onboard status` → verify progress
2. `cm onboard gaps` → check remaining gaps
3. `cm stats --json` → verify playbook health

Why Agent-Native Onboarding?

  1. Zero additional cost: Uses the AI agent you're already paying for
  2. Better analysis: Your agent understands your codebase context
  3. Resumable: Progress persists across sessions
  4. Gap-aware: Automatically prioritizes underrepresented categories
  5. Batch-friendly: Add multiple rules efficiently
  6. 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:

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.1 --verify       # Specific version
install.sh --system --verify             # Install to /usr/local/bin (requires sudo)
install.sh --from-source --version v0.6.1 # 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 .sha256 sidecars. 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 sha256sum on Linux, shasum -a 256 on macOS

Source builds cannot satisfy a downloaded binary's checksum or an explicit artifact URL, so combining those requirements with source mode (including automatic musl fallback) fails before building. The 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, or GOOGLE_GENERATIVE_AI_API_KEY

Building cass from source requires rustup + nightly. The cass source tree's .cargo/config.toml unconditionally passes the nightly-only -Z threads rustflag, and its rust-toolchain.toml pins a nightly channel that only a rustup proxy will honor. A non-rustup Rust (e.g. Homebrew's cargo/rustc) fails before compilation with the option `Z` is 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

With --workspace, automatic discovery requires a working directory recorded by cass or the session transcript. Claude project folder names alone are ambiguous because directory separators and punctuation both become hyphens. For an older session without workspace metadata, supply its path explicitly with --session <path> --workspace <directory>. A conflicting recorded directory stops that explicit request before reflection or feedback. Discovery reads at most the first 64 KiB of a local transcript for workspace metadata. For a large JSON envelope or array, only complete fields or entries in that prefix contribute file metadata. Reflection also checks the structured export.

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 <transcript> 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: later invocations process pending or newly appended records, and skip an unchanged session once its source is fully processed.

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 retain their middle lessons. The diary provides a bounded summary, while the reflector examines every contiguous part of the selected original transcript. Each source part fits within the smaller of diaryMaxInputChars and 20,000 characters after prompt escaping. An empty result from one part does not skip later parts, and a failed part leaves the session's previously committed progress intact. Secret redaction runs before the source is split. Long sessions can require more model calls, each subject to the usual budget and timeout checks; Reflection Settings control the diary summary and passes over each source part.

Ordinary reflection selects up to reflectSessionMaxChars rendered characters per session (200,000 by default), stopping at a complete record boundary. A single larger record stays intact and is covered through multiple bounded reflector requests. The saved cursor advances only with the committed rules and feedback. cm reflect --json reports pendingSessions with processed, total, and remaining record counts; rerun cm reflect to continue even if the transcript has not grown or its timeline entry has aged out. Secret patterns see the full transcript before any window is selected, and feedback is restricted to the selected records. If an unfinished transcript is rewritten, cm preserves its cursor and reports the problem instead of discarding unseen evidence. Restore the original source or use cm reflect --session <path> --force to deliberately examine its current contents. --force revisits the full transcript while preventing already processed turns from receiving duplicate feedback.

Reflection includes textual tool inputs and results from Codex, Claude Code, and Gemini CLI transcripts: executed commands, patches, error output, and test results remain available to the diary and reflector, including continuations containing only tool activity. Project redaction applies before this evidence reaches the model; environment payloads, reasoning blocks, and media are omitted. Automatic rule feedback uses conversational evidence separately, so a tool response listing playbook rules or feedback examples cannot award those rules confidence.

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: reflection reaches it as the pending source windows are processed. Treat such lists as hints for the diary, not as rules: cm still checks candidate rules against history and feedback before trusting them.

Generate a diary from an archived session. cm diary ./session.jsonl --json uses the session's recorded project for extraction settings, even when you run the command from another repository. Use --raw to read the transcript directly, or --workspace /path/to/project to select a different project's extraction settings. The diary keeps the original session's workspace and agent; an unknown source stays unknown. Redaction patterns from your user settings, the calling project, the recorded project, and any explicit workspace are combined before content reaches the provider or the saved diary.

For an enabled SSH source, pass its canonical cass-remote:// session reference to cm diary without --raw. The host must appear in your user-level remoteCass.hosts allowlist. cm reads complete structured records over SSH, validates their source metadata, and saves host-qualified session and workspace provenance, so identical paths on two machines remain distinct. Remote workspace paths never select a local repository's configuration. Your calling project's redaction policy and any explicit local --workspace policy protect the source and saved diary; the remote machine's repository configuration is not imported. An invalid, truncated, unauthorized, or failed SSH export creates no diary and never falls back to a similarly named local file.


🛠️ CLI Reference

Quick Reference Table

Command Purpose Agent Use
cm context "<task>" --json 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 "<query>" 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"
cm similar "database migrations" --workspace ~/code/api --language python --json

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

cm similar uses the same workspace and named scope filters, including portable repository rules and linked worktrees. Its keyword fallback ranks query terms, inflections, tags, and categories using the same lexical scorer as context, so short queries can find longer rules when embeddings are disabled or unavailable. similarity is cosine similarity in semantic mode and normalized lexical relevance in keyword mode; --threshold applies to the active mode's 0–1 score. A threshold of zero still excludes rules with no lexical match. Results identify anti-patterns with type: "anti-pattern" and isNegative: true; human output labels these as pitfalls to avoid.

Playbook Commands (Inspect & Manage Rules)

# List all active rules
cm playbook list

# Get detailed info for a specific rule
cm playbook get b-8f3a2c

# Set a rule's confidence half-life, or follow the current configured default
cm playbook decay b-8f3a2c 30 --json
cm playbook decay b-8f3a2c inherit --json
# Select the global rule explicitly when a repository rule shadows its ID
cm playbook decay b-8f3a2c 180 --global --json

# Add a new rule manually
cm playbook add "Always run tests before committing"
# Save a pitfall for later context and project instructions
cm playbook add "Regenerating expected results inside the test" --anti-pattern
# In batch JSON, each entry can set "antiPattern" to true or false.

# 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

# Retry this exact submission safely after a lost response
cm mark b-8f3a2c --helpful --workspace ~/code/api --request-id review-42-rule-1

# 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

# Retract the latest feedback, including on later outcome replay and playbook import
cm undo b-xyz789 --feedback

# Check sessions for rule violations
cm audit --days 30

Session audits preserve each rule's applicability and whether it is an instruction or a pitfall to avoid. A followed or violated verdict must quote text that is present in the sanitized session excerpt supplied to the model. Missing verdicts, ambiguous scope, invented evidence, and failed exports produce an incomplete audit instead of an all-clear result; findings from completed batches remain available.

For automated feedback, supply --request-id (or requestId to MCP cm_feedback) and reuse it with the same workspace, rule, polarity, session and reason when retrying. The durable receipt returns the original result without adding feedback again, including after a restart or interrupted save. Reusing the ID with a different submission is rejected. A new ID records a new observation; omitting the ID keeps each call independent. Later retraction or archival does not make an acknowledged submission apply again.

System Commands (Setup & Diagnostics)

# Initialize configuration and playbook
cm init
cm init --starter typescript  # With starter template
cm starters                   # List available starters

# Check system health
cm doctor --json
cm doctor --fix               # Auto-fix issues

# Check 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)

# Preview rules for AGENTS.md
cm project --format agents.md
# Export rules for another project's stack, including rule IDs for cm why and cm mark
cm project --workspace ~/code/api --language typescript --framework express
# Append or refresh the generated section while preserving hand-written instructions
cm project --section --output AGENTS.md
cm project --format claude.md --section --output CLAUDE.md

# Show LLM cost and usage statistics
cm usage

# Run MCP HTTP server for agent integration (default: 127.0.0.1:8765)
cm serve

# Privacy controls
cm privacy status
cm privacy enable   # Enable cross-agent enrichment
cm privacy disable  # Disable cross-agent enrichment

Safety Commands (Trauma Guard)

# View active trauma patterns
cm trauma list

# Add a dangerous pattern
cm trauma add "DROP TABLE" --description "Database table deletion" --severity critical

# Temporarily disable a pattern
cm trauma heal t-abc123 --reason "Intentional migration cleanup"

# Permanently remove a pattern
cm trauma remove t-abc123

# Scan sessions for potential traumas
cm trauma scan --days 30

# Import patterns from file
cm trauma import shared-traumas.yaml

# Install safety hooks
cm guard --install           # Claude Code pre-tool hook (this project)
cm guard --install --user    # Claude Code pre-tool hook (every project)
cm guard --git               # Git pre-commit hook
cm doctor                    # Check that every registered guard hook resolves here

Command Output Modes

All commands support multiple output formats:

Flag Output
(default) Human-readable text
--json Machine-readable JSON
--quiet Minimal output

🔬 The ACE Pipeline

cass-memory implements the Agentic Context Engineering (ACE) framework with four stages:

┌──────────────┐     ┌──────────────┐     ┌──────────────┐     ┌──────────────┐
│  GENERATOR   │ ──▶ │  REFLECTOR   │ ──▶ │  VALIDATOR   │ ──▶ │   CURATOR    │
│              │     │              │     │              │     │              │
│ Pre-task     │     │ LLM pattern  │     │ Evidence     │     │ Deterministic│
│ context      │     │ extraction   │     │ gate against │     │ delta merge  │
│ hydration    │     │ from diary   │     │ cass history │     │ (NO LLM!)    │
└──────────────┘     └──────────────┘     └──────────────┘     └──────────────┘

Stage 1: Generator (cm context)

Hydrates the agent with relevant rules before starting a task.

Implementation (src/commands/context.ts):

async function generateContext(task: string): Promise<ContextResult> {
  // 1. Extract keywords from task
  const keywords = extractKeywords(task);

  // 2. Relevance: BM25 over the playbook (IDF-weighted share of the query a
  //    bullet covers, 0..10), blended with embedding similarity when enabled
  const lexical = scoreLexicalRelevance(bullets, keywords);
  const scored = bullets.map(b => {
    const relevanceScore = blend(lexical.get(b.id), cosine(taskEmbedding, b.embedding) * 10);
    // 3. Track record only reorders within a bounded band: [1 - w, 1 + w],
    //    damped while a bullet has few marks (feedbackWeight, default 0.1)
    return { ...b, relevanceScore, finalScore: relevanceScore * getFeedbackMultiplier(b) };
  }).sort(byFinalScore);

  // 4. Keep what is relevant and fits: absolute + relative relevance floors,
  //    maxBulletsInContext, then contextTokenBudget
  const { selected, stats } = selectContextBullets(scored, config);

  // 5. Search cass for historical context
  const historySnippets = await safeCassSearch(task, {
    limit: config.maxHistoryInContext,
    days: config.sessionLookbackDays
  });

  return {
    task,
    relevantBullets: selected.filter(isRule).map(toContextBullet),  // compact: no event log
    antiPatterns: selected.filter(isAntiPattern).map(toContextBullet),
    historySnippets,
    retrieval: stats,  // candidates / returned / dropped by relevance, limit, budget
    suggestedCassQueries: generateSuggestedQueries(task, keywords)
  };
}

Bullets in cm context output are a compact projection (id, content, category, kind, scope, scopeKey, maturity, tags, counts, scores, reasoning). The full record, including the feedback-event log and source sessions, is one cm playbook get <id> away.

Stage 2: Reflector (cm reflect)

Processes unprocessed sessions to extract new rules.

How It Works:

  1. Find unprocessed sessions via cass timeline API
  2. Generate diary entries - structured summaries of each session:
    • Accomplishments (what was completed)
    • Decisions (design choices made)
    • Challenges (problems encountered)
    • Key learnings (reusable insights)
  3. Run LLM reflector - multi-iteration pattern extraction
  4. Output deltas - add/helpful/harmful/deprecate operations

The Reflector Prompt (simplified):

Analyze this session diary and extract actionable rules.
For each pattern you identify:
1. Formulate as an imperative rule ("Always...", "Never...", "When X, do Y")
2. Categorize (testing, debugging, git, architecture, etc.)
3. Assess scope (global, workspace, language, framework)
4. Provide reasoning for why this is valuable

Output format: JSON array of proposed rules

Stage 3: Validator

Scientific gate ensuring rules have evidence.

Implementation (src/ace/validator.ts):

async function validateRule(rule: ProposedRule): Promise<ValidationResult> {
  // 1. Evidence count gate - fast pre-filter
  const evidenceCount = await countEvidenceInCass(rule);
  if (evidenceCount < MIN_EVIDENCE_COUNT) {
    return { verdict: 'NEEDS_MORE_EVIDENCE', evidenceCount };
  }

  // 2. LLM validation - deep analysis
  const llmVerdict = await llmValidate(rule, evidenceCount);

  // 3. Final verdict
  return {
    verdict: llmVerdict.valid ? 'ACCEPT' : 'REJECT',
    reasoning: llmVerdict.reasoning,
    evidenceCount
  };
}

Stage 4: Curator

Critical: NO LLM in this stage - pure deterministic logic to prevent context collapse.

Why No LLM? LLMs tend to "drift" when iteratively refining their own outputs. By keeping curation deterministic, we:

  • Prevent feedback loops that degrade rule quality
  • Ensure reproducible behavior
  • Avoid expensive redundant LLM calls

Curation Operations:

function curate(playbook: Playbook, deltas: Delta[]): Playbook {
  for (const delta of deltas) {
    switch (delta.type) {
      case 'add':
        // Conflict detection - find contradicting rules
        const conflicts = findConflicts(playbook, delta.rule);
        if (conflicts.length > 0) {
          resolveConflicts(playbook, conflicts, delta);
        }

        // Duplicate detection - hash-based and semantic
        const duplicate = findDuplicate(playbook, delta.rule);
        if (duplicate) {
          mergeDuplicate(duplicate, delta.rule);
          continue;
        }

        // Add new rule
        playbook.bullets.push(delta.rule);
        break;

      case 'helpful':
        // Update feedback
        addFeedback(playbook, delta.bulletId, 'helpful', delta.timestamp);
        maybePromoteMaturity(playbook, delta.bulletId);
        break;

      case 'harmful':
        // Update feedback with harmful multiplier consideration
        addFeedback(playbook, delta.bulletId, 'harmful', delta.timestamp);
        maybeConvertToAntiPattern(playbook, delta.bulletId);
        break;

      case 'deprecate':
        deprecateRule(playbook, delta.bulletId, delta.reason);
        break;
    }
  }

  // Maturity promotions based on feedback thresholds
  promoteQualifiedRules(playbook);

  return playbook;
}

📊 Data Models

Playbook Bullet

The core data structure for rules:

interface PlaybookBullet {
  // Identity
  id: string;                    // "b-{timestamp}-{random}"
  content: string;               // The actual rule
  category: string;              // "testing" | "git" | "debugging" | etc.

  // Classification
  scope: "global" | "workspace" | "language" | "framework" | "task";
  scopeKey?: string;             // Exact language, framework, or task selector
  workspace?: string;            // Explicit project scope; repo rules may omit it
  type: "rule" | "anti-pattern";
  kind: "project_convention" | "stack_pattern" | "workflow_rule" | "anti_pattern";
  isNegative: boolean;

  // Lifecycle
  state: "draft" | "active" | "retired";
  maturity: "candidate" | "established" | "proven" | "deprecated";

  // Feedback & Scoring
  helpfulCount: number;          // Raw count
  harmfulCount: number;          // Raw count
  feedbackEvents: FeedbackEvent[];  // Full history with timestamps
  effectiveScore?: number;       // Calculated decay-adjusted score

  // Provenance
  sourceSessions: string[];      // Sessions that generated this rule
  sourceAgents: string[];        // Agents involved (claude, codex, cursor, etc.)
  reasoning?: string;            // Why this rule exists
  sourceSession?: string;        // Flexible field for reflection metadata

  // Metadata
  tags: string[];
  embedding?: number[];          // Semantic search vector (768 dimensions)
  pinned: boolean;               // Prevent auto-deprecation
  deprecated: boolean;

  // Timestamps
  createdAt: string;             // ISO 8601
  updatedAt: string;             // ISO 8601
}

Feedback Event

Immutable record of feedback:

interface FeedbackEvent {
  id: string;                    // UUID
  type: "helpful" | "harmful";
  timestamp: string;             // ISO 8601
  source: "inline" | "manual" | "outcome" | "audit";
  sessionPath?: string;          // Session where feedback was given
  reason?: string;               // Optional explanation
}

Diary Entry

Working memory structure:

interface DiaryEntry {
  id: string;                    // Deterministic hash of content
  sessionPath: string;           // Original cass session
  timestamp: string;             // ISO 8601
  agent: string;                 // "claude" | "codex" | "cursor" | etc.
  workspace?: string;            // Project directory

  // Session status
  status: "success" | "failure" | "mixed";

  // Core content
  accomplishments: string[];     // What was completed
  decisions: string[];           // Design choices made
  challenges: string[];          // Problems encountered
  keyLearnings: string[];        // Reusable insights
  preferences: string[];         // User style revelations

  // Cross-agent enrichment
  relatedSessions?: RelatedSession[];

  // Search optimization
  searchAnchors: string[];       // Keywords for retrieval
  tags: string[];                // File/component tags
}

Session Outcome

Outcome records use the following fields (older logs may omit event identity and workspace ownership):

interface OutcomeRecord {
  id?: string;                   // Stable UUID for new events
  sessionId: string;
  recordedAt: string;            // ISO 8601
  outcome: "success" | "failure" | "mixed" | "partial";
  workspace?: string;            // Absolute source workspace
  globalPlaybookPath?: string;   // Preparing owner; cannot authorize other files
  path: string;                  // Outcome log destination
  rulesUsed?: string[];
  ruleTargets?: Array<{
    ruleId: string;
    playbookPath: string | null; // Recorded owner; null means unresolved
  }>;
  task?: string;
  notes?: string;
  durationSec?: number;
  errorCount?: number;
  hadRetries?: boolean;
  sentiment?: "positive" | "negative" | "neutral";
  autoGraded?: boolean;          // Shown rules need stricter harm attribution
  transcriptEvidence?: Array<{
    ruleId: string;
    recordKeys: string[];        // Stable keys for original transcript records
  }>;
}

Applied events carry their outcomeId in each rule's feedback history. Transcript-backed events also retain newly consumed transcriptEvidenceKeys. Legacy events retain timestamp/session deduplication and use the requested workspace when no recorded workspace is available.


📈 Scoring Algorithm

Effective Score Calculation

The effective score determines rule ranking, maturity transitions, and anti-pattern conversion:

function getEffectiveScore(bullet: PlaybookBullet): number {
  const HARMFUL_MULTIPLIER = 4;    // One harmful = 4× one helpful
  const HALF_LIFE_DAYS = 90;       // 90 days for half decay

  // Calculate decayed helpful count
  const decayedHelpful = bullet.feedbackEvents
    .filter(e => e.type === "helpful")
    .reduce((sum, event) => {
      const daysAgo = daysSince(event.timestamp);
      const decayFactor = Math.pow(0.5, daysAgo / HALF_LIFE_DAYS);
      return sum + decayFactor;
    }, 0);

  // Calculate decayed harmful count
  const decayedHarmful = bullet.feedbackEvents
    .filter(e => e.type === "harmful")
    .reduce((sum, event) => {
      const daysAgo = daysSince(event.timestamp);
      const decayFactor = Math.pow(0.5, daysAgo / HALF_LIFE_DAYS);
      return sum + decayFactor;
    }, 0);

  // Effective score with harmful multiplier
  return decayedHelpful - (HARMFUL_MULTIPLIER * decayedHarmful);
}

Score Decay Visualization

Each rule can set confidenceDecayHalfLifeDays to a positive, finite number. That saved policy takes precedence over scoring.decayHalfLifeDays, including an explicit value of 90. Rules without a policy inherit the current configured half-life (90 days by default); nonpositive legacy values also fall back to the configured policy. New rules record the configured half-life at creation unless an explicit rule policy is supplied. Omit the field when a rule should follow future configuration changes. The same policy drives helpful and harmful feedback decay, retrieval confidence, maturity, and automatic retirement.

Use cm playbook decay <id> <days|inherit> to change this policy safely. Positive fractional days are supported. By default, the command updates the repository rule when it shadows a global rule; --repo and --global select a specific owner. cm playbook get <id> shows the effective half-life and whether it is custom or inherited, including bullet.decay in JSON output.

Changing the policy immediately recalculates an active rule's maturity from its existing feedback. A longer half-life can make old harmful feedback count enough to retire a rule. Pinned rules keep their lifecycle protection, and changing the policy of an already retired rule does not revive it. Feedback history and source provenance stay intact; repeating the existing policy does not rewrite the file. Policy changes do not create replacement warnings; that requires new feedback.

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

Why Time Decay?

  1. Codebases evolve - A pattern helpful for React 17 may not apply to React 19
  2. Tools change - Agent capabilities improve over time
  3. Prevents stale rules - Forces ongoing validation
  4. Natural cleanup - Unvalidated rules fade rather than accumulate

Maturity State Machine

  ┌──────────┐       ┌─────────────┐    ┌────────┐
  │ candidate│──────▶│ established │───▶│ proven │
  └──────────┘       └─────────────┘    └────────┘
       │                   │                  │
       │                   │ (harmful >25%)   │
       │                   ▼                  │
       │             ┌─────────────┐          │
       └────────────▶│ deprecated  │◀─────────┘
                     └─────────────┘

Transition Rules:

Transition Criteria
candidate → established 3+ helpful, harmful ratio <25%
established → proven 10+ helpful, harmful ratio <10%
any → deprecated Harmful ratio >25% OR explicit deprecation

Anti-Pattern Conversion

When decayed harmful evidence reaches pruneHarmfulThreshold (default: 3) and exceeds twice the decayed helpful evidence, an eligible positive rule becomes an AVOID: warning. Manual marks, recorded outcomes, and reflection curation share this behavior. New harmful evidence can complete conversion after an automatic feedback retirement; manual, merged, forgotten, and pinned rules retain their existing protection.

The original stays retired, while the warning starts with independent feedback and preserves its source's scope, provenance, and decay policy. Both changes are saved together in the owning playbook. A receipt records the exact source, warning definition, and harmful evidence so corrections can be applied safely.

cm undo <rule-id> --feedback removes the latest observation. If the remaining evidence no longer supports an unchanged warning with no independent feedback, that warning is retired and the original's maturity is reconsidered. Scrubbing polluted sessions also withdraws unsupported warnings, but leaves retired originals retired. Imported corrections carry the same protection against stale copies reintroducing an unsupported warning.

Edited, pinned, or independently judged warnings retain their own lifecycle. Explicit cm undo <rule-id> restores a source and retires its verified, unchanged warning together; it reports an error when that pairing cannot be verified or the warning needs separate review. Passive aging alone never restores the original instruction.


⚙️ Configuration

Config lives at ~/.cass-memory/config.json (global) and .cass/config.json (repo). Both locations also accept config.yaml / config.yml (keys may be written in snake_case); if more than one exists in the same directory, config.json wins and cm doctor flags the ignored file. cm init creates config.json; commands that persist settings (cm privacy …, cm doctor --fix, budget baking) write back to whichever file is active, in its own format.

Precedence: CLI flags > Repo config > Global config > Defaults

Security: Repo config cannot override sensitive paths (cassPath, playbookPath, diaryDir), trusted playbook limits (playbookLimits), or user-level consent settings (crossAgent, remoteCass).

Complete Configuration Reference

{
  // LLM Settings
  "provider": "anthropic",
  "model": "claude-sonnet-5",
  "budget": {
    "dailyLimit": 1.00,
    "monthlyLimit": 20.00,
    "warningThreshold": 80
  },

  // Scoring Settings
  "scoring": {
    "decayHalfLifeDays": 90,
    "harmfulMultiplier": 4,
    "minFeedbackForActive": 3,
    "minHelpfulForProven": 10,
    "maxHarmfulRatioForProven": 0.1
  },

  // Context Settings
  "maxBulletsInContext": 10,
  "contextTokenBudget": 4000,
  "minRelativeRelevance": 0.2,
  "feedbackWeight": 0.1,
  "maxHistoryInContext": 10,
  "sessionLookbackDays": 7,
  "minRelevanceScore": 0.1,

  // Privacy Settings
  "crossAgent": {
    "enabled": false,
    "consentGiven": false,
    "agents": [],
    "auditLog": true
  },

  // Semantic Search Settings
  // (omit semanticSearchEnabled entirely for the automatic default; set it to
  //  true or false only when you want to pin the answer)
  "semanticWeight": 0.6,
  "embeddingModel": "Xenova/all-MiniLM-L6-v2",
  "dedupSimilarityThreshold": 0.85,

  // Paths (usually auto-detected)
  "cassPath": "cass",
  "remoteCass": {
    "enabled": false,
    "hosts": []
  },
  "playbookPath": "~/.cass-memory/playbook.yaml",
  "playbookLimits": {
    "maxBytes": 16777216,
    "maxNodes": 200000,
    "maxArrayLength": 10000
  },
  "diaryDir": "~/.cass-memory/diary"
}

Configuration Options Explained

Trusted Local Playbook Limits

Large playbooks created by earlier cm versions can exceed the default parsing budget. Set playbookLimits in the global ~/.cass-memory/config.json (or its YAML equivalent) to select a finite budget for your trusted local playbook:

{
  "playbookLimits": {
    "maxNodes": 1000000,
    "maxBytes": 33554432,
    "maxArrayLength": 20000
  }
}
Setting Default Maximum Environment override
maxNodes 200,000 2,000,000 CM_PLAYBOOK_MAX_NODES
maxBytes 16 MiB 64 MiB CM_PLAYBOOK_MAX_BYTES
maxArrayLength 10,000 100,000 CM_PLAYBOOK_MAX_ARRAY_LENGTH

Values must be positive integers within the maximum. maxBytes bounds both file size and expanded text/key bytes; maxNodes counts every expanded value, including repeated YAML aliases. Depth (32), object keys (10,000), alias expansion (100), and cycle protections stay fixed; YAML token work is bounded by four times the selected node budget. Larger budgets use more memory and parsing time; choose a budget that fits the host.

Authority comes only from the bounded global configuration and the environment. The selected global playbookPath must be absolute (or start with ~/) and refer to an ordinary local file outside a Git checkout and .cass directories. Neither the configuration nor the playbook may be a symbolic or hard link; linked parent directories also prevent elevation. The default path follows CASS_MEMORY_HOME and XDG resolution. A repository cannot raise its own limit by overriding playbookPath, supplying playbookLimits, using aliases, or embedding settings in the playbook. Imports, custom starters, and batch additions retain strict limits even when the destination global playbook has a larger budget.

To calculate a suitable budget from an existing trusted file, use cm playbook repair --recover-limits. It preserves the entire playbook and previews the exact configuration change. Environment overrides take precedence; recovery reports an override that is too small and requires the operator to change or unset it.

LLM Settings

Option Default Description
provider "anthropic" LLM provider: anthropic, openai, google, ollama, bedrock, cli
model "default" for cli; "claude-sonnet-5" otherwise Model for reflection. The CLI provider passes a selected model as --model <model>; "default" uses the CLI's own configured model.
baseUrl (unset) Custom base URL for OpenAI-compatible gateways (OpenRouter, Z.AI, Azure, etc.)
disableStructuredOutputs false Opt-in escape hatch for OpenAI strict structured-outputs mode. The reflect/audit/validate Zod schemas are written to be strict-compliant, but if you hit cm reflect returning zero deltas with "Invalid JSON response" warnings on a particular gateway/model combination (see #47), flipping this to true falls back to plain JSON mode while still applying the schemas as a post-hoc validator. Leave false unless you've confirmed strict-mode is the failure surface.
cliCommand (auto-detected) CLI executable name or path. Overrides CASS_CLI_COMMAND; otherwise cm looks for claude, codex, then gemini. Keep model selection in model, not in this executable name.
cliSubprocessCwd "~/.cass-memory/llm-subprocess-cwd" Working directory for cm's own LLM subprocesses on provider: "cli". Agent CLIs name their per-project transcript folder after the working directory, so running cm's claude -p / codex / gemini calls in one cm-owned directory keeps every transcript cm generates in a single place that cm reflect skips — otherwise cm reads its own prompts back as work sessions and grades its own rules (#76). Must be absolute or ~-rooted; set to "" to inherit cm's own working directory (the prompt still carries an internal marker that reflect recognises).
budget.dailyLimit 1.00 Daily threshold for estimated API spend (USD); nonpositive values mean unlimited
budget.monthlyLimit 20.00 Monthly threshold for estimated API spend (USD); nonpositive values mean unlimited
budget.warningThreshold 80 Percentage before warning

To use a separate reflection model with your existing Claude Code login, set:

{
  "provider": "cli",
  "cliCommand": "claude",
  "model": "haiku"
}

This passes --model haiku on every diary, reflector, and validator call, including retries, without changing your interactive Claude Code model. Use "sonnet" or another model identifier supported by your CLI as needed. Absolute paths to Claude retain -p --strict-mcp-config as well as the model selection.

With provider: "cli", omitting model or setting it to "default" leaves model selection to the CLI. An explicitly configured model is always honored, even if it equals cm's API default; when changing an existing config to the CLI provider, set model to your intended choice or to "default". Automatic fallback from an API provider to a CLI uses the CLI default rather than the API provider's model. Codex and Gemini also receive --model; custom wrapper scripts must accept or forward that option, or use "model": "default" to manage selection themselves.

Diary extraction, reflection, validation, context generation, and audits can recover from a temporary API-provider outage by trying another available provider. The selected primary keeps its configured model and credentials. Available alternates are considered in Anthropic, OpenAI, Google, Bedrock, Ollama, then CLI order; each uses its own credentials and default model. The request schema follows the actual provider, including transitions between native structured output and prompt-only JSON or CLI output.

Explicit provider: "cli", provider: "ollama", and custom baseUrl settings keep requests on the selected backend, including when its executable or credentials are missing. cm doctor reports that unavailable backend so you can repair its configuration. Ordinary API configurations with a missing key can still use another available provider.

Provider switching handles transient service and transport failures. Invalid credentials, rejected requests, and output-validation errors do not trigger a switch; invalid output receives the existing bounded repair attempts on the same provider. Every API attempt checks the shared budget and records usage under its actual provider and model. Accounting failures stop further requests, and a caller's total deadline covers the whole provider chain.

Scoring Settings

Option Default Description
scoring.decayHalfLifeDays 90 Days for feedback to decay to half value
scoring.harmfulMultiplier 4 Weight harmful feedback N× more than helpful
scoring.minFeedbackForActive 3 Min feedback to consider bullet "active"
scoring.minHelpfulForProven 10 Min helpful marks for "proven" status
scoring.maxHarmfulRatioForProven 0.1 Max harmful ratio for "proven" (10%)

Context Settings

Option Default Description
maxBulletsInContext 10 Max rules to return in context (--limit overrides)
contextTokenBudget 4000 Approximate token budget for the returned rules (~4 chars/token); ranked rules are added until the next would exceed it, the top rule is always kept. --max-tokens overrides; 0 = unlimited
minRelativeRelevance 0.2 Drop rules whose relevance is below this fraction of the best match for the same task; 0 disables
feedbackWeight 0.1 How far helpful/harmful marks can move a rule's rank: a bounded multiplier in [1 - w, 1 + w], damped while a rule has few marks. Relevance decides what is retrieved; feedback only reorders it. 0 ignores feedback for ranking
maxHistoryInContext 10 Max history snippets to return
sessionLookbackDays 7 Days of sessions cm reflect discovers
relatedSessionsDays 30 Days of history searched for cross-agent diary enrichment
maxRelatedSessions 5 Maximum distinct related sessions per enriched diary. Zero skips the search. Remote citations carry their host.
historyLookbackDays 90 Days of cass history cm context searches for history snippets (--days overrides)
minRelevanceScore 0.1 Min relevance to include a bullet
cassHistoryTimeoutSeconds 20 Budget for the cass search behind cm context history snippets; raise it on large archives (env: CM_CASS_HISTORY_TIMEOUT_SECONDS)
cassExportTimeoutSeconds 30 Time limit for each transcript export or snippet expansion. An overdue export is terminated before cass-memory attempts to read a local session file. Override with CM_CASS_EXPORT_TIMEOUT_SECONDS.
cassTimelineTimeoutSeconds 120 Budget for the cass timeline session discovery behind cm reflect (env: CM_CASS_TIMELINE_TIMEOUT_SECONDS). cm onboard status caps its own timeline call at 15 s (or this value, if lower): when that runs out it still answers, reports the conversation/message counts as 0 and explains why in degraded.cass

Reflection Settings

LLM budget accounting includes provider-reported token usage from failed JSON or schema outputs before another request is attempted. A failed response can therefore exhaust the budget and stop a retry or provider fallback. If local usage accounting cannot be saved, the request stops instead of repeating paid work. Costs use CM's model-rate estimates; responses without reported usage cannot be priced, and the ledger is not a provider invoice.

API requests sharing a cost directory take turns through budget admission and usage settlement. Every request checks the latest saved totals after acquiring admission. A waiting request whose deadline expires cannot start later, and an in-flight request retains admission until its provider promise settles. Invalid or incomplete accounting blocks further API requests. A total.json saved by an older cm without daily and monthly sums is still accepted: any spend it may hold for the current day or month is rebuilt from the usage logs. The thresholds are checked before each request; one admitted response can cross a threshold because CM does not reserve its maximum possible cost in advance. CLI providers do not report priced API usage and remain outside this monetary accounting.

Option Default Description
diaryMaxInputChars 50000 How much of a session's transcript the diary step reads (10,000 to 2,000,000). A longer transcript keeps its first 60% and last 40% of this budget. Raise it if your reflection model has a large context window; the cost of each diary call grows with it.
diaryMiddleScanChars 8000 Extra room (0 to 200,000; 0 turns it off) for lines from the cut middle of a long transcript that report errors or corrections: tool errors, failed tests, "actually", "no, ...", "wrong", reverts, and the user turn that follows an error. They are found by a plain text scan, not an LLM call, and are passed to the diary step as marked excerpts.
maxReflectorIterations 3 Positive integer number of reflector passes per contiguous source part. Empty results can end that part early; later source parts are still examined.
reflectSessionMaxChars 200000 Rendered source characters selected per session in an ordinary reflection run (10,000 to 2,000,000). Stops at a whole-record boundary; one oversized record is processed intact through bounded requests. Saved pending records resume on later runs. Explicit --force examines the full transcript.

Privacy Settings

Option Default Description
crossAgent.enabled false Enable cross-agent diary enrichment
crossAgent.consentGiven false Explicit consent flag
crossAgent.agents [] Allowlist; empty means "all agents". Codebuff and Freebuff share one session store (~/.config/manicode) that cass reports as codebuff, so codebuff admits sessions from either app
crossAgent.auditLog true Log enrichment events

Remote History (SSH)

Remote cass is opt-in and queries other machines via SSH (using your existing SSH config/keys). Remote hits are tagged with historySnippets[].origin.kind="remote", origin.host (the display label), and origin.sshTarget (the configured SSH target).

Option Default Description
remoteCass.enabled false Enable SSH-based remote cass history
remoteCass.hosts [] List of SSH targets: { host: "workstation", label?: "work" }
Onboarding from another machine

cm onboard sample --json includes remote sessions when remote history is enabled. Each remote sample's path is a copyable cass-remote:// reference containing the SSH target and encoded transcript pathname. Its sourcePath retains the original pathname, and origin identifies the source machine. Copy the returned path through the complete onboarding flow:

cm onboard sample --json

# Use the path returned by sampling; this is an example for the workstation target.
remote_session='cass-remote://workstation/%2Fhome%2Fme%2Fsessions%2Fchat.jsonl'
cm onboard read "$remote_session" --template --json
cm playbook add --file rules.json --session "$remote_session"
cm onboard mark-done "$remote_session"

Reading exports the transcript through SSH, applies both the caller's and selected local project's redactions, and uses the selected project's rules and gaps for extraction. Select a destination explicitly with cm onboard read "$remote_session" --workspace /path/to/project. Remote paths are never interpreted as local source-project directories. Hosts must match an enabled entry's host; display labels are not connection targets.

When sampling with --workspace, a remote session's indexed workspace must match the requested workspace exactly. Missing, different, or nested remote workspace metadata is withheld and reported in remoteSessionsSkipped and warnings.

The target stays part of session identity in rule provenance and completion tracking, so identical transcript paths on two machines and the local machine remain separate. Sampling reports unavailable history in historyIssues. Failed remote reads return an error without falling back to a same-named local file. An explicitly selected remote session can also run the complete reflection pipeline, including rule extraction, curation, feedback and resumable record windows:

cm reflect --session "$remote_session" --destination-workspace ~/code/project --json
cm reflect --session "$remote_session" --destination-workspace ~/code/project --dry-run --json

The destination must be an existing local directory. Its configuration and rules apply to the learning run, together with the caller's privacy protections; the source machine's project configuration is never opened locally. The remote export must contain complete structured records and an absolute source workspace. Diary and rule provenance retain the host-qualified source, while project rules and outcomes belong to the selected local destination.

Remote reflection uses one durable ledger regardless of the launch directory. Its first verified attempt fixes the source workspace, destination, playbook owners and project-routing policy. Continuations and --force reject changes to that binding instead of moving learned rules or awarding duplicate feedback. Restore the original destination and policy to resume interrupted work. Remote diary creation is also supported with cm diary "$remote_session" --workspace ~/code/project --json.

To discover and learn remote sessions during ordinary cm reflect runs, enable learning separately for each host in your global configuration and map its source projects to local destinations:

{
  "remoteCass": {
    "enabled": true,
    "hosts": [{
      "host": "workstation",
      "learning": {
        "enabled": true,
        "workspaceMappings": [{
          "remote": "/srv/code/api",
          "local": "~/code/api"
        }]
      }
    }]
  }
}
cm reflect --days 7 --max-sessions 10 --json
cm reflect --workspace ~/code/api --agent codex,claude --json

History access alone does not enable learning. A mapping covers its source root and descendants; the most specific matching root wins. Every descendant learns into that mapping's fixed local destination, so a remote directory suffix cannot select an unrelated local repository. --workspace filters local session projects and mapped remote destinations. Remote source paths remain literal POSIX paths; local destinations accept absolute paths or ~/....

Local and remote sessions share --max-sessions, with new or grown sessions ahead of retries and capacity shared between the two sources. Remote backlogs remain resumable after their timeline entry ages out. Disabling a host's learning stops new discovery; changing a pending session's mapping reports an error and preserves its original cursor. The complete export is checked again against the discovered source, agent and destination before any model request. Failures on one source are reported while other selected sources can still complete.

Older remote timelines without workspace or growth metadata use complete-export probes, bounded to five per host and twenty per pass. Reaching this bound is reported; update the remote cass indexer or select a session explicitly to proceed. cm onboard mark-done uses the shared remote ledger to keep skipped sessions out of automatic learning. MCP clients can invoke memory_reflect with session and destinationWorkspace, or omit both to use the same configured discovery.

Semantic Search Settings

Option Default Description
semanticSearchEnabled (unset — automatic) Tri-state. Leave it out and semantic search runs whenever the configured embedding backend can already embed offline: the local model is cached in ~/.cache/cass-memory/transformers/, or embeddingBackend: "ollama" and the daemon answers /api/tags with the model pulled. Otherwise it stays keyword-only. Setting it to true or false always wins over the probe
semanticWeight 0.6 Weight of semantic vs keyword (0-1)
embeddingModel Xenova/all-MiniLM-L6-v2 Transformer model
embeddingBackend xenova Embedding backend: xenova (local WASM) or ollama
ollamaBaseUrl http://localhost:11434 Base URL when embeddingBackend: "ollama"
dedupSimilarityThreshold 0.85 Threshold for duplicate detection
semanticDedupThreshold 0.75 Embedding similarity at which cm reflect reinforces an existing rule with the same applicability instead of adding a rewording. Only used while semantic search is on, and never across rules whose directives disagree ("always X" vs "never X")
When does semantic search turn itself on?

semanticSearchEnabled is a tri-state setting, and the default is unset:

semanticSearchEnabled Behaviour cm doctor posture
(absent — the default) Automatic: semantic when the backend is ready offline, keyword-only otherwise auto-on / auto-off
true Always attempts semantic, and says so loudly if the backend fails explicit-on
false Always keyword-only, even on a machine that could embed explicit-off
any, with embeddingModel: "none" Always keyword-only (the strongest opt-out) model-none

"Ready offline" means the check costs nothing and downloads nothing:

  • xenova (default): the MiniLM model is already cached in ~/.cache/cass-memory/transformers/. So a fresh install is keyword-only — no surprise 23 MB download from a session-start hook — and the first cm context after the model lands is semantic, with no config edit.
  • ollama: the daemon at ollamaBaseUrl answers GET /api/tags within 1.5 s and the configured model is in the list.

A one-shot cm command runs the probe at most once. A long-lived process (cm serve, the MCP server) re-checks lazily — within a minute of a "not ready" answer — so starting Ollama or finishing a model download takes effect without a restart.

Concurrent local-model readiness checks share a probe. If the inference model is already loaded, readiness reuses it without creating another ONNX session; otherwise the temporary probe releases its session before returning. Concurrent callers also wait for WASM initialization to finish, and failed initialization can be retried on a later request.

How do I tell whether semantic search actually ran?

The cm context command emits a semanticMode field in JSON/TOON output (one of "semantic" or "keyword"). The reason for a keyword result is never left implicit:

  • semanticError — you asked for semantic (explicitly or automatically) and the runtime failed. Human output prints a yellow banner.
  • semanticNotice — nobody asked; the backend is simply not ready yet, and this says what would make it ready. Human output prints a dim one-liner.

The two are mutually exclusive:

$ cm context "optimize API latency" --json | jq '.data | {semanticMode, semanticError, semanticNotice}'
{ "semanticMode": "semantic", "semanticError": null, "semanticNotice": null }
Pinning semantic search on

If you would rather not depend on the probe, set it in the global config the loader actually reads (~/.cass-memory/config.json, or config.yaml if that is what you use), or let the doctor do it:

cm doctor            # "Semantic Search: Status" reports the posture above
cm doctor --fix      # cautious fix: verifies the embedding backend, then pins semanticSearchEnabled: true

The fix is deliberately cautious (it needs confirmation, or --force when non-interactive) because it may download the ~23 MB MiniLM model on first use and it refuses to flip the flag when the backend does not actually work — so you never end up with "enabled" config and a silent keyword fallback. It writes true rather than leaving the key unset, so the answer stays stable even if the model cache is later cleared.

Sharing an embedding backend with other tools

cass-memory embeds with Xenova/all-MiniLM-L6-v2 (384-d, ONNX, via transformers.js). Other tools — e.g. eidetic_engine_cli (ee), which uses the potion-multilingual-128M model2vec model (256-d, safetensors) — use a different model family, so their model files cannot be shared byte-for-byte with cass-memory today, and embeddings from one are not comparable with the other. What can be shared:

  • One local Ollama daemon for every tool. cass-memory's Ollama backend uses the standard /api/embed endpoint, so any tool that can talk to Ollama can share the same daemon and the same pulled model:

    ollama pull all-minilm          # 384-d, same family as the built-in model
    
    {
      "embeddingBackend": "ollama",
      "embeddingModel": "all-minilm",
      "ollamaBaseUrl": "http://localhost:11434"
    }
    

    No semanticSearchEnabled needed: with the daemon up and all-minilm pulled, the readiness probe sees it and semantic search turns on by itself.

    OLLAMA_BASE_URL overrides ollamaBaseUrl, which is handy when the daemon runs on another host. The bullet embedding cache (~/.cass-memory/embeddings/bullets.json) is keyed by embeddingModel, so changing the model rebuilds it lazily.

  • The local model cache location is fixed. With the default xenova backend the model is downloaded once into ~/.cache/cass-memory/transformers/ (transformers.js's own layout, not the Hugging Face hub layout). transformers.js v2 does not honour HF_HOME or TRANSFORMERS_CACHE, and cass-memory pins the cache there because the library default resolves inside the read-only virtual filesystem of the standalone binary. Pre-seed or symlink that directory on air-gapped machines; there is currently no config knob to relocate it.

Troubleshooting: "Semantic search unavailable" in the prebuilt binary

Releases ≤ v0.2.5 shipped a prebuilt binary that could not locate its bundled WASM runtime inside Bun's virtual filesystem. This was fixed in v0.2.6 (see issue #42): the onnxruntime-web WASM files are now embedded via Bun's type: "file" imports and wired up at startup. If you see ENOENT: ... /$bunfs/dist/ort-wasm-*.wasm on an older binary, upgrade:

curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/cass_memory_system/main/install.sh | bash -s -- --easy-mode

Alternatively, point cass-memory at a local Ollama daemon (no WASM):

{
  "embeddingBackend": "ollama",
  "embeddingModel": "all-minilm"
}

Environment Variables

Variable Purpose
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
CM_CASS_HISTORY_TIMEOUT_SECONDS Overrides cassHistoryTimeoutSeconds (budget for cm context history search)
CM_CASS_TIMELINE_TIMEOUT_SECONDS Overrides cassTimelineTimeoutSeconds (budget for cm reflect session discovery)
CASS_MEMORY_LLM Set to none for LLM-free mode

🔌 MCP Server

Run cass-memory as an MCP (Model Context Protocol) HTTP server for programmatic agent integration. The transport is HTTP-only (no stdio or SSE):

# Local-only by default (recommended) — listens on 127.0.0.1:8765
cm serve

# Explicit port
cm serve --port 9000

# If binding to a non-loopback host, set an auth token
MCP_HTTP_TOKEN="<random>" cm serve --host 0.0.0.0 --port 8765

When MCP_HTTP_TOKEN is set, clients must send either Authorization: Bearer <token> or X-MCP-Token: <token>.

POST requests must use Content-Type: application/json (an optional charset is accepted). Native MCP clients may omit Origin. When an Origin is present, it must match the listener's exact HTTP origin, including its port. Opaque origins (null), foreign origins, and unrecognized Host authorities are rejected before tools run. This prevents a web page from modifying local memory through a simple cross-origin POST or DNS rebinding. Binding to 0.0.0.0 or :: trusts the socket's local interface address, not arbitrary domain names.

For a reverse proxy or a public DNS name, explicitly allow its external origin:

MCP_HTTP_TOKEN="<random>" \
MCP_HTTP_ALLOWED_ORIGINS="https://memory.example.com" \
  cm serve --host 127.0.0.1 --port 8765

MCP_HTTP_ALLOWED_ORIGINS is a comma-separated list of exact HTTP(S) origins. It also permits their corresponding Host authorities, so a proxy can preserve the public Host or forward the upstream listener's Host. Non-loopback origins require authentication just like non-loopback listeners. Paths, wildcards, and credentials are not allowed. Forwarded headers do not grant trust, and the server does not enable cross-origin browser access with CORS headers.

Tools Exposed

Tool Purpose Parameters
cm_context Get relevant rules + history for a task task: string, limit?: number, top?: number (deprecated), minScore?: number (0–10 relevance), history?: number, days?: number, workspace?: string, language?: string, framework?: string, taskType?: string, maxTokens?: number, sessionId?: string, logContext?: boolean
cm_feedback Record helpful/harmful feedback; reuse a request ID for safe retries bulletId: string, helpful?: boolean, harmful?: boolean, reason?: string, session?: string, workspace?: string, requestId?: string
cm_outcome Record a session outcome and apply implicit feedback sessionId: string, outcome: "success" | "failure" | "mixed" | "partial", rulesUsed?: string[], workspace?: string, apply?: boolean (default true)
cm_outcome_apply Replay stored outcomes without counting feedback twice workspace?: string, sessionId?: string, outcomeId?: string, limit?: number (1–1000, default 50), playbook?: string
memory_search Search rules with configured semantic/keyword ranking and/or cass history query: string, scope?: "playbook" | "cass" | "both", limit?: number, days?: number, workspace?: string, language?: string, framework?: string, taskType?: string
memory_read Open a local or enabled SSH search hit at its exact historical message path: string, lineNumber: number, sourceId?: string, conversationId?: number, origin?: object, workspace?: string, sourceWorkspace?: string, contextLines?: number (0–100), maxChars?: number (1–50000)
memory_reflect Reflect on recent sessions or an explicit mapped remote source days?: number, maxSessions?: number, dryRun?: boolean, workspace?: string, agent?: string, session?: string, destinationWorkspace?: string
cm_why Explain a rule using its recorded sources, feedback and matching cass history bulletId: string, workspace?: string, history?: boolean, verbose?: boolean
cm_conflicts List directly opposing instructions with clause evidence for scope review category?: string, workspace?: string

For a server serving several projects, pass the same workspace to cm_context, memory_search, cm_why, cm_feedback, cm_outcome, and cm_outcome_apply. These tools resolve that project's playbook and configuration without changing the server's working directory. Feedback prefers the selected repository rule, then a global rule with the requested ID; it does not fall back to another project's rule. An unreadable repository playbook is an error, since silently updating a global rule could credit the wrong instruction. Named scope filters on cm_context and memory_search have the same exact-match behavior as the CLI flags.

memory_search uses the same semantic configuration and relevance blend as context retrieval, so paraphrased rules can match even without shared words. Exact rule IDs, exact fields, and literal phrases keep their lookup priority. The result's semanticMode reports whether semantic scoring ran; semanticError explains a fallback after an embedding failure, while semanticNotice explains why automatic mode stayed with keywords. Rules without usable embeddings retain their lexical scores, and the result limit is applied after combining those matches. Explicit semantic opt-outs remain keyword-only.

To inspect a historical match, call memory_read with the hit's path, lineNumber, sourceId, conversationId, and origin, plus its workspace as sourceWorkspace. Pass the same caller workspace used for search. The reader resolves the indexed message through cass, including archived sessions whose original files are gone. lineNumber is a message coordinate, so it must not be treated as a physical JSONL line.

The response identifies coordinateSpace: "message_index", the exact target with isTarget: true, and neighboring messages in their original order. contextLines requests up to 5 messages on each side by default (maximum 100). maxChars bounds the total returned content (default 20,000; maximum 50,000), giving the target priority. truncated and omittedMessages report clipping. Complete decoded messages are sanitized using the current caller and known source policies before applying that budget; an unverifiable source policy returns an error.

This reader requires cass's canonical expand --message-index support. Older cass versions return an actionable upgrade result, and ambiguous or missing targets return explicit failures. SSH reads require an enabled, explicitly configured remoteCass.hosts target. Pass the search hit's origin.sshTarget with its raw remote path, or use a canonical cass-remote:// reference; a display label alone cannot authorize a host. The remote archive must confirm the exact source, conversation and message coordinate. SSH failures never retry against local cass or a local file. Remote workspace values remain provenance, while the local caller's redaction policy protects the complete messages before truncation. Disabled or unknown SSH targets return REMOTE_NOT_CONFIGURED; unsupported non-SSH references return REMOTE_UNSUPPORTED. Failed reads retain their degraded details in both MCP content and structuredContent, with isError: true.

Use cm why <id> --workspace <project> to inspect the same rule from another directory. Diary evidence comes from the rule's recorded sources. The optional history search looks for additional matches within the selected workspace.

For newly reflected rules, cm why <id> --json and MCP cm_why include validationHistory with total, omitted, and records. The latest 10 records are shown by default, or 20 with --verbose. Each record's matchesCurrentRule indicates whether it evaluated the current wording and scope. Edits, refinements, and merges retain the original evaluated instruction, so an older verdict is not presented as validation of different advice. Existing rules without saved records still show their available sources; no history is fabricated for them. Validated replacements also retain replacedRules: the exact source definitions the validator considered before authorizing retirement. These definitions use the same source-aware redaction as the rest of the explanation.

Use cm why <id> --no-history to inspect recorded evidence without searching cass again. Current caller, selected-project, and recorded local source redactions protect explanations on every read, including in a long-running MCP server. Private validation excerpts are omitted from generic playbook get/list and repeated-add responses, the MCP cm://playbook resource, and portable exports (including cm project --format raw, json, or yaml). These projections leave the stored evidence intact for why. cm playbook scrub removes a validation record when its proposing session or any cited session matches the selected source pattern.

To link a briefing to an outcome, call cm_context with logContext: true and a sessionId. Then call cm_outcome with the same workspace and sessionId. If you omit rulesUsed, the outcome can credit rules from the logged briefing as implicit feedback. Pass the IDs in rulesUsed when you know which rules the agent used. Context logging is off by default. A server can enable it with CASS_CONTEXT_LOG=1, and a client can disable it for a single request with logContext: false.

New logged briefings keep the playbook that supplied each rule. If a project or linked worktree subsequently adds its own rule with the same ID, an inferred outcome still credits the original playbook. The lookup uses the latest briefing for that session in the same checkout at or before the outcome. Older briefings that contain only IDs use the playbooks available at grading time.

cm_outcome durably records the event, then applies feedback using its stored rule owners and the selected workspace's scoring policy. Its result separates recorded from feedback.status, including applied, partial (missing rules), and not_applicable (no rules or insufficient evidence). Learning from these outcomes does not require an LLM. Set apply: false to record an event for later application; the result reports feedback.status: "deferred" and a replay call.

If feedback cannot be applied, the MCP result has isError: true, recorded: true, feedback.status: "pending", and a recovery object containing the exact cm_outcome_apply arguments. After resolving the error, replay that stored event instead of creating a fresh outcome:

{
  "name": "cm_outcome_apply",
  "arguments": {
    "workspace": "/path/to/project",
    "outcomeId": "<id returned by cm_outcome>"
  }
}

Omit outcomeId to replay recent outcomes, optionally filtered by sessionId. Already applied events do not count twice. The CLI equivalent remains cm outcome-apply --workspace <project>. If the configured global playbook has changed, inspect skippedOwners and explicitly select the known original file with the MCP playbook argument or CLI --playbook <path>. Recorded paths alone never grant authority to modify another playbook.

Resources Exposed

URI Purpose
cm://playbook Active rules applicable to the server's current workspace
cm://diary Recent diary entries with current and source redactions applied
cm://outcomes Session outcomes
cm://stats Playbook health metrics

The playbook resource uses the same workspace applicability rules as context retrieval, including portable repository rules. Retired, deprecated, blocked, and unrelated workspace rules are excluded. Diary reads reapply sanitization to stored entries using the current policy and every identified local source project's redactions. If a source policy cannot be read or compiled, the entire read returns an error. Explicitly disabling sanitization in the current config is honored. These reads leave persisted playbooks and diaries unchanged.

MCP Client Configuration

cm serve is an HTTP transport server (not stdio). Start it first, then point your MCP client at the URL.

For Claude Code (~/.config/claude/mcp.json):

{
  "mcpServers": {
    "cm": {
      "type": "url",
      "url": "http://127.0.0.1:8765/"
    }
  }
}

For VS Code (Cline/Continue):

{
  "mcp": {
    "servers": {
      "cass-memory": {
        "type": "url",
        "url": "http://127.0.0.1:8765/"
      }
    }
  }
}

🧠 Architecture & Engineering

System Overview

flowchart TB
    subgraph Sources["Agent Sources (Episodic)"]
        CC[Claude Code]
        CX[Codex]
        CR[Cursor]
        AD[Aider]
        PI[PI]
        GM[Gemini]
    end

    subgraph CASS["cass Engine"]
        IDX[Search Index]
        NRM[Normalizers]
    end

    subgraph Memory["cass-memory"]
        GEN[Generator]
        REF[Reflector]
        VAL[Validator]
        CUR[Curator]
        PB[(Playbook)]
        DY[(Diary)]
    end

    subgraph Consumers["Consumers"]
        CLI[CLI]
        MCP[MCP Server]
        API[JSON API]
    end

    CC --> NRM
    CX --> NRM
    CR --> NRM
    AD --> NRM
    PI --> NRM
    GM --> NRM
    NRM --> IDX

    IDX --> GEN
    DY --> REF
    REF --> VAL
    VAL --> CUR
    CUR --> PB

    PB --> GEN
    GEN --> CLI
    GEN --> MCP
    GEN --> API

Directory Structure

~/.cass-memory/                  # Global (user-level)
├── config.json                  # User configuration (config.yaml/.yml also accepted)
├── playbook.yaml                # Personal playbook
├── diary/                       # Session summaries
│   ├── d-abc123.json
│   └── d-def456.json
├── outcomes/                    # Session outcomes
│   └── YYYY-MM/
│       └── outcome-<timestamp>.json
├── blocked.log                  # Deprecated content hashes
├── privacy-audit.jsonl          # Cross-agent enrichment audit trail
├── context-log.jsonl            # Context usage tracking
├── processed-sessions.jsonl     # Reflection progress log
└── usage.jsonl                  # LLM cost tracking

.cass/                           # Project-level (in repo)
├── config.json                  # Project-specific overrides (config.yaml/.yml also accepted)
├── playbook.yaml                # Project-specific rules
├── blocked.yaml                 # Anti-patterns to block
└── context-log.jsonl            # Local context usage

Component Responsibilities

Component Responsibility LLM?
Generator Context hydration before tasks No
Reflector Pattern extraction from sessions Yes
Validator Evidence-based rule verification Yes
Curator Deterministic playbook management No
Scorer Decay-adjusted effectiveness calculation No
MCP Server Protocol bridge for agent integration No

Why Curator Has No LLM

This is the most important architectural decision:

  1. Prevents context collapse: LLMs iteratively refining their own outputs tend to drift toward generic, less useful content
  2. Ensures reproducibility: Same inputs always produce same outputs
  3. Reduces costs: Curation runs frequently; LLM calls would be expensive
  4. Enables auditing: Deterministic logic is easier to debug and trust

The LLM's job is to propose patterns. The curator's job is to manage them according to explicit rules.

Concurrency Safety

Multiple processes may access shared files (playbook, trauma registry, diary entries) simultaneously. cass-memory uses atomic file locking to prevent corruption:

Process A                    Lock Directory              Process B
┌─────────────┐             ┌─────────────┐             ┌─────────────┐
│ mkdir lock/ │──────────▶  │ .lock.d/    │  ◀──────────│ mkdir lock/ │
│ (succeeds)  │             │  ├── pid    │             │ (EEXIST!)   │
│             │             │  └── owner  │             │ retry...    │
│ write file  │             │             │             │             │
│ rmdir lock/ │──────────▶  │ (deleted)   │  ◀──────────│ mkdir lock/ │
│             │             │ .lock.d/    │             │ (succeeds)  │
└─────────────┘             └─────────────┘             └─────────────┘

Key features:

  • Atomic acquisition: Uses mkdir() which is atomic across all operating systems
  • Heartbeat: Long operations refresh the lock timestamp every 10 seconds
  • Stale detection: Locks older than 30 seconds without an active heartbeat are automatically cleaned up
  • Orphan cleanup: Detects dead PIDs and removes abandoned locks
  • Ownership verification: Stores random UUID to prevent accidental lock theft

This ensures that even with multiple agents or background jobs running concurrently, data files remain consistent.


🔬 Deep Dive: Core Algorithms

Relevance Scoring

When retrieving context for a task, bullets are scored by relevance:

function scoreRelevance(bullet: PlaybookBullet, task: string): number {
  // 1. Keyword overlap (fast)
  const taskKeywords = extractKeywords(task);
  const bulletKeywords = extractKeywords(bullet.content);
  const keywordOverlap = intersection(taskKeywords, bulletKeywords).size
    / union(taskKeywords, bulletKeywords).size;

  // 2. Category bonus
  const categoryBonus = taskCategories.includes(bullet.category) ? 0.2 : 0;

  // 3. Semantic similarity (optional, if enabled)
  //    `semanticSearchEnabled` is tri-state, so never read it by truthiness:
  //    resolveSemanticEnabled() settles explicit true/false and, when it is
  //    unset, probes whether the backend can embed offline.
  const { enabled: semanticEnabled } = await resolveSemanticEnabled(config);

  let semanticScore = 0;
  if (semanticEnabled && bullet.embedding) {
    const taskEmbedding = await embed(task);
    semanticScore = cosineSimilarity(taskEmbedding, bullet.embedding);
  }

  // 4. Combined score
  const keywordWeight = semanticEnabled ? (1 - config.semanticWeight) : 1;
  const semanticWeight = semanticEnabled ? config.semanticWeight : 0;

  return (keywordOverlap * keywordWeight)
       + (semanticScore * semanticWeight)
       + categoryBonus;
}

function extractKeywords(text: string): Set<string> {
  const stopwords = new Set(['the', 'a', 'an', 'in', 'on', 'at', 'to', 'for', ...]);

  return new Set(
    text.toLowerCase()
      .replace(/[^a-z0-9\s]/g, ' ')
      .split(/\s+/)
      .filter(word => word.length > 2 && !stopwords.has(word))
  );
}

Duplicate Detection

Rule identity includes applicability. Exact text, word overlap, and embedding similarity can reinforce an existing rule only within the same scope:

  • Global advice stays distinct from workspace, language, framework, and task rules.
  • Workspace identities normalize paths, symlinks, and linked worktrees. A parent directory and one of its subdirectories remain distinct scopes.
  • Language, framework, and task selectors use scopeKey; different selectors retain separate rules and feedback histories.
  • Portable repository rules may omit an absolute workspace. They are deduplicated against other implicit workspace rules only when their shared owner is known; a global import cannot infer that ownership.

The reflector retains scope selectors, curation checks exact and lexical matches before optional semantic matches, and imports preserve rules with different applicability. Opposing instructions and meaningful condition differences remain protected from similarity-based merging even when their embeddings are identical.

A source session contributes evidence to a duplicate rule only once. Replaying or forcing reflection of the session that first taught a rule does not raise its helpful count or maturity. A different session can reinforce that rule once; curation records its provenance for exact, lexical, and semantic matches. Explicit helpful feedback remains a separate signal.

Explicit merges require distinct, active sources with the same applicability and compatible rule types. They preserve scope, selectors, tags, and source provenance. An evidenced rule's changed wording receives a separate successor ID; its old helpful and harmful feedback, maturity, and validation timestamp remain attached to the original instruction. An unobserved draft can still be edited in place. Draft edits retain their validation observations and proposing sources; exact qualified approval can activate the revised draft without adding feedback votes.

Before an evidenced replacement or any merge retires its sources, the historical validator evaluates both the exact proposed instruction and the frozen source definitions. Approval requires five independent supporting sessions, no contradictory citations or degraded history, and an ACCEPT verdict for preserving or independently justified changes to the original guidance. The curator checks the same definitions again before writing. Missing, disabled, cautious, refined, or mismatched validation preserves the originals; propose a separate rule when independent support is not yet available. Successors receive their own validation record without inheriting the originals' feedback votes.

Retirement and anti-pattern inversion are resolved before choosing a replacement; originals are retired only after a valid replacement is retained. Repository-only merges stay in the repository playbook. A merge across storage layers keeps its replacement in the global playbook with an explicit workspace when needed, and saves that replacement before retiring repository sources. Missing sources, conflicting scopes, and unsafe replacements produce a rejected decision while preserving the original rules.

Conflict Detection

Conflict reporting uses conservative, deterministic instruction matching in src/curate.ts. It requires opposing guidance about the same action and object, with matching actors and overlapping conditions and rule scopes. Shared topic words, a negative word in an explanation, or an exception marker alone are not evidence of a contradiction. This works offline without an LLM or embedding model.

For example, "Always commit generated lockfiles" and "Never commit generated lockfiles" are reported. "Never cache tokens without expiry" and "Must cache tokens to improve speed" are compatible: caching with an expiry satisfies both. An only if prerequisite does not by itself require taking the action, and an unless or except clause does not by itself recommend the opposite action. Quoted examples and nested parenthetical text are kept separate from instructions. An object that refers back into its own rule, such as "use it" or "run these checks", is never matched against another rule, since each refers to something different; deduplication and merge checks still keep such opposing rules apart.

import { detectConflicts, findBulletConflicts } from "./src/curate.js";

const pairs = findBulletConflicts(playbook.bullets);
const conflictsForNewRule = detectConflicts(newRule.content, playbook.bullets, newRule);

cm playbook conflicts --json, import conflict reports, and MCP cm_conflicts include evidence with the matched aClause, bClause, normalized action, and condition. Review the full rules and their applicability before retiring either one. Curation still accepts opposing rules and reports them for review; it does not automatically delete or choose between them. Deprecated and retired rules are excluded, while draft candidates remain eligible for checking.

Only directly opposing matches produce the doctor conflict warning that can make health degraded. "No direct rule conflicts detected" does not certify that every rule is consistent: unsupported wording, uncertain conditions, and workspace scopes without resolvable paths are not assessed as contradictions. Duplicate protection is deliberately more cautious than conflict reporting, so differently conditioned or qualified rules can remain separate even when their embeddings are very similar. The scan indexes actions before comparing opposing clauses to avoid an all-pairs topic scan on large, mostly compatible playbooks.

cass Integration

The cass search wrapper handles JSON parsing and fallback modes:

async function safeCassSearch(
  query: string,
  options: CassSearchOptions,
  cassPath?: string,
  config?: Config
): Promise<CassHit[]> {
  // Check cass availability
  const availability = await handleCassUnavailable({ cassPath });
  if (!availability.canContinue) {
    return [];
  }

  if (availability.fallbackMode === 'playbook-only') {
    // No cass available - return empty, let caller use playbook only
    return [];
  }

  // Build command
  const args = ['search', query, '--robot', '--limit', String(options.limit || 10)];
  if (options.days) args.push('--days', String(options.days));
  if (options.agent) args.push('--agent', options.agent);

  // Execute
  const result = await execAsync(`${availability.resolvedCassPath} ${args.join(' ')}`);

  // Parse output - handle both array and wrapped object formats
  const rawHits = parseCassJsonOutput(result.stdout);

  // cass search --robot returns { count, hits, ... } wrapper
  let hitsArray: unknown[];
  if (Array.isArray(rawHits)) {
    hitsArray = rawHits;
  } else if (rawHits && typeof rawHits === 'object' && Array.isArray((rawHits as any).hits)) {
    hitsArray = (rawHits as any).hits;
  } else {
    hitsArray = [rawHits];
  }

  // Validate with Zod schema
  return hitsArray.map(h => CassHitSchema.parse(h));
}

Embedding Generation

For semantic search (when enabled):

CM uses @huggingface/transformers 4.3.2 with quantized text inference through ONNX Web's Node-capable WASM runtime. The public embeddingBackend: xenova setting and Xenova/all-MiniLM-L6-v2 model name remain unchanged; custom model names and local model directories are still accepted. Model files stay in ~/.cache/cass-memory/transformers/ for offline reuse. Derived local embedding caches are version 3 because batch vectors can change with the newer runtime; Ollama's version 2 caches remain valid. Each operation retains its own backend, effective model, endpoint identity and expected vector dimensions.

The postinstall patch verifies exact upstream source hashes, selects the source entry, and excludes native ONNX and image decoding from CM's text runtime. The compiled executable embeds the matching WASM binary and JavaScript factory. Installation fails if the pinned package no longer matches the verified patch. The dependency graph includes Sharp 0.35.5 and native ONNX 1.30.0, but CM does not load them for embeddings. ONNX Web is intentionally the upstream-pinned 1.31.0-dev.20260914-8d85527a0 prerelease, not an all-stable runtime stack.

Compiled standalone inference, cold MiniLM download, offline cache reuse, and bit-identical numerical parity have been verified on linux-x64 (native), macos-arm64 (native), macos-x64 (Rosetta), and linux-arm64 (emulated aarch64). Native windows-x64 execution remains tracked in issue #92.

import { pipeline } from '@huggingface/transformers';
import { ensureOnnxWasmRuntime } from './wasm-runtime.js';

let embeddingPipeline: any = null;

async function getEmbedding(text: string): Promise<number[]> {
  if (!embeddingPipeline) {
    await ensureOnnxWasmRuntime();
    embeddingPipeline = await pipeline(
      'feature-extraction',
      config.embeddingModel || 'Xenova/all-MiniLM-L6-v2',
      { device: 'wasm', dtype: 'q8' }
    );
  }

  const result = await embeddingPipeline(text, {
    pooling: 'mean',
    normalize: true
  });

  return Array.from(result.data);
}

function cosineSimilarity(a: number[], b: number[]): number {
  if (a.length !== b.length) throw new Error('Vectors must have same length');

  let dotProduct = 0;
  let normA = 0;
  let normB = 0;

  for (let i = 0; i < a.length; i++) {
    dotProduct += a[i] * b[i];
    normA += a[i] * a[i];
    normB += b[i] * b[i];
  }

  return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}

🔒 Privacy & Security

Untrusted Playbooks and Configuration

Repository-controlled .cass/playbook.yaml and .cass/config.json, .yaml, or .yml files are bounded before normalization and schema validation, including when selected through an MCP tool's workspace argument. The same protections apply by default to global files, playbook imports, batch additions, custom starters, and doctor's independent configuration checks. An independently trusted global playbook can use the bounded, operator-selected limits described above.

Limit per input Playbooks and imports Configuration
File or batch stdin size 16 MiB 1 MiB
Elements in any array 10,000 1,000
Keys in any object 10,000 1,000
Total expanded values 200,000 20,000
Nesting depth 32 32
Total expanded string and key bytes 16 MiB 1 MiB

Every limit applies independently. YAML also has a streaming token budget before syntax-tree construction and an alias-expansion ceiling; cyclic aliases are rejected. Array schemas declare maximum lengths, using patched Zod to reject oversized arrays before evaluating their elements (GHSA-mrhx-c7xc-m3w5, #98).

Excessive repository inputs fail the request with a bounded diagnostic. They do not silently fall back to defaults, trigger playbook recovery, or cause doctor to reset global configuration. Writes are checked before replacing existing files. These untrusted-input ceilings cannot be raised by any configuration. Reduce oversized collections or split import batches before retrying.

For trusted local legacy playbooks containing derived inline embeddings, the explicit cm playbook repair --strip-embeddings operation has a separate, bounded migration reader. It does not make oversized imports acceptable. The separate --recover-limits operation can configure a trusted global file without changing any playbook bytes. See legacy playbook recovery.

Local-First Design

  • All data stays on your machine - No cloud sync, no telemetry
  • No network calls except optional LLM API calls for reflection
  • Cross-agent enrichment is opt-in - Must explicitly enable with consent

Data Access Patterns

What cass-memory reads:

  • Agent session files (via cass)
  • Local playbook and diary files
  • Environment variables (configuration only)

What cass-memory writes:

  • ~/.cass-memory/ directory contents
  • .cass/ directory in repos (if project-level config)

What cass-memory NEVER does:

  • Modify source code files
  • Make network requests (except LLM API when configured)
  • Execute code from playbook content
  • Access files outside known directories

Secret Sanitization

Before any data is processed, it's sanitized to remove sensitive content:

const DEFAULT_SECRET_PATTERNS = [
  // API Keys
  /sk-[a-zA-Z0-9]{20,}/g,           // OpenAI
  /sk-ant-[a-zA-Z0-9-]{20,}/g,      // Anthropic
  /AKIA[A-Z0-9]{16}/g,              // AWS
  /AIza[a-zA-Z0-9_-]{35}/g,         // Google

  // Tokens
  /ghp_[a-zA-Z0-9]{36}/g,           // GitHub PAT
  /ghu_[a-zA-Z0-9]{36}/g,           // GitHub user token
  /eyJ[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+\.[a-zA-Z0-9_-]+/g,  // JWT

  // Passwords
  /password\s*[=:]\s*['"][^'"]+['"]/gi,
  /secret\s*[=:]\s*['"][^'"]+['"]/gi,

  // Environment variables with sensitive names
  /\b(API_KEY|SECRET|PASSWORD|TOKEN|PRIVATE_KEY)\s*=\s*\S+/gi,
];

function sanitizeContent(content: string, extraPatterns?: RegExp[]): string {
  let sanitized = content;

  const patterns = [...DEFAULT_SECRET_PATTERNS, ...(extraPatterns || [])];

  for (const pattern of patterns) {
    sanitized = sanitized.replace(pattern, '[REDACTED]');
  }

  return sanitized;
}

Privacy Controls

# Check current settings
cm privacy status

# Enable cross-agent enrichment (requires explicit consent)
cm privacy enable

# Disable cross-agent enrichment
cm privacy disable

When cross-agent enrichment is enabled:

  • An audit log is written to privacy-audit.jsonl
  • You can filter by agent with crossAgent.agents allowlist
  • Consent date is recorded for compliance

Threat Model

cass-memory assumes:

  • The local filesystem is trusted
  • The user running cm should have access to all indexed content
  • LLM API providers (when configured) are trusted with sanitized content

cass-memory does NOT protect against:

  • Root/admin access to the machine
  • Memory forensics while running
  • Physical access to the storage device
  • Malicious LLM providers (use trusted providers only)

🛡️ Trauma Guard: Safety System

The "Hot Stove" Principle

AI coding agents are powerful, but that power comes with risk. A mistyped rm -rf, an accidental git push --force, or a database DROP TABLE can cause catastrophic damage. The Trauma Guard system learns from past incidents and prevents them from recurring—like how touching a hot stove once teaches you not to do it again.

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│
└─────────────────┘         └─────────────────┘         └─────────────────┘
  1. Detection: Scans session history for dangerous commands combined with "apology" signals (errors, "oops", "sorry", rollbacks)
  2. Registration: Stores dangerous patterns in a registry with severity and provenance
  3. Prevention: Hooks into Claude Code and Git to block matching commands before execution

Built-in Doom Patterns

The system ships with 20+ predefined patterns covering common catastrophic operations:

Category Examples
Filesystem rm -rf /, rm -rf ~, recursive deletes without confirmation
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 operations

CLI Commands

# View all active trauma patterns
cm trauma list

# Add a custom dangerous pattern
cm trauma add "DELETE FROM users" --description "Mass user deletion" --severity critical

# Temporarily disable a pattern (when you really need to run it)
cm trauma heal t-abc123 --reason "Intentional cleanup"

# Permanently remove a pattern
cm trauma remove t-abc123

# Import patterns from a file
cm trauma import team-traumas.yaml

# Scan recent sessions for potential traumas
cm trauma scan --days 30

Installing the Guard Hooks

The trauma guard requires hooks to intercept commands before execution:

# Install Claude Code hook for this project (intercepts Bash commands)
cm guard --install

# Install it once for every project (Claude Code's user settings, ~/.claude)
cm guard --install --user

# Install Git pre-commit hook (scans commits)
cm guard --git

# Check that each registered hook resolves to a script in the current project
cm doctor

Project or user scope. cm guard --install writes .claude/hooks/trauma_guard.py and registers it in the project's .claude/settings.json (commit both to share the guard). cm guard --install --user writes ~/.claude/hooks/trauma_guard.py (or under $CLAUDE_CONFIG_DIR) and registers it in your user settings, so every project, branch and worktree is guarded without its own copy; running the plain install from your home directory does the same. Both hook commands fail open: in a checkout where the script is absent (an older branch, a fresh worktree) the hook exits quietly instead of printing a "not found" hook error on every Bash call. With both scopes installed the guard simply runs twice per Bash call. Re-running either install rewrites an older cm hook command to the current form, and cm doctor reports any registered hook whose script does not exist in the current project, with the settings file it comes from.

What happens when a pattern matches:

🔥 HOT STOVE: Command blocked by trauma guard

  Pattern: rm -rf /*
  Severity: FATAL
  Reason: Recursive delete of root filesystem

  This pattern was marked dangerous after session:
    ~/.claude/sessions/session-abc123.jsonl

  To proceed anyway (use extreme caution):
    cm trauma heal t-abc123 --reason "your justification"

Trauma Storage

Patterns are stored at two levels:

Scope Location Purpose
Global ~/.cass-memory/traumas.jsonl Personal patterns across all projects
Project .cass/traumas.jsonl Project-specific patterns (commit to repo)

Project patterns can be committed to your repository, creating shared team knowledge about dangerous operations specific to that codebase.

Pattern Lifecycle

┌────────────┐     heal      ┌────────────┐     activate    ┌────────────┐
│   ACTIVE   │ ───────────▶  │   HEALED   │ ────────────▶   │   ACTIVE   │
│  (blocking)│               │(temp bypass)│                │  (blocking)│
└────────────┘               └────────────┘                 └────────────┘
      │                                                           ▲
      │ remove                                                    │
      ▼                                                           │
┌────────────┐                                                    │
│  DELETED   │ ───────────────────────────────────────────────────┘
│ (can re-add)│           manual add
└────────────┘
  • Active: Pattern blocks matching commands
  • Healed: Temporarily bypassed (with reason and timestamp)
  • Deleted: Removed from registry (can be re-added later)

Integration with Claude Code

When installed via cm guard --install, the trauma guard integrates as a Claude Code pre-tool hook:

// .claude/settings.json (auto-configured)
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "g=\"$CLAUDE_PROJECT_DIR/.claude/hooks/trauma_guard.py\"; [ -f \"$g\" ] || exit 0; exec python3 \"$g\""
          }
        ]
      }
    ]
  }
}

The hook runs before every Bash command, checking against active patterns. If a match is found, the command is blocked with an explanation—the agent never executes the dangerous operation.

Why This Matters

Traditional safety approaches rely on:

  • Allowlists: Too restrictive, break legitimate workflows
  • Manual review: Doesn't scale, humans miss things
  • Hope: Eventually fails catastrophically

Trauma Guard is different:

  • Learning: Patterns come from actual incidents, not theoretical risks
  • Contextual: Project-specific patterns for project-specific risks
  • Recoverable: Healing allows intentional operations with audit trail
  • Shared: Team patterns create collective institutional memory

📊 Performance Characteristics

Benchmarked Operations

Operation Typical Latency Conditions
cm context (cached) 50-150ms Warm cache, <100 bullets
cm context (cold) 200-500ms First run, cass search
cm context (no cass) 30-80ms Playbook-only mode
cm reflect (1 session) 5-15s Depends on session length
cm reflect (5 sessions) 20-60s Parallel diary, serial reflect
cm playbook list <50ms Local file read
cm similar (keyword) 20-50ms No embeddings
cm similar (semantic) 100-300ms With embeddings

Memory Usage

Component Typical Size Notes
Base process ~50MB Bun runtime + application
Embedding model (loaded) ~100MB Only when semantic search enabled
Playbook (1000 bullets) ~5MB YAML + embeddings
Diary cache ~10MB Recent entries

Scaling Characteristics

Bullet Count Context Latency Recommendation
<100 <100ms Optimal
100-500 100-300ms Good
500-1000 300-500ms Consider pruning stale rules
>1000 >500ms Use cm top to focus on best rules

LLM Cost Estimates

Operation Typical Cost Notes
Reflect (1 session) $0.01-0.05 Depends on session length
Reflect (7 days, 5 sessions) $0.05-0.20 Batched processing
Validate (1 rule) $0.005-0.01 Short prompts

With default budget limits ($0.10/day, $2.00/month), you can typically:

  • Reflect on 5-10 sessions per day
  • Validate 10-20 new rules per day

📚 Starter Playbooks

Starting with an empty playbook is daunting. Starter playbooks provide curated collections of best practices for specific tech stacks, giving you a solid foundation to build upon.

Built-in Starters

# List all available starters
cm starters

# Initialize with a starter
cm init --starter typescript

# Apply a starter to an existing playbook
cm playbook bootstrap react
Starter Focus Rules
general Universal best practices 5
typescript TypeScript/Node.js patterns 4
react React/Next.js development 4
python Python/FastAPI/Django 4
node Node.js/Express services 4
rust Rust service patterns 4

What's In a Starter

Each starter contains battle-tested rules with proper metadata:

General Starter (universal):

  • Keep functions small and focused (single responsibility)
  • Validate inputs at system boundaries
  • Implement graceful shutdown for services
  • Add observability from the start
  • Set timeouts on all external calls

React Starter:

  • Always specify dependency arrays in useEffect
  • Use unique, stable keys for list items
  • Check typeof window before browser-only code
  • Include ARIA attributes for accessibility

Python Starter:

  • Use type hints for function signatures
  • Prefer dependency injection over global state
  • Set explicit timeouts on HTTP clients
  • Use structured logging (JSON format)

Node Starter:

  • Wrap async route handlers in try/catch
  • Set timeouts on HTTP requests and DB queries
  • Validate environment variables at startup
  • Handle SIGTERM gracefully for container orchestration

Rust Starter:

  • Use ? operator and thiserror for error handling
  • Run clippy and rustfmt before commits
  • Avoid blocking in async context
  • Use structured tracing for observability

Creating Custom Starters

Create YAML files in ~/.cass-memory/starters/:

# ~/.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, database]

  - content: "Run migrations before deploying"
    category: deployment
    maturity: proven
    tags: [django, migrations, deploy]

  - content: "Use Django's CSRF protection on all POST forms"
    category: security
    maturity: proven
    tags: [django, security, csrf]

  - content: "Configure ALLOWED_HOSTS in production settings"
    category: security
    maturity: established
    tags: [django, security, config]

Custom starters are discovered automatically and appear in cm starters.

Starter vs Reflection

Source When to Use Trust Level
Starters Bootstrap new projects Pre-validated, established
Reflection Learn from your sessions Candidate until proven

Starters give you a head start. Reflection adds project-specific learning. Use both for a comprehensive playbook.


🔧 Extensibility: Adding New Components

Adding a New Starter Playbook

Create a file at src/starters/<name>.yaml:

# src/starters/django.yaml
metadata:
  name: django
  description: Django web framework best practices
  version: "1.0"
  tags: [python, django, web]

bullets:
  - content: "Always use Django's ORM for database operations"
    category: database
    scope: framework
    kind: stack_pattern
    maturity: established

  - content: "Run migrations before deploying"
    category: deployment
    scope: framework
    kind: workflow_rule
    maturity: proven

Register in src/commands/starters.ts:

const STARTERS = ['typescript', 'react', 'python', 'go', 'django'];  // Add here

Adding a New Scoring Factor

Extend the scoring calculation in src/scoring.ts:

interface ScoringConfig {
  decayHalfLifeDays: number;
  harmfulMultiplier: number;
  // Add new factor
  recencyBonus: number;  // Boost for recently created rules
}

function getEffectiveScore(bullet: PlaybookBullet, config: ScoringConfig): number {
  // Existing decay calculation...
  const baseScore = decayedHelpful - (config.harmfulMultiplier * decayedHarmful);

  // Add recency bonus for new rules
  const daysSinceCreation = daysSince(bullet.createdAt);
  const recencyFactor = daysSinceCreation < 30 ? config.recencyBonus : 0;

  return baseScore + recencyFactor;
}

Adding a New MCP Tool

Add tool definition in src/mcp/tools.ts:

const tools = {
  // Existing tools...

  memory_bulk_feedback: {
    description: 'Record feedback on multiple rules at once',
    inputSchema: {
      type: 'object',
      properties: {
        feedback: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              bulletId: { type: 'string' },
              type: { type: 'string', enum: ['helpful', 'harmful'] },
              reason: { type: 'string' }
            },
            required: ['bulletId', 'type']
          }
        }
      },
      required: ['feedback']
    },
    handler: async (args: { feedback: FeedbackItem[] }) => {
      const results = [];
      for (const item of args.feedback) {
        const result = await recordFeedback(item.bulletId, item.type, item.reason);
        results.push(result);
      }
      return { results };
    }
  }
};

Adding a New Output Format

Extend cm project for new export formats:

// src/commands/project.ts

const FORMATS = {
  'agents.md': formatForAgentsMd,
  'claude.md': formatForClaudeMd,
  'json': formatAsJson,
  // Add new format
  'notion': formatForNotion,
};

function formatForNotion(playbook: Playbook): string {
  // Notion-compatible markdown with toggle blocks
  let output = '# Playbook Rules\n\n';

  for (const bullet of playbook.bullets.filter(b => b.state === 'active')) {
    output += `<details>\n`;
    output += `<summary>${bullet.content}</summary>\n\n`;
    output += `- **Category**: ${bullet.category}\n`;
    output += `- **Maturity**: ${bullet.maturity}\n`;
    output += `- **Score**: ${bullet.effectiveScore?.toFixed(2)}\n`;
    if (bullet.reasoning) {
      output += `- **Reasoning**: ${bullet.reasoning}\n`;
    }
    output += `</details>\n\n`;
  }

  return output;
}

🔧 Troubleshooting

Common Errors

Error Cause Solution
cass not found cass CLI not installed Install from cass repo
cass search failed cass index missing or corrupt Run cass index --full
API key missing No LLM API key set Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_GENERATIVE_AI_API_KEY
Playbook corrupt Invalid YAML in playbook Run cm doctor --fix
Rate limited Too many LLM requests Wait for retry (exponential backoff is automatic)
Budget exceeded Daily/monthly limit hit Check cm usage, adjust limits in config
Config invalid Malformed config file Validate JSON syntax, check schema
Session not found Path doesn't exist Verify path with cass sessions
Embedding model failed Model download issue Check network, try cm doctor --fix

Diagnostic Commands

# Check system health
cm doctor --json

# Auto-fix common issues
cm doctor --fix

# Check LLM budget status
cm usage

# List playbook health
cm stats --json

# Show bullet provenance
cm why <bullet-id>

# Verify cass integration
cm context "test" --json  # Check degraded field

Recovery Steps

Oversized legacy playbooks

An older playbook may contain more than 200,000 expanded values from legitimate learned rules, feedback and metadata. That was possible before v0.5.1 introduced the ordinary input caps. A limit failure does not mean the playbook is corrupt. Stop scheduled reflection jobs and other writers while performing recovery.

For your trusted global playbook, restore loading by configuring a bounded budget without rewriting the playbook:

# Read-only inspection under fixed recovery ceilings, with proposed limits
cm playbook repair --recover-limits --dry-run --json

# Apply the reviewed limit change; preserve every playbook byte
cm playbook repair --recover-limits --json

# Check retrieval after recovery
cm stats --json
cm context "test memory retrieval" --history 0 --json

This operation inspects the complete file under the fixed 64 MiB, 2,000,000-value, 100,000-element recovery ceilings. It validates both the original document and the schema-expanded form used by future writes, then proposes sufficient limits with up to 25% growth room within those ceilings. The preview reports actual usage, proposed/effective limits and a SHA-256 digest. Applying it changes only the global playbookLimits settings, preserves unrelated configuration and its YAML comments, and creates a byte-exact, verified configuration backup before atomic replacement. Playbook bytes, rules, IDs, feedback events (including repeated events), retired/candidate status and metadata are untouched. No backup or lock is created by a dry run. Interruption before the configuration replacement leaves the original configuration and playbook intact; retry the same command.

--recover-limits accepts only the independently configured trusted global owner. --file must match that owner; --repo is rejected. A lower environment override is reported instead of silently bypassed. Invalid schemas, unsafe YAML or files over the fixed recovery ceilings fail without replacing either file. The JSON result identifies any configuration backup. doctor --fix --dry-run includes this as a manual recovery step; even doctor --fix --force does not automatically trust an unreadable document or raise a parsing limit.

If the oversized file also contains derived inline embedding arrays, you can remove those separately. This existing repair is available for an explicitly selected trusted local file, including a repository file:

# Preview the configured playbook without changing it or creating a backup
cm playbook repair --strip-embeddings --dry-run --json

# Apply the reviewed repair, creating a verified backup first
cm playbook repair --strip-embeddings --json

# Or explicitly select a trusted file (also works with broken configuration)
cm playbook repair --strip-embeddings --file /trusted/path/playbook.yaml --dry-run

# Select only this repository's playbook
cm playbook repair --strip-embeddings --repo --dry-run

# Verify normal operations after applying the repair
cm stats --json
cm context "test memory retrieval" --json

Repair removes only each bullet's derived embedding field. It preserves all bullets, IDs, feedback, counters, timestamps, provenance, and other non-embedding fields, including fields unknown to the current schema. It verifies that the result passes the selected file's input limits and schema before replacing the file. The preview reports bullet/vector counts, original and repaired sizes, SHA-256 hashes, and preservation status. Applying the repair requires a verified, exclusive backup and uses atomic replacement under the playbook lock; any validation or backup failure leaves the original in place. The JSON result gives the backup path. Keep that backup until subsequent operations are verified. YAML formatting and comments may change during repair; the backup retains the exact original bytes.

The migration reader accepts at most 64 MiB and 2,000,000 expanded values, with bounded arrays, keys, depth, YAML tokens, and aliases. Those maximum bounds cannot be raised in configuration. If removing vectors does not bring the result within its selected limits, repair refuses to replace it. Stdin, URLs, symlinks, and nonregular files are not supported repair inputs. cm doctor reports files near or over the selected byte limit and recommends a preview; doctor --fix does not silently run this migration.

Existing external embeddings in ~/.cass-memory/embeddings/ remain available through their existing bullet IDs and content hashes. Repair leaves that cache untouched; missing vectors are regenerated when semantic search needs them. Normal playbook writes keep derived embeddings out of YAML, including after cache hydration, so subsequent reflection and feedback writes can continue safely. Ordinary loads and saves also retain legacy evidence such as derivedFrom and helpfulEvents, including nested fields unknown to the current schema. Known fields remain validated, and retained fields still count toward resource limits.

Retired rule archival

cm playbook archive --retired provides an explicit way to make room in the trusted global playbook. A rule is eligible only if it is already marked state: retired, maturity: deprecated, or deprecated: true, and is not pinned. Active candidates with no feedback remain untouched. The operation does not deduplicate feedback or decide which learned rules are worth keeping.

# Inspect the exact eligible IDs and the resulting size before changing active state
cm playbook archive --retired --dry-run --json

# Preserve the complete original, then remove only the reviewed retired records
cm playbook archive --retired --json

# An explicit selector must match the independently configured trusted global owner
cm playbook archive --retired --file /trusted/path/playbook.yaml --dry-run

The archive is a complete byte-exact snapshot of the original playbook, saved next to it as playbook.yaml.archive.retired.<timestamp>.<uuid>.yaml. It retains every rule, identifier, feedback event, metadata field, comment and original formatting. The active document's learned data changes only by removing the selected records from its bullets array; surviving records keep their order and all their fields. Active YAML formatting and comments may change; the archive keeps the exact original. Metadata and pinned records are preserved even when they reference retired rules. Legacy duplicate IDs are handled by record position, so archiving one retired record does not erase an active record with the same ID.

A dry run creates no archive, temporary file or lock. It reports selected IDs, archived/retained/pinned counts, bytes and hashes. Application verifies and flushes the original snapshot before atomically replacing active state under the writer lock. The result includes the archive path. A failed archive or staging write leaves the original active file intact; errors after the replacement explicitly report that the new active file was installed. Keep any reported archive, including an incomplete copy left by an interrupted write. A later retry creates a new exclusive snapshot instead of overwriting previous evidence.

Archival refuses to proceed until outstanding reflection and feedback obligations finish. If a pending transaction or queued outcome still needs the playbook, run cm reflect to complete recovery and feedback delivery, then preview archival again. Unreadable or ambiguous recovery ledgers also block archival; they are not treated as empty queues. This prevents a retired rule from disappearing before its final queued feedback reaches the snapshot.

The source is read under the fixed trusted recovery ceilings, and the remaining active playbook must fit its selected ordinary/trusted limits. If too much learned state remains, the command fails without replacing the source; preview cm playbook repair --recover-limits --dry-run first. Repository files, imports, symlinks and arbitrary --file targets cannot use this operation. Reflection never invokes archival automatically.

Retention policy: archives are retained indefinitely and are never loaded into ordinary context automatically or deleted by cm. Keep them for inspection and deliberate restoration, together with the active playbook containing later learning. Repeating archival without newly eligible records makes no changes and creates no additional snapshot. Review and explicitly retire individual rules only when you intend to remove them from active use; lack of feedback alone does not authorize that decision.

Corrupted playbook:

# 1. Check for backup
ls ~/.cass-memory/playbook.yaml.backup.*

# 2. Run doctor to diagnose
cm doctor

# 3. If needed, re-initialize (creates backups)
cm init --force

Missing API key:

# For Anthropic (recommended)
export ANTHROPIC_API_KEY="sk-ant-..."

# For OpenAI
export OPENAI_API_KEY="sk-..."

# Add to shell profile for persistence
echo 'export ANTHROPIC_API_KEY="..."' >> ~/.zshrc

LLM-free mode:

# Run without LLM calls (limited functionality)
CASS_MEMORY_LLM=none cm context "task" --json

cass integration issues:

# Check cass directly
cass health

# Rebuild cass index if needed
cass index --full

# Test cass-memory integration
cm doctor --json | jq '.checks[] | select(.category | contains("cass"))'

🎯 Design Philosophy

Core Principles

1. Deterministic Curation (No LLM)

The curator stage uses NO LLM. This is the most critical design decision:

  • Prevents context collapse from feedback loops
  • Ensures reproducible behavior
  • Avoids expensive redundant LLM calls

LLM extracts patterns (Reflector). Deterministic logic manages them (Curator).

2. Scientific Validation

Rules aren't accepted on faith. Every new rule must pass an evidence gate:

  • Search cass for sessions where the pattern would apply
  • Count successful vs failed outcomes
  • Only accept rules with positive evidence

3. Time-Aware Confidence

Knowledge decays. A rule that was helpful 8 times in January but never validated since:

  • Loses half its confidence by April
  • Loses 75% by July
  • May be auto-deprecated by October

This prevents stale rules from polluting the playbook.

4. Fail-Safe Degradation

Every external dependency has a fallback:

  • cass unavailable → playbook-only mode
  • LLM unavailable → deterministic reflection
  • Network down → cached embeddings
  • Config corrupt → safe defaults

Architectural Trade-offs

Decision Rationale Cost
No LLM in Curator Prevents context collapse Less "smart" merging
90-day decay Keeps playbook fresh Requires ongoing validation
4x harmful weight One mistake is costly Slower positive learning
Local-first Privacy, speed, offline No cloud sync
YAML playbook Human-editable, git-friendly Merge conflicts possible
Bun runtime Fast startup, TypeScript native Less mature than Node

What We Deliberately Avoid

  1. Auto-executing rules - We advise, never execute
  2. Cloud sync - Data stays local by design
  3. Real-time collaboration - Different tool category
  4. Complex UI - CLI-first for agent consumption
  5. Proprietary formats - YAML/JSON for transparency

⚖️ Comparison with Alternatives

Why Not Just Comments/Notes?

Aspect Manual Notes cass-memory
Cross-agent Manual sync Automatic
Confidence tracking No Built-in decay
Evidence-based No cass validation
Searchable Depends on format Always
Auto-learning No Yes
Anti-patterns Manual Auto-inverted

Why Not Just Search cass Directly?

Aspect Raw cass cass-memory
Distilled rules No Yes
Confidence scoring No Yes
Anti-patterns No Auto-inverted
Task relevance Manual query Automatic
Semantic search No Optional
Maturity tracking No Yes

Verdict: cass is the foundation. cass-memory adds the learning layer.

Why Not Cursor Rules / Claude Memory?

Aspect Vendor Memory cass-memory
Cross-agent Single vendor All agents
Local control Vendor-managed You own it
Confidence decay No Yes
Evidence validation No cass-based
Open source No Yes
Customizable Limited Fully

Verdict: Vendor memory is convenient but siloed. cass-memory unifies all agents.

Why Not LangChain Memory / MemGPT?

Aspect LangChain/MemGPT cass-memory
Focus General LLM memory Coding agents specifically
Learning source User-provided Auto from sessions
Rules format Embeddings only Rules + embeddings
Decay No Yes
Anti-patterns No Yes
Offline Limited Full

Verdict: General memory systems lack coding-specific features like anti-pattern inversion and session outcome tracking.


🗺️ Roadmap

Near-Term

  • Improved semantic search with better embedding models
  • More starter playbooks (Ruby, Go, Rust, Java)
  • Better conflict resolution in curation
  • VS Code extension for inline feedback visualization

Medium-Term

  • Team playbook sharing (opt-in, encrypted)
  • Web dashboard for playbook visualization
  • Active learning - ask agents for feedback on uncertain rules
  • Git-based playbook sync across machines

Long-Term

  • Federated learning across teams
  • Automatic rule refinement based on outcomes
  • Multi-modal rules (diagrams, code snippets)
  • Integration with more agent platforms

Non-Goals

These are explicitly out of scope:

  • Cloud sync - This is local-first by design
  • Real-time collaboration - That's a different tool category
  • Agent execution - We search and advise, not execute
  • Universal knowledge base - Focus remains on coding agents

🧪 Development

git clone https://github.com/Dicklesworthstone/cass_memory_system.git
cd cass_memory_system
bun install

# Dev with hot reload
bun --watch run src/cm.ts <command>

# Tests
bun test
bun run test:watch
bun run test:coverage

# Type check
bun run typecheck

# Lint
bun run lint

# Build all platforms
bun run build:all

Testing Categories

Category Naming Run
Unit *.test.ts bun run test:unit
Integration *.integration.test.ts bun run test:integration
E2E *.e2e.test.ts bun run test:e2e
Property *.property.test.ts bun run test:property

Coverage targets: ~80% lines, 80% functions, 70% branches.

Build Outputs

Platform Output
Linux x64 dist/cass-memory-linux-x64
Linux ARM64 dist/cass-memory-linux-arm64
macOS ARM64 dist/cass-memory-macos-arm64
macOS x64 dist/cass-memory-macos-x64
Windows x64 dist/cass-memory-windows-x64.exe

📜 License

MIT License (with OpenAI/Anthropic Rider). See LICENSE for details.


🙏 Acknowledgments

  • cass — The foundation that makes cross-agent search possible
  • ACE Paper — The Agentic Context Engineering framework that inspired the pipeline design
  • Xenova/transformers — Browser/Node.js transformers for embeddings
  • Bun — Fast JavaScript runtime that makes CLI tools snappy

About Contributions: Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via gh and independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.

Explorar proyectos relacionados

Cargando…