brain-memory 0.2.0 → 0.4.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 +193 -0
- package/README.md +27 -3
- package/SECURITY.md +44 -3
- package/bin/audit.js +18 -1
- package/bin/brain +4 -0
- package/bin/cloud-sync.js +49 -6
- 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/commands/brain/sync.md +23 -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 +10 -4
- 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/cloud-sync.js +121 -9
- 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/store/CONTRACT.md +244 -0
- package/store/Dockerfile +24 -0
- package/store/README.md +43 -0
- package/store/SELF-HOSTING.md +200 -0
- package/store/bin/brain-store.js +189 -0
- package/store/conformance/conformance.test.js +341 -0
- package/store/conformance/helpers.js +145 -0
- package/store/deploy/Caddyfile +14 -0
- package/store/deploy/connector.Dockerfile +38 -0
- package/store/deploy/docker-compose.yml +83 -0
- package/store/deploy/env.example +19 -0
- package/store/lib/auth.js +174 -0
- package/store/lib/oidc.js +206 -0
- package/store/lib/storage.js +333 -0
- package/store/lib/tar.js +150 -0
- package/store/openapi.yaml +318 -0
- package/store/server.js +465 -0
- package/store/test/mock-issuer.js +104 -0
- package/store/test/oidc.test.js +217 -0
- package/store/test/store.test.js +445 -0
package/bin/memorize.js
CHANGED
|
@@ -38,6 +38,8 @@ const {
|
|
|
38
38
|
const { addDocument, createSearchIndex, readSearchIndex, writeSearchIndex } = require('../src/tfidf');
|
|
39
39
|
const { appendAudit } = require('../src/audit');
|
|
40
40
|
const { lintMemoryContent } = require('../src/content-lint');
|
|
41
|
+
const { contentHash } = require('../src/integrity');
|
|
42
|
+
const { proposeSupersessions } = require('../src/contradiction');
|
|
41
43
|
const { quarantineDecision } = require('../src/quarantine');
|
|
42
44
|
const {
|
|
43
45
|
validateValidity,
|
|
@@ -88,6 +90,7 @@ const COGNITIVE_ADJUSTMENTS = {
|
|
|
88
90
|
// that holds regardless of caller honesty: entrenchment is simply not
|
|
89
91
|
// reachable from this path without an explicit user origin.
|
|
90
92
|
const { ORIGIN_POLICY, DEFAULT_ORIGIN } = require('../src/provenance');
|
|
93
|
+
const { sensitivityDecision, SENSITIVE_OPT_OUT_REASON } = require('../src/sensitivity');
|
|
91
94
|
|
|
92
95
|
// --- Args ---
|
|
93
96
|
|
|
@@ -222,6 +225,8 @@ function buildMemoryFileContent(mem, id, now, origin, originDecayMultiplier, qua
|
|
|
222
225
|
// (when it was recorded). Emitted only when the author bounded it.
|
|
223
226
|
if (mem.valid_from) fmLines.push(`valid_from: "${mem.valid_from}"`);
|
|
224
227
|
if (mem.valid_until) fmLines.push(`valid_until: "${mem.valid_until}"`);
|
|
228
|
+
// Consent tier (src/sensitivity.js) — only non-standard levels are written.
|
|
229
|
+
if (mem.sensitivity && mem.sensitivity !== 'standard') fmLines.push(`sensitivity: "${mem.sensitivity}"`);
|
|
225
230
|
fmLines.push(
|
|
226
231
|
`tags: [${(mem.tags || []).map(t => `"${t}"`).join(', ')}]`,
|
|
227
232
|
`related: [${(mem.related || []).map(r => `"${r}"`).join(', ')}]`,
|
|
@@ -277,6 +282,7 @@ function buildIndexEntry(mem, id, strength, decayRate, now, origin, quarantine)
|
|
|
277
282
|
if (mem.supersedes && mem.supersedes.length) entry.supersedes = mem.supersedes;
|
|
278
283
|
if (mem.valid_from) entry.valid_from = mem.valid_from;
|
|
279
284
|
if (mem.valid_until) entry.valid_until = mem.valid_until;
|
|
285
|
+
if (mem.sensitivity && mem.sensitivity !== 'standard') entry.sensitivity = mem.sensitivity;
|
|
280
286
|
return entry;
|
|
281
287
|
}
|
|
282
288
|
|
|
@@ -486,6 +492,31 @@ async function main() {
|
|
|
486
492
|
const lint = lintMemoryContent(mem);
|
|
487
493
|
const quarantine = quarantineDecision({ origin, lintResult: lint, config });
|
|
488
494
|
|
|
495
|
+
// Sensitive-topic consent (src/sensitivity.js). `blocked` content is
|
|
496
|
+
// refused outright; `sensitive` content is stored only after the user
|
|
497
|
+
// opted in — otherwise it lands quarantined and hidden, and approving it
|
|
498
|
+
// is the per-item consent. Evaluated after the origin gate so a refusal
|
|
499
|
+
// names the real reason, and before anything reaches disk.
|
|
500
|
+
const sensitivity = sensitivityDecision(mem, config);
|
|
501
|
+
if (sensitivity.error) {
|
|
502
|
+
console.error(JSON.stringify({ error: `${sensitivity.error} — memory: ${JSON.stringify(rawMem.title)}` }));
|
|
503
|
+
process.exit(1);
|
|
504
|
+
}
|
|
505
|
+
if (sensitivity.action === 'refuse') {
|
|
506
|
+
console.error(JSON.stringify({
|
|
507
|
+
error: `Refused: content classified "blocked" (${sensitivity.categories.join(', ') || 'declared by caller'}) — ` +
|
|
508
|
+
`identification numbers, criminal history and immigration status are never stored — memory: ${JSON.stringify(rawMem.title)}`,
|
|
509
|
+
sensitivity: 'blocked',
|
|
510
|
+
categories: sensitivity.categories,
|
|
511
|
+
}));
|
|
512
|
+
process.exit(1);
|
|
513
|
+
}
|
|
514
|
+
if (sensitivity.action === 'quarantine') {
|
|
515
|
+
quarantine.quarantined = true;
|
|
516
|
+
quarantine.reasons = [...quarantine.reasons, SENSITIVE_OPT_OUT_REASON];
|
|
517
|
+
}
|
|
518
|
+
mem.sensitivity = sensitivity.level;
|
|
519
|
+
|
|
489
520
|
// Generate ID
|
|
490
521
|
const id = generateId();
|
|
491
522
|
newIds.push(id);
|
|
@@ -523,6 +554,7 @@ async function main() {
|
|
|
523
554
|
clamped: policy.clamps.map((c) => c.field),
|
|
524
555
|
...(lint.flags.length ? { lint: lint.flags.map((f) => f.rule) } : {}),
|
|
525
556
|
...(quarantine.quarantined ? { quarantined: true, quarantine_reasons: quarantine.reasons } : {}),
|
|
557
|
+
...(mem.sensitivity !== 'standard' ? { sensitivity: mem.sensitivity, sensitivity_categories: sensitivity.categories } : {}),
|
|
526
558
|
});
|
|
527
559
|
} catch (err) {
|
|
528
560
|
auditErrors.push({ id, error: err.message });
|
|
@@ -530,6 +562,12 @@ async function main() {
|
|
|
530
562
|
|
|
531
563
|
// Update index
|
|
532
564
|
const indexEntry = buildIndexEntry(mem, id, strength, decay_rate, now, origin, quarantine);
|
|
565
|
+
// Integrity baseline (OWASP ASI06, Store phase): record what this memory
|
|
566
|
+
// said the moment the brain agreed with it, hashed from the exact bytes
|
|
567
|
+
// just written. `brain audit` compares against this to catch edits that
|
|
568
|
+
// never came through a write path — the one poisoning route every other
|
|
569
|
+
// defense here is blind to. See src/integrity.js.
|
|
570
|
+
indexEntry.content_hash = contentHash(fileContent);
|
|
533
571
|
addMemory(index, id, indexEntry);
|
|
534
572
|
|
|
535
573
|
// CoALA Phase 1: register a born-pinned memory in the pinned manifest
|
|
@@ -579,14 +617,17 @@ async function main() {
|
|
|
579
617
|
reinforceEdge(associations, id, overlapId, 'tag_overlap', 0.10);
|
|
580
618
|
}
|
|
581
619
|
|
|
582
|
-
// Tier B §10.2: surface potential contradictions
|
|
583
|
-
//
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
620
|
+
// Tier B §10.2: surface potential contradictions so the agent can
|
|
621
|
+
// adjudicate — never auto-resolved here. Each proposal carries the
|
|
622
|
+
// `valid_until` a supersede would stamp, so the agent can offer the
|
|
623
|
+
// boundary ("shall I mark the old one as ended on <date>?") instead of
|
|
624
|
+
// leaving two unbounded facts competing in every future recall.
|
|
625
|
+
const potentialConflicts = proposeSupersessions(
|
|
626
|
+
index,
|
|
627
|
+
{ ...mem, created: now },
|
|
628
|
+
tagOverlaps,
|
|
629
|
+
{ now },
|
|
630
|
+
);
|
|
590
631
|
|
|
591
632
|
// Update search index
|
|
592
633
|
addDocument(searchIndex, id, {
|
|
@@ -620,6 +661,10 @@ async function main() {
|
|
|
620
661
|
? { quarantine_pending: true, quarantine_reasons: quarantine.reasons }
|
|
621
662
|
: {}),
|
|
622
663
|
...(lint.flags.length ? { lint_flags: lint.flags.map((f) => f.rule) } : {}),
|
|
664
|
+
// Consent tier. `sensitive_opt_out` means the memory is stored but hidden
|
|
665
|
+
// until the user opts in (config) or approves it (`brain verify approve`).
|
|
666
|
+
...(mem.sensitivity !== 'standard' ? { sensitivity: mem.sensitivity } : {}),
|
|
667
|
+
...(sensitivity.action === 'quarantine' ? { sensitive_opt_out: true } : {}),
|
|
623
668
|
...(supersededNow.length ? { superseded: supersededNow } : {}),
|
|
624
669
|
// Held back until verification — surfaced so the agent can tell the user
|
|
625
670
|
// the replacement it asked for has not taken effect yet.
|
package/bin/recall.js
CHANGED
|
@@ -47,6 +47,7 @@ const {
|
|
|
47
47
|
const { receiptFor } = require('../src/receipt');
|
|
48
48
|
const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
|
|
49
49
|
const { parseInstant } = require('../src/temporal');
|
|
50
|
+
const { isSensitiveHidden } = require('../src/sensitivity');
|
|
50
51
|
|
|
51
52
|
// Minimum relevance (or spreading bonus) for a memory to appear in explicit-
|
|
52
53
|
// query results. Filters the zero/near-zero-relevance memories that would
|
|
@@ -85,19 +86,32 @@ function main() {
|
|
|
85
86
|
process.exit(1);
|
|
86
87
|
}
|
|
87
88
|
|
|
88
|
-
let
|
|
89
|
+
let results;
|
|
89
90
|
try {
|
|
90
|
-
|
|
91
|
+
results = computeRecall(args);
|
|
91
92
|
} catch (err) {
|
|
92
93
|
console.error(JSON.stringify({
|
|
93
94
|
error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
|
|
94
95
|
}));
|
|
95
96
|
process.exit(1);
|
|
96
97
|
}
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
98
|
+
|
|
99
|
+
console.log(JSON.stringify(results, null, 2));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Rank memories for a query — the engine behind `brain recall`, callable
|
|
104
|
+
* in-process (plugin hooks, tests) with byte-identical scoring to the CLI.
|
|
105
|
+
* Throws when index.json is corrupt; returns [] for an empty brain.
|
|
106
|
+
*
|
|
107
|
+
* @param {Object} args - { query, project, task, topics, top, context, asOf, asKnownOf }
|
|
108
|
+
* @param {string} [projectRoot] - Filesystem root whose .brain/ to read
|
|
109
|
+
* @returns {Object[]} scored results, best first
|
|
110
|
+
*/
|
|
111
|
+
function computeRecall(args, projectRoot) {
|
|
112
|
+
const brainDir = getBrainDir(projectRoot);
|
|
113
|
+
const index = readIndex(projectRoot);
|
|
114
|
+
if (!index || !index.memories || Object.keys(index.memories).length === 0) return [];
|
|
101
115
|
|
|
102
116
|
// Ensure search index exists
|
|
103
117
|
let searchIndex;
|
|
@@ -129,9 +143,13 @@ function main() {
|
|
|
129
143
|
// verification) memories are excluded here — before ranking — which also
|
|
130
144
|
// removes them as spreading-activation sources. readConfig tolerates a
|
|
131
145
|
// missing/corrupt config.json (falls back to the 'flag' default).
|
|
132
|
-
const
|
|
146
|
+
const config = readConfig(projectRoot);
|
|
147
|
+
const quarantineMode = config.quarantine_mode || 'flag';
|
|
148
|
+
// Sensitive-topic memories are hidden until the user opts in (config) or
|
|
149
|
+
// approves them individually — consent is evaluated at read time too.
|
|
133
150
|
const memories = Object.entries(index.memories)
|
|
134
151
|
.filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
|
|
152
|
+
.filter(([, entry]) => !isSensitiveHidden(entry, config))
|
|
135
153
|
.map(([id, entry]) => ({
|
|
136
154
|
id,
|
|
137
155
|
...entry,
|
|
@@ -140,7 +158,7 @@ function main() {
|
|
|
140
158
|
// Load associations for spreading activation
|
|
141
159
|
let associations;
|
|
142
160
|
try {
|
|
143
|
-
associations = readAssociations();
|
|
161
|
+
associations = readAssociations(projectRoot);
|
|
144
162
|
} catch (_) {
|
|
145
163
|
associations = null;
|
|
146
164
|
}
|
|
@@ -149,7 +167,7 @@ function main() {
|
|
|
149
167
|
const recallContext = {};
|
|
150
168
|
if (args.project) recallContext.project = args.project;
|
|
151
169
|
if (args.task) recallContext.task_type = args.task;
|
|
152
|
-
if (args.topics) recallContext.topics = args.topics.split(',');
|
|
170
|
+
if (args.topics) recallContext.topics = String(args.topics).split(',');
|
|
153
171
|
|
|
154
172
|
// Rank using scorer.js with TF-IDF as the relevance function
|
|
155
173
|
const ranked = rankMemories(
|
|
@@ -168,7 +186,7 @@ function main() {
|
|
|
168
186
|
|
|
169
187
|
// Return top N
|
|
170
188
|
const top = args.top || 10;
|
|
171
|
-
|
|
189
|
+
return ranked.slice(0, top).map((mem) => {
|
|
172
190
|
const title = mem.title || path.basename(mem.path, '.md');
|
|
173
191
|
const origin = mem.origin || DEFAULT_ORIGIN;
|
|
174
192
|
return {
|
|
@@ -199,14 +217,13 @@ function main() {
|
|
|
199
217
|
...(mem.valid_from ? { valid_from: mem.valid_from } : {}),
|
|
200
218
|
...(mem.valid_until ? { valid_until: mem.valid_until } : {}),
|
|
201
219
|
...(mem.temporal_state === 'expired' ? { expired: true } : {}),
|
|
220
|
+
...(mem.sensitivity && mem.sensitivity !== 'standard' ? { sensitivity: mem.sensitivity } : {}),
|
|
202
221
|
tags: mem.tags,
|
|
203
222
|
// Recall receipt — the engine mints it, agents copy it verbatim when
|
|
204
223
|
// this memory materially shapes an answer (so it can't be hallucinated).
|
|
205
224
|
receipt: receiptFor({ ...mem, title }),
|
|
206
225
|
};
|
|
207
226
|
});
|
|
208
|
-
|
|
209
|
-
console.log(JSON.stringify(results, null, 2));
|
|
210
227
|
}
|
|
211
228
|
|
|
212
229
|
/**
|
|
@@ -316,4 +333,6 @@ function parseArgs(argv) {
|
|
|
316
333
|
return args;
|
|
317
334
|
}
|
|
318
335
|
|
|
319
|
-
main();
|
|
336
|
+
if (require.main === module) main();
|
|
337
|
+
|
|
338
|
+
module.exports = { main, computeRecall, parseArgs, RELEVANCE_FLOOR };
|
package/bin/reinforce.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* - Spaced reinforcement boost to each memory's strength
|
|
16
16
|
* - Decay rate improvement (more forgetting-resistant)
|
|
17
17
|
* - access_count++, last_accessed = now
|
|
18
|
+
* - recall_history entry (timestamp + interval + strength delta), capped
|
|
18
19
|
* - Hebbian co-retrieval: strengthens association edges between all pairs
|
|
19
20
|
* - Updates index.json, associations.json, and memory files
|
|
20
21
|
*/
|
|
@@ -38,6 +39,10 @@ const {
|
|
|
38
39
|
improveDecayRate,
|
|
39
40
|
} = require('../src/scorer');
|
|
40
41
|
|
|
42
|
+
// Recall-history rows kept per memory. Enough to fit an interval curve;
|
|
43
|
+
// small enough that a hot memory's frontmatter stays cheap to parse.
|
|
44
|
+
const RECALL_HISTORY_MAX = 50;
|
|
45
|
+
|
|
41
46
|
function main() {
|
|
42
47
|
const args = parseArgs(process.argv.slice(2));
|
|
43
48
|
|
|
@@ -86,12 +91,35 @@ function main() {
|
|
|
86
91
|
entry.last_accessed = nowISO;
|
|
87
92
|
entry.access_count = accessCount + 1;
|
|
88
93
|
|
|
94
|
+
// Recall history: one row per reinforcement, capped.
|
|
95
|
+
//
|
|
96
|
+
// `access_count` says a memory was recalled N times; it cannot say *when*,
|
|
97
|
+
// and the interval is the entire signal. Spaced reinforcement is built on
|
|
98
|
+
// the premise that longer gaps produce larger, more durable boosts — but
|
|
99
|
+
// without the timestamps that premise is unfalsifiable, and the decay
|
|
100
|
+
// constants stay hand-set forever because there is nothing to fit them to.
|
|
101
|
+
// This is the series that makes calibration possible (see
|
|
102
|
+
// benchmark/harness/decay-calibration.js).
|
|
103
|
+
//
|
|
104
|
+
// Bounded at RECALL_HISTORY_MAX: a frequently-recalled memory would
|
|
105
|
+
// otherwise grow an unbounded array inside a file that is read on every
|
|
106
|
+
// recall. Oldest rows drop first; the recent intervals carry the signal.
|
|
107
|
+
const history = Array.isArray(entry.recall_history) ? entry.recall_history : [];
|
|
108
|
+
history.push({
|
|
109
|
+
at: nowISO,
|
|
110
|
+
days_since_last: Math.round(daysSince * 100) / 100,
|
|
111
|
+
strength_before: oldStrength,
|
|
112
|
+
strength_after: entry.strength,
|
|
113
|
+
});
|
|
114
|
+
entry.recall_history = history.slice(-RECALL_HISTORY_MAX);
|
|
115
|
+
|
|
89
116
|
// Update the memory file's frontmatter on disk
|
|
90
117
|
updateMemoryFile(brainDir, entry.path, {
|
|
91
118
|
strength: entry.strength,
|
|
92
119
|
decay_rate: entry.decay_rate,
|
|
93
120
|
last_accessed: nowISO,
|
|
94
121
|
access_count: entry.access_count,
|
|
122
|
+
recall_history: entry.recall_history,
|
|
95
123
|
});
|
|
96
124
|
|
|
97
125
|
reinforced.push({
|
|
@@ -157,7 +185,12 @@ function updateMemoryFile(brainDir, memPath, updates) {
|
|
|
157
185
|
// Update each field in the YAML
|
|
158
186
|
for (const [key, value] of Object.entries(updates)) {
|
|
159
187
|
const regex = new RegExp(`^(${key}:\\s*).*$`, 'm');
|
|
160
|
-
|
|
188
|
+
// Arrays and objects must be JSON-encoded: `String(value)` renders an
|
|
189
|
+
// array of objects as "[object Object]", which is both lossy and invalid
|
|
190
|
+
// YAML. JSON is a YAML subset, so a flow-style array round-trips cleanly.
|
|
191
|
+
const formatted = typeof value === 'string'
|
|
192
|
+
? `"${value}"`
|
|
193
|
+
: (value !== null && typeof value === 'object' ? JSON.stringify(value) : String(value));
|
|
161
194
|
if (regex.test(frontmatter)) {
|
|
162
195
|
frontmatter = frontmatter.replace(regex, `$1${formatted}`);
|
|
163
196
|
}
|
package/bin/session-start.js
CHANGED
|
@@ -8,7 +8,11 @@
|
|
|
8
8
|
* Brain can never bloat the host's context window.
|
|
9
9
|
*
|
|
10
10
|
* Usage:
|
|
11
|
-
* brain session-start [--project P] [--topics a,b] [--task T] [--top N]
|
|
11
|
+
* brain session-start [--project P] [--topics a,b] [--task T] [--top N] [--budget TOKENS]
|
|
12
|
+
*
|
|
13
|
+
* --budget lowers the working-memory cap for this call only (never raises it):
|
|
14
|
+
* hosts with a smaller injection window than config.json assumes — Codex caps
|
|
15
|
+
* hook context at ~2,500 tokens — pass the room they actually have.
|
|
12
16
|
*
|
|
13
17
|
* Output (JSON):
|
|
14
18
|
* {
|
|
@@ -45,15 +49,17 @@ const { advertisedSummaries } = require('../src/skills');
|
|
|
45
49
|
const { receiptFor } = require('../src/receipt');
|
|
46
50
|
const { temporalState } = require('../src/temporal');
|
|
47
51
|
const { DEFAULT_ORIGIN, isLowTrust } = require('../src/provenance');
|
|
52
|
+
const { isSensitiveHidden } = require('../src/sensitivity');
|
|
48
53
|
|
|
49
54
|
function parseArgs(argv) {
|
|
50
|
-
const args = { project: null, topics: null, task: null, top: 5 };
|
|
55
|
+
const args = { project: null, topics: null, task: null, top: 5, budget: null };
|
|
51
56
|
for (let i = 0; i < argv.length; i++) {
|
|
52
57
|
switch (argv[i]) {
|
|
53
58
|
case '--project': args.project = argv[++i]; break;
|
|
54
59
|
case '--topics': args.topics = argv[++i]; break;
|
|
55
60
|
case '--task': args.task = argv[++i]; break;
|
|
56
61
|
case '--top': args.top = parseInt(argv[++i], 10) || 5; break;
|
|
62
|
+
case '--budget': args.budget = parseInt(argv[++i], 10) || null; break;
|
|
57
63
|
default: break;
|
|
58
64
|
}
|
|
59
65
|
}
|
|
@@ -110,14 +116,17 @@ function buildContextQuery(args) {
|
|
|
110
116
|
* it is directly unit-testable.
|
|
111
117
|
*
|
|
112
118
|
* @param {string} [projectRoot] - Filesystem root whose .brain/ to read
|
|
113
|
-
* @param {Object} [args] - { project, topics, task, top }
|
|
119
|
+
* @param {Object} [args] - { project, topics, task, top, budget }
|
|
114
120
|
* @returns {Object} The session-start payload
|
|
115
121
|
*/
|
|
116
122
|
function computeSessionStart(projectRoot, args = {}) {
|
|
117
123
|
const top = args.top || 5;
|
|
118
124
|
const brainDir = getBrainDir(projectRoot);
|
|
119
125
|
const config = readConfig(projectRoot);
|
|
120
|
-
|
|
126
|
+
// A caller-supplied budget can only tighten the configured cap.
|
|
127
|
+
const cap = args.budget > 0
|
|
128
|
+
? Math.min(config.working_memory_budget_tokens, args.budget)
|
|
129
|
+
: config.working_memory_budget_tokens;
|
|
121
130
|
|
|
122
131
|
const empty = {
|
|
123
132
|
memory_count: 0,
|
|
@@ -160,6 +169,9 @@ function computeSessionStart(projectRoot, args = {}) {
|
|
|
160
169
|
const quarantineMode = config.quarantine_mode || 'flag';
|
|
161
170
|
const memories = Object.entries(index.memories)
|
|
162
171
|
.filter(([, entry]) => quarantineMode !== 'enforce' || !entry.quarantined)
|
|
172
|
+
// Consent: sensitive-topic memories stay out of working memory until the
|
|
173
|
+
// user opts in or approves them one by one.
|
|
174
|
+
.filter(([, entry]) => !isSensitiveHidden(entry, config))
|
|
163
175
|
.map(([id, entry]) => ({ id, ...entry }));
|
|
164
176
|
|
|
165
177
|
let associations = null;
|
|
@@ -190,6 +202,7 @@ function computeSessionStart(projectRoot, args = {}) {
|
|
|
190
202
|
// Defensive: pinning a quarantined memory is refused, but state synced
|
|
191
203
|
// from another device could carry both flags — never load it every session.
|
|
192
204
|
if (entry.quarantined && quarantineMode !== 'off') continue;
|
|
205
|
+
if (isSensitiveHidden(entry, config)) continue;
|
|
193
206
|
// Bitemporal: the pinned tier is presented to the agent as always-apply
|
|
194
207
|
// active constraints, and a fact whose validity window has closed is not a
|
|
195
208
|
// constraint any more. Drop it here rather than asserting it every session
|
package/bin/skill.js
CHANGED
|
@@ -8,6 +8,9 @@
|
|
|
8
8
|
* brain skill show <name> Full SKILL.md (L1 disclosure)
|
|
9
9
|
* brain skill use <name> [--failed] Record a use; success strengthens,
|
|
10
10
|
* --failed weakens (demotion feedback)
|
|
11
|
+
* brain skill verify <name> Check the skill's declared
|
|
12
|
+
* preconditions against the current
|
|
13
|
+
* directory. Read-only, never executes.
|
|
11
14
|
* brain skill remove <name> Delete a skill
|
|
12
15
|
* brain skill add Create a skill from JSON on stdin:
|
|
13
16
|
* { name, description, triggers[], body }
|
|
@@ -15,14 +18,14 @@
|
|
|
15
18
|
|
|
16
19
|
const fs = require('fs');
|
|
17
20
|
const {
|
|
18
|
-
addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill,
|
|
21
|
+
addSkill, listSkills, showSkill, useSkill, removeSkill, exportSkill, verifySkillByName,
|
|
19
22
|
} = require('../src/skills');
|
|
20
23
|
|
|
21
24
|
function emit(obj) { console.log(JSON.stringify(obj, null, 2)); }
|
|
22
25
|
function fail(obj) { console.error(JSON.stringify(obj)); process.exit(1); }
|
|
23
26
|
function done(result) { return result && result.error ? fail(result) : emit(result); }
|
|
24
27
|
|
|
25
|
-
const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|add|remove <name>|export <name> [--target claude|gemini]>';
|
|
28
|
+
const USAGE = 'Usage: brain skill <list|show <name>|use <name> [--failed]|verify <name>|add|remove <name>|export <name> [--target claude|gemini]>';
|
|
26
29
|
|
|
27
30
|
function main(argv) {
|
|
28
31
|
const args = argv || process.argv.slice(2);
|
|
@@ -39,6 +42,9 @@ function main(argv) {
|
|
|
39
42
|
case 'use':
|
|
40
43
|
if (!firstName) return fail({ error: USAGE });
|
|
41
44
|
return done(useSkill(undefined, firstName, { failed: rest.includes('--failed') }));
|
|
45
|
+
case 'verify':
|
|
46
|
+
if (!firstName) return fail({ error: USAGE });
|
|
47
|
+
return done(verifySkillByName(undefined, firstName));
|
|
42
48
|
case 'remove':
|
|
43
49
|
if (!firstName) return fail({ error: USAGE });
|
|
44
50
|
return done(removeSkill(undefined, firstName));
|
package/commands/brain/import.md
CHANGED
|
@@ -10,7 +10,7 @@ A new brain is empty. But your agents have been keeping transcripts for months
|
|
|
10
10
|
**User input:** $ARGUMENTS
|
|
11
11
|
|
|
12
12
|
**Flags** (passed straight through to the CLI):
|
|
13
|
-
- `--source <id>` — Which history store to read (
|
|
13
|
+
- `--source <id>` — Which history store to read (`claude-code` by default, or `codex` for `~/.codex/sessions/`; `--sources` lists what's detected)
|
|
14
14
|
- `--project <name>` — Only sessions from one project
|
|
15
15
|
- `--since <30d|6m|2026-01-01>` — Only sessions since then
|
|
16
16
|
- `--limit <N>` — Max sessions to consider (default 40)
|
|
@@ -56,6 +56,16 @@ For each memory, determine:
|
|
|
56
56
|
|
|
57
57
|
Label honestly by **provenance, not confidence**. A fact you are certain about but read in an email is still `external`. Untrusted origins get capped salience/confidence and faster decay, so a planted fact fades instead of hardening — and the CLI reports any value it had to lower.
|
|
58
58
|
|
|
59
|
+
**Sensitivity** (consent tier — classify every memory; the CLI has a narrow backstop but you read the conversation):
|
|
60
|
+
|
|
61
|
+
| sensitivity | Use when | What the CLI does |
|
|
62
|
+
|---|---|---|
|
|
63
|
+
| `standard` | Everything else. **Default.** | Stores normally. |
|
|
64
|
+
| `sensitive` | Health, race, ethnicity, religious beliefs, politics, gender identity or sexual orientation, and similar personal topics. | Stored **only if** `sensitive_topics: true` in `~/.brain/config.json`; otherwise it lands quarantined (`sensitive_opt_out`) and hidden from recall until the user approves it with `brain verify approve <id>`. Receipts carry `⚠ sensitive`. |
|
|
65
|
+
| `blocked` | Government / national ID numbers, criminal history, immigration status. | **Refused.** Never stored, whatever the toggle says. |
|
|
66
|
+
|
|
67
|
+
Label the topic, not the person's wish to remember it: "user is diabetic" is `sensitive` even when the user asked you to remember it. If the CLI reports `sensitive_opt_out: true`, tell the user plainly that the memory is held until they opt in (`sensitive_topics: true`) or approve it, and never re-store it as `standard` to get around the gate. Opting in is never retroactive.
|
|
68
|
+
|
|
59
69
|
**Pinned & stable** (optional, CoALA Phase 1) — **requires `origin: "user"`; the CLI rejects the write otherwise:**
|
|
60
70
|
- `pinned: true` — always inject this memory at session start regardless of recall score (and decay-exempt). Optionally `pin_scope: "project:<name>"` (default `"global"`) and `pin_priority: <N>`.
|
|
61
71
|
- `stable: true` — exempt from decay (never fades) without forcing it to always load — for timeless facts recalled on demand.
|
|
@@ -116,12 +126,23 @@ If the output contains `quarantine_pending: true`, the memory landed in the pend
|
|
|
116
126
|
|
|
117
127
|
### 5. Resolve contradictions (Tier B §10.2)
|
|
118
128
|
|
|
119
|
-
If a stored memory's result includes `potential_conflicts`,
|
|
120
|
-
|
|
121
|
-
|
|
129
|
+
If a stored memory's result includes `potential_conflicts`, the new write overlaps memories it may have ended. Each proposal carries:
|
|
130
|
+
|
|
131
|
+
| Field | Meaning |
|
|
132
|
+
|---|---|
|
|
133
|
+
| `authority` | `pinned` / `stable` / `same-type` — how much weight the older memory carries |
|
|
134
|
+
| `shared_tags` | Why it was surfaced |
|
|
135
|
+
| `proposed_valid_until` | The exact boundary a supersede would stamp on the older memory |
|
|
136
|
+
|
|
137
|
+
`pinned` and `stable` facts never decay out of contention, so a stale one is dangerous. `same-type` means a like-for-like memory (a `decision` that may have replaced a `decision`) — the ordinary "we changed our minds" case, which is precisely the one users never think to flag.
|
|
138
|
+
|
|
139
|
+
**Do not silently keep both.** Inspect the conflicting memory (`brain recall` or read its file) and, if the new memory genuinely contradicts it, propose a resolution — quoting `proposed_valid_until` so the user sees the concrete boundary:
|
|
140
|
+
|
|
141
|
+
- **Supersede** — store the new fact with `"supersedes": ["<old_id>"]`, which stamps the older memory's `valid_until` (see below). Say it plainly: *"Shall I mark 'Deploy to Fly.io' as true until 2026-08-21?"*
|
|
142
|
+
- **Keep both, scoped** — e.g. pin each to its own project. Right when the two facts coexist rather than replace ("Postgres for analytics" vs "Postgres for sessions").
|
|
122
143
|
- **Reject the new one** — the old fact stands.
|
|
123
144
|
|
|
124
|
-
Never auto-resolve
|
|
145
|
+
Never auto-resolve. Tag overlap is a *relatedness* signal, not a contradiction signal — only the conversation can tell whether B actually ended A, so surface the proposal and let the user decide.
|
|
125
146
|
|
|
126
147
|
### Superseding an outdated memory (temporal invalidation)
|
|
127
148
|
|
package/commands/brain/skills.md
CHANGED
|
@@ -58,3 +58,32 @@ brain skill export <name> [--target claude|gemini]
|
|
|
58
58
|
- Advertise skills with a **crisp, matchable description** — that single line is all the agent sees at L0, so it must convey when to reach for the skill.
|
|
59
59
|
- Reach for `show` only when a task genuinely matches; don't pre-load skills speculatively.
|
|
60
60
|
- Always record the outcome with `use` (success or `--failed`) so the strength/demotion feedback loop stays accurate.
|
|
61
|
+
|
|
62
|
+
### Verifying a skill (`brain skill verify <name>`)
|
|
63
|
+
|
|
64
|
+
A skill is a claim about how a repo works, and repos move. `brain skill verify <name>` checks the skill's declared preconditions against the current directory and answers whether the claim still holds — **without running the agent**:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
brain skill verify pg-migration
|
|
68
|
+
# → { "status": "passed", "passed": 2, "total": 2 }
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
Skills declare preconditions as a `verify` array when they are added:
|
|
72
|
+
|
|
73
|
+
```json
|
|
74
|
+
{ "name": "pg-migration", "description": "...", "body": "...",
|
|
75
|
+
"verify": [
|
|
76
|
+
{ "file_exists": "migrations/" },
|
|
77
|
+
{ "file_contains": { "path": "package.json", "text": "\"migrate\"" } },
|
|
78
|
+
{ "command_available": "psql" }
|
|
79
|
+
] }
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Available checks: `file_exists`, `file_absent`, `file_contains`, `command_available`, `env_set`.
|
|
83
|
+
|
|
84
|
+
**Checks are declarative and read-only — nothing is ever executed.** Skills are crystallized automatically, they sync between machines, and they can be imported from other people; a `verify` field holding arbitrary shell would be a memory file that runs code, which is the OWASP ASI06 scenario with the hard part removed. There is deliberately no escape hatch. Paths that escape the working directory fail the check.
|
|
85
|
+
|
|
86
|
+
Outcomes:
|
|
87
|
+
- `passed` — preconditions hold. Strength is **not** raised: applicability is not the same as a good outcome, and a cheap automatic check should not let a skill climb the index.
|
|
88
|
+
- `failed` — demotes exactly like a failed use (`-0.10`), because a skill describing a layout that no longer exists will confidently misdirect the next matching session.
|
|
89
|
+
- `unverifiable` — no `verify` block. Most skills are prose; this is normal and changes nothing.
|
package/commands/brain/sync.md
CHANGED
|
@@ -46,6 +46,7 @@ Parse the user's input to determine the subcommand:
|
|
|
46
46
|
|
|
47
47
|
**Cloud Sync (Brain Cloud API):**
|
|
48
48
|
- `cloud login [--api-url URL]` → Authenticate via device code flow
|
|
49
|
+
- `cloud login --api-url URL --token-stdin` → Authenticate to a self-hosted `brain-store` with a token
|
|
49
50
|
- `cloud push` → Upload ~/.brain/ to Brain Cloud
|
|
50
51
|
- `cloud pull` → Download from Brain Cloud to ~/.brain/
|
|
51
52
|
- `cloud status` → Show cloud connection info
|
|
@@ -66,6 +67,20 @@ If no subcommand is given, show available subcommands.
|
|
|
66
67
|
|
|
67
68
|
## `/brain:sync cloud login [--api-url URL]`
|
|
68
69
|
|
|
70
|
+
### Self-hosted store
|
|
71
|
+
|
|
72
|
+
If the user names their own store (an `--api-url` that is not Brain Cloud) and has a
|
|
73
|
+
token from its operator, the login is a token login, not the device code flow:
|
|
74
|
+
|
|
75
|
+
```
|
|
76
|
+
pbpaste | brain cloud login --api-url <store URL> --token-stdin
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
**Never ask the user to paste the token into the conversation, and never echo it.**
|
|
80
|
+
Have them copy it to the clipboard and run the command above themselves (`! <command>`),
|
|
81
|
+
or set `BRAIN_STORE_TOKEN` in their own shell. The CLI refuses plain HTTP to a remote
|
|
82
|
+
host; do not add `--allow-http` unless the user says the network is trusted.
|
|
83
|
+
|
|
69
84
|
### Steps
|
|
70
85
|
|
|
71
86
|
1. **Check if already logged in:**
|
|
@@ -126,6 +141,14 @@ Then return — do not attempt the push.
|
|
|
126
141
|
Checksum: <checksum>
|
|
127
142
|
```
|
|
128
143
|
|
|
144
|
+
3. **If the push is refused because the store has changes that were not pulled**
|
|
145
|
+
(`The store has changes you have not pulled`): nothing was uploaded and nothing
|
|
146
|
+
was lost. Tell the user another device pushed first, then run `brain cloud pull`
|
|
147
|
+
followed by `brain cloud push`. Only use `brain cloud push --force` when the user
|
|
148
|
+
explicitly asks to overwrite what the store holds; it discards the other
|
|
149
|
+
device's changes (the store keeps a snapshot, so it can be undone with
|
|
150
|
+
`brain restore --from cloud`).
|
|
151
|
+
|
|
129
152
|
---
|
|
130
153
|
|
|
131
154
|
## `/brain:sync cloud pull`
|
package/hooks/hooks.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"hooks": {
|
|
3
|
+
"SessionStart": [
|
|
4
|
+
{
|
|
5
|
+
"hooks": [
|
|
6
|
+
{
|
|
7
|
+
"type": "command",
|
|
8
|
+
"command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start.mjs\"",
|
|
9
|
+
"timeout": 20,
|
|
10
|
+
"statusMessage": "Loading brain memory context"
|
|
11
|
+
}
|
|
12
|
+
]
|
|
13
|
+
}
|
|
14
|
+
],
|
|
15
|
+
"UserPromptSubmit": [
|
|
16
|
+
{
|
|
17
|
+
"hooks": [
|
|
18
|
+
{
|
|
19
|
+
"type": "command",
|
|
20
|
+
"command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/prompt-recall.mjs\"",
|
|
21
|
+
"timeout": 10,
|
|
22
|
+
"statusMessage": "Recalling brain memories"
|
|
23
|
+
}
|
|
24
|
+
]
|
|
25
|
+
}
|
|
26
|
+
],
|
|
27
|
+
"SessionEnd": [
|
|
28
|
+
{
|
|
29
|
+
"hooks": [
|
|
30
|
+
{
|
|
31
|
+
"type": "command",
|
|
32
|
+
"command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-end.mjs\"",
|
|
33
|
+
"timeout": 3
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
]
|
|
38
|
+
}
|
|
39
|
+
}
|