brain-memory 0.1.0-beta.13 → 0.1.0-beta.14

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/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**, and **OpenAI Codex CLI**.
15
+ Works with **Claude Code**, **Gemini CLI**, **OpenAI Codex CLI**, and **OpenCode**.
16
16
 
17
17
  ```
18
18
  ~/.brain/
@@ -51,35 +51,43 @@ Existing AI memory solutions use flat databases with tag-based retrieval. Brain
51
51
  ## Install
52
52
 
53
53
  ```bash
54
- npx brain-memory@beta
54
+ npm install -g brain-memory@beta
55
+ brain-memory
55
56
  ```
56
57
 
57
- The interactive installer asks which runtime(s) to configure (Claude Code, Gemini CLI, OpenAI Codex CLI, or all) and whether to install globally or for the current project.
58
+ The first command installs the package globally — this gives you both the interactive setup wizard and the CLI tools (`brain-memorize`, `brain-recall`, `brain-reinforce`) that agents rely on for deterministic scoring.
59
+
60
+ 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.
58
61
 
59
62
  ### Non-interactive
60
63
 
61
64
  ```bash
62
- npx brain-memory --claude --global # Claude Code, global
63
- npx brain-memory --gemini --local # Gemini CLI, local project
64
- npx brain-memory --codex --global # OpenAI Codex CLI, global
65
- npx brain-memory --all --global # All runtimes, global
65
+ brain-memory --claude --global # Claude Code, global
66
+ brain-memory --gemini --local # Gemini CLI, local project
67
+ brain-memory --codex --global # OpenAI Codex CLI, global
68
+ brain-memory --opencode --global # OpenCode, global
69
+ brain-memory --all --global # All runtimes, global
66
70
  ```
67
71
 
68
72
  ### Update
69
73
 
70
74
  ```bash
71
- npx brain-memory@beta update
75
+ npm install -g brain-memory@beta
76
+ brain-memory update
72
77
  ```
73
78
 
74
- Auto-detects installed runtimes and refreshes commands + prompt sections. Target specific runtimes with `--claude`, `--gemini`, `--openai`, or `--all`.
79
+ The first command updates the package and CLI tools. The second command refreshes the slash command prompts for your installed runtimes. Target specific runtimes with `--claude`, `--gemini`, `--openai`, or `--all`.
80
+
81
+ > **Why not `npx`?** `npx` runs the setup wizard in a temporary directory that is discarded after execution. The CLI tools (`brain-memorize`, `brain-recall`, `brain-reinforce`) won't be available in your PATH, which means agents will fall back to less reliable manual file operations. Always use `npm install -g` to ensure everything works correctly.
75
82
 
76
83
  ### Uninstall
77
84
 
78
85
  ```bash
79
- npx brain-memory@beta uninstall
86
+ brain-memory uninstall
87
+ npm uninstall -g brain-memory
80
88
  ```
81
89
 
82
- Removes commands and prompt sections. Your `~/.brain/` directory (memories) is preserved by default. Add `--delete-data` to remove it too. Use `--yes` to skip confirmation prompts.
90
+ The first command removes slash commands and prompt sections from your agent configs. The second removes the package and CLI tools. Your `~/.brain/` directory (memories) is preserved by default. Add `--delete-data` to the uninstall command to remove it too. Use `--yes` to skip confirmation prompts.
83
91
 
84
92
  ### Manual Install
85
93
 
package/bin/install.js CHANGED
@@ -51,7 +51,8 @@ function resolveRuntimesFromFlags(flags) {
51
51
  if (flags.has('claude')) runtimes.push('claude');
52
52
  if (flags.has('gemini')) runtimes.push('gemini');
53
53
  if (flags.has('openai') || flags.has('codex')) runtimes.push('openai');
54
- if (flags.has('all')) return ['claude', 'gemini', 'openai'];
54
+ if (flags.has('opencode')) runtimes.push('opencode');
55
+ if (flags.has('all')) return ['claude', 'gemini', 'openai', 'opencode'];
55
56
  return runtimes;
56
57
  }
57
58
 
@@ -73,14 +74,15 @@ async function runInstall(flags) {
73
74
  try {
74
75
  // Interactive runtime selection
75
76
  if (runtimes.length === 0) {
76
- console.log(' Which runtimes would you like to install for?\n');
77
- console.log(' 1) Claude Code');
78
- console.log(' 2) Gemini CLI');
79
- console.log(' 3) OpenAI Codex CLI');
80
- console.log(' 4) All');
77
+ console.log(' Which runtimes would you like to install for?\n');
78
+ 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
83
  console.log('');
82
84
 
83
- const choice = await ask(rl, ' Select (1/2/3/4): ');
85
+ const choice = await ask(rl, ' Select (1/2/3/4/5): ');
84
86
  switch (choice.trim()) {
85
87
  case '1':
86
88
  runtimes = ['claude'];
@@ -92,22 +94,25 @@ async function runInstall(flags) {
92
94
  runtimes = ['openai'];
93
95
  break;
94
96
  case '4':
95
- runtimes = ['claude', 'gemini', 'openai'];
97
+ runtimes = ['opencode'];
98
+ break;
99
+ case '5':
100
+ runtimes = ['claude', 'gemini', 'openai', 'opencode'];
96
101
  break;
97
102
  default:
98
- console.log(' Invalid choice. Defaulting to Claude Code.');
103
+ console.log(' Invalid choice. Defaulting to Claude Code.');
99
104
  runtimes = ['claude'];
100
105
  }
101
106
  }
102
107
 
103
108
  // Interactive scope selection
104
109
  if (!scope) {
105
- console.log('\n Installation scope:\n');
106
- console.log(' 1) Global — Available in all projects (~/.claude/, ~/.gemini/, ~/.codex/)');
107
- console.log(' 2) Local — This project only (./.claude/, ./.gemini/, ./.codex/)');
110
+ 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/)');
108
113
  console.log('');
109
114
 
110
- const choice = await ask(rl, ' Select (1/2): ');
115
+ const choice = await ask(rl, ' Select (1/2): ');
111
116
  scope = choice.trim() === '2' ? 'local' : 'global';
112
117
  }
113
118
 
@@ -187,7 +192,7 @@ async function runUpdate(flags) {
187
192
 
188
193
  if (detections.length === 0) {
189
194
  console.log(' No existing brain-memory installations found.\n');
190
- console.log(' To install, run: npx brain-memory@beta');
195
+ console.log(' To install, run: npm install -g brain-memory@beta && brain-memory');
191
196
  if (filterRuntimes.length > 0) {
192
197
  console.log(` (Searched for: ${filterRuntimes.join(', ')})`);
193
198
  }
package/bin/memorize.js CHANGED
@@ -247,9 +247,33 @@ async function main() {
247
247
  }
248
248
 
249
249
  // Read current state
250
- const index = readIndex();
251
- let associations = readAssociations() || { version: 1, edges: {} };
252
- let searchIndex = readSearchIndex(brainDir) || createSearchIndex();
250
+ let index;
251
+ try {
252
+ index = readIndex();
253
+ } catch (err) {
254
+ console.error(JSON.stringify({
255
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
256
+ }));
257
+ process.exit(1);
258
+ }
259
+
260
+ let associations;
261
+ try {
262
+ associations = readAssociations() || { version: 1, edges: {} };
263
+ } catch (err) {
264
+ console.error(JSON.stringify({
265
+ error: `Corrupt associations.json in ~/.brain/ — ${err.message}`,
266
+ }));
267
+ process.exit(1);
268
+ }
269
+
270
+ let searchIndex;
271
+ try {
272
+ searchIndex = readSearchIndex(brainDir) || createSearchIndex();
273
+ } catch (err) {
274
+ // Search index is non-critical — rebuild from scratch
275
+ searchIndex = createSearchIndex();
276
+ }
253
277
 
254
278
  const now = new Date().toISOString();
255
279
  const results = [];
package/bin/recall.js CHANGED
@@ -58,14 +58,27 @@ function main() {
58
58
  process.exit(1);
59
59
  }
60
60
 
61
- const index = readIndex();
61
+ let index;
62
+ try {
63
+ index = readIndex();
64
+ } catch (err) {
65
+ console.error(JSON.stringify({
66
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
67
+ }));
68
+ process.exit(1);
69
+ }
62
70
  if (!index || !index.memories || Object.keys(index.memories).length === 0) {
63
71
  console.log(JSON.stringify([]));
64
72
  return;
65
73
  }
66
74
 
67
75
  // Ensure search index exists
68
- let searchIndex = readSearchIndex(brainDir);
76
+ let searchIndex;
77
+ try {
78
+ searchIndex = readSearchIndex(brainDir);
79
+ } catch (_) {
80
+ searchIndex = null;
81
+ }
69
82
  if (!searchIndex) {
70
83
  searchIndex = rebuildIndex(brainDir, index);
71
84
  writeSearchIndex(brainDir, searchIndex);
@@ -86,7 +99,12 @@ function main() {
86
99
  }));
87
100
 
88
101
  // Load associations for spreading activation
89
- const associations = readAssociations();
102
+ let associations;
103
+ try {
104
+ associations = readAssociations();
105
+ } catch (_) {
106
+ associations = null;
107
+ }
90
108
 
91
109
  // Build recall context
92
110
  const recallContext = {};
@@ -127,7 +145,15 @@ function main() {
127
145
  * Rebuild the search index from all memories.
128
146
  */
129
147
  function handleReindex(brainDir) {
130
- const index = readIndex();
148
+ let index;
149
+ try {
150
+ index = readIndex();
151
+ } catch (err) {
152
+ console.error(JSON.stringify({
153
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
154
+ }));
155
+ process.exit(1);
156
+ }
131
157
  if (!index) {
132
158
  console.error(JSON.stringify({ error: 'No index.json found.' }));
133
159
  process.exit(1);
package/bin/reinforce.js CHANGED
@@ -46,7 +46,15 @@ function main() {
46
46
  }
47
47
 
48
48
  const brainDir = getBrainDir();
49
- const index = readIndex();
49
+ let index;
50
+ try {
51
+ index = readIndex();
52
+ } catch (err) {
53
+ console.error(JSON.stringify({
54
+ error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
55
+ }));
56
+ process.exit(1);
57
+ }
50
58
 
51
59
  if (!index) {
52
60
  console.error(JSON.stringify({ error: 'Brain not initialized.' }));
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.1.0-beta.13",
3
+ "version": "0.1.0-beta.14",
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",
7
7
  "gemini-cli",
8
8
  "openai-codex",
9
+ "opencode",
9
10
  "memory",
10
11
  "ai-agent",
11
12
  "context-engineering",
@@ -0,0 +1,176 @@
1
+ # Brain Memory System
2
+
3
+ This project uses the **Brain Memory** plugin — a hierarchical, file-system-based memory system that mimics human cognition with neuroscience-inspired mechanisms including associative networks, spreading activation, context-dependent recall, spaced reinforcement, and cognitive memory types.
4
+
5
+ ## Memory Location
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.
8
+
9
+ ## How It Works
10
+
11
+ ### Memory Format
12
+ Each memory is a Markdown file with YAML frontmatter containing: `id`, `type`, `cognitive_type` (episodic/semantic/procedural), `created`, `last_accessed`, `access_count`, `recall_history`, `strength` (0.0-1.0), `decay_rate` (per day), `salience` (0.0-1.0), `confidence` (0.0-1.0), `tags`, `related` memory IDs, `source`, and `encoding_context`.
13
+
14
+ ### Strength & Decay Model
15
+ - Memories have a base `strength` set at creation based on their impact/type/cognitive type
16
+ - Strength decays over time: `effective = strength * (decay_rate ^ days_since_access)`
17
+ - Recalled memories get **stronger** via spaced reinforcement — the longer since last recall, the bigger the boost
18
+ - Memories become progressively more forgetting-resistant with each recall (decay_rate improves)
19
+ - Weak memories can be consolidated into stronger combined memories
20
+ - During sleep, global synaptic homeostasis prevents strength inflation
21
+
22
+ ### Cognitive Types
23
+ - **Episodic** — Event-specific memories. Higher initial strength, faster decay. The details fade but lessons persist.
24
+ - **Semantic** — Abstracted knowledge. Default decay. Stable long-term storage.
25
+ - **Procedural** — Skills and workflows. Lower initial strength but extremely slow decay once established.
26
+
27
+ ### Memory Types & Default Strengths
28
+ | Type | Strength | Decay/day | Description |
29
+ |------|----------|-----------|-------------|
30
+ | decision | 0.85 | 0.995 | Choices made and rationale |
31
+ | insight | 0.90 | 0.997 | Deep realizations, patterns |
32
+ | goal | 0.80 | 0.993 | Objectives and aspirations |
33
+ | experience | 0.75 | 0.985 | Notable events or processes |
34
+ | learning | 0.70 | 0.990 | New knowledge acquired |
35
+ | relationship | 0.70 | 0.997 | Connections between entities |
36
+ | preference | 0.60 | 0.998 | User preferences and style |
37
+ | observation | 0.40 | 0.950 | Casual facts or notices |
38
+
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.
41
+
42
+ ### Context-Dependent Recall
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.
44
+
45
+ ### Salience & Confidence
46
+ - **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
47
+ - **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
48
+
49
+ ## Available Commands
50
+
51
+ - `/brain:init` — Initialize the brain structure
52
+ - `/brain:memorize [topic]` — Store memories from current context
53
+ - `/brain:remember [query]` — Recall relevant memories with spreading activation and context matching
54
+ - `/brain:review [scope]` — Spaced repetition review session for due memories
55
+ - `/brain:explore [category]` — Browse the brain hierarchy
56
+ - `/brain:consolidate [scope]` — Merge related weak memories into stronger ones
57
+ - `/brain:forget [target]` — Decay or archive memories
58
+ - `/brain:sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
59
+ - `/brain:sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
60
+ - `/brain:status` — Dashboard with brain health overview
61
+ - `/brain:sync [subcommand]` — Sync memories via Git remote or export/import for portability
62
+
63
+ ## Session Start Behavior
64
+
65
+ **Perform these steps at session start — but keep it lightweight.**
66
+
67
+ If `~/.brain/index.json` exists:
68
+
69
+ 1. **Read the index** to get memory count and categories
70
+ 2. **Run the recall engine only if the current project has relevant memories:**
71
+ ```bash
72
+ brain-recall --context --project "<current project>" --top 5
73
+ ```
74
+ If the project is unrelated to any stored memories (e.g., a new project with no matching context), skip the recall and just show the count. Don't waste cycles searching when nothing will match.
75
+ 3. **Silently internalize** results — do NOT dump memory contents
76
+ 4. **Output a single status line:**
77
+
78
+ ```
79
+ 🧠 Brain active — <N> memories (<M> in project context)
80
+ ```
81
+
82
+ Only add extra lines if actionable:
83
+ - `📋 <X> due for review` — if review queue has items
84
+ - `⚠️ <N> low-confidence memories used frequently` — if access_count ≥ 3 and confidence < 0.5
85
+
86
+ **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. Reference them naturally when relevant.
87
+
88
+ ## Ambient Session Tracking
89
+
90
+ **Throughout the session, maintain a running mental log of notable events.** This requires no file writes — just internal awareness.
91
+
92
+ Track these categories as they happen:
93
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
94
+ - **Learnings** — New patterns, debugging insights, API discoveries
95
+ - **Insights** — Realizations about the codebase, project, or process
96
+ - **Experiences** — Significant events like incidents, deployments, milestones
97
+ - **Goals** — New objectives discussed or planned
98
+
99
+ **Why this matters:** Without active tracking, you can only evaluate what happened at session end — by which point early-session events may be forgotten or the user may have already left. By tracking as events occur, nothing is lost.
100
+
101
+ ## Periodic Memory Checkpoint
102
+
103
+ **Every ~10 substantive interactions** (file edits, architecture decisions, debugging breakthroughs, significant discussions — not trivial reads or simple answers), silently evaluate whether your ambient tracking log contains memorizable content.
104
+
105
+ If notable items have accumulated, append a **brief one-liner** at the end of your next natural response:
106
+
107
+ ```
108
+ 🧠 Notable <type(s)> this session — /brain:memorize when ready
109
+ ```
110
+
111
+ **Rules:**
112
+ - **Never interrupt flow** — only append to the end of a response the user is already receiving, never send as a standalone message
113
+ - **At most once per ~10 substantive interactions** — no spamming
114
+ - **Reset the counter** after the user runs `/brain:memorize`
115
+ - **Don't mention if nothing notable** has accumulated
116
+ - **Be specific about types** — say "decisions and learnings" not just "notable content"
117
+
118
+ ## Session End Behavior
119
+
120
+ When a session is ending (user says bye/thanks/done, conversation wraps up, or you sense the interaction is concluding), perform these steps **in order**:
121
+
122
+ ### Step 1: Save Session Context (ALWAYS — do this first)
123
+
124
+ **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.
125
+
126
+ ```json
127
+ {
128
+ "session_id": "<timestamp-based-id>",
129
+ "started": "<session start ISO timestamp>",
130
+ "ended": "<session end ISO timestamp>",
131
+ "project": "<current project name>",
132
+ "topics": ["<key topics discussed>"],
133
+ "task_type": "<primary task type>",
134
+ "memories_created": ["<IDs of memories stored this session>"],
135
+ "memories_recalled": ["<IDs of memories retrieved this session>"],
136
+ "notable_unsaved": ["<brief descriptions of notable items NOT yet memorized>"]
137
+ }
138
+ ```
139
+
140
+ Keep only the last 20 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — future sessions can reference it.
141
+
142
+ ### Step 2: Suggest Memorization (if warranted)
143
+
144
+ If the session contained meaningful content based on your ambient tracking:
145
+
146
+ ```
147
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
148
+ Run /brain:memorize to capture them before this context is lost.
149
+ ```
150
+
151
+ **Rules:**
152
+ - Do NOT auto-memorize without user consent
153
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
154
+ - Only suggest when there is genuinely valuable context worth preserving
155
+ - **Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively
156
+
157
+ ## When Recalling Memories
158
+
159
+ When the user asks you to "remember" something, or when context from past sessions would be helpful, use the **deterministic recall engine** instead of manually computing scores:
160
+
161
+ 1. Run `brain-recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
162
+ 2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
163
+ 3. Read the top-scoring memory files and present results
164
+ 4. Run `brain-reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
165
+ 5. If no matches, search the archive (`~/.brain/_archived/`)
166
+
167
+ The recall engine ensures **identical scoring across all agents** — Claude, Gemini, Codex, and OpenCode all get the same rankings for the same query.
168
+
169
+ ## Portable Sync
170
+
171
+ Brain memories can be synced across devices in two ways:
172
+
173
+ 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`.
174
+ 2. **Export/Import** — Pack the entire `~/.brain/` into a single portable file for manual transfer. Run `/brain:sync export` and `/brain:sync import <path>`.
175
+
176
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
package/src/installer.js CHANGED
@@ -32,6 +32,15 @@ const RUNTIMES = {
32
32
  promptSource: 'openai.md',
33
33
  commandStyle: 'skills',
34
34
  },
35
+ opencode: {
36
+ name: 'OpenCode',
37
+ globalDir: path.join(os.homedir(), '.config', 'opencode'),
38
+ localDir: '.opencode',
39
+ commandsSubdir: 'commands',
40
+ promptFile: 'AGENTS.md',
41
+ promptSource: 'opencode.md',
42
+ commandStyle: 'flat',
43
+ },
35
44
  };
36
45
 
37
46
  const BRAIN_MARKER_START = '<!-- BRAIN-MEMORY-START -->';