brain-memory 0.1.0-beta.1

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/scorer.js ADDED
@@ -0,0 +1,452 @@
1
+ /**
2
+ * Brain Memory — Scoring Utilities
3
+ *
4
+ * Computes effective memory strength after decay, relevance scoring,
5
+ * spreading activation, context matching, spaced reinforcement,
6
+ * and composite recall scores. Used by hooks and can be imported
7
+ * by external tools.
8
+ */
9
+
10
+ /**
11
+ * Compute the effective (decayed) strength of a memory.
12
+ *
13
+ * @param {number} baseStrength - Original strength (0.0-1.0)
14
+ * @param {number} decayRate - Daily decay factor (e.g., 0.995)
15
+ * @param {string|Date} lastAccessed - ISO timestamp of last access
16
+ * @returns {number} Effective strength after decay
17
+ */
18
+ function computeDecayedStrength(baseStrength, decayRate, lastAccessed) {
19
+ const lastDate = new Date(lastAccessed);
20
+ const now = new Date();
21
+ const daysElapsed = (now - lastDate) / (1000 * 60 * 60 * 24);
22
+ return baseStrength * Math.pow(decayRate, daysElapsed);
23
+ }
24
+
25
+ /**
26
+ * Compute recency bonus — linear decay over one year.
27
+ *
28
+ * @param {string|Date} lastAccessed - ISO timestamp of last access
29
+ * @returns {number} Recency bonus (0.0-1.0)
30
+ */
31
+ function computeRecencyBonus(lastAccessed) {
32
+ const lastDate = new Date(lastAccessed);
33
+ const now = new Date();
34
+ const daysElapsed = (now - lastDate) / (1000 * 60 * 60 * 24);
35
+ return Math.min(1.0, Math.max(0, 1 - daysElapsed / 365));
36
+ }
37
+
38
+ /**
39
+ * Compute the composite recall score for a memory (v4 formula).
40
+ *
41
+ * Weights: relevance 0.38, decayed_strength 0.18, recency 0.08,
42
+ * spreading_bonus 0.14, context_match 0.14, salience 0.08
43
+ *
44
+ * Falls back gracefully when newer fields are absent by
45
+ * renormalizing weights to available terms.
46
+ *
47
+ * @param {number} relevance - Query relevance (0.0-1.0)
48
+ * @param {number} decayedStrength - Effective strength after decay
49
+ * @param {number} recencyBonus - Recency bonus
50
+ * @param {Object} [extras] - Optional v2-v4 scoring components
51
+ * @param {number} [extras.spreadingBonus] - Spreading activation bonus (0.0-1.0)
52
+ * @param {number} [extras.contextMatch] - Context match score (0.0-1.0)
53
+ * @param {number} [extras.salience] - Emotional/motivational salience (0.0-1.0)
54
+ * @returns {number} Composite score
55
+ */
56
+ function computeRecallScore(relevance, decayedStrength, recencyBonus, extras = {}) {
57
+ // Full v4 weights
58
+ const weights = {
59
+ relevance: 0.38,
60
+ decayedStrength: 0.18,
61
+ recencyBonus: 0.08,
62
+ spreadingBonus: 0.14,
63
+ contextMatch: 0.14,
64
+ salience: 0.08,
65
+ };
66
+
67
+ const values = {
68
+ relevance,
69
+ decayedStrength,
70
+ recencyBonus,
71
+ };
72
+
73
+ // Add optional components if provided
74
+ if (extras.spreadingBonus != null) values.spreadingBonus = extras.spreadingBonus;
75
+ if (extras.contextMatch != null) values.contextMatch = extras.contextMatch;
76
+ if (extras.salience != null) values.salience = extras.salience;
77
+
78
+ // Renormalize weights to available terms
79
+ let totalWeight = 0;
80
+ for (const key of Object.keys(values)) {
81
+ totalWeight += weights[key];
82
+ }
83
+
84
+ let score = 0;
85
+ for (const key of Object.keys(values)) {
86
+ score += (weights[key] / totalWeight) * values[key];
87
+ }
88
+
89
+ return score;
90
+ }
91
+
92
+ // --- Phase 1: Spreading Activation ---
93
+
94
+ /**
95
+ * Compute spreading activation bonus for a memory reached via association links.
96
+ *
97
+ * Traverses associations up to maxDepth hops. For each path from a scored memory
98
+ * to a candidate, the bonus is: parent_score * link_weight * (0.5 ^ hop).
99
+ * Takes the maximum bonus across all paths.
100
+ *
101
+ * @param {string} memoryId - The candidate memory ID
102
+ * @param {Object[]} scoredMemories - Array of {id, score} from initial scoring
103
+ * @param {Object} associations - The associations graph
104
+ * @param {number} [maxDepth=2] - Maximum hop depth
105
+ * @returns {number} Spreading activation bonus (0.0-1.0)
106
+ */
107
+ function computeSpreadingActivation(memoryId, scoredMemories, associations, maxDepth = 2) {
108
+ if (!associations || !associations.edges) return 0;
109
+
110
+ const edges = associations.edges;
111
+ let maxBonus = 0;
112
+
113
+ for (const source of scoredMemories) {
114
+ if (source.id === memoryId) continue;
115
+ if (source.score <= 0.3) continue;
116
+
117
+ // BFS up to maxDepth hops
118
+ const visited = new Set([source.id]);
119
+ let frontier = [{ id: source.id, accumulator: source.score }];
120
+
121
+ for (let hop = 1; hop <= maxDepth; hop++) {
122
+ const nextFrontier = [];
123
+ const dampening = Math.pow(0.5, hop);
124
+ for (const node of frontier) {
125
+ const neighbors = edges[node.id];
126
+ if (!neighbors) continue;
127
+
128
+ for (const neighborId in neighbors) {
129
+ if (visited.has(neighborId)) continue;
130
+ visited.add(neighborId);
131
+
132
+ const bonus = node.accumulator * neighbors[neighborId].weight * dampening;
133
+
134
+ if (neighborId === memoryId) {
135
+ maxBonus = Math.max(maxBonus, bonus);
136
+ }
137
+
138
+ nextFrontier.push({ id: neighborId, accumulator: bonus });
139
+ }
140
+ }
141
+ frontier = nextFrontier;
142
+ }
143
+ }
144
+
145
+ return Math.min(1.0, maxBonus);
146
+ }
147
+
148
+ /**
149
+ * Discover candidate memories reachable via spreading activation that weren't
150
+ * in the initial result set.
151
+ *
152
+ * @param {Object[]} scoredMemories - Array of {id, score} from initial scoring
153
+ * @param {Object} associations - The associations graph
154
+ * @param {number} [maxDepth=2] - Maximum hop depth
155
+ * @param {number} [minBonus=0.05] - Minimum bonus to include
156
+ * @returns {Object[]} Array of {id, spreadingBonus} for new candidates
157
+ */
158
+ function discoverViaActivation(scoredMemories, associations, maxDepth = 2, minBonus = 0.05) {
159
+ if (!associations || !associations.edges) return [];
160
+
161
+ const scoredIds = new Set(scoredMemories.map((m) => m.id));
162
+ const candidates = {};
163
+
164
+ for (const source of scoredMemories) {
165
+ if (source.score <= 0.3) continue;
166
+
167
+ const visited = new Set([source.id]);
168
+ let frontier = [{ id: source.id, accumulator: source.score }];
169
+
170
+ for (let hop = 1; hop <= maxDepth; hop++) {
171
+ const nextFrontier = [];
172
+ for (const node of frontier) {
173
+ const neighbors = associations.edges[node.id];
174
+ if (!neighbors) continue;
175
+
176
+ for (const [neighborId, edge] of Object.entries(neighbors)) {
177
+ if (visited.has(neighborId)) continue;
178
+ visited.add(neighborId);
179
+
180
+ const bonus = node.accumulator * edge.weight * Math.pow(0.5, hop);
181
+ nextFrontier.push({ id: neighborId, accumulator: bonus });
182
+
183
+ if (!scoredIds.has(neighborId) && bonus >= minBonus) {
184
+ candidates[neighborId] = Math.max(candidates[neighborId] || 0, bonus);
185
+ }
186
+ }
187
+ }
188
+ frontier = nextFrontier;
189
+ }
190
+ }
191
+
192
+ return Object.entries(candidates).map(([id, spreadingBonus]) => ({
193
+ id,
194
+ spreadingBonus,
195
+ }));
196
+ }
197
+
198
+ // --- Phase 2: Context-Dependent Memory ---
199
+
200
+ /**
201
+ * Compute context match score between encoding context and recall context.
202
+ *
203
+ * Formula: 0.3 * (project matches) + 0.4 * jaccard(topics) + 0.3 * (task_type matches)
204
+ *
205
+ * @param {Object} encodingCtx - Encoding context {project, topics, task_type}
206
+ * @param {Object} recallCtx - Current recall context {project, topics, task_type}
207
+ * @returns {number} Context match score (0.0-1.0)
208
+ */
209
+ function computeContextMatch(encodingCtx, recallCtx) {
210
+ if (!encodingCtx || !recallCtx) return 0;
211
+
212
+ const projectMatch =
213
+ encodingCtx.project && recallCtx.project && encodingCtx.project === recallCtx.project
214
+ ? 1.0
215
+ : 0.0;
216
+
217
+ let topicJaccard = 0;
218
+ if (encodingCtx.topics && recallCtx.topics) {
219
+ const encTopics = new Set(encodingCtx.topics);
220
+ const recTopics = new Set(recallCtx.topics);
221
+ const intersection = [...encTopics].filter((t) => recTopics.has(t)).length;
222
+ const union = new Set([...encTopics, ...recTopics]).size;
223
+ topicJaccard = union > 0 ? intersection / union : 0;
224
+ }
225
+
226
+ const taskMatch =
227
+ encodingCtx.task_type && recallCtx.task_type && encodingCtx.task_type === recallCtx.task_type
228
+ ? 1.0
229
+ : 0.0;
230
+
231
+ return 0.3 * projectMatch + 0.4 * topicJaccard + 0.3 * taskMatch;
232
+ }
233
+
234
+ // --- Phase 2: Spaced Reinforcement ---
235
+
236
+ /**
237
+ * Compute spaced reinforcement boost for a recall event.
238
+ *
239
+ * Uses spacing effect: memories recalled after longer intervals get larger boosts.
240
+ * Uses diminishing returns: cramming produces smaller and smaller boosts.
241
+ *
242
+ * Formula:
243
+ * spacingMultiplier = min(3.0, 1.0 + log2(1 + daysSinceLastAccess))
244
+ * diminishingFactor = 1.0 / (1.0 + 0.1 * recallCount)
245
+ * boost = 0.05 * spacingMultiplier * diminishingFactor
246
+ *
247
+ * @param {number} daysSinceLastAccess - Days since last recall
248
+ * @param {number} recallCount - Total prior recall count
249
+ * @returns {number} Strength boost amount
250
+ */
251
+ function computeSpacedBoost(daysSinceLastAccess, recallCount) {
252
+ const spacingMultiplier = Math.min(3.0, 1.0 + Math.log2(1 + daysSinceLastAccess));
253
+ const diminishingFactor = 1.0 / (1.0 + 0.1 * recallCount);
254
+ return 0.05 * spacingMultiplier * diminishingFactor;
255
+ }
256
+
257
+ /**
258
+ * Compute the reinforced strength after a recall event (v2 — spaced reinforcement).
259
+ *
260
+ * @param {number} currentStrength - Current base strength
261
+ * @param {number} [daysSinceLastAccess] - Days since last recall (null for flat boost)
262
+ * @param {number} [recallCount] - Total prior recall count
263
+ * @returns {number} New base strength (capped at 1.0)
264
+ */
265
+ function reinforceStrength(currentStrength, daysSinceLastAccess, recallCount) {
266
+ // Backward-compatible: if no spacing info, use flat +0.05
267
+ if (daysSinceLastAccess == null || recallCount == null) {
268
+ return Math.min(1.0, currentStrength + 0.05);
269
+ }
270
+ const boost = computeSpacedBoost(daysSinceLastAccess, recallCount);
271
+ return Math.min(1.0, currentStrength + boost);
272
+ }
273
+
274
+ /**
275
+ * Improve a memory's decay rate after recall (it becomes more forgetting-resistant).
276
+ *
277
+ * Formula: new_decay_rate = decay_rate + 0.10 * (0.999 - decay_rate)
278
+ *
279
+ * @param {number} decayRate - Current daily decay rate
280
+ * @returns {number} Improved decay rate (approaches 0.999 asymptotically)
281
+ */
282
+ function improveDecayRate(decayRate) {
283
+ return decayRate + 0.10 * (0.999 - decayRate);
284
+ }
285
+
286
+ /**
287
+ * Compute consolidated strength from multiple source memories.
288
+ *
289
+ * @param {number[]} sourceStrengths - Strengths of source memories
290
+ * @returns {number} Consolidated strength (capped at 1.0)
291
+ */
292
+ function computeConsolidatedStrength(sourceStrengths) {
293
+ const maxStrength = Math.max(...sourceStrengths);
294
+ return Math.min(1.0, maxStrength + 0.15);
295
+ }
296
+
297
+ /**
298
+ * Batch-compute spreading activation bonuses for all memories in a single pass.
299
+ *
300
+ * Instead of calling computeSpreadingActivation per-memory (O(N*M*E)),
301
+ * this does one BFS per high-scoring source and collects bonuses for all
302
+ * reachable targets at once (O(M*E)).
303
+ *
304
+ * @param {Object[]} scoredMemories - Array of {id, score}
305
+ * @param {Object} associations - The associations graph
306
+ * @param {number} [maxDepth=2] - Maximum hop depth
307
+ * @returns {Object} Map of memoryId -> spreading activation bonus
308
+ */
309
+ function computeSpreadingActivationBatch(scoredMemories, associations, maxDepth = 2) {
310
+ if (!associations || !associations.edges) return {};
311
+
312
+ const edges = associations.edges;
313
+ const bonuses = {};
314
+
315
+ for (const source of scoredMemories) {
316
+ if (source.score <= 0.3) continue;
317
+
318
+ const visited = new Set([source.id]);
319
+ let frontier = [{ id: source.id, accumulator: source.score }];
320
+
321
+ for (let hop = 1; hop <= maxDepth; hop++) {
322
+ const nextFrontier = [];
323
+ const dampening = Math.pow(0.5, hop);
324
+ for (const node of frontier) {
325
+ const neighbors = edges[node.id];
326
+ if (!neighbors) continue;
327
+
328
+ for (const neighborId in neighbors) {
329
+ if (visited.has(neighborId)) continue;
330
+ visited.add(neighborId);
331
+
332
+ const bonus = node.accumulator * neighbors[neighborId].weight * dampening;
333
+ if (bonus > (bonuses[neighborId] || 0)) {
334
+ bonuses[neighborId] = bonus;
335
+ }
336
+
337
+ nextFrontier.push({ id: neighborId, accumulator: bonus });
338
+ }
339
+ }
340
+ frontier = nextFrontier;
341
+ }
342
+ }
343
+
344
+ // Cap at 1.0
345
+ for (const id in bonuses) {
346
+ if (bonuses[id] > 1.0) bonuses[id] = 1.0;
347
+ }
348
+
349
+ return bonuses;
350
+ }
351
+
352
+ /**
353
+ * Score and rank a list of memory entries for a given query.
354
+ *
355
+ * @param {Object[]} memories - Array of memory index entries
356
+ * @param {Function} relevanceFn - Function(memory) => relevance score (0.0-1.0)
357
+ * @param {Object} [options] - Optional scoring parameters
358
+ * @param {Object} [options.associations] - Associations graph for spreading activation
359
+ * @param {Object} [options.recallContext] - Current session context for context matching
360
+ * @returns {Object[]} Scored and sorted memories (highest first)
361
+ */
362
+ function rankMemories(memories, relevanceFn, options = {}) {
363
+ // First pass: compute base scores
364
+ const scored = memories.map((mem) => {
365
+ const decayedStrength = computeDecayedStrength(
366
+ mem.strength,
367
+ mem.decay_rate,
368
+ mem.last_accessed
369
+ );
370
+ const recencyBonus = computeRecencyBonus(mem.last_accessed);
371
+ const relevance = relevanceFn(mem);
372
+
373
+ return {
374
+ ...mem,
375
+ decayed_strength: decayedStrength,
376
+ recency_bonus: recencyBonus,
377
+ relevance: relevance,
378
+ spreading_bonus: 0,
379
+ context_match: 0,
380
+ };
381
+ });
382
+
383
+ // Second pass: spreading activation (batch — single traversal for all memories)
384
+ if (options.associations) {
385
+ const scoredSummary = scored.map((m) => ({
386
+ id: m.id,
387
+ score: 0.55 * m.relevance + 0.30 * m.decayed_strength + 0.15 * m.recency_bonus,
388
+ }));
389
+
390
+ const bonuses = computeSpreadingActivationBatch(
391
+ scoredSummary,
392
+ options.associations
393
+ );
394
+
395
+ for (const mem of scored) {
396
+ mem.spreading_bonus = bonuses[mem.id] || 0;
397
+ }
398
+ }
399
+
400
+ // Third pass: context matching
401
+ if (options.recallContext) {
402
+ for (const mem of scored) {
403
+ if (mem.encoding_context) {
404
+ mem.context_match = computeContextMatch(mem.encoding_context, options.recallContext);
405
+ }
406
+ }
407
+ }
408
+
409
+ // Final score
410
+ return scored
411
+ .map((mem) => {
412
+ const extras = {};
413
+ if (mem.spreading_bonus > 0) extras.spreadingBonus = mem.spreading_bonus;
414
+ if (mem.context_match > 0) extras.contextMatch = mem.context_match;
415
+ if (mem.salience != null) extras.salience = mem.salience;
416
+
417
+ const score = computeRecallScore(
418
+ mem.relevance,
419
+ mem.decayed_strength,
420
+ mem.recency_bonus,
421
+ extras
422
+ );
423
+
424
+ return {
425
+ ...mem,
426
+ decayed_strength: Math.round(mem.decayed_strength * 1000) / 1000,
427
+ recency_bonus: Math.round(mem.recency_bonus * 1000) / 1000,
428
+ relevance: Math.round(mem.relevance * 1000) / 1000,
429
+ spreading_bonus: Math.round(mem.spreading_bonus * 1000) / 1000,
430
+ context_match: Math.round(mem.context_match * 1000) / 1000,
431
+ score: Math.round(score * 1000) / 1000,
432
+ };
433
+ })
434
+ .sort((a, b) => b.score - a.score);
435
+ }
436
+
437
+ module.exports = {
438
+ computeDecayedStrength,
439
+ computeRecencyBonus,
440
+ computeRecallScore,
441
+ reinforceStrength,
442
+ computeConsolidatedStrength,
443
+ rankMemories,
444
+ // Phase 1: Spreading Activation
445
+ computeSpreadingActivation,
446
+ computeSpreadingActivationBatch,
447
+ discoverViaActivation,
448
+ // Phase 2: Context & Spaced Reinforcement
449
+ computeContextMatch,
450
+ computeSpacedBoost,
451
+ improveDecayRate,
452
+ };
@@ -0,0 +1,82 @@
1
+ {
2
+ "version": 2,
3
+ "description": "Default brain category structure. Categories and subcategories are created on-demand as memories are stored.",
4
+ "top_categories": [
5
+ {
6
+ "name": "professional",
7
+ "description": "Work, career, technical skills, companies, projects",
8
+ "suggested_subcategories": ["companies", "skills", "projects", "decisions", "career"]
9
+ },
10
+ {
11
+ "name": "personal",
12
+ "description": "Education, health, hobbies, goals, self-improvement",
13
+ "suggested_subcategories": ["education", "health", "hobbies", "goals", "finance"]
14
+ },
15
+ {
16
+ "name": "social",
17
+ "description": "Communities, networks, collaborations, events",
18
+ "suggested_subcategories": ["communities", "networks", "events", "collaborations"]
19
+ },
20
+ {
21
+ "name": "family",
22
+ "description": "Family relationships, events, traditions, planning",
23
+ "suggested_subcategories": ["relationships", "events", "traditions", "planning"]
24
+ }
25
+ ],
26
+ "memory_types": [
27
+ "decision",
28
+ "learning",
29
+ "experience",
30
+ "insight",
31
+ "observation",
32
+ "goal",
33
+ "preference",
34
+ "relationship"
35
+ ],
36
+ "strength_presets": {
37
+ "decision": 0.85,
38
+ "learning": 0.70,
39
+ "experience": 0.75,
40
+ "insight": 0.90,
41
+ "observation": 0.40,
42
+ "goal": 0.80,
43
+ "preference": 0.60,
44
+ "relationship": 0.70
45
+ },
46
+ "decay_presets": {
47
+ "decision": 0.995,
48
+ "learning": 0.990,
49
+ "experience": 0.985,
50
+ "insight": 0.997,
51
+ "observation": 0.950,
52
+ "goal": 0.993,
53
+ "preference": 0.998,
54
+ "relationship": 0.997
55
+ },
56
+ "cognitive_decay_profiles": {
57
+ "episodic": {
58
+ "strength_modifier": 0.10,
59
+ "decay_modifier": 0.995,
60
+ "description": "Tied to a specific event/time. Higher initial strength but faster decay."
61
+ },
62
+ "semantic": {
63
+ "strength_modifier": 0.0,
64
+ "decay_modifier": 1.0,
65
+ "description": "Abstracted knowledge, context-free. Uses default decay rate."
66
+ },
67
+ "procedural": {
68
+ "strength_modifier": -0.10,
69
+ "decay_modifier": 1.003,
70
+ "description": "How-to workflows and skills. Lower initial strength but extremely slow decay once established."
71
+ }
72
+ },
73
+ "association_config": {
74
+ "co_retrieval_boost": 0.10,
75
+ "link_decay_rate": 0.998,
76
+ "link_prune_threshold": 0.05,
77
+ "spreading_activation_depth": 2,
78
+ "spreading_activation_decay": 0.5,
79
+ "auto_link_initial_weight": 0.10,
80
+ "manual_link_initial_weight": 0.20
81
+ }
82
+ }