brain-memory 0.1.0-beta.26 → 0.1.0-beta.27

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,264 @@
1
+ # Changelog
2
+
3
+ All notable changes to brain-memory will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.1.0-beta.27] - 2026-06-10
10
+
11
+ ### Security
12
+
13
+ - **Hosted-service hardening (Brain Cloud + connector).** Memories synced to Brain
14
+ Cloud are now **encrypted at rest** (AES-256-GCM, per-user key, with keys managed
15
+ in a cloud KMS — the key never sits on the server); the connector keeps per-user
16
+ working copies in **RAM only** (tmpfs), never on disk. CLI sessions use
17
+ **rotating refresh tokens with automatic reuse detection** and real **logout**
18
+ (one device or all). The connector now fails closed without an identity provider,
19
+ runs as an unprivileged sandboxed service, safely handles untrusted brain
20
+ bundles, and rate-limits its endpoints; OAuth account-linking requires a
21
+ **verified** email. None of this changes local-only or Git/export use, which stay
22
+ passphrase-encrypted and never touch the cloud. See [SECURITY.md](SECURITY.md).
23
+ - The published package now also ships `SECURITY.md` and `CHANGELOG.md`.
24
+
25
+ ## [0.1.0-beta.25] - 2026-06-07
26
+
27
+ ### Changed
28
+
29
+ - **Brand refresh.** Adopted the firing-neuron "activation" glyph in place of the brain emoji across the prompts, command output, CLI help text, and the README, and refreshed the icon set (`assets/`). No behavior change.
30
+
31
+ ## [0.1.0-beta.24] - 2026-06-05
32
+
33
+ ### Added
34
+
35
+ - **`BRAIN_DIR` environment variable** — point your brain at any folder instead of the default `~/.brain`. Set it to a folder your existing tools already sync (Google Drive, Dropbox, iCloud Drive, OneDrive, Syncthing, or a git working copy) to get cross-device sync with no account and no extra setup. A leading `~/` is expanded. Honored everywhere the brain is resolved — recall, memorize, init, and Cloud sync.
36
+
37
+ ## [0.1.0-beta.23] - 2026-06-05
38
+
39
+ ### Changed
40
+
41
+ - **Command surface collapsed to a six-verb core.** The everyday loop is ambient (recall + memorize), with a small manual surface and maintenance demoted to the background. Removed/merged six commands: `consolidate` and `review` are now handled by `/brain:sleep`; `unpin` is folded into `/brain:pin` (a toggle — `--off` unpins); `sunshine` (forensic erasure) is now `/brain:forget --deep`; `explore` is dropped (browse `~/.brain/` directly or use the web dashboard); and `init` is folded into install + first `/brain:sync` (which auto-creates the structure if missing). The surviving commands are `remember`, `memorize`, `status`, `pin`, `forget`, `sync`, `skills`, and `sleep`. This aligns the plugin with the forthcoming Claude connector, which exposes the same minimal tool set.
42
+
43
+ ### Fixed
44
+
45
+ - **Install detection no longer depends on a specific command.** The Codex/OpenAI skills-style detector keyed off `brain-init/SKILL.md`; it now matches any `brain-*` skill directory, so detection survives command-set changes.
46
+
47
+ ## [0.1.0-beta.21] - 2026-06-03
48
+
49
+ ### Changed
50
+
51
+ - **Primary domain moved to `brainmemory.ai`.** The website, dashboard, and Brain Cloud API now live at `brainmemory.ai`, `app.brainmemory.ai`, and `api.brainmemory.ai`. The plugin's default sync endpoint (`DEFAULT_API_URL`) is now `https://api.brainmemory.ai`. The old `brainmemory.work` hosts remain as redirects — `api.brainmemory.work` issues a `308` to the new API, so existing installs keep syncing without changes.
52
+
53
+ ## [0.1.0-beta.20] - 2026-05-31
54
+
55
+ ### Fixed
56
+
57
+ - **`memorize` and `skill add` now read piped stdin portably (fixes CI on Linux & Windows).** Both CLIs read input by opening the `/dev/stdin` *path*, which works on macOS but throws `ENXIO` on Linux CI runners and doesn't exist on Windows — so the contradiction-surfacing tests failed on every non-macOS job. Switched to reading file descriptor `0` (`fs.readFileSync(0, …)`), which reads piped stdin correctly across Linux, macOS, and Windows.
58
+
59
+ ### Changed
60
+
61
+ - **Project moved to the Omelas organization.** Repository transferred to `github.com/omelas-tech/brain` (old `onurkarali/brain` URLs redirect). Updated `repository`, `bugs`, and all in-repo/website GitHub references accordingly, and set `homepage` to `https://brainmemory.work/`. No code or behavior changes — metadata only. The npm package name stays `brain-memory` (unscoped); install is unchanged.
62
+
63
+ ## [0.1.0-beta.19] - 2026-05-30
64
+
65
+ ### Fixed
66
+
67
+ - **Installer now removes stale command files on update**, so the beta.18 `/brain:skill` → `/brain:skills` rename actually takes effect for existing users. Previously the installer only *copied* the current command set and never deleted renamed/removed files — so an upgrader's old `skill.md` lingered next to the new `skills.md`, and on case-insensitive filesystems that leftover `skill.md` (== `SKILL.md`) kept the whole `commands/brain/` directory shadowed as a single skill, hiding every `/brain:*` command. `installForRuntime` now wipes the `brain` command dir (and stale `brain-*` skill dirs for the Codex skills layout) before writing the fresh set.
68
+
69
+ ## [0.1.0-beta.18] - 2026-05-30
70
+
71
+ ### Fixed
72
+
73
+ - **`/brain:*` slash commands now actually register in Claude Code** (completes the beta.17 fix). On case-insensitive filesystems (default on macOS), the `skill` command file `skill.md` collides with `SKILL.md` — Claude Code's skill loader treated the entire `commands/brain/` directory as a single skill named `brain`, shadowing all 14 commands so none appeared in autocomplete. Renamed the command `skill` → `skills` (`commands/brain/skills.md`, invoked as `/brain:skills`) to remove the collision. The CLI subcommand remains `brain skill`. Updated slash-command references in `prompts/{claude,gemini,opencode}.md`, `CLAUDE.md`, and `README.md`.
74
+
75
+ ## [0.1.0-beta.17] - 2026-05-29
76
+
77
+ ### Fixed
78
+
79
+ - **Claude Code now registers all `/brain:*` slash commands.** The command files (`commands/brain/*.md`) shipped without YAML frontmatter; current Claude Code requires a `description` field to register a `.md` as a slash command, so all 14 commands were silently skipped (only `/brain:skill` surfaced, via the separate skills path). Added `description` + `argument-hint` frontmatter to every command file — the field Claude Code needs, and tolerated by the Gemini / Codex / OpenCode install targets too.
80
+
81
+ ## [0.1.0-beta.16] - 2026-05-28
82
+
83
+ ### Changed
84
+
85
+ - **Benchmark redesigned around 2025-2026 long-term-memory SOTA.** No runtime changes to the brain CLI; this release is a milestone marker for the new evaluation methodology shipped in `benchmark/` and documented at `/docs/benchmarks/`.
86
+ - New N-arm matrix harness with cross-family LLM judge (Claude judges Gemini and vice-versa) — mitigates preference leakage (arxiv 2502.01534) and position bias (arxiv 2509.20293).
87
+ - Six pitchable scenarios (A-F) replacing the legacy 5-scenario suite: Noisy Project Folder (LongMemEval-S retrieval-under-distractors), Three Sessions / One Decision (Pinned Tier ablation), The Contradiction Test (decay + recency), Skill Progressive Disclosure (CoALA Phase-2 L0/L1/L2 ablation), Continual Coding (SWE-Bench-CL style with real `brain memorize` between tasks), Abstention (confabulation resistance).
88
+ - Deterministic 200-memory distractor haystack; real `brain session-start` / `brain recall` integration with Recall@k / NDCG@k scoring against oracle ID sets.
89
+ - Tokens-per-successful-task adopted as the headline efficiency metric (Mem0/BEAM standard); write-side cost co-reported.
90
+ - New OpenCode CLI agent adapter (default model `deepseek/deepseek-v4-pro`), with `--opencode-model` override for cheaper DeepSeek variants.
91
+ - Codex CLI dropped from the default benchmark suite (no token reporting); remains a fully supported brain install target.
92
+ - Legacy scenarios 1-5 stay on disk for reproducing historical reports; invoke explicitly via `--scenario scenario-N-…`.
93
+
94
+ ## [0.1.0-beta.15] - 2026-05-27
95
+
96
+ ### Changed
97
+
98
+ - **BREAKING: unified CLI surface** — the five separate binaries (`brain-memory`, `brain-recall`, `brain-reinforce`, `brain-cloud`, `brain-memorize`) are replaced by a single `brain` dispatcher with subcommands: `brain recall`, `brain memorize`, `brain reinforce`, `brain cloud <…>`, and `brain install|update|uninstall` (bare `brain` runs the installer). New features ship as subcommands rather than new top-level binaries. Re-run the installer/update to refresh prompts; agents now invoke `brain <command>`. (`bin/brain.js`)
99
+
100
+ ### Added
101
+
102
+ - `brain --help` / `brain --version` on the unified dispatcher
103
+ - **CoALA Phase 0 — budget-aware working memory.** New `brain session-start` aggregator returns a single deterministic, token-budget-bounded startup payload (`memory_count`, `pinned`, `skills_index`, `context_recall`, `due_for_review`, `low_confidence_alerts`, `budget`); `~/.brain/config.json` holds the working-memory budget (created lazily with safe defaults); each new memory records a `token_estimate`. Session-start prompts/hook now make one `brain session-start` call instead of hand-rolled recall + review + low-confidence checks.
104
+ - **CoALA Phase 3 — procedural crystallization.** New `/brain:sleep` phase (4b) clusters repeated procedural/experience memories and proposes distilling a recurring task-solving procedure into a `SKILL.md` (user-confirmed, never silent) — learned skills, not just hand-authored ones.
105
+ - **CoALA Phase 4 — host skill export.** `brain skill export <name> [--target claude|gemini]` emits a native `.claude/skills/<name>/SKILL.md` (or `.gemini/...`) so distilled skills become directly executable by the host. The new state files (`config.json`, `pinned.json`, `skills-index.json`, `_skills/`) sync automatically via the existing whole-directory git/export-import engines.
106
+ - **Tier B §10.1 — obsolescence / context-shift detection.** `/brain:sleep` Prune phase flags memory clusters whose project/role has been absent from recent sessions (`contexts.json`) as reversible archive candidates — catching abrupt relevance loss that decay misses. Never flags pinned memories.
107
+ - **Tier B §10.2 — contradiction surfacing.** `brain memorize` now reports `potential_conflicts` when a new memory heavily overlaps a pinned/stable memory; `/brain:memorize` guidance has the agent adjudicate (supersede / keep-both-scoped / reject) instead of silently keeping both.
108
+ - **Tier B §10.4 — primacy/recency ordering.** `brain session-start` orders recalled memories so the highest-ranked land at the edges of the payload, mitigating "lost in the middle."
109
+ - **CoALA Phase 2 — procedural skills layer.** Skills are stored as `~/.brain/_skills/<name>/SKILL.md` and served via three-level progressive disclosure (L0 session-start advertises name + description only; L1 reads the full skill on a matching task; L2 loads resources at execution). `brain skill list|show <name>|use <name> [--failed]|add|remove <name>` and `/brain:skill`. Procedural strength rises on successful `use` and falls on `--failed`; a skill that fails too often demotes itself out of the advertised L0 index (Tier B §10.3). `~/.brain/skills-index.json` holds the L0 list; session-start injects skill summaries budget-capped by `skills_index_budget_tokens`.
110
+ - **CoALA Phase 1 — pinned semantic tier + stable flag.** `brain pin <id> [--scope global|project:<name>] [--priority N]` / `brain unpin <id>` and the `/brain:pin` `/brain:unpin` commands. Pinned memories are injected at every session start regardless of recall score and are decay-exempt; `stable: true` exempts a memory from decay without forcing it to always load. `pinned`/`stable` memories are skipped by sleep-cycle homeostasis and pruning. `~/.brain/pinned.json` manifest; `/brain:memorize` now proposes pinning durable conventions. Fixes the long-standing hole where a stored preference (e.g. "always use tabs") only applied if recall happened to surface it.
111
+
112
+ ## [0.1.0-beta.14] - 2026-04-25
113
+
114
+ ### Added
115
+
116
+ - **OpenCode support** — `brain --opencode` installs Brain Memory for the OpenCode agent (`prompts/opencode.md`), bringing the supported runtimes to Claude Code, Gemini CLI, OpenAI Codex CLI, and OpenCode.
117
+
118
+ ### Fixed
119
+
120
+ - **Graceful handling of corrupt brain state files** — CLI tools now emit a clear, actionable error (naming the offending JSON and suggesting a sync/backup restore) instead of crashing when `index.json`, `associations.json`, or the search index is malformed.
121
+
122
+ ### Changed
123
+
124
+ - **Install docs recommend `npm install -g` over `npx`** — `npx` discards the temporary install, so the `brain` CLI never lands in `PATH` and agents fall back to less reliable manual file operations.
125
+
126
+ ## [0.1.0-beta.13] - 2026-04-05
127
+
128
+ ### Added
129
+
130
+ - **`brain-memorize` CLI** — single-command memory storage that handles all plumbing (ID generation, strength/decay computation, directory creation, file writing, index updates, association edges, search index) in one call
131
+ - `--sync` flag for `/brain:memorize` — auto-pushes to cloud/git after storing, eliminating the separate `/brain:sync push` step
132
+ - `--confirm` flag for `/brain:memorize` — opt-in confirmation (was previously the default)
133
+ - Install check for `brain-cloud` CLI in `/brain:sync cloud push` — shows install instructions if missing
134
+
135
+ ### Changed
136
+
137
+ - **`/brain:memorize` is now non-interactive by default** — stores immediately and shows results after, instead of asking "Store these memories?" before writing. The user said "memorize" — they want it stored.
138
+ - **`/brain:sync push` and `cloud push` are now non-interactive** — execute immediately without confirmation, matching `git push` behavior. Pull/import still confirm before overwriting.
139
+ - **Memorize prompt reduced ~60%** — AI classifies memories and pipes JSON to `brain-memorize` CLI instead of manually writing files. One bash call instead of 6-8 tool calls.
140
+ - **Session start behavior made lightweight** — recall engine skips if project has no matching memories, output condensed to single status line, removed heavy mandatory phrasing
141
+
142
+ ## [0.1.0-beta.12] - 2026-04-02
143
+
144
+ ### Added
145
+
146
+ - **Brain Cloud sync** — push/pull `~/.brain/` to Brain Cloud (`api.brainmemory.work`) via new cloud subcommands
147
+ - `brain-cloud` CLI (`bin/cloud-sync.js`) — device code auth, push, pull, status, logout
148
+ - `src/cloud-sync.js` — zero-dependency cloud sync engine using Node.js built-in `https` module
149
+ - Device code OAuth flow for CLI authentication (`/brain:sync cloud login`)
150
+ - Tar.gz archive-based sync protocol for efficient uploads/downloads
151
+ - Token management with automatic refresh
152
+ - Cloud subcommands in `/brain:sync`: `cloud login`, `cloud push`, `cloud pull`, `cloud status`, `cloud logout`
153
+
154
+ ## [0.1.0-beta.11] - 2026-03-22
155
+
156
+ ### Added
157
+
158
+ - **Ambient Session Tracking** — agent maintains a running mental log of decisions, learnings, insights, experiences, and goals as they happen throughout the session, so nothing is lost by session end
159
+ - **Periodic Memory Checkpoint** — every ~10 substantive interactions, the agent appends a one-liner nudge to its next response, never interrupting flow
160
+ - `notable_unsaved` field in session context — preserves what happened even when the user doesn't memorize, so future sessions can reference it
161
+ - `update` subcommand — auto-detects existing installations and refreshes commands + prompt sections (`brain-memory update`)
162
+ - `uninstall` subcommand — removes commands and prompt sections, preserves `.brain/` by default (`brain-memory uninstall`)
163
+ - `detectInstallations()`, `removePromptSection()`, `removeCommands()`, `uninstallForRuntime()` in `src/installer.js`
164
+ - Subcommand routing in `bin/install.js` with `parseArgs()`, `runUpdate()`, `runUninstall()`
165
+ - 20 new tests covering detection, removal, and round-trip install/uninstall
166
+ - Git-based sync — push/pull `.brain/` to any private Git remote (GitHub, GitLab, Codeberg, self-hosted) via `/brain:sync setup/push/pull`
167
+ - Export/Import — single-file encrypted backup for portable transfers via `/brain:sync export` and `/brain:sync import`
168
+ - `src/crypto.js` — standalone AES-256-GCM crypto module extracted from the old sync code
169
+ - `src/git-sync.js` — Git sync engine using `child_process.execFileSync`
170
+ - `src/export-import.js` — single-file export/import with encryption and merge mode
171
+ - 74 new tests: installer unit tests (`test/install.test.js`) and prompt content validation + integration tests (`test/prompts.test.js`)
172
+ - Deterministic recall engine with TF-IDF scoring (`bin/recall.js`, `bin/reinforce.js`)
173
+ - Benchmark suite with automated multi-agent evaluation
174
+ - Website with full documentation site at brainmemory.work
175
+
176
+ ### Changed
177
+
178
+ - **Session End Behavior** — context save to `contexts.json` is now the first action (was an afterthought), saves unconditionally even for trivial sessions, and proactively detects session endings without waiting for explicit signals
179
+ - **`/brain:memorize` command** — restructured prompt for efficiency: batches all file writes into a single parallel call, skips reads when state is already in context, presents proposed memories for user confirmation before writing, targets 3-4 tool call rounds total (was 6+)
180
+ - `/brain:sync` now uses Git remotes instead of OAuth cloud providers — no more registering OAuth apps
181
+ - Replaced cloud sync dashboard in `/brain:status` with git sync status (remote URL, ahead/behind counts)
182
+ - Extracted installer logic from `bin/install.js` into `src/installer.js` for testability — `bin/install.js` is now a thin CLI wrapper
183
+ - Hook files (`hooks/session-start.md`, `hooks/session-end.md`) now have reference notes clarifying that behavior is delivered through prompt injection, not native hook events
184
+ - Removed dead `settingsFile` config from runtime definitions — it was never used
185
+ - Removed `hooks/` from npm package since they are internal reference docs, not user-facing files
186
+ - Website redesigned with clean light theme and updated icon
187
+
188
+ ### Removed
189
+
190
+ - Cloud sync module (`src/sync/`) — OAuth2, Dropbox, Google Drive, and OneDrive providers
191
+ - OAuth token storage (`credentials.enc`) and three-way diff sync state (`sync-state.json`)
192
+
193
+ ### Fixed
194
+
195
+ - Git sync repo isolation — the `git()` helper in `src/git-sync.js` only used `cwd` to scope commands; if `.brain/.sync/repo/.git` didn't exist yet (first push or failed init), git would walk up the directory tree and commit brain files to the parent project repo. Now uses `GIT_DIR` + `GIT_WORK_TREE` env vars to fully isolate the sync repo.
196
+ - Session lifecycle was dead code — session-start/end hook instructions were defined in `hooks/` but never installed or referenced anywhere. The prompt injected into CLAUDE.md/GEMINI.md/AGENTS.md only had a weak one-liner about memorization. Now all three prompt files contain full "Session Start Behavior" and "Session End Behavior" sections with automatic brain context loading, review queue alerts, and end-of-session memorization suggestions.
197
+ - `release:beta` npm script now automatically updates the `latest` dist-tag after publishing
198
+ - Accurate model names in benchmark results
199
+
200
+ ## [0.1.0-beta.4] - 2026-03-03
201
+
202
+ ### Added
203
+
204
+ - `/brain:sync` command — cloud sync for pushing/pulling memories to Dropbox, Google Drive, or OneDrive
205
+ - Cloud sync module (`src/sync/`) with OAuth2 PKCE + Device Code Flow, AES-256-GCM encryption, three-way diff algorithm, and provider-specific implementations (Dropbox API v2, Google Drive API v3, Microsoft Graph API)
206
+ - Zero new dependencies — uses Node.js 18+ built-in `fetch`, `crypto`, `http`
207
+
208
+ ### Changed
209
+
210
+ - Removed all v1 migration code and references — no v1 users exist
211
+ - Updated documentation to reflect 11 slash commands and cloud sync
212
+
213
+ ## [0.1.0-beta.3] - 2026-02-28
214
+
215
+ ### Added
216
+
217
+ - `/brain:sunshine` command — deep forensic memory erasure that traces and removes all references across the `.brain/` tree (related arrays, content mentions, association edges, context sessions, review queue, archive index, crystallization comments)
218
+ - `removeEdgesForMemory()` utility in index-manager for removing all association edges involving a memory
219
+ - `removeFromReviewQueue()` utility in index-manager for removing a memory from the review queue
220
+ - `_erased.json` audit log schema for tracking erasures without preserving erased content
221
+ - 16 new tests for erasure utilities
222
+ - npm release scripts (`release:beta`, `release:patch`, `release:minor`, `release:major`)
223
+
224
+ ### Fixed
225
+
226
+ - Windows CI compatibility: explicit test file listing, bash shell for glob expansion, `path.join` in tests
227
+ - Relaxed stress test thresholds for CI runners (5x multiplier)
228
+
229
+ ## [0.1.0-beta.1] - 2026-02-22
230
+
231
+ ### Added
232
+
233
+ - 375x faster `rankMemories` via batch spreading activation
234
+
235
+ ### Fixed
236
+
237
+ - Clamped recency bonus and optimized spreading activation loop
238
+ - Normalized `package.json` bin and repository fields for npm
239
+
240
+ ## [0.1.0] - 2026-02-15
241
+
242
+ Initial beta release.
243
+
244
+ ### Added
245
+
246
+ - 9 slash commands: `init`, `memorize`, `remember`, `review`, `explore`, `consolidate`, `forget`, `sleep`, `status`
247
+ - Neuroscience-inspired scoring with Ebbinghaus exponential decay
248
+ - Associative memory network with spreading activation (BFS, 2-hop, 50% decay per hop)
249
+ - Hebbian learning for co-retrieved memories
250
+ - Context-dependent recall scoring (project, topic Jaccard, task type matching)
251
+ - Spaced reinforcement with logarithmic spacing multiplier and diminishing returns
252
+ - 3 cognitive memory types: episodic, semantic, procedural (each with distinct decay behavior)
253
+ - Salience-based protection preventing auto-pruning of important memories
254
+ - Confidence tracking with contradiction detection
255
+ - 9-phase sleep cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, expertise detection
256
+ - SM-2 spaced repetition review scheduler
257
+ - Memory consolidation with salience anchoring
258
+ - Archive system with recoverable memories
259
+ - Multi-factor recall scoring formula (relevance, strength, recency, spreading, context, salience)
260
+ - Multi-runtime installer: Claude Code, Gemini CLI, OpenAI Codex CLI
261
+ - Interactive and non-interactive installation modes
262
+ - Session lifecycle hook definitions (session-start, session-end)
263
+ - 114 tests covering scorer, index-manager, and end-to-end lifecycle
264
+ - Zero external dependencies
package/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
 
13
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.
14
14
 
15
- Works with **Claude Code**, **Gemini CLI**, **OpenAI Codex CLI**, and **OpenCode**.
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.
16
16
 
17
17
  ```
18
18
  ~/.brain/
@@ -52,6 +52,50 @@ Existing AI memory solutions use flat databases with tag-based retrieval. Brain
52
52
 
53
53
  ## Install
54
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
+
66
+ ```bash
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
72
+ ```
73
+
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`.)*
92
+
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
98
+
55
99
  ```bash
56
100
  npm install -g brain-memory@beta
57
101
  brain
@@ -59,16 +103,23 @@ brain
59
103
 
60
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.
61
105
 
62
- The second command runs the setup wizard, which 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.
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:
63
107
 
64
- ### Non-interactive
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
65
116
 
66
117
  ```bash
67
- brain --claude --global # Claude Code, global
68
- brain --gemini --local # Gemini CLI, local project
69
- brain --codex --global # OpenAI Codex CLI, global
70
- brain --opencode --global # OpenCode, global
71
- brain --all --global # All runtimes, global
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
72
123
  ```
73
124
 
74
125
  ### Update
@@ -78,7 +129,7 @@ npm install -g brain-memory@beta
78
129
  brain update
79
130
  ```
80
131
 
81
- 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`, `--gemini`, `--openai`, or `--all`.
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`.
82
133
 
83
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.
84
135
 
@@ -95,27 +146,38 @@ The first command removes slash commands and prompt sections from your agent con
95
146
 
96
147
  ### Manual Install
97
148
 
98
- 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.
99
150
 
100
151
  ```bash
101
- # Claude Code
152
+ # Claude Code — flat slash commands
102
153
  cp -r commands/brain/ ~/.claude/commands/brain/
103
154
 
104
- # Gemini CLI
105
- 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/
106
158
 
107
- # OpenAI Codex CLI (each command becomes a skill)
159
+ # OpenAI Codex CLI — each command becomes a skill under the cross-tool skills dir
108
160
  for f in commands/brain/*.md; do
109
161
  name=$(basename "$f" .md)
110
- mkdir -p ~/.codex/skills/brain-"$name"
111
- cp "$f" ~/.codex/skills/brain-"$name"/SKILL.md
162
+ mkdir -p ~/.agents/skills/brain-"$name"
163
+ cp "$f" ~/.agents/skills/brain-"$name"/SKILL.md
164
+ done
165
+
166
+ # Google Antigravity (experimental — verify paths) — skills under ~/.gemini/skills/
167
+ for f in commands/brain/*.md; do
168
+ name=$(basename "$f" .md)
169
+ mkdir -p ~/.gemini/skills/brain-"$name"
170
+ cp "$f" ~/.gemini/skills/brain-"$name"/SKILL.md
112
171
  done
113
172
  ```
114
173
 
115
174
  Then append the contents of the corresponding prompt file to your agent's instructions file:
116
175
  - `prompts/claude.md` → `CLAUDE.md`
117
- - `prompts/gemini.md` → `GEMINI.md`
118
- - `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).
119
181
 
120
182
  ## Commands
121
183
 
@@ -446,7 +508,7 @@ Failed recalls reset the interval to 1 day. Successful recalls extend the interv
446
508
 
447
509
  ### Cross-Agent Memory Sharing
448
510
 
449
- `~/.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 Gemini CLI, OpenAI Codex CLI, or OpenCode 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.
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.
450
512
 
451
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.**
452
514
 
@@ -494,6 +556,13 @@ confirmation) — so you can capture a memory on your phone and recall it on you
494
556
 
495
557
  → Full guide: **[Use Brain in Claude apps](https://brainmemory.ai/docs/getting-started/claude-apps)**
496
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)**.
565
+
497
566
  ## File Structure
498
567
 
499
568
  ```
package/SECURITY.md ADDED
@@ -0,0 +1,61 @@
1
+ # Security Policy
2
+
3
+ ## Reporting Vulnerabilities
4
+
5
+ If you discover a security vulnerability, please report it privately via email to **onur@omelas.tech**. Do not open a public GitHub issue for security vulnerabilities.
6
+
7
+ You should receive a response within 48 hours. Please include:
8
+ - Description of the vulnerability
9
+ - Steps to reproduce
10
+ - Potential impact
11
+
12
+ ## Scope
13
+
14
+ Brain Memory handles sensitive data in several areas:
15
+
16
+ - **AES-256-GCM encryption** — Optional encryption for Git-synced and exported memory files using a user-provided passphrase (PBKDF2-SHA512, 100K iterations)
17
+ - **File system access** — Reads and writes to the `.brain/` directory tree
18
+ - **Git operations** — When sync is configured, pushes/pulls to a user-specified Git remote using the system `git` binary and the user's existing Git/SSH authentication
19
+
20
+ ## Hosted service: Brain Cloud & the connector
21
+
22
+ Brain Memory is **local-first** — by default your memories are plain files on your
23
+ own disk and never leave it. The hosted **Brain Cloud** sync hub and the **Claude
24
+ connector** (a remote MCP server) are entirely optional. When you do use them, this
25
+ is how your data is protected:
26
+
27
+ - **Encrypted at rest.** Brains stored in Brain Cloud are encrypted on disk with
28
+ **AES-256-GCM** using a **per-user key** (HKDF-derived from a server master key).
29
+ A stolen disk, backup, or snapshot yields no readable memories.
30
+ - **No plaintext on the connector.** The connector keeps each user's working copy
31
+ in **RAM only** (a tmpfs, wiped on restart) — it is never written to the
32
+ connector's disk.
33
+ - **Encrypted in transit.** All traffic to `api.brainmemory.ai` and the connector
34
+ is HTTPS/TLS.
35
+ - **Strict tenant isolation.** Every cloud request is authorized against the
36
+ authenticated user; one account can never read or overwrite another's brain.
37
+ - **Revocable sessions.** CLI sessions use **rotating refresh tokens with
38
+ automatic reuse detection** — a replayed (stolen) token revokes the whole
39
+ session family. You can log out a device, or **all** devices, at any time.
40
+ - **Verified-identity sign-in.** Connector and dashboard login is Google OAuth via
41
+ Firebase; account-linking requires a **verified** email.
42
+ - **Least privilege.** The connector runs as an unprivileged, sandboxed service
43
+ (systemd hardening: no new privileges, read-only filesystem, private tmp).
44
+
45
+ Because the cloud runs deterministic recall server-side, this is **server-side**
46
+ encryption at rest, not end-to-end encryption: the service necessarily processes
47
+ your memories in memory. If you require that the server never sees plaintext, keep
48
+ your brain **local-only** (the default) or use Git/export sync with a passphrase
49
+ (below) instead of Brain Cloud.
50
+
51
+ ## Supported Versions
52
+
53
+ | Version | Supported |
54
+ |---------|-----------|
55
+ | 0.1.x (beta) | Yes |
56
+
57
+ ## Design Principles
58
+
59
+ - **No runtime dependencies** — Reduces supply chain attack surface
60
+ - **Local-first** — Sensitive data stays on disk by default; sync is opt-in
61
+ - **No stored credentials** — Git sync relies on the user's existing SSH keys or Git credential helpers; Brain Memory never stores auth tokens
package/assets/icon.png CHANGED
Binary file
package/assets/icon.svg CHANGED
@@ -1 +1,19 @@
1
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="1024" height="1024" role="img" aria-label="Brain Memory"><defs><filter id="bi0-lg" x="-20%" y="-20%" width="140%" height="140%"><feGaussianBlur stdDeviation="1.6"/></filter><radialGradient id="bi0-g0"><stop offset="0%" stop-color="#adb5c2" stop-opacity="1.00"/><stop offset="100%" stop-color="#5A6B84" stop-opacity="0"/></radialGradient><radialGradient id="bi0-g1"><stop offset="0%" stop-color="#b7d4eb" stop-opacity="0.66"/><stop offset="100%" stop-color="#6FA8D6" stop-opacity="0"/></radialGradient><radialGradient id="bi0-g2"><stop offset="0%" stop-color="#f8d09f" stop-opacity="0.67"/><stop offset="100%" stop-color="#F0A03E" stop-opacity="0"/></radialGradient><radialGradient id="bi0-g3"><stop offset="0%" stop-color="#9fc7c7" stop-opacity="0.80"/><stop offset="100%" stop-color="#3F8E8E" stop-opacity="0"/></radialGradient><radialGradient id="bi0-g4"><stop offset="0%" stop-color="#fae1a5" stop-opacity="0.70"/><stop offset="100%" stop-color="#F5C24B" stop-opacity="0"/></radialGradient></defs><rect x="0" y="0" width="256" height="256" rx="56" ry="56" fill="#07090A"/><g filter="url(#bi0-lg)" opacity="0.9"><line x1="128" y1="128" x2="138.9" y2="230.8" stroke="#658aad" stroke-width="3.71" stroke-opacity="0.40" stroke-linecap="round"/><line x1="128" y1="128" x2="231.4" y2="127.5" stroke="#a89768" stroke-width="3.84" stroke-opacity="0.42" stroke-linecap="round"/><line x1="128" y1="128" x2="24.8" y2="134.6" stroke="#a58661" stroke-width="3.73" stroke-opacity="0.41" stroke-linecap="round"/><line x1="138.9" y1="230.8" x2="231.4" y2="127.5" stroke="#b2b591" stroke-width="2.75" stroke-opacity="0.30" stroke-linecap="round"/><line x1="138.9" y1="230.8" x2="24.8" y2="134.6" stroke="#b0a48a" stroke-width="2.64" stroke-opacity="0.29" stroke-linecap="round"/><line x1="24.8" y1="134.6" x2="122.7" y2="24.7" stroke="#989766" stroke-width="3.10" stroke-opacity="0.34" stroke-linecap="round"/><line x1="128" y1="128" x2="122.7" y2="24.7" stroke="#4d7d89" stroke-width="4.18" stroke-opacity="0.45" stroke-linecap="round"/><line x1="122.7" y1="24.7" x2="231.4" y2="127.5" stroke="#9aa86d" stroke-width="3.22" stroke-opacity="0.35" stroke-linecap="round"/></g><circle cx="128" cy="128" r="62.40" fill="url(#bi0-g0)"/><circle cx="128" cy="128" r="18.72" fill="#dbdee4" fill-opacity="1.00"/><circle cx="138.9" cy="230.8" r="34.66" fill="url(#bi0-g1)"/><circle cx="138.9" cy="230.8" r="10.40" fill="#dfecf6" fill-opacity="0.80"/><circle cx="24.8" cy="134.6" r="35.06" fill="url(#bi0-g2)"/><circle cx="24.8" cy="134.6" r="10.52" fill="#fcead5" fill-opacity="0.80"/><circle cx="122.7" cy="24.7" r="46.49" fill="url(#bi0-g3)"/><circle cx="122.7" cy="24.7" r="13.95" fill="#d5e6e6" fill-opacity="0.88"/><circle cx="231.4" cy="127.5" r="37.92" fill="url(#bi0-g4)"/><circle cx="231.4" cy="127.5" r="11.38" fill="#fdf2d7" fill-opacity="0.82"/></svg>
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="1024" height="1024" role="img" aria-label="Brain Memory"><defs><radialGradient id="core" cx="50%" cy="50%" r="50%"><stop offset="0%" stop-color="#8FDDFF" stop-opacity="0.95"/><stop offset="100%" stop-color="#46C6FF" stop-opacity="0"/></radialGradient></defs><rect x="0" y="0" width="32" height="32" rx="7" ry="7" fill="#07090A"/>
2
+ <circle cx="16" cy="16" r="12" fill="url(#core)" opacity="0.7"/>
3
+ <g stroke="#2E9FD6" stroke-width="1.25" stroke-linecap="round">
4
+ <line x1="16" y1="16" x2="8" y2="8" stroke-opacity="0.4"/>
5
+ <line x1="16" y1="16" x2="25" y2="8" stroke-opacity="0.82"/>
6
+ <line x1="16" y1="16" x2="27" y2="17" stroke-opacity="0.5"/>
7
+ <line x1="16" y1="16" x2="24" y2="25" stroke-opacity="0.75"/>
8
+ <line x1="16" y1="16" x2="8" y2="23" stroke-opacity="0.4"/>
9
+ <line x1="16" y1="16" x2="6" y2="16" stroke-opacity="0.35"/>
10
+ </g>
11
+ <circle cx="8" cy="8" r="1.6" fill="#1C7FB0"/>
12
+ <circle cx="27" cy="17" r="1.4" fill="#4FB8E6"/>
13
+ <circle cx="24" cy="25" r="1.9" fill="#2E9FD6"/>
14
+ <circle cx="8" cy="23" r="1.6" fill="#2389BE"/>
15
+ <circle cx="6" cy="16" r="1.3" fill="#1B6E97"/>
16
+ <circle cx="25" cy="8" r="2.4" fill="#6FD3FF"/>
17
+ <circle cx="21" cy="11.5" r="1.3" fill="#CFEEFF"/>
18
+ <circle cx="16" cy="16" r="3.7" fill="#DFF4FF"/>
19
+ <circle cx="16" cy="16" r="1.9" fill="#FFFFFF"/></svg>
package/bin/forget.js ADDED
@@ -0,0 +1,120 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain forget <id> — archive a memory (recoverable). Deterministic helper used
5
+ * by the connector's `brain_forget` tool. Honors BRAIN_DIR.
6
+ *
7
+ * Archive (default): move the memory file into `_archived/`, record it in
8
+ * `_archived/index.json`, and remove it from the live index, associations,
9
+ * review queue, and search index — so it stops surfacing in recall but stays
10
+ * recoverable. Deep / forensic erasure remains the agent-driven `/brain:forget
11
+ * --deep` path; this primitive only archives.
12
+ *
13
+ * Usage:
14
+ * BRAIN_DIR=/path/to/.brain node bin/forget.js mem_20260101_abc123
15
+ *
16
+ * Output: JSON describing the result.
17
+ */
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+
22
+ const {
23
+ getBrainDir,
24
+ readIndex, writeIndex, removeMemory,
25
+ readAssociations, writeAssociations, removeEdgesForMemory,
26
+ readReviewQueue, writeReviewQueue, removeFromReviewQueue,
27
+ readArchiveIndex, writeArchiveIndex,
28
+ readSearchIndex, writeSearchIndex,
29
+ } = require('../src/index-manager');
30
+ const { removeDocument } = require('../src/tfidf');
31
+
32
+ function main(argv) {
33
+ const args = argv || process.argv.slice(2);
34
+ const id = args.find((a) => a && !a.startsWith('--'));
35
+ const force = args.includes('--force');
36
+ if (!id) {
37
+ console.error(JSON.stringify({ error: 'Usage: brain forget <id> [--force]' }));
38
+ process.exit(1);
39
+ }
40
+
41
+ const brainDir = getBrainDir();
42
+ const index = readIndex();
43
+ if (!index) {
44
+ console.error(JSON.stringify({ error: 'Brain not initialized.' }));
45
+ process.exit(1);
46
+ }
47
+ const entry = index.memories[id];
48
+ if (!entry) {
49
+ console.error(JSON.stringify({ error: `Memory not found: ${id}` }));
50
+ process.exit(1);
51
+ }
52
+
53
+ // CoALA salience protection: high-salience memories are "never auto-pruned"
54
+ // (the documented guarantee). Enforce it deterministically here — the only
55
+ // archival primitive — instead of relying on the agent to honor it. --force
56
+ // overrides for a deliberate, explicit removal.
57
+ const SALIENCE_FLOOR = 0.7;
58
+ if (!force && typeof entry.salience === 'number' && entry.salience >= SALIENCE_FLOOR) {
59
+ console.error(JSON.stringify({
60
+ error: `Refusing to archive high-salience memory ${id} (salience ${entry.salience} >= ${SALIENCE_FLOOR}). Pass --force to override.`,
61
+ protected: true,
62
+ }));
63
+ process.exit(1);
64
+ }
65
+
66
+ const now = new Date().toISOString();
67
+
68
+ // 1. Move the memory file into _archived/ (recoverable).
69
+ let archivedPath = null;
70
+ if (entry.path) {
71
+ const src = path.join(brainDir, entry.path);
72
+ const dest = path.join(brainDir, '_archived', entry.path);
73
+ if (fs.existsSync(src)) {
74
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
75
+ fs.renameSync(src, dest);
76
+ archivedPath = path.join('_archived', entry.path);
77
+ }
78
+ }
79
+
80
+ // 2. Record in the archive index.
81
+ const arch = readArchiveIndex() || { version: 1, archived_count: 0, memories: {} };
82
+ arch.memories[id] = {
83
+ path: entry.path, archived_path: archivedPath, title: entry.title, type: entry.type,
84
+ cognitive_type: entry.cognitive_type, strength: entry.strength, salience: entry.salience,
85
+ confidence: entry.confidence, tags: entry.tags || [], archived_date: now, archived_reason: 'forget',
86
+ };
87
+ arch.archived_count = Object.keys(arch.memories).length;
88
+ writeArchiveIndex(arch);
89
+
90
+ // 3. Remove from the live index.
91
+ removeMemory(index, id);
92
+ writeIndex(index);
93
+
94
+ // 4. Remove association edges.
95
+ const assoc = readAssociations() || { version: 1, edges: {} };
96
+ removeEdgesForMemory(assoc, id);
97
+ writeAssociations(assoc);
98
+
99
+ // 5. Remove from the review queue.
100
+ const queue = readReviewQueue();
101
+ if (queue) {
102
+ removeFromReviewQueue(queue, id);
103
+ writeReviewQueue(queue);
104
+ }
105
+
106
+ // 6. Remove from the search index (so it stops being recalled).
107
+ const searchIndex = readSearchIndex(brainDir);
108
+ if (searchIndex) {
109
+ removeDocument(searchIndex, id);
110
+ writeSearchIndex(brainDir, searchIndex);
111
+ }
112
+
113
+ console.log(JSON.stringify({ archived: true, id, title: entry.title, memory_count: index.memory_count }));
114
+ }
115
+
116
+ if (require.main === module) {
117
+ main(process.argv.slice(2));
118
+ }
119
+
120
+ module.exports = { main };
package/bin/install.js CHANGED
@@ -49,10 +49,12 @@ function parseArgs(argv) {
49
49
  function resolveRuntimesFromFlags(flags) {
50
50
  const runtimes = [];
51
51
  if (flags.has('claude')) runtimes.push('claude');
52
- if (flags.has('gemini')) runtimes.push('gemini');
53
52
  if (flags.has('openai') || flags.has('codex')) runtimes.push('openai');
54
53
  if (flags.has('opencode')) runtimes.push('opencode');
55
- if (flags.has('all')) return ['claude', 'gemini', 'openai', 'opencode'];
54
+ if (flags.has('antigravity')) runtimes.push('antigravity');
55
+ // --all installs the verified CLIs. Antigravity stays opt-in (--antigravity)
56
+ // because its native paths are experimental / pending live verification.
57
+ if (flags.has('all')) return ['claude', 'openai', 'opencode'];
56
58
  return runtimes;
57
59
  }
58
60
 
@@ -76,10 +78,10 @@ async function runInstall(flags) {
76
78
  if (runtimes.length === 0) {
77
79
  console.log(' Which runtimes would you like to install for?\n');
78
80
  console.log(' 1) Claude Code');
79
- console.log(' 2) Gemini CLI');
80
- console.log(' 3) OpenAI Codex CLI');
81
- console.log(' 4) OpenCode');
82
- console.log(' 5) All');
81
+ console.log(' 2) OpenAI Codex CLI');
82
+ console.log(' 3) OpenCode');
83
+ console.log(' 4) Google Antigravity (experimental)');
84
+ console.log(' 5) All current CLIs (Claude Code + Codex + OpenCode)');
83
85
  console.log('');
84
86
 
85
87
  const choice = await ask(rl, ' Select (1/2/3/4/5): ');
@@ -88,16 +90,16 @@ async function runInstall(flags) {
88
90
  runtimes = ['claude'];
89
91
  break;
90
92
  case '2':
91
- runtimes = ['gemini'];
93
+ runtimes = ['openai'];
92
94
  break;
93
95
  case '3':
94
- runtimes = ['openai'];
96
+ runtimes = ['opencode'];
95
97
  break;
96
98
  case '4':
97
- runtimes = ['opencode'];
99
+ runtimes = ['antigravity'];
98
100
  break;
99
- case '5':
100
- runtimes = ['claude', 'gemini', 'openai', 'opencode'];
101
+ case '5':
102
+ runtimes = ['claude', 'openai', 'opencode'];
101
103
  break;
102
104
  default:
103
105
  console.log(' Invalid choice. Defaulting to Claude Code.');
@@ -108,8 +110,8 @@ async function runInstall(flags) {
108
110
  // Interactive scope selection
109
111
  if (!scope) {
110
112
  console.log('\n Installation scope:\n');
111
- console.log(' 1) Global — Available in all projects (~/.claude/, ~/.gemini/, ~/.codex/, ~/.config/opencode/)');
112
- console.log(' 2) Local — This project only (./.claude/, ./.gemini/, ./.codex/, ./.opencode/)');
113
+ console.log(' 1) Global — Available in all projects (~/.claude/, ~/.codex/, ~/.config/opencode/, ~/.agents/skills/)');
114
+ console.log(' 2) Local — This project only (./.claude/, ./.codex/, ./.opencode/, ./.agents/skills/)');
113
115
  console.log('');
114
116
 
115
117
  const choice = await ask(rl, ' Select (1/2): ');
package/bin/memorize.js CHANGED
@@ -74,7 +74,12 @@ function computeStrengthAndDecay(type, cognitiveType, strengthAdjustment = 0) {
74
74
  const strength = Math.max(0, Math.min(1.0,
75
75
  typeDefaults.strength + cogAdj.strength_delta + strengthAdjustment
76
76
  ));
77
- const decay_rate = typeDefaults.decay_rate * cogAdj.decay_multiplier;
77
+ // Cap strictly below 1.0. Procedural memories are meant to decay *slowly*, but
78
+ // a multiplier that pushed decay_rate >= 1.0 would make effective strength GROW
79
+ // over time (strength * decay_rate^days) — inverted decay. 0.9999/day is
80
+ // "extremely slow" (a memory loses ~3% of its strength per year) without ever
81
+ // inverting.
82
+ const decay_rate = Math.min(0.9999, typeDefaults.decay_rate * cogAdj.decay_multiplier);
78
83
 
79
84
  return { strength: Math.round(strength * 100) / 100, decay_rate };
80
85
  }
package/bin/recall.js CHANGED
@@ -23,6 +23,7 @@ const {
23
23
  readSearchIndex,
24
24
  writeSearchIndex,
25
25
  search,
26
+ bm25Search,
26
27
  rebuildIndex,
27
28
  createSearchIndex,
28
29
  } = require('../src/tfidf');
@@ -79,7 +80,12 @@ function main() {
79
80
  } catch (_) {
80
81
  searchIndex = null;
81
82
  }
82
- if (!searchIndex) {
83
+ // Rebuild when ABSENT *or* STALE. The search index drifts out of sync with
84
+ // index.json whenever memories change outside memorize's addDocument path
85
+ // (forget, sleep/consolidate, sync pull, manual edit) — and a present-but-
86
+ // empty index silently makes every relevance score 0. Compare the doc set,
87
+ // not just presence.
88
+ if (isSearchIndexStale(searchIndex, index)) {
83
89
  searchIndex = rebuildIndex(brainDir, index);
84
90
  writeSearchIndex(brainDir, searchIndex);
85
91
  }
@@ -89,8 +95,9 @@ function main() {
89
95
  ? buildContextQuery(args)
90
96
  : args.query;
91
97
 
92
- // Compute TF-IDF relevance scores
93
- const tfidfScores = search(searchIndex, query);
98
+ // Compute relevance scores (BM25 — length-normalized, TF-saturated; better
99
+ // than raw TF-IDF cosine at surfacing long, detailed memories under noise).
100
+ const tfidfScores = bm25Search(searchIndex, query);
94
101
 
95
102
  // Build memory list from index
96
103
  const memories = Object.entries(index.memories).map(([id, entry]) => ({
@@ -141,6 +148,23 @@ function main() {
141
148
  console.log(JSON.stringify(results, null, 2));
142
149
  }
143
150
 
151
+ /**
152
+ * The TF-IDF search index is stale if it is missing, has a different document
153
+ * count than the live index, or is missing any indexed memory id. Catches the
154
+ * empty-index and add/remove/rename drift cases (in-place same-id body edits
155
+ * are not detected by count alone — acceptable until a version/mtime check).
156
+ */
157
+ function isSearchIndexStale(searchIndex, index) {
158
+ if (!searchIndex || !searchIndex.documents) return true;
159
+ const memIds = Object.keys((index && index.memories) || {});
160
+ const docCount = searchIndex.doc_count != null
161
+ ? searchIndex.doc_count
162
+ : Object.keys(searchIndex.documents).length;
163
+ if (docCount !== memIds.length) return true;
164
+ for (const id of memIds) if (!(id in searchIndex.documents)) return true;
165
+ return false;
166
+ }
167
+
144
168
  /**
145
169
  * Rebuild the search index from all memories.
146
170
  */
@@ -27,6 +27,7 @@ const {
27
27
  readSearchIndex,
28
28
  writeSearchIndex,
29
29
  search,
30
+ bm25Search,
30
31
  rebuildIndex,
31
32
  } = require('../src/tfidf');
32
33
 
@@ -136,7 +137,7 @@ function computeSessionStart(projectRoot, args = {}) {
136
137
  writeSearchIndex(brainDir, searchIndex);
137
138
  }
138
139
 
139
- const tfidfScores = search(searchIndex, buildContextQuery(args));
140
+ const tfidfScores = bm25Search(searchIndex, buildContextQuery(args));
140
141
  const memories = Object.entries(index.memories).map(([id, entry]) => ({ id, ...entry }));
141
142
 
142
143
  let associations = null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.1.0-beta.26",
3
+ "version": "0.1.0-beta.27",
4
4
  "description": "A brain-inspired hierarchical memory system for AI coding agents. Deep nested file structure that mimics human memory with time-decay and strength-based recall.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -35,6 +35,8 @@
35
35
  "templates/",
36
36
  "src/",
37
37
  "README.md",
38
+ "SECURITY.md",
39
+ "CHANGELOG.md",
38
40
  "LICENSE"
39
41
  ],
40
42
  "repository": {
@@ -4,7 +4,7 @@ This project uses the **Brain Memory** plugin — a hierarchical, file-system-ba
4
4
 
5
5
  ## Memory Location
6
6
 
7
- All memories are stored in a single global `~/.brain/` directory in the user's home folder, shared across all projects and all supported AI agents. The directory uses a deep nested structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
7
+ All memories are stored in `~/.brain/` with a deep nested directory structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
8
8
 
9
9
  ## How It Works
10
10
 
@@ -48,22 +48,22 @@ Memories store their encoding context (project, topics, task type). During recal
48
48
 
49
49
  ## Available Commands
50
50
 
51
- Commands are available via `/brain:` prefix:
51
+ Brain skills are available via `/brain-` prefix:
52
52
  The everyday loop is **ambient** — `remember` and `memorize` run automatically at session start/end; you rarely type them.
53
53
 
54
- **Core**
55
- - `/brain:remember [query]` — Recall relevant memories with spreading activation and context matching
56
- - `/brain:memorize [topic]` — Store memories from the current context
57
- - `/brain:status` — Dashboard with brain health overview
58
- - `/brain:pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
59
- - `/brain:forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
54
+ Core:
55
+ - `/brain-remember [query]` — Recall relevant memories with spreading activation and context matching
56
+ - `/brain-memorize [topic]` — Store memories from the current context
57
+ - `/brain-status` — Dashboard with brain health overview
58
+ - `/brain-pin [id|query]` — Pin a memory to the always-present tier (toggle — also unpins, e.g. `--off`)
59
+ - `/brain-forget [target]` — Decay or archive memories (`--deep` = forensic erasure of every reference)
60
60
 
61
- **Sync & skills**
62
- - `/brain:sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
63
- - `/brain:skills [list|show|add|use|remove|export]` — Manage procedural skills
61
+ Sync & skills:
62
+ - `/brain-sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
63
+ - `/brain-skills [list|show|add|use|remove|export]` — Manage procedural skills
64
64
 
65
- **Maintenance (usually automatic — runs in the background)**
66
- - `/brain:sleep [scope]` — Full maintenance cycle: replay, homeostasis, propagation, crystallization, reorganize, consolidate, prune, review reinforcement, REM dreaming, expertise detection
65
+ Maintenance (usually automatic — runs in the background):
66
+ - `/brain-sleep [scope]` — Full maintenance cycle: replay, homeostasis, propagation, crystallization, reorganize, consolidate, prune, review reinforcement, REM dreaming, expertise detection
67
67
 
68
68
  ## Session Start Behavior
69
69
 
@@ -109,13 +109,13 @@ Track these categories as they happen:
109
109
  If notable items have accumulated, append a **brief one-liner** at the end of your next natural response:
110
110
 
111
111
  ```
112
- ◉ Notable <type(s)> this session — /brain:memorize when ready
112
+ ◉ Notable <type(s)> this session — /brain-memorize when ready
113
113
  ```
114
114
 
115
115
  **Rules:**
116
116
  - **Never interrupt flow** — only append to the end of a response the user is already receiving, never send as a standalone message
117
117
  - **At most once per ~10 substantive interactions** — no spamming
118
- - **Reset the counter** after the user runs `/brain:memorize`
118
+ - **Reset the counter** after the user runs `/brain-memorize`
119
119
  - **Don't mention if nothing notable** has accumulated
120
120
  - **Be specific about types** — say "decisions and learnings" not just "notable content"
121
121
 
@@ -149,7 +149,7 @@ If the session contained meaningful content based on your ambient tracking:
149
149
 
150
150
  ```
151
151
  💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
152
- Run /brain:memorize to capture them before this context is lost.
152
+ Run /brain-memorize to capture them before this context is lost.
153
153
  ```
154
154
 
155
155
  **Rules:**
@@ -174,7 +174,7 @@ The recall engine ensures **identical scoring across all agents** — Claude, Ge
174
174
 
175
175
  Brain memories can be synced across devices in two ways:
176
176
 
177
- 1. **Git remote** — Push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain:sync setup <url>` to configure, then use `/brain:sync push` and `/brain:sync pull`.
178
- 2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain:sync export` and `/brain:sync import <path>`.
177
+ 1. **Git remote** — Push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain-sync setup <url>` to configure, then use `/brain-sync push` and `/brain-sync pull`.
178
+ 2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain-sync export` and `/brain-sync import <path>`.
179
179
 
180
180
  Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/prompts/openai.md CHANGED
@@ -4,7 +4,7 @@ This project uses the **Brain Memory** plugin — a hierarchical, file-system-ba
4
4
 
5
5
  ## Memory Location
6
6
 
7
- All memories are stored in `.brain/` with a deep nested directory structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
7
+ All memories are stored in `~/.brain/` with a deep nested directory structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
8
8
 
9
9
  ## How It Works
10
10
 
@@ -37,7 +37,7 @@ Each memory is a Markdown file with YAML frontmatter containing: `id`, `type`, `
37
37
  | observation | 0.40 | 0.950 | Casual facts or notices |
38
38
 
39
39
  ### Associative Network
40
- Memories are connected via weighted edges in `.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
40
+ Memories are connected via weighted edges in `~/.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
41
41
 
42
42
  ### Context-Dependent Recall
43
43
  Memories store their encoding context (project, topics, task type). During recall, memories encoded in a similar context to the current session are scored higher — matching how human memory works better when recall context matches encoding context.
@@ -60,7 +60,7 @@ Core:
60
60
 
61
61
  Sync & skills:
62
62
  - `/brain-sync [subcommand]` — Sync via Brain Cloud, Git remote, or export/import (auto-initializes on first run)
63
- - `/brain-skill [list|show|add|use|remove|export]` — Manage procedural skills
63
+ - `/brain-skills [list|show|add|use|remove|export]` — Manage procedural skills
64
64
 
65
65
  Maintenance (usually automatic — runs in the background):
66
66
  - `/brain-sleep [scope]` — Full maintenance cycle: replay, homeostasis, propagation, crystallization, reorganize, consolidate, prune, review reinforcement, REM dreaming, expertise detection
@@ -69,7 +69,7 @@ Maintenance (usually automatic — runs in the background):
69
69
 
70
70
  **Perform these steps at session start — but keep it lightweight.**
71
71
 
72
- If `.brain/index.json` exists:
72
+ If `~/.brain/index.json` exists:
73
73
 
74
74
  1. **Run the session-start aggregator** — one deterministic, budget-bounded call:
75
75
  ```bash
@@ -125,7 +125,7 @@ When a session is ending (user says bye/thanks/done, conversation wraps up, or y
125
125
 
126
126
  ### Step 1: Save Session Context (ALWAYS — do this first)
127
127
 
128
- **Immediately** append a session summary to `.brain/contexts.json`, even for trivial sessions. Context tracking is cheap and provides valuable recall signals for future sessions.
128
+ **Immediately** append a session summary to `~/.brain/contexts.json`, even for trivial sessions. Context tracking is cheap and provides valuable recall signals for future sessions.
129
129
 
130
130
  ```json
131
131
  {
@@ -166,7 +166,7 @@ When the user asks you to "remember" something, or when context from past sessio
166
166
  2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
167
167
  3. Read the top-scoring memory files and present results
168
168
  4. Run `brain reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
169
- 5. If no matches, search the archive (`.brain/_archived/`)
169
+ 5. If no matches, search the archive (`~/.brain/_archived/`)
170
170
 
171
171
  The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
172
172
 
@@ -174,7 +174,7 @@ The recall engine ensures **identical scoring across all agents** — Claude, Ge
174
174
 
175
175
  Brain memories can be synced across devices in two ways:
176
176
 
177
- 1. **Git remote** — Push/pull `.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain-sync setup <url>` to configure, then use `/brain-sync push` and `/brain-sync pull`.
178
- 2. **Export/Import** — Pack the entire `.brain/` into a single portable file for manual transfer. Run `/brain-sync export` and `/brain-sync import <path>`.
177
+ 1. **Git remote** — Push/pull `~/.brain/` to any private Git repository (GitHub, GitLab, Codeberg, self-hosted). Run `/brain-sync setup <url>` to configure, then use `/brain-sync push` and `/brain-sync pull`.
178
+ 2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain-sync export` and `/brain-sync import <path>`.
179
179
 
180
180
  Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/src/installer.js CHANGED
@@ -6,6 +6,17 @@ const { getBrainDir } = require('./index-manager');
6
6
 
7
7
  const PACKAGE_ROOT = path.resolve(__dirname, '..');
8
8
 
9
+ // Local-first integration targets, current as of mid-2026. The hosted MCP
10
+ // connector (Brain Cloud) is the universal path for everything else (Claude.ai,
11
+ // ChatGPT, mobile, Antigravity/Gemini-Enterprise via remote MCP); these are the
12
+ // CLIs where a native install adds the ambient zero-config loop MCP can't.
13
+ //
14
+ // `skillsGlobalDir`/`skillsLocalDir` decouple where skills land from where the
15
+ // prompt lands (Codex prompts go to ~/.codex/AGENTS.md but skills go to the
16
+ // cross-tool ~/.agents/skills/). `skillName: true` injects the `name:`
17
+ // frontmatter that Codex/Antigravity require to match the skill folder.
18
+ //
19
+ // Gemini CLI was retired 2026-06-18 (absorbed into Antigravity) and is removed.
9
20
  const RUNTIMES = {
10
21
  claude: {
11
22
  name: 'Claude Code',
@@ -16,23 +27,33 @@ const RUNTIMES = {
16
27
  promptSource: 'claude.md',
17
28
  commandStyle: 'flat',
18
29
  },
19
- gemini: {
20
- name: 'Gemini CLI',
21
- globalDir: path.join(os.homedir(), '.gemini'),
22
- localDir: '.gemini',
23
- commandsSubdir: 'commands',
24
- promptFile: 'GEMINI.md',
25
- promptSource: 'gemini.md',
26
- commandStyle: 'flat',
27
- },
28
30
  openai: {
29
31
  name: 'OpenAI Codex CLI',
30
32
  globalDir: path.join(os.homedir(), '.codex'),
31
33
  localDir: '.codex',
32
34
  commandsSubdir: 'skills',
35
+ // Codex reads skills from the cross-tool ~/.agents/skills/, NOT ~/.codex/skills/.
36
+ skillsGlobalDir: path.join(os.homedir(), '.agents', 'skills'),
37
+ skillsLocalDir: path.join('.agents', 'skills'),
33
38
  promptFile: 'AGENTS.md',
34
39
  promptSource: 'openai.md',
35
40
  commandStyle: 'skills',
41
+ skillName: true,
42
+ },
43
+ antigravity: {
44
+ name: 'Google Antigravity',
45
+ // NB: Antigravity reuses ~/.gemini/ and reads GEMINI.md globally + Markdown
46
+ // SKILL.md skills under ~/.gemini/skills/. These paths are community-sourced
47
+ // (official docs are JS SPAs) — VERIFY against a live Antigravity install.
48
+ globalDir: path.join(os.homedir(), '.gemini'),
49
+ localDir: '.',
50
+ commandsSubdir: 'skills',
51
+ skillsGlobalDir: path.join(os.homedir(), '.gemini', 'skills'),
52
+ skillsLocalDir: path.join('.agents', 'skills'),
53
+ promptFile: 'GEMINI.md',
54
+ promptSource: 'antigravity.md',
55
+ commandStyle: 'skills',
56
+ skillName: true,
36
57
  },
37
58
  opencode: {
38
59
  name: 'OpenCode',
@@ -45,6 +66,14 @@ const RUNTIMES = {
45
66
  },
46
67
  };
47
68
 
69
+ /** Where skills install for a runtime+scope (decoupled from the prompt target). */
70
+ function skillsDestFor(config, scope) {
71
+ if (scope === 'global') {
72
+ return config.skillsGlobalDir || path.join(config.globalDir, config.commandsSubdir);
73
+ }
74
+ return config.skillsLocalDir || path.join(config.localDir, config.commandsSubdir);
75
+ }
76
+
48
77
  const BRAIN_MARKER_START = '<!-- BRAIN-MEMORY-START -->';
49
78
  const BRAIN_MARKER_END = '<!-- BRAIN-MEMORY-END -->';
50
79
 
@@ -66,17 +95,32 @@ function copyDir(src, dest, _depth = 0) {
66
95
  }
67
96
  }
68
97
 
69
- function installSkills(commandsSrc, skillsDest) {
98
+ function installSkills(commandsSrc, skillsDest, addName = false) {
70
99
  const entries = fs.readdirSync(commandsSrc).filter((f) => f.endsWith('.md'));
71
100
  for (const file of entries) {
72
101
  const name = file.replace('.md', '');
73
- const skillDir = path.join(skillsDest, `brain-${name}`);
102
+ const skillFolder = `brain-${name}`;
103
+ const skillDir = path.join(skillsDest, skillFolder);
74
104
  fs.mkdirSync(skillDir, { recursive: true });
75
- fs.copyFileSync(
76
- path.join(commandsSrc, file),
77
- path.join(skillDir, 'SKILL.md')
78
- );
105
+ let content = fs.readFileSync(path.join(commandsSrc, file), 'utf-8');
106
+ if (addName) content = ensureSkillName(content, skillFolder);
107
+ fs.writeFileSync(path.join(skillDir, 'SKILL.md'), content);
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Codex and Antigravity require a `name:` frontmatter field that matches the
113
+ * skill folder. The source command files only carry `description:`, so inject
114
+ * `name:` as the first frontmatter field (idempotent — skips if already present).
115
+ */
116
+ function ensureSkillName(content, name) {
117
+ if (/^---\s*\n/.test(content)) {
118
+ const end = content.indexOf('\n---', 3);
119
+ const block = end !== -1 ? content.slice(0, end) : content;
120
+ if (/^\s*name\s*:/m.test(block)) return content;
121
+ return content.replace(/^---\s*\n/, `---\nname: ${name}\n`);
79
122
  }
123
+ return `---\nname: ${name}\n---\n\n${content}`;
80
124
  }
81
125
 
82
126
  function injectPrompt(targetDir, promptFile, promptSource) {
@@ -85,6 +129,11 @@ function injectPrompt(targetDir, promptFile, promptSource) {
85
129
  'utf-8'
86
130
  );
87
131
  const targetPath = path.join(targetDir, promptFile);
132
+ // Ensure the prompt dir exists. Previously this was created as a side-effect
133
+ // of installing commands/skills into the same dir; now that skills can land
134
+ // elsewhere (e.g. Codex skills → ~/.agents/skills), the prompt dir (~/.codex)
135
+ // must be created explicitly.
136
+ fs.mkdirSync(targetDir, { recursive: true });
88
137
 
89
138
  const wrappedContent = `\n${BRAIN_MARKER_START}\n${promptContent}\n${BRAIN_MARKER_END}\n`;
90
139
 
@@ -115,7 +164,7 @@ function detectInstallations() {
115
164
  // Check for command files/dirs
116
165
  let commandsFound = false;
117
166
  if (config.commandStyle === 'skills') {
118
- const skillsDir = path.join(targetDir, config.commandsSubdir);
167
+ const skillsDir = skillsDestFor(config, scope);
119
168
  commandsFound = fs.existsSync(skillsDir) &&
120
169
  fs.readdirSync(skillsDir).some(
121
170
  (d) => d.startsWith('brain-') &&
@@ -176,11 +225,14 @@ function removePromptSection(promptPath) {
176
225
  return { removed: true, fileDeleted: false };
177
226
  }
178
227
 
179
- function removeCommands(targetDir, config) {
228
+ function removeCommands(targetDir, config, scope = 'global') {
180
229
  const removed = [];
181
230
 
182
231
  if (config.commandStyle === 'skills') {
183
- const skillsDir = path.join(targetDir, config.commandsSubdir);
232
+ // Honor an explicit skills override; otherwise resolve relative to the
233
+ // passed targetDir (so callers that pass a custom targetDir still work).
234
+ const override = scope === 'global' ? config.skillsGlobalDir : config.skillsLocalDir;
235
+ const skillsDir = override || path.join(targetDir, config.commandsSubdir);
184
236
  if (fs.existsSync(skillsDir)) {
185
237
  const entries = fs.readdirSync(skillsDir).filter((d) => d.startsWith('brain-'));
186
238
  for (const entry of entries) {
@@ -212,7 +264,7 @@ function uninstallForRuntime(runtime, scope) {
212
264
  const promptTarget = scope === 'global' ? config.globalDir : '.';
213
265
  const promptPath = path.join(promptTarget, config.promptFile);
214
266
 
215
- const removedCommands = removeCommands(targetDir, config);
267
+ const removedCommands = removeCommands(targetDir, config, scope);
216
268
  const promptResult = removePromptSection(promptPath);
217
269
 
218
270
  return { removedCommands, promptResult };
@@ -230,7 +282,7 @@ function installForRuntime(runtime, scope) {
230
282
  const commandsSrc = path.join(PACKAGE_ROOT, 'commands', 'brain');
231
283
 
232
284
  if (config.commandStyle === 'skills') {
233
- const skillsDest = path.join(targetDir, config.commandsSubdir);
285
+ const skillsDest = skillsDestFor(config, scope);
234
286
  // Clear stale brain-* skill dirs first so renamed/removed commands don't
235
287
  // linger across upgrades (e.g. brain-skill → brain-skills).
236
288
  if (fs.existsSync(skillsDest)) {
@@ -240,7 +292,7 @@ function installForRuntime(runtime, scope) {
240
292
  }
241
293
  }
242
294
  }
243
- installSkills(commandsSrc, skillsDest);
295
+ installSkills(commandsSrc, skillsDest, config.skillName);
244
296
  } else {
245
297
  const commandsDest = path.join(targetDir, config.commandsSubdir, 'brain');
246
298
  // Wipe the brain command dir before copying so renamed/removed commands
package/src/scorer.js CHANGED
@@ -365,16 +365,21 @@ function computeSpreadingActivationBatch(scoredMemories, associations, maxDepth
365
365
  * @returns {Object[]} Scored and sorted memories (highest first)
366
366
  */
367
367
  function rankMemories(memories, relevanceFn, options = {}) {
368
+ // Guard every term against NaN (e.g. a missing/invalid last_accessed or
369
+ // strength) — a single NaN score sorts non-deterministically and can outrank
370
+ // valid results.
371
+ const fin = (x) => (Number.isFinite(x) ? x : 0);
372
+
368
373
  // First pass: compute base scores
369
374
  const scored = memories.map((mem) => {
370
- const decayedStrength = computeDecayedStrength(
375
+ const decayedStrength = fin(computeDecayedStrength(
371
376
  mem.strength,
372
377
  mem.decay_rate,
373
378
  mem.last_accessed,
374
379
  !!(mem.stable || mem.pinned) // pinned ⇒ implicitly stable (decay-exempt)
375
- );
376
- const recencyBonus = computeRecencyBonus(mem.last_accessed);
377
- const relevance = relevanceFn(mem);
380
+ ));
381
+ const recencyBonus = fin(computeRecencyBonus(mem.last_accessed));
382
+ const relevance = fin(relevanceFn(mem));
378
383
 
379
384
  return {
380
385
  ...mem,
@@ -420,12 +425,12 @@ function rankMemories(memories, relevanceFn, options = {}) {
420
425
  if (mem.context_match > 0) extras.contextMatch = mem.context_match;
421
426
  if (mem.salience != null) extras.salience = mem.salience;
422
427
 
423
- const score = computeRecallScore(
428
+ const score = fin(computeRecallScore(
424
429
  mem.relevance,
425
430
  mem.decayed_strength,
426
431
  mem.recency_bonus,
427
432
  extras
428
- );
433
+ ));
429
434
 
430
435
  return {
431
436
  ...mem,
@@ -437,7 +442,9 @@ function rankMemories(memories, relevanceFn, options = {}) {
437
442
  score: Math.round(score * 1000) / 1000,
438
443
  };
439
444
  })
440
- .sort((a, b) => b.score - a.score);
445
+ // Deterministic order: score desc, then id asc to break ties (scores are
446
+ // rounded to 3dp, which manufactures ties at scale).
447
+ .sort((a, b) => (b.score - a.score) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
441
448
  }
442
449
 
443
450
  module.exports = {
package/src/tfidf.js CHANGED
@@ -348,6 +348,74 @@ function search(searchIndex, query) {
348
348
  return scores;
349
349
  }
350
350
 
351
+ /**
352
+ * BM25 relevance scoring for a query against all indexed memories.
353
+ *
354
+ * Fixes two TF-IDF-cosine weaknesses that buried long, detailed memories under
355
+ * short distractors: BM25 SATURATES term frequency (k1) and normalizes document
356
+ * length GENTLY (b), instead of dividing TF by full length and cosine by full
357
+ * magnitude (which penalized the richer oracle memories for being longer). The
358
+ * field weighting baked into the index (title 3x, tags 2x via buildMemoryText)
359
+ * is preserved. Scores are normalized to 0..1 by the top score so they blend
360
+ * cleanly into the scorer's recall formula (which expects relevance in [0,1]).
361
+ *
362
+ * @param {Object} searchIndex - The search index
363
+ * @param {string} query - The search query
364
+ * @param {Object} [opts] - { k1 = 1.5, b = 0.75 }
365
+ * @returns {Object} Map of memoryId → normalized relevance score (0.0-1.0)
366
+ */
367
+ function bm25Search(searchIndex, query, opts = {}) {
368
+ if (!searchIndex || searchIndex.doc_count === 0) return {};
369
+
370
+ const queryTokens = tokenize(query);
371
+ if (queryTokens.length === 0) return {};
372
+
373
+ const k1 = opts.k1 != null ? opts.k1 : 1.5;
374
+ const b = opts.b != null ? opts.b : 0.75;
375
+ const N = searchIndex.doc_count;
376
+
377
+ // Average document length (for length normalization).
378
+ let totalLen = 0;
379
+ for (const d of Object.values(searchIndex.documents)) totalLen += d.length || 0;
380
+ const avgdl = N > 0 ? totalLen / N : 0;
381
+
382
+ // BM25 IDF per (deduped) query term, floored at 0 so a term present in nearly
383
+ // every document can't contribute a negative score.
384
+ const qTerms = [...new Set(queryTokens)];
385
+ const idf = {};
386
+ for (const t of qTerms) {
387
+ const df = searchIndex.df[t] || 0;
388
+ idf[t] = Math.max(0, Math.log(1 + (N - df + 0.5) / (df + 0.5)));
389
+ }
390
+
391
+ const raw = {};
392
+ let maxScore = 0;
393
+ for (const [memoryId, doc] of Object.entries(searchIndex.documents)) {
394
+ const dl = doc.length || 0;
395
+ let score = 0;
396
+ for (const t of qTerms) {
397
+ const f = doc.tf[t] || 0;
398
+ if (f === 0) continue;
399
+ const denom = f + k1 * (1 - b + b * (avgdl > 0 ? dl / avgdl : 0));
400
+ score += idf[t] * (f * (k1 + 1)) / denom;
401
+ }
402
+ if (score > 0) {
403
+ raw[memoryId] = score;
404
+ if (score > maxScore) maxScore = score;
405
+ }
406
+ }
407
+
408
+ // Normalize to 0..1 by the top score — preserves ranking and keeps the [0,1]
409
+ // contract the recall scorer's relevance blend expects.
410
+ const scores = {};
411
+ if (maxScore > 0) {
412
+ for (const [id, s] of Object.entries(raw)) {
413
+ scores[id] = Math.round((s / maxScore) * 1000) / 1000;
414
+ }
415
+ }
416
+ return scores;
417
+ }
418
+
351
419
  /**
352
420
  * Rebuild the entire search index from memory files on disk.
353
421
  *
@@ -401,6 +469,7 @@ module.exports = {
401
469
  removeDocument,
402
470
  computeIdf,
403
471
  search,
472
+ bm25Search,
404
473
  rebuildIndex,
405
474
  // Constants
406
475
  SEARCH_INDEX_FILE,