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

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/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,8 +23,10 @@ const {
23
23
  readSearchIndex,
24
24
  writeSearchIndex,
25
25
  search,
26
+ bm25Search,
26
27
  rebuildIndex,
27
28
  createSearchIndex,
29
+ isSearchIndexStale,
28
30
  } = require('../src/tfidf');
29
31
 
30
32
  const {
@@ -79,7 +81,12 @@ function main() {
79
81
  } catch (_) {
80
82
  searchIndex = null;
81
83
  }
82
- if (!searchIndex) {
84
+ // Rebuild when ABSENT *or* STALE. The search index drifts out of sync with
85
+ // index.json whenever memories change outside memorize's addDocument path
86
+ // (forget, sleep/consolidate, sync pull, manual edit) — and a present-but-
87
+ // empty index silently makes every relevance score 0. Compare the doc set,
88
+ // not just presence.
89
+ if (isSearchIndexStale(searchIndex, index)) {
83
90
  searchIndex = rebuildIndex(brainDir, index);
84
91
  writeSearchIndex(brainDir, searchIndex);
85
92
  }
@@ -89,8 +96,9 @@ function main() {
89
96
  ? buildContextQuery(args)
90
97
  : args.query;
91
98
 
92
- // Compute TF-IDF relevance scores
93
- const tfidfScores = search(searchIndex, query);
99
+ // Compute relevance scores (BM25 — length-normalized, TF-saturated; better
100
+ // than raw TF-IDF cosine at surfacing long, detailed memories under noise).
101
+ const tfidfScores = bm25Search(searchIndex, query);
94
102
 
95
103
  // Build memory list from index
96
104
  const memories = Object.entries(index.memories).map(([id, entry]) => ({
@@ -141,6 +149,12 @@ function main() {
141
149
  console.log(JSON.stringify(results, null, 2));
142
150
  }
143
151
 
152
+ /**
153
+ * The TF-IDF search index is stale if it is missing, has a different document
154
+ * count than the live index, or is missing any indexed memory id. Catches the
155
+ * empty-index and add/remove/rename drift cases (in-place same-id body edits
156
+ * are not detected by count alone — acceptable until a version/mtime check).
157
+ */
144
158
  /**
145
159
  * Rebuild the search index from all memories.
146
160
  */
@@ -27,7 +27,9 @@ const {
27
27
  readSearchIndex,
28
28
  writeSearchIndex,
29
29
  search,
30
+ bm25Search,
30
31
  rebuildIndex,
32
+ isSearchIndexStale,
31
33
  } = require('../src/tfidf');
32
34
 
33
35
  const {
@@ -129,14 +131,18 @@ function computeSessionStart(projectRoot, args = {}) {
129
131
  const memoryCount = Object.keys(index.memories).length;
130
132
 
131
133
  // --- Context recall (deterministic, reuses the recall engine) ---
134
+ // Rebuild when ABSENT *or* STALE — session-start is the first thing a session
135
+ // runs (e.g. right after a `sync pull`), so it is the most likely path to hit
136
+ // a search index that has drifted out of sync with index.json. A present-but-
137
+ // stale index silently zeroes every relevance score (matches recall.js).
132
138
  let searchIndex = null;
133
139
  try { searchIndex = readSearchIndex(brainDir); } catch (_) { searchIndex = null; }
134
- if (!searchIndex) {
140
+ if (isSearchIndexStale(searchIndex, index)) {
135
141
  searchIndex = rebuildIndex(brainDir, index);
136
142
  writeSearchIndex(brainDir, searchIndex);
137
143
  }
138
144
 
139
- const tfidfScores = search(searchIndex, buildContextQuery(args));
145
+ const tfidfScores = bm25Search(searchIndex, buildContextQuery(args));
140
146
  const memories = Object.entries(index.memories).map(([id, entry]) => ({ id, ...entry }));
141
147
 
142
148
  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.29",
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