brain-memory 0.1.0-beta.3 → 0.1.0-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +319 -0
  2. package/README.md +379 -95
  3. package/SECURITY.md +61 -0
  4. package/assets/brand/README.md +28 -0
  5. package/assets/brand/icon-dark.svg +19 -0
  6. package/assets/brand/icon-light.svg +20 -0
  7. package/assets/brand/linkedin_cover.png +0 -0
  8. package/assets/brand/linkedin_cover_light.png +0 -0
  9. package/assets/brand/mark-dark.svg +19 -0
  10. package/assets/brand/mark-light.svg +20 -0
  11. package/assets/brand/png/icon-dark-1024.png +0 -0
  12. package/assets/brand/png/icon-dark-128.png +0 -0
  13. package/assets/brand/png/icon-dark-256.png +0 -0
  14. package/assets/brand/png/icon-dark-512.png +0 -0
  15. package/assets/brand/png/icon-dark-64.png +0 -0
  16. package/assets/brand/png/icon-light-1024.png +0 -0
  17. package/assets/brand/png/icon-light-128.png +0 -0
  18. package/assets/brand/png/icon-light-256.png +0 -0
  19. package/assets/brand/png/icon-light-512.png +0 -0
  20. package/assets/brand/png/icon-light-64.png +0 -0
  21. package/assets/brand/png/mark-dark-1024.png +0 -0
  22. package/assets/brand/png/mark-light-1024.png +0 -0
  23. package/assets/icon.png +0 -0
  24. package/assets/icon.svg +19 -0
  25. package/bin/brain.js +111 -0
  26. package/bin/cloud-sync.js +150 -0
  27. package/bin/forget.js +122 -0
  28. package/bin/install.js +229 -254
  29. package/bin/memorize.js +458 -0
  30. package/bin/pin.js +44 -0
  31. package/bin/recall.js +251 -0
  32. package/bin/reinforce.js +187 -0
  33. package/bin/session-start.js +298 -0
  34. package/bin/skill.js +67 -0
  35. package/bin/unpin.js +38 -0
  36. package/commands/brain/forget.md +245 -15
  37. package/commands/brain/memorize.md +76 -144
  38. package/commands/brain/pin.md +79 -0
  39. package/commands/brain/remember.md +48 -105
  40. package/commands/brain/skills.md +60 -0
  41. package/commands/brain/sleep.md +69 -28
  42. package/commands/brain/status.md +24 -10
  43. package/commands/brain/sync.md +386 -0
  44. package/package.json +22 -8
  45. package/prompts/antigravity.md +180 -0
  46. package/prompts/claude.md +124 -20
  47. package/prompts/openai.md +124 -20
  48. package/prompts/opencode.md +179 -0
  49. package/src/cloud-sync.js +534 -0
  50. package/src/crypto.js +130 -0
  51. package/src/export-import.js +200 -0
  52. package/src/git-sync.js +444 -0
  53. package/src/index-manager.js +219 -18
  54. package/src/installer.js +444 -0
  55. package/src/pinning.js +124 -0
  56. package/src/scorer.js +22 -9
  57. package/src/skills.js +208 -0
  58. package/src/tfidf.js +501 -0
  59. package/commands/brain/consolidate.md +0 -153
  60. package/commands/brain/explore.md +0 -79
  61. package/commands/brain/init.md +0 -157
  62. package/commands/brain/review.md +0 -130
  63. package/commands/brain/sunshine.md +0 -337
  64. package/hooks/session-end.md +0 -48
  65. package/hooks/session-start.md +0 -48
  66. package/prompts/gemini.md +0 -76
package/README.md CHANGED
@@ -1,13 +1,21 @@
1
- # Brain Memory
1
+ <p align="center">
2
+ <img src="assets/icon.png" alt="Brain Memory" width="128" height="128">
3
+ </p>
2
4
 
3
- [![CI](https://github.com/onurkarali/brain/actions/workflows/ci.yml/badge.svg)](https://github.com/onurkarali/brain/actions/workflows/ci.yml)
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>
4
12
 
5
13
  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.
6
14
 
7
- Works with **Claude Code**, **Gemini CLI**, and **OpenAI Codex CLI**.
15
+ One hosted **MCP connector** reaches every major agent and chat app — **Claude Code**, **OpenAI Codex CLI**, **OpenCode**, the **Claude.ai** apps, **ChatGPT**, and **Google Antigravity** (Gemini CLI's successor). Prefer a free, local-first install? The native plugin runs entirely from `~/.brain/` on Claude Code, Codex, OpenCode, and Antigravity.
8
16
 
9
17
  ```
10
- .brain/
18
+ ~/.brain/
11
19
  ├── professional/
12
20
  │ └── companies/
13
21
  │ └── acme-corp/
@@ -36,65 +44,205 @@ Existing AI memory solutions use flat databases with tag-based retrieval. Brain
36
44
  - **Context-dependent recall** — Memories encoded in a similar context to the current session are scored higher
37
45
  - **Spaced reinforcement** — Memories recalled after longer intervals get bigger boosts, cramming produces diminishing returns
38
46
  - **Cognitive types** — Episodic, semantic, and procedural memories each decay differently, just like in the brain
47
+ - **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
48
+ - **Procedural skills** — Reusable how-to workflows with progressive disclosure, learned automatically from repeated experience and exportable to your agent's native skills
39
49
  - **On-demand depth** — Subcategories are created as needed, not pre-defined
40
50
  - **Consolidation** — Weak related memories merge into stronger combined knowledge
41
51
  - **Zero dependencies** — Pure file I/O, no databases, no servers, no embeddings required
42
52
 
43
53
  ## Install
44
54
 
55
+ There are two ways to give an agent its brain. They are complementary — most people end up with both:
56
+
57
+ | Path | Reaches | Storage | Cost | Best for |
58
+ |------|---------|---------|------|----------|
59
+ | **Hosted MCP connector** | Every MCP-capable host (Claude Code, Codex CLI, OpenCode, Claude.ai apps, ChatGPT, Antigravity) | Brain Cloud (hosted) | account | One connector, everywhere — including web & mobile chat |
60
+ | **Local-first native plugin** | The current CLIs (Claude Code, Codex CLI, OpenCode, Antigravity) | `~/.brain/` on your machine | free | Zero-config ambient memory, no account, files you own |
61
+
62
+ ### 1. Universal path — the hosted MCP connector
63
+
64
+ 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.
65
+
45
66
  ```bash
46
- npx brain-memory@beta
67
+ # Claude Code
68
+ claude mcp add --transport http brain https://mcp.brainmemory.ai/mcp
69
+
70
+ # OpenAI Codex CLI
71
+ codex mcp add brain --url https://mcp.brainmemory.ai/mcp
47
72
  ```
48
73
 
49
- The interactive installer asks which runtime(s) to configure (Claude Code, Gemini CLI, OpenAI Codex CLI, or all) and whether to install globally or for the current project.
74
+ <details>
75
+ <summary>Per-host setup for every other connector</summary>
76
+
77
+ - **Codex CLI (config file)** — add to `~/.codex/config.toml`:
78
+ ```toml
79
+ [mcp_servers.brain]
80
+ url = "https://mcp.brainmemory.ai/mcp"
81
+ ```
82
+ - **OpenCode** — add to `opencode.json`:
83
+ ```json
84
+ {
85
+ "mcp": {
86
+ "brain": { "type": "remote", "url": "https://mcp.brainmemory.ai/mcp" }
87
+ }
88
+ }
89
+ ```
90
+ - **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.)
91
+ - **Google Antigravity** — add to `mcp_config.json` under the `serverUrl` key. *(Legacy Gemini CLI used the `httpUrl` key in `settings.json`.)*
50
92
 
51
- ### Non-interactive
93
+ </details>
94
+
95
+ 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](https://brainmemory.ai/docs/getting-started/claude-apps)** for the full walkthrough.
96
+
97
+ ### 2. Local-first path — the native plugin
52
98
 
53
99
  ```bash
54
- npx brain-memory --claude --global # Claude Code, global
55
- npx brain-memory --gemini --local # Gemini CLI, local project
56
- npx brain-memory --codex --global # OpenAI Codex CLI, global
57
- npx brain-memory --all --global # All runtimes, global
100
+ npm install -g brain-memory@beta
101
+ brain
58
102
  ```
59
103
 
104
+ 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.
105
+
106
+ 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:
107
+
108
+ | Runtime | Instructions file | Commands land at |
109
+ |---------|-------------------|------------------|
110
+ | **Claude Code** | `CLAUDE.md` | `~/.claude/commands/brain/` (plugin slash commands) |
111
+ | **OpenAI Codex CLI** | `AGENTS.md` (`~/.codex/`) | `~/.agents/skills/<name>/SKILL.md` |
112
+ | **OpenCode** | `AGENTS.md` | `~/.config/opencode/commands/` |
113
+ | **Google Antigravity** | `GEMINI.md` | `~/.gemini/skills/` *(experimental — verify paths against a live install)* |
114
+
115
+ #### Non-interactive
116
+
117
+ ```bash
118
+ brain --claude --global # Claude Code, global
119
+ brain --codex --global # OpenAI Codex CLI, global
120
+ brain --opencode --global # OpenCode, global
121
+ brain --antigravity --global # Google Antigravity, global (experimental)
122
+ brain --all --global # All runtimes, global
123
+ ```
124
+
125
+ ### Update
126
+
127
+ ```bash
128
+ npm install -g brain-memory@beta
129
+ brain update
130
+ ```
131
+
132
+ 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`.
133
+
134
+ > **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.
135
+
136
+ > **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.
137
+
138
+ ### Uninstall
139
+
140
+ ```bash
141
+ brain uninstall
142
+ npm uninstall -g brain-memory
143
+ ```
144
+
145
+ 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.
146
+
60
147
  ### Manual Install
61
148
 
62
- Copy the `commands/brain/` directory to your agent's commands folder:
149
+ 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.
63
150
 
64
151
  ```bash
65
- # Claude Code
152
+ # Claude Code — flat slash commands
66
153
  cp -r commands/brain/ ~/.claude/commands/brain/
67
154
 
68
- # Gemini CLI
69
- cp -r commands/brain/ ~/.gemini/commands/brain/
155
+ # OpenCode — flat slash commands
156
+ mkdir -p ~/.config/opencode/commands/brain
157
+ cp -r commands/brain/. ~/.config/opencode/commands/brain/
158
+
159
+ # OpenAI Codex CLI — each command becomes a skill under the cross-tool skills dir
160
+ for f in commands/brain/*.md; do
161
+ name=$(basename "$f" .md)
162
+ mkdir -p ~/.agents/skills/brain-"$name"
163
+ cp "$f" ~/.agents/skills/brain-"$name"/SKILL.md
164
+ done
70
165
 
71
- # OpenAI Codex CLI (each command becomes a skill)
166
+ # Google Antigravity (experimental — verify paths) — skills under ~/.gemini/skills/
72
167
  for f in commands/brain/*.md; do
73
168
  name=$(basename "$f" .md)
74
- mkdir -p ~/.codex/skills/brain-"$name"
75
- cp "$f" ~/.codex/skills/brain-"$name"/SKILL.md
169
+ mkdir -p ~/.gemini/skills/brain-"$name"
170
+ cp "$f" ~/.gemini/skills/brain-"$name"/SKILL.md
76
171
  done
77
172
  ```
78
173
 
79
174
  Then append the contents of the corresponding prompt file to your agent's instructions file:
80
175
  - `prompts/claude.md` → `CLAUDE.md`
81
- - `prompts/gemini.md` → `GEMINI.md`
82
- - `prompts/openai.md` → `AGENTS.md`
176
+ - `prompts/openai.md` → `AGENTS.md` (Codex, in `~/.codex/`)
177
+ - `prompts/opencode.md` → `AGENTS.md` (OpenCode)
178
+ - `prompts/antigravity.md` → `GEMINI.md` (experimental)
179
+
180
+ > **`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).
83
181
 
84
182
  ## Commands
85
183
 
184
+ 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:
185
+
86
186
  | Command | Description |
87
187
  |---------|-------------|
88
- | `/brain:init` | Initialize `.brain/` directory structure with default categories |
89
- | `/brain:memorize [topic]` | Store memories from current session context |
90
188
  | `/brain:remember [query]` | Recall relevant memories with spreading activation and context matching |
91
- | `/brain:review [scope]` | Spaced repetition review session for due memories |
92
- | `/brain:explore [category]` | Browse the brain hierarchy with visual tree view |
93
- | `/brain:consolidate [scope]` | Merge related weak memories into stronger combined ones |
94
- | `/brain:forget [target]` | Decay, archive, or remove memories |
95
- | `/brain:sunshine [target]` | Deep forensic erasure — trace and remove all references |
96
- | `/brain:sleep [scope]` | Full maintenance cycle — 9 neuroscience-inspired phases |
189
+ | `/brain:memorize [topic] [--sync]` | Store memories from current session context (add `--sync` to auto-push) |
97
190
  | `/brain:status` | Dashboard with brain health metrics and recommendations |
191
+ | `/brain:pin [id\|query]` | Pin a memory to the always-present tier — loads every session, never decays. Toggles: also unpins (`--off`) |
192
+ | `/brain:forget [target]` | Decay, archive, or remove memories. `--deep` performs forensic erasure — traces and removes every reference |
193
+ | `/brain:sync [subcommand]` | Sync via Brain Cloud, Git remote, or export/import (auto-initializes the brain on first run) |
194
+ | `/brain:skills [list\|show\|add\|use\|remove\|export]` | Manage procedural skills — reusable how-to workflows with progressive disclosure |
195
+ | `/brain:sleep [scope]` | Full maintenance cycle — 9 neuroscience-inspired phases (replay, consolidation, review reinforcement, pruning, dreaming, …). Usually runs automatically/in the background |
196
+
197
+ ## Session Lifecycle
198
+
199
+ Brain Memory works automatically in the background — no commands needed for basic context awareness.
200
+
201
+ ### Session Start
202
+
203
+ 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`):
204
+
205
+ 1. **Pinned memories** — always-present conventions and preferences, injected verbatim regardless of recall score
206
+ 2. **Skills index** — the name + description of each available procedural skill (~100 tokens each; full instructions are loaded only when a task matches)
207
+ 3. **Context recall** — the top memories relevant to the current project
208
+ 4. **Review queue + low-confidence alerts**, then a brief status line:
209
+
210
+ ```
211
+ ◉ Brain active — 42 memories loaded (8 in current project context)
212
+ 📋 3 memories due for review — reinforced automatically during /brain:sleep
213
+ ```
214
+
215
+ 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.
216
+
217
+ ### Ambient Session Tracking
218
+
219
+ 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.
220
+
221
+ ### Periodic Memory Checkpoint
222
+
223
+ 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:
224
+
225
+ ```
226
+ ◉ Notable decisions and learnings this session — /brain:memorize when ready
227
+ ```
228
+
229
+ 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`.
230
+
231
+ ### Session End
232
+
233
+ When a session ends, the agent performs two steps in order:
234
+
235
+ 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.
236
+
237
+ 2. **Suggests memorization** if the session contained meaningful decisions, learnings, or insights:
238
+
239
+ ```
240
+ 💡 This session contained notable decisions and learnings.
241
+ Would you like to store them as brain memories?
242
+ Run /brain:memorize to capture them before this context is lost.
243
+ ```
244
+
245
+ The agent never auto-memorizes without user consent. Context is saved proactively — the agent doesn't wait for an explicit goodbye signal.
98
246
 
99
247
  ## How It Works
100
248
 
@@ -111,13 +259,13 @@ Create → Store → Decay → Recall → Reinforce → Review → Sleep → Arc
111
259
  3. **Decay** — Memories naturally weaken over time: `effective_strength = base_strength * (decay_rate ^ days_since_access)`
112
260
  4. **Recall** — `/brain:remember` searches, scores with spreading activation and context matching, and returns the best memories. Archived memories are searched as a fallback.
113
261
  5. **Reinforce** — Each recall applies spaced reinforcement (longer gaps = bigger boosts) and improves the memory's decay resistance
114
- 6. **Review** — `/brain:review` implements SM-2 spaced repetition, surfacing memories at optimal intervals for long-term retention
115
- 7. **Sleep** — `/brain:sleep` performs a 9-phase maintenance cycle inspired by real neuroscience
262
+ 6. **Review** — SM-2 spaced repetition surfaces memories at optimal intervals for long-term retention; reinforcement runs automatically during the sleep cycle
263
+ 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
116
264
  8. **Archive** — Fully decayed memories move to `_archived/` (recoverable and searchable) or can be permanently deleted
117
265
 
118
266
  ### Neuroscience Foundations
119
267
 
120
- Brain Memory v2 is grounded in peer-reviewed neuroscience research. Here's how each mechanism maps to the brain:
268
+ Brain Memory is grounded in peer-reviewed neuroscience research. Here's how each mechanism maps to the brain:
121
269
 
122
270
  | Brain Mechanism | Implementation |
123
271
  |-----------------|---------------|
@@ -158,6 +306,38 @@ Each memory is also classified by how the brain processes it:
158
306
 
159
307
  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.
160
308
 
309
+ ### Always-Present Memories (Pinning)
310
+
311
+ 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:
312
+
313
+ - **`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).
314
+ - **`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.
315
+
316
+ ```bash
317
+ brain pin <id> --scope global --priority 1 # or: /brain:pin always use tabs
318
+ ```
319
+
320
+ 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](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).
321
+
322
+ ### Procedural Skills
323
+
324
+ 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**:
325
+
326
+ | Level | When | What loads |
327
+ |-------|------|------------|
328
+ | **L0** | Every session start | Only each skill's name + description (~100 tokens) |
329
+ | **L1** | A task matches a skill | The full `SKILL.md` step-by-step instructions |
330
+ | **L2** | A step needs them | Referenced `resources/` (templates, scripts) |
331
+
332
+ ```bash
333
+ brain skill list # advertised skills (L0)
334
+ brain skill show structured-code-review # full instructions (L1)
335
+ brain skill use structured-code-review # record outcome (--failed weakens it)
336
+ brain skill export structured-code-review --target claude # → native .claude/skills/
337
+ ```
338
+
339
+ 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.
340
+
161
341
  ### Memory File Format
162
342
 
163
343
  Each memory is a Markdown file with YAML frontmatter:
@@ -226,8 +406,6 @@ score = 0.38 * relevance
226
406
  - **context_match** (0.14) — How similar the encoding context is to the current session
227
407
  - **salience** (0.08) — Emotional/motivational significance
228
408
 
229
- The formula gracefully degrades for v1 memories missing newer fields — weights are renormalized across available terms.
230
-
231
409
  The agent then decides the response strategy:
232
410
  - **Single strong match** (top score > 0.7) → Return the full memory
233
411
  - **Multiple related** (2-5 candidates > 0.4) → Synthesize a consolidated response
@@ -236,7 +414,7 @@ The agent then decides the response strategy:
236
414
 
237
415
  ### Associative Network
238
416
 
239
- Memories are connected via weighted edges in `.brain/associations.json`:
417
+ Memories are connected via weighted edges in `~/.brain/associations.json`:
240
418
 
241
419
  ```json
242
420
  {
@@ -261,7 +439,7 @@ Memories are connected via weighted edges in `.brain/associations.json`:
261
439
 
262
440
  ### Spaced Reinforcement
263
441
 
264
- Unlike the flat +0.05 boost per recall in v1, spaced reinforcement rewards optimal recall timing:
442
+ Spaced reinforcement rewards optimal recall timing:
265
443
 
266
444
  ```
267
445
  spacingMultiplier = min(3.0, 1.0 + log2(1 + daysSinceLastAccess))
@@ -320,7 +498,7 @@ Each expertise area gets an `_expertise.md` profile documenting what you know we
320
498
 
321
499
  ### Spaced Repetition Review
322
500
 
323
- `/brain:review` implements the SM-2 algorithm to surface memories at optimal intervals for long-term retention. The review queue is generated during sleep and tracks:
501
+ 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:
324
502
 
325
503
  - **Interval** — Time until next review (grows exponentially with successful recalls)
326
504
  - **Ease factor** — How easily the memory is recalled (adjusts based on recall quality 1-5)
@@ -328,24 +506,78 @@ Each expertise area gets an `_expertise.md` profile documenting what you know we
328
506
 
329
507
  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.
330
508
 
331
- ### Migration from v1
509
+ ### Cross-Agent Memory Sharing
510
+
511
+ `~/.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.
512
+
513
+ 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.**
332
514
 
333
- Existing v1 brains upgrade automatically. The first `/brain:sleep` after upgrade runs a migration phase that:
334
- - Creates `associations.json` from existing `related` fields
335
- - Backfills `recall_history` from `access_count`
336
- - Sets sensible defaults for new fields (`cognitive_type: semantic`, `salience: 0.5`, `confidence: 0.8`)
337
- - Bumps `index.json` version to 2
515
+ To share memories across different machines, use `/brain:sync` (see below).
338
516
 
339
- No data is lost. All new scoring gracefully falls back when newer fields are absent.
517
+ ### Portable Sync — your memory, no lock-in
518
+
519
+ **Your brain is plain files in a folder — sync it however you already sync files.** No account or cloud provider is required.
520
+
521
+ **Any synced folder** — Point `BRAIN_DIR` at a folder your existing tools already sync, and you're done:
522
+
523
+ ```bash
524
+ export BRAIN_DIR="$HOME/Google Drive/brain" # or Dropbox, iCloud Drive, OneDrive, Syncthing…
525
+ ```
526
+
527
+ **Git remote** — `/brain:sync` push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, or self-hosted), using your existing Git/SSH auth.
528
+
529
+ **Export/Import** — Pack the entire brain into a single encrypted file for manual transfer via USB, email, or any file-sharing service.
530
+
531
+ **Brain Cloud** (optional) — A hosted, zero-config hub if you'd rather not run your own. Entirely optional — everything above works without it.
532
+
533
+ **Key features:**
534
+ - **Manual push/pull** — No background watchers, no auto-sync. You control when data moves.
535
+ - **Optional encryption** — AES-256-GCM encryption with a user-provided passphrase. When enabled, all files are encrypted before committing or exporting.
536
+ - **Merge mode** — Import supports merge mode (only import newer files) or overwrite mode.
537
+ - **Zero dependencies** — Uses Node.js built-in `crypto` and the system `git` binary.
538
+
539
+ **Setup:**
540
+ 1. Create a private Git repo (e.g., `gh repo create brain-data --private`)
541
+ 2. Run `/brain:sync setup git@github.com:you/brain-data.git`
542
+ 3. Use `/brain:sync push` and `/brain:sync pull` to keep memories in sync
543
+
544
+ For one-off transfers, use `/brain:sync export` and `/brain:sync import <path>`.
545
+
546
+ Sync state is stored locally in `~/.brain/.sync/` and is never pushed to the remote.
547
+
548
+ ### Brain in Claude apps (web & mobile) — beta
549
+
550
+ Beyond the CLI, you can use your brain from the **Claude apps** (web, desktop, and your
551
+ **phone**) via the **Brain connector** — a remote MCP server hosted by [Brain Cloud](https://app.brainmemory.ai).
552
+ Add it once on claude.ai (**Settings → Connectors → Add custom connector → `https://mcp.brainmemory.ai/mcp`**),
553
+ sign in with the Google account holding your cloud brain, and it syncs to every Claude client on
554
+ your account. Read **and write**: recall + status, plus memorize / pin / unpin (writes prompt for
555
+ confirmation) — so you can capture a memory on your phone and recall it on your laptop.
556
+
557
+ → Full guide: **[Use Brain in Claude apps](https://brainmemory.ai/docs/getting-started/claude-apps)**
558
+
559
+ **Your data, protected.** Brains synced to Brain Cloud are **encrypted at rest**
560
+ (AES-256-GCM, per-user key); the connector holds working copies in **RAM only**
561
+ (never on disk); all traffic is **TLS**; sessions use **rotating, revocable tokens
562
+ with reuse detection** (log out one device or all); and every request is isolated
563
+ to your account. Prefer the server never sees plaintext? Stay **local-only** (the
564
+ default) or use Git/export sync with a passphrase. See **[SECURITY.md](SECURITY.md)**.
340
565
 
341
566
  ## File Structure
342
567
 
343
568
  ```
344
- .brain/
569
+ ~/.brain/
345
570
  ├── index.json # Memory inventory — fast lookup for all memories
571
+ ├── config.json # Working-memory token budgets (session-start injection)
346
572
  ├── associations.json # Weighted associative network between memories
347
573
  ├── contexts.json # Session context snapshots for context-dependent recall
348
574
  ├── review-queue.json # Spaced repetition scheduling
575
+ ├── pinned.json # Always-present tier manifest (pinned memory IDs + scope)
576
+ ├── skills-index.json # Advertised procedural skills (L0 — name + description)
577
+ ├── _skills/ # Procedural skills
578
+ │ └── <skill-name>/
579
+ │ ├── SKILL.md # Advertised description + step-by-step instructions
580
+ │ └── resources/ # Optional templates/scripts (loaded only at execution)
349
581
  ├── professional/ # Work, career, technical skills
350
582
  │ ├── _meta.json # Category metadata and stats
351
583
  │ ├── _expertise.md # Generated expertise profile
@@ -368,16 +600,19 @@ No data is lost. All new scoring gracefully falls back when newer fields are abs
368
600
  │ └── events/
369
601
  ├── _consolidated/ # Merged memories from consolidation
370
602
  │ └── _meta.json
371
- └── _archived/ # Decayed memories (recoverable + searchable)
372
- ├── _meta.json
373
- └── index.json # Searchable archive index
603
+ ├── _archived/ # Decayed memories (recoverable + searchable)
604
+ │ ├── _meta.json
605
+ │ └── index.json # Searchable archive index
606
+ └── .sync/ # Sync state (local only, never pushed)
607
+ ├── config.json # Remote URL, encryption flag
608
+ └── repo/ # Hidden git repo for sync
374
609
  ```
375
610
 
376
611
  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/`.
377
612
 
378
613
  ## Configuration
379
614
 
380
- Brain configuration lives in `.brain/index.json` under the `config` key:
615
+ Brain configuration lives in `~/.brain/index.json` under the `config` key:
381
616
 
382
617
  ```json
383
618
  {
@@ -413,53 +648,102 @@ Brain configuration lives in `.brain/index.json` under the `config` key:
413
648
  | `association_config.spreading_activation_depth` | 2 | Maximum hops for spreading activation traversal |
414
649
  | `association_config.spreading_activation_decay` | 0.5 | Decay factor per hop during spreading activation |
415
650
 
416
- ## Project Structure
417
-
418
- ```
419
- brain/
420
- ├── bin/
421
- │ └── install.js # Interactive installer (npx brain-memory)
422
- ├── commands/
423
- │ └── brain/ # Slash command definitions
424
- │ ├── init.md
425
- │ ├── memorize.md
426
- │ ├── remember.md
427
- │ ├── review.md
428
- │ ├── explore.md
429
- │ ├── consolidate.md
430
- │ ├── forget.md
431
- │ ├── sunshine.md
432
- │ ├── sleep.md
433
- │ └── status.md
434
- ├── prompts/
435
- │ ├── claude.md # CLAUDE.md content (injected by installer)
436
- │ ├── gemini.md # GEMINI.md content (injected by installer)
437
- │ └── openai.md # AGENTS.md content (injected by installer)
438
- ├── hooks/
439
- │ ├── session-start.md # Ambient memory loading + review notifications
440
- │ └── session-end.md # Auto-memorize suggestion + context capture
441
- ├── templates/
442
- │ └── default-categories.json # Default brain category definitions
443
- ├── src/
444
- │ ├── scorer.js # Decay, spreading activation, context matching, spaced reinforcement
445
- │ └── index-manager.js # Index, associations, contexts, review queue, archive CRUD
446
- ├── CLAUDE.md # Development guide for this repo
447
- ├── package.json
448
- └── README.md
449
- ```
450
-
451
- ## Inspired By
452
-
453
- - [get-shit-done](https://github.com/gsd-build/get-shit-done) — Structured file-based workflow orchestration for AI agents
454
- - [Memory in the Age of AI Agents](https://arxiv.org/abs/2512.13564) — Comprehensive survey on agent memory architectures
455
- - [Mem0](https://arxiv.org/pdf/2504.19413) — Human-like memory reinforcement and decay
456
- - [MemOS](https://arxiv.org/pdf/2507.03724) — Memory lifecycle state management
457
- - [Ebbinghaus forgetting curve](https://en.wikipedia.org/wiki/Forgetting_curve) — Exponential memory decay
458
- - [Spreading activation](https://en.wikipedia.org/wiki/Spreading_activation) — Collins & Loftus network model of semantic memory
459
- - [Hebbian theory](https://en.wikipedia.org/wiki/Hebbian_theory) — "Neurons that fire together wire together"
460
- - [Synaptic homeostasis hypothesis](https://doi.org/10.1016/j.neuron.2013.10.024) — Tononi & Cirelli's theory of sleep function
461
- - [SM-2 algorithm](https://en.wikipedia.org/wiki/SuperMemo#Description_of_SM-2_algorithm) — Spaced repetition scheduling
462
- - [Memory reconsolidation](https://en.wikipedia.org/wiki/Memory_consolidation#Reconsolidation) — How recalling memories makes them temporarily malleable
651
+ ### Working-Memory Budget
652
+
653
+ 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:
654
+
655
+ ```json
656
+ {
657
+ "working_memory_budget_tokens": 3000,
658
+ "pin_budget_tokens": 1500,
659
+ "skills_index_budget_tokens": 800,
660
+ "recall_budget_tokens": 700
661
+ }
662
+ ```
663
+
664
+ | Setting | Default | Description |
665
+ |---------|---------|-------------|
666
+ | `working_memory_budget_tokens` | 3000 | Total token ceiling for the whole `brain session-start` payload |
667
+ | `pin_budget_tokens` | 1500 | Sub-budget for pinned, always-present memories |
668
+ | `skills_index_budget_tokens` | 800 | Sub-budget for the advertised skills index (L0) |
669
+ | `recall_budget_tokens` | 700 | Sub-budget for context-relevant recalled memories |
670
+
671
+ 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.
672
+
673
+ ## Benchmark
674
+
675
+ 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**](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.
676
+
677
+ **Six scenarios**, each describable in one sentence:
678
+
679
+ | Id | Pitch | Tests |
680
+ |---|---|---|
681
+ | **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) |
682
+ | **B** *Three Sessions, One Decision* | "Postgres Monday, gRPC rewrite Wednesday, new resource Friday — still Postgres?" | Multi-session continuity + Pinned Tier ablation |
683
+ | **C** *The Contradiction Test* | "Tabs, then spaces, then tabs again — which version wins?" | Decay-weighted recency + contradiction handling |
684
+ | **D** *Skill Progressive Disclosure* | "Five skills indexed, one needed — does brain load just the one?" | CoALA Phase-2 L0/L1/L2 token efficiency |
685
+ | **E** *Continual Coding* | "Five bugs in order — does bug 5 finish faster than bug 1?" | Forward transfer; agent writes memories between tasks |
686
+ | **F** *Abstention* | "No deployment target in memory — does the agent ask or invent?" | Confabulation resistance |
687
+
688
+ **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.
689
+
690
+ > 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).
691
+
692
+ Run the benchmarks yourself:
693
+
694
+ ```bash
695
+ cd benchmark
696
+ cp .env.example .env # Add your API keys
697
+ npm test # Unit tests
698
+ node harness/runner.js # Full benchmark (cloud APIs)
699
+ ```
700
+
701
+ Live methodology and per-scenario detail: [brainmemory.ai/docs/benchmarks](https://brainmemory.ai/docs/benchmarks) · Source: [`benchmark/`](benchmark/)
702
+
703
+ ## Contributing
704
+
705
+ Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup, project structure, and how to submit changes.
706
+
707
+ ## References
708
+
709
+ Brain Memory's architecture and benchmark methodology are grounded in the following work.
710
+
711
+ ### Foundations — the agent-memory model Brain implements
712
+
713
+ - [**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.
714
+ - [**MemGPT — LLMs as Operating Systems**](https://arxiv.org/abs/2310.08560) (arxiv 2310.08560) — Packer et al. Paging-style memory management.
715
+ - [**Generative Agents — Interactive Simulacra of Human Behavior**](https://arxiv.org/abs/2304.03442) (arxiv 2304.03442) — Park et al. Recency · importance · relevance retrieval blend.
716
+ - [**Memory in the Age of AI Agents**](https://arxiv.org/abs/2512.13564) (arxiv 2512.13564) — Comprehensive survey on agent memory architectures.
717
+ - [**Mem0**](https://arxiv.org/abs/2504.19413) (arxiv 2504.19413) — Human-like memory reinforcement and decay.
718
+ - [**MemOS**](https://arxiv.org/abs/2507.03724) (arxiv 2507.03724) — Memory lifecycle state management.
719
+
720
+ ### Memory benchmarks (the suite this work follows)
721
+
722
+ - [**LongMemEval**](https://arxiv.org/abs/2410.10813) (arxiv 2410.10813) — distractor haystacks (S / M / Oracle), abstention category, GPT-4o judge with 97% human agreement.
723
+ - [**MemoryAgentBench**](https://arxiv.org/abs/2507.05257) (arxiv 2507.05257) — four-competency framework; FactConsolidation inspired Scenario C.
724
+ - [**SWE-Bench-CL**](https://arxiv.org/abs/2507.00014) (arxiv 2507.00014) — repo-scoped chronological evaluation; template for Scenario E.
725
+ - [**LoCoMo**](https://arxiv.org/abs/2402.17753) (arxiv 2402.17753) — long-conversation memory benchmark.
726
+ - [**MIRIX**](https://arxiv.org/abs/2507.07957) (arxiv 2507.07957) — realistic synthetic-but-grounded memory benchmarks.
727
+
728
+ ### Methodology — judging and benchmark hygiene
729
+
730
+ - [**Preference Leakage in LLM-as-judge**](https://arxiv.org/abs/2502.01534) (arxiv 2502.01534) — drives cross-family judging.
731
+ - [**When Judgment Becomes Noise — position bias**](https://arxiv.org/abs/2509.20293) (arxiv 2509.20293) — drives position-swap mitigation.
732
+ - [**Silent Judge — shortcut bias**](https://arxiv.org/abs/2509.26072) (arxiv 2509.26072) — drives rubric-based judging.
733
+ - [**LastingBench**](https://arxiv.org/abs/2506.21614) (arxiv 2506.21614) — benchmark-leakage defense.
734
+
735
+ ### Neuroscience
736
+
737
+ - [**Ebbinghaus forgetting curve**](https://en.wikipedia.org/wiki/Forgetting_curve) — exponential memory decay.
738
+ - [**Spreading activation**](https://en.wikipedia.org/wiki/Spreading_activation) — Collins & Loftus network model of semantic memory.
739
+ - [**Hebbian theory**](https://en.wikipedia.org/wiki/Hebbian_theory) — "neurons that fire together wire together."
740
+ - [**Synaptic homeostasis hypothesis**](https://doi.org/10.1016/j.neuron.2013.10.024) — Tononi & Cirelli's theory of sleep function.
741
+ - [**SM-2 algorithm**](https://en.wikipedia.org/wiki/SuperMemo#Description_of_SM-2_algorithm) — spaced repetition scheduling.
742
+ - [**Memory reconsolidation**](https://en.wikipedia.org/wiki/Memory_consolidation#Reconsolidation) — recalling memories makes them temporarily malleable.
743
+
744
+ ### Related projects
745
+
746
+ - [get-shit-done](https://github.com/gsd-build/get-shit-done) — Structured file-based workflow orchestration for AI agents.
463
747
 
464
748
  ## License
465
749