Zenbrain agent

Zenbrain — ZenBrain Playground Demo (from the zensation-ai/zenbrain skill folder)

Illustration · not a resultImage from zensation-ai's README.mdsource ↗

Dynamic agent memory for LLM agents: 7 neuroscience-inspired layers (working, episodic, semantic, procedural) with FSRS spaced repetition and memory consolidation.

by zensation-ai·Apache-2.0 license·★ 26 Stars on the repo·GitHub ↗

Files of Zenbrain

zensation-ai/main1 file
README.md
Show the full text555 lines

ZenBrain

The neuroscience-inspired memory system for AI agents.

7 memory layers and a library of 20 neuroscience-inspired algorithm modules: FSRS, Hebbian learning, sleep replay, emotional tagging, plus 10 advanced research modules (vmPFC-FSRS, two-factor Hebbian, simulation-selection sleep, Fiedler-value KG health, IB budget, Hopfield STM, ...).
Pure TypeScript. Zero dependencies. 822 tests. Extracted from a production AI platform.

npm version npm downloads CI License TypeScript Zero Dependencies

Status: pre-1.0, semver — the public API can still change before 1.0.
822 tests green in CI, on Node 22, 24 and 26 and against PostgreSQL with pgvector · the current version of every package published to npm with build provenance · every change recorded in the CHANGELOG · issues and pull requests are answered; replications and counter-results are especially welcome.

Self-hosted: the library makes no network calls of its own. Memory lives in SQLite or PostgreSQL that you operate; an embedding model or an LLM is optional and your choice.


ZenBrain Playground Demo

▶ Try the live playground in your browser — runs this published code, no install required.

📄 Paper & Citation — ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture for Autonomous AI Systems
@misc{bering2026zenbrain,
  title         = {ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture for Autonomous AI Systems},
  author        = {Bering, Alexander},
  year          = {2026},
  eprint        = {2604.23878},
  archivePrefix = {arXiv},
  primaryClass  = {cs.AI},
  doi           = {10.5281/zenodo.19353663},
  url           = {https://arxiv.org/abs/2604.23878}
}

Feedback, replications, and counter-results are explicitly welcome — please open an issue or reach out via [email protected].

Your AI forgets everything after every conversation. ZenBrain gives it a memory that lasts across sessions, split into layers the way human memory is, and ships the mechanisms memory research describes (spaced repetition, emotional tagging, Hebbian strengthening, forgetting curves, sleep replay) as tested functions. Which of them run on their own and which you call yourself is in one table.

Architecture vs. this package. ZenBrain's architecture is 15 neuroscience-inspired mechanisms — 9 foundational algorithms + 6 Predictive Memory Architecture (PMA) components (paper). The 6 PMA components are proprietary and run in the production system. This open-source package ships the algorithm library: 10 core algorithms + 10 advanced research modules (20 modules), zero-dependency.


Benchmark: LongMemEval-500

On LongMemEval-500, three of nine head-to-head comparisons hold against Letta, Mem0 and A-Mem — all three against A-Mem, the remaining six are ties, none lost. Three competitors x three LLM judges, Bonferroni-corrected (alpha = 0.05/18) and version-matched. It reaches 91.3% of a full-context oracle's binary-judge accuracy at 1/109.6 of the per-query token cost (47.7% vs. 52.2%).

Works out of the box without an embedding provider — lexical ranking, zero dependencies. With nomic-embed-text as the embedding provider you get the configuration those figures were measured in.

The paper prints where ZenBrain loses as well: on LoCoMo, substring-based aggregate F1 favours lexical retrieval (BM25) by metric design, and we do not contest that. The advantage is most pronounced in the judge-graded comparisons and on cross-session reasoning.

The mechanism comparison further down re-runs from this repository in under a minute — bash scripts/compare-mechanisms.sh, no API keys and nothing to install. It prints a positive and a negative control before the result, so the instrument can be checked before its output is trusted. The method, the effect sizes and the ablations behind the numbers above are in the paper; this repository ships no runner for them. The archived packages below run the significance tests and effect sizes in full, and the mechanism ablation behind paper Tables 7–9.


Reproduction packages

The raw material behind the numbers above is deposited on Zenodo, open access and citable. Both links are concept DOIs and resolve to the latest version, the same convention this README uses for the paper archive; each description was measured against the version named after it.

  • Mechanism ablation, paper Tables 7–9 — 10.5281/zenodo.22162063 (described here: v1.0.0). Four experiment suites (95 tests), the reference JSON the paper's tables were generated from, and verify-against-reference.mjs, which diffs a fresh run against that reference and exits non-zero on drift. npm install && npm run experiments; the run itself needs no API keys and no network, and finishes in under a minute on a laptop. Two of the paper's other ablation tables need data this package does not carry: Table 11 the LoCoMo corpus, Table 13 a different pipeline. The package says so itself.
  • Measurement package, LongMemEval-500 and the real-pipeline flag ablation — 10.5281/zenodo.22161977 (described here: v1). Per-(system, judge, seed) judged outputs, the flag manifests as recorded at run time, a SHA256SUMS.txt covering every file in the package, and the analysis scripts. Three of those scripts are stdlib-only and self-checking — the oracle comparison behind the 91.3% figure, the judge-agreement figures, and the real-pipeline flag-ablation table: each prints every re-derived value next to the reference it has to match, and exits non-zero on mismatch. The significance tests behind the nine head-to-head comparisons against Letta, Mem0 and A-Mem sit in a separate script that needs numpy and scipy; it recomputes all eighteen pairwise tests and rewrites the deposited significance JSON byte-identically, so what catches a mismatch there is the checksum, not an exit code.

Both packages name what they do not cover. Replications and counter-results are welcome: [email protected].


How ZenBrain differs from Mem0, Letta and Zep

ZenBrain implements fifteen mechanisms taken from human memory research. No system among those surveyed in the paper integrates more than two of them. The table below records which of the mechanisms appear in the public source of three widely used memory systems, at pinned versions, on a fixed date.

Mechanism ZenBrain Mem0 Letta Zep
FSRS spaced repetition yes — — —
Hebbian learning yes — — —
Ebbinghaus forgetting curves yes — — —
Sleep consolidation yes — — —
Emotional tagging yes — — —
Zero runtime dependencies yes — — —

How this was measured, 27 August 2026. Full-text search over the checked-out public source of mem0ai/mem0 (npm mem0ai 3.1.7, PyPI mem0ai 2.0.19), letta-ai/letta-code (npm @letta-ai/letta-code 0.31.2) and getzep/zep, lockfiles excluded. A dash means the term does not occur in that snapshot — not that the system cannot do something comparable under another name. One case we know of: Letta Code revises memory in the background and calls it "dreaming" (sleep-time compute), which the term search for sleep consolidation does not match. In ZenBrain the mechanisms in this table are library functions; which of them the coordinator runs is in this table. Dependency counts are declared direct dependencies: @zensation/core resolves to two packages, both our own; mem0ai declares four, @letta-ai/letta-code eighteen. Re-run the whole check yourself with scripts/compare-mechanisms.sh; it prints its own positive and negative controls so you can see the instrument works before you trust the result.

Human memory does not work like a key-value store. The brain keeps specialised systems for different kinds of memory, forgets actively, modulates by emotion and retrieves by context. ZenBrain brings those mechanisms to AI agents, as a memory system with seven layers and as a library of the algorithms behind them.

Advanced algorithms (since v0.3.0, May 2026)

On top of the 10 core algorithms above, @zensation/algorithms ships 10 advanced algorithms grounded in recent neuroscience and ML research. Each is exposed as its own sub-path (@zensation/algorithms/<name>) and remains zero-dependency:

  • fsrs-vmPFC — Prediction-Error coupled FSRS
  • hebbian-two-factor — Two-Factor synaptic consolidation
  • sleep-simulation-selection — RL-based replay selection
  • spectral-health — Fiedler-value KG health monitor
  • ib-budget — Information-Bottleneck retention budget
  • dopamine-routing · hopfield-stm · personalized-pagerank · surprise-gradient-memory · temporal-multi-route

See CHANGELOG.md for details.

What runs on its own, and what you call yourself

@zensation/core is a memory system: the MemoryCoordinator stores, recalls, consolidates and forgets. @zensation/algorithms is a library of twenty modules of tested functions, and the coordinator calls only a few of them. Several mechanisms named in this README live in the library alone; you wire them into your own system where you want them.

Mechanism The coordinator (@zensation/core) The library (@zensation/algorithms)
Layers Seven layer classes. recall() searches episodic, semantic, procedural and core memory, working memory on request; the cross-context layer is not part of recall. —
Routing store() picks the layer: step-by-step content becomes a procedure, an emotional weight above 0.5 an episode, a confidence above 0.9 a pinned core block, anything else a fact. —
Emotional tagging At every store(). The weight decides episode or fact, and which episodes consolidation promotes. tagEmotion, computeEmotionalWeight
Spaced repetition (FSRS) Every fact gets an FSRS schedule. getReviewQueue() lists the due facts; a review your application reports with recordReview() updates the schedule. Recall does not rank by retrievability. FSRS, prediction-error-coupled FSRS
Forgetting Nothing in long-term memory decays or is deleted on its own; forget(id, layer) deletes on request. Working memory decays (Ebbinghaus). Ebbinghaus retention, personal decay profiles
Consolidation consolidate() turns each emotionally weighted episode into a fact, once. Sleep replay (selectForReplay, simulateReplay, pruneWeakConnections), simulation-selection loop
Hebbian learning Not used: core keeps no knowledge graph. Classic and two-factor Hebbian
Bayesian confidence Not used. propagateForRelation and the rest of the module
Context-dependent retrieval Not used. The includeContext option never had an effect and was withdrawn in 0.5.0. captureEncodingContext, calculateContextSimilarity

The six Predictive Memory Architecture components of the paper are in neither package (see Architecture vs. this package above).

Quick Start

Requires Node.js 22 or newer (since 0.4.0). On Node 20 or older, npm silently installs the last compatible release (@zensation/[email protected], @zensation/[email protected]) instead of the current one — which looks like a broken package but is a platform mismatch. See CHANGELOG.

npm install @zensation/algorithms
import {
  initFromDecayClass,
  getRetrievability,
  updateAfterRecall,
  tagEmotion,
  computeEmotionalWeight,
  computeHebbianStrengthening,
  propagateForRelation,
} from '@zensation/algorithms';

// 1. Schedule a memory with FSRS
const memory = initFromDecayClass('normal_decay');

// 2. A week later, check recall probability (Ebbinghaus curve)
const aWeekLater = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
const retention = getRetrievability(memory, aWeekLater);
console.log(`Recall probability: ${(retention * 100).toFixed(1)}%`);
// ~36.8% — retrievability has decayed over the week

// 3. User recalled it anyway — update scheduling
const updated = updateAfterRecall(memory, 4, retention, aWeekLater);
// stability 7 -> 8.19: recalling at low retrievability gives a bigger boost

// 4. Tag emotional significance
const emotion = tagEmotion('I am absolutely thrilled — I got the promotion!');
const weight = computeEmotionalWeight(emotion);
console.log(`Decay multiplier: ${weight.decayMultiplier}x`);
// 2.7x — emotional memories decay nearly 3x slower

// 5. Strengthen knowledge connections (Hebbian)
const stronger = computeHebbianStrengthening(1.0);
// 1.09 — "neurons that fire together wire together"

// 6. Propagate confidence through your knowledge graph
const confidence = propagateForRelation(0.5, 0.8, 1.0, 'supports');
// 0.9 — supporting evidence increases confidence
Want the advanced algorithms?
import {
  computeKGPredictionError,
  computeAdaptiveFSRSInterval,
} from '@zensation/algorithms/fsrs-vmPFC';

// Couple FSRS scheduling with the prediction-error signal from your
// knowledge graph: when the embedding has shifted a lot since the last
// review (high cosine distance), shrink the next interval; otherwise push
// it out. Both arrays must have the same length.
const lastEmbedding = [0.1, 0.2, 0.3, 0.4];
const currentEmbedding = [0.5, 0.4, 0.1, 0.2];
const pe = computeKGPredictionError(lastEmbedding, currentEmbedding);
const nextInterval = computeAdaptiveFSRSInterval(14, pe);

Each advanced algorithm has its own sub-path (@zensation/algorithms/spectral-health, @zensation/algorithms/ib-budget, …). All zero dependencies.

Runnable examples

Seven self-contained examples live in examples/:

Example Shows
basic-chatbot.ts Working Memory + Short-Term Memory for conversation context — no SDK needed
with-claude.ts An Anthropic Claude assistant that remembers across conversations
with-langchain.ts ZenBrain as the memory backend of a LangChain agent
with-crewai.ts Multiple agents sharing Working Memory, with Hebbian strengthening
with-vercel-ai.ts A memory-aware system prompt for the Vercel AI SDK streamText pattern
with-llamaindex.ts ZenBrain as long-term memory for a LlamaIndex.TS agent — LlamaIndex keeps the short-term window, ZenBrain decides what outlives it
with-mastra.ts ZenBrain behind a Mastra agent: a Processor records each turn, and the instructions are rebuilt from what is currently recallable
npx tsx examples/basic-chatbot.ts

The integration examples additionally need their respective SDK installed; examples/README.md lists which. Open good first issues are the best way in if you want to contribute.

The Science Behind It

7-Layer Memory Architecture
Layer 7: Cross-Context Memory    ← Shared knowledge across domains
Layer 6: Core Memory             ← Pinned facts (Letta-style)
Layer 5: Procedural Memory       ← "How to do X" (skills & workflows)
Layer 4: Long-Term Semantic      ← Facts with FSRS scheduling
Layer 3: Episodic Memory         ← Concrete experiences & events
Layer 2: Short-Term / Session    ← Current conversation context
Layer 1: Working Memory          ← Active task focus (7±2 items)

Each layer holds a different kind of memory and is stored and searched in its own way.

FSRS Spaced Repetition

FSRS (Free Spaced Repetition Scheduler) outperforms SM-2 by 30%. It uses the desirable difficulty principle: reviewing when retention is low gives a bigger stability boost. In @zensation/core every fact gets an FSRS schedule; your application reports each review with recordReview(), and FSRS sets the next one.

Emotional Memory

The amygdala modulates memory consolidation — emotional events are remembered more vividly (flashbulb memory). ZenBrain's emotional tagger assigns arousal, valence, and significance scores using a 400+ keyword lexicon (English & German). In the library, emotional weight stretches decay half-lives up to 3x (computeEmotionalWeight); the coordinator uses the weight to route emotional content to episodic memory and to choose what consolidation promotes.

Hebbian Learning

"Neurons that fire together wire together" (Hebb, 1949). Knowledge graph edges that are frequently co-activated grow stronger. Unused edges decay and eventually get pruned. The result: a self-organizing knowledge structure that reflects actual usage patterns, with homeostatic normalization to prevent runaway growth. These are library functions; @zensation/core keeps no knowledge graph, so you apply them to a graph of your own.

Ebbinghaus Forgetting Curves

Ebbinghaus (1885) showed that memory decays exponentially: R = e^(-t/S). The library implements personalized decay profiles that adapt to individual learning patterns, with SM-2 compatibility for existing spaced repetition systems. In the coordinator, only working memory decays.

Context-Dependent Retrieval

Tulving's Encoding Specificity Principle (1973): memories are recalled better when the retrieval context matches the encoding context. The library captures temporal context (time of day, day of week) and task type, and calculateContextSimilarity turns a match between a stored and the current context into a retrieval boost of up to 30%. The coordinator stores no encoding context; its includeContext option never had an effect and was withdrawn in 0.5.0.

Bayesian Confidence Propagation

Knowledge isn't isolated — facts support or contradict each other. The library propagates confidence through a knowledge graph you keep, using Bayesian belief updates: supporting evidence increases confidence, contradictions decrease it, with damping for numerical stability.

Sleep Consolidation

During sleep, the hippocampus replays recent experiences, strengthening important memories and pruning weak connections (Stickgold & Walker, 2013). ZenBrain simulates this process: selectForReplay() prioritizes emotional and recently-accessed memories, simulateReplay() boosts their stability by 50%, and pruneWeakConnections() removes weak Hebbian edges — implementing the Synaptic Homeostasis Hypothesis (Tononi & Cirelli, 2006). The coordinator's consolidate() does not run this replay; it turns emotionally weighted episodes into facts, once each.

import { selectForReplay, simulateReplay } from '@zensation/algorithms/sleep-consolidation';

// Select memories for overnight consolidation
const toReplay = selectForReplay(allMemories);
// Simulate sleep replay — stability ↑, weak edges pruned
const result = simulateReplay(toReplay);
console.log(`Replayed ${result.summary.totalReplayed} memories, avg stability +${result.summary.avgStabilityIncrease.toFixed(1)} days`);
Memory Coordinator

The MemoryCoordinator puts the layers behind one API — inspired by Global Workspace Theory (Baars, 1988):

import { MemoryCoordinator } from '@zensation/core';

const memory = new MemoryCoordinator({ storage: adapter, embedding: embedder });

// Auto-routes to the right layer (semantic, episodic, procedural, or core)
await memory.store('User prefers TypeScript', { type: 'auto' });

// Cross-layer search with ranked, deduplicated results
const results = await memory.recall('programming preferences');

// Forget one memory for good, by the id and layer of a recall result
await memory.forget(results[0].id, results[0].layer);

// Consolidate: emotionally weighted episodes become facts, once each; working memory decays
await memory.consolidate();

// Facts whose FSRS review is due; report each review with recordReview()
const dueItems = await memory.getReviewQueue();

Packages

Package Description Status
@zensation/algorithms · source 20 algorithm modules — 10 core (FSRS, Hebbian, Ebbinghaus, emotional, Bayesian, sleep consolidation, intervals, visualization) + 10 advanced (vmPFC-FSRS, two-factor Hebbian, IB budget, Hopfield STM, …) :white_check_mark: Published
@zensation/core · source Memory layers, coordinator, adapter interfaces :white_check_mark: Published
@zensation/adapter-postgres · source PostgreSQL + pgvector storage adapter :white_check_mark: Published
@zensation/adapter-sqlite · source SQLite storage adapter (zero-config) :white_check_mark: Published
@zensation/mcp · source MCP server — gives any MCP client (Claude Desktop, Claude Code, Cursor) the seven layers as four tools. Carries the protocol SDK, so the core stays dependency-free :white_check_mark: Published
@zensation/ai-sdk · source Vercel AI SDK middleware — recall before the model call, store after it. Works with any provider, zero runtime dependencies :white_check_mark: Published
Tree-Shakeable Imports

Every algorithm is available as a subpath export:

// Import everything
import { tagEmotion, updateAfterRecall } from '@zensation/algorithms';

// Or just what you need (better tree-shaking)
import { updateAfterRecall } from '@zensation/algorithms/fsrs';
import { tagEmotion } from '@zensation/algorithms/emotional';
import { computeHebbianStrengthening } from '@zensation/algorithms/hebbian';
import { propagateForRelation } from '@zensation/algorithms/bayesian';
import { selectForReplay } from '@zensation/algorithms/sleep-consolidation';
import { getRetrievabilityWithCI } from '@zensation/algorithms/intervals';
import { generateRetentionCurve } from '@zensation/algorithms/visualization';

Use Cases

AI Chatbots with Long-Term Memory
import { updateAfterRecall, getRetrievability, scheduleNextReview } from '@zensation/algorithms/fsrs';
import { tagEmotion, computeEmotionalWeight } from '@zensation/algorithms/emotional';

// When your AI learns a fact about the user:
function rememberFact(fact: string) {
  const memory = initFromDecayClass('normal_decay');
  const emotion = tagEmotion(fact);
  const weight = computeEmotionalWeight(emotion);

  // Emotional facts get longer retention
  return {
    ...memory,
    emotionalWeight: weight.consolidationWeight,
    decayMultiplier: weight.decayMultiplier,
  };
}

// Before each conversation, check what needs reinforcement:
function getFactsDueForReview(facts: MemoryState[]) {
  return facts.filter(f => getRetrievability(f) < 0.7);
}
Knowledge Graph with Self-Organizing Edges
import { computeHebbianStrengthening, computeHebbianDecay } from '@zensation/algorithms/hebbian';
import { propagateForRelation } from '@zensation/algorithms/bayesian';

// When two concepts are mentioned together:
function coActivate(edge: { weight: number }) {
  edge.weight = computeHebbianStrengthening(edge.weight);
}

// Periodic maintenance — decay unused edges:
function decayEdges(edges: { weight: number; lastUsed: Date }[]) {
  for (const edge of edges) {
    edge.weight = computeHebbianDecay(edge.weight);
    // Edges below MIN_WEIGHT (0.1) can be pruned
  }
}
RAG with Confidence Scoring
import { propagateForRelation, isSignificantChange } from '@zensation/algorithms/bayesian';

// After retrieval, propagate confidence through related facts:
function updateConfidenceGraph(facts: Fact[], relations: Relation[]) {
  for (const rel of relations) {
    const newConf = propagateForRelation(
      rel.target.confidence,
      rel.source.confidence,
      rel.weight,
      rel.type // 'supports' | 'contradicts' | 'related_to'
    );
    if (isSignificantChange(newConf, rel.target.confidence)) {
      rel.target.confidence = newConf;
    }
  }
}

Extracted From Production

These aren't toy implementations — ZenBrain's algorithms are extracted from ZenAI, a production AI platform. Everything claimed here is verifiable in this repository:

  • 822 tests (489 algorithms · 138 core · 61 adapter-sqlite · 54 adapter-postgres, 6 of them against a real PostgreSQL · 58 mcp · 22 ai-sdk), all passing
  • Zero runtime dependencies — pure TypeScript, dual ESM + CJS, tree-shakeable subpath exports
  • Reproducible — building from this source produces the same 153-file @zensation/[email protected] tarball published on npm
  • 7-layer memory architecture grounded in published neuroscience

Contributing

We welcome contributions! See CONTRIBUTING.md for guidelines. Issues and pull requests are answered; replications and counter-results are especially welcome.

Resources: API Reference | Recipes | Architecture | Benchmarks | FAQ | Roadmap

# Clone the repo
git clone https://github.com/zensation-ai/zenbrain.git
cd zenbrain

# Install dependencies
npm install

# Run tests
npm test

# Build all packages
npm run build

Research

ZenBrain's architecture and algorithms are documented in an open-access technical disclosure:

If you use ZenBrain in academic work, please cite:

@misc{bering2026zenbrain,
  title         = {ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture for Autonomous AI Systems},
  author        = {Bering, Alexander},
  year          = {2026},
  eprint        = {2604.23878},
  archivePrefix = {arXiv},
  primaryClass  = {cs.AI},
  doi           = {10.5281/zenodo.19353663},
  url           = {https://arxiv.org/abs/2604.23878}
}

Cited by

Five works cite ZenBrain (as of 28 September 2026): a survey by the Sico team at Microsoft Research, MindMemOS by Huawei's Noah's Ark Lab, the EVD preprint, the HindsightTag manuscript and the Lamperouge manifesto.

  • Agentic Evolution: From Self-Improving Agents to Co-Evolving Human-AI Systems, a survey by the Sico team at Microsoft Research (2026), calls forgetting "critically understudied": very few of the roughly 100 Memory & Sense papers it surveys implement explicit forgetting. It lists ZenBrain as one of four works in its forgetting/lifecycle group and as its only source for sleep-based consolidation.
  • MindMemOS (Huawei's Noah's Ark Lab, arXiv:2608.12428, August 2026) relies on exactly three references for the foundational claim of its introduction: two field surveys and a single system paper — ZenBrain.
  • HindsightTag (Vivek Govindbhai Dudhat, manuscript, July 2026, revised 30 September 2026) discusses ZenBrain as its closest prior system and uses its MemoryCoordinator interface as the integration example.
  • EVD: An Emotional Valence Dimension for Persistent Agent Memory (R. J. Vandelinder and I. Vandelinder, Exile Research, Zenodo, June 2026) places ZenBrain in its related work.
  • The field measures the wrong thing (Lamperouge, manifesto, Zenodo, August 2026) selects ZenBrain among six works on persistent internal state and notes that its "days" are simulation steps.

Each work with the sentence that cites ZenBrain: zensation.ai/en/publikationen.

Projects that build the library into their code:

  • ACMS reads and writes the ZenBrain SQLite database directly.
  • neurograph-runtime uses the FSRS implementation of @zensation/algorithms as the ranking and feedback layer of a knowledge base on radiotherapy literature.

Citing ZenBrain or building on it? Open an issue and we will add you here.

Community

License

Apache 2.0 — use it in production, modify it, distribute it. Just keep the attribution.


Built by ZenSation in Kiel, Germany.

1<p align="center">
2 <h1 align="center">ZenBrain</h1>
3 <p align="center"><strong>The neuroscience-inspired memory system for AI agents.</strong></p>
4 <p align="center">7 memory layers and a library of 20 neuroscience-inspired algorithm modules: FSRS, Hebbian learning, sleep replay, emotional tagging, plus 10 advanced research modules (vmPFC-FSRS, two-factor Hebbian, simulation-selection sleep, Fiedler-value KG health, IB budget, Hopfield STM, ...).<br/>Pure TypeScript. Zero dependencies. 822 tests. Extracted from a production AI platform.</p>
5</p>
6 
7<p align="center">
8 <a href="https://www.npmjs.com/package/@zensation/algorithms"><img src="https://img.shields.io/npm/v/@zensation/algorithms?color=blue&label=npm" alt="npm version"></a>
9 <a href="https://www.npmjs.com/package/@zensation/algorithms"><img src="https://img.shields.io/npm/dm/@zensation/algorithms?color=blue" alt="npm downloads"></a>
10 <a href="https://github.com/zensation-ai/zenbrain/actions/workflows/ci.yml"><img src="https://github.com/zensation-ai/zenbrain/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
11 <a href="https://github.com/zensation-ai/zenbrain/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-blue.svg" alt="License"></a>
12 <a href="https://www.typescriptlang.org/"><img src="https://img.shields.io/badge/TypeScript-5.7+-blue.svg" alt="TypeScript"></a>
13 <img src="https://img.shields.io/badge/dependencies-0-brightgreen.svg" alt="Zero Dependencies">
14</p>
15 
16<p align="center">
17 <sub><strong>Status:</strong> pre-1.0, semver — the public API can still change before <code>1.0</code>.<br/>
18 822 tests green in CI, on Node 22, 24 and 26 and against PostgreSQL with pgvector · the current version of every package published to npm with build provenance ·
19 every change recorded in the <a href="./CHANGELOG.md">CHANGELOG</a> · issues and pull requests are answered; replications and counter-results are especially welcome.</sub>
20</p>
21 
22<p align="center">
23 <sub><strong>Self-hosted:</strong> the library makes no network calls of its own. Memory lives in SQLite or PostgreSQL that you operate; an embedding model or an LLM is optional and your choice.</sub>
24</p>
25 
26---
27 
28<p align="center">
29 <img src="docs/demo.gif" alt="ZenBrain Playground Demo" width="700"/>
30</p>
31 
32<p align="center">
33 <strong><a href="https://zensation.ai/en/playground?utm_source=github&utm_medium=readme&utm_campaign=evergreen">▶ Try the live playground in your browser</a></strong> — runs this published code, no install required.
34</p>
35 
36<details>
37<summary><strong>📄 Paper & Citation</strong> — ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture for Autonomous AI Systems</summary>
38 
39<br/>
40 
41- **arXiv preprint** (cs.AI): [arxiv.org/abs/2604.23878](https://arxiv.org/abs/2604.23878)
42- **Open-access archive** (Zenodo / CERN): [doi.org/10.5281/zenodo.19353663](https://doi.org/10.5281/zenodo.19353663)
43- **ORCID**: [0009-0001-1793-012X](https://orcid.org/0009-0001-1793-012X)
44- **License**: CC BY 4.0 (paper) · Apache-2.0 (code)
45 
46```bibtex
47@misc{bering2026zenbrain,
48 title = {ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture for Autonomous AI Systems},
49 author = {Bering, Alexander},
50 year = {2026},
51 eprint = {2604.23878},
52 archivePrefix = {arXiv},
53 primaryClass = {cs.AI},
54 doi = {10.5281/zenodo.19353663},
55 url = {https://arxiv.org/abs/2604.23878}
56}
57```
58 
59Feedback, replications, and counter-results are explicitly welcome — please open an issue or reach out via [[email protected]](mailto:[email protected]).
60 
61</details>
62 
63> **Your AI forgets everything after every conversation.** ZenBrain gives it a memory that lasts across sessions, split into layers the way human memory is, and ships the mechanisms memory research describes (spaced repetition, emotional tagging, Hebbian strengthening, forgetting curves, sleep replay) as tested functions. Which of them run on their own and which you call yourself is in [one table](#what-runs-on-its-own-and-what-you-call-yourself).
64 
65> **Architecture vs. this package.** ZenBrain's architecture is **15 neuroscience-inspired mechanisms — 9 foundational algorithms + 6 Predictive Memory Architecture (PMA) components** ([paper](https://arxiv.org/abs/2604.23878)). The 6 PMA components are proprietary and run in the production system. **This open-source package ships the algorithm library: 10 core algorithms + 10 advanced research modules (20 modules), zero-dependency.**
66 
67---
68 
69## Benchmark: LongMemEval-500
70 
71On LongMemEval-500, **three of nine head-to-head comparisons hold** against
72Letta, Mem0 and A-Mem — all three against A-Mem, the remaining six are ties, none lost. Three
73competitors x three LLM judges, Bonferroni-corrected (alpha = 0.05/18) and version-matched. It
74reaches **91.3% of a full-context oracle's binary-judge accuracy at 1/109.6 of the per-query
75token cost** (47.7% vs. 52.2%).
76 
77Works out of the box without an embedding provider — lexical ranking, zero
78dependencies. With `nomic-embed-text` as the embedding provider you get the
79configuration those figures were measured in.
80 
81The paper prints where ZenBrain loses as well: on LoCoMo, substring-based aggregate F1 favours
82lexical retrieval (BM25) by metric design, and we do not contest that. The advantage is most
83pronounced in the judge-graded comparisons and on cross-session reasoning.
84 
85**The mechanism comparison further down re-runs from this repository in under a minute** —
86`bash scripts/compare-mechanisms.sh`, no API keys and nothing to install. It prints a positive
87and a negative control before the result, so the instrument can be checked before its output
88is trusted. The method, the effect sizes and the ablations behind the numbers above are in the
89paper; this repository ships no runner for them. The archived packages below run the significance
90tests and effect sizes in full, and the mechanism ablation behind paper Tables 7–9.
91 
92- Method, effect sizes and ablations: [arXiv:2604.23878](https://arxiv.org/abs/2604.23878)
93- Open-access archive: [10.5281/zenodo.19353663](https://doi.org/10.5281/zenodo.19353663)
94 
95---
96 
97## Reproduction packages
98 
99The raw material behind the numbers above is deposited on Zenodo, open access and citable. Both
100links are concept DOIs and resolve to the latest version, the same convention this README uses for
101the paper archive; each description was measured against the version named after it.
102 
103- **Mechanism ablation, paper Tables 7–9** — [10.5281/zenodo.22162063](https://doi.org/10.5281/zenodo.22162063)
104 (described here: v1.0.0). Four experiment suites (95 tests), the reference JSON the paper's
105 tables were generated from, and `verify-against-reference.mjs`, which diffs a fresh run against
106 that reference and exits non-zero on drift. `npm install && npm run experiments`; the run itself
107 needs no API keys and no network, and finishes in under a minute on a laptop. Two of the paper's
108 other ablation tables need data this package does not carry: Table 11 the LoCoMo corpus, Table 13
109 a different pipeline. The package says so itself.
110- **Measurement package, LongMemEval-500 and the real-pipeline flag ablation** —
111 [10.5281/zenodo.22161977](https://doi.org/10.5281/zenodo.22161977) (described here: v1).
112 Per-(system, judge, seed) judged outputs, the flag manifests as recorded at run time, a
113 `SHA256SUMS.txt` covering every file in the package, and the analysis scripts. Three of those
114 scripts are stdlib-only and self-checking — the oracle comparison behind the 91.3% figure, the
115 judge-agreement figures, and the real-pipeline flag-ablation table: each prints every re-derived
116 value next to the reference it has to match, and exits non-zero on mismatch. The significance
117 tests behind the nine head-to-head comparisons against Letta, Mem0 and A-Mem sit in a separate
118 script that needs numpy and scipy; it recomputes all eighteen pairwise tests and rewrites the
119 deposited significance JSON byte-identically, so what catches a mismatch there is the checksum,
120 not an exit code.
121 
122Both packages name what they do not cover. Replications and counter-results are welcome:
123[[email protected]](mailto:[email protected]).
124 
125---
126 
127## How ZenBrain differs from Mem0, Letta and Zep
128 
129ZenBrain implements fifteen mechanisms taken from human memory research. No system among those
130surveyed in the paper integrates more than two of them. The table below records which of the
131mechanisms appear in the public source of three widely used memory systems, at pinned versions,
132on a fixed date.
133 
134| Mechanism | ZenBrain | Mem0 | Letta | Zep |
135|---|:--:|:--:|:--:|:--:|
136| FSRS spaced repetition | yes | — | — | — |
137| Hebbian learning | yes | — | — | — |
138| Ebbinghaus forgetting curves | yes | — | — | — |
139| Sleep consolidation | yes | — | — | — |
140| Emotional tagging | yes | — | — | — |
141| Zero runtime dependencies | yes | — | — | — |
142 
143<sub><strong>How this was measured, 27 August 2026.</strong> Full-text search over the
144checked-out public source of <a href="https://github.com/mem0ai/mem0">mem0ai/mem0</a>
145(npm <code>mem0ai</code> 3.1.7, PyPI <code>mem0ai</code> 2.0.19),
146<a href="https://github.com/letta-ai/letta-code">letta-ai/letta-code</a>
147(npm <code>@letta-ai/letta-code</code> 0.31.2) and
148<a href="https://github.com/getzep/zep">getzep/zep</a>, lockfiles excluded. A dash means
149<strong>the term does not occur in that snapshot</strong> — not that the system cannot do
150something comparable under another name. One case we know of: Letta Code revises memory in the
151background and calls it "dreaming" (sleep-time compute), which the term search for sleep
152consolidation does not match. In ZenBrain the mechanisms in this table are library functions;
153which of them the coordinator runs is in <a href="#what-runs-on-its-own-and-what-you-call-yourself">this table</a>. Dependency counts are declared direct dependencies:
154<code>@zensation/core</code> resolves to two packages, both our own; <code>mem0ai</code>
155declares four, <code>@letta-ai/letta-code</code> eighteen. Re-run the whole check yourself with
156<a href="./scripts/compare-mechanisms.sh"><code>scripts/compare-mechanisms.sh</code></a>; it
157prints its own positive and negative controls so you can see the instrument works before you
158trust the result.</sub>
159 
160Human memory does not work like a key-value store. The brain keeps specialised systems for
161different kinds of memory, forgets actively, modulates by emotion and retrieves by context.
162ZenBrain brings those mechanisms to AI agents, as a memory system with seven layers and as a
163library of the algorithms behind them.
164 
165### Advanced algorithms (since v0.3.0, May 2026)
166 
167On top of the 10 core algorithms above, `@zensation/algorithms` ships 10 advanced algorithms grounded in recent neuroscience and ML research. Each is exposed as its own sub-path (`@zensation/algorithms/<name>`) and remains zero-dependency:
168 
169- **`fsrs-vmPFC`** — Prediction-Error coupled FSRS
170- **`hebbian-two-factor`** — Two-Factor synaptic consolidation
171- **`sleep-simulation-selection`** — RL-based replay selection
172- **`spectral-health`** — Fiedler-value KG health monitor
173- **`ib-budget`** — Information-Bottleneck retention budget
174- **`dopamine-routing`** · **`hopfield-stm`** · **`personalized-pagerank`** · **`surprise-gradient-memory`** · **`temporal-multi-route`**
175 
176See [`CHANGELOG.md`](./CHANGELOG.md#030--2026-05-08) for details.
177 
178## What runs on its own, and what you call yourself
179 
180`@zensation/core` is a memory system: the `MemoryCoordinator` stores, recalls, consolidates and
181forgets. `@zensation/algorithms` is a library of twenty modules of tested functions, and the
182coordinator calls only a few of them. Several mechanisms named in this README live in the library
183alone; you wire them into your own system where you want them.
184 
185| Mechanism | The coordinator (`@zensation/core`) | The library (`@zensation/algorithms`) |
186|---|---|---|
187| Layers | Seven layer classes. `recall()` searches episodic, semantic, procedural and core memory, working memory on request; the cross-context layer is not part of recall. | — |
188| Routing | `store()` picks the layer: step-by-step content becomes a procedure, an emotional weight above 0.5 an episode, a confidence above 0.9 a pinned core block, anything else a fact. | — |
189| Emotional tagging | At every `store()`. The weight decides episode or fact, and which episodes consolidation promotes. | `tagEmotion`, `computeEmotionalWeight` |
190| Spaced repetition (FSRS) | Every fact gets an FSRS schedule. `getReviewQueue()` lists the due facts; a review your application reports with `recordReview()` updates the schedule. Recall does not rank by retrievability. | FSRS, prediction-error-coupled FSRS |
191| Forgetting | Nothing in long-term memory decays or is deleted on its own; `forget(id, layer)` deletes on request. Working memory decays (Ebbinghaus). | Ebbinghaus retention, personal decay profiles |
192| Consolidation | `consolidate()` turns each emotionally weighted episode into a fact, once. | Sleep replay (`selectForReplay`, `simulateReplay`, `pruneWeakConnections`), simulation-selection loop |
193| Hebbian learning | Not used: core keeps no knowledge graph. | Classic and two-factor Hebbian |
194| Bayesian confidence | Not used. | `propagateForRelation` and the rest of the module |
195| Context-dependent retrieval | Not used. The `includeContext` option never had an effect and was withdrawn in 0.5.0. | `captureEncodingContext`, `calculateContextSimilarity` |
196 
197The six Predictive Memory Architecture components of the paper are in neither package (see
198*Architecture vs. this package* above).
199 
200## Quick Start
201 
202> **Requires Node.js 22 or newer** (since `0.4.0`). On Node 20 or older, npm silently installs the last
203> compatible release (`@zensation/[email protected]`, `@zensation/[email protected]`) instead of the current one —
204> which looks like a broken package but is a platform mismatch. See [CHANGELOG](./CHANGELOG.md#040--2026-08-05).
205 
206```bash
207npm install @zensation/algorithms
208```
209 
210```typescript
211import {
212 initFromDecayClass,
213 getRetrievability,
214 updateAfterRecall,
215 tagEmotion,
216 computeEmotionalWeight,
217 computeHebbianStrengthening,
218 propagateForRelation,
219} from '@zensation/algorithms';
220 
221// 1. Schedule a memory with FSRS
222const memory = initFromDecayClass('normal_decay');
223 
224// 2. A week later, check recall probability (Ebbinghaus curve)
225const aWeekLater = new Date(Date.now() + 7 * 24 * 60 * 60 * 1000);
226const retention = getRetrievability(memory, aWeekLater);
227console.log(`Recall probability: ${(retention * 100).toFixed(1)}%`);
228// ~36.8% — retrievability has decayed over the week
229 
230// 3. User recalled it anyway — update scheduling
231const updated = updateAfterRecall(memory, 4, retention, aWeekLater);
232// stability 7 -> 8.19: recalling at low retrievability gives a bigger boost
233 
234// 4. Tag emotional significance
235const emotion = tagEmotion('I am absolutely thrilled — I got the promotion!');
236const weight = computeEmotionalWeight(emotion);
237console.log(`Decay multiplier: ${weight.decayMultiplier}x`);
238// 2.7x — emotional memories decay nearly 3x slower
239 
240// 5. Strengthen knowledge connections (Hebbian)
241const stronger = computeHebbianStrengthening(1.0);
242// 1.09 — "neurons that fire together wire together"
243 
244// 6. Propagate confidence through your knowledge graph
245const confidence = propagateForRelation(0.5, 0.8, 1.0, 'supports');
246// 0.9 — supporting evidence increases confidence
247```
248 
249### Want the advanced algorithms?
250 
251```typescript
252import {
253 computeKGPredictionError,
254 computeAdaptiveFSRSInterval,
255} from '@zensation/algorithms/fsrs-vmPFC';
256 
257// Couple FSRS scheduling with the prediction-error signal from your
258// knowledge graph: when the embedding has shifted a lot since the last
259// review (high cosine distance), shrink the next interval; otherwise push
260// it out. Both arrays must have the same length.
261const lastEmbedding = [0.1, 0.2, 0.3, 0.4];
262const currentEmbedding = [0.5, 0.4, 0.1, 0.2];
263const pe = computeKGPredictionError(lastEmbedding, currentEmbedding);
264const nextInterval = computeAdaptiveFSRSInterval(14, pe);
265```
266 
267Each advanced algorithm has its own sub-path (`@zensation/algorithms/spectral-health`, `@zensation/algorithms/ib-budget`, …). All zero dependencies.
268 
269## Runnable examples
270 
271Seven self-contained examples live in [`examples/`](./examples):
272 
273| Example | Shows |
274|---|---|
275| [`basic-chatbot.ts`](./examples/basic-chatbot.ts) | Working Memory + Short-Term Memory for conversation context — no SDK needed |
276| [`with-claude.ts`](./examples/with-claude.ts) | An Anthropic Claude assistant that remembers across conversations |
277| [`with-langchain.ts`](./examples/with-langchain.ts) | ZenBrain as the memory backend of a LangChain agent |
278| [`with-crewai.ts`](./examples/with-crewai.ts) | Multiple agents sharing Working Memory, with Hebbian strengthening |
279| [`with-vercel-ai.ts`](./examples/with-vercel-ai.ts) | A memory-aware system prompt for the Vercel AI SDK `streamText` pattern |
280| [`with-llamaindex.ts`](./examples/with-llamaindex.ts) | ZenBrain as long-term memory for a LlamaIndex.TS agent — LlamaIndex keeps the short-term window, ZenBrain decides what outlives it |
281| [`with-mastra.ts`](./examples/with-mastra.ts) | ZenBrain behind a Mastra agent: a Processor records each turn, and the instructions are rebuilt from what is currently recallable |
282 
283```bash
284npx tsx examples/basic-chatbot.ts
285```
286 
287The integration examples additionally need their respective SDK installed; [`examples/README.md`](./examples/README.md) lists which. Open [good first issues](https://github.com/zensation-ai/zenbrain/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) are the best way in if you want to contribute.
288 
289## The Science Behind It
290 
291### 7-Layer Memory Architecture
292 
293```
294Layer 7: Cross-Context Memory ← Shared knowledge across domains
295Layer 6: Core Memory ← Pinned facts (Letta-style)
296Layer 5: Procedural Memory ← "How to do X" (skills & workflows)
297Layer 4: Long-Term Semantic ← Facts with FSRS scheduling
298Layer 3: Episodic Memory ← Concrete experiences & events
299Layer 2: Short-Term / Session ← Current conversation context
300Layer 1: Working Memory ← Active task focus (7±2 items)
301```
302 
303Each layer holds a different kind of memory and is stored and searched in its own way.
304 
305### FSRS Spaced Repetition
306 
307[FSRS](https://github.com/open-spaced-repetition/fsrs4anki) (Free Spaced Repetition Scheduler) outperforms SM-2 by 30%. It uses the **desirable difficulty** principle: reviewing when retention is low gives a bigger stability boost. In `@zensation/core` every fact gets an FSRS schedule; your application reports each review with `recordReview()`, and FSRS sets the next one.
308 
309### Emotional Memory
310 
311The amygdala modulates memory consolidation — emotional events are remembered more vividly (flashbulb memory). ZenBrain's emotional tagger assigns arousal, valence, and significance scores using a 400+ keyword lexicon (English & German). In the library, emotional weight stretches decay half-lives up to **3x** (`computeEmotionalWeight`); the coordinator uses the weight to route emotional content to episodic memory and to choose what consolidation promotes.
312 
313### Hebbian Learning
314 
315"Neurons that fire together wire together" (Hebb, 1949). Knowledge graph edges that are frequently co-activated grow stronger. Unused edges decay and eventually get pruned. The result: a self-organizing knowledge structure that reflects actual usage patterns, with homeostatic normalization to prevent runaway growth. These are library functions; `@zensation/core` keeps no knowledge graph, so you apply them to a graph of your own.
316 
317### Ebbinghaus Forgetting Curves
318 
319Ebbinghaus (1885) showed that memory decays exponentially: `R = e^(-t/S)`. The library implements personalized decay profiles that adapt to individual learning patterns, with SM-2 compatibility for existing spaced repetition systems. In the coordinator, only working memory decays.
320 
321### Context-Dependent Retrieval
322 
323Tulving's Encoding Specificity Principle (1973): memories are recalled better when the retrieval context matches the encoding context. The library captures temporal context (time of day, day of week) and task type, and `calculateContextSimilarity` turns a match between a stored and the current context into a retrieval boost of up to **30%**. The coordinator stores no encoding context; its `includeContext` option never had an effect and was withdrawn in 0.5.0.
324 
325### Bayesian Confidence Propagation
326 
327Knowledge isn't isolated — facts support or contradict each other. The library propagates confidence through a knowledge graph you keep, using Bayesian belief updates: supporting evidence increases confidence, contradictions decrease it, with damping for numerical stability.
328 
329### Sleep Consolidation
330 
331During sleep, the hippocampus replays recent experiences, strengthening important memories and pruning weak connections (Stickgold & Walker, 2013). ZenBrain simulates this process: `selectForReplay()` prioritizes emotional and recently-accessed memories, `simulateReplay()` boosts their stability by 50%, and `pruneWeakConnections()` removes weak Hebbian edges — implementing the Synaptic Homeostasis Hypothesis (Tononi & Cirelli, 2006). The coordinator's `consolidate()` does not run this replay; it turns emotionally weighted episodes into facts, once each.
332 
333```typescript
334import { selectForReplay, simulateReplay } from '@zensation/algorithms/sleep-consolidation';
335 
336// Select memories for overnight consolidation
337const toReplay = selectForReplay(allMemories);
338// Simulate sleep replay — stability ↑, weak edges pruned
339const result = simulateReplay(toReplay);
340console.log(`Replayed ${result.summary.totalReplayed} memories, avg stability +${result.summary.avgStabilityIncrease.toFixed(1)} days`);
341```
342 
343### Memory Coordinator
344 
345The `MemoryCoordinator` puts the layers behind one API — inspired by Global Workspace Theory (Baars, 1988):
346 
347```typescript
348import { MemoryCoordinator } from '@zensation/core';
349 
350const memory = new MemoryCoordinator({ storage: adapter, embedding: embedder });
351 
352// Auto-routes to the right layer (semantic, episodic, procedural, or core)
353await memory.store('User prefers TypeScript', { type: 'auto' });
354 
355// Cross-layer search with ranked, deduplicated results
356const results = await memory.recall('programming preferences');
357 
358// Forget one memory for good, by the id and layer of a recall result
359await memory.forget(results[0].id, results[0].layer);
360 
361// Consolidate: emotionally weighted episodes become facts, once each; working memory decays
362await memory.consolidate();
363 
364// Facts whose FSRS review is due; report each review with recordReview()
365const dueItems = await memory.getReviewQueue();
366```
367 
368## Packages
369 
370| Package | Description | Status |
371|---------|-------------|--------|
372| [`@zensation/algorithms`](https://www.npmjs.com/package/@zensation/algorithms) · [source](./packages/algorithms) | 20 algorithm modules — 10 core (FSRS, Hebbian, Ebbinghaus, emotional, Bayesian, sleep consolidation, intervals, visualization) + 10 advanced (vmPFC-FSRS, two-factor Hebbian, IB budget, Hopfield STM, …) | :white_check_mark: Published |
373| [`@zensation/core`](https://www.npmjs.com/package/@zensation/core) · [source](./packages/core) | Memory layers, coordinator, adapter interfaces | :white_check_mark: Published |
374| [`@zensation/adapter-postgres`](https://www.npmjs.com/package/@zensation/adapter-postgres) · [source](./packages/adapters/postgres) | PostgreSQL + pgvector storage adapter | :white_check_mark: Published |
375| [`@zensation/adapter-sqlite`](https://www.npmjs.com/package/@zensation/adapter-sqlite) · [source](./packages/adapters/sqlite) | SQLite storage adapter (zero-config) | :white_check_mark: Published |
376| [`@zensation/mcp`](https://www.npmjs.com/package/@zensation/mcp) · [source](./packages/mcp) | MCP server — gives any MCP client (Claude Desktop, Claude Code, Cursor) the seven layers as four tools. Carries the protocol SDK, so the core stays dependency-free | :white_check_mark: Published |
377| [`@zensation/ai-sdk`](https://www.npmjs.com/package/@zensation/ai-sdk) · [source](./packages/ai-sdk) | Vercel AI SDK middleware — recall before the model call, store after it. Works with any provider, **zero runtime dependencies** | :white_check_mark: Published |
378 
379### Tree-Shakeable Imports
380 
381Every algorithm is available as a subpath export:
382 
383```typescript
384// Import everything
385import { tagEmotion, updateAfterRecall } from '@zensation/algorithms';
386 
387// Or just what you need (better tree-shaking)
388import { updateAfterRecall } from '@zensation/algorithms/fsrs';
389import { tagEmotion } from '@zensation/algorithms/emotional';
390import { computeHebbianStrengthening } from '@zensation/algorithms/hebbian';
391import { propagateForRelation } from '@zensation/algorithms/bayesian';
392import { selectForReplay } from '@zensation/algorithms/sleep-consolidation';
393import { getRetrievabilityWithCI } from '@zensation/algorithms/intervals';
394import { generateRetentionCurve } from '@zensation/algorithms/visualization';
395```
396 
397## Use Cases
398 
399### AI Chatbots with Long-Term Memory
400 
401```typescript
402import { updateAfterRecall, getRetrievability, scheduleNextReview } from '@zensation/algorithms/fsrs';
403import { tagEmotion, computeEmotionalWeight } from '@zensation/algorithms/emotional';
404 
405// When your AI learns a fact about the user:
406function rememberFact(fact: string) {
407 const memory = initFromDecayClass('normal_decay');
408 const emotion = tagEmotion(fact);
409 const weight = computeEmotionalWeight(emotion);
410 
411 // Emotional facts get longer retention
412 return {
413 ...memory,
414 emotionalWeight: weight.consolidationWeight,
415 decayMultiplier: weight.decayMultiplier,
416 };
417}
418 
419// Before each conversation, check what needs reinforcement:
420function getFactsDueForReview(facts: MemoryState[]) {
421 return facts.filter(f => getRetrievability(f) < 0.7);
422}
423```
424 
425### Knowledge Graph with Self-Organizing Edges
426 
427```typescript
428import { computeHebbianStrengthening, computeHebbianDecay } from '@zensation/algorithms/hebbian';
429import { propagateForRelation } from '@zensation/algorithms/bayesian';
430 
431// When two concepts are mentioned together:
432function coActivate(edge: { weight: number }) {
433 edge.weight = computeHebbianStrengthening(edge.weight);
434}
435 
436// Periodic maintenance — decay unused edges:
437function decayEdges(edges: { weight: number; lastUsed: Date }[]) {
438 for (const edge of edges) {
439 edge.weight = computeHebbianDecay(edge.weight);
440 // Edges below MIN_WEIGHT (0.1) can be pruned
441 }
442}
443```
444 
445### RAG with Confidence Scoring
446 
447```typescript
448import { propagateForRelation, isSignificantChange } from '@zensation/algorithms/bayesian';
449 
450// After retrieval, propagate confidence through related facts:
451function updateConfidenceGraph(facts: Fact[], relations: Relation[]) {
452 for (const rel of relations) {
453 const newConf = propagateForRelation(
454 rel.target.confidence,
455 rel.source.confidence,
456 rel.weight,
457 rel.type // 'supports' | 'contradicts' | 'related_to'
458 );
459 if (isSignificantChange(newConf, rel.target.confidence)) {
460 rel.target.confidence = newConf;
461 }
462 }
463}
464```
465 
466## Extracted From Production
467 
468These aren't toy implementations — ZenBrain's algorithms are extracted from [ZenAI](https://zensation.ai/?utm_source=github&utm_medium=readme&utm_campaign=evergreen), a production AI platform. Everything claimed here is verifiable in this repository:
469 
470- **822 tests** (489 algorithms · 138 core · 61 adapter-sqlite · 54 adapter-postgres, 6 of them against a real PostgreSQL · 58 mcp · 22 ai-sdk), all passing
471- **Zero runtime dependencies** — pure TypeScript, dual ESM + CJS, tree-shakeable subpath exports
472- **Reproducible** — building from this source produces the same 153-file `@zensation/[email protected]` tarball published on npm
473- **7-layer** memory architecture grounded in published neuroscience
474 
475## Contributing
476 
477We welcome contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.
478Issues and pull requests are answered; replications and counter-results are especially welcome.
479 
480**Resources:** [API Reference](./docs/api-reference.md) | [Recipes](./docs/recipes.md) | [Architecture](./docs/architecture.md) | [Benchmarks](./docs/benchmarks.md) | [FAQ](./docs/FAQ.md) | [Roadmap](./docs/ROADMAP.md)
481 
482```bash
483# Clone the repo
484git clone https://github.com/zensation-ai/zenbrain.git
485cd zenbrain
486 
487# Install dependencies
488npm install
489 
490# Run tests
491npm test
492 
493# Build all packages
494npm run build
495```
496 
497## Research
498 
499ZenBrain's architecture and algorithms are documented in an open-access technical disclosure:
500 
501- **arXiv preprint** (cs.AI): [arxiv.org/abs/2604.23878](https://arxiv.org/abs/2604.23878)
502- **Open-access archive:** [ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture for Autonomous AI Systems](https://doi.org/10.5281/zenodo.19353663) (Zenodo, DOI: [10.5281/zenodo.19353663](https://doi.org/10.5281/zenodo.19353663) — resolves to the latest version)
503- **TDCommons:** [Technical Disclosure](https://www.tdcommons.org/dpubs_series/9683) (CC BY 4.0)
504- **HuggingFace:** [Model Card & Benchmarks](https://huggingface.co/zensation-ai/zenbrain)
505 
506If you use ZenBrain in academic work, please cite:
507 
508```bibtex
509@misc{bering2026zenbrain,
510 title = {ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture for Autonomous AI Systems},
511 author = {Bering, Alexander},
512 year = {2026},
513 eprint = {2604.23878},
514 archivePrefix = {arXiv},
515 primaryClass = {cs.AI},
516 doi = {10.5281/zenodo.19353663},
517 url = {https://arxiv.org/abs/2604.23878}
518}
519```
520 
521## Cited by
522 
523Five works cite ZenBrain (as of 28 September 2026): a survey by the Sico team at Microsoft Research, MindMemOS by Huawei's Noah's Ark Lab, the EVD preprint, the HindsightTag manuscript and the Lamperouge manifesto.
524 
525- **Agentic Evolution: From Self-Improving Agents to Co-Evolving Human-AI Systems**, a survey by the Sico team at [Microsoft Research](https://www.microsoft.com/en-us/research/publication/agentic-evolution-from-self-improving-agents-to-co-evolving-human-ai-systems/) (2026), calls forgetting "critically understudied": very few of the roughly 100 Memory & Sense papers it surveys implement explicit forgetting. It lists ZenBrain as one of four works in its forgetting/lifecycle group and as its only source for sleep-based consolidation.
526- **MindMemOS** (Huawei's Noah's Ark Lab, [arXiv:2608.12428](https://arxiv.org/abs/2608.12428), August 2026) relies on exactly three references for the foundational claim of its introduction: two field surveys and a single system paper — ZenBrain.
527- **HindsightTag** (Vivek Govindbhai Dudhat, [manuscript](https://github.com/ViveK1One/hindsighttag/blob/main/HindsightTag_paper.pdf), July 2026, revised 30 September 2026) discusses ZenBrain as its closest prior system and uses its `MemoryCoordinator` interface as the integration example.
528- **EVD: An Emotional Valence Dimension for Persistent Agent Memory** (R. J. Vandelinder and I. Vandelinder, Exile Research, [Zenodo](https://doi.org/10.5281/zenodo.20706465), June 2026) places ZenBrain in its related work.
529- **The field measures the wrong thing** (Lamperouge, manifesto, [Zenodo](https://doi.org/10.5281/zenodo.21982684), August 2026) selects ZenBrain among six works on persistent internal state and notes that its "days" are simulation steps.
530 
531Each work with the sentence that cites ZenBrain: [zensation.ai/en/publikationen](https://zensation.ai/en/publikationen).
532 
533Projects that build the library into their code:
534 
535- [ACMS](https://github.com/newtogi/ACMS-Agentic-Cognitive-Memory-System) reads and writes the ZenBrain SQLite database directly.
536- [neurograph-runtime](https://github.com/cwang-95/neurograph-runtime) uses the FSRS implementation of `@zensation/algorithms` as the ranking and feedback layer of a knowledge base on radiotherapy literature.
537 
538Citing ZenBrain or building on it? Open an issue and we will add you here.
539 
540## Community
541 
542- **GitHub Discussions**: [Ask a question, show what you built](https://github.com/zensation-ai/zenbrain/discussions) — help, show-and-tell, feature requests
543- **GitHub Issues**: [Bug reports & feature requests](https://github.com/zensation-ai/zenbrain/issues)
544- **Email**: [email protected]
545 
546## License
547 
548[Apache 2.0](./LICENSE) — use it in production, modify it, distribute it. Just keep the attribution.
549 
550---
551 
552<p align="center">
553 Built by <a href="https://zensation.ai/?utm_source=github&utm_medium=readme&utm_campaign=evergreen">ZenSation</a> in Kiel, Germany.
554</p>
555 

Discussion

Alternatives

API and interface designGuides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend.Coding · MITContext7Pulls up-to-date, version-specific library docs and code examples into the prompt so the AI stops inventing old APIs.Coding · MITContext7 Documentation LookupFetch up-to-date documentation and code examples for any library, framework, SDK, CLI tool, or cloud service. Use whenever the user asks about a specific library — even well-known ones like React, Next.js, Prisma, Express, Tailwind, Django, or Spring Boot — because training data may not reflect recent API changes or version updates. Always use for: API syntax questions, configuration options, version migration issues, "how do I" questions mentioning a library name, debugging that involves library-specific behavior, setup instructions, and CLI tool usage. Use even when you think you know the answer. Do not rely on training data for API details, signatures, or configuration options — they are frequently out of date. Prefer this over web search for library documentation.Coding · MITAdaptyv Bio Foundry APIHow to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.Science · MIT