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.
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);
package/src/skills.js ADDED
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Brain Memory — Procedural Skills (CoALA Phase 2 + Tier B §10.3)
3
+ *
4
+ * Stores "how to do things" as `_skills/<name>/SKILL.md` folders and serves them
5
+ * via three-level progressive disclosure:
6
+ * L0 — session start advertises only name + description (skills-index.json)
7
+ * L1 — on a matching task, the agent reads the full SKILL.md
8
+ * L2 — referenced resources/ load only at execution
9
+ *
10
+ * Procedural memory strengthens with successful use and weakens on failure
11
+ * (Tier B §10.3), so a bad crystallized skill demotes itself out of the index.
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+
17
+ const {
18
+ getBrainDir,
19
+ readSkillsIndex,
20
+ writeSkillsIndex,
21
+ validateBrainPath,
22
+ atomicWriteSync,
23
+ } = require('./index-manager');
24
+ const { setFrontmatterFields } = require('./pinning');
25
+
26
+ const SKILLS_DIR = '_skills';
27
+ const DEFAULT_STRENGTH = 0.6;
28
+ // A skill whose failure rate exceeds this drops below the L0 advertisement cut.
29
+ const DEMOTE_FAIL_RATIO = 0.5;
30
+
31
+ /** Normalize a skill name to a filesystem-safe slug. */
32
+ function slug(name) {
33
+ return String(name || '').toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
34
+ }
35
+
36
+ function skillPath(name) {
37
+ return `${SKILLS_DIR}/${slug(name)}/SKILL.md`;
38
+ }
39
+
40
+ function buildSkillFile(skill) {
41
+ const fm = [
42
+ '---',
43
+ `name: ${slug(skill.name)}`,
44
+ `description: ${JSON.stringify(skill.description || '')}`,
45
+ `triggers: [${(skill.triggers || []).map((t) => JSON.stringify(t)).join(', ')}]`,
46
+ 'cognitive_type: procedural',
47
+ `strength: ${skill.strength ?? DEFAULT_STRENGTH}`,
48
+ `last_used: ${skill.last_used ? JSON.stringify(skill.last_used) : 'null'}`,
49
+ `use_count: ${skill.use_count ?? 0}`,
50
+ `fail_count: ${skill.fail_count ?? 0}`,
51
+ '---',
52
+ '',
53
+ ].join('\n');
54
+ return fm + (skill.body || '') + '\n';
55
+ }
56
+
57
+ /** Is this skill advertised at L0? Demoted skills stay on disk but go quiet. */
58
+ function isAdvertised(s) {
59
+ const uses = s.use_count || 0;
60
+ const fails = s.fail_count || 0;
61
+ return !(uses >= 3 && fails / uses > DEMOTE_FAIL_RATIO);
62
+ }
63
+
64
+ /**
65
+ * Create or replace a skill.
66
+ * @param {string} [projectRoot]
67
+ * @param {Object} skill - { name, description, triggers[], body, strength? }
68
+ */
69
+ function addSkill(projectRoot, skill) {
70
+ const name = slug(skill && skill.name);
71
+ if (!name) return { error: 'Skill name required' };
72
+
73
+ const brainDir = getBrainDir(projectRoot);
74
+ const dir = path.join(brainDir, SKILLS_DIR, name);
75
+ validateBrainPath(dir, brainDir);
76
+ fs.mkdirSync(dir, { recursive: true });
77
+
78
+ const record = {
79
+ name,
80
+ description: skill.description || '',
81
+ triggers: skill.triggers || [],
82
+ strength: skill.strength ?? DEFAULT_STRENGTH,
83
+ use_count: 0,
84
+ fail_count: 0,
85
+ last_used: null,
86
+ };
87
+ atomicWriteSync(path.join(dir, 'SKILL.md'), buildSkillFile({ ...record, body: skill.body }));
88
+
89
+ const idx = readSkillsIndex(projectRoot);
90
+ idx.skills = idx.skills.filter((s) => s.name !== name);
91
+ idx.skills.push({ ...record, path: skillPath(name) });
92
+ writeSkillsIndex(idx, projectRoot);
93
+
94
+ return { name, added: true };
95
+ }
96
+
97
+ /** Full advertised index (every stored skill, advertised or demoted). */
98
+ function listSkills(projectRoot) {
99
+ return readSkillsIndex(projectRoot).skills;
100
+ }
101
+
102
+ /** L0 summaries (name + description) for advertised skills only. */
103
+ function advertisedSummaries(projectRoot) {
104
+ return readSkillsIndex(projectRoot).skills
105
+ .filter(isAdvertised)
106
+ .map((s) => ({ name: s.name, description: s.description, triggers: s.triggers || [] }));
107
+ }
108
+
109
+ /** L1: the full SKILL.md body. */
110
+ function showSkill(projectRoot, name) {
111
+ const full = path.join(getBrainDir(projectRoot), skillPath(name));
112
+ try {
113
+ return { name: slug(name), content: fs.readFileSync(full, 'utf-8') };
114
+ } catch (_) {
115
+ return { error: `Skill not found: ${name}` };
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Record a use. Success strengthens; failure weakens and counts toward demotion.
121
+ * @param {Object} [opts] - { failed: boolean }
122
+ */
123
+ function useSkill(projectRoot, name, opts = {}) {
124
+ const idx = readSkillsIndex(projectRoot);
125
+ const s = idx.skills.find((x) => x.name === slug(name));
126
+ if (!s) return { error: `Skill not found: ${name}` };
127
+
128
+ s.use_count = (s.use_count || 0) + 1;
129
+ if (opts.failed) {
130
+ s.fail_count = (s.fail_count || 0) + 1;
131
+ s.strength = Math.max(0, (s.strength ?? DEFAULT_STRENGTH) - 0.10);
132
+ } else {
133
+ const cur = s.strength ?? DEFAULT_STRENGTH;
134
+ s.strength = Math.min(1.0, cur + 0.05 * (1.0 - cur));
135
+ }
136
+ s.last_used = new Date().toISOString();
137
+ writeSkillsIndex(idx, projectRoot);
138
+
139
+ setFrontmatterFields(getBrainDir(projectRoot), skillPath(name), {
140
+ strength: Math.round(s.strength * 1000) / 1000,
141
+ use_count: s.use_count,
142
+ fail_count: s.fail_count,
143
+ last_used: s.last_used,
144
+ });
145
+
146
+ return {
147
+ name: s.name,
148
+ use_count: s.use_count,
149
+ fail_count: s.fail_count,
150
+ strength: Math.round(s.strength * 1000) / 1000,
151
+ advertised: isAdvertised(s),
152
+ };
153
+ }
154
+
155
+ /**
156
+ * Export a stored skill into the host agent's native skill format so it becomes
157
+ * directly executable (CoALA Phase 4 host bridge). Brain stores/distills; the
158
+ * host executes.
159
+ *
160
+ * @param {string} [projectRoot] - Brain filesystem root
161
+ * @param {string} name - Skill name
162
+ * @param {string} [target='claude'] - 'claude' | 'gemini'
163
+ * @param {string} [destRoot=process.cwd()] - Host project root to write into
164
+ */
165
+ function exportSkill(projectRoot, name, target = 'claude', destRoot = process.cwd()) {
166
+ const src = showSkill(projectRoot, name);
167
+ if (src.error) return src;
168
+
169
+ const dests = {
170
+ claude: path.join(destRoot, '.claude', 'skills', slug(name)),
171
+ gemini: path.join(destRoot, '.gemini', 'skills', slug(name)),
172
+ };
173
+ const dir = dests[target];
174
+ if (!dir) return { error: `Unknown target: ${target} (use claude|gemini)` };
175
+
176
+ fs.mkdirSync(dir, { recursive: true });
177
+ const outPath = path.join(dir, 'SKILL.md');
178
+ fs.writeFileSync(outPath, src.content);
179
+ return { name: slug(name), target, path: outPath };
180
+ }
181
+
182
+ function removeSkill(projectRoot, name) {
183
+ const n = slug(name);
184
+ const dir = path.join(getBrainDir(projectRoot), SKILLS_DIR, n);
185
+ let removedDir = false;
186
+ try { fs.rmSync(dir, { recursive: true, force: true }); removedDir = true; } catch (_) { /* ignore */ }
187
+
188
+ const idx = readSkillsIndex(projectRoot);
189
+ const before = idx.skills.length;
190
+ idx.skills = idx.skills.filter((s) => s.name !== n);
191
+ writeSkillsIndex(idx, projectRoot);
192
+
193
+ return { name: n, removed: removedDir || before !== idx.skills.length };
194
+ }
195
+
196
+ module.exports = {
197
+ slug,
198
+ skillPath,
199
+ isAdvertised,
200
+ addSkill,
201
+ listSkills,
202
+ advertisedSummaries,
203
+ showSkill,
204
+ useSkill,
205
+ removeSkill,
206
+ exportSkill,
207
+ DEMOTE_FAIL_RATIO,
208
+ };