brain-memory 0.1.0 → 0.3.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 +216 -0
- package/README.md +34 -5
- package/bin/audit.js +18 -1
- package/bin/brain +4 -0
- package/bin/forget.js +10 -1
- package/bin/import.js +1 -1
- package/bin/install.js +10 -0
- package/bin/memorize.js +99 -21
- package/bin/recall.js +64 -13
- package/bin/reinforce.js +34 -1
- package/bin/session-start.js +32 -4
- package/bin/skill.js +8 -2
- package/bin/verify.js +35 -3
- package/commands/brain/import.md +1 -1
- package/commands/brain/memorize.md +45 -4
- package/commands/brain/remember.md +10 -1
- package/commands/brain/skills.md +29 -0
- package/commands/brain/sleep.md +1 -1
- package/commands/brain/verify.md +6 -0
- package/hooks/hooks.json +39 -0
- package/hooks/lib.mjs +117 -0
- package/hooks/prompt-recall.mjs +123 -0
- package/hooks/session-end.md +54 -0
- package/hooks/session-end.mjs +63 -0
- package/hooks/session-start.md +58 -0
- package/hooks/session-start.mjs +82 -0
- package/integrations/agentskills/brain-memory/SKILL.md +5 -0
- package/package.json +5 -3
- package/prompts/antigravity.md +26 -2
- package/prompts/claude.md +26 -2
- package/prompts/copilot.md +26 -2
- package/prompts/kilo.md +26 -2
- package/prompts/openai.md +26 -2
- package/prompts/opencode.md +26 -2
- package/src/anomaly.js +7 -0
- package/src/contradiction.js +106 -0
- package/src/harvest.js +174 -2
- package/src/index-manager.js +8 -0
- package/src/installer.js +126 -3
- package/src/integrity.js +155 -0
- package/src/receipt.js +14 -4
- package/src/scorer.js +75 -7
- package/src/sensitivity.js +134 -0
- package/src/skill-verify.js +191 -0
- package/src/skills.js +63 -0
- package/src/temporal.js +228 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brain Memory — Contradiction Proposals (bitemporal boundary suggestions)
|
|
3
|
+
*
|
|
4
|
+
* A brain that only ever appends accumulates contradictions. "We deploy to
|
|
5
|
+
* Fly.io" recorded in June and "we deploy to Render" recorded in August are not
|
|
6
|
+
* two competing facts — they are one fact with a boundary. src/temporal.js can
|
|
7
|
+
* already represent that (`valid_until`, stamped automatically when B
|
|
8
|
+
* supersedes A). What was missing is anyone NOTICING that a new write implies
|
|
9
|
+
* such a boundary.
|
|
10
|
+
*
|
|
11
|
+
* Until now the boundary was only drawn when the agent explicitly passed
|
|
12
|
+
* `supersedes`. Nothing prompted it to. So the common path — user states a new
|
|
13
|
+
* decision that quietly replaces an old one, without saying "this replaces X" —
|
|
14
|
+
* left both memories live, unbounded, and equally recallable. That is exactly
|
|
15
|
+
* the "memory staleness" failure competitors report as unsolved: a
|
|
16
|
+
* high-relevance fact that is now confidently wrong.
|
|
17
|
+
*
|
|
18
|
+
* This module looks at the memories a new write overlaps and proposes which of
|
|
19
|
+
* them it probably ended, and when.
|
|
20
|
+
*
|
|
21
|
+
* ── It proposes; it never applies ────────────────────────────────────────
|
|
22
|
+
* Deciding that B replaces A is a semantic judgement this code cannot make —
|
|
23
|
+
* "use Postgres for analytics" does not contradict "use Postgres for sessions"
|
|
24
|
+
* however many tags they share. So the output is a SUGGESTION carried back to
|
|
25
|
+
* the agent, which has the conversation and can ask. Auto-stamping
|
|
26
|
+
* `valid_until` on a tag heuristic would silently expire correct memories,
|
|
27
|
+
* which is a worse failure than leaving a stale one live.
|
|
28
|
+
*
|
|
29
|
+
* ── Why these filters ────────────────────────────────────────────────────
|
|
30
|
+
* Tag overlap alone is a relatedness signal, not a contradiction signal. Three
|
|
31
|
+
* additional filters cut the noise to something worth showing a user:
|
|
32
|
+
*
|
|
33
|
+
* same type A `decision` can end a `decision`. An `observation` that
|
|
34
|
+
* shares tags with a decision is context, not a reversal.
|
|
35
|
+
* not already bounded A memory with an explicit `valid_until` has an author's
|
|
36
|
+
* window; never second-guess it.
|
|
37
|
+
* not already superseded Already resolved — proposing again is noise.
|
|
38
|
+
*
|
|
39
|
+
* Pinned and stable memories are surfaced regardless of type, preserving the
|
|
40
|
+
* pre-existing behaviour: those carry the most authority, so a possible
|
|
41
|
+
* conflict with one is worth a look even when the heuristic is unsure.
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
const { supersessionInstant } = require('./temporal');
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Rank how much authority a memory carries, so the most consequential possible
|
|
48
|
+
* contradiction is the first thing the agent reads.
|
|
49
|
+
*/
|
|
50
|
+
function authorityOf(entry) {
|
|
51
|
+
if (entry.pinned) return 'pinned';
|
|
52
|
+
if (entry.stable) return 'stable';
|
|
53
|
+
return 'same-type';
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const AUTHORITY_RANK = { pinned: 3, stable: 2, 'same-type': 1 };
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Propose which existing memories a new write may have ended, and when.
|
|
60
|
+
*
|
|
61
|
+
* @param {Object} index - Live brain index
|
|
62
|
+
* @param {Object} newMem - The incoming memory (needs type, valid_from/created)
|
|
63
|
+
* @param {string[]} overlapIds - Candidate ids (from findTagOverlaps)
|
|
64
|
+
* @param {Object} [opts]
|
|
65
|
+
* @param {string} [opts.now] - ISO instant the successor starts at, when the
|
|
66
|
+
* memory carries neither `valid_from` nor `created` yet
|
|
67
|
+
* @returns {Array<Object>} proposals, highest authority first
|
|
68
|
+
*/
|
|
69
|
+
function proposeSupersessions(index, newMem, overlapIds, opts = {}) {
|
|
70
|
+
const memories = (index && index.memories) || {};
|
|
71
|
+
const newTags = new Set(newMem.tags || []);
|
|
72
|
+
const boundary = supersessionInstant(newMem) || opts.now || null;
|
|
73
|
+
|
|
74
|
+
const proposals = [];
|
|
75
|
+
for (const id of overlapIds || []) {
|
|
76
|
+
const entry = memories[id];
|
|
77
|
+
if (!entry) continue;
|
|
78
|
+
|
|
79
|
+
// Already resolved, or the author drew their own window — leave both alone.
|
|
80
|
+
if (entry.superseded_by) continue;
|
|
81
|
+
if (entry.valid_until) continue;
|
|
82
|
+
|
|
83
|
+
const authority = authorityOf(entry);
|
|
84
|
+
// Beyond pinned/stable, only a like-for-like memory is a plausible
|
|
85
|
+
// reversal. An observation sharing tags with a decision is context.
|
|
86
|
+
if (authority === 'same-type' && entry.type !== newMem.type) continue;
|
|
87
|
+
|
|
88
|
+
proposals.push({
|
|
89
|
+
id,
|
|
90
|
+
title: entry.title,
|
|
91
|
+
type: entry.type,
|
|
92
|
+
authority,
|
|
93
|
+
shared_tags: (entry.tags || []).filter((t) => newTags.has(t)),
|
|
94
|
+
// What `brain memorize --supersedes <id>` would stamp if confirmed.
|
|
95
|
+
proposed_valid_until: boundary,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
return proposals.sort(
|
|
100
|
+
(a, b) => (AUTHORITY_RANK[b.authority] - AUTHORITY_RANK[a.authority])
|
|
101
|
+
|| (b.shared_tags.length - a.shared_tags.length)
|
|
102
|
+
|| (a.id < b.id ? -1 : 1),
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
module.exports = { proposeSupersessions, AUTHORITY_RANK };
|
package/src/harvest.js
CHANGED
|
@@ -57,6 +57,10 @@ const STRIP_PATTERNS = [
|
|
|
57
57
|
/<local-command-stdout>[\s\S]*?<\/local-command-stdout>/g,
|
|
58
58
|
/<local-command-stderr>[\s\S]*?<\/local-command-stderr>/g,
|
|
59
59
|
/<user-prompt-submit-hook>[\s\S]*?<\/user-prompt-submit-hook>/g,
|
|
60
|
+
// Brain's own hook injections (hooks/*.mjs) — recalled memories must never be
|
|
61
|
+
// harvested back into new memories.
|
|
62
|
+
/<brain-session-context>[\s\S]*?<\/brain-session-context>/g,
|
|
63
|
+
/<brain-context>[\s\S]*?<\/brain-context>/g,
|
|
60
64
|
/\[Image #\d+\]/g,
|
|
61
65
|
/\[Request interrupted[^\]]*\]/g,
|
|
62
66
|
];
|
|
@@ -257,7 +261,174 @@ function slugToPathGuess(slug) {
|
|
|
257
261
|
return '/' + slug.slice(1).replace(/-/g, '/');
|
|
258
262
|
}
|
|
259
263
|
|
|
260
|
-
|
|
264
|
+
/**
|
|
265
|
+
* OpenAI Codex CLI — one JSONL "rollout" per thread under
|
|
266
|
+
* `$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<ts>-<thread>[_<rollout>].jsonl`
|
|
267
|
+
* (verified against openai/codex 0.153, codex-rs/rollout/). Every line is
|
|
268
|
+
* `{timestamp, ordinal?, type, payload}`; the user's prompts are
|
|
269
|
+
* `response_item` messages with `role: "user"`.
|
|
270
|
+
*
|
|
271
|
+
* Codex also injects context *as user-role messages* (AGENTS.md, the
|
|
272
|
+
* environment block, turn-aborted notices, hook output). Since 0.148 genuine
|
|
273
|
+
* prompts carry `internal_chat_message_metadata_passthrough.content_item_kinds`
|
|
274
|
+
* containing `user.*`, which is the reliable discriminator; older rollouts lack
|
|
275
|
+
* it, so the wrapper markers Codex renders are the fallback.
|
|
276
|
+
*/
|
|
277
|
+
const CODEX_INJECTED_MARKERS = [
|
|
278
|
+
/^\s*# AGENTS\.md instructions/i,
|
|
279
|
+
/^\s*<user_instructions>/i,
|
|
280
|
+
/^\s*<environment_context>/i,
|
|
281
|
+
/^\s*<turn_aborted>/i,
|
|
282
|
+
/^\s*<user_shell_command>/i,
|
|
283
|
+
/^\s*<subagent_notification>/i,
|
|
284
|
+
/^\s*<codex_internal_context/i,
|
|
285
|
+
/^\s*<goal_context>/i,
|
|
286
|
+
/^\s*<hook_prompt/i,
|
|
287
|
+
/^\s*<brain-/i,
|
|
288
|
+
];
|
|
289
|
+
|
|
290
|
+
// rollout-YYYY-MM-DDTHH-MM-SS-<thread>[_<rollout>].jsonl → the id token
|
|
291
|
+
const CODEX_ROLLOUT_NAME = /^rollout-\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-(.+)\.jsonl$/;
|
|
292
|
+
|
|
293
|
+
// Threads Codex runs for itself (subagents, guardian reviews, memory
|
|
294
|
+
// consolidation) contain no user speech.
|
|
295
|
+
const CODEX_BACKGROUND_THREADS = new Set(['subagent', 'guardian_review', 'memory_consolidation']);
|
|
296
|
+
|
|
297
|
+
function codexHome() {
|
|
298
|
+
return process.env.CODEX_HOME || path.join(os.homedir(), '.codex');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function codexInputText(payload) {
|
|
302
|
+
const content = Array.isArray(payload.content) ? payload.content : [];
|
|
303
|
+
return content
|
|
304
|
+
.filter((block) => block && block.type === 'input_text' && typeof block.text === 'string')
|
|
305
|
+
.map((block) => block.text)
|
|
306
|
+
.join('\n');
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function codexIsUserAuthored(payload) {
|
|
310
|
+
const meta = payload.internal_chat_message_metadata_passthrough;
|
|
311
|
+
const kinds = meta && Array.isArray(meta.content_item_kinds) ? meta.content_item_kinds : [];
|
|
312
|
+
if (kinds.length > 0) {
|
|
313
|
+
return kinds.some((k) => typeof k === 'string' && (k.startsWith('user.') || k === 'unknown'));
|
|
314
|
+
}
|
|
315
|
+
return !CODEX_INJECTED_MARKERS.some((marker) => marker.test(codexInputText(payload)));
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function codexIsBackgroundThread(meta) {
|
|
319
|
+
if (meta.parent_thread_id) return true;
|
|
320
|
+
if (typeof meta.thread_source === 'string' && CODEX_BACKGROUND_THREADS.has(meta.thread_source)) return true;
|
|
321
|
+
const source = meta.source;
|
|
322
|
+
return Boolean(source && typeof source === 'object' && ('subagent' in source || 'internal' in source));
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* User-assigned thread names from `$CODEX_HOME/session_index.jsonl` (last
|
|
327
|
+
* entry per id wins). Cached per home dir — one read per harvest.
|
|
328
|
+
*/
|
|
329
|
+
const codexThreadNames = new Map();
|
|
330
|
+
function codexThreadName(home, threadId) {
|
|
331
|
+
if (!codexThreadNames.has(home)) {
|
|
332
|
+
const names = new Map();
|
|
333
|
+
for (const entry of readJsonl(path.join(home, 'session_index.jsonl'))) {
|
|
334
|
+
if (entry && typeof entry.id === 'string' && typeof entry.thread_name === 'string') {
|
|
335
|
+
names.set(entry.id, entry.thread_name);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
codexThreadNames.set(home, names);
|
|
339
|
+
}
|
|
340
|
+
return codexThreadNames.get(home).get(threadId) || null;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const codex = {
|
|
344
|
+
id: 'codex',
|
|
345
|
+
label: 'OpenAI Codex CLI',
|
|
346
|
+
root: () => path.join(codexHome(), 'sessions'),
|
|
347
|
+
|
|
348
|
+
listFiles(root) {
|
|
349
|
+
// Exactly sessions/<year>/<month>/<day>/rollout-*.jsonl. Compressed
|
|
350
|
+
// rollouts (`.jsonl.zst`, an opt-in Codex feature) are skipped.
|
|
351
|
+
const files = [];
|
|
352
|
+
const walk = (dir, depth) => {
|
|
353
|
+
let entries;
|
|
354
|
+
try {
|
|
355
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
356
|
+
} catch (_) {
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
for (const entry of entries) {
|
|
360
|
+
const full = path.join(dir, entry.name);
|
|
361
|
+
if (entry.isDirectory() && depth < 3 && /^\d+$/.test(entry.name)) walk(full, depth + 1);
|
|
362
|
+
else if (entry.isFile() && depth === 3 && CODEX_ROLLOUT_NAME.test(entry.name)) files.push(full);
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
walk(root, 0);
|
|
366
|
+
return files.sort();
|
|
367
|
+
},
|
|
368
|
+
|
|
369
|
+
/** Session id = the id token in the filename (unique per rollout file). */
|
|
370
|
+
sessionIdFor(file) {
|
|
371
|
+
const match = path.basename(file).match(CODEX_ROLLOUT_NAME);
|
|
372
|
+
return match ? match[1] : path.basename(file, '.jsonl');
|
|
373
|
+
},
|
|
374
|
+
|
|
375
|
+
parse(file) {
|
|
376
|
+
const records = readJsonl(file);
|
|
377
|
+
if (records.length === 0) return null;
|
|
378
|
+
|
|
379
|
+
const sessionId = codex.sessionIdFor(file);
|
|
380
|
+
const session = {
|
|
381
|
+
source: 'codex',
|
|
382
|
+
session_id: sessionId,
|
|
383
|
+
title: null,
|
|
384
|
+
cwd: null,
|
|
385
|
+
git_branch: null,
|
|
386
|
+
started: null,
|
|
387
|
+
ended: null,
|
|
388
|
+
models: new Set(),
|
|
389
|
+
prompts: [],
|
|
390
|
+
files_touched: new Set(),
|
|
391
|
+
turns: 0,
|
|
392
|
+
};
|
|
393
|
+
|
|
394
|
+
for (const record of records) {
|
|
395
|
+
if (!record || typeof record !== 'object') continue;
|
|
396
|
+
const payload = record.payload && typeof record.payload === 'object' ? record.payload : {};
|
|
397
|
+
if (record.timestamp) {
|
|
398
|
+
if (!session.started || record.timestamp < session.started) session.started = record.timestamp;
|
|
399
|
+
if (!session.ended || record.timestamp > session.ended) session.ended = record.timestamp;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
if (record.type === 'session_meta') {
|
|
403
|
+
if (codexIsBackgroundThread(payload)) return null;
|
|
404
|
+
if (payload.cwd) session.cwd = payload.cwd;
|
|
405
|
+
if (payload.git && payload.git.branch) session.git_branch = payload.git.branch;
|
|
406
|
+
} else if (record.type === 'turn_context') {
|
|
407
|
+
if (payload.model) session.models.add(payload.model);
|
|
408
|
+
if (payload.cwd && !session.cwd) session.cwd = payload.cwd;
|
|
409
|
+
} else if (record.type === 'response_item') {
|
|
410
|
+
if (payload.type === 'message' && payload.role === 'user') {
|
|
411
|
+
if (!codexIsUserAuthored(payload)) continue;
|
|
412
|
+
const text = cleanPromptText(codexInputText(payload));
|
|
413
|
+
if (text) session.prompts.push(text);
|
|
414
|
+
} else if (payload.type === 'message' && payload.role === 'assistant') {
|
|
415
|
+
session.turns++;
|
|
416
|
+
} else if (payload.type === 'custom_tool_call' && payload.name === 'apply_patch' && typeof payload.input === 'string') {
|
|
417
|
+
for (const match of payload.input.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)) {
|
|
418
|
+
session.files_touched.add(match[1].trim());
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// <home>/sessions/YYYY/MM/DD/<file> → <home>; names are keyed by thread id.
|
|
425
|
+
const home = path.resolve(path.dirname(file), '..', '..', '..', '..');
|
|
426
|
+
session.title = codexThreadName(home, sessionId.split('_')[0]);
|
|
427
|
+
return session;
|
|
428
|
+
},
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
const SOURCES = { [claudeCode.id]: claudeCode, [codex.id]: codex };
|
|
261
432
|
|
|
262
433
|
/** Sources that actually have a history store on this machine. */
|
|
263
434
|
function availableSources() {
|
|
@@ -327,7 +498,8 @@ function markImported(sourceId, sessionIds, projectRoot, knownIds) {
|
|
|
327
498
|
if (adapter) {
|
|
328
499
|
const root = adapter.root();
|
|
329
500
|
if (fs.existsSync(root)) {
|
|
330
|
-
known = new Set(adapter.listFiles(root).map((f) =>
|
|
501
|
+
known = new Set(adapter.listFiles(root).map((f) =>
|
|
502
|
+
(adapter.sessionIdFor ? adapter.sessionIdFor(f) : path.basename(f, '.jsonl'))));
|
|
331
503
|
}
|
|
332
504
|
}
|
|
333
505
|
}
|
package/src/index-manager.js
CHANGED
|
@@ -29,6 +29,14 @@ const DEFAULT_CONFIG = {
|
|
|
29
29
|
pin_budget_tokens: 1500,
|
|
30
30
|
skills_index_budget_tokens: 800,
|
|
31
31
|
recall_budget_tokens: 700,
|
|
32
|
+
// Prompt-time recall (UserPromptSubmit hook): memories injected alongside a
|
|
33
|
+
// user prompt. Small on purpose — it fires on every substantive prompt.
|
|
34
|
+
prompt_recall_top: 3,
|
|
35
|
+
prompt_recall_budget_tokens: 600,
|
|
36
|
+
// Sensitive-topic consent (see src/sensitivity.js). Off by default: writes
|
|
37
|
+
// classified `sensitive` are quarantined and hidden until the user opts in
|
|
38
|
+
// here or approves them one by one with `brain verify approve`.
|
|
39
|
+
sensitive_topics: false,
|
|
32
40
|
// ASI06 quarantine for low-trust writes: 'off' (never flag), 'flag'
|
|
33
41
|
// (recallable but marked + surfaced for verification — the default), or
|
|
34
42
|
// 'enforce' (excluded from recall/session-start until approved). Exclusion
|
package/src/installer.js
CHANGED
|
@@ -39,6 +39,10 @@ const RUNTIMES = {
|
|
|
39
39
|
promptSource: 'openai.md',
|
|
40
40
|
commandStyle: 'skills',
|
|
41
41
|
skillName: true,
|
|
42
|
+
// Codex hooks engine (0.148+): SessionStart / UserPromptSubmit / SessionEnd
|
|
43
|
+
// command hooks pointing at this package's hooks/*.mjs. Merged into the
|
|
44
|
+
// host's hooks.json non-destructively; the user trusts them via /hooks.
|
|
45
|
+
hooksFile: 'hooks.json',
|
|
42
46
|
},
|
|
43
47
|
antigravity: {
|
|
44
48
|
name: 'Google Antigravity',
|
|
@@ -248,6 +252,110 @@ function removeInstructionsEntry(configPath, entry) {
|
|
|
248
252
|
return { removed: true };
|
|
249
253
|
}
|
|
250
254
|
|
|
255
|
+
// ---------------------------------------------------------------------------
|
|
256
|
+
// Host hooks (Codex). The hook scripts in <package>/hooks/ run the engine
|
|
257
|
+
// in-process, so registering them is just writing their absolute paths into
|
|
258
|
+
// the host's hooks.json. hooks/hooks.json is the single source of truth (the
|
|
259
|
+
// plugin install uses the same file with ${CLAUDE_PLUGIN_ROOT} expanded by the
|
|
260
|
+
// host); here the placeholder is expanded to this package's root.
|
|
261
|
+
// ---------------------------------------------------------------------------
|
|
262
|
+
|
|
263
|
+
const HOOK_SCRIPT_RE = /[\\/]hooks[\\/](session-start|prompt-recall|session-end)\.mjs"?$/;
|
|
264
|
+
|
|
265
|
+
function isBrainHook(hook) {
|
|
266
|
+
return Boolean(hook) && typeof hook.command === 'string' && HOOK_SCRIPT_RE.test(hook.command);
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/** hooks/hooks.json with ${CLAUDE_PLUGIN_ROOT} resolved to `root`. */
|
|
270
|
+
function renderHooksConfig(root = PACKAGE_ROOT) {
|
|
271
|
+
const raw = fs.readFileSync(path.join(PACKAGE_ROOT, 'hooks', 'hooks.json'), 'utf-8');
|
|
272
|
+
return JSON.parse(raw.split('${CLAUDE_PLUGIN_ROOT}').join(root.replace(/\\/g, '/')));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* Merge brain's hook groups into an existing hooks config, replacing any
|
|
277
|
+
* earlier brain groups and leaving everything else untouched.
|
|
278
|
+
*/
|
|
279
|
+
function mergeHooksConfig(existing, ours) {
|
|
280
|
+
const base = existing && typeof existing === 'object' && !Array.isArray(existing) ? { ...existing } : {};
|
|
281
|
+
const hooks = base.hooks && typeof base.hooks === 'object' && !Array.isArray(base.hooks) ? { ...base.hooks } : {};
|
|
282
|
+
for (const [event, groups] of Object.entries(ours.hooks)) {
|
|
283
|
+
const kept = (Array.isArray(hooks[event]) ? hooks[event] : [])
|
|
284
|
+
.filter((group) => !(group && Array.isArray(group.hooks) && group.hooks.some(isBrainHook)));
|
|
285
|
+
hooks[event] = kept.concat(groups);
|
|
286
|
+
}
|
|
287
|
+
base.hooks = hooks;
|
|
288
|
+
return base;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Remove brain's hook groups; returns the config and how many were removed. */
|
|
292
|
+
function stripHooksConfig(existing) {
|
|
293
|
+
if (!existing || typeof existing !== 'object' || Array.isArray(existing)) return { config: existing, removed: 0 };
|
|
294
|
+
const hooks = existing.hooks && typeof existing.hooks === 'object' ? existing.hooks : {};
|
|
295
|
+
let removed = 0;
|
|
296
|
+
const next = {};
|
|
297
|
+
for (const [event, groups] of Object.entries(hooks)) {
|
|
298
|
+
if (!Array.isArray(groups)) { next[event] = groups; continue; }
|
|
299
|
+
const kept = groups.filter((group) => {
|
|
300
|
+
const mine = group && Array.isArray(group.hooks) && group.hooks.some(isBrainHook);
|
|
301
|
+
if (mine) removed++;
|
|
302
|
+
return !mine;
|
|
303
|
+
});
|
|
304
|
+
if (kept.length > 0) next[event] = kept;
|
|
305
|
+
}
|
|
306
|
+
return { config: { ...existing, hooks: next }, removed };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function readJsonFile(file) {
|
|
310
|
+
if (!fs.existsSync(file)) return { exists: false, data: null };
|
|
311
|
+
try {
|
|
312
|
+
return { exists: true, data: JSON.parse(fs.readFileSync(file, 'utf-8')) };
|
|
313
|
+
} catch {
|
|
314
|
+
return { exists: true, data: null, corrupt: true };
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Register brain's hooks in a host hooks.json. A file we cannot parse is
|
|
320
|
+
* never rewritten — the caller prints the one manual step instead.
|
|
321
|
+
*/
|
|
322
|
+
function installHooks(hooksFile, root = PACKAGE_ROOT) {
|
|
323
|
+
const { exists, data, corrupt } = readJsonFile(hooksFile);
|
|
324
|
+
if (corrupt) return { registered: false, manual: true, reason: 'not-json', path: hooksFile };
|
|
325
|
+
fs.mkdirSync(path.dirname(hooksFile), { recursive: true });
|
|
326
|
+
const merged = mergeHooksConfig(exists ? data : null, renderHooksConfig(root));
|
|
327
|
+
fs.writeFileSync(hooksFile, JSON.stringify(merged, null, 2) + '\n');
|
|
328
|
+
return { registered: true, created: !exists, path: hooksFile };
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
function uninstallHooks(hooksFile) {
|
|
332
|
+
const { exists, data, corrupt } = readJsonFile(hooksFile);
|
|
333
|
+
if (!exists) return { removed: 0, reason: 'file-not-found' };
|
|
334
|
+
if (corrupt) return { removed: 0, manual: true, reason: 'not-json', path: hooksFile };
|
|
335
|
+
const { config, removed } = stripHooksConfig(data);
|
|
336
|
+
if (removed === 0) return { removed: 0, reason: 'not-registered' };
|
|
337
|
+
const onlyHooks = Object.keys(config).every((k) => k === 'hooks');
|
|
338
|
+
if (onlyHooks && Object.keys(config.hooks).length === 0) {
|
|
339
|
+
fs.unlinkSync(hooksFile);
|
|
340
|
+
return { removed, fileDeleted: true };
|
|
341
|
+
}
|
|
342
|
+
fs.writeFileSync(hooksFile, JSON.stringify(config, null, 2) + '\n');
|
|
343
|
+
return { removed, fileDeleted: false };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
function hooksFileFor(config, scope) {
|
|
347
|
+
if (!config.hooksFile) return null;
|
|
348
|
+
return path.join(scope === 'global' ? config.globalDir : config.localDir, config.hooksFile);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function hooksInstalled(hooksFile) {
|
|
352
|
+
const { data } = readJsonFile(hooksFile);
|
|
353
|
+
if (!data || !data.hooks || typeof data.hooks !== 'object') return false;
|
|
354
|
+
return Object.values(data.hooks).some(
|
|
355
|
+
(groups) => Array.isArray(groups) && groups.some((g) => g && Array.isArray(g.hooks) && g.hooks.some(isBrainHook))
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
|
|
251
359
|
function detectInstallations() {
|
|
252
360
|
const results = [];
|
|
253
361
|
for (const [runtime, config] of Object.entries(RUNTIMES)) {
|
|
@@ -278,13 +386,17 @@ function detectInstallations() {
|
|
|
278
386
|
promptFound = content.includes(BRAIN_MARKER_START) && content.includes(BRAIN_MARKER_END);
|
|
279
387
|
}
|
|
280
388
|
|
|
281
|
-
|
|
389
|
+
const hooksFile = hooksFileFor(config, scope);
|
|
390
|
+
const hooksFound = Boolean(hooksFile) && hooksInstalled(hooksFile);
|
|
391
|
+
|
|
392
|
+
if (commandsFound || promptFound || hooksFound) {
|
|
282
393
|
results.push({
|
|
283
394
|
runtime,
|
|
284
395
|
scope,
|
|
285
396
|
runtimeName: config.name,
|
|
286
397
|
commandsFound,
|
|
287
398
|
promptFound,
|
|
399
|
+
hooksFound,
|
|
288
400
|
targetDir,
|
|
289
401
|
promptPath,
|
|
290
402
|
});
|
|
@@ -361,6 +473,8 @@ function uninstallForRuntime(runtime, scope) {
|
|
|
361
473
|
|
|
362
474
|
const removedCommands = removeCommands(targetDir, config, scope);
|
|
363
475
|
const promptResult = removePromptSection(promptPath);
|
|
476
|
+
const hooksFile = hooksFileFor(config, scope);
|
|
477
|
+
const hooksResult = hooksFile ? uninstallHooks(hooksFile) : undefined;
|
|
364
478
|
|
|
365
479
|
let promptRegistration;
|
|
366
480
|
if (scope === 'global' && config.instructionsConfig) {
|
|
@@ -370,7 +484,7 @@ function uninstallForRuntime(runtime, scope) {
|
|
|
370
484
|
);
|
|
371
485
|
}
|
|
372
486
|
|
|
373
|
-
return { removedCommands, promptResult, promptRegistration };
|
|
487
|
+
return { removedCommands, promptResult, promptRegistration, hooksResult };
|
|
374
488
|
}
|
|
375
489
|
|
|
376
490
|
function installForRuntime(runtime, scope) {
|
|
@@ -418,7 +532,10 @@ function installForRuntime(runtime, scope) {
|
|
|
418
532
|
);
|
|
419
533
|
}
|
|
420
534
|
|
|
421
|
-
|
|
535
|
+
const hooksFile = hooksFileFor(config, scope);
|
|
536
|
+
const hooks = hooksFile ? installHooks(hooksFile) : undefined;
|
|
537
|
+
|
|
538
|
+
return { promptRegistration, hooks };
|
|
422
539
|
}
|
|
423
540
|
|
|
424
541
|
function initializeBrain(overrideBase) {
|
|
@@ -557,4 +674,10 @@ module.exports = {
|
|
|
557
674
|
removePromptSection,
|
|
558
675
|
removeCommands,
|
|
559
676
|
uninstallForRuntime,
|
|
677
|
+
renderHooksConfig,
|
|
678
|
+
mergeHooksConfig,
|
|
679
|
+
stripHooksConfig,
|
|
680
|
+
installHooks,
|
|
681
|
+
uninstallHooks,
|
|
682
|
+
hooksInstalled,
|
|
560
683
|
};
|
package/src/integrity.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brain Memory — Content Integrity (OWASP ASI06: store-phase tamper detection)
|
|
3
|
+
*
|
|
4
|
+
* Every other poisoning defense in this codebase guards the *write path*:
|
|
5
|
+
* provenance clamps what an origin may claim, content-lint inspects the payload
|
|
6
|
+
* shape, quarantine holds low-trust writes for review, anomaly.js reads the
|
|
7
|
+
* audit log for attack-shaped write patterns. All of them assume the attacker
|
|
8
|
+
* arrives through `brain memorize`.
|
|
9
|
+
*
|
|
10
|
+
* They are all blind to an editor.
|
|
11
|
+
*
|
|
12
|
+
* `~/.brain/` is plain Markdown on disk — that is the product's best feature and
|
|
13
|
+
* its widest attack surface. Anything with write access to the home directory
|
|
14
|
+
* can rewrite the body of an already-trusted, already-vetted, already-pinned
|
|
15
|
+
* memory without touching the index, the audit log, or any origin label. The
|
|
16
|
+
* memory keeps its `user` origin and its 1.0 trust factor, and the new text
|
|
17
|
+
* rides into every future session with full authority. No detector here fires,
|
|
18
|
+
* because no *write event* ever happened.
|
|
19
|
+
*
|
|
20
|
+
* This module closes that gap the only way a file-based store can: record what
|
|
21
|
+
* each memory said when the brain last agreed with it, and notice when the
|
|
22
|
+
* bytes stop matching. That is the "cryptographic baseline" half of OWASP's
|
|
23
|
+
* Agent Memory Guard guidance, and the Store phase of the memory lifecycle in
|
|
24
|
+
* the LTM security survey (arXiv:2604.16548), which argues integrity cannot be
|
|
25
|
+
* retrofitted at retrieval time alone.
|
|
26
|
+
*
|
|
27
|
+
* ── What a finding means ─────────────────────────────────────────────────
|
|
28
|
+
* `content_hash` drift is EVIDENCE OF AN EDIT, not proof of an attack. Brain's
|
|
29
|
+
* own maintenance rewrites memory bodies legitimately: `/brain:sleep` phases
|
|
30
|
+
* (consolidation, crystallization, reorganize) are agent-driven and edit files
|
|
31
|
+
* directly, and a user is entitled to fix a typo in their own memory with vim.
|
|
32
|
+
* So this detector is deliberately ADVISORY — it never auto-quarantines, and
|
|
33
|
+
* `runAudit`'s `--apply` path does not act on it.
|
|
34
|
+
*
|
|
35
|
+
* The signal is only meaningful against the baseline, so re-baseline after any
|
|
36
|
+
* legitimate bulk rewrite: `brain audit --rebaseline`.
|
|
37
|
+
*
|
|
38
|
+
* ── Why not compare against the audit log? ───────────────────────────────
|
|
39
|
+
* Tempting: every legitimate write appends to audit.log, so "changed without an
|
|
40
|
+
* audit entry" would be a sharper signal. It does not hold — sleep is a prompt,
|
|
41
|
+
* not a CLI path, so it edits files without writing audit events. Until every
|
|
42
|
+
* mutation path routes through an audited helper, an audit-log-derived baseline
|
|
43
|
+
* would produce false positives on every sleep cycle.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
const fs = require('fs');
|
|
47
|
+
const path = require('path');
|
|
48
|
+
const crypto = require('crypto');
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* SHA-256 of a memory's on-disk bytes, hex-encoded.
|
|
52
|
+
*
|
|
53
|
+
* Hashes the WHOLE file, frontmatter included. Frontmatter carries strength,
|
|
54
|
+
* trust, pin state, and quarantine flags — fields an attacker would rather edit
|
|
55
|
+
* than the prose, so excluding them would leave the most valuable target
|
|
56
|
+
* unguarded. The cost is that ordinary recall (which bumps `last_accessed` and
|
|
57
|
+
* `access_count`) also moves the hash, which is why re-baselining is a normal
|
|
58
|
+
* part of the workflow rather than an alarm.
|
|
59
|
+
*
|
|
60
|
+
* @param {string} text - Raw file contents
|
|
61
|
+
* @returns {string} 64-char hex digest
|
|
62
|
+
*/
|
|
63
|
+
function contentHash(text) {
|
|
64
|
+
return crypto.createHash('sha256').update(text, 'utf-8').digest('hex');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Hash the memory file an index entry points at.
|
|
69
|
+
*
|
|
70
|
+
* @param {string} brainDir - Absolute path to ~/.brain/
|
|
71
|
+
* @param {string} relPath - Index entry's `path`
|
|
72
|
+
* @returns {string|null} Digest, or null when the file is unreadable/missing
|
|
73
|
+
*/
|
|
74
|
+
function hashMemoryFile(brainDir, relPath) {
|
|
75
|
+
try {
|
|
76
|
+
return contentHash(fs.readFileSync(path.join(brainDir, relPath), 'utf-8'));
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Compare every indexed memory's current bytes against its recorded baseline.
|
|
84
|
+
*
|
|
85
|
+
* Three outcomes per memory:
|
|
86
|
+
* - no baseline recorded → not a finding (unbaselined, not tampered)
|
|
87
|
+
* - file missing/unreadable → `missing_file` finding
|
|
88
|
+
* - hash differs → `content_drift` finding
|
|
89
|
+
*
|
|
90
|
+
* Findings are ordered most-trusted-first: drift in a pinned, user-origin
|
|
91
|
+
* memory is the one worth waking up for, because that memory carries the most
|
|
92
|
+
* authority into future sessions.
|
|
93
|
+
*
|
|
94
|
+
* @param {string} brainDir - Absolute path to ~/.brain/
|
|
95
|
+
* @param {Object} index - Parsed index.json
|
|
96
|
+
* @returns {Array<Object>} findings
|
|
97
|
+
*/
|
|
98
|
+
function detectContentDrift(brainDir, index) {
|
|
99
|
+
const findings = [];
|
|
100
|
+
for (const [id, entry] of Object.entries((index && index.memories) || {})) {
|
|
101
|
+
if (!entry.content_hash) continue; // never baselined — not a finding
|
|
102
|
+
const actual = hashMemoryFile(brainDir, entry.path);
|
|
103
|
+
if (actual === null) {
|
|
104
|
+
findings.push({ kind: 'missing_file', id, path: entry.path, advisory: true });
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
if (actual !== entry.content_hash) {
|
|
108
|
+
findings.push({
|
|
109
|
+
kind: 'content_drift',
|
|
110
|
+
id,
|
|
111
|
+
path: entry.path,
|
|
112
|
+
origin: entry.origin || 'agent-inferred',
|
|
113
|
+
pinned: Boolean(entry.pinned),
|
|
114
|
+
vetted: Boolean(entry.vetted),
|
|
115
|
+
expected: entry.content_hash.slice(0, 12),
|
|
116
|
+
actual: actual.slice(0, 12),
|
|
117
|
+
advisory: true,
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Authority-first: pinned outranks vetted outranks user-origin, so the most
|
|
123
|
+
// load-bearing memory in the brain is the first line the user reads.
|
|
124
|
+
const authority = (f) =>
|
|
125
|
+
(f.pinned ? 4 : 0) + (f.vetted ? 2 : 0) + (f.origin === 'user' ? 1 : 0);
|
|
126
|
+
return findings.sort((a, b) => authority(b) - authority(a) || (a.id < b.id ? -1 : 1));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Stamp `content_hash` on index entries from the files' current bytes.
|
|
131
|
+
*
|
|
132
|
+
* Called after a legitimate rewrite (memorize, sleep, restore, sync pull) and
|
|
133
|
+
* by `brain audit --rebaseline`. Mutates `index` in place; the caller writes it.
|
|
134
|
+
*
|
|
135
|
+
* @param {string} brainDir - Absolute path to ~/.brain/
|
|
136
|
+
* @param {Object} index - Parsed index.json (mutated)
|
|
137
|
+
* @param {string[]} [ids] - Restrict to these IDs; omit to baseline everything
|
|
138
|
+
* @returns {{ baselined: number, unreadable: string[] }}
|
|
139
|
+
*/
|
|
140
|
+
function rebaseline(brainDir, index, ids) {
|
|
141
|
+
const entries = Object.entries((index && index.memories) || {});
|
|
142
|
+
const targets = ids ? entries.filter(([id]) => ids.includes(id)) : entries;
|
|
143
|
+
|
|
144
|
+
let baselined = 0;
|
|
145
|
+
const unreadable = [];
|
|
146
|
+
for (const [id, entry] of targets) {
|
|
147
|
+
const h = hashMemoryFile(brainDir, entry.path);
|
|
148
|
+
if (h === null) { unreadable.push(id); continue; }
|
|
149
|
+
entry.content_hash = h;
|
|
150
|
+
baselined++;
|
|
151
|
+
}
|
|
152
|
+
return { baselined, unreadable };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
module.exports = { contentHash, hashMemoryFile, detectContentDrift, rebaseline };
|