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/LICENSE +21 -0
- package/README.md +466 -0
- package/bin/install.js +361 -0
- package/commands/brain/consolidate.md +153 -0
- package/commands/brain/explore.md +79 -0
- package/commands/brain/forget.md +115 -0
- package/commands/brain/init.md +157 -0
- package/commands/brain/memorize.md +176 -0
- package/commands/brain/remember.md +176 -0
- package/commands/brain/review.md +130 -0
- package/commands/brain/sleep.md +535 -0
- package/commands/brain/status.md +122 -0
- package/commands/brain/sunshine.md +337 -0
- package/hooks/session-end.md +48 -0
- package/hooks/session-start.md +48 -0
- package/package.json +46 -0
- package/prompts/claude.md +75 -0
- package/prompts/gemini.md +76 -0
- package/prompts/openai.md +76 -0
- package/src/index-manager.js +401 -0
- package/src/scorer.js +452 -0
- package/templates/default-categories.json +82 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Brain Memory System
|
|
2
|
+
|
|
3
|
+
This project uses the **Brain Memory** plugin — a hierarchical, file-system-based memory system that mimics human cognition with neuroscience-inspired mechanisms including associative networks, spreading activation, context-dependent recall, spaced reinforcement, and cognitive memory types.
|
|
4
|
+
|
|
5
|
+
## Memory Location
|
|
6
|
+
|
|
7
|
+
All memories are stored in `.brain/` with a deep nested directory structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
|
|
8
|
+
|
|
9
|
+
## How It Works
|
|
10
|
+
|
|
11
|
+
### Memory Format
|
|
12
|
+
Each memory is a Markdown file with YAML frontmatter containing: `id`, `type`, `cognitive_type` (episodic/semantic/procedural), `created`, `last_accessed`, `access_count`, `recall_history`, `strength` (0.0-1.0), `decay_rate` (per day), `salience` (0.0-1.0), `confidence` (0.0-1.0), `tags`, `related` memory IDs, `source`, and `encoding_context`.
|
|
13
|
+
|
|
14
|
+
### Strength & Decay Model
|
|
15
|
+
- Memories have a base `strength` set at creation based on their impact/type/cognitive type
|
|
16
|
+
- Strength decays over time: `effective = strength * (decay_rate ^ days_since_access)`
|
|
17
|
+
- Recalled memories get **stronger** via spaced reinforcement — the longer since last recall, the bigger the boost
|
|
18
|
+
- Memories become progressively more forgetting-resistant with each recall (decay_rate improves)
|
|
19
|
+
- Weak memories can be consolidated into stronger combined memories
|
|
20
|
+
- During sleep, global synaptic homeostasis prevents strength inflation
|
|
21
|
+
|
|
22
|
+
### Cognitive Types
|
|
23
|
+
- **Episodic** — Event-specific memories. Higher initial strength, faster decay. The details fade but lessons persist.
|
|
24
|
+
- **Semantic** — Abstracted knowledge. Default decay. Stable long-term storage.
|
|
25
|
+
- **Procedural** — Skills and workflows. Lower initial strength but extremely slow decay once established.
|
|
26
|
+
|
|
27
|
+
### Memory Types & Default Strengths
|
|
28
|
+
| Type | Strength | Decay/day | Description |
|
|
29
|
+
|------|----------|-----------|-------------|
|
|
30
|
+
| decision | 0.85 | 0.995 | Choices made and rationale |
|
|
31
|
+
| insight | 0.90 | 0.997 | Deep realizations, patterns |
|
|
32
|
+
| goal | 0.80 | 0.993 | Objectives and aspirations |
|
|
33
|
+
| experience | 0.75 | 0.985 | Notable events or processes |
|
|
34
|
+
| learning | 0.70 | 0.990 | New knowledge acquired |
|
|
35
|
+
| relationship | 0.70 | 0.997 | Connections between entities |
|
|
36
|
+
| preference | 0.60 | 0.998 | User preferences and style |
|
|
37
|
+
| observation | 0.40 | 0.950 | Casual facts or notices |
|
|
38
|
+
|
|
39
|
+
### Associative Network
|
|
40
|
+
Memories are connected via weighted edges in `.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
|
|
41
|
+
|
|
42
|
+
### Context-Dependent Recall
|
|
43
|
+
Memories store their encoding context (project, topics, task type). During recall, memories encoded in a similar context to the current session are scored higher — matching how human memory works better when recall context matches encoding context.
|
|
44
|
+
|
|
45
|
+
### Salience & Confidence
|
|
46
|
+
- **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
|
|
47
|
+
- **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
|
|
48
|
+
|
|
49
|
+
## Available Commands
|
|
50
|
+
|
|
51
|
+
Commands are available via `/brain:` prefix:
|
|
52
|
+
- `/brain:init` — Initialize the brain structure
|
|
53
|
+
- `/brain:memorize [topic]` — Store memories from current context
|
|
54
|
+
- `/brain:remember [query]` — Recall relevant memories with spreading activation and context matching
|
|
55
|
+
- `/brain:review [scope]` — Spaced repetition review session for due memories
|
|
56
|
+
- `/brain:explore [category]` — Browse the brain hierarchy
|
|
57
|
+
- `/brain:consolidate [scope]` — Merge related weak memories into stronger ones
|
|
58
|
+
- `/brain:forget [target]` — Decay or archive memories
|
|
59
|
+
- `/brain:sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
|
|
60
|
+
- `/brain:sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
|
|
61
|
+
- `/brain:status` — Dashboard with brain health overview
|
|
62
|
+
|
|
63
|
+
## Auto-Memorize Guidance
|
|
64
|
+
|
|
65
|
+
At the end of significant sessions, consider suggesting `/brain:memorize` to the user if important decisions, learnings, or insights occurred during the conversation. Do NOT automatically memorize without the user's awareness.
|
|
66
|
+
|
|
67
|
+
## When Recalling Memories
|
|
68
|
+
|
|
69
|
+
When the user asks you to "remember" something, or when context from past sessions would be helpful:
|
|
70
|
+
1. Check `.brain/index.json` for relevant memories
|
|
71
|
+
2. Load `.brain/associations.json` for spreading activation
|
|
72
|
+
3. Score by v4 formula: `0.38*relevance + 0.18*decayed_strength + 0.08*recency + 0.14*spreading_bonus + 0.14*context_match + 0.08*salience`
|
|
73
|
+
4. Return strong individual matches or synthesize from multiple related memories
|
|
74
|
+
5. Apply spaced reinforcement (spacing-aware boost) and improve decay rate
|
|
75
|
+
6. Strengthen Hebbian links between co-retrieved memories
|
|
76
|
+
7. If no active matches, search the archive (`.brain/_archived/`)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
# Brain Memory System
|
|
2
|
+
|
|
3
|
+
This project uses the **Brain Memory** plugin — a hierarchical, file-system-based memory system that mimics human cognition with neuroscience-inspired mechanisms including associative networks, spreading activation, context-dependent recall, spaced reinforcement, and cognitive memory types.
|
|
4
|
+
|
|
5
|
+
## Memory Location
|
|
6
|
+
|
|
7
|
+
All memories are stored in `.brain/` with a deep nested directory structure organized by life domains (professional, personal, social, family) with on-demand subcategories.
|
|
8
|
+
|
|
9
|
+
## How It Works
|
|
10
|
+
|
|
11
|
+
### Memory Format
|
|
12
|
+
Each memory is a Markdown file with YAML frontmatter containing: `id`, `type`, `cognitive_type` (episodic/semantic/procedural), `created`, `last_accessed`, `access_count`, `recall_history`, `strength` (0.0-1.0), `decay_rate` (per day), `salience` (0.0-1.0), `confidence` (0.0-1.0), `tags`, `related` memory IDs, `source`, and `encoding_context`.
|
|
13
|
+
|
|
14
|
+
### Strength & Decay Model
|
|
15
|
+
- Memories have a base `strength` set at creation based on their impact/type/cognitive type
|
|
16
|
+
- Strength decays over time: `effective = strength * (decay_rate ^ days_since_access)`
|
|
17
|
+
- Recalled memories get **stronger** via spaced reinforcement — the longer since last recall, the bigger the boost
|
|
18
|
+
- Memories become progressively more forgetting-resistant with each recall (decay_rate improves)
|
|
19
|
+
- Weak memories can be consolidated into stronger combined memories
|
|
20
|
+
- During sleep, global synaptic homeostasis prevents strength inflation
|
|
21
|
+
|
|
22
|
+
### Cognitive Types
|
|
23
|
+
- **Episodic** — Event-specific memories. Higher initial strength, faster decay. The details fade but lessons persist.
|
|
24
|
+
- **Semantic** — Abstracted knowledge. Default decay. Stable long-term storage.
|
|
25
|
+
- **Procedural** — Skills and workflows. Lower initial strength but extremely slow decay once established.
|
|
26
|
+
|
|
27
|
+
### Memory Types & Default Strengths
|
|
28
|
+
| Type | Strength | Decay/day | Description |
|
|
29
|
+
|------|----------|-----------|-------------|
|
|
30
|
+
| decision | 0.85 | 0.995 | Choices made and rationale |
|
|
31
|
+
| insight | 0.90 | 0.997 | Deep realizations, patterns |
|
|
32
|
+
| goal | 0.80 | 0.993 | Objectives and aspirations |
|
|
33
|
+
| experience | 0.75 | 0.985 | Notable events or processes |
|
|
34
|
+
| learning | 0.70 | 0.990 | New knowledge acquired |
|
|
35
|
+
| relationship | 0.70 | 0.997 | Connections between entities |
|
|
36
|
+
| preference | 0.60 | 0.998 | User preferences and style |
|
|
37
|
+
| observation | 0.40 | 0.950 | Casual facts or notices |
|
|
38
|
+
|
|
39
|
+
### Associative Network
|
|
40
|
+
Memories are connected via weighted edges in `.brain/associations.json`. When you recall memory A, **spreading activation** automatically surfaces related memories B and C — just like how the brain activates linked neurons. Links are strengthened through **Hebbian learning**: memories recalled together become more tightly connected over time.
|
|
41
|
+
|
|
42
|
+
### Context-Dependent Recall
|
|
43
|
+
Memories store their encoding context (project, topics, task type). During recall, memories encoded in a similar context to the current session are scored higher — matching how human memory works better when recall context matches encoding context.
|
|
44
|
+
|
|
45
|
+
### Salience & Confidence
|
|
46
|
+
- **Salience** (0.0-1.0): Emotional/motivational significance. High-salience memories (>= 0.7) are never auto-pruned.
|
|
47
|
+
- **Confidence** (0.0-1.0): Epistemic certainty. Low-confidence memories are flagged during recall.
|
|
48
|
+
|
|
49
|
+
## Available Commands
|
|
50
|
+
|
|
51
|
+
Brain skills are available via `/brain-` prefix:
|
|
52
|
+
- `/brain-init` — Initialize the brain structure
|
|
53
|
+
- `/brain-memorize [topic]` — Store memories from current context
|
|
54
|
+
- `/brain-remember [query]` — Recall relevant memories with spreading activation and context matching
|
|
55
|
+
- `/brain-review [scope]` — Spaced repetition review session for due memories
|
|
56
|
+
- `/brain-explore [category]` — Browse the brain hierarchy
|
|
57
|
+
- `/brain-consolidate [scope]` — Merge related weak memories into stronger ones
|
|
58
|
+
- `/brain-forget [target]` — Decay or archive memories
|
|
59
|
+
- `/brain-sunshine [target]` — Deep forensic erasure — trace and remove all references to a memory
|
|
60
|
+
- `/brain-sleep [scope]` — Full maintenance cycle: replay, synaptic homeostasis, knowledge propagation, semantic crystallization, reorganize, consolidate, prune, REM dreaming, and expertise detection
|
|
61
|
+
- `/brain-status` — Dashboard with brain health overview
|
|
62
|
+
|
|
63
|
+
## Auto-Memorize Guidance
|
|
64
|
+
|
|
65
|
+
At the end of significant sessions, consider suggesting `/brain-memorize` to the user if important decisions, learnings, or insights occurred during the conversation. Do NOT automatically memorize without the user's awareness.
|
|
66
|
+
|
|
67
|
+
## When Recalling Memories
|
|
68
|
+
|
|
69
|
+
When the user asks you to "remember" something, or when context from past sessions would be helpful:
|
|
70
|
+
1. Check `.brain/index.json` for relevant memories
|
|
71
|
+
2. Load `.brain/associations.json` for spreading activation
|
|
72
|
+
3. Score by v4 formula: `0.38*relevance + 0.18*decayed_strength + 0.08*recency + 0.14*spreading_bonus + 0.14*context_match + 0.08*salience`
|
|
73
|
+
4. Return strong individual matches or synthesize from multiple related memories
|
|
74
|
+
5. Apply spaced reinforcement (spacing-aware boost) and improve decay rate
|
|
75
|
+
6. Strengthen Hebbian links between co-retrieved memories
|
|
76
|
+
7. If no active matches, search the archive (`.brain/_archived/`)
|
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brain Memory — Index Manager
|
|
3
|
+
*
|
|
4
|
+
* Utilities for reading, updating, and maintaining the .brain/index.json
|
|
5
|
+
* file. Used by hooks and external integrations.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
|
|
11
|
+
const DEFAULT_BRAIN_DIR = '.brain';
|
|
12
|
+
const INDEX_FILE = 'index.json';
|
|
13
|
+
const ASSOCIATIONS_FILE = 'associations.json';
|
|
14
|
+
const CONTEXTS_FILE = 'contexts.json';
|
|
15
|
+
const REVIEW_QUEUE_FILE = 'review-queue.json';
|
|
16
|
+
const ARCHIVE_INDEX_FILE = '_archived/index.json';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Resolve the brain directory path.
|
|
20
|
+
*
|
|
21
|
+
* @param {string} [projectRoot] - Project root directory (defaults to cwd)
|
|
22
|
+
* @returns {string} Absolute path to .brain/
|
|
23
|
+
*/
|
|
24
|
+
function getBrainDir(projectRoot) {
|
|
25
|
+
return path.join(projectRoot || process.cwd(), DEFAULT_BRAIN_DIR);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Read and parse the brain index.
|
|
30
|
+
*
|
|
31
|
+
* @param {string} [projectRoot] - Project root directory
|
|
32
|
+
* @returns {Object|null} Parsed index or null if not found
|
|
33
|
+
*/
|
|
34
|
+
function readIndex(projectRoot) {
|
|
35
|
+
const indexPath = path.join(getBrainDir(projectRoot), INDEX_FILE);
|
|
36
|
+
if (!fs.existsSync(indexPath)) return null;
|
|
37
|
+
return JSON.parse(fs.readFileSync(indexPath, 'utf-8'));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Write the brain index back to disk.
|
|
42
|
+
*
|
|
43
|
+
* @param {Object} index - The index object to write
|
|
44
|
+
* @param {string} [projectRoot] - Project root directory
|
|
45
|
+
*/
|
|
46
|
+
function writeIndex(index, projectRoot) {
|
|
47
|
+
const indexPath = path.join(getBrainDir(projectRoot), INDEX_FILE);
|
|
48
|
+
index.last_updated = new Date().toISOString();
|
|
49
|
+
fs.writeFileSync(indexPath, JSON.stringify(index, null, 2) + '\n');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Add a memory entry to the index.
|
|
54
|
+
*
|
|
55
|
+
* @param {Object} index - The index object
|
|
56
|
+
* @param {string} id - Memory ID
|
|
57
|
+
* @param {Object} entry - Memory index entry
|
|
58
|
+
* @returns {Object} Updated index
|
|
59
|
+
*/
|
|
60
|
+
function addMemory(index, id, entry) {
|
|
61
|
+
index.memories[id] = entry;
|
|
62
|
+
index.memory_count = Object.keys(index.memories).length;
|
|
63
|
+
return index;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Remove a memory entry from the index.
|
|
68
|
+
*
|
|
69
|
+
* @param {Object} index - The index object
|
|
70
|
+
* @param {string} id - Memory ID to remove
|
|
71
|
+
* @returns {Object} Updated index
|
|
72
|
+
*/
|
|
73
|
+
function removeMemory(index, id) {
|
|
74
|
+
delete index.memories[id];
|
|
75
|
+
index.memory_count = Object.keys(index.memories).length;
|
|
76
|
+
return index;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Update a memory entry in the index (partial update).
|
|
81
|
+
*
|
|
82
|
+
* @param {Object} index - The index object
|
|
83
|
+
* @param {string} id - Memory ID
|
|
84
|
+
* @param {Object} updates - Fields to update
|
|
85
|
+
* @returns {Object} Updated index
|
|
86
|
+
*/
|
|
87
|
+
function updateMemory(index, id, updates) {
|
|
88
|
+
if (index.memories[id]) {
|
|
89
|
+
Object.assign(index.memories[id], updates);
|
|
90
|
+
}
|
|
91
|
+
return index;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Generate a new memory ID.
|
|
96
|
+
*
|
|
97
|
+
* @returns {string} Memory ID in format mem_YYYYMMDD_<6-hex>
|
|
98
|
+
*/
|
|
99
|
+
function generateId() {
|
|
100
|
+
const now = new Date();
|
|
101
|
+
const date = now.toISOString().slice(0, 10).replace(/-/g, '');
|
|
102
|
+
const hex = Math.random().toString(16).slice(2, 8);
|
|
103
|
+
return `mem_${date}_${hex}`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Read a _meta.json file from a brain subdirectory.
|
|
108
|
+
*
|
|
109
|
+
* @param {string} categoryPath - Relative path within .brain/
|
|
110
|
+
* @param {string} [projectRoot] - Project root directory
|
|
111
|
+
* @returns {Object|null} Parsed meta or null
|
|
112
|
+
*/
|
|
113
|
+
function readMeta(categoryPath, projectRoot) {
|
|
114
|
+
const metaPath = path.join(getBrainDir(projectRoot), categoryPath, '_meta.json');
|
|
115
|
+
if (!fs.existsSync(metaPath)) return null;
|
|
116
|
+
return JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Write a _meta.json file to a brain subdirectory.
|
|
121
|
+
*
|
|
122
|
+
* @param {string} categoryPath - Relative path within .brain/
|
|
123
|
+
* @param {Object} meta - Meta object to write
|
|
124
|
+
* @param {string} [projectRoot] - Project root directory
|
|
125
|
+
*/
|
|
126
|
+
function writeMeta(categoryPath, meta, projectRoot) {
|
|
127
|
+
const metaPath = path.join(getBrainDir(projectRoot), categoryPath, '_meta.json');
|
|
128
|
+
fs.mkdirSync(path.dirname(metaPath), { recursive: true });
|
|
129
|
+
fs.writeFileSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Get all memories grouped by category.
|
|
134
|
+
*
|
|
135
|
+
* @param {Object} index - The index object
|
|
136
|
+
* @returns {Object} Map of category => [memory entries]
|
|
137
|
+
*/
|
|
138
|
+
function groupByCategory(index) {
|
|
139
|
+
const groups = {};
|
|
140
|
+
for (const [id, entry] of Object.entries(index.memories)) {
|
|
141
|
+
const category = entry.path.split('/')[0];
|
|
142
|
+
if (!groups[category]) groups[category] = [];
|
|
143
|
+
groups[category].push({ id, ...entry });
|
|
144
|
+
}
|
|
145
|
+
return groups;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// --- Associations (Phase 1: Associative Network) ---
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Read the associations graph.
|
|
152
|
+
*
|
|
153
|
+
* @param {string} [projectRoot] - Project root directory
|
|
154
|
+
* @returns {Object|null} Parsed associations or null
|
|
155
|
+
*/
|
|
156
|
+
function readAssociations(projectRoot) {
|
|
157
|
+
const filePath = path.join(getBrainDir(projectRoot), ASSOCIATIONS_FILE);
|
|
158
|
+
if (!fs.existsSync(filePath)) return null;
|
|
159
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Write the associations graph to disk.
|
|
164
|
+
*
|
|
165
|
+
* @param {Object} associations - The associations object
|
|
166
|
+
* @param {string} [projectRoot] - Project root directory
|
|
167
|
+
*/
|
|
168
|
+
function writeAssociations(associations, projectRoot) {
|
|
169
|
+
const filePath = path.join(getBrainDir(projectRoot), ASSOCIATIONS_FILE);
|
|
170
|
+
fs.writeFileSync(filePath, JSON.stringify(associations, null, 2) + '\n');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Reinforce (or create) an edge between two memories.
|
|
175
|
+
*
|
|
176
|
+
* @param {Object} associations - The associations object
|
|
177
|
+
* @param {string} idA - First memory ID
|
|
178
|
+
* @param {string} idB - Second memory ID
|
|
179
|
+
* @param {string} origin - Origin type (manual, tag_overlap, co_retrieval, propagation, creative)
|
|
180
|
+
* @param {number} [initialWeight=0.20] - Weight for new edges
|
|
181
|
+
* @returns {Object} Updated associations
|
|
182
|
+
*/
|
|
183
|
+
function reinforceEdge(associations, idA, idB, origin, initialWeight = 0.20) {
|
|
184
|
+
if (idA === idB) return associations;
|
|
185
|
+
if (!associations.edges) associations.edges = {};
|
|
186
|
+
|
|
187
|
+
// Ensure bidirectional entries
|
|
188
|
+
for (const [src, dst] of [[idA, idB], [idB, idA]]) {
|
|
189
|
+
if (!associations.edges[src]) associations.edges[src] = {};
|
|
190
|
+
const edge = associations.edges[src][dst];
|
|
191
|
+
if (edge) {
|
|
192
|
+
// Hebbian reinforcement: new_weight = min(1.0, weight + 0.10 * (1.0 - weight))
|
|
193
|
+
edge.weight = Math.min(1.0, edge.weight + 0.10 * (1.0 - edge.weight));
|
|
194
|
+
edge.co_retrievals = (edge.co_retrievals || 0) + 1;
|
|
195
|
+
edge.last_activated = new Date().toISOString();
|
|
196
|
+
} else {
|
|
197
|
+
associations.edges[src][dst] = {
|
|
198
|
+
weight: initialWeight,
|
|
199
|
+
co_retrievals: 0,
|
|
200
|
+
last_activated: new Date().toISOString(),
|
|
201
|
+
origin: origin,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return associations;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Get all neighbors of a memory with their edge weights.
|
|
210
|
+
*
|
|
211
|
+
* @param {Object} associations - The associations object
|
|
212
|
+
* @param {string} id - Memory ID
|
|
213
|
+
* @returns {Object[]} Array of {id, weight, co_retrievals, last_activated, origin}
|
|
214
|
+
*/
|
|
215
|
+
function getNeighbors(associations, id) {
|
|
216
|
+
if (!associations || !associations.edges || !associations.edges[id]) return [];
|
|
217
|
+
return Object.entries(associations.edges[id]).map(([neighborId, edge]) => ({
|
|
218
|
+
id: neighborId,
|
|
219
|
+
...edge,
|
|
220
|
+
}));
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Apply time-based decay to all association weights and prune weak links.
|
|
225
|
+
*
|
|
226
|
+
* @param {Object} associations - The associations object
|
|
227
|
+
* @param {number} [decayBase=0.998] - Daily decay base
|
|
228
|
+
* @param {number} [pruneThreshold=0.05] - Prune links below this weight
|
|
229
|
+
* @returns {Object} Updated associations with decayed/pruned edges
|
|
230
|
+
*/
|
|
231
|
+
function decayAssociations(associations, decayBase = 0.998, pruneThreshold = 0.05) {
|
|
232
|
+
if (!associations || !associations.edges) return associations;
|
|
233
|
+
const now = new Date();
|
|
234
|
+
|
|
235
|
+
for (const srcId of Object.keys(associations.edges)) {
|
|
236
|
+
for (const dstId of Object.keys(associations.edges[srcId])) {
|
|
237
|
+
const edge = associations.edges[srcId][dstId];
|
|
238
|
+
const lastActivated = new Date(edge.last_activated);
|
|
239
|
+
const daysSince = (now - lastActivated) / (1000 * 60 * 60 * 24);
|
|
240
|
+
edge.weight = edge.weight * Math.pow(decayBase, daysSince);
|
|
241
|
+
|
|
242
|
+
if (edge.weight < pruneThreshold) {
|
|
243
|
+
delete associations.edges[srcId][dstId];
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
// Clean up empty neighbor maps
|
|
247
|
+
if (Object.keys(associations.edges[srcId]).length === 0) {
|
|
248
|
+
delete associations.edges[srcId];
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return associations;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// --- Contexts (Phase 2: Context-Dependent Memory) ---
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Read the contexts file.
|
|
258
|
+
*
|
|
259
|
+
* @param {string} [projectRoot] - Project root directory
|
|
260
|
+
* @returns {Object|null} Parsed contexts or null
|
|
261
|
+
*/
|
|
262
|
+
function readContexts(projectRoot) {
|
|
263
|
+
const filePath = path.join(getBrainDir(projectRoot), CONTEXTS_FILE);
|
|
264
|
+
if (!fs.existsSync(filePath)) return null;
|
|
265
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* Write the contexts file to disk.
|
|
270
|
+
*
|
|
271
|
+
* @param {Object} contexts - The contexts object
|
|
272
|
+
* @param {string} [projectRoot] - Project root directory
|
|
273
|
+
*/
|
|
274
|
+
function writeContexts(contexts, projectRoot) {
|
|
275
|
+
const filePath = path.join(getBrainDir(projectRoot), CONTEXTS_FILE);
|
|
276
|
+
fs.writeFileSync(filePath, JSON.stringify(contexts, null, 2) + '\n');
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// --- Review Queue (Phase 4: Spaced Repetition) ---
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* Read the review queue.
|
|
283
|
+
*
|
|
284
|
+
* @param {string} [projectRoot] - Project root directory
|
|
285
|
+
* @returns {Object|null} Parsed review queue or null
|
|
286
|
+
*/
|
|
287
|
+
function readReviewQueue(projectRoot) {
|
|
288
|
+
const filePath = path.join(getBrainDir(projectRoot), REVIEW_QUEUE_FILE);
|
|
289
|
+
if (!fs.existsSync(filePath)) return null;
|
|
290
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* Write the review queue to disk.
|
|
295
|
+
*
|
|
296
|
+
* @param {Object} queue - The review queue object
|
|
297
|
+
* @param {string} [projectRoot] - Project root directory
|
|
298
|
+
*/
|
|
299
|
+
function writeReviewQueue(queue, projectRoot) {
|
|
300
|
+
const filePath = path.join(getBrainDir(projectRoot), REVIEW_QUEUE_FILE);
|
|
301
|
+
fs.writeFileSync(filePath, JSON.stringify(queue, null, 2) + '\n');
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// --- Archive Index (Phase 4: Archive Search) ---
|
|
305
|
+
|
|
306
|
+
/**
|
|
307
|
+
* Read the archive index.
|
|
308
|
+
*
|
|
309
|
+
* @param {string} [projectRoot] - Project root directory
|
|
310
|
+
* @returns {Object|null} Parsed archive index or null
|
|
311
|
+
*/
|
|
312
|
+
function readArchiveIndex(projectRoot) {
|
|
313
|
+
const filePath = path.join(getBrainDir(projectRoot), ARCHIVE_INDEX_FILE);
|
|
314
|
+
if (!fs.existsSync(filePath)) return null;
|
|
315
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Write the archive index to disk.
|
|
320
|
+
*
|
|
321
|
+
* @param {Object} archiveIndex - The archive index object
|
|
322
|
+
* @param {string} [projectRoot] - Project root directory
|
|
323
|
+
*/
|
|
324
|
+
function writeArchiveIndex(archiveIndex, projectRoot) {
|
|
325
|
+
const filePath = path.join(getBrainDir(projectRoot), ARCHIVE_INDEX_FILE);
|
|
326
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
327
|
+
fs.writeFileSync(filePath, JSON.stringify(archiveIndex, null, 2) + '\n');
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Remove ALL association edges involving a memory (both directions).
|
|
332
|
+
*
|
|
333
|
+
* Deletes the memory's own neighbor map and removes it from every other
|
|
334
|
+
* memory's neighbor map. Cleans up empty neighbor maps afterward.
|
|
335
|
+
*
|
|
336
|
+
* @param {Object} associations - The associations object
|
|
337
|
+
* @param {string} memoryId - Memory ID to remove
|
|
338
|
+
* @returns {Object} Updated associations
|
|
339
|
+
*/
|
|
340
|
+
function removeEdgesForMemory(associations, memoryId) {
|
|
341
|
+
if (!associations || !associations.edges) return associations;
|
|
342
|
+
|
|
343
|
+
// Remove the memory's own outgoing edges
|
|
344
|
+
delete associations.edges[memoryId];
|
|
345
|
+
|
|
346
|
+
// Remove all incoming edges from other memories
|
|
347
|
+
for (const srcId of Object.keys(associations.edges)) {
|
|
348
|
+
delete associations.edges[srcId][memoryId];
|
|
349
|
+
// Clean up empty neighbor maps
|
|
350
|
+
if (Object.keys(associations.edges[srcId]).length === 0) {
|
|
351
|
+
delete associations.edges[srcId];
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return associations;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Remove a memory from the review queue.
|
|
360
|
+
*
|
|
361
|
+
* Filters out any items matching the given memory ID.
|
|
362
|
+
*
|
|
363
|
+
* @param {Object} queue - The review queue object (with items array)
|
|
364
|
+
* @param {string} memoryId - Memory ID to remove
|
|
365
|
+
* @returns {Object} Updated queue
|
|
366
|
+
*/
|
|
367
|
+
function removeFromReviewQueue(queue, memoryId) {
|
|
368
|
+
if (!queue || !Array.isArray(queue.items)) return queue;
|
|
369
|
+
queue.items = queue.items.filter((item) => item.memory_id !== memoryId);
|
|
370
|
+
return queue;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
module.exports = {
|
|
374
|
+
getBrainDir,
|
|
375
|
+
readIndex,
|
|
376
|
+
writeIndex,
|
|
377
|
+
addMemory,
|
|
378
|
+
removeMemory,
|
|
379
|
+
updateMemory,
|
|
380
|
+
generateId,
|
|
381
|
+
readMeta,
|
|
382
|
+
writeMeta,
|
|
383
|
+
groupByCategory,
|
|
384
|
+
// Phase 1: Associative Network
|
|
385
|
+
readAssociations,
|
|
386
|
+
writeAssociations,
|
|
387
|
+
reinforceEdge,
|
|
388
|
+
getNeighbors,
|
|
389
|
+
decayAssociations,
|
|
390
|
+
// Phase 2: Context-Dependent Memory
|
|
391
|
+
readContexts,
|
|
392
|
+
writeContexts,
|
|
393
|
+
// Phase 4: Spaced Repetition & Archive
|
|
394
|
+
readReviewQueue,
|
|
395
|
+
writeReviewQueue,
|
|
396
|
+
readArchiveIndex,
|
|
397
|
+
writeArchiveIndex,
|
|
398
|
+
// Deep erasure utilities
|
|
399
|
+
removeEdgesForMemory,
|
|
400
|
+
removeFromReviewQueue,
|
|
401
|
+
};
|