@nxuss/lemma 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/bin/init.js +4 -0
  2. package/dist/cjs/mcp/tools.d.ts.map +1 -1
  3. package/dist/cjs/mcp/tools.js +279 -9
  4. package/dist/cjs/mcp/tools.js.map +1 -1
  5. package/dist/cjs/mcp/utils.d.ts.map +1 -1
  6. package/dist/cjs/mcp/utils.js +21 -2
  7. package/dist/cjs/mcp/utils.js.map +1 -1
  8. package/dist/cjs/pr-review/bridge/BrainBridge.js +1 -1
  9. package/dist/cjs/pr-review/bridge/BrainBridge.js.map +1 -1
  10. package/dist/cjs/subconscious/BrainEmbeddings.d.ts +59 -0
  11. package/dist/cjs/subconscious/BrainEmbeddings.d.ts.map +1 -0
  12. package/dist/cjs/subconscious/BrainEmbeddings.js +222 -0
  13. package/dist/cjs/subconscious/BrainEmbeddings.js.map +1 -0
  14. package/dist/cjs/subconscious/GitIngest.js +2 -2
  15. package/dist/cjs/subconscious/GitIngest.js.map +1 -1
  16. package/dist/cjs/subconscious/TheBrainV2.d.ts +284 -2
  17. package/dist/cjs/subconscious/TheBrainV2.d.ts.map +1 -1
  18. package/dist/cjs/subconscious/TheBrainV2.js +871 -46
  19. package/dist/cjs/subconscious/TheBrainV2.js.map +1 -1
  20. package/dist/cjs/utils/ConversationCheckpoint.js +1 -1
  21. package/dist/cjs/utils/ConversationCheckpoint.js.map +1 -1
  22. package/dist/esm/mcp/tools.d.ts.map +1 -1
  23. package/dist/esm/mcp/tools.js +280 -10
  24. package/dist/esm/mcp/tools.js.map +1 -1
  25. package/dist/esm/mcp/utils.d.ts.map +1 -1
  26. package/dist/esm/mcp/utils.js +21 -2
  27. package/dist/esm/mcp/utils.js.map +1 -1
  28. package/dist/esm/pr-review/bridge/BrainBridge.js +1 -1
  29. package/dist/esm/pr-review/bridge/BrainBridge.js.map +1 -1
  30. package/dist/esm/subconscious/BrainEmbeddings.d.ts +59 -0
  31. package/dist/esm/subconscious/BrainEmbeddings.d.ts.map +1 -0
  32. package/dist/esm/subconscious/BrainEmbeddings.js +211 -0
  33. package/dist/esm/subconscious/BrainEmbeddings.js.map +1 -0
  34. package/dist/esm/subconscious/GitIngest.js +2 -2
  35. package/dist/esm/subconscious/GitIngest.js.map +1 -1
  36. package/dist/esm/subconscious/TheBrainV2.d.ts +284 -2
  37. package/dist/esm/subconscious/TheBrainV2.d.ts.map +1 -1
  38. package/dist/esm/subconscious/TheBrainV2.js +866 -46
  39. package/dist/esm/subconscious/TheBrainV2.js.map +1 -1
  40. package/dist/esm/utils/ConversationCheckpoint.js +1 -1
  41. package/dist/esm/utils/ConversationCheckpoint.js.map +1 -1
  42. package/package.json +1 -1
@@ -13,10 +13,25 @@ import fs from 'fs';
13
13
  import path from 'path';
14
14
  import os from 'os';
15
15
  import crypto from 'crypto';
16
+ import { execSync } from 'child_process';
16
17
  import { getSymbolSurgicalContext, normalizeForFreshness } from '../utils/SymbolSurgicalContext.js';
18
+ import { EmbeddingSidecar, embeddingsEnabled, semanticRerank } from './BrainEmbeddings.js';
17
19
  // ─── BM25 Constants ───────────────────────────────────────────────────────────
18
20
  const BM25_K1 = 1.5; // Term saturation (1.2-2.0)
19
21
  const BM25_B = 0.75; // Length normalization (0-1)
22
+ // ─── Recency decay ────────────────────────────────────────────────────────────
23
+ //
24
+ // Deliberately gentle and grace-periodded. Age is a weak proxy for "no longer true" —
25
+ // plenty of architectural decisions stay correct for years — so this is sized to break ties
26
+ // between comparable memories, not to bury an old one that is still the best match. A
27
+ // memory that goes stale is caught by hashing, which is the real signal; this only covers
28
+ // the case hashing can't see, where a memory tracks no files at all.
29
+ /** Days a memory is treated as current with no penalty at all. */
30
+ const RECENCY_GRACE_DAYS = 30;
31
+ /** Days past the grace period at which the penalty reaches its cap. */
32
+ const RECENCY_FULL_DECAY_DAYS = 365;
33
+ /** Cap, in the same 0-1 similarity space as the popularity/outcome/demerit adjustments. */
34
+ const MAX_RECENCY_PENALTY = 0.10;
20
35
  // ─── Storage Paths ────────────────────────────────────────────────────────────
21
36
  /**
22
37
  * LEMMA_BRAIN_DIR redirects storage — required so tests never write into the user's real
@@ -27,6 +42,273 @@ const BRAIN_DIR = process.env.LEMMA_BRAIN_DIR || path.join(os.homedir(), '.lemma
27
42
  const ENTRIES_FILE = path.join(BRAIN_DIR, 'entries.ndjson');
28
43
  const INDEX_FILE = path.join(BRAIN_DIR, 'index.json');
29
44
  const META_FILE = path.join(BRAIN_DIR, 'meta.json');
45
+ /** Advisory cross-process write lock. See acquireLock() for why it is advisory, not a guarantee. */
46
+ const LOCK_FILE = path.join(BRAIN_DIR, '.write.lock');
47
+ /** Sidecar vector cache for the optional semantic re-rank. See BrainEmbeddings.ts. */
48
+ const EMBEDDINGS_FILE = path.join(BRAIN_DIR, 'embeddings.ndjson');
49
+ // ─── Cross-process durability ─────────────────────────────────────────────────
50
+ //
51
+ // Every MCP client session starts its own server process, and each one holds the whole
52
+ // corpus in memory. Before this section existed, save() blind-rewrote entries.ndjson in
53
+ // full: two concurrent sessions meant whichever flushed last silently erased everything the
54
+ // other had stored since it loaded. That is the exact usage pattern the tool descriptions
55
+ // advertise ("memories from ALL your projects"), so it was not a rare race.
56
+ //
57
+ // Three things fix it, and none of them require a database:
58
+ // 1. save() merges what is on disk into memory before writing, so a full rewrite can only
59
+ // ever be a superset — a writer can add, never subtract (except via tombstones).
60
+ // 2. Writes go through a temp file + rename, so a crash mid-write can't truncate the
61
+ // corpus into something load() would discard as "corrupt, start fresh".
62
+ // 3. An advisory lock file serializes the read-merge-write window between processes.
63
+ // Reads get the same benefit through syncIfChanged(): a long-lived server picks up a
64
+ // sibling session's memories on the next search instead of at the next restart.
65
+ /** A lock older than this is assumed to belong to a process that died holding it. */
66
+ const LOCK_STALE_MS = 10000;
67
+ /** How long a writer waits for another process's lock before proceeding regardless. */
68
+ const LOCK_WAIT_MS = 2000;
69
+ /** Deleted ids stop being suppressed after this long — a tombstone list must not grow forever. */
70
+ const TOMBSTONE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
71
+ /** Blocking sleep. save() is synchronous and its callers must never observe a partial corpus. */
72
+ function sleepSync(ms) {
73
+ try {
74
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
75
+ }
76
+ catch {
77
+ // SharedArrayBuffer unavailable (locked-down runtime) — spin instead of failing.
78
+ const until = Date.now() + ms;
79
+ while (Date.now() < until) { /* busy wait */ }
80
+ }
81
+ }
82
+ /**
83
+ * Take the write lock, or give up after LOCK_WAIT_MS and return null.
84
+ *
85
+ * Deliberately advisory and fail-open: a caller that can't get the lock still writes. The
86
+ * merge in save() is what actually prevents data loss; the lock only narrows the window
87
+ * where two mergers interleave. Blocking a memory write forever on a lock — or throwing —
88
+ * would be a worse outcome than the rare interleave it prevents.
89
+ */
90
+ function acquireLock() {
91
+ const deadline = Date.now() + LOCK_WAIT_MS;
92
+ for (;;) {
93
+ try {
94
+ return fs.openSync(LOCK_FILE, 'wx');
95
+ }
96
+ catch {
97
+ try {
98
+ if (Date.now() - fs.statSync(LOCK_FILE).mtimeMs > LOCK_STALE_MS) {
99
+ fs.unlinkSync(LOCK_FILE);
100
+ continue; // retry immediately against the freed lock
101
+ }
102
+ }
103
+ catch {
104
+ continue; // lock vanished between open and stat — the holder just released it
105
+ }
106
+ if (Date.now() >= deadline)
107
+ return null;
108
+ sleepSync(15);
109
+ }
110
+ }
111
+ }
112
+ function releaseLock(fd) {
113
+ if (fd === null)
114
+ return;
115
+ try {
116
+ fs.closeSync(fd);
117
+ }
118
+ catch { /* already closed */ }
119
+ try {
120
+ fs.unlinkSync(LOCK_FILE);
121
+ }
122
+ catch { /* already gone */ }
123
+ }
124
+ /**
125
+ * Write via temp file + rename. rename(2) is atomic within a filesystem, so a reader either
126
+ * sees the whole previous file or the whole new one — never a truncated prefix, which
127
+ * load()'s catch-all would have silently turned into an empty Brain.
128
+ */
129
+ function writeFileAtomic(target, data) {
130
+ const tmp = `${target}.tmp.${process.pid}.${Date.now().toString(36)}`;
131
+ try {
132
+ fs.writeFileSync(tmp, data, 'utf8');
133
+ fs.renameSync(tmp, target);
134
+ }
135
+ catch (err) {
136
+ try {
137
+ fs.unlinkSync(tmp);
138
+ }
139
+ catch { /* nothing to clean up */ }
140
+ throw err;
141
+ }
142
+ }
143
+ function stampOf(file) {
144
+ try {
145
+ const s = fs.statSync(file);
146
+ return { mtimeMs: s.mtimeMs, size: s.size };
147
+ }
148
+ catch {
149
+ return null;
150
+ }
151
+ }
152
+ function sameStamp(a, b) {
153
+ if (a === null || b === null)
154
+ return a === b;
155
+ return a.mtimeMs === b.mtimeMs && a.size === b.size;
156
+ }
157
+ /** Parses entries.ndjson exactly the way load() does, without touching instance state. */
158
+ function readEntriesFile() {
159
+ const out = new Map();
160
+ let raw;
161
+ try {
162
+ raw = fs.readFileSync(ENTRIES_FILE, 'utf8');
163
+ }
164
+ catch {
165
+ return out;
166
+ }
167
+ for (const line of raw.split('\n')) {
168
+ if (!line)
169
+ continue;
170
+ try {
171
+ const entry = JSON.parse(line);
172
+ if (!entry || typeof entry.id !== 'string')
173
+ continue;
174
+ // Entries written before the format was compacted still carry `terms`; newer ones
175
+ // don't. Rebuilding from termFreq covers both without a migration step.
176
+ if (!Array.isArray(entry.terms))
177
+ entry.terms = Object.keys(entry.termFreq || {});
178
+ out.set(entry.id, entry);
179
+ }
180
+ catch { /* skip corrupt lines */ }
181
+ }
182
+ return out;
183
+ }
184
+ /** Reads the tombstone map straight off disk, for absorbing a peer process's deletions. */
185
+ function readTombstonesFile() {
186
+ try {
187
+ return readTombstones(JSON.parse(fs.readFileSync(META_FILE, 'utf8')));
188
+ }
189
+ catch {
190
+ return new Map();
191
+ }
192
+ }
193
+ /** Reads the tombstone map out of a parsed meta.json, tolerating older files without one. */
194
+ function readTombstones(meta) {
195
+ const out = new Map();
196
+ const raw = meta?.tombstones;
197
+ if (!raw || typeof raw !== 'object')
198
+ return out;
199
+ for (const [id, at] of Object.entries(raw)) {
200
+ if (typeof at === 'string')
201
+ out.set(id, at);
202
+ }
203
+ return out;
204
+ }
205
+ /** Effective age anchor: a refreshed memory is as young as its last re-verification. */
206
+ function effectiveTime(entry) {
207
+ const t = Date.parse(entry.refreshedAt || entry.timestamp || '');
208
+ return Number.isFinite(t) ? t : 0;
209
+ }
210
+ /**
211
+ * Union two views of the corpus. Never subtracts: an id present in either side survives
212
+ * unless it is tombstoned, because "absent from my copy" and "deleted" are indistinguishable
213
+ * from inside one process, and guessing wrong loses a user's memory permanently.
214
+ *
215
+ * For an id on both sides, the newer version (by refreshedAt/timestamp) supplies the content
216
+ * and the counters take the max of both — `hits` and `demerits` are monotonic tallies that
217
+ * each process accumulated independently, so max is the only merge that doesn't discard
218
+ * feedback one of them collected.
219
+ */
220
+ export function mergeEntryMaps(mine, theirs, tombstones = new Set()) {
221
+ const merged = new Map();
222
+ const put = (entry) => {
223
+ if (tombstones.has(entry.id))
224
+ return;
225
+ const existing = merged.get(entry.id);
226
+ if (!existing) {
227
+ merged.set(entry.id, entry);
228
+ return;
229
+ }
230
+ const winner = effectiveTime(entry) > effectiveTime(existing) ? entry : existing;
231
+ merged.set(entry.id, {
232
+ ...winner,
233
+ hits: Math.max(entry.hits || 0, existing.hits || 0),
234
+ demerits: Math.max(entry.demerits || 0, existing.demerits || 0),
235
+ });
236
+ };
237
+ for (const entry of mine.values())
238
+ put(entry);
239
+ for (const entry of theirs.values())
240
+ put(entry);
241
+ return merged;
242
+ }
243
+ // ─── Git context ──────────────────────────────────────────────────────────────
244
+ /**
245
+ * Current HEAD and branch, cached briefly.
246
+ *
247
+ * Read at store time and again when reporting a stale result, so the Brain can tell
248
+ * "someone edited this function" apart from "you switched branches" — a content hash
249
+ * reports both identically, and only the first is a reason to distrust the memory.
250
+ *
251
+ * Cached because a stale result is attributed inside the search result loop: without it,
252
+ * one search over five stale hits would spawn ten git processes.
253
+ */
254
+ const GIT_CONTEXT_TTL_MS = 5000;
255
+ let _gitContextCache = null;
256
+ export function currentGitContext(cwd = process.cwd()) {
257
+ const now = Date.now();
258
+ if (_gitContextCache && _gitContextCache.cwd === cwd && now - _gitContextCache.at < GIT_CONTEXT_TTL_MS) {
259
+ return _gitContextCache.ctx;
260
+ }
261
+ let ctx = {};
262
+ try {
263
+ // Not a git repo, no git binary, detached worktree — all of these must produce {} and
264
+ // never throw. Git context is an explanatory nicety; nothing depends on it existing.
265
+ const run = (args) => execSync(`git ${args}`, { cwd, encoding: 'utf8', timeout: 1500, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
266
+ const commit = run('rev-parse HEAD');
267
+ const branch = run('rev-parse --abbrev-ref HEAD');
268
+ ctx = {
269
+ ...(commit ? { commit } : {}),
270
+ // "HEAD" is what git reports in a detached checkout — not a branch name, so don't
271
+ // record it as one and later claim the user "switched branches" away from it.
272
+ ...(branch && branch !== 'HEAD' ? { branch } : {}),
273
+ };
274
+ }
275
+ catch {
276
+ ctx = {};
277
+ }
278
+ _gitContextCache = { cwd, at: now, ctx };
279
+ return ctx;
280
+ }
281
+ /** Test seam: forget the cached git context so a test can change branches mid-run. */
282
+ export function resetGitContextCache() {
283
+ _gitContextCache = null;
284
+ }
285
+ /**
286
+ * Why a stale entry is stale. Pure attribution over data already gathered — it never
287
+ * changes whether something is stale, only how the staleness is explained.
288
+ */
289
+ export function attributeStaleness(entry, git) {
290
+ if (entry.gitBranch && git.branch && entry.gitBranch !== git.branch) {
291
+ return { staleCause: 'branch-changed', storedOnBranch: entry.gitBranch };
292
+ }
293
+ return { staleCause: 'content-changed' };
294
+ }
295
+ /**
296
+ * Normalized provenance for an entry, back-deriving one for entries written before `source`
297
+ * existed. Those overloaded the free-text `provider` field with the same information, so
298
+ * reading it here keeps historical stats meaningful instead of a wall of "unknown".
299
+ */
300
+ export function entrySource(entry) {
301
+ if (entry.source)
302
+ return entry.source;
303
+ switch (entry.provider) {
304
+ case 'test_oracle_auto': return 'auto-test';
305
+ case 'checkpoint': return 'auto-checkpoint';
306
+ case 'git-commit':
307
+ case 'changelog': return 'auto-git';
308
+ case 'pr-review': return 'auto-pr-review';
309
+ default: return 'unknown';
310
+ }
311
+ }
30
312
  // ─── Project Scoping ──────────────────────────────────────────────────────────
31
313
  /**
32
314
  * Stable identity for the project a memory belongs to.
@@ -617,6 +899,11 @@ export class TheBrainV2 {
617
899
  this.sessionMisses = 0;
618
900
  this.dirty = false;
619
901
  this.flushTimer = null;
902
+ /** State of entries.ndjson as of our last read/write — see syncIfChanged(). */
903
+ this.diskStamp = null;
904
+ /** id -> ISO deletion time, for ids that must not come back through a merge. */
905
+ this.tombstones = new Map();
906
+ this.sidecar = null;
620
907
  this.ensureDir();
621
908
  this.load();
622
909
  }
@@ -627,36 +914,23 @@ export class TheBrainV2 {
627
914
  }
628
915
  load() {
629
916
  try {
630
- // Load entries from NDJSON
631
- if (fs.existsSync(ENTRIES_FILE)) {
632
- const lines = fs.readFileSync(ENTRIES_FILE, 'utf8').split('\n').filter(Boolean);
633
- for (const line of lines) {
634
- try {
635
- const entry = JSON.parse(line);
636
- // Entries written before the format was compacted still carry `terms`; newer
637
- // ones don't. Rebuilding from termFreq covers both without a migration step.
638
- if (!Array.isArray(entry.terms))
639
- entry.terms = Object.keys(entry.termFreq || {});
640
- this.entries.set(entry.id, entry);
641
- }
642
- catch { /* skip corrupt lines */ }
643
- }
644
- }
645
- // Load inverted index
646
- if (fs.existsSync(INDEX_FILE)) {
647
- const raw = JSON.parse(fs.readFileSync(INDEX_FILE, 'utf8'));
648
- for (const [term, ids] of Object.entries(raw)) {
649
- this.invertedIndex.set(term, new Set(ids));
650
- }
651
- }
652
- // Load bloom filter and meta
917
+ // Meta first: the tombstone list decides which entries are allowed back in.
653
918
  if (fs.existsSync(META_FILE)) {
654
919
  const meta = JSON.parse(fs.readFileSync(META_FILE, 'utf8'));
655
- if (meta.bloom) {
920
+ if (meta.bloom)
656
921
  this.bloom = new BloomFilter(meta.bloom);
657
- }
658
922
  this.avgDocLength = meta.avgDocLength || 0;
923
+ this.tombstones = readTombstones(meta);
659
924
  }
925
+ this.entries = readEntriesFile();
926
+ for (const id of this.tombstones.keys())
927
+ this.entries.delete(id);
928
+ this.diskStamp = stampOf(ENTRIES_FILE);
929
+ // The inverted index is rebuilt from the entries rather than read back from
930
+ // index.json. It is a pure derivation of the entries, so reconstructing it is the
931
+ // only way it can never disagree with them — and a stale or half-written index.json
932
+ // used to be able to hide entries from search entirely while they sat on disk intact.
933
+ this.rebuildIndex();
660
934
  this.recalcAvgDocLength();
661
935
  }
662
936
  catch (err) {
@@ -664,6 +938,52 @@ export class TheBrainV2 {
664
938
  this.entries.clear();
665
939
  this.invertedIndex.clear();
666
940
  this.bloom = new BloomFilter();
941
+ this.tombstones = new Map();
942
+ }
943
+ }
944
+ /** Recomputes the inverted index from scratch over the current entries. */
945
+ rebuildIndex() {
946
+ this.invertedIndex = new Map();
947
+ for (const entry of this.entries.values()) {
948
+ for (const term of entry.terms) {
949
+ let ids = this.invertedIndex.get(term);
950
+ if (!ids) {
951
+ ids = new Set();
952
+ this.invertedIndex.set(term, ids);
953
+ }
954
+ ids.add(entry.id);
955
+ }
956
+ }
957
+ }
958
+ /**
959
+ * Pull in anything another process wrote since we last touched the corpus.
960
+ *
961
+ * Called at the top of every read path. Two statSync calls when nothing changed (the
962
+ * overwhelmingly common case) is far below the cost of the search that follows, and it
963
+ * turns sibling sessions from a data-loss hazard into a live shared corpus: a memory
964
+ * stored in one project's session is searchable from another within one tool call.
965
+ *
966
+ * Merges rather than reloads, so memories stored locally but not yet flushed survive.
967
+ */
968
+ syncIfChanged() {
969
+ const stamp = stampOf(ENTRIES_FILE);
970
+ if (sameStamp(stamp, this.diskStamp))
971
+ return;
972
+ try {
973
+ this.absorbPeerTombstones();
974
+ const onDisk = readEntriesFile();
975
+ const before = this.entries.size;
976
+ this.entries = mergeEntryMaps(this.entries, onDisk, new Set(this.tombstones.keys()));
977
+ this.diskStamp = stamp;
978
+ if (this.entries.size !== before || onDisk.size > 0) {
979
+ this.rebuildIndex();
980
+ this.recalcAvgDocLength();
981
+ }
982
+ }
983
+ catch {
984
+ // A read failure here must never break a search: worst case we keep serving the
985
+ // in-memory corpus, which is exactly the pre-existing behavior.
986
+ this.diskStamp = stamp;
667
987
  }
668
988
  }
669
989
  recalcAvgDocLength() {
@@ -685,38 +1005,111 @@ export class TheBrainV2 {
685
1005
  }, 500);
686
1006
  }
687
1007
  save() {
1008
+ const fd = acquireLock();
688
1009
  try {
689
1010
  this.ensureDir();
1011
+ // Merge before writing. A full rewrite of what this process happens to hold would
1012
+ // erase every memory a sibling session stored since we loaded — the concurrency bug
1013
+ // this whole section exists to close. After the merge the file we write is a superset
1014
+ // of both views, so a writer can only ever add.
1015
+ this.absorbPeerTombstones();
1016
+ const onDisk = readEntriesFile();
1017
+ if (onDisk.size > 0) {
1018
+ this.entries = mergeEntryMaps(this.entries, onDisk, new Set(this.tombstones.keys()));
1019
+ this.rebuildIndex();
1020
+ this.recalcAvgDocLength();
1021
+ }
1022
+ this.pruneTombstones();
1023
+ // Post-merge, so the file we write respects the cap even when the merge pulled in
1024
+ // entries a peer had already evicted.
1025
+ this.evictIfOverCapacity();
690
1026
  // Write NDJSON entries. `terms` is dropped: it is exactly Object.keys(termFreq),
691
1027
  // and persisting both made the entry file 38% redundant bytes that every session
692
1028
  // re-read at startup. load() reconstructs it.
693
1029
  const ndjson = Array.from(this.entries.values())
694
1030
  .map(({ terms: _terms, ...persisted }) => JSON.stringify(persisted))
695
1031
  .join('\n');
696
- fs.writeFileSync(ENTRIES_FILE, ndjson, 'utf8');
697
- // Write inverted index
1032
+ writeFileAtomic(ENTRIES_FILE, ndjson);
1033
+ // Write inverted index. load() rebuilds this from the entries rather than reading it
1034
+ // back, so it is now purely an inspection artifact for the dashboard and for anyone
1035
+ // poking at the brain directory — kept because removing a file other tooling may read
1036
+ // is not worth the handful of bytes it saves.
698
1037
  const indexObj = {};
699
1038
  for (const [term, ids] of this.invertedIndex) {
700
1039
  indexObj[term] = Array.from(ids);
701
1040
  }
702
- fs.writeFileSync(INDEX_FILE, JSON.stringify(indexObj), 'utf8');
1041
+ writeFileAtomic(INDEX_FILE, JSON.stringify(indexObj));
703
1042
  // Write meta
704
- fs.writeFileSync(META_FILE, JSON.stringify({
1043
+ writeFileAtomic(META_FILE, JSON.stringify({
705
1044
  bloom: this.bloom.serialize(),
706
1045
  avgDocLength: this.avgDocLength,
707
1046
  totalEntries: this.entries.size,
708
1047
  savedAt: new Date().toISOString(),
709
- }), 'utf8');
1048
+ tombstones: Object.fromEntries(this.tombstones),
1049
+ }));
1050
+ this.diskStamp = stampOf(ENTRIES_FILE);
710
1051
  this.dirty = false;
711
1052
  }
712
1053
  catch { /* fail silently */ }
1054
+ finally {
1055
+ releaseLock(fd);
1056
+ }
1057
+ }
1058
+ /**
1059
+ * Pull in deletions made by other processes.
1060
+ *
1061
+ * Tombstones are shared state, not per-process bookkeeping: a peer that deleted a memory
1062
+ * wrote the tombstone to meta.json, and a process that still holds the entry in memory
1063
+ * would otherwise merge it right back on its next flush — undoing a deliberate deletion
1064
+ * from a session that had nothing to do with it.
1065
+ */
1066
+ absorbPeerTombstones() {
1067
+ for (const [id, at] of readTombstonesFile()) {
1068
+ if (!this.tombstones.has(id))
1069
+ this.tombstones.set(id, at);
1070
+ const entry = this.entries.get(id);
1071
+ if (entry)
1072
+ this.dropEntry(entry);
1073
+ }
1074
+ }
1075
+ /**
1076
+ * Records an id as deliberately deleted, so a merge with a peer that still holds it
1077
+ * doesn't resurrect it. Without this, forget() would be undone the moment any other
1078
+ * session flushed, and eviction would thrash forever between two processes.
1079
+ */
1080
+ tombstone(id) {
1081
+ this.tombstones.set(id, new Date().toISOString());
1082
+ }
1083
+ /** Drops tombstones older than TOMBSTONE_TTL_MS — by then no peer still holds the entry. */
1084
+ pruneTombstones() {
1085
+ const cutoff = Date.now() - TOMBSTONE_TTL_MS;
1086
+ for (const [id, at] of this.tombstones) {
1087
+ const t = Date.parse(at);
1088
+ if (!Number.isFinite(t) || t < cutoff)
1089
+ this.tombstones.delete(id);
1090
+ }
1091
+ }
1092
+ /** Removes an entry from the in-memory corpus and the inverted index. No persistence. */
1093
+ dropEntry(entry) {
1094
+ this.entries.delete(entry.id);
1095
+ for (const term of entry.terms) {
1096
+ const ids = this.invertedIndex.get(term);
1097
+ if (!ids)
1098
+ continue;
1099
+ ids.delete(entry.id);
1100
+ if (ids.size === 0)
1101
+ this.invertedIndex.delete(term);
1102
+ }
713
1103
  }
714
1104
  // ─── Store ────────────────────────────────────────────────────────────────
715
1105
  /**
716
1106
  * Store a query+response pair in the brain.
717
1107
  * Returns false if detected as duplicate (>= dupThreshold similarity).
718
1108
  */
719
- store(query, response, provider = 'generic', dupThreshold = 0.92, filePaths, projectId = deriveProjectId(), outcome, symbolRefs, claimInputs, domain, derivedFrom) {
1109
+ store(query, response, provider = 'generic', dupThreshold = 0.92, filePaths, projectId = deriveProjectId(), outcome, symbolRefs, claimInputs, domain, derivedFrom, options = {}) {
1110
+ // Another session may have stored this exact thing since we loaded; without the sync
1111
+ // the dedup check below would miss it and write a second copy.
1112
+ this.syncIfChanged();
720
1113
  // Quick bloom check
721
1114
  const queryKey = query.trim().toLowerCase().substring(0, 200);
722
1115
  if (this.bloom.has(queryKey)) {
@@ -754,11 +1147,20 @@ export class TheBrainV2 {
754
1147
  }
755
1148
  const terms = tokenize(query + ' ' + response);
756
1149
  const termFreq = termFrequencies(terms);
1150
+ // Salted with random bytes, not just the clock: the id used to be sha1(queryKey + now),
1151
+ // so two memories sharing a query prefix and landing in the same millisecond produced
1152
+ // the same id and the second silently overwrote the first — a lost memory that nothing
1153
+ // reported. Batch paths (git ingest, importBundle, auto-capture) hit that window.
757
1154
  const id = crypto
758
1155
  .createHash('sha1')
759
- .update(queryKey + Date.now())
1156
+ .update(queryKey + Date.now() + crypto.randomBytes(8).toString('hex'))
760
1157
  .digest('hex')
761
1158
  .substring(0, 12);
1159
+ // Recorded so a later stale result can say whether the code changed or the caller
1160
+ // simply moved branches. Never consulted by freshness itself.
1161
+ const git = options.skipGitContext
1162
+ ? { commit: options.gitCommit, branch: options.gitBranch }
1163
+ : currentGitContext();
762
1164
  const entry = {
763
1165
  id,
764
1166
  query: query.trim(),
@@ -766,7 +1168,7 @@ export class TheBrainV2 {
766
1168
  terms: [...new Set(terms)],
767
1169
  termFreq,
768
1170
  provider,
769
- timestamp: new Date().toISOString(),
1171
+ timestamp: options.timestamp || new Date().toISOString(),
770
1172
  hits: 0,
771
1173
  charCount: query.length + response.length,
772
1174
  projectId,
@@ -777,6 +1179,9 @@ export class TheBrainV2 {
777
1179
  claims: claimInputs && claimInputs.length > 0 ? buildClaims(claimInputs) : undefined,
778
1180
  domain,
779
1181
  derivedFrom: derivedFrom && derivedFrom.length > 0 ? derivedFrom : undefined,
1182
+ source: options.source || 'manual',
1183
+ ...(git.commit ? { gitCommit: git.commit } : {}),
1184
+ ...(git.branch ? { gitBranch: git.branch } : {}),
780
1185
  };
781
1186
  this.entries.set(id, entry);
782
1187
  // Update inverted index
@@ -791,7 +1196,7 @@ export class TheBrainV2 {
791
1196
  this.recalcAvgDocLength();
792
1197
  this.evictIfOverCapacity();
793
1198
  this.scheduleSave();
794
- return { stored: true, reason: 'Stored successfully', conflicts };
1199
+ return { stored: true, reason: 'Stored successfully', id, conflicts };
795
1200
  }
796
1201
  /**
797
1202
  * Evict the lowest-value entries once the Brain is over capacity. Value = hits (proven
@@ -818,15 +1223,11 @@ export class TheBrainV2 {
818
1223
  });
819
1224
  const toEvict = ranked.slice(0, TheBrainV2.EVICT_BATCH);
820
1225
  for (const entry of toEvict) {
821
- this.entries.delete(entry.id);
822
- for (const term of entry.terms) {
823
- const ids = this.invertedIndex.get(term);
824
- if (!ids)
825
- continue;
826
- ids.delete(entry.id);
827
- if (ids.size === 0)
828
- this.invertedIndex.delete(term);
829
- }
1226
+ this.dropEntry(entry);
1227
+ // Tombstoned, not just dropped: another session's merge would otherwise hand back
1228
+ // every entry this pass just decided was worthless, and the two processes would
1229
+ // evict-and-resurrect the same 500 entries against each other indefinitely.
1230
+ this.tombstone(entry.id);
830
1231
  }
831
1232
  this.recalcAvgDocLength();
832
1233
  }
@@ -838,6 +1239,8 @@ export class TheBrainV2 {
838
1239
  search(query, limit = 5, minSimilarity = 0, options = {}) {
839
1240
  // Internal callers (dedup) must not move the counters the savings ledger reports.
840
1241
  const countStats = options.countStats !== false;
1242
+ // Pick up anything a sibling session stored since the last read. Two statSync calls.
1243
+ this.syncIfChanged();
841
1244
  if (this.entries.size === 0) {
842
1245
  if (countStats)
843
1246
  this.sessionMisses++;
@@ -928,6 +1331,16 @@ export class TheBrainV2 {
928
1331
  // popularity prior above rather than just canceling it out.
929
1332
  if (s.entry.demerits)
930
1333
  similarity -= Math.min(s.entry.demerits * 0.06, 0.25);
1334
+ // Age decay. Every other signal here is about the memory's track record; none of them
1335
+ // notice that the codebase it describes has been rewritten twice since. A confirmed
1336
+ // memory from a year ago is not as likely to be current as yesterday's, and until now
1337
+ // they ranked identically. Kept in the same small, additive register as the rest — it
1338
+ // demotes among relevant candidates, it can't bury one. `refreshedAt` resets the clock,
1339
+ // which is the point of refresh(): a re-verified memory really is current again.
1340
+ const ageDays = (Date.now() - effectiveTime(s.entry)) / 86400000;
1341
+ if (Number.isFinite(ageDays) && ageDays > RECENCY_GRACE_DAYS) {
1342
+ similarity -= Math.min((ageDays - RECENCY_GRACE_DAYS) / RECENCY_FULL_DECAY_DAYS, 1) * MAX_RECENCY_PENALTY;
1343
+ }
931
1344
  return { entry: s.entry, similarity: Math.max(0, similarity) };
932
1345
  });
933
1346
  // 6. Sort and filter
@@ -935,6 +1348,9 @@ export class TheBrainV2 {
935
1348
  const claimIndex = buildClaimIndex(this.entries);
936
1349
  const resolveNode = (id) => resolveFreshnessNode(this.entries, claimIndex, id);
937
1350
  const semanticDiff = options.semanticDiff === true;
1351
+ // Resolved once per search, not per stale hit — five stale results would otherwise
1352
+ // spawn ten git processes for one query.
1353
+ const git = currentGitContext();
938
1354
  const results = combined
939
1355
  .filter(r => r.similarity >= minSimilarity)
940
1356
  .slice(0, limit)
@@ -949,7 +1365,7 @@ export class TheBrainV2 {
949
1365
  provider: r.entry.provider,
950
1366
  timestamp: r.entry.timestamp,
951
1367
  fresh,
952
- ...(fresh ? {} : { staleFiles }),
1368
+ ...(fresh ? {} : { staleFiles, ...attributeStaleness(r.entry, git) }),
953
1369
  ...(r.entry.outcome ? { outcome: r.entry.outcome } : {}),
954
1370
  ...(claims && claims.length > 0 ? { claims } : {}),
955
1371
  ...(r.entry.domain ? { domain: r.entry.domain } : {}),
@@ -977,6 +1393,69 @@ export class TheBrainV2 {
977
1393
  * Entries belonging to a project, including the unscoped ones written before entries
978
1394
  * carried a projectId — same fallback rule search() uses, so counts and results agree.
979
1395
  */
1396
+ /**
1397
+ * search(), with an optional semantic re-rank layered on top.
1398
+ *
1399
+ * BM25 still does the retrieving — this only reorders what it already found, and only
1400
+ * when LEMMA_BRAIN_EMBEDDINGS is set and Ollama answers. With the flag off (the default)
1401
+ * this is exactly `search()` plus one boolean check, so callers can use it unconditionally
1402
+ * and no session pays for a feature it hasn't turned on. See BrainEmbeddings.ts.
1403
+ *
1404
+ * The candidate pool is widened before re-ranking: re-ordering the same `limit` results
1405
+ * BM25 already picked can only shuffle them, never surface the memory BM25 ranked 9th
1406
+ * because it happened to use different words — which is the entire point.
1407
+ */
1408
+ async searchHybrid(query, limit = 5, minSimilarity = 0, options = {}) {
1409
+ if (!embeddingsEnabled())
1410
+ return this.search(query, limit, minSimilarity, options);
1411
+ const poolSize = Math.max(limit * 4, 20);
1412
+ // minSimilarity 0 for the pool: a candidate the re-rank would promote must not be cut
1413
+ // by a lexical floor before the semantic score is ever computed. The floor is applied
1414
+ // again below, against the blended score.
1415
+ const pool = this.search(query, poolSize, 0, { ...options, countStats: false });
1416
+ if (pool.length === 0) {
1417
+ if (options.countStats !== false)
1418
+ this.sessionMisses++;
1419
+ return [];
1420
+ }
1421
+ let ranked = pool;
1422
+ try {
1423
+ const scores = await semanticRerank(query, pool.map((r) => ({ id: r.id, similarity: r.similarity, text: `${r.query}\n${r.response}` })), this.embeddingSidecar());
1424
+ if (scores) {
1425
+ ranked = pool
1426
+ .map((r) => ({ ...r, similarity: scores.get(r.id) ?? r.similarity }))
1427
+ .sort((a, b) => b.similarity - a.similarity);
1428
+ this.sidecar?.flush(new Set(this.entries.keys()));
1429
+ }
1430
+ }
1431
+ catch {
1432
+ // Re-ranking is an enhancement; a failure in it must never cost the caller the
1433
+ // results BM25 already produced.
1434
+ ranked = pool;
1435
+ }
1436
+ const results = ranked.filter((r) => r.similarity >= minSimilarity).slice(0, limit);
1437
+ // Stats bookkeeping the pool search was told to skip, applied once against the final list
1438
+ // so a hybrid search counts exactly like a lexical one.
1439
+ if (options.countStats !== false) {
1440
+ if (results.length > 0) {
1441
+ this.sessionHits++;
1442
+ const topEntry = this.entries.get(results[0].id);
1443
+ if (topEntry) {
1444
+ topEntry.hits++;
1445
+ this.scheduleSave();
1446
+ }
1447
+ }
1448
+ else {
1449
+ this.sessionMisses++;
1450
+ }
1451
+ }
1452
+ return results;
1453
+ }
1454
+ embeddingSidecar() {
1455
+ if (!this.sidecar)
1456
+ this.sidecar = new EmbeddingSidecar(EMBEDDINGS_FILE);
1457
+ return this.sidecar;
1458
+ }
980
1459
  getEntriesForProject(projectId) {
981
1460
  return Array.from(this.entries.values()).filter((e) => e.projectId === undefined || e.projectId === projectId);
982
1461
  }
@@ -1017,6 +1496,7 @@ export class TheBrainV2 {
1017
1496
  * differently-phrased query tomorrow.
1018
1497
  */
1019
1498
  downvote(id) {
1499
+ this.syncIfChanged();
1020
1500
  const entry = this.entries.get(id);
1021
1501
  if (!entry)
1022
1502
  return { ok: false, message: `No entry with id "${id}" in the Brain.` };
@@ -1024,6 +1504,136 @@ export class TheBrainV2 {
1024
1504
  this.scheduleSave();
1025
1505
  return { ok: true, message: `Recorded negative feedback on entry "${id}" (demerits: ${entry.demerits}). It will rank lower and be evicted sooner.` };
1026
1506
  }
1507
+ // ─── Deletion ───────────────────────────────────────────────────────────────
1508
+ /**
1509
+ * Permanently remove one memory.
1510
+ *
1511
+ * The Brain had no way to delete anything: downvote() only demotes, and eviction only
1512
+ * fires at capacity. A memory that is simply wrong, or that captured something that
1513
+ * should never have been stored, had no exit — the only recourse was to downvote it
1514
+ * repeatedly and wait for the corpus to fill up. This is that exit.
1515
+ *
1516
+ * The id is tombstoned as well as dropped, so a concurrent session's merge can't hand it
1517
+ * straight back. The bloom filter cannot un-add a key, so the deleted query may still
1518
+ * register as a possible duplicate later; that costs one extra dedup search and never
1519
+ * produces a wrong answer, which is the right side of that trade for a probabilistic
1520
+ * filter that is rebuilt on the next clear().
1521
+ */
1522
+ forget(id) {
1523
+ this.syncIfChanged();
1524
+ const entry = this.entries.get(id);
1525
+ if (!entry)
1526
+ return { ok: false, message: `No entry with id "${id}" in the Brain.` };
1527
+ this.dropEntry(entry);
1528
+ this.tombstone(id);
1529
+ this.recalcAvgDocLength();
1530
+ this.scheduleSave();
1531
+ return {
1532
+ ok: true,
1533
+ message: `Deleted memory "${id}". It will not come back from another session's copy.`,
1534
+ // Echoed back so a deletion is auditable: the caller (and the user reading the
1535
+ // transcript) can see exactly what was destroyed, since nothing else can recover it.
1536
+ forgotten: { id, query: entry.query, timestamp: entry.timestamp, hits: entry.hits },
1537
+ };
1538
+ }
1539
+ // ─── Re-anchoring ───────────────────────────────────────────────────────────
1540
+ /**
1541
+ * Re-verify a memory against the code as it stands now, keeping its identity.
1542
+ *
1543
+ * Staleness used to be terminal: once tracked evidence changed, an entry was stale
1544
+ * forever, even in the very common case where the insight is still true and the code just
1545
+ * moved. The only workaround was to store a near-duplicate — which store()'s own dedup
1546
+ * guard would often refuse — losing the entry's id, its hit count, its demerits, and every
1547
+ * `derivedFrom` edge pointing at it.
1548
+ *
1549
+ * With no arguments this re-hashes whatever the entry already tracks (and each claim's own
1550
+ * evidence), which is the "yes, I checked, this is still correct" path. Passing filePaths
1551
+ * or symbols instead re-points the entry at new evidence, which is the "the code moved"
1552
+ * path. Either way the caller is asserting the memory is currently true — this tool
1553
+ * records that assertion, it cannot verify it, so it is never called automatically.
1554
+ *
1555
+ * `derivedFrom` dependencies are deliberately not re-anchored: a conclusion inherited from
1556
+ * a memory that is itself stale is exactly what Fase B exists to catch, and silently
1557
+ * clearing that would defeat it. Those come back in `stillStale` instead.
1558
+ */
1559
+ refresh(id, opts = {}) {
1560
+ this.syncIfChanged();
1561
+ const entry = this.entries.get(id);
1562
+ if (!entry)
1563
+ return { ok: false, message: `No entry with id "${id}" in the Brain.` };
1564
+ const retracked = [];
1565
+ const rel = (abs) => {
1566
+ const r = path.relative(process.cwd(), abs);
1567
+ return r.startsWith('..') ? abs : r;
1568
+ };
1569
+ const hasNewTracking = (opts.filePaths?.length || 0) > 0 || (opts.symbols?.length || 0) > 0;
1570
+ if (hasNewTracking) {
1571
+ // Re-point: the new tracking replaces the old wholesale rather than merging, because
1572
+ // a moved symbol's old path must stop counting against the entry forever.
1573
+ entry.fileHashes = opts.filePaths?.length ? hashFilesForFreshness(opts.filePaths) : undefined;
1574
+ entry.symbolHashes = opts.symbols?.length ? hashSymbolsForFreshness(opts.symbols) : undefined;
1575
+ entry.symbolNormalizedHashes = opts.symbols?.length ? hashSymbolsNormalizedForFreshness(opts.symbols) : undefined;
1576
+ for (const p of opts.filePaths || [])
1577
+ retracked.push(rel(path.resolve(p)));
1578
+ for (const s of opts.symbols || [])
1579
+ retracked.push(`${rel(path.resolve(s.filePath))}::${s.symbolName}`);
1580
+ }
1581
+ else {
1582
+ // Re-anchor in place: same files, same symbols, hashes recomputed against current
1583
+ // content. A tracked path that no longer exists hashes to 'MISSING' exactly as it
1584
+ // does at store time, so the entry stays honestly stale instead of being blessed.
1585
+ if (entry.fileHashes) {
1586
+ const paths = Object.keys(entry.fileHashes);
1587
+ entry.fileHashes = hashFilesForFreshness(paths);
1588
+ for (const p of paths)
1589
+ retracked.push(rel(p));
1590
+ }
1591
+ if (entry.symbolHashes) {
1592
+ const refs = Object.keys(entry.symbolHashes).map((key) => {
1593
+ const sep = key.lastIndexOf('::');
1594
+ return { filePath: key.substring(0, sep), symbolName: key.substring(sep + 2) };
1595
+ });
1596
+ entry.symbolHashes = hashSymbolsForFreshness(refs);
1597
+ entry.symbolNormalizedHashes = hashSymbolsNormalizedForFreshness(refs);
1598
+ for (const r of refs)
1599
+ retracked.push(`${rel(r.filePath)}::${r.symbolName}`);
1600
+ }
1601
+ if (entry.claims) {
1602
+ for (const claim of entry.claims) {
1603
+ if (claim.fileHashes)
1604
+ claim.fileHashes = hashFilesForFreshness(Object.keys(claim.fileHashes));
1605
+ if (claim.symbolHashes) {
1606
+ const refs = Object.keys(claim.symbolHashes).map((key) => {
1607
+ const sep = key.lastIndexOf('::');
1608
+ return { filePath: key.substring(0, sep), symbolName: key.substring(sep + 2) };
1609
+ });
1610
+ claim.symbolHashes = hashSymbolsForFreshness(refs);
1611
+ claim.symbolNormalizedHashes = hashSymbolsNormalizedForFreshness(refs);
1612
+ }
1613
+ }
1614
+ }
1615
+ }
1616
+ // Re-stamp git context and the age clock: this memory was just re-verified here, now.
1617
+ const git = currentGitContext();
1618
+ if (git.commit)
1619
+ entry.gitCommit = git.commit;
1620
+ if (git.branch)
1621
+ entry.gitBranch = git.branch;
1622
+ entry.refreshedAt = new Date().toISOString();
1623
+ const claimIndex = buildClaimIndex(this.entries);
1624
+ const { fresh, staleFiles } = checkEntryFreshness(entry, (depId) => resolveFreshnessNode(this.entries, claimIndex, depId));
1625
+ this.scheduleSave();
1626
+ return {
1627
+ ok: true,
1628
+ fresh,
1629
+ retracked,
1630
+ ...(staleFiles.length > 0 ? { stillStale: staleFiles } : {}),
1631
+ message: fresh
1632
+ ? `Memory "${id}" re-anchored to current code and is fresh again.`
1633
+ : `Memory "${id}" re-anchored, but still stale: ${staleFiles.join(', ')}. ` +
1634
+ `A "derived:" entry here means an upstream memory it was built on is stale — refresh that one first.`,
1635
+ };
1636
+ }
1027
1637
  // ─── Batch verification ─────────────────────────────────────────────────────
1028
1638
  /**
1029
1639
  * Revalidate ids from a prior search_memory/store_memory result via hash-compare only —
@@ -1033,9 +1643,14 @@ export class TheBrainV2 {
1033
1643
  * either way there is nothing left to vouch for it).
1034
1644
  */
1035
1645
  verifyByIds(ids, options = {}) {
1646
+ // An id handed over by a subagent or another MCP client may belong to an entry this
1647
+ // process has never loaded. Without the sync it would come back 'unknown' — which the
1648
+ // caller is told means "purged", and acting on that would be wrong.
1649
+ this.syncIfChanged();
1036
1650
  const claimIndex = buildClaimIndex(this.entries);
1037
1651
  const resolveNode = (id) => resolveFreshnessNode(this.entries, claimIndex, id);
1038
1652
  const semanticDiff = options.semanticDiff === true;
1653
+ const git = currentGitContext();
1039
1654
  return ids.map((id) => {
1040
1655
  const entry = this.entries.get(id);
1041
1656
  if (entry) {
@@ -1043,6 +1658,7 @@ export class TheBrainV2 {
1043
1658
  return {
1044
1659
  id,
1045
1660
  status: fresh ? 'fresh' : 'stale',
1661
+ ...(fresh ? {} : attributeStaleness(entry, git)),
1046
1662
  ...(staleFiles.length > 0 ? { staleFiles } : {}),
1047
1663
  ...(entry.claims ? { claimBreakdown: entry.claims.map((c) => checkClaimFreshness(c, semanticDiff)) } : {}),
1048
1664
  ...(cosmeticChanges && cosmeticChanges.length > 0 ? { cosmeticChanges } : {}),
@@ -1068,11 +1684,162 @@ export class TheBrainV2 {
1068
1684
  * next search) — see findBlastRadius for the algorithm and cost.
1069
1685
  */
1070
1686
  findBlastRadius(filePath, symbolName) {
1687
+ this.syncIfChanged();
1071
1688
  return findBlastRadius(this.entries, filePath, symbolName);
1072
1689
  }
1073
- // ─── Stats ────────────────────────────────────────────────────────────────
1074
- getStats() {
1690
+ // ─── Portability ────────────────────────────────────────────────────────────
1691
+ /**
1692
+ * Serialize memories to a portable NDJSON bundle: a header line, then one entry per line.
1693
+ *
1694
+ * The Brain is a single file under one user's home directory with no way in or out. That
1695
+ * makes it unshareable with a teammate, unmovable to another machine, and unbackupable
1696
+ * except by copying the directory wholesale (which also copies every other project's
1697
+ * memories). This is the smallest thing that fixes all three.
1698
+ */
1699
+ exportBundle(opts = {}) {
1700
+ this.syncIfChanged();
1701
+ const claimIndex = buildClaimIndex(this.entries);
1702
+ const resolveNode = (id) => resolveFreshnessNode(this.entries, claimIndex, id);
1703
+ let skippedStale = 0;
1704
+ const selected = [];
1705
+ for (const entry of this.entries.values()) {
1706
+ // Same unscoped-entry fallback search() uses: an entry written before scoping existed
1707
+ // belongs to no project in particular, so excluding it from every export would quietly
1708
+ // make it unbackupable.
1709
+ if (opts.projectId && entry.projectId !== undefined && entry.projectId !== opts.projectId)
1710
+ continue;
1711
+ if (opts.domain && entry.domain !== opts.domain)
1712
+ continue;
1713
+ if (!opts.includeStale && !checkEntryFreshness(entry, resolveNode).fresh) {
1714
+ skippedStale++;
1715
+ continue;
1716
+ }
1717
+ selected.push(entry);
1718
+ }
1719
+ const header = JSON.stringify({
1720
+ lemmaBrainExport: 1,
1721
+ exportedAt: new Date().toISOString(),
1722
+ count: selected.length,
1723
+ ...(opts.projectId ? { projectId: opts.projectId } : {}),
1724
+ ...(opts.domain ? { domain: opts.domain } : {}),
1725
+ });
1726
+ const body = selected.map(({ terms: _t, ...persisted }) => JSON.stringify(persisted));
1727
+ return { text: [header, ...body].join('\n'), count: selected.length, skippedStale };
1728
+ }
1729
+ /**
1730
+ * Merge a bundle produced by exportBundle into this Brain.
1731
+ *
1732
+ * Import is additive and never destructive: an id already present keeps whichever version
1733
+ * is newer and the higher of both counters (the same rule cross-process merging uses), and
1734
+ * a tombstoned id stays deleted — importing a bundle must not resurrect something the user
1735
+ * deliberately forgot.
1736
+ *
1737
+ * Imported entries keep their origin machine's absolute paths, so most of them will read
1738
+ * as stale here until refresh() re-anchors them. That is the honest outcome: their
1739
+ * evidence genuinely cannot be verified against this checkout, and reporting them as fresh
1740
+ * would be the one failure mode this whole system is built to prevent.
1741
+ */
1742
+ importBundle(text, opts = {}) {
1743
+ this.syncIfChanged();
1744
+ const lines = text.split('\n').filter(Boolean);
1745
+ if (lines.length === 0)
1746
+ return { ok: false, imported: 0, updated: 0, skipped: 0, message: 'Bundle is empty.' };
1747
+ let start = 0;
1748
+ try {
1749
+ const header = JSON.parse(lines[0]);
1750
+ if (header && header.lemmaBrainExport)
1751
+ start = 1;
1752
+ }
1753
+ catch {
1754
+ // No header — treat the whole file as entries. A raw entries.ndjson copied off another
1755
+ // machine is a perfectly reasonable thing to hand this, and rejecting it would be
1756
+ // pedantry rather than safety.
1757
+ }
1758
+ let imported = 0;
1759
+ let updated = 0;
1760
+ let skipped = 0;
1761
+ const markSource = opts.markSource !== false;
1762
+ for (const line of lines.slice(start)) {
1763
+ let entry;
1764
+ try {
1765
+ entry = JSON.parse(line);
1766
+ }
1767
+ catch {
1768
+ skipped++;
1769
+ continue;
1770
+ }
1771
+ if (!entry || typeof entry.id !== 'string' || typeof entry.query !== 'string') {
1772
+ skipped++;
1773
+ continue;
1774
+ }
1775
+ if (this.tombstones.has(entry.id)) {
1776
+ skipped++;
1777
+ continue;
1778
+ }
1779
+ if (!Array.isArray(entry.terms))
1780
+ entry.terms = Object.keys(entry.termFreq || {});
1781
+ if (entry.terms.length === 0) {
1782
+ // A bundle from a version that persisted neither terms nor termFreq — re-tokenize
1783
+ // rather than admit an entry the inverted index could never retrieve.
1784
+ const terms = tokenize(entry.query + ' ' + (entry.response || ''));
1785
+ entry.terms = [...new Set(terms)];
1786
+ entry.termFreq = termFrequencies(terms);
1787
+ }
1788
+ if (markSource)
1789
+ entry.source = 'import';
1790
+ const existing = this.entries.get(entry.id);
1791
+ if (existing) {
1792
+ if (effectiveTime(entry) <= effectiveTime(existing)) {
1793
+ // Older or same age: keep ours, but never lose feedback the other side collected.
1794
+ existing.hits = Math.max(existing.hits || 0, entry.hits || 0);
1795
+ existing.demerits = Math.max(existing.demerits || 0, entry.demerits || 0);
1796
+ skipped++;
1797
+ continue;
1798
+ }
1799
+ this.dropEntry(existing);
1800
+ entry.hits = Math.max(existing.hits || 0, entry.hits || 0);
1801
+ entry.demerits = Math.max(existing.demerits || 0, entry.demerits || 0);
1802
+ updated++;
1803
+ }
1804
+ else {
1805
+ imported++;
1806
+ }
1807
+ this.entries.set(entry.id, entry);
1808
+ for (const term of entry.terms) {
1809
+ let ids = this.invertedIndex.get(term);
1810
+ if (!ids) {
1811
+ ids = new Set();
1812
+ this.invertedIndex.set(term, ids);
1813
+ }
1814
+ ids.add(entry.id);
1815
+ }
1816
+ this.bloom.add(entry.query.trim().toLowerCase().substring(0, 200));
1817
+ }
1818
+ this.recalcAvgDocLength();
1819
+ this.evictIfOverCapacity();
1820
+ this.scheduleSave();
1075
1821
  return {
1822
+ ok: true,
1823
+ imported,
1824
+ updated,
1825
+ skipped,
1826
+ message: `Imported ${imported} new memor${imported === 1 ? 'y' : 'ies'}, updated ${updated}, skipped ${skipped}. ` +
1827
+ `Imported memories track the paths of the machine they came from, so expect them to read as stale here ` +
1828
+ `until refresh_memory re-anchors them.`,
1829
+ };
1830
+ }
1831
+ // ─── Stats ────────────────────────────────────────────────────────────────
1832
+ /**
1833
+ * Corpus counters, plus health signals that answer the question counts alone can't:
1834
+ * is this Brain getting better or is it accumulating dead weight?
1835
+ *
1836
+ * Everything is computed from memory except `staleEntries`, which re-hashes every tracked
1837
+ * file and symbol in the corpus and is therefore behind `deep` — on a full Brain that is
1838
+ * thousands of file reads and has no business running on a routine stats call.
1839
+ */
1840
+ getStats(options = {}) {
1841
+ this.syncIfChanged();
1842
+ const base = {
1076
1843
  totalEntries: this.entries.size,
1077
1844
  totalTerms: this.invertedIndex.size,
1078
1845
  avgDocLength: Math.round(this.avgDocLength),
@@ -1080,6 +1847,52 @@ export class TheBrainV2 {
1080
1847
  cacheHits: this.sessionHits,
1081
1848
  cacheMisses: this.sessionMisses,
1082
1849
  };
1850
+ let neverHit = 0;
1851
+ let downvoted = 0;
1852
+ let unscoped = 0;
1853
+ let oldest = '';
1854
+ const bySource = {};
1855
+ const projects = new Set();
1856
+ for (const entry of this.entries.values()) {
1857
+ if (!entry.hits)
1858
+ neverHit++;
1859
+ if (entry.demerits)
1860
+ downvoted++;
1861
+ if (entry.projectId === undefined)
1862
+ unscoped++;
1863
+ else
1864
+ projects.add(entry.projectId);
1865
+ const src = entrySource(entry);
1866
+ bySource[src] = (bySource[src] || 0) + 1;
1867
+ if (entry.timestamp && (!oldest || entry.timestamp < oldest))
1868
+ oldest = entry.timestamp;
1869
+ }
1870
+ base.neverHit = neverHit;
1871
+ base.downvoted = downvoted;
1872
+ base.bySource = bySource;
1873
+ base.projects = projects.size;
1874
+ base.unscopedEntries = unscoped;
1875
+ base.tombstones = this.tombstones.size;
1876
+ if (oldest)
1877
+ base.oldestEntry = oldest;
1878
+ base.corpusBytes = stampOf(ENTRIES_FILE)?.size ?? 0;
1879
+ if (options.deep) {
1880
+ const claimIndex = buildClaimIndex(this.entries);
1881
+ const resolveNode = (id) => resolveFreshnessNode(this.entries, claimIndex, id);
1882
+ let stale = 0;
1883
+ let tracked = 0;
1884
+ for (const entry of this.entries.values()) {
1885
+ const tracksSomething = !!entry.fileHashes || !!entry.symbolHashes || !!entry.derivedFrom || !!entry.claims;
1886
+ if (!tracksSomething)
1887
+ continue; // untracked entries are fresh by definition, not evidence
1888
+ tracked++;
1889
+ if (!checkEntryFreshness(entry, resolveNode).fresh)
1890
+ stale++;
1891
+ }
1892
+ base.staleEntries = stale;
1893
+ base.staleRatio = tracked > 0 ? Number((stale / tracked).toFixed(3)) : 0;
1894
+ }
1895
+ return base;
1083
1896
  }
1084
1897
  clear() {
1085
1898
  this.entries.clear();
@@ -1088,6 +1901,9 @@ export class TheBrainV2 {
1088
1901
  this.avgDocLength = 0;
1089
1902
  this.sessionHits = 0;
1090
1903
  this.sessionMisses = 0;
1904
+ this.tombstones.clear();
1905
+ this.diskStamp = null;
1906
+ this.sidecar = null;
1091
1907
  try {
1092
1908
  if (fs.existsSync(ENTRIES_FILE))
1093
1909
  fs.unlinkSync(ENTRIES_FILE);
@@ -1095,6 +1911,10 @@ export class TheBrainV2 {
1095
1911
  fs.unlinkSync(INDEX_FILE);
1096
1912
  if (fs.existsSync(META_FILE))
1097
1913
  fs.unlinkSync(META_FILE);
1914
+ if (fs.existsSync(LOCK_FILE))
1915
+ fs.unlinkSync(LOCK_FILE);
1916
+ if (fs.existsSync(EMBEDDINGS_FILE))
1917
+ fs.unlinkSync(EMBEDDINGS_FILE);
1098
1918
  }
1099
1919
  catch { /* ignore */ }
1100
1920
  }