brain-memory 0.5.2 → 0.6.2
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 +86 -0
- package/README.md +8 -2
- package/bin/brain.js +3 -0
- package/bin/forget.js +15 -1
- package/bin/memorize.js +113 -2
- package/bin/reinforce.js +15 -165
- package/bin/session-start.js +101 -1
- package/bin/supersede.js +121 -0
- package/commands/brain/memorize.md +4 -0
- package/commands/brain/sleep.md +32 -0
- package/hooks/citation-check.mjs +23 -3
- package/hooks/session-end.md +1 -1
- package/hooks/session-end.mjs +3 -1
- package/hooks/session-start.mjs +13 -1
- package/integrations/agentskills/brain-memory/SKILL.md +4 -3
- package/package.json +2 -2
- package/prompts/antigravity.md +3 -1
- package/prompts/claude.md +3 -1
- package/prompts/copilot.md +3 -1
- package/prompts/kilo.md +3 -1
- package/prompts/openai.md +3 -1
- package/prompts/opencode.md +3 -1
- package/src/index-manager.js +48 -1
- package/src/reinforce.js +144 -0
- package/src/surfaced.js +32 -0
package/bin/supersede.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* brain supersede — bound an existing memory by an existing successor.
|
|
5
|
+
*
|
|
6
|
+
* Usage:
|
|
7
|
+
* brain supersede <old_id> [<old_id>...] --by <new_id> [--valid-until ISO] [--dry-run]
|
|
8
|
+
*
|
|
9
|
+
* `memorize --supersedes` only works at write time, so a contradiction noticed
|
|
10
|
+
* later — during sleep, during recall, or in an audit — had no way to be
|
|
11
|
+
* resolved short of writing a duplicate of the newer fact. This links two
|
|
12
|
+
* memories that already exist: the old one gets `superseded_by` and a
|
|
13
|
+
* `valid_until` (default: the successor's valid_from / created), the successor
|
|
14
|
+
* records `supersedes`, and a manual association edge joins them. Nothing is
|
|
15
|
+
* deleted — recall demotes the old fact and still answers "that was true until
|
|
16
|
+
* <date>".
|
|
17
|
+
*
|
|
18
|
+
* Deciding that B ended A is a judgement call, so this is an explicit command
|
|
19
|
+
* the agent runs after confirming with the user (or during a user-approved
|
|
20
|
+
* sleep pass) — never something recall does on its own.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const {
|
|
24
|
+
readIndex,
|
|
25
|
+
writeIndex,
|
|
26
|
+
readAssociations,
|
|
27
|
+
writeAssociations,
|
|
28
|
+
reinforceEdge,
|
|
29
|
+
getBrainDir,
|
|
30
|
+
} = require('../src/index-manager');
|
|
31
|
+
const { applySupersession, supersessionInstant, parseInstant } = require('../src/temporal');
|
|
32
|
+
const { setFrontmatterFields } = require('../src/pinning');
|
|
33
|
+
const { appendAudit } = require('../src/audit');
|
|
34
|
+
|
|
35
|
+
function parseArgs(argv) {
|
|
36
|
+
const args = { olds: [], by: null, validUntil: undefined, dryRun: false };
|
|
37
|
+
for (let i = 0; i < argv.length; i++) {
|
|
38
|
+
const a = argv[i];
|
|
39
|
+
if (a === '--by') args.by = argv[++i];
|
|
40
|
+
else if (a === '--valid-until') args.validUntil = argv[++i];
|
|
41
|
+
else if (a === '--dry-run') args.dryRun = true;
|
|
42
|
+
else if (!a.startsWith('--')) args.olds.push(a);
|
|
43
|
+
}
|
|
44
|
+
return args;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function fail(msg) {
|
|
48
|
+
console.error(JSON.stringify({ error: msg }));
|
|
49
|
+
process.exit(1);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function main() {
|
|
53
|
+
const args = parseArgs(process.argv.slice(2));
|
|
54
|
+
if (!args.by || !args.olds.length) {
|
|
55
|
+
fail('Usage: brain supersede <old_id> [<old_id>...] --by <new_id> [--valid-until ISO] [--dry-run]');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const brainDir = getBrainDir();
|
|
59
|
+
const index = readIndex();
|
|
60
|
+
if (!index) fail('Brain not initialized.');
|
|
61
|
+
const successor = index.memories[args.by];
|
|
62
|
+
if (!successor) fail(`Unknown successor id: ${args.by}`);
|
|
63
|
+
|
|
64
|
+
let validUntil = supersessionInstant(successor);
|
|
65
|
+
if (args.validUntil !== undefined) {
|
|
66
|
+
const t = parseInstant(args.validUntil);
|
|
67
|
+
if (t == null) fail(`Invalid --valid-until: ${args.validUntil}`);
|
|
68
|
+
validUntil = new Date(t).toISOString();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const skipped = [];
|
|
72
|
+
const targets = [];
|
|
73
|
+
for (const id of new Set(args.olds)) {
|
|
74
|
+
const entry = index.memories[id];
|
|
75
|
+
if (!entry) skipped.push({ id, reason: 'unknown id' });
|
|
76
|
+
else if (id === args.by) skipped.push({ id, reason: 'cannot supersede itself' });
|
|
77
|
+
else if (successor.superseded_by === id) skipped.push({ id, reason: 'would form a cycle' });
|
|
78
|
+
else targets.push(id);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (args.dryRun) {
|
|
82
|
+
console.log(JSON.stringify({
|
|
83
|
+
dry_run: true,
|
|
84
|
+
successor: { id: args.by, title: successor.title },
|
|
85
|
+
would_supersede: targets.map((id) => ({ id, title: index.memories[id].title, valid_until: index.memories[id].valid_until || validUntil })),
|
|
86
|
+
skipped,
|
|
87
|
+
}, null, 2));
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const applied = applySupersession(brainDir, index, args.by, targets, { validUntil });
|
|
92
|
+
|
|
93
|
+
if (applied.length) {
|
|
94
|
+
const list = [...new Set([...(successor.supersedes || []), ...applied.map((a) => a.id)])];
|
|
95
|
+
successor.supersedes = list;
|
|
96
|
+
setFrontmatterFields(brainDir, successor.path, {
|
|
97
|
+
supersedes: `[${list.map((s) => `"${s}"`).join(', ')}]`,
|
|
98
|
+
}, { raw: ['supersedes'] });
|
|
99
|
+
writeIndex(index);
|
|
100
|
+
|
|
101
|
+
const associations = readAssociations() || { version: 1, edges: {} };
|
|
102
|
+
for (const a of applied) reinforceEdge(associations, args.by, a.id, 'manual', 0.20);
|
|
103
|
+
writeAssociations(associations);
|
|
104
|
+
|
|
105
|
+
appendAudit(brainDir, {
|
|
106
|
+
ts: new Date().toISOString(),
|
|
107
|
+
event: 'supersede',
|
|
108
|
+
id: args.by,
|
|
109
|
+
superseded: applied.map((a) => a.id),
|
|
110
|
+
valid_until: validUntil,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
console.log(JSON.stringify({
|
|
115
|
+
successor: { id: args.by, title: successor.title },
|
|
116
|
+
superseded: applied.map((a) => ({ ...a, valid_until: index.memories[a.id].valid_until })),
|
|
117
|
+
skipped,
|
|
118
|
+
}, null, 2));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
main();
|
|
@@ -150,6 +150,10 @@ If a stored memory's result includes `potential_conflicts`, the new write overla
|
|
|
150
150
|
- **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").
|
|
151
151
|
- **Reject the new one** — the old fact stands.
|
|
152
152
|
|
|
153
|
+
Candidates come from tag overlap **and** from same-project memories whose text is closest to the new one, so a fact restated in different words (and different tags) is still caught.
|
|
154
|
+
|
|
155
|
+
**Already stored both?** When you notice a stale memory after the fact — during recall, or because the new memory was written without `supersedes` — bound the pair directly instead of writing a duplicate: `brain supersede <old_id> --by <new_id> [--valid-until <date>]` (`--dry-run` to preview). Same confirmation rule applies.
|
|
156
|
+
|
|
153
157
|
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.
|
|
154
158
|
|
|
155
159
|
### Superseding an outdated memory (temporal invalidation)
|
package/commands/brain/sleep.md
CHANGED
|
@@ -21,6 +21,7 @@ Sleep performs an integrity sweep plus nine phases, mimicking real neuroscience:
|
|
|
21
21
|
- **4b. Procedural Crystallization** — Distill repeated procedures into reusable skills (CoALA Phase 3)
|
|
22
22
|
5. **Reorganize** — Detect flat clusters and restructure into deeper sub-categories
|
|
23
23
|
6. **Consolidate** — Merge weak related memories into stronger combined knowledge
|
|
24
|
+
- **6b. Supersession Sweep** — Find older facts a newer memory quietly replaced and bound them with `brain supersede`
|
|
24
25
|
7. **Prune** — Archive memories that have decayed beyond recovery, including context-shift obsolescence (Tier B §10.1)
|
|
25
26
|
8. **REM Dreaming** — Discover creative cross-domain associations via analogical reasoning
|
|
26
27
|
9. **Expertise Detection** — Identify dense knowledge areas and generate expertise profiles
|
|
@@ -409,6 +410,33 @@ During deep sleep, the brain merges related experiences into generalized knowled
|
|
|
409
410
|
|
|
410
411
|
---
|
|
411
412
|
|
|
413
|
+
## Phase 6b: Supersession Sweep (Truth Maintenance)
|
|
414
|
+
|
|
415
|
+
Decay retires memories that fade; nothing retires memories that are **still strong but no longer true**. In a long-lived brain this is the main source of contradictions: every migration, rebrand, pricing change, or redesign leaves the old memory asserting the old state. Recall then shows both, and the older one often wins on strength.
|
|
416
|
+
|
|
417
|
+
### Steps
|
|
418
|
+
|
|
419
|
+
1. Group live memories (not `superseded_by`, no `valid_until`) by `encoding_context.project`, then by subject — deploy procedure, domain/URLs, brand/design system, pricing, auth, hosting/infrastructure, "which service is canonical", release process, plus anything where two titles describe the same thing.
|
|
420
|
+
2. Within each group, read the bodies and look for **incompatible current-state claims**: two domains, two deploy commands, two palettes, two prices, "X is live" vs "X was retired". Also flag *goals* whose outcome a later memory records (done or abandoned) and *status notes* ("uncommitted", "not yet deployed", "phase 3 remaining") that a later memory resolved.
|
|
421
|
+
3. For each conflict, the **newer accurate memory is the successor**. If no single memory states the current truth (it is spread across several, or only exists in the conversation), propose writing one with `brain memorize` that passes `supersedes`.
|
|
422
|
+
4. Present the list:
|
|
423
|
+
```
|
|
424
|
+
## Phase 6b: Supersession Sweep
|
|
425
|
+
|
|
426
|
+
<old title> (<date>) → superseded by <new title> (<date>)
|
|
427
|
+
conflict: "<old claim>" vs "<new claim>"
|
|
428
|
+
```
|
|
429
|
+
5. On approval, apply each with the CLI (it stamps `superseded_by` + `valid_until`, records `supersedes` on the successor, links the pair, and logs to audit):
|
|
430
|
+
```bash
|
|
431
|
+
brain supersede <old_id> [<old_id>...] --by <new_id> # boundary = successor's start
|
|
432
|
+
brain supersede <old_id> --by <new_id> --valid-until 2026-06-04 # known cut-over date
|
|
433
|
+
```
|
|
434
|
+
Use `--dry-run` first when unsure. Never hand-edit `superseded_by`.
|
|
435
|
+
|
|
436
|
+
Two facts that **coexist** (Postgres for analytics *and* for sessions; a global default overridden per project) are not a supersession — scope them instead (tags/project), or note the exception in the newer memory.
|
|
437
|
+
|
|
438
|
+
---
|
|
439
|
+
|
|
412
440
|
## Phase 7: Prune (Synaptic Pruning)
|
|
413
441
|
|
|
414
442
|
During sleep, the brain prunes weak synaptic connections to maintain efficiency. Here, we archive memories that have faded beyond usefulness.
|
|
@@ -563,6 +591,7 @@ After all phases complete, present a comprehensive sleep report:
|
|
|
563
591
|
║ Phase 4 — Crystallized: <N> episodic → semantic ║
|
|
564
592
|
║ Phase 5 — Reorganized: <N> memories, <M> new dirs ║
|
|
565
593
|
║ Phase 6 — Consolidated: <N> memories merged into <M> ║
|
|
594
|
+
║ Phase 6b — Superseded: <N> stale facts bounded ║
|
|
566
595
|
║ Phase 7 — Pruned: <N> faded memories archived ║
|
|
567
596
|
║ Phase 8 — REM Dreams: <N> creative insights ║
|
|
568
597
|
║ Phase 9 — Expertise: <N> domains profiled ║
|
|
@@ -601,3 +630,6 @@ After all phases complete, present a comprehensive sleep report:
|
|
|
601
630
|
7. **Idempotent expertise** — if `_expertise.md` already exists, update it rather than creating a duplicate.
|
|
602
631
|
8. **Skip empty phases** — if there's nothing to do in a phase (e.g., no flat clusters to reorganize), briefly note it and move on.
|
|
603
632
|
9. **Salience protection** — never auto-prune memories with salience >= 0.7.
|
|
633
|
+
10. **Edge shape** — `associations.json` edges are a nested map, `edges[<src_id>][<dst_id>] = {weight, co_retrievals, last_activated, origin}`, written in both directions. Never write flat `"a::b"` keys (the reader folds them in, but they are a sign of hand-rolled writes).
|
|
634
|
+
11. **Folder and project hygiene** — in Phase 5, merge synonym folders (e.g. `tools/` vs `tooling/`, `workflow/` vs `workflows/`, `patterns/` vs `engineering/patterns/`) and keep one `encoding_context.project` slug per project (no display names, no aliases).
|
|
635
|
+
12. **Record the run** — as the very last step, write `~/.brain/sleep-log.json` as `{"last_sleep": "<ISO now>", "phases_run": [...]}`. `brain session-start` reads it to decide when to report `sleep_due`; without it, sleep looks overdue forever.
|
package/hooks/citation-check.mjs
CHANGED
|
@@ -8,6 +8,10 @@
|
|
|
8
8
|
* logged as a `citation_violation` audit event and queued so prompt-recall
|
|
9
9
|
* tells the agent on its next turn.
|
|
10
10
|
*
|
|
11
|
+
* It also reinforces the memories whose receipts check out: a verified
|
|
12
|
+
* receipt is the strongest signal that a memory was used, and agents rarely
|
|
13
|
+
* run `brain reinforce` on their own.
|
|
14
|
+
*
|
|
11
15
|
* Advisory, never blocking: the hook prints `{}`, so the reply is delivered
|
|
12
16
|
* unchanged. Blocking a Stop would make the agent keep talking, which is a
|
|
13
17
|
* worse failure than a flagged receipt.
|
|
@@ -77,12 +81,28 @@ export async function handleStop(input, options = {}) {
|
|
|
77
81
|
|
|
78
82
|
const session = sessionOf(record);
|
|
79
83
|
const surfaced = options.surfaced || loadModule("src/surfaced.js");
|
|
80
|
-
const
|
|
84
|
+
const dir = brainDir();
|
|
85
|
+
|
|
86
|
+
// Implicit reinforcement: every verified receipt is a memory that shaped the
|
|
87
|
+
// answer. Best-effort — a failed write must never disturb the reply.
|
|
88
|
+
try {
|
|
89
|
+
const ids = surfaced.citedUnreinforcedIds(dir, { session, text });
|
|
90
|
+
if (ids.length) {
|
|
91
|
+
const { reinforceMemories } = options.reinforce || loadModule("src/reinforce.js");
|
|
92
|
+
const { reinforced } = reinforceMemories(ids, { brainDir: dir });
|
|
93
|
+
const usedIds = reinforced.map((r) => r.id);
|
|
94
|
+
if (usedIds.length) surfaced.recordUsed(dir, { session, ids: usedIds });
|
|
95
|
+
}
|
|
96
|
+
} catch {
|
|
97
|
+
// never block the Stop
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const { unsurfaced } = surfaced.checkCitations(dir, { session, text });
|
|
81
101
|
if (!unsurfaced.length) return {};
|
|
82
102
|
|
|
83
|
-
surfaced.recordViolation(
|
|
103
|
+
surfaced.recordViolation(dir, { session, titles: unsurfaced });
|
|
84
104
|
const { appendAudit } = options.audit || loadModule("src/audit.js");
|
|
85
|
-
appendAudit(
|
|
105
|
+
appendAudit(dir, {
|
|
86
106
|
ts: new Date().toISOString(),
|
|
87
107
|
event: "citation_violation",
|
|
88
108
|
session,
|
package/hooks/session-end.md
CHANGED
|
@@ -26,7 +26,7 @@ When a session is ending (user signals they are done, says bye/thanks, or the co
|
|
|
26
26
|
}
|
|
27
27
|
```
|
|
28
28
|
|
|
29
|
-
Keep only the last
|
|
29
|
+
Keep only the last 100 session entries in `contexts.json` to prevent unbounded growth. The `notable_unsaved` field preserves what happened even if the user didn't memorize — future sessions can reference it.
|
|
30
30
|
|
|
31
31
|
**Do not wait for explicit session-end signals** — if the conversation appears to be wrapping up, save context proactively.
|
|
32
32
|
|
package/hooks/session-end.mjs
CHANGED
|
@@ -14,7 +14,9 @@
|
|
|
14
14
|
|
|
15
15
|
import { hasBrain, isMain, loadModule, projectFromInput, runHook } from "./lib.mjs";
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
// 100, not 20: at a few sessions a day, 20 entries was about three days of
|
|
18
|
+
// history, and `notable_unsaved` rotated out before anyone read it back.
|
|
19
|
+
export const MAX_CONTEXT_ENTRIES = 100;
|
|
18
20
|
|
|
19
21
|
/** Build the entry in the shape the prompt-based session-end contract uses. */
|
|
20
22
|
export function buildContextEntry(input, now = new Date()) {
|
package/hooks/session-start.mjs
CHANGED
|
@@ -43,6 +43,14 @@ export function buildContext(payload, { project, host }) {
|
|
|
43
43
|
if (Array.isArray(payload.low_confidence_alerts) && payload.low_confidence_alerts.length > 0) {
|
|
44
44
|
extras.push(`⚠️ ${payload.low_confidence_alerts.length} low-confidence memories used frequently`);
|
|
45
45
|
}
|
|
46
|
+
if (payload.unsaved_notables && payload.unsaved_notables.count > 0) {
|
|
47
|
+
extras.push(`📝 ${payload.unsaved_notables.count} notable items from recent sessions never memorized — /brain:memorize`);
|
|
48
|
+
}
|
|
49
|
+
if (payload.sleep_due && payload.sleep_due.due) {
|
|
50
|
+
const sd = payload.sleep_due;
|
|
51
|
+
const age = sd.days_since_last == null ? "never run" : `${sd.days_since_last}d ago`;
|
|
52
|
+
extras.push(`💤 sleep due (last ${age}, ${sd.memorized_since} new memories) — /brain:sleep`);
|
|
53
|
+
}
|
|
46
54
|
const statusLine = `◉ Brain active — ${count} memories (${recall} in project context)`;
|
|
47
55
|
|
|
48
56
|
return [
|
|
@@ -60,7 +68,11 @@ export function buildContext(payload, { project, host }) {
|
|
|
60
68
|
"- Every ~10 substantive interactions, if notable decisions or learnings accumulated, append one line " +
|
|
61
69
|
"`◉ Notable <types> this session — /brain:memorize when ready` to a reply. Do not memorize without consent.",
|
|
62
70
|
"- When the session is wrapping up, save a summary entry to `~/.brain/contexts.json` (topics, task type, " +
|
|
63
|
-
"memories created/recalled, notable unsaved items; keep the last
|
|
71
|
+
"memories created/recalled, notable unsaved items; keep the last 100) and suggest memorizing if warranted.",
|
|
72
|
+
"- `unsaved_notables` are items earlier sessions flagged but never stored; when relevant, offer to memorize them " +
|
|
73
|
+
"(with consent). `sleep_due` means maintenance is overdue; mention it once, never run sleep unasked.",
|
|
74
|
+
"- Receipts reinforce automatically: a verified receipt in your final reply strengthens that memory, so cite " +
|
|
75
|
+
"honestly and you need not run `brain reinforce` yourself.",
|
|
64
76
|
`- ${COMMANDS[host] || COMMANDS.unknown}`,
|
|
65
77
|
"```json",
|
|
66
78
|
JSON.stringify(payload),
|
|
@@ -118,7 +118,8 @@ brain audit --window 7d # scan for poisoning patterns (bursts, cliques
|
|
|
118
118
|
## Guidelines
|
|
119
119
|
|
|
120
120
|
- Never store secrets, credentials, or trivia.
|
|
121
|
-
- If `brain memorize` reports `potential_conflicts
|
|
122
|
-
|
|
121
|
+
- If `brain memorize` reports `potential_conflicts`, check whether the new
|
|
122
|
+
fact replaced the older one and let the user decide. Bound a stale pair
|
|
123
|
+
noticed later with `brain supersede <old_id> --by <new_id>`.
|
|
123
124
|
- On session boundaries, append a summary to `~/.brain/contexts.json` (keep the
|
|
124
|
-
last
|
|
125
|
+
last 100) so future sessions get context-dependent recall.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "brain-memory",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.2",
|
|
4
4
|
"description": "A brain-inspired hierarchical memory system for AI coding agents. Deep nested file structure that mimics human memory with time-decay and strength-based recall.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude-code",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"url": "git+https://github.com/omelas-tech/brain.git"
|
|
49
49
|
},
|
|
50
50
|
"scripts": {
|
|
51
|
-
"test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/receipt.test.js test/recall.test.js test/recall-cli.test.js test/forget.test.js test/functional.test.js test/erasure.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/restore.test.js test/trust-recall.test.js test/cloud-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js test/session-start.test.js test/memorize.test.js test/pinning.test.js test/skills.test.js test/contradiction.test.js test/harvest.test.js test/content-lint.test.js test/audit-log.test.js test/quarantine.test.js test/anomaly.test.js test/path-hardening.test.js test/supersede.test.js test/bitemporal.test.js test/integrity.test.js test/skill-verify.test.js test/decay-calibration.test.js test/recall-history.test.js test/plugin-manifests.test.js test/plugin-hooks.test.js test/surfaced.test.js test/adapters.test.js test/sensitivity.test.js test/cloud-store.test.js store/test/store.test.js store/test/oidc.test.js store/conformance/conformance.test.js",
|
|
51
|
+
"test": "node --test test/index-manager.test.js test/scorer.test.js test/tfidf.test.js test/receipt.test.js test/recall.test.js test/recall-cli.test.js test/forget.test.js test/functional.test.js test/erasure.test.js test/stress.test.js test/crypto.test.js test/git-sync.test.js test/restore.test.js test/trust-recall.test.js test/cloud-sync.test.js test/export-import.test.js test/install.test.js test/prompts.test.js test/session-start.test.js test/memorize.test.js test/pinning.test.js test/skills.test.js test/contradiction.test.js test/harvest.test.js test/content-lint.test.js test/audit-log.test.js test/quarantine.test.js test/anomaly.test.js test/path-hardening.test.js test/supersede.test.js test/bitemporal.test.js test/integrity.test.js test/skill-verify.test.js test/decay-calibration.test.js test/recall-history.test.js test/plugin-manifests.test.js test/plugin-hooks.test.js test/surfaced.test.js test/adapters.test.js test/sensitivity.test.js test/cloud-store.test.js test/maintenance-loop.test.js store/test/store.test.js store/test/oidc.test.js store/conformance/conformance.test.js",
|
|
52
52
|
"test:integrations": "npm run test:integrations:agentskills && npm run test:integrations:openclaw && npm run test:integrations:copilot && npm run test:integrations:kilo && npm run test:integrations:api && npm run test:integrations:hermes",
|
|
53
53
|
"test:integrations:agentskills": "node --test integrations/agentskills/test/*.test.mjs",
|
|
54
54
|
"test:integrations:openclaw": "node --test integrations/openclaw/test/*.test.mjs",
|
package/prompts/antigravity.md
CHANGED
|
@@ -94,6 +94,8 @@ Only add extra lines if actionable:
|
|
|
94
94
|
- `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
|
|
95
95
|
- `⌛ <N> pinned memories expired` — if `expired_pins > 0` (their validity window closed; update or unpin them)
|
|
96
96
|
- `⊘ <N> pending verification` — if `pending_verification > 0` (memories from untrusted sources are quarantined for review — resolve with `brain verify list`)
|
|
97
|
+
- `📝 <N> notable items from recent sessions never memorized` — if `unsaved_notables` is present (offer to store the relevant ones, with consent)
|
|
98
|
+
- `💤 sleep due` — if `sleep_due` is present (maintenance overdue; mention once, never run `/brain:sleep` unasked)
|
|
97
99
|
|
|
98
100
|
The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
|
|
99
101
|
|
|
@@ -149,7 +151,7 @@ When a session is ending (user says bye/thanks/done, conversation wraps up, or y
|
|
|
149
151
|
}
|
|
150
152
|
```
|
|
151
153
|
|
|
152
|
-
Keep only the last
|
|
154
|
+
Keep only the last 100 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — `brain session-start` reads it back as `unsaved_notables` so a later session can offer to store it.
|
|
153
155
|
|
|
154
156
|
### Step 2: Suggest Memorization (if warranted)
|
|
155
157
|
|
package/prompts/claude.md
CHANGED
|
@@ -93,6 +93,8 @@ Only add extra lines if actionable:
|
|
|
93
93
|
- `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
|
|
94
94
|
- `⌛ <N> pinned memories expired` — if `expired_pins > 0` (their validity window closed; update or unpin them)
|
|
95
95
|
- `⊘ <N> pending verification` — if `pending_verification > 0` (memories from untrusted sources are quarantined for review — resolve with `brain verify list`)
|
|
96
|
+
- `📝 <N> notable items from recent sessions never memorized` — if `unsaved_notables` is present (offer to store the relevant ones, with consent)
|
|
97
|
+
- `💤 sleep due` — if `sleep_due` is present (maintenance overdue; mention once, never run `/brain:sleep` unasked)
|
|
96
98
|
|
|
97
99
|
The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
|
|
98
100
|
|
|
@@ -148,7 +150,7 @@ When a session is ending (user says bye/thanks/done, conversation wraps up, or y
|
|
|
148
150
|
}
|
|
149
151
|
```
|
|
150
152
|
|
|
151
|
-
Keep only the last
|
|
153
|
+
Keep only the last 100 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — `brain session-start` reads it back as `unsaved_notables` so a later session can offer to store it.
|
|
152
154
|
|
|
153
155
|
### Step 2: Suggest Memorization (if warranted)
|
|
154
156
|
|
package/prompts/copilot.md
CHANGED
|
@@ -96,6 +96,8 @@ Only add extra lines if actionable:
|
|
|
96
96
|
- `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
|
|
97
97
|
- `⌛ <N> pinned memories expired` — if `expired_pins > 0` (their validity window closed; update or unpin them)
|
|
98
98
|
- `⊘ <N> pending verification` — if `pending_verification > 0` (memories from untrusted sources are quarantined for review — resolve with `brain verify list`)
|
|
99
|
+
- `📝 <N> notable items from recent sessions never memorized` — if `unsaved_notables` is present (offer to store the relevant ones, with consent)
|
|
100
|
+
- `💤 sleep due` — if `sleep_due` is present (maintenance overdue; mention once, never run `/brain:sleep` unasked)
|
|
99
101
|
|
|
100
102
|
The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
|
|
101
103
|
|
|
@@ -151,7 +153,7 @@ When a session is ending (user says bye/thanks/done, conversation wraps up, or y
|
|
|
151
153
|
}
|
|
152
154
|
```
|
|
153
155
|
|
|
154
|
-
Keep only the last
|
|
156
|
+
Keep only the last 100 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — `brain session-start` reads it back as `unsaved_notables` so a later session can offer to store it.
|
|
155
157
|
|
|
156
158
|
### Step 2: Suggest Memorization (if warranted)
|
|
157
159
|
|
package/prompts/kilo.md
CHANGED
|
@@ -95,6 +95,8 @@ Only add extra lines if actionable:
|
|
|
95
95
|
- `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
|
|
96
96
|
- `⌛ <N> pinned memories expired` — if `expired_pins > 0` (their validity window closed; update or unpin them)
|
|
97
97
|
- `⊘ <N> pending verification` — if `pending_verification > 0` (memories from untrusted sources are quarantined for review — resolve with `brain verify list`)
|
|
98
|
+
- `📝 <N> notable items from recent sessions never memorized` — if `unsaved_notables` is present (offer to store the relevant ones, with consent)
|
|
99
|
+
- `💤 sleep due` — if `sleep_due` is present (maintenance overdue; mention once, never run `/brain:sleep` unasked)
|
|
98
100
|
|
|
99
101
|
The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
|
|
100
102
|
|
|
@@ -150,7 +152,7 @@ When a session is ending (user says bye/thanks/done, conversation wraps up, or y
|
|
|
150
152
|
}
|
|
151
153
|
```
|
|
152
154
|
|
|
153
|
-
Keep only the last
|
|
155
|
+
Keep only the last 100 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — `brain session-start` reads it back as `unsaved_notables` so a later session can offer to store it.
|
|
154
156
|
|
|
155
157
|
### Step 2: Suggest Memorization (if warranted)
|
|
156
158
|
|
package/prompts/openai.md
CHANGED
|
@@ -94,6 +94,8 @@ Only add extra lines if actionable:
|
|
|
94
94
|
- `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
|
|
95
95
|
- `⌛ <N> pinned memories expired` — if `expired_pins > 0` (their validity window closed; update or unpin them)
|
|
96
96
|
- `⊘ <N> pending verification` — if `pending_verification > 0` (memories from untrusted sources are quarantined for review — resolve with `brain verify list`)
|
|
97
|
+
- `📝 <N> notable items from recent sessions never memorized` — if `unsaved_notables` is present (offer to store the relevant ones, with consent)
|
|
98
|
+
- `💤 sleep due` — if `sleep_due` is present (maintenance overdue; mention once, never run `/brain:sleep` unasked)
|
|
97
99
|
|
|
98
100
|
The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
|
|
99
101
|
|
|
@@ -149,7 +151,7 @@ When a session is ending (user says bye/thanks/done, conversation wraps up, or y
|
|
|
149
151
|
}
|
|
150
152
|
```
|
|
151
153
|
|
|
152
|
-
Keep only the last
|
|
154
|
+
Keep only the last 100 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — `brain session-start` reads it back as `unsaved_notables` so a later session can offer to store it.
|
|
153
155
|
|
|
154
156
|
### Step 2: Suggest Memorization (if warranted)
|
|
155
157
|
|
package/prompts/opencode.md
CHANGED
|
@@ -93,6 +93,8 @@ Only add extra lines if actionable:
|
|
|
93
93
|
- `⚠️ <N> low-confidence memories used frequently` — if `low_confidence_alerts` is non-empty
|
|
94
94
|
- `⌛ <N> pinned memories expired` — if `expired_pins > 0` (their validity window closed; update or unpin them)
|
|
95
95
|
- `⊘ <N> pending verification` — if `pending_verification > 0` (memories from untrusted sources are quarantined for review — resolve with `brain verify list`)
|
|
96
|
+
- `📝 <N> notable items from recent sessions never memorized` — if `unsaved_notables` is present (offer to store the relevant ones, with consent)
|
|
97
|
+
- `💤 sleep due` — if `sleep_due` is present (maintenance overdue; mention once, never run `/brain:sleep` unasked)
|
|
96
98
|
|
|
97
99
|
The aggregator is budget-bounded (`~/.brain/config.json`) and never exceeds the working-memory token budget, so just internalize whatever it returns. **The goal is ambient awareness** — know about past decisions, learnings, and preferences without reciting them.
|
|
98
100
|
|
|
@@ -148,7 +150,7 @@ When a session is ending (user says bye/thanks/done, conversation wraps up, or y
|
|
|
148
150
|
}
|
|
149
151
|
```
|
|
150
152
|
|
|
151
|
-
Keep only the last
|
|
153
|
+
Keep only the last 100 session entries. The `notable_unsaved` field preserves what happened even if the user didn't memorize — `brain session-start` reads it back as `unsaved_notables` so a later session can offer to store it.
|
|
152
154
|
|
|
153
155
|
### Step 2: Suggest Memorization (if warranted)
|
|
154
156
|
|
package/src/index-manager.js
CHANGED
|
@@ -276,7 +276,53 @@ function groupByCategory(index) {
|
|
|
276
276
|
function readAssociations(projectRoot) {
|
|
277
277
|
const filePath = path.join(getBrainDir(projectRoot), ASSOCIATIONS_FILE);
|
|
278
278
|
if (!fs.existsSync(filePath)) return null;
|
|
279
|
-
return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
|
|
279
|
+
return normalizeAssociations(JSON.parse(fs.readFileSync(filePath, 'utf-8')));
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Fold flat `"a::b": {source, target, weight, …}` edges into the nested
|
|
284
|
+
* adjacency map (`edges[a][b]`) every reader expects.
|
|
285
|
+
*
|
|
286
|
+
* The sleep cycle is agent-driven and some agents wrote propagation / dream /
|
|
287
|
+
* manual links in the flat shape. The scorer looks edges up by memory id, so a
|
|
288
|
+
* flat key could never match a node: those links were stored but never fired
|
|
289
|
+
* during spreading activation. Normalizing on read repairs existing brains on
|
|
290
|
+
* the next write, and any future flat edge is absorbed the same way.
|
|
291
|
+
* Bidirectional, like reinforceEdge; an existing nested edge keeps the higher
|
|
292
|
+
* weight.
|
|
293
|
+
*
|
|
294
|
+
* @param {Object} associations
|
|
295
|
+
* @returns {Object} the same object, normalized in place
|
|
296
|
+
*/
|
|
297
|
+
function normalizeAssociations(associations) {
|
|
298
|
+
if (!associations || typeof associations !== 'object') return associations;
|
|
299
|
+
const edges = associations.edges;
|
|
300
|
+
if (!edges || typeof edges !== 'object') return associations;
|
|
301
|
+
for (const key of Object.keys(edges)) {
|
|
302
|
+
if (!key.includes('::')) continue;
|
|
303
|
+
const flat = edges[key];
|
|
304
|
+
delete edges[key];
|
|
305
|
+
if (!flat || typeof flat !== 'object') continue;
|
|
306
|
+
const [a, b] = key.split('::');
|
|
307
|
+
const src = flat.source || a;
|
|
308
|
+
const dst = flat.target || b;
|
|
309
|
+
if (!src || !dst || src === dst) continue;
|
|
310
|
+
const edge = {
|
|
311
|
+
weight: typeof flat.weight === 'number' ? flat.weight : 0.2,
|
|
312
|
+
co_retrievals: flat.co_retrievals ?? flat.co_activations ?? 0,
|
|
313
|
+
last_activated: flat.last_activated || flat.created || new Date().toISOString(),
|
|
314
|
+
origin: flat.origin || 'manual',
|
|
315
|
+
};
|
|
316
|
+
for (const extra of ['note', 'insight', 'dream_score']) {
|
|
317
|
+
if (flat[extra] !== undefined) edge[extra] = flat[extra];
|
|
318
|
+
}
|
|
319
|
+
for (const [from, to] of [[src, dst], [dst, src]]) {
|
|
320
|
+
if (!edges[from] || typeof edges[from] !== 'object') edges[from] = {};
|
|
321
|
+
const existing = edges[from][to];
|
|
322
|
+
if (!existing || (existing.weight ?? 0) < edge.weight) edges[from][to] = { ...edge };
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return associations;
|
|
280
326
|
}
|
|
281
327
|
|
|
282
328
|
/**
|
|
@@ -630,6 +676,7 @@ module.exports = {
|
|
|
630
676
|
groupByCategory,
|
|
631
677
|
// Phase 1: Associative Network
|
|
632
678
|
readAssociations,
|
|
679
|
+
normalizeAssociations,
|
|
633
680
|
writeAssociations,
|
|
634
681
|
reinforceEdge,
|
|
635
682
|
getNeighbors,
|
package/src/reinforce.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Brain Memory — Reinforcement (library form)
|
|
3
|
+
*
|
|
4
|
+
* Spaced reinforcement + Hebbian co-retrieval, shared by `brain reinforce`
|
|
5
|
+
* (explicit, agent-invoked) and the Stop hook (implicit: a memory the agent
|
|
6
|
+
* cited with a verified receipt shaped the answer, so it was used).
|
|
7
|
+
*
|
|
8
|
+
* Why the implicit path exists: the whole strength model assumes recall makes
|
|
9
|
+
* a memory stronger, but in practice agents almost never ran `brain reinforce`
|
|
10
|
+
* after recalling — one real brain had 328 surfaced events and zero `used`
|
|
11
|
+
* events across seven months, leaving 93% of memories at access_count 0. A
|
|
12
|
+
* receipt in the final reply is a stronger "this memory was used" signal than
|
|
13
|
+
* anything the agent would remember to report, and it is already verified
|
|
14
|
+
* against the surfaced ledger by the citation lock.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const fs = require('fs');
|
|
18
|
+
const path = require('path');
|
|
19
|
+
|
|
20
|
+
const {
|
|
21
|
+
readIndex,
|
|
22
|
+
writeIndex,
|
|
23
|
+
readAssociations,
|
|
24
|
+
writeAssociations,
|
|
25
|
+
reinforceEdge,
|
|
26
|
+
getBrainDir,
|
|
27
|
+
validateBrainPath,
|
|
28
|
+
} = require('./index-manager');
|
|
29
|
+
const { reinforceStrength, improveDecayRate } = require('./scorer');
|
|
30
|
+
|
|
31
|
+
// Recall-history rows kept per memory. Enough to fit an interval curve;
|
|
32
|
+
// small enough that a hot memory's frontmatter stays cheap to parse.
|
|
33
|
+
const RECALL_HISTORY_MAX = 50;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Update a memory file's YAML frontmatter fields on disk (existing keys only).
|
|
37
|
+
*/
|
|
38
|
+
function updateMemoryFile(brainDir, memPath, updates) {
|
|
39
|
+
const fullPath = path.join(brainDir, memPath);
|
|
40
|
+
try {
|
|
41
|
+
// The path comes from index.json — which syncs across devices, so a
|
|
42
|
+
// tampered index entry must not become a write primitive outside ~/.brain.
|
|
43
|
+
validateBrainPath(fullPath, brainDir);
|
|
44
|
+
let content = fs.readFileSync(fullPath, 'utf-8');
|
|
45
|
+
const firstDash = content.indexOf('---');
|
|
46
|
+
const secondDash = content.indexOf('---', firstDash + 3);
|
|
47
|
+
if (firstDash === -1 || secondDash === -1) return;
|
|
48
|
+
let frontmatter = content.slice(firstDash + 3, secondDash);
|
|
49
|
+
for (const [key, value] of Object.entries(updates)) {
|
|
50
|
+
const regex = new RegExp(`^(${key}:\\s*).*$`, 'm');
|
|
51
|
+
// Arrays/objects are JSON-encoded (JSON is a YAML subset); String() would
|
|
52
|
+
// render an array of objects as "[object Object]".
|
|
53
|
+
const formatted = typeof value === 'string'
|
|
54
|
+
? `"${value}"`
|
|
55
|
+
: (value !== null && typeof value === 'object' ? JSON.stringify(value) : String(value));
|
|
56
|
+
if (regex.test(frontmatter)) frontmatter = frontmatter.replace(regex, `$1${formatted}`);
|
|
57
|
+
}
|
|
58
|
+
content = content.slice(0, firstDash + 3) + frontmatter + content.slice(secondDash);
|
|
59
|
+
fs.writeFileSync(fullPath, content);
|
|
60
|
+
} catch { /* skip if file not readable/writable */ }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Reinforce memories by id.
|
|
65
|
+
*
|
|
66
|
+
* @param {string[]} ids
|
|
67
|
+
* @param {Object} [opts] - { now: Date, brainDir }
|
|
68
|
+
* @returns {{ reinforced: Object[], edges_reinforced: number }}
|
|
69
|
+
*/
|
|
70
|
+
function reinforceMemories(ids, opts = {}) {
|
|
71
|
+
const now = opts.now || new Date();
|
|
72
|
+
const nowISO = now.toISOString();
|
|
73
|
+
const brainDir = opts.brainDir || getBrainDir();
|
|
74
|
+
const index = readIndex();
|
|
75
|
+
if (!index) throw new Error('Brain not initialized.');
|
|
76
|
+
|
|
77
|
+
const unique = [...new Set((ids || []).filter(Boolean))];
|
|
78
|
+
const reinforced = [];
|
|
79
|
+
|
|
80
|
+
for (const memId of unique) {
|
|
81
|
+
const entry = index.memories[memId];
|
|
82
|
+
if (!entry) continue;
|
|
83
|
+
|
|
84
|
+
const lastAccessed = new Date(entry.last_accessed || entry.created);
|
|
85
|
+
const daysSince = Math.max(0, (now - lastAccessed) / (1000 * 60 * 60 * 24));
|
|
86
|
+
const accessCount = entry.access_count || 0;
|
|
87
|
+
|
|
88
|
+
const oldStrength = entry.strength;
|
|
89
|
+
const newStrength = reinforceStrength(oldStrength, daysSince, accessCount);
|
|
90
|
+
const newDecayRate = improveDecayRate(entry.decay_rate);
|
|
91
|
+
|
|
92
|
+
entry.strength = Math.round(newStrength * 1000) / 1000;
|
|
93
|
+
entry.decay_rate = Math.round(newDecayRate * 10000) / 10000;
|
|
94
|
+
entry.last_accessed = nowISO;
|
|
95
|
+
entry.access_count = accessCount + 1;
|
|
96
|
+
|
|
97
|
+
// One row per reinforcement, capped — the interval series is what makes
|
|
98
|
+
// decay calibration possible (benchmark/harness/decay-calibration.js).
|
|
99
|
+
const history = Array.isArray(entry.recall_history) ? entry.recall_history : [];
|
|
100
|
+
history.push({
|
|
101
|
+
at: nowISO,
|
|
102
|
+
days_since_last: Math.round(daysSince * 100) / 100,
|
|
103
|
+
strength_before: oldStrength,
|
|
104
|
+
strength_after: entry.strength,
|
|
105
|
+
});
|
|
106
|
+
entry.recall_history = history.slice(-RECALL_HISTORY_MAX);
|
|
107
|
+
|
|
108
|
+
updateMemoryFile(brainDir, entry.path, {
|
|
109
|
+
strength: entry.strength,
|
|
110
|
+
decay_rate: entry.decay_rate,
|
|
111
|
+
last_accessed: nowISO,
|
|
112
|
+
access_count: entry.access_count,
|
|
113
|
+
recall_history: entry.recall_history,
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
reinforced.push({
|
|
117
|
+
id: memId,
|
|
118
|
+
old_strength: oldStrength,
|
|
119
|
+
new_strength: entry.strength,
|
|
120
|
+
boost: Math.round((newStrength - oldStrength) * 1000) / 1000,
|
|
121
|
+
decay_rate: entry.decay_rate,
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (reinforced.length) writeIndex(index);
|
|
126
|
+
|
|
127
|
+
// Hebbian co-retrieval: strengthen edges between every pair used together.
|
|
128
|
+
let edgesReinforced = 0;
|
|
129
|
+
const present = reinforced.map((r) => r.id);
|
|
130
|
+
if (present.length > 1) {
|
|
131
|
+
const associations = readAssociations() || { version: 1, edges: {} };
|
|
132
|
+
for (let i = 0; i < present.length; i++) {
|
|
133
|
+
for (let j = i + 1; j < present.length; j++) {
|
|
134
|
+
reinforceEdge(associations, present[i], present[j], 'co_retrieval');
|
|
135
|
+
edgesReinforced++;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
writeAssociations(associations);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return { reinforced, edges_reinforced: edgesReinforced };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
module.exports = { reinforceMemories, updateMemoryFile, RECALL_HISTORY_MAX };
|