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.
@@ -0,0 +1,292 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain session-start — budget-aware working-memory payload (CoALA Phase 0).
5
+ *
6
+ * One deterministic call returning everything the agent should internalize at
7
+ * session start, bounded by the working-memory token budget in config.json so
8
+ * Brain can never bloat the host's context window.
9
+ *
10
+ * Usage:
11
+ * brain session-start [--project P] [--topics a,b] [--task T] [--top N]
12
+ *
13
+ * Output (JSON):
14
+ * {
15
+ * memory_count, pinned[], skills_index[], context_recall[],
16
+ * due_for_review, low_confidence_alerts[], budget{}
17
+ * }
18
+ *
19
+ * pinned[] (Phase 1) and skills_index[] (Phase 2) are present but empty here;
20
+ * the budget framework already accounts for them so later phases just fill in.
21
+ */
22
+
23
+ const fs = require('fs');
24
+ const path = require('path');
25
+
26
+ const {
27
+ readSearchIndex,
28
+ writeSearchIndex,
29
+ search,
30
+ rebuildIndex,
31
+ } = require('../src/tfidf');
32
+
33
+ const {
34
+ readIndex,
35
+ readAssociations,
36
+ readReviewQueue,
37
+ readConfig,
38
+ getBrainDir,
39
+ } = require('../src/index-manager');
40
+
41
+ const { rankMemories } = require('../src/scorer');
42
+ const { advertisedSummaries } = require('../src/skills');
43
+
44
+ function parseArgs(argv) {
45
+ const args = { project: null, topics: null, task: null, top: 5 };
46
+ for (let i = 0; i < argv.length; i++) {
47
+ switch (argv[i]) {
48
+ case '--project': args.project = argv[++i]; break;
49
+ case '--topics': args.topics = argv[++i]; break;
50
+ case '--task': args.task = argv[++i]; break;
51
+ case '--top': args.top = parseInt(argv[++i], 10) || 5; break;
52
+ default: break;
53
+ }
54
+ }
55
+ return args;
56
+ }
57
+
58
+ /** chars/4 token estimate; falls back to the title line for pre-Phase-0 entries. */
59
+ function estimateTokens(entry) {
60
+ if (typeof entry.token_estimate === 'number') return entry.token_estimate;
61
+ return Math.ceil(((entry.title || '').length + 8) / 4);
62
+ }
63
+
64
+ /**
65
+ * Tier B §10.4 — reorder an importance-sorted list so the top items land at the
66
+ * edges (start + end), where models attend best, leaving the middle for lower
67
+ * ranks. Deterministic. e.g. [1,2,3,4,5] → [1,3,5,4,2].
68
+ */
69
+ function edgeOrder(arr) {
70
+ const front = [];
71
+ const back = [];
72
+ arr.forEach((item, i) => { if (i % 2 === 0) front.push(item); else back.unshift(item); });
73
+ return front.concat(back);
74
+ }
75
+
76
+ /** Read a memory file's body (content after the frontmatter block). */
77
+ function readMemoryBody(brainDir, memPath) {
78
+ try {
79
+ const content = fs.readFileSync(path.join(brainDir, memPath), 'utf-8');
80
+ const first = content.indexOf('---');
81
+ const second = content.indexOf('---', first + 3);
82
+ if (first !== -1 && second !== -1) return content.slice(second + 3).trim();
83
+ return content.trim();
84
+ } catch (_) {
85
+ return '';
86
+ }
87
+ }
88
+
89
+ function buildContextQuery(args) {
90
+ const parts = [];
91
+ if (args.project) parts.push(args.project);
92
+ if (args.topics) parts.push(args.topics);
93
+ if (args.task) parts.push(args.task);
94
+ return parts.length > 0 ? parts.join(' ') : '*';
95
+ }
96
+
97
+ /**
98
+ * Compute the session-start payload for the brain at `projectRoot` (undefined =
99
+ * the real ~/.brain). Pure: performs no console output and never calls exit, so
100
+ * it is directly unit-testable.
101
+ *
102
+ * @param {string} [projectRoot] - Filesystem root whose .brain/ to read
103
+ * @param {Object} [args] - { project, topics, task, top }
104
+ * @returns {Object} The session-start payload
105
+ */
106
+ function computeSessionStart(projectRoot, args = {}) {
107
+ const top = args.top || 5;
108
+ const brainDir = getBrainDir(projectRoot);
109
+ const config = readConfig(projectRoot);
110
+ const cap = config.working_memory_budget_tokens;
111
+
112
+ const empty = {
113
+ memory_count: 0,
114
+ pinned: [], // Phase 1: always-present semantic tier
115
+ skills_index: [], // Phase 2: procedural skill summaries
116
+ context_recall: [],
117
+ due_for_review: 0,
118
+ low_confidence_alerts: [],
119
+ budget: { cap, recall_cap: config.recall_budget_tokens, used: 0, included: 0, excluded: 0 },
120
+ };
121
+
122
+ if (!fs.existsSync(path.join(brainDir, 'index.json'))) return empty;
123
+
124
+ const index = readIndex(projectRoot);
125
+ if (!index || !index.memories) return empty;
126
+
127
+ // Note: we proceed even with zero memories — pins and skills are independent
128
+ // of episodic memory and should still be surfaced.
129
+ const memoryCount = Object.keys(index.memories).length;
130
+
131
+ // --- Context recall (deterministic, reuses the recall engine) ---
132
+ let searchIndex = null;
133
+ try { searchIndex = readSearchIndex(brainDir); } catch (_) { searchIndex = null; }
134
+ if (!searchIndex) {
135
+ searchIndex = rebuildIndex(brainDir, index);
136
+ writeSearchIndex(brainDir, searchIndex);
137
+ }
138
+
139
+ const tfidfScores = search(searchIndex, buildContextQuery(args));
140
+ const memories = Object.entries(index.memories).map(([id, entry]) => ({ id, ...entry }));
141
+
142
+ let associations = null;
143
+ try { associations = readAssociations(projectRoot); } catch (_) { associations = null; }
144
+
145
+ const recallContext = {};
146
+ if (args.project) recallContext.project = args.project;
147
+ if (args.task) recallContext.task_type = args.task;
148
+ if (args.topics) recallContext.topics = String(args.topics).split(',');
149
+
150
+ const ranked = rankMemories(
151
+ memories,
152
+ (mem) => tfidfScores[mem.id] || 0,
153
+ {
154
+ associations: associations || undefined,
155
+ recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
156
+ }
157
+ );
158
+
159
+ // --- Pinned tier (CoALA Phase 1): always present, scope-filtered, budget-capped ---
160
+ // The index entry is the source of truth (pinned.json is a maintained cache);
161
+ // scanning the index here avoids manifest/index drift.
162
+ const pinnedCandidates = [];
163
+ for (const [id, entry] of Object.entries(index.memories)) {
164
+ if (!entry.pinned) continue;
165
+ const scope = entry.pin_scope || 'global';
166
+ if (scope !== 'global') {
167
+ const scopedProject = scope.startsWith('project:') ? scope.slice('project:'.length) : null;
168
+ if (!args.project || scopedProject !== args.project) continue; // out-of-project pin
169
+ }
170
+ pinnedCandidates.push({ id, entry, scope, priority: entry.pin_priority || 0 });
171
+ }
172
+ pinnedCandidates.sort((a, b) =>
173
+ (b.priority - a.priority) ||
174
+ ((b.entry.strength || 0) - (a.entry.strength || 0)) ||
175
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
176
+ );
177
+
178
+ const pinned = [];
179
+ let pinnedTokens = 0;
180
+ let pinnedExcluded = 0;
181
+ const pinCap = Math.min(config.pin_budget_tokens, cap);
182
+ for (const c of pinnedCandidates) {
183
+ const est = estimateTokens(c.entry);
184
+ if (pinnedTokens + est > pinCap && pinned.length > 0) { pinnedExcluded++; continue; }
185
+ pinned.push({
186
+ id: c.id,
187
+ title: c.entry.title,
188
+ content: readMemoryBody(brainDir, c.entry.path),
189
+ scope: c.scope,
190
+ priority: c.priority,
191
+ tokens: est,
192
+ });
193
+ pinnedTokens += est;
194
+ }
195
+
196
+ // --- Skills index (CoALA Phase 2): advertise name + description only (L0) ---
197
+ const skills_index = [];
198
+ let skillsTokens = 0;
199
+ let skillsExcluded = 0;
200
+ const skillsCap = Math.min(config.skills_index_budget_tokens, Math.max(0, cap - pinnedTokens));
201
+ for (const s of advertisedSummaries(projectRoot)) {
202
+ const est = Math.ceil(((s.name || '').length + (s.description || '').length + 8) / 4);
203
+ if (skillsTokens + est > skillsCap && skills_index.length > 0) { skillsExcluded++; continue; }
204
+ skills_index.push({ name: s.name, description: s.description });
205
+ skillsTokens += est;
206
+ }
207
+
208
+ // --- Budget-bound the recall set with whatever the pin/skills tiers leave ---
209
+ const recallCap = Math.max(0, Math.min(config.recall_budget_tokens, cap - pinnedTokens - skillsTokens));
210
+ const pinnedIds = new Set(pinned.map((p) => p.id));
211
+
212
+ const context_recall = [];
213
+ let used = 0;
214
+ let excluded = 0;
215
+ for (const mem of ranked.slice(0, top)) {
216
+ if (pinnedIds.has(mem.id)) continue; // already presented in the pinned tier
217
+ const est = estimateTokens(mem);
218
+ if (used + est > recallCap && context_recall.length > 0) {
219
+ excluded++;
220
+ continue;
221
+ }
222
+ context_recall.push({
223
+ id: mem.id,
224
+ title: mem.title || path.basename(mem.path || '', '.md'),
225
+ path: mem.path,
226
+ type: mem.type,
227
+ score: mem.score,
228
+ token_estimate: est,
229
+ });
230
+ used += est;
231
+ }
232
+
233
+ // --- Due for review (matches the existing "has items" heuristic) ---
234
+ let dueForReview = 0;
235
+ try {
236
+ const queue = readReviewQueue(projectRoot);
237
+ if (queue && Array.isArray(queue.items)) dueForReview = queue.items.length;
238
+ } catch (_) { dueForReview = 0; }
239
+
240
+ // --- Low-confidence-but-frequently-used alerts ---
241
+ const low_confidence_alerts = [];
242
+ for (const [id, entry] of Object.entries(index.memories)) {
243
+ if ((entry.access_count || 0) >= 3 && (entry.confidence ?? 1) < 0.5) {
244
+ low_confidence_alerts.push({
245
+ id,
246
+ title: entry.title,
247
+ confidence: entry.confidence,
248
+ access_count: entry.access_count,
249
+ });
250
+ }
251
+ }
252
+
253
+ return {
254
+ memory_count: memoryCount,
255
+ pinned,
256
+ skills_index,
257
+ context_recall: edgeOrder(context_recall), // Tier B §10.4: top ranks at the edges
258
+ due_for_review: dueForReview,
259
+ low_confidence_alerts,
260
+ budget: {
261
+ cap,
262
+ pin_cap: pinCap,
263
+ skills_cap: skillsCap,
264
+ recall_cap: recallCap,
265
+ used: pinnedTokens + skillsTokens + used,
266
+ pinned_tokens: pinnedTokens,
267
+ skills_tokens: skillsTokens,
268
+ recall_used: used,
269
+ included: context_recall.length,
270
+ excluded,
271
+ pinned_excluded: pinnedExcluded,
272
+ skills_excluded: skillsExcluded,
273
+ },
274
+ };
275
+ }
276
+
277
+ function main(argv) {
278
+ const args = parseArgs(argv || process.argv.slice(2));
279
+ try {
280
+ const payload = computeSessionStart(undefined, args);
281
+ console.log(JSON.stringify(payload, null, 2));
282
+ } catch (err) {
283
+ console.error(JSON.stringify({ error: err.message }));
284
+ process.exit(1);
285
+ }
286
+ }
287
+
288
+ if (require.main === module) {
289
+ main(process.argv.slice(2));
290
+ }
291
+
292
+ module.exports = { main, computeSessionStart, estimateTokens, parseArgs, edgeOrder };
package/bin/skill.js ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain skill — manage procedural skills (CoALA Phase 2).
5
+ *
6
+ * Usage:
7
+ * brain skill list Advertised index (name + description)
8
+ * brain skill show <name> Full SKILL.md (L1 disclosure)
9
+ * brain skill use <name> [--failed] Record a use; success strengthens,
10
+ * --failed weakens (demotion feedback)
11
+ * brain skill remove <name> Delete a skill
12
+ * brain skill add Create a skill from JSON on stdin:
13
+ * { name, description, triggers[], body }
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const {
18
+ addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill,
19
+ } = require('../src/skills');
20
+
21
+ function emit(obj) { console.log(JSON.stringify(obj, null, 2)); }
22
+ function fail(obj) { console.error(JSON.stringify(obj)); process.exit(1); }
23
+ function done(result) { return result && result.error ? fail(result) : emit(result); }
24
+
25
+ const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|add|remove <name>|export <name> [--target claude|gemini]>';
26
+
27
+ function main(argv) {
28
+ const args = argv || process.argv.slice(2);
29
+ const action = args[0];
30
+ const rest = args.slice(1);
31
+ const firstName = rest.find((a) => !a.startsWith('--'));
32
+
33
+ switch (action) {
34
+ case 'list':
35
+ return emit(listSkills(undefined));
36
+ case 'show':
37
+ if (!firstName) return fail({ error: USAGE });
38
+ return done(showSkill(undefined, firstName));
39
+ case 'use':
40
+ if (!firstName) return fail({ error: USAGE });
41
+ return done(useSkill(undefined, firstName, { failed: rest.includes('--failed') }));
42
+ case 'remove':
43
+ if (!firstName) return fail({ error: USAGE });
44
+ return done(removeSkill(undefined, firstName));
45
+ case 'export': {
46
+ if (!firstName) return fail({ error: 'Usage: brain skill export <name> [--target claude|gemini]' });
47
+ const ti = rest.indexOf('--target');
48
+ const target = ti !== -1 ? rest[ti + 1] : 'claude';
49
+ return done(exportSkill(undefined, firstName, target));
50
+ }
51
+ case 'add': {
52
+ if (process.stdin.isTTY) return fail({ error: 'Pipe a skill JSON via stdin' });
53
+ let input;
54
+ try { input = JSON.parse(fs.readFileSync('/dev/stdin', 'utf-8')); }
55
+ catch (e) { return fail({ error: `Invalid JSON: ${e.message}` }); }
56
+ return done(addSkill(undefined, input));
57
+ }
58
+ default:
59
+ return fail({ error: USAGE });
60
+ }
61
+ }
62
+
63
+ if (require.main === module) {
64
+ main(process.argv.slice(2));
65
+ }
66
+
67
+ module.exports = { main };
package/bin/unpin.js ADDED
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * brain unpin — remove a memory from the always-present semantic tier.
5
+ *
6
+ * Usage:
7
+ * brain unpin <id>
8
+ */
9
+
10
+ const { unpinMemory } = require('../src/pinning');
11
+
12
+ function parseArgs(argv) {
13
+ const args = { id: null };
14
+ for (const a of argv) {
15
+ if (!a.startsWith('--') && !args.id) args.id = a;
16
+ }
17
+ return args;
18
+ }
19
+
20
+ function main(argv) {
21
+ const args = parseArgs(argv || process.argv.slice(2));
22
+ if (!args.id) {
23
+ console.error(JSON.stringify({ error: 'Usage: brain unpin <id>' }));
24
+ process.exit(1);
25
+ }
26
+ const result = unpinMemory(undefined, args.id);
27
+ if (result.error) {
28
+ console.error(JSON.stringify(result));
29
+ process.exit(1);
30
+ }
31
+ console.log(JSON.stringify(result, null, 2));
32
+ }
33
+
34
+ if (require.main === module) {
35
+ main(process.argv.slice(2));
36
+ }
37
+
38
+ module.exports = { main, parseArgs };
@@ -1,6 +1,6 @@
1
1
  # /brain:memorize — Store a New Memory
2
2
 
3
- You are storing memories in the Brain Memory system. Your job is to decide **what** to remember and **how to classify** it. The `brain-memorize` CLI handles all file operations.
3
+ You are storing memories in the Brain Memory system. Your job is to decide **what** to remember and **how to classify** it. The `brain memorize` CLI handles all file operations.
4
4
 
5
5
  **User input:** $ARGUMENTS
6
6
 
@@ -40,12 +40,17 @@ For each memory, determine:
40
40
 
41
41
  **strength_adjustment** (optional, -0.15 to +0.15): Tweak base strength based on significance.
42
42
 
43
- ### 3. Call brain-memorize
43
+ **Pinned & stable** (optional, CoALA Phase 1):
44
+ - `pinned: true` — always inject this memory at session start regardless of recall score (and decay-exempt). Optionally `pin_scope: "project:<name>"` (default `"global"`) and `pin_priority: <N>`.
45
+ - `stable: true` — exempt from decay (never fades) without forcing it to always load — for timeless facts recalled on demand.
46
+ - **Propose, don't assume:** when a memory is a durable convention/preference/standing decision (type ∈ {preference, decision, insight, relationship}, high confidence, low time-sensitivity), *suggest* pinning it — but only set `pinned` if the user agrees (or pin later with `/brain:pin`).
47
+
48
+ ### 3. Call brain memorize
44
49
 
45
50
  Pipe the classified memories as JSON to the CLI in a **single bash call**:
46
51
 
47
52
  ```bash
48
- brain-memorize <<'EOF'
53
+ brain memorize <<'EOF'
49
54
  {
50
55
  "memories": [
51
56
  {
@@ -73,7 +78,7 @@ EOF
73
78
 
74
79
  Add `--sync` flag if the user requested it or passed `--sync` to the command:
75
80
  ```bash
76
- brain-memorize --sync <<'EOF'
81
+ brain memorize --sync <<'EOF'
77
82
  ...
78
83
  EOF
79
84
  ```
@@ -87,3 +92,12 @@ The CLI outputs JSON with what was stored. Present the results to the user:
87
92
  - Type, strength, tags
88
93
  - Edges created
89
94
  - Sync result (if applicable)
95
+
96
+ ### 5. Resolve contradictions (Tier B §10.2)
97
+
98
+ If a stored memory's result includes `potential_conflicts`, it shares heavy tag overlap with a **pinned or stable** memory — and pinned/stable facts never decay out of contention, so a stale one is dangerous. **Do not silently keep both.** Inspect the conflicting memory (`brain recall` or read its file) and, if the new memory genuinely contradicts it, propose a resolution to the user:
99
+ - **Supersede** — unpin/forget the old fact, keep the new one (record the supersession).
100
+ - **Keep both, scoped** — e.g. pin each to its own project.
101
+ - **Reject the new one** — the old fact stands.
102
+
103
+ Never auto-resolve; surface the conflict and let the user decide.
@@ -0,0 +1,32 @@
1
+ # /brain:pin — Pin a Memory (Always-Present Tier)
2
+
3
+ You are pinning a memory into the **always-present semantic tier**. Pinned memories are injected at every session start regardless of recall score, and are decay-exempt — they never fade.
4
+
5
+ **User input:** $ARGUMENTS
6
+
7
+ ## Behavior
8
+
9
+ 1. **Resolve the target memory:**
10
+ - If `$ARGUMENTS` is a memory ID (`mem_...`), use it directly.
11
+ - Otherwise run `brain recall "$ARGUMENTS" --top 5`, show the top matches, and confirm which one to pin.
12
+
13
+ 2. **Choose a scope** (default `global`):
14
+ - `global` — loads in every project.
15
+ - `project:<name>` — loads only while working in that project. Use for project-specific conventions.
16
+
17
+ 3. **Pin it:**
18
+ ```bash
19
+ brain pin <id> [--scope global|project:<name>] [--priority N]
20
+ ```
21
+ `--priority` (default 0) breaks ties when the pin budget (`~/.brain/config.json` → `pin_budget_tokens`) is tight; higher wins.
22
+
23
+ 4. Confirm:
24
+ ```
25
+ 📌 Pinned <title> (<scope>) — will load every session.
26
+ ```
27
+
28
+ ## When to pin
29
+
30
+ Durable conventions, preferences, and standing decisions the agent must **always** honor — e.g. "always use tabs", "deploy via Cloudflare", "never touch the legacy billing module". Good candidates are `preference`, `decision`, `insight`, and `relationship` memories with high confidence and low time-sensitivity.
31
+
32
+ **Do not pin** episodic or time-sensitive content (a one-off incident, a temporary workaround). Those belong in normal recall, where decay can retire them.
@@ -1,6 +1,6 @@
1
1
  # /brain:remember — Recall Relevant Memories
2
2
 
3
- You are recalling memories from the Brain Memory system. This command uses the **deterministic recall engine** (`brain-recall`) to score and rank memories, then presents the results.
3
+ You are recalling memories from the Brain Memory system. This command uses the **deterministic recall engine** (`brain recall`) to score and rank memories, then presents the results.
4
4
 
5
5
  **User query:** $ARGUMENTS
6
6
 
@@ -31,7 +31,7 @@ node <brain-memory-install-path>/bin/recall.js "$ARGUMENTS" \
31
31
 
32
32
  If the brain-memory package is installed globally, use:
33
33
  ```bash
34
- brain-recall "$ARGUMENTS" --project "<project>" --task "<task_type>" --top 10
34
+ brain recall "$ARGUMENTS" --project "<project>" --task "<task_type>" --top 10
35
35
  ```
36
36
 
37
37
  The engine computes **TF-IDF relevance** (cosine similarity between query and memory content), then combines it with decayed strength, recency, spreading activation, context match, and salience using the v4 formula. All scoring is deterministic — same query always produces the same ranking.
@@ -70,7 +70,7 @@ node <brain-memory-install-path>/bin/reinforce.js <mem_id1> <mem_id2> ...
70
70
 
71
71
  Or if globally installed:
72
72
  ```bash
73
- brain-reinforce <mem_id1> <mem_id2> ...
73
+ brain reinforce <mem_id1> <mem_id2> ...
74
74
  ```
75
75
 
76
76
  This deterministically applies:
@@ -0,0 +1,55 @@
1
+ # /brain:skill — Manage Procedural Skills
2
+
3
+ You are managing **procedural memory** — reusable "how to do things" stored as `~/.brain/_skills/<name>/SKILL.md`. Skills use **progressive disclosure** so they never bloat the context window:
4
+
5
+ - **L0 (session start):** only each skill's name + description is advertised (≈100 tokens each).
6
+ - **L1 (on a matching task):** read the full `SKILL.md` for step-by-step instructions.
7
+ - **L2 (at execution):** load any referenced `resources/` (templates, scripts) only when a step needs them.
8
+
9
+ **User input:** $ARGUMENTS
10
+
11
+ ## Actions
12
+
13
+ **List** advertised skills:
14
+ ```bash
15
+ brain skill list
16
+ ```
17
+
18
+ **Show** a skill's full instructions (do this when a task matches a skill's description/triggers):
19
+ ```bash
20
+ brain skill show <name>
21
+ ```
22
+
23
+ **Add** a skill — pipe JSON on stdin:
24
+ ```bash
25
+ brain skill add <<'EOF'
26
+ {
27
+ "name": "structured-code-review",
28
+ "description": "One-paragraph advertised summary used for matching (~100 tokens).",
29
+ "triggers": ["code review", "review PR", "audit changes"],
30
+ "body": "## Steps\n1. ...\n2. ..."
31
+ }
32
+ EOF
33
+ ```
34
+
35
+ **Use** — record an outcome after running a skill. Success strengthens it; `--failed` weakens it (a skill that fails too often demotes itself out of the advertised L0 index):
36
+ ```bash
37
+ brain skill use <name> # succeeded
38
+ brain skill use <name> --failed # produced a bad outcome
39
+ ```
40
+
41
+ **Remove** a skill:
42
+ ```bash
43
+ brain skill remove <name>
44
+ ```
45
+
46
+ **Export** a skill into the host agent's native format so it becomes directly executable (writes `.claude/skills/<name>/SKILL.md` or `.gemini/...` in the current project):
47
+ ```bash
48
+ brain skill export <name> [--target claude|gemini]
49
+ ```
50
+
51
+ ## Guidance
52
+
53
+ - Advertise skills with a **crisp, matchable description** — that single line is all the agent sees at L0, so it must convey when to reach for the skill.
54
+ - Reach for `show` only when a task genuinely matches; don't pre-load skills speculatively.
55
+ - Always record the outcome with `use` (success or `--failed`) so the strength/demotion feedback loop stays accurate.
@@ -12,9 +12,10 @@ Sleep performs nine phases, mimicking real neuroscience:
12
12
  2. **Synaptic Homeostasis** — Proportionally scale down all strengths to prevent inflation (Tononi & Cirelli SHY)
13
13
  3. **Knowledge Propagation** — Evaluate recent memories against the hierarchy and update related memories
14
14
  4. **Semantic Crystallization** — Extract generalizable knowledge from frequently-recalled episodic memories
15
+ - **4b. Procedural Crystallization** — Distill repeated procedures into reusable skills (CoALA Phase 3)
15
16
  5. **Reorganize** — Detect flat clusters and restructure into deeper sub-categories
16
17
  6. **Consolidate** — Merge weak related memories into stronger combined knowledge
17
- 7. **Prune** — Archive memories that have decayed beyond recovery
18
+ 7. **Prune** — Archive memories that have decayed beyond recovery, including context-shift obsolescence (Tier B §10.1)
18
19
  8. **REM Dreaming** — Discover creative cross-domain associations via analogical reasoning
19
20
  9. **Expertise Detection** — Identify dense knowledge areas and generate expertise profiles
20
21
 
@@ -33,6 +34,8 @@ days_elapsed = (now - last_accessed) / (1000 * 60 * 60 * 24)
33
34
  decayed_strength = strength * (decay_rate ^ days_elapsed)
34
35
  ```
35
36
 
37
+ **Decay-exempt memories (CoALA Phase 1):** if a memory is `pinned` or `stable`, its `decayed_strength` equals its raw `strength` (it never fades). Treat such memories as **Strong** regardless of elapsed time.
38
+
36
39
  4. Categorize each memory into tiers:
37
40
  - **Strong** (decayed_strength >= 0.6) — healthy, no action needed
38
41
  - **Moderate** (0.3 <= decayed_strength < 0.6) — consolidation candidates
@@ -78,7 +81,7 @@ Based on Tononi & Cirelli's **Synaptic Homeostasis Hypothesis (SHY)** — during
78
81
  scaling_factor = max(0.85, 0.5 / mean_effective_strength)
79
82
  ```
80
83
 
81
- 3. For every memory: `strength = strength * scaling_factor`
84
+ 3. For every memory: `strength = strength * scaling_factor` — **except** `pinned` or `stable` memories, which are exempt from homeostatic downscaling (their strength is never altered).
82
85
 
83
86
  4. Selectively re-boost important memories:
84
87
  - **High salience** (salience >= 0.7): +0.05
@@ -264,6 +267,47 @@ Approve crystallizations? [all / select / skip]
264
267
 
265
268
  ---
266
269
 
270
+ ## Phase 4b: Procedural Crystallization (Episodic → Procedural) — CoALA Phase 3
271
+
272
+ Beyond abstracting *principles* (Phase 4), the brain also turns repeated *procedures* into skills. When the same kind of task has been solved the same way several times, distill it into a reusable `SKILL.md` — Brain's genuine value-add over CoALA, which only describes hand-authored skills.
273
+
274
+ ### Steps
275
+
276
+ 1. Cluster `procedural`/`experience` memories by tag overlap + association edges (the same clustering used elsewhere). Look for a recurring *task-solving procedure* represented across **≥ N similar memories** (default N = 3).
277
+
278
+ 2. For each qualifying cluster, evaluate: **is there a repeatable, step-by-step procedure here that would help on a future task?**
279
+
280
+ 3. If yes, draft a skill (do not write silently — propose it):
281
+ - `name`: a short kebab-case slug
282
+ - `description`: one matchable line (~100 tokens) — the L0 advertisement
283
+ - `triggers`: phrases that should surface it
284
+ - body: the step-by-step instructions, drawn from the source memories
285
+ - Create it with `brain skill add` once approved.
286
+
287
+ 4. Link the new skill to its source memories (note the skill name in their `related`/notes).
288
+
289
+ **Example:**
290
+ - 3× episodic: "set up Cloudflare Worker + D1 for project X / Y / Z" solved the same way
291
+ - → Skill `deploy-cloudflare-worker-d1`: the distilled step list.
292
+
293
+ Present proposals for user approval (never auto-create):
294
+
295
+ ```
296
+ ## Phase 4b: Procedural Crystallization
297
+
298
+ Found <N> recurring procedures ready to become skills:
299
+
300
+ 🛠️ Pattern seen 3× across {projX, projY, projZ}
301
+ → Proposed skill: "deploy-cloudflare-worker-d1"
302
+ Triggers: "deploy worker", "set up D1"
303
+
304
+ Approve skill creation? [all / select / skip]
305
+ ```
306
+
307
+ These crystallized skills are *hypotheses*: their strength/demotion feedback (`brain skill use [--failed]`) validates or retires them over time.
308
+
309
+ ---
310
+
267
311
  ## Phase 5: Reorganize (Neocortical Restructuring)
268
312
 
269
313
  During sleep, the brain transfers memories from the hippocampus to the neocortex, organizing them into structured long-term storage. This phase detects **flat clusters** — directories with many memories that should be organized into deeper sub-categories.
@@ -337,16 +381,27 @@ During deep sleep, the brain merges related experiences into generalized knowled
337
381
 
338
382
  During sleep, the brain prunes weak synaptic connections to maintain efficiency. Here, we archive memories that have faded beyond usefulness.
339
383
 
384
+ ### Obsolescence / context-shift detection (Tier B §10.1)
385
+
386
+ Decay handles *slow fade*; this catches *abrupt relevance loss*. A memory cluster can become obsolete overnight (the user changed jobs, abandoned a project, switched stacks) while still carrying high strength — so decay alone never retires it.
387
+
388
+ - Read `~/.brain/contexts.json`. Identify any `encoding_context.project` (or role/domain) that appears in older memories but has been **absent from the last N sessions** (default N = 10).
389
+ - Flag the affected cluster (by project + association edges) as **candidate-obsolete** — these become *additional* archive candidates below.
390
+ - **Never** flag `pinned` memories (an explicit, active user choice). `stable` memories *can* be flagged — stability exempts from decay, not from obsolescence (a timeless fact about a former employer is still obsolete).
391
+ - This is reversible: candidates are *archived* (recoverable from `_archived/`), never erased, and only after user confirmation.
392
+
340
393
  ### Steps
341
394
 
342
- 1. Take all **Fading** tier memories (decayed_strength < 0.1) that were NOT already consolidated in Phase 6
395
+ 1. Take all **Fading** tier memories (decayed_strength < 0.1) that were NOT already consolidated in Phase 6 — plus any **candidate-obsolete** clusters from the detection step above
343
396
 
344
397
  2. **Salience protection**: Memories with `salience >= 0.7` are NEVER auto-pruned, regardless of strength. Skip them with a note:
345
398
  ```
346
399
  ⚡ Skipping <title> — high salience (0.8) protects from auto-pruning
347
400
  ```
348
401
 
349
- 3. Present the prune list (excluding salience-protected memories)
402
+ **Pinned/stable protection (CoALA Phase 1):** `pinned` or `stable` memories are also NEVER pruned or archived — they are decay-exempt, so they never reach the Fading tier in the first place. Skip them too.
403
+
404
+ 3. Present the prune list (excluding salience- and pin/stable-protected memories)
350
405
 
351
406
  4. Get user approval (default: archive all)
352
407