brain-memory 0.2.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 +139 -0
- package/README.md +27 -3
- package/bin/audit.js +18 -1
- package/bin/brain +4 -0
- package/bin/import.js +1 -1
- package/bin/install.js +10 -0
- package/bin/memorize.js +53 -8
- package/bin/recall.js +32 -13
- package/bin/reinforce.js +34 -1
- package/bin/session-start.js +17 -4
- package/bin/skill.js +8 -2
- package/commands/brain/import.md +1 -1
- package/commands/brain/memorize.md +25 -4
- package/commands/brain/skills.md +29 -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 +4 -1
- package/prompts/claude.md +4 -1
- package/prompts/copilot.md +4 -1
- package/prompts/kilo.md +4 -1
- package/prompts/openai.md +4 -1
- package/prompts/opencode.md +4 -1
- 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 +8 -4
- package/src/sensitivity.js +134 -0
- package/src/skill-verify.js +191 -0
- package/src/skills.js +63 -0
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 };
|
package/src/receipt.js
CHANGED
|
@@ -14,8 +14,9 @@
|
|
|
14
14
|
* wherever its receipt appears: ◉ memory: "<title>" (<type>, <age>, ⚠ external)
|
|
15
15
|
* Memories pending verification (quarantined — see src/quarantine.js) carry a
|
|
16
16
|
* further "⊘ unverified" segment, and memories whose validity window has closed
|
|
17
|
-
* (see src/temporal.js) a "⌛ expired" one
|
|
18
|
-
*
|
|
17
|
+
* (see src/temporal.js) a "⌛ expired" one, and sensitive-topic memories (see
|
|
18
|
+
* src/sensitivity.js) a "⚠ sensitive" one. User/agent-inferred, vetted, current,
|
|
19
|
+
* standard receipts are byte-identical to the base format.
|
|
19
20
|
*
|
|
20
21
|
* Age is derived from the memory's `created` timestamp (falling back to
|
|
21
22
|
* `last_accessed`; omitted entirely when neither parses):
|
|
@@ -78,10 +79,13 @@ function receiptFor(memoryLike, nowFn) {
|
|
|
78
79
|
// still be the right answer ("that was true until March") — but it must
|
|
79
80
|
// never look current, so the marker rides along with the receipt.
|
|
80
81
|
const expired = temporalState(mem, now.getTime()) === 'expired' ? ', ⌛ expired' : '';
|
|
82
|
+
// Consent: a sensitive-topic memory stays visibly marked even after the user
|
|
83
|
+
// opted in or approved it, so the agent knows to handle it with care.
|
|
84
|
+
const sensitive = mem.sensitivity === 'sensitive' ? ', ⚠ sensitive' : '';
|
|
81
85
|
|
|
82
86
|
return age
|
|
83
|
-
? `◉ memory: "${title}" (${type}, ${age}${trust}${pending}${expired})`
|
|
84
|
-
: `◉ memory: "${title}" (${type}${trust}${pending}${expired})`;
|
|
87
|
+
? `◉ memory: "${title}" (${type}, ${age}${trust}${pending}${expired}${sensitive})`
|
|
88
|
+
: `◉ memory: "${title}" (${type}${trust}${pending}${expired}${sensitive})`;
|
|
85
89
|
}
|
|
86
90
|
|
|
87
91
|
module.exports = { receiptFor, ageLabel };
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brain Memory — Sensitive-topic consent (per-fragment)
|
|
3
|
+
*
|
|
4
|
+
* Three tiers, deliberately matching the vocabulary of the largest deployed
|
|
5
|
+
* consent model for assistant memory (Anthropic's, Aug 2026) so a brain is
|
|
6
|
+
* interoperable with it rather than inventing a bespoke schema:
|
|
7
|
+
*
|
|
8
|
+
* standard Stored normally. The default.
|
|
9
|
+
* sensitive Health, race, ethnicity, religious beliefs, politics, gender
|
|
10
|
+
* identity and similar. Excluded from storage unless the user has
|
|
11
|
+
* opted in (`sensitive_topics: true` in ~/.brain/config.json) —
|
|
12
|
+
* until then the write lands quarantined (`sensitive_opt_out`) and
|
|
13
|
+
* is hidden from recall and session-start. `brain verify approve`
|
|
14
|
+
* is per-item consent and lifts the exclusion for that memory.
|
|
15
|
+
* Never retroactive: opting in never rewrites what was refused.
|
|
16
|
+
* blocked Government / national ID numbers, criminal history, immigration
|
|
17
|
+
* status. Refused at write time whatever the toggle says.
|
|
18
|
+
*
|
|
19
|
+
* The agent classifies (it read the conversation); the patterns here are a
|
|
20
|
+
* backstop for the two tiers that must never depend on a caller's honesty.
|
|
21
|
+
* They are narrow on purpose: a false "blocked" refuses a write the user asked
|
|
22
|
+
* for, so only unambiguous identifiers and phrases qualify, and the sensitive
|
|
23
|
+
* backstop flags rather than blocks. Nothing here is PII detection.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
const SENSITIVITY_LEVELS = ['standard', 'sensitive', 'blocked'];
|
|
27
|
+
const DEFAULT_SENSITIVITY = 'standard';
|
|
28
|
+
const SENSITIVE_OPT_OUT_REASON = 'sensitive_opt_out';
|
|
29
|
+
|
|
30
|
+
/** Category → description, as published. Kept as data so docs and prompts can cite it. */
|
|
31
|
+
const SENSITIVE_CATEGORIES = {
|
|
32
|
+
health: 'physical or mental health, conditions, medication, treatment',
|
|
33
|
+
race: 'race',
|
|
34
|
+
ethnicity: 'ethnicity or national origin',
|
|
35
|
+
religion: 'religious or philosophical beliefs',
|
|
36
|
+
politics: 'political opinions or affiliation',
|
|
37
|
+
gender_identity: 'gender identity or sexual orientation',
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const BLOCKED_CATEGORIES = {
|
|
41
|
+
government_id: 'social-security, passport, national-ID, tax or similar identification numbers',
|
|
42
|
+
criminal_history: 'criminal history, charges, convictions',
|
|
43
|
+
immigration_status: 'immigration or visa status',
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
// --- Backstop patterns ---
|
|
47
|
+
|
|
48
|
+
const BLOCKED_RULES = [
|
|
49
|
+
// Structured identifiers: a US SSN, or an ID-word within a few tokens of a
|
|
50
|
+
// 6-12 digit run (passport/national/tax IDs vary by country; the word makes
|
|
51
|
+
// the digits unambiguous).
|
|
52
|
+
{ category: 'government_id', re: /\b\d{3}-\d{2}-\d{4}\b/ },
|
|
53
|
+
{
|
|
54
|
+
category: 'government_id',
|
|
55
|
+
re: /\b(?:ssn|social\s+security|passport|national\s+id|tax\s+id|citizen\s+service|bsn|nino|sin)\b(?:\s+(?:number|no\.?|#))?[^\n\d]{0,20}\d(?:[\s-]?\d){5,11}\b/i,
|
|
56
|
+
},
|
|
57
|
+
{ category: 'criminal_history', re: /\b(?:criminal\s+(?:record|history|charges?)|convicted\s+of|felony\s+conviction|misdemeanou?r\s+conviction|was\s+arrested\s+for|serv(?:ed|ing)\s+(?:time|a\s+sentence))\b/i },
|
|
58
|
+
{ category: 'immigration_status', re: /\b(?:immigration\s+status|visa\s+status|undocumented\s+immigrant|asylum\s+(?:seeker|claim|status)|deportation\s+order|green\s+card\s+(?:status|application)|overstayed\s+(?:a|the|my|their)\s+visa)\b/i },
|
|
59
|
+
];
|
|
60
|
+
|
|
61
|
+
const SENSITIVE_RULES = [
|
|
62
|
+
{ category: 'health', re: /\b(?:diagnos(?:ed|is)\s+with|my\s+(?:therapist|psychiatrist|oncologist|medication|diagnosis)|(?:takes?|taking|prescribed)\s+(?:antidepressants?|insulin|chemotherapy|adhd\s+medication)|mental\s+health\s+(?:condition|history|diagnosis)|(?:has|have|had)\s+(?:cancer|diabetes|epilepsy|hiv|depression|bipolar|schizophrenia|ptsd|anorexia|bulimia))\b/i },
|
|
63
|
+
{ category: 'race', re: /\b(?:racial\s+(?:identity|background)|(?:identif(?:y|ies)\s+as|is|am)\s+(?:black|white|asian|latino|latina|latinx|hispanic|indigenous|native\s+american|mixed[- ]race))\b/i },
|
|
64
|
+
{ category: 'ethnicity', re: /\b(?:ethnic(?:ity|\s+background)|(?:is|am|are)\s+(?:of\s+)?(?:kurdish|turkish|arab|jewish|romani|han\s+chinese|tamil|uyghur|persian|armenian|pashtun)\s*(?:descent|origin|heritage)?)\b/i },
|
|
65
|
+
{ category: 'religion', re: /\b(?:religious\s+(?:beliefs?|affiliation|background)|(?:is|am|are)\s+(?:a\s+)?(?:practi[sc]ing\s+)?(?:muslim|christian|catholic|protestant|jewish|hindu|buddhist|sikh|atheist|agnostic)\b|converted\s+to\s+(?:islam|christianity|judaism|buddhism|hinduism)|attends?\s+(?:church|mosque|synagogue|temple)\s+(?:every|weekly|regularly))/i },
|
|
66
|
+
{ category: 'politics', re: /\b(?:political\s+(?:views?|affiliation|opinions?|party)|vot(?:ed|es|ing)\s+(?:for|against)\s+(?:the\s+)?[A-Z][\w-]+|(?:is|am|are)\s+(?:a\s+)?(?:registered\s+)?(?:democrat|republican|conservative|liberal|socialist|libertarian|green\s+party\s+member)|member\s+of\s+(?:the\s+)?\w+\s+party)\b/i },
|
|
67
|
+
{ category: 'gender_identity', re: /\b(?:gender\s+identity|(?:is|am|are|identif(?:y|ies)\s+as)\s+(?:transgender|trans|non-?binary|genderfluid|genderqueer|gay|lesbian|bisexual|queer|asexual|pansexual)|sexual\s+orientation|came\s+out\s+as)\b/i },
|
|
68
|
+
];
|
|
69
|
+
|
|
70
|
+
function textOf(mem) {
|
|
71
|
+
return `${(mem && mem.title) || ''}\n${(mem && mem.content) || ''}`;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Backstop classification of a memory's text.
|
|
76
|
+
*
|
|
77
|
+
* @param {Object} mem - { title, content }
|
|
78
|
+
* @returns {{ level: string, categories: string[] }}
|
|
79
|
+
*/
|
|
80
|
+
function classifySensitivity(mem) {
|
|
81
|
+
const text = textOf(mem);
|
|
82
|
+
const blocked = BLOCKED_RULES.filter((r) => r.re.test(text)).map((r) => r.category);
|
|
83
|
+
if (blocked.length > 0) return { level: 'blocked', categories: [...new Set(blocked)] };
|
|
84
|
+
const sensitive = SENSITIVE_RULES.filter((r) => r.re.test(text)).map((r) => r.category);
|
|
85
|
+
if (sensitive.length > 0) return { level: 'sensitive', categories: [...new Set(sensitive)] };
|
|
86
|
+
return { level: 'standard', categories: [] };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Resolve the final sensitivity of a write and what to do with it.
|
|
91
|
+
*
|
|
92
|
+
* The caller's label can only raise the level (an agent may not call a match
|
|
93
|
+
* for "criminal record" `standard`), and the backstop can only raise it too.
|
|
94
|
+
*
|
|
95
|
+
* @param {Object} mem - { title, content, sensitivity? }
|
|
96
|
+
* @param {Object} config - brain config (sensitive_topics)
|
|
97
|
+
* @returns {{ level, categories, action: 'store'|'quarantine'|'refuse', requested, error? }}
|
|
98
|
+
*/
|
|
99
|
+
function sensitivityDecision(mem, config) {
|
|
100
|
+
const requested = mem && mem.sensitivity != null ? String(mem.sensitivity) : null;
|
|
101
|
+
if (requested != null && !SENSITIVITY_LEVELS.includes(requested)) {
|
|
102
|
+
return { error: `Unknown sensitivity "${requested}" (expected one of: ${SENSITIVITY_LEVELS.join(', ')})` };
|
|
103
|
+
}
|
|
104
|
+
const detected = classifySensitivity(mem);
|
|
105
|
+
const rank = (l) => SENSITIVITY_LEVELS.indexOf(l);
|
|
106
|
+
const level = rank(detected.level) > rank(requested || DEFAULT_SENSITIVITY) ? detected.level : (requested || DEFAULT_SENSITIVITY);
|
|
107
|
+
|
|
108
|
+
let action = 'store';
|
|
109
|
+
if (level === 'blocked') action = 'refuse';
|
|
110
|
+
else if (level === 'sensitive' && !(config && config.sensitive_topics === true)) action = 'quarantine';
|
|
111
|
+
|
|
112
|
+
return { level, categories: detected.categories, action, requested };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Read-side gate: a sensitive memory is hidden from recall and session-start
|
|
117
|
+
* unless the user opted in globally or approved this one (`vetted`).
|
|
118
|
+
*/
|
|
119
|
+
function isSensitiveHidden(entry, config) {
|
|
120
|
+
if (!entry || entry.sensitivity !== 'sensitive') return false;
|
|
121
|
+
if (config && config.sensitive_topics === true) return false;
|
|
122
|
+
return !entry.vetted;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
module.exports = {
|
|
126
|
+
SENSITIVITY_LEVELS,
|
|
127
|
+
DEFAULT_SENSITIVITY,
|
|
128
|
+
SENSITIVE_OPT_OUT_REASON,
|
|
129
|
+
SENSITIVE_CATEGORIES,
|
|
130
|
+
BLOCKED_CATEGORIES,
|
|
131
|
+
classifySensitivity,
|
|
132
|
+
sensitivityDecision,
|
|
133
|
+
isSensitiveHidden,
|
|
134
|
+
};
|