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

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,6 +1,6 @@
1
1
  {
2
2
  "name": "brain-memory",
3
- "version": "0.1.0-beta.14",
3
+ "version": "0.1.0-beta.16",
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",
@@ -25,11 +25,7 @@
25
25
  "url": "https://github.com/onurkarali/brain/issues"
26
26
  },
27
27
  "bin": {
28
- "brain-memory": "bin/install.js",
29
- "brain-recall": "bin/recall.js",
30
- "brain-reinforce": "bin/reinforce.js",
31
- "brain-cloud": "bin/cloud-sync.js",
32
- "brain-memorize": "bin/memorize.js"
28
+ "brain": "bin/brain.js"
33
29
  },
34
30
  "files": [
35
31
  "assets/",
@@ -46,7 +42,7 @@
46
42
  "url": "git+https://github.com/onurkarali/brain.git"
47
43
  },
48
44
  "scripts": {
49
- "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",
50
46
  "prerelease": "npm test",
51
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",
52
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.
@@ -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 @@ Run /brain:memorize to capture them before this context is lost.
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, Codex, and OpenCode all get the same rankings for the same query.
@@ -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/pinning.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Brain Memory — Pinning (CoALA Phase 1)
3
+ *
4
+ * Pin/unpin a memory into the always-present semantic tier. Pinning is the fix
5
+ * for the core reliability hole: a durable convention/preference must apply
6
+ * every session regardless of recall score. A pinned memory is implicitly
7
+ * decay-exempt (the scorer treats pinned || stable as exempt).
8
+ *
9
+ * The index entry is the source of truth read by recall/session-start; the
10
+ * memory file's frontmatter is kept in sync for human-readability and git.
11
+ */
12
+
13
+ const fs = require('fs');
14
+ const path = require('path');
15
+
16
+ const {
17
+ getBrainDir,
18
+ readIndex,
19
+ writeIndex,
20
+ readPinned,
21
+ writePinned,
22
+ } = require('./index-manager');
23
+
24
+ /** chars/4 token estimate; falls back to the title line for older entries. */
25
+ function estimateTokens(entry) {
26
+ if (entry && typeof entry.token_estimate === 'number') return entry.token_estimate;
27
+ return Math.ceil((((entry && entry.title) || '').length + 8) / 4);
28
+ }
29
+
30
+ /**
31
+ * Update-or-insert scalar YAML frontmatter fields in a memory file (best effort;
32
+ * the index entry remains the source of truth if the file is unreadable).
33
+ */
34
+ function setFrontmatterFields(brainDir, memPath, fields) {
35
+ const fullPath = path.join(brainDir, memPath);
36
+ let content;
37
+ try { content = fs.readFileSync(fullPath, 'utf-8'); } catch (_) { return; }
38
+
39
+ const first = content.indexOf('---');
40
+ const second = content.indexOf('---', first + 3);
41
+ if (first === -1 || second === -1) return;
42
+
43
+ let fm = content.slice(first + 3, second);
44
+ const inserts = [];
45
+ for (const [key, value] of Object.entries(fields)) {
46
+ const formatted = typeof value === 'string' ? `"${value}"` : String(value);
47
+ const re = new RegExp(`^(${key}:\\s*).*$`, 'm');
48
+ if (re.test(fm)) fm = fm.replace(re, `$1${formatted}`);
49
+ else inserts.push(`${key}: ${formatted}\n`);
50
+ }
51
+ if (inserts.length) fm = fm.replace(/\s*$/, '\n') + inserts.join('');
52
+
53
+ content = content.slice(0, first + 3) + fm + content.slice(second);
54
+ fs.writeFileSync(fullPath, content);
55
+ }
56
+
57
+ /**
58
+ * Pin a memory (always-loaded). Sets pinned/pin_scope/pin_priority on the index
59
+ * entry + frontmatter and records it in pinned.json.
60
+ *
61
+ * @param {string} [projectRoot] - Filesystem root (undefined = real ~/.brain)
62
+ * @param {string} id - Memory ID
63
+ * @param {Object} [opts] - { scope = "global"|"project:<name>", priority = 0 }
64
+ * @returns {Object} Result or { error }
65
+ */
66
+ function pinMemory(projectRoot, id, opts = {}) {
67
+ const scope = opts.scope || 'global';
68
+ const priority = Number.isFinite(opts.priority) ? opts.priority : 0;
69
+
70
+ const index = readIndex(projectRoot);
71
+ if (!index || !index.memories || !index.memories[id]) {
72
+ return { error: `Memory not found: ${id}` };
73
+ }
74
+
75
+ const entry = index.memories[id];
76
+ entry.pinned = true;
77
+ entry.pin_scope = scope;
78
+ entry.pin_priority = priority;
79
+ writeIndex(index, projectRoot);
80
+
81
+ setFrontmatterFields(getBrainDir(projectRoot), entry.path, {
82
+ pinned: true,
83
+ pin_scope: scope,
84
+ pin_priority: priority,
85
+ });
86
+
87
+ const pinned = readPinned(projectRoot);
88
+ pinned.pins = pinned.pins.filter((p) => p.id !== id);
89
+ pinned.pins.push({ id, scope, priority, token_estimate: estimateTokens(entry) });
90
+ writePinned(pinned, projectRoot);
91
+
92
+ return { id, pinned: true, scope, priority };
93
+ }
94
+
95
+ /**
96
+ * Unpin a memory. Clears the pinned flag and removes it from pinned.json. Leaves
97
+ * an independent `stable` flag untouched.
98
+ *
99
+ * @param {string} [projectRoot] - Filesystem root (undefined = real ~/.brain)
100
+ * @param {string} id - Memory ID
101
+ * @returns {Object} Result or { error }
102
+ */
103
+ function unpinMemory(projectRoot, id) {
104
+ const index = readIndex(projectRoot);
105
+ if (!index || !index.memories || !index.memories[id]) {
106
+ return { error: `Memory not found: ${id}` };
107
+ }
108
+
109
+ const entry = index.memories[id];
110
+ const wasPinned = !!entry.pinned;
111
+ entry.pinned = false;
112
+ writeIndex(index, projectRoot);
113
+
114
+ setFrontmatterFields(getBrainDir(projectRoot), entry.path, { pinned: false });
115
+
116
+ const pinned = readPinned(projectRoot);
117
+ const before = pinned.pins.length;
118
+ pinned.pins = pinned.pins.filter((p) => p.id !== id);
119
+ writePinned(pinned, projectRoot);
120
+
121
+ return { id, pinned: false, was_pinned: wasPinned, removed: before !== pinned.pins.length };
122
+ }
123
+
124
+ module.exports = { pinMemory, unpinMemory, estimateTokens, setFrontmatterFields };
package/src/scorer.js CHANGED
@@ -13,9 +13,12 @@
13
13
  * @param {number} baseStrength - Original strength (0.0-1.0)
14
14
  * @param {number} decayRate - Daily decay factor (e.g., 0.995)
15
15
  * @param {string|Date} lastAccessed - ISO timestamp of last access
16
+ * @param {boolean} [exempt=false] - CoALA Phase 1: pinned/stable memories are
17
+ * decay-exempt — their strength never fades (semantic "stable" property).
16
18
  * @returns {number} Effective strength after decay
17
19
  */
18
- function computeDecayedStrength(baseStrength, decayRate, lastAccessed) {
20
+ function computeDecayedStrength(baseStrength, decayRate, lastAccessed, exempt = false) {
21
+ if (exempt) return baseStrength;
19
22
  const lastDate = new Date(lastAccessed);
20
23
  const now = new Date();
21
24
  const daysElapsed = (now - lastDate) / (1000 * 60 * 60 * 24);
@@ -365,7 +368,8 @@ function rankMemories(memories, relevanceFn, options = {}) {
365
368
  const decayedStrength = computeDecayedStrength(
366
369
  mem.strength,
367
370
  mem.decay_rate,
368
- mem.last_accessed
371
+ mem.last_accessed,
372
+ !!(mem.stable || mem.pinned) // pinned ⇒ implicitly stable (decay-exempt)
369
373
  );
370
374
  const recencyBonus = computeRecencyBonus(mem.last_accessed);
371
375
  const relevance = relevanceFn(mem);