back
whitepaper · v3.0 · october 2026 · brainctl 2.9.0

brainctl: a local-first memory store for LLM agents

Terrence Schonleber & contributors · github.com/TSchonleber/brainctl
abstract

LLM agents lose what they learn at every session boundary. Long context windows and plain retrieval each address part of this, but neither tells an agent which of two stored values is current, which stored fact is a restated duplicate, or that nothing it remembers answers the question. brainctl is an open-source memory store that keeps an agent’s memories, events, decisions and entity graph in one SQLite file, with FTS5 keyword search, optional sqlite-vec embeddings, and a 100-tool Model Context Protocol server. Its write and read paths make no LLM calls. This paper describes the system as it ships in version 2.9.0, with three mechanisms borrowed from the cognitive neuroscience of memory: a write-time gate that reinforces near-duplicates and keeps near-misses apart (dentate gyrus pattern separation and CA3 pattern completion); bi-temporal supersession, in which a newer value retires an older one unless the older one is entrenched (retroactive interference and reconsolidation); and a familiarity score that lets search report that a query is not in memory (dual-process recognition). On retrieval-only runs of LongMemEval (289 questions) and LoCoMo (1,982 questions), keyword retrieval reaches Hit@5 of 0.979 and 0.613. On small purpose-built suites, the write gate suppresses every exact and surface duplicate with no false merges, supersession lifts latest-value P@1 from 0.00 to 1.00, and the familiarity score separates answerable from unanswerable queries with AUROC 0.9955. We state which mechanisms run by default, which are opt-in or experimental, and what has not been measured, including end-to-end question answering.

introduction

the problem

A coding agent decides on day one to honour Retry-After headers because the server owns the rate-limit window. On day two a fresh session is asked to “improve backoff” and, with no record of the reason, adds exponential backoff that fights the headers. On day three a third session layers a reconciliation shim over both. Each session reasoned correctly from what it could see. What failed is memory: the decision and its rationale did not survive the session boundary.

Persisting text is easy. The hard parts are the questions a store has to answer once it holds months of writes: is this new note a restatement of something already stored, or a different fact that only looks similar? When two notes disagree, which one is current? When a query arrives, does anything stored actually answer it, or do the hits merely share a word with it? brainctl is an attempt to answer those three questions deterministically, locally, and in a way an operator can audit.

why long context and plain retrieval are not enough

Putting the whole history in the prompt is costly and degrades with length. Liu et al. (2024) showed that models use information at the start and end of a long context better than information in the middle. LongMemEval (Wu et al., 2025) measured the effect on memory directly: GPT-4o answered 0.870 of its questions when given only the evidence sessions, and 0.606 when the same evidence sat inside a history of roughly 115K tokens.

Retrieval over stored chunks fixes the cost but not the semantics. A vector or keyword index ranks by surface similarity, so “Alice is CTO” and “Alice left the company” come back side by side with no notion of which is current; restating a fact five times stores it five times; and an index always returns its nearest neighbours, so a question about something never stored still gets confident-looking hits. Systems in this space (Section 10) increasingly add temporal models, deduplication and memory management on top of retrieval. Most do it with an LLM in the write path.

design stance

contributions

  1. A write-time decision with three outcomes (reinforce, separate, insert), driven by a normalised lexical signature and a key-token rule, so that restatements strengthen one memory while near-misses such as negations or changed numbers are stored apart and linked (Section 3.2).
  2. Bi-temporal supersession gated by how entrenched the incumbent is, so the latest value of a fact wins by default but one injected “correction” cannot erase a well-established memory (Section 3.3).
  3. A familiarity score computed from pre-normalisation retrieval evidence, which lets search abstain on queries the store cannot answer (Section 4.3).
  4. A retrieval and memory-quality benchmark harness with committed baselines and CI gates, and the results in Section 9.

scope

brainctl is not a planner, a reasoning engine or a model. It does not decide what the agent does next and it trains nothing. It is not a hosted multi-tenant service: the single-file design targets one operator or a small team. It is not a transcript store either; it expects the agent to write distilled memories, decisions and events rather than every turn. Earlier versions of this paper also described an on-chain marketplace layer; that layer is specified separately and is out of scope here.

system overview

substrate

The store is one SQLite database in WAL mode with foreign keys on. Keyword search uses FTS5 with BM25 ranking (Robertson & Zaragoza, 2009) and the Porter stemmer. Vector search uses the sqlite-vec extension over embeddings from a local Ollama model (nomic-embed-text by default, four alternatives selectable); when no embedder is reachable, vector legs drop out and everything runs on FTS5. The schema is built from 86 numbered, append-only migrations (002 to 087) plus an unnumbered schema file; a fresh init_schema.sql creates 142 tables, 7 virtual tables and 3 views. Since 2.9.0 the migrations ship inside the wheel, and the runner refuses to replay migrations over a populated database whose version table is empty.

SQLite was chosen for operational reasons: it needs no server, it is one file, it has a long durability record, and FTS5, vectors and relational data live in the same engine, so ranking can join across them without a network hop. The cost is a single writer at a time, which suits the access pattern of an agent that reads often and writes a few rows per step.

data model

The core tables follow Tulving’s (1972) distinction between episodic and semantic memory, with separate stores for procedures, decisions and the entity graph.

storetable(s)role
semanticmemoriesfacts, conventions, lessons, preferences; gated, FTS-indexed, Beta(α, β) confidence, validity interval
episodiceventstyped, time-stamped log; append-only
proceduralprocedures, procedure_stepsordered steps with success / failure feedback
decisionsdecisionsa decision with its rationale
associativeentities, knowledge_edgestyped nodes with observations; typed, weighted edges
prospectivememory_triggerskeyword triggers that surface a note when matched
handoffhandoff_packetsgoal, current state, open loops, next step

A memory row carries its agent, scope, category (one of nine: convention, decision, environment, identity, integration, lesson, preference, project, user), a temporal class that sets its decay rate, recall counters, Beta parameters, a Q-value, and, since migration 087, valid_from and valid_to.

interfaces

The same store is reachable from a CLI (brainctl), a Python class (agentmemory.Brain) and an MCP server over stdio or streamable HTTP. The MCP server registers 376 tools and exposes 100: core operations by name, and the rest through action-discriminated dispatchers, because many clients cap the visible tool count and 370 tool descriptions cost about 50K prompt tokens. Nineteen plugins wire the server into agent frameworks and trading bots.

The three write entry points are not equivalent in 2.9.0. The CLI memory add runs every gate in Section 3 plus entity linking; the MCP memory_add runs the same gates without entity linking; the Python Brain.remember inserts directly. Retrieval converges: Brain.search delegates to the CLI search pipeline. Unifying the write paths is listed in Section 11.

write pathread pathmemory addCLI · MCP memory_addadmission scoreA-MAC five factorspattern separationreinforce · separate · newsupersede gatePII tier · valid_toqueryCLI · Brain.searchBM25 + vectorFTS5 · sqlite-vecRRF k=30 · validitydrop superseded rowsgated rerankersrecency · trust · contextfamiliarity gateanswerable · familiarityreadsbrain.dbone SQLite file · WAL · FTS5 · vectors · entity graphoffline: consolidation and dream cyclesdecay · downscale · replay · schema promotion · Hebbian
1. The write path, the read path and offline maintenance around one SQLite file.

status labels

Each mechanism below is labelled default (runs on the standard install’s main path), opt-in (needs a flag, an extra or a separate command) or experimental (present in the code but not wired into the default path, dependent on modules outside the package, or not yet exercised by the benchmarks).

the write path

admission scoring

default Every CLI and MCP write is scored by a five-factor admission function following Zhang et al. (2026), who decompose memory admission into future utility, factual confidence, semantic novelty, temporal recency and a content-type prior, and found the type prior the most influential factor:

W(m) = 0.15·utility + 0.15·confidence + 0.20·novelty + 0.10·recency + 0.40·type_prior

Novelty is one minus the maximum cosine similarity to stored memories, or a keyword-overlap estimate without embeddings. The type prior is a per-category constant (identity 0.90, decision and lesson 0.85, down to environment 0.60). In 2.9.0 utility and recency are constants, so with the default weights the score cannot fall below the 0.30 rejection threshold: the gate records a worthiness score rather than filtering. Deduplication, the job an admission gate is usually expected to do, is handled by the decision in Section 3.2.

experimental A second, embedding-based gate weighs novelty 0.45, long-term utility 0.25, confidence 0.20 and scope 0.10, scales the result by an arousal gain, and routes writes into a full tier (≥ 0.7), an unindexed construct tier (0.3 to 0.7) or rejection. It runs only when an embedding exists, and the CLI loads it from a path outside the package, so a standard install skips it.

pattern separation and completion

Neuroscience. The hippocampus faces the write-time problem directly. Marr (1971) proposed that a recurrent network can store a pattern quickly and later recall the whole from a partial cue, which is pattern completion; McNaughton and Morris (1987) and Treves and Rolls (1994) mapped this onto the hippocampus, with CA3’s recurrent collaterals doing completion and the dentate gyrus’s sparse input decorrelating similar patterns before storage, which is pattern separation. Recordings support the division: Leutgeb et al. (2007) found dentate population activity changed sharply with small changes to an environment, and Neunuebel and Knierim (2014) found that under conflicting cues dentate representations decorrelated while CA3 stayed more coherent than its input. In humans, Bakker et al. (2008) saw the CA3 and dentate region respond to slightly altered images almost as if they were new. Yassa and Stark (2011) review the evidence.

The engineering problem has the same shape. A memory store needs completion for restatements (“deploys go through staging” written twice should become one stronger memory) and separation for near-misses (“service X should call Y” and “service X should never call Y” must stay two memories, and must not be merged by a similarity threshold).

Implementation. default Before insert, one function shared by the CLI and MCP paths compares the candidate with its nearest active neighbours of the same agent, scope and category: up to 10 FTS5 candidates and up to 5 vector neighbours when an embedding exists. Similarity is token-set Jaccard over a normalised signature (case-folded, “n’t” expanded to “not”, punctuation stripped), or cosine when available. A key-token set is extracted from each side: numbers (versions and times kept whole, so 4.2 and 9:30 are single tokens), unambiguous date words, negations, and proper nouns or known entity names. Three outcomes follow:

The rule is deliberately conservative. It merges only near-verbatim restatements, so paraphrases written with different words are kept as separate memories unless embeddings are on; Section 9.4 measures both sides. Every database error degrades to “no decision”, and the write proceeds as before.

candidate memoryagent · scope · category · contentnearest active neighbourssame agent, scope, category · FTS5 top 10, vec top 5near-identical?Jaccard ≥ 0.85 or cos ≥ 0.97, no key diffreinforceno insert · α+1nosimilar, key token differs?≥ 0.60 / 0.85 · number, date, not, nameseparateinsert + edgenoinsertpassthrough or novelsupersedes an existing memory?--supersedes · supersedes_id · memory replaceincumbent PII < 0.40PII ≥ 0.40retire incumbentclose valid_tohistory keptkeep incumbentnew row startsat Beta(a, a)memory replace always retires the incumbent.
2. The write decision (Section 3.2) and the supersede gate (Section 3.3).

interference control and supersession

Neuroscience.Classic forgetting research attributes much forgetting to interference rather than disuse (McGeoch, 1932): new learning disrupts old (retroactive interference), and old learning disrupts new (proactive interference; Underwood, 1957; reviewed by Anderson & Neely, 1996). Reconsolidation adds a second point. Nader, Schafe and LeDoux (2000) showed that a reactivated memory becomes labile and must be re-stabilised, and later work frames this as the mechanism by which memories are updated (Lee, 2009), triggered mainly when reactivation produces a prediction error rather than by retrieval alone (Sinclair & Barense, 2019). Not every memory updates equally easily; well-established memories resist change.

For an agent the useful reading is: the latest value of a fact should win at retrieval, the old value should be kept for audit rather than destroyed, and a strongly established fact should not be overwritten by a single contradicting write, because that write may be wrong or adversarial.

Implementation. defaultMigration 087 gives memories bi-temporal columns in the database sense (Snodgrass & Ahn, 1985; Jensen et al., 1994): created_at and retired_at are transaction time, valid_from and valid_to are valid time. A write that names its predecessor (memory add --supersedes, or MCP supersedes_id) is checked against the incumbent’s Proactive Interference Index:

PII = E[p] · ln(1 + recalls) / ln(1 + max_recalls) · w(temporal class)

where E[p] = α / (α + β) and w runs from 1.0 for permanent memories to 0.15 for ephemeral ones. PII sorts incumbents into four tiers: open (< 0.20), established (0.20 to 0.40), entrenched (0.40 to 0.70) and crystallised (≥ 0.70). Below 0.40 the incumbent’s validity interval is closed and it is retired. At 0.40 or above the incumbent stays active and searchable; the new memory keeps the supersedes link and starts with a symmetric Beta prior whose strength grows with the incumbent’s PII, so it has to win the recall competition before it outranks the incumbent. memory replace is an explicit override and always retires. brainctl memory history prints the full version chain.

Retrieval enforces the same rule. Search drops candidates whose valid_to has passed, and candidates that an active memory supersedes (through the supersedes link or a supersedes edge), unless the superseded row is entrenched or above. Keyword-only search seeds each candidate with its BM25 strength rather than zero, so recency applies even without embeddings, and exact score ties go to the newer memory when the candidates’ timestamps differ by more than 60 seconds.

The closest precedent is Zep’s Graphiti (Rasmussen et al., 2025), which also keeps valid time and ingestion time on graph edges and invalidates an edge when a contradicting one arrives. The differences are that brainctl requires the writer to name the superseded memory (it does not detect contradictions with an LLM) and that entrenchment can keep the incumbent in place.

confidence and retrieval practice

defaultEach memory carries a Beta(α, β) distribution, starting at Beta(1, 1). Being returned as a direct search hit counts as a retrieval: α rises by 1, β by 0.1 (a small counterweight so frequently retrieved memories do not run away), confidence rises in proportion to a retrieval prediction error, the Q-value takes a temporal-difference step, and the memory becomes labile for two hours. The design borrows the testing effect, in which retrieving a memory strengthens it more than restudying it (Roediger & Karpicke, 2006). A reinforce decision (Section 3.2) also adds 1 to α; losing a contradiction pass adds 1 to β; decay (Section 5.1) adds to β over time. Both parameters stop growing once α + β reaches 1,000.

The honest limit: “retrieved” is a weak proxy for “useful”. No path yet feeds task outcomes back into α or β, so confidence measures how often and how recently a memory has been relevant, not whether it was right.

entity linking

default On the CLI path, each new memory is scanned for the names of known entities (word-boundary match, names of three characters or more) and linked by weighted mentions edges. opt-in A batch command adds two layers: zero-shot named-entity recognition with GLiNER (Zaratiana et al., 2024) and entity-to-entity co_occurs edges for memories that mention two or more entities. A tree-sitter ingester writes file, function and class entities with contains and imports edges for Python, TypeScript and Go source trees, with SHA-256 caching so re-runs on unchanged files are metadata-only.

the read path

candidates and fusion

default A query fans out to FTS5 and, when an embedding is available, to sqlite-vec. BM25 weights the content column three times the category and tag columns, so a full-text match outranks a matching label. The two ranked lists are fused with reciprocal rank fusion (Cormack et al., 2009):

score(d) = Σ 1 / (k + rank(d)), k = 30

Cormack et al. used k = 60. brainctl uses 30 because agents consume the top 5 to 10 results, and at k = 60 the fused score barely separates rank 1 from rank 10 (1/61 against 1/70). The vector leg is skipped when the keyword leg already has a strong anchor or the query is classified as a factual lookup, because on exact-term questions vector neighbours dilute the precise match.

reranking

defaultFused candidates pass through a chain of multiplicative rerankers, each behind an informativeness check that skips it when the candidates show no variance on that signal (a uniform-timestamp corpus gets no recency reranking, for example). The chain covers recency (exponential, permanent and long-lived memories exempt), source expertise, context match, Q-value and trust. Context match applies encoding specificity (Tulving & Thomson, 1973): each memory stores a snapshot of its write context, and a match with the current context raises its score by up to 20%. A regex intent classifier picks a rerank profile; for general and factual queries, the common case, recency and Q-value reranking are switched off so they cannot scramble a strong keyword ranking. Graph expansion appends one-hop neighbours of the top five hits. A cross-encoder reranker is available behind --rerank opt-in.

experimentalThree further stages exist in the code but do not run on a standard install: Thompson-sampling exploration over the Beta posteriors (Thompson, 1933; Chapelle & Li, 2011), adaptive salience routing, and a “quantum-inspired” amplitude reranker. All three load from paths outside the package; the amplitude reranker’s graph term is also currently empty. We do not count them as part of the system until they are packaged and benchmarked.

the familiarity gate

Neuroscience.Dual-process accounts of recognition separate a fast, graded sense that something has been seen before (familiarity) from slow retrieval of the specific episode and its context (recollection) (Mandler, 1980; Jacoby, 1991; Yonelinas, 2002). In the medial temporal lobe, perirhinal cortex is associated with item familiarity and the hippocampus with binding items to context for recollection (Eichenbaum, Yonelinas & Ranganath, 2007). The related metamemory literature shows that people can judge whether they know an answer they cannot yet recall (Hart, 1965), and that this feeling of knowing tracks how much partial information comes to mind (Koriat, 1993).

A retrieval system has the recollection half and lacks the familiarity half. brainctl’s ranker normalises scores per result bucket, so the best hit always scores the same whether it answers the query or shares one word with it. In the abstention suite (Section 9.4) the normalised top score separates answerable from unanswerable queries with AUROC 0.56, barely above chance.

Implementation. default Every search result now carries familiarity in [0, 1] and answerable. The score is built from evidence that exists before normalisation, over the query’s salient terms (stopwords and question scaffolding removed, Porter-stemmed exactly like the index):

The weighted mean r of the signals present goes through a logistic squash centred at 0.65 with slope 8, which turns it into an estimate of P(answerable). The answerable threshold is 0.25, not 0.5: treating a false “not in memory” as three times as costly as a false “maybe” puts the Bayes cut at 1 / (1 + 3). The signal weights and the threshold were set by argument; only the midpoint and slope were fitted, on each half of the abstention fixtures with the other half held out.

By default the gate only annotates. With --abstain (CLI) or abstain=true(MCP), a search judged unanswerable returns no hits, and hits in the uncertain band (0.10 to 0.50) first get one recollection pass: the store is re-probed with a query that requires the terms the best hit was missing, and a better-covering memory replaces it. This is selective prediction (Geifman & El-Yaniv, 2017) applied at the retrieval layer, the same idea SQuAD 2.0 (Rajpurkar et al., 2018) and selective QA (Kamath et al., 2020) apply to reading comprehension.

signals (before normalisation)coverage 0.45IDF-weighted termsbm25 ratio 0.20vs. an ideal hitentity 0.20named things foundvector 0.20cosine, if presentmargin 0.05top-1 vs top-2absent signals drop out;weights renormaliser = weighted mean of present signalsf = 1 / (1 + exp(−8 (r − 0.65)))read as P(answerable)answerable = f ≥ 0.25--abstain: 0.10 ≤ f ≤ 0.50 gets one re-probe
3. The familiarity gate (Section 4.3).

orientation, triggers and handoffs

default Three operations sit around search. orient starts a session with a context package: the pending handoff, recent events, active triggers, top keyword matches for the project, and recent procedures. wrap_upends one by logging a session-end event and storing a handoff packet of four fields (goal, current state, open loops, next step). Triggers are a minimal form of prospective memory, the ability to remember to act when a cue recurs (Einstein & McDaniel, 1990): a trigger holds keywords and an action note, and CLI search and MCP event writes check it by substring match. Triggers move from active to fired only on an explicit call, and expire by date.

offline maintenance

Neuroscience.Complementary learning systems theory (McClelland, McNaughton & O’Reilly, 1995) explains why brains pair a fast learner with a slow one: a network that learns new items quickly overwrites old ones, so the hippocampus stores episodes quickly and trains the neocortex slowly by interleaved replay. Buzsáki (1989) proposed a two-stage model in which traces encoded during active waking are replayed during sharp-wave bursts in rest and slow-wave sleep, and Wilson and McNaughton (1994) observed co-activation patterns from waking exploration recurring in later sleep. Over time memories come to depend less on the hippocampus and more on neocortex (Squire & Alvarez, 1995; Frankland & Bontempi, 2005; reviewed by Diekelmann & Born, 2010). The synaptic homeostasis hypothesis adds that waking learning increases net synaptic strength and sleep scales it back down (Tononi & Cirelli, 2003, 2014). Kumaran, Hassabis and McClelland (2016) update the theory: information that fits an existing schema can be absorbed quickly, as Tse et al. (2007) showed in rats, and replay can be prioritised by goals. brainctl borrows the architecture (cheap fast writes, expensive offline restructuring) and several of its operations. It does not replay neural sequences, and its “sleep” is a batch job.

decay

opt-in The consolidation-cycle command decays each memory’s confidence exponentially from its last recall, with half-lives set by temporal class: 3.5 days (ephemeral), 10 (short), 23.1 (medium) and 69.3 (long); permanent memories are exempt and semantic memories decay three times more slowly. Memories that are labile, protected or depended on are skipped. Below a confidence of 0.1 a memory is retired (soft-deleted), not destroyed. Recall resets the clock and frequent access can promote a memory to a slower class, which is the store’s version of Ebbinghaus’s (1885) observation that repetition slows forgetting. The exponential form is a simplification: Wixted and Ebbesen (1991) found human retention is better fit by a power function. experimental A spaced-review scheduler modelled on the spacing effect (Cepeda et al., 2006) is present but not called.

consolidation and the dream cycle

opt-in Two batch pipelines run outside the request path. The default consolidation-cycle computes importance weights, locks frequently recalled high-confidence memories as protected, reclassifies temporal classes, applies decay, retires the lower-confidence member of near-duplicate pairs, merges clusters, promotes recurring episodic content to semantic memory, mines causal chains between events, and runs a Hebbian pass. Its --phased variant follows the sleep framing more literally:

  1. tagging.Memories inside their labile window are tagged and exempted from downscaling for three cycles, after synaptic tagging and capture (Frey & Morris, 1997; Redondo & Morris, 2011).
  2. downscaling. With homeostatic pressure defined as mean confidence and a setpoint of 0.55, each untagged, non-permanent memory’s confidence is multiplied by f^(1 − importance), where f = min(0.99, 0.55 / pressure). Importance protects in the spirit of elastic weight consolidation (Kirkpatrick et al., 2017), as an analogy only: here it is a score per memory, not a Fisher-weighted penalty on parameters.
  3. replay. Episodic memories written within two hours of a high-importance event are selected by salience and have their recall counters bumped.
  4. schema promotion. Episodic memories linked to three or more entities are promoted to long-lived semantic memories, after the finding that schema-consistent information consolidates faster (Tse et al., 2007).
  5. REM and Hebbian passes, as in the dream cycle below.

Two further phases, a coupling gate and a de-overlap pass, currently report counts without changing any rows.

The dream-cycle command (also run by an opt-in daemon after 300 seconds idle or 50 new memories) has three phases. NREM replays the most recalled memories with a reconsolidation-style confidence boost that shrinks with recall count, strengthens edges between memories retrieved within 60 seconds of each other (Hebb, 1949), weakens edges idle for 30 days and prunes the weakest. REM looks for cross-scope pairs of memories with cosine ≥ 0.70 and records up to 20 candidate connections as hypotheses with a seven-day incubation period; despite the name it calls no LLM, and its hypotheses are templated text. An insight phase runs label-propagation community detection (Raghavan et al., 2007) and betweenness centrality (Brandes, 2001) and writes short notes about bridge nodes.

contradictions

opt-in The consolidation cycle retires the lower-confidence member of highly similar memory pairs and adds 1 to its β; memories with importance above 0.7 need similarity above 0.9 before they can lose. experimentalA credibility-weighted conflict resolver (posterior mean × recall × age × trust × expertise) and a belief “superposition and collapse” module exist as manual tools. Earlier versions of this paper described this as AGM belief revision (Alchourrón, Gärdenfors & Makinson, 1985). That overstated it: the resolver selects a winner by score and does not satisfy the AGM postulates, and neither tool runs on the default path.

sessions, handoffs and multiple agents

Every write carries an agent_id and a scope string such as global or project:api-v2, and the write gate compares a candidate only with memories of the same agent, scope and category. Scopes are filters the caller passes; they are not access control. CLI search spans all agents and scopes, MCP search takes an optional scope, and the visibility and read_acl columns are not enforced. Agents sharing a brain therefore share its contents. Handoff packets are plain rows: earlier versions of this paper said they were signed, which they are not.

experimentalA theory-of-mind layer, after the false-belief tradition in psychology (Premack & Woodruff, 1978; Wimmer & Perner, 1983; Baron-Cohen, Leslie & Frith, 1985) and its machine-learning counterpart (Rabinowitz et al., 2018), lets one agent record what it believes another agent believes, scan for gaps against that agent’s tasks, and inject a corrective memory. The tools work end to end, but they are manual: a belief counts as stale after 24 hours regardless of what has changed. The design’s intended payoff, flagging an agent’s belief as stale the moment a write changes the underlying fact and queueing a correction before that agent acts, is not implemented (issue #156).

the subsystem layer

Version 2.8.0 added a layer of 27 subsystems named after brain regions and nuclei: locus coeruleus, nucleus basalis, ARAS, habenula, VTA, raphe, septum, claustrum, colliculi, mammillary bodies, olfactory, CA1, sleep architecture, memory aging, workspace bandwidth, connectome, basal ganglia, cerebellum, thalamus, amygdala, hippocampal subfields, ACC, default mode network, drives, insula, PFC and entorhinal cortex. Each draws on a literature (for example, the adaptive-gain theory of the locus coeruleus, Aston-Jones & Cohen, 2005; dopamine as reward prediction error, Schultz, Dayan & Montague, 1997; the habenula as a source of negative reward signals, Matsumoto & Hikosaka, 2007; the global workspace, Baars, 1988; Dehaene & Naccache, 2001), and each has its own state tables and actions behind the subsystem_* dispatchers.

what the subsystem does todaysubsystems
changes what is writtenhippocampal pattern separation (implemented in the shared write gate, Section 3.2)
observes every MCP call and logs predictions, without altering resultsbasal ganglia, cerebellum
state, telemetry and manual actionsthe other 24

We report this plainly because the names invite a stronger reading. The layer is a research scaffold: a place to try mechanisms against real traffic. A mechanism moves into Sections 3 to 5 when it changes what is written or retrieved and a benchmark shows the effect, as pattern separation did in 2.9.0. Separately, a neuromodulation_state record does feed search, setting the recency decay rate and an exploration bias.

threat model and provenance

The main threat to a persistent agent memory is poisoning. Indirect prompt injection (Greshake et al., 2023) delivers instructions through content the agent reads; an agent that writes what it reads to memory carries the injection into every later session that retrieves it.

What helps today:

What does not exist yet, though earlier versions of this paper implied it:

evaluation

methodology

Every number below comes from a baseline file committed under tests/bench/baselines/ and is reproducible with python3 -m tests.bench.run. All runs are retrieval-only: there is no answer generator and no LLM judge, so the numbers measure whether brainctl returns the right evidence, not whether an agent answers correctly. Each conversation or question gets a fresh database. CI fails a change that drops P@1, P@5, Recall@5, MRR or nDCG@5 by more than 2% against the baseline (5% for the 50-question LongMemEval subset). The memory-quality suites point the embedder at a closed port, so they run keyword-only and match CI exactly; for the LongMemEval and LoCoMo baselines, whether the vector leg was active is not recorded in the files.

longmemeval

LongMemEval_S (Wu et al., 2025) places one to three evidence sessions among roughly 50 sessions of distractor history per question. Each session is ingested as one memory, and a hit is a gold session in the top k. We score the 289 questions in the four axes whose gold evidence is a session containing the answer; temporal-reasoning, knowledge-update and abstention questions are excluded because their retrieval target is less well defined, which also means this run does not test Sections 3.3 or 4.3.

axisnHit@1Hit@5MRRRecall@5
single-session-user700.9291.0000.9471.000
single-session-assistant561.0001.0001.0001.000
single-session-preference300.3670.8330.6000.833
multi-session1330.8870.9930.9290.855
overall2890.8650.9790.9130.916

Source: longmemeval.json (re-baselined October 2026). nDCG@5 0.880, Hit@10 0.990, Recall@10 0.961.

Three axes nearly saturate because the gold session contains the answer’s words. Preferences are the weak axis: “I prefer X” is short and lexically generic against long distractor sessions.

locomo

LoCoMo (Maharana et al., 2024) has 10 long conversations (5,882 turns in the public file). Each turn is ingested as one memory and a hit is a gold evidence turn in the top k; 1,982 of the 1,986 questions carry usable evidence IDs.

categorynHit@1Hit@5MRRRecall@5
single-hop8410.4070.6500.5120.634
multi-hop2820.2270.4650.3390.252
temporal3210.4640.6600.5520.636
open-domain920.1520.3700.2460.257
adversarial4460.3920.6500.5020.641
overall1,9820.3750.6130.4790.564

Source: locomo.json. nDCG@5 0.474, Hit@10 0.691, Recall@10 0.635. Category names follow the counts in the ACL paper (841 single-hop, 282 multi-hop, 321 temporal, 96 open-domain, 446 adversarial); the harness and its baseline file label categories 1, 3 and 4 differently, which we will correct there.

LoCoMo is much harder for keyword retrieval than LongMemEval. Evidence is a single short turn among about 590, questions often paraphrase the turn, and multi-hop questions need several turns at once. Before the 2.8.1 index fixes the same harness scored Hit@1 of 0.025, because metadata updates were silently eroding the FTS index; that regression is now gated.

memory-quality suites

The 2.9.0 mechanisms change how the store behaves as it is written to, which static retrieval benchmarks do not exercise. Three suites write through the real CLI path (and the MCP path, for deduplication) and query through the real search pipeline. They are small and purpose-built: they demonstrate that each mechanism does what it claims, and they gate regressions; they are not estimates of real-world rates.

suitemeasure2.8.x2.9.0
dedup (32 pairs)exact and surface duplicates suppressed (12)CLI only1.00
false merges of near-miss pairs (12)0.1670.00
paraphrases suppressed (8)—0.00
temporal (12 facts, 15 queries)latest-value P@1, --supersedes0.001.00
stale value in top 5, --supersedes1.000.00
latest-value P@1, plain re-add0.001.00
abstention (30 queries)AUROC, familiarity—0.996
AUROC, raw top BM25 / normalised top score—0.868 / 0.563
abstention precision / recall, --abstain— / 0.1251.00 / 0.688
false abstentions; answerable P@1—0.00; 1.00

Sources: memory_dedup.json, memory_temporal.json, memory_abstention.json; 2.8.x figures from the 2.9.0 changelog. The 2.8.x abstention recall is the rate at which an unanswerable query happened to return no hits.

internal search quality and latency

A 20-query fixture across seven query types gates the search pipeline itself: P@1 0.80, MRR 0.867, nDCG@5 0.861, Recall@5 0.85 (search_quality.json). Temporal queries are its weakest category (P@1 0.0 on two queries).

operation (p50, ms)1001,00010,000
Brain.remember (no embedding)0.460.440.48
Brain.search, keyword5.816.3190
MCP memory_search, in process5.818.9320
Brain.orient4.614.6458
CLI search, cold process132140422

Source: latency.json, macOS, Python 3.14, 100 runs per cell, no embedder, measured April 2026 before the 2.8.1 and 2.9.0 changes, so it predates the familiarity gate.

Writes are sub-millisecond without embeddings. Search and orientation grow roughly linearly with store size and pass 100 ms near 10,000 memories, so “sub-millisecond hot path” claims in earlier versions were wrong for large stores. The per-agent cap of 10,000 active memories (retiring down to 8,000) bounds this today; making search sublinear is listed in Section 11.

comparing with published numbers

Published LoCoMo and LongMemEval results for other systems are end-to-end QA accuracy under an LLM judge, usually with the adversarial category dropped and with different answer models, judges and configurations. Even those papers disagree about each other’s numbers (Section 10.1). Retrieval Hit@k is a different quantity. We therefore put no brainctl figure beside another system’s. A same-fixture harness for six other memory systems exists under tests/bench/competitor_runs/; we will report it once every system runs with the same answer model and a named judge.

agent memory systems

MemGPT / Letta (Packer et al., 2023) treats the context window like an operating system treats RAM: a working context and message queue in the prompt, recall and archival storage outside it, and the LLM itself paging data in and out through function calls. Memory management is LLM tool use; in brainctl it is deterministic code. MemGPT also introduced the DMR benchmark, now close to saturated.

Mem0(Chhikara et al., 2025) extracts salient facts from conversations with an LLM and uses an LLM to decide how each fact updates the store, with an optional graph variant. On LoCoMo (adversarial category excluded, GPT-4o-mini throughout, 10 runs) it reports an LLM-judge score of 66.88 against 52.90 for OpenAI’s memory and 72.90 for a full-context baseline, with 91% lower p95 latency than full context. Zep’s team disputes the setup used for Zep in that comparison and reports 75.14 for its own configuration (Chalef & Rasmussen, 2025), and Letta reports 74.0 for a plain file-tool agent (Letta, 2025). We cite these to show how setting-dependent the numbers are, not to rank anyone.

Zep / Graphiti (Rasmussen et al., 2025) builds a temporal knowledge graph of episodes, entities and communities, with LLM extraction and two timelines per edge. It is the nearest relative of brainctl’s supersession. It reports 94.8% on DMR and, on LongMemEval_S with a GPT-4o judge, 71.2% against 60.2% for full context with GPT-4o, at about 90% lower latency.

A-MEM (Xu et al., 2025) builds Zettelkasten-style notes whose keywords, tags and links an LLM writes, and lets new notes rewrite old ones. brainctl never rewrites a stored memory in place. Generative Agents (Park et al., 2023) introduced the memory stream with retrieval by recency, LLM-rated importance and relevance, plus periodic reflection. MemoryBank (Zhong et al., 2024) applies an Ebbinghaus-style forgetting curve to a companion chatbot’s memories. Reflexion (Shinn et al., 2023) stores verbal self-reflections for later attempts. HippoRAG(Gutiérrez et al., 2024) and HippoRAG 2 (Gutiérrez et al., 2025) borrow hippocampal indexing theory, using an LLM-built knowledge graph and Personalized PageRank as the index. MemoryOS (Kang et al., 2025) and MIRIX (Wang & Chen, 2025) organise memory into tiers or typed stores managed by LLM agents.

LLM in write pathstoragetime model
MemGPT / Lettayesserver + DBmessage timestamps
Mem0yesvector DB (+ graph)LLM-decided updates
Zep / Graphitiyesgraph DB servicebi-temporal edges
A-MEMyesvector storenotes evolve in place
brainctlnoone SQLite filebi-temporal rows, PII-gated

Summarised from each system’s paper; products change faster than papers.

The trade-off is real in both directions. An LLM in the write path can detect that two differently worded notes contradict each other, merge paraphrases, and extract facts from raw dialogue; brainctl cannot, unless the writer names the superseded memory or embeddings are on. In exchange, brainctl’s writes cost no model calls, give the same answer every time, and can be audited.

benchmarks

LongMemEval (Wu et al., 2025) tests five abilities, including knowledge updates and abstention (30 of its 500 questions), with a GPT-4o judge reported at over 97% agreement with human experts. LoCoMo (Maharana et al., 2024) supplies 10 very long conversations with QA, summarisation and multimodal tasks; most memory papers drop its adversarial category. MSC (Xu, Szlam & Weston, 2022) introduced long-term multi-session chat. Section 9.6 explains why we report retrieval metrics only, for now.

surveys

Zhang et al. (2024), Wu et al. (2025b), Du et al. (2025) and Hu et al. (2025) survey memory in LLM agents. Du et al.’s six operations (consolidation, updating, indexing, forgetting, retrieval and condensation) map onto this paper: consolidation and condensation onto Section 5, updating onto Sections 3.2 and 3.3, indexing and retrieval onto Section 4, forgetting onto Section 5.1.

limitations and future work

  1. No end-to-end evaluation. Every result is retrieval-only. The next step is LongMemEval_S end to end, including its knowledge-update and abstention questions, which test Sections 3.3 and 4.3 directly, and LoCoMo with the adversarial category kept, all with a named judge and every compared system in one harness.
  2. Small memory-quality suites. 32 pairs, 15 queries and 30 queries are enough to show the mechanisms work and to catch regressions, not to estimate error rates on real traffic.
  3. Lexical deduplication. Without embeddings, paraphrases are stored separately, and contradiction is detected only when the writer names the superseded memory.
  4. Three write paths. Brain.remember bypasses the write gates and MCP writes skip entity linking. All three should share one path.
  5. Confidence without outcomes. α and β count retrievals, not successes. Feeding task outcomes back is the obvious extension, and the Q-value column is ready for it.
  6. Packaging. Thompson sampling, salience routing, the amplitude reranker and the embedding-based write gate load from paths outside the package, so a standard install does not run them. They need packaging and a benchmark, or removal.
  7. Scaling. Search passes 100 ms around 10,000 memories. Candidate pruning before reranking and an index on the familiarity statistics are the first targets.
  8. Theory of mind. The automatic staleness hook (issue #156): when a write changes a fact, find agents whose recorded beliefs depend on it, open a conflict and queue a correction.
  9. Event-log noise. Accidental event writes have no lifecycle or suppression controls (issue #155).
  10. Isolation and trust. Read access control between agents, a write-time quarantine for untrusted sources, and signed writes.
  11. Subsystems. Each of the 24 state-only subsystems should either earn a place in the write or read path with a measured effect, or be documented as telemetry.

references

back