brain-memory 0.1.0-beta.3 → 0.1.0-beta.5

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,231 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+
5
+ const PACKAGE_ROOT = path.resolve(__dirname, '..');
6
+
7
+ const RUNTIMES = {
8
+ claude: {
9
+ name: 'Claude Code',
10
+ globalDir: path.join(os.homedir(), '.claude'),
11
+ localDir: '.claude',
12
+ commandsSubdir: 'commands',
13
+ promptFile: 'CLAUDE.md',
14
+ promptSource: 'claude.md',
15
+ commandStyle: 'flat',
16
+ },
17
+ gemini: {
18
+ name: 'Gemini CLI',
19
+ globalDir: path.join(os.homedir(), '.gemini'),
20
+ localDir: '.gemini',
21
+ commandsSubdir: 'commands',
22
+ promptFile: 'GEMINI.md',
23
+ promptSource: 'gemini.md',
24
+ commandStyle: 'flat',
25
+ },
26
+ openai: {
27
+ name: 'OpenAI Codex CLI',
28
+ globalDir: path.join(os.homedir(), '.codex'),
29
+ localDir: '.codex',
30
+ commandsSubdir: 'skills',
31
+ promptFile: 'AGENTS.md',
32
+ promptSource: 'openai.md',
33
+ commandStyle: 'skills',
34
+ },
35
+ };
36
+
37
+ const BRAIN_MARKER_START = '<!-- BRAIN-MEMORY-START -->';
38
+ const BRAIN_MARKER_END = '<!-- BRAIN-MEMORY-END -->';
39
+
40
+ function copyDir(src, dest) {
41
+ fs.mkdirSync(dest, { recursive: true });
42
+ const entries = fs.readdirSync(src, { withFileTypes: true });
43
+ for (const entry of entries) {
44
+ const srcPath = path.join(src, entry.name);
45
+ const destPath = path.join(dest, entry.name);
46
+ if (entry.isDirectory()) {
47
+ copyDir(srcPath, destPath);
48
+ } else {
49
+ fs.copyFileSync(srcPath, destPath);
50
+ }
51
+ }
52
+ }
53
+
54
+ function installSkills(commandsSrc, skillsDest) {
55
+ const entries = fs.readdirSync(commandsSrc).filter((f) => f.endsWith('.md'));
56
+ for (const file of entries) {
57
+ const name = file.replace('.md', '');
58
+ const skillDir = path.join(skillsDest, `brain-${name}`);
59
+ fs.mkdirSync(skillDir, { recursive: true });
60
+ fs.copyFileSync(
61
+ path.join(commandsSrc, file),
62
+ path.join(skillDir, 'SKILL.md')
63
+ );
64
+ }
65
+ }
66
+
67
+ function injectPrompt(targetDir, promptFile, promptSource) {
68
+ const promptContent = fs.readFileSync(
69
+ path.join(PACKAGE_ROOT, 'prompts', promptSource),
70
+ 'utf-8'
71
+ );
72
+ const targetPath = path.join(targetDir, promptFile);
73
+
74
+ const wrappedContent = `\n${BRAIN_MARKER_START}\n${promptContent}\n${BRAIN_MARKER_END}\n`;
75
+
76
+ if (fs.existsSync(targetPath)) {
77
+ let existing = fs.readFileSync(targetPath, 'utf-8');
78
+ // Remove old brain section if present
79
+ const startIdx = existing.indexOf(BRAIN_MARKER_START);
80
+ const endIdx = existing.indexOf(BRAIN_MARKER_END);
81
+ if (startIdx !== -1 && endIdx !== -1) {
82
+ existing =
83
+ existing.substring(0, startIdx) +
84
+ existing.substring(endIdx + BRAIN_MARKER_END.length);
85
+ }
86
+ fs.writeFileSync(targetPath, existing.trimEnd() + '\n' + wrappedContent);
87
+ } else {
88
+ fs.writeFileSync(targetPath, wrappedContent.trim() + '\n');
89
+ }
90
+ }
91
+
92
+ function installForRuntime(runtime, scope) {
93
+ const config = RUNTIMES[runtime];
94
+ const targetDir = scope === 'global' ? config.globalDir : config.localDir;
95
+ const commandsSrc = path.join(PACKAGE_ROOT, 'commands', 'brain');
96
+
97
+ if (config.commandStyle === 'skills') {
98
+ const skillsDest = path.join(targetDir, config.commandsSubdir);
99
+ installSkills(commandsSrc, skillsDest);
100
+ } else {
101
+ const commandsDest = path.join(targetDir, config.commandsSubdir, 'brain');
102
+ copyDir(commandsSrc, commandsDest);
103
+ }
104
+
105
+ const promptTarget = scope === 'global' ? config.globalDir : '.';
106
+ injectPrompt(promptTarget, config.promptFile, config.promptSource);
107
+ }
108
+
109
+ function initializeBrain(projectDir) {
110
+ const brainDir = path.join(projectDir || process.cwd(), '.brain');
111
+
112
+ if (fs.existsSync(brainDir)) {
113
+ return { alreadyExists: true };
114
+ }
115
+
116
+ const now = new Date().toISOString();
117
+
118
+ // Create directories
119
+ const categories = ['professional', 'personal', 'social', 'family', '_consolidated', '_archived'];
120
+ for (const cat of categories) {
121
+ fs.mkdirSync(path.join(brainDir, cat), { recursive: true });
122
+ }
123
+
124
+ // Create index.json
125
+ const index = {
126
+ version: 2,
127
+ created: now,
128
+ last_updated: now,
129
+ memory_count: 0,
130
+ memories: {},
131
+ config: {
132
+ max_depth: 6,
133
+ consolidation_threshold: 0.3,
134
+ decay_check_interval_days: 7,
135
+ strength_boost_on_recall: 0.05,
136
+ auto_consolidate: true,
137
+ propagation_window_days: 7,
138
+ association_config: {
139
+ co_retrieval_boost: 0.10,
140
+ link_decay_rate: 0.998,
141
+ link_prune_threshold: 0.05,
142
+ spreading_activation_depth: 2,
143
+ spreading_activation_decay: 0.5,
144
+ },
145
+ },
146
+ };
147
+ fs.writeFileSync(
148
+ path.join(brainDir, 'index.json'),
149
+ JSON.stringify(index, null, 2) + '\n'
150
+ );
151
+
152
+ // Create associations.json
153
+ fs.writeFileSync(
154
+ path.join(brainDir, 'associations.json'),
155
+ JSON.stringify({ version: 1, edges: {} }, null, 2) + '\n'
156
+ );
157
+
158
+ // Create contexts.json
159
+ fs.writeFileSync(
160
+ path.join(brainDir, 'contexts.json'),
161
+ JSON.stringify({ version: 1, sessions: [] }, null, 2) + '\n'
162
+ );
163
+
164
+ // Create review-queue.json
165
+ fs.writeFileSync(
166
+ path.join(brainDir, 'review-queue.json'),
167
+ JSON.stringify({ version: 1, items: [] }, null, 2) + '\n'
168
+ );
169
+
170
+ // Create _archived/index.json
171
+ fs.writeFileSync(
172
+ path.join(brainDir, '_archived', 'index.json'),
173
+ JSON.stringify({ version: 1, archived_count: 0, memories: {} }, null, 2) + '\n'
174
+ );
175
+
176
+ // Load category descriptions from template
177
+ const templatePath = path.join(PACKAGE_ROOT, 'templates', 'default-categories.json');
178
+ let template = { top_categories: [] };
179
+ if (fs.existsSync(templatePath)) {
180
+ template = JSON.parse(fs.readFileSync(templatePath, 'utf-8'));
181
+ }
182
+
183
+ // Create _meta.json for each category
184
+ const mainCategories = ['professional', 'personal', 'social', 'family'];
185
+ for (const cat of mainCategories) {
186
+ const templateCat = template.top_categories.find((c) => c.name === cat) || {};
187
+ const meta = {
188
+ category: cat,
189
+ description: templateCat.description || cat,
190
+ created: now,
191
+ memory_count: 0,
192
+ subcategories: [],
193
+ };
194
+ fs.writeFileSync(
195
+ path.join(brainDir, cat, '_meta.json'),
196
+ JSON.stringify(meta, null, 2) + '\n'
197
+ );
198
+ }
199
+
200
+ // Create _meta.json for special directories
201
+ for (const special of ['_consolidated', '_archived']) {
202
+ const meta = {
203
+ category: special,
204
+ description:
205
+ special === '_consolidated'
206
+ ? 'Merged memories from consolidation operations'
207
+ : 'Archived memories preserved for recovery',
208
+ created: now,
209
+ memory_count: 0,
210
+ subcategories: [],
211
+ };
212
+ fs.writeFileSync(
213
+ path.join(brainDir, special, '_meta.json'),
214
+ JSON.stringify(meta, null, 2) + '\n'
215
+ );
216
+ }
217
+
218
+ return { alreadyExists: false, brainDir };
219
+ }
220
+
221
+ module.exports = {
222
+ RUNTIMES,
223
+ BRAIN_MARKER_START,
224
+ BRAIN_MARKER_END,
225
+ PACKAGE_ROOT,
226
+ copyDir,
227
+ installSkills,
228
+ injectPrompt,
229
+ installForRuntime,
230
+ initializeBrain,
231
+ };
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Brain Memory — Crypto Utilities
3
+ *
4
+ * AES-256-GCM encryption for sync credentials and file content.
5
+ * Zero external dependencies — uses only Node.js built-in crypto.
6
+ */
7
+
8
+ const crypto = require('crypto');
9
+ const fs = require('fs');
10
+ const path = require('path');
11
+ const os = require('os');
12
+ const { getBrainDir } = require('../index-manager');
13
+
14
+ const SYNC_DIR = '.sync';
15
+ const CREDENTIALS_FILE = 'credentials.enc';
16
+
17
+ const PBKDF2_ITERATIONS = 100000;
18
+ const PBKDF2_DIGEST = 'sha512';
19
+ const KEY_LENGTH = 32; // 256 bits
20
+ const IV_LENGTH = 12; // 96 bits for GCM
21
+ const SALT_LENGTH = 32;
22
+ const AUTH_TAG_LENGTH = 16;
23
+
24
+ /**
25
+ * Derive an AES-256 key from a passphrase using PBKDF2.
26
+ *
27
+ * @param {string} passphrase - User-provided passphrase
28
+ * @param {Buffer} salt - 32-byte salt
29
+ * @returns {Buffer} 32-byte derived key
30
+ */
31
+ function deriveKey(passphrase, salt) {
32
+ return crypto.pbkdf2Sync(passphrase, salt, PBKDF2_ITERATIONS, KEY_LENGTH, PBKDF2_DIGEST);
33
+ }
34
+
35
+ /**
36
+ * Generate a machine-specific identifier (convenience default, not strong security).
37
+ * SHA-256 of hostname + username.
38
+ *
39
+ * @returns {string} Hex-encoded machine identifier
40
+ */
41
+ function getMachineIdentifier() {
42
+ const data = `${os.hostname()}:${os.userInfo().username}`;
43
+ return crypto.createHash('sha256').update(data).digest('hex');
44
+ }
45
+
46
+ /**
47
+ * Encrypt a UTF-8 string with AES-256-GCM.
48
+ *
49
+ * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
50
+ *
51
+ * @param {string} plaintext - UTF-8 string to encrypt
52
+ * @param {string} passphrase - Passphrase (key derived via PBKDF2)
53
+ * @returns {Buffer} Encrypted buffer
54
+ */
55
+ function encrypt(plaintext, passphrase) {
56
+ const salt = crypto.randomBytes(SALT_LENGTH);
57
+ const key = deriveKey(passphrase, salt);
58
+ const iv = crypto.randomBytes(IV_LENGTH);
59
+
60
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
61
+ const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
62
+ const authTag = cipher.getAuthTag();
63
+
64
+ return Buffer.concat([salt, iv, authTag, encrypted]);
65
+ }
66
+
67
+ /**
68
+ * Decrypt an AES-256-GCM encrypted buffer back to a UTF-8 string.
69
+ *
70
+ * @param {Buffer} encrypted - Buffer produced by encrypt()
71
+ * @param {string} passphrase - Same passphrase used for encryption
72
+ * @returns {string} Decrypted UTF-8 string
73
+ * @throws {Error} If passphrase is wrong or data is tampered
74
+ */
75
+ function decrypt(encrypted, passphrase) {
76
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH + 1) {
77
+ throw new Error('Invalid encrypted data: too short');
78
+ }
79
+
80
+ const salt = encrypted.subarray(0, SALT_LENGTH);
81
+ const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
82
+ const authTag = encrypted.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
83
+ const ciphertext = encrypted.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
84
+
85
+ const key = deriveKey(passphrase, salt);
86
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
87
+ decipher.setAuthTag(authTag);
88
+
89
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8');
90
+ }
91
+
92
+ /**
93
+ * Encrypt a Buffer with AES-256-GCM (for file content before upload).
94
+ *
95
+ * Output format: salt (32) + iv (12) + authTag (16) + ciphertext
96
+ *
97
+ * @param {Buffer} buffer - Raw file content
98
+ * @param {string} passphrase - Passphrase
99
+ * @returns {Buffer} Encrypted buffer
100
+ */
101
+ function encryptBuffer(buffer, passphrase) {
102
+ const salt = crypto.randomBytes(SALT_LENGTH);
103
+ const key = deriveKey(passphrase, salt);
104
+ const iv = crypto.randomBytes(IV_LENGTH);
105
+
106
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
107
+ const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
108
+ const authTag = cipher.getAuthTag();
109
+
110
+ return Buffer.concat([salt, iv, authTag, encrypted]);
111
+ }
112
+
113
+ /**
114
+ * Decrypt a Buffer encrypted with encryptBuffer().
115
+ *
116
+ * @param {Buffer} encrypted - Buffer produced by encryptBuffer()
117
+ * @param {string} passphrase - Same passphrase used for encryption
118
+ * @returns {Buffer} Decrypted buffer
119
+ * @throws {Error} If passphrase is wrong or data is tampered
120
+ */
121
+ function decryptBuffer(encrypted, passphrase) {
122
+ if (encrypted.length < SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH) {
123
+ throw new Error('Invalid encrypted data: too short');
124
+ }
125
+
126
+ const salt = encrypted.subarray(0, SALT_LENGTH);
127
+ const iv = encrypted.subarray(SALT_LENGTH, SALT_LENGTH + IV_LENGTH);
128
+ const authTag = encrypted.subarray(SALT_LENGTH + IV_LENGTH, SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
129
+ const ciphertext = encrypted.subarray(SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH);
130
+
131
+ const key = deriveKey(passphrase, salt);
132
+ const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
133
+ decipher.setAuthTag(authTag);
134
+
135
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
136
+ }
137
+
138
+ /**
139
+ * Get the path to the .sync directory.
140
+ *
141
+ * @param {string} [projectRoot] - Project root directory
142
+ * @returns {string} Absolute path to .brain/.sync/
143
+ */
144
+ function getSyncDir(projectRoot) {
145
+ return path.join(getBrainDir(projectRoot), SYNC_DIR);
146
+ }
147
+
148
+ /**
149
+ * Save OAuth tokens encrypted to .brain/.sync/credentials.enc.
150
+ * Sets file permissions to 0600 (owner read/write only).
151
+ *
152
+ * @param {Object} tokens - OAuth tokens to store
153
+ * @param {string} [projectRoot] - Project root directory
154
+ * @param {string} [passphrase] - Passphrase (defaults to machine identifier)
155
+ */
156
+ function saveCredentials(tokens, projectRoot, passphrase) {
157
+ const syncDir = getSyncDir(projectRoot);
158
+ fs.mkdirSync(syncDir, { recursive: true });
159
+
160
+ const pass = passphrase || getMachineIdentifier();
161
+ const encrypted = encrypt(JSON.stringify(tokens), pass);
162
+ const credPath = path.join(syncDir, CREDENTIALS_FILE);
163
+
164
+ fs.writeFileSync(credPath, encrypted);
165
+ try {
166
+ fs.chmodSync(credPath, 0o600);
167
+ } catch {
168
+ // chmod may not be supported on all platforms
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Load and decrypt OAuth tokens from .brain/.sync/credentials.enc.
174
+ *
175
+ * @param {string} [projectRoot] - Project root directory
176
+ * @param {string} [passphrase] - Passphrase (defaults to machine identifier)
177
+ * @returns {Object|null} Decrypted tokens or null if file doesn't exist
178
+ * @throws {Error} If passphrase is wrong
179
+ */
180
+ function loadCredentials(projectRoot, passphrase) {
181
+ const credPath = path.join(getSyncDir(projectRoot), CREDENTIALS_FILE);
182
+ if (!fs.existsSync(credPath)) return null;
183
+
184
+ const pass = passphrase || getMachineIdentifier();
185
+ const encrypted = fs.readFileSync(credPath);
186
+ return JSON.parse(decrypt(encrypted, pass));
187
+ }
188
+
189
+ /**
190
+ * Delete stored credentials.
191
+ *
192
+ * @param {string} [projectRoot] - Project root directory
193
+ */
194
+ function deleteCredentials(projectRoot) {
195
+ const credPath = path.join(getSyncDir(projectRoot), CREDENTIALS_FILE);
196
+ if (fs.existsSync(credPath)) {
197
+ fs.unlinkSync(credPath);
198
+ }
199
+ }
200
+
201
+ module.exports = {
202
+ deriveKey,
203
+ getMachineIdentifier,
204
+ encrypt,
205
+ decrypt,
206
+ encryptBuffer,
207
+ decryptBuffer,
208
+ getSyncDir,
209
+ saveCredentials,
210
+ loadCredentials,
211
+ deleteCredentials,
212
+ // Expose constants for testing
213
+ PBKDF2_ITERATIONS,
214
+ SALT_LENGTH,
215
+ IV_LENGTH,
216
+ AUTH_TAG_LENGTH,
217
+ };