brain-memory 0.1.0-beta.2 → 0.1.0-beta.21
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/README.md +272 -72
- package/assets/icon.png +0 -0
- package/assets/icon.svg +27 -0
- package/bin/brain.js +111 -0
- package/bin/cloud-sync.js +149 -0
- package/bin/install.js +217 -242
- package/bin/memorize.js +436 -0
- package/bin/pin.js +44 -0
- package/bin/recall.js +237 -0
- package/bin/reinforce.js +187 -0
- package/bin/session-start.js +292 -0
- package/bin/skill.js +67 -0
- package/bin/unpin.js +38 -0
- package/commands/brain/consolidate.md +7 -2
- package/commands/brain/explore.md +7 -2
- package/commands/brain/forget.md +7 -2
- package/commands/brain/init.md +8 -12
- package/commands/brain/memorize.md +76 -144
- package/commands/brain/pin.md +37 -0
- package/commands/brain/remember.md +48 -105
- package/commands/brain/review.md +7 -2
- package/commands/brain/skills.md +60 -0
- package/commands/brain/sleep.md +68 -27
- package/commands/brain/status.md +19 -5
- package/commands/brain/sunshine.md +18 -13
- package/commands/brain/sync.md +360 -0
- package/commands/brain/unpin.md +26 -0
- package/package.json +18 -8
- package/prompts/claude.md +115 -12
- package/prompts/gemini.md +115 -12
- package/prompts/openai.md +113 -10
- package/prompts/opencode.md +178 -0
- package/src/cloud-sync.js +534 -0
- package/src/crypto.js +130 -0
- package/src/export-import.js +200 -0
- package/src/git-sync.js +444 -0
- package/src/index-manager.js +205 -18
- package/src/installer.js +384 -0
- package/src/pinning.js +124 -0
- package/src/scorer.js +8 -2
- package/src/skills.js +208 -0
- package/src/tfidf.js +408 -0
- package/hooks/session-end.md +0 -48
- package/hooks/session-start.md +0 -48
package/bin/reinforce.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Brain Memory — Deterministic Reinforcement Engine
|
|
5
|
+
*
|
|
6
|
+
* Applies spaced reinforcement and Hebbian co-retrieval strengthening
|
|
7
|
+
* to recalled memories. The agent calls this after presenting recall
|
|
8
|
+
* results instead of manually updating frontmatter.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* brain reinforce mem_123 mem_456 mem_789
|
|
12
|
+
* brain reinforce mem_123 --project my-app
|
|
13
|
+
*
|
|
14
|
+
* Effects:
|
|
15
|
+
* - Spaced reinforcement boost to each memory's strength
|
|
16
|
+
* - Decay rate improvement (more forgetting-resistant)
|
|
17
|
+
* - access_count++, last_accessed = now
|
|
18
|
+
* - Hebbian co-retrieval: strengthens association edges between all pairs
|
|
19
|
+
* - Updates index.json, associations.json, and memory files
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
const fs = require('fs');
|
|
23
|
+
const path = require('path');
|
|
24
|
+
const os = require('os');
|
|
25
|
+
|
|
26
|
+
const {
|
|
27
|
+
readIndex,
|
|
28
|
+
writeIndex,
|
|
29
|
+
readAssociations,
|
|
30
|
+
writeAssociations,
|
|
31
|
+
reinforceEdge,
|
|
32
|
+
getBrainDir,
|
|
33
|
+
} = require('../src/index-manager');
|
|
34
|
+
|
|
35
|
+
const {
|
|
36
|
+
reinforceStrength,
|
|
37
|
+
improveDecayRate,
|
|
38
|
+
} = require('../src/scorer');
|
|
39
|
+
|
|
40
|
+
function main() {
|
|
41
|
+
const args = parseArgs(process.argv.slice(2));
|
|
42
|
+
|
|
43
|
+
if (args.memoryIds.length === 0) {
|
|
44
|
+
console.error(JSON.stringify({ error: 'Usage: brain reinforce <mem_id1> [mem_id2] ...' }));
|
|
45
|
+
process.exit(1);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const brainDir = getBrainDir();
|
|
49
|
+
let index;
|
|
50
|
+
try {
|
|
51
|
+
index = readIndex();
|
|
52
|
+
} catch (err) {
|
|
53
|
+
console.error(JSON.stringify({
|
|
54
|
+
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
55
|
+
}));
|
|
56
|
+
process.exit(1);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (!index) {
|
|
60
|
+
console.error(JSON.stringify({ error: 'Brain not initialized.' }));
|
|
61
|
+
process.exit(1);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const now = new Date();
|
|
65
|
+
const nowISO = now.toISOString();
|
|
66
|
+
const reinforced = [];
|
|
67
|
+
|
|
68
|
+
// Apply spaced reinforcement to each memory
|
|
69
|
+
for (const memId of args.memoryIds) {
|
|
70
|
+
const entry = index.memories[memId];
|
|
71
|
+
if (!entry) continue;
|
|
72
|
+
|
|
73
|
+
const lastAccessed = new Date(entry.last_accessed || entry.created);
|
|
74
|
+
const daysSince = (now - lastAccessed) / (1000 * 60 * 60 * 24);
|
|
75
|
+
const accessCount = entry.access_count || 0;
|
|
76
|
+
|
|
77
|
+
// Compute boost
|
|
78
|
+
const oldStrength = entry.strength;
|
|
79
|
+
const newStrength = reinforceStrength(oldStrength, daysSince, accessCount);
|
|
80
|
+
const newDecayRate = improveDecayRate(entry.decay_rate);
|
|
81
|
+
|
|
82
|
+
// Update index entry
|
|
83
|
+
entry.strength = Math.round(newStrength * 1000) / 1000;
|
|
84
|
+
entry.decay_rate = Math.round(newDecayRate * 10000) / 10000;
|
|
85
|
+
entry.last_accessed = nowISO;
|
|
86
|
+
entry.access_count = accessCount + 1;
|
|
87
|
+
|
|
88
|
+
// Update the memory file's frontmatter on disk
|
|
89
|
+
updateMemoryFile(brainDir, entry.path, {
|
|
90
|
+
strength: entry.strength,
|
|
91
|
+
decay_rate: entry.decay_rate,
|
|
92
|
+
last_accessed: nowISO,
|
|
93
|
+
access_count: entry.access_count,
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
reinforced.push({
|
|
97
|
+
id: memId,
|
|
98
|
+
old_strength: oldStrength,
|
|
99
|
+
new_strength: entry.strength,
|
|
100
|
+
boost: Math.round((newStrength - oldStrength) * 1000) / 1000,
|
|
101
|
+
decay_rate: entry.decay_rate,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Save index
|
|
106
|
+
writeIndex(index);
|
|
107
|
+
|
|
108
|
+
// Hebbian co-retrieval: strengthen edges between all pairs
|
|
109
|
+
let edgesReinforced = 0;
|
|
110
|
+
if (args.memoryIds.length > 1) {
|
|
111
|
+
let associations = readAssociations() || { version: 1, edges: {} };
|
|
112
|
+
|
|
113
|
+
for (let i = 0; i < args.memoryIds.length; i++) {
|
|
114
|
+
for (let j = i + 1; j < args.memoryIds.length; j++) {
|
|
115
|
+
const idA = args.memoryIds[i];
|
|
116
|
+
const idB = args.memoryIds[j];
|
|
117
|
+
// Only reinforce if both exist in index
|
|
118
|
+
if (index.memories[idA] && index.memories[idB]) {
|
|
119
|
+
reinforceEdge(associations, idA, idB, 'co_retrieval');
|
|
120
|
+
edgesReinforced++;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
writeAssociations(associations);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
console.log(JSON.stringify({
|
|
129
|
+
reinforced,
|
|
130
|
+
edges_reinforced: edgesReinforced,
|
|
131
|
+
}, null, 2));
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Update a memory file's YAML frontmatter fields on disk.
|
|
136
|
+
*
|
|
137
|
+
* @param {string} brainDir - Path to ~/.brain/
|
|
138
|
+
* @param {string} memPath - Relative path to memory file
|
|
139
|
+
* @param {Object} updates - Fields to update in frontmatter
|
|
140
|
+
*/
|
|
141
|
+
function updateMemoryFile(brainDir, memPath, updates) {
|
|
142
|
+
const fullPath = path.join(brainDir, memPath);
|
|
143
|
+
try {
|
|
144
|
+
let content = fs.readFileSync(fullPath, 'utf-8');
|
|
145
|
+
|
|
146
|
+
// Find frontmatter boundaries
|
|
147
|
+
const firstDash = content.indexOf('---');
|
|
148
|
+
const secondDash = content.indexOf('---', firstDash + 3);
|
|
149
|
+
if (firstDash === -1 || secondDash === -1) return;
|
|
150
|
+
|
|
151
|
+
let frontmatter = content.slice(firstDash + 3, secondDash);
|
|
152
|
+
|
|
153
|
+
// Update each field in the YAML
|
|
154
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
155
|
+
const regex = new RegExp(`^(${key}:\\s*).*$`, 'm');
|
|
156
|
+
const formatted = typeof value === 'string' ? `"${value}"` : String(value);
|
|
157
|
+
if (regex.test(frontmatter)) {
|
|
158
|
+
frontmatter = frontmatter.replace(regex, `$1${formatted}`);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
content = content.slice(0, firstDash + 3) + frontmatter + content.slice(secondDash);
|
|
163
|
+
fs.writeFileSync(fullPath, content);
|
|
164
|
+
} catch { /* skip if file not readable/writable */ }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Parse CLI arguments.
|
|
169
|
+
*/
|
|
170
|
+
function parseArgs(argv) {
|
|
171
|
+
const args = {
|
|
172
|
+
memoryIds: [],
|
|
173
|
+
project: null,
|
|
174
|
+
};
|
|
175
|
+
|
|
176
|
+
for (let i = 0; i < argv.length; i++) {
|
|
177
|
+
if (argv[i] === '--project') {
|
|
178
|
+
args.project = argv[++i];
|
|
179
|
+
} else if (!argv[i].startsWith('--')) {
|
|
180
|
+
args.memoryIds.push(argv[i]);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return args;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
main();
|
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* brain session-start — budget-aware working-memory payload (CoALA Phase 0).
|
|
5
|
+
*
|
|
6
|
+
* One deterministic call returning everything the agent should internalize at
|
|
7
|
+
* session start, bounded by the working-memory token budget in config.json so
|
|
8
|
+
* Brain can never bloat the host's context window.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* brain session-start [--project P] [--topics a,b] [--task T] [--top N]
|
|
12
|
+
*
|
|
13
|
+
* Output (JSON):
|
|
14
|
+
* {
|
|
15
|
+
* memory_count, pinned[], skills_index[], context_recall[],
|
|
16
|
+
* due_for_review, low_confidence_alerts[], budget{}
|
|
17
|
+
* }
|
|
18
|
+
*
|
|
19
|
+
* pinned[] (Phase 1) and skills_index[] (Phase 2) are present but empty here;
|
|
20
|
+
* the budget framework already accounts for them so later phases just fill in.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const fs = require('fs');
|
|
24
|
+
const path = require('path');
|
|
25
|
+
|
|
26
|
+
const {
|
|
27
|
+
readSearchIndex,
|
|
28
|
+
writeSearchIndex,
|
|
29
|
+
search,
|
|
30
|
+
rebuildIndex,
|
|
31
|
+
} = require('../src/tfidf');
|
|
32
|
+
|
|
33
|
+
const {
|
|
34
|
+
readIndex,
|
|
35
|
+
readAssociations,
|
|
36
|
+
readReviewQueue,
|
|
37
|
+
readConfig,
|
|
38
|
+
getBrainDir,
|
|
39
|
+
} = require('../src/index-manager');
|
|
40
|
+
|
|
41
|
+
const { rankMemories } = require('../src/scorer');
|
|
42
|
+
const { advertisedSummaries } = require('../src/skills');
|
|
43
|
+
|
|
44
|
+
function parseArgs(argv) {
|
|
45
|
+
const args = { project: null, topics: null, task: null, top: 5 };
|
|
46
|
+
for (let i = 0; i < argv.length; i++) {
|
|
47
|
+
switch (argv[i]) {
|
|
48
|
+
case '--project': args.project = argv[++i]; break;
|
|
49
|
+
case '--topics': args.topics = argv[++i]; break;
|
|
50
|
+
case '--task': args.task = argv[++i]; break;
|
|
51
|
+
case '--top': args.top = parseInt(argv[++i], 10) || 5; break;
|
|
52
|
+
default: break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return args;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** chars/4 token estimate; falls back to the title line for pre-Phase-0 entries. */
|
|
59
|
+
function estimateTokens(entry) {
|
|
60
|
+
if (typeof entry.token_estimate === 'number') return entry.token_estimate;
|
|
61
|
+
return Math.ceil(((entry.title || '').length + 8) / 4);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Tier B §10.4 — reorder an importance-sorted list so the top items land at the
|
|
66
|
+
* edges (start + end), where models attend best, leaving the middle for lower
|
|
67
|
+
* ranks. Deterministic. e.g. [1,2,3,4,5] → [1,3,5,4,2].
|
|
68
|
+
*/
|
|
69
|
+
function edgeOrder(arr) {
|
|
70
|
+
const front = [];
|
|
71
|
+
const back = [];
|
|
72
|
+
arr.forEach((item, i) => { if (i % 2 === 0) front.push(item); else back.unshift(item); });
|
|
73
|
+
return front.concat(back);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Read a memory file's body (content after the frontmatter block). */
|
|
77
|
+
function readMemoryBody(brainDir, memPath) {
|
|
78
|
+
try {
|
|
79
|
+
const content = fs.readFileSync(path.join(brainDir, memPath), 'utf-8');
|
|
80
|
+
const first = content.indexOf('---');
|
|
81
|
+
const second = content.indexOf('---', first + 3);
|
|
82
|
+
if (first !== -1 && second !== -1) return content.slice(second + 3).trim();
|
|
83
|
+
return content.trim();
|
|
84
|
+
} catch (_) {
|
|
85
|
+
return '';
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function buildContextQuery(args) {
|
|
90
|
+
const parts = [];
|
|
91
|
+
if (args.project) parts.push(args.project);
|
|
92
|
+
if (args.topics) parts.push(args.topics);
|
|
93
|
+
if (args.task) parts.push(args.task);
|
|
94
|
+
return parts.length > 0 ? parts.join(' ') : '*';
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Compute the session-start payload for the brain at `projectRoot` (undefined =
|
|
99
|
+
* the real ~/.brain). Pure: performs no console output and never calls exit, so
|
|
100
|
+
* it is directly unit-testable.
|
|
101
|
+
*
|
|
102
|
+
* @param {string} [projectRoot] - Filesystem root whose .brain/ to read
|
|
103
|
+
* @param {Object} [args] - { project, topics, task, top }
|
|
104
|
+
* @returns {Object} The session-start payload
|
|
105
|
+
*/
|
|
106
|
+
function computeSessionStart(projectRoot, args = {}) {
|
|
107
|
+
const top = args.top || 5;
|
|
108
|
+
const brainDir = getBrainDir(projectRoot);
|
|
109
|
+
const config = readConfig(projectRoot);
|
|
110
|
+
const cap = config.working_memory_budget_tokens;
|
|
111
|
+
|
|
112
|
+
const empty = {
|
|
113
|
+
memory_count: 0,
|
|
114
|
+
pinned: [], // Phase 1: always-present semantic tier
|
|
115
|
+
skills_index: [], // Phase 2: procedural skill summaries
|
|
116
|
+
context_recall: [],
|
|
117
|
+
due_for_review: 0,
|
|
118
|
+
low_confidence_alerts: [],
|
|
119
|
+
budget: { cap, recall_cap: config.recall_budget_tokens, used: 0, included: 0, excluded: 0 },
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
if (!fs.existsSync(path.join(brainDir, 'index.json'))) return empty;
|
|
123
|
+
|
|
124
|
+
const index = readIndex(projectRoot);
|
|
125
|
+
if (!index || !index.memories) return empty;
|
|
126
|
+
|
|
127
|
+
// Note: we proceed even with zero memories — pins and skills are independent
|
|
128
|
+
// of episodic memory and should still be surfaced.
|
|
129
|
+
const memoryCount = Object.keys(index.memories).length;
|
|
130
|
+
|
|
131
|
+
// --- Context recall (deterministic, reuses the recall engine) ---
|
|
132
|
+
let searchIndex = null;
|
|
133
|
+
try { searchIndex = readSearchIndex(brainDir); } catch (_) { searchIndex = null; }
|
|
134
|
+
if (!searchIndex) {
|
|
135
|
+
searchIndex = rebuildIndex(brainDir, index);
|
|
136
|
+
writeSearchIndex(brainDir, searchIndex);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const tfidfScores = search(searchIndex, buildContextQuery(args));
|
|
140
|
+
const memories = Object.entries(index.memories).map(([id, entry]) => ({ id, ...entry }));
|
|
141
|
+
|
|
142
|
+
let associations = null;
|
|
143
|
+
try { associations = readAssociations(projectRoot); } catch (_) { associations = null; }
|
|
144
|
+
|
|
145
|
+
const recallContext = {};
|
|
146
|
+
if (args.project) recallContext.project = args.project;
|
|
147
|
+
if (args.task) recallContext.task_type = args.task;
|
|
148
|
+
if (args.topics) recallContext.topics = String(args.topics).split(',');
|
|
149
|
+
|
|
150
|
+
const ranked = rankMemories(
|
|
151
|
+
memories,
|
|
152
|
+
(mem) => tfidfScores[mem.id] || 0,
|
|
153
|
+
{
|
|
154
|
+
associations: associations || undefined,
|
|
155
|
+
recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
|
|
156
|
+
}
|
|
157
|
+
);
|
|
158
|
+
|
|
159
|
+
// --- Pinned tier (CoALA Phase 1): always present, scope-filtered, budget-capped ---
|
|
160
|
+
// The index entry is the source of truth (pinned.json is a maintained cache);
|
|
161
|
+
// scanning the index here avoids manifest/index drift.
|
|
162
|
+
const pinnedCandidates = [];
|
|
163
|
+
for (const [id, entry] of Object.entries(index.memories)) {
|
|
164
|
+
if (!entry.pinned) continue;
|
|
165
|
+
const scope = entry.pin_scope || 'global';
|
|
166
|
+
if (scope !== 'global') {
|
|
167
|
+
const scopedProject = scope.startsWith('project:') ? scope.slice('project:'.length) : null;
|
|
168
|
+
if (!args.project || scopedProject !== args.project) continue; // out-of-project pin
|
|
169
|
+
}
|
|
170
|
+
pinnedCandidates.push({ id, entry, scope, priority: entry.pin_priority || 0 });
|
|
171
|
+
}
|
|
172
|
+
pinnedCandidates.sort((a, b) =>
|
|
173
|
+
(b.priority - a.priority) ||
|
|
174
|
+
((b.entry.strength || 0) - (a.entry.strength || 0)) ||
|
|
175
|
+
(a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
|
|
176
|
+
);
|
|
177
|
+
|
|
178
|
+
const pinned = [];
|
|
179
|
+
let pinnedTokens = 0;
|
|
180
|
+
let pinnedExcluded = 0;
|
|
181
|
+
const pinCap = Math.min(config.pin_budget_tokens, cap);
|
|
182
|
+
for (const c of pinnedCandidates) {
|
|
183
|
+
const est = estimateTokens(c.entry);
|
|
184
|
+
if (pinnedTokens + est > pinCap && pinned.length > 0) { pinnedExcluded++; continue; }
|
|
185
|
+
pinned.push({
|
|
186
|
+
id: c.id,
|
|
187
|
+
title: c.entry.title,
|
|
188
|
+
content: readMemoryBody(brainDir, c.entry.path),
|
|
189
|
+
scope: c.scope,
|
|
190
|
+
priority: c.priority,
|
|
191
|
+
tokens: est,
|
|
192
|
+
});
|
|
193
|
+
pinnedTokens += est;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// --- Skills index (CoALA Phase 2): advertise name + description only (L0) ---
|
|
197
|
+
const skills_index = [];
|
|
198
|
+
let skillsTokens = 0;
|
|
199
|
+
let skillsExcluded = 0;
|
|
200
|
+
const skillsCap = Math.min(config.skills_index_budget_tokens, Math.max(0, cap - pinnedTokens));
|
|
201
|
+
for (const s of advertisedSummaries(projectRoot)) {
|
|
202
|
+
const est = Math.ceil(((s.name || '').length + (s.description || '').length + 8) / 4);
|
|
203
|
+
if (skillsTokens + est > skillsCap && skills_index.length > 0) { skillsExcluded++; continue; }
|
|
204
|
+
skills_index.push({ name: s.name, description: s.description });
|
|
205
|
+
skillsTokens += est;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// --- Budget-bound the recall set with whatever the pin/skills tiers leave ---
|
|
209
|
+
const recallCap = Math.max(0, Math.min(config.recall_budget_tokens, cap - pinnedTokens - skillsTokens));
|
|
210
|
+
const pinnedIds = new Set(pinned.map((p) => p.id));
|
|
211
|
+
|
|
212
|
+
const context_recall = [];
|
|
213
|
+
let used = 0;
|
|
214
|
+
let excluded = 0;
|
|
215
|
+
for (const mem of ranked.slice(0, top)) {
|
|
216
|
+
if (pinnedIds.has(mem.id)) continue; // already presented in the pinned tier
|
|
217
|
+
const est = estimateTokens(mem);
|
|
218
|
+
if (used + est > recallCap && context_recall.length > 0) {
|
|
219
|
+
excluded++;
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
context_recall.push({
|
|
223
|
+
id: mem.id,
|
|
224
|
+
title: mem.title || path.basename(mem.path || '', '.md'),
|
|
225
|
+
path: mem.path,
|
|
226
|
+
type: mem.type,
|
|
227
|
+
score: mem.score,
|
|
228
|
+
token_estimate: est,
|
|
229
|
+
});
|
|
230
|
+
used += est;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// --- Due for review (matches the existing "has items" heuristic) ---
|
|
234
|
+
let dueForReview = 0;
|
|
235
|
+
try {
|
|
236
|
+
const queue = readReviewQueue(projectRoot);
|
|
237
|
+
if (queue && Array.isArray(queue.items)) dueForReview = queue.items.length;
|
|
238
|
+
} catch (_) { dueForReview = 0; }
|
|
239
|
+
|
|
240
|
+
// --- Low-confidence-but-frequently-used alerts ---
|
|
241
|
+
const low_confidence_alerts = [];
|
|
242
|
+
for (const [id, entry] of Object.entries(index.memories)) {
|
|
243
|
+
if ((entry.access_count || 0) >= 3 && (entry.confidence ?? 1) < 0.5) {
|
|
244
|
+
low_confidence_alerts.push({
|
|
245
|
+
id,
|
|
246
|
+
title: entry.title,
|
|
247
|
+
confidence: entry.confidence,
|
|
248
|
+
access_count: entry.access_count,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
return {
|
|
254
|
+
memory_count: memoryCount,
|
|
255
|
+
pinned,
|
|
256
|
+
skills_index,
|
|
257
|
+
context_recall: edgeOrder(context_recall), // Tier B §10.4: top ranks at the edges
|
|
258
|
+
due_for_review: dueForReview,
|
|
259
|
+
low_confidence_alerts,
|
|
260
|
+
budget: {
|
|
261
|
+
cap,
|
|
262
|
+
pin_cap: pinCap,
|
|
263
|
+
skills_cap: skillsCap,
|
|
264
|
+
recall_cap: recallCap,
|
|
265
|
+
used: pinnedTokens + skillsTokens + used,
|
|
266
|
+
pinned_tokens: pinnedTokens,
|
|
267
|
+
skills_tokens: skillsTokens,
|
|
268
|
+
recall_used: used,
|
|
269
|
+
included: context_recall.length,
|
|
270
|
+
excluded,
|
|
271
|
+
pinned_excluded: pinnedExcluded,
|
|
272
|
+
skills_excluded: skillsExcluded,
|
|
273
|
+
},
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function main(argv) {
|
|
278
|
+
const args = parseArgs(argv || process.argv.slice(2));
|
|
279
|
+
try {
|
|
280
|
+
const payload = computeSessionStart(undefined, args);
|
|
281
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
282
|
+
} catch (err) {
|
|
283
|
+
console.error(JSON.stringify({ error: err.message }));
|
|
284
|
+
process.exit(1);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (require.main === module) {
|
|
289
|
+
main(process.argv.slice(2));
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
module.exports = { main, computeSessionStart, estimateTokens, parseArgs, edgeOrder };
|
package/bin/skill.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* brain skill — manage procedural skills (CoALA Phase 2).
|
|
5
|
+
*
|
|
6
|
+
* Usage:
|
|
7
|
+
* brain skill list Advertised index (name + description)
|
|
8
|
+
* brain skill show <name> Full SKILL.md (L1 disclosure)
|
|
9
|
+
* brain skill use <name> [--failed] Record a use; success strengthens,
|
|
10
|
+
* --failed weakens (demotion feedback)
|
|
11
|
+
* brain skill remove <name> Delete a skill
|
|
12
|
+
* brain skill add Create a skill from JSON on stdin:
|
|
13
|
+
* { name, description, triggers[], body }
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const fs = require('fs');
|
|
17
|
+
const {
|
|
18
|
+
addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill,
|
|
19
|
+
} = require('../src/skills');
|
|
20
|
+
|
|
21
|
+
function emit(obj) { console.log(JSON.stringify(obj, null, 2)); }
|
|
22
|
+
function fail(obj) { console.error(JSON.stringify(obj)); process.exit(1); }
|
|
23
|
+
function done(result) { return result && result.error ? fail(result) : emit(result); }
|
|
24
|
+
|
|
25
|
+
const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|add|remove <name>|export <name> [--target claude|gemini]>';
|
|
26
|
+
|
|
27
|
+
function main(argv) {
|
|
28
|
+
const args = argv || process.argv.slice(2);
|
|
29
|
+
const action = args[0];
|
|
30
|
+
const rest = args.slice(1);
|
|
31
|
+
const firstName = rest.find((a) => !a.startsWith('--'));
|
|
32
|
+
|
|
33
|
+
switch (action) {
|
|
34
|
+
case 'list':
|
|
35
|
+
return emit(listSkills(undefined));
|
|
36
|
+
case 'show':
|
|
37
|
+
if (!firstName) return fail({ error: USAGE });
|
|
38
|
+
return done(showSkill(undefined, firstName));
|
|
39
|
+
case 'use':
|
|
40
|
+
if (!firstName) return fail({ error: USAGE });
|
|
41
|
+
return done(useSkill(undefined, firstName, { failed: rest.includes('--failed') }));
|
|
42
|
+
case 'remove':
|
|
43
|
+
if (!firstName) return fail({ error: USAGE });
|
|
44
|
+
return done(removeSkill(undefined, firstName));
|
|
45
|
+
case 'export': {
|
|
46
|
+
if (!firstName) return fail({ error: 'Usage: brain skill export <name> [--target claude|gemini]' });
|
|
47
|
+
const ti = rest.indexOf('--target');
|
|
48
|
+
const target = ti !== -1 ? rest[ti + 1] : 'claude';
|
|
49
|
+
return done(exportSkill(undefined, firstName, target));
|
|
50
|
+
}
|
|
51
|
+
case 'add': {
|
|
52
|
+
if (process.stdin.isTTY) return fail({ error: 'Pipe a skill JSON via stdin' });
|
|
53
|
+
let input;
|
|
54
|
+
try { input = JSON.parse(fs.readFileSync(0, 'utf-8')); }
|
|
55
|
+
catch (e) { return fail({ error: `Invalid JSON: ${e.message}` }); }
|
|
56
|
+
return done(addSkill(undefined, input));
|
|
57
|
+
}
|
|
58
|
+
default:
|
|
59
|
+
return fail({ error: USAGE });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
if (require.main === module) {
|
|
64
|
+
main(process.argv.slice(2));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
module.exports = { main };
|
package/bin/unpin.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* brain unpin — remove a memory from the always-present semantic tier.
|
|
5
|
+
*
|
|
6
|
+
* Usage:
|
|
7
|
+
* brain unpin <id>
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const { unpinMemory } = require('../src/pinning');
|
|
11
|
+
|
|
12
|
+
function parseArgs(argv) {
|
|
13
|
+
const args = { id: null };
|
|
14
|
+
for (const a of argv) {
|
|
15
|
+
if (!a.startsWith('--') && !args.id) args.id = a;
|
|
16
|
+
}
|
|
17
|
+
return args;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function main(argv) {
|
|
21
|
+
const args = parseArgs(argv || process.argv.slice(2));
|
|
22
|
+
if (!args.id) {
|
|
23
|
+
console.error(JSON.stringify({ error: 'Usage: brain unpin <id>' }));
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
const result = unpinMemory(undefined, args.id);
|
|
27
|
+
if (result.error) {
|
|
28
|
+
console.error(JSON.stringify(result));
|
|
29
|
+
process.exit(1);
|
|
30
|
+
}
|
|
31
|
+
console.log(JSON.stringify(result, null, 2));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
if (require.main === module) {
|
|
35
|
+
main(process.argv.slice(2));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
module.exports = { main, parseArgs };
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Merge related weak memories into stronger combined memories
|
|
3
|
+
argument-hint: "[scope]"
|
|
4
|
+
---
|
|
5
|
+
|
|
1
6
|
# /brain:consolidate — Merge Related Memories
|
|
2
7
|
|
|
3
8
|
You are consolidating memories in the Brain Memory system. Consolidation combines multiple related or weakening memories into a single stronger, more coherent memory — mimicking how human brains merge similar experiences into generalized knowledge.
|
|
@@ -9,7 +14,7 @@ You are consolidating memories in the Brain Memory system. Consolidation combine
|
|
|
9
14
|
### 1. Determine Scope
|
|
10
15
|
|
|
11
16
|
- If $ARGUMENTS specifies a category path, consolidate within that subtree
|
|
12
|
-
- If $ARGUMENTS is empty, scan the entire
|
|
17
|
+
- If $ARGUMENTS is empty, scan the entire `~/.brain/` for consolidation candidates
|
|
13
18
|
- If $ARGUMENTS is "auto", perform automatic consolidation based on thresholds
|
|
14
19
|
|
|
15
20
|
### 2. Find Consolidation Candidates
|
|
@@ -126,7 +131,7 @@ encoding_context:
|
|
|
126
131
|
|
|
127
132
|
### 7. Archive Source Memories
|
|
128
133
|
|
|
129
|
-
Move the original source memory files to a
|
|
134
|
+
Move the original source memory files to a `~/.brain/_archived/` directory (create if needed), preserving their paths as subdirectories. This keeps them recoverable and searchable via `/brain:remember`.
|
|
130
135
|
|
|
131
136
|
Update `index.json`:
|
|
132
137
|
- Remove archived memory entries from `memories`
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Browse the brain memory hierarchy
|
|
3
|
+
argument-hint: "[category]"
|
|
4
|
+
---
|
|
5
|
+
|
|
1
6
|
# /brain:explore — Browse the Brain Structure
|
|
2
7
|
|
|
3
8
|
You are exploring the Brain Memory system's hierarchical structure. This gives the user a visual overview of their memory landscape.
|
|
@@ -13,7 +18,7 @@ You are exploring the Brain Memory system's hierarchical structure. This gives t
|
|
|
13
18
|
|
|
14
19
|
### 2. Read Structure
|
|
15
20
|
|
|
16
|
-
Read the directory structure of
|
|
21
|
+
Read the directory structure of `~/.brain/` (or the specified subtree). For each directory, read its `_meta.json` to get metadata.
|
|
17
22
|
|
|
18
23
|
### 3. Display Tree View
|
|
19
24
|
|
|
@@ -24,7 +29,7 @@ Present the brain structure as a visual tree with statistics:
|
|
|
24
29
|
Last updated: <timestamp>
|
|
25
30
|
Total memories: <count>
|
|
26
31
|
|
|
27
|
-
|
|
32
|
+
~/.brain/
|
|
28
33
|
├── professional/ (12 memories)
|
|
29
34
|
│ ├── companies/ (8 memories)
|
|
30
35
|
│ │ ├── acme-corp/ (5 memories)
|
package/commands/brain/forget.md
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Decay or archive memories
|
|
3
|
+
argument-hint: "[target]"
|
|
4
|
+
---
|
|
5
|
+
|
|
1
6
|
# /brain:forget — Decay or Remove Memories
|
|
2
7
|
|
|
3
8
|
You are managing memory decay in the Brain Memory system. This command accelerates forgetting for specific memories or prunes memories that have naturally decayed below usefulness.
|
|
@@ -64,8 +69,8 @@ The user must explicitly choose an action. Default to **archive** (safest).
|
|
|
64
69
|
### 5. Execute
|
|
65
70
|
|
|
66
71
|
**Archive:**
|
|
67
|
-
- Move memory files to
|
|
68
|
-
- Add entry to
|
|
72
|
+
- Move memory files to `~/.brain/_archived/<original-path>/`
|
|
73
|
+
- Add entry to `~/.brain/_archived/index.json` with all original metadata:
|
|
69
74
|
```json
|
|
70
75
|
{
|
|
71
76
|
"<memory_id>": {
|