Generated banner for mempal
Generated logo for mempal

mempal

Memory framework

First committed by ZhangHanDong

Published in ZhangHanDong/mempal. Publisher page

284 GitHub stars

What it is

AI Agent Memory
— the description by ZhangHanDong

AutoGineer overview, from the brain’s own files

Mempal is a project memory system designed for coding agents, implemented as a single binary. It enables agents to store, search, and retrieve decision context across sessions. The system utilizes a hybrid search approach combining BM25 keyword matching and vector semantic search, alongside a knowledge graph for tracking entity relationships. It includes a self-describing protocol that allows agents to understand how to interact with the memory system without manual system prompt configuration. Mempal supports cross-project tunnels, multilingual embedding, and collaborative agent workflows through inbox-based handoffs.

How it works

Memory model: Hybrid

AutoGineer overview, from the brain’s own files

Mempal stores data in a SQLite database located at ~/.mempal/palace.db. It ingests project information by chunking and embedding content, which is then searchable via CLI or MCP tools. The system uses a memory protocol to guide agent behavior, such as verifying facts before ingestion and citing sources. It supports collaborative agent interactions by allowing agents to push messages to a per-project inbox, which are then processed via hooks during user prompt submission. The knowledge graph tracks triples with temporal validity, and the system provides tools for fact-checking and context assembly.

Folders
FolderRoleFiles
.claudeagent-config2
.githubagent-config3
docsdocs129
hookshooks2
srcsource-code30
teststests31
benchmarksfolder1
booksfolder41
cratesfolder71
specsfolder131

The agent writes

Requirements

Runtimes: Rust

Databases: SQLite

Works with: Claude Code, OpenAI Codex, GitHub Copilot, Cursor, Kiro, OpenCode, Amp, Cline, JetBrains Junie, Devin (ex-Windsurf)

Set it up

  1. This brain runs code automatically: 2 hooks (claude-code). Review .claude/settings.json before opening the folder in Claude Code. No step below turns a hook on for you.

    • .claude/settings.json: if echo "$TOOL_INPUT" | grep -q 'git commit'; then echo 'MEMPAL REMINDER: You just committed code. Call mempal_ingest to save the decision context (what was built, why, what was considered). Rule 4: SAVE AFTER DECISIONS.'; fi
    • .claude/settings.json: bash .claude/hooks/user-prompt-submit.sh
  2. Not scanned by AutoGineerThe author’s MCP configuration (.mcp.json) also starts it in a way AutoGineer does not offer. Read that file: AutoGineer did not scan that path; what it runs is listed under “This brain runs”. https://github.com/ZhangHanDong/mempal/blob/9ed705d78321daf5878e9579777b1a471e97c6f1/.mcp.json
  3. Not scanned by AutoGineerThe author’s README also describes installing it with cargo. Read its install section: AutoGineer did not scan that path. https://github.com/ZhangHanDong/mempal/blob/9ed705d78321daf5878e9579777b1a471e97c6f1/README.md#quick-start
  4. First committed by ZhangHanDong. Published in ZhangHanDong/mempal. Licence: MIT License.

Usage

AutoGineer overview, from the brain’s own files

  • Initialize project memory for a directory
  • Ingest project files into a specific wing
  • Perform hybrid search for past decisions
  • Fact-check assertions against the knowledge graph
  • Collaborate between agents using inbox pushes
  • Manage knowledge lifecycle and anchor publication
“mempal search "auth decision clerk"”
Returns past decisions related to authentication and Clerk, including source citations.
“mempal fact-check path/to/file”
Identifies potential contradictions like similar name conflicts or stale facts against the knowledge graph.

Documentation by ZhangHanDong

mempal

Image: Crates.io Image: Downloads Image: docs.rs Image: CI Image: Release Image: License: MIT

Project memory for coding agents. Single binary, cargo install mempal, find past decisions with citations in seconds.

Latest release: v0.9.1 (2026-08-19).

What It Does

Agent writes code → commits → mempal saves the decision context
Next session (any agent) → mempal search → finds the decision with source citation
  • Hybrid search: BM25 keyword matching + vector semantic search, merged via Reciprocal Rank Fusion

  • Knowledge graph: subject-predicate-object triples with temporal validity (valid_from/valid_to)

  • Cross-project tunnels: automatic discovery when the same room appears in multiple wings

  • Self-describing protocol: MEMORY_PROTOCOL embedded in MCP ServerInfo teaches any agent how to use mempal — no system prompt configuration required

  • Multilingual: model2vec-rs (BGE-M3 distilled) as default embedder, zero native dependencies

  • Single file: everything lives in ~/.mempal/palace.db (SQLite + sqlite-vec)

Quick Start

cargo install mempal --version 0.9.1 --locked

mempal init ~/code/myapp
mempal ingest ~/code/myapp --wing myapp
mempal search "auth decision clerk"
mempal wake-up

With REST support:

cargo install mempal --version 0.9.1 --locked --features rest

From a source checkout:

cargo install --path . --locked

Configuration

Config at ~/.mempal/config.toml (optional, defaults work without it):

db_path = "~/.mempal/palace.db"

[embed]
backend = "model2vec"                          # default, zero native deps
# model = "minishlab/potion-multilingual-128M" # default multilingual model (1024d)

Other backends:

# Local ONNX (requires --features onnx)
[embed]
backend = "onnx"

# External API
[embed]
backend = "api"
api_endpoint = "http://localhost:11434/api/embeddings"
api_model = "nomic-embed-text"
dimensions = 768  # optional; defaults to 384 when omitted

Commands

CommandPurpose
mempal init <DIR> [--dry-run]Infer wing/rooms from project tree
mempal ingest <DIR> --wing <W> [--dry-run]Chunk, embed, and store
mempal search <QUERY> [--wing W] [--room R] [--json]Hybrid search (BM25 + vector + RRF)
mempal wake-up [--format aaak]Context refresh, sorted by importance
mempal compress <TEXT>AAAK format output
mempal delete <DRAWER_ID>Soft-delete a drawer
mempal purge [--before TIMESTAMP]Permanently remove soft-deleted drawers
mempal kg add <S> <P> <O>Add a knowledge graph triple
mempal kg query [--subject S] [--predicate P]Query triples
mempal kg timeline <ENTITY>Chronological view of an entity
mempal kg statsKnowledge graph statistics
mempal tunnelsCross-wing room links
mempal taxonomy list / editManage routing keywords
mempal reindexRe-embed all drawers after model change
mempal statusDB stats, schema version, scopes
mempal serve [--mcp]MCP server (+ REST with feature)
mempal cowork-install-hooks [--global-codex]Install UserPromptSubmit hooks for Claude Code (+ optional Codex merge)
mempal cowork-drain --target <claude|codex>Drain inbox messages (for hook use; exits 0 on any failure)
mempal cowork-status --cwd <PATH>Read-only view of both inboxes at <PATH>
mempal fact-check [PATH|-] [--wing W] [--room R] [--now <UNIX_SECS>]Offline contradiction check against KG triples + known entities
mempal bench longmemeval <FILE>LongMemEval retrieval benchmark
Project ignore rules

mempal init <DIR> and directory-mode mempal ingest <DIR> use the target project's ignore rules by default. They respect .gitignore, .git/info/exclude, global Git excludes, and a root-level .mempalignore. Built artifacts that should never become project memory can be listed in .mempalignore without changing the project's Git behavior.

Use --ignore-file <PATH> to add one or more extra ignore files for a run. Use --no-gitignore or --no-mempalignore to disable either default source. Explicit file ingest remains explicit: mempal ingest path/to/file --wing <W> still ingests that file even if the project ignore rules would skip it during directory traversal.

MCP Server (10 tools)

mempal serve --mcp exposes these tools via Model Context Protocol:

ToolPurpose
mempal_statusState + protocol + AAAK spec (teaches agent on first call)
mempal_searchHybrid search with tunnel hints, citations, and AAAK-derived structured signals
mempal_ingestStore memories with optional importance (0-5) and dry_run; reports lock_wait_ms when concurrent ingest was observed
mempal_deleteSoft-delete with audit trail
mempal_taxonomyList or edit routing keywords
mempal_kgKnowledge graph: add/query/invalidate/timeline/stats
mempal_tunnelsCross-wing room discovery
mempal_peek_partnerRead partner agent's live session (Claude ↔ Codex), pure read, never writes
mempal_session_peekRead an explicit Claude/Codex local session by concrete tool + cwd, including same-tool cross-project reads
mempal_cowork_pushSend a short handoff message to partner agent's inbox (at-next-submit delivery)
mempal_fact_checkOffline contradiction detection vs KG triples + known entities (similar-name, relation mismatch, stale facts)

The server embeds MEMORY_PROTOCOL (11 behavioral rules) in the MCP initialize.instructions field. Any MCP client learns the workflow automatically.

Memory Protocol

mempal teaches agents these rules through self-description:

  1. FIRST-TIME SETUP — call mempal_status to discover wings before filtering

  2. WAKE UP — different clients have different pre-load mechanisms

  3. VERIFY BEFORE ASSERTING — search before stating project facts

  4. QUERY WHEN UNCERTAIN — search on "why did we...", "last time we..." 3a. TRANSLATE TO ENGLISH — translate non-English queries before searching

  5. SAVE AFTER DECISIONS — persist rationale, not just outcomes

  6. CITE EVERYTHING — reference drawer_id and source_file 5a. KEEP A DIARY — record behavioral observations in wing="agent-diary"

  7. PARTNER AWARENESS — use mempal_peek_partner for live partner-agent session, mempal_session_peek for explicit same-tool/cross-project local sessions, and mempal search only for crystallized drawers

  8. DECISION CAPTURE — mempal_ingest is for firm decisions only; include partner input when peek informed the call

  9. COWORK PUSH — use mempal_cowork_push as the SEND primitive in the SEND/READ/PERSIST triad; at-next-submit delivery, not real-time

  10. VERIFY BEFORE INGEST — call mempal_fact_check before persisting a decision that asserts entity relationships; it catches similar-name typos, relation mismatches against the KG, and stale facts with expired valid_to

Agent Cowork (P6 peek + P8 push)

Two coding agents (Claude Code and Codex) can collaborate on the same repo through a per-project inbox + hook-driven injection channel, on top of mempal_peek_partner (read live partner session), mempal_session_peek (read an explicit local session by concrete tool + cwd), and mempal_cowork_push (send ephemeral handoff).

Install hooks once per repo (run at the repo root):

mempal cowork-install-hooks --global-codex

This writes:

  • .claude/hooks/user-prompt-submit.sh + merges a registration entry into .claude/settings.json so Claude Code fires the hook on every user prompt.

  • ~/.codex/hooks.json UserPromptSubmit entry so Codex fires the same drain on every user prompt.

The --global-codex part is optional. The re-run is idempotent and self-heals stale/wrong drain entries — re-installing after a mempal upgrade is always safe.

Delivery is at-next-UserPromptSubmit, not real-time: a push from Claude to Codex becomes visible only when the Codex user submits their next prompt, at which point the hook drains the inbox and prepends the message as additionalContext on that turn.

Check inbox state at any time without draining:

mempal cowork-status --cwd "$PWD"
Known limitations
  • Codex feature flag dependency: Codex's hooks runtime is gated behind the codex_hooks feature flag (currently "under development" in shipped codex-cli). If the flag is off, Codex silently ignores ~/.codex/hooks.json. install-hooks detects this and prints a warning with the activation command: codex features enable codex_hooks.

  • Two Claude-side artifacts: Claude Code does not auto-discover hook scripts by filename. Both .claude/hooks/user-prompt-submit.sh and the matching entry in .claude/settings.json are required. install-hooks writes both; do not remove either by hand.

  • TUI restart needed after config changes on the Codex side: Codex reads config.toml + hooks.json at process startup only. After enabling the feature flag or running install-hooks, fully quit and relaunch the Codex TUI before expecting hooks to fire.

  • MCP server re-spawn: Claude Code spawns the mempal MCP server at client startup. After upgrading the mempal binary (cargo install ...), restart Claude Code so the MCP server respawns and exposes newly added tools like mempal_cowork_push or mempal_fact_check.

  • Bidirectional scope: mempal_cowork_push currently requires an MCP client identifying itself as claude-code or codex (or their aliases). Generic MCP clients cannot push because caller identity is required to fill the from field and enforce self-push rejection. This is by design for the Claude ↔ Codex pair.

Concurrent Ingest Safety (P9-B)

Two agents writing to the same source simultaneously used to be a TOCTOU race: both would pass the dedup check, both would insert, producing duplicate drawers or mismatched vectors. Since 0.4.0, mempal_ingest and ingest_file_with_options acquire a per-source advisory lock before entering the dedup + insert critical section.

  • Lock files live at ~/.mempal/locks/<16-hex>.lock, created lazily, released on guard drop.

  • 5 s timeout, 50 ms retry + jitter; LockError::Timeout surfaces as an ingest error.

  • Every non-dry-run response carries lock_wait_ms: Option<u64> so agents can detect contention.

  • Dry-run does not acquire the lock (no writes, no race).

  • Unix only in 0.4.0. On Windows the lock path is a no-op fallback; LockFileEx support is tracked for a follow-up.

Offline Fact Checking (P9-A)

mempal_fact_check — and its CLI counterpart mempal fact-check — compare a text blob against the existing KG triples + the entity registry derived from recent drawers. It flags three issue classes, all deterministic and zero-LLM:

IssueTrigger
SimilarNameConflictText mentions a name within Levenshtein distance ≤ 2 of a known entity, and the names are not equal.
RelationContradictionText asserts a predicate (e.g. brother_of) that's in the incompatibility dictionary against an existing KG triple with the same (subject, object) endpoints.
StaleFactText asserts a triple whose KG row has valid_to < now (Unix seconds).

Extracted triples today cover three narrow patterns: "X is Y's ROLE", "X works at / for Y", and "X is [the|a|an] ROLE of Y". Unknown sentence shapes are silently ignored, so the tool errs toward under-reporting rather than false positives.

Protocol Rule 11 guides agents to run this before ingesting a decision that asserts entity relationships. See specs/p9-fact-checker.spec.md for the full contract.

Search Architecture

query → BM25 (FTS5)     → ranked by keyword match
      → Vector (sqlite-vec) → ranked by semantic similarity
      → RRF Fusion (k=60)   → merged ranking
      → Wing/Room filter     → scoped results
      → Tunnel hints         → cross-project references

Knowledge Graph

mempal kg add "Kai" "recommends" "Clerk"
mempal kg add "Clerk" "replaced" "Auth0" --source-drawer drawer_xxx
mempal kg timeline "Kai"
mempal kg stats

Triples support temporal validity — relationships can be invalidated when they expire.

Agent Diary

Cross-session behavioral learning — agents record observations, lessons, and patterns:

# Search diary entries
mempal search "lesson" --wing agent-diary
mempal search "pattern" --wing agent-diary --room claude

Diary entries use the existing mempal_ingest tool with wing="agent-diary" and room=agent-name. MEMORY_PROTOCOL Rule 5a teaches agents to write diary entries. Integrates with Claude Code's auto-dream for automatic memory consolidation.

Ingest Formats (5)

FormatAuto-detected by
Claude Code JSONLtype + message fields
ChatGPT JSONArray or mapping tree
Codex CLI JSONLsession_meta + event_msg entries
Slack DM JSONtype: "message" + user + text
Plain textFallback

AAAK Compression

Output-only format readable by any LLM without decoding:

mempal compress "Kai recommended Clerk over Auth0 based on pricing and DX"
# V1|manual|compress|1744156800|cli
# 0:KAI+CLK+AUT|kai_clerk_auth0|"Kai recommended Clerk over Auth0..."|★★★★|determ|DECISION

Chinese text uses jieba-rs POS tagging for proper word segmentation.

Architecture

CrateResponsibility
mempalInstallable CLI package, REST entrypoint, and legacy facade paths
mempal-embedPublic Embedder / EmbedderFactory traits, API embedder, model2vec and ONNX implementations
mempal-search-corePublic FTS5 query escaping and RRF rank-fusion primitives
mempal-agent-memoryPublic agent-memory domain types and anchor helpers
mempal-mcp-protocolPublic self-describing MEMORY_PROTOCOL text
mempal-store-sqlitePublic SQLite storage layer: schema, migrations, Database, FTS5, sqlite-vec, KG, tunnels, cards, adoption tables
mempal-runtimePublic runtime workflows: ingest, search orchestration, context, brief, knowledge, factcheck, projects, cowork, doctor, AAAK
mempal-mcp-serverPublic MCP server adapter and tool wiring for the runtime

Key design choices:

  • model2vec-rs default embedder — zero native deps, multilingual (BGE-M3 distilled)

  • ort (ONNX) available behind onnx feature flag for max quality

  • FTS5 for BM25 keyword search — synced via SQLite triggers

  • Soft-delete with audit trail — mempal delete + mempal purge

  • Importance ranking — drawers have 0-5 importance, wake-up sorts by importance

  • Semantic dedup — ingest warns (doesn't block) when similar content exists

  • Public workspace crates — reusable libraries are maintained in this repo and published as versioned crates while cargo install mempal remains the CLI path. P114 keeps the split coarse: storage, runtime, and MCP server are separate crates, but feature families such as knowledge, cowork, and context remain in mempal-runtime.

Development

cargo test --workspace
cargo test --workspace --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo fmt --all --check

After changing the embedding model or dimensions, re-embed existing drawers:

mempal reindex

Docs

Book: MemPalace — Reforging Memory in Rust

mempal 的设计分析和完整技术叙事,收录在《MemPalace: AI 记忆的第一性原理》Part 10(第 26-30 章):

章节内容
第 26 章为什么用 Rust 重铸 — 触发点、重写判断、语言选择
第 27 章保留了什么、改变了什么 — 5 维度对比 + 架构图
第 28 章自描述协议 — MEMORY_PROTOCOL、7 条规则、agent 生命周期
第 29 章多 Agent 协作 — Claude↔Codex 接力、反模式发现、agent 日记
第 30 章诚实的差距 — benchmark 数据、6 个 gap

README_zh.md

mempal

Image: Crates.io Image: 下载量 Image: docs.rs Image: CI Image: Release Image: License: MIT

Coding agent 的项目记忆工具。单二进制,cargo install mempal,10 秒内带出处找回历史决策。

最新版本:v0.9.1(2026-08-19)。

做什么

Agent 写代码 → 提交 → mempal 保存决策上下文
下一个 session(任何 agent)→ mempal search → 带出处找回决策
  • 混合检索:BM25 关键词匹配 + 向量语义搜索,通过 RRF(Reciprocal Rank Fusion)融合

  • 知识图谱:subject-predicate-object 三元组,支持时态验证(valid_from/valid_to)

  • 跨项目隧道:自动发现多个 Wing 中同名 Room 的链接

  • 自描述协议:MEMORY_PROTOCOL 嵌入 MCP ServerInfo,任何 agent 连接后自动学会使用方式——无需系统提示配置

  • 多语言:model2vec-rs(BGE-M3 蒸馏)作为默认嵌入器,零原生依赖

  • 单文件:所有数据在 ~/.mempal/palace.db(SQLite + sqlite-vec)

快速开始

cargo install mempal --version 0.9.1 --locked

mempal init ~/code/myapp
mempal ingest ~/code/myapp --wing myapp
mempal search "auth decision clerk"
mempal wake-up

启用 REST 支持:

cargo install mempal --version 0.9.1 --locked --features rest

从源码 checkout 安装:

cargo install --path . --locked

配置

配置文件 ~/.mempal/config.toml(可选,不存在时使用默认值):

db_path = "~/.mempal/palace.db"

[embed]
backend = "model2vec"                          # 默认,零原生依赖
# model = "minishlab/potion-multilingual-128M" # 默认多语言模型

其他后端:

# 本地 ONNX(需要 --features onnx)
[embed]
backend = "onnx"

# 外部 API
[embed]
backend = "api"
api_endpoint = "http://localhost:11434/api/embeddings"
api_model = "nomic-embed-text"
dimensions = 768  # 可选;省略时默认 384

命令一览

命令用途
mempal init <DIR> [--dry-run]从项目目录推断 wing/room
mempal ingest <DIR> --wing <W> [--dry-run]分块、嵌入、存储
mempal search <QUERY> [--wing W] [--room R] [--json]混合检索(BM25 + 向量 + RRF)
mempal wake-up [--format aaak]上下文刷新,按重要性排序
mempal compress <TEXT>AAAK 格式输出
mempal delete <DRAWER_ID>软删除
mempal purge [--before TIMESTAMP]永久清除已软删除的记忆
mempal kg add <S> <P> <O>添加知识图谱三元组
mempal kg query [--subject S] [--predicate P]查询三元组
mempal kg timeline <ENTITY>实体的时间线视图
mempal kg stats知识图谱统计
mempal tunnels跨 Wing room 链接
mempal taxonomy list / edit管理路由关键词
mempal reindex切换模型后重新嵌入所有 drawer
mempal status数据库统计、schema 版本、scope 分布
mempal serve [--mcp]MCP 服务器(+ REST)
mempal cowork-install-hooks [--global-codex]一键安装 Claude Code + Codex 的 UserPromptSubmit hook
mempal cowork-drain --target <claude|codex>排空 inbox(供 hook 调用,任意错误均 exit 0)
mempal cowork-status --cwd <PATH>只读查看双方 inbox 当前状态
mempal fact-check [PATH|-] [--wing W] [--room R] [--now <UNIX_SECS>]离线矛盾检查(对照 KG 三元组 + 已知 entity)
mempal bench longmemeval <FILE>LongMemEval 检索 benchmark
项目 ignore 规则

mempal init <DIR> 和目录模式的 mempal ingest <DIR> 默认复用目标项目自己的 ignore 规则。它们会尊重 .gitignore、.git/info/exclude、全局 Git exclude, 以及项目根目录的 .mempalignore。只想从项目记忆中排除的编译产物、缓存目录或 生成文件,可以写进 .mempalignore,不需要改变项目本身的 Git 行为。

单次运行可以用 --ignore-file <PATH> 追加一个或多个 ignore 文件。需要关闭默认 来源时,用 --no-gitignore 或 --no-mempalignore。显式文件导入保持显式: mempal ingest path/to/file --wing <W> 即使在目录遍历时会被 ignore 规则跳过, 仍然会导入这个文件。

MCP 服务器(10 个工具)

mempal serve --mcp 通过 Model Context Protocol 暴露:

工具用途
mempal_status状态 + 协议 + AAAK spec(首次调用即教会 agent)
mempal_search混合检索 + tunnel 提示 + 引用 + P7 的 AAAK 结构化 signals
mempal_ingest存记忆(可选 importance 0-5 + dry_run);并发写入时返回 lock_wait_ms
mempal_delete软删除 + 审计
mempal_taxonomy路由关键词管理
mempal_kg知识图谱:add/query/invalidate/timeline/stats
mempal_tunnels跨 Wing room 发现
mempal_peek_partner读 partner agent 当前 session(Claude ↔ Codex),纯只读
mempal_session_peek按明确 tool + cwd 读取本地 Claude/Codex session,支持同工具跨项目读取
mempal_cowork_push向 partner agent inbox 投递短消息(at-next-submit 交付)
mempal_fact_check离线矛盾检测(相似名 / 关系对立 / 时态失效,纯本地无 LLM)

服务器在 MCP initialize.instructions 中嵌入 MEMORY_PROTOCOL(11 条行为规则),任何 MCP 客户端自动接收。

记忆协议

mempal 通过自描述教 agent 这些规则:

  1. 首次设置 — 调用 mempal_status 发现 wing 名称

  2. 唤醒 — 不同客户端有不同的预加载机制

  3. 断言前验证 — 陈述项目事实前先搜索

  4. 不确定时查询 — "我们为什么..."、"上次我们..." 3a. 翻译为英文 — 非英文查询先翻译再搜索

  5. 决策后保存 — 保存理由,不仅是结果

  6. 引用一切 — 引用 drawer_id 和 source_file 5a. 记日记 — session 结束时在 wing="agent-diary" 下记行为观察

  7. Partner 感知 — 问 partner 当前状态用 mempal_peek_partner(live session),明确同工具/跨项目本地 session 用 mempal_session_peek,问已沉淀决策才用 mempal_search

  8. 决策沉淀 — mempal_ingest 只存已达成的硬决策;partner 参与时要把 partner 的关键贡献带进 drawer 正文

  9. COWORK PUSH — mempal_cowork_push 是 SEND 原语,at-next-submit 交付、非实时;别用它做该 ingest 的事

  10. 入库前校验 — 在 ingest 含 entity 关系断言的决策前调 mempal_fact_check,它抓相似名拼错、KG 关系矛盾、以及 valid_to 已过期的 stale fact

并发 Ingest 安全(P9-B)

两个 agent 同时向同一个 source 写入以前是 TOCTOU race:两边都通过 dedup 检查、都 insert,结果重复 drawer 或 vector 错配。从 0.4.0 起 mempal_ingest 和 ingest_file_with_options 在进入 dedup + insert 临界区前获取 per-source 建议锁。

  • 锁文件 ~/.mempal/locks/<16-hex>.lock,懒建,guard drop 时 OS 自动释放

  • 默认 5s 超时,50ms 重试 + jitter;超时返回 LockError::Timeout

  • 非 dry-run 的 ingest response 携带 lock_wait_ms: Option<u64>,agent 可据此察觉并发

  • dry-run 不占锁(零写入,零 race)

  • 0.4.0 仅覆盖 Unix(flock 内联 extern,不引 libc crate);Windows 暂为 no-op 占位,后续用 LockFileEx 补齐

离线事实核查(P9-A)

mempal_fact_check(以及 CLI mempal fact-check)对一段文本在现有 KG triples + 最近 drawer 聚合的 entity registry 上做比对,标记三类确定性问题(不调 LLM、不走网络):

问题类型触发条件
SimilarNameConflict文本中的名字与已知 entity Levenshtein 距离 ≤ 2 且不相等
RelationContradiction文本断言的 predicate 与 KG 中同 (subject, object) 的现存 triple 在不兼容字典中
StaleFact文本断言的三元组在 KG 中 valid_to < now(Unix 秒)

文本 → 三元组当前支持三种窄模式:"X is Y's ROLE"、"X works at / for Y"、"X is [the|a|an] ROLE of Y"。不认得的句型静默返回空,倾向少报不多报。协议 Rule 11 指导 agent 在 ingest 含实体关系断言的决策前跑一次。完整契约见 specs/p9-fact-checker.spec.md。

检索架构

query → BM25 (FTS5)         → 关键词排序
      → Vector (sqlite-vec) → 语义相似度排序
      → RRF 融合 (k=60)     → 合并排序
      → Wing/Room 过滤      → 范围限定
      → Tunnel 提示         → 跨项目引用

知识图谱

mempal kg add "Kai" "recommends" "Clerk"
mempal kg add "Clerk" "replaced" "Auth0" --source-drawer drawer_xxx
mempal kg timeline "Kai"
mempal kg stats

三元组支持时态验证——关系过期后可标记为无效。

Agent 日记

跨 session 行为学习——agent 记录观察、教训和模式:

# 搜索日记
mempal search "lesson" --wing agent-diary
mempal search "pattern" --wing agent-diary --room claude

日记通过现有的 mempal_ingest 工具写入,wing="agent-diary",room=agent 名字。MEMORY_PROTOCOL Rule 5a 教 agent 在 session 结束时写日记。可与 Claude Code 的 auto-dream 集成,实现自动记忆整理。

导入格式(5 种)

格式自动检测方式
Claude Code JSONLtype + message 字段
ChatGPT JSON数组或 mapping 树
Codex CLI JSONLsession_meta + event_msg 条目
Slack DM JSONtype: "message" + user + text
纯文本兜底

AAAK 压缩

输出格式化器,任何 LLM 无需解码即可阅读:

mempal compress "Kai recommended Clerk over Auth0 based on pricing and DX"
# V1|manual|compress|1744156800|cli
# 0:KAI+CLK+AUT|kai_clerk_auth0|"Kai recommended Clerk over Auth0..."|★★★★|determ|DECISION

中文文本使用 jieba-rs 词性标注进行分词。

架构

Crate职责
mempal可安装 CLI package、REST 入口、legacy facade paths
mempal-embed公共 Embedder / EmbedderFactory trait、API embedder、model2vec 与 ONNX 实现
mempal-search-core公共 FTS5 query escaping 与 RRF rank-fusion 基础能力
mempal-agent-memory公共 agent-memory 领域类型与 anchor helper
mempal-mcp-protocol公共自描述 MEMORY_PROTOCOL 文本
mempal-store-sqlite公共 SQLite 存储层:schema、migration、Database、FTS5、sqlite-vec、KG、tunnels、cards、adoption tables
mempal-runtime公共 runtime workflows:ingest、search orchestration、context、brief、knowledge、factcheck、projects、cowork、doctor、AAAK
mempal-mcp-server公共 MCP server adapter 与工具 wiring

关键设计:

  • model2vec-rs 默认嵌入——零原生依赖,多语言(BGE-M3 蒸馏)

  • ort (ONNX) 通过 onnx feature flag 可选启用

  • FTS5 BM25 关键词搜索——通过 SQLite 触发器同步

  • 软删除 + 审计日志——mempal delete + mempal purge

  • 重要性排序——drawer 有 0-5 重要性评分,wake-up 按重要性排序

  • 语义去重——ingest 时检测相似内容,warning 但不阻塞

  • 公共 workspace crates——可复用库在同一 repo/workspace 内维护并以 versioned crates 发布, cargo install mempal 继续作为 CLI 安装路径。P114 保持粗粒度拆分:storage、 runtime、MCP server 独立成 crate,但 knowledge、cowork、context 等功能族仍留在 mempal-runtime,不继续碎拆。

开发

cargo test --workspace
cargo test --workspace --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo fmt --all --check

切换嵌入模型后重建向量:

mempal reindex

文档

453 files · 436 not served here

Advantages

  • Hybrid search combines BM25 and vector semantic search for improved retrieval. evidence: README.md
  • Self-describing protocol allows agents to learn interaction rules automatically. evidence: README.md
  • Per-source advisory locking prevents race conditions during concurrent agent ingestion. evidence: README.md

Limitations

Security

Risk level: Low risk

This brain runs

Hooks (2)

  • .claude/settings.json (PostToolUse): if echo "$TOOL_INPUT" | grep -q 'git commit'; then echo 'MEMPAL REMINDER: You just committed code. Call mempal_ingest to save the decision context (what was built, why, what was considered). Rule 4: SAVE AFTER DECISIONS.'; fi
  • .claude/settings.json (UserPromptSubmit): bash .claude/hooks/user-prompt-submit.sh

MCP servers (1)

  • .mcp.json (mempal): mempal serve --mcp

Agent instructions that run or fetch something (22)

  • AGENTS.md: Rust 实现的 coding agent 项目记忆工具。单二进制,`cargo install mempal`,10 秒内带出处找回历史决策。
  • AGENTS.md: | Spec | 状态 | 范围 | |------|------|------| | `specs/p0-core-scaffold.spec.md` | 完成 | workspace 骨架 + SQLite schema | | `specs/p0-embed-trait.spec.md` | 完成 | Embedder trait(model2vec 默认 + ort 可选) | | `specs/p0-ingest.spec.md` | 完成 | 导入管道(格式检测/归一化/分块/存储) | | `specs/p0-search-cli.spec.md` …[+7715 chars]
  • AGENTS.md: `docs/plans/2026-05-26-p98-release-install-doctor.md` — P98 release install doctor(已完成)
  • AGENTS.md: `docs/plans/2026-05-26-p100-guided-maintenance-run.md` — P100 guided maintenance run(已完成)
  • AGENTS.md: `docs/plans/2026-08-18-p117-reindex-atomic-replace.md` — P117 atomic reindex replace + dry-run feasibility report(已完成)
  • AGENTS.md: | 工具 | 作用 | |------|------| | `mempal_status` | 状态 + 协议 + AAAK spec | | `mempal_doctor` | release/install + MCP runtime diagnostics:报告 binary/PATH/schema 兼容性和 required MCP tool/action 能力清单(P99) | | `mempal_search` | 混合检索(BM25 + 向量 + RRF + tunnel hints)+ AAAK 结构化 signals(P7) | | `mempa …[+2688 chars]
  • AGENTS.md: Cargo workspace,root package 仍是 `mempal`,并继续提供 `cargo install mempal` 的 CLI binary。P113/P114 已把可复用边界拆成公开 workspace crates;root crate 现在主要负责 CLI、REST entrypoint、package metadata 和 legacy facade paths。
  • AGENTS.md: **`mempal cowork-install-hooks` 写两件 Claude 侧制品**:`.claude/hooks/user-prompt-submit.sh`(脚本)+ `.claude/settings.json` 下的 `hooks.UserPromptSubmit` 条目(注册)。Claude Code 不按文件名约定自动发现脚本,两件**都必须有**hook 才会 fire。`install-hooks` 已自动处理 + 自愈 stale 条目;请勿手工移除其中任一。
  • AGENTS.md: **Codex 侧依赖 `codex_hooks` feature flag**:shipped `codex-cli ≤ 0.120.0` 该 flag 处于 "under development" 且默认 `false`,此时 Codex runtime 完全忽略 `~/.codex/hooks.json`。`install-hooks` 检测到会打印 warning + 激活命令 `codex features enable codex_hooks`。
  • AGENTS.md: **Codex TUI 进程启动时一次性缓存 config**:改完 `config.toml` 或 `hooks.json`(含 feature flag / install-hooks)后,必须完全退出并重启 Codex TUI;已在跑的进程拿不到新配置。
  • AGENTS.md: **Claude Code 的 MCP server 是 session startup spawn**:`cargo install` 升级 mempal binary 后,Claude Code 还在用旧 MCP server 进程,**不认识新加的工具**(如 `mempal_cowork_push`)。升级后重启 Claude Code,MCP server 会 respawn 到新 binary。
  • CLAUDE.md: Rust 实现的 coding agent 项目记忆工具。单二进制,`cargo install mempal`,10 秒内带出处找回历史决策。
  • CLAUDE.md: | Spec | 状态 | 范围 | |------|------|------| | `specs/p0-core-scaffold.spec.md` | 完成 | workspace 骨架 + SQLite schema | | `specs/p0-embed-trait.spec.md` | 完成 | Embedder trait(model2vec 默认 + ort 可选) | | `specs/p0-ingest.spec.md` | 完成 | 导入管道(格式检测/归一化/分块/存储) | | `specs/p0-search-cli.spec.md` …[+7715 chars]
  • CLAUDE.md: `docs/plans/2026-05-26-p98-release-install-doctor.md` — P98 release install doctor(已完成)
  • CLAUDE.md: `docs/plans/2026-05-26-p100-guided-maintenance-run.md` — P100 guided maintenance run(已完成)
  • CLAUDE.md: `docs/plans/2026-08-18-p117-reindex-atomic-replace.md` — P117 atomic reindex replace + dry-run feasibility report(已完成)
  • CLAUDE.md: | 工具 | 作用 | |------|------| | `mempal_status` | 状态 + 协议 + AAAK spec | | `mempal_doctor` | release/install + MCP runtime diagnostics:报告 binary/PATH/schema 兼容性和 required MCP tool/action 能力清单(P99) | | `mempal_search` | 混合检索(BM25 + 向量 + RRF + tunnel hints)+ AAAK 结构化 signals(P7) | | `mempa …[+2688 chars]
  • CLAUDE.md: Cargo workspace,root package 仍是 `mempal`,并继续提供 `cargo install mempal` 的 CLI binary。P113/P114 已把可复用边界拆成公开 workspace crates;root crate 现在主要负责 CLI、REST entrypoint、package metadata 和 legacy facade paths。
  • CLAUDE.md: **`mempal cowork-install-hooks` 写两件 Claude 侧制品**:`.claude/hooks/user-prompt-submit.sh`(脚本)+ `.claude/settings.json` 下的 `hooks.UserPromptSubmit` 条目(注册)。Claude Code 不按文件名约定自动发现脚本,两件**都必须有**hook 才会 fire。`install-hooks` 已自动处理 + 自愈 stale 条目;请勿手工移除其中任一。
  • CLAUDE.md: **Codex 侧依赖 `codex_hooks` feature flag**:shipped `codex-cli ≤ 0.120.0` 该 flag 处于 "under development" 且默认 `false`,此时 Codex runtime 完全忽略 `~/.codex/hooks.json`。`install-hooks` 检测到会打印 warning + 激活命令 `codex features enable codex_hooks`。
  • CLAUDE.md: **Codex TUI 进程启动时一次性缓存 config**:改完 `config.toml` 或 `hooks.json`(含 feature flag / install-hooks)后,必须完全退出并重启 Codex TUI;已在跑的进程拿不到新配置。
  • CLAUDE.md: **Claude Code 的 MCP server 是 session startup spawn**:`cargo install` 升级 mempal binary 后,Claude Code 还在用旧 MCP server 进程,**不认识新加的工具**(如 `mempal_cowork_push`)。升级后重启 Claude Code,MCP server 会 respawn 到新 binary。
  • Low risk: scripts-present (.claude/hooks/user-prompt-submit.sh)

Attribution and licence

First committed by
GitHub avatar of ZhangHanDongZhangHanDong
Publisher
Alex (Community)
Source
ZhangHanDong/mempal · commit 9ed705d
Licence
MIT License (files served here)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Contributors
ZhangHanDong, LiuZiqi-dual, TigerInYourDream, jolestar, ryushione

AutoGineer is not affiliated with or endorsed by ZhangHanDong.

Install from source

436 of its files are not served here, so there is no ZIP. ZhangHanDong/mempal at 9ed705d