brain-memory 0.1.0-beta.3 → 0.1.0-beta.30
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 +319 -0
- package/README.md +379 -95
- package/SECURITY.md +61 -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/brain.js +111 -0
- package/bin/cloud-sync.js +150 -0
- package/bin/forget.js +122 -0
- package/bin/install.js +229 -254
- package/bin/memorize.js +458 -0
- package/bin/pin.js +44 -0
- package/bin/recall.js +251 -0
- package/bin/reinforce.js +187 -0
- package/bin/session-start.js +298 -0
- package/bin/skill.js +67 -0
- package/bin/unpin.js +38 -0
- package/commands/brain/forget.md +245 -15
- package/commands/brain/memorize.md +76 -144
- package/commands/brain/pin.md +79 -0
- package/commands/brain/remember.md +48 -105
- package/commands/brain/skills.md +60 -0
- package/commands/brain/sleep.md +69 -28
- package/commands/brain/status.md +24 -10
- package/commands/brain/sync.md +386 -0
- package/package.json +22 -8
- package/prompts/antigravity.md +180 -0
- package/prompts/claude.md +124 -20
- package/prompts/openai.md +124 -20
- package/prompts/opencode.md +179 -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 +219 -18
- package/src/installer.js +444 -0
- package/src/pinning.js +124 -0
- package/src/scorer.js +22 -9
- package/src/skills.js +208 -0
- package/src/tfidf.js +501 -0
- package/commands/brain/consolidate.md +0 -153
- package/commands/brain/explore.md +0 -79
- package/commands/brain/init.md +0 -157
- package/commands/brain/review.md +0 -130
- package/commands/brain/sunshine.md +0 -337
- package/hooks/session-end.md +0 -48
- package/hooks/session-start.md +0 -48
- package/prompts/gemini.md +0 -76
package/bin/memorize.js
ADDED
|
@@ -0,0 +1,458 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* brain memorize — Store memories from AI agent input
|
|
5
|
+
*
|
|
6
|
+
* Accepts a JSON payload via stdin with memory definitions.
|
|
7
|
+
* Handles all plumbing: ID generation, directory creation, file writing,
|
|
8
|
+
* index updates, association edges, search index, and optional sync.
|
|
9
|
+
*
|
|
10
|
+
* Usage:
|
|
11
|
+
* brain memorize [--sync] <<'EOF'
|
|
12
|
+
* { "memories": [{ "title": "...", "type": "learning", ... }] }
|
|
13
|
+
* EOF
|
|
14
|
+
*
|
|
15
|
+
* The AI agent decides WHAT to remember. This CLI handles HOW to write it.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
const { execSync } = require('child_process');
|
|
21
|
+
const {
|
|
22
|
+
getBrainDir,
|
|
23
|
+
readIndex,
|
|
24
|
+
writeIndex,
|
|
25
|
+
addMemory,
|
|
26
|
+
generateId,
|
|
27
|
+
readMeta,
|
|
28
|
+
writeMeta,
|
|
29
|
+
readAssociations,
|
|
30
|
+
writeAssociations,
|
|
31
|
+
reinforceEdge,
|
|
32
|
+
readPinned,
|
|
33
|
+
writePinned,
|
|
34
|
+
atomicWriteSync,
|
|
35
|
+
validateBrainPath,
|
|
36
|
+
} = require('../src/index-manager');
|
|
37
|
+
const { addDocument, createSearchIndex, readSearchIndex, writeSearchIndex } = require('../src/tfidf');
|
|
38
|
+
|
|
39
|
+
// Best-effort detection of the host AI agent, recorded on each memory's
|
|
40
|
+
// encoding_context for "where your brain is used" analytics. An explicit
|
|
41
|
+
// BRAIN_AGENT env var always wins (a per-agent install can set it); otherwise we
|
|
42
|
+
// sniff known markers. Unrecognized hosts record "unknown" (the cloud tolerates
|
|
43
|
+
// it). The non-Claude markers are best-effort.
|
|
44
|
+
function detectAgent() {
|
|
45
|
+
const e = process.env;
|
|
46
|
+
if (e.BRAIN_AGENT) return e.BRAIN_AGENT;
|
|
47
|
+
if (e.CLAUDECODE || e.CLAUDE_CODE_ENTRYPOINT) return 'claude-code';
|
|
48
|
+
if (e.GEMINI_CLI || e.GEMINI_CLI_VERSION) return 'gemini-cli';
|
|
49
|
+
if (e.CODEX_HOME || e.CODEX_SANDBOX) return 'codex';
|
|
50
|
+
if (e.OPENCODE || e.OPENCODE_BIN) return 'opencode';
|
|
51
|
+
return 'unknown';
|
|
52
|
+
}
|
|
53
|
+
const HOST_AGENT = detectAgent();
|
|
54
|
+
|
|
55
|
+
// --- Type defaults ---
|
|
56
|
+
|
|
57
|
+
const TYPE_DEFAULTS = {
|
|
58
|
+
decision: { strength: 0.85, decay_rate: 0.995 },
|
|
59
|
+
insight: { strength: 0.90, decay_rate: 0.997 },
|
|
60
|
+
goal: { strength: 0.80, decay_rate: 0.993 },
|
|
61
|
+
experience: { strength: 0.75, decay_rate: 0.985 },
|
|
62
|
+
learning: { strength: 0.70, decay_rate: 0.990 },
|
|
63
|
+
relationship: { strength: 0.70, decay_rate: 0.997 },
|
|
64
|
+
preference: { strength: 0.60, decay_rate: 0.998 },
|
|
65
|
+
observation: { strength: 0.40, decay_rate: 0.950 },
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
const COGNITIVE_ADJUSTMENTS = {
|
|
69
|
+
episodic: { strength_delta: +0.10, decay_multiplier: 0.995 },
|
|
70
|
+
semantic: { strength_delta: 0, decay_multiplier: 1.0 },
|
|
71
|
+
procedural: { strength_delta: -0.10, decay_multiplier: 1.003 },
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// --- Args ---
|
|
75
|
+
|
|
76
|
+
function parseArgs(argv) {
|
|
77
|
+
const args = { sync: false };
|
|
78
|
+
for (const arg of argv) {
|
|
79
|
+
if (arg === '--sync') args.sync = true;
|
|
80
|
+
}
|
|
81
|
+
return args;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// --- Helpers ---
|
|
85
|
+
|
|
86
|
+
function computeStrengthAndDecay(type, cognitiveType, strengthAdjustment = 0) {
|
|
87
|
+
const typeDefaults = TYPE_DEFAULTS[type] || TYPE_DEFAULTS.observation;
|
|
88
|
+
const cogAdj = COGNITIVE_ADJUSTMENTS[cognitiveType] || COGNITIVE_ADJUSTMENTS.semantic;
|
|
89
|
+
|
|
90
|
+
const strength = Math.max(0, Math.min(1.0,
|
|
91
|
+
typeDefaults.strength + cogAdj.strength_delta + strengthAdjustment
|
|
92
|
+
));
|
|
93
|
+
// Cap strictly below 1.0. Procedural memories are meant to decay *slowly*, but
|
|
94
|
+
// a multiplier that pushed decay_rate >= 1.0 would make effective strength GROW
|
|
95
|
+
// over time (strength * decay_rate^days) — inverted decay. 0.9999/day is
|
|
96
|
+
// "extremely slow" (a memory loses ~3% of its strength per year) without ever
|
|
97
|
+
// inverting.
|
|
98
|
+
const decay_rate = Math.min(0.9999, typeDefaults.decay_rate * cogAdj.decay_multiplier);
|
|
99
|
+
|
|
100
|
+
return { strength: Math.round(strength * 100) / 100, decay_rate };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function buildMemoryFileContent(mem, id, now) {
|
|
104
|
+
const { strength, decay_rate } = computeStrengthAndDecay(
|
|
105
|
+
mem.type, mem.cognitive_type, mem.strength_adjustment
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
const fmLines = [
|
|
109
|
+
'---',
|
|
110
|
+
`id: ${id}`,
|
|
111
|
+
`type: ${mem.type}`,
|
|
112
|
+
`cognitive_type: ${mem.cognitive_type || 'semantic'}`,
|
|
113
|
+
`created: "${now}"`,
|
|
114
|
+
`last_accessed: "${now}"`,
|
|
115
|
+
`access_count: 0`,
|
|
116
|
+
`recall_history: []`,
|
|
117
|
+
`strength: ${strength}`,
|
|
118
|
+
`decay_rate: ${decay_rate}`,
|
|
119
|
+
`salience: ${mem.salience ?? 0.5}`,
|
|
120
|
+
`confidence: ${mem.confidence ?? 0.7}`,
|
|
121
|
+
];
|
|
122
|
+
// CoALA Phase 1: pinned (always-loaded) and stable (decay-exempt) are emitted
|
|
123
|
+
// only when set, so ordinary memories keep their existing frontmatter shape.
|
|
124
|
+
if (mem.pinned) {
|
|
125
|
+
fmLines.push('pinned: true');
|
|
126
|
+
fmLines.push(`pin_scope: "${mem.pin_scope || 'global'}"`);
|
|
127
|
+
fmLines.push(`pin_priority: ${mem.pin_priority || 0}`);
|
|
128
|
+
}
|
|
129
|
+
if (mem.stable) fmLines.push('stable: true');
|
|
130
|
+
fmLines.push(
|
|
131
|
+
`tags: [${(mem.tags || []).map(t => `"${t}"`).join(', ')}]`,
|
|
132
|
+
`related: [${(mem.related || []).map(r => `"${r}"`).join(', ')}]`,
|
|
133
|
+
`source: "${mem.source || ''}"`,
|
|
134
|
+
`encoding_context:`,
|
|
135
|
+
` project: "${(mem.encoding_context && mem.encoding_context.project) || ''}"`,
|
|
136
|
+
` topics: [${((mem.encoding_context && mem.encoding_context.topics) || []).map(t => `"${t}"`).join(', ')}]`,
|
|
137
|
+
` task_type: "${(mem.encoding_context && mem.encoding_context.task_type) || ''}"`,
|
|
138
|
+
` agent: "${HOST_AGENT}"`,
|
|
139
|
+
'---',
|
|
140
|
+
'',
|
|
141
|
+
);
|
|
142
|
+
const frontmatter = fmLines.join('\n');
|
|
143
|
+
|
|
144
|
+
return { fileContent: frontmatter + mem.content + '\n', strength, decay_rate };
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function buildIndexEntry(mem, id, strength, decayRate, now) {
|
|
148
|
+
const entry = {
|
|
149
|
+
title: mem.title,
|
|
150
|
+
path: mem.path,
|
|
151
|
+
type: mem.type,
|
|
152
|
+
cognitive_type: mem.cognitive_type || 'semantic',
|
|
153
|
+
created: now,
|
|
154
|
+
last_accessed: now,
|
|
155
|
+
access_count: 0,
|
|
156
|
+
strength,
|
|
157
|
+
decay_rate: decayRate,
|
|
158
|
+
salience: mem.salience ?? 0.5,
|
|
159
|
+
confidence: mem.confidence ?? 0.7,
|
|
160
|
+
tags: mem.tags || [],
|
|
161
|
+
related: mem.related || [],
|
|
162
|
+
encoding_context: { ...(mem.encoding_context || {}), agent: HOST_AGENT },
|
|
163
|
+
// CoALA Phase 0: cheap chars/4 token estimate for working-memory budgeting.
|
|
164
|
+
token_estimate: Math.ceil((mem.content || '').length / 4),
|
|
165
|
+
};
|
|
166
|
+
// CoALA Phase 1: only set when present — keeps existing index entries lean.
|
|
167
|
+
if (mem.pinned) {
|
|
168
|
+
entry.pinned = true;
|
|
169
|
+
entry.pin_scope = mem.pin_scope || 'global';
|
|
170
|
+
entry.pin_priority = mem.pin_priority || 0;
|
|
171
|
+
}
|
|
172
|
+
if (mem.stable) entry.stable = true;
|
|
173
|
+
return entry;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function updateMetaFiles(brainDir, memPath) {
|
|
177
|
+
const parts = memPath.split('/');
|
|
178
|
+
// Walk up the directory chain, updating _meta.json at each level
|
|
179
|
+
for (let i = 1; i <= parts.length - 1; i++) {
|
|
180
|
+
const dirParts = parts.slice(0, i);
|
|
181
|
+
const categoryPath = dirParts.join('/');
|
|
182
|
+
const fullDir = path.join(brainDir, categoryPath);
|
|
183
|
+
|
|
184
|
+
if (!fs.existsSync(fullDir)) continue;
|
|
185
|
+
|
|
186
|
+
const metaPath = path.join(fullDir, '_meta.json');
|
|
187
|
+
let meta;
|
|
188
|
+
try {
|
|
189
|
+
meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
|
|
190
|
+
} catch {
|
|
191
|
+
meta = { description: categoryPath, memory_count: 0, subcategories: [] };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
meta.memory_count = (meta.memory_count || 0) + 1;
|
|
195
|
+
|
|
196
|
+
// Add subcategory if this isn't the leaf directory
|
|
197
|
+
if (i < parts.length - 1) {
|
|
198
|
+
const subcat = parts[i];
|
|
199
|
+
if (!meta.subcategories) meta.subcategories = [];
|
|
200
|
+
if (!meta.subcategories.includes(subcat)) {
|
|
201
|
+
meta.subcategories.push(subcat);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
atomicWriteSync(metaPath, JSON.stringify(meta, null, 2) + '\n');
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function findTagOverlaps(index, newTags, newId, minOverlap = 2) {
|
|
210
|
+
const overlaps = [];
|
|
211
|
+
if (!newTags || newTags.length < minOverlap) return overlaps;
|
|
212
|
+
|
|
213
|
+
const newTagSet = new Set(newTags);
|
|
214
|
+
for (const [id, entry] of Object.entries(index.memories)) {
|
|
215
|
+
if (id === newId) continue;
|
|
216
|
+
const entryTags = entry.tags || [];
|
|
217
|
+
const shared = entryTags.filter(t => newTagSet.has(t));
|
|
218
|
+
if (shared.length >= minOverlap) {
|
|
219
|
+
overlaps.push(id);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return overlaps;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function trySync() {
|
|
226
|
+
const brainDir = getBrainDir();
|
|
227
|
+
|
|
228
|
+
// Try cloud sync first
|
|
229
|
+
const cloudConfig = path.join(brainDir, '.cloud', 'config.json');
|
|
230
|
+
if (fs.existsSync(cloudConfig)) {
|
|
231
|
+
try {
|
|
232
|
+
execSync('brain cloud push', { stdio: 'pipe', timeout: 30000 });
|
|
233
|
+
return { method: 'cloud', success: true };
|
|
234
|
+
} catch (err) {
|
|
235
|
+
return { method: 'cloud', success: false, error: err.message };
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Try git sync
|
|
240
|
+
const gitConfig = path.join(brainDir, '.sync', 'config.json');
|
|
241
|
+
if (fs.existsSync(gitConfig)) {
|
|
242
|
+
try {
|
|
243
|
+
// Use the git-sync module
|
|
244
|
+
const gitSync = require('../src/git-sync');
|
|
245
|
+
// Sync push is async, but we run sync for CLI simplicity
|
|
246
|
+
execSync(`node -e "require('${path.join(__dirname, '..', 'src', 'git-sync.js')}').push('${brainDir}').then(() => process.exit(0)).catch(() => process.exit(1))"`, {
|
|
247
|
+
stdio: 'pipe',
|
|
248
|
+
timeout: 30000,
|
|
249
|
+
});
|
|
250
|
+
return { method: 'git', success: true };
|
|
251
|
+
} catch (err) {
|
|
252
|
+
return { method: 'git', success: false, error: err.message };
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return { method: 'none', success: false, error: 'No sync configured (cloud or git)' };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// --- Main ---
|
|
260
|
+
|
|
261
|
+
async function main() {
|
|
262
|
+
const args = parseArgs(process.argv.slice(2));
|
|
263
|
+
|
|
264
|
+
// Read JSON from stdin
|
|
265
|
+
let inputData = '';
|
|
266
|
+
if (process.stdin.isTTY) {
|
|
267
|
+
console.error(JSON.stringify({ error: 'No input provided. Pipe JSON via stdin.' }));
|
|
268
|
+
process.exit(1);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Read from fd 0 rather than the '/dev/stdin' path: the path form fails with
|
|
272
|
+
// ENXIO on Linux CI runners and doesn't exist on Windows, whereas fd 0 reads
|
|
273
|
+
// piped stdin portably across Linux, macOS, and Windows.
|
|
274
|
+
inputData = fs.readFileSync(0, 'utf-8');
|
|
275
|
+
|
|
276
|
+
let input;
|
|
277
|
+
try {
|
|
278
|
+
input = JSON.parse(inputData);
|
|
279
|
+
} catch (err) {
|
|
280
|
+
console.error(JSON.stringify({ error: `Invalid JSON input: ${err.message}` }));
|
|
281
|
+
process.exit(1);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
if (!input.memories || !Array.isArray(input.memories) || input.memories.length === 0) {
|
|
285
|
+
console.error(JSON.stringify({ error: 'Input must have a non-empty "memories" array' }));
|
|
286
|
+
process.exit(1);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const brainDir = getBrainDir();
|
|
290
|
+
|
|
291
|
+
// Validate brain exists
|
|
292
|
+
if (!fs.existsSync(path.join(brainDir, 'index.json'))) {
|
|
293
|
+
console.error(JSON.stringify({ error: `Brain not initialized. Run brain install first.` }));
|
|
294
|
+
process.exit(1);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Read current state
|
|
298
|
+
let index;
|
|
299
|
+
try {
|
|
300
|
+
index = readIndex();
|
|
301
|
+
} catch (err) {
|
|
302
|
+
console.error(JSON.stringify({
|
|
303
|
+
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
304
|
+
}));
|
|
305
|
+
process.exit(1);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
let associations;
|
|
309
|
+
try {
|
|
310
|
+
associations = readAssociations() || { version: 1, edges: {} };
|
|
311
|
+
} catch (err) {
|
|
312
|
+
console.error(JSON.stringify({
|
|
313
|
+
error: `Corrupt associations.json in ~/.brain/ — ${err.message}`,
|
|
314
|
+
}));
|
|
315
|
+
process.exit(1);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
let searchIndex;
|
|
319
|
+
try {
|
|
320
|
+
searchIndex = readSearchIndex(brainDir) || createSearchIndex();
|
|
321
|
+
} catch (err) {
|
|
322
|
+
// Search index is non-critical — rebuild from scratch
|
|
323
|
+
searchIndex = createSearchIndex();
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const now = new Date().toISOString();
|
|
327
|
+
const results = [];
|
|
328
|
+
const newIds = [];
|
|
329
|
+
const pinnedToAdd = [];
|
|
330
|
+
|
|
331
|
+
for (const mem of input.memories) {
|
|
332
|
+
// Validate required fields
|
|
333
|
+
if (!mem.title || !mem.type || !mem.path || !mem.content) {
|
|
334
|
+
console.error(JSON.stringify({
|
|
335
|
+
error: `Memory missing required fields (title, type, path, content): ${JSON.stringify(mem.title || 'untitled')}`,
|
|
336
|
+
}));
|
|
337
|
+
process.exit(1);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
if (!TYPE_DEFAULTS[mem.type]) {
|
|
341
|
+
console.error(JSON.stringify({ error: `Unknown memory type: ${mem.type}` }));
|
|
342
|
+
process.exit(1);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Generate ID
|
|
346
|
+
const id = generateId();
|
|
347
|
+
newIds.push(id);
|
|
348
|
+
|
|
349
|
+
// Compute strength/decay
|
|
350
|
+
const { fileContent, strength, decay_rate } = buildMemoryFileContent(mem, id, now);
|
|
351
|
+
|
|
352
|
+
// Create directories
|
|
353
|
+
const fullPath = path.join(brainDir, mem.path);
|
|
354
|
+
validateBrainPath(fullPath, brainDir);
|
|
355
|
+
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
|
356
|
+
|
|
357
|
+
// Write memory file
|
|
358
|
+
atomicWriteSync(fullPath, fileContent);
|
|
359
|
+
|
|
360
|
+
// Update index
|
|
361
|
+
const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now);
|
|
362
|
+
addMemory(index, id, indexEntry);
|
|
363
|
+
|
|
364
|
+
// CoALA Phase 1: register a born-pinned memory in the pinned manifest
|
|
365
|
+
if (mem.pinned) {
|
|
366
|
+
pinnedToAdd.push({
|
|
367
|
+
id,
|
|
368
|
+
scope: mem.pin_scope || 'global',
|
|
369
|
+
priority: mem.pin_priority || 0,
|
|
370
|
+
token_estimate: indexEntry.token_estimate,
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Update associations — explicit related links
|
|
375
|
+
for (const relatedId of (mem.related || [])) {
|
|
376
|
+
if (index.memories[relatedId]) {
|
|
377
|
+
reinforceEdge(associations, id, relatedId, 'manual', 0.20);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Update associations — tag overlaps
|
|
382
|
+
const tagOverlaps = findTagOverlaps(index, mem.tags, id);
|
|
383
|
+
for (const overlapId of tagOverlaps) {
|
|
384
|
+
reinforceEdge(associations, id, overlapId, 'tag_overlap', 0.10);
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// Tier B §10.2: surface potential contradictions with pinned/stable memories
|
|
388
|
+
// (high tag overlap) so the agent can adjudicate — never auto-resolved here.
|
|
389
|
+
const potentialConflicts = tagOverlaps
|
|
390
|
+
.filter((oid) => {
|
|
391
|
+
const e = index.memories[oid];
|
|
392
|
+
return e && (e.pinned || e.stable);
|
|
393
|
+
})
|
|
394
|
+
.map((oid) => ({ id: oid, title: index.memories[oid].title }));
|
|
395
|
+
|
|
396
|
+
// Update search index
|
|
397
|
+
addDocument(searchIndex, id, {
|
|
398
|
+
title: mem.title,
|
|
399
|
+
tags: mem.tags,
|
|
400
|
+
body: mem.content,
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
// Update _meta.json files
|
|
404
|
+
updateMetaFiles(brainDir, mem.path);
|
|
405
|
+
|
|
406
|
+
const edgesCreated = (mem.related || []).filter(r => index.memories[r]).length + tagOverlaps.length;
|
|
407
|
+
|
|
408
|
+
results.push({
|
|
409
|
+
id,
|
|
410
|
+
title: mem.title,
|
|
411
|
+
path: mem.path,
|
|
412
|
+
type: mem.type,
|
|
413
|
+
cognitive_type: mem.cognitive_type || 'semantic',
|
|
414
|
+
strength,
|
|
415
|
+
decay_rate,
|
|
416
|
+
salience: mem.salience ?? 0.5,
|
|
417
|
+
confidence: mem.confidence ?? 0.7,
|
|
418
|
+
tags: mem.tags || [],
|
|
419
|
+
edges_created: edgesCreated,
|
|
420
|
+
...(potentialConflicts.length ? { potential_conflicts: potentialConflicts } : {}),
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// Write all updated state
|
|
425
|
+
writeIndex(index);
|
|
426
|
+
writeAssociations(associations);
|
|
427
|
+
writeSearchIndex(brainDir, searchIndex);
|
|
428
|
+
|
|
429
|
+
// CoALA Phase 1: persist any born-pinned memories to the pinned manifest
|
|
430
|
+
if (pinnedToAdd.length > 0) {
|
|
431
|
+
const pinned = readPinned();
|
|
432
|
+
for (const p of pinnedToAdd) {
|
|
433
|
+
pinned.pins = pinned.pins.filter((x) => x.id !== p.id);
|
|
434
|
+
pinned.pins.push(p);
|
|
435
|
+
}
|
|
436
|
+
writePinned(pinned);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// Build output
|
|
440
|
+
const output = {
|
|
441
|
+
stored: results,
|
|
442
|
+
total: results.length,
|
|
443
|
+
index_count: index.memory_count,
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
// Sync if requested
|
|
447
|
+
if (args.sync || input.auto_sync) {
|
|
448
|
+
const syncResult = trySync();
|
|
449
|
+
output.sync = syncResult;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
console.log(JSON.stringify(output, null, 2));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
main().catch((err) => {
|
|
456
|
+
console.error(JSON.stringify({ error: err.message }));
|
|
457
|
+
process.exit(1);
|
|
458
|
+
});
|
package/bin/pin.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* brain pin — pin a memory into the always-present semantic tier (CoALA Phase 1).
|
|
5
|
+
*
|
|
6
|
+
* Usage:
|
|
7
|
+
* brain pin <id> [--scope global|project:<name>] [--priority N]
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
const { pinMemory } = require('../src/pinning');
|
|
11
|
+
|
|
12
|
+
function parseArgs(argv) {
|
|
13
|
+
const args = { id: null, scope: 'global', priority: 0 };
|
|
14
|
+
for (let i = 0; i < argv.length; i++) {
|
|
15
|
+
switch (argv[i]) {
|
|
16
|
+
case '--scope': args.scope = argv[++i]; break;
|
|
17
|
+
case '--priority': args.priority = parseInt(argv[++i], 10) || 0; break;
|
|
18
|
+
default:
|
|
19
|
+
if (!argv[i].startsWith('--') && !args.id) args.id = argv[i];
|
|
20
|
+
break;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return args;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function main(argv) {
|
|
27
|
+
const args = parseArgs(argv || process.argv.slice(2));
|
|
28
|
+
if (!args.id) {
|
|
29
|
+
console.error(JSON.stringify({ error: 'Usage: brain pin <id> [--scope global|project:<name>] [--priority N]' }));
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
const result = pinMemory(undefined, args.id, { scope: args.scope, priority: args.priority });
|
|
33
|
+
if (result.error) {
|
|
34
|
+
console.error(JSON.stringify(result));
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
console.log(JSON.stringify(result, null, 2));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (require.main === module) {
|
|
41
|
+
main(process.argv.slice(2));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
module.exports = { main, parseArgs };
|