1. Executive Summary
Miaomory is a local memory engine with two thin adapters, one for
Codex and one for Claude Code, writing to the same
~/.miaomory store. The hooks record every prompt and reply
in SQLite without calling a model. A detached background process later
sends batches of those messages to the host's own command-line model
(codex exec, claude -p). The model proposes
claims, and each claim is kept only if its quote is found in a
message it cites. Reads are lexical and model-free.
The engine is the evaluation code behind the README's LongMemEval-S
figure, carried over byte for byte. A test fingerprints
core/newmem.py, core/newmem_opt.py, the
prompts and the configuration against a reference copy, and allows only
import lines to differ. What runs in the plugins is what was evaluated.
The 93.4% figure itself is the project's own and is not checked
here.
The part to read is the quote gate and the forget path. Forget follows the supersession chain backwards, hides the source messages and the reply after each, and has a test that looks at every read surface. The weak part is what happens after a correction. A superseded claim leaves the claim corpus, but the message it was booked from does not. Raw messages from both roles stay in recall and search, ranked by term score, and the rule that the newest record wins is a sentence at the bottom of the block for the answering model to apply.
2. Mental Model
Think of a bookkeeper working behind a tape recorder. The tape is the
SQLite messages table: every word the person and the
assistant said, in order, with session, turn and working directory. The
bookkeeper reads unbooked tape in batches and writes ledger entries into
a daily Markdown file. Each entry quotes the tape it came from. A new
entry can point at an older one it replaces; nothing edits the older
one.
Status is never stored. all_claims() works it out on
every read: a claim that some other claim's supersedes
names is superseded, one whose valid_until has passed is
expired, and the rest are active
(src/miaomory/core/newmem.py:294-306). The standing index
card, MEMORY.md, is rewritten in place when a preference changes, with
the old value kept as "原……已作废" ("the old … is void") on the same
line (src/miaomory/core/newmem_opt.py:338,
:561-564).
The tape is also searched. That is why a correction does not fully land: the ledger entry for the old preference stops being returned, while the old words on the tape still are.
Diagram source
%% caption: hooks write the tape without a model; a background model books claims that must quote the tape; status is derived on every read; recall and search read active claims and the raw tape, so a corrected message still surfaces beside its correction; forget hides tape rows and archives claim text into a file nothing reads back
flowchart TD
H[Codex or Claude Code hook] -->|record, no model| M[(SQLite messages<br/>role, session_id, cwd, text, hidden)]
M -->|unbooked batch| B[background: codex exec / claude -p]
B --> Q{quote_ok against<br/>a cited message?}
Q -->|no| X[claim rejected]
Q -->|yes| C[claim block in memory/daily/*.md<br/>kind, quote, sources, supersedes, valid_until]
B -->|revise| MEM[MEMORY.md line rewritten<br/>old value marked void]
C --> D{all_claims on read}
D -->|named by a supersedes| S[superseded: out of the claim corpus]
D -->|valid_until passed| E[expired: kept, labelled]
D -->|otherwise| A[active]
A --> R[recall and memory_search<br/>term-weighted, lexical]
E --> R
M -->|hidden = 0, both roles| R
R --> F[footer: the newest dated record wins]
FG[forget topic] -->|model picks claims| C
FG -->|hide source, similar and next reply| M
FG --> AR[workspace/memory/forget/FORGOTTEN.md<br/>written, never read]3. Architecture
Three layers, each with its own module.
- Engine.
src/miaomory/engine.pyexposesMemoryEngine, the one class a host uses. Its docstring sorts the methods into writes that call no model (record,open_turn,enqueue_remember,enqueue_forget), reads that call no model and change no state (session_context,recall,search,get_file,explain), and background work that calls the model (advance,process_forgets). - Memory logic.
core/newmem.pyandcore/newmem_opt.pyare the evaluation code.host_memory.pysubclassesOptMemoryto read messages from SQLite, keep neighbouring-message views inside one session, and blockworkspace/frommemory_get. - Hosts.
hosts/codex/miaomory_codexandhosts/claude/miaomory_claudeeach carry hooks, an MCP server, a model runner and a spawner for the detached worker. The two read one~/.miaomory/config.json(hosts/claude/miaomory_claude/settings.py:3,:57).
The configuration is fixed. R12A in
src/miaomory/config.py:11-55 is the evaluated flag set,
copied from r12a.json and checked equal by a test; the
config's docstring says these switches are part of the design and not
for users to change. HostOptions holds the host-side knobs:
time zone, early booking, a 120-minute turn timeout, notebook refresh,
and a cap of 300 background model calls a day
(config.py:58-69).
Deployment and ergonomics
Installation is a plugin per host. Both plugins call the person's own
CLI for background work, so the memory costs no separate API key.
Nothing listens on a port. The worker is spawned detached by the hooks
(src/miaomory/oscompat.py:122-128) and works through queued
requests, retrying transient failures at 1, 5, 15 and 60 minutes.
4. Essential Implementation Paths
| Path | Where | What it does |
|---|---|---|
| Record a turn | engine.py:117-122, store.py:102-109 |
Inserts role, text, source (always the default
private), session_id, turn_id,
cwd and a dedupe key |
| Book a batch | newmem_opt.py:446-551 |
Parses the model's JSON; keeps a claim if its quote matches a cited
message; dedups against active claim text and quotes; maps
supersedes; rewrites MEMORY.md |
| Entity facts | newmem_opt.py:528-536 |
Keeps an entity fact only if a cited source is a user message |
| Derive status | newmem.py:294-306 |
superseded, expired or active, on every read |
| Build the corpus | newmem.py:1043-1063,
newmem_opt.py:1070-1099 |
Active claims, note lines, raw message chunks of both roles; expired claims added with a label |
| Per-turn recall | newmem_opt.py:1299-1434 |
IDF-weighted term match, claims then a user-quote channel, trimmed to 1,800 characters, footer on recency |
| On-demand search | newmem_opt.py:1470-1517,
host_memory.py:458-478 |
Same corpus; sorts by score bucket, then date |
| Forget | engine.py:398-492 |
Model-chosen claims, supersedes chain, message hiding, archive, page deletion, dream reset |
| Read one message | host_memory.py:495-505 |
Refuses hidden messages and limits the window to the same session |
5. Memory Data Model
Messages. store.py:18-31 defines
messages with seq, id,
ts, role, source (default
private), session_id, turn_id,
cwd, text, hidden,
booked and dedupe_key. messages()
returns rows with hidden=0 unless asked otherwise
(store.py:125-126). hide() sets
hidden=1, booked=1 by message id (:145-148).
No message is deleted.
Claims. append_verified
(newmem.py:223) writes a block per claim into
memory/daily/YYYY-MM-DD.md: a line
- [kind|salience] text followed by the claim id, the quote,
the source ids, keywords, the speaker, first_seen, and
optionally supersedes and valid_until.
KINDS are fact, preference, event and correction. The block
is the record; nothing outside the file indexes it.
Standing files. MEMORY.md holds Facts, Preferences
and Commitments; the booking prompt allows two new lines per booking,
each dated. USER.md, SOUL.md, AGENTS.md (lessons, capped at 12 by
lessons_cap) and PROACTIVE_PREFERENCES.md are injected at
session start. Entity pages live under people/,
groups/, orgs/ and projects/.
Time. A claim has first_seen, which is
booking time, and may have valid_until, which the model
sets for one-off arrangements. There is no start of validity separate
from first_seen; the recorded searches below show no
valid_from anywhere in src/.
6. Retrieval Mechanics
Both read paths take the same three tiers from
corpus():
- active claims, and expired claims prefixed "(一次性安排,已于 …
到期)" ("one-off arrangement, expired on …") because
keep_expiredis on; - note lines without a claim;
- raw message chunks of every unhidden message, user and assistant
alike (
newmem.py:1058-1062).
Superseded claims are left out of tier 1. sup_events,
which would keep superseded events searchable with a label, is off in
R12A.
Per-turn recall
(newmem_opt.py:1299-1434) weights each query term by
log(1 + n/df) over the whole corpus and marks rare terms
strong. It picks claims, then a user-quote channel: the best-scoring
user messages that are not already the source of a chosen claim. Each
line carries a relative date. When the block passes 1,800 characters,
whole lines with the lowest score are dropped. The block ends with
"同一件事以日期最新的记录为准" ("for the same matter, the record with
the latest date prevails").
memory_search (newmem_opt.py:1470-1517)
scores each item by the share of query grams it contains and sorts on
(round(score / best, 1), date), descending
(:1491). Recency breaks ties only inside one tenth of the
best score. An older message that repeats more of the query's words
ranks above the correction that replaced it. The block ends with the
same instruction.
This is the behaviour the nomination's notebook reports at a later commit: a weekly-update preference corrected in one host, recalled in the other, with the older message first. At the pin, the code does what the notebook shows. The superseded claim is gone; the user message it was booked from is still tier 3, and the ordering is lexical. Whether the answer comes out right depends on the model obeying the footer.
7. Write Mechanics
Capture. The Claude Code hooks call
eng.record on UserPromptSubmit and on Stop
(hosts/claude/miaomory_claude/hooks.py:179,
:211-215), and the Codex hooks do the same
(hosts/codex/miaomory_codex/hooks.py:114,
:142-146). A prompt from a directory the person excluded,
or from the engine's own working directory, is not recorded
(hooks.py:75-79).
Booking. apply_book
(newmem_opt.py:446-551) is the gate. A claim needs text, a
known kind, at least one cited message id present in the batch, and a
quote that quote_ok finds in one of those messages
(newmem.py:94, a normalised subsequence match). A claim or
quote matching the secret pattern is refused. A claim whose normalised
text or quote equals an active claim's is skipped.
supersedes is accepted only as one of the codes
c1, c2, … that the prompt gave to existing
claims related to the batch's user text (:418-424), mapped
back to a claim id.
The sources may be of either role. by_id holds every
message in the batch, and the claim filter does not look at
role (:481-485). The entity filter a few lines
further down does, keeping only user-sourced entity facts
(:533). So a claim about the person can be quoted from the
assistant's paraphrase of what the person said; an entity fact
cannot.
Index card. MEMORY.md edits arrive as
add and revise operations.
reconcile_one (:564) asks the model to rewrite
any MEMORY.md line still stating a value a new claim just superseded,
keeping the void marker.
Operational cost
Every booking, entity page, nightly review and forget is a model call
through the person's CLI. max_calls_per_day stops the
worker at 300 and treats the rest as a transient failure. The hooks
themselves call no model; the engine's docstring calls the write methods
millisecond work (engine.py:3).
8. Agent Integration
At SessionStart the hook injects the standing files and the notebook
as one block (hooks.py:113-151). At UserPromptSubmit it
records the prompt and injects the recall block inside
<运行时上下文> ("runtime context") tags
(:157-185). At Stop it records the reply, backfilling the
prompt from the transcript if the earlier hook missed it
(:199-215).
Five MCP tools are registered
(hosts/claude/miaomory_claude/mcp_server.py:39-45,
:134-137): memory_search,
memory_get, remember, forget and
memory_explain. remember and
forget only enqueue; the worker does the model work.
memory_explain returns the claim, quote and evidence behind
a line, which is the provenance a person can ask for.
9. Reliability, Safety, and Trust
The quote gate holds on every claim
No claim enters the daily files without a quote found in a message it cites. This is the strongest write-side check here, and it is code, not prompt. Its limit is the role filter it does not have: a quote from an assistant reply passes.
A correction does not displace its source
Supersession removes the old claim from tier 1 but leaves the old
message in tier 3. Recall and search then rank by lexical score. Nothing
in the read path down-weights a message whose claim was superseded, and
the newest-wins rule is a sentence for the model. A product that cannot
tolerate a stale preference reaching the answer would need the
superseded claim's sources excluded from tier 3, the way
recall already excludes the sources of chosen claims from its quote
channel.
Forget is thorough, and does not hold against a restatement
forget() (engine.py:398-492) asks the model
which claims, MEMORY.md lines and pages match the topic. It adds every
claim those supersede (:420-421), hides each source
message, any message at least 0.6 similar or containing a quote, and the
assistant reply after each, deletes matched pages, clears the dream
files and resets ALIGNMENT_SYNTHESIS.md. The claim text is
archived in workspace/memory/forget/FORGOTTEN.md and
pending.json.
The archive header says the file is not given to the assistant and
not searched (engine.py:34), and the recorded searches find
no reader of it in src/ or hosts/.
hidden is keyed by message id. If the person says the same
thing again, the next booking extracts it as a new claim. For a forget
the person asked for, that is arguably correct, but it is not a
tombstone.
What holds
memory_getrefuses hidden messages, files underworkspace/, paths outside the memory root and symlinks that escape it.- Neighbouring messages shown beside a search hit are taken from the
same session only (
host_memory.py:458-478). - Secrets matching the pattern are refused on write and masked on read
when
mask_readis on, whichR12Asets.
Marks
negative_eval— awarded.test_forgetasserts the forgotten term is absent from MEMORY.md, the notebook and search, that the source message and the reply after it are not readable, and that the archive is not readable, with an unrelated item asserted present in the same case.scope_enforced— withheld.session_idandcwdare stored on every message.session_idlimits the neighbouring-message view; neither filters recall or search, andcwdis read only on the capture side.tombstone— withheld. FORGOTTEN.md is written and never read; hiding is by message id; nothing compares a new claim with a forgotten one.trust_state— withheld. Status is derived on every read fromsupersedesandvalid_until; no stored status exists to set or filter.bitemporal— withheld.valid_untilbounds the end of validity; the start isfirst_seen, which is booking time.audit_log— withheld. MEMORY.md revisions overwrite the line; the daily files are rewritten by forget; FORGOTTEN.md records deletions only. Therunstable records background runs, not memory mutations.human_review— withheld. Every claim is active on booking.
10. Tests, Evals, and Benchmarks
The 126 test functions run on unittest with a fake model
(tests/support/fake_brain.py) and fake claude
and codex binaries for the smoke tests.
tests/unit/test_reference.py is the unusual part: it checks
SHA-256 fingerprints of the reference copy, runs the original evaluation
tests against both the reference and the vendored code, asserts that
only import lines differ, that R12A equals
r12a.json, that the prompts are identical, and that no
network module is imported.
tests/golden/test_golden.py:263
(test_g5_supersede) checks that a superseding claim
produces the same files as the reference. No test asserts the ordering
of a superseded message against its correction in recall or search.
The evals/ directory holds the LongMemEval-S runners for
both hosts. The data is outside the repository
(MIAOMORY_LME_DIR). The pin has no CI workflow. I did not
run the tests or the evaluation.
11. For Your Own Build
Steal
- A quote gate in code. Refuse any extracted claim whose quote is not in a message it cites. Add a role check if claims are about the person.
- A fingerprint test on carried-over code. If the production path is meant to be the evaluated path, hash it and allow only named diffs.
- A forget that walks supersession backwards and hides the conversation the claim came from, with a test that checks each read surface and keeps a positive control.
Avoid
- Leaving the source of a superseded claim in the raw tier. Exclude it, or label it, before ranking.
- Recency as a footer. If the newest record should win, sort on it or drop the older one; a sentence for the model is a request.
Fit
A single person using two coding agents on one machine, who wants both to share what they learned. It is not a fit for anything shared between people or projects that must not see each other: there is one store and no read filter.
12. Open Questions
- Does the answering model follow the footer often enough in practice? The notebook at a later commit shows one case; the evaluation does not isolate it.
- Should a forgotten topic be refused on the next booking? The design treats forget as a one-time removal; a restated fact returns.
- What share of claims are quoted from assistant messages? The booking stats count considered, rejected and inserted claims, not their source roles.
Appendix: File Index
- Engine and forget:
src/miaomory/engine.py - SQLite store:
src/miaomory/store.py - Host subclass and read limits:
src/miaomory/host_memory.py - Evaluated memory logic:
src/miaomory/core/newmem.py,src/miaomory/core/newmem_opt.py - Fixed configuration:
src/miaomory/config.py - Claude Code adapter:
hosts/claude/miaomory_claude/hooks.py,hosts/claude/miaomory_claude/mcp_server.py,hosts/claude/miaomory_claude/settings.py - Codex adapter:
hosts/codex/miaomory_codex/hooks.py,hosts/codex/miaomory_codex/mcp_server.py - Tests:
tests/unit/test_engine.py,tests/unit/test_reference.py,tests/golden/test_golden.py,tests/reference/ - Design:
docs/DESIGN.md
Recorded searches
Run from the repository root at the pinned commit with
/usr/bin/git grep.
cwdis stored and not read back by the memory logic.git grep -n cwd -- 'src/*.py'returnssrc/miaomory/engine.py:117,:121,src/miaomory/oscompat.py:122,:128(the worker's process directory) andsrc/miaomory/store.py:27,:103,:107,:109,:130(the column, the insert and the row mapping). The hosts read it athosts/claude/miaomory_claude/hooks.py:75,:79andhosts/codex/miaomory_codex/hooks.py:70,:74, all on the capture side.- Nothing reads the forget archive.
git grep -n -E 'FORGOTTEN|forget/' -- 'src/*.py' 'hosts/*.py'returnssrc/miaomory/engine.py:34(the header),:480(the write) and the two opener notes inhosts/*/opener.py:9. - No start-of-validity field.
git grep -n -E 'valid_from|validFrom' -- 'src/*.py'returns nothing. - No mutation log.
git grep -n -i -E 'audit|history|changelog' -- 'src/*.py'returns nothing. - No CI workflow.
git ls-files .githubreturns nothing. - Recency is a tie-break in search.
git grep -n 'kept.sort(key=lambda x: (round' -- src/miaomory/core/newmem_opt.pyreturns:1491.
History
2026-12-03 — 8f6c9ed2….
First reading at the commit the nomination names (v0.1.8), the
repository's first. One mark: negative_eval. Screened
before reading: four auto-run surfaces, all the Claude Code plugin's own
(marketplace.json, plugin.json,
.mcp.json and four hooks); no build-time execution, no
dependency surface inside the cooldown and no floating range;
AGENTS.md and CLAUDE.md read as data. The
notebook the nomination cites is at 7b08457, 18 commits
later; between the two, engine.py and
host_memory.py gain an off-by-default deepen
path and nothing in the recall or search ranking changes. Nothing was
installed or run, and no test was run.