brain-memory 0.1.0-beta.9 → 0.1.0
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/CHANGELOG.md +555 -0
- package/README.md +385 -84
- package/SECURITY.md +100 -0
- package/assets/brand/README.md +28 -0
- package/assets/brand/icon-dark.svg +19 -0
- package/assets/brand/icon-light.svg +20 -0
- package/assets/brand/linkedin_cover.png +0 -0
- package/assets/brand/linkedin_cover_light.png +0 -0
- package/assets/brand/mark-dark.svg +19 -0
- package/assets/brand/mark-light.svg +20 -0
- package/assets/brand/png/icon-dark-1024.png +0 -0
- package/assets/brand/png/icon-dark-128.png +0 -0
- package/assets/brand/png/icon-dark-256.png +0 -0
- package/assets/brand/png/icon-dark-512.png +0 -0
- package/assets/brand/png/icon-dark-64.png +0 -0
- package/assets/brand/png/icon-light-1024.png +0 -0
- package/assets/brand/png/icon-light-128.png +0 -0
- package/assets/brand/png/icon-light-256.png +0 -0
- package/assets/brand/png/icon-light-512.png +0 -0
- package/assets/brand/png/icon-light-64.png +0 -0
- package/assets/brand/png/mark-dark-1024.png +0 -0
- package/assets/brand/png/mark-light-1024.png +0 -0
- package/assets/icon.png +0 -0
- package/assets/icon.svg +19 -0
- package/bin/audit.js +93 -0
- package/bin/brain.js +132 -0
- package/bin/cloud-sync.js +150 -0
- package/bin/forget.js +163 -0
- package/bin/import.js +132 -0
- package/bin/install.js +63 -31
- package/bin/memorize.js +637 -0
- package/bin/pin.js +44 -0
- package/bin/recall.js +287 -0
- package/bin/reinforce.js +191 -0
- package/bin/restore.js +122 -0
- package/bin/session-start.js +337 -0
- package/bin/skill.js +67 -0
- package/bin/unpin.js +38 -0
- package/bin/verify.js +154 -0
- package/commands/brain/forget.md +243 -13
- package/commands/brain/import.md +125 -0
- package/commands/brain/memorize.md +95 -137
- package/commands/brain/pin.md +79 -0
- package/commands/brain/remember.md +53 -103
- package/commands/brain/skills.md +60 -0
- package/commands/brain/sleep.md +93 -6
- package/commands/brain/status.md +15 -6
- package/commands/brain/sync.md +181 -17
- package/commands/brain/verify.md +57 -0
- package/integrations/README.md +29 -0
- package/integrations/agentskills/brain-memory/SKILL.md +115 -0
- package/integrations/agentskills/brain-memory/scripts/session-start.mjs +34 -0
- package/package.json +19 -7
- package/prompts/antigravity.md +201 -0
- package/prompts/claude.md +107 -40
- package/prompts/copilot.md +203 -0
- package/prompts/kilo.md +202 -0
- package/prompts/openai.md +112 -45
- package/prompts/opencode.md +200 -0
- package/src/anomaly.js +260 -0
- package/src/audit.js +71 -0
- package/src/cloud-sync.js +672 -0
- package/src/content-lint.js +118 -0
- package/src/export-import.js +45 -7
- package/src/git-sync.js +170 -11
- package/src/harvest.js +562 -0
- package/src/index-manager.js +250 -11
- package/src/installer.js +250 -29
- package/src/pinning.js +146 -0
- package/src/provenance.js +79 -0
- package/src/quarantine.js +111 -0
- package/src/receipt.js +81 -0
- package/src/scorer.js +69 -12
- package/src/skills.js +208 -0
- package/src/tfidf.js +520 -0
- package/commands/brain/consolidate.md +0 -153
- package/commands/brain/explore.md +0 -79
- package/commands/brain/init.md +0 -149
- package/commands/brain/review.md +0 -130
- package/commands/brain/sunshine.md +0 -337
- package/prompts/gemini.md +0 -134
package/src/installer.js
CHANGED
|
@@ -2,8 +2,21 @@ const fs = require('fs');
|
|
|
2
2
|
const path = require('path');
|
|
3
3
|
const os = require('os');
|
|
4
4
|
|
|
5
|
+
const { getBrainDir } = require('./index-manager');
|
|
6
|
+
|
|
5
7
|
const PACKAGE_ROOT = path.resolve(__dirname, '..');
|
|
6
8
|
|
|
9
|
+
// Local-first integration targets, current as of mid-2026. The hosted MCP
|
|
10
|
+
// connector (Brain Cloud) is the universal path for everything else (Claude.ai,
|
|
11
|
+
// ChatGPT, mobile, Antigravity/Gemini-Enterprise via remote MCP); these are the
|
|
12
|
+
// CLIs where a native install adds the ambient zero-config loop MCP can't.
|
|
13
|
+
//
|
|
14
|
+
// `skillsGlobalDir`/`skillsLocalDir` decouple where skills land from where the
|
|
15
|
+
// prompt lands (Codex prompts go to ~/.codex/AGENTS.md but skills go to the
|
|
16
|
+
// cross-tool ~/.agents/skills/). `skillName: true` injects the `name:`
|
|
17
|
+
// frontmatter that Codex/Antigravity require to match the skill folder.
|
|
18
|
+
//
|
|
19
|
+
// Gemini CLI was retired 2026-06-18 (absorbed into Antigravity) and is removed.
|
|
7
20
|
const RUNTIMES = {
|
|
8
21
|
claude: {
|
|
9
22
|
name: 'Claude Code',
|
|
@@ -14,62 +27,158 @@ const RUNTIMES = {
|
|
|
14
27
|
promptSource: 'claude.md',
|
|
15
28
|
commandStyle: 'flat',
|
|
16
29
|
},
|
|
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
30
|
openai: {
|
|
27
31
|
name: 'OpenAI Codex CLI',
|
|
28
32
|
globalDir: path.join(os.homedir(), '.codex'),
|
|
29
33
|
localDir: '.codex',
|
|
30
34
|
commandsSubdir: 'skills',
|
|
35
|
+
// Codex reads skills from the cross-tool ~/.agents/skills/, NOT ~/.codex/skills/.
|
|
36
|
+
skillsGlobalDir: path.join(os.homedir(), '.agents', 'skills'),
|
|
37
|
+
skillsLocalDir: path.join('.agents', 'skills'),
|
|
31
38
|
promptFile: 'AGENTS.md',
|
|
32
39
|
promptSource: 'openai.md',
|
|
33
40
|
commandStyle: 'skills',
|
|
41
|
+
skillName: true,
|
|
42
|
+
},
|
|
43
|
+
antigravity: {
|
|
44
|
+
name: 'Google Antigravity',
|
|
45
|
+
// NB: Antigravity reuses ~/.gemini/ and reads GEMINI.md globally + Markdown
|
|
46
|
+
// SKILL.md skills under ~/.gemini/skills/. These paths are community-sourced
|
|
47
|
+
// (official docs are JS SPAs) — VERIFY against a live Antigravity install.
|
|
48
|
+
globalDir: path.join(os.homedir(), '.gemini'),
|
|
49
|
+
localDir: '.',
|
|
50
|
+
commandsSubdir: 'skills',
|
|
51
|
+
skillsGlobalDir: path.join(os.homedir(), '.gemini', 'skills'),
|
|
52
|
+
skillsLocalDir: path.join('.agents', 'skills'),
|
|
53
|
+
promptFile: 'GEMINI.md',
|
|
54
|
+
promptSource: 'antigravity.md',
|
|
55
|
+
commandStyle: 'skills',
|
|
56
|
+
skillName: true,
|
|
57
|
+
},
|
|
58
|
+
opencode: {
|
|
59
|
+
name: 'OpenCode',
|
|
60
|
+
globalDir: path.join(os.homedir(), '.config', 'opencode'),
|
|
61
|
+
localDir: '.opencode',
|
|
62
|
+
commandsSubdir: 'commands',
|
|
63
|
+
promptFile: 'AGENTS.md',
|
|
64
|
+
promptSource: 'opencode.md',
|
|
65
|
+
commandStyle: 'flat',
|
|
66
|
+
},
|
|
67
|
+
copilot: {
|
|
68
|
+
name: 'GitHub Copilot CLI',
|
|
69
|
+
globalDir: path.join(os.homedir(), '.copilot'),
|
|
70
|
+
localDir: '.copilot',
|
|
71
|
+
commandsSubdir: 'skills',
|
|
72
|
+
// Copilot reads the cross-tool ~/.agents/skills/ (same dir Codex uses) in
|
|
73
|
+
// addition to its own ~/.copilot/skills/ — reuse the shared location.
|
|
74
|
+
skillsGlobalDir: path.join(os.homedir(), '.agents', 'skills'),
|
|
75
|
+
skillsLocalDir: path.join('.agents', 'skills'),
|
|
76
|
+
// Copilot's GLOBAL instructions file is ~/.copilot/copilot-instructions.md
|
|
77
|
+
// but its repo-local file is AGENTS.md — the same root AGENTS.md the openai
|
|
78
|
+
// and opencode runtimes write locally. The marker-delimited section is
|
|
79
|
+
// shared: whichever runtime installed last owns it (the prompt bodies are
|
|
80
|
+
// near-identical, so this is by design, not a conflict).
|
|
81
|
+
promptFile: 'copilot-instructions.md',
|
|
82
|
+
localPromptFile: 'AGENTS.md',
|
|
83
|
+
promptSource: 'copilot.md',
|
|
84
|
+
commandStyle: 'skills',
|
|
85
|
+
skillName: true,
|
|
86
|
+
},
|
|
87
|
+
kilo: {
|
|
88
|
+
name: 'Kilo',
|
|
89
|
+
globalDir: path.join(os.homedir(), '.config', 'kilo'),
|
|
90
|
+
localDir: '.kilo',
|
|
91
|
+
commandsSubdir: 'commands',
|
|
92
|
+
// Kilo v7 is OpenCode-based: repo-root AGENTS.md is read natively (shared
|
|
93
|
+
// with the openai/opencode runtimes), but there is NO global markdown file
|
|
94
|
+
// read directly — the global prompt must be written to a file AND
|
|
95
|
+
// registered in the `instructions` array of ~/.config/kilo/kilo.jsonc
|
|
96
|
+
// (see instructionsConfig + ensureInstructionsEntry).
|
|
97
|
+
promptFile: path.join('rules', 'brain-memory.md'),
|
|
98
|
+
localPromptFile: 'AGENTS.md',
|
|
99
|
+
instructionsConfig: 'kilo.jsonc',
|
|
100
|
+
promptSource: 'kilo.md',
|
|
101
|
+
commandStyle: 'flat',
|
|
34
102
|
},
|
|
35
103
|
};
|
|
36
104
|
|
|
105
|
+
/** Prompt filename for a runtime+scope (Copilot's differs between scopes). */
|
|
106
|
+
function promptFileFor(config, scope) {
|
|
107
|
+
if (scope === 'local' && config.localPromptFile) return config.localPromptFile;
|
|
108
|
+
return config.promptFile;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** Where skills install for a runtime+scope (decoupled from the prompt target). */
|
|
112
|
+
function skillsDestFor(config, scope) {
|
|
113
|
+
if (scope === 'global') {
|
|
114
|
+
return config.skillsGlobalDir || path.join(config.globalDir, config.commandsSubdir);
|
|
115
|
+
}
|
|
116
|
+
return config.skillsLocalDir || path.join(config.localDir, config.commandsSubdir);
|
|
117
|
+
}
|
|
118
|
+
|
|
37
119
|
const BRAIN_MARKER_START = '<!-- BRAIN-MEMORY-START -->';
|
|
38
120
|
const BRAIN_MARKER_END = '<!-- BRAIN-MEMORY-END -->';
|
|
39
121
|
|
|
40
|
-
function copyDir(src, dest) {
|
|
122
|
+
function copyDir(src, dest, _depth = 0) {
|
|
123
|
+
if (_depth > 20) {
|
|
124
|
+
throw new Error(`copyDir: max depth (20) exceeded at ${src}`);
|
|
125
|
+
}
|
|
41
126
|
fs.mkdirSync(dest, { recursive: true });
|
|
42
127
|
const entries = fs.readdirSync(src, { withFileTypes: true });
|
|
43
128
|
for (const entry of entries) {
|
|
129
|
+
if (entry.isSymbolicLink()) continue;
|
|
44
130
|
const srcPath = path.join(src, entry.name);
|
|
45
131
|
const destPath = path.join(dest, entry.name);
|
|
46
132
|
if (entry.isDirectory()) {
|
|
47
|
-
copyDir(srcPath, destPath);
|
|
133
|
+
copyDir(srcPath, destPath, _depth + 1);
|
|
48
134
|
} else {
|
|
49
135
|
fs.copyFileSync(srcPath, destPath);
|
|
50
136
|
}
|
|
51
137
|
}
|
|
52
138
|
}
|
|
53
139
|
|
|
54
|
-
function installSkills(commandsSrc, skillsDest) {
|
|
140
|
+
function installSkills(commandsSrc, skillsDest, addName = false) {
|
|
55
141
|
const entries = fs.readdirSync(commandsSrc).filter((f) => f.endsWith('.md'));
|
|
56
142
|
for (const file of entries) {
|
|
57
143
|
const name = file.replace('.md', '');
|
|
58
|
-
const
|
|
144
|
+
const skillFolder = `brain-${name}`;
|
|
145
|
+
const skillDir = path.join(skillsDest, skillFolder);
|
|
59
146
|
fs.mkdirSync(skillDir, { recursive: true });
|
|
60
|
-
fs.
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
);
|
|
147
|
+
let content = fs.readFileSync(path.join(commandsSrc, file), 'utf-8');
|
|
148
|
+
if (addName) content = ensureSkillName(content, skillFolder);
|
|
149
|
+
fs.writeFileSync(path.join(skillDir, 'SKILL.md'), content);
|
|
64
150
|
}
|
|
65
151
|
}
|
|
66
152
|
|
|
153
|
+
/**
|
|
154
|
+
* Codex and Antigravity require a `name:` frontmatter field that matches the
|
|
155
|
+
* skill folder. The source command files only carry `description:`, so inject
|
|
156
|
+
* `name:` as the first frontmatter field (idempotent — skips if already present).
|
|
157
|
+
*/
|
|
158
|
+
function ensureSkillName(content, name) {
|
|
159
|
+
if (/^---\s*\n/.test(content)) {
|
|
160
|
+
const end = content.indexOf('\n---', 3);
|
|
161
|
+
const block = end !== -1 ? content.slice(0, end) : content;
|
|
162
|
+
if (/^\s*name\s*:/m.test(block)) return content;
|
|
163
|
+
return content.replace(/^---\s*\n/, `---\nname: ${name}\n`);
|
|
164
|
+
}
|
|
165
|
+
return `---\nname: ${name}\n---\n\n${content}`;
|
|
166
|
+
}
|
|
167
|
+
|
|
67
168
|
function injectPrompt(targetDir, promptFile, promptSource) {
|
|
68
169
|
const promptContent = fs.readFileSync(
|
|
69
170
|
path.join(PACKAGE_ROOT, 'prompts', promptSource),
|
|
70
171
|
'utf-8'
|
|
71
172
|
);
|
|
72
173
|
const targetPath = path.join(targetDir, promptFile);
|
|
174
|
+
// Ensure the prompt dir exists. Previously this was created as a side-effect
|
|
175
|
+
// of installing commands/skills into the same dir; now that skills can land
|
|
176
|
+
// elsewhere (e.g. Codex skills → ~/.agents/skills), the prompt dir (~/.codex)
|
|
177
|
+
// must be created explicitly.
|
|
178
|
+
fs.mkdirSync(targetDir, { recursive: true });
|
|
179
|
+
|
|
180
|
+
// promptFile may contain a subdirectory (e.g. Kilo's rules/brain-memory.md).
|
|
181
|
+
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
|
|
73
182
|
|
|
74
183
|
const wrappedContent = `\n${BRAIN_MARKER_START}\n${promptContent}\n${BRAIN_MARKER_END}\n`;
|
|
75
184
|
|
|
@@ -89,19 +198,73 @@ function injectPrompt(targetDir, promptFile, promptSource) {
|
|
|
89
198
|
}
|
|
90
199
|
}
|
|
91
200
|
|
|
201
|
+
/**
|
|
202
|
+
* Register a prompt file in a JSONC config's `instructions` array (Kilo reads
|
|
203
|
+
* no global markdown file directly). Conservative by design: creates a minimal
|
|
204
|
+
* config when none exists; edits only files that parse as strict JSON (JSONC
|
|
205
|
+
* comments or trailing commas fail JSON.parse, so a hand-commented config is
|
|
206
|
+
* never rewritten). When it can't edit safely it returns `manual: true` so the
|
|
207
|
+
* caller can print the one-line manual step instead.
|
|
208
|
+
*/
|
|
209
|
+
function ensureInstructionsEntry(configPath, entry) {
|
|
210
|
+
if (!fs.existsSync(configPath)) {
|
|
211
|
+
fs.mkdirSync(path.dirname(configPath), { recursive: true });
|
|
212
|
+
fs.writeFileSync(configPath, JSON.stringify({ instructions: [entry] }, null, 2) + '\n');
|
|
213
|
+
return { registered: true, created: true };
|
|
214
|
+
}
|
|
215
|
+
const raw = fs.readFileSync(configPath, 'utf-8');
|
|
216
|
+
let cfg;
|
|
217
|
+
try {
|
|
218
|
+
cfg = JSON.parse(raw);
|
|
219
|
+
} catch {
|
|
220
|
+
return { registered: false, manual: true, reason: 'not-strict-json' };
|
|
221
|
+
}
|
|
222
|
+
if (cfg === null || typeof cfg !== 'object' || Array.isArray(cfg)) {
|
|
223
|
+
return { registered: false, manual: true, reason: 'unexpected-shape' };
|
|
224
|
+
}
|
|
225
|
+
if (cfg.instructions === undefined) cfg.instructions = [];
|
|
226
|
+
if (!Array.isArray(cfg.instructions)) {
|
|
227
|
+
return { registered: false, manual: true, reason: 'instructions-not-array' };
|
|
228
|
+
}
|
|
229
|
+
if (cfg.instructions.includes(entry)) return { registered: true, already: true };
|
|
230
|
+
cfg.instructions.push(entry);
|
|
231
|
+
fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2) + '\n');
|
|
232
|
+
return { registered: true };
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function removeInstructionsEntry(configPath, entry) {
|
|
236
|
+
if (!fs.existsSync(configPath)) return { removed: false, reason: 'file-not-found' };
|
|
237
|
+
let cfg;
|
|
238
|
+
try {
|
|
239
|
+
cfg = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
|
240
|
+
} catch {
|
|
241
|
+
return { removed: false, manual: true, reason: 'not-strict-json' };
|
|
242
|
+
}
|
|
243
|
+
if (!cfg || !Array.isArray(cfg.instructions)) return { removed: false, reason: 'no-instructions' };
|
|
244
|
+
const before = cfg.instructions.length;
|
|
245
|
+
cfg.instructions = cfg.instructions.filter((e) => e !== entry);
|
|
246
|
+
if (cfg.instructions.length === before) return { removed: false, reason: 'not-registered' };
|
|
247
|
+
fs.writeFileSync(configPath, JSON.stringify(cfg, null, 2) + '\n');
|
|
248
|
+
return { removed: true };
|
|
249
|
+
}
|
|
250
|
+
|
|
92
251
|
function detectInstallations() {
|
|
93
252
|
const results = [];
|
|
94
253
|
for (const [runtime, config] of Object.entries(RUNTIMES)) {
|
|
95
254
|
for (const scope of ['global', 'local']) {
|
|
96
255
|
const targetDir = scope === 'global' ? config.globalDir : config.localDir;
|
|
97
256
|
const promptTarget = scope === 'global' ? config.globalDir : '.';
|
|
98
|
-
const promptPath = path.join(promptTarget, config
|
|
257
|
+
const promptPath = path.join(promptTarget, promptFileFor(config, scope));
|
|
99
258
|
|
|
100
259
|
// Check for command files/dirs
|
|
101
260
|
let commandsFound = false;
|
|
102
261
|
if (config.commandStyle === 'skills') {
|
|
103
|
-
const skillsDir =
|
|
104
|
-
commandsFound = fs.existsSync(
|
|
262
|
+
const skillsDir = skillsDestFor(config, scope);
|
|
263
|
+
commandsFound = fs.existsSync(skillsDir) &&
|
|
264
|
+
fs.readdirSync(skillsDir).some(
|
|
265
|
+
(d) => d.startsWith('brain-') &&
|
|
266
|
+
fs.existsSync(path.join(skillsDir, d, 'SKILL.md'))
|
|
267
|
+
);
|
|
105
268
|
} else {
|
|
106
269
|
const commandsDir = path.join(targetDir, config.commandsSubdir, 'brain');
|
|
107
270
|
commandsFound = fs.existsSync(commandsDir) &&
|
|
@@ -157,11 +320,14 @@ function removePromptSection(promptPath) {
|
|
|
157
320
|
return { removed: true, fileDeleted: false };
|
|
158
321
|
}
|
|
159
322
|
|
|
160
|
-
function removeCommands(targetDir, config) {
|
|
323
|
+
function removeCommands(targetDir, config, scope = 'global') {
|
|
161
324
|
const removed = [];
|
|
162
325
|
|
|
163
326
|
if (config.commandStyle === 'skills') {
|
|
164
|
-
|
|
327
|
+
// Honor an explicit skills override; otherwise resolve relative to the
|
|
328
|
+
// passed targetDir (so callers that pass a custom targetDir still work).
|
|
329
|
+
const override = scope === 'global' ? config.skillsGlobalDir : config.skillsLocalDir;
|
|
330
|
+
const skillsDir = override || path.join(targetDir, config.commandsSubdir);
|
|
165
331
|
if (fs.existsSync(skillsDir)) {
|
|
166
332
|
const entries = fs.readdirSync(skillsDir).filter((d) => d.startsWith('brain-'));
|
|
167
333
|
for (const entry of entries) {
|
|
@@ -182,36 +348,83 @@ function removeCommands(targetDir, config) {
|
|
|
182
348
|
}
|
|
183
349
|
|
|
184
350
|
function uninstallForRuntime(runtime, scope) {
|
|
351
|
+
if (!Object.keys(RUNTIMES).includes(runtime)) {
|
|
352
|
+
throw new Error(`Unknown runtime: ${runtime}. Valid: ${Object.keys(RUNTIMES).join(', ')}`);
|
|
353
|
+
}
|
|
354
|
+
if (scope !== 'global' && scope !== 'local') {
|
|
355
|
+
throw new Error(`Invalid scope: ${scope}. Must be 'global' or 'local'.`);
|
|
356
|
+
}
|
|
185
357
|
const config = RUNTIMES[runtime];
|
|
186
358
|
const targetDir = scope === 'global' ? config.globalDir : config.localDir;
|
|
187
359
|
const promptTarget = scope === 'global' ? config.globalDir : '.';
|
|
188
|
-
const promptPath = path.join(promptTarget, config
|
|
360
|
+
const promptPath = path.join(promptTarget, promptFileFor(config, scope));
|
|
189
361
|
|
|
190
|
-
const removedCommands = removeCommands(targetDir, config);
|
|
362
|
+
const removedCommands = removeCommands(targetDir, config, scope);
|
|
191
363
|
const promptResult = removePromptSection(promptPath);
|
|
192
364
|
|
|
193
|
-
|
|
365
|
+
let promptRegistration;
|
|
366
|
+
if (scope === 'global' && config.instructionsConfig) {
|
|
367
|
+
promptRegistration = removeInstructionsEntry(
|
|
368
|
+
path.join(config.globalDir, config.instructionsConfig),
|
|
369
|
+
promptPath
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
return { removedCommands, promptResult, promptRegistration };
|
|
194
374
|
}
|
|
195
375
|
|
|
196
376
|
function installForRuntime(runtime, scope) {
|
|
377
|
+
if (!Object.keys(RUNTIMES).includes(runtime)) {
|
|
378
|
+
throw new Error(`Unknown runtime: ${runtime}. Valid: ${Object.keys(RUNTIMES).join(', ')}`);
|
|
379
|
+
}
|
|
380
|
+
if (scope !== 'global' && scope !== 'local') {
|
|
381
|
+
throw new Error(`Invalid scope: ${scope}. Must be 'global' or 'local'.`);
|
|
382
|
+
}
|
|
197
383
|
const config = RUNTIMES[runtime];
|
|
198
384
|
const targetDir = scope === 'global' ? config.globalDir : config.localDir;
|
|
199
385
|
const commandsSrc = path.join(PACKAGE_ROOT, 'commands', 'brain');
|
|
200
386
|
|
|
201
387
|
if (config.commandStyle === 'skills') {
|
|
202
|
-
const skillsDest =
|
|
203
|
-
|
|
388
|
+
const skillsDest = skillsDestFor(config, scope);
|
|
389
|
+
// Clear stale brain-* skill dirs first so renamed/removed commands don't
|
|
390
|
+
// linger across upgrades (e.g. brain-skill → brain-skills).
|
|
391
|
+
if (fs.existsSync(skillsDest)) {
|
|
392
|
+
for (const entry of fs.readdirSync(skillsDest)) {
|
|
393
|
+
if (entry.startsWith('brain-')) {
|
|
394
|
+
fs.rmSync(path.join(skillsDest, entry), { recursive: true, force: true });
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
installSkills(commandsSrc, skillsDest, config.skillName);
|
|
204
399
|
} else {
|
|
205
400
|
const commandsDest = path.join(targetDir, config.commandsSubdir, 'brain');
|
|
401
|
+
// Wipe the brain command dir before copying so renamed/removed commands
|
|
402
|
+
// don't linger across upgrades. This is critical on case-insensitive
|
|
403
|
+
// filesystems: a leftover skill.md (== SKILL.md) makes Claude Code treat
|
|
404
|
+
// the whole dir as one skill and hides every /brain:* command.
|
|
405
|
+
fs.rmSync(commandsDest, { recursive: true, force: true });
|
|
206
406
|
copyDir(commandsSrc, commandsDest);
|
|
207
407
|
}
|
|
208
408
|
|
|
209
409
|
const promptTarget = scope === 'global' ? config.globalDir : '.';
|
|
210
|
-
|
|
410
|
+
const promptFile = promptFileFor(config, scope);
|
|
411
|
+
injectPrompt(promptTarget, promptFile, config.promptSource);
|
|
412
|
+
|
|
413
|
+
let promptRegistration;
|
|
414
|
+
if (scope === 'global' && config.instructionsConfig) {
|
|
415
|
+
promptRegistration = ensureInstructionsEntry(
|
|
416
|
+
path.join(config.globalDir, config.instructionsConfig),
|
|
417
|
+
path.join(promptTarget, promptFile)
|
|
418
|
+
);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
return { promptRegistration };
|
|
211
422
|
}
|
|
212
423
|
|
|
213
424
|
function initializeBrain(overrideBase) {
|
|
214
|
-
|
|
425
|
+
// Honors $BRAIN_DIR (via getBrainDir) so a fresh brain is created wherever the
|
|
426
|
+
// user points it — e.g. inside a Google Drive / Dropbox / iCloud synced folder.
|
|
427
|
+
const brainDir = overrideBase ? path.join(overrideBase, '.brain') : getBrainDir();
|
|
215
428
|
|
|
216
429
|
if (fs.existsSync(brainDir)) {
|
|
217
430
|
return { alreadyExists: true };
|
|
@@ -277,6 +490,12 @@ function initializeBrain(overrideBase) {
|
|
|
277
490
|
JSON.stringify({ version: 1, archived_count: 0, memories: {} }, null, 2) + '\n'
|
|
278
491
|
);
|
|
279
492
|
|
|
493
|
+
// Create search-index.json (TF-IDF)
|
|
494
|
+
fs.writeFileSync(
|
|
495
|
+
path.join(brainDir, 'search-index.json'),
|
|
496
|
+
JSON.stringify({ version: 1, doc_count: 0, documents: {}, df: {} }, null, 2) + '\n'
|
|
497
|
+
);
|
|
498
|
+
|
|
280
499
|
// Load category descriptions from template
|
|
281
500
|
const templatePath = path.join(PACKAGE_ROOT, 'templates', 'default-categories.json');
|
|
282
501
|
let template = { top_categories: [] };
|
|
@@ -330,6 +549,8 @@ module.exports = {
|
|
|
330
549
|
copyDir,
|
|
331
550
|
installSkills,
|
|
332
551
|
injectPrompt,
|
|
552
|
+
ensureInstructionsEntry,
|
|
553
|
+
removeInstructionsEntry,
|
|
333
554
|
installForRuntime,
|
|
334
555
|
initializeBrain,
|
|
335
556
|
detectInstallations,
|
package/src/pinning.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
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
|
+
validateBrainPath,
|
|
23
|
+
} = require('./index-manager');
|
|
24
|
+
|
|
25
|
+
/** chars/4 token estimate; falls back to the title line for older entries. */
|
|
26
|
+
function estimateTokens(entry) {
|
|
27
|
+
if (entry && typeof entry.token_estimate === 'number') return entry.token_estimate;
|
|
28
|
+
return Math.ceil((((entry && entry.title) || '').length + 8) / 4);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Update-or-insert scalar YAML frontmatter fields in a memory file (best effort;
|
|
33
|
+
* the index entry remains the source of truth if the file is unreadable).
|
|
34
|
+
*
|
|
35
|
+
* A `null` value REMOVES the field's line (used by quarantine approval to strip
|
|
36
|
+
* flags). Keys listed in `opts.raw` are written verbatim, without quoting —
|
|
37
|
+
* for pre-formatted YAML values like inline arrays.
|
|
38
|
+
*/
|
|
39
|
+
function setFrontmatterFields(brainDir, memPath, fields, opts = {}) {
|
|
40
|
+
const fullPath = path.join(brainDir, memPath);
|
|
41
|
+
let content;
|
|
42
|
+
// Best-effort contract: on a path violation (tampered/synced-in index entry
|
|
43
|
+
// pointing outside ~/.brain) the file write is skipped — the index entry
|
|
44
|
+
// remains the source of truth either way.
|
|
45
|
+
try { validateBrainPath(fullPath, brainDir); } catch (_) { return; }
|
|
46
|
+
try { content = fs.readFileSync(fullPath, 'utf-8'); } catch (_) { return; }
|
|
47
|
+
|
|
48
|
+
const first = content.indexOf('---');
|
|
49
|
+
const second = content.indexOf('---', first + 3);
|
|
50
|
+
if (first === -1 || second === -1) return;
|
|
51
|
+
|
|
52
|
+
const raw = new Set(opts.raw || []);
|
|
53
|
+
let fm = content.slice(first + 3, second);
|
|
54
|
+
const inserts = [];
|
|
55
|
+
for (const [key, value] of Object.entries(fields)) {
|
|
56
|
+
const re = new RegExp(`^(${key}:\\s*).*$`, 'm');
|
|
57
|
+
if (value === null) {
|
|
58
|
+
fm = fm.replace(new RegExp(`^${key}:.*\\n?`, 'm'), '');
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const formatted = raw.has(key) || typeof value !== 'string' ? String(value) : `"${value}"`;
|
|
62
|
+
if (re.test(fm)) fm = fm.replace(re, `$1${formatted}`);
|
|
63
|
+
else inserts.push(`${key}: ${formatted}\n`);
|
|
64
|
+
}
|
|
65
|
+
if (inserts.length) fm = fm.replace(/\s*$/, '\n') + inserts.join('');
|
|
66
|
+
|
|
67
|
+
content = content.slice(0, first + 3) + fm + content.slice(second);
|
|
68
|
+
fs.writeFileSync(fullPath, content);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Pin a memory (always-loaded). Sets pinned/pin_scope/pin_priority on the index
|
|
73
|
+
* entry + frontmatter and records it in pinned.json.
|
|
74
|
+
*
|
|
75
|
+
* @param {string} [projectRoot] - Filesystem root (undefined = real ~/.brain)
|
|
76
|
+
* @param {string} id - Memory ID
|
|
77
|
+
* @param {Object} [opts] - { scope = "global"|"project:<name>", priority = 0 }
|
|
78
|
+
* @returns {Object} Result or { error }
|
|
79
|
+
*/
|
|
80
|
+
function pinMemory(projectRoot, id, opts = {}) {
|
|
81
|
+
const scope = opts.scope || 'global';
|
|
82
|
+
const priority = Number.isFinite(opts.priority) ? opts.priority : 0;
|
|
83
|
+
|
|
84
|
+
const index = readIndex(projectRoot);
|
|
85
|
+
if (!index || !index.memories || !index.memories[id]) {
|
|
86
|
+
return { error: `Memory not found: ${id}` };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const entry = index.memories[id];
|
|
90
|
+
// ASI06: pinning is entrenchment — a memory still pending verification must
|
|
91
|
+
// not reach the always-present tier. memorize already refuses born-pinned
|
|
92
|
+
// low-trust writes; this closes the flag-then-pin bypass.
|
|
93
|
+
if (entry.quarantined) {
|
|
94
|
+
return {
|
|
95
|
+
error: `Memory is pending verification — approve it first: brain verify approve ${id}`,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
entry.pinned = true;
|
|
99
|
+
entry.pin_scope = scope;
|
|
100
|
+
entry.pin_priority = priority;
|
|
101
|
+
writeIndex(index, projectRoot);
|
|
102
|
+
|
|
103
|
+
setFrontmatterFields(getBrainDir(projectRoot), entry.path, {
|
|
104
|
+
pinned: true,
|
|
105
|
+
pin_scope: scope,
|
|
106
|
+
pin_priority: priority,
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const pinned = readPinned(projectRoot);
|
|
110
|
+
pinned.pins = pinned.pins.filter((p) => p.id !== id);
|
|
111
|
+
pinned.pins.push({ id, scope, priority, token_estimate: estimateTokens(entry) });
|
|
112
|
+
writePinned(pinned, projectRoot);
|
|
113
|
+
|
|
114
|
+
return { id, pinned: true, scope, priority };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Unpin a memory. Clears the pinned flag and removes it from pinned.json. Leaves
|
|
119
|
+
* an independent `stable` flag untouched.
|
|
120
|
+
*
|
|
121
|
+
* @param {string} [projectRoot] - Filesystem root (undefined = real ~/.brain)
|
|
122
|
+
* @param {string} id - Memory ID
|
|
123
|
+
* @returns {Object} Result or { error }
|
|
124
|
+
*/
|
|
125
|
+
function unpinMemory(projectRoot, id) {
|
|
126
|
+
const index = readIndex(projectRoot);
|
|
127
|
+
if (!index || !index.memories || !index.memories[id]) {
|
|
128
|
+
return { error: `Memory not found: ${id}` };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const entry = index.memories[id];
|
|
132
|
+
const wasPinned = !!entry.pinned;
|
|
133
|
+
entry.pinned = false;
|
|
134
|
+
writeIndex(index, projectRoot);
|
|
135
|
+
|
|
136
|
+
setFrontmatterFields(getBrainDir(projectRoot), entry.path, { pinned: false });
|
|
137
|
+
|
|
138
|
+
const pinned = readPinned(projectRoot);
|
|
139
|
+
const before = pinned.pins.length;
|
|
140
|
+
pinned.pins = pinned.pins.filter((p) => p.id !== id);
|
|
141
|
+
writePinned(pinned, projectRoot);
|
|
142
|
+
|
|
143
|
+
return { id, pinned: false, was_pinned: wasPinned, removed: before !== pinned.pins.length };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
module.exports = { pinMemory, unpinMemory, estimateTokens, setFrontmatterFields };
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brain Memory — Provenance Policy (OWASP ASI06: memory poisoning)
|
|
3
|
+
*
|
|
4
|
+
* Single source of truth for what a memory's origin allows it to claim — at
|
|
5
|
+
* write time (bin/memorize.js clamps salience/confidence and refuses
|
|
6
|
+
* entrenchment) and at recall time (src/scorer.js weighs trust into ranking,
|
|
7
|
+
* bin/recall.js and bin/session-start.js flag low-trust results).
|
|
8
|
+
*
|
|
9
|
+
* The failure mode this defends against: content the agent *read* (an email, a
|
|
10
|
+
* web page, a tool result) persuades it to write a fact, and that fact then
|
|
11
|
+
* hardens — pinned into every session, exempt from decay, immune to pruning,
|
|
12
|
+
* never flagged as uncertain, and boosted by its own planted neighbors at
|
|
13
|
+
* recall. See MemGhost (arXiv:2607.05189).
|
|
14
|
+
*
|
|
15
|
+
* `origin` is asserted by the caller, so it does not defend against a fully
|
|
16
|
+
* hostile agent — but the dominant real case is an *honest* agent relaying
|
|
17
|
+
* poisoned content, and there it holds.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const ORIGIN_POLICY = {
|
|
21
|
+
// The user asked for this directly, in-session.
|
|
22
|
+
user: { max_salience: 1.0, max_confidence: 1.0, allow_entrench: true, decay_multiplier: 1.0, trust_factor: 1.0 },
|
|
23
|
+
// The agent inferred or summarized it from session context. Default.
|
|
24
|
+
'agent-inferred': { max_salience: 0.6, max_confidence: 0.8, allow_entrench: false, decay_multiplier: 1.0, trust_factor: 0.95 },
|
|
25
|
+
// Derived from tool output — file reads, command results, MCP responses.
|
|
26
|
+
'tool-output': { max_salience: 0.5, max_confidence: 0.6, allow_entrench: false, decay_multiplier: 0.997, trust_factor: 0.85 },
|
|
27
|
+
// Derived from untrusted external content — email, web pages, issue text.
|
|
28
|
+
external: { max_salience: 0.4, max_confidence: 0.4, allow_entrench: false, decay_multiplier: 0.99, trust_factor: 0.75 },
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// Absent origin means the agent didn't tell us — assume the weaker claim, never
|
|
32
|
+
// the stronger one. A memory that deserves `user` is one keystroke away.
|
|
33
|
+
const DEFAULT_ORIGIN = 'agent-inferred';
|
|
34
|
+
|
|
35
|
+
// Salience >= 0.7 is exempt from auto-pruning, so every non-user ceiling sits
|
|
36
|
+
// below it: an unattended poisoned memory must remain collectable.
|
|
37
|
+
const PRUNE_EXEMPT_SALIENCE = 0.7;
|
|
38
|
+
|
|
39
|
+
// Origins whose content came from outside the user/agent dialogue — surfaced
|
|
40
|
+
// with a low_trust flag at recall and a ⚠ marker on receipts.
|
|
41
|
+
const LOW_TRUST_ORIGINS = new Set(['tool-output', 'external']);
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Recall-time trust weight for an origin (0.75-1.0).
|
|
45
|
+
*
|
|
46
|
+
* Applied as a multiplier on the composite recall score and on spreading-
|
|
47
|
+
* activation source strength. Trust bounds *entrenchment and volume*, not
|
|
48
|
+
* relevance: a genuinely more relevant external memory can still rank first —
|
|
49
|
+
* it just can't get there on bulk or clique self-amplification.
|
|
50
|
+
*
|
|
51
|
+
* Unknown/missing origins weigh as DEFAULT_ORIGIN: legacy memories (written
|
|
52
|
+
* before origin existed) rank exactly as if memorize had stamped its default,
|
|
53
|
+
* so their relative order is unchanged.
|
|
54
|
+
*
|
|
55
|
+
* @param {string} [origin] - Memory origin (frontmatter/index `origin` field)
|
|
56
|
+
* @returns {number} Trust factor
|
|
57
|
+
*/
|
|
58
|
+
function trustFactor(origin) {
|
|
59
|
+
const policy = ORIGIN_POLICY[origin] || ORIGIN_POLICY[DEFAULT_ORIGIN];
|
|
60
|
+
return policy.trust_factor;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Whether an origin is low-trust (content sourced outside the dialogue).
|
|
65
|
+
*
|
|
66
|
+
* @param {string} [origin] - Memory origin
|
|
67
|
+
* @returns {boolean}
|
|
68
|
+
*/
|
|
69
|
+
function isLowTrust(origin) {
|
|
70
|
+
return LOW_TRUST_ORIGINS.has(origin);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
module.exports = {
|
|
74
|
+
ORIGIN_POLICY,
|
|
75
|
+
DEFAULT_ORIGIN,
|
|
76
|
+
PRUNE_EXEMPT_SALIENCE,
|
|
77
|
+
trustFactor,
|
|
78
|
+
isLowTrust,
|
|
79
|
+
};
|