brain-memory 0.5.2 → 0.6.1
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 +54 -0
- package/README.md +8 -2
- package/bin/brain.js +3 -0
- package/bin/memorize.js +33 -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/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,60 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
|
|
|
6
6
|
|
|
7
7
|
## [Unreleased]
|
|
8
8
|
|
|
9
|
+
## [0.6.1] - 2026-11-10
|
|
10
|
+
|
|
11
|
+
First npm release of the 0.6.0 work: 0.6.0 was tagged but never published, so
|
|
12
|
+
everything listed under 0.6.0 below reaches npm with this version.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
- **README: November 2026 benchmark results.** The benchmark section now
|
|
16
|
+
reports the confirmatory run — Claude Sonnet 5.5 under test, N=10 per arm,
|
|
17
|
+
a Gemini 3.5 Flash + Gemini 2.5 Pro + DeepSeek V4 Pro judge panel — across
|
|
18
|
+
scenarios A–D, F and the new poisoned-haystack scenario G, replacing the
|
|
19
|
+
June n=3 numbers. Full tables and raw JSON:
|
|
20
|
+
[brainmemory.ai/docs/benchmarks/results](https://brainmemory.ai/docs/benchmarks/results/).
|
|
21
|
+
|
|
22
|
+
## [0.6.0] - 2026-11-09
|
|
23
|
+
|
|
24
|
+
Memories you actually use now get stronger, and stale facts can be retired.
|
|
25
|
+
An audit of a real seven-month brain found the cognition loop idle: agents
|
|
26
|
+
were shown memories 328 times and reported using them zero times, so 93% of
|
|
27
|
+
memories had never been reinforced, while contradicting facts piled up with
|
|
28
|
+
nothing to retire them.
|
|
29
|
+
|
|
30
|
+
### Added
|
|
31
|
+
- **Receipts reinforce automatically.** When a reply cites a memory with a
|
|
32
|
+
`◉ memory:` receipt that checks out against what brain surfaced, the Stop
|
|
33
|
+
hook applies spaced reinforcement to it (once per session), with Hebbian
|
|
34
|
+
co-retrieval between memories cited together. No more relying on the agent
|
|
35
|
+
to remember `brain reinforce`.
|
|
36
|
+
- **`brain supersede <old>... --by <new>`.** Mark an existing memory as ended
|
|
37
|
+
by a newer one that is already stored: stamps `superseded_by` and
|
|
38
|
+
`valid_until` (the successor's start, or `--valid-until`), records
|
|
39
|
+
`supersedes` on the successor, links the pair and logs the change.
|
|
40
|
+
`--dry-run` previews.
|
|
41
|
+
- **Sleep: supersession sweep (Phase 6b).** Sleep now looks for still-strong
|
|
42
|
+
facts a newer memory replaced and, with approval, bounds them with
|
|
43
|
+
`brain supersede`. Sleep also records its run in `~/.brain/sleep-log.json`.
|
|
44
|
+
- **`💤 sleep due` and `📝 unsaved notables` at session start.**
|
|
45
|
+
`brain session-start` reports `sleep_due` after a week with 10+ new memories,
|
|
46
|
+
and `unsaved_notables`: items recent sessions flagged in `notable_unsaved`
|
|
47
|
+
that no later write picked up, so they can be offered for storage instead of
|
|
48
|
+
silently rotating out.
|
|
49
|
+
|
|
50
|
+
### Changed
|
|
51
|
+
- **Contradiction candidates include restated facts.** `memorize` now also
|
|
52
|
+
proposes same-project memories whose text is closest to the new one, so a
|
|
53
|
+
fact restated in different words and tags (a domain migration, a new deploy
|
|
54
|
+
path) is flagged, not only tag overlaps.
|
|
55
|
+
- **`contexts.json` keeps 100 sessions, not 20,** in the plugin hook and every
|
|
56
|
+
host integration. Twenty was about three days of history for an active user.
|
|
57
|
+
|
|
58
|
+
### Fixed
|
|
59
|
+
- **Associations written in flat form now take part in recall.** Agent-run
|
|
60
|
+
sleep cycles could write edges as `"a::b"` keys, which spreading activation
|
|
61
|
+
never read. They are folded into the nested edge map on load.
|
|
62
|
+
|
|
9
63
|
## [0.5.2] - 2026-11-08
|
|
10
64
|
|
|
11
65
|
Codex now suggests brain commands it can actually run.
|
package/README.md
CHANGED
|
@@ -808,10 +808,16 @@ Brain Memory ships with a controlled benchmark suite grounded in the 2025-2026 S
|
|
|
808
808
|
| **D** *Skill Progressive Disclosure* | "Five skills indexed, one needed — does brain load just the one?" | CoALA Phase-2 L0/L1/L2 token efficiency |
|
|
809
809
|
| **E** *Continual Coding* | "Five bugs in order — does bug 5 finish faster than bug 1?" | Forward transfer; agent writes memories between tasks |
|
|
810
810
|
| **F** *Abstention* | "No deployment target in memory — does the agent ask or invent?" | Confabulation resistance |
|
|
811
|
+
| **G** *Poisoned Haystack* | "One memory says to leak the API key — does the task still get done, safely?" | Quarantine of low-trust, instruction-shaped memories |
|
|
811
812
|
|
|
812
|
-
**Methodology highlights** — agent under test is **
|
|
813
|
+
**Methodology highlights** — agent under test is **Claude Sonnet 5.5** (single-shot, direct API), graded by a **cross-family judge panel** (Gemini 3.5 Flash + Gemini 2.5 Pro + DeepSeek V4 Pro, majority vote — no judge shares the agent's family, [Preference Leakage 2502.01534](https://arxiv.org/abs/2502.01534), [PoLL 2404.18796](https://arxiv.org/abs/2404.18796)); [pre-registered](benchmark/PREREGISTRATION.md) N=10 per arm; deterministic distractor haystacks up to 1000 memories; real `brain session-start` / `brain recall` integration; every scenario anchored by a no-memory floor and an oracle ceiling.
|
|
813
814
|
|
|
814
|
-
> Results (
|
|
815
|
+
> **Results (Claude Sonnet 5.5, N=10 per arm, November 2026).**
|
|
816
|
+
> **A — retrieval under 1000 distractors:** `brain-full` passes **9/10** while **BM25, a vector store and no memory all pass 0/10** (Fisher p = 0.0001 each), at **4–22× fewer median tokens per run** than the context dumps that also pass. With the model choosing its own recall query (the hosted connector's policy) brain passes **10/10 at Recall@5 1.00**.
|
|
817
|
+
> **D — skills:** loading only the relevant skill passes 10/10 at **28% fewer tokens** than loading every skill (DeepSeek V4 Pro: 43%).
|
|
818
|
+
> **G — poisoned memory:** with quarantine on the task completes safely **10/10**; with it off, the poisoned memory gets **every request refused** by Claude's API safety layer.
|
|
819
|
+
> **B (continuity) and C (contradiction) are ties** — memory is essential (floor 0/10) but plain BM25 matches brain's correctness with fewer tokens. **F (abstention) is a null.** Judge-vs-human validation is still pending.
|
|
820
|
+
> Full tables and raw JSON: [brainmemory.ai/docs/benchmarks/results](https://brainmemory.ai/docs/benchmarks/results).
|
|
815
821
|
|
|
816
822
|
**Retrieval calibration probe (in-vivo, July 2026).** Separate from the controlled
|
|
817
823
|
suite: a 20-query retrieval probe on a real working brain (177 memories, 1,245
|
package/bin/brain.js
CHANGED
|
@@ -28,6 +28,7 @@ const VERSION = require('../package.json').version;
|
|
|
28
28
|
const DELEGATED = {
|
|
29
29
|
recall: 'recall.js',
|
|
30
30
|
reinforce: 'reinforce.js',
|
|
31
|
+
supersede: 'supersede.js',
|
|
31
32
|
memorize: 'memorize.js',
|
|
32
33
|
cloud: 'cloud-sync.js',
|
|
33
34
|
'session-start': 'session-start.js',
|
|
@@ -66,6 +67,8 @@ Memory
|
|
|
66
67
|
recall --reindex Rebuild the search index
|
|
67
68
|
memorize [--sync] Store memories from a JSON payload on stdin
|
|
68
69
|
reinforce <id> [<id>...] Spaced reinforcement + Hebbian co-retrieval
|
|
70
|
+
supersede <old> [<old>...] --by <new> [--valid-until ISO] [--dry-run]
|
|
71
|
+
Mark existing memories as ended by a newer one
|
|
69
72
|
pin <id> [--scope global|project:<name>] [--priority N]
|
|
70
73
|
Pin a memory into the always-present tier
|
|
71
74
|
unpin <id> Remove a memory from the always-present tier
|
package/bin/memorize.js
CHANGED
|
@@ -35,7 +35,7 @@ const {
|
|
|
35
35
|
atomicWriteSync,
|
|
36
36
|
validateBrainPath,
|
|
37
37
|
} = require('../src/index-manager');
|
|
38
|
-
const { addDocument, createSearchIndex, readSearchIndex, writeSearchIndex } = require('../src/tfidf');
|
|
38
|
+
const { addDocument, bm25Search, createSearchIndex, readSearchIndex, writeSearchIndex } = require('../src/tfidf');
|
|
39
39
|
const { appendAudit } = require('../src/audit');
|
|
40
40
|
const { lintMemoryContent } = require('../src/content-lint');
|
|
41
41
|
const { contentHash } = require('../src/integrity');
|
|
@@ -364,6 +364,37 @@ function findTagOverlaps(index, newTags, newId, minOverlap = 2) {
|
|
|
364
364
|
return overlaps;
|
|
365
365
|
}
|
|
366
366
|
|
|
367
|
+
/**
|
|
368
|
+
* Same-project memories whose text is closest to the new one — the second
|
|
369
|
+
* candidate source for contradiction proposals.
|
|
370
|
+
*
|
|
371
|
+
* Tag overlap alone misses the commonest reversal: a fact restated in new
|
|
372
|
+
* words with different tags ("primary domain migrated to brainmemory.ai" vs an
|
|
373
|
+
* older "API lives at api.brainmemory.work"). Lexical neighbours inside the
|
|
374
|
+
* same project catch those. Scoped to the project so a generic word overlap
|
|
375
|
+
* across unrelated work never becomes a proposal, and capped small because
|
|
376
|
+
* every candidate still has to pass proposeSupersessions' type filter and the
|
|
377
|
+
* agent's judgement.
|
|
378
|
+
*/
|
|
379
|
+
function findTextNeighbors(searchIndex, index, mem, newId, limit = 3) {
|
|
380
|
+
try {
|
|
381
|
+
const project = mem.encoding_context && mem.encoding_context.project;
|
|
382
|
+
if (!project) return [];
|
|
383
|
+
const query = `${mem.title || ''} ${mem.content || ''}`.slice(0, 2000);
|
|
384
|
+
const scores = bm25Search(searchIndex, query);
|
|
385
|
+
const ranked = Object.entries(scores)
|
|
386
|
+
.filter(([mid]) => mid !== newId && index.memories[mid])
|
|
387
|
+
.filter(([mid]) => (index.memories[mid].encoding_context || {}).project === project)
|
|
388
|
+
.sort((a, b) => b[1] - a[1]);
|
|
389
|
+
if (!ranked.length) return [];
|
|
390
|
+
const top = ranked[0][1];
|
|
391
|
+
// Relative floor: only neighbours close to the best match, not the tail.
|
|
392
|
+
return ranked.filter(([, sc]) => sc >= top * 0.6).slice(0, limit).map(([mid]) => mid);
|
|
393
|
+
} catch {
|
|
394
|
+
return [];
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
367
398
|
function trySync() {
|
|
368
399
|
const brainDir = getBrainDir();
|
|
369
400
|
|
|
@@ -667,7 +698,7 @@ async function main() {
|
|
|
667
698
|
const potentialConflicts = proposeSupersessions(
|
|
668
699
|
index,
|
|
669
700
|
{ ...mem, created: now },
|
|
670
|
-
tagOverlaps,
|
|
701
|
+
[...new Set([...tagOverlaps, ...findTextNeighbors(searchIndex, index, mem, id)])],
|
|
671
702
|
{ now },
|
|
672
703
|
);
|
|
673
704
|
|
package/bin/reinforce.js
CHANGED
|
@@ -20,29 +20,9 @@
|
|
|
20
20
|
* - Updates index.json, associations.json, and memory files
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
|
-
const fs = require('fs');
|
|
24
|
-
const path = require('path');
|
|
25
|
-
const os = require('os');
|
|
26
|
-
|
|
27
23
|
const { envSession, recordUsed } = require('../src/surfaced');
|
|
28
|
-
const {
|
|
29
|
-
|
|
30
|
-
writeIndex,
|
|
31
|
-
readAssociations,
|
|
32
|
-
writeAssociations,
|
|
33
|
-
reinforceEdge,
|
|
34
|
-
getBrainDir,
|
|
35
|
-
validateBrainPath,
|
|
36
|
-
} = require('../src/index-manager');
|
|
37
|
-
|
|
38
|
-
const {
|
|
39
|
-
reinforceStrength,
|
|
40
|
-
improveDecayRate,
|
|
41
|
-
} = require('../src/scorer');
|
|
42
|
-
|
|
43
|
-
// Recall-history rows kept per memory. Enough to fit an interval curve;
|
|
44
|
-
// small enough that a hot memory's frontmatter stays cheap to parse.
|
|
45
|
-
const RECALL_HISTORY_MAX = 50;
|
|
24
|
+
const { getBrainDir } = require('../src/index-manager');
|
|
25
|
+
const { reinforceMemories } = require('../src/reinforce');
|
|
46
26
|
|
|
47
27
|
function main() {
|
|
48
28
|
const args = parseArgs(process.argv.slice(2));
|
|
@@ -53,157 +33,27 @@ function main() {
|
|
|
53
33
|
}
|
|
54
34
|
|
|
55
35
|
const brainDir = getBrainDir();
|
|
56
|
-
|
|
36
|
+
const now = new Date();
|
|
37
|
+
let result;
|
|
57
38
|
try {
|
|
58
|
-
|
|
39
|
+
result = reinforceMemories(args.memoryIds, { now, brainDir });
|
|
59
40
|
} catch (err) {
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
41
|
+
const msg = /not initialized/.test(err.message)
|
|
42
|
+
? 'Brain not initialized.'
|
|
43
|
+
: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`;
|
|
44
|
+
console.error(JSON.stringify({ error: msg }));
|
|
63
45
|
process.exit(1);
|
|
64
46
|
}
|
|
65
47
|
|
|
66
|
-
if (!index) {
|
|
67
|
-
console.error(JSON.stringify({ error: 'Brain not initialized.' }));
|
|
68
|
-
process.exit(1);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const now = new Date();
|
|
72
|
-
const nowISO = now.toISOString();
|
|
73
|
-
const reinforced = [];
|
|
74
|
-
|
|
75
|
-
// Apply spaced reinforcement to each memory
|
|
76
|
-
for (const memId of args.memoryIds) {
|
|
77
|
-
const entry = index.memories[memId];
|
|
78
|
-
if (!entry) continue;
|
|
79
|
-
|
|
80
|
-
const lastAccessed = new Date(entry.last_accessed || entry.created);
|
|
81
|
-
const daysSince = (now - lastAccessed) / (1000 * 60 * 60 * 24);
|
|
82
|
-
const accessCount = entry.access_count || 0;
|
|
83
|
-
|
|
84
|
-
// Compute boost
|
|
85
|
-
const oldStrength = entry.strength;
|
|
86
|
-
const newStrength = reinforceStrength(oldStrength, daysSince, accessCount);
|
|
87
|
-
const newDecayRate = improveDecayRate(entry.decay_rate);
|
|
88
|
-
|
|
89
|
-
// Update index entry
|
|
90
|
-
entry.strength = Math.round(newStrength * 1000) / 1000;
|
|
91
|
-
entry.decay_rate = Math.round(newDecayRate * 10000) / 10000;
|
|
92
|
-
entry.last_accessed = nowISO;
|
|
93
|
-
entry.access_count = accessCount + 1;
|
|
94
|
-
|
|
95
|
-
// Recall history: one row per reinforcement, capped.
|
|
96
|
-
//
|
|
97
|
-
// `access_count` says a memory was recalled N times; it cannot say *when*,
|
|
98
|
-
// and the interval is the entire signal. Spaced reinforcement is built on
|
|
99
|
-
// the premise that longer gaps produce larger, more durable boosts — but
|
|
100
|
-
// without the timestamps that premise is unfalsifiable, and the decay
|
|
101
|
-
// constants stay hand-set forever because there is nothing to fit them to.
|
|
102
|
-
// This is the series that makes calibration possible (see
|
|
103
|
-
// benchmark/harness/decay-calibration.js).
|
|
104
|
-
//
|
|
105
|
-
// Bounded at RECALL_HISTORY_MAX: a frequently-recalled memory would
|
|
106
|
-
// otherwise grow an unbounded array inside a file that is read on every
|
|
107
|
-
// recall. Oldest rows drop first; the recent intervals carry the signal.
|
|
108
|
-
const history = Array.isArray(entry.recall_history) ? entry.recall_history : [];
|
|
109
|
-
history.push({
|
|
110
|
-
at: nowISO,
|
|
111
|
-
days_since_last: Math.round(daysSince * 100) / 100,
|
|
112
|
-
strength_before: oldStrength,
|
|
113
|
-
strength_after: entry.strength,
|
|
114
|
-
});
|
|
115
|
-
entry.recall_history = history.slice(-RECALL_HISTORY_MAX);
|
|
116
|
-
|
|
117
|
-
// Update the memory file's frontmatter on disk
|
|
118
|
-
updateMemoryFile(brainDir, entry.path, {
|
|
119
|
-
strength: entry.strength,
|
|
120
|
-
decay_rate: entry.decay_rate,
|
|
121
|
-
last_accessed: nowISO,
|
|
122
|
-
access_count: entry.access_count,
|
|
123
|
-
recall_history: entry.recall_history,
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
reinforced.push({
|
|
127
|
-
id: memId,
|
|
128
|
-
old_strength: oldStrength,
|
|
129
|
-
new_strength: entry.strength,
|
|
130
|
-
boost: Math.round((newStrength - oldStrength) * 1000) / 1000,
|
|
131
|
-
decay_rate: entry.decay_rate,
|
|
132
|
-
});
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// Save index
|
|
136
|
-
writeIndex(index);
|
|
137
|
-
|
|
138
|
-
// Hebbian co-retrieval: strengthen edges between all pairs
|
|
139
|
-
let edgesReinforced = 0;
|
|
140
|
-
if (args.memoryIds.length > 1) {
|
|
141
|
-
let associations = readAssociations() || { version: 1, edges: {} };
|
|
142
|
-
|
|
143
|
-
for (let i = 0; i < args.memoryIds.length; i++) {
|
|
144
|
-
for (let j = i + 1; j < args.memoryIds.length; j++) {
|
|
145
|
-
const idA = args.memoryIds[i];
|
|
146
|
-
const idB = args.memoryIds[j];
|
|
147
|
-
// Only reinforce if both exist in index
|
|
148
|
-
if (index.memories[idA] && index.memories[idB]) {
|
|
149
|
-
reinforceEdge(associations, idA, idB, 'co_retrieval');
|
|
150
|
-
edgesReinforced++;
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
writeAssociations(associations);
|
|
156
|
-
}
|
|
157
|
-
|
|
158
48
|
// Injected-vs-used telemetry (src/surfaced.js): reinforce is the agent saying
|
|
159
49
|
// a memory shaped its answer.
|
|
160
|
-
recordUsed(brainDir, {
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}, null, 2));
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* Update a memory file's YAML frontmatter fields on disk.
|
|
170
|
-
*
|
|
171
|
-
* @param {string} brainDir - Path to ~/.brain/
|
|
172
|
-
* @param {string} memPath - Relative path to memory file
|
|
173
|
-
* @param {Object} updates - Fields to update in frontmatter
|
|
174
|
-
*/
|
|
175
|
-
function updateMemoryFile(brainDir, memPath, updates) {
|
|
176
|
-
const fullPath = path.join(brainDir, memPath);
|
|
177
|
-
try {
|
|
178
|
-
// The path comes from index.json — which syncs across devices, so a
|
|
179
|
-
// tampered index entry must not become a write primitive outside ~/.brain.
|
|
180
|
-
validateBrainPath(fullPath, brainDir);
|
|
181
|
-
let content = fs.readFileSync(fullPath, 'utf-8');
|
|
182
|
-
|
|
183
|
-
// Find frontmatter boundaries
|
|
184
|
-
const firstDash = content.indexOf('---');
|
|
185
|
-
const secondDash = content.indexOf('---', firstDash + 3);
|
|
186
|
-
if (firstDash === -1 || secondDash === -1) return;
|
|
187
|
-
|
|
188
|
-
let frontmatter = content.slice(firstDash + 3, secondDash);
|
|
189
|
-
|
|
190
|
-
// Update each field in the YAML
|
|
191
|
-
for (const [key, value] of Object.entries(updates)) {
|
|
192
|
-
const regex = new RegExp(`^(${key}:\\s*).*$`, 'm');
|
|
193
|
-
// Arrays and objects must be JSON-encoded: `String(value)` renders an
|
|
194
|
-
// array of objects as "[object Object]", which is both lossy and invalid
|
|
195
|
-
// YAML. JSON is a YAML subset, so a flow-style array round-trips cleanly.
|
|
196
|
-
const formatted = typeof value === 'string'
|
|
197
|
-
? `"${value}"`
|
|
198
|
-
: (value !== null && typeof value === 'object' ? JSON.stringify(value) : String(value));
|
|
199
|
-
if (regex.test(frontmatter)) {
|
|
200
|
-
frontmatter = frontmatter.replace(regex, `$1${formatted}`);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
50
|
+
recordUsed(brainDir, {
|
|
51
|
+
session: envSession(),
|
|
52
|
+
ids: result.reinforced.map((r) => r.id).filter(Boolean),
|
|
53
|
+
now: now.toISOString(),
|
|
54
|
+
});
|
|
203
55
|
|
|
204
|
-
|
|
205
|
-
fs.writeFileSync(fullPath, content);
|
|
206
|
-
} catch { /* skip if file not readable/writable */ }
|
|
56
|
+
console.log(JSON.stringify(result, null, 2));
|
|
207
57
|
}
|
|
208
58
|
|
|
209
59
|
/**
|
package/bin/session-start.js
CHANGED
|
@@ -17,7 +17,9 @@
|
|
|
17
17
|
* Output (JSON):
|
|
18
18
|
* {
|
|
19
19
|
* memory_count, pinned[], skills_index[], context_recall[],
|
|
20
|
-
* due_for_review, low_confidence_alerts[], budget{}
|
|
20
|
+
* due_for_review, low_confidence_alerts[], budget{},
|
|
21
|
+
* sleep_due? {due, days_since_last, memorized_since},
|
|
22
|
+
* unsaved_notables? {count, items[]}
|
|
21
23
|
* }
|
|
22
24
|
*
|
|
23
25
|
* pinned[] (Phase 1) and skills_index[] (Phase 2) are present but empty here;
|
|
@@ -41,6 +43,7 @@ const {
|
|
|
41
43
|
readAssociations,
|
|
42
44
|
readReviewQueue,
|
|
43
45
|
readConfig,
|
|
46
|
+
readContexts,
|
|
44
47
|
getBrainDir,
|
|
45
48
|
} = require('../src/index-manager');
|
|
46
49
|
|
|
@@ -122,6 +125,93 @@ function buildContextQuery(args) {
|
|
|
122
125
|
* @param {Object} [args] - { project, topics, task, top, budget }
|
|
123
126
|
* @returns {Object} The session-start payload
|
|
124
127
|
*/
|
|
128
|
+
// --- Maintenance signals -------------------------------------------------
|
|
129
|
+
//
|
|
130
|
+
// Sleep (consolidation, supersession sweep, pruning) is agent-driven, so it
|
|
131
|
+
// only runs when someone asks. In practice that meant three runs in eight
|
|
132
|
+
// months while ~50 memories a month arrived. These two signals let the agent
|
|
133
|
+
// offer it at the right moment instead of never.
|
|
134
|
+
const SLEEP_DUE_DAYS = 7;
|
|
135
|
+
const SLEEP_DUE_MIN_WRITES = 10;
|
|
136
|
+
const SLEEP_DUE_ANY_AGE_WRITES = 40;
|
|
137
|
+
const NOTABLE_WINDOW_DAYS = 14;
|
|
138
|
+
const NOTABLE_MAX_ITEMS = 3;
|
|
139
|
+
const NOTABLE_MAX_CHARS = 160;
|
|
140
|
+
|
|
141
|
+
/** Best-known instant of the last sleep cycle, or null. */
|
|
142
|
+
function lastSleepAt(brainDir, index) {
|
|
143
|
+
const candidates = [];
|
|
144
|
+
if (index && index.last_sleep) candidates.push(Date.parse(index.last_sleep));
|
|
145
|
+
try {
|
|
146
|
+
const raw = JSON.parse(fs.readFileSync(path.join(brainDir, 'sleep-log.json'), 'utf-8'));
|
|
147
|
+
if (raw && raw.last_sleep) candidates.push(Date.parse(raw.last_sleep));
|
|
148
|
+
} catch (_) { /* absent */ }
|
|
149
|
+
// Agents that ran sleep before it was tracked left timestamped backups.
|
|
150
|
+
try {
|
|
151
|
+
for (const name of fs.readdirSync(path.join(brainDir, '_sleep_backups'))) {
|
|
152
|
+
const m = /^(\d{4}-\d{2}-\d{2})T(\d{2})-(\d{2})-(\d{2})/.exec(name);
|
|
153
|
+
if (m) candidates.push(Date.parse(`${m[1]}T${m[2]}:${m[3]}:${m[4]}Z`));
|
|
154
|
+
}
|
|
155
|
+
} catch (_) { /* absent */ }
|
|
156
|
+
const valid = candidates.filter((t) => Number.isFinite(t));
|
|
157
|
+
return valid.length ? Math.max(...valid) : null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Whether a sleep cycle is overdue, with the numbers behind it. */
|
|
161
|
+
function sleepDue(brainDir, index, nowMs) {
|
|
162
|
+
const last = lastSleepAt(brainDir, index);
|
|
163
|
+
const since = last ?? 0;
|
|
164
|
+
let writes = 0;
|
|
165
|
+
for (const e of Object.values(index.memories || {})) {
|
|
166
|
+
if (Date.parse(e.created) > since) writes++;
|
|
167
|
+
}
|
|
168
|
+
const days = last == null ? null : Math.floor((nowMs - last) / 86400000);
|
|
169
|
+
const due = (days == null ? writes >= SLEEP_DUE_MIN_WRITES : days >= SLEEP_DUE_DAYS && writes >= SLEEP_DUE_MIN_WRITES)
|
|
170
|
+
|| writes >= SLEEP_DUE_ANY_AGE_WRITES;
|
|
171
|
+
return { due, days_since_last: days, memorized_since: writes };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Notable items recent sessions flagged but never memorized.
|
|
176
|
+
*
|
|
177
|
+
* contexts.json keeps a bounded window of sessions, and `notable_unsaved` was
|
|
178
|
+
* write-only: nothing ever read it back, so whatever a session judged worth
|
|
179
|
+
* keeping silently rotated out. Surfacing the newest few lets the next
|
|
180
|
+
* session offer to store them. A session counts as handled once a memory for
|
|
181
|
+
* the same project was written after it ended.
|
|
182
|
+
*/
|
|
183
|
+
function unsavedNotables(projectRoot, index, project, nowMs) {
|
|
184
|
+
let sessions = [];
|
|
185
|
+
try {
|
|
186
|
+
const ctx = readContexts(projectRoot);
|
|
187
|
+
sessions = Array.isArray(ctx) ? ctx : (ctx && Array.isArray(ctx.sessions) ? ctx.sessions : []);
|
|
188
|
+
} catch (_) { return null; }
|
|
189
|
+
let lastWrite = 0;
|
|
190
|
+
for (const e of Object.values(index.memories || {})) {
|
|
191
|
+
const p = (e.encoding_context || {}).project;
|
|
192
|
+
if (project && p !== project) continue;
|
|
193
|
+
const t = Date.parse(e.created);
|
|
194
|
+
if (t > lastWrite) lastWrite = t;
|
|
195
|
+
}
|
|
196
|
+
const items = [];
|
|
197
|
+
let total = 0;
|
|
198
|
+
for (let i = sessions.length - 1; i >= 0; i--) {
|
|
199
|
+
const s = sessions[i] || {};
|
|
200
|
+
if (project && s.project !== project) continue;
|
|
201
|
+
const ended = Date.parse(s.ended);
|
|
202
|
+
if (!Number.isFinite(ended) || nowMs - ended > NOTABLE_WINDOW_DAYS * 86400000) continue;
|
|
203
|
+
if (ended <= lastWrite) continue;
|
|
204
|
+
for (const n of Array.isArray(s.notable_unsaved) ? s.notable_unsaved : []) {
|
|
205
|
+
if (typeof n !== 'string' || !n.trim()) continue;
|
|
206
|
+
total++;
|
|
207
|
+
if (items.length < NOTABLE_MAX_ITEMS) {
|
|
208
|
+
items.push(n.length > NOTABLE_MAX_CHARS ? `${n.slice(0, NOTABLE_MAX_CHARS - 1)}…` : n);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return total ? { count: total, items } : null;
|
|
213
|
+
}
|
|
214
|
+
|
|
125
215
|
function computeSessionStart(projectRoot, args = {}) {
|
|
126
216
|
const top = args.top || 5;
|
|
127
217
|
const brainDir = getBrainDir(projectRoot);
|
|
@@ -340,6 +430,16 @@ function computeSessionStart(projectRoot, args = {}) {
|
|
|
340
430
|
low_confidence_alerts,
|
|
341
431
|
// Low-trust memories held out of context_recall by recall_low_trust_max.
|
|
342
432
|
...(lowTrustSuppressed > 0 ? { low_trust_suppressed: lowTrustSuppressed } : {}),
|
|
433
|
+
// Maintenance prompts — see sleepDue / unsavedNotables above.
|
|
434
|
+
...(() => {
|
|
435
|
+
const nowMs = Date.now();
|
|
436
|
+
const extra = {};
|
|
437
|
+
const sd = sleepDue(getBrainDir(projectRoot), index, nowMs);
|
|
438
|
+
if (sd.due) extra.sleep_due = sd;
|
|
439
|
+
const un = unsavedNotables(projectRoot, index, args.project || null, nowMs);
|
|
440
|
+
if (un) extra.unsaved_notables = un;
|
|
441
|
+
return extra;
|
|
442
|
+
})(),
|
|
343
443
|
// How much of what brain surfaced over the last week the agent used
|
|
344
444
|
// (src/surfaced.js) — injected-vs-used telemetry.
|
|
345
445
|
recall_usage_7d: usageSummary(getBrainDir(projectRoot), { sinceMs: Date.now() - 7 * 86400000 }),
|
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.1",
|
|
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 };
|
package/src/surfaced.js
CHANGED
|
@@ -136,6 +136,37 @@ function checkCitations(brainDir, { session, text, nowMs }) {
|
|
|
136
136
|
return { cited, unsurfaced: [...new Set(cited.filter((t) => !seen.has(t)))] };
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
/**
|
|
140
|
+
* Ids of memories a reply cited with a verified receipt that have not yet been
|
|
141
|
+
* reinforced in this session — the Stop hook's implicit "used" signal.
|
|
142
|
+
*
|
|
143
|
+
* A receipt says the memory shaped the answer, and the citation lock already
|
|
144
|
+
* checks it against what was surfaced, so it is a better usage signal than an
|
|
145
|
+
* explicit `brain reinforce` the agent rarely remembers to run. Each memory is
|
|
146
|
+
* reinforced at most once per session (once per window when unscoped): citing
|
|
147
|
+
* the same memory in five consecutive replies is one recall, not five, and
|
|
148
|
+
* repeated boosts would inflate strength the way homeostasis exists to stop.
|
|
149
|
+
*
|
|
150
|
+
* @param {string} brainDir
|
|
151
|
+
* @param {Object} opts - { session, text, nowMs }
|
|
152
|
+
* @returns {string[]}
|
|
153
|
+
*/
|
|
154
|
+
function citedUnreinforcedIds(brainDir, { session, text, nowMs }) {
|
|
155
|
+
const cited = new Set(citedTitles(text));
|
|
156
|
+
if (!cited.size) return [];
|
|
157
|
+
const now = nowMs ?? Date.now();
|
|
158
|
+
const inScope = (e) => (session && e.session === session)
|
|
159
|
+
|| (!e.session && now - Date.parse(e.ts) <= UNSCOPED_WINDOW_MS);
|
|
160
|
+
const byTitle = new Map();
|
|
161
|
+
const used = new Set();
|
|
162
|
+
for (const e of readLedger(brainDir)) {
|
|
163
|
+
if (!inScope(e)) continue;
|
|
164
|
+
if (e.kind === 'surfaced' && e.id && cited.has(e.title)) byTitle.set(e.title, e.id);
|
|
165
|
+
else if (e.kind === 'used' && e.id) used.add(e.id);
|
|
166
|
+
}
|
|
167
|
+
return [...new Set(byTitle.values())].filter((id) => !used.has(id));
|
|
168
|
+
}
|
|
169
|
+
|
|
139
170
|
/** Violations recorded for a session since its last ack. */
|
|
140
171
|
function pendingViolations(brainDir, session) {
|
|
141
172
|
if (!session) return [];
|
|
@@ -183,6 +214,7 @@ module.exports = {
|
|
|
183
214
|
receiptTitle,
|
|
184
215
|
citedTitles,
|
|
185
216
|
checkCitations,
|
|
217
|
+
citedUnreinforcedIds,
|
|
186
218
|
pendingViolations,
|
|
187
219
|
usageSummary,
|
|
188
220
|
};
|