cass-memory

repository·main·Indexed 19 days ago

https://github.com/dicklesworthstone/cass_memory_system

A universal procedural memory system for AI coding agents implementing the ACE (Agentic Context Engineering) framework. It transforms unstructured agent session logs into a persistent, cross-agent knowledge base of actionable rules and anti-patterns. The system utilizes a three-layer cognitive architecture consisting of Episodic Memory (via cass), Working Memory (Diaries), and Procedural Memory (Playbook), featuring confidence decay and automatic anti-pattern learning to prevent context collapse and stale information.

Tokens
101K
Snippets
313
Records
425
Agent score
64%

What's inside cass-memory

  1. Overview of the CASS Memory System Testing Strategy

    main

    The CASS Memory System uses a multi-layered testing approach to ensure reliability across logic, persistence, and LLM integrations. The strategy is categorized as follows:

    CategoryFocusFramework
    Unit TestsIndividual functions, pure logicbun test
    Integration Testscass interaction, file I/Obun test + fixtures
    LLM TestsMocked LLM responsesbun test + mocks
    E2E TestsFull command workflowsShell scripts
    Property TestsEdge cases, fuzzingfast-check
  2. Overview of ace (Agentic Context Engine)

    main

    What is ace?

    ace (Agentic Context Engine) is a universal "Memory Middleware" designed for coding agents. It decouples memory management from the agent itself to prevent hallucinations and ensure a "Scientific Memory" loop.

    Instead of relying on an agent's internal reflection, ace uses the cass tool to enforce a two-step workflow:

    1. Hydrate: Before starting a task, search cass to retrieve the "Ground Truth" of historical context.
    2. Reflect: After completing work, validate new insights against cass history before committing them to a permanent playbook.

    ace is implemented as a single-file TypeScript CLI that runs on Bun and utilizes the Vercel AI SDK.

  3. Overview of the agent-reflect CLI

    main

    The agent-reflect CLI is a single-file TypeScript tool designed for coding agents (e.g., Claude Code, Cursor, Aider) to perform reflection and memory updates. It integrates with the cass memory system to act as a cross-agent retriever, allowing agents to fetch historical insights from all indexed agents to enrich their own reflections.

    Key capabilities include:

    • Episodic Memory: Distilling session logs into "diary" entries.
    • Procedural Memory: Synthesizing rules for playbooks (e.g., CLAUDE.md).
    • Cross-Agent Retrieval: Using cass search --robot to fetch relevant historical snippets.
    • AI-Powered Reflection: Using the Vercel AI SDK to analyze traces and curate updates via LLMs (OpenAI, Anthropic, etc.).
  4. Understand the CASS Memory System implementation roadmap

    main

    The CASS Memory System is being implemented in four distinct phases, moving from foundational core features to advanced intelligent capabilities.

    • Phase 1 (Foundation): Focuses on high-ROI core features including confidence decay, state lifecycles (draft/active/retired), Kind enums, secret sanitization, and basic CLI scaffolding (cm init, cm context --json).
    • Phase 2 (Core Pipeline): Introduces the diary → reflect → curate pipeline, including commands like diary, forget, mark, and doctor for system health.
    • Phase 3 (Advanced Intelligence): Adds multi-iteration reflection (ACE pattern), local semantic search using @xenova/transformers, and a stats dashboard.
    • Phase 4 (Polish & Integration): Finalizes production readiness with audit and project commands (for AGENTS.md generation), binary compilation, and MCP server mode support.
  5. How anti-pattern conversion works

    main

    When a rule accumulates significant negative feedback (harmful ratio > 50% and at least 3 harmful marks), the system can convert it into an anti-pattern.

    The process involves:

    1. Inversion: The content is transformed (e.g., "Always X" becomes "PITFALL: Don't always x").
    2. Replacement: The original rule is marked as deprecated.
    3. Reset: The new anti-pattern starts with a fresh candidate maturity and zeroed feedback counts.
    // Example of content inversion logic
    // "Always X" → "PITFALL: Don't always x"
    // "Use X for Y" → "PITFALL: Avoid using X for Y without consideration"
  6. How the Reflector Phase extracts insights

    main

    The Reflector Phase uses a multi-iteration LLM approach to extract insights from a session. It takes a DiaryEntry, the sessionContent, and existingBullets to produce PlaybookDelta[].

    To ensure high-quality insights and avoid redundancy, the process:

    • Iterates up to config.maxReflectorIterations times.
    • Uses a schema-driven LLM call to generate deltas.
    • Deduplicates insights within a single reflection cycle using hashDelta to ensure the same insight isn't proposed multiple times.
    async function reflectOnSession(
      diary: DiaryEntry,
      sessionContent: string,
      existingBullets: Bullet[],
      config: Config
    ): Promise<PlaybookDelta[]> {
      const allDeltas: PlaybookDelta[] = [];
      const seenHashes = new Set<string>();
    
      for (let i = 0; i < config.maxReflectorIterations; i++) {
        const deltas = await llm.generateObject({
          schema: DeltaSchema,
          prompt: buildReflectorPrompt(diary, sessionContent, existingBullets, i)
        });
    
        for (const delta of deltas) {
          const hash = hashDelta(delta);
          if (!seenHashes.has(hash)) {
            seenHashes.add(hash);
            allDeltas.push(delta);
          }
        }
    
        if (deltas.length === 0) break;
      }
    
      return allDeltas;
    }
  7. Understand the cass-memory three-layer architecture

    main

    The cass-memory system uses a three-layer cognitive architecture to transform raw agent interactions into actionable procedural knowledge. This prevents 'context collapse' (loss of detail during summarization) and ensures knowledge is shared across different AI agents.

    1. Episodic Memory (via cass): The raw ground truth. It consists of raw session logs from all agents (e.g., Claude Code, Cursor, Aider, Gemini). This layer is accessed using cass search --robot.
    2. Working Memory (Diary Layer): Structured session summaries that bridge raw logs to rules. It tracks accomplishments, decisions, challenges, and preferences.
    3. Procedural Memory (Playbook): Distilled, actionable rules. These include bullets, counters (for helpful/harmful tracking), source tracing, and deprecation (tombstones).
  8. Configure Trauma Guard storage scopes

    main

    Trauma patterns are stored at two levels depending on the desired scope:

    • Global: Stored in ~/.cass-memory/traumas.jsonl. These patterns apply to all your projects.
    • Project: Stored in .cass/traumas.jsonl. These are project-specific and can be committed to your repository to share safety knowledge with your team.
  9. How cass-reflect prevents context collapse

    main

    To avoid "context collapse" (where LLMs lose information by over-summarizing), cass-reflect uses deterministic delta merging in its Curator.

    This approach ensures:

    1. Information Preservation: Prevents loss from over-summarization.
    2. Reproducibility: Enables reproducible evolution of your playbook.
    3. Cost Efficiency: Avoids unnecessary API costs for the curation process itself.
    4. Append-only Growth: The system grows by appending new information, only pruning bullets that are explicitly identified as harmful.
  10. Cass Data Model: Sessions, Diaries, and Playbooks

    main

    The proposed memory architecture builds three layers on top of the existing Cass index:

    1. Sessions (Existing)

    Cass normalizes logs into a Session model containing source_path, agent, workspace, created_at, and messages. These serve as the 'reasoning trajectories' for the system.

    2. Cass Diary Entries (Episodic Layer)

    Summaries of sessions stored as Markdown files.

    • Global Path: ~/.cass/memory/diary/YYYY-MM-DD-session-<short-hash>.md
    • Workspace Path: <workspace>/.agent-memory/diary/YYYY-MM-DD-session-<short-hash>.md
    • Fields: id, session_path, agent, workspace, created_at, status, tags, summary, design_decisions, mistakes_and_fixes, user_preferences, and tooling_insights.

    3. ACE-style Playbooks (Procedural Layer)

    Structured bullets for reusable strategies, stored in .jsonl format.

    • Global Path: ~/.cass/memory/playbooks/global-playbook.jsonl
    • Workspace Path: <workspace>/.agent-memory/playbook.jsonl
    • Fields: id, scope (global or workspace), category, content, helpful_count, harmful_count, created_at, last_updated, and source (links to diary/session paths).
  11. How duplicate and conflict detection works

    main

    To maintain a clean and reliable playbook, cass-memory employs several detection algorithms:

    Duplicate Detection

    Prevents redundant rules using two methods:

    • Exact Hash Match: Normalizes content (lowercase, removes special characters, collapses whitespace) and compares hashes.
    • Semantic Similarity: If embeddings are available and semanticSearchEnabled is true, it checks if the cosineSimilarity exceeds config.dedupSimilarityThreshold.

    Conflict Detection

    Identifies contradicting rules by:

    • Direct Negation: Checking if a new rule is the logical negation of an existing active rule (e.g., 'always do X' vs 'never do X').
    • Semantic Contradiction: Using LLM-based or embedding-based checks to find rules that semantically oppose existing active bullets (threshold typically > 0.8).
  12. Understand the Trauma Pattern lifecycle

    main

    Trauma patterns move through three states:

    • Active: The pattern is currently blocking matching commands.
    • Healed: The pattern is temporarily bypassed (requires a reason and timestamp). This is used for intentional, controlled operations.
    • Deleted: The pattern is removed from the registry but can be re-added later.