CJK-first BM25 memory whose corrections close two time windows and leave scope to the caller

Brain4Agent

A local Python memory for agents over one SQLite file: BM25 over stored turns, no model in the core path, and validity and belief windows.

LicenceApache-2.0 in LICENSE and pyproject.toml
Size5,748 lines of Python in 13 files under src/brain4agent (store.py is 1,859 and the tokenizer 1,205), 6,939 lines of tests and 7,720 lines of benchmark harnesses and probes
Activity154 commits dated 6 to 22 November 2026, all under one author name; the GitHub repository was created on 8 November; version 0.2.0
Tests533 pytest functions in 30 files; CI runs them on Ubuntu and Windows under Python 3.11 and 3.12, then three retrieval benchmarks as threshold gates; none run here

Carries 2 of 7 rubric mechanisms. Most systems here carry none or one (41%), and a dash means the mechanism was not found at this commit — not that the system needed it. Each mark is one LLM reviewer's reading of the code at this commit rather than a run of it — known limits.

  • Tombstone
  • Trust state
  • Bi-temporal
  • Scope enforced
  • Mutation audit
  • Human review
  • Negative evals

1. Executive Summary

Brain4Agent is a local long-term memory for agents: a Python library, CLI and MCP server over one SQLite file. Turns are stored verbatim and retrieved by session through an in-memory BM25 index tuned for Chinese, with no model call on the default path. A search returns evidence beside the ranking: which question words the whole corpus lacks, which each session lacks, and how many sessions hold each word.

Notable: every memory carries two half-open windows, one for when the fact held and one for when the store believed it. A correction closes both, at two different instants, and recall can ask either question or both at once. A hit on a replaced memory is redirected to its replacement, which inherits the old row's terms and tags.

Weak: scope is a tag list the caller may omit, and untagged memories pass every filter. A recall without a date ignores the validity window. Undoing a correction erases the record of when the store stopped believing the old value. Any agent tool call may supersede any memory.

Two marks are present and five are withheld (section 9).

Licence. Apache-2.0 in LICENSE, unmodified, with the template's copyright placeholder unfilled, so the tree names no copyright holder; pyproject.toml declares Apache-2.0 and credits "Brain4Agent contributors". There is no SECURITY.md and no NOTICE.

2. Mental Model

A memory is a turn of conversation, and the unit of retrieval is the session that holds it. Nothing about a memory's truth is modelled as a state: there is no status column, only a pointer to the memory that replaced it and two time windows (src/brain4agent/store.py:141-162).

The two windows answer different questions. valid_from and valid_to say when the fact held in the world; known_from and known_to say when this store held the belief (src/brain4agent/store.py:211-228). Both open at the write instant unless the caller names another, and both are half-open, so at the moment of a switch exactly one memory answers.

A correction is a separate memory plus a link. supersede(old, new) sets the old row's superseded_by, closes its validity where the replacement's validity opens, and closes its belief where the replacement's belief opens (src/brain4agent/store.py:1614-1625, :1688-1692). A later write closes nothing on its own: without a supersede call, two values coexist and both are returned.

Diagram — a supersede closes both windows and redirects undated recall; dates and tags filter only when the caller passes them
Diagram source
%% caption: a supersede closes both windows and redirects undated recall; dates and tags filter only when the caller passes them
flowchart TD
    REM["b4a_remember"] --> ROW["memories row<br/>valid_from, known_from"]
    ENV["BRAIN4AGENT_PROJECT"] --> TAG["tags: project,<br/>kind, date"]
    TAG --> ROW
    ROW --> IDX["in-memory BM25<br/>over turns"]
    SUP["b4a_supersede"] --> CLOSE["old row gets<br/>superseded_by,<br/>valid_to, known_to"]
    CLOSE --> ROW
    UNS["b4a_unsupersede"] --> NUL["all three<br/>set to NULL"]
    NUL --> ROW
    Q["b4a_recall"] --> IDX
    IDX --> D{"as_of or<br/>known_as_of?"}
    D -- "yes" --> WIN["keep rows inside<br/>the named windows"]
    D -- "no" --> RED["superseded hit<br/>goes to successor"]
    WIN --> T{"tags passed?"}
    RED --> T
    T -- "yes" --> F["drop rows tagged<br/>outside the list;<br/>untagged pass"]
    F --> OUT["whole session<br/>text returned"]
    T -- "no" --> OUT

3. Architecture

src/brain4agent/store.py is the system: the schema, the migrations that add columns to older files, writes, supersession, the windows and search. tokenize.py holds the tokenisers and the BM25 index with its incremental add and single-row patch. evidence.py builds the per-search evidence. mcp_server.py is a JSON-RPC loop over stdio written against the standard library, and cli.py exposes the same store. extract.py, llm.py, judge.py and read.py are the optional model paths, all off unless a key is set. graph.py, an entity co-occurrence graph, is imported only by its test.

Deployment and ergonomics

pip install Brain4Agent has no dependencies; the precise extra adds jieba (pyproject.toml:11, :36-46). The MCP server opens the file named by BRAIN4AGENT_DB, or brain.db in the working directory (src/brain4agent/mcp_server.py:269-279). WAL mode lets the MCP server and the CLI hold the same file, and each process reloads its index when SQLite's data_version moves (src/brain4agent/store.py:483-501). The whole corpus sits in memory; the README puts resident cost at about 1.2 GB per 100,000 memories.

4. Essential Implementation Paths

  • Remember. b4a_remember → _structured_tags adds date:, kind: and project: tags → MemoryStore.add, or remember when distil is true (src/brain4agent/mcp_server.py:346-419).
  • Store a turn. add: reject empty or over 100,000 characters, normalise the timestamp and both window openings, tokenise, insert, commit, extend the index in place (src/brain4agent/store.py:558-744).
  • Recall. b4a_recall → search with the caller's tags, as_of and known_as_of → _visible per hit → _fold_sessions → build_evidence → _annotate increments access counts (src/brain4agent/mcp_server.py:484-532, src/brain4agent/store.py:1073-1254, :1338-1365).
  • Correct. b4a_supersede → supersede: cycle check, window closures, inversion checks, token and tag inheritance, one update on the old row (src/brain4agent/store.py:1584-1723).
  • Undo. b4a_unsupersede → unsupersede clears the pointer and both closures (src/brain4agent/store.py:1725-1764).
  • Inject. brain4agent recall-context reads a prompt on stdin and prints matching sessions under a header that calls them possibly unrelated (src/brain4agent/cli.py:143-195).
  • Forget. forget <session> and prune --keep N delete rows (src/brain4agent/store.py:993-1056, src/brain4agent/cli.py:349-368).

5. Memory Data Model

One table, memories (src/brain4agent/store.py:141-162):

  • identity and text: id, session_id, role, content, created_at, and tokens, the cached index-side tokenisation;
  • structure: kind (free-form), importance, entities, source_text for a distilled memory's original turn;
  • metadata: tags (space-separated, no spaces inside a tag), superseded_by, refs;
  • maintenance: fingerprint (SimHash), accesses, weight;
  • time: valid_from, valid_to, known_from, known_to.

Migrations add each column to an older file and backfill both window openings from created_at (src/brain4agent/store.py:325-376). Every instant a caller supplies is normalised to a UTC ISO string, a bare date to midnight (:253-264), and a stored value that does not parse counts as inside its window rather than hiding the row (:1488-1526).

Nothing is append-only. Supersession, unsupersession, reinforcement, decay and linking update the row in place, and forget and prune delete it.

6. Retrieval Mechanics

The index side tokenises into Chinese character bigrams plus jieba words; the query side uses words with interrogatives removed. Without jieba both sides use bigrams (src/brain4agent/store.py:48-67). English terms are stemmed and stopwords dropped on the query side, an unknown English word may match a corpus word one edit away, and two multiplicative bonuses reward adjacent query pairs and query terms clustered in a 40-token window (src/brain4agent/store.py:79-139, :461-478). A session scores its best turn plus half of its next two (:1283-1313).

Because the default excludes superseded memories, the filtered path runs on every recall: it ranks the whole index, redirects each superseded hit to the end of its chain, and applies _visible (src/brain4agent/store.py:1144-1192). With a date, the window replaces the redirect, so a March question gets the row that held in March.

A recall without a date checks neither window. _visible tests the windows only when as_of or known_as_of is given, and otherwise tests only superseded_by (src/brain4agent/store.py:1461-1476). The valid_from description on b4a_remember says a memory whose window has not opened is invisible to recall (src/brain4agent/mcp_server.py:103-112); that holds only for a dated recall.

Every result carries corpus_missing, per-session missing_terms, term_frequencies and up to five related_terms (src/brain4agent/evidence.py:262-383). A dated search computes coverage against that era and corpus_missing against the whole corpus, so a word first written later is reported as absent then, not as never written.

What a hit returns is the session. The MCP row's text and the CLI's output are session_text, every turn of the session in write order (src/brain4agent/mcp_server.py:481, src/brain4agent/store.py:1817-1825). A superseded turn, a turn outside the tag filter and a turn outside the asked era are all printed if they share a session with the hit.

7. Write Mechanics

A write is one synchronous insert and commit, then an in-place extension of the BM25 index, so the memory is searchable on the next call; the corpus-wide idf tables are recomputed lazily on the next query (src/brain4agent/store.py:676-744). batch() defers the commit for imports and rolls back on an exception (:891-916). Writes block the caller for a few milliseconds; the README reports 16.3 ms for the first search after a write at 2,930 memories.

Distillation is opt-in on b4a_remember and costs one call to an OpenAI-compatible chat endpoint, DeepSeek by default (src/brain4agent/llm.py:27-28, :82-97). The extractor keeps the question's vocabulary, returns up to five memories, and stores the original turn as source_text; an empty extraction stores nothing, and a failed one stores the raw turn (src/brain4agent/store.py:816-890). Its own tool description says distilling hurts retrieval.

Nothing deduplicates or reconciles on write. The SimHash fingerprint is computed on every insert and compared only in duplicates_of, which no shipped surface calls. A restated value, including one superseded before, becomes a new current memory.

Operational cost

No model on the default path, no background pass, and no pass rewrites the store. Every search writes one access-count update per returned session (src/brain4agent/store.py:1361-1364). Opening a store rebuilds the index; the README reports 393 ms at 2,925 turns.

8. Agent Integration

The MCP server registers seven tools: b4a_remember, b4a_supersede, b4a_unsupersede, b4a_recall, b4a_ask, b4a_session and b4a_stats (src/brain4agent/mcp_server.py:44-266). b4a_ask retrieves without tags and sends the sessions to the configured model under a prompt that asks it to prefer the later date and to say when the evidence lacks the answer (src/brain4agent/read.py:37-45, :97-135). b4a_session returns any session by id.

b4a_supersede tells the model to use it only when the caller identifies a correction; nothing else limits it, and b4a_unsupersede reverses any link (src/brain4agent/mcp_server.py:128-183). Neither records who called it.

Proactive recall is the client's job. recall-context prints up to 1,500 characters of matching sessions or nothing, and integrations/hooks/recall-before-prompt.ps1 pipes a prompt into it with no tag filter. The skill under integrations/skills/brain4agent/ is written in Chinese and lists the CLI's forget and prune among its commands.

9. Reliability, Safety, and Trust

Two clocks, closed separately

supersede closes the old validity at the replacement's valid_from and the old belief at the replacement's known_from, and accepts either explicitly (src/brain4agent/store.py:1614-1625). It refuses a closure before the opening on either axis, a self-link and a cycle (:1606-1645). A committed timeline separates them: a June change recorded in August answers July's known_as_of with the old value and July's as_of with the new one (tests/test_bitemporal.py:604-611).

Undo rewrites the belief axis

unsupersede sets superseded_by, valid_to and known_to to NULL (src/brain4agent/store.py:1747-1752). The old row is then believed from its original known_from with no gap, so a known_as_of inside the span between the supersede and the undo returns both values, though the store held only the replacement then. The test's comment says the old row is believed from the moment the link was withdrawn (tests/test_bitemporal.py:634-644); the code keeps no such moment. Terms and tags the replacement inherited stay, by design.

Scope fails open

Tags filter only when the caller passes a list, match on any overlap, and never exclude an untagged memory (src/brain4agent/store.py:1478-1485). The server writes project: from BRAIN4AGENT_PROJECT on every remember and never reads it on recall (src/brain4agent/mcp_server.py:279, :361, :484-500). b4a_ask, b4a_session and the shipped hook take no tags.

No record of change

There is one table and no event log. A supersede, an undo, a decay or a forget leaves only the row's current values, or no row.

Marks

  • bitemporal — present. Validity and belief windows apart from created_at, set through MCP, closed by supersede, filtered by as_of and known_as_of; an undated recall ignores them, and undo erases a closure.
  • negative_eval — present. Populated cases assert a superseded memory, another era and another tag absent from results.
  • scope_enforced — withheld. The tag filter is a real predicate on the read path, and it is optional: omitted, it filters nothing, and an untagged memory passes it. The project tag the server writes never reaches a read.
  • trust_state — withheld. superseded_by is a pointer, kind is free-form, and importance and weight are floats; the judge's uncertain is a search result and is never stored (src/brain4agent/store.py:1766-1815).
  • audit_log — withheld. One table, updated in place; no mutation record.
  • tombstone — withheld. A superseded row keeps its content, and add consults neither it nor the fingerprint, so the same value written again is a new current memory.
  • human_review — withheld. No memory waits in any state, and the agent holds both correction verbs.

10. Tests, Evals, and Benchmarks

The suite is 533 pytest functions in 30 files under tests/, none skipped by a guard. CI installs with pip install -e ".[precise,dev]", runs ruff and the suite on Ubuntu and Windows under Python 3.11 and 3.12, then three gates: the Chinese end-to-end benchmark at hit@1 0.92, PrecisionMemBench at pass 0.82 and active 0.78, and LoCoMo session retrieval at hit@1 0.62 (.github/workflows/test.yml:16-59). A test pins that the PrecisionMemBench runner fails above its actual rate (tests/test_bench.py:275-293).

The bitemporal file has 43 cases, written before the implementation by its own account. The negative cases that earn the mark sit on populated stores: the superseded value beside its replacement (tests/test_metadata.py:80-85), January and June values asked about March (tests/test_bitemporal.py:162-179), and two scopes holding rows the third must not see (tests/test_supersede_scope.py:49-66).

The README reports PrecisionMemBench passing 74 cases out of 77, with 42 passes among the 43 active ones, LongMemEval s hit@10 0.9660, and LoCoMo session hit@1 0.7054. LoCoMo and PrecisionMemBench data are committed; LongMemEval data is fetched. The README also shows a dense same-topic corpus taking Chinese hit@1 from 0.950 to 0.000. I ran none of them.

Cases to want first: a forward-dated memory under an undated recall; a known_as_of inside a superseded-then-restored span; a correction appended to the old memory's session, asserting the returned text.

No paper describes Brain4Agent. CITATION.cff is absent, and the arXiv identifiers in the tree cite other work as the basis for design decisions.

11. For Your Own Build

Steal

  • Close the two axes at two instants. The fact stopped at the replacement's valid start; the belief stopped when the replacement was recorded. Default each from the replacement, refuse an inverted window.
  • Redirect, do not drop. A hit on the old wording resolves to the replacement, and the replacement inherits the old row's terms and scope, so a correction is findable by the question that found the mistake.
  • Return absence as evidence. Words the corpus never held, and words each session lacks, cost nothing to compute and let the caller abstain.
  • Gate CI on retrieval numbers. A threshold per benchmark makes a ranking regression a red build.

Avoid

  • Do not make the undo a NULL. Reopening a closed belief by clearing known_to rewrites what the store believed; append a new interval instead.
  • Do not let scope be absent by default. A filter the caller may omit, and that untagged rows pass, is a hint. Apply the server's own project on read.
  • Do not return the container when the filter judged the row. Whole sessions carry turns the filter excluded.

Fit

Fits one developer, one machine and a corpus in the low thousands of turns, mostly Chinese or mixed, where keyword recall with honest absence signals beats an embedding service. The code is small, carefully reasoned and measured, and the decision log explains nearly every constant.

Walk away if several projects or people share a file and must not read each other's memory, if a correction must be durable against the agent that made it, or if the corpus will reach hundreds of thousands of turns.

12. Open Questions

  • Whether a recall without a date is meant to exclude a memory whose validity has not opened, as the remember tool's description says.
  • Whether unsupersede should record its own instant on the belief axis.
  • Whether the server's BRAIN4AGENT_PROJECT is meant to scope recall as well as tag writes.
  • Whether recall should return the matched turns rather than the whole session.

Appendix: File Index

  • Store, schema, windows, supersession: src/brain4agent/store.py
  • Tokenisers and BM25: src/brain4agent/tokenize.py
  • Evidence: src/brain4agent/evidence.py
  • Agent surface: src/brain4agent/mcp_server.py, src/brain4agent/cli.py, integrations/hooks/recall-before-prompt.ps1, integrations/skills/brain4agent/SKILL.md
  • Model paths: src/brain4agent/extract.py, src/brain4agent/llm.py, src/brain4agent/judge.py, src/brain4agent/read.py
  • Unwired: src/brain4agent/graph.py
  • Decisions: docs/decisions.md
  • Tests: tests/test_bitemporal.py, tests/test_metadata.py, tests/test_supersede_scope.py, tests/test_unsupersede.py, tests/test_mcp_server.py, tests/test_bench.py; harness bench/pmb/harness.py

Recorded searches

Run from the repository root at the pinned commit with /usr/bin/git grep. .gitmodules is absent.

  • One table, no mutation log. git grep -n 'CREATE TABLE' -- . returns src/brain4agent/store.py:142 and three fixtures in tests; git grep -n -i -E 'audit|journal|history_table|event_log' -- src returns a comment at store.py:224 and the WAL comment and pragma at :296 and :300.
  • No review or status state. git grep -n -i -E 'pending|approve|review|status' -- src/brain4agent/store.py src/brain4agent/mcp_server.py returns nothing.
  • Maintenance functions have no shipped caller. git grep -n -E 'prune_by_weight\(|\.decay\(|\.reinforce\(|\.link\(|duplicates_of\(' -- src integrations returns the two definitions at store.py:1022 and :1256 and two comments.
  • No duplicate check on write. git grep -n 'near_duplicate' -- src returns the definition in simhash.py:81, the import, and store.py:1279 inside duplicates_of.
  • No value-keyed rejection. git grep -n -i -E 'reject|tombstone|blocklist|denylist' -- src returns comments and docstrings only.
  • The project tag is write-only. git grep -n -E 'self\.project' -- src returns mcp_server.py:279 and :361, the latter in _structured_tags.
  • The graph is unwired. git grep -n -F 'brain4agent.graph' -- . returns tests/test_graph.py:13 only.
  • No paper. CITATION.cff is absent; git grep -l -i -E 'arxiv|doi\.org|bibtex' -- . returns two benchmark scripts, three documents in docs/, mcp_server.py and read.py, all citing other work.

History

2026-12-04 — 3d4b177d…. First reading, from the 2026-12-04 triage shortlist, at the head of main. Screened: three files scanned; no auto-run surface, none inside the cooldown, no build-time execution point, and one floating surface (pyproject.toml with no lockfile); FOR_AGENTS.md read as data. Nothing was installed, built or run, and none of the 533 test functions was run. Two marks (section 9).