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 CHANGED
@@ -6,6 +6,92 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/), and this
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.6.2] - 2026-11-16
10
+
11
+ Writes are safe to repeat, and two memories can no longer share a file.
12
+
13
+ ### Fixed
14
+ - **A second memory with the same path no longer overwrites the first.** Two
15
+ memories with the same title derive the same file path; the second write
16
+ replaced the first one's file while both stayed in the index, so the older
17
+ memory's content was lost and its id pointed at the newer text. The second
18
+ memory now gets its own file (`<name>-<id suffix>.md`). Most exposed through
19
+ the connector, which derives the path from the title.
20
+
21
+ ### Added
22
+ - **Replayed writes are recognised.** A `memorize` that repeats one from the
23
+ last ten minutes — same title, type, origin, path and content — returns the
24
+ memory already stored, marked `duplicate: true`, instead of storing it again.
25
+ This covers a client retrying after a timeout and a host executing an approved
26
+ tool call twice. `brain forget` on a memory that is already archived now
27
+ reports `already_archived` instead of failing. The connector says "Already
28
+ stored" / "Already archived" for these.
29
+ - **Connector: the Memory Inspector follows the MCP Apps specification.** With
30
+ `CONNECTOR_ENABLE_UI=1`, `brain_verify` links a view (`ui://brain/inspector`,
31
+ `text/html;profile=mcp-app`) that shows the review queue: each memory held
32
+ for verification, its origin and why it was held. The view is read-only —
33
+ approving and rejecting stay in the conversation. On for the hosted connector
34
+ (mcp.brainmemory.ai); off by default when self-hosting.
35
+ - **Docs: importing brain memories into Codex** via the `claude-memory` export.
36
+
37
+ ### Changed
38
+ - **Connector deploy installs from the lock file** (`npm ci`), so a deploy
39
+ cannot pick up a dependency version that was not tested.
40
+
41
+ ## [0.6.1] - 2026-11-10
42
+
43
+ First npm release of the 0.6.0 work: 0.6.0 was tagged but never published, so
44
+ everything listed under 0.6.0 below reaches npm with this version.
45
+
46
+ ### Changed
47
+ - **README: November 2026 benchmark results.** The benchmark section now
48
+ reports the confirmatory run — Claude Sonnet 5.5 under test, N=10 per arm,
49
+ a Gemini 3.5 Flash + Gemini 2.5 Pro + DeepSeek V4 Pro judge panel — across
50
+ scenarios A–D, F and the new poisoned-haystack scenario G, replacing the
51
+ June n=3 numbers. Full tables and raw JSON:
52
+ [brainmemory.ai/docs/benchmarks/results](https://brainmemory.ai/docs/benchmarks/results/).
53
+
54
+ ## [0.6.0] - 2026-11-09
55
+
56
+ Memories you actually use now get stronger, and stale facts can be retired.
57
+ An audit of a real seven-month brain found the cognition loop idle: agents
58
+ were shown memories 328 times and reported using them zero times, so 93% of
59
+ memories had never been reinforced, while contradicting facts piled up with
60
+ nothing to retire them.
61
+
62
+ ### Added
63
+ - **Receipts reinforce automatically.** When a reply cites a memory with a
64
+ `◉ memory:` receipt that checks out against what brain surfaced, the Stop
65
+ hook applies spaced reinforcement to it (once per session), with Hebbian
66
+ co-retrieval between memories cited together. No more relying on the agent
67
+ to remember `brain reinforce`.
68
+ - **`brain supersede <old>... --by <new>`.** Mark an existing memory as ended
69
+ by a newer one that is already stored: stamps `superseded_by` and
70
+ `valid_until` (the successor's start, or `--valid-until`), records
71
+ `supersedes` on the successor, links the pair and logs the change.
72
+ `--dry-run` previews.
73
+ - **Sleep: supersession sweep (Phase 6b).** Sleep now looks for still-strong
74
+ facts a newer memory replaced and, with approval, bounds them with
75
+ `brain supersede`. Sleep also records its run in `~/.brain/sleep-log.json`.
76
+ - **`💤 sleep due` and `📝 unsaved notables` at session start.**
77
+ `brain session-start` reports `sleep_due` after a week with 10+ new memories,
78
+ and `unsaved_notables`: items recent sessions flagged in `notable_unsaved`
79
+ that no later write picked up, so they can be offered for storage instead of
80
+ silently rotating out.
81
+
82
+ ### Changed
83
+ - **Contradiction candidates include restated facts.** `memorize` now also
84
+ proposes same-project memories whose text is closest to the new one, so a
85
+ fact restated in different words and tags (a domain migration, a new deploy
86
+ path) is flagged, not only tag overlaps.
87
+ - **`contexts.json` keeps 100 sessions, not 20,** in the plugin hook and every
88
+ host integration. Twenty was about three days of history for an active user.
89
+
90
+ ### Fixed
91
+ - **Associations written in flat form now take part in recall.** Agent-run
92
+ sleep cycles could write edges as `"a::b"` keys, which spreading activation
93
+ never read. They are folded into the nested edge map on load.
94
+
9
95
  ## [0.5.2] - 2026-11-08
10
96
 
11
97
  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 **DeepSeek V4 Pro** (single-shot), graded by a **cross-family judge panel** (Gemini + Gemma-4 + Qwen-3.5, 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)); deterministic distractor haystacks up to 1000 memories; real `brain session-start` / `brain recall` integration; tokens-per-successful-task as the headline efficiency metric; every scenario anchored by a no-memory floor and an oracle ceiling.
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 (DeepSeek V4 Pro, 3 runs/arm, June 2026). **Scenario A — retrieval under 1000 distractors:** `brain-full` is the only retriever whose memories let the model succeed — it passes **100%** while both **BM25 (0%)** and a **vector store (0%)** fail to surface the oracle memories — and it does so at the **leanest tokens-per-success (3,199)** of any passing arm. **Scenario D — skills:** loading only the relevant skill passes 100% at **1,580 tok/success, ~31% leaner** than dumping all skill bodies. Scenarios B (continuity) shows brain efficient-and-correct; C (contradiction) and F (abstention) are honest **nulls** — the base model handles them without memory. At n=3 the token gaps are directional, not yet significant; the pass-rate gradient is the result. Full tables: [brainmemory.ai/docs/benchmarks/results](https://brainmemory.ai/docs/benchmarks/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/forget.js CHANGED
@@ -58,7 +58,21 @@ function archiveMemory(brainDir, id, opts = {}) {
58
58
  const index = readIndex();
59
59
  if (!index) return { error: 'Brain not initialized.' };
60
60
  const entry = index.memories[id];
61
- if (!entry) return { error: `Memory not found: ${id}` };
61
+ if (!entry) {
62
+ // Archiving is repeatable: a second call for a memory already in the
63
+ // archive (a retried or replayed tool call) reports the state it asked for.
64
+ const archivedEntry = (readArchiveIndex() || { memories: {} }).memories[id];
65
+ if (archivedEntry) {
66
+ return {
67
+ archived: true,
68
+ already_archived: true,
69
+ id,
70
+ title: archivedEntry.title,
71
+ memory_count: index.memory_count,
72
+ };
73
+ }
74
+ return { error: `Memory not found: ${id}` };
75
+ }
62
76
 
63
77
  if (!force && typeof entry.salience === 'number' && entry.salience >= SALIENCE_FLOOR) {
64
78
  return {
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
 
@@ -406,6 +437,52 @@ function trySync() {
406
437
 
407
438
  // --- Main ---
408
439
 
440
+ // --- Replay protection -------------------------------------------------------
441
+ //
442
+ // A tool call can be executed twice: a client retries after a timeout, or a host
443
+ // replays an approved write. Without a guard the second run stores the same
444
+ // memory again under a new id. A write is treated as a replay — and answered
445
+ // with the memory already stored — when title, type, origin, path and content
446
+ // all match a memory created inside this window. Outside it, storing the same
447
+ // text again is taken to be deliberate.
448
+ const REPLAY_WINDOW_MS = 10 * 60 * 1000;
449
+
450
+ function bodyHash(content) {
451
+ return contentHash(String(content).trim());
452
+ }
453
+
454
+ /** The id of a just-stored memory this write repeats, or null. */
455
+ function findReplay(index, mem, origin, hash, now) {
456
+ const nowMs = Date.parse(now);
457
+ for (const [id, entry] of Object.entries(index.memories || {})) {
458
+ if (entry.body_hash !== hash) continue;
459
+ if (entry.title !== mem.title || entry.type !== mem.type || entry.origin !== origin) continue;
460
+ // The first write may have been moved off an occupied path (uniquePath).
461
+ if (entry.path !== mem.path && entry.path !== suffixedPath(mem.path, id)) continue;
462
+ const age = nowMs - Date.parse(entry.created);
463
+ if (age >= 0 && age <= REPLAY_WINDOW_MS) return id;
464
+ }
465
+ return null;
466
+ }
467
+
468
+ /** `notes/x.md` → `notes/x-<id suffix>.md`. */
469
+ function suffixedPath(relPath, id) {
470
+ const ext = path.posix.extname(relPath);
471
+ return `${relPath.slice(0, relPath.length - ext.length)}-${id.split('_').pop()}${ext}`;
472
+ }
473
+
474
+ /**
475
+ * A path no other memory occupies. Two memories with the same title derive the
476
+ * same path; writing the second over the first would destroy the first one's
477
+ * content while its index entry lived on, pointing at the wrong file.
478
+ */
479
+ function uniquePath(brainDir, index, relPath, id) {
480
+ const taken = (p) =>
481
+ fs.existsSync(path.join(brainDir, p)) ||
482
+ Object.values(index.memories || {}).some((e) => e.path === p);
483
+ return taken(relPath) ? suffixedPath(relPath, id) : relPath;
484
+ }
485
+
409
486
  async function main() {
410
487
  const args = parseArgs(process.argv.slice(2));
411
488
 
@@ -559,10 +636,42 @@ async function main() {
559
636
  const pinDropped = Boolean(mem.pinned && quarantine.quarantined);
560
637
  if (pinDropped) mem.pinned = false;
561
638
 
639
+ // Replay protection: an identical write that just landed is answered with
640
+ // the memory already stored, not stored again.
641
+ const hash = bodyHash(mem.content);
642
+ const replayId = findReplay(index, mem, origin, hash, now);
643
+ if (replayId) {
644
+ const prior = index.memories[replayId];
645
+ results.push({
646
+ id: replayId,
647
+ title: prior.title,
648
+ path: prior.path,
649
+ type: prior.type,
650
+ cognitive_type: prior.cognitive_type,
651
+ strength: prior.strength,
652
+ decay_rate: prior.decay_rate,
653
+ origin: prior.origin,
654
+ salience: prior.salience,
655
+ confidence: prior.confidence,
656
+ tags: prior.tags || [],
657
+ edges_created: 0,
658
+ duplicate: true,
659
+ ...(prior.quarantined
660
+ ? { quarantine_pending: true, quarantine_reasons: prior.quarantine_reasons || [] }
661
+ : {}),
662
+ });
663
+ continue;
664
+ }
665
+
562
666
  // Generate ID
563
667
  const id = generateId();
564
668
  newIds.push(id);
565
669
 
670
+ // Validated before it is made unique, so a traversal attempt is refused
671
+ // rather than renamed.
672
+ validateBrainPath(path.join(brainDir, mem.path), brainDir);
673
+ mem.path = uniquePath(brainDir, index, mem.path, id);
674
+
566
675
  // Compute strength/decay
567
676
  const { fileContent, strength, decay_rate } = buildMemoryFileContent(
568
677
  mem, id, now, origin, policy.policy.decay_multiplier, quarantine
@@ -610,6 +719,8 @@ async function main() {
610
719
  // never came through a write path — the one poisoning route every other
611
720
  // defense here is blind to. See src/integrity.js.
612
721
  indexEntry.content_hash = contentHash(fileContent);
722
+ // The content alone, so a repeat of this write can be recognised.
723
+ indexEntry.body_hash = hash;
613
724
  addMemory(index, id, indexEntry);
614
725
 
615
726
  // CoALA Phase 1: register a born-pinned memory in the pinned manifest
@@ -667,7 +778,7 @@ async function main() {
667
778
  const potentialConflicts = proposeSupersessions(
668
779
  index,
669
780
  { ...mem, created: now },
670
- tagOverlaps,
781
+ [...new Set([...tagOverlaps, ...findTextNeighbors(searchIndex, index, mem, id)])],
671
782
  { now },
672
783
  );
673
784
 
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
- readIndex,
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
- let index;
36
+ const now = new Date();
37
+ let result;
57
38
  try {
58
- index = readIndex();
39
+ result = reinforceMemories(args.memoryIds, { now, brainDir });
59
40
  } catch (err) {
60
- console.error(JSON.stringify({
61
- error: `Corrupt index.json in ~/.brain/ — ${err.message}. Fix the JSON manually or restore from sync/backup.`,
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, { session: envSession(), ids: reinforced.map((r) => r.id).filter(Boolean), now: nowISO });
161
-
162
- console.log(JSON.stringify({
163
- reinforced,
164
- edges_reinforced: edgesReinforced,
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
- content = content.slice(0, firstDash + 3) + frontmatter + content.slice(secondDash);
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
  /**
@@ -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 }),