mempal

repository·main·Indexed 42 days ago

https://github.com/zhanghandong/mempal

A project memory system for coding agents featuring a single-binary solution with hybrid search (BM25 + vector) and a knowledge graph. It provides tools for storing decision context, cross-session learning via an Agent Diary, and MCP server integration for agents like Claude Code and Codex.

Tokens
186.7K
Snippets
538
Records
844
Agent score
52%

What's inside mempal

  1. mempal Interface Options: MCP and REST API

    main

    mempal can be integrated into workflows using several interface types:

    • MCP Server: Implemented via the rmcp crate, providing 10 tools for Model Context Protocol compatibility.
    • REST API: An axum-based REST API is available, but it is feature-gated. You must enable the rest feature during installation/build to use it.
    • CLI: A command-line interface built with clap 4.x.
  2. What is AAAK dialect?

    main

    AAAK is an AI-oriented shorthand format designed to compress natural language text into structured, pipe-delimited lines. It allows Large Language Models (LLMs) to quickly understand context summaries without the overhead of full natural language.

    Key distinction: AAAK is not a storage format. The original raw text is always preserved in the drawers (the core storage), while AAAK is used exclusively on the output side via the wake-up --format aaak command or the compress command.

    V1|myapp|auth|2026-04-08|readme
    0:KAI+CLK|clerk_auth|"Kai recommended Clerk over Auth0 based on pricing and DX"|★★★★|determ|DECISION
    1:KAI|auth_rollout|"roll out Clerk next sprint"|★★★|relief|TECHNICAL
    T:0<->1|auth_link
    ARC:anx->determ->relief
  3. Understand the P114 Coarse Workspace Split Architecture

    main

    The mempal project is undergoing a workspace split to move implementation details from the root package into specialized, reusable crates. The root mempal package remains the primary CLI, configuration, and API facade, ensuring backward compatibility through re-exports (facade paths).

    New Crate Structure:

    • mempal-store-sqlite: Handles SQLite persistence.
    • mempal-runtime: Contains core business logic and runtime modules (e.g., search, ingest, context, cowork).
    • mempal-mcp-server: Handles Model Context Protocol (MCP) server wiring.

    Key Constraints:

    • The root package name remains mempal.
    • CURRENT_SCHEMA_VERSION must remain 9.
    • Legacy root facade paths must be preserved via pub use statements.
  4. Research Ingestion Policy (P49)

    main

    The P49 policy defines how external research-rs outputs are integrated into the mempal memory system. To prevent research from becoming a parallel authority to the dao, research outputs must follow a specific ingestion path that respects existing memory lifecycle gates.

    Ingestion Rules

    • Evidence Entry: Research raw or source output must enter the system as memory_kind=evidence with provenance=research.
    • Knowledge Promotion: Research summaries or insights cannot directly create dao_tian, canonical, or promoted knowledge. They may only become candidate knowledge through the distill process from existing evidence references.
    • Handling Contradictions: If research produces signals that contradict existing memory, these should be stored as evidence or counterexamples to be evaluated during later demotion or gate evaluation cycles.

    Constraints

    • Research is considered external qi and is not a dao container.
    • Research must not bypass lifecycle gates or directly create promoted knowledge types.
  5. Automatic format detection during ingestion

    main
    When running the mempal ingest command, you are not required to manually specify the --format flag. MemPal uses an internal detect_format() mechanism to automatically identify the file structure (e.g., recognizing a Slack export directory or a Codex CLI JSONL file) and applies the appropriate parsing and normalization logic.
  6. How text chunking works in mempal-ingest

    main

    The mempal-ingest crate provides two primary methods for breaking down content into manageable chunks for embedding:

    1. Fixed Window Chunking: chunk_text(text, window, overlap) splits a continuous string into chunks of a specific size (window) with a specified amount of overlap between adjacent chunks. This is useful for standard text files.
    2. Conversation/QA Chunking: chunk_conversation(transcript) is designed for dialogue-style data (like chat logs). It splits content based on conversational turns (e.g., separating user/assistant pairs) to preserve the context of individual exchanges.
    // Example of fixed window chunking
    let text = "a".repeat(2000);
    let chunks = chunk_text(&text, 800, 100);
    
    // Example of conversation chunking
    let transcript = "> How do I fix this?\nTry restarting.\n\n> What about the config?\nCheck settings.toml.";
    let chunks = chunk_conversation(transcript);
  7. How project identity and directory scoping works

    main

    Mempal uses project_identity(cwd) to determine the target inbox.

    • Git Repositories: The identity is normalized to the git repository root. This means any sub-directory within the same git repo will resolve to the same project_identity, allowing seamless collaboration across different folders in the same project.
    • Non-Git Projects: The identity falls back to the raw current working directory (cwd). In these cases, sub-directories are isolated from each other.
    • Special Characters: The encode_project_identity function replaces / with - but preserves other special characters (like spaces or brackets) that the OS filesystem can handle.
    • Codex Integration: For Codex users, mempal cowork-drain --cwd-source stdin-json is used to read the cwd field from the Codex hook's stdin JSON. This ensures the correct project identity is used regardless of the shell's $PWD.
  8. Understand Cowork Receipt Handles and Message IDs

    main

    In the mempal Cowork protocol, every message push generates a unique, trackable receipt_handle (also referred to as message_id).

    Key characteristics of these handles:

    • Format: They are prefixed with msg_ followed by a 12-hex string.
    • Determinism: When using build_message_id, the ID is deterministic based on pushed_at, from, and content.
    • Uniqueness: Even with identical content and timestamps, concurrent pushes are guaranteed to receive unique handles.
    • Fallback Mechanism: If the system cannot read the existing receipts log (e.g., due to malformed lines or IO issues), it uses a collision-resistant fallback handle instead of the deterministic one to ensure the push still succeeds.
    • MCP Compatibility: When using the mempal-mcp-server, the mempal_cowork_push tool returns a message_id that is required by the CoworkPushResponse schema.
    // Example of the expected message_id format
    // "msg_" + 12-hex handle
    // e.g., "msg_a1b2c3d4e5f6"
  9. Core Architecture and Storage of mempal

    main

    mempal is a Rust-based memory tool designed for coding agents to retrieve historical decisions with source citations in under 10 seconds. It uses a Wing/Room organizational structure and follows a 'verbatim storage' philosophy where data is stored in its raw form.

    Storage Details:

    • Engine: SQLite with sqlite-vec extension.
    • Database Path: A single file located at ~/.mempal/palace.db.
    • Data Integrity: Data is stored as raw verbatim in the drawers table. Formatting (via the AAAK crate) only occurs during the output phase.
  10. How Evaluators interact with the Knowledge Lifecycle

    main

    In the Mempal system, Evaluators serve an advisory role and are strictly prohibited from acting as lifecycle writers. This ensures that the system maintains deterministic replay, evidence citation, and audit semantics.

    What Evaluators CAN do:

    • Recommend promotion or demotion candidates.
    • Propose supporting, verification, teaching, and counterexample evidence references.
    • Produce contradiction candidates and risk notes.
    • Explain why a knowledge item appears ready or unsafe.

    What Evaluators MUST NOT do:

    • Directly mutate the status of a knowledge item.
    • Append lifecycle refs as authoritative gate input.
    • Bypass deterministic promotion or demotion gates.
    • Satisfy reviewer requirements via evaluator-only review.
    • Create automatic promotion or demotion paths.

    Note: Canonicalization of dao_tian requires a human reviewer; evaluator-only canonization is forbidden.

  11. Understand the card-context rollback mechanism

    main

    The card-context rollback policy is designed to manage the adoption of card-aware context. It monitors runtime_adoption_events for specific signals to determine if a feature should be disabled.

    How it works

    1. Evidence Collection: The system looks for events where track=card_context, feature=include_cards, and signal=rollback.
    2. Evaluation: The rollback executor checks if these signals exist in the runtime adoption history.
    3. Action: If rollback is required and --execute is used, the executor sets context.include_cards_default=false in the local configuration.

    Constraints

    • Rollback execution cannot alter knowledge card lifecycle states (promotion/demotion).
    • Rollback execution cannot write or mutate runtime adoption events.
    • If include_cards_default is already false, the execution is a no-op and will report applied=false even if rollback is required.
  12. Understand the mempal mental model

    main

    mempal is a local memory system for coding agents that stores raw text in SQLite and builds embeddings for retrieval. It uses a hierarchical scope system and a raw-first storage approach.

    Core Abstractions

    • wing: The top-level scope, typically representing a single project or a specific knowledge domain.
    • room: A sub-scope within a wing, usually inferred from directory structures or managed via taxonomy.
    • drawer: A single stored memory item or text chunk.
    • source_file: The origin of a drawer. For directory ingests, this is stored relative to the ingest root.

    Storage Model

    mempal is "raw-first", meaning it preserves original data:

    • Original text is stored in the drawers table.
    • Vectors are stored in the drawer_vectors table.
    • AAAK (an output format) is output-only and does not replace the stored raw text.