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
|
@@ -0,0 +1,337 @@
|
|
|
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
|
+
bm25Search,
|
|
31
|
+
rebuildIndex,
|
|
32
|
+
isSearchIndexStale,
|
|
33
|
+
} = require('../src/tfidf');
|
|
34
|
+
|
|
35
|
+
const {
|
|
36
|
+
readIndex,
|
|
37
|
+
readAssociations,
|
|
38
|
+
readReviewQueue,
|
|
39
|
+
readConfig,
|
|
40
|
+
getBrainDir,
|
|
41
|
+
} = require('../src/index-manager');
|
|
42
|
+
|
|
43
|
+
const { rankMemories } = require('../src/scorer');
|
|
44
|
+
const { advertisedSummaries } = require('../src/skills');
|
|
45
|
+
const { receiptFor } = require('../src/receipt');
|
|
46
|
+
const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
|
|
47
|
+
|
|
48
|
+
function parseArgs(argv) {
|
|
49
|
+
const args = { project: null, topics: null, task: null, top: 5 };
|
|
50
|
+
for (let i = 0; i < argv.length; i++) {
|
|
51
|
+
switch (argv[i]) {
|
|
52
|
+
case '--project': args.project = argv[++i]; break;
|
|
53
|
+
case '--topics': args.topics = argv[++i]; break;
|
|
54
|
+
case '--task': args.task = argv[++i]; break;
|
|
55
|
+
case '--top': args.top = parseInt(argv[++i], 10) || 5; break;
|
|
56
|
+
default: break;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return args;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** chars/4 token estimate; falls back to the title line for pre-Phase-0 entries. */
|
|
63
|
+
function estimateTokens(entry) {
|
|
64
|
+
if (typeof entry.token_estimate === 'number') return entry.token_estimate;
|
|
65
|
+
return Math.ceil(((entry.title || '').length + 8) / 4);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** chars/4 token estimate for a minted receipt line (counted against budgets). */
|
|
69
|
+
function receiptTokens(receipt) {
|
|
70
|
+
return receipt ? Math.ceil(receipt.length / 4) : 0;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Tier B §10.4 — reorder an importance-sorted list so the top items land at the
|
|
75
|
+
* edges (start + end), where models attend best, leaving the middle for lower
|
|
76
|
+
* ranks. Deterministic. e.g. [1,2,3,4,5] → [1,3,5,4,2].
|
|
77
|
+
*/
|
|
78
|
+
function edgeOrder(arr) {
|
|
79
|
+
const front = [];
|
|
80
|
+
const back = [];
|
|
81
|
+
arr.forEach((item, i) => { if (i % 2 === 0) front.push(item); else back.unshift(item); });
|
|
82
|
+
return front.concat(back);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Read a memory file's body (content after the frontmatter block). */
|
|
86
|
+
function readMemoryBody(brainDir, memPath) {
|
|
87
|
+
try {
|
|
88
|
+
const content = fs.readFileSync(path.join(brainDir, memPath), 'utf-8');
|
|
89
|
+
const first = content.indexOf('---');
|
|
90
|
+
const second = content.indexOf('---', first + 3);
|
|
91
|
+
if (first !== -1 && second !== -1) return content.slice(second + 3).trim();
|
|
92
|
+
return content.trim();
|
|
93
|
+
} catch (_) {
|
|
94
|
+
return '';
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function buildContextQuery(args) {
|
|
99
|
+
const parts = [];
|
|
100
|
+
if (args.project) parts.push(args.project);
|
|
101
|
+
if (args.topics) parts.push(args.topics);
|
|
102
|
+
if (args.task) parts.push(args.task);
|
|
103
|
+
return parts.length > 0 ? parts.join(' ') : '*';
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Compute the session-start payload for the brain at `projectRoot` (undefined =
|
|
108
|
+
* the real ~/.brain). Pure: performs no console output and never calls exit, so
|
|
109
|
+
* it is directly unit-testable.
|
|
110
|
+
*
|
|
111
|
+
* @param {string} [projectRoot] - Filesystem root whose .brain/ to read
|
|
112
|
+
* @param {Object} [args] - { project, topics, task, top }
|
|
113
|
+
* @returns {Object} The session-start payload
|
|
114
|
+
*/
|
|
115
|
+
function computeSessionStart(projectRoot, args = {}) {
|
|
116
|
+
const top = args.top || 5;
|
|
117
|
+
const brainDir = getBrainDir(projectRoot);
|
|
118
|
+
const config = readConfig(projectRoot);
|
|
119
|
+
const cap = config.working_memory_budget_tokens;
|
|
120
|
+
|
|
121
|
+
const empty = {
|
|
122
|
+
memory_count: 0,
|
|
123
|
+
pinned: [], // Phase 1: always-present semantic tier
|
|
124
|
+
skills_index: [], // Phase 2: procedural skill summaries
|
|
125
|
+
context_recall: [],
|
|
126
|
+
due_for_review: 0,
|
|
127
|
+
pending_verification: 0,
|
|
128
|
+
pending_verification_items: [],
|
|
129
|
+
low_confidence_alerts: [],
|
|
130
|
+
budget: { cap, recall_cap: config.recall_budget_tokens, used: 0, included: 0, excluded: 0 },
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
if (!fs.existsSync(path.join(brainDir, 'index.json'))) return empty;
|
|
134
|
+
|
|
135
|
+
const index = readIndex(projectRoot);
|
|
136
|
+
if (!index || !index.memories) return empty;
|
|
137
|
+
|
|
138
|
+
// Note: we proceed even with zero memories — pins and skills are independent
|
|
139
|
+
// of episodic memory and should still be surfaced.
|
|
140
|
+
const memoryCount = Object.keys(index.memories).length;
|
|
141
|
+
|
|
142
|
+
// --- Context recall (deterministic, reuses the recall engine) ---
|
|
143
|
+
// Rebuild when ABSENT *or* STALE — session-start is the first thing a session
|
|
144
|
+
// runs (e.g. right after a `sync pull`), so it is the most likely path to hit
|
|
145
|
+
// a search index that has drifted out of sync with index.json. A present-but-
|
|
146
|
+
// stale index silently zeroes every relevance score (matches recall.js).
|
|
147
|
+
let searchIndex = null;
|
|
148
|
+
try { searchIndex = readSearchIndex(brainDir); } catch (_) { searchIndex = null; }
|
|
149
|
+
if (isSearchIndexStale(searchIndex, index)) {
|
|
150
|
+
searchIndex = rebuildIndex(brainDir, index);
|
|
151
|
+
writeSearchIndex(brainDir, searchIndex);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const tfidfScores = bm25Search(searchIndex, buildContextQuery(args));
|
|
155
|
+
// Enforce-mode quarantine: pending-verification memories are excluded from
|
|
156
|
+
// the ranked pool entirely (flag mode includes them, marked). The pending
|
|
157
|
+
// COUNT below always scans the full index, so the agent still learns that
|
|
158
|
+
// items are waiting even when they are hidden.
|
|
159
|
+
const quarantineMode = config.quarantine_mode || 'flag';
|
|
160
|
+
const memories = Object.entries(index.memories)
|
|
161
|
+
.filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
|
|
162
|
+
.map(([id, entry]) => ({ id, ...entry }));
|
|
163
|
+
|
|
164
|
+
let associations = null;
|
|
165
|
+
try { associations = readAssociations(projectRoot); } catch (_) { associations = null; }
|
|
166
|
+
|
|
167
|
+
const recallContext = {};
|
|
168
|
+
if (args.project) recallContext.project = args.project;
|
|
169
|
+
if (args.task) recallContext.task_type = args.task;
|
|
170
|
+
if (args.topics) recallContext.topics = String(args.topics).split(',');
|
|
171
|
+
|
|
172
|
+
const ranked = rankMemories(
|
|
173
|
+
memories,
|
|
174
|
+
(mem) => tfidfScores[mem.id] || 0,
|
|
175
|
+
{
|
|
176
|
+
associations: associations || undefined,
|
|
177
|
+
recallContext: Object.keys(recallContext).length > 0 ? recallContext : undefined,
|
|
178
|
+
}
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
// --- Pinned tier (CoALA Phase 1): always present, scope-filtered, budget-capped ---
|
|
182
|
+
// The index entry is the source of truth (pinned.json is a maintained cache);
|
|
183
|
+
// scanning the index here avoids manifest/index drift.
|
|
184
|
+
const pinnedCandidates = [];
|
|
185
|
+
for (const [id, entry] of Object.entries(index.memories)) {
|
|
186
|
+
if (!entry.pinned) continue;
|
|
187
|
+
// Defensive: pinning a quarantined memory is refused, but state synced
|
|
188
|
+
// from another device could carry both flags — never load it every session.
|
|
189
|
+
if (entry.quarantined && quarantineMode !== 'off') continue;
|
|
190
|
+
const scope = entry.pin_scope || 'global';
|
|
191
|
+
if (scope !== 'global') {
|
|
192
|
+
const scopedProject = scope.startsWith('project:') ? scope.slice('project:'.length) : null;
|
|
193
|
+
if (!args.project || scopedProject !== args.project) continue; // out-of-project pin
|
|
194
|
+
}
|
|
195
|
+
pinnedCandidates.push({ id, entry, scope, priority: entry.pin_priority || 0 });
|
|
196
|
+
}
|
|
197
|
+
pinnedCandidates.sort((a, b) =>
|
|
198
|
+
(b.priority - a.priority) ||
|
|
199
|
+
((b.entry.strength || 0) - (a.entry.strength || 0)) ||
|
|
200
|
+
(a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
|
|
201
|
+
);
|
|
202
|
+
|
|
203
|
+
const pinned = [];
|
|
204
|
+
let pinnedTokens = 0;
|
|
205
|
+
let pinnedExcluded = 0;
|
|
206
|
+
const pinCap = Math.min(config.pin_budget_tokens, cap);
|
|
207
|
+
for (const c of pinnedCandidates) {
|
|
208
|
+
const receipt = receiptFor(c.entry);
|
|
209
|
+
const est = estimateTokens(c.entry) + receiptTokens(receipt);
|
|
210
|
+
if (pinnedTokens + est > pinCap && pinned.length > 0) { pinnedExcluded++; continue; }
|
|
211
|
+
pinned.push({
|
|
212
|
+
id: c.id,
|
|
213
|
+
title: c.entry.title,
|
|
214
|
+
content: readMemoryBody(brainDir, c.entry.path),
|
|
215
|
+
scope: c.scope,
|
|
216
|
+
priority: c.priority,
|
|
217
|
+
tokens: est,
|
|
218
|
+
receipt,
|
|
219
|
+
});
|
|
220
|
+
pinnedTokens += est;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// --- Skills index (CoALA Phase 2): advertise name + description only (L0) ---
|
|
224
|
+
const skills_index = [];
|
|
225
|
+
let skillsTokens = 0;
|
|
226
|
+
let skillsExcluded = 0;
|
|
227
|
+
const skillsCap = Math.min(config.skills_index_budget_tokens, Math.max(0, cap - pinnedTokens));
|
|
228
|
+
for (const s of advertisedSummaries(projectRoot)) {
|
|
229
|
+
const est = Math.ceil(((s.name || '').length + (s.description || '').length + 8) / 4);
|
|
230
|
+
if (skillsTokens + est > skillsCap && skills_index.length > 0) { skillsExcluded++; continue; }
|
|
231
|
+
skills_index.push({ name: s.name, description: s.description });
|
|
232
|
+
skillsTokens += est;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// --- Budget-bound the recall set with whatever the pin/skills tiers leave ---
|
|
236
|
+
const recallCap = Math.max(0, Math.min(config.recall_budget_tokens, cap - pinnedTokens - skillsTokens));
|
|
237
|
+
const pinnedIds = new Set(pinned.map((p) => p.id));
|
|
238
|
+
|
|
239
|
+
const context_recall = [];
|
|
240
|
+
let used = 0;
|
|
241
|
+
let excluded = 0;
|
|
242
|
+
for (const mem of ranked.slice(0, top)) {
|
|
243
|
+
if (pinnedIds.has(mem.id)) continue; // already presented in the pinned tier
|
|
244
|
+
const title = mem.title || path.basename(mem.path || '', '.md');
|
|
245
|
+
const receipt = receiptFor({ ...mem, title });
|
|
246
|
+
const est = estimateTokens(mem) + receiptTokens(receipt);
|
|
247
|
+
if (used + est > recallCap && context_recall.length > 0) {
|
|
248
|
+
excluded++;
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
const origin = mem.origin || DEFAULT_ORIGIN;
|
|
252
|
+
context_recall.push({
|
|
253
|
+
id: mem.id,
|
|
254
|
+
title,
|
|
255
|
+
path: mem.path,
|
|
256
|
+
type: mem.type,
|
|
257
|
+
score: mem.score,
|
|
258
|
+
origin,
|
|
259
|
+
...(isLowTrust(origin) ? { low_trust: true } : {}),
|
|
260
|
+
...(mem.quarantined ? { quarantine_pending: true } : {}),
|
|
261
|
+
token_estimate: est,
|
|
262
|
+
receipt,
|
|
263
|
+
});
|
|
264
|
+
used += est;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// --- Due for review (matches the existing "has items" heuristic) ---
|
|
268
|
+
let dueForReview = 0;
|
|
269
|
+
try {
|
|
270
|
+
const queue = readReviewQueue(projectRoot);
|
|
271
|
+
if (queue && Array.isArray(queue.items)) dueForReview = queue.items.length;
|
|
272
|
+
} catch (_) { dueForReview = 0; }
|
|
273
|
+
|
|
274
|
+
// --- Pending verification (ASI06 quarantine) — count over the FULL index ---
|
|
275
|
+
// Cheapest possible surface: a count plus up to five {id, title, origin}
|
|
276
|
+
// stubs, so the agent can say "N memories are awaiting review" and route the
|
|
277
|
+
// user to `brain verify list` without spending budget on bodies.
|
|
278
|
+
const pendingAll = [];
|
|
279
|
+
for (const [id, entry] of Object.entries(index.memories)) {
|
|
280
|
+
if (entry.quarantined) pendingAll.push({ id, title: entry.title, origin: entry.origin });
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// --- Low-confidence-but-frequently-used alerts ---
|
|
284
|
+
const low_confidence_alerts = [];
|
|
285
|
+
for (const [id, entry] of Object.entries(index.memories)) {
|
|
286
|
+
if ((entry.access_count || 0) >= 3 && (entry.confidence ?? 1) < 0.5) {
|
|
287
|
+
low_confidence_alerts.push({
|
|
288
|
+
id,
|
|
289
|
+
title: entry.title,
|
|
290
|
+
confidence: entry.confidence,
|
|
291
|
+
access_count: entry.access_count,
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return {
|
|
297
|
+
memory_count: memoryCount,
|
|
298
|
+
pinned,
|
|
299
|
+
skills_index,
|
|
300
|
+
context_recall: edgeOrder(context_recall), // Tier B §10.4: top ranks at the edges
|
|
301
|
+
due_for_review: dueForReview,
|
|
302
|
+
pending_verification: pendingAll.length,
|
|
303
|
+
pending_verification_items: pendingAll.slice(0, 5),
|
|
304
|
+
low_confidence_alerts,
|
|
305
|
+
budget: {
|
|
306
|
+
cap,
|
|
307
|
+
pin_cap: pinCap,
|
|
308
|
+
skills_cap: skillsCap,
|
|
309
|
+
recall_cap: recallCap,
|
|
310
|
+
used: pinnedTokens + skillsTokens + used,
|
|
311
|
+
pinned_tokens: pinnedTokens,
|
|
312
|
+
skills_tokens: skillsTokens,
|
|
313
|
+
recall_used: used,
|
|
314
|
+
included: context_recall.length,
|
|
315
|
+
excluded,
|
|
316
|
+
pinned_excluded: pinnedExcluded,
|
|
317
|
+
skills_excluded: skillsExcluded,
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
function main(argv) {
|
|
323
|
+
const args = parseArgs(argv || process.argv.slice(2));
|
|
324
|
+
try {
|
|
325
|
+
const payload = computeSessionStart(undefined, args);
|
|
326
|
+
console.log(JSON.stringify(payload, null, 2));
|
|
327
|
+
} catch (err) {
|
|
328
|
+
console.error(JSON.stringify({ error: err.message }));
|
|
329
|
+
process.exit(1);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if (require.main === module) {
|
|
334
|
+
main(process.argv.slice(2));
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
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 };
|
package/bin/verify.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* brain verify — the quarantine workflow for unverified writes (OWASP ASI06).
|
|
5
|
+
*
|
|
6
|
+
* Low-trust writes (origin tool-output/external, or lint-flagged content) land
|
|
7
|
+
* with a pending-verification flag. This CLI is how they get resolved:
|
|
8
|
+
*
|
|
9
|
+
* brain verify list Pending memories (JSON)
|
|
10
|
+
* brain verify show <id> Full frontmatter + body for inspection
|
|
11
|
+
* brain verify approve <id> [...] [--force]
|
|
12
|
+
* Clear the flag, mark vetted (audited)
|
|
13
|
+
* brain verify reject <id> [...] [--force]
|
|
14
|
+
* Archive via the forget primitive (audited)
|
|
15
|
+
*
|
|
16
|
+
* Approval clears the flag only — origin, write-time clamps, and recall trust
|
|
17
|
+
* weighting stay. --force on approve vets a non-pending id; on reject it
|
|
18
|
+
* overrides the high-salience archival guard.
|
|
19
|
+
*
|
|
20
|
+
* Note: _archived/ is excluded from cloud sync, so a reject propagates the
|
|
21
|
+
* index removal to other devices but may leave an orphaned .md file there —
|
|
22
|
+
* harmless (recall reads only the index; reindex rebuilds from the index).
|
|
23
|
+
*
|
|
24
|
+
* Output: JSON. Honors BRAIN_DIR.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const fs = require('fs');
|
|
28
|
+
const path = require('path');
|
|
29
|
+
|
|
30
|
+
const { getBrainDir, readIndex, writeIndex } = require('../src/index-manager');
|
|
31
|
+
const { listPending, approveQuarantine } = require('../src/quarantine');
|
|
32
|
+
const { appendAudit } = require('../src/audit');
|
|
33
|
+
const { archiveMemory } = require('./forget');
|
|
34
|
+
|
|
35
|
+
function fail(message) {
|
|
36
|
+
console.error(JSON.stringify({ error: message }));
|
|
37
|
+
process.exit(1);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function loadIndex() {
|
|
41
|
+
let index;
|
|
42
|
+
try {
|
|
43
|
+
index = readIndex();
|
|
44
|
+
} catch (err) {
|
|
45
|
+
fail(`Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`);
|
|
46
|
+
}
|
|
47
|
+
if (!index) fail('Brain not initialized.');
|
|
48
|
+
return index;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function pendingItem(id, entry) {
|
|
52
|
+
return {
|
|
53
|
+
id,
|
|
54
|
+
title: entry.title,
|
|
55
|
+
path: entry.path,
|
|
56
|
+
type: entry.type,
|
|
57
|
+
origin: entry.origin,
|
|
58
|
+
reasons: entry.quarantine_reasons || [],
|
|
59
|
+
flagged: entry.quarantine_flagged,
|
|
60
|
+
tags: entry.tags || [],
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function main(argv) {
|
|
65
|
+
const args = argv || process.argv.slice(2);
|
|
66
|
+
const sub = args[0];
|
|
67
|
+
const force = args.includes('--force');
|
|
68
|
+
const ids = args.slice(1).filter((a) => a && !a.startsWith('--'));
|
|
69
|
+
|
|
70
|
+
const brainDir = getBrainDir();
|
|
71
|
+
|
|
72
|
+
if (sub === 'list' || sub === undefined) {
|
|
73
|
+
const index = loadIndex();
|
|
74
|
+
const pending = listPending(index).map(({ id, entry }) => pendingItem(id, entry));
|
|
75
|
+
console.log(JSON.stringify({ pending, total: pending.length }, null, 2));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (sub === 'show') {
|
|
80
|
+
if (ids.length !== 1) fail('Usage: brain verify show <id>');
|
|
81
|
+
const index = loadIndex();
|
|
82
|
+
const entry = index.memories[ids[0]];
|
|
83
|
+
if (!entry) fail(`Memory not found: ${ids[0]}`);
|
|
84
|
+
let content = null;
|
|
85
|
+
try { content = fs.readFileSync(path.join(brainDir, entry.path), 'utf-8'); } catch (_) { /* index is source of truth */ }
|
|
86
|
+
console.log(JSON.stringify({ ...pendingItem(ids[0], entry), quarantined: !!entry.quarantined, content }, null, 2));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
if (sub === 'approve') {
|
|
91
|
+
if (ids.length === 0) fail('Usage: brain verify approve <id> [<id>...] [--force]');
|
|
92
|
+
const index = loadIndex();
|
|
93
|
+
const now = new Date().toISOString();
|
|
94
|
+
const approved = [];
|
|
95
|
+
const errors = [];
|
|
96
|
+
for (const id of ids) {
|
|
97
|
+
const entry = index.memories[id];
|
|
98
|
+
if (!entry) { errors.push({ id, error: 'not found' }); continue; }
|
|
99
|
+
if (!entry.quarantined && !force) {
|
|
100
|
+
errors.push({ id, error: 'not pending verification (--force to vet anyway)' });
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (entry.quarantined) {
|
|
104
|
+
const r = approveQuarantine(brainDir, index, id, now);
|
|
105
|
+
if (r.error) { errors.push({ id, error: r.error }); continue; }
|
|
106
|
+
} else {
|
|
107
|
+
entry.vetted = true;
|
|
108
|
+
entry.vetted_at = now;
|
|
109
|
+
}
|
|
110
|
+
try {
|
|
111
|
+
appendAudit(brainDir, { ts: now, event: 'verify_approve', id, title: entry.title, origin: entry.origin, forced: force });
|
|
112
|
+
} catch (_) { /* approval already applied */ }
|
|
113
|
+
approved.push(id);
|
|
114
|
+
}
|
|
115
|
+
if (approved.length > 0) writeIndex(index);
|
|
116
|
+
const output = { approved, ...(errors.length ? { errors } : {}) };
|
|
117
|
+
if (errors.length && approved.length === 0) {
|
|
118
|
+
console.error(JSON.stringify(output));
|
|
119
|
+
process.exit(1);
|
|
120
|
+
}
|
|
121
|
+
console.log(JSON.stringify(output, null, 2));
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (sub === 'reject') {
|
|
126
|
+
if (ids.length === 0) fail('Usage: brain verify reject <id> [<id>...] [--force]');
|
|
127
|
+
const now = new Date().toISOString();
|
|
128
|
+
const rejected = [];
|
|
129
|
+
const errors = [];
|
|
130
|
+
for (const id of ids) {
|
|
131
|
+
const result = archiveMemory(brainDir, id, { force, reason: 'verify_reject' });
|
|
132
|
+
if (result.error) { errors.push({ id, error: result.error, ...(result.protected ? { protected: true } : {}) }); continue; }
|
|
133
|
+
try {
|
|
134
|
+
appendAudit(brainDir, { ts: now, event: 'verify_reject', id, title: result.title, forced: force });
|
|
135
|
+
} catch (_) { /* archival already applied */ }
|
|
136
|
+
rejected.push(id);
|
|
137
|
+
}
|
|
138
|
+
const output = { rejected, ...(errors.length ? { errors } : {}) };
|
|
139
|
+
if (errors.length && rejected.length === 0) {
|
|
140
|
+
console.error(JSON.stringify(output));
|
|
141
|
+
process.exit(1);
|
|
142
|
+
}
|
|
143
|
+
console.log(JSON.stringify(output, null, 2));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
fail(`Unknown subcommand "${sub}". Usage: brain verify <list|show|approve|reject>`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (require.main === module) {
|
|
151
|
+
main(process.argv.slice(2));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
module.exports = { main };
|