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

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.
@@ -42,7 +42,7 @@ If no subcommand is given, show available subcommands.
42
42
  - If already connected, show current user and ask if they want to re-authenticate.
43
43
 
44
44
  2. **Start device code flow:**
45
- - Run `brain-cloud login` (or call `login()` from `src/cloud-sync.js`).
45
+ - Run `brain cloud login` (or call `login()` from `src/cloud-sync.js`).
46
46
  - This calls `POST /auth/device/request` and returns a user code + verification URL.
47
47
 
48
48
  3. **Display instructions to user:**
@@ -74,9 +74,9 @@ If no subcommand is given, show available subcommands.
74
74
 
75
75
  ### Prerequisites
76
76
 
77
- Check that `brain-cloud` CLI is available. If not:
77
+ Check that the `brain` CLI is available (run `brain --version`). If not:
78
78
  ```
79
- brain-cloud is not installed. Install it with:
79
+ brain CLI is not installed. Install it with:
80
80
  npm install -g brain-memory
81
81
  ```
82
82
  Then return — do not attempt the push.
@@ -86,7 +86,7 @@ Then return — do not attempt the push.
86
86
  1. **Check logged in.** If not, suggest `cloud login`.
87
87
 
88
88
  2. **Execute push immediately** — no confirmation needed:
89
- - Run `brain-cloud push`.
89
+ - Run `brain cloud push`.
90
90
  - Show result:
91
91
  ```
92
92
  ✓ Push complete!
@@ -113,7 +113,7 @@ Then return — do not attempt the push.
113
113
  3. **Ask for confirmation.**
114
114
 
115
115
  4. **Execute pull:**
116
- - Run `brain-cloud pull` (or call `pull()` from `src/cloud-sync.js`).
116
+ - Run `brain cloud pull` (or call `pull()` from `src/cloud-sync.js`).
117
117
  - Downloads tar.gz from `GET /api/brains/{id}/sync` and extracts to `~/.brain/`.
118
118
  - Show result:
119
119
  ```
@@ -344,7 +344,7 @@ Then return — do not attempt the push.
344
344
  ## Key Implementation Notes
345
345
 
346
346
  - **Cloud sync engine**: `src/cloud-sync.js` — API client for Brain Cloud
347
- - **Cloud CLI**: `bin/cloud-sync.js` — installed as `brain-cloud` command
347
+ - **Cloud CLI**: `bin/cloud-sync.js` — installed as `brain cloud` command
348
348
  - **Cloud config**: stored in `~/.brain/.cloud/config.json` (tokens, brain ID, API URL)
349
349
  - **Cloud protocol**: tar.gz archives uploaded/downloaded via REST API
350
350
  - Git sync engine: `src/git-sync.js`
@@ -0,0 +1,21 @@
1
+ # /brain:unpin — Remove a Memory from the Always-Present Tier
2
+
3
+ You are unpinning a memory. It will no longer load automatically at session start and returns to normal recall + decay (an independent `stable` flag, if set, is left untouched).
4
+
5
+ **User input:** $ARGUMENTS
6
+
7
+ ## Behavior
8
+
9
+ 1. **Resolve the target:**
10
+ - If `$ARGUMENTS` is a memory ID (`mem_...`), use it directly.
11
+ - Otherwise inspect `~/.brain/pinned.json` (the list of current pins) or run `brain recall "$ARGUMENTS" --top 5`, and confirm which pin to remove.
12
+
13
+ 2. **Unpin it:**
14
+ ```bash
15
+ brain unpin <id>
16
+ ```
17
+
18
+ 3. Confirm:
19
+ ```
20
+ 📌 Unpinned <title> — no longer auto-loaded.
21
+ ```
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.15",
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",
@@ -24,11 +25,7 @@
24
25
  "url": "https://github.com/onurkarali/brain/issues"
25
26
  },
26
27
  "bin": {
27
- "brain-memory": "bin/install.js",
28
- "brain-recall": "bin/recall.js",
29
- "brain-reinforce": "bin/reinforce.js",
30
- "brain-cloud": "bin/cloud-sync.js",
31
- "brain-memorize": "bin/memorize.js"
28
+ "brain": "bin/brain.js"
32
29
  },
33
30
  "files": [
34
31
  "assets/",
@@ -45,7 +42,7 @@
45
42
  "url": "git+https://github.com/onurkarali/brain.git"
46
43
  },
47
44
  "scripts": {
48
- "test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/recall.test.js test/functional.test.js test/sunshine.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js",
45
+ "test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/recall.test.js test/functional.test.js test/sunshine.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js test/session-start.test.js test/pinning.test.js test/skills.test.js test/contradiction.test.js",
49
46
  "prerelease": "npm test",
50
47
  "release:beta": "npm version prerelease --preid beta && npm publish --tag beta && npm dist-tag add brain-memory@$(node -p \"require('./package.json').version\") latest",
51
48
  "release:patch": "npm version patch && npm publish",
package/prompts/claude.md CHANGED
@@ -59,6 +59,9 @@ Memories store their encoding context (project, topics, task type). During recal
59
59
  - `/brain:sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
60
60
  - `/brain:status` — Dashboard with brain health overview
61
61
  - `/brain:sync [subcommand]` — Sync memories via Git remote or export/import for portability
62
+ - `/brain:pin [id|query]` — Pin a memory to the always-present tier (CoALA Phase 1)
63
+ - `/brain:unpin [id|query]` — Remove a memory from the always-present tier
64
+ - `/brain:skill [list|show|add|use|remove|export]` — Manage procedural skills (CoALA Phase 2)
62
65
 
63
66
  ## Session Start Behavior
64
67
 
@@ -66,24 +69,23 @@ Memories store their encoding context (project, topics, task type). During recal
66
69
 
67
70
  If `~/.brain/index.json` exists:
68
71
 
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:**
72
+ 1. **Run the session-start aggregator** — one deterministic, budget-bounded call:
71
73
  ```bash
72
- brain-recall --context --project "<current project>" --top 5
74
+ brain session-start --project "<current project>"
73
75
  ```
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:**
76
+ It returns JSON with `memory_count`, `pinned` (always-apply conventions/preferences), `skills_index` (available procedural skills — name + description only), `context_recall` (memories relevant to this project), `due_for_review`, `low_confidence_alerts`, and `budget`. If `~/.brain/index.json` is absent it returns an empty payload.
77
+ 2. **Silently internalize** the payload — treat `pinned` facts as active constraints, note which `skills_index` skills exist (load a skill's full `SKILL.md` only when a task matches it), and keep `context_recall` in mind. Do **NOT** dump contents.
78
+ 3. **Output a single status line:**
77
79
 
78
80
  ```
79
81
  🧠 Brain active — <N> memories (<M> in project context)
80
82
  ```
81
83
 
82
84
  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
+ - `📋 <X> due for review` — if `due_for_review > 0`
86
+ - `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
85
87
 
86
- **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. Reference them naturally when relevant.
88
+ The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
87
89
 
88
90
  ## Ambient Session Tracking
89
91
 
@@ -158,10 +160,10 @@ If the session contained meaningful content based on your ambient tracking:
158
160
 
159
161
  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
162
 
161
- 1. Run `brain-recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
163
+ 1. Run `brain recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
162
164
  2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
163
165
  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
166
+ 4. Run `brain reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
165
167
  5. If no matches, search the archive (`~/.brain/_archived/`)
166
168
 
167
169
  The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
package/prompts/gemini.md CHANGED
@@ -60,6 +60,9 @@ Commands are available via `/brain:` prefix:
60
60
  - `/brain:sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
61
61
  - `/brain:status` — Dashboard with brain health overview
62
62
  - `/brain:sync [subcommand]` — Sync memories via Git remote or export/import for portability
63
+ - `/brain:pin [id|query]` — Pin a memory to the always-present tier (CoALA Phase 1)
64
+ - `/brain:unpin [id|query]` — Remove a memory from the always-present tier
65
+ - `/brain:skill [list|show|add|use|remove|export]` — Manage procedural skills (CoALA Phase 2)
63
66
 
64
67
  ## Session Start Behavior
65
68
 
@@ -67,24 +70,23 @@ Commands are available via `/brain:` prefix:
67
70
 
68
71
  If `~/.brain/index.json` exists:
69
72
 
70
- 1. **Read the index** to get memory count and categories
71
- 2. **Run the recall engine only if the current project has relevant memories:**
73
+ 1. **Run the session-start aggregator** — one deterministic, budget-bounded call:
72
74
  ```bash
73
- brain-recall --context --project "<current project>" --top 5
75
+ brain session-start --project "<current project>"
74
76
  ```
75
- 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.
76
- 3. **Silently internalize** results — do NOT dump memory contents
77
- 4. **Output a single status line:**
77
+ It returns JSON with `memory_count`, `pinned` (always-apply conventions/preferences), `skills_index` (available procedural skills — name + description only), `context_recall` (memories relevant to this project), `due_for_review`, `low_confidence_alerts`, and `budget`. If `~/.brain/index.json` is absent it returns an empty payload.
78
+ 2. **Silently internalize** the payload — treat `pinned` facts as active constraints, note which `skills_index` skills exist (load a skill's full `SKILL.md` only when a task matches it), and keep `context_recall` in mind. Do **NOT** dump contents.
79
+ 3. **Output a single status line:**
78
80
 
79
81
  ```
80
82
  🧠 Brain active — <N> memories (<M> in project context)
81
83
  ```
82
84
 
83
85
  Only add extra lines if actionable:
84
- - `📋 <X> due for review` — if review queue has items
85
- - `⚠️ <N> low-confidence memories used frequently` — if access_count ≥ 3 and confidence < 0.5
86
+ - `📋 <X> due for review` — if `due_for_review > 0`
87
+ - `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
86
88
 
87
- **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. Reference them naturally when relevant.
89
+ The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
88
90
 
89
91
  ## Ambient Session Tracking
90
92
 
@@ -159,10 +161,10 @@ If the session contained meaningful content based on your ambient tracking:
159
161
 
160
162
  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:
161
163
 
162
- 1. Run `brain-recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
164
+ 1. Run `brain recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
163
165
  2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
164
166
  3. Read the top-scoring memory files and present results
165
- 4. Run `brain-reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
167
+ 4. Run `brain reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
166
168
  5. If no matches, search the archive (`~/.brain/_archived/`)
167
169
 
168
170
  The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
package/prompts/openai.md CHANGED
@@ -60,6 +60,9 @@ Brain skills are available via `/brain-` prefix:
60
60
  - `/brain-sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
61
61
  - `/brain-status` — Dashboard with brain health overview
62
62
  - `/brain-sync [subcommand]` — Sync memories via Git remote or export/import for portability
63
+ - `/brain-pin [id|query]` — Pin a memory to the always-present tier (CoALA Phase 1)
64
+ - `/brain-unpin [id|query]` — Remove a memory from the always-present tier
65
+ - `/brain-skill [list|show|add|use|remove|export]` — Manage procedural skills (CoALA Phase 2)
63
66
 
64
67
  ## Session Start Behavior
65
68
 
@@ -67,24 +70,23 @@ Brain skills are available via `/brain-` prefix:
67
70
 
68
71
  If `.brain/index.json` exists:
69
72
 
70
- 1. **Read the index** to get memory count and categories
71
- 2. **Run the recall engine only if the current project has relevant memories:**
73
+ 1. **Run the session-start aggregator** — one deterministic, budget-bounded call:
72
74
  ```bash
73
- brain-recall --context --project "<current project>" --top 5
75
+ brain session-start --project "<current project>"
74
76
  ```
75
- 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.
76
- 3. **Silently internalize** results — do NOT dump memory contents
77
- 4. **Output a single status line:**
77
+ It returns JSON with `memory_count`, `pinned` (always-apply conventions/preferences), `skills_index` (available procedural skills — name + description only), `context_recall` (memories relevant to this project), `due_for_review`, `low_confidence_alerts`, and `budget`. If `~/.brain/index.json` is absent it returns an empty payload.
78
+ 2. **Silently internalize** the payload — treat `pinned` facts as active constraints, note which `skills_index` skills exist (load a skill's full `SKILL.md` only when a task matches it), and keep `context_recall` in mind. Do **NOT** dump contents.
79
+ 3. **Output a single status line:**
78
80
 
79
81
  ```
80
82
  🧠 Brain active — <N> memories (<M> in project context)
81
83
  ```
82
84
 
83
85
  Only add extra lines if actionable:
84
- - `📋 <X> due for review` — if review queue has items
85
- - `⚠️ <N> low-confidence memories used frequently` — if access_count ≥ 3 and confidence < 0.5
86
+ - `📋 <X> due for review` — if `due_for_review > 0`
87
+ - `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
86
88
 
87
- **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them. Reference them naturally when relevant.
89
+ The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
88
90
 
89
91
  ## Ambient Session Tracking
90
92
 
@@ -159,10 +161,10 @@ If the session contained meaningful content based on your ambient tracking:
159
161
 
160
162
  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:
161
163
 
162
- 1. Run `brain-recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
164
+ 1. Run `brain recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
163
165
  2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
164
166
  3. Read the top-scoring memory files and present results
165
- 4. Run `brain-reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
167
+ 4. Run `brain reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
166
168
  5. If no matches, search the archive (`.brain/_archived/`)
167
169
 
168
170
  The recall engine ensures **identical scoring across all agents** — Claude, Gemini, and Codex all get the same rankings for the same query.
@@ -0,0 +1,178 @@
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
+ - `/brain:pin [id|query]` — Pin a memory to the always-present tier (CoALA Phase 1)
63
+ - `/brain:unpin [id|query]` — Remove a memory from the always-present tier
64
+ - `/brain:skill [list|show|add|use|remove|export]` — Manage procedural skills (CoALA Phase 2)
65
+
66
+ ## Session Start Behavior
67
+
68
+ **Perform these steps at session start — but keep it lightweight.**
69
+
70
+ If `~/.brain/index.json` exists:
71
+
72
+ 1. **Run the session-start aggregator** — one deterministic, budget-bounded call:
73
+ ```bash
74
+ brain session-start --project "<current project>"
75
+ ```
76
+ It returns JSON with `memory_count`, `pinned` (always-apply conventions/preferences), `skills_index` (available procedural skills — name + description only), `context_recall` (memories relevant to this project), `due_for_review`, `low_confidence_alerts`, and `budget`. If `~/.brain/index.json` is absent it returns an empty payload.
77
+ 2. **Silently internalize** the payload — treat `pinned` facts as active constraints, note which `skills_index` skills exist (load a skill's full `SKILL.md` only when a task matches it), and keep `context_recall` in mind. Do **NOT** dump contents.
78
+ 3. **Output a single status line:**
79
+
80
+ ```
81
+ 🧠 Brain active — <N> memories (<M> in project context)
82
+ ```
83
+
84
+ Only add extra lines if actionable:
85
+ - `📋 <X> due for review` — if `due_for_review > 0`
86
+ - `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
87
+
88
+ The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
89
+
90
+ ## Ambient Session Tracking
91
+
92
+ **Throughout the session, maintain a running mental log of notable events.** This requires no file writes — just internal awareness.
93
+
94
+ Track these categories as they happen:
95
+ - **Decisions** — Architecture choices, technology selections, trade-off resolutions
96
+ - **Learnings** — New patterns, debugging insights, API discoveries
97
+ - **Insights** — Realizations about the codebase, project, or process
98
+ - **Experiences** — Significant events like incidents, deployments, milestones
99
+ - **Goals** — New objectives discussed or planned
100
+
101
+ **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.
102
+
103
+ ## Periodic Memory Checkpoint
104
+
105
+ **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.
106
+
107
+ If notable items have accumulated, append a **brief one-liner** at the end of your next natural response:
108
+
109
+ ```
110
+ 🧠 Notable <type(s)> this session — /brain:memorize when ready
111
+ ```
112
+
113
+ **Rules:**
114
+ - **Never interrupt flow** — only append to the end of a response the user is already receiving, never send as a standalone message
115
+ - **At most once per ~10 substantive interactions** — no spamming
116
+ - **Reset the counter** after the user runs `/brain:memorize`
117
+ - **Don't mention if nothing notable** has accumulated
118
+ - **Be specific about types** — say "decisions and learnings" not just "notable content"
119
+
120
+ ## Session End Behavior
121
+
122
+ 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**:
123
+
124
+ ### Step 1: Save Session Context (ALWAYS — do this first)
125
+
126
+ **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.
127
+
128
+ ```json
129
+ {
130
+ "session_id": "<timestamp-based-id>",
131
+ "started": "<session start ISO timestamp>",
132
+ "ended": "<session end ISO timestamp>",
133
+ "project": "<current project name>",
134
+ "topics": ["<key topics discussed>"],
135
+ "task_type": "<primary task type>",
136
+ "memories_created": ["<IDs of memories stored this session>"],
137
+ "memories_recalled": ["<IDs of memories retrieved this session>"],
138
+ "notable_unsaved": ["<brief descriptions of notable items NOT yet memorized>"]
139
+ }
140
+ ```
141
+
142
+ 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.
143
+
144
+ ### Step 2: Suggest Memorization (if warranted)
145
+
146
+ If the session contained meaningful content based on your ambient tracking:
147
+
148
+ ```
149
+ 💡 This session contained notable <type(s)>. Would you like to store them as brain memories?
150
+ Run /brain:memorize to capture them before this context is lost.
151
+ ```
152
+
153
+ **Rules:**
154
+ - Do NOT auto-memorize without user consent
155
+ - Do NOT prompt for trivial sessions (quick fixes, typo corrections, simple questions)
156
+ - Only suggest when there is genuinely valuable context worth preserving
157
+ - **Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively
158
+
159
+ ## When Recalling Memories
160
+
161
+ 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:
162
+
163
+ 1. Run `brain recall "<query>" --project <project> --task <task_type> --top 10` (or `node <install-path>/bin/recall.js`)
164
+ 2. The engine computes TF-IDF relevance, decayed strength, spreading activation, context match, and salience — all deterministically
165
+ 3. Read the top-scoring memory files and present results
166
+ 4. Run `brain reinforce <mem_id1> <mem_id2> ...` to apply spaced reinforcement and Hebbian co-retrieval strengthening
167
+ 5. If no matches, search the archive (`~/.brain/_archived/`)
168
+
169
+ The recall engine ensures **identical scoring across all agents** — Claude, Gemini, Codex, and OpenCode all get the same rankings for the same query.
170
+
171
+ ## Portable Sync
172
+
173
+ Brain memories can be synced across devices in two ways:
174
+
175
+ 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`.
176
+ 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
+
178
+ Both methods support optional AES-256-GCM encryption. Sync is always manual — never automatic.
@@ -17,6 +17,19 @@ const CONTEXTS_FILE = 'contexts.json';
17
17
  const REVIEW_QUEUE_FILE = 'review-queue.json';
18
18
  const ARCHIVE_INDEX_FILE = '_archived/index.json';
19
19
  const SEARCH_INDEX_FILE = 'search-index.json';
20
+ const CONFIG_FILE = 'config.json';
21
+ const PINNED_FILE = 'pinned.json';
22
+ const SKILLS_INDEX_FILE = 'skills-index.json';
23
+
24
+ // CoALA Phase 0 — working-memory budget (token estimates, chars/4 heuristic).
25
+ // All values are conservative caps; the session-start aggregator never exceeds
26
+ // working_memory_budget_tokens and reports overflow rather than dropping silently.
27
+ const DEFAULT_CONFIG = {
28
+ working_memory_budget_tokens: 3000,
29
+ pin_budget_tokens: 1500,
30
+ skills_index_budget_tokens: 800,
31
+ recall_budget_tokens: 700,
32
+ };
20
33
 
21
34
  /**
22
35
  * Write data to a file atomically by writing to a temp file first,
@@ -440,8 +453,106 @@ function writeSearchIndex(searchIndex, projectRoot) {
440
453
  atomicWriteSync(filePath, JSON.stringify(searchIndex, null, 2) + '\n');
441
454
  }
442
455
 
456
+ // --- Config (CoALA Phase 0: working-memory budget) ---
457
+
458
+ /**
459
+ * Read the brain config, merged over safe defaults. Created lazily — a missing
460
+ * or unreadable config falls back to DEFAULT_CONFIG so session-start is robust.
461
+ *
462
+ * @param {string} [projectRoot] - Project root directory
463
+ * @returns {Object} Config with all budget keys guaranteed present
464
+ */
465
+ function readConfig(projectRoot) {
466
+ const filePath = path.join(getBrainDir(projectRoot), CONFIG_FILE);
467
+ let onDisk = {};
468
+ try {
469
+ onDisk = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
470
+ } catch (_) {
471
+ // ENOENT (not yet created) or corrupt JSON → fall back to defaults.
472
+ // Budgets are non-critical; a broken config must not break startup.
473
+ onDisk = {};
474
+ }
475
+ return { ...DEFAULT_CONFIG, ...onDisk };
476
+ }
477
+
478
+ /**
479
+ * Write the brain config to disk atomically.
480
+ *
481
+ * @param {Object} config - The config object
482
+ * @param {string} [projectRoot] - Project root directory
483
+ */
484
+ function writeConfig(config, projectRoot) {
485
+ const filePath = path.join(getBrainDir(projectRoot), CONFIG_FILE);
486
+ atomicWriteSync(filePath, JSON.stringify(config, null, 2) + '\n');
487
+ }
488
+
489
+ // --- Pinned manifest (CoALA Phase 1: always-present semantic tier) ---
490
+
491
+ /**
492
+ * Read the pinned-memory manifest. Lets session-start load pins without
493
+ * scanning the whole index. Missing/corrupt → empty manifest.
494
+ *
495
+ * @param {string} [projectRoot] - Project root directory
496
+ * @returns {Object} { version, pins: [{ id, scope, priority, token_estimate }] }
497
+ */
498
+ function readPinned(projectRoot) {
499
+ const filePath = path.join(getBrainDir(projectRoot), PINNED_FILE);
500
+ try {
501
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
502
+ if (data && Array.isArray(data.pins)) return data;
503
+ } catch (_) { /* fall through */ }
504
+ return { version: 1, pins: [] };
505
+ }
506
+
507
+ /**
508
+ * Write the pinned-memory manifest to disk atomically.
509
+ *
510
+ * @param {Object} pinned - The pinned manifest
511
+ * @param {string} [projectRoot] - Project root directory
512
+ */
513
+ function writePinned(pinned, projectRoot) {
514
+ const filePath = path.join(getBrainDir(projectRoot), PINNED_FILE);
515
+ atomicWriteSync(filePath, JSON.stringify(pinned, null, 2) + '\n');
516
+ }
517
+
518
+ // --- Skills index (CoALA Phase 2: procedural progressive disclosure) ---
519
+
520
+ /**
521
+ * Read the lightweight skills index (the L0 advertised list). Missing/corrupt
522
+ * → empty index.
523
+ *
524
+ * @param {string} [projectRoot] - Project root directory
525
+ * @returns {Object} { version, skills: [{ name, description, triggers, path, strength, use_count, fail_count, last_used }] }
526
+ */
527
+ function readSkillsIndex(projectRoot) {
528
+ const filePath = path.join(getBrainDir(projectRoot), SKILLS_INDEX_FILE);
529
+ try {
530
+ const data = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
531
+ if (data && Array.isArray(data.skills)) return data;
532
+ } catch (_) { /* fall through */ }
533
+ return { version: 1, skills: [] };
534
+ }
535
+
536
+ /**
537
+ * Write the skills index to disk atomically.
538
+ *
539
+ * @param {Object} skillsIndex - The skills index
540
+ * @param {string} [projectRoot] - Project root directory
541
+ */
542
+ function writeSkillsIndex(skillsIndex, projectRoot) {
543
+ const filePath = path.join(getBrainDir(projectRoot), SKILLS_INDEX_FILE);
544
+ atomicWriteSync(filePath, JSON.stringify(skillsIndex, null, 2) + '\n');
545
+ }
546
+
443
547
  module.exports = {
444
548
  getBrainDir,
549
+ DEFAULT_CONFIG,
550
+ readConfig,
551
+ writeConfig,
552
+ readPinned,
553
+ writePinned,
554
+ readSkillsIndex,
555
+ writeSkillsIndex,
445
556
  readIndex,
446
557
  writeIndex,
447
558
  addMemory,
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 -->';