dsh-layers-hippocampus 1.7.2 → 1.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/graph.js CHANGED
@@ -137,6 +137,79 @@ export function buildGraph(events = [], { maxEdges = GRAPH_HARD_CAP, topNeighbor
137
137
  };
138
138
  }
139
139
 
140
+ /** Lexicographic (code-unit) comparison, so trimming is locale-independent. */
141
+ function compareText(a, b) {
142
+ const left = String(a);
143
+ const right = String(b);
144
+ if (left < right) return -1;
145
+ if (left > right) return 1;
146
+ return 0;
147
+ }
148
+
149
+ /**
150
+ * Read-time trim: cap the cached graph to `maxNodes` nodes and `maxEdges` edges
151
+ * without touching the cache file.
152
+ *
153
+ * Eviction is deterministic and purely local:
154
+ * - nodes sort by `events` ASC, then `weight` ASC, then `id` ASC; the nodes with
155
+ * the fewest events are evicted first, so the tail is what survives;
156
+ * - edges keep only endpoints that survived, then sort by `weight` DESC, then
157
+ * `source`, then `target`, and are sliced to `maxEdges`.
158
+ *
159
+ * The input is never mutated: arrays and node/edge objects in the result are
160
+ * copies. Every other field of the source graph is carried over unchanged.
161
+ *
162
+ * @param {object} graph a `buildGraph()`/`GraphCache.view()` shaped object
163
+ * @param {{maxNodes?: number, maxEdges?: number}} [options]
164
+ * @returns {object} new graph object with trim accounting
165
+ */
166
+ export function trimGraph(graph, { maxNodes = 80, maxEdges = 500 } = {}) {
167
+ const source = graph && typeof graph === 'object' ? graph : {};
168
+ const sourceNodes = Array.isArray(source.nodes) ? source.nodes : [];
169
+ const sourceEdges = Array.isArray(source.edges) ? source.edges : [];
170
+ const totalNodes = sourceNodes.length;
171
+ const totalEdges = sourceEdges.length;
172
+ const nodeLimit = Math.max(0, Math.trunc(Number(maxNodes)) || 0);
173
+ const edgeLimit = Math.max(0, Math.trunc(Number(maxEdges)) || 0);
174
+
175
+ const byEvictionPriority = [...sourceNodes].sort((a, b) => {
176
+ const eventsA = Number.isFinite(a?.events) ? a.events : 0;
177
+ const eventsB = Number.isFinite(b?.events) ? b.events : 0;
178
+ if (eventsA !== eventsB) return eventsA - eventsB;
179
+ const weightA = Number.isFinite(a?.weight) ? a.weight : 0;
180
+ const weightB = Number.isFinite(b?.weight) ? b.weight : 0;
181
+ if (weightA !== weightB) return weightA - weightB;
182
+ return compareText(a?.id, b?.id);
183
+ });
184
+ const dropCount = Math.max(0, totalNodes - nodeLimit);
185
+ const keptNodes = byEvictionPriority.slice(dropCount).map((node) => ({ ...node }));
186
+ const keptIds = new Set(keptNodes.map((node) => String(node.id)));
187
+
188
+ const keptEdges = sourceEdges
189
+ .filter((edge) => keptIds.has(String(edge?.source)) && keptIds.has(String(edge?.target)))
190
+ .sort((a, b) => {
191
+ const weightA = Number.isFinite(a?.weight) ? a.weight : 0;
192
+ const weightB = Number.isFinite(b?.weight) ? b.weight : 0;
193
+ if (weightA !== weightB) return weightB - weightA;
194
+ return compareText(a?.source, b?.source) || compareText(a?.target, b?.target);
195
+ })
196
+ .slice(0, edgeLimit)
197
+ .map((edge) => ({ ...edge }));
198
+
199
+ return {
200
+ ...source,
201
+ nodes: keptNodes,
202
+ edges: keptEdges,
203
+ nodeCount: keptNodes.length,
204
+ edgeCount: keptEdges.length,
205
+ totalNodes,
206
+ totalEdges,
207
+ droppedNodes: totalNodes - keptNodes.length,
208
+ droppedEdges: totalEdges - keptEdges.length,
209
+ truncated: totalNodes > keptNodes.length || totalEdges > keptEdges.length,
210
+ };
211
+ }
212
+
140
213
  /** Read-only view over the cached graph file. */
141
214
  export class GraphCache {
142
215
  constructor({ dataDir, clock }) {
package/src/memory.js CHANGED
@@ -53,7 +53,7 @@ import {
53
53
  import { SemanticStore } from './semantic/semanticStore.js';
54
54
  import { TempSemanticStore } from './semantic/tempSemantic.js';
55
55
  import { ContextEngine } from './context/contextEngine.js';
56
- import { rehandoffDecision } from './context/windowGuard.js';
56
+ import { HANDOFF_CLEAR_RATIO, relievedDecision, rehandoffDecision } from './context/windowGuard.js';
57
57
  import { DEFAULT_SPACE_ID, SpaceRouter, normaliseSpaceId, validateNewSpaceId } from './spaces/singleSpace.js';
58
58
  import { nextRun, parseCron } from './cron.js';
59
59
 
@@ -116,6 +116,9 @@ function validateRoutedNewSpaceId(value) {
116
116
  import { ensureDir, dayKey, genNumber, sha256, readJson, writeJsonAtomic, snippet } from './util.js';
117
117
  import { detectCiphertext } from './entropy.js';
118
118
  import { filterSecret, isSecretRecord, privacyMetaFor } from './privacy.js';
119
+ // v1.7.3 (module 3): fine-grained `sensitive:*` categories replace the coarse
120
+ // `privacy:secret` marker on the WRITE path (the old tag keeps filtering reads).
121
+ import { detectSensitive, filterSensitive, sensitiveMetaFor, sensitiveTag } from './sensitive.js';
119
122
 
120
123
  /** Recursive byte size of a directory tree (symlinks count as their target size). */
121
124
  function diskUsage(dir) {
@@ -354,13 +357,17 @@ export class Memory {
354
357
  * @param {object} [options.clock] Clock with now(); never defaulted in tests
355
358
  * @param {object} [options.policy] partial policy overrides
356
359
  * @param {object} [options.config] { maxSegmentRecords, context }
360
+ * @param {object|null} [options.activity] v1.7.4 activity ring (read-time hints only)
357
361
  */
358
- constructor({ dataDir, clock = new SystemClock(), policy = {}, config = {}, spaces = null, spacesFactory = null, transfer = null, federation = null, dedupe = null, spaceId = DEFAULT_SPACE_ID }) {
362
+ constructor({ dataDir, clock = new SystemClock(), policy = {}, config = {}, spaces = null, spacesFactory = null, transfer = null, federation = null, dedupe = null, spaceId = DEFAULT_SPACE_ID, activity = null }) {
359
363
  if (!dataDir) throw new MemoryError(ErrorCodes.INVALID_CONFIG, 'dataDir is required');
360
364
  assertClock(clock);
361
365
  this.dataDir = path.resolve(dataDir);
362
366
  this.clock = clock;
363
367
  this.config = config;
368
+ // v1.7.4: optional activity ring. `null` means "no hints" and every caller must
369
+ // behave identically; a store failure is swallowed at the use site.
370
+ this.activity = activity;
364
371
  // v1.5.6 pre-ingest tagging: counters for the panel, and a warning hook the
365
372
  // plugin adapter wires to the Host logger (a miss must never break a write).
366
373
  this._autoTag = { applied: 0, misses: 0, lastMissAt: null };
@@ -813,6 +820,20 @@ export class Memory {
813
820
  if (secretMeta) {
814
821
  payloadMeta = { ...(payloadMeta && typeof payloadMeta === 'object' ? payloadMeta : {}), ...secretMeta };
815
822
  }
823
+ // v1.7.3 (module 3): Pre-Ingest classification. The content is stored verbatim
824
+ // (the black box must work with no other service running); what changes is that
825
+ // the record now carries a category the READ path can enforce.
826
+ const sensitiveCategories = detectSensitive(content);
827
+ if (sensitiveCategories.length > 0) {
828
+ for (const category of sensitiveCategories) {
829
+ const tag = sensitiveTag(category);
830
+ if (!tagInfo.tags.includes(tag)) tagInfo.tags.push(tag);
831
+ }
832
+ const sensitiveMeta = sensitiveMetaFor(sensitiveCategories);
833
+ if (sensitiveMeta) {
834
+ payloadMeta = { ...(payloadMeta && typeof payloadMeta === 'object' ? payloadMeta : {}), ...sensitiveMeta };
835
+ }
836
+ }
816
837
  const payload = {
817
838
  content,
818
839
  tags: tagInfo.tags,
@@ -1245,7 +1266,13 @@ export class Memory {
1245
1266
  };
1246
1267
  }
1247
1268
  const job = await this.deletePipeline.request({ eventIds: ids, mode, reason });
1248
- if (mode === 'purge') await this.raw.tombstone(contentHashes, { at: this.clock.now() });
1269
+ if (mode === 'purge') {
1270
+ // v1.7.3 (module 2): tombstone BOTH granularities. The content hash covers
1271
+ // the fragment that was deleted; the turn id covers the raw turn it came
1272
+ // from, so `deep_raw` cannot hand back "the turn behind the deleted memory".
1273
+ const turnIds = await this.raw.turnIdsForHashes(contentHashes);
1274
+ await this.raw.tombstone({ hashes: contentHashes, turnIds, at: this.clock.now() });
1275
+ }
1249
1276
  const maintenance = await this.maintenance.run({ reason: `forget:${job.id}` });
1250
1277
  return { state: 'deleted', job: this.publicJob(job), maintenance: this.publicMaintenance(maintenance) };
1251
1278
  }
@@ -1327,7 +1354,7 @@ export class Memory {
1327
1354
  }
1328
1355
 
1329
1356
  /** The space-local read path. */
1330
- async _recallLocal({ text = '', tags = [], topK, maxAssociativeHops, includeSecret = false } = {}, { mergeRecall = true } = {}) {
1357
+ async _recallLocal({ text = '', tags = [], topK, maxAssociativeHops, includeSecret = false, allowSensitive = false } = {}, { mergeRecall = true } = {}) {
1331
1358
  this.assertOpen();
1332
1359
  const now = this.clock.now();
1333
1360
  // v1.6.9: validated BEFORE any work (and before the empty-index shortcut) so an
@@ -1400,9 +1427,12 @@ export class Memory {
1400
1427
  // v1.7.0 (M3): the last gate before a hit can reach the model. `withheld` is a
1401
1428
  // COUNT only — a caller may learn that something was withheld, never what it was.
1402
1429
  const visible = filterSecret(merged.hits, { includeSecret });
1430
+ // v1.7.3 (module 3): sensitive records are PHYSICALLY excluded unless the caller
1431
+ // passes `allow_sensitive`. The count is reported, the content never is.
1432
+ const cleared = filterSensitive(visible.list, { allowSensitive });
1403
1433
  const payload = {
1404
1434
  ...result,
1405
- hits: visible.list,
1435
+ hits: cleared.list,
1406
1436
  ...(merged.stats ? { merge: merged.stats } : {}),
1407
1437
  ghostHints: ghostPass.ghostHints,
1408
1438
  oversizedTagHints: result.oversizedTagHints ?? [],
@@ -1417,9 +1447,15 @@ export class Memory {
1417
1447
  ...(associations.length > 0 ? [`graph-associations:${associations.length}`] : []),
1418
1448
  ...(merged.stats ? [`read-merge:${merged.stats.total}`] : []),
1419
1449
  ...(visible.withheld > 0 ? [`privacy-withheld:${visible.withheld}`] : []),
1450
+ ...(cleared.withheld > 0 ? [`sensitive-withheld:${cleared.withheld}`] : []),
1420
1451
  ...(this._boot && this._boot.status !== 'ok' ? [`boot-check:${this._boot.status}`] : []),
1421
1452
  ],
1422
1453
  };
1454
+ // v1.7.4 activity ring: recorded by the RUNTIME (`index.js#noteRecallActivity`),
1455
+ // not here. In a multi-space profile a recall is routed through `spaces.run()`
1456
+ // and cross-space reads fan out to per-space `Memory` instances, so a hook at
1457
+ // this level only fires for whichever instance happened to serve the call and
1458
+ // the graph's default ring stayed empty. See index.js for the single hook.
1423
1459
  return this.applyPayloadBudget(payload);
1424
1460
  }
1425
1461
 
@@ -1626,6 +1662,8 @@ export class Memory {
1626
1662
  });
1627
1663
  }
1628
1664
  return this.raw.scan({
1665
+ // v1.7.3 (module 3): the raw scan is a read path like any other.
1666
+ allowSensitive: query.allowSensitive === true || query.allow_sensitive === true,
1629
1667
  text: query.text,
1630
1668
  startTime: query.startTime,
1631
1669
  endTime: query.endTime,
@@ -1971,6 +2009,67 @@ export class Memory {
1971
2009
  return { ...marker, active: marker.active === true };
1972
2010
  }
1973
2011
 
2012
+ /**
2013
+ * v1.7.4: keep an ACTIVE marker honest — it must EXPIRE with the pressure that
2014
+ * wrote it.
2015
+ *
2016
+ * Before this, `checkHandoff()` ran only when a request already could not fit, so
2017
+ * a marker was written at ≥80% pressure and then never cleared. The prompt kept
2018
+ * injecting "[交接标记] 上下文已接近原生窗口上限" every turn no matter how small the
2019
+ * conversation became — external compaction (billion-context) can drop the same
2020
+ * session from ~900k to ~120k tokens and the plugin had no way to notice. The model
2021
+ * trusted the claim and handed off "early" by design.
2022
+ *
2023
+ * Runs synchronously in the prompt path (state/handoff.json is a small JSON read and
2024
+ * nativeState() is pure arithmetic), because it has to be true for THIS turn.
2025
+ *
2026
+ * @param {{ usage?: { sessionId?: string|null, tokens?: number }|null, threshold?: number|null }} input
2027
+ * @returns {{ marker: object, cleared: boolean, relieved: boolean, ratio: number|null, reason: string }}
2028
+ */
2029
+ maintainHandoffMarker({ usage = null, ratio = null, threshold = null } = {}) {
2030
+ const marker = this.handoffState();
2031
+ if (!marker || marker.active !== true) {
2032
+ return { marker, cleared: false, relieved: false, ratio: null, reason: 'inactive' };
2033
+ }
2034
+ const limit = Number.isFinite(threshold) ? threshold : this.config?.context?.handoffClearRatio ?? HANDOFF_CLEAR_RATIO;
2035
+ // The host's own measurement (`tokenMeter.contextPressure`, threaded through
2036
+ // `guardRequest`) is authoritative. The local session counter is only a fallback:
2037
+ // nothing in the real host calls observeSessionTokens, so it is usually EMPTY — and
2038
+ // an absent ratio must never be mistaken for 0 pressure (that would clear a marker
2039
+ // that is still true).
2040
+ let projectedRatio = Number.isFinite(ratio) ? ratio : null;
2041
+ if (projectedRatio === null) {
2042
+ const sessionTokens = Number.isFinite(usage?.tokens) && usage.tokens > 0 ? usage.tokens : this.sessionUsage()?.tokens;
2043
+ if (!Number.isFinite(sessionTokens) || sessionTokens <= 0) {
2044
+ return { marker, cleared: false, relieved: false, ratio: null, reason: 'no-pressure' };
2045
+ }
2046
+ try {
2047
+ projectedRatio = this.context?.nativeState?.({ sessionTokens })?.projectedRatio ?? null;
2048
+ } catch {
2049
+ projectedRatio = null;
2050
+ }
2051
+ }
2052
+ if (!Number.isFinite(projectedRatio)) {
2053
+ return { marker, cleared: false, relieved: false, ratio: null, reason: 'no-pressure' };
2054
+ }
2055
+ const decision = relievedDecision({ markerRatio: marker.ratio ?? null, projectedRatio, threshold: limit });
2056
+ if (!decision.relieved) {
2057
+ return { marker, cleared: false, relieved: false, ratio: projectedRatio, reason: decision.reason };
2058
+ }
2059
+ const consumedBy = usage?.sessionId ?? null;
2060
+ let cleared = marker;
2061
+ try {
2062
+ cleared = this.clearHandoff({
2063
+ reason: `pressure-relieved:${decision.reason}`,
2064
+ consumedBy: `${consumedBy ?? 'unknown'}:ratio=${projectedRatio}`,
2065
+ });
2066
+ } catch {
2067
+ /* a stale marker is bad, but failing the prompt would be worse */
2068
+ return { marker, cleared: false, relieved: true, ratio: projectedRatio, reason: `${decision.reason}:write-failed` };
2069
+ }
2070
+ return { marker: cleared, cleared: true, relieved: true, ratio: projectedRatio, reason: decision.reason };
2071
+ }
2072
+
1974
2073
  /** Mark a handoff consumed (new session, or an explicit clear). */
1975
2074
  clearHandoff({ reason = 'manual', consumedBy = null } = {}) {
1976
2075
  const current = readJson(this.handoffPath(), null);
@@ -2431,6 +2530,27 @@ export class Memory {
2431
2530
  } catch (error) {
2432
2531
  report.rawIndexError = error instanceof Error ? error.message : String(error);
2433
2532
  }
2533
+ // v1.7.3 (module 2): one-time migration of the OLD tombstone format. Up to 1.7.2 a
2534
+ // purge appended `{type:'raw_tombstone'}` lines INTO the day shards; that made the
2535
+ // shards stop being "turns in append order" and re-scanning them on every read was
2536
+ // the real cost. Move those keys into the overlay, then rewrite the shards clean.
2537
+ try {
2538
+ const legacy = this.raw._loadTombstones?.();
2539
+ if (legacy && legacy.size > 0) {
2540
+ const bytesBefore = await this.raw.shardBytes?.();
2541
+ report.rawTombstoneMigration = await this.raw.stripLegacyTombstoneLines({ limit: 50 });
2542
+ report.rawTombstoneMigration.bytesBefore = bytesBefore ?? null;
2543
+ if (report.rawTombstoneMigration.removedLines > 0) {
2544
+ this.logger?.info?.(
2545
+ `raw tombstones moved to state/raw-tombstones.json: ${report.rawTombstoneMigration.removedLines} legacy lines`,
2546
+ );
2547
+ }
2548
+ } else {
2549
+ report.rawTombstoneMigration = { shards: 0, removedLines: 0, skipped: true };
2550
+ }
2551
+ } catch (error) {
2552
+ report.rawTombstoneMigrationError = error instanceof Error ? error.message : String(error);
2553
+ }
2434
2554
  try {
2435
2555
  const due = this.pendingDeletes.due(this.clock.now());
2436
2556
  const promoted = [];
@@ -2440,7 +2560,10 @@ export class Memory {
2440
2560
  .map((id) => sha256(snapshot.records.find((record) => record.event_id === id)?.content ?? ''))
2441
2561
  .filter(Boolean);
2442
2562
  await this.deletePipeline.request({ eventIds: item.eventIds, mode: item.mode, reason: item.reason });
2443
- if (item.mode === 'purge') await this.raw.tombstone(hashes, { at: this.clock.now() });
2563
+ if (item.mode === 'purge') {
2564
+ const turnIds = await this.raw.turnIdsForHashes(hashes);
2565
+ await this.raw.tombstone({ hashes, turnIds, at: this.clock.now() });
2566
+ }
2444
2567
  this.pendingDeletes.remove(item.id);
2445
2568
  promoted.push({ id: item.id, events: item.eventIds.length });
2446
2569
  }
package/src/policy.js CHANGED
@@ -333,6 +333,20 @@ export function hashPolicy(policy) {
333
333
  /** tag token normalisation: trim, lowercase, collapse separators. */
334
334
  export function normaliseTagToken(token) {
335
335
  if (typeof token !== 'string') return '';
336
+ // v1.7.3 (module 3): `sensitive:*` categories are a READ-PATH CONTRACT — the gate
337
+ // matches the literal prefix and external consumers key on `sensitive:api_key`.
338
+ // Collapsing `_` to `-` here would silently rename the contract to `api-key`, so
339
+ // this one family keeps its separators (spaces still normalise).
340
+ const lowered = token.trim().toLowerCase();
341
+ if (lowered.startsWith('sensitive:')) {
342
+ const head = lowered.slice(0, 'sensitive:'.length);
343
+ const tail = lowered
344
+ .slice('sensitive:'.length)
345
+ .replace(/\s+/g, '-')
346
+ .replace(/-+/g, '-')
347
+ .replace(/^-|-$/g, '');
348
+ return (head + tail).slice(0, 64);
349
+ }
336
350
  return token
337
351
  .trim()
338
352
  .toLowerCase()
package/src/rawStore.js CHANGED
@@ -30,6 +30,8 @@ import { RawArchive, archiveMonthOf, isArchiveName, scanGzipArchive } from './ra
30
30
  import { engineForArchive } from './compression.js';
31
31
  import { buildIndex, indexFileFor, isIndexFile, readIndex, shardOverlapsWindow, writeIndex } from './rawIndex.js';
32
32
  import { detectCiphertext } from './entropy.js';
33
+ import { RawTombstoneStore, RAW_TOMBSTONE_FILE } from './tombstones.js';
34
+ import { detectSensitive } from './sensitive.js';
33
35
 
34
36
  export const RAW_DIR = 'raw';
35
37
  /** Records queued before a forced flush. */
@@ -212,7 +214,13 @@ export class RawStore {
212
214
  this._flushChain = Promise.resolve();
213
215
  this._hashes = new Map(); // day -> Set(sha256)
214
216
  this._dayBytes = new Map(); // day -> bytes
215
- this._tombstones = null; // Set(sha256), loaded lazily
217
+ /**
218
+ * v1.7.3 (module 2): tombstone keys live in `state/raw-tombstones.json`, NOT in the
219
+ * log. The shard files must contain turns and nothing else, so the overlay is an
220
+ * external read-time filter (`turn_id` + `content_hash`).
221
+ */
222
+ this.tombstones = new RawTombstoneStore({ file: path.join(dataDir, 'state', RAW_TOMBSTONE_FILE), clock });
223
+ this._legacyTombstones = null; // Set(sha256) parsed from pre-1.7.3 shard lines
216
224
  this._total = null;
217
225
  }
218
226
 
@@ -408,26 +416,40 @@ export class RawStore {
408
416
  this._flushChain = Promise.resolve();
409
417
  this._hashes.clear();
410
418
  this._dayBytes.clear();
411
- this._tombstones = null;
419
+ this._legacyTombstones = null;
412
420
  this._total = null;
413
421
  }
414
422
 
415
- /** Tombstone content hashes at the raw layer (called after a purge). */
416
- async tombstone(hashes = [], { at = this.clock.now() } = {}) {
417
- const unique = [...new Set(hashes)].filter(Boolean);
418
- if (unique.length === 0) return { tombstoned: 0 };
419
- ensureDir(this.dir);
420
- const day = dayKey(at);
421
- const lines = unique.map((hash) => JSON.stringify({ type: 'raw_tombstone', hash, timestamp: at }));
422
- await fs.promises.appendFile(this.dayFile(day), `${lines.join('\n')}\n`, 'utf8');
423
- if (this._tombstones) for (const hash of unique) this._tombstones.add(hash);
424
- this._total = null;
425
- this._dayBytes.delete(day);
426
- return { tombstoned: unique.length };
423
+ /**
424
+ * v1.7.3 (module 2): record tombstones in the OVERLAY, never in a shard.
425
+ *
426
+ * Accepts both keys because deletion happens at two granularities:
427
+ * - `hashes` — content fragments (an episode distilled out of a turn);
428
+ * - `turnIds` — whole captured turns (`turn_<seq>_<role>`).
429
+ * Nothing is appended to `raw/*.jsonl`, which is what keeps the log "turns only".
430
+ */
431
+ async tombstone({ hashes = [], turnIds = [], at = this.clock.now() } = {}) {
432
+ const cleanHashes = [...new Set(hashes)].filter((hash) => typeof hash === 'string' && hash.length > 0);
433
+ const cleanTurns = [...new Set(turnIds)].filter((id) => typeof id === 'string' && id.length > 0);
434
+ if (cleanHashes.length === 0 && cleanTurns.length === 0) return { tombstoned: 0, added: 0 };
435
+ const result = this.tombstones.add({ turnIds: cleanTurns, contentHashes: cleanHashes, at });
436
+ return {
437
+ tombstoned: cleanHashes.length + cleanTurns.length,
438
+ added: result.added,
439
+ total: result.total,
440
+ file: this.tombstones.file,
441
+ };
442
+ }
443
+
444
+ /** Undo a purge (used by `restore` when the events are still in the log). */
445
+ async untombstone({ hashes = [], turnIds = [] } = {}) {
446
+ const removed = this.tombstones.remove({ turnIds, contentHashes: hashes });
447
+ return { restored: removed };
427
448
  }
428
449
 
450
+ /** Legacy `{type:'raw_tombstone'}` lines written by <=1.7.2 (read-only fallback). */
429
451
  _loadTombstones() {
430
- if (this._tombstones) return this._tombstones;
452
+ if (this._legacyTombstones) return this._legacyTombstones;
431
453
  const set = new Set();
432
454
  for (const name of this.listShards()) {
433
455
  try {
@@ -445,10 +467,115 @@ export class RawStore {
445
467
  if (!error || error.code !== 'ENOENT') throw error;
446
468
  }
447
469
  }
448
- this._tombstones = set;
470
+ this._legacyTombstones = set;
449
471
  return set;
450
472
  }
451
473
 
474
+ /**
475
+ * One-time migration: physically remove `raw_tombstone` lines from every shard.
476
+ *
477
+ * Rewriting a shard is normally forbidden (append-only), and the ONLY exception is
478
+ * this: a bookkeeping line is not a turn, and leaving it in place means every
479
+ * reader has to keep special-casing it. Turn lines are copied byte-for-byte, so the
480
+ * log's turn content and order are unchanged; the keys are already in the overlay
481
+ * by the time the rewrite runs.
482
+ */
483
+ async stripLegacyTombstoneLines({ limit = Infinity } = {}) {
484
+ const report = { shards: 0, removedLines: 0, bytesBefore: 0, bytesAfter: 0, skipped: 0 };
485
+ if (!fs.existsSync(this.dir)) return report;
486
+ for (const name of this.listShards()) {
487
+ if (report.shards >= limit) break;
488
+ const file = path.join(this.dir, name);
489
+ let text;
490
+ try {
491
+ text = fs.readFileSync(file, 'utf8');
492
+ } catch (error) {
493
+ if (error && error.code === 'ENOENT') continue;
494
+ throw error;
495
+ }
496
+ if (!text.includes('"raw_tombstone"')) continue;
497
+ report.shards += 1;
498
+ report.bytesBefore += Buffer.byteLength(text, 'utf8');
499
+ const kept = [];
500
+ let removed = 0;
501
+ for (const line of text.split('\n')) {
502
+ if (line.includes('"raw_tombstone"')) {
503
+ let record = null;
504
+ try {
505
+ record = JSON.parse(line);
506
+ } catch {
507
+ record = null;
508
+ }
509
+ if (record && record.type === 'raw_tombstone') {
510
+ // Preserve the key before dropping the line, so a crash mid-rewrite cannot
511
+ // resurrect content that was already purged.
512
+ if (record.hash) this.tombstones.add({ contentHashes: [record.hash], at: record.timestamp ?? this.clock.now() });
513
+ removed += 1;
514
+ continue;
515
+ }
516
+ }
517
+ if (line.length > 0) kept.push(line);
518
+ }
519
+ if (removed === 0) continue;
520
+ const next = kept.length > 0 ? `${kept.join('\n')}\n` : '';
521
+ const temp = `${file}.tmp-clean`;
522
+ fs.writeFileSync(temp, next, 'utf8');
523
+ fs.renameSync(temp, file);
524
+ report.removedLines += removed;
525
+ report.bytesAfter += Buffer.byteLength(next, 'utf8');
526
+ this._dayBytes.delete(name.replace('.jsonl', ''));
527
+ this._hashes.delete(name.replace('.jsonl', ''));
528
+ }
529
+ this._legacyTombstones = new Set();
530
+ this._total = null;
531
+ return report;
532
+ }
533
+
534
+ /** True when a raw record is tombstoned by turn id OR by content hash. */
535
+ _isTombstoned(record) {
536
+ if (!record) return true;
537
+ if (this.tombstones.has({ turnId: record.turn_id, contentHash: sha256(record.content) })) return true;
538
+ return this._loadTombstones().has(sha256(record.content));
539
+ }
540
+
541
+ /** Overlay status for the panel/`/memory status`. */
542
+ tombstoneStatus() {
543
+ return { ...this.tombstones.status(), legacyLines: this._loadTombstones().size };
544
+ }
545
+
546
+ /**
547
+ * v1.7.3 (module 2): which raw TURNS produced these content hashes?
548
+ *
549
+ * A purge knows the episode ids and their content hashes, but the overlay also has
550
+ * to match at `turn_id` granularity — otherwise `deep_raw` could still find the
551
+ * turn that the deleted episode was distilled from. Deleting is rare, so one bounded
552
+ * pass over the shards is an acceptable price for a 100%-matching overlay.
553
+ */
554
+ async turnIdsForHashes(hashes = []) {
555
+ const wanted = new Set((Array.isArray(hashes) ? hashes : []).filter((hash) => typeof hash === 'string' && hash.length > 0));
556
+ if (wanted.size === 0) return [];
557
+ const found = new Set();
558
+ for (const name of this.listShards()) {
559
+ try {
560
+ for await (const line of readLinesForward(path.join(this.dir, name))) {
561
+ if (line.length === 0) continue;
562
+ let record;
563
+ try {
564
+ record = JSON.parse(line);
565
+ } catch {
566
+ continue;
567
+ }
568
+ if (typeof record?.turn_id !== 'string' || typeof record?.content !== 'string') continue;
569
+ if (wanted.has(sha256(record.content))) found.add(record.turn_id);
570
+ }
571
+ } catch (error) {
572
+ if (error && error.code === 'ENOENT') continue;
573
+ throw error;
574
+ }
575
+ }
576
+ return [...found];
577
+ }
578
+
452
579
  /** Non-empty line count of one shard (bounded streaming pass, no full read). */
453
580
  async _countLines(file) {
454
581
  let total = 0;
@@ -466,7 +593,7 @@ export class RawStore {
466
593
  * Bounded deep scan with a mandatory time window (enforced by the caller) and
467
594
  * a token budget. Returns redacted snippets; disk remains plaintext.
468
595
  */
469
- async scan({ text = '', startTime, endTime, limit = 20, regex = false, maxTokens } = {}) {
596
+ async scan({ text = '', startTime, endTime, limit = 20, regex = false, maxTokens, allowSensitive = false } = {}) {
470
597
  const config = this.config();
471
598
  if (!config || config.mode === 'off') {
472
599
  throw new MemoryError(ErrorCodes.RAW_DISABLED, 'raw storage is disabled (raw.mode=off); enable it to use deep_raw', {
@@ -520,7 +647,7 @@ export class RawStore {
520
647
  const hits = [];
521
648
  const archiveErrors = [];
522
649
  const notes = [];
523
- const scanned = { turns: 0, bytes: 0, shards: 0, tombstonesSkipped: 0, peakBufferBytes: 0 };
650
+ const scanned = { turns: 0, bytes: 0, shards: 0, tombstonesSkipped: 0, sensitiveSkipped: 0, peakBufferBytes: 0 };
524
651
  // The caller's `limit` is advisory; the engine enforces its own ceiling so a
525
652
  // direct embedder can never request an unbounded result set.
526
653
  const effectiveLimit = Math.min(Math.max(1, Math.floor(Number(limit) || 20)), MAX_SCAN_RESULTS);
@@ -570,10 +697,17 @@ export class RawStore {
570
697
  // A raw turn carries no `type`: the four-field shape is the record.
571
698
  if (typeof record.turn_id !== 'string' || typeof record.content !== 'string') continue;
572
699
  if (record.timestamp < startTime || record.timestamp > endTime) continue;
573
- if (tombstones.has(sha256(record.content))) {
700
+ if (this._isTombstoned(record)) {
574
701
  scanned.tombstonesSkipped += 1;
575
702
  continue;
576
703
  }
704
+ // v1.7.3 (module 3): a sensitive turn is physically excluded unless the
705
+ // caller presented the opt-in. The raw bytes stay on disk (plaintext by
706
+ // design); the read path is the gate.
707
+ if (allowSensitive !== true && detectSensitive(record.content).length > 0) {
708
+ scanned.sensitiveSkipped += 1;
709
+ continue;
710
+ }
577
711
  const haystack = record.content;
578
712
  if (!matcher.test(haystack)) continue;
579
713
  const at = needle ? haystack.toLowerCase().indexOf(needle.toLowerCase()) : 0;
@@ -622,10 +756,14 @@ export class RawStore {
622
756
  if (record?.type === 'raw_tombstone') return true;
623
757
  if (typeof record?.turn_id !== 'string' || typeof record?.content !== 'string') return true;
624
758
  if (record.timestamp < startTime || record.timestamp > endTime) return true;
625
- if (tombstones.has(sha256(record.content))) {
759
+ if (this._isTombstoned(record)) {
626
760
  scanned.tombstonesSkipped += 1;
627
761
  return true;
628
762
  }
763
+ if (allowSensitive !== true && detectSensitive(record.content).length > 0) {
764
+ scanned.sensitiveSkipped += 1;
765
+ return true;
766
+ }
629
767
  if (!matcher.test(record.content)) return true;
630
768
  const at = needle ? record.content.toLowerCase().indexOf(needle.toLowerCase()) : 0;
631
769
  const snippet = redactSecrets(record.content.slice(Math.max(0, at - 120), at + 120 + needle.length));
@@ -855,12 +993,12 @@ export class RawStore {
855
993
  throw error;
856
994
  }
857
995
  }
858
- if (hashes.size > 0) await this.tombstone([...hashes], { at: now });
996
+ if (hashes.size > 0) await this.tombstone({ hashes: [...hashes], at: now });
859
997
  if (removed.length > 0) {
860
998
  this._total = null;
861
999
  this._hashes.clear();
862
1000
  this._dayBytes.clear();
863
- this._tombstones = null;
1001
+ this._legacyTombstones = null;
864
1002
  }
865
1003
  return { enabled: true, removed, freedBytes: freed, tombstoned: hashes.size, hotWindowDays: windowDays };
866
1004
  }
@@ -910,7 +1048,7 @@ export class RawStore {
910
1048
  this._total = null;
911
1049
  this._hashes.clear();
912
1050
  this._dayBytes.clear();
913
- this._tombstones = null;
1051
+ this._legacyTombstones = null;
914
1052
  if (removedArchives.length > 0) {
915
1053
  try {
916
1054
  const state = this.archive.readState();