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

docs/MIND-MODEL-IMPLEMENTATION-ARTICLE.md

From Memory Tool to Governed Mind Model

This article explains the design decisions and implemented surfaces behind mempal's mind-model work from the initial dao/shu/qi discussion through the completed P54-P59 Phase-3 runtime baseline.

1. The Problem: Memory Is Not Just Recall

Most agent memory systems start from a simple premise: if the agent has seen something before, store it, retrieve it later, and put it back into context. That premise is useful, but it is not enough for a long-running coding agent.

A coding agent does not merely need old text. It needs to know which old text is evidence, which part is a stable conclusion, which part is a workflow, which part is a tool-specific command, and which part has already been contradicted. If all memories are stored as the same kind of item, the system eventually loses the difference between observation and law.

The mind-model work in mempal starts from that failure mode.

The thesis is:

Memory should be a governed knowledge evolution layer. Raw evidence is recorded first, candidate knowledge is distilled second, and trusted runtime guidance is promoted only through explicit gates.

That is why this work is not "RAG plus skills." RAG retrieves old material. Skills encode procedures. The mind model tries to govern how evidence becomes knowledge, how knowledge affects skills, and how runtime behavior feeds back into future evolution.

The current implementation has reached a concrete baseline:

  • Stage 1 typed drawers separate evidence from knowledge.

  • Runtime context assembles dao_tian -> dao_ren -> shu -> qi.

  • Knowledge lifecycle supports distill, gate, promote, demote, and outward anchor publication.

  • Phase 2 knowledge cards separate governed beliefs from raw evidence drawers.

  • Card retrieval and card-aware context exist, but remain opt-in.

  • Phase 3 runtime adoption evidence now exists as schema v9 and CLI gates.

The next stage should therefore not reopen the baseline. It should test whether the baseline improves real agent behavior.

2. Dao, Shu, Qi: A Knowledge Axis, Not a Storage Folder

The original conceptual split is dao / shu / qi.

In mempal, the split means:

  • dao: governing principles and high-level knowledge.

  • shu: reusable methods, workflows, and procedures.

  • qi: concrete tools, interfaces, commands, and tool-specific usage.

dao is further split:

  • dao_tian: cross-domain high-level principles, minimal and extremely stable.

  • dao_ren: domain-specific laws, still stable but with clear field boundaries.

This matters because a coding agent uses different kinds of knowledge differently.

A dao_tian item should shape judgment. It is the type of knowledge that says "evidence precedes assertion" or "promotion without demotion causes knowledge pollution." It should not be numerous, and it should not change often.

A dao_ren item should shape domain reasoning. For a Rust project, this may be a stable rule about schema migration boundaries, citation semantics, or agent runtime behavior.

A shu item should shape action. It can bias workflow and skill choice. For example, before implementing a feature, inspect the existing spec, write a minimal contract, and verify with deterministic tools.

A qi item should bind execution. It may say which CLI command exists, which MCP tool accepts which fields, or which feature flag controls a runtime path.

The key design decision is that dao / shu / qi is not the same thing as project memory, agent memory, or skill memory. Those are different axes.

The orthogonal coordinates are:

  • domain: who the memory is for, such as project, agent, skill, or global.

  • tier: what kind of knowledge it is, such as dao_ren, shu, or qi.

  • field: which subject area it belongs to.

  • provenance: where it came from, such as runtime, research, or human.

  • anchor: which persistence scope it belongs to, such as global, repo, or worktree.

This prevents several common errors:

  • A local project workaround should not become universal law.

  • A temporary tool behavior should not become a stable domain principle.

  • A workflow tip should not be confused with a governing rule.

  • A research summary should not directly create dao.

The design therefore treats dao as memory-level high-order knowledge. External tools may produce evidence, but memory owns promotion.

3. Evidence and Knowledge Must Be Different Objects

The central implementation split is between evidence memory and knowledge memory.

Evidence memory stores what was observed:

  • raw research output

  • runtime observations

  • human teachings

  • concrete failures

  • contradictions

  • counterexamples

Evidence can be inconsistent. That is expected. The world is messy, and the agent should be allowed to record competing observations without prematurely resolving them.

Knowledge memory stores what the system currently believes:

  • a tool note

  • a workflow method

  • a domain pattern

  • a governing principle

Knowledge is lower-volume, auditable, and stateful. It has a status. It can be candidate, promoted, canonical, demoted, or retired.

This split answers a basic question: what counts as learning?

Learning is not "we stored more text." Learning happens when observations accumulate, patterns are distilled, useful candidates are promoted, and false or obsolete beliefs can be demoted.

The resulting lifecycle is:

  1. record: store raw evidence.

  2. distill: create candidate knowledge from evidence.

  3. promote: move knowledge into trusted runtime use.

  4. demote: weaken or retire knowledge when contradicted.

This is intentionally asymmetric. Evidence should grow quickly. Law should grow slowly.

The project has already implemented this in two forms:

  • Stage 1 uses typed drawers as a bootstrap model.

  • Phase 2 introduces dedicated knowledge card tables.

That progression matters. It allowed mempal to validate the model without rewriting the entire storage system first, then move toward a cleaner knowledge object once the governance shape became stable.

4. Stage 1: Typed Drawers as the Bootstrap Architecture

Before the mind-model work, a drawer was essentially the durable memory unit. Stage 1 did not replace that system. It made the drawer model typed.

The core distinction became:

  • evidence drawer

  • knowledge drawer

Both share base drawer fields, but they carry different metadata and different runtime meaning.

An evidence drawer records source-backed material. It includes fields such as memory_kind=evidence, domain, field, provenance, anchor_kind, and anchor_id. It does not carry tier, status, statement, or lifecycle refs.

A knowledge drawer records a distilled belief. It includes memory_kind=knowledge, statement, tier, status, role-separated evidence refs, scope constraints, trigger hints, and anchor metadata.

The statement field is important. It is the short wake-up proposition. The longer content field explains rationale, examples, and boundaries. Runtime context should be able to wake a concise claim without dumping the entire explanation every time.

Stage 1 also introduced role-separated refs:

  • supporting_refs

  • verification_refs

  • counterexample_refs

  • teaching_refs

This is not just cleaner metadata. It is what lets promotion gates understand why a claim is believed. A supporting reference and a counterexample reference should not be collapsed into the same anonymous evidence list.

The minimum lifecycle surfaces were then added:

  • mempal knowledge distill

  • mempal knowledge gate

  • mempal knowledge promote

  • mempal knowledge demote

  • mempal knowledge publish-anchor

And equivalent MCP surfaces were added where runtime agents needed direct access:

  • mempal_knowledge_distill

  • mempal_knowledge_gate

  • mempal_knowledge_promote

  • mempal_knowledge_demote

  • mempal_knowledge_publish_anchor

The important constraint is that these operations do not let the caller simply declare confidence. Promotion depends on deterministic policy. For example, Stage 1 policy requires evidence counts, verification refs, and, for dao_tian, human review.

This is how the system avoids the dangerous shortcut:

"The agent found an interesting pattern, therefore the system learned a law."

That shortcut is explicitly forbidden.

5. Anchors: Worktree, Repo, Global

The mind model also needed to solve project identity.

The early temptation is to use wing as the project identity. That fails because wing is semantic. It answers which area the memory belongs to, not which checkout produced it.

The implemented anchor model separates:

  • global

  • repo

  • worktree

This distinction is necessary for coding work.

A repo-only anchor is too broad. Branch experiments contaminate each other. A failed experiment in one worktree can pollute reasoning in another.

A worktree-only anchor is too narrow. Stable project knowledge fragments across checkouts, and every new worktree starts too empty.

The design therefore uses a dual-scope model:

  • write local observations at worktree

  • publish verified project knowledge outward to repo

  • publish only cross-project principles to global

This creates two separate promotion movements:

  • tier promotion, such as qi -> shu or shu -> dao_ren

  • anchor publication, such as worktree -> repo -> global

Those operations are intentionally not the same. A workflow may be trusted inside one worktree but not yet shareable across the repo. A repo-level pattern may be stable for mempal but not universal enough to become global dao_tian.

At runtime, context assembly prefers:

  1. current worktree

  2. current repo

  3. global

This ordering gives the agent branch-local context first, stable project memory second, and universal law last. The tier order still applies inside that anchor logic.

6. Runtime Context: Wake-Up Is Not Context Assembly

A major boundary in the implementation is the separation between wake-up and mind-model context.

Wake-up remains an L0/L1 memory refresh surface. It can bring old material back into attention, but it does not assemble typed operating guidance.

The typed operating guidance belongs to:

  • mempal context

  • mempal_context

Those surfaces assemble context in this order:

  1. dao_tian

  2. dao_ren

  3. shu

  4. qi

  5. optional evidence

The order is deliberate.

dao_tian calibrates worldview. dao_ren calibrates the current field. shu biases workflow and skill selection. qi binds concrete tools. Evidence grounds exceptions and proofs.

The implementation keeps dao_tian sparse by default. mempal context and mempal_context inject at most one dao_tian item unless the caller explicitly raises the budget. This avoids drowning practical execution under abstract principles.

The runtime skill guidance is also intentionally non-authoritative. trigger_hints may bias workflow and tool choice, but they do not execute skills and do not override system, user, repository, or client-native skill rules.

This boundary is one of the most important practical decisions. If memory hints could directly trigger tools or override explicit instructions, the system would become an ungoverned policy engine. Instead, memory provides guidance, and the agent still operates under the normal instruction hierarchy.

7. Phase 2: Knowledge Cards as Governed Beliefs

Typed drawers proved the model, but they are still a bootstrap architecture. Drawers are the right shape for raw evidence. They are not the final shape for governed beliefs.

Phase 2 introduced dedicated knowledge card storage in the same SQLite palace.db.

The key tables are:

  • knowledge_cards

  • knowledge_evidence_links

  • knowledge_events

This was an explicit storage decision. Cards should not live in an external database by default. mempal's product invariant is a local, single-binary, single-file memory palace. Keeping cards in the same SQLite database preserves transactional lifecycle updates and avoids adding operational complexity before the model proves it needs a separate store.

The separation is clean:

  • drawers remain raw evidence and citation roots

  • cards store distilled beliefs

  • evidence links connect cards to source-backed drawers

  • events record how beliefs evolved

A card contains statement, content, tier, status, domain, field, anchor metadata, trigger hints, and timestamps.

An evidence link connects a card to an evidence drawer by role:

  • supporting

  • verification

  • counterexample

  • teaching

An event records lifecycle history:

  • created

  • promoted

  • demoted

  • retired

  • linked

  • unlinked

  • updated

  • published_anchor

This makes the Phase 2 model more explicit than Stage 1. A drawer can still hold evidence. A card can now hold belief. The event stream can explain why that belief changed.

The implemented surfaces include:

  • mempal knowledge-card create

  • mempal knowledge-card get

  • mempal knowledge-card list

  • mempal knowledge-card link

  • mempal knowledge-card event

  • mempal knowledge-card events

  • mempal knowledge-card backfill-plan

  • mempal knowledge-card backfill-apply

  • mempal knowledge-card gate

  • mempal knowledge-card promote

  • mempal knowledge-card demote

  • mempal knowledge-card retrieve

The MCP tool mempal_knowledge_cards exposes read and lifecycle actions, including retrieval.

The important boundary is that Phase 2 cards are governed objects, but they are not default runtime sources. They can be retrieved. They can be injected into context with --include-cards or include_cards=true. But ordinary mempal_search remains drawer-based, and default context remains drawer-only.

This is not an implementation gap. It is a trust boundary.

Default runtime context is a high-trust path. Switching from drawer-backed knowledge to card-backed guidance should require runtime evidence that the change improves behavior without damaging citations, lifecycle semantics, or context budget.

8. Research and Evaluators: Evidence Producers, Not Authority

The design also fixes the role of external research and evaluator systems.

research-rs is an external tool. It is qi, not dao.

Its job is to gather and organize external material:

  • raw sources

  • wiki pages

  • schema

  • index

  • logs

  • lint reports

Its output can become evidence. It can produce structured summaries, candidate insights, and contradiction signals. But it must not directly create dao_tian, promoted knowledge, or canonical knowledge.

That boundary is now part of the implemented policy:

  • research output enters as evidence

  • candidate knowledge must be distilled from evidence refs

  • promotion remains controlled by lifecycle gates

  • contradictions become counterexamples or demotion evidence

Evaluators have a similar boundary.

An evaluator may recommend promotion or demotion. It may propose supporting refs, verification refs, counterexample refs, and risk notes. It may explain why a knowledge item appears ready or unsafe.

But it must not mutate lifecycle state directly.

Evaluator output is advisory-only. It cannot satisfy human reviewer requirements. It cannot bypass deterministic gates. It cannot canonicalize dao_tian.

This is the difference between assistance and authority. The system can use evaluator advice, but it does not let the evaluator become the lifecycle actor.

9. Phase 3 So Far: Runtime Evidence Before Runtime Power

After P51, the baseline was closed. P52 defined Phase 3 as a new stage, not a continuation of unfinished P12-P50 work. P53 audited candidate tracks and found that no candidate should jump directly into default behavior changes.

The recommended first Phase 3 track was runtime adoption evidence.

That recommendation has now been implemented through P54-P59.

P54 adds schema v9 table runtime_adoption_events. This table records concrete runtime signals:

  • which track the signal belongs to

  • which signal occurred

  • which feature was involved

  • optional query, context hash, card id, evaluator id, research report id

  • note, metadata, timestamp

The supported tracks include runtime adoption, card context, card embedding, evaluator, and research adapter work. The supported signals include used, accepted, rejected, miss, rollback, contradiction, and neutral.

P55 exposes the table through CLI:

  • mempal phase3 adoption record

  • mempal phase3 adoption list

  • mempal phase3 adoption stats

P56 adds a read-only gate for making card context default. The current policy is still opt-in. The gate merely reports whether enough accepted card_context evidence exists and whether rollback signals are absent.

P57 adds a read-only card embedding gate. It intentionally adds no card vector schema. Card embeddings require repeated measured misses showing that linked-evidence retrieval failed because the card statement itself needed to be retrieved.

P58 adds a read-only evaluator API gate. It preserves the advisory-only boundary. Evaluator signals do not mutate lifecycle state or bypass gates.

P59 adds mempal phase3 research-validate-plan. This validates an external research report contract with report_id, title, sources, findings, and optional candidate_insights. It validates and plans; it does not ingest promoted or canonical knowledge.

The pattern is consistent:

Before adding runtime power, collect runtime evidence.

That is the Phase 3 goal.

10. What Has Actually Been Built

The implemented system can now be summarized as a governed cognition stack.

Storage and retrieval:

  • SQLite palace.db is the single local storage root.

  • Drawers remain raw memory and evidence citation roots.

  • BM25 plus vector retrieval remains the base search path.

  • AAAK remains an output formatter, not a storage dependency.

Stage 1 mind model:

  • evidence and knowledge drawers are typed

  • statement is used for knowledge wake-up

  • dao_tian, dao_ren, shu, and qi have explicit status rules

  • anchors separate worktree, repo, and global scope

  • lifecycle operations are explicit and evidence-backed

Runtime context:

  • mempal context and mempal_context assemble typed guidance

  • context order is dao_tian -> dao_ren -> shu -> qi

  • evidence is opt-in

  • card context is opt-in

  • memory hints bias skill/tool choice but do not execute

Phase 2 cards:

  • knowledge_cards store governed beliefs

  • knowledge_evidence_links preserve role-separated citations

  • knowledge_events provide append-only lifecycle audit

  • cards can be backfilled from Stage 1 knowledge

  • cards can be gated, promoted, demoted, and retrieved

  • default search does not return cards

Policy boundaries:

  • research output cannot directly create dao

  • evaluator output is advisory-only

  • dao_tian canonicalization requires human review

  • card embeddings are deferred until evidence justifies them

  • default card context is deferred until runtime evidence justifies it

Phase 3 baseline:

  • runtime adoption events are stored in schema v9

  • adoption evidence is inspectable through CLI

  • readiness gates exist for card context default, card embeddings, evaluator APIs, and research adapter ingestion

  • research report validation exists without automatic promotion

This is enough to enter a new phase because the system is no longer just a design. It has implemented storage, lifecycle, runtime context, MCP surfaces, card governance, and measurement gates.

11. What Is Still Deliberately Not Done

Several things remain intentionally unfinished.

Card-aware context is not default. It remains opt-in because default runtime context is a trust boundary. The system needs repeated runtime traces showing benefit before enabling cards by default.

Card embeddings do not exist. Current card retrieval is linked-evidence-first. This preserves citation semantics and avoids stale card-vector maintenance. Card embeddings require measured statement-match misses and a rollback plan.

Research adapters do not directly ingest promoted knowledge. They can validate input plans and eventually write evidence or candidate insights, but promotion must stay under memory lifecycle governance.

Evaluator APIs do not mutate knowledge state. They can advise, but gates and human-review requirements remain authoritative.

The system also does not claim fully autonomous self-improvement yet. What it has is a governed substrate for self-improvement:

  • evidence capture

  • candidate distillation

  • gate evaluation

  • reversible lifecycle

  • runtime adoption measurement

Autonomy should be added only where evidence shows it improves behavior and where rollback is explicit.

12. The Design Principle Going Forward

The next phase should be judged by one question:

Does this change produce measurable runtime improvement without weakening evidence, citation, audit, or rollback boundaries?

If the answer is no, the change should remain advisory, opt-in, or deferred.

That is why the next likely work should expose Phase 3 runtime surfaces to MCP and define an adoption-recording protocol. Agents need a direct way to record whether a context item, card, evaluator suggestion, or research result was used, accepted, rejected, missed, or rolled back.

Only after that evidence accumulates should the system consider stronger defaults:

  • card context default-on

  • card embeddings

  • evaluator APIs

  • research adapter apply paths

The mind model therefore advances in a disciplined order:

  1. define the knowledge hierarchy

  2. separate evidence from knowledge

  3. implement lifecycle governance

  4. expose runtime context

  5. extract governed cards

  6. preserve citations and audit

  7. measure runtime adoption

  8. only then increase authority

That ordering is the main achievement of the current implementation.

It turns memory from passive recall into a governed learning loop.

It keeps dao in memory, shu in reusable methods, qi in tools, and evidence as the substrate from which all durable belief must be justified.

And it gives the next stage a clear mission:

Move from implemented cognition architecture to measured, reversible, evidence-driven agent evolution.

Source Notes

This article is based on the repository design and implementation inventory:

  • docs/MIND-MODEL-DESIGN.md

  • AGENTS.md

  • CLAUDE.md

  • specs/p12-mind-model-bootstrap.spec.md

  • specs/p14-context-assembler.spec.md

  • specs/p15-mcp-context.spec.md

  • specs/p17-knowledge-lifecycle.spec.md

  • specs/p18-knowledge-distill.spec.md

  • specs/p20-promotion-gate-policy.spec.md

  • specs/p31-knowledge-card-schema.spec.md

  • specs/p32-knowledge-card-schema-v8.spec.md

  • specs/p38-knowledge-card-gate.spec.md

  • specs/p44-card-context-assembler.spec.md

  • specs/p45-card-linked-evidence-retrieval.spec.md

  • specs/p49-research-ingestion-policy.spec.md

  • specs/p50-evaluator-promotion-policy.spec.md

  • specs/p51-mind-model-closure-audit.spec.md

  • specs/p52-phase-3-intake-roadmap.spec.md

  • specs/p53-phase-3-candidate-evidence-audit.spec.md

  • specs/p54-runtime-adoption-evidence.spec.md

  • specs/p55-runtime-adoption-cli.spec.md

  • specs/p56-card-context-default-gate.spec.md

  • specs/p57-card-embedding-evidence-gate.spec.md

  • specs/p58-evaluator-api-evidence-gate.spec.md

  • specs/p59-research-adapter-ingestion-contract.spec.md

It also cross-checks stored mempal evidence, including:

  • drawer_mempal_p31_cc86ab94, source_file=mempal-p31-knowledge-card-schema-spec.md

  • drawer_mempal_p36_3770af58, source_file=mempal-p36-knowledge-card-backfill-report.md

  • drawer_mempal_p18_b6dac6fe, source_file=mempal-p18-knowledge-distill-memory.md

  • drawer_mempal_p30_7451b74c, source_file=mempal-p30-knowledge-card-storage-boundary.md

  • drawer_mempal_p53_82a98e1f, source_file=mempal-p53-phase-3-candidate-evidence-audit.md

  • drawer_mempal_p54_p59_866027ab, source_file=mempal-p54-p59-phase3-runtime.md

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