@nxuss/lemma 1.22.1 → 1.23.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 (52) hide show
  1. package/README.md +33 -7
  2. package/dist/cjs/cloud/store/FileBrainStore.d.ts.map +1 -1
  3. package/dist/cjs/cloud/store/FileBrainStore.js +5 -2
  4. package/dist/cjs/cloud/store/FileBrainStore.js.map +1 -1
  5. package/dist/cjs/mcp/tool-profiles.d.ts.map +1 -1
  6. package/dist/cjs/mcp/tool-profiles.js +3 -0
  7. package/dist/cjs/mcp/tool-profiles.js.map +1 -1
  8. package/dist/cjs/mcp/tools/memory.d.ts.map +1 -1
  9. package/dist/cjs/mcp/tools/memory.js +212 -7
  10. package/dist/cjs/mcp/tools/memory.js.map +1 -1
  11. package/dist/cjs/mcp/tools.d.ts +9 -0
  12. package/dist/cjs/mcp/tools.d.ts.map +1 -1
  13. package/dist/cjs/mcp/tools.js +25 -4
  14. package/dist/cjs/mcp/tools.js.map +1 -1
  15. package/dist/cjs/security/scrubForStorage.d.ts +16 -0
  16. package/dist/cjs/security/scrubForStorage.d.ts.map +1 -0
  17. package/dist/cjs/security/scrubForStorage.js +35 -0
  18. package/dist/cjs/security/scrubForStorage.js.map +1 -0
  19. package/dist/cjs/subconscious/BrainEncryption.d.ts +38 -0
  20. package/dist/cjs/subconscious/BrainEncryption.d.ts.map +1 -0
  21. package/dist/cjs/subconscious/BrainEncryption.js +137 -0
  22. package/dist/cjs/subconscious/BrainEncryption.js.map +1 -0
  23. package/dist/cjs/subconscious/TheBrainV2.d.ts +294 -0
  24. package/dist/cjs/subconscious/TheBrainV2.d.ts.map +1 -1
  25. package/dist/cjs/subconscious/TheBrainV2.js +1070 -111
  26. package/dist/cjs/subconscious/TheBrainV2.js.map +1 -1
  27. package/dist/esm/cloud/store/FileBrainStore.d.ts.map +1 -1
  28. package/dist/esm/cloud/store/FileBrainStore.js +5 -2
  29. package/dist/esm/cloud/store/FileBrainStore.js.map +1 -1
  30. package/dist/esm/mcp/tool-profiles.d.ts.map +1 -1
  31. package/dist/esm/mcp/tool-profiles.js +3 -0
  32. package/dist/esm/mcp/tool-profiles.js.map +1 -1
  33. package/dist/esm/mcp/tools/memory.d.ts.map +1 -1
  34. package/dist/esm/mcp/tools/memory.js +212 -7
  35. package/dist/esm/mcp/tools/memory.js.map +1 -1
  36. package/dist/esm/mcp/tools.d.ts +9 -0
  37. package/dist/esm/mcp/tools.d.ts.map +1 -1
  38. package/dist/esm/mcp/tools.js +25 -5
  39. package/dist/esm/mcp/tools.js.map +1 -1
  40. package/dist/esm/security/scrubForStorage.d.ts +16 -0
  41. package/dist/esm/security/scrubForStorage.d.ts.map +1 -0
  42. package/dist/esm/security/scrubForStorage.js +32 -0
  43. package/dist/esm/security/scrubForStorage.js.map +1 -0
  44. package/dist/esm/subconscious/BrainEncryption.d.ts +38 -0
  45. package/dist/esm/subconscious/BrainEncryption.d.ts.map +1 -0
  46. package/dist/esm/subconscious/BrainEncryption.js +126 -0
  47. package/dist/esm/subconscious/BrainEncryption.js.map +1 -0
  48. package/dist/esm/subconscious/TheBrainV2.d.ts +294 -0
  49. package/dist/esm/subconscious/TheBrainV2.d.ts.map +1 -1
  50. package/dist/esm/subconscious/TheBrainV2.js +1068 -111
  51. package/dist/esm/subconscious/TheBrainV2.js.map +1 -1
  52. package/package.json +1 -1
@@ -15,6 +15,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.TheBrainV2 = exports.MAX_DERIVED_DEPTH = exports.BloomFilter = void 0;
18
+ exports.resetBrainKeyCache = resetBrainKeyCache;
19
+ exports.listSnapshotNames = listSnapshotNames;
18
20
  exports.mergeEntryMaps = mergeEntryMaps;
19
21
  exports.currentGitContext = currentGitContext;
20
22
  exports.resetGitContextCache = resetGitContextCache;
@@ -40,6 +42,8 @@ const crypto_1 = __importDefault(require("crypto"));
40
42
  const child_process_1 = require("child_process");
41
43
  const LocalFsResolver_1 = require("./freshness/LocalFsResolver");
42
44
  const BrainEmbeddings_1 = require("./BrainEmbeddings");
45
+ const scrubForStorage_1 = require("../security/scrubForStorage");
46
+ const BrainEncryption_1 = require("./BrainEncryption");
43
47
  /**
44
48
  * Default resolver for the local MCP path. Behaviour is byte-for-byte identical to
45
49
  * the pre-refactor inline `fs.readFileSync` hashing — it never returns `null`, so
@@ -99,13 +103,20 @@ const LOCK_FILE = path_1.default.join(BRAIN_DIR, '.write.lock');
99
103
  /** Sidecar vector cache for the optional semantic re-rank. See BrainEmbeddings.ts. */
100
104
  const EMBEDDINGS_FILE = path_1.default.join(BRAIN_DIR, 'embeddings.ndjson');
101
105
  /**
102
- * Append-only archive of everything forget() destroyed. Deletion is the one Brain operation
103
- * with no undo, and the deleted body is by definition the only copy of that text — telling the
104
- * caller "nothing else can recover it" and then handing back metadata only is the worst of both
105
- * worlds. The id stays tombstoned (a deliberate deletion must not come back through a merge),
106
- * so this file is an archive to read, not a bundle to re-import.
106
+ * The trash: an append-only archive of everything forget() removed, and the restore path
107
+ * for it (see restoreForgotten/purgeForgotten). The id stays tombstoned (a deliberate
108
+ * deletion must not come back through a merge), so this file is read as history and
109
+ * restored from by id never re-imported as a bundle.
107
110
  */
108
111
  const FORGOTTEN_FILE = path_1.default.join(BRAIN_DIR, 'forgotten.ndjson');
112
+ /** Whole-file sha256 of entries.ndjson, written alongside it on every save. */
113
+ const ENTRIES_SHA_FILE = `${ENTRIES_FILE}.sha256`;
114
+ /** Last known-good copy of entries.ndjson, rotated on every clean save. */
115
+ const ENTRIES_PREV_FILE = `${ENTRIES_FILE}.prev`;
116
+ /** Timestamped full-corpus copies taken before destructive operations. See snapshotCorpus(). */
117
+ const SNAP_DIR = path_1.default.join(BRAIN_DIR, 'snapshots');
118
+ /** How many snapshots to keep — a rollback history, not an archive. */
119
+ const MAX_SNAPSHOTS = 10;
109
120
  // ─── Cross-process durability ─────────────────────────────────────────────────
110
121
  //
111
122
  // Every MCP client session starts its own server process, and each one holds the whole
@@ -200,6 +211,95 @@ function writeFileAtomic(target, data) {
200
211
  throw err;
201
212
  }
202
213
  }
214
+ /**
215
+ * Disk protection: every byte that reaches the corpus files passes through protectForDisk
216
+ * (encrypted when a key resolves, plaintext otherwise), and every byte read back passes
217
+ * through unprotectFromDisk. An envelope without a resolvable key — or one that fails
218
+ * authentication — returns null, which the checked loader treats exactly like corruption:
219
+ * fall back, never serve half a corpus.
220
+ */
221
+ function protectForDisk(plain) {
222
+ const key = brainDiskKey();
223
+ return key ? (0, BrainEncryption_1.encryptEnvelope)(key, plain) : plain;
224
+ }
225
+ function unprotectFromDisk(stored) {
226
+ if (!stored.startsWith(BrainEncryption_1.BRAIN_ENC_MAGIC))
227
+ return stored;
228
+ const key = brainDiskKey();
229
+ if (!key)
230
+ return null;
231
+ return (0, BrainEncryption_1.decryptEnvelope)(key, stored);
232
+ }
233
+ /**
234
+ * Process-wide data key, resolved once from env/key-file (see BrainEncryption) and
235
+ * validated eagerly by the constructor — a malformed key configuration fails loud at
236
+ * startup, never as silent plaintext mid-session.
237
+ */
238
+ let cachedDiskKey = undefined;
239
+ function brainDiskKey() {
240
+ if (cachedDiskKey === undefined)
241
+ cachedDiskKey = (0, BrainEncryption_1.resolveBrainKey)(BRAIN_DIR);
242
+ return cachedDiskKey;
243
+ }
244
+ /** Test seam: drop the cached key so a test can rotate env/key-file mid-process. */
245
+ function resetBrainKeyCache() {
246
+ cachedDiskKey = undefined;
247
+ }
248
+ function sha256hex(text) {
249
+ return crypto_1.default.createHash('sha256').update(text, 'utf8').digest('hex');
250
+ }
251
+ /**
252
+ * Read a corpus file with whole-file verification. No sidecar hash (files written before
253
+ * this existed) means legacy trust: parse it as before. A sidecar mismatch means the file
254
+ * changed outside a save() — bitrot, a killed process mid-rename, a foreign write — and
255
+ * the raw bytes still come back (verified:false) so the caller can salvage intact lines;
256
+ * only an unreadable or absent file comes back with text:null.
257
+ */
258
+ function readStoredText(file) {
259
+ let raw;
260
+ try {
261
+ raw = fs_1.default.readFileSync(file, 'utf8');
262
+ }
263
+ catch {
264
+ return { text: null, verified: true, present: false }; // absent file: nothing to distrust
265
+ }
266
+ let expected = null;
267
+ try {
268
+ expected = fs_1.default.readFileSync(`${file}.sha256`, 'utf8').trim() || null;
269
+ }
270
+ catch { /* legacy file without a sidecar */ }
271
+ if (!expected)
272
+ return { text: raw, verified: true, present: true };
273
+ return sha256hex(raw) === expected
274
+ ? { text: raw, verified: true, present: true }
275
+ : { text: raw, verified: false, present: true };
276
+ }
277
+ /** Move an untrustworthy corpus file aside instead of deleting it — it may hold recoverable text. */
278
+ function quarantineFile(file) {
279
+ try {
280
+ if (!fs_1.default.existsSync(file))
281
+ return null;
282
+ const dest = path_1.default.join(path_1.default.dirname(file), `corrupt-${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}.ndjson`);
283
+ fs_1.default.renameSync(file, dest);
284
+ try {
285
+ fs_1.default.unlinkSync(`${file}.sha256`);
286
+ }
287
+ catch { /* sidecar already describes garbage */ }
288
+ return dest;
289
+ }
290
+ catch {
291
+ return null;
292
+ }
293
+ }
294
+ /** Names of rollback snapshots on disk, newest last. */
295
+ function listSnapshotNames() {
296
+ try {
297
+ return fs_1.default.readdirSync(SNAP_DIR).filter((n) => n.endsWith('.ndjson')).sort();
298
+ }
299
+ catch {
300
+ return [];
301
+ }
302
+ }
203
303
  function stampOf(file) {
204
304
  try {
205
305
  const s = fs_1.default.statSync(file);
@@ -214,32 +314,125 @@ function sameStamp(a, b) {
214
314
  return a === b;
215
315
  return a.mtimeMs === b.mtimeMs && a.size === b.size;
216
316
  }
217
- /** Parses entries.ndjson exactly the way load() does, without touching instance state. */
218
- function readEntriesFile() {
317
+ /** Parse NDJSON corpus text into entries, counting skipped lines. Pure: no filesystem. */
318
+ function parseEntriesWithStats(raw) {
219
319
  const out = new Map();
220
- let raw;
221
- try {
222
- raw = fs_1.default.readFileSync(ENTRIES_FILE, 'utf8');
223
- }
224
- catch {
225
- return out;
226
- }
320
+ let skipped = 0;
227
321
  for (const line of raw.split('\n')) {
228
322
  if (!line)
229
323
  continue;
230
324
  try {
231
325
  const entry = JSON.parse(line);
232
- if (!entry || typeof entry.id !== 'string')
326
+ if (!entry || typeof entry.id !== 'string') {
327
+ skipped++;
233
328
  continue;
329
+ }
234
330
  // Entries written before the format was compacted still carry `terms`; newer ones
235
331
  // don't. Rebuilding from termFreq covers both without a migration step.
236
332
  if (!Array.isArray(entry.terms))
237
333
  entry.terms = Object.keys(entry.termFreq || {});
238
334
  out.set(entry.id, entry);
239
335
  }
240
- catch { /* skip corrupt lines */ }
336
+ catch {
337
+ skipped++;
338
+ }
241
339
  }
242
- return out;
340
+ return { entries: out, skipped };
341
+ }
342
+ /** Parse NDJSON corpus text into entries, skipping corrupt lines. Pure: no filesystem. */
343
+ function parseEntriesText(raw) {
344
+ return parseEntriesWithStats(raw).entries;
345
+ }
346
+ /** Parses entries.ndjson exactly the way load() does, without touching instance state. */
347
+ function readEntriesFile() {
348
+ try {
349
+ return parseEntriesText(fs_1.default.readFileSync(ENTRIES_FILE, 'utf8'));
350
+ }
351
+ catch {
352
+ return new Map();
353
+ }
354
+ }
355
+ /**
356
+ * Load the corpus with verification and graceful degradation. Policy, in order:
357
+ *
358
+ * 1. Verified file (or legacy file without a sidecar): serve everything, no incident.
359
+ * 2. Changed out-of-band but with intact lines: serve the survivors and record a
360
+ * `partial-corpus` incident — discarding good memories because one line rotted would
361
+ * be worse than the rot. The next save() rewrites the file clean and heals this.
362
+ * 3. Total loss (nothing parses, or the envelope won't decrypt): fall back to the .prev
363
+ * backup, or start empty if there is none — quarantining the bad bytes either way
364
+ * when asked, never deleting them.
365
+ * 4. No main file at all: a fresh canvas. The .prev backup is deliberately NOT consulted
366
+ * here — absence of the corpus is a state (fresh install, clear()), not damage, and
367
+ * resurrecting an old backup over it would undo exactly that.
368
+ *
369
+ * Only load() — the startup path — quarantines: a long-lived process that quarantined on
370
+ * every racing read could destroy the corpus a concurrent writer is mid-merge on. save()
371
+ * and syncIfChanged() record the issue and heal on their own terms instead.
372
+ */
373
+ function loadCorpusChecked(opts) {
374
+ const at = new Date().toISOString();
375
+ const main = readStoredText(ENTRIES_FILE);
376
+ if (!main.present || main.text === null) {
377
+ return { entries: new Map(), issue: null, diskUsable: true };
378
+ }
379
+ const plain = unprotectFromDisk(main.text);
380
+ const parsed = plain !== null ? parseEntriesWithStats(plain) : { entries: new Map(), skipped: Number.MAX_SAFE_INTEGER };
381
+ if (main.verified && plain !== null && parsed.skipped === 0) {
382
+ return { entries: parsed.entries, issue: null, diskUsable: true };
383
+ }
384
+ if (parsed.entries.size > 0) {
385
+ return {
386
+ entries: parsed.entries,
387
+ issue: {
388
+ at,
389
+ file: ENTRIES_FILE,
390
+ action: 'partial-corpus',
391
+ detail: plain === null
392
+ ? 'entries.ndjson could not be decrypted with the available key; serving intact lines only.'
393
+ : `entries.ndjson changed outside a save() (${parsed.skipped} unreadable line(s) skipped); serving the intact entries. The next save rewrites the file clean.`,
394
+ },
395
+ diskUsable: true,
396
+ };
397
+ }
398
+ // Total loss: fall back to the backup, which has no sidecar of its own — acceptance is
399
+ // parse-ability, and a backup that parses to entries is strictly better than bytes that
400
+ // verify to nothing.
401
+ let prevEntries = null;
402
+ try {
403
+ const prevRaw = fs_1.default.readFileSync(ENTRIES_PREV_FILE, 'utf8');
404
+ const prevPlain = unprotectFromDisk(prevRaw);
405
+ if (prevPlain !== null) {
406
+ const prevParsed = parseEntriesText(prevPlain);
407
+ if (prevParsed.size > 0)
408
+ prevEntries = prevParsed;
409
+ }
410
+ }
411
+ catch { /* no usable backup */ }
412
+ if (opts.quarantine)
413
+ quarantineFile(ENTRIES_FILE);
414
+ if (prevEntries) {
415
+ return {
416
+ entries: prevEntries,
417
+ issue: {
418
+ at,
419
+ file: ENTRIES_FILE,
420
+ action: 'fallback-to-backup',
421
+ detail: 'entries.ndjson is entirely unreadable; serving the last known-good backup instead. The bad file was quarantined, not deleted.',
422
+ },
423
+ diskUsable: true,
424
+ };
425
+ }
426
+ return {
427
+ entries: new Map(),
428
+ issue: {
429
+ at,
430
+ file: ENTRIES_FILE,
431
+ action: 'fresh-start',
432
+ detail: 'entries.ndjson is entirely unreadable and no usable backup exists; starting empty. The bad file was quarantined, not deleted.',
433
+ },
434
+ diskUsable: false,
435
+ };
243
436
  }
244
437
  /** Reads the tombstone map straight off disk, for absorbing a peer process's deletions. */
245
438
  function readTombstonesFile() {
@@ -288,11 +481,19 @@ function mergeEntryMaps(mine, theirs, tombstones = new Set()) {
288
481
  return;
289
482
  }
290
483
  const winner = effectiveTime(entry) > effectiveTime(existing) ? entry : existing;
291
- merged.set(entry.id, {
484
+ const mergedEntry = {
292
485
  ...winner,
293
486
  hits: Math.max(entry.hits || 0, existing.hits || 0),
294
487
  demerits: Math.max(entry.demerits || 0, existing.demerits || 0),
295
- });
488
+ };
489
+ // ROI is a monotonic tally like hits: keep the best either side collected, and keep
490
+ // the field absent (not zero) when neither side ever saved anything.
491
+ const bestSavings = Math.max(entry.tokensSaved || 0, existing.tokensSaved || 0);
492
+ if (bestSavings > 0)
493
+ mergedEntry.tokensSaved = bestSavings;
494
+ else
495
+ delete mergedEntry.tokensSaved;
496
+ merged.set(entry.id, mergedEntry);
296
497
  };
297
498
  for (const entry of mine.values())
298
499
  put(entry);
@@ -1000,6 +1201,13 @@ class TheBrainV2 {
1000
1201
  this.diskStamp = null;
1001
1202
  /** id -> ISO deletion time, for ids that must not come back through a merge. */
1002
1203
  this.tombstones = new Map();
1204
+ /**
1205
+ * Last integrity incident on the corpus files (corrupt main file, undecryptable
1206
+ * envelope, skipped sync). Set by load()/save()/syncIfChanged(), never cleared
1207
+ * except by a clean verified read — health() and brain_stats surface it so a silent
1208
+ * fallback never looks like a healthy Brain.
1209
+ */
1210
+ this.integrityIssue = null;
1003
1211
  /**
1004
1212
  * id -> terms of that entry's own `query` field. Derived state, never persisted: `terms`
1005
1213
  * covers query+response together, so scoring the query field on its own (see the
@@ -1011,6 +1219,10 @@ class TheBrainV2 {
1011
1219
  this.queryTermCache = new Map();
1012
1220
  this.sidecar = null;
1013
1221
  this.ensureDir();
1222
+ // Validate key configuration before touching the corpus: a malformed LEMMA_BRAIN_KEY
1223
+ // or corrupt key file throws here, loud, instead of degrading into silent plaintext
1224
+ // (or an unreadable corpus) mid-session.
1225
+ brainDiskKey();
1014
1226
  this.load();
1015
1227
  }
1016
1228
  ensureDir() {
@@ -1028,7 +1240,12 @@ class TheBrainV2 {
1028
1240
  this.avgDocLength = meta.avgDocLength || 0;
1029
1241
  this.tombstones = readTombstones(meta);
1030
1242
  }
1031
- this.entries = readEntriesFile();
1243
+ // Checked: a corrupt main file falls back to the .prev backup (quarantining the
1244
+ // bad bytes) instead of silently starting empty and letting the next save()
1245
+ // legitimize the data loss with a fresh sidecar hash.
1246
+ const checked = loadCorpusChecked({ quarantine: true });
1247
+ this.integrityIssue = checked.issue;
1248
+ this.entries = checked.entries;
1032
1249
  for (const id of this.tombstones.keys())
1033
1250
  this.entries.delete(id);
1034
1251
  this.diskStamp = stampOf(ENTRIES_FILE);
@@ -1089,10 +1306,23 @@ class TheBrainV2 {
1089
1306
  return;
1090
1307
  try {
1091
1308
  this.absorbPeerTombstones();
1092
- const onDisk = readEntriesFile();
1309
+ // No quarantine here (see loadCorpusChecked): a mismatch on a live read is most
1310
+ // likely a racing writer, so record it, keep serving memory, and let save()/load()
1311
+ // do the healing. The stamp still advances — re-reading the same bad bytes on
1312
+ // every search would turn one incident into a permanent slowdown.
1313
+ const checked = loadCorpusChecked({ quarantine: false });
1314
+ if (checked.issue) {
1315
+ this.integrityIssue = { ...checked.issue, action: 'sync-skipped' };
1316
+ this.diskStamp = stamp;
1317
+ return;
1318
+ }
1319
+ const onDisk = checked.entries;
1093
1320
  const before = this.entries.size;
1094
1321
  this.entries = mergeEntryMaps(this.entries, onDisk, new Set(this.tombstones.keys()));
1095
1322
  this.diskStamp = stamp;
1323
+ // A clean verified read heals a previously recorded incident — the next save()
1324
+ // rewrites the sidecar, so whatever was wrong is gone, not just unnoticed.
1325
+ this.integrityIssue = null;
1096
1326
  if (this.entries.size !== before || onDisk.size > 0) {
1097
1327
  this.rebuildIndex();
1098
1328
  this.recalcAvgDocLength();
@@ -1124,6 +1354,7 @@ class TheBrainV2 {
1124
1354
  }
1125
1355
  save() {
1126
1356
  const fd = acquireLock();
1357
+ let wroteClean = false;
1127
1358
  try {
1128
1359
  this.ensureDir();
1129
1360
  // Merge before writing. A full rewrite of what this process happens to hold would
@@ -1131,8 +1362,15 @@ class TheBrainV2 {
1131
1362
  // this whole section exists to close. After the merge the file we write is a superset
1132
1363
  // of both views, so a writer can only ever add.
1133
1364
  this.absorbPeerTombstones();
1134
- const onDisk = readEntriesFile();
1135
- if (onDisk.size > 0) {
1365
+ const checked = loadCorpusChecked({ quarantine: false });
1366
+ if (checked.issue) {
1367
+ // The file on disk doesn't verify. Merge only what the fallback recovered (the
1368
+ // backup, never the corrupt bytes), surface the issue, and — critically — do NOT
1369
+ // rotate .prev below: the corrupt main file must not become the "last good" copy.
1370
+ this.integrityIssue = checked.issue;
1371
+ }
1372
+ const onDisk = checked.issue && checked.issue.action === 'fresh-start' ? new Map() : checked.entries;
1373
+ if (checked.diskUsable && onDisk.size > 0) {
1136
1374
  this.entries = mergeEntryMaps(this.entries, onDisk, new Set(this.tombstones.keys()));
1137
1375
  this.rebuildIndex();
1138
1376
  this.recalcAvgDocLength();
@@ -1141,13 +1379,39 @@ class TheBrainV2 {
1141
1379
  // Post-merge, so the file we write respects the cap even when the merge pulled in
1142
1380
  // entries a peer had already evicted.
1143
1381
  this.evictIfOverCapacity();
1382
+ // Total loss on disk (nothing parseable, or an envelope this key cannot open):
1383
+ // preserve those bytes before overwriting. They may be a corpus under a different
1384
+ // key, and an overwrite is forever while a quarantine is a rename. No-op when
1385
+ // load() already quarantined them at startup.
1386
+ if (checked.issue && (checked.issue.action === 'fresh-start' || checked.issue.action === 'fallback-to-backup')) {
1387
+ quarantineFile(ENTRIES_FILE);
1388
+ }
1389
+ // Rotate the backup BEFORE overwriting, but only when the file being replaced is
1390
+ // itself trustworthy — rotating a corrupt file would destroy the last good copy.
1391
+ if (!checked.issue) {
1392
+ try {
1393
+ if (fs_1.default.existsSync(ENTRIES_FILE))
1394
+ fs_1.default.copyFileSync(ENTRIES_FILE, ENTRIES_PREV_FILE);
1395
+ }
1396
+ catch { /* backup rotation is best-effort; the write below is what matters */ }
1397
+ }
1144
1398
  // Write NDJSON entries. `terms` is dropped: it is exactly Object.keys(termFreq),
1145
1399
  // and persisting both made the entry file 38% redundant bytes that every session
1146
1400
  // re-read at startup. load() reconstructs it.
1147
1401
  const ndjson = Array.from(this.entries.values())
1148
1402
  .map(({ terms: _terms, ...persisted }) => JSON.stringify(persisted))
1149
1403
  .join('\n');
1150
- writeFileAtomic(ENTRIES_FILE, ndjson);
1404
+ const stored = protectForDisk(ndjson);
1405
+ writeFileAtomic(ENTRIES_FILE, stored);
1406
+ // Sidecar hash over the exact bytes on disk, so any out-of-band change fails the
1407
+ // next checked read instead of being served as corpus.
1408
+ try {
1409
+ writeFileAtomic(ENTRIES_SHA_FILE, sha256hex(stored));
1410
+ // Whatever was wrong before is gone: what is on disk now is exactly this
1411
+ // process's verified corpus, so a recorded incident must not linger past it.
1412
+ wroteClean = true;
1413
+ }
1414
+ catch { /* an unverified corpus still beats no corpus */ }
1151
1415
  // Write inverted index. load() rebuilds this from the entries rather than reading it
1152
1416
  // back, so it is now purely an inspection artifact for the dashboard and for anyone
1153
1417
  // poking at the brain directory — kept because removing a file other tooling may read
@@ -1172,6 +1436,8 @@ class TheBrainV2 {
1172
1436
  finally {
1173
1437
  releaseLock(fd);
1174
1438
  }
1439
+ if (wroteClean)
1440
+ this.integrityIssue = null;
1175
1441
  }
1176
1442
  /**
1177
1443
  * Pull in deletions made by other processes.
@@ -1229,6 +1495,22 @@ class TheBrainV2 {
1229
1495
  // Another session may have stored this exact thing since we loaded; without the sync
1230
1496
  // the dedup check below would miss it and write a second copy.
1231
1497
  this.syncIfChanged();
1498
+ // Secrets never reach the corpus: redact before dedup, indexing, and persistence
1499
+ // alike, so the inverted index and the NDJSON see only the redacted text. Two fixes
1500
+ // differing only in their pasted API keys correctly dedup to one entry afterwards.
1501
+ const scrubbedQuery = (0, scrubForStorage_1.scrubSecretsForStorage)(query);
1502
+ const scrubbedResponse = (0, scrubForStorage_1.scrubSecretsForStorage)(response);
1503
+ query = scrubbedQuery.text;
1504
+ response = scrubbedResponse.text;
1505
+ let redactions = scrubbedQuery.redactions + scrubbedResponse.redactions;
1506
+ let scrubbedClaims = claimInputs;
1507
+ if (claimInputs && claimInputs.length > 0) {
1508
+ scrubbedClaims = claimInputs.map((c) => {
1509
+ const s = (0, scrubForStorage_1.scrubSecretsForStorage)(c.text);
1510
+ redactions += s.redactions;
1511
+ return s.redactions > 0 ? { ...c, text: s.text } : c;
1512
+ });
1513
+ }
1232
1514
  // Quick bloom check
1233
1515
  const queryKey = query.trim().toLowerCase().substring(0, 200);
1234
1516
  if (this.bloom.has(queryKey)) {
@@ -1239,6 +1521,7 @@ class TheBrainV2 {
1239
1521
  stored: false,
1240
1522
  reason: `Duplicate detected (${(existing[0].similarity * 100).toFixed(1)}% similar)`,
1241
1523
  duplicate: existing[0],
1524
+ redactions,
1242
1525
  };
1243
1526
  }
1244
1527
  }
@@ -1246,24 +1529,10 @@ class TheBrainV2 {
1246
1529
  // outcome, is worth flagging before this one is even written — two memories about one
1247
1530
  // function disagreeing on whether an approach works is a trap for whoever searches next.
1248
1531
  // Not a block, just a warning: the newer entry may legitimately supersede the older one.
1249
- let conflicts;
1250
- if (symbolRefs && symbolRefs.length > 0) {
1251
- const newKeys = new Set(symbolRefs.map((r) => `${path_1.default.resolve(r.filePath)}::${r.symbolName}`));
1252
- const newOutcome = outcome === 'failed' ? 'failed' : 'confirmed';
1253
- const found = [];
1254
- for (const existingEntry of this.entries.values()) {
1255
- if (!existingEntry.symbolHashes)
1256
- continue;
1257
- const existingOutcome = existingEntry.outcome === 'failed' ? 'failed' : 'confirmed';
1258
- if (existingOutcome === newOutcome)
1259
- continue;
1260
- const sharesSymbol = Object.keys(existingEntry.symbolHashes).some((k) => newKeys.has(k));
1261
- if (sharesSymbol)
1262
- found.push({ id: existingEntry.id, query: existingEntry.query, outcome: existingOutcome });
1263
- }
1264
- if (found.length > 0)
1265
- conflicts = found;
1266
- }
1532
+ const foundConflicts = symbolRefs && symbolRefs.length > 0
1533
+ ? this.findOutcomeConflicts(symbolRefs, outcome === 'failed' ? 'failed' : 'confirmed')
1534
+ : [];
1535
+ const conflicts = foundConflicts.length > 0 ? foundConflicts : undefined;
1267
1536
  const terms = tokenize(query + ' ' + response);
1268
1537
  const termFreq = termFrequencies(terms);
1269
1538
  // Salted with random bytes, not just the clock: the id used to be sha1(queryKey + now),
@@ -1298,7 +1567,8 @@ class TheBrainV2 {
1298
1567
  (symbolRefs && symbolRefs.length > 0 ? hashSymbolsForFreshness(symbolRefs) : undefined),
1299
1568
  symbolNormalizedHashes: options.evidence?.symbolsNormalized ??
1300
1569
  (symbolRefs && symbolRefs.length > 0 ? hashSymbolsNormalizedForFreshness(symbolRefs) : undefined),
1301
- claims: claimInputs && claimInputs.length > 0 ? buildClaims(claimInputs) : undefined,
1570
+ claims: scrubbedClaims && scrubbedClaims.length > 0 ? buildClaims(scrubbedClaims) : undefined,
1571
+ ...(redactions > 0 ? { redactions } : {}),
1302
1572
  domain,
1303
1573
  derivedFrom: derivedFrom && derivedFrom.length > 0 ? derivedFrom : undefined,
1304
1574
  source: options.source || 'manual',
@@ -1318,7 +1588,7 @@ class TheBrainV2 {
1318
1588
  this.recalcAvgDocLength();
1319
1589
  this.evictIfOverCapacity();
1320
1590
  this.scheduleSave();
1321
- return { stored: true, reason: 'Stored successfully', id, conflicts };
1591
+ return { stored: true, reason: 'Stored successfully', id, conflicts, redactions };
1322
1592
  }
1323
1593
  /**
1324
1594
  * Evict the lowest-value entries once the Brain is over capacity. Value = hits (proven
@@ -1450,25 +1720,41 @@ class TheBrainV2 {
1450
1720
  let similarity = exactPrompt
1451
1721
  ? 1
1452
1722
  : (s.bm25 / maxBm25) * BM25_WEIGHT + s.jaccard * JACCARD_WEIGHT + queryFieldMatch * QUERY_FIELD_WEIGHT;
1723
+ // whyShown: the human-readable half of the adjustments below. A memory the caller
1724
+ // can't audit is a memory the caller can't trust — and a downvote without a visible
1725
+ // reason teaches the ranker nothing. Only signals that actually fired are listed.
1726
+ const whyShown = [];
1727
+ if (exactPrompt)
1728
+ whyShown.push('exact-prompt-match');
1453
1729
  // Popularity prior: entries other searches actually reused are more likely to be
1454
1730
  // reused again. Log-scaled and capped at +0.08 so a handful of hits can't outrank a
1455
1731
  // much better textual match.
1456
- similarity += Math.min(Math.log2(s.entry.hits + 1) * 0.02, 0.08);
1732
+ const popularityBonus = Math.min(Math.log2(s.entry.hits + 1) * 0.02, 0.08);
1733
+ similarity += popularityBonus;
1734
+ if (s.entry.hits > 0)
1735
+ whyShown.push(`reused ${s.entry.hits}x (+${popularityBonus.toFixed(2)})`);
1457
1736
  // A documented dead end ranking above a working fix is actively harmful — it reads as
1458
1737
  // a suggestion even with the "STALE"/"FAILED" label attached downstream. Demote, don't
1459
1738
  // hide: the warning is still worth surfacing, just not first.
1460
- if (s.entry.outcome === 'failed')
1739
+ if (s.entry.outcome === 'failed') {
1461
1740
  similarity -= 0.15;
1741
+ whyShown.push('failed-attempt (-0.15)');
1742
+ }
1462
1743
  // Soft domain preference (see projectId scoping above for why this stays soft): an
1463
1744
  // entry tagged with the requested domain is more likely relevant, but an untagged or
1464
1745
  // cross-domain entry may still be the right answer.
1465
- if (options.domain && s.entry.domain === options.domain)
1746
+ if (options.domain && s.entry.domain === options.domain) {
1466
1747
  similarity += 0.05;
1748
+ whyShown.push(`domain '${options.domain}' match (+0.05)`);
1749
+ }
1467
1750
  // Explicit negative feedback from downvote() — a caller saying "this was wrong" is a
1468
1751
  // stronger, more deliberate signal than the absence of hits, so it outweighs the
1469
1752
  // popularity prior above rather than just canceling it out.
1470
- if (s.entry.demerits)
1471
- similarity -= Math.min(s.entry.demerits * 0.06, 0.25);
1753
+ if (s.entry.demerits) {
1754
+ const demeritPenalty = Math.min(s.entry.demerits * 0.06, 0.25);
1755
+ similarity -= demeritPenalty;
1756
+ whyShown.push(`downvoted x${s.entry.demerits} (-${demeritPenalty.toFixed(2)})`);
1757
+ }
1472
1758
  // Age decay. Every other signal here is about the memory's track record; none of them
1473
1759
  // notice that the codebase it describes has been rewritten twice since. A confirmed
1474
1760
  // memory from a year ago is not as likely to be current as yesterday's, and until now
@@ -1477,9 +1763,20 @@ class TheBrainV2 {
1477
1763
  // which is the point of refresh(): a re-verified memory really is current again.
1478
1764
  const ageDays = (Date.now() - effectiveTime(s.entry)) / 86400000;
1479
1765
  if (Number.isFinite(ageDays) && ageDays > RECENCY_GRACE_DAYS) {
1480
- similarity -= Math.min((ageDays - RECENCY_GRACE_DAYS) / RECENCY_FULL_DECAY_DAYS, 1) * MAX_RECENCY_PENALTY;
1766
+ const agePenalty = Math.min((ageDays - RECENCY_GRACE_DAYS) / RECENCY_FULL_DECAY_DAYS, 1) * MAX_RECENCY_PENALTY;
1767
+ similarity -= agePenalty;
1768
+ whyShown.push(`age ${Math.floor(ageDays)}d (-${agePenalty.toFixed(2)})`);
1481
1769
  }
1482
- return { entry: s.entry, similarity: Math.max(0, similarity) };
1770
+ if (s.entry.refreshedAt)
1771
+ whyShown.push(`re-verified ${s.entry.refreshedAt.slice(0, 10)}`);
1772
+ // Evidence the freshness verdict was judged against: absolute tracked paths and
1773
+ // path::symbol keys. Handlers relativize these for display; the Brain keeps them
1774
+ // absolute because cwd is a caller-side notion.
1775
+ const evidence = [
1776
+ ...Object.keys(s.entry.fileHashes || {}),
1777
+ ...Object.keys(s.entry.symbolHashes || {}),
1778
+ ];
1779
+ return { entry: s.entry, similarity: Math.max(0, similarity), whyShown, evidence };
1483
1780
  });
1484
1781
  // 6. Sort and filter
1485
1782
  combined.sort((a, b) => b.similarity - a.similarity);
@@ -1505,6 +1802,10 @@ class TheBrainV2 {
1505
1802
  provider: r.entry.provider,
1506
1803
  timestamp: r.entry.timestamp,
1507
1804
  fresh,
1805
+ ...(r.entry.hits ? { hits: r.entry.hits } : {}),
1806
+ ...(r.entry.tokensSaved ? { tokensSaved: r.entry.tokensSaved } : {}),
1807
+ ...(r.whyShown.length > 0 ? { whyShown: r.whyShown } : {}),
1808
+ ...(r.evidence.length > 0 ? { evidence: r.evidence } : {}),
1508
1809
  ...(fresh ? {} : { staleFiles, ...(unverified ? {} : attributeStaleness(r.entry, git)) }),
1509
1810
  ...(unverifiedFiles.length > 0 ? { unverifiedFiles } : {}),
1510
1811
  ...(r.entry.outcome ? { outcome: r.entry.outcome } : {}),
@@ -1600,6 +1901,28 @@ class TheBrainV2 {
1600
1901
  getEntriesForProject(projectId) {
1601
1902
  return Array.from(this.entries.values()).filter((e) => e.projectId === undefined || e.projectId === projectId);
1602
1903
  }
1904
+ /**
1905
+ * Opposite-outcome entries tracking any of these symbols. Shared by store() (warn before
1906
+ * writing) and previewImport() (warn before importing): two memories about one function
1907
+ * disagreeing on whether an approach works is a trap for whoever searches next.
1908
+ */
1909
+ findOutcomeConflicts(symbolRefs, outcome, excludeIds = new Set()) {
1910
+ const newKeys = new Set(symbolRefs.map((r) => `${path_1.default.resolve(r.filePath)}::${r.symbolName}`));
1911
+ const found = [];
1912
+ for (const existingEntry of this.entries.values()) {
1913
+ if (excludeIds.has(existingEntry.id))
1914
+ continue;
1915
+ if (!existingEntry.symbolHashes)
1916
+ continue;
1917
+ const existingOutcome = existingEntry.outcome === 'failed' ? 'failed' : 'confirmed';
1918
+ if (existingOutcome === outcome)
1919
+ continue;
1920
+ const sharesSymbol = Object.keys(existingEntry.symbolHashes).some((k) => newKeys.has(k));
1921
+ if (sharesSymbol)
1922
+ found.push({ id: existingEntry.id, query: existingEntry.query, outcome: existingOutcome });
1923
+ }
1924
+ return found;
1925
+ }
1603
1926
  // ─── Dedup Check ─────────────────────────────────────────────────────────
1604
1927
  /**
1605
1928
  * Check if a query is likely a duplicate before storing.
@@ -1677,7 +2000,44 @@ class TheBrainV2 {
1677
2000
  this.scheduleSave();
1678
2001
  return { ok: true, message: `Recorded negative feedback on entry "${id}" (demerits: ${entry.demerits}). It will rank lower and be evicted sooner.` };
1679
2002
  }
2003
+ /**
2004
+ * Book tokens saved by reusing a memory, called by search_memory on a fresh hit — the
2005
+ * same event that books the savings ledger, so the two can never disagree about
2006
+ * whether a reuse happened. Unknown ids fail silently (a peer may have forgotten the
2007
+ * entry since the search ranked it); savings attribution must never break a search.
2008
+ */
2009
+ creditSavings(id, tokens) {
2010
+ if (!Number.isFinite(tokens) || tokens <= 0)
2011
+ return;
2012
+ const entry = this.entries.get(id);
2013
+ if (!entry)
2014
+ return;
2015
+ entry.tokensSaved = (entry.tokensSaved || 0) + Math.floor(tokens);
2016
+ this.scheduleSave();
2017
+ }
1680
2018
  // ─── Deletion ───────────────────────────────────────────────────────────────
2019
+ /**
2020
+ * Archive one entry to the trash, drop it from the corpus, and tombstone the id so no
2021
+ * merge resurrects it. Shared by forget() (one memory) and mergeEntries() (folded
2022
+ * fragments). Returns whether the archive write succeeded — a failure never blocks the
2023
+ * removal itself, it only narrows the restore paths.
2024
+ */
2025
+ dropWithArchive(entry) {
2026
+ try {
2027
+ this.ensureDir();
2028
+ const { terms: _terms, ...persisted } = entry;
2029
+ fs_1.default.appendFileSync(FORGOTTEN_FILE, JSON.stringify({ ...persisted, forgottenAt: new Date().toISOString() }) + '\n', 'utf8');
2030
+ }
2031
+ catch {
2032
+ // An unwritable trash must not block a removal the caller asked for.
2033
+ this.dropEntry(entry);
2034
+ this.tombstone(entry.id);
2035
+ return false;
2036
+ }
2037
+ this.dropEntry(entry);
2038
+ this.tombstone(entry.id);
2039
+ return true;
2040
+ }
1681
2041
  /**
1682
2042
  * Permanently remove one memory.
1683
2043
  *
@@ -1697,21 +2057,13 @@ class TheBrainV2 {
1697
2057
  const entry = this.entries.get(id);
1698
2058
  if (!entry)
1699
2059
  return { ok: false, message: `No entry with id "${id}" in the Brain.` };
2060
+ // Snapshot BEFORE destroying: forget() with no restore point is exactly the data-loss
2061
+ // story snapshots exist to prevent.
2062
+ this.snapshotCorpus('forget');
1700
2063
  // Archived before it is dropped: the body is the only copy of that text anywhere, and
1701
- // "nothing else can recover it" has to be a description of the archive, not of a gap.
1702
- let archivePath;
1703
- try {
1704
- this.ensureDir();
1705
- const { terms: _terms, ...persisted } = entry;
1706
- fs_1.default.appendFileSync(FORGOTTEN_FILE, JSON.stringify({ ...persisted, forgottenAt: new Date().toISOString() }) + '\n', 'utf8');
1707
- archivePath = FORGOTTEN_FILE;
1708
- }
1709
- catch {
1710
- // An unwritable archive must not block a deletion the user asked for — the body still
1711
- // comes back in the result below, which is the copy that matters in the moment.
1712
- }
1713
- this.dropEntry(entry);
1714
- this.tombstone(id);
2064
+ // the trash is what makes this deletion restorable.
2065
+ const archived = this.dropWithArchive(entry);
2066
+ const archivePath = archived ? FORGOTTEN_FILE : undefined;
1715
2067
  this.recalcAvgDocLength();
1716
2068
  this.scheduleSave();
1717
2069
  return {
@@ -1725,6 +2077,320 @@ class TheBrainV2 {
1725
2077
  ...(archivePath ? { archivePath } : {}),
1726
2078
  };
1727
2079
  }
2080
+ // ─── Consolidation ──────────────────────────────────────────────────────────
2081
+ //
2082
+ // Long-lived Brains accumulate near-duplicate fragments about the same topic — each
2083
+ // stored in a different session, each partially overlapping. findMergeCandidates()
2084
+ // finds the pairs; this folds them: every folded fragment becomes a claim on the
2085
+ // keeper (carrying its own evidence, so per-claim freshness survives the merge), the
2086
+ // keeper inherits the counters, and the fragments leave through the same trash door
2087
+ // as forget(). The keeper's own text is untouched — merging rewrites nothing, it only
2088
+ // attaches.
2089
+ /**
2090
+ * Fold entries into a keeper. All-or-nothing on validation (unknown keeper, unknown or
2091
+ * repeated fragment, keeper listed as its own fragment all fail before anything
2092
+ * changes), then one snapshot covers the whole operation.
2093
+ */
2094
+ mergeEntries(keepId, foldIds) {
2095
+ this.syncIfChanged();
2096
+ const keeper = this.entries.get(keepId);
2097
+ if (!keeper)
2098
+ return { ok: false, message: `No memory with id "${keepId}" in the Brain.` };
2099
+ const folds = [...new Set(foldIds || [])].filter((id) => id !== keepId);
2100
+ if (folds.length === 0) {
2101
+ return { ok: false, message: `Nothing to fold into "${keepId}" — name at least one other memory id.` };
2102
+ }
2103
+ const missing = folds.filter((id) => !this.entries.has(id));
2104
+ if (missing.length > 0) {
2105
+ return { ok: false, message: `Cannot merge: ${missing.map((id) => `"${id}"`).join(', ')} ${missing.length === 1 ? 'is' : 'are'} not in the Brain. Nothing was changed.` };
2106
+ }
2107
+ this.snapshotCorpus('merge');
2108
+ // Out of the index before mutating, same as update(): postings built from the old
2109
+ // text would keep serving the keeper under words the merge removed.
2110
+ this.dropEntry(keeper);
2111
+ const newClaims = [];
2112
+ for (const foldId of folds) {
2113
+ const folded = this.entries.get(foldId);
2114
+ newClaims.push({
2115
+ id: crypto_1.default.createHash('sha1').update(`merge:${keepId}:${foldId}:${Date.now()}:${crypto_1.default.randomBytes(4).toString('hex')}`).digest('hex').substring(0, 10),
2116
+ text: `[merged from ${foldId} — "${folded.query.slice(0, 120)}"] ${folded.response}`,
2117
+ ...(folded.fileHashes ? { fileHashes: { ...folded.fileHashes } } : {}),
2118
+ ...(folded.symbolHashes ? { symbolHashes: { ...folded.symbolHashes } } : {}),
2119
+ ...(folded.symbolNormalizedHashes ? { symbolNormalizedHashes: { ...folded.symbolNormalizedHashes } } : {}),
2120
+ });
2121
+ keeper.hits += folded.hits || 0;
2122
+ keeper.demerits = Math.max(keeper.demerits || 0, folded.demerits || 0);
2123
+ keeper.tokensSaved = (keeper.tokensSaved || 0) + (folded.tokensSaved || 0);
2124
+ if (keeper.tokensSaved === 0)
2125
+ delete keeper.tokensSaved;
2126
+ if (folded.redactions)
2127
+ keeper.redactions = (keeper.redactions || 0) + folded.redactions;
2128
+ keeper.mergedFrom = [...(keeper.mergedFrom || []), foldId];
2129
+ // Folded fragments leave through the trash door: individually restorable, and the
2130
+ // merge snapshot restores the pre-merge corpus wholesale. No per-fragment snapshot
2131
+ // here — one snapshot already covers the operation.
2132
+ this.dropWithArchive(folded);
2133
+ }
2134
+ keeper.claims = [...(keeper.claims || []), ...newClaims];
2135
+ // The curator just reviewed this memory against the folded fragments: its age clock
2136
+ // restarts, exactly as refresh() does after a human re-verification.
2137
+ keeper.refreshedAt = new Date().toISOString();
2138
+ const terms = tokenize(keeper.query + ' ' + keeper.response);
2139
+ keeper.terms = [...new Set(terms)];
2140
+ keeper.termFreq = termFrequencies(terms);
2141
+ keeper.charCount = keeper.query.length + keeper.response.length;
2142
+ this.entries.set(keepId, keeper);
2143
+ for (const term of keeper.terms) {
2144
+ let ids = this.invertedIndex.get(term);
2145
+ if (!ids) {
2146
+ ids = new Set();
2147
+ this.invertedIndex.set(term, ids);
2148
+ }
2149
+ ids.add(keepId);
2150
+ }
2151
+ this.bloom.add(keeper.query.trim().toLowerCase().substring(0, 200));
2152
+ this.recalcAvgDocLength();
2153
+ this.scheduleSave();
2154
+ return {
2155
+ ok: true,
2156
+ kept: keepId,
2157
+ folded: folds,
2158
+ claimsAdded: newClaims.length,
2159
+ message: `Merged ${folds.length} ${folds.length === 1 ? 'fragment' : 'fragments'} into "${keepId}" as independently-verifiable claims (evidence carried over). The fragments are in the trash individually, and the pre-merge corpus is snapshotted — both undo paths work.`,
2160
+ };
2161
+ }
2162
+ // ─── Rollback: snapshots + trash ──────────────────────────────────────────
2163
+ //
2164
+ // forget() used to be a one-way door with the archive as its only safety net, and
2165
+ // import/clear had no net at all. Snapshots are automatic, timestamped, pruned full
2166
+ // copies taken before every destructive operation; the trash (forgotten.ndjson) is the
2167
+ // per-memory undo. Neither is consulted by freshness, ranking, or export — rollback
2168
+ // state must never leak into retrieval.
2169
+ /**
2170
+ * Persist the current in-memory corpus as a timestamped snapshot. Best-effort and
2171
+ * synchronous like save(): a failed snapshot must never block the operation it
2172
+ * protects. Returns the snapshot name, or null when nothing was written.
2173
+ */
2174
+ snapshotCorpus(reason) {
2175
+ try {
2176
+ this.ensureDir();
2177
+ fs_1.default.mkdirSync(SNAP_DIR, { recursive: true });
2178
+ const safeReason = reason.replace(/[^a-z0-9-]+/gi, '-').slice(0, 24) || 'manual';
2179
+ const name = `${new Date().toISOString().replace(/[:.]/g, '-')}-${process.pid}-${crypto_1.default.randomBytes(3).toString('hex')}-${safeReason}.ndjson`;
2180
+ const ndjson = Array.from(this.entries.values())
2181
+ .map(({ terms: _terms, ...persisted }) => JSON.stringify(persisted))
2182
+ .join('\n');
2183
+ writeFileAtomic(path_1.default.join(SNAP_DIR, name), protectForDisk(ndjson));
2184
+ // Prune oldest, newest-last ordering: a rollback history, not an archive.
2185
+ const names = listSnapshotNames();
2186
+ for (const old of names.slice(0, Math.max(0, names.length - MAX_SNAPSHOTS))) {
2187
+ try {
2188
+ fs_1.default.unlinkSync(path_1.default.join(SNAP_DIR, old));
2189
+ }
2190
+ catch { /* keep the rest */ }
2191
+ }
2192
+ return name;
2193
+ }
2194
+ catch {
2195
+ return null;
2196
+ }
2197
+ }
2198
+ /** Rollback points on disk, newest last: name, size, and modification time. */
2199
+ listSnapshots() {
2200
+ return listSnapshotNames().map((name) => {
2201
+ try {
2202
+ const st = fs_1.default.statSync(path_1.default.join(SNAP_DIR, name));
2203
+ return { name, bytes: st.size, mtime: st.mtime.toISOString() };
2204
+ }
2205
+ catch {
2206
+ return { name, bytes: 0, mtime: '' };
2207
+ }
2208
+ });
2209
+ }
2210
+ /**
2211
+ * Replace the corpus with a snapshot. The current state is snapshotted first
2212
+ * (`pre-restore`), so a restore is itself undoable. Deliberately does NOT tombstone
2213
+ * the ids that vanish: a peer session holding unflushed memories would lose them on
2214
+ * its next read, and "restore never destroys" beats "restore is total" — whatever a
2215
+ * peer still holds comes back on its next flush, honestly, through the normal merge.
2216
+ */
2217
+ restoreSnapshot(name) {
2218
+ if (typeof name !== 'string' || name.includes('/') || name.includes('\\') || !name.endsWith('.ndjson')) {
2219
+ return { ok: false, message: `Refusing to read "${name}": not a snapshot name.` };
2220
+ }
2221
+ if (!listSnapshotNames().includes(name)) {
2222
+ return { ok: false, message: `No snapshot named "${name}". Use brain_trash action=snapshots to list them.` };
2223
+ }
2224
+ let raw;
2225
+ try {
2226
+ raw = fs_1.default.readFileSync(path_1.default.join(SNAP_DIR, name), 'utf8');
2227
+ }
2228
+ catch {
2229
+ return { ok: false, message: `Could not read snapshot "${name}".` };
2230
+ }
2231
+ const plain = unprotectFromDisk(raw);
2232
+ if (plain === null) {
2233
+ return { ok: false, message: `Snapshot "${name}" cannot be decrypted with the available key — refusing to wipe the live corpus for bytes I cannot read.` };
2234
+ }
2235
+ const { entries } = parseEntriesWithStats(plain);
2236
+ if (entries.size === 0) {
2237
+ return { ok: false, message: `Snapshot "${name}" parses to zero entries — refusing to replace a live corpus with an empty one.` };
2238
+ }
2239
+ this.syncIfChanged();
2240
+ this.snapshotCorpus('pre-restore');
2241
+ this.entries = entries;
2242
+ this.rebuildIndex();
2243
+ this.queryTermCache.clear();
2244
+ this.recalcAvgDocLength();
2245
+ // Fresh bloom: the filter cannot un-add the deleted queries, and a restored corpus
2246
+ // with a stale filter would keep reporting ghosts as possible duplicates.
2247
+ this.bloom = new BloomFilter();
2248
+ for (const entry of this.entries.values()) {
2249
+ this.bloom.add(entry.query.trim().toLowerCase().substring(0, 200));
2250
+ }
2251
+ // A restored id was deliberately brought back — its old tombstone must not suppress it.
2252
+ for (const id of this.entries.keys())
2253
+ this.tombstones.delete(id);
2254
+ this.scheduleSave();
2255
+ return { ok: true, restored: entries.size, message: `Restored ${entries.size} memories from snapshot "${name}". The pre-restore state was snapshotted, so this is undoable too.` };
2256
+ }
2257
+ /** What the trash holds: one row per archived deletion, newest last. */
2258
+ listForgotten() {
2259
+ const out = [];
2260
+ let raw;
2261
+ try {
2262
+ raw = fs_1.default.readFileSync(FORGOTTEN_FILE, 'utf8');
2263
+ }
2264
+ catch {
2265
+ return out;
2266
+ }
2267
+ for (const line of raw.split('\n')) {
2268
+ if (!line)
2269
+ continue;
2270
+ try {
2271
+ const archived = JSON.parse(line);
2272
+ if (!archived || typeof archived.id !== 'string')
2273
+ continue;
2274
+ out.push({
2275
+ id: archived.id,
2276
+ query: typeof archived.query === 'string' ? archived.query.slice(0, 120) : '',
2277
+ timestamp: archived.timestamp || '',
2278
+ hits: typeof archived.hits === 'number' ? archived.hits : 0,
2279
+ forgottenAt: archived.forgottenAt || '',
2280
+ });
2281
+ }
2282
+ catch { /* a half-written archive line is not worth failing the listing */ }
2283
+ }
2284
+ return out;
2285
+ }
2286
+ /**
2287
+ * Bring a forgotten memory back. The archived copy becomes a live entry again under its
2288
+ * original id (so any external reference to the id keeps working), its old tombstone is
2289
+ * lifted, and freshness is re-judged on the next search like any other entry. The
2290
+ * archive line stays as history — the trash is append-only, restore doesn't rewrite it.
2291
+ */
2292
+ restoreForgotten(id) {
2293
+ this.syncIfChanged();
2294
+ if (this.entries.has(id)) {
2295
+ return { ok: false, message: `Memory "${id}" is already in the Brain — nothing to restore.` };
2296
+ }
2297
+ let raw;
2298
+ try {
2299
+ raw = fs_1.default.readFileSync(FORGOTTEN_FILE, 'utf8');
2300
+ }
2301
+ catch {
2302
+ return { ok: false, message: `The trash is empty — nothing to restore.` };
2303
+ }
2304
+ let found = null;
2305
+ for (const line of raw.split('\n')) {
2306
+ if (!line)
2307
+ continue;
2308
+ try {
2309
+ const archived = JSON.parse(line);
2310
+ if (archived && archived.id === id && typeof archived.query === 'string')
2311
+ found = archived;
2312
+ }
2313
+ catch { /* skip */ }
2314
+ }
2315
+ if (!found)
2316
+ return { ok: false, message: `No forgotten memory with id "${id}" in the trash.` };
2317
+ const { forgottenAt: _forgottenAt, ...revived } = found;
2318
+ if (!Array.isArray(revived.terms))
2319
+ revived.terms = Object.keys(revived.termFreq || {});
2320
+ if (revived.terms.length === 0) {
2321
+ const terms = tokenize(revived.query + ' ' + (revived.response || ''));
2322
+ revived.terms = [...new Set(terms)];
2323
+ revived.termFreq = termFrequencies(terms);
2324
+ }
2325
+ this.entries.set(id, revived);
2326
+ for (const term of revived.terms) {
2327
+ let ids = this.invertedIndex.get(term);
2328
+ if (!ids) {
2329
+ ids = new Set();
2330
+ this.invertedIndex.set(term, ids);
2331
+ }
2332
+ ids.add(id);
2333
+ }
2334
+ this.bloom.add(revived.query.trim().toLowerCase().substring(0, 200));
2335
+ this.tombstones.delete(id);
2336
+ this.recalcAvgDocLength();
2337
+ this.scheduleSave();
2338
+ return { ok: true, message: `Restored memory "${id}" from the trash (${revived.hits || 0} prior reuse(s) kept). Its freshness will be re-judged on the next search.` };
2339
+ }
2340
+ /**
2341
+ * Permanently drop archived deletions. Without a filter this empties the whole trash;
2342
+ * with olderThanDays it keeps recent deletions restorable. Tombstones are untouched —
2343
+ * purging the archive removes the restore path, not the deletion itself, so purged ids
2344
+ * still cannot come back through a merge or an import.
2345
+ */
2346
+ purgeForgotten(olderThanDays) {
2347
+ let raw = '';
2348
+ try {
2349
+ raw = fs_1.default.readFileSync(FORGOTTEN_FILE, 'utf8');
2350
+ }
2351
+ catch {
2352
+ return { purged: 0, remaining: 0 };
2353
+ }
2354
+ const cutoff = typeof olderThanDays === 'number' && Number.isFinite(olderThanDays) && olderThanDays > 0
2355
+ ? Date.now() - olderThanDays * 86400000
2356
+ : null;
2357
+ const kept = [];
2358
+ let purged = 0;
2359
+ for (const line of raw.split('\n')) {
2360
+ if (!line)
2361
+ continue;
2362
+ let drop = false;
2363
+ try {
2364
+ const archived = JSON.parse(line);
2365
+ if (!archived || typeof archived.id !== 'string')
2366
+ drop = true; // useless line, not a memory
2367
+ else if (cutoff !== null) {
2368
+ const at = Date.parse(archived.forgottenAt || '');
2369
+ drop = Number.isFinite(at) && at < cutoff;
2370
+ }
2371
+ else
2372
+ drop = true;
2373
+ }
2374
+ catch {
2375
+ drop = true; // half-written line: un-restorable, so purging loses nothing
2376
+ }
2377
+ if (drop)
2378
+ purged++;
2379
+ else
2380
+ kept.push(line);
2381
+ }
2382
+ if (purged > 0) {
2383
+ const fd = acquireLock();
2384
+ try {
2385
+ writeFileAtomic(FORGOTTEN_FILE, kept.join('\n') + (kept.length > 0 ? '\n' : ''));
2386
+ }
2387
+ catch { /* best-effort; counts below still report honestly */ }
2388
+ finally {
2389
+ releaseLock(fd);
2390
+ }
2391
+ }
2392
+ return { purged, remaining: kept.length };
2393
+ }
1728
2394
  // ─── Re-anchoring ───────────────────────────────────────────────────────────
1729
2395
  /**
1730
2396
  * Re-verify a memory against the code as it stands now, keeping its identity.
@@ -1855,6 +2521,28 @@ class TheBrainV2 {
1855
2521
  const entry = this.entries.get(id);
1856
2522
  if (!entry)
1857
2523
  return { ok: false, message: `No entry with id "${id}" in the Brain.` };
2524
+ // Same one-way redaction as store(): a corrected response pasted with a fresh secret
2525
+ // must not be the one write path that persists credentials.
2526
+ let updateRedactions = 0;
2527
+ if (typeof patch.query === 'string' && patch.query) {
2528
+ const s = (0, scrubForStorage_1.scrubSecretsForStorage)(patch.query);
2529
+ patch.query = s.text;
2530
+ updateRedactions += s.redactions;
2531
+ }
2532
+ if (typeof patch.response === 'string' && patch.response) {
2533
+ const s = (0, scrubForStorage_1.scrubSecretsForStorage)(patch.response);
2534
+ patch.response = s.text;
2535
+ updateRedactions += s.redactions;
2536
+ }
2537
+ if (patch.claims !== undefined) {
2538
+ patch.claims = patch.claims.map((c) => {
2539
+ const s = (0, scrubForStorage_1.scrubSecretsForStorage)(c.text);
2540
+ updateRedactions += s.redactions;
2541
+ return s.redactions > 0 ? { ...c, text: s.text } : c;
2542
+ });
2543
+ }
2544
+ if (updateRedactions > 0)
2545
+ entry.redactions = (entry.redactions || 0) + updateRedactions;
1858
2546
  const beforeChars = entry.charCount;
1859
2547
  // Out of the index before its terms change: a posting list built from the old text would
1860
2548
  // keep serving this entry under words the new text no longer contains.
@@ -1980,6 +2668,126 @@ class TheBrainV2 {
1980
2668
  this.syncIfChanged();
1981
2669
  return findBlastRadius(this.entries, filePath, symbolName);
1982
2670
  }
2671
+ // ─── Upkeep: one command to tend the corpus ───────────────────────────────
2672
+ //
2673
+ // Every maintenance primitive existed (verify/refresh/forget/downvote/stats) but each
2674
+ // one needed the agent to remember it, name an id, and interpret the result — so in
2675
+ // practice nobody maintained anything and the corpus rotted by default. upkeep() inverts
2676
+ // that: one call revalidates what gets reused most, surfaces duplicates and dead
2677
+ // weight, and reports the savings ledger. It never deletes, merges, or refreshes
2678
+ // anything itself — refresh() records a human assertion no automation can make, and a
2679
+ // janitor that destroys memories on its own schedule is a data-loss vector, not care.
2680
+ /**
2681
+ * Near-duplicate entry pairs worth consolidating with brain_merge (see Fase E). Pairs
2682
+ * at or above `hi` are excluded: those should have been refused at store time, so a
2683
+ * surviving one is a `forget one of them` case, not a merge — report those separately
2684
+ * via the same call with lo=hi. Bounded: at most `sample` entries each issue one
2685
+ * search, and at most 20 pairs come back.
2686
+ */
2687
+ findMergeCandidates(opts = {}) {
2688
+ const lo = opts.lo ?? 0.6;
2689
+ const hi = opts.hi ?? 0.92;
2690
+ const sample = Math.max(0, opts.sample ?? 100);
2691
+ this.syncIfChanged();
2692
+ const pool = Array.from(this.entries.values())
2693
+ .sort((a, b) => (b.hits - a.hits) || (effectiveTime(b) - effectiveTime(a)))
2694
+ .slice(0, sample);
2695
+ const seen = new Set();
2696
+ const out = [];
2697
+ for (const entry of pool) {
2698
+ // Internal sweep, not a question: must not move hit counters or the ledger.
2699
+ const results = this.search(entry.query, 6, lo, { countStats: false });
2700
+ for (const r of results) {
2701
+ if (r.id === entry.id)
2702
+ continue;
2703
+ if (r.similarity >= hi)
2704
+ continue;
2705
+ const key = [entry.id, r.id].sort().join('|');
2706
+ if (seen.has(key))
2707
+ continue;
2708
+ seen.add(key);
2709
+ const other = this.entries.get(r.id);
2710
+ out.push({
2711
+ ids: [entry.id, r.id],
2712
+ similarity: Number(r.similarity.toFixed(3)),
2713
+ queries: [entry.query.slice(0, 100), (other?.query || '').slice(0, 100)],
2714
+ });
2715
+ if (out.length >= 20)
2716
+ return out;
2717
+ }
2718
+ }
2719
+ return out;
2720
+ }
2721
+ /**
2722
+ * Full upkeep pass. Read-only over the corpus: revalidates the top-N most-reused
2723
+ * memories by hash-compare, lists exact duplicates and merge candidates, dead weight,
2724
+ * and the savings ledger — with a concrete suggested action per finding.
2725
+ */
2726
+ upkeep(opts = {}) {
2727
+ this.syncIfChanged();
2728
+ const topN = Math.max(0, opts.topN ?? 20);
2729
+ const top = Array.from(this.entries.values())
2730
+ .sort((a, b) => (b.hits - a.hits) || (effectiveTime(b) - effectiveTime(a)))
2731
+ .slice(0, topN);
2732
+ const verdicts = this.verifyByIds(top.map((e) => e.id));
2733
+ const queryOf = (id) => this.entries.get(id)?.query.slice(0, 100) || '';
2734
+ const revalidated = { checked: top.length, fresh: [], stale: [], untracked: [], unverified: [] };
2735
+ for (const v of verdicts) {
2736
+ if (v.status === 'fresh')
2737
+ revalidated.fresh.push(v.id);
2738
+ else if (v.status === 'stale') {
2739
+ revalidated.stale.push({ id: v.id, query: queryOf(v.id), staleFiles: v.staleFiles || [], action: 'refresh_memory after checking it is still true' });
2740
+ }
2741
+ else if (v.status === 'untracked') {
2742
+ revalidated.untracked.push({ id: v.id, query: queryOf(v.id), action: 'update_memory with filePaths/symbols so it becomes verifiable' });
2743
+ }
2744
+ else if (v.status === 'unverified') {
2745
+ revalidated.unverified.push({ id: v.id, query: queryOf(v.id), action: 'check the tracked paths exist on this machine, then refresh_memory' });
2746
+ }
2747
+ }
2748
+ // Exact duplicates (>= store threshold) slipped in through imports or forced stores:
2749
+ // merging paraphrases is brain_merge's job, but a 98%-identical pair just needs one
2750
+ // of them forgotten.
2751
+ const duplicatePairs = this.findMergeCandidates({ sample: opts.sample ?? 50, lo: 0.92, hi: 1.01 })
2752
+ .map((c) => ({ ...c, action: 'forget_memory one of the pair (they are the same memory twice)' }));
2753
+ const mergeCandidates = this.findMergeCandidates({ sample: opts.sample ?? 50, lo: 0.75, hi: 0.92 })
2754
+ .map((c) => ({ ...c, action: 'brain_merge the pair into one canonical memory' }));
2755
+ const neverHitIds = [];
2756
+ const downvoted = [];
2757
+ for (const entry of this.entries.values()) {
2758
+ if (!entry.hits && neverHitIds.length < 10)
2759
+ neverHitIds.push(entry.id);
2760
+ if (entry.demerits)
2761
+ downvoted.push({ id: entry.id, demerits: entry.demerits });
2762
+ }
2763
+ downvoted.sort((a, b) => b.demerits - a.demerits);
2764
+ const stats = this.getStats({ deep: opts.deep === true });
2765
+ const report = {
2766
+ checkedAt: new Date().toISOString(),
2767
+ totalEntries: this.entries.size,
2768
+ revalidated,
2769
+ duplicatePairs,
2770
+ mergeCandidates,
2771
+ deadWeight: {
2772
+ neverHit: stats.neverHit || 0,
2773
+ neverHitSample: neverHitIds,
2774
+ downvoted,
2775
+ action: 'forget_memory entries that are both never reused and downvoted; leave the rest — an unused memory costs bytes, a deleted one costs knowledge',
2776
+ },
2777
+ savings: {
2778
+ totalTokensSaved: stats.totalTokensSaved || 0,
2779
+ topSavers: (stats.topSavers || []).slice(0, 3),
2780
+ },
2781
+ };
2782
+ if (stats.staleEntries !== undefined) {
2783
+ report.deep = {
2784
+ staleEntries: stats.staleEntries,
2785
+ staleRatio: stats.staleRatio || 0,
2786
+ action: 'work the revalidated.stale list above oldest-first; refresh_memory what still holds, forget_memory what does not',
2787
+ };
2788
+ }
2789
+ return report;
2790
+ }
1983
2791
  // ─── Portability ────────────────────────────────────────────────────────────
1984
2792
  /**
1985
2793
  * Serialize memories to a portable NDJSON bundle: a header line, then one entry per line.
@@ -2019,6 +2827,149 @@ class TheBrainV2 {
2019
2827
  const body = selected.map(({ terms: _t, ...persisted }) => JSON.stringify(persisted));
2020
2828
  return { text: [header, ...body].join('\n'), count: selected.length, skippedStale };
2021
2829
  }
2830
+ /**
2831
+ * Classify one bundle line without touching the corpus. The single planning step behind
2832
+ * both importBundle() (which then applies the plan) and previewImport() (which only
2833
+ * reports it) — one classifier means a dry run can never disagree with the real thing
2834
+ * about what would happen. Scrubbing the freshly-parsed object is safe: it is not
2835
+ * corpus state yet.
2836
+ */
2837
+ planImportLine(line, markSource) {
2838
+ let entry;
2839
+ try {
2840
+ entry = JSON.parse(line);
2841
+ }
2842
+ catch {
2843
+ return { disposition: 'skip', reason: 'unparseable line' };
2844
+ }
2845
+ if (!entry || typeof entry.id !== 'string' || typeof entry.query !== 'string') {
2846
+ return { disposition: 'skip', reason: 'missing id/query' };
2847
+ }
2848
+ if (this.tombstones.has(entry.id)) {
2849
+ return { disposition: 'skip', reason: 'id was deliberately forgotten here', entry, tombstoned: true };
2850
+ }
2851
+ // Bundles from pre-scrub Brains (or hand-written ones) can carry live secrets;
2852
+ // redact on the way in. Already-scrubbed `[NAME_n]` spans pass through untouched.
2853
+ if (typeof entry.query === 'string')
2854
+ entry.query = (0, scrubForStorage_1.scrubSecretsForStorage)(entry.query).text;
2855
+ if (typeof entry.response === 'string')
2856
+ entry.response = (0, scrubForStorage_1.scrubSecretsForStorage)(entry.response).text;
2857
+ if (Array.isArray(entry.claims)) {
2858
+ for (const claim of entry.claims) {
2859
+ if (claim && typeof claim.text === 'string')
2860
+ claim.text = (0, scrubForStorage_1.scrubSecretsForStorage)(claim.text).text;
2861
+ }
2862
+ }
2863
+ if (!Array.isArray(entry.terms))
2864
+ entry.terms = Object.keys(entry.termFreq || {});
2865
+ if (entry.terms.length === 0) {
2866
+ // A bundle from a version that persisted neither terms nor termFreq — re-tokenize
2867
+ // rather than admit an entry the inverted index could never retrieve.
2868
+ const terms = tokenize(entry.query + ' ' + (entry.response || ''));
2869
+ entry.terms = [...new Set(terms)];
2870
+ entry.termFreq = termFrequencies(terms);
2871
+ }
2872
+ if (markSource)
2873
+ entry.source = 'import';
2874
+ const existing = this.entries.get(entry.id);
2875
+ if (existing) {
2876
+ if (effectiveTime(entry) <= effectiveTime(existing)) {
2877
+ return { disposition: 'skip', reason: 'local copy is newer or same age', entry };
2878
+ }
2879
+ return { disposition: 'update', reason: 'bundle copy is newer', entry };
2880
+ }
2881
+ return { disposition: 'import', reason: 'new id', entry };
2882
+ }
2883
+ /** Fold the other side's counters into ours without losing feedback either side collected. */
2884
+ absorbImportCounters(existing, incoming) {
2885
+ existing.hits = Math.max(existing.hits || 0, incoming.hits || 0);
2886
+ existing.demerits = Math.max(existing.demerits || 0, incoming.demerits || 0);
2887
+ const bestSavings = Math.max(existing.tokensSaved || 0, incoming.tokensSaved || 0);
2888
+ if (bestSavings > 0)
2889
+ existing.tokensSaved = bestSavings;
2890
+ else
2891
+ delete existing.tokensSaved;
2892
+ }
2893
+ /** Split a bundle into candidate lines. No header means raw entries — see below. */
2894
+ static splitBundleLines(text) {
2895
+ const lines = text.split('\n').filter(Boolean);
2896
+ if (lines.length === 0)
2897
+ return { lines: [] };
2898
+ try {
2899
+ const header = JSON.parse(lines[0]);
2900
+ if (header && header.lemmaBrainExport)
2901
+ return { lines: lines.slice(1) };
2902
+ }
2903
+ catch {
2904
+ // No header — treat the whole file as entries. A raw entries.ndjson copied off another
2905
+ // machine is a perfectly reasonable thing to hand this, and rejecting it would be
2906
+ // pedantry rather than safety.
2907
+ }
2908
+ return { lines };
2909
+ }
2910
+ /**
2911
+ * What importBundle() WOULD do, without writing anything: counts, the first 50 items,
2912
+ * and opposite-outcome conflicts against the live corpus. Run this before importing a
2913
+ * bundle from a teammate or another machine — especially a large one — so a flood of
2914
+ * stale, wrong-project memories is a preview, not a surprise.
2915
+ */
2916
+ previewImport(text, opts = {}) {
2917
+ this.syncIfChanged();
2918
+ const { lines } = TheBrainV2.splitBundleLines(text);
2919
+ const empty = { ok: false, wouldImport: 0, wouldUpdate: 0, wouldSkip: 0, items: [], truncated: false, conflicts: [], message: 'Bundle is empty.' };
2920
+ if (lines.length === 0)
2921
+ return empty;
2922
+ const markSource = opts.markSource !== false;
2923
+ let wouldImport = 0;
2924
+ let wouldUpdate = 0;
2925
+ let wouldSkip = 0;
2926
+ const items = [];
2927
+ const conflicts = [];
2928
+ const seenConflicts = new Set();
2929
+ for (const line of lines) {
2930
+ const plan = this.planImportLine(line, markSource);
2931
+ if (plan.disposition === 'import')
2932
+ wouldImport++;
2933
+ else if (plan.disposition === 'update')
2934
+ wouldUpdate++;
2935
+ else
2936
+ wouldSkip++;
2937
+ if (items.length < 50) {
2938
+ items.push({
2939
+ id: plan.entry?.id ?? '(unparseable)',
2940
+ query: (plan.entry?.query || '').slice(0, 100),
2941
+ action: plan.disposition,
2942
+ reason: plan.reason,
2943
+ });
2944
+ }
2945
+ if (plan.entry && plan.disposition !== 'skip' && plan.entry.symbolHashes) {
2946
+ const refs = Object.keys(plan.entry.symbolHashes).map((key) => {
2947
+ const sep = key.lastIndexOf('::');
2948
+ return { filePath: key.substring(0, sep), symbolName: key.substring(sep + 2) };
2949
+ });
2950
+ const outcome = plan.entry.outcome === 'failed' ? 'failed' : 'confirmed';
2951
+ for (const c of this.findOutcomeConflicts(refs, outcome, new Set([plan.entry.id]))) {
2952
+ const ck = `${c.id}|${plan.entry.id}`;
2953
+ if (seenConflicts.has(ck))
2954
+ continue;
2955
+ seenConflicts.add(ck);
2956
+ conflicts.push({ ...c, against: plan.entry.id });
2957
+ }
2958
+ }
2959
+ }
2960
+ return {
2961
+ ok: true,
2962
+ wouldImport,
2963
+ wouldUpdate,
2964
+ wouldSkip,
2965
+ items,
2966
+ truncated: lines.length > items.length,
2967
+ conflicts,
2968
+ message: `Dry run: would import ${wouldImport}, update ${wouldUpdate}, skip ${wouldSkip}.` +
2969
+ (conflicts.length > 0 ? ` ${conflicts.length} opposite-outcome conflict(s) with live memories — review before importing.` : '') +
2970
+ ` Nothing was written.`,
2971
+ };
2972
+ }
2022
2973
  /**
2023
2974
  * Merge a bundle produced by exportBundle into this Brain.
2024
2975
  *
@@ -2034,64 +2985,35 @@ class TheBrainV2 {
2034
2985
  */
2035
2986
  importBundle(text, opts = {}) {
2036
2987
  this.syncIfChanged();
2037
- const lines = text.split('\n').filter(Boolean);
2988
+ const { lines } = TheBrainV2.splitBundleLines(text);
2038
2989
  if (lines.length === 0)
2039
2990
  return { ok: false, imported: 0, updated: 0, skipped: 0, message: 'Bundle is empty.' };
2040
- let start = 0;
2041
- try {
2042
- const header = JSON.parse(lines[0]);
2043
- if (header && header.lemmaBrainExport)
2044
- start = 1;
2045
- }
2046
- catch {
2047
- // No header — treat the whole file as entries. A raw entries.ndjson copied off another
2048
- // machine is a perfectly reasonable thing to hand this, and rejecting it would be
2049
- // pedantry rather than safety.
2050
- }
2991
+ // Snapshot before merging foreign entries: an import is the easiest way to flood a
2992
+ // clean corpus with hundreds of stale, wrong-project memories.
2993
+ this.snapshotCorpus('import');
2051
2994
  let imported = 0;
2052
2995
  let updated = 0;
2053
2996
  let skipped = 0;
2054
2997
  const markSource = opts.markSource !== false;
2055
- for (const line of lines.slice(start)) {
2056
- let entry;
2057
- try {
2058
- entry = JSON.parse(line);
2059
- }
2060
- catch {
2061
- skipped++;
2062
- continue;
2063
- }
2064
- if (!entry || typeof entry.id !== 'string' || typeof entry.query !== 'string') {
2065
- skipped++;
2066
- continue;
2067
- }
2068
- if (this.tombstones.has(entry.id)) {
2998
+ for (const line of lines) {
2999
+ const plan = this.planImportLine(line, markSource);
3000
+ if (plan.disposition === 'skip') {
3001
+ // Tombstoned skips excepted: a deliberately forgotten id gets no counter updates,
3002
+ // exactly as before the planner existed — the deletion stands completely.
3003
+ if (plan.entry && !plan.tombstoned) {
3004
+ const existing = this.entries.get(plan.entry.id);
3005
+ // Older or same age: keep ours, but never lose feedback the other side collected.
3006
+ if (existing)
3007
+ this.absorbImportCounters(existing, plan.entry);
3008
+ }
2069
3009
  skipped++;
2070
3010
  continue;
2071
3011
  }
2072
- if (!Array.isArray(entry.terms))
2073
- entry.terms = Object.keys(entry.termFreq || {});
2074
- if (entry.terms.length === 0) {
2075
- // A bundle from a version that persisted neither terms nor termFreq — re-tokenize
2076
- // rather than admit an entry the inverted index could never retrieve.
2077
- const terms = tokenize(entry.query + ' ' + (entry.response || ''));
2078
- entry.terms = [...new Set(terms)];
2079
- entry.termFreq = termFrequencies(terms);
2080
- }
2081
- if (markSource)
2082
- entry.source = 'import';
3012
+ const entry = plan.entry;
2083
3013
  const existing = this.entries.get(entry.id);
2084
3014
  if (existing) {
2085
- if (effectiveTime(entry) <= effectiveTime(existing)) {
2086
- // Older or same age: keep ours, but never lose feedback the other side collected.
2087
- existing.hits = Math.max(existing.hits || 0, entry.hits || 0);
2088
- existing.demerits = Math.max(existing.demerits || 0, entry.demerits || 0);
2089
- skipped++;
2090
- continue;
2091
- }
2092
3015
  this.dropEntry(existing);
2093
- entry.hits = Math.max(existing.hits || 0, entry.hits || 0);
2094
- entry.demerits = Math.max(existing.demerits || 0, entry.demerits || 0);
3016
+ this.absorbImportCounters(entry, existing);
2095
3017
  updated++;
2096
3018
  }
2097
3019
  else {
@@ -2145,6 +3067,8 @@ class TheBrainV2 {
2145
3067
  let unscoped = 0;
2146
3068
  let untracked = 0;
2147
3069
  let oldest = '';
3070
+ let totalTokensSaved = 0;
3071
+ const savers = [];
2148
3072
  const bySource = {};
2149
3073
  const projects = new Set();
2150
3074
  for (const entry of this.entries.values()) {
@@ -2158,11 +3082,20 @@ class TheBrainV2 {
2158
3082
  projects.add(entry.projectId);
2159
3083
  if (trackedArtifactCount(entry) === 0)
2160
3084
  untracked++;
3085
+ if (entry.tokensSaved) {
3086
+ totalTokensSaved += entry.tokensSaved;
3087
+ savers.push({ id: entry.id, query: entry.query.slice(0, 80), tokensSaved: entry.tokensSaved, hits: entry.hits });
3088
+ }
2161
3089
  const src = entrySource(entry);
2162
3090
  bySource[src] = (bySource[src] || 0) + 1;
2163
3091
  if (entry.timestamp && (!oldest || entry.timestamp < oldest))
2164
3092
  oldest = entry.timestamp;
2165
3093
  }
3094
+ savers.sort((a, b) => b.tokensSaved - a.tokensSaved);
3095
+ base.totalTokensSaved = totalTokensSaved;
3096
+ if (savers.length > 0)
3097
+ base.topSavers = savers.slice(0, 5);
3098
+ base.integrity = this.health();
2166
3099
  base.neverHit = neverHit;
2167
3100
  base.downvoted = downvoted;
2168
3101
  base.bySource = bySource;
@@ -2191,7 +3124,26 @@ class TheBrainV2 {
2191
3124
  }
2192
3125
  return base;
2193
3126
  }
3127
+ /**
3128
+ * Integrity + rollback posture in one cheap call (no hashing, no disk reads beyond a
3129
+ * directory listing). `ok` is false while an unverified read, a backup fallback, or an
3130
+ * undecryptable envelope is the reason this process is serving what it serves.
3131
+ */
3132
+ health() {
3133
+ this.syncIfChanged();
3134
+ return {
3135
+ ok: this.integrityIssue === null,
3136
+ lastIssue: this.integrityIssue,
3137
+ snapshots: listSnapshotNames().length,
3138
+ backups: fs_1.default.existsSync(ENTRIES_PREV_FILE),
3139
+ encrypted: (0, BrainEncryption_1.encryptionActive)(BRAIN_DIR).enabled,
3140
+ };
3141
+ }
2194
3142
  clear() {
3143
+ // Even a deliberate wipe gets a restore point: "I didn't mean that clear" is a
3144
+ // support ticket, "I didn't mean that clear and there is no snapshot" is data loss.
3145
+ if (this.entries.size > 0)
3146
+ this.snapshotCorpus('clear');
2195
3147
  this.entries.clear();
2196
3148
  this.invertedIndex.clear();
2197
3149
  this.bloom = new BloomFilter();
@@ -2201,9 +3153,14 @@ class TheBrainV2 {
2201
3153
  this.tombstones.clear();
2202
3154
  this.diskStamp = null;
2203
3155
  this.sidecar = null;
3156
+ this.integrityIssue = null;
2204
3157
  try {
2205
3158
  if (fs_1.default.existsSync(ENTRIES_FILE))
2206
3159
  fs_1.default.unlinkSync(ENTRIES_FILE);
3160
+ if (fs_1.default.existsSync(ENTRIES_SHA_FILE))
3161
+ fs_1.default.unlinkSync(ENTRIES_SHA_FILE);
3162
+ if (fs_1.default.existsSync(ENTRIES_PREV_FILE))
3163
+ fs_1.default.unlinkSync(ENTRIES_PREV_FILE);
2207
3164
  if (fs_1.default.existsSync(INDEX_FILE))
2208
3165
  fs_1.default.unlinkSync(INDEX_FILE);
2209
3166
  if (fs_1.default.existsSync(META_FILE))
@@ -2212,6 +3169,8 @@ class TheBrainV2 {
2212
3169
  fs_1.default.unlinkSync(LOCK_FILE);
2213
3170
  if (fs_1.default.existsSync(EMBEDDINGS_FILE))
2214
3171
  fs_1.default.unlinkSync(EMBEDDINGS_FILE);
3172
+ // Snapshots deliberately survive clear(): they are the rollback history, and a wipe
3173
+ // that also destroys every restore point is not a wipe, it is data loss.
2215
3174
  }
2216
3175
  catch { /* ignore */ }
2217
3176
  }