dsh-layers-hippocampus 1.7.2 → 1.7.3

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.
@@ -116,3 +116,33 @@ export function rehandoffDecision({ markerRatio = null, projectedRatio = 0, same
116
116
  if (projectedRatio - base >= REHANDOFF_DELTA) return { rehandoff: true, reason: 'pressure-growth' };
117
117
  return { rehandoff: false, reason: 'below-delta' };
118
118
  }
119
+
120
+ /**
121
+ * v1.7.4: when does an ACTIVE handoff marker stop being true?
122
+ *
123
+ * `checkHandoff()` used to run only on the fail-fast path, and since 1.6.3 a
124
+ * conversation keeps its session id across a handoff, so the stale-session branch
125
+ * never fired either: once a marker went active NOTHING cleared it. The prompt then
126
+ * announced "context near the native window limit" on every single turn — even after
127
+ * the host compacted this conversation down to ~10% — and the model duly handed off
128
+ * early. Relief is observable: pressure below half the window, or a 30-point drop
129
+ * against the marker's own ratio, means the marker is no longer telling the truth.
130
+ */
131
+ export const HANDOFF_CLEAR_RATIO = 0.5;
132
+
133
+ /** How far pressure must fall below the marker's own ratio to count as relief. */
134
+ export const RELIEF_COLLAPSE_DELTA = 0.3;
135
+
136
+ /**
137
+ * @param {{ markerRatio?: number|null, projectedRatio?: number, threshold?: number }} input
138
+ * @returns {{ relieved: boolean, reason: string }}
139
+ */
140
+ export function relievedDecision({ markerRatio = null, projectedRatio = 0, threshold = HANDOFF_CLEAR_RATIO }) {
141
+ const limit = Number.isFinite(threshold) && threshold > 0 && threshold < 1 ? threshold : HANDOFF_CLEAR_RATIO;
142
+ const base = Number.isFinite(markerRatio) && markerRatio > 0 ? markerRatio : null;
143
+ if (projectedRatio <= limit) return { relieved: true, reason: 'below-clear-ratio' };
144
+ if (base !== null && projectedRatio <= base - RELIEF_COLLAPSE_DELTA) {
145
+ return { relieved: true, reason: 'pressure-collapsed' };
146
+ }
147
+ return { relieved: false, reason: 'pressure-still-high' };
148
+ }
package/src/errors.js CHANGED
@@ -150,6 +150,10 @@ export const ErrorCodes = Object.freeze({
150
150
  * paying for the prompt.
151
151
  */
152
152
  CONTEXT_EXCEEDED: 'MEM_E_CONTEXT_EXCEEDED',
153
+ // v1.7.3 (module 3): a caller asked for a specific record that carries a
154
+ // `sensitive:*` tag without passing `allow_sensitive`. Refusing loudly beats
155
+ // returning "[withheld]" and letting the caller believe the record is gone.
156
+ SENSITIVE_ACCESS_DENIED: 'MEM_E_SENSITIVE_ACCESS_DENIED',
153
157
  });
154
158
 
155
159
  export class MemoryError extends Error {
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) {
@@ -813,6 +816,20 @@ export class Memory {
813
816
  if (secretMeta) {
814
817
  payloadMeta = { ...(payloadMeta && typeof payloadMeta === 'object' ? payloadMeta : {}), ...secretMeta };
815
818
  }
819
+ // v1.7.3 (module 3): Pre-Ingest classification. The content is stored verbatim
820
+ // (the black box must work with no other service running); what changes is that
821
+ // the record now carries a category the READ path can enforce.
822
+ const sensitiveCategories = detectSensitive(content);
823
+ if (sensitiveCategories.length > 0) {
824
+ for (const category of sensitiveCategories) {
825
+ const tag = sensitiveTag(category);
826
+ if (!tagInfo.tags.includes(tag)) tagInfo.tags.push(tag);
827
+ }
828
+ const sensitiveMeta = sensitiveMetaFor(sensitiveCategories);
829
+ if (sensitiveMeta) {
830
+ payloadMeta = { ...(payloadMeta && typeof payloadMeta === 'object' ? payloadMeta : {}), ...sensitiveMeta };
831
+ }
832
+ }
816
833
  const payload = {
817
834
  content,
818
835
  tags: tagInfo.tags,
@@ -1245,7 +1262,13 @@ export class Memory {
1245
1262
  };
1246
1263
  }
1247
1264
  const job = await this.deletePipeline.request({ eventIds: ids, mode, reason });
1248
- if (mode === 'purge') await this.raw.tombstone(contentHashes, { at: this.clock.now() });
1265
+ if (mode === 'purge') {
1266
+ // v1.7.3 (module 2): tombstone BOTH granularities. The content hash covers
1267
+ // the fragment that was deleted; the turn id covers the raw turn it came
1268
+ // from, so `deep_raw` cannot hand back "the turn behind the deleted memory".
1269
+ const turnIds = await this.raw.turnIdsForHashes(contentHashes);
1270
+ await this.raw.tombstone({ hashes: contentHashes, turnIds, at: this.clock.now() });
1271
+ }
1249
1272
  const maintenance = await this.maintenance.run({ reason: `forget:${job.id}` });
1250
1273
  return { state: 'deleted', job: this.publicJob(job), maintenance: this.publicMaintenance(maintenance) };
1251
1274
  }
@@ -1327,7 +1350,7 @@ export class Memory {
1327
1350
  }
1328
1351
 
1329
1352
  /** The space-local read path. */
1330
- async _recallLocal({ text = '', tags = [], topK, maxAssociativeHops, includeSecret = false } = {}, { mergeRecall = true } = {}) {
1353
+ async _recallLocal({ text = '', tags = [], topK, maxAssociativeHops, includeSecret = false, allowSensitive = false } = {}, { mergeRecall = true } = {}) {
1331
1354
  this.assertOpen();
1332
1355
  const now = this.clock.now();
1333
1356
  // v1.6.9: validated BEFORE any work (and before the empty-index shortcut) so an
@@ -1400,9 +1423,12 @@ export class Memory {
1400
1423
  // v1.7.0 (M3): the last gate before a hit can reach the model. `withheld` is a
1401
1424
  // COUNT only — a caller may learn that something was withheld, never what it was.
1402
1425
  const visible = filterSecret(merged.hits, { includeSecret });
1426
+ // v1.7.3 (module 3): sensitive records are PHYSICALLY excluded unless the caller
1427
+ // passes `allow_sensitive`. The count is reported, the content never is.
1428
+ const cleared = filterSensitive(visible.list, { allowSensitive });
1403
1429
  const payload = {
1404
1430
  ...result,
1405
- hits: visible.list,
1431
+ hits: cleared.list,
1406
1432
  ...(merged.stats ? { merge: merged.stats } : {}),
1407
1433
  ghostHints: ghostPass.ghostHints,
1408
1434
  oversizedTagHints: result.oversizedTagHints ?? [],
@@ -1417,6 +1443,7 @@ export class Memory {
1417
1443
  ...(associations.length > 0 ? [`graph-associations:${associations.length}`] : []),
1418
1444
  ...(merged.stats ? [`read-merge:${merged.stats.total}`] : []),
1419
1445
  ...(visible.withheld > 0 ? [`privacy-withheld:${visible.withheld}`] : []),
1446
+ ...(cleared.withheld > 0 ? [`sensitive-withheld:${cleared.withheld}`] : []),
1420
1447
  ...(this._boot && this._boot.status !== 'ok' ? [`boot-check:${this._boot.status}`] : []),
1421
1448
  ],
1422
1449
  };
@@ -1626,6 +1653,8 @@ export class Memory {
1626
1653
  });
1627
1654
  }
1628
1655
  return this.raw.scan({
1656
+ // v1.7.3 (module 3): the raw scan is a read path like any other.
1657
+ allowSensitive: query.allowSensitive === true || query.allow_sensitive === true,
1629
1658
  text: query.text,
1630
1659
  startTime: query.startTime,
1631
1660
  endTime: query.endTime,
@@ -1971,6 +2000,67 @@ export class Memory {
1971
2000
  return { ...marker, active: marker.active === true };
1972
2001
  }
1973
2002
 
2003
+ /**
2004
+ * v1.7.4: keep an ACTIVE marker honest — it must EXPIRE with the pressure that
2005
+ * wrote it.
2006
+ *
2007
+ * Before this, `checkHandoff()` ran only when a request already could not fit, so
2008
+ * a marker was written at ≥80% pressure and then never cleared. The prompt kept
2009
+ * injecting "[交接标记] 上下文已接近原生窗口上限" every turn no matter how small the
2010
+ * conversation became — external compaction (billion-context) can drop the same
2011
+ * session from ~900k to ~120k tokens and the plugin had no way to notice. The model
2012
+ * trusted the claim and handed off "early" by design.
2013
+ *
2014
+ * Runs synchronously in the prompt path (state/handoff.json is a small JSON read and
2015
+ * nativeState() is pure arithmetic), because it has to be true for THIS turn.
2016
+ *
2017
+ * @param {{ usage?: { sessionId?: string|null, tokens?: number }|null, threshold?: number|null }} input
2018
+ * @returns {{ marker: object, cleared: boolean, relieved: boolean, ratio: number|null, reason: string }}
2019
+ */
2020
+ maintainHandoffMarker({ usage = null, ratio = null, threshold = null } = {}) {
2021
+ const marker = this.handoffState();
2022
+ if (!marker || marker.active !== true) {
2023
+ return { marker, cleared: false, relieved: false, ratio: null, reason: 'inactive' };
2024
+ }
2025
+ const limit = Number.isFinite(threshold) ? threshold : this.config?.context?.handoffClearRatio ?? HANDOFF_CLEAR_RATIO;
2026
+ // The host's own measurement (`tokenMeter.contextPressure`, threaded through
2027
+ // `guardRequest`) is authoritative. The local session counter is only a fallback:
2028
+ // nothing in the real host calls observeSessionTokens, so it is usually EMPTY — and
2029
+ // an absent ratio must never be mistaken for 0 pressure (that would clear a marker
2030
+ // that is still true).
2031
+ let projectedRatio = Number.isFinite(ratio) ? ratio : null;
2032
+ if (projectedRatio === null) {
2033
+ const sessionTokens = Number.isFinite(usage?.tokens) && usage.tokens > 0 ? usage.tokens : this.sessionUsage()?.tokens;
2034
+ if (!Number.isFinite(sessionTokens) || sessionTokens <= 0) {
2035
+ return { marker, cleared: false, relieved: false, ratio: null, reason: 'no-pressure' };
2036
+ }
2037
+ try {
2038
+ projectedRatio = this.context?.nativeState?.({ sessionTokens })?.projectedRatio ?? null;
2039
+ } catch {
2040
+ projectedRatio = null;
2041
+ }
2042
+ }
2043
+ if (!Number.isFinite(projectedRatio)) {
2044
+ return { marker, cleared: false, relieved: false, ratio: null, reason: 'no-pressure' };
2045
+ }
2046
+ const decision = relievedDecision({ markerRatio: marker.ratio ?? null, projectedRatio, threshold: limit });
2047
+ if (!decision.relieved) {
2048
+ return { marker, cleared: false, relieved: false, ratio: projectedRatio, reason: decision.reason };
2049
+ }
2050
+ const consumedBy = usage?.sessionId ?? null;
2051
+ let cleared = marker;
2052
+ try {
2053
+ cleared = this.clearHandoff({
2054
+ reason: `pressure-relieved:${decision.reason}`,
2055
+ consumedBy: `${consumedBy ?? 'unknown'}:ratio=${projectedRatio}`,
2056
+ });
2057
+ } catch {
2058
+ /* a stale marker is bad, but failing the prompt would be worse */
2059
+ return { marker, cleared: false, relieved: true, ratio: projectedRatio, reason: `${decision.reason}:write-failed` };
2060
+ }
2061
+ return { marker: cleared, cleared: true, relieved: true, ratio: projectedRatio, reason: decision.reason };
2062
+ }
2063
+
1974
2064
  /** Mark a handoff consumed (new session, or an explicit clear). */
1975
2065
  clearHandoff({ reason = 'manual', consumedBy = null } = {}) {
1976
2066
  const current = readJson(this.handoffPath(), null);
@@ -2431,6 +2521,27 @@ export class Memory {
2431
2521
  } catch (error) {
2432
2522
  report.rawIndexError = error instanceof Error ? error.message : String(error);
2433
2523
  }
2524
+ // v1.7.3 (module 2): one-time migration of the OLD tombstone format. Up to 1.7.2 a
2525
+ // purge appended `{type:'raw_tombstone'}` lines INTO the day shards; that made the
2526
+ // shards stop being "turns in append order" and re-scanning them on every read was
2527
+ // the real cost. Move those keys into the overlay, then rewrite the shards clean.
2528
+ try {
2529
+ const legacy = this.raw._loadTombstones?.();
2530
+ if (legacy && legacy.size > 0) {
2531
+ const bytesBefore = await this.raw.shardBytes?.();
2532
+ report.rawTombstoneMigration = await this.raw.stripLegacyTombstoneLines({ limit: 50 });
2533
+ report.rawTombstoneMigration.bytesBefore = bytesBefore ?? null;
2534
+ if (report.rawTombstoneMigration.removedLines > 0) {
2535
+ this.logger?.info?.(
2536
+ `raw tombstones moved to state/raw-tombstones.json: ${report.rawTombstoneMigration.removedLines} legacy lines`,
2537
+ );
2538
+ }
2539
+ } else {
2540
+ report.rawTombstoneMigration = { shards: 0, removedLines: 0, skipped: true };
2541
+ }
2542
+ } catch (error) {
2543
+ report.rawTombstoneMigrationError = error instanceof Error ? error.message : String(error);
2544
+ }
2434
2545
  try {
2435
2546
  const due = this.pendingDeletes.due(this.clock.now());
2436
2547
  const promoted = [];
@@ -2440,7 +2551,10 @@ export class Memory {
2440
2551
  .map((id) => sha256(snapshot.records.find((record) => record.event_id === id)?.content ?? ''))
2441
2552
  .filter(Boolean);
2442
2553
  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() });
2554
+ if (item.mode === 'purge') {
2555
+ const turnIds = await this.raw.turnIdsForHashes(hashes);
2556
+ await this.raw.tombstone({ hashes, turnIds, at: this.clock.now() });
2557
+ }
2444
2558
  this.pendingDeletes.remove(item.id);
2445
2559
  promoted.push({ id: item.id, events: item.eventIds.length });
2446
2560
  }
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();
@@ -0,0 +1,130 @@
1
+ /**
2
+ * v1.7.3 (module 3): cross-platform sensitive tags + read-time hard block.
3
+ *
4
+ * Replaces the single coarse `privacy:secret` marker with THREE categories, because
5
+ * "secret" cannot be acted on: a credential may be rotated, an API key may be
6
+ * scrapped, PII may be reported — but the correct response differs per category.
7
+ *
8
+ * sensitive:api_key — a token/API key that can be rotated
9
+ * sensitive:credential — a password / private key / connection string
10
+ * sensitive:pii — personal data (email, phone, card, ID number)
11
+ *
12
+ * The raw log keeps the PLAINTEXT on purpose: the black box has to be useful on a
13
+ * machine with no other service running, so the protection is a READ-TIME filter,
14
+ * not encryption (encryption without a key store is theatre).
15
+ *
16
+ * `privacy:secret` still exists as a deprecated alias: old records keep working, and
17
+ * a caller passing `includeSecret` keeps seeing them, but nothing new is written
18
+ * with it.
19
+ */
20
+
21
+ import { PRIVACY_SECRET_TAG } from './privacy.js';
22
+
23
+ export const SENSITIVE_TAG_PREFIX = 'sensitive:';
24
+ /** Ordered: more specific categories win when several patterns match. */
25
+ export const SENSITIVE_CATEGORIES = Object.freeze(['credential', 'api_key', 'pii']);
26
+ export const SENSITIVE_WITHHOLD_TEXT = '[System: 包含敏感内容,已被拦截]';
27
+
28
+ /** Assignment of a secret to a name: `password = ...`, `api_key: ...`, `token=...`. */
29
+ const CREDENTIAL_ASSIGNMENT =
30
+ /(?:^|[\s"'`((])(?:password|passwd|pwd|secret|private[_ -]?key|client[_ -]?secret|access[_ -]?token|auth[_ -]?token|connection[_ -]?string)\s*[:=]\s*\S{6,}/i;
31
+ /** Private key blocks. */
32
+ const PRIVATE_KEY_BLOCK = /-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/;
33
+ /** Well-known key shapes: OpenAI/DeepSeek style `sk-…`, GitHub `ghp_…`, AWS `AKIA…`, generic `xoxb-`. */
34
+ const KEY_SHAPES = [
35
+ /\bsk-[A-Za-z0-9_-]{16,}\b/,
36
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/,
37
+ /\bAKIA[0-9A-Z]{16}\b/,
38
+ /\bxox[abposr]-[A-Za-z0-9-]{10,}\b/,
39
+ /\bAIza[0-9A-Za-z_-]{30,}\b/,
40
+ ];
41
+ /** PII: email, CN mobile, landline, 15/16/18-digit card/ID numbers. */
42
+ const PII_PATTERNS = [
43
+ /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/,
44
+ /\b(?:\+?86[- ]?)?1[3-9]\d{9}\b/,
45
+ /\b0\d{2,3}-\d{7,8}\b/,
46
+ /\b(?:\d[ -]?){15,18}\b/,
47
+ ];
48
+
49
+ /**
50
+ * Classify a piece of text. Returns the matched categories (specific first, may be
51
+ * empty). Pure and deterministic: same bytes in, same answer out, no network, no
52
+ * model call — this runs on the ingest path.
53
+ */
54
+ export function detectSensitive(text) {
55
+ const value = typeof text === 'string' ? text : '';
56
+ if (value.length === 0) return [];
57
+ const found = [];
58
+ if (CREDENTIAL_ASSIGNMENT.test(value) || PRIVATE_KEY_BLOCK.test(value)) found.push('credential');
59
+ if (KEY_SHAPES.some((pattern) => pattern.test(value))) found.push('api_key');
60
+ if (PII_PATTERNS.some((pattern) => pattern.test(value))) found.push('pii');
61
+ return SENSITIVE_CATEGORIES.filter((category) => found.includes(category));
62
+ }
63
+
64
+ /** The tag this machine writes for a category. */
65
+ export function sensitiveTag(category) {
66
+ return `${SENSITIVE_TAG_PREFIX}${category}`;
67
+ }
68
+
69
+ /** Categories carried by a tag list (strings or `{tag,strength}` records). */
70
+ export function sensitiveCategoriesOf(tags) {
71
+ const out = new Set();
72
+ for (const entry of Array.isArray(tags) ? tags : []) {
73
+ const name = typeof entry === 'string' ? entry : entry?.tag;
74
+ if (typeof name !== 'string' || !name.startsWith(SENSITIVE_TAG_PREFIX)) continue;
75
+ const category = name.slice(SENSITIVE_TAG_PREFIX.length);
76
+ if (category.length > 0) out.add(category);
77
+ }
78
+ return [...out];
79
+ }
80
+
81
+ export function isSensitiveTags(tags) {
82
+ return sensitiveCategoriesOf(tags).length > 0;
83
+ }
84
+
85
+ /** A record is sensitive when its tags say so, or its metadata already recorded a category. */
86
+ export function isSensitiveRecord(record) {
87
+ if (!record || typeof record !== 'object') return false;
88
+ if (isSensitiveTags(record.tags)) return true;
89
+ const meta = record.meta ?? record.meta_json ?? null;
90
+ if (meta && typeof meta === 'object') {
91
+ if (Array.isArray(meta.sensitive) && meta.sensitive.length > 0) return true;
92
+ if (typeof meta.sensitive === 'string' && meta.sensitive.length > 0) return true;
93
+ }
94
+ return false;
95
+ }
96
+
97
+ /**
98
+ * Split records into visible / withheld. `allowSensitive` is the ONE switch: with it,
99
+ * every record passes (the caller asked, and the tool result says so); without it,
100
+ * sensitive records are physically dropped and counted so the caller can report
101
+ * "N withheld" instead of silently returning a shorter list.
102
+ */
103
+ export function filterSensitive(records, { allowSensitive = false } = {}) {
104
+ const list = Array.isArray(records) ? records : [];
105
+ if (allowSensitive) return { list, withheld: 0, categories: [] };
106
+ const kept = [];
107
+ const categories = new Set();
108
+ let withheld = 0;
109
+ for (const record of list) {
110
+ if (!isSensitiveRecord(record)) {
111
+ kept.push(record);
112
+ continue;
113
+ }
114
+ withheld += 1;
115
+ for (const category of sensitiveCategoriesOf(record.tags)) categories.add(category);
116
+ }
117
+ return { list: kept, withheld, categories: [...categories].sort() };
118
+ }
119
+
120
+ /** Metadata written onto an episode whose content was classified sensitive. */
121
+ export function sensitiveMetaFor(categories) {
122
+ const list = Array.isArray(categories) ? categories.filter(Boolean) : [];
123
+ if (list.length === 0) return null;
124
+ return { sensitive: list, sensitive_detected_by: 'hippocampus:detectSensitive' };
125
+ }
126
+
127
+ /** Deprecated alias: `privacy:secret` still filters, and the new tags are a superset. */
128
+ export function isLegacySecret(tags) {
129
+ return (Array.isArray(tags) ? tags : []).some((entry) => (typeof entry === 'string' ? entry : entry?.tag) === PRIVACY_SECRET_TAG);
130
+ }