Brain agent

Create a file structure model and tooling that an ai model can benefit previous history, selective and context relevant

by omelas-tech·MIT license·★ 2 Stars on the repo·GitHub ↗

Inside this agent

README.md · the author's own words
<h1 align="center">Brain Memory</h1>

  <a href="https://github.com/omelas-tech/brain/actions/workflows/ci.yml"><img src="https://github.com/omelas-tech/brain/actions/workflows/…
  <a href="https://www.npmjs.com/package/brain-memory"><img src="https://img.shields.io/npm/v/brain-memory" alt="npm version"></a>
  <a href="https://github.com/omelas-tech/brain/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/brain-memory" alt="license"></a>

A hierarchical, file-system-based memory plugin for AI coding agents. Inspired by human neuroscience — memories are organized into deep nes…

One hosted **MCP connector** reaches every major agent and chat app — **Claude Code**, **OpenAI Codex CLI**, **OpenCode**, **GitHub Copilot…

```
~/.brain/
├── professional/
│   └── companies/
│       └── acme-corp/
│           └── projects/

Word-for-word excerpt, not a result. Read the full README.md ↓

Files of Brain

omelas-tech/main1 file
README.md
Show the full text887 lines

Brain Memory

Brain Memory

CI npm version license

A hierarchical, file-system-based memory plugin for AI coding agents. Inspired by human neuroscience — memories are organized into deep nested life-domain categories, connected via associative networks, strengthened through spaced recall, and naturally decay over time.

One hosted MCP connector reaches every major agent and chat app — Claude Code, OpenAI Codex CLI, OpenCode, GitHub Copilot CLI, Kilo, the Claude.ai apps, ChatGPT, Google Antigravity (Gemini CLI's successor), OpenClaw / NVIDIA NemoClaw, Hermes Agent, and Goose. Prefer a free, local-first install? The native plugin runs entirely from ~/.brain/ on Claude Code, Codex, OpenCode, Copilot CLI, Kilo, and Antigravity — and dedicated native integrations plug the same brain into OpenClaw and Hermes as their memory engine.

~/.brain/
├── professional/
│   └── companies/
│       └── acme-corp/
│           └── projects/
│               └── alpha-launch.md        ⚡ 0.88
├── personal/
│   └── education/
│       └── typescript-generics.md         ⚡ 0.72
├── social/
│   └── communities/
│       └── open-source-contrib.md         ⚡ 0.65
└── family/
    └── events/
        └── annual-reunion-planning.md     ⚡ 0.55

Why Brain Memory?

Existing AI memory solutions use flat databases with tag-based retrieval. Brain Memory is different:

  • The directory tree IS the semantic structure — professional/companies/acme/projects/ tells the agent everything about context without vector search
  • Human-inspectable — Browse your "brain" in any file explorer
  • Git-friendly — Full version history of how memories evolve
  • Strength + decay — Recalled memories get stronger, forgotten ones fade. Just like your brain
  • Recall receipts — Memory that visibly fires: every answer shaped by a memory ends with a one-line attributable receipt (◉ memory: "<title>" (<type>, <age>)), minted by the engine so it can't be hallucinated
  • Provenance-bounded trust — Every memory records where it came from (user, agent-inferred, tool-output, external), and recall weighs it: a fact planted by a web page or tool output is down-ranked, flagged low_trust, marked ⚠ on its receipt, and can never outrank what you said directly — no matter how many copies of it get written. And because memories are plain files, Brain records a SHA-256 baseline of each one at write time — so brain audit also catches a memory edited outside any write path, the one poisoning route every write-path defense is blind to
  • Bitemporal — it knows when a fact was true — Every memory separates record time (when the brain learned it) from valid time (valid_from / valid_until, when it was actually true). So "we deploy to Fly.io" and "we deploy to Render" aren't a contradiction to guess between — they're one fact with a boundary. brain recall "deploy target" --as-of 2026-03-01 answers what was true in March; --as-known-of answers what the brain knew then. Facts that stopped being true are demoted and marked ⌛ expired, never silently served as current
  • Deterministic recall — every agent ranks identically — Scoring is arithmetic over files, not a model call: TF-IDF/BM25 relevance, decayed strength, spreading activation, context match, salience. Claude, Codex, and Gemini asking the same question of the same brain get the same ranking, in the same order, offline. No embedding-model version can silently reshuffle what your agent remembers
  • Associative network — Memories link to each other with weighted connections. Recalling one activates related ones automatically
  • Context-dependent recall — Memories encoded in a similar context to the current session are scored higher
  • Spaced reinforcement — Memories recalled after longer intervals get bigger boosts, cramming produces diminishing returns
  • Cognitive types — Episodic, semantic, and procedural memories each decay differently, just like in the brain
  • Always-present knowledge — Pin critical conventions and preferences so they load every session, bypassing recall and never decaying — the facts your agent must never miss
  • Procedural skills — Reusable how-to workflows with progressive disclosure, learned automatically from repeated experience and exportable to your agent's native skills
  • On-demand depth — Subcategories are created as needed, not pre-defined
  • Consolidation — Weak related memories merge into stronger combined knowledge
  • Zero dependencies — and measured, not assumed — Pure file I/O: no database, no server, no embedding model. That is a deliberate result, not a shortcut. On our hardest retrieval scenario (1,021 memories, 1,000 plausible distractors) a real embedding model ranked the target memories worse than BM25 — see the retrieval-only pilot

Install

There are two ways to give an agent its brain. They are complementary — most people end up with both:

Path Reaches Storage Cost Best for
Hosted MCP connector Every MCP-capable host (Claude Code, Codex CLI, OpenCode, Copilot CLI, Kilo, Claude.ai apps, ChatGPT, Antigravity, OpenClaw, Hermes, Goose) Brain Cloud (hosted) account One connector, everywhere — including web & mobile chat
Local-first native plugin The current CLIs (Claude Code, Codex CLI, OpenCode, Copilot CLI, Kilo, Antigravity) ~/.brain/ on your machine free Zero-config ambient memory, no account, files you own
Assistant integrations OpenClaw / NVIDIA NemoClaw (memory-slot plugin), Hermes Agent (memory provider) ~/.brain/ on your machine free Your always-on personal assistant sharing one brain with your coding agents
1. Universal path — the hosted MCP connector

Brain Cloud exposes a single remote MCP server (streamable-HTTP + OAuth) at https://mcp.brainmemory.ai/mcp. Add it once per host and that host can recall, memorize, pin, and check status — no local install, no per-project setup. It works everywhere MCP does, including the chat apps that can't run a native plugin.

# Claude Code
claude mcp add --transport http brain https://mcp.brainmemory.ai/mcp

# OpenAI Codex CLI
codex mcp add brain --url https://mcp.brainmemory.ai/mcp
Per-host setup for every other connector
  • Codex CLI (config file) — add to ~/.codex/config.toml:
    [mcp_servers.brain]
    url = "https://mcp.brainmemory.ai/mcp"
    
  • OpenCode — add to opencode.json:
    {
      "mcp": {
        "brain": { "type": "remote", "url": "https://mcp.brainmemory.ai/mcp" }
      }
    }
    
  • Claude.ai / ChatGPT — Settings → Connectors → Add custom connector, paste https://mcp.brainmemory.ai/mcp, and complete the OAuth sign-in. (ChatGPT requires a paid plan or Developer Mode.)
  • Google Antigravity — add to mcp_config.json under the serverUrl key. (Legacy Gemini CLI used the httpUrl key in settings.json.)
  • GitHub Copilot CLI — add to ~/.copilot/mcp-config.json (OAuth via /mcp auth brain in-session):
    {
      "mcpServers": {
        "brain-memory": { "type": "http", "url": "https://mcp.brainmemory.ai/mcp", "tools": ["*"] }
      }
    }
    
  • OpenClaw — openclaw mcp add brain-memory --url https://mcp.brainmemory.ai/mcp --auth oauth, then openclaw mcp login brain-memory. (Inside NVIDIA NemoClaw, allowlist the endpoint first — see integrations/openclaw.)
  • Hermes Agent — add to ~/.hermes/config.yaml:
    mcp_servers:
      brain: { url: "https://mcp.brainmemory.ai/mcp", auth: oauth }
    
  • Goose — add a remote extension (streamable-HTTP) pointing at https://mcp.brainmemory.ai/mcp.
  • Kilo — add to kilo.jsonc (OAuth starts automatically):
    {
      "mcp": {
        "brain-memory": { "type": "remote", "url": "https://mcp.brainmemory.ai/mcp", "enabled": true }
      }
    }
    

The first time a host connects you'll complete an OAuth sign-in with the Google account that holds your cloud brain; the connector then syncs to every client on that account. See Use Brain in Claude apps for the full walkthrough.

2. Local-first path — the native plugin
npm install -g brain-memory
brain

The first command installs the package globally — this gives you both the interactive setup wizard and the brain CLI (brain recall, brain memorize, brain reinforce, …) that agents rely on for deterministic scoring.

The second command runs the setup wizard, which asks which runtime(s) to configure and whether to install globally or for the current project. Each runtime gets its instructions file plus the brain commands/skills:

Runtime Instructions file Commands land at
Claude Code CLAUDE.md ~/.claude/commands/brain/ (plugin slash commands)
OpenAI Codex CLI AGENTS.md (~/.codex/) + hooks in ~/.codex/hooks.json (SessionStart, UserPromptSubmit, SessionEnd — trust once via /hooks) ~/.agents/skills/<name>/SKILL.md
OpenCode AGENTS.md ~/.config/opencode/commands/
GitHub Copilot CLI copilot-instructions.md (~/.copilot/), repo-local AGENTS.md ~/.agents/skills/<name>/SKILL.md (shared with Codex)
Kilo rules/brain-memory.md + kilo.jsonc instructions entry (~/.config/kilo/), repo-local AGENTS.md ~/.config/kilo/commands/
Google Antigravity GEMINI.md ~/.gemini/skills/ (experimental — verify paths against a live install)
Plugin install — Claude Code, Codex, ChatGPT workspaces

This repository is also a plugin marketplace. Installing the brain plugin gives Claude Code and Codex the same /brain:* commands plus deterministic hooks: SessionStart injects the budget-bounded brain session-start payload as context (no prompt file to edit, nothing for the model to remember to run) and SessionEnd records the session boundary in ~/.brain/contexts.json. The plugin bundles the CLI, so no npm install is required for the hooks.

# Claude Code
claude plugin marketplace add omelas-tech/brain
claude plugin install brain@brain-memory          # local-first: hooks + /brain:* commands
claude plugin install brain-cloud@brain-memory    # optional: the hosted MCP connector

# Codex CLI — same repo, same two plugins (Codex reads the Claude manifests)
codex /plugins                                    # then add marketplace omelas-tech/brain

ChatGPT Business / Enterprise / Edu: a workspace admin imports the marketplace once (Admin → Plugins → Add → Import marketplace → https://github.com/omelas-tech/brain) and the workspace picks up new versions daily. brain (skills + hooks) serves Codex users in the workspace; brain-cloud (the MCP connector) serves ChatGPT desktop. Import does not grant access by itself — each user completes the connector's OAuth sign-in on first use.

Non-interactive
brain --claude --global    # Claude Code, global
brain --codex --global     # OpenAI Codex CLI, global
brain --opencode --global  # OpenCode, global
brain --copilot --global   # GitHub Copilot CLI, global
brain --kilo --global      # Kilo, global
brain --antigravity --global  # Google Antigravity, global (experimental)
brain --all --global       # All runtimes, global

These run without a terminal, so an agent or a CI job can install brain itself. With no terminal to ask on, the installer initializes ~/.brain/ if it doesn't exist yet (it never overwrites an existing brain) — add --yes to skip that question outright. Leave out the runtime and it stops with an error rather than guessing.

For the deepest Copilot CLI integration — deterministic session-start context injection via its sessionStart hook — install the Copilot plugin from the brain marketplace:

copilot plugin marketplace add omelas-tech/brain
copilot plugin install brain-memory@brain

Kilo gets the same treatment via its runtime plugin — deterministic session-start injection, session tracking, and BRAIN_AGENT labeling (details):

mkdir -p ~/.config/kilo/plugin
cp integrations/kilo/plugin/brain-memory.js ~/.config/kilo/plugin/
3. Personal-assistant integrations — OpenClaw, NemoClaw, Hermes

Always-on personal assistants get deeper, first-class integrations that make ~/.brain/ their actual memory engine — the same brain your coding agents read and write:

  • OpenClaw / NVIDIA NemoClaw — a native memory-slot plugin (openclaw plugins install openclaw-brain-memory + plugins.slots.memory: "brain-memory") that replaces memory-core with deterministic brain recall, session-start context injection, and model-driven capture. Also ships a slot-neutral hook pack, a ClawHub skill, and a NemoClaw egress-policy preset.
  • Hermes Agent — a native memory provider (plugins/memory/brain/) implementing the full MemoryProvider lifecycle: session-start prompt block, pre-turn prefetch, brain_recall/brain_memorize/brain_reinforce tools, and session-context logging. Plus lightweight hook-script glue if you keep another provider active.

Both are backed by the same brain CLI the coding-agent installs use — one memory, every agent.

Update
npm install -g brain-memory
brain update

The first command updates the package and the brain CLI. The second command refreshes the slash command prompts for your installed runtimes. Target specific runtimes with --claude, --codex, --opencode, --antigravity, or --all.

Upgrading from an older version? The separate binaries (brain-recall, brain-memorize, brain-reinforce, brain-cloud, brain-memory) were unified into a single brain dispatcher — use brain recall, brain memorize, brain reinforce, brain cloud <…> instead. Run brain update to refresh your runtime prompts to the new command surface.

Why not npx? npx runs the setup wizard in a temporary directory that is discarded after execution. The brain CLI (brain recall, brain memorize, brain reinforce) won't be available in your PATH, which means agents will fall back to less reliable manual file operations. Always use npm install -g to ensure everything works correctly.

Using nvm, fnm, asdf, mise or nodenv? npm install -g puts brain inside whichever Node version is active, and only there. The command then disappears when your default version moves — a 22 alias drifting to a newer 22.x is enough — and shells that never load the version manager (agent hooks, GUI-launched agents, non-interactive shells) can't see it at all. Nothing errors: agents quietly fall back to editing memory files by hand, and it looks like brain works "sometimes". Install brain-memory with a system Node instead (Homebrew, apt, the nodejs.org installer) so brain lives in one stable place. npm takes its global prefix from the node that runs it, so put the system Node first on PATH for that one command — on macOS with Homebrew: PATH="/opt/homebrew/bin:$PATH" npm install -g brain-memory. Check with which -a brain; it should print exactly one path, outside your version manager's directory. The installer warns when it detects this. Volta is fine as-is — it keeps global packages available across versions.

Uninstall
brain uninstall
npm uninstall -g brain-memory

The first command removes slash commands and prompt sections from your agent configs. The second removes the package and CLI tools. Your ~/.brain/ directory (memories) is preserved by default. Add --delete-data to the uninstall command to remove it too. Use --yes to skip confirmation prompts.

Manual Install

If you'd rather wire up the native plugin by hand, copy the brain commands into your agent's folder, then append the matching prompt file to its instructions file.

# Claude Code — flat slash commands
cp -r commands/brain/ ~/.claude/commands/brain/

# OpenCode — flat slash commands
mkdir -p ~/.config/opencode/commands/brain
cp -r commands/brain/. ~/.config/opencode/commands/brain/

# OpenAI Codex CLI — each command becomes a skill under the cross-tool skills dir
for f in commands/brain/*.md; do
  name=$(basename "$f" .md)
  mkdir -p ~/.agents/skills/brain-"$name"
  cp "$f" ~/.agents/skills/brain-"$name"/SKILL.md
done

# Google Antigravity (experimental — verify paths) — skills under ~/.gemini/skills/
for f in commands/brain/*.md; do
  name=$(basename "$f" .md)
  mkdir -p ~/.gemini/skills/brain-"$name"
  cp "$f" ~/.gemini/skills/brain-"$name"/SKILL.md
done

Then append the contents of the corresponding prompt file to your agent's instructions file:

  • prompts/claude.md → CLAUDE.md
  • prompts/openai.md → AGENTS.md (Codex, in ~/.codex/)
  • prompts/opencode.md → AGENTS.md (OpenCode)
  • prompts/antigravity.md → GEMINI.md (experimental)

AGENTS.md collision (local scope): Codex and OpenCode both read a project-local AGENTS.md. If you install both for the same project, point only one at the local file (or install one globally) so their brain sections don't conflict. Globally they're separate (~/.codex/AGENTS.md vs OpenCode's own config dir).

Commands

The everyday loop is ambient — remember and memorize run automatically at session start/end, so you rarely type a command. The surface is a small core plus a background maintenance job:

Command Description
/brain:remember [query] Recall relevant memories with spreading activation and context matching
/brain:memorize [topic] [--sync] Store memories from current session context (add --sync to auto-push)
/brain:status Dashboard with brain health metrics and recommendations
/brain:pin [id|query] Pin a memory to the always-present tier — loads every session, never decays. Toggles: also unpins (--off)
/brain:forget [target] Decay, archive, or remove memories. --deep performs forensic erasure — traces and removes every reference
/brain:import [--project P] [--since 30d] Cold-start a new brain from transcripts your agents already wrote. Incremental — safe to re-run
/brain:sync [subcommand] Sync via Brain Cloud, Git remote, or export/import (auto-initializes the brain on first run)
/brain:skills [list|show|add|use|remove|export] Manage procedural skills — reusable how-to workflows with progressive disclosure
/brain:sleep [scope] Full maintenance cycle — 9 neuroscience-inspired phases (replay, consolidation, review reinforcement, pruning, dreaming, …). Usually runs automatically/in the background

Cold Start

A new brain is empty, and an empty brain is worth nothing until something fills it. But your agents have been keeping local transcripts for months — decisions, preferences, corrections, conventions. /brain:import reads them.

brain import --sources          # what history exists on this machine
brain import --project my-app   # digest that project's past sessions
brain import --since 30d        # or scope by time

The split matters. The CLI harvests — deterministic, budget-bounded, no model call: it extracts session titles, user prompts, projects, branches, and edited files, filters out harness noise and subagent traffic, and interleaves across projects so one busy repo can't eat the budget. The agent then distills that digest into memories through the ordinary brain memorize path.

That split is deliberate. Extracting meaning is a semantic judgement, and doing it in the CLI would mean shipping an embedding model or calling an LLM — the two things Brain exists to avoid. So the harvester reports facts and never infers, and every imported memory lands as agent-inferred provenance: it inherits the existing ceilings for free, and an import can never pin, entrench, or outrank something you said directly.

Import is incremental. A cursor in ~/.brain/.import/state.json records which sessions have been read, so re-running only offers new ones (--all overrides). Nothing is written without you — brain import only ever reads and prints.

Session Lifecycle

Brain Memory works automatically in the background — no commands needed for basic context awareness.

Session Start

When a session begins and ~/.brain/ exists, the agent makes a single brain session-start call. This aggregator returns one deterministic, token-budget-bounded payload so the brain can never bloat the context window (the budget lives in ~/.brain/config.json):

  1. Pinned memories — always-present conventions and preferences, injected verbatim regardless of recall score
  2. Skills index — the name + description of each available procedural skill (~100 tokens each; full instructions are loaded only when a task matches)
  3. Context recall — the top memories relevant to the current project
  4. Review queue + low-confidence alerts, then a brief status line:
◉ Brain active — 42 memories loaded (8 in current project context)
📋 3 memories due for review — reinforced automatically during /brain:sleep

The agent treats pinned facts as active constraints, notes which skills exist, silently internalizes relevant memories, and references them naturally during the session — no information dump.

Ambient Session Tracking

Throughout the session, the agent maintains a running mental log of notable events — decisions made, things learned, insights realized, significant experiences. This is purely internal awareness with no file writes. It ensures that early-session events aren't forgotten by the time the session ends.

Periodic Memory Checkpoint

Every ~10 substantive interactions (file edits, architecture decisions, debugging breakthroughs), the agent evaluates whether memorizable content has accumulated. If so, it appends a brief reminder to its next response:

◉ Notable decisions and learnings this session — /brain:memorize when ready

This never interrupts your flow — it's a one-liner appended to an existing response, at most once per ~10 interactions. The counter resets after you run /brain:memorize.

Session End

When a session ends, the agent performs two steps in order:

  1. Saves session context to ~/.brain/contexts.json — always, even for trivial sessions. This includes a notable_unsaved field listing items you didn't memorize, so future sessions can reference what happened.

  2. Suggests memorization if the session contained meaningful decisions, learnings, or insights:

💡 This session contained notable decisions and learnings.
   Would you like to store them as brain memories?
   Run /brain:memorize to capture them before this context is lost.

The agent never auto-memorizes without user consent. Context is saved proactively — the agent doesn't wait for an explicit goodbye signal.

How It Works

Memory Lifecycle
Create → Store → Decay → Recall → Reinforce → Review → Sleep → Archive
                                      ↑                   │
                                      └── Associations ────┘
  1. Create — When you use /brain:memorize, the agent analyzes the session and extracts significant decisions, learnings, insights, or experiences
  2. Store — Each memory is filed into the hierarchy at the appropriate depth, with YAML frontmatter tracking metadata. Association edges are created to related memories.
  3. Decay — Memories naturally weaken over time: effective_strength = base_strength * (decay_rate ^ days_since_access)
  4. Recall — /brain:remember searches, scores with spreading activation and context matching, and returns the best memories. Archived memories are searched as a fallback.
  5. Reinforce — Each recall applies spaced reinforcement (longer gaps = bigger boosts) and improves the memory's decay resistance
  6. Review — SM-2 spaced repetition surfaces memories at optimal intervals for long-term retention; reinforcement runs automatically during the sleep cycle
  7. Sleep — /brain:sleep performs a 9-phase maintenance cycle inspired by real neuroscience (replay, consolidation, review reinforcement, pruning, dreaming, …), usually run automatically/in the background
  8. Archive — Fully decayed memories move to _archived/ (recoverable and searchable) or can be permanently deleted
Neuroscience Foundations

Brain Memory is grounded in peer-reviewed neuroscience research. Here's how each mechanism maps to the brain:

Brain Mechanism Implementation
Spreading activation Recalling memory A automatically surfaces linked memories B and C via weighted association graph
Hebbian learning "Neurons that fire together wire together" — memories recalled together strengthen mutual links
Context-dependent recall Memories encoded in a similar context (project, task type) are scored higher at retrieval
Spacing effect Longer intervals between recalls produce larger strength boosts; cramming yields diminishing returns
Ebbinghaus decay Exponential forgetting curve with per-memory decay rates
Episodic → Semantic Event-specific memories crystallize into abstract principles during sleep
Synaptic homeostasis (SHY) Global strength downscaling during sleep prevents inflation, then selectively re-boosts important memories
REM dreaming Creative cross-domain association discovery via analogical reasoning
Memory reconsolidation Recent knowledge updates and reshapes older related memories during sleep
Cue-dependent forgetting Archival preserves availability — memories aren't deleted, just moved to _archived/
Targeted forgetting Deep erasure that traces and removes all references, like how the brain can selectively erase specific memory traces
Memory Types
Type Base Strength Daily Decay Use Case
insight 0.90 0.997 Deep realizations, patterns discovered
decision 0.85 0.995 Choices made and their rationale
goal 0.80 0.993 Objectives and aspirations
experience 0.75 0.985 Notable events or processes
learning 0.70 0.990 New knowledge acquired
relationship 0.70 0.997 Connections between people/things
preference 0.60 0.998 User style and preferences
observation 0.40 0.950 Casual facts or notices
Cognitive Types

Each memory is also classified by how the brain processes it:

Cognitive Type Strength Modifier Decay Behavior Example
Episodic +0.10 Faster decay — event details fade "The deploy failed Tuesday because of X"
Semantic default Standard decay — stable knowledge "React hooks must follow rules of hooks"
Procedural -0.10 Very slow decay — skills persist "Steps to debug memory leaks"

During sleep, frequently-recalled episodic memories are crystallized into semantic memories — the specific event fades but the lesson persists. This mirrors how humans extract general principles from repeated experiences.

Always-Present Memories (Pinning)

Recall is probabilistic — a stored preference only applies if scoring happens to surface it. For the facts an agent must never miss (coding conventions, standing decisions, hard constraints), that's not good enough. Pinning fixes it:

  • pinned — the memory is injected at every session start regardless of recall score, and is decay-exempt (it never fades). Scope it global (loads everywhere) or project:<name> (loads only in that project).
  • stable — an independent flag that exempts a memory from decay and pruning without forcing it to always load — for timeless facts you recall on demand but don't want to fade.
brain pin <id> --scope global --priority 1   # or: /brain:pin always use tabs

Pinned and stable memories are skipped by sleep-cycle homeostasis and pruning, and /brain:memorize proactively proposes pinning durable conventions. The always-present set is budget-capped (pin_budget_tokens) so it can't crowd out the context window. This maps cleanly to the semantic memory type in the CoALA agent-memory model — knowledge that is always in context — decomposed into two orthogonal properties (always-loaded vs. non-decaying).

Procedural Skills

Procedural memory is how to do things — reusable, step-by-step workflows stored as ~/.brain/_skills/<name>/SKILL.md. To keep them from flooding the context window, skills use three-level progressive disclosure:

Level When What loads
L0 Every session start Only each skill's name + description (~100 tokens)
L1 A task matches a skill The full SKILL.md step-by-step instructions
L2 A step needs them Referenced resources/ (templates, scripts)
brain skill list                       # advertised skills (L0)
brain skill show structured-code-review # full instructions (L1)
brain skill use structured-code-review  # record outcome (--failed weakens it)
brain skill export structured-code-review --target claude  # → native .claude/skills/

Skills strengthen on successful use and weaken on --failed — one that fails too often demotes itself out of the advertised L0 index. And they aren't only hand-authored: during sleep, Brain crystallizes recurring task-solving patterns from repeated experience into new skills (user-confirmed). Finally, brain skill export emits a skill in your agent's native format so it becomes directly executable.

Memory File Format

Each memory is a Markdown file with YAML frontmatter:

---
id: mem_20260213_a3f2c1
type: decision
cognitive_type: semantic
created: 2026-02-13T14:30:00Z
last_accessed: 2026-02-13T14:30:00Z
access_count: 3
recall_history: ["2026-02-13T14:30:00Z", "2026-02-13T18:00:00Z", "2026-02-14T09:00:00Z"]
strength: 0.92
decay_rate: 0.995
salience: 0.8
confidence: 0.9
# Valid time — when the fact was TRUE, as distinct from `created` above (when
# it was recorded). Optional and half-open [from, until); omit for facts that
# are simply true. Superseding stamps `valid_until` on the old memory for you.
valid_from: 2026-02-13T14:30:00Z
tags: [architecture, microservices, scaling]
related: [mem_20260210_b4e5d6]
source: project-alpha-session
encoding_context:
  project: project-alpha
  topics: [architecture, scaling, kafka]
  task_type: designing
---

# Chose Event-Driven Architecture for Project Alpha

We decided to use event-driven architecture with Kafka instead of synchronous
REST calls between services, because the traffic analysis showed 10x burst
patterns that would overwhelm synchronous endpoints.

## Context

Sprint planning for Q2, evaluating scaling strategy for the notification system.

## Key Details

- Kafka chosen over RabbitMQ for its replay capability
- Event schema registry added to prevent breaking changes
- Estimated 3-week implementation vs 1-week for REST (but REST would need rework at scale)

## Connections

Related to the capacity planning decision (mem_20260210_b4e5d6) where we
identified the 10x burst pattern in notification traffic.
Scoring Formula

When recalling memories, each candidate is scored using a 6-factor formula:

score = 0.38 * relevance
      + 0.18 * decayed_strength
      + 0.08 * recency_bonus
      + 0.14 * spreading_bonus
      + 0.14 * context_match
      + 0.08 * salience
  • relevance (0.38) — How well the memory matches the query
  • decayed_strength (0.18) — Base strength after time decay
  • recency_bonus (0.08) — Linear bonus that fades over one year
  • spreading_bonus (0.14) — Activation received from linked memories in the association graph
  • context_match (0.14) — How similar the encoding context is to the current session
  • salience (0.08) — Emotional/motivational significance

Relevance is calibrated in absolute terms: BM25 scores are scaled by IDF-weighted query coverage, so a memory matching one term of a four-term query cannot claim relevance 1.0 just for being the best available match. Explicit-query recall also applies a relevance floor — memories that are neither query-relevant nor activated by a relevant associate are excluded rather than padding the results on strength alone. A query about things the brain doesn't know returns few results with honestly low scores (or none), instead of confident-looking noise. Context-mode recall (session start) is exempt, where strength-ranked topical padding is the intended behavior.

The agent then decides the response strategy:

  • Single strong match (top score > 0.7) → Return the full memory
  • Multiple related (2-5 candidates > 0.4) → Synthesize a consolidated response
  • Many weak (>5, all < 0.4) → List candidates for the user to choose
  • No active matches → Search the archive, then suggest alternatives
Associative Network

Memories are connected via weighted edges in ~/.brain/associations.json:

{
  "edges": {
    "mem_20260213_a3f2c1": {
      "mem_20260210_b4e5d6": {
        "weight": 0.45,
        "co_retrievals": 3,
        "last_activated": "2026-02-14T09:00:00Z",
        "origin": "co_retrieval"
      }
    }
  }
}

Spreading activation: When you recall memory A, activation spreads along weighted edges to surface related memories B and C — even if they didn't match the query directly. Activation decays by 50% per hop, up to 2 hops deep.

Hebbian learning: When multiple memories are recalled together, their mutual edge weights are strengthened: new_weight = min(1.0, weight + 0.10 * (1.0 - weight)). Memories that fire together wire together.

Link dynamics: Edges decay over time (weight * 0.998^days) and are pruned below 0.05 during sleep. New links are created automatically when memories share 2+ tags (weight 0.10) or are explicitly related (weight 0.20).

Spaced Reinforcement

Spaced reinforcement rewards optimal recall timing:

spacingMultiplier = min(3.0, 1.0 + log2(1 + daysSinceLastAccess))
diminishingFactor = 1.0 / (1.0 + 0.1 * recallCount)
boost = 0.05 * spacingMultiplier * diminishingFactor
Scenario Boost
1 day gap, first recall +0.05
7 day gap +0.08
30 day gap +0.10
Same day, 20th recall (cramming) +0.02

Each recall also improves the memory's decay rate: new_rate = rate + 0.10 * (0.999 - rate). Memories become progressively more forgetting-resistant with each retrieval.

Salience & Confidence

Salience (0.0-1.0) captures emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned — they must be explicitly forgotten via /brain:forget. They also serve as anchors during consolidation.

Confidence (0.0-1.0) tracks epistemic certainty. Set at encoding based on source quality, reduced when contradictions are found during Knowledge Propagation (-0.20), boosted during validations (+0.10). Low-confidence memories are flagged during recall.

Every memory carries a consent tier: standard (default), sensitive (health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation, and similar), or blocked (government ID numbers, criminal history, immigration status — never stored). Classify honestly when memorizing ("sensitivity": "sensitive"). Sensitive memories are stored only when the user has opted in (sensitive_topics: true in ~/.brain/config.json); otherwise they wait quarantined and hidden until the user approves them (brain verify approve <id>), and their receipts carry ⚠ sensitive. Opting in is never retroactive, and the CLI refuses blocked content outright.

Consolidation

When memories decay below the threshold (default: 0.3), they become candidates for consolidation. The agent groups related weak memories by path proximity, tag overlap, and temporal closeness, then merges them into a single stronger memory:

consolidated_strength = max(source_strengths) + 0.15   (capped at 1.0)
consolidated_decay    = min(source_decay_rates)         (slowest decay wins)

The highest-salience memory in each group serves as the anchor — its framing and key details take priority in the synthesis. Original memories are moved to _archived/ (recoverable and searchable).

Sleep Cycle

/brain:sleep is the brain's overnight maintenance — inspired by how human brains reorganize memories during sleep. It runs nine phases:

  1. Replay — Scans all memories and computes current decayed strengths, categorizing into tiers (Strong / Moderate / Weak / Fading)
  2. Synaptic Homeostasis — If mean strength exceeds 0.5, proportionally scales down ALL strengths to prevent inflation, then selectively re-boosts high-salience, recently-accessed, and frequently-recalled memories. Based on Tononi & Cirelli's SHY hypothesis.
  3. Knowledge Propagation — Evaluates recent memories against the hierarchy (ancestors, descendants, siblings, tag-related, association-linked) and updates existing memories through enrichment, contradiction detection, validation, obsolescence marking, and cross-referencing. Based on memory reconsolidation research.
  4. Semantic Crystallization — Finds frequently-recalled episodic memories and extracts generalizable principles into new semantic memories. The event details begin fading but the lesson persists.
  5. Reorganize — Detects flat clusters (3+ related memories at the same level) and restructures them into deeper sub-categories automatically
  6. Consolidate — Merges weak related memories into stronger combined knowledge with salience anchoring
  7. Prune — Archives memories that have faded below 0.1 strength (salience-protected memories are exempt)
  8. REM Dreaming — Selects random memories from different categories and discovers creative cross-domain connections via analogical reasoning. Scored by novelty, utility, and surprise.
  9. Expertise Detection — Identifies dense knowledge areas and generates expertise profiles, then populates the spaced repetition review queue
Expertise Level Score Meaning
Awareness 0.2 - 0.4 Surface familiarity
Working Knowledge 0.4 - 0.6 Competent with reference
Deep Knowledge 0.6 - 0.8 Strong command, can reason about trade-offs
Expert 0.8 - 1.0 Mastery — dense, frequently-recalled, long-standing

Each expertise area gets an _expertise.md profile documenting what you know well, knowledge gaps, and contributing memories. Sleep can target a specific subtree (e.g., /brain:sleep professional/skills) or process the entire brain.

Spaced Repetition Review

Brain Memory implements the SM-2 algorithm to surface memories at optimal intervals for long-term retention. The review queue is generated and reinforced during /brain:sleep, and tracks:

  • Interval — Time until next review (grows exponentially with successful recalls)
  • Ease factor — How easily the memory is recalled (adjusts based on recall quality 1-5)
  • Review count — Total number of review sessions

Failed recalls reset the interval to 1 day. Successful recalls extend the interval by the ease factor. This ensures you spend time on memories that need reinforcement, not ones you already know well.

Cross-Agent Memory Sharing

~/.brain/ is a single global directory in the user's home folder. All memories are shared across every project and every supported agent automatically. A decision stored by Claude Code in one project is immediately available to OpenAI Codex CLI, OpenCode, or Google Antigravity in any other project — no configuration, no export, no per-project setup. The format is agent-agnostic: plain Markdown files with YAML frontmatter, readable by any tool.

Brain Memory is model-agnostic as well as agent-portable: because memory is plain files rather than embeddings welded to a particular model, the LLM underneath your agent can be anything — GPT, Claude, Gemini, or any model routed through a gateway — and your memory is unaffected. Switch your model or switch your agent, and you keep remembering and pick up exactly where you left off.

To share memories across different machines, use /brain:sync (see below).

Portable Sync — your memory, no lock-in

Your brain is plain files in a folder — sync it however you already sync files. No account or cloud provider is required.

Any synced folder — Point BRAIN_DIR at a folder your existing tools already sync, and you're done:

export BRAIN_DIR="$HOME/Google Drive/brain"   # or Dropbox, iCloud Drive, OneDrive, Syncthing…

Git remote — /brain:sync push/pull ~/.brain/ to any private Git repository (GitHub, GitLab, Codeberg, or self-hosted), using your existing Git/SSH auth.

Export/Import — Pack the entire brain into a single encrypted file for manual transfer via USB, email, or any file-sharing service.

Brain Cloud (optional) — A hosted, zero-config hub if you'd rather not run your own. Entirely optional — everything above works without it.

Key features:

  • Manual push/pull — No background watchers, no auto-sync. You control when data moves.
  • Optional encryption — AES-256-GCM encryption with a user-provided passphrase. When enabled, all files are encrypted before committing or exporting.
  • Merge mode — Import supports merge mode (only import newer files) or overwrite mode.
  • Zero dependencies — Uses Node.js built-in crypto and the system git binary.

Setup:

  1. Create a private Git repo (e.g., gh repo create brain-data --private)
  2. Run /brain:sync setup [email protected]:you/brain-data.git
  3. Use /brain:sync push and /brain:sync pull to keep memories in sync

For one-off transfers, use /brain:sync export and /brain:sync import <path>.

Restore — an undo button for your whole brain. Every push is a restore point, and the CLI can roll the entire brain back to any of them:

brain restore --list                      # list restore points (the Git sync history)
brain restore --to <commit>               # roll ~/.brain/ back to that point
brain restore --list --from cloud         # list Brain Cloud's pre-push snapshots
brain restore --to <version> --from cloud # restore from a cloud snapshot

Before touching anything, restore preserves your current state — the Git path commits it as a safety snapshot, the cloud path writes a local backup under ~/.brain/.cloud/ — so a restore is always undoable, even for work you never pushed. (Brain Cloud also snapshots the brain it's about to replace on every push, server-side.) The append-only audit.log is carried forward through restores (never rolled back), and every restore is itself logged there. Restore granularity follows push frequency: push often for finer-grained history.

Sync state is stored locally in ~/.brain/.sync/ and is never pushed to the remote.

Brain in Claude apps (web & mobile) — beta

Beyond the CLI, you can use your brain from the Claude apps (web, desktop, and your phone) via the Brain connector — a remote MCP server hosted by Brain Cloud. Add it once on claude.ai (Settings → Connectors → Add custom connector → https://mcp.brainmemory.ai/mcp), sign in with the Google account holding your cloud brain, and it syncs to every Claude client on your account. Read and write: recall + status, plus memorize / pin / unpin (writes prompt for confirmation) — so you can capture a memory on your phone and recall it on your laptop.

→ Full guide: Use Brain in Claude apps

Your data, protected. Brains synced to Brain Cloud are encrypted at rest (AES-256-GCM, per-user key); the connector holds working copies in RAM only (never on disk); all traffic is TLS; sessions use rotating, revocable tokens with reuse detection (log out one device or all); and every request is isolated to your account. Prefer the server never sees plaintext? Stay local-only (the default) or use Git/export sync with a passphrase. See SECURITY.md.

File Structure

~/.brain/
├── index.json              # Memory inventory — fast lookup for all memories
├── config.json             # Working-memory token budgets (session-start injection)
├── associations.json       # Weighted associative network between memories
├── contexts.json           # Session context snapshots for context-dependent recall
├── review-queue.json       # Spaced repetition scheduling
├── pinned.json             # Always-present tier manifest (pinned memory IDs + scope)
├── skills-index.json       # Advertised procedural skills (L0 — name + description)
├── _skills/                # Procedural skills
│   └── <skill-name>/
│       ├── SKILL.md        # Advertised description + step-by-step instructions
│       └── resources/      # Optional templates/scripts (loaded only at execution)
├── professional/           # Work, career, technical skills
│   ├── _meta.json          # Category metadata and stats
│   ├── _expertise.md       # Generated expertise profile
│   ├── companies/          # On-demand: created when first needed
│   │   └── <company>/
│   │       ├── projects/
│   │       └── decisions/
│   ├── skills/
│   └── career/
├── personal/               # Education, health, hobbies, goals
│   ├── _meta.json
│   ├── education/
│   ├── health/
│   └── goals/
├── social/                 # Communities, networks, collaborations
│   ├── _meta.json
│   └── communities/
├── family/                 # Family relationships and events
│   ├── _meta.json
│   └── events/
├── _consolidated/          # Merged memories from consolidation
│   └── _meta.json
├── _archived/              # Decayed memories (recoverable + searchable)
│   ├── _meta.json
│   └── index.json          # Searchable archive index
└── .sync/                  # Sync state (local only, never pushed)
    ├── config.json          # Remote URL, encryption flag
    └── repo/                # Hidden git repo for sync

Subdirectories are created on demand — the agent decides placement depth based on how specific the memory is. A generic career thought lands in professional/, but a specific deployment incident goes to professional/companies/acme/projects/alpha/.

Configuration

Brain configuration lives in ~/.brain/index.json under the config key:

{
  "config": {
    "max_depth": 6,
    "consolidation_threshold": 0.3,
    "decay_check_interval_days": 7,
    "strength_boost_on_recall": 0.05,
    "auto_consolidate": true,
    "propagation_window_days": 7,
    "association_config": {
      "co_retrieval_boost": 0.10,
      "link_decay_rate": 0.998,
      "link_prune_threshold": 0.05,
      "spreading_activation_depth": 2,
      "spreading_activation_decay": 0.5
    }
  }
}
Setting Default Description
max_depth 6 Maximum directory nesting depth
consolidation_threshold 0.3 Strength below which memories are consolidation candidates
decay_check_interval_days 7 How often to suggest decay maintenance
strength_boost_on_recall 0.05 Base strength increase per recall event
auto_consolidate true Suggest consolidation when candidates are found
propagation_window_days 7 How far back to look for recent memories during knowledge propagation
association_config.co_retrieval_boost 0.10 Hebbian reinforcement increment for co-retrieved memories
association_config.link_decay_rate 0.998 Daily decay factor for association edge weights
association_config.link_prune_threshold 0.05 Minimum weight before an association link is pruned
association_config.spreading_activation_depth 2 Maximum hops for spreading activation traversal
association_config.spreading_activation_decay 0.5 Decay factor per hop during spreading activation
Sensitive Topics

sensitive_topics (default false). Memories classified sensitive — health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation — are stored only when this is true; otherwise they wait quarantined and hidden until you approve them one by one (brain verify approve <id>). Turning it on is never retroactive. blocked content (government ID numbers, criminal history, immigration status) is refused whatever the setting. See src/sensitivity.js for the exact tiers.

Working-Memory Budget

A separate ~/.brain/config.json (created lazily with safe defaults) caps how much the brain injects into the context window at session start, so the always-present tier can never crowd out your actual work:

{
  "working_memory_budget_tokens": 3000,
  "pin_budget_tokens": 1500,
  "skills_index_budget_tokens": 800,
  "recall_budget_tokens": 700
}
Setting Default Description
working_memory_budget_tokens 3000 Total token ceiling for the whole brain session-start payload
pin_budget_tokens 1500 Sub-budget for pinned, always-present memories
skills_index_budget_tokens 800 Sub-budget for the advertised skills index (L0)
recall_budget_tokens 700 Sub-budget for context-relevant recalled memories

Token counts use a dependency-free heuristic stored on each memory at write time. When pins exceed their budget they're selected by --priority then strength, and the overflow is reported rather than silently dropped.

Benchmark

Brain Memory ships with a controlled benchmark suite grounded in the 2025-2026 SOTA in long-term-memory evaluation. The system itself is a direct implementation of the CoALA agent-memory model (Sumers et al., 2023) — Pinned Tier maps to CoALA's semantic memory, procedural skills to procedural memory.

Six scenarios, each describable in one sentence:

Id Pitch Tests
A Noisy Project Folder "Your brain has 200 memories from 6 projects — does it find the 3 relevant ones?" Retrieval under distractors (LongMemEval-S analog)
B Three Sessions, One Decision "Postgres Monday, gRPC rewrite Wednesday, new resource Friday — still Postgres?" Multi-session continuity + Pinned Tier ablation
C The Contradiction Test "Tabs, then spaces, then tabs again — which version wins?" Decay-weighted recency + contradiction handling
D Skill Progressive Disclosure "Five skills indexed, one needed — does brain load just the one?" CoALA Phase-2 L0/L1/L2 token efficiency
E Continual Coding "Five bugs in order — does bug 5 finish faster than bug 1?" Forward transfer; agent writes memories between tasks
F Abstention "No deployment target in memory — does the agent ask or invent?" Confabulation resistance

Methodology highlights — agent under test is DeepSeek V4 Pro (single-shot), graded by a cross-family judge panel (Gemini + Gemma-4 + Qwen-3.5, majority vote — no judge shares the agent's family, Preference Leakage 2502.01534, PoLL 2404.18796); deterministic distractor haystacks up to 1000 memories; real brain session-start / brain recall integration; tokens-per-successful-task as the headline efficiency metric; every scenario anchored by a no-memory floor and an oracle ceiling.

Results (DeepSeek V4 Pro, 3 runs/arm, June 2026). Scenario A — retrieval under 1000 distractors: brain-full is the only retriever whose memories let the model succeed — it passes 100% while both BM25 (0%) and a vector store (0%) fail to surface the oracle memories — and it does so at the leanest tokens-per-success (3,199) of any passing arm. Scenario D — skills: loading only the relevant skill passes 100% at 1,580 tok/success, ~31% leaner than dumping all skill bodies. Scenarios B (continuity) shows brain efficient-and-correct; C (contradiction) and F (abstention) are honest nulls — the base model handles them without memory. At n=3 the token gaps are directional, not yet significant; the pass-rate gradient is the result. Full tables: brainmemory.ai/docs/benchmarks/results.

Retrieval calibration probe (in-vivo, July 2026). Separate from the controlled suite: a 20-query retrieval probe on a real working brain (177 memories, 1,245 association edges; tag-derived topical queries with known targets) measured the scoring-calibration fix shipped after beta.30. Before: hit@1 90%, MRR 0.950 — and a four-term nonsense control query still returned ten results, the top scoring a confident-looking 0.679. After query-coverage scaling and the relevance floor: hit@1 100% / hit@3 100% / MRR 1.000, the nonsense control returns a single result with honestly low relevance (0.213), and recall latency stays at ~46 ms (p50). Caveats: n=20, single brain, tag-derived queries favor the index's tag field, not judge-graded — this is a calibration probe, not the controlled benchmark above. Method and detail: brainmemory.ai/docs/benchmarks/results.

Run the benchmarks yourself:

cd benchmark
cp .env.example .env   # Add your API keys
npm test               # Unit tests
node harness/runner.js # Full benchmark (cloud APIs)

Live methodology and per-scenario detail: brainmemory.ai/docs/benchmarks · Source: benchmark/

Contributing

Contributions are welcome! See CONTRIBUTING.md for development setup, project structure, and how to submit changes.

References

Brain Memory's architecture and benchmark methodology are grounded in the following work.

Foundations — the agent-memory model Brain implements
Memory benchmarks (the suite this work follows)
  • LongMemEval (arxiv 2410.10813) — distractor haystacks (S / M / Oracle), abstention category, GPT-4o judge with 97% human agreement.
  • MemoryAgentBench (arxiv 2507.05257) — four-competency framework; FactConsolidation inspired Scenario C.
  • SWE-Bench-CL (arxiv 2507.00014) — repo-scoped chronological evaluation; template for Scenario E.
  • LoCoMo (arxiv 2402.17753) — long-conversation memory benchmark.
  • MIRIX (arxiv 2507.07957) — realistic synthetic-but-grounded memory benchmarks.
Methodology — judging and benchmark hygiene
Neuroscience
  • get-shit-done — Structured file-based workflow orchestration for AI agents.

License

MIT

1<p align="center">
2 <img src="assets/icon.png" alt="Brain Memory" width="128" height="128">
3</p>
4 
5<h1 align="center">Brain Memory</h1>
6 
7<p align="center">
8 <a href="https://github.com/omelas-tech/brain/actions/workflows/ci.yml"><img src="https://github.com/omelas-tech/brain/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
9 <a href="https://www.npmjs.com/package/brain-memory"><img src="https://img.shields.io/npm/v/brain-memory" alt="npm version"></a>
10 <a href="https://github.com/omelas-tech/brain/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/brain-memory" alt="license"></a>
11</p>
12 
13A hierarchical, file-system-based memory plugin for AI coding agents. Inspired by human neuroscience — memories are organized into deep nested life-domain categories, connected via associative networks, strengthened through spaced recall, and naturally decay over time.
14 
15One hosted **MCP connector** reaches every major agent and chat app — **Claude Code**, **OpenAI Codex CLI**, **OpenCode**, **GitHub Copilot CLI**, **Kilo**, the **Claude.ai** apps, **ChatGPT**, **Google Antigravity** (Gemini CLI's successor), **OpenClaw** / **NVIDIA NemoClaw**, **Hermes Agent**, and **Goose**. Prefer a free, local-first install? The native plugin runs entirely from `~/.brain/` on Claude Code, Codex, OpenCode, Copilot CLI, Kilo, and Antigravity — and dedicated [native integrations](integrations/) plug the same brain into OpenClaw and Hermes as their memory engine.
16 
17```
18~/.brain/
19├── professional/
20│ └── companies/
21│ └── acme-corp/
22│ └── projects/
23│ └── alpha-launch.md ⚡ 0.88
24├── personal/
25│ └── education/
26│ └── typescript-generics.md ⚡ 0.72
27├── social/
28│ └── communities/
29│ └── open-source-contrib.md ⚡ 0.65
30└── family/
31 └── events/
32 └── annual-reunion-planning.md ⚡ 0.55
33```
34 
35## Why Brain Memory?
36 
37Existing AI memory solutions use flat databases with tag-based retrieval. Brain Memory is different:
38 
39- **The directory tree IS the semantic structure** — `professional/companies/acme/projects/` tells the agent everything about context without vector search
40- **Human-inspectable** — Browse your "brain" in any file explorer
41- **Git-friendly** — Full version history of how memories evolve
42- **Strength + decay** — Recalled memories get stronger, forgotten ones fade. Just like your brain
43- **Recall receipts** — Memory that visibly fires: every answer shaped by a memory ends with a one-line attributable receipt (`◉ memory: "<title>" (<type>, <age>)`), minted by the engine so it can't be hallucinated
44- **Provenance-bounded trust** — Every memory records where it came from (`user`, `agent-inferred`, `tool-output`, `external`), and recall weighs it: a fact planted by a web page or tool output is down-ranked, flagged `low_trust`, marked `⚠` on its receipt, and can never outrank what you said directly — no matter how many copies of it get written. And because memories are plain files, Brain records a **SHA-256 baseline** of each one at write time — so `brain audit` also catches a memory edited *outside* any write path, the one poisoning route every write-path defense is blind to
45- **Bitemporal — it knows *when* a fact was true** — Every memory separates record time (when the brain learned it) from valid time (`valid_from` / `valid_until`, when it was actually true). So "we deploy to Fly.io" and "we deploy to Render" aren't a contradiction to guess between — they're one fact with a boundary. `brain recall "deploy target" --as-of 2026-03-01` answers what was true in March; `--as-known-of` answers what the brain knew then. Facts that stopped being true are demoted and marked `⌛ expired`, never silently served as current
46- **Deterministic recall — every agent ranks identically** — Scoring is arithmetic over files, not a model call: TF-IDF/BM25 relevance, decayed strength, spreading activation, context match, salience. Claude, Codex, and Gemini asking the same question of the same brain get the *same* ranking, in the same order, offline. No embedding-model version can silently reshuffle what your agent remembers
47- **Associative network** — Memories link to each other with weighted connections. Recalling one activates related ones automatically
48- **Context-dependent recall** — Memories encoded in a similar context to the current session are scored higher
49- **Spaced reinforcement** — Memories recalled after longer intervals get bigger boosts, cramming produces diminishing returns
50- **Cognitive types** — Episodic, semantic, and procedural memories each decay differently, just like in the brain
51- **Always-present knowledge** — Pin critical conventions and preferences so they load every session, bypassing recall and never decaying — the facts your agent must never miss
52- **Procedural skills** — Reusable how-to workflows with progressive disclosure, learned automatically from repeated experience and exportable to your agent's native skills
53- **On-demand depth** — Subcategories are created as needed, not pre-defined
54- **Consolidation** — Weak related memories merge into stronger combined knowledge
55- **Zero dependencies — and measured, not assumed** — Pure file I/O: no database, no server, no embedding model. That is a deliberate result, not a shortcut. On our hardest retrieval scenario (1,021 memories, 1,000 plausible distractors) a real embedding model ranked the target memories *worse* than BM25 — see the [retrieval-only pilot](benchmark/README.md#retrieval-only-pilot-no-agent-no-llm-spend)
56 
57## Install
58 
59There are two ways to give an agent its brain. They are complementary — most people end up with both:
60 
61| Path | Reaches | Storage | Cost | Best for |
62|------|---------|---------|------|----------|
63| **Hosted MCP connector** | Every MCP-capable host (Claude Code, Codex CLI, OpenCode, Copilot CLI, Kilo, Claude.ai apps, ChatGPT, Antigravity, OpenClaw, Hermes, Goose) | Brain Cloud (hosted) | account | One connector, everywhere — including web & mobile chat |
64| **Local-first native plugin** | The current CLIs (Claude Code, Codex CLI, OpenCode, Copilot CLI, Kilo, Antigravity) | `~/.brain/` on your machine | free | Zero-config ambient memory, no account, files you own |
65| **[Assistant integrations](integrations/)** | OpenClaw / NVIDIA NemoClaw (memory-slot plugin), Hermes Agent (memory provider) | `~/.brain/` on your machine | free | Your always-on personal assistant sharing one brain with your coding agents |
66 
67### 1. Universal path — the hosted MCP connector
68 
69Brain Cloud exposes a single remote MCP server (streamable-HTTP + OAuth) at **`https://mcp.brainmemory.ai/mcp`**. Add it once per host and that host can recall, memorize, pin, and check status — no local install, no per-project setup. It works everywhere MCP does, including the chat apps that can't run a native plugin.
70 
71```bash
72# Claude Code
73claude mcp add --transport http brain https://mcp.brainmemory.ai/mcp
74 
75# OpenAI Codex CLI
76codex mcp add brain --url https://mcp.brainmemory.ai/mcp
77```
78 
79<details>
80<summary>Per-host setup for every other connector</summary>
81 
82- **Codex CLI (config file)** — add to `~/.codex/config.toml`:
83 ```toml
84 [mcp_servers.brain]
85 url = "https://mcp.brainmemory.ai/mcp"
86 ```
87- **OpenCode** — add to `opencode.json`:
88 ```json
89 {
90 "mcp": {
91 "brain": { "type": "remote", "url": "https://mcp.brainmemory.ai/mcp" }
92 }
93 }
94 ```
95- **Claude.ai / ChatGPT** — **Settings → Connectors → Add custom connector**, paste `https://mcp.brainmemory.ai/mcp`, and complete the OAuth sign-in. (ChatGPT requires a paid plan or Developer Mode.)
96- **Google Antigravity** — add to `mcp_config.json` under the `serverUrl` key. *(Legacy Gemini CLI used the `httpUrl` key in `settings.json`.)*
97- **GitHub Copilot CLI** — add to `~/.copilot/mcp-config.json` (OAuth via `/mcp auth brain` in-session):
98 ```json
99 {
100 "mcpServers": {
101 "brain-memory": { "type": "http", "url": "https://mcp.brainmemory.ai/mcp", "tools": ["*"] }
102 }
103 }
104 ```
105- **OpenClaw** — `openclaw mcp add brain-memory --url https://mcp.brainmemory.ai/mcp --auth oauth`, then `openclaw mcp login brain-memory`. (Inside NVIDIA NemoClaw, allowlist the endpoint first — see [integrations/openclaw](integrations/openclaw/).)
106- **Hermes Agent** — add to `~/.hermes/config.yaml`:
107 ```yaml
108 mcp_servers:
109 brain: { url: "https://mcp.brainmemory.ai/mcp", auth: oauth }
110 ```
111- **Goose** — add a remote extension (streamable-HTTP) pointing at `https://mcp.brainmemory.ai/mcp`.
112- **Kilo** — add to `kilo.jsonc` (OAuth starts automatically):
113 ```json
114 {
115 "mcp": {
116 "brain-memory": { "type": "remote", "url": "https://mcp.brainmemory.ai/mcp", "enabled": true }
117 }
118 }
119 ```
120 
121</details>
122 
123The first time a host connects you'll complete an OAuth sign-in with the Google account that holds your cloud brain; the connector then syncs to every client on that account. See **[Use Brain in Claude apps](https://brainmemory.ai/docs/getting-started/claude-apps)** for the full walkthrough.
124 
125### 2. Local-first path — the native plugin
126 
127```bash
128npm install -g brain-memory
129brain
130```
131 
132The first command installs the package globally — this gives you both the interactive setup wizard and the `brain` CLI (`brain recall`, `brain memorize`, `brain reinforce`, …) that agents rely on for deterministic scoring.
133 
134The second command runs the setup wizard, which asks which runtime(s) to configure and whether to install globally or for the current project. Each runtime gets its instructions file plus the brain commands/skills:
135 
136| Runtime | Instructions file | Commands land at |
137|---------|-------------------|------------------|
138| **Claude Code** | `CLAUDE.md` | `~/.claude/commands/brain/` (plugin slash commands) |
139| **OpenAI Codex CLI** | `AGENTS.md` (`~/.codex/`) + hooks in `~/.codex/hooks.json` (SessionStart, UserPromptSubmit, SessionEnd — trust once via `/hooks`) | `~/.agents/skills/<name>/SKILL.md` |
140| **OpenCode** | `AGENTS.md` | `~/.config/opencode/commands/` |
141| **GitHub Copilot CLI** | `copilot-instructions.md` (`~/.copilot/`), repo-local `AGENTS.md` | `~/.agents/skills/<name>/SKILL.md` (shared with Codex) |
142| **Kilo** | `rules/brain-memory.md` + `kilo.jsonc` `instructions` entry (`~/.config/kilo/`), repo-local `AGENTS.md` | `~/.config/kilo/commands/` |
143| **Google Antigravity** | `GEMINI.md` | `~/.gemini/skills/` *(experimental — verify paths against a live install)* |
144 
145#### Plugin install — Claude Code, Codex, ChatGPT workspaces
146 
147This repository is also a plugin marketplace. Installing the `brain` plugin gives Claude Code and Codex the same `/brain:*` commands **plus deterministic hooks**: `SessionStart` injects the budget-bounded `brain session-start` payload as context (no prompt file to edit, nothing for the model to remember to run) and `SessionEnd` records the session boundary in `~/.brain/contexts.json`. The plugin bundles the CLI, so no npm install is required for the hooks.
148 
149```bash
150# Claude Code
151claude plugin marketplace add omelas-tech/brain
152claude plugin install brain@brain-memory # local-first: hooks + /brain:* commands
153claude plugin install brain-cloud@brain-memory # optional: the hosted MCP connector
154 
155# Codex CLI — same repo, same two plugins (Codex reads the Claude manifests)
156codex /plugins # then add marketplace omelas-tech/brain
157```
158 
159**ChatGPT Business / Enterprise / Edu:** a workspace admin imports the marketplace once (Admin → Plugins → Add → Import marketplace → `https://github.com/omelas-tech/brain`) and the workspace picks up new versions daily. `brain` (skills + hooks) serves Codex users in the workspace; `brain-cloud` (the MCP connector) serves ChatGPT desktop. Import does not grant access by itself — each user completes the connector's OAuth sign-in on first use.
160 
161#### Non-interactive
162 
163```bash
164brain --claude --global # Claude Code, global
165brain --codex --global # OpenAI Codex CLI, global
166brain --opencode --global # OpenCode, global
167brain --copilot --global # GitHub Copilot CLI, global
168brain --kilo --global # Kilo, global
169brain --antigravity --global # Google Antigravity, global (experimental)
170brain --all --global # All runtimes, global
171```
172 
173These run without a terminal, so an agent or a CI job can install brain itself. With no terminal to ask on, the installer initializes `~/.brain/` if it doesn't exist yet (it never overwrites an existing brain) — add `--yes` to skip that question outright. Leave out the runtime and it stops with an error rather than guessing.
174 
175For the deepest Copilot CLI integration — deterministic session-start context injection via its `sessionStart` hook — install the [Copilot plugin](integrations/copilot/) from the brain marketplace:
176 
177```bash
178copilot plugin marketplace add omelas-tech/brain
179copilot plugin install brain-memory@brain
180```
181 
182Kilo gets the same treatment via its runtime plugin — deterministic session-start injection, session tracking, and `BRAIN_AGENT` labeling ([details](integrations/kilo/)):
183 
184```bash
185mkdir -p ~/.config/kilo/plugin
186cp integrations/kilo/plugin/brain-memory.js ~/.config/kilo/plugin/
187```
188 
189### 3. Personal-assistant integrations — OpenClaw, NemoClaw, Hermes
190 
191Always-on personal assistants get deeper, first-class integrations that make `~/.brain/` their actual memory engine — the same brain your coding agents read and write:
192 
193- **[OpenClaw / NVIDIA NemoClaw](integrations/openclaw/)** — a native **memory-slot plugin** (`openclaw plugins install openclaw-brain-memory` + `plugins.slots.memory: "brain-memory"`) that replaces `memory-core` with deterministic brain recall, session-start context injection, and model-driven capture. Also ships a slot-neutral hook pack, a ClawHub skill, and a NemoClaw egress-policy preset.
194- **[Hermes Agent](integrations/hermes/)** — a native **memory provider** (`plugins/memory/brain/`) implementing the full `MemoryProvider` lifecycle: session-start prompt block, pre-turn prefetch, `brain_recall`/`brain_memorize`/`brain_reinforce` tools, and session-context logging. Plus lightweight hook-script glue if you keep another provider active.
195 
196Both are backed by the same `brain` CLI the coding-agent installs use — one memory, every agent.
197 
198### Update
199 
200```bash
201npm install -g brain-memory
202brain update
203```
204 
205The first command updates the package and the `brain` CLI. The second command refreshes the slash command prompts for your installed runtimes. Target specific runtimes with `--claude`, `--codex`, `--opencode`, `--antigravity`, or `--all`.
206 
207> **Upgrading from an older version?** The separate binaries (`brain-recall`, `brain-memorize`, `brain-reinforce`, `brain-cloud`, `brain-memory`) were unified into a single `brain` dispatcher — use `brain recall`, `brain memorize`, `brain reinforce`, `brain cloud <…>` instead. Run `brain update` to refresh your runtime prompts to the new command surface.
208 
209> **Why not `npx`?** `npx` runs the setup wizard in a temporary directory that is discarded after execution. The `brain` CLI (`brain recall`, `brain memorize`, `brain reinforce`) won't be available in your PATH, which means agents will fall back to less reliable manual file operations. Always use `npm install -g` to ensure everything works correctly.
210 
211> **Using nvm, fnm, asdf, mise or nodenv?** `npm install -g` puts `brain` inside whichever Node version is active, and only there. The command then disappears when your default version moves — a `22` alias drifting to a newer 22.x is enough — and shells that never load the version manager (agent hooks, GUI-launched agents, non-interactive shells) can't see it at all. Nothing errors: agents quietly fall back to editing memory files by hand, and it looks like brain works "sometimes". Install brain-memory with a system Node instead (Homebrew, apt, the nodejs.org installer) so `brain` lives in one stable place. npm takes its global prefix from the `node` that runs it, so put the system Node first on `PATH` for that one command — on macOS with Homebrew: `PATH="/opt/homebrew/bin:$PATH" npm install -g brain-memory`. Check with `which -a brain`; it should print exactly one path, outside your version manager's directory. The installer warns when it detects this. Volta is fine as-is — it keeps global packages available across versions.
212 
213### Uninstall
214 
215```bash
216brain uninstall
217npm uninstall -g brain-memory
218```
219 
220The first command removes slash commands and prompt sections from your agent configs. The second removes the package and CLI tools. Your `~/.brain/` directory (memories) is preserved by default. Add `--delete-data` to the uninstall command to remove it too. Use `--yes` to skip confirmation prompts.
221 
222### Manual Install
223 
224If you'd rather wire up the native plugin by hand, copy the brain commands into your agent's folder, then append the matching prompt file to its instructions file.
225 
226```bash
227# Claude Code — flat slash commands
228cp -r commands/brain/ ~/.claude/commands/brain/
229 
230# OpenCode — flat slash commands
231mkdir -p ~/.config/opencode/commands/brain
232cp -r commands/brain/. ~/.config/opencode/commands/brain/
233 
234# OpenAI Codex CLI — each command becomes a skill under the cross-tool skills dir
235for f in commands/brain/*.md; do
236 name=$(basename "$f" .md)
237 mkdir -p ~/.agents/skills/brain-"$name"
238 cp "$f" ~/.agents/skills/brain-"$name"/SKILL.md
239done
240 
241# Google Antigravity (experimental — verify paths) — skills under ~/.gemini/skills/
242for f in commands/brain/*.md; do
243 name=$(basename "$f" .md)
244 mkdir -p ~/.gemini/skills/brain-"$name"
245 cp "$f" ~/.gemini/skills/brain-"$name"/SKILL.md
246done
247```
248 
249Then append the contents of the corresponding prompt file to your agent's instructions file:
250- `prompts/claude.md` → `CLAUDE.md`
251- `prompts/openai.md` → `AGENTS.md` (Codex, in `~/.codex/`)
252- `prompts/opencode.md` → `AGENTS.md` (OpenCode)
253- `prompts/antigravity.md` → `GEMINI.md` (experimental)
254 
255> **`AGENTS.md` collision (local scope):** Codex and OpenCode both read a project-local `AGENTS.md`. If you install both for the *same* project, point only one at the local file (or install one globally) so their brain sections don't conflict. Globally they're separate (`~/.codex/AGENTS.md` vs OpenCode's own config dir).
256 
257## Commands
258 
259The everyday loop is **ambient** — `remember` and `memorize` run automatically at session start/end, so you rarely type a command. The surface is a small core plus a background maintenance job:
260 
261| Command | Description |
262|---------|-------------|
263| `/brain:remember [query]` | Recall relevant memories with spreading activation and context matching |
264| `/brain:memorize [topic] [--sync]` | Store memories from current session context (add `--sync` to auto-push) |
265| `/brain:status` | Dashboard with brain health metrics and recommendations |
266| `/brain:pin [id\|query]` | Pin a memory to the always-present tier — loads every session, never decays. Toggles: also unpins (`--off`) |
267| `/brain:forget [target]` | Decay, archive, or remove memories. `--deep` performs forensic erasure — traces and removes every reference |
268| `/brain:import [--project P] [--since 30d]` | Cold-start a new brain from transcripts your agents already wrote. Incremental — safe to re-run |
269| `/brain:sync [subcommand]` | Sync via Brain Cloud, Git remote, or export/import (auto-initializes the brain on first run) |
270| `/brain:skills [list\|show\|add\|use\|remove\|export]` | Manage procedural skills — reusable how-to workflows with progressive disclosure |
271| `/brain:sleep [scope]` | Full maintenance cycle — 9 neuroscience-inspired phases (replay, consolidation, review reinforcement, pruning, dreaming, …). Usually runs automatically/in the background |
272 
273## Cold Start
274 
275A new brain is empty, and an empty brain is worth nothing until something fills it. But your agents have been keeping local transcripts for months — decisions, preferences, corrections, conventions. `/brain:import` reads them.
276 
277```bash
278brain import --sources # what history exists on this machine
279brain import --project my-app # digest that project's past sessions
280brain import --since 30d # or scope by time
281```
282 
283The split matters. The CLI **harvests** — deterministic, budget-bounded, no model call: it extracts session titles, user prompts, projects, branches, and edited files, filters out harness noise and subagent traffic, and interleaves across projects so one busy repo can't eat the budget. The agent then **distills** that digest into memories through the ordinary `brain memorize` path.
284 
285That split is deliberate. Extracting meaning is a semantic judgement, and doing it in the CLI would mean shipping an embedding model or calling an LLM — the two things Brain exists to avoid. So the harvester reports facts and never infers, and every imported memory lands as `agent-inferred` provenance: it inherits the existing ceilings for free, and **an import can never pin, entrench, or outrank something you said directly.**
286 
287Import is incremental. A cursor in `~/.brain/.import/state.json` records which sessions have been read, so re-running only offers new ones (`--all` overrides). Nothing is written without you — `brain import` only ever reads and prints.
288 
289## Session Lifecycle
290 
291Brain Memory works automatically in the background — no commands needed for basic context awareness.
292 
293### Session Start
294 
295When a session begins and `~/.brain/` exists, the agent makes a single `brain session-start` call. This aggregator returns one deterministic, **token-budget-bounded** payload so the brain can never bloat the context window (the budget lives in `~/.brain/config.json`):
296 
2971. **Pinned memories** — always-present conventions and preferences, injected verbatim regardless of recall score
2982. **Skills index** — the name + description of each available procedural skill (~100 tokens each; full instructions are loaded only when a task matches)
2993. **Context recall** — the top memories relevant to the current project
3004. **Review queue + low-confidence alerts**, then a brief status line:
301 
302```
303◉ Brain active — 42 memories loaded (8 in current project context)
304📋 3 memories due for review — reinforced automatically during /brain:sleep
305```
306 
307The agent treats pinned facts as active constraints, notes which skills exist, silently internalizes relevant memories, and references them naturally during the session — no information dump.
308 
309### Ambient Session Tracking
310 
311Throughout the session, the agent maintains a running mental log of notable events — decisions made, things learned, insights realized, significant experiences. This is purely internal awareness with no file writes. It ensures that early-session events aren't forgotten by the time the session ends.
312 
313### Periodic Memory Checkpoint
314 
315Every ~10 substantive interactions (file edits, architecture decisions, debugging breakthroughs), the agent evaluates whether memorizable content has accumulated. If so, it appends a brief reminder to its next response:
316 
317```
318◉ Notable decisions and learnings this session — /brain:memorize when ready
319```
320 
321This never interrupts your flow — it's a one-liner appended to an existing response, at most once per ~10 interactions. The counter resets after you run `/brain:memorize`.
322 
323### Session End
324 
325When a session ends, the agent performs two steps in order:
326 
3271. **Saves session context** to `~/.brain/contexts.json` — always, even for trivial sessions. This includes a `notable_unsaved` field listing items you didn't memorize, so future sessions can reference what happened.
328 
3292. **Suggests memorization** if the session contained meaningful decisions, learnings, or insights:
330 
331```
332💡 This session contained notable decisions and learnings.
333 Would you like to store them as brain memories?
334 Run /brain:memorize to capture them before this context is lost.
335```
336 
337The agent never auto-memorizes without user consent. Context is saved proactively — the agent doesn't wait for an explicit goodbye signal.
338 
339## How It Works
340 
341### Memory Lifecycle
342 
343```
344Create → Store → Decay → Recall → Reinforce → Review → Sleep → Archive
345 ↑ │
346 └── Associations ────┘
347```
348 
3491. **Create** — When you use `/brain:memorize`, the agent analyzes the session and extracts significant decisions, learnings, insights, or experiences
3502. **Store** — Each memory is filed into the hierarchy at the appropriate depth, with YAML frontmatter tracking metadata. Association edges are created to related memories.
3513. **Decay** — Memories naturally weaken over time: `effective_strength = base_strength * (decay_rate ^ days_since_access)`
3524. **Recall** — `/brain:remember` searches, scores with spreading activation and context matching, and returns the best memories. Archived memories are searched as a fallback.
3535. **Reinforce** — Each recall applies spaced reinforcement (longer gaps = bigger boosts) and improves the memory's decay resistance
3546. **Review** — SM-2 spaced repetition surfaces memories at optimal intervals for long-term retention; reinforcement runs automatically during the sleep cycle
3557. **Sleep** — `/brain:sleep` performs a 9-phase maintenance cycle inspired by real neuroscience (replay, consolidation, review reinforcement, pruning, dreaming, …), usually run automatically/in the background
3568. **Archive** — Fully decayed memories move to `_archived/` (recoverable and searchable) or can be permanently deleted
357 
358### Neuroscience Foundations
359 
360Brain Memory is grounded in peer-reviewed neuroscience research. Here's how each mechanism maps to the brain:
361 
362| Brain Mechanism | Implementation |
363|-----------------|---------------|
364| **Spreading activation** | Recalling memory A automatically surfaces linked memories B and C via weighted association graph |
365| **Hebbian learning** | "Neurons that fire together wire together" — memories recalled together strengthen mutual links |
366| **Context-dependent recall** | Memories encoded in a similar context (project, task type) are scored higher at retrieval |
367| **Spacing effect** | Longer intervals between recalls produce larger strength boosts; cramming yields diminishing returns |
368| **Ebbinghaus decay** | Exponential forgetting curve with per-memory decay rates |
369| **Episodic → Semantic** | Event-specific memories crystallize into abstract principles during sleep |
370| **Synaptic homeostasis (SHY)** | Global strength downscaling during sleep prevents inflation, then selectively re-boosts important memories |
371| **REM dreaming** | Creative cross-domain association discovery via analogical reasoning |
372| **Memory reconsolidation** | Recent knowledge updates and reshapes older related memories during sleep |
373| **Cue-dependent forgetting** | Archival preserves availability — memories aren't deleted, just moved to `_archived/` |
374| **Targeted forgetting** | Deep erasure that traces and removes all references, like how the brain can selectively erase specific memory traces |
375 
376### Memory Types
377 
378| Type | Base Strength | Daily Decay | Use Case |
379|------|:---:|:---:|---|
380| `insight` | 0.90 | 0.997 | Deep realizations, patterns discovered |
381| `decision` | 0.85 | 0.995 | Choices made and their rationale |
382| `goal` | 0.80 | 0.993 | Objectives and aspirations |
383| `experience` | 0.75 | 0.985 | Notable events or processes |
384| `learning` | 0.70 | 0.990 | New knowledge acquired |
385| `relationship` | 0.70 | 0.997 | Connections between people/things |
386| `preference` | 0.60 | 0.998 | User style and preferences |
387| `observation` | 0.40 | 0.950 | Casual facts or notices |
388 
389### Cognitive Types
390 
391Each memory is also classified by how the brain processes it:
392 
393| Cognitive Type | Strength Modifier | Decay Behavior | Example |
394|----------------|:-:|---|---|
395| **Episodic** | +0.10 | Faster decay — event details fade | "The deploy failed Tuesday because of X" |
396| **Semantic** | default | Standard decay — stable knowledge | "React hooks must follow rules of hooks" |
397| **Procedural** | -0.10 | Very slow decay — skills persist | "Steps to debug memory leaks" |
398 
399During sleep, frequently-recalled episodic memories are **crystallized** into semantic memories — the specific event fades but the lesson persists. This mirrors how humans extract general principles from repeated experiences.
400 
401### Always-Present Memories (Pinning)
402 
403Recall is probabilistic — a stored preference only applies if scoring happens to surface it. For the facts an agent must **never** miss (coding conventions, standing decisions, hard constraints), that's not good enough. Pinning fixes it:
404 
405- **`pinned`** — the memory is injected at **every** session start regardless of recall score, and is **decay-exempt** (it never fades). Scope it `global` (loads everywhere) or `project:<name>` (loads only in that project).
406- **`stable`** — an independent flag that exempts a memory from decay and pruning **without** forcing it to always load — for timeless facts you recall on demand but don't want to fade.
407 
408```bash
409brain pin <id> --scope global --priority 1 # or: /brain:pin always use tabs
410```
411 
412Pinned and stable memories are skipped by sleep-cycle homeostasis and pruning, and `/brain:memorize` proactively proposes pinning durable conventions. The always-present set is budget-capped (`pin_budget_tokens`) so it can't crowd out the context window. This maps cleanly to the **semantic memory** type in the [CoALA](https://arxiv.org/abs/2309.02427) agent-memory model — knowledge that is always in context — decomposed into two orthogonal properties (always-loaded vs. non-decaying).
413 
414### Procedural Skills
415 
416Procedural memory is *how* to do things — reusable, step-by-step workflows stored as `~/.brain/_skills/<name>/SKILL.md`. To keep them from flooding the context window, skills use **three-level progressive disclosure**:
417 
418| Level | When | What loads |
419|-------|------|------------|
420| **L0** | Every session start | Only each skill's name + description (~100 tokens) |
421| **L1** | A task matches a skill | The full `SKILL.md` step-by-step instructions |
422| **L2** | A step needs them | Referenced `resources/` (templates, scripts) |
423 
424```bash
425brain skill list # advertised skills (L0)
426brain skill show structured-code-review # full instructions (L1)
427brain skill use structured-code-review # record outcome (--failed weakens it)
428brain skill export structured-code-review --target claude # → native .claude/skills/
429```
430 
431Skills strengthen on successful `use` and weaken on `--failed` — one that fails too often demotes itself out of the advertised L0 index. And they aren't only hand-authored: during sleep, Brain **crystallizes** recurring task-solving patterns from repeated experience into new skills (user-confirmed). Finally, `brain skill export` emits a skill in your agent's **native** format so it becomes directly executable.
432 
433### Memory File Format
434 
435Each memory is a Markdown file with YAML frontmatter:
436 
437```markdown
438---
439id: mem_20260213_a3f2c1
440type: decision
441cognitive_type: semantic
442created: 2026-02-13T14:30:00Z
443last_accessed: 2026-02-13T14:30:00Z
444access_count: 3
445recall_history: ["2026-02-13T14:30:00Z", "2026-02-13T18:00:00Z", "2026-02-14T09:00:00Z"]
446strength: 0.92
447decay_rate: 0.995
448salience: 0.8
449confidence: 0.9
450# Valid time — when the fact was TRUE, as distinct from `created` above (when
451# it was recorded). Optional and half-open [from, until); omit for facts that
452# are simply true. Superseding stamps `valid_until` on the old memory for you.
453valid_from: 2026-02-13T14:30:00Z
454tags: [architecture, microservices, scaling]
455related: [mem_20260210_b4e5d6]
456source: project-alpha-session
457encoding_context:
458 project: project-alpha
459 topics: [architecture, scaling, kafka]
460 task_type: designing
461---
462 
463# Chose Event-Driven Architecture for Project Alpha
464 
465We decided to use event-driven architecture with Kafka instead of synchronous
466REST calls between services, because the traffic analysis showed 10x burst
467patterns that would overwhelm synchronous endpoints.
468 
469## Context
470 
471Sprint planning for Q2, evaluating scaling strategy for the notification system.
472 
473## Key Details
474 
475- Kafka chosen over RabbitMQ for its replay capability
476- Event schema registry added to prevent breaking changes
477- Estimated 3-week implementation vs 1-week for REST (but REST would need rework at scale)
478 
479## Connections
480 
481Related to the capacity planning decision (mem_20260210_b4e5d6) where we
482identified the 10x burst pattern in notification traffic.
483```
484 
485### Scoring Formula
486 
487When recalling memories, each candidate is scored using a 6-factor formula:
488 
489```
490score = 0.38 * relevance
491 + 0.18 * decayed_strength
492 + 0.08 * recency_bonus
493 + 0.14 * spreading_bonus
494 + 0.14 * context_match
495 + 0.08 * salience
496```
497 
498- **relevance** (0.38) — How well the memory matches the query
499- **decayed_strength** (0.18) — Base strength after time decay
500- **recency_bonus** (0.08) — Linear bonus that fades over one year
501- **spreading_bonus** (0.14) — Activation received from linked memories in the association graph
502- **context_match** (0.14) — How similar the encoding context is to the current session
503- **salience** (0.08) — Emotional/motivational significance
504 
505Relevance is **calibrated in absolute terms**: BM25 scores are scaled by
506IDF-weighted *query coverage*, so a memory matching one term of a four-term query
507cannot claim relevance 1.0 just for being the best available match. Explicit-query
508recall also applies a **relevance floor** — memories that are neither
509query-relevant nor activated by a relevant associate are excluded rather than
510padding the results on strength alone. A query about things the brain doesn't
511know returns few results with honestly low scores (or none), instead of
512confident-looking noise. Context-mode recall (session start) is exempt, where
513strength-ranked topical padding is the intended behavior.
514 
515The agent then decides the response strategy:
516- **Single strong match** (top score > 0.7) → Return the full memory
517- **Multiple related** (2-5 candidates > 0.4) → Synthesize a consolidated response
518- **Many weak** (>5, all < 0.4) → List candidates for the user to choose
519- **No active matches** → Search the archive, then suggest alternatives
520 
521### Associative Network
522 
523Memories are connected via weighted edges in `~/.brain/associations.json`:
524 
525```json
526{
527 "edges": {
528 "mem_20260213_a3f2c1": {
529 "mem_20260210_b4e5d6": {
530 "weight": 0.45,
531 "co_retrievals": 3,
532 "last_activated": "2026-02-14T09:00:00Z",
533 "origin": "co_retrieval"
534 }
535 }
536 }
537}
538```
539 
540**Spreading activation**: When you recall memory A, activation spreads along weighted edges to surface related memories B and C — even if they didn't match the query directly. Activation decays by 50% per hop, up to 2 hops deep.
541 
542**Hebbian learning**: When multiple memories are recalled together, their mutual edge weights are strengthened: `new_weight = min(1.0, weight + 0.10 * (1.0 - weight))`. Memories that fire together wire together.
543 
544**Link dynamics**: Edges decay over time (`weight * 0.998^days`) and are pruned below 0.05 during sleep. New links are created automatically when memories share 2+ tags (weight 0.10) or are explicitly related (weight 0.20).
545 
546### Spaced Reinforcement
547 
548Spaced reinforcement rewards optimal recall timing:
549 
550```
551spacingMultiplier = min(3.0, 1.0 + log2(1 + daysSinceLastAccess))
552diminishingFactor = 1.0 / (1.0 + 0.1 * recallCount)
553boost = 0.05 * spacingMultiplier * diminishingFactor
554```
555 
556| Scenario | Boost |
557|----------|:---:|
558| 1 day gap, first recall | +0.05 |
559| 7 day gap | +0.08 |
560| 30 day gap | +0.10 |
561| Same day, 20th recall (cramming) | +0.02 |
562 
563Each recall also improves the memory's decay rate: `new_rate = rate + 0.10 * (0.999 - rate)`. Memories become progressively more forgetting-resistant with each retrieval.
564 
565### Salience & Confidence
566 
567**Salience** (0.0-1.0) captures emotional/motivational significance. High-salience memories (>= 0.7) are **never auto-pruned** — they must be explicitly forgotten via `/brain:forget`. They also serve as anchors during consolidation.
568 
569**Confidence** (0.0-1.0) tracks epistemic certainty. Set at encoding based on source quality, reduced when contradictions are found during Knowledge Propagation (-0.20), boosted during validations (+0.10). Low-confidence memories are flagged during recall.
570 
571### Sensitive Topics (Consent)
572Every memory carries a consent tier: `standard` (default), `sensitive` (health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation, and similar), or `blocked` (government ID numbers, criminal history, immigration status — never stored). Classify honestly when memorizing (`"sensitivity": "sensitive"`). Sensitive memories are stored only when the user has opted in (`sensitive_topics: true` in `~/.brain/config.json`); otherwise they wait quarantined and hidden until the user approves them (`brain verify approve <id>`), and their receipts carry `⚠ sensitive`. Opting in is never retroactive, and the CLI refuses `blocked` content outright.
573 
574### Consolidation
575 
576When memories decay below the threshold (default: 0.3), they become candidates for consolidation. The agent groups related weak memories by path proximity, tag overlap, and temporal closeness, then merges them into a single stronger memory:
577 
578```
579consolidated_strength = max(source_strengths) + 0.15 (capped at 1.0)
580consolidated_decay = min(source_decay_rates) (slowest decay wins)
581```
582 
583The highest-salience memory in each group serves as the anchor — its framing and key details take priority in the synthesis. Original memories are moved to `_archived/` (recoverable and searchable).
584 
585### Sleep Cycle
586 
587`/brain:sleep` is the brain's overnight maintenance — inspired by how human brains reorganize memories during sleep. It runs nine phases:
588 
5891. **Replay** — Scans all memories and computes current decayed strengths, categorizing into tiers (Strong / Moderate / Weak / Fading)
5902. **Synaptic Homeostasis** — If mean strength exceeds 0.5, proportionally scales down ALL strengths to prevent inflation, then selectively re-boosts high-salience, recently-accessed, and frequently-recalled memories. Based on Tononi & Cirelli's SHY hypothesis.
5913. **Knowledge Propagation** — Evaluates recent memories against the hierarchy (ancestors, descendants, siblings, tag-related, association-linked) and updates existing memories through enrichment, contradiction detection, validation, obsolescence marking, and cross-referencing. Based on memory reconsolidation research.
5924. **Semantic Crystallization** — Finds frequently-recalled episodic memories and extracts generalizable principles into new semantic memories. The event details begin fading but the lesson persists.
5935. **Reorganize** — Detects flat clusters (3+ related memories at the same level) and restructures them into deeper sub-categories automatically
5946. **Consolidate** — Merges weak related memories into stronger combined knowledge with salience anchoring
5957. **Prune** — Archives memories that have faded below 0.1 strength (salience-protected memories are exempt)
5968. **REM Dreaming** — Selects random memories from different categories and discovers creative cross-domain connections via analogical reasoning. Scored by novelty, utility, and surprise.
5979. **Expertise Detection** — Identifies dense knowledge areas and generates expertise profiles, then populates the spaced repetition review queue
598 
599| Expertise Level | Score | Meaning |
600|-------|:---:|---------|
601| Awareness | 0.2 - 0.4 | Surface familiarity |
602| Working Knowledge | 0.4 - 0.6 | Competent with reference |
603| Deep Knowledge | 0.6 - 0.8 | Strong command, can reason about trade-offs |
604| Expert | 0.8 - 1.0 | Mastery — dense, frequently-recalled, long-standing |
605 
606Each expertise area gets an `_expertise.md` profile documenting what you know well, knowledge gaps, and contributing memories. Sleep can target a specific subtree (e.g., `/brain:sleep professional/skills`) or process the entire brain.
607 
608### Spaced Repetition Review
609 
610Brain Memory implements the SM-2 algorithm to surface memories at optimal intervals for long-term retention. The review queue is generated and reinforced during `/brain:sleep`, and tracks:
611 
612- **Interval** — Time until next review (grows exponentially with successful recalls)
613- **Ease factor** — How easily the memory is recalled (adjusts based on recall quality 1-5)
614- **Review count** — Total number of review sessions
615 
616Failed recalls reset the interval to 1 day. Successful recalls extend the interval by the ease factor. This ensures you spend time on memories that need reinforcement, not ones you already know well.
617 
618### Cross-Agent Memory Sharing
619 
620`~/.brain/` is a single global directory in the user's home folder. All memories are shared across every project and every supported agent automatically. A decision stored by Claude Code in one project is immediately available to OpenAI Codex CLI, OpenCode, or Google Antigravity in any other project — no configuration, no export, no per-project setup. The format is agent-agnostic: plain Markdown files with YAML frontmatter, readable by any tool.
621 
622Brain Memory is **model-agnostic** as well as agent-portable: because memory is plain files rather than embeddings welded to a particular model, the LLM underneath your agent can be anything — GPT, Claude, Gemini, or any model routed through a gateway — and your memory is unaffected. **Switch your model or switch your agent, and you keep remembering and pick up exactly where you left off.**
623 
624To share memories across different machines, use `/brain:sync` (see below).
625 
626### Portable Sync — your memory, no lock-in
627 
628**Your brain is plain files in a folder — sync it however you already sync files.** No account or cloud provider is required.
629 
630**Any synced folder** — Point `BRAIN_DIR` at a folder your existing tools already sync, and you're done:
631 
632```bash
633export BRAIN_DIR="$HOME/Google Drive/brain" # or Dropbox, iCloud Drive, OneDrive, Syncthing…
634```
635 
636**Git remote** — `/brain:sync` push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, or self-hosted), using your existing Git/SSH auth.
637 
638**Export/Import** — Pack the entire brain into a single encrypted file for manual transfer via USB, email, or any file-sharing service.
639 
640**Brain Cloud** (optional) — A hosted, zero-config hub if you'd rather not run your own. Entirely optional — everything above works without it.
641 
642**Key features:**
643- **Manual push/pull** — No background watchers, no auto-sync. You control when data moves.
644- **Optional encryption** — AES-256-GCM encryption with a user-provided passphrase. When enabled, all files are encrypted before committing or exporting.
645- **Merge mode** — Import supports merge mode (only import newer files) or overwrite mode.
646- **Zero dependencies** — Uses Node.js built-in `crypto` and the system `git` binary.
647 
648**Setup:**
6491. Create a private Git repo (e.g., `gh repo create brain-data --private`)
6502. Run `/brain:sync setup [email protected]:you/brain-data.git`
6513. Use `/brain:sync push` and `/brain:sync pull` to keep memories in sync
652 
653For one-off transfers, use `/brain:sync export` and `/brain:sync import <path>`.
654 
655**Restore — an undo button for your whole brain.** Every push is a restore point, and the CLI can roll the entire brain back to any of them:
656 
657```bash
658brain restore --list # list restore points (the Git sync history)
659brain restore --to <commit> # roll ~/.brain/ back to that point
660brain restore --list --from cloud # list Brain Cloud's pre-push snapshots
661brain restore --to <version> --from cloud # restore from a cloud snapshot
662```
663 
664Before touching anything, restore preserves your *current* state — the Git path commits it as a safety snapshot, the cloud path writes a local backup under `~/.brain/.cloud/` — so a restore is always undoable, even for work you never pushed. (Brain Cloud also snapshots the brain it's about to replace on every push, server-side.) The append-only `audit.log` is carried forward through restores (never rolled back), and every restore is itself logged there. Restore granularity follows push frequency: push often for finer-grained history.
665 
666Sync state is stored locally in `~/.brain/.sync/` and is never pushed to the remote.
667 
668### Brain in Claude apps (web & mobile) — beta
669 
670Beyond the CLI, you can use your brain from the **Claude apps** (web, desktop, and your
671**phone**) via the **Brain connector** — a remote MCP server hosted by [Brain Cloud](https://app.brainmemory.ai).
672Add it once on claude.ai (**Settings → Connectors → Add custom connector → `https://mcp.brainmemory.ai/mcp`**),
673sign in with the Google account holding your cloud brain, and it syncs to every Claude client on
674your account. Read **and write**: recall + status, plus memorize / pin / unpin (writes prompt for
675confirmation) — so you can capture a memory on your phone and recall it on your laptop.
676 
677→ Full guide: **[Use Brain in Claude apps](https://brainmemory.ai/docs/getting-started/claude-apps)**
678 
679**Your data, protected.** Brains synced to Brain Cloud are **encrypted at rest**
680(AES-256-GCM, per-user key); the connector holds working copies in **RAM only**
681(never on disk); all traffic is **TLS**; sessions use **rotating, revocable tokens
682with reuse detection** (log out one device or all); and every request is isolated
683to your account. Prefer the server never sees plaintext? Stay **local-only** (the
684default) or use Git/export sync with a passphrase. See **[SECURITY.md](SECURITY.md)**.
685 
686## File Structure
687 
688```
689~/.brain/
690├── index.json # Memory inventory — fast lookup for all memories
691├── config.json # Working-memory token budgets (session-start injection)
692├── associations.json # Weighted associative network between memories
693├── contexts.json # Session context snapshots for context-dependent recall
694├── review-queue.json # Spaced repetition scheduling
695├── pinned.json # Always-present tier manifest (pinned memory IDs + scope)
696├── skills-index.json # Advertised procedural skills (L0 — name + description)
697├── _skills/ # Procedural skills
698│ └── <skill-name>/
699│ ├── SKILL.md # Advertised description + step-by-step instructions
700│ └── resources/ # Optional templates/scripts (loaded only at execution)
701├── professional/ # Work, career, technical skills
702│ ├── _meta.json # Category metadata and stats
703│ ├── _expertise.md # Generated expertise profile
704│ ├── companies/ # On-demand: created when first needed
705│ │ └── <company>/
706│ │ ├── projects/
707│ │ └── decisions/
708│ ├── skills/
709│ └── career/
710├── personal/ # Education, health, hobbies, goals
711│ ├── _meta.json
712│ ├── education/
713│ ├── health/
714│ └── goals/
715├── social/ # Communities, networks, collaborations
716│ ├── _meta.json
717│ └── communities/
718├── family/ # Family relationships and events
719│ ├── _meta.json
720│ └── events/
721├── _consolidated/ # Merged memories from consolidation
722│ └── _meta.json
723├── _archived/ # Decayed memories (recoverable + searchable)
724│ ├── _meta.json
725│ └── index.json # Searchable archive index
726└── .sync/ # Sync state (local only, never pushed)
727 ├── config.json # Remote URL, encryption flag
728 └── repo/ # Hidden git repo for sync
729```
730 
731Subdirectories are created **on demand** — the agent decides placement depth based on how specific the memory is. A generic career thought lands in `professional/`, but a specific deployment incident goes to `professional/companies/acme/projects/alpha/`.
732 
733## Configuration
734 
735Brain configuration lives in `~/.brain/index.json` under the `config` key:
736 
737```json
738{
739 "config": {
740 "max_depth": 6,
741 "consolidation_threshold": 0.3,
742 "decay_check_interval_days": 7,
743 "strength_boost_on_recall": 0.05,
744 "auto_consolidate": true,
745 "propagation_window_days": 7,
746 "association_config": {
747 "co_retrieval_boost": 0.10,
748 "link_decay_rate": 0.998,
749 "link_prune_threshold": 0.05,
750 "spreading_activation_depth": 2,
751 "spreading_activation_decay": 0.5
752 }
753 }
754}
755```
756 
757| Setting | Default | Description |
758|---------|---------|-------------|
759| `max_depth` | 6 | Maximum directory nesting depth |
760| `consolidation_threshold` | 0.3 | Strength below which memories are consolidation candidates |
761| `decay_check_interval_days` | 7 | How often to suggest decay maintenance |
762| `strength_boost_on_recall` | 0.05 | Base strength increase per recall event |
763| `auto_consolidate` | true | Suggest consolidation when candidates are found |
764| `propagation_window_days` | 7 | How far back to look for recent memories during knowledge propagation |
765| `association_config.co_retrieval_boost` | 0.10 | Hebbian reinforcement increment for co-retrieved memories |
766| `association_config.link_decay_rate` | 0.998 | Daily decay factor for association edge weights |
767| `association_config.link_prune_threshold` | 0.05 | Minimum weight before an association link is pruned |
768| `association_config.spreading_activation_depth` | 2 | Maximum hops for spreading activation traversal |
769| `association_config.spreading_activation_decay` | 0.5 | Decay factor per hop during spreading activation |
770 
771### Sensitive Topics
772 
773`sensitive_topics` (default `false`). Memories classified `sensitive` — health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation — are stored only when this is `true`; otherwise they wait quarantined and hidden until you approve them one by one (`brain verify approve <id>`). Turning it on is never retroactive. `blocked` content (government ID numbers, criminal history, immigration status) is refused whatever the setting. See `src/sensitivity.js` for the exact tiers.
774 
775### Working-Memory Budget
776 
777A separate `~/.brain/config.json` (created lazily with safe defaults) caps how much the brain injects into the context window at session start, so the always-present tier can never crowd out your actual work:
778 
779```json
780{
781 "working_memory_budget_tokens": 3000,
782 "pin_budget_tokens": 1500,
783 "skills_index_budget_tokens": 800,
784 "recall_budget_tokens": 700
785}
786```
787 
788| Setting | Default | Description |
789|---------|---------|-------------|
790| `working_memory_budget_tokens` | 3000 | Total token ceiling for the whole `brain session-start` payload |
791| `pin_budget_tokens` | 1500 | Sub-budget for pinned, always-present memories |
792| `skills_index_budget_tokens` | 800 | Sub-budget for the advertised skills index (L0) |
793| `recall_budget_tokens` | 700 | Sub-budget for context-relevant recalled memories |
794 
795Token counts use a dependency-free heuristic stored on each memory at write time. When pins exceed their budget they're selected by `--priority` then strength, and the overflow is reported rather than silently dropped.
796 
797## Benchmark
798 
799Brain Memory ships with a controlled benchmark suite grounded in the 2025-2026 SOTA in long-term-memory evaluation. The system itself is a direct implementation of the [**CoALA**](https://arxiv.org/abs/2309.02427) agent-memory model (Sumers et al., 2023) — Pinned Tier maps to CoALA's *semantic* memory, procedural skills to *procedural* memory.
800 
801**Six scenarios**, each describable in one sentence:
802 
803| Id | Pitch | Tests |
804|---|---|---|
805| **A** *Noisy Project Folder* | "Your brain has 200 memories from 6 projects — does it find the 3 relevant ones?" | Retrieval under distractors (LongMemEval-S analog) |
806| **B** *Three Sessions, One Decision* | "Postgres Monday, gRPC rewrite Wednesday, new resource Friday — still Postgres?" | Multi-session continuity + Pinned Tier ablation |
807| **C** *The Contradiction Test* | "Tabs, then spaces, then tabs again — which version wins?" | Decay-weighted recency + contradiction handling |
808| **D** *Skill Progressive Disclosure* | "Five skills indexed, one needed — does brain load just the one?" | CoALA Phase-2 L0/L1/L2 token efficiency |
809| **E** *Continual Coding* | "Five bugs in order — does bug 5 finish faster than bug 1?" | Forward transfer; agent writes memories between tasks |
810| **F** *Abstention* | "No deployment target in memory — does the agent ask or invent?" | Confabulation resistance |
811 
812**Methodology highlights** — agent under test is **DeepSeek V4 Pro** (single-shot), graded by a **cross-family judge panel** (Gemini + Gemma-4 + Qwen-3.5, majority vote — no judge shares the agent's family, [Preference Leakage 2502.01534](https://arxiv.org/abs/2502.01534), [PoLL 2404.18796](https://arxiv.org/abs/2404.18796)); deterministic distractor haystacks up to 1000 memories; real `brain session-start` / `brain recall` integration; tokens-per-successful-task as the headline efficiency metric; every scenario anchored by a no-memory floor and an oracle ceiling.
813 
814> Results (DeepSeek V4 Pro, 3 runs/arm, June 2026). **Scenario A — retrieval under 1000 distractors:** `brain-full` is the only retriever whose memories let the model succeed — it passes **100%** while both **BM25 (0%)** and a **vector store (0%)** fail to surface the oracle memories — and it does so at the **leanest tokens-per-success (3,199)** of any passing arm. **Scenario D — skills:** loading only the relevant skill passes 100% at **1,580 tok/success, ~31% leaner** than dumping all skill bodies. Scenarios B (continuity) shows brain efficient-and-correct; C (contradiction) and F (abstention) are honest **nulls** — the base model handles them without memory. At n=3 the token gaps are directional, not yet significant; the pass-rate gradient is the result. Full tables: [brainmemory.ai/docs/benchmarks/results](https://brainmemory.ai/docs/benchmarks/results).
815 
816**Retrieval calibration probe (in-vivo, July 2026).** Separate from the controlled
817suite: a 20-query retrieval probe on a real working brain (177 memories, 1,245
818association edges; tag-derived topical queries with known targets) measured the
819scoring-calibration fix shipped after beta.30. Before: hit@1 90%, MRR 0.950 — and a
820four-term nonsense control query still returned ten results, the top scoring a
821confident-looking 0.679. After query-coverage scaling and the relevance floor:
822**hit@1 100% / hit@3 100% / MRR 1.000**, the nonsense control returns a single result
823with honestly low relevance (0.213), and recall latency stays at ~46 ms (p50).
824*Caveats: n=20, single brain, tag-derived queries favor the index's tag field, not
825judge-graded — this is a calibration probe, not the controlled benchmark above.*
826Method and detail: [brainmemory.ai/docs/benchmarks/results](https://brainmemory.ai/docs/benchmarks/results).
827 
828Run the benchmarks yourself:
829 
830```bash
831cd benchmark
832cp .env.example .env # Add your API keys
833npm test # Unit tests
834node harness/runner.js # Full benchmark (cloud APIs)
835```
836 
837Live methodology and per-scenario detail: [brainmemory.ai/docs/benchmarks](https://brainmemory.ai/docs/benchmarks) · Source: [`benchmark/`](benchmark/)
838 
839## Contributing
840 
841Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, project structure, and how to submit changes.
842 
843## References
844 
845Brain Memory's architecture and benchmark methodology are grounded in the following work.
846 
847### Foundations — the agent-memory model Brain implements
848 
849- [**CoALA — Cognitive Architectures for Language Agents**](https://arxiv.org/abs/2309.02427) (arxiv 2309.02427) — Sumers, Yao, Narasimhan, Griffiths. The agent-memory taxonomy Brain implements directly. Pinned Tier → semantic memory, Skills → procedural memory, session-start aggregator → working memory.
850- [**MemGPT — LLMs as Operating Systems**](https://arxiv.org/abs/2310.08560) (arxiv 2310.08560) — Packer et al. Paging-style memory management.
851- [**Generative Agents — Interactive Simulacra of Human Behavior**](https://arxiv.org/abs/2304.03442) (arxiv 2304.03442) — Park et al. Recency · importance · relevance retrieval blend.
852- [**Memory in the Age of AI Agents**](https://arxiv.org/abs/2512.13564) (arxiv 2512.13564) — Comprehensive survey on agent memory architectures.
853- [**Mem0**](https://arxiv.org/abs/2504.19413) (arxiv 2504.19413) — Human-like memory reinforcement and decay.
854- [**MemOS**](https://arxiv.org/abs/2507.03724) (arxiv 2507.03724) — Memory lifecycle state management.
855 
856### Memory benchmarks (the suite this work follows)
857 
858- [**LongMemEval**](https://arxiv.org/abs/2410.10813) (arxiv 2410.10813) — distractor haystacks (S / M / Oracle), abstention category, GPT-4o judge with 97% human agreement.
859- [**MemoryAgentBench**](https://arxiv.org/abs/2507.05257) (arxiv 2507.05257) — four-competency framework; FactConsolidation inspired Scenario C.
860- [**SWE-Bench-CL**](https://arxiv.org/abs/2507.00014) (arxiv 2507.00014) — repo-scoped chronological evaluation; template for Scenario E.
861- [**LoCoMo**](https://arxiv.org/abs/2402.17753) (arxiv 2402.17753) — long-conversation memory benchmark.
862- [**MIRIX**](https://arxiv.org/abs/2507.07957) (arxiv 2507.07957) — realistic synthetic-but-grounded memory benchmarks.
863 
864### Methodology — judging and benchmark hygiene
865 
866- [**Preference Leakage in LLM-as-judge**](https://arxiv.org/abs/2502.01534) (arxiv 2502.01534) — drives cross-family judging.
867- [**When Judgment Becomes Noise — position bias**](https://arxiv.org/abs/2509.20293) (arxiv 2509.20293) — drives position-swap mitigation.
868- [**Silent Judge — shortcut bias**](https://arxiv.org/abs/2509.26072) (arxiv 2509.26072) — drives rubric-based judging.
869- [**LastingBench**](https://arxiv.org/abs/2506.21614) (arxiv 2506.21614) — benchmark-leakage defense.
870 
871### Neuroscience
872 
873- [**Ebbinghaus forgetting curve**](https://en.wikipedia.org/wiki/Forgetting_curve) — exponential memory decay.
874- [**Spreading activation**](https://en.wikipedia.org/wiki/Spreading_activation) — Collins & Loftus network model of semantic memory.
875- [**Hebbian theory**](https://en.wikipedia.org/wiki/Hebbian_theory) — "neurons that fire together wire together."
876- [**Synaptic homeostasis hypothesis**](https://doi.org/10.1016/j.neuron.2013.10.024) — Tononi & Cirelli's theory of sleep function.
877- [**SM-2 algorithm**](https://en.wikipedia.org/wiki/SuperMemo#Description_of_SM-2_algorithm) — spaced repetition scheduling.
878- [**Memory reconsolidation**](https://en.wikipedia.org/wiki/Memory_consolidation#Reconsolidation) — recalling memories makes them temporarily malleable.
879 
880### Related projects
881 
882- [get-shit-done](https://github.com/gsd-build/get-shit-done) — Structured file-based workflow orchestration for AI agents.
883 
884## License
885 
886MIT
887 

Discussion