@equationalapplications/core-llm-wiki 9.1.0 → 9.3.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.
package/dist/testing.js CHANGED
@@ -724,6 +724,15 @@ var SEVERITY = {
724
724
  resolve_failed: "warn",
725
725
  read_budget: "info",
726
726
  event_retention_held: "info",
727
+ prune_checkpoint_incomplete: "warn",
728
+ erase_secure_delete_off: "error",
729
+ erase_entity_skipped: "warn",
730
+ erase_retired_vtab_undroppable: "warn",
731
+ erase_retired_remaining: "error",
732
+ erase_tombstones_remaining: "error",
733
+ erase_retired_read_failed: "error",
734
+ erase_registry_sweep_skipped: "info",
735
+ import_tombstone_skipped: "info",
727
736
  event_created_at_clamped: "warn",
728
737
  event_created_at_restamped: "info",
729
738
  external_deletion_pending: "warn",
@@ -731,7 +740,12 @@ var SEVERITY = {
731
740
  guidance_too_long: "warn",
732
741
  guidance_resolver_failed: "warn",
733
742
  source_pointer_unresolved: "warn",
734
- source_pointer_invalid: "warn"
743
+ source_pointer_invalid: "warn",
744
+ source_store_source_too_large: "warn",
745
+ source_store_budget_exceeded: "warn",
746
+ source_store_hash_mismatch: "warn",
747
+ source_store_duplicate_hash: "warn",
748
+ source_store_text_not_storable: "warn"
735
749
  };
736
750
  var MESSAGE = {
737
751
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -754,6 +768,15 @@ var MESSAGE = {
754
768
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
755
769
  read_budget: "A read was packed to a token budget.",
756
770
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
771
+ prune_checkpoint_incomplete: "The post-VACUUM WAL checkpoint was incomplete while a prune partial failure was also reported; deleted bytes may remain in the WAL.",
772
+ erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
773
+ erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow tables were emptied and the name stays listed until an FTS5-capable open drops it.",
774
+ erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
775
+ erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
776
+ erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
777
+ erase_entity_skipped: "Erase skipped an entity because another operation held its prune lock.",
778
+ erase_registry_sweep_skipped: "Erase skipped the source_ref_index tombstone sweep because the table does not exist (pre-v9 store).",
779
+ import_tombstone_skipped: "Import skipped live dump rows (facts and tasks) whose ids were forgotten locally. The protection holds while the tombstone is retained; once a prune hard-deletes the row, an old dump can import the fact again \u2014 see the OKF guide\u2019s restore caveat.",
757
780
  event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
758
781
  event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
759
782
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
@@ -761,7 +784,12 @@ var MESSAGE = {
761
784
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
762
785
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
763
786
  source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
764
- source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
787
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
788
+ source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
789
+ source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
790
+ source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
791
+ source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
792
+ source_store_text_not_storable: "A source document text could not be stored as given."
765
793
  };
766
794
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
767
795
  function copyDetail(detail) {
@@ -1241,6 +1269,280 @@ function entitySummaryMetaKey(entityId) {
1241
1269
  return `entity_summary:${entityId}`;
1242
1270
  }
1243
1271
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1272
+ var CheckpointIncompleteError = class extends Error {
1273
+ constructor() {
1274
+ super(...arguments);
1275
+ this.code = "erase_checkpoint_incomplete";
1276
+ }
1277
+ };
1278
+ function generateId(prefix = "") {
1279
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1280
+ return prefix + crypto.randomUUID().replace(/-/g, "").substring(0, 24);
1281
+ }
1282
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
1283
+ const bytes = new Uint8Array(16);
1284
+ crypto.getRandomValues(bytes);
1285
+ return prefix + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("").substring(0, 24);
1286
+ }
1287
+ throw new Error(
1288
+ "generateId: no cryptographically secure random source available (crypto.randomUUID and crypto.getRandomValues are both missing, and no configureRandomSource() injection was provided)."
1289
+ );
1290
+ }
1291
+
1292
+ // src/utils/passageCutter.ts
1293
+ var MAX_PASSAGE_UNITS = 12e3;
1294
+ var WHITESPACE = /\s/;
1295
+ function isHigh(code) {
1296
+ return code >= 55296 && code <= 56319;
1297
+ }
1298
+ function isLow(code) {
1299
+ return code >= 56320 && code <= 57343;
1300
+ }
1301
+ function cutPassages(text, maxUnits = MAX_PASSAGE_UNITS) {
1302
+ const limit = Math.max(2, Math.floor(maxUnits));
1303
+ const spans = [];
1304
+ let start = 0;
1305
+ while (start < text.length) {
1306
+ if (text.length - start <= limit) {
1307
+ spans.push({ start, end: text.length });
1308
+ break;
1309
+ }
1310
+ let end = start + limit;
1311
+ let cut = -1;
1312
+ for (let i = end - 1; i > start; i--) {
1313
+ if (WHITESPACE.test(text[i])) {
1314
+ cut = i + 1;
1315
+ break;
1316
+ }
1317
+ }
1318
+ if (cut > start) {
1319
+ end = cut;
1320
+ } else if (isHigh(text.charCodeAt(end - 1)) && isLow(text.charCodeAt(end))) {
1321
+ end -= 1;
1322
+ }
1323
+ spans.push({ start, end });
1324
+ start = end;
1325
+ }
1326
+ return spans;
1327
+ }
1328
+
1329
+ // src/utils/sha256.ts
1330
+ var K = new Uint32Array([
1331
+ 1116352408,
1332
+ 1899447441,
1333
+ 3049323471,
1334
+ 3921009573,
1335
+ 961987163,
1336
+ 1508970993,
1337
+ 2453635748,
1338
+ 2870763221,
1339
+ 3624381080,
1340
+ 310598401,
1341
+ 607225278,
1342
+ 1426881987,
1343
+ 1925078388,
1344
+ 2162078206,
1345
+ 2614888103,
1346
+ 3248222580,
1347
+ 3835390401,
1348
+ 4022224774,
1349
+ 264347078,
1350
+ 604807628,
1351
+ 770255983,
1352
+ 1249150122,
1353
+ 1555081692,
1354
+ 1996064986,
1355
+ 2554220882,
1356
+ 2821834349,
1357
+ 2952996808,
1358
+ 3210313671,
1359
+ 3336571891,
1360
+ 3584528711,
1361
+ 113926993,
1362
+ 338241895,
1363
+ 666307205,
1364
+ 773529912,
1365
+ 1294757372,
1366
+ 1396182291,
1367
+ 1695183700,
1368
+ 1986661051,
1369
+ 2177026350,
1370
+ 2456956037,
1371
+ 2730485921,
1372
+ 2820302411,
1373
+ 3259730800,
1374
+ 3345764771,
1375
+ 3516065817,
1376
+ 3600352804,
1377
+ 4094571909,
1378
+ 275423344,
1379
+ 430227734,
1380
+ 506948616,
1381
+ 659060556,
1382
+ 883997877,
1383
+ 958139571,
1384
+ 1322822218,
1385
+ 1537002063,
1386
+ 1747873779,
1387
+ 1955562222,
1388
+ 2024104815,
1389
+ 2227730452,
1390
+ 2361852424,
1391
+ 2428436474,
1392
+ 2756734187,
1393
+ 3204031479,
1394
+ 3329325298
1395
+ ]);
1396
+ var rotr = (x, n) => x >>> n | x << 32 - n;
1397
+ var IV = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
1398
+ function compress(H, W, view, off) {
1399
+ for (let t = 0; t < 16; t++) W[t] = view.getUint32(off + t * 4);
1400
+ for (let t = 16; t < 64; t++) {
1401
+ const s0 = rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ W[t - 15] >>> 3;
1402
+ const s1 = rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ W[t - 2] >>> 10;
1403
+ W[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;
1404
+ }
1405
+ let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];
1406
+ for (let t = 0; t < 64; t++) {
1407
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
1408
+ const ch = e & f ^ ~e & g;
1409
+ const t1 = h + S1 + ch + K[t] + W[t] >>> 0;
1410
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
1411
+ const maj = a & b ^ a & c ^ b & c;
1412
+ const t2 = S0 + maj >>> 0;
1413
+ h = g;
1414
+ g = f;
1415
+ f = e;
1416
+ e = d + t1 >>> 0;
1417
+ d = c;
1418
+ c = b;
1419
+ b = a;
1420
+ a = t1 + t2 >>> 0;
1421
+ }
1422
+ H[0] = H[0] + a >>> 0;
1423
+ H[1] = H[1] + b >>> 0;
1424
+ H[2] = H[2] + c >>> 0;
1425
+ H[3] = H[3] + d >>> 0;
1426
+ H[4] = H[4] + e >>> 0;
1427
+ H[5] = H[5] + f >>> 0;
1428
+ H[6] = H[6] + g >>> 0;
1429
+ H[7] = H[7] + h >>> 0;
1430
+ }
1431
+ function sha256(bytes) {
1432
+ const H = new Uint32Array(IV);
1433
+ const W = new Uint32Array(64);
1434
+ const whole = bytes.length - bytes.length % 64;
1435
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1436
+ for (let off = 0; off < whole; off += 64) compress(H, W, view, off);
1437
+ const rest = bytes.subarray(whole);
1438
+ const bitLen = bytes.length * 8;
1439
+ const padded = new Uint8Array(rest.length + 9 + 63 >> 6 << 6);
1440
+ padded.set(rest);
1441
+ padded[rest.length] = 128;
1442
+ const pv = new DataView(padded.buffer);
1443
+ pv.setUint32(padded.length - 8, Math.floor(bitLen / 4294967296));
1444
+ pv.setUint32(padded.length - 4, bitLen >>> 0);
1445
+ for (let off = 0; off < padded.length; off += 64) compress(H, W, pv, off);
1446
+ const out = new Uint8Array(32);
1447
+ const outView = new DataView(out.buffer);
1448
+ for (let i = 0; i < 8; i++) outView.setUint32(i * 4, H[i]);
1449
+ return out;
1450
+ }
1451
+ function utf8Encode(s) {
1452
+ const out = [];
1453
+ for (let i = 0; i < s.length; i++) {
1454
+ let cp = s.charCodeAt(i);
1455
+ if (cp >= 55296 && cp <= 56319) {
1456
+ const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
1457
+ if (next >= 56320 && next <= 57343) {
1458
+ cp = 65536 + (cp - 55296 << 10) + (next - 56320);
1459
+ i++;
1460
+ } else {
1461
+ cp = 65533;
1462
+ }
1463
+ } else if (cp >= 56320 && cp <= 57343) {
1464
+ cp = 65533;
1465
+ }
1466
+ if (cp < 128) out.push(cp);
1467
+ else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63);
1468
+ else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
1469
+ else out.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
1470
+ }
1471
+ return Uint8Array.from(out);
1472
+ }
1473
+ function sha256Hex(text) {
1474
+ let hex = "";
1475
+ for (const b of sha256(utf8Encode(text))) hex += b.toString(16).padStart(2, "0");
1476
+ return hex;
1477
+ }
1478
+
1479
+ // src/services/sourceStoreUpsert.ts
1480
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
1481
+ async function upsertStoredSource(tx, prefix, entityId, src, limits, onRefusal, opts = {}) {
1482
+ const { sourceRef, sourceHash, text } = src;
1483
+ const refuse = (code) => {
1484
+ onRefusal(code);
1485
+ return { status: "refused" };
1486
+ };
1487
+ if (text.includes("\0") || LONE_SURROGATE.test(text)) return refuse("source_store_text_not_storable");
1488
+ if (text.length > limits.maxCharsPerSource) return refuse("source_store_source_too_large");
1489
+ const textHash = sha256Hex(text);
1490
+ const charCount = text.length;
1491
+ const docs = `${prefix}source_documents`;
1492
+ const passages = `${prefix}source_passages`;
1493
+ const registry = `${prefix}source_ref_index`;
1494
+ const existing = await tx.getFirstAsync(
1495
+ `SELECT id, source_hash, text_hash, char_count, created_at FROM ${docs}
1496
+ WHERE entity_id = ? AND source_ref = ?`,
1497
+ [entityId, sourceRef]
1498
+ );
1499
+ if (opts.idempotentSamePair && existing && existing.source_hash === sourceHash) {
1500
+ if (existing.text_hash !== textHash) return refuse("source_store_hash_mismatch");
1501
+ const row = await tx.getFirstAsync(
1502
+ `SELECT COUNT(*) AS n FROM ${passages} WHERE entity_id = ? AND document_id = ?`,
1503
+ [entityId, existing.id]
1504
+ );
1505
+ return { status: "stored", charCount: existing.char_count, passageCount: row?.n ?? 0, storedAt: existing.created_at };
1506
+ }
1507
+ const heldByStore = await tx.getFirstAsync(
1508
+ `SELECT source_ref FROM ${docs} WHERE entity_id = ? AND source_hash = ? AND source_ref <> ?`,
1509
+ [entityId, sourceHash, sourceRef]
1510
+ );
1511
+ const heldByFacts = await tx.getFirstAsync(
1512
+ `SELECT source_ref FROM ${registry}
1513
+ WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL AND source_ref <> ?`,
1514
+ [entityId, sourceHash, sourceRef]
1515
+ );
1516
+ if (heldByStore || heldByFacts) return refuse("source_store_duplicate_hash");
1517
+ const total = await tx.getFirstAsync(
1518
+ `SELECT COALESCE(SUM(char_count), 0) AS n FROM ${docs} WHERE entity_id = ? AND source_ref <> ?`,
1519
+ [entityId, sourceRef]
1520
+ );
1521
+ if ((total?.n ?? 0) + charCount > limits.maxTotalChars) return refuse("source_store_budget_exceeded");
1522
+ if (existing) {
1523
+ await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ? AND document_id = ?`, [entityId, existing.id]);
1524
+ await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ? AND id = ?`, [entityId, existing.id]);
1525
+ }
1526
+ const id = generateId("sdoc_");
1527
+ const storedAt = typeof src.storedAt === "number" && Number.isFinite(src.storedAt) ? src.storedAt : Date.now();
1528
+ await tx.runAsync(
1529
+ `INSERT INTO ${docs} (id, entity_id, source_ref, source_hash, text, text_hash, char_count, created_at)
1530
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
1531
+ [id, entityId, sourceRef, sourceHash, text, textHash, charCount, storedAt]
1532
+ );
1533
+ const spans = cutPassages(text);
1534
+ for (let seq = 0; seq < spans.length; seq++) {
1535
+ await tx.runAsync(
1536
+ `INSERT INTO ${passages} (id, entity_id, document_id, seq, start_offset, end_offset) VALUES (?, ?, ?, ?, ?, ?)`,
1537
+ [generateId("spas_"), entityId, id, seq, spans[seq].start, spans[seq].end]
1538
+ );
1539
+ }
1540
+ return { status: "stored", charCount, passageCount: spans.length, storedAt };
1541
+ }
1542
+
1543
+ // src/services/SourceStoreService.ts
1544
+ var DEFAULT_MAX_CHARS_PER_SOURCE = 2e5;
1545
+ var DEFAULT_MAX_TOTAL_CHARS = 5e6;
1244
1546
 
1245
1547
  // src/utils/sourcePointer.ts
1246
1548
  var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
@@ -1364,7 +1666,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1364
1666
  var IMPORT_TITLE_MAX = 500;
1365
1667
  var IMPORT_BODY_MAX = 8e3;
1366
1668
  var ImportExportService = class {
1367
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
1669
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
1368
1670
  this.db = db;
1369
1671
  this.entryRepo = entryRepo;
1370
1672
  this.taskRepo = taskRepo;
@@ -1376,13 +1678,22 @@ var ImportExportService = class {
1376
1678
  this.embeddingService = embeddingService;
1377
1679
  this.options = options;
1378
1680
  this.vectorRemoval = vectorRemoval;
1681
+ this.prefix = prefix;
1379
1682
  }
1380
- async exportDump(entityIds) {
1683
+ async exportDump(entityIds, opts) {
1684
+ const includeForgotten = opts?.includeForgotten === true;
1381
1685
  let ids;
1382
1686
  if (entityIds && entityIds.length > 0) {
1383
1687
  ids = Array.from(new Set(entityIds));
1384
1688
  } else {
1385
1689
  ids = await this.metadataRepo.getDistinctEntityIds();
1690
+ const prefix = this.storePrefix();
1691
+ if (prefix !== void 0 && await this.storePresent(prefix)) {
1692
+ const rows = await this.db.getAllAsync(
1693
+ `SELECT DISTINCT entity_id FROM ${prefix}source_documents`
1694
+ );
1695
+ ids = Array.from(/* @__PURE__ */ new Set([...ids, ...rows.map((r) => r.entity_id)])).sort();
1696
+ }
1386
1697
  }
1387
1698
  const entities = {};
1388
1699
  const BATCH = 3;
@@ -1390,10 +1701,11 @@ var ImportExportService = class {
1390
1701
  const batch = ids.slice(i, i + BATCH);
1391
1702
  const batchResults = await Promise.all(
1392
1703
  batch.map(
1393
- async (id) => [
1394
- id,
1395
- await this.getFullBundle(id, { includeBlobs: true })
1396
- ]
1704
+ async (id) => {
1705
+ const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
1706
+ const storedSources = await this.exportStoredSources(id);
1707
+ return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
1708
+ }
1397
1709
  )
1398
1710
  );
1399
1711
  for (const [id, bundle] of batchResults) {
@@ -1404,22 +1716,103 @@ var ImportExportService = class {
1404
1716
  }
1405
1717
  async importDump(dump, opts) {
1406
1718
  const merge = opts?.merge ?? false;
1719
+ const skippedSources = [];
1407
1720
  const entityIds = Object.keys(dump.entities);
1408
1721
  this.jobManager.acquireImportLocks(entityIds);
1409
1722
  try {
1410
1723
  await this.assertNoLegacySourceTypes();
1411
1724
  for (const [entityId, bundle] of Object.entries(dump.entities)) {
1412
- await this.doImportEntity(entityId, bundle, merge);
1725
+ skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
1413
1726
  }
1414
1727
  } finally {
1415
1728
  this.jobManager.releaseImportLocks(entityIds);
1416
1729
  }
1730
+ return { skippedSources };
1731
+ }
1732
+ storePrefix() {
1733
+ return typeof this.prefix === "string" ? this.prefix : void 0;
1734
+ }
1735
+ // `source_ref_index` needs no check: the v9 migration (add_source_ref_index) creates it, and the
1736
+ // store tables come from v17, which only runs after v9 — so it exists whenever they do.
1737
+ async storePresent(prefix, tx) {
1738
+ return await this.metadataRepo.tableExists(`${prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${prefix}source_passages`, tx);
1739
+ }
1740
+ /** Spec source-store §8: stored sources for one exported entity; [] when none. */
1741
+ async exportStoredSources(entityId) {
1742
+ const prefix = this.storePrefix();
1743
+ if (prefix === void 0 || !await this.storePresent(prefix)) return [];
1744
+ const docs = await this.db.getAllAsync(
1745
+ `SELECT id, source_ref, source_hash, text, text_hash, char_count, created_at FROM ${prefix}source_documents
1746
+ WHERE entity_id = ? ORDER BY source_ref COLLATE BINARY`,
1747
+ [entityId]
1748
+ );
1749
+ const out = [];
1750
+ for (const d of docs) {
1751
+ const ps = await this.db.getAllAsync(
1752
+ `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages
1753
+ WHERE entity_id = ? AND document_id = ? ORDER BY seq`,
1754
+ [entityId, d.id]
1755
+ );
1756
+ out.push({
1757
+ sourceRef: d.source_ref,
1758
+ sourceHash: d.source_hash,
1759
+ text: d.text,
1760
+ textHash: d.text_hash,
1761
+ charCount: Number(d.char_count),
1762
+ storedAt: Number(d.created_at),
1763
+ passages: ps.map((p) => ({ seq: Number(p.seq), startOffset: Number(p.start_offset), endOffset: Number(p.end_offset) }))
1764
+ });
1765
+ }
1766
+ return out;
1767
+ }
1768
+ /**
1769
+ * Spec source-store §8/§9 import step, inside the import transaction. One
1770
+ * source at a time; a refusal skips that source only. Uses the
1771
+ * same upsert helper as SourceStoreService.storeSource, inside this transaction. A ref already stored is replaced: the dump is the
1772
+ * truth for that ref (so no hash_mismatch refusal on import).
1773
+ */
1774
+ async importStoredSources(tx, entityId, sources, merge, skipped, deferredDiagnostics) {
1775
+ const prefix = this.storePrefix();
1776
+ if (prefix === void 0) return;
1777
+ if (merge && !sources?.length) return;
1778
+ if (!await this.storePresent(prefix, tx)) return;
1779
+ const docs = `${prefix}source_documents`;
1780
+ const passages = `${prefix}source_passages`;
1781
+ if (!merge) {
1782
+ await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ?`, [entityId]);
1783
+ await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ?`, [entityId]);
1784
+ }
1785
+ const cfg = this.options.config?.sourceStore;
1786
+ const lim = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : d;
1787
+ const limits = {
1788
+ maxCharsPerSource: lim(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
1789
+ maxTotalChars: lim(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
1790
+ };
1791
+ for (const src of sources ?? []) {
1792
+ const sourceRef = normalizeSourceRef(src?.sourceRef);
1793
+ const sourceHash = normalizeSourceHash(src?.sourceHash);
1794
+ if (!sourceRef || !sourceHash || typeof src.text !== "string") {
1795
+ throw new Error(`importDump: invalid stored source for entity "${entityId}" (sourceRef, sourceHash and text are required)`);
1796
+ }
1797
+ await upsertStoredSource(
1798
+ tx,
1799
+ prefix,
1800
+ entityId,
1801
+ { sourceRef, sourceHash, text: src.text, storedAt: src.storedAt },
1802
+ limits,
1803
+ (code) => {
1804
+ skipped.push({ sourceRef, code });
1805
+ deferredDiagnostics.push({ code, operation: "importDump", trigger: "call", entityId, detail: { sourceRef } });
1806
+ }
1807
+ );
1808
+ }
1417
1809
  }
1418
1810
  async getFullBundle(entityId, opts) {
1811
+ const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
1419
1812
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
1420
1813
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
1421
- opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
1422
- this.taskRepo.findAllByEntityId(entityId),
1814
+ opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
1815
+ this.taskRepo.findAllByEntityId(entityId, void 0, incl),
1423
1816
  this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
1424
1817
  this.edgeRepo.getByEntityId(entityId),
1425
1818
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
@@ -1452,13 +1845,18 @@ var ImportExportService = class {
1452
1845
  }
1453
1846
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
1454
1847
  async doImportEntity(entityId, bundle, merge) {
1848
+ const skippedSources = [];
1849
+ const refusalDiagnostics = [];
1455
1850
  const upsertedFactIds = /* @__PURE__ */ new Set();
1851
+ const liveEmbedFactIds = /* @__PURE__ */ new Set();
1456
1852
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
1457
1853
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
1458
1854
  const preservedBlobDims = /* @__PURE__ */ new Set();
1459
1855
  const softDeletedFactIds = [];
1856
+ const softDeletedTaskIds = [];
1460
1857
  const clippedTextByFactId = /* @__PURE__ */ new Map();
1461
1858
  let clampedEvents = 0;
1859
+ let tombstoneSkipped = 0;
1462
1860
  const restamped = { behind_watermark: 0, invalid: 0 };
1463
1861
  await this.db.withTransactionAsync(async (tx) => {
1464
1862
  if (!merge) {
@@ -1469,8 +1867,9 @@ var ImportExportService = class {
1469
1867
  tx,
1470
1868
  false
1471
1869
  );
1472
- softDeletedFactIds.push(...deletedLiveFactIds);
1870
+ for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
1473
1871
  await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
1872
+ for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
1474
1873
  await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
1475
1874
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
1476
1875
  await this.metadataRepo.deleteCheckpoint(entityId, tx);
@@ -1480,6 +1879,8 @@ var ImportExportService = class {
1480
1879
  } else if (!merge) {
1481
1880
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
1482
1881
  }
1882
+ const wipedByThisImport = new Set(softDeletedFactIds);
1883
+ const wipedTasksByThisImport = new Set(softDeletedTaskIds);
1483
1884
  const factIds = bundle.facts.map((fact) => fact.id);
1484
1885
  const existingFactsById = /* @__PURE__ */ new Map();
1485
1886
  const existingFacts = await this.entryRepo.findExistingMetadataByIds(
@@ -1555,11 +1956,16 @@ var ImportExportService = class {
1555
1956
  );
1556
1957
  continue;
1557
1958
  }
1558
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
1959
+ if (existing.deleted_at != null && fact.deleted_at == null && !wipedByThisImport.has(fact.id)) {
1960
+ tombstoneSkipped++;
1961
+ continue;
1962
+ }
1963
+ if (merge && safeUpdatedAt <= existing.updated_at && fact.deleted_at == null) continue;
1559
1964
  }
1560
1965
  const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
1561
1966
  const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
1562
- clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody });
1967
+ const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
1968
+ clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
1563
1969
  let normalizedSourceRef = null;
1564
1970
  if (fact.source_ref !== null && fact.source_ref !== void 0) {
1565
1971
  normalizedSourceRef = normalizeSourceRef(fact.source_ref);
@@ -1626,15 +2032,22 @@ var ImportExportService = class {
1626
2032
  }, tx, { outbox: false });
1627
2033
  if (blobData != null) {
1628
2034
  factsWithPreservedBlob.set(fact.id, blobData);
1629
- if (!fact.deleted_at) preservedBlobDims.add(blobData.byteLength / 4);
2035
+ if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
1630
2036
  }
1631
2037
  existingFactsById.set(fact.id, {
1632
2038
  id: fact.id,
1633
2039
  entity_id: entityId,
1634
- updated_at: safeUpdatedAt
2040
+ updated_at: safeUpdatedAt,
2041
+ deleted_at: fact.deleted_at ?? null
1635
2042
  });
2043
+ wipedByThisImport.delete(fact.id);
1636
2044
  upsertedFactIds.add(fact.id);
1637
- if (fact.deleted_at) upsertedDeletedFactIds.add(fact.id);
2045
+ if (fact.deleted_at != null) {
2046
+ upsertedDeletedFactIds.add(fact.id);
2047
+ liveEmbedFactIds.delete(fact.id);
2048
+ } else {
2049
+ liveEmbedFactIds.add(fact.id);
2050
+ }
1638
2051
  }
1639
2052
  const taskIds = bundle.tasks.map((task) => task.id);
1640
2053
  const existingTasksById = /* @__PURE__ */ new Map();
@@ -1658,7 +2071,11 @@ var ImportExportService = class {
1658
2071
  );
1659
2072
  continue;
1660
2073
  }
1661
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
2074
+ if (existing.deleted_at != null && task.deleted_at == null && !wipedTasksByThisImport.has(task.id)) {
2075
+ tombstoneSkipped++;
2076
+ continue;
2077
+ }
2078
+ if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
1662
2079
  }
1663
2080
  await this.taskRepo.upsertForImport(
1664
2081
  {
@@ -1691,8 +2108,10 @@ var ImportExportService = class {
1691
2108
  existingTasksById.set(task.id, {
1692
2109
  id: task.id,
1693
2110
  entity_id: entityId,
1694
- updated_at: safeUpdatedAt
2111
+ updated_at: safeUpdatedAt,
2112
+ deleted_at: task.deleted_at ?? null
1695
2113
  });
2114
+ wipedTasksByThisImport.delete(task.id);
1696
2115
  }
1697
2116
  const now = Date.now();
1698
2117
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
@@ -1729,7 +2148,18 @@ var ImportExportService = class {
1729
2148
  tx
1730
2149
  );
1731
2150
  }
2151
+ await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
1732
2152
  });
2153
+ for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
2154
+ if (tombstoneSkipped > 0) {
2155
+ emitDiagnostic(this.options, {
2156
+ code: "import_tombstone_skipped",
2157
+ operation: "importDump",
2158
+ trigger: "call",
2159
+ entityId,
2160
+ detail: { count: tombstoneSkipped }
2161
+ });
2162
+ }
1733
2163
  if (clampedEvents > 0) {
1734
2164
  emitDiagnostic(this.options, {
1735
2165
  code: "event_created_at_clamped",
@@ -1755,28 +2185,28 @@ var ImportExportService = class {
1755
2185
  } else {
1756
2186
  await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
1757
2187
  }
1758
- for (const fact of bundle.facts) {
1759
- if (!fact.deleted_at && upsertedFactIds.has(fact.id) && !factsWithPreservedBlob.has(fact.id)) {
1760
- const clipped = clippedTextByFactId.get(fact.id);
2188
+ for (const id of liveEmbedFactIds) {
2189
+ if (!factsWithPreservedBlob.has(id)) {
2190
+ const clipped = clippedTextByFactId.get(id);
1761
2191
  const embedded = await this.embeddingService.embedFact({
1762
- id: fact.id,
2192
+ id,
1763
2193
  entity_id: entityId,
1764
- title: clipped?.title ?? fact.title,
1765
- body: clipped?.body ?? fact.body,
1766
- tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
2194
+ title: clipped?.title ?? "",
2195
+ body: clipped?.body ?? "",
2196
+ tags: clipped?.tags ?? []
1767
2197
  }, { operation: "importDump", trigger: "call" });
1768
2198
  if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
1769
2199
  try {
1770
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
2200
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
1771
2201
  } catch (hookErr) {
1772
2202
  console.warn(
1773
- `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
2203
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
1774
2204
  hookErr
1775
2205
  );
1776
2206
  this.embeddingService.reportHookFailed(
1777
2207
  { operation: "importDump", trigger: "call" },
1778
2208
  entityId,
1779
- fact.id
2209
+ id
1780
2210
  );
1781
2211
  }
1782
2212
  }
@@ -1784,7 +2214,7 @@ var ImportExportService = class {
1784
2214
  }
1785
2215
  for (const fact of bundle.facts) {
1786
2216
  const blobData = factsWithPreservedBlob.get(fact.id);
1787
- if (blobData && !fact.deleted_at && upsertedFactIds.has(fact.id)) {
2217
+ if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
1788
2218
  try {
1789
2219
  const float32Vector = new Float32Array(
1790
2220
  blobData.buffer,
@@ -1897,6 +2327,7 @@ var ImportExportService = class {
1897
2327
  } finally {
1898
2328
  this.searchService.evictCache(entityId);
1899
2329
  }
2330
+ return skippedSources;
1900
2331
  }
1901
2332
  _warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
1902
2333
  console.warn(
@@ -1931,19 +2362,6 @@ After running the migration SQL, restart your application.`
1931
2362
  );
1932
2363
  }
1933
2364
  };
1934
- function generateId(prefix = "") {
1935
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1936
- return prefix + crypto.randomUUID().replace(/-/g, "").substring(0, 24);
1937
- }
1938
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
1939
- const bytes = new Uint8Array(16);
1940
- crypto.getRandomValues(bytes);
1941
- return prefix + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("").substring(0, 24);
1942
- }
1943
- throw new Error(
1944
- "generateId: no cryptographically secure random source available (crypto.randomUUID and crypto.getRandomValues are both missing, and no configureRandomSource() injection was provided)."
1945
- );
1946
- }
1947
2365
 
1948
2366
  // src/prompts.ts
1949
2367
  var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
@@ -3174,6 +3592,106 @@ function classifierStateForFact(fact) {
3174
3592
  return parts.join("\n\n");
3175
3593
  }
3176
3594
 
3595
+ // src/utils/temporal.ts
3596
+ function liveAtSql(mode, alias = "") {
3597
+ const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3598
+ return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3599
+ }
3600
+ function assertEpochMs(name, v) {
3601
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3602
+ throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3603
+ }
3604
+ return Math.trunc(v);
3605
+ }
3606
+
3607
+ // src/services/TemporalService.ts
3608
+ var HISTORY_MAX_DEPTH = 100;
3609
+ var TemporalService = class {
3610
+ constructor(db, options, entryRepo, searchService, embeddingService) {
3611
+ this.db = db;
3612
+ this.options = options;
3613
+ this.entryRepo = entryRepo;
3614
+ this.searchService = searchService;
3615
+ this.embeddingService = embeddingService;
3616
+ }
3617
+ /**
3618
+ * Link `oldId` → `newId` inside the caller's transaction. `newId` must
3619
+ * already exist. Throws WikiSupersedeError on any rule violation; the
3620
+ * caller's transaction then rolls back.
3621
+ */
3622
+ async supersedeInTx(tx, entityId, oldId, newId, t, now) {
3623
+ const old = await this.entryRepo.findTemporalRow(oldId, tx);
3624
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
3625
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3626
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3627
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
3628
+ if (newId === oldId) throw new WikiSupersedeError("cycle");
3629
+ const repl = await this.entryRepo.findTemporalRow(newId, tx);
3630
+ if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
3631
+ if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3632
+ if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3633
+ const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
3634
+ if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
3635
+ await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
3636
+ if (repl.valid_from == null) {
3637
+ await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
3638
+ }
3639
+ }
3640
+ async supersede(entityId, oldId, replacement, options) {
3641
+ const now = Date.now();
3642
+ const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
3643
+ let created = null;
3644
+ if (typeof replacement !== "string") {
3645
+ if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
3646
+ throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
3647
+ }
3648
+ created = {
3649
+ id: generateId("fact_"),
3650
+ entity_id: entityId,
3651
+ title: replacement.title,
3652
+ body: replacement.body,
3653
+ tags: Array.isArray(replacement.tags) ? replacement.tags : [],
3654
+ confidence: replacement.confidence ?? "certain",
3655
+ source_type: replacement.source_type ?? "user_stated",
3656
+ source_hash: null,
3657
+ source_ref: null,
3658
+ created_at: now,
3659
+ updated_at: now,
3660
+ last_accessed_at: null,
3661
+ access_count: 0,
3662
+ deleted_at: null
3663
+ };
3664
+ }
3665
+ const newId = typeof replacement === "string" ? replacement : created.id;
3666
+ const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
3667
+ await this.db.withTransactionAsync(async (tx) => {
3668
+ if (created) {
3669
+ await this.entryRepo.upsert(created, tx);
3670
+ if (newValidFrom !== void 0) {
3671
+ await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
3672
+ }
3673
+ }
3674
+ await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
3675
+ });
3676
+ await this.searchService.syncEntries(entityId, [oldId, newId]);
3677
+ if (created) {
3678
+ await this.embeddingService.embedFact(
3679
+ { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
3680
+ { operation: "supersede", trigger: "call" }
3681
+ );
3682
+ }
3683
+ this.searchService.evictCache(entityId);
3684
+ return { newId };
3685
+ }
3686
+ async history(entityId, factId) {
3687
+ const start = await this.entryRepo.findTemporalRow(factId);
3688
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
3689
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
3690
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
3691
+ return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
3692
+ }
3693
+ };
3694
+
3177
3695
  // src/utils/engineDefaults.ts
3178
3696
  var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3179
3697
  var DEFAULT_MAINTENANCE_MODE = "deferred";
@@ -3219,18 +3737,6 @@ function removalGate(options) {
3219
3737
  return "none";
3220
3738
  }
3221
3739
 
3222
- // src/utils/temporal.ts
3223
- function liveAtSql(mode, alias = "") {
3224
- const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3225
- return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3226
- }
3227
- function assertEpochMs(name, v) {
3228
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3229
- throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3230
- }
3231
- return Math.trunc(v);
3232
- }
3233
-
3234
3740
  // src/repositories/EdgeRepository.ts
3235
3741
  var CONFIDENCE_RANK = {
3236
3742
  tentative: 0,
@@ -3592,6 +4098,10 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
3592
4098
 
3593
4099
  // src/services/search/fts5Sql.ts
3594
4100
  var FTS5_STATE_KEY = "fts5_index_state";
4101
+ var FTS5_RETIRED_TABLES_KEY = "fts5_retired_tables";
4102
+ function isRetiredTableName(p, name) {
4103
+ return typeof name === "string" && name.startsWith(`${p}entries_fts_retired_`) && /^\d+$/.test(name.slice(`${p}entries_fts_retired_`.length));
4104
+ }
3595
4105
  var FTS5_REBUILD_WM_KEY = "fts5_rebuild_wm";
3596
4106
  var FTS5_REBUILD_SNAPSHOT_KEY = "fts5_rebuild_snapshot";
3597
4107
  var FTS5_SWEEP_CURSOR_KEY = "fts5_orphan_sweep_cursor";
@@ -3905,6 +4415,57 @@ var MIGRATIONS = [
3905
4415
  await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
3906
4416
  }
3907
4417
  }
4418
+ },
4419
+ {
4420
+ version: 17,
4421
+ description: "add_source_store",
4422
+ run: async (db, prefix) => {
4423
+ const expected = {
4424
+ source_documents: ["id", "entity_id", "source_ref", "source_hash", "text", "text_hash", "char_count", "created_at"],
4425
+ source_passages: ["id", "entity_id", "document_id", "seq", "start_offset", "end_offset"]
4426
+ };
4427
+ for (const [table, want] of Object.entries(expected)) {
4428
+ const full = `${prefix}${table}`;
4429
+ const cols = (await db.getAllAsync(`PRAGMA table_info(${full})`)).map((c) => c.name);
4430
+ if (cols.length === 0) continue;
4431
+ const same = cols.length === want.length && want.every((c) => cols.includes(c));
4432
+ if (!same) {
4433
+ throw new Error(
4434
+ `Migration v17 (add_source_store) failed: table ${full} exists with columns [${cols.join(", ")}], expected [${want.join(", ")}]. Drop the stray table (it predates the source store) and re-run setup().`
4435
+ );
4436
+ }
4437
+ const row = await db.getFirstAsync(`SELECT COUNT(*) AS n FROM ${full}`);
4438
+ if (row && row.n > 0) {
4439
+ throw new Error(
4440
+ `Migration v17 (add_source_store) failed: table ${full} already holds ${row.n} row(s), but no source text exists before v17. Back up and drop the table, then re-run setup().`
4441
+ );
4442
+ }
4443
+ }
4444
+ await db.execAsync(
4445
+ `CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
4446
+ id TEXT PRIMARY KEY,
4447
+ entity_id TEXT NOT NULL,
4448
+ source_ref TEXT NOT NULL,
4449
+ source_hash TEXT NOT NULL,
4450
+ text TEXT NOT NULL,
4451
+ text_hash TEXT NOT NULL,
4452
+ char_count INTEGER NOT NULL,
4453
+ created_at INTEGER NOT NULL
4454
+ );
4455
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref
4456
+ ON ${prefix}source_documents (entity_id, source_ref);
4457
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash
4458
+ ON ${prefix}source_documents (entity_id, source_hash);
4459
+ CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
4460
+ id TEXT PRIMARY KEY,
4461
+ entity_id TEXT NOT NULL,
4462
+ document_id TEXT NOT NULL,
4463
+ seq INTEGER NOT NULL,
4464
+ start_offset INTEGER NOT NULL,
4465
+ end_offset INTEGER NOT NULL
4466
+ );`
4467
+ );
4468
+ }
3908
4469
  }
3909
4470
  ];
3910
4471
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -4411,103 +4972,15 @@ async function runResolve(deps, ctx, ambiguous) {
4411
4972
  return out;
4412
4973
  }
4413
4974
 
4414
- // src/services/TemporalService.ts
4415
- var HISTORY_MAX_DEPTH = 100;
4416
- var TemporalService = class {
4417
- constructor(db, options, entryRepo, searchService, embeddingService) {
4418
- this.db = db;
4419
- this.options = options;
4420
- this.entryRepo = entryRepo;
4421
- this.searchService = searchService;
4422
- this.embeddingService = embeddingService;
4423
- }
4424
- /**
4425
- * Link `oldId` → `newId` inside the caller's transaction. `newId` must
4426
- * already exist. Throws WikiSupersedeError on any rule violation; the
4427
- * caller's transaction then rolls back.
4428
- */
4429
- async supersedeInTx(tx, entityId, oldId, newId, t, now) {
4430
- const old = await this.entryRepo.findTemporalRow(oldId, tx);
4431
- if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
4432
- if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
4433
- if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
4434
- if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
4435
- if (newId === oldId) throw new WikiSupersedeError("cycle");
4436
- const repl = await this.entryRepo.findTemporalRow(newId, tx);
4437
- if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
4438
- if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
4439
- if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
4440
- const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
4441
- if (predecessors.includes(newId)) throw new WikiSupersedeError("cycle");
4442
- await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
4443
- if (repl.valid_from == null) {
4444
- await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
4445
- }
4446
- }
4447
- async supersede(entityId, oldId, replacement, options) {
4448
- const now = Date.now();
4449
- const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
4450
- let created = null;
4451
- if (typeof replacement !== "string") {
4452
- if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
4453
- throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
4454
- }
4455
- created = {
4456
- id: generateId("fact_"),
4457
- entity_id: entityId,
4458
- title: replacement.title,
4459
- body: replacement.body,
4460
- tags: Array.isArray(replacement.tags) ? replacement.tags : [],
4461
- confidence: replacement.confidence ?? "certain",
4462
- source_type: replacement.source_type ?? "user_stated",
4463
- source_hash: null,
4464
- source_ref: null,
4465
- created_at: now,
4466
- updated_at: now,
4467
- last_accessed_at: null,
4468
- access_count: 0,
4469
- deleted_at: null
4470
- };
4471
- }
4472
- const newId = typeof replacement === "string" ? replacement : created.id;
4473
- const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
4474
- await this.db.withTransactionAsync(async (tx) => {
4475
- if (created) {
4476
- await this.entryRepo.upsert(created, tx);
4477
- if (newValidFrom !== void 0) {
4478
- await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
4479
- }
4480
- }
4481
- await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
4482
- });
4483
- await this.searchService.syncEntries(entityId, [oldId, newId]);
4484
- if (created) {
4485
- await this.embeddingService.embedFact(
4486
- { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
4487
- { operation: "supersede", trigger: "call" }
4488
- );
4489
- }
4490
- this.searchService.evictCache(entityId);
4491
- return { newId };
4492
- }
4493
- async history(entityId, factId) {
4494
- const start = await this.entryRepo.findTemporalRow(factId);
4495
- if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
4496
- const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
4497
- const facts = await this.entryRepo.findByIds([...predecessors, factId, ...successors], [entityId]);
4498
- return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
4499
- }
4500
- };
4501
-
4502
- // src/services/librarian/ops/apply.ts
4503
- function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
4504
- if (candidate.sourceEventId === null) return null;
4505
- let quote = null;
4506
- if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
4507
- const part = groundingCorpus?.[candidate.sourcePartIndex];
4508
- if (part !== void 0) {
4509
- quote = verdict.retained.find((q) => part.includes(q)) ?? null;
4510
- }
4975
+ // src/services/librarian/ops/apply.ts
4976
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
4977
+ if (candidate.sourceEventId === null) return null;
4978
+ let quote = null;
4979
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
4980
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
4981
+ if (part !== void 0) {
4982
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
4983
+ }
4511
4984
  }
4512
4985
  return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
4513
4986
  }
@@ -4764,6 +5237,7 @@ async function runLibrarianStrategy(deps, ctx) {
4764
5237
  }
4765
5238
 
4766
5239
  // src/services/MaintenanceService.ts
5240
+ var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HISTORY_MAX_DEPTH} links per direction); the chain is longer than the ids listed. Run forget again on a remaining chain id to continue.`;
4767
5241
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
4768
5242
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
4769
5243
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -4812,6 +5286,20 @@ var formatSkipError = (err) => {
4812
5286
  }
4813
5287
  return base;
4814
5288
  };
5289
+ function eraseRuntime() {
5290
+ const g = globalThis;
5291
+ if (g.process?.versions?.node) return `node ${g.process.versions.node}`;
5292
+ return g.HermesInternal ? "hermes" : "unknown";
5293
+ }
5294
+ var EraseStepError = class extends Error {
5295
+ constructor(code, message, report, cause) {
5296
+ super(message);
5297
+ this.code = code;
5298
+ this.report = report;
5299
+ this.name = "EraseStepError";
5300
+ if (cause !== void 0) this.cause = cause;
5301
+ }
5302
+ };
4815
5303
  var MaintenanceService = class {
4816
5304
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
4817
5305
  this.db = db;
@@ -4832,7 +5320,15 @@ var MaintenanceService = class {
4832
5320
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
4833
5321
  }
4834
5322
  async runPrune(entityId, options) {
4835
- this.jobManager.acquireLock("prune", entityId);
5323
+ return this._runPrune(entityId, options, "host");
5324
+ }
5325
+ /**
5326
+ * Shared prune body. `owner: 'erase'` lets erase()'s own per-entity prune
5327
+ * through the universal erase fence in JobManager; the public `runPrune`
5328
+ * always passes `'host'`.
5329
+ */
5330
+ async _runPrune(entityId, options, owner) {
5331
+ this.jobManager.acquireLock("prune", entityId, void 0, owner);
4836
5332
  try {
4837
5333
  const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
4838
5334
  const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
@@ -4863,8 +5359,9 @@ var MaintenanceService = class {
4863
5359
  }
4864
5360
  }
4865
5361
  if (retainSoftDeletedFor !== null) {
4866
- const cutoff = now - retainSoftDeletedFor * 864e5;
4867
- const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
5362
+ const softDeletedAll = options?.softDeletedCutoff === "all";
5363
+ const cutoff = softDeletedAll ? 0 : options?.softDeletedCutoff ?? now - retainSoftDeletedFor * 864e5;
5364
+ const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff, void 0, { noCutoff: softDeletedAll });
4868
5365
  const prunableIds = entriesToDelete.map((r) => r.id);
4869
5366
  const vr = this.vectorRemoval;
4870
5367
  const vrRepo = this.vectorRemovalRepo;
@@ -4910,7 +5407,7 @@ var MaintenanceService = class {
4910
5407
  }
4911
5408
  if (deletable.length > 0) {
4912
5409
  const deletedIds = [];
4913
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
5410
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds, noCutoff: softDeletedAll });
4914
5411
  if (hookLedger) {
4915
5412
  const gone = new Set(deletedIds);
4916
5413
  const skipped = deletable.filter((id) => !gone.has(id));
@@ -4925,7 +5422,7 @@ var MaintenanceService = class {
4925
5422
  else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
4926
5423
  }
4927
5424
  }
4928
- deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
5425
+ deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
4929
5426
  });
4930
5427
  if (hookLedger) {
4931
5428
  const keptSet = new Set(kept);
@@ -4970,12 +5467,20 @@ var MaintenanceService = class {
4970
5467
  }
4971
5468
  }
4972
5469
  }
5470
+ let vacuumCheckpointErr;
4973
5471
  if (vacuum) {
4974
- await resetNormalizeWatermarks(this.metadataRepo);
4975
- await this.metadataRepo.vacuum();
4976
- await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5472
+ try {
5473
+ await this._wrappedVacuum();
5474
+ } catch (err) {
5475
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
5476
+ vacuumCheckpointErr = err;
5477
+ }
4977
5478
  }
5479
+ if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
4978
5480
  await this.searchService.syncEntries(entityId, syncedIds);
5481
+ if (prunePartial && vacuumCheckpointErr) {
5482
+ emitDiagnostic(this.options, { code: "prune_checkpoint_incomplete", operation: "prune", trigger: "call", entityId, detail: { reason: vacuumCheckpointErr.message } });
5483
+ }
4979
5484
  if (prunePartial) {
4980
5485
  throw new PrunePartialFailureError(
4981
5486
  deletedEntries,
@@ -4986,11 +5491,327 @@ var MaintenanceService = class {
4986
5491
  deletedEvents
4987
5492
  );
4988
5493
  }
5494
+ if (vacuumCheckpointErr) throw vacuumCheckpointErr;
4989
5495
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
4990
5496
  } finally {
4991
5497
  this.jobManager.releaseLock("prune", entityId);
4992
5498
  }
4993
5499
  }
5500
+ /** Shared by runPrune and erase step 5. */
5501
+ async _wrappedVacuum() {
5502
+ await resetNormalizeWatermarks(this.metadataRepo);
5503
+ let checkpointErr;
5504
+ try {
5505
+ await this.metadataRepo.vacuum();
5506
+ } catch (err) {
5507
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
5508
+ checkpointErr = err;
5509
+ }
5510
+ await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5511
+ if (checkpointErr) throw checkpointErr;
5512
+ }
5513
+ /**
5514
+ * Erase core (forget-erasure spec §2, steps 0 / 1 / 1b). Thin entry: T6
5515
+ * completes the pipeline (FTS, VACUUM, checkpoint, sync). Never reports a
5516
+ * success it cannot verify: a failed step throws {@link EraseStepError}
5517
+ * carrying the partial report with `verified: false`.
5518
+ */
5519
+ async erase(opts) {
5520
+ const rebuild = opts?.rebuild === true;
5521
+ this.jobManager.acquireLock("erase", "*");
5522
+ const report = {
5523
+ verified: false,
5524
+ secureDelete: null,
5525
+ sqliteVersion: "",
5526
+ entities: [],
5527
+ holds: [],
5528
+ skipped: [],
5529
+ syncedIds: [],
5530
+ registrySweep: { skipped: false, deleted: 0 },
5531
+ retiredUndroppable: [],
5532
+ failedStep: null,
5533
+ runtime: eraseRuntime(),
5534
+ steps: []
5535
+ };
5536
+ const ok = (step, outcome = "ok") => {
5537
+ report.steps.push({ step, outcome });
5538
+ };
5539
+ try {
5540
+ const readPragma = async () => (await this.db.getFirstAsync("PRAGMA secure_delete"))?.secure_delete ?? null;
5541
+ let pragma;
5542
+ try {
5543
+ pragma = await readPragma();
5544
+ if (pragma !== 1) {
5545
+ await this.db.execAsync("PRAGMA secure_delete=ON");
5546
+ pragma = await readPragma();
5547
+ }
5548
+ report.secureDelete = pragma;
5549
+ report.sqliteVersion = (await this.db.getFirstAsync("SELECT sqlite_version() AS v"))?.v ?? "";
5550
+ } catch (err) {
5551
+ report.failedStep = "secure_delete";
5552
+ throw new EraseStepError("erase_secure_delete_read_failed", "erase stopped at step 0: secure_delete pragma read failed; erasure is unverified", report, err);
5553
+ }
5554
+ if (pragma !== 1) {
5555
+ emitDiagnostic(this.options, { code: "erase_secure_delete_off", operation: "erase", trigger: "call", entityId: "" });
5556
+ report.failedStep = "secure_delete";
5557
+ throw new EraseStepError("erase_secure_delete_off", "erase stopped at step 0: secure_delete is not ON; erasure is unverified", report);
5558
+ }
5559
+ ok("secure_delete");
5560
+ try {
5561
+ report.entities = await this.metadataRepo.getDistinctEntityIds(void 0, { softDeletedAll: true });
5562
+ } catch (err) {
5563
+ report.failedStep = "prune";
5564
+ throw new EraseStepError("erase_prune_failed", "erase stopped at step 1: the entity walk failed; erasure is unverified", report, err);
5565
+ }
5566
+ const syncedByEntity = /* @__PURE__ */ new Map();
5567
+ for (const entityId of report.entities) {
5568
+ const syncedIds = [];
5569
+ syncedByEntity.set(entityId, syncedIds);
5570
+ try {
5571
+ await this._runPrune(entityId, { retainSoftDeletedFor: 0, retainEventsFor: null, vacuum: false, syncedIds, softDeletedCutoff: "all" }, "erase");
5572
+ } catch (err) {
5573
+ if (err instanceof PrunePartialFailureError) {
5574
+ report.holds.push({ entityId, deleted: err.deleted, deletedTasks: err.deletedTasks, failedAt: err.failedAt, remaining: err.remaining });
5575
+ } else if (err instanceof WikiBusyError) {
5576
+ report.skipped.push(entityId);
5577
+ emitDiagnostic(this.options, { code: "erase_entity_skipped", operation: "erase", trigger: "call", entityId });
5578
+ } else {
5579
+ report.failedStep = "prune";
5580
+ throw new EraseStepError("erase_prune_failed", `erase stopped at step 1 (entity ${entityId})`, report, err);
5581
+ }
5582
+ }
5583
+ for (const id of syncedIds) report.syncedIds.push(id);
5584
+ }
5585
+ ok("prune", report.holds.length > 0 || report.skipped.length > 0 ? "partial" : "ok");
5586
+ try {
5587
+ await this.db.withTransactionAsync(async (tx) => {
5588
+ if (await this.sourceRefIndexPresent(tx)) {
5589
+ const r = await tx.runAsync(`DELETE FROM ${this.prefix}source_ref_index WHERE deleted_at IS NOT NULL`);
5590
+ report.registrySweep = { skipped: false, deleted: r.changes };
5591
+ } else {
5592
+ report.registrySweep = { skipped: true, deleted: 0 };
5593
+ }
5594
+ });
5595
+ } catch (err) {
5596
+ report.failedStep = "registry_sweep";
5597
+ throw new EraseStepError("erase_registry_sweep_failed", "erase stopped at step 1b", report, err);
5598
+ }
5599
+ if (report.registrySweep.skipped) {
5600
+ emitDiagnostic(this.options, { code: "erase_registry_sweep_skipped", operation: "erase", trigger: "call", entityId: "" });
5601
+ }
5602
+ ok("registry_sweep", report.registrySweep.skipped ? "partial" : "ok");
5603
+ await this._eraseDrainPassages(report);
5604
+ ok("passage_drain");
5605
+ await this._eraseReclaimRetired(report);
5606
+ ok("retired_reclaim");
5607
+ try {
5608
+ await this._wrappedVacuum();
5609
+ } catch (err) {
5610
+ if (err instanceof CheckpointIncompleteError) {
5611
+ report.failedStep = "checkpoint";
5612
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 5: WAL checkpoint incomplete; erasure is unverified", report, err);
5613
+ }
5614
+ report.failedStep = "vacuum";
5615
+ throw new EraseStepError("erase_vacuum_failed", "erase stopped at step 5: VACUUM failed (commonly an unfenced writer holding the database \u2014 quiesce and retry; also any other VACUUM failure, e.g. disk-full or I/O errors)", report, err);
5616
+ }
5617
+ ok("vacuum");
5618
+ const byEntity = /* @__PURE__ */ new Map();
5619
+ for (const e of report.entities) byEntity.set(e, []);
5620
+ for (const [entityId, ids] of syncedByEntity) byEntity.set(entityId, ids);
5621
+ for (const [entityId, ids] of byEntity) {
5622
+ if (ids.length > 0) await this._eraseSyncEntries(entityId, ids, report);
5623
+ }
5624
+ ok("index_sync");
5625
+ if (rebuild) {
5626
+ try {
5627
+ await this.searchService.rebuildSurfaced();
5628
+ } catch (err) {
5629
+ report.failedStep = "rebuild";
5630
+ throw new EraseStepError("erase_rebuild_failed", "erase stopped at step 7: FTS rebuild failed", report, err);
5631
+ }
5632
+ ok("rebuild");
5633
+ }
5634
+ await this._eraseReclaimRetired(report);
5635
+ let present;
5636
+ try {
5637
+ present = await this.db.getAllAsync(
5638
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%entries_fts_retired_%'`
5639
+ );
5640
+ } catch (err) {
5641
+ report.failedStep = "retired_reclaim";
5642
+ emitDiagnostic(this.options, { code: "erase_retired_read_failed", operation: "erase", trigger: "call", entityId: "" });
5643
+ throw new EraseStepError("erase_retired_read_failed", "erase stopped after step 6: the retired-table read failed; erasure is unverified", report, err);
5644
+ }
5645
+ const left = present.map((r) => r.name).filter((n) => isRetiredTableName(this.prefix, n) && !report.retiredUndroppable.includes(n));
5646
+ if (left.length > 0) {
5647
+ report.failedStep = "retired_reclaim";
5648
+ emitDiagnostic(this.options, { code: "erase_retired_remaining", operation: "erase", trigger: "call", entityId: "", detail: { tables: left } });
5649
+ throw new EraseStepError("erase_retired_remaining", `erase stopped after step 6: retired FTS tables remain (${left.join(", ")})`, report);
5650
+ }
5651
+ ok("retired_reclaim_rerun");
5652
+ await this._eraseOptimize(report);
5653
+ ok("optimize");
5654
+ try {
5655
+ await this.metadataRepo.checkpointTruncateVerified();
5656
+ } catch (err) {
5657
+ report.failedStep = "checkpoint";
5658
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 8: WAL checkpoint incomplete; erasure is unverified", report, err);
5659
+ }
5660
+ ok("checkpoint");
5661
+ if (report.skipped.length === 0 && report.holds.length === 0) {
5662
+ let remainingTombstones;
5663
+ try {
5664
+ const row = await this.db.getFirstAsync(
5665
+ `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
5666
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
5667
+ );
5668
+ remainingTombstones = row?.n ?? 0;
5669
+ } catch (err) {
5670
+ report.failedStep = "tombstone_gate";
5671
+ throw new EraseStepError("erase_tombstone_gate_failed", "erase stopped at step 9: could not count remaining tombstones; erasure is unverified", report, err);
5672
+ }
5673
+ if (remainingTombstones > 0) {
5674
+ emitDiagnostic(this.options, { code: "erase_tombstones_remaining", operation: "erase", trigger: "call", entityId: "", detail: { count: remainingTombstones } });
5675
+ report.failedStep = "tombstone_gate";
5676
+ throw new EraseStepError("erase_tombstones_remaining", `erase stopped at step 9: ${remainingTombstones} soft-deleted row(s) remain; erasure is unverified`, report);
5677
+ }
5678
+ ok("tombstone_gate");
5679
+ } else {
5680
+ report.steps.push({ step: "tombstone_gate", outcome: "partial" });
5681
+ }
5682
+ report.verified = report.skipped.length === 0 && report.holds.length === 0;
5683
+ return report;
5684
+ } catch (err) {
5685
+ if (err instanceof EraseStepError && err.report === report && report.failedStep) {
5686
+ report.steps.push({ step: report.failedStep, outcome: "failed" });
5687
+ report.verified = false;
5688
+ }
5689
+ throw err;
5690
+ } finally {
5691
+ this.jobManager.releaseLock("erase", "*");
5692
+ }
5693
+ }
5694
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
5695
+ /**
5696
+ * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
5697
+ * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
5698
+ * N2 guard (probe lives here, strategy-agnostic): a strategy without the strict
5699
+ * drains (Unavailable / MiniSearch) cannot drain, so rows in either FTS ledger
5700
+ * mean text was never drained -> the step fails and erasure is unverified.
5701
+ * Absent or empty ledgers proceed.
5702
+ */
5703
+ async _eraseDrainPassages(report) {
5704
+ if (!this.searchService.hasStrictDrain()) {
5705
+ for (const [table, failedStep, code] of [
5706
+ [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
5707
+ [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
5708
+ ]) {
5709
+ let rows = false;
5710
+ try {
5711
+ rows = await this.sourceTableExists(table) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${table} LIMIT 1`) != null;
5712
+ } catch (err) {
5713
+ report.failedStep = failedStep;
5714
+ throw new EraseStepError(code, `erase stopped at step 3: could not probe ${table}`, report, err);
5715
+ }
5716
+ if (rows) {
5717
+ report.failedStep = failedStep;
5718
+ throw new EraseStepError(code, `erase stopped at step 3: ${table} holds undrained rows and the FTS index strategy cannot drain them; erasure is unverified`, report);
5719
+ }
5720
+ }
5721
+ for (const suffix of ["entries_fts_content", "source_passages_fts_content"]) {
5722
+ let orphaned = false;
5723
+ try {
5724
+ orphaned = await this.sourceTableExists(`${this.prefix}${suffix}`);
5725
+ } catch (err) {
5726
+ report.failedStep = "index_sync";
5727
+ throw new EraseStepError("erase_orphaned_fts_content", `erase stopped: could not probe ${this.prefix}${suffix}`, report, err);
5728
+ }
5729
+ if (orphaned) {
5730
+ report.failedStep = "index_sync";
5731
+ throw new EraseStepError("erase_orphaned_fts_content", "erase stopped: orphaned full-text content tables may still hold forgotten text", report);
5732
+ }
5733
+ }
5734
+ }
5735
+ try {
5736
+ await this.searchService.drainEntriesLedgerSurfaced();
5737
+ } catch (err) {
5738
+ report.failedStep = "index_sync";
5739
+ throw new EraseStepError("erase_index_sync_failed", "erase stopped at step 3: entries ledger drain failed", report, err);
5740
+ }
5741
+ try {
5742
+ await this.searchService.drainPassagesSurfaced();
5743
+ } catch (err) {
5744
+ report.failedStep = "passage_drain";
5745
+ throw new EraseStepError("erase_passage_drain_failed", "erase stopped at step 3: passage drain failed", report, err);
5746
+ }
5747
+ }
5748
+ /**
5749
+ * Step 4 (and its re-run after step 6): reclaim retired FTS tables to
5750
+ * completion. A module-less runtime cannot DROP a virtual table, so each
5751
+ * retired table's shadow tables are emptied under the pragma and the name
5752
+ * stays listed; a later FTS5-capable open's step 4 completes the DROP.
5753
+ */
5754
+ async _eraseReclaimRetired(report) {
5755
+ if (this.searchService.canReclaimRetired()) {
5756
+ try {
5757
+ await this.searchService.reclaimRetiredSurfaced();
5758
+ return;
5759
+ } catch (err) {
5760
+ if (!/no such module/i.test(err instanceof Error ? err.message : String(err))) {
5761
+ report.failedStep = "retired_reclaim";
5762
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: retired FTS table reclaim failed", report, err);
5763
+ }
5764
+ }
5765
+ }
5766
+ try {
5767
+ for (const name of await this._retiredList()) {
5768
+ for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
5769
+ if (await this.sourceTableExists(`${name}${sfx}`)) await this.db.runAsync(`DELETE FROM ${name}${sfx}`);
5770
+ }
5771
+ if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
5772
+ emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
5773
+ }
5774
+ } catch (err) {
5775
+ report.failedStep = "retired_reclaim";
5776
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: module-less shadow-table clear failed", report, err);
5777
+ }
5778
+ }
5779
+ /** Retired list straight from metadata (same key Fts5IndexStrategy maintains), independent of the active strategy. */
5780
+ async _retiredList() {
5781
+ let raw;
5782
+ try {
5783
+ raw = JSON.parse(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY) ?? "[]");
5784
+ } catch {
5785
+ return [];
5786
+ }
5787
+ return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
5788
+ }
5789
+ sourceTableExists(name) {
5790
+ return this.metadataRepo.tableExists(name);
5791
+ }
5792
+ /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
5793
+ async _eraseSyncEntries(entityId, ids, report) {
5794
+ let ok = false;
5795
+ try {
5796
+ ok = await this.searchService.syncEntries(entityId, ids);
5797
+ } catch (err) {
5798
+ report.failedStep = "index_sync";
5799
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId})`, report, err);
5800
+ }
5801
+ if (!ok) {
5802
+ report.failedStep = "index_sync";
5803
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId}): ledger drain failed`, report);
5804
+ }
5805
+ }
5806
+ /** Step 7: FTS optimize on both FTS tables, after syncEntries. */
5807
+ async _eraseOptimize(report) {
5808
+ try {
5809
+ await this.searchService.optimizeSurfaced();
5810
+ } catch (err) {
5811
+ report.failedStep = "optimize";
5812
+ throw new EraseStepError("erase_optimize_failed", "erase stopped at step 7: FTS optimize failed", report, err);
5813
+ }
5814
+ }
4994
5815
  async runLibrarian(entityId, options) {
4995
5816
  this.jobManager.acquireLock("librarian", entityId);
4996
5817
  try {
@@ -5111,6 +5932,9 @@ var MaintenanceService = class {
5111
5932
  if (params.includeEvents && !params.clearAll) {
5112
5933
  throw new Error("forget() includeEvents requires clearAll: true");
5113
5934
  }
5935
+ if (params.includeChain && (params.entryId === void 0 || params.clearAll || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
5936
+ throw new Error("forget() includeChain composes only with entryId");
5937
+ }
5114
5938
  if (opts?.dryRun === true) {
5115
5939
  return this.forgetDryRun(entityId, params);
5116
5940
  }
@@ -5120,6 +5944,8 @@ var MaintenanceService = class {
5120
5944
  let deletedEntries = 0;
5121
5945
  let deletedTasks = 0;
5122
5946
  let deletedEvents = 0;
5947
+ let chainIds = [];
5948
+ let chainTruncated = false;
5123
5949
  const deletedEntryIds = [];
5124
5950
  const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
5125
5951
  await this.db.withTransactionAsync(async (tx) => {
@@ -5130,6 +5956,10 @@ var MaintenanceService = class {
5130
5956
  if (await this.sourceRefIndexPresent(tx)) {
5131
5957
  await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
5132
5958
  }
5959
+ if (await this.sourceStorePresent(tx)) {
5960
+ await tx.runAsync(`DELETE FROM ${this.prefix}source_passages WHERE entity_id = ?`, [entityId]);
5961
+ await tx.runAsync(`DELETE FROM ${this.prefix}source_documents WHERE entity_id = ?`, [entityId]);
5962
+ }
5133
5963
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
5134
5964
  if (params.includeEvents) {
5135
5965
  deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
@@ -5152,6 +5982,22 @@ var MaintenanceService = class {
5152
5982
  if (params.entryId) {
5153
5983
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
5154
5984
  if (entryId) deletedEntryIds.push(entryId);
5985
+ if (entryId && params.includeChain) {
5986
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, entryId, HISTORY_MAX_DEPTH, tx);
5987
+ chainIds = walk.ids.filter((id) => id !== entryId);
5988
+ chainTruncated = walk.truncated;
5989
+ for (const id of chainIds) deletedEntryIds.push(id);
5990
+ }
5991
+ }
5992
+ if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
5993
+ const docs = `${this.prefix}source_documents`;
5994
+ const sel = "entity_id = ? AND (? IS NULL OR source_ref = ?) AND (? IS NULL OR source_hash = ?)";
5995
+ const selArgs = [entityId, sourceRef, sourceRef, sourceHash, sourceHash];
5996
+ await tx.runAsync(
5997
+ `DELETE FROM ${this.prefix}source_passages WHERE entity_id = ? AND document_id IN (SELECT id FROM ${docs} WHERE ${sel})`,
5998
+ [entityId, ...selArgs]
5999
+ );
6000
+ await tx.runAsync(`DELETE FROM ${docs} WHERE ${sel}`, selArgs);
5155
6001
  }
5156
6002
  if (sourceRef || sourceHash) {
5157
6003
  for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
@@ -5167,6 +6013,9 @@ var MaintenanceService = class {
5167
6013
  sourceRefIndexPromise ?? Promise.resolve(void 0)
5168
6014
  ]);
5169
6015
  if (entryResult) deletedEntries++;
6016
+ for (const id of chainIds) {
6017
+ if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
6018
+ }
5170
6019
  if (taskResult) deletedTasks++;
5171
6020
  deletedEntries += refResult;
5172
6021
  }
@@ -5220,7 +6069,17 @@ var MaintenanceService = class {
5220
6069
  });
5221
6070
  }
5222
6071
  }
5223
- if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
6072
+ if (!params.clearAll) {
6073
+ const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
6074
+ if (params.includeChain) {
6075
+ base.chainEntryIds = chainIds;
6076
+ if (chainTruncated) {
6077
+ base.truncated = true;
6078
+ base.notice = CHAIN_TRUNCATED_NOTICE;
6079
+ }
6080
+ }
6081
+ return base;
6082
+ }
5224
6083
  return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
5225
6084
  } finally {
5226
6085
  this.jobManager.releaseLock("forget", entityId);
@@ -5269,6 +6128,10 @@ var MaintenanceService = class {
5269
6128
  if (version < 9) return false;
5270
6129
  throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
5271
6130
  }
6131
+ /** A never-set-up store has no source-store tables (#316 recovery); nothing to delete there. */
6132
+ async sourceStorePresent(tx) {
6133
+ return await this.metadataRepo.tableExists(`${this.prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${this.prefix}source_passages`, tx);
6134
+ }
5272
6135
  /**
5273
6136
  * Read-only dry-run preview of {@link forget}. Returns the same shape as a
5274
6137
  * real call would, without acquiring the lock, opening a transaction, staging
@@ -5282,8 +6145,25 @@ var MaintenanceService = class {
5282
6145
  * (the spec keeps dry-run narrow).
5283
6146
  */
5284
6147
  async forgetDryRun(entityId, params) {
6148
+ if (params.entryId !== void 0 && params.includeChain && params.taskId === void 0) {
6149
+ const id = await this.entryRepo.findIdById(params.entryId, entityId);
6150
+ if (!id) return { deleted: { entries: 0, tasks: 0 }, chainEntryIds: [] };
6151
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, id, HISTORY_MAX_DEPTH);
6152
+ const chainEntryIds = walk.ids.filter((c) => c !== id);
6153
+ const all = [id, ...chainEntryIds];
6154
+ const live = await this.db.getFirstAsync(
6155
+ `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND id IN (${all.map(() => "?").join(",")})`,
6156
+ [entityId, ...all]
6157
+ );
6158
+ const out = { deleted: { entries: live?.n ?? 0, tasks: 0 }, chainEntryIds };
6159
+ if (walk.truncated) {
6160
+ out.truncated = true;
6161
+ out.notice = CHAIN_TRUNCATED_NOTICE;
6162
+ }
6163
+ return out;
6164
+ }
5285
6165
  if (params.entryId !== void 0 || params.taskId !== void 0) {
5286
- throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors; use sourceRef/sourceHash or clearAll");
6166
+ throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors (entryId is accepted only with includeChain); use sourceRef/sourceHash or clearAll");
5287
6167
  }
5288
6168
  if (params.clearAll) {
5289
6169
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
@@ -6130,6 +7010,63 @@ function packFactsByBudget(items, budget, scores) {
6130
7010
 
6131
7011
  // src/services/RetrievalService.ts
6132
7012
  var EMPTY_ID_SET = /* @__PURE__ */ new Set();
7013
+ var DEFAULT_SOURCE_PASSAGES = 8;
7014
+ var DEFAULT_SOURCE_CHAR_BUDGET = 4e3;
7015
+ var asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
7016
+ var isHigh2 = (c) => c >= 55296 && c <= 56319;
7017
+ var isLow2 = (c) => c >= 56320 && c <= 57343;
7018
+ function queryTerms(query) {
7019
+ return [...new Set(asciiLower(query).split(/[^\p{L}\p{N}]+/u).filter((t) => t.length > 0))];
7020
+ }
7021
+ function assertSourcesQuery(opt) {
7022
+ const query = opt?.query;
7023
+ if (typeof query !== "string" || query.trim() === "") {
7024
+ throw new WikiInvalidReadOptions("sources.query", "must be a non-empty string");
7025
+ }
7026
+ if (queryTerms(query).length === 0) {
7027
+ throw new WikiInvalidReadOptions("sources.query", "must contain at least one searchable term");
7028
+ }
7029
+ }
7030
+ function windowPassage(text, terms, budget) {
7031
+ if (text.length <= budget) return { start: 0, end: text.length, truncated: false };
7032
+ const lower = asciiLower(text);
7033
+ let a = -1;
7034
+ let len = 0;
7035
+ for (const t of terms) {
7036
+ const i = lower.indexOf(t);
7037
+ if (i >= 0 && (a < 0 || i < a || i === a && t.length > len)) {
7038
+ a = i;
7039
+ len = t.length;
7040
+ }
7041
+ }
7042
+ const hardCut = (from) => {
7043
+ let end = Math.min(text.length, from + budget);
7044
+ if (end < text.length && isHigh2(text.charCodeAt(end - 1)) && isLow2(text.charCodeAt(end))) {
7045
+ if (end - 1 > from) end -= 1;
7046
+ else return { start: from, end: from, truncated: true };
7047
+ }
7048
+ return { start: from, end, truncated: from > 0 || end < text.length };
7049
+ };
7050
+ if (a < 0) return hardCut(0);
7051
+ if (len > budget) return hardCut(a);
7052
+ const toks = [];
7053
+ for (const m of text.matchAll(/\S+/g)) toks.push([m.index, m.index + m[0].length]);
7054
+ const mEnd = a + len;
7055
+ const ti = toks.findIndex(([, e]) => e > a);
7056
+ if (ti < 0) return hardCut(a);
7057
+ let tj = ti;
7058
+ while (tj + 1 < toks.length && toks[tj][1] < mEnd) tj++;
7059
+ if (toks[tj][1] - toks[ti][0] > budget) return hardCut(a);
7060
+ let r = toks.length - 1;
7061
+ let best = { start: toks[ti][0], end: toks[tj][1] };
7062
+ for (let l = ti; l >= 0; l--) {
7063
+ const s = toks[l][0];
7064
+ while (r > tj && toks[r][1] - s > budget) r--;
7065
+ if (toks[r][1] - s > budget) break;
7066
+ if (toks[r][1] - s > best.end - best.start) best = { start: s, end: toks[r][1] };
7067
+ }
7068
+ return { ...best, truncated: true };
7069
+ }
6133
7070
  var RetrievalService = class {
6134
7071
  constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
6135
7072
  this.options = options;
@@ -6144,8 +7081,10 @@ var RetrievalService = class {
6144
7081
  const entityIds = normalizeEntityIds(entityId);
6145
7082
  const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
6146
7083
  const exposeMetadata = shouldExposeReadMetadata(entityId);
7084
+ if (options?.sources) assertSourcesQuery(options.sources);
6147
7085
  if (entityIds.length === 0) {
6148
7086
  const empty = { facts: [], tasks: [], events: [], edges: [] };
7087
+ if (options?.sources) empty.sources = [];
6149
7088
  if (exposeMetadata) {
6150
7089
  empty.metadata = { query, entityIds: [] };
6151
7090
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
@@ -6660,6 +7599,7 @@ var RetrievalService = class {
6660
7599
  factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
6661
7600
  }
6662
7601
  const bundle = { facts, tasks, events: events.reverse(), edges: [] };
7602
+ if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
6663
7603
  if (exposeMetadata) {
6664
7604
  bundle.metadata = { query, entityIds };
6665
7605
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
@@ -6668,6 +7608,42 @@ var RetrievalService = class {
6668
7608
  }
6669
7609
  return bundle;
6670
7610
  }
7611
+ /**
7612
+ * The `sources` group (spec source-store section 7). One search per entity,
7613
+ * so ranking and caps never cross entities. No model call anywhere.
7614
+ * `charBudget` is per entity: windows are cut in rank order against the
7615
+ * entity's remaining budget, and once it is spent lower-ranked hits are not returned.
7616
+ */
7617
+ async _readSources(entityIds, opt) {
7618
+ const pos = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : d;
7619
+ const maxPassages = pos(opt.maxPassages, DEFAULT_SOURCE_PASSAGES);
7620
+ const charBudget = pos(opt.charBudget, DEFAULT_SOURCE_CHAR_BUDGET);
7621
+ assertSourcesQuery(opt);
7622
+ const query = opt.query;
7623
+ const terms = queryTerms(query);
7624
+ const out = [];
7625
+ for (const entityId of entityIds) {
7626
+ const hits = await this.searchService.searchPassages(query, entityId, maxPassages);
7627
+ let remaining = charBudget;
7628
+ for (const h of hits) {
7629
+ if (remaining <= 0) break;
7630
+ const w = windowPassage(h.text, terms, remaining);
7631
+ if (w.end === w.start) continue;
7632
+ remaining -= w.end - w.start;
7633
+ out.push({
7634
+ entityId,
7635
+ sourceRef: h.source_ref,
7636
+ sourceHash: h.source_hash,
7637
+ seq: h.seq,
7638
+ startOffset: h.start_offset + w.start,
7639
+ endOffset: h.start_offset + w.end,
7640
+ truncated: w.truncated,
7641
+ text: h.text.slice(w.start, w.end)
7642
+ });
7643
+ }
7644
+ }
7645
+ return out;
7646
+ }
6671
7647
  /**
6672
7648
  * Returns entity IDs that will participate in scored retrieval.
6673
7649
  * Excludes zero-weight entities unless includeZeroWeightEntities is true.
@@ -6795,6 +7771,10 @@ var UnavailableIndexStrategy = class {
6795
7771
  }
6796
7772
  async drain(_opts) {
6797
7773
  }
7774
+ /** Degraded like everything else: no passages, no throw (spec source-store section 7). */
7775
+ async searchPassages() {
7776
+ return [];
7777
+ }
6798
7778
  };
6799
7779
 
6800
7780
  // src/services/SearchService.ts
@@ -7016,6 +7996,91 @@ var _SearchService = class _SearchService {
7016
7996
  const results = finiteResults(await this.indexStrategy.search(query, { entityIds, limit }));
7017
7997
  return results.sort((a, b) => this._compareSearchResults(a, b)).slice(0, limit);
7018
7998
  }
7999
+ /**
8000
+ * Post-commit passage index sync (spec source-store section 6). FTS5: drains the
8001
+ * passage ledger (per document, entity-scoped when given). MiniSearch: reloads
8002
+ * the entity's stored passages (all stored entities when omitted: the open-time
8003
+ * pass). Serialized on the sync chain; never rejects, like sync().
8004
+ */
8005
+ async syncPassages(db, prefix, entityId, deadline) {
8006
+ const s = this.indexStrategy;
8007
+ if (!s.drainPassages && !s.reindexSourcePassages) return;
8008
+ const work = this.syncChain.then(async () => {
8009
+ try {
8010
+ if (s.drainPassages) await s.drainPassages({ entityId, deadline });
8011
+ else await s.reindexSourcePassages(db, prefix, entityId);
8012
+ } catch (err) {
8013
+ console.warn(`[WikiMemory] passage index sync failed for ${entityId ?? "*"}:`, err);
8014
+ }
8015
+ });
8016
+ this.syncChain = work;
8017
+ return work;
8018
+ }
8019
+ /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
8020
+ chainSurfaced(fn) {
8021
+ const work = this.syncChain.then(fn);
8022
+ this.syncChain = work.then(() => void 0, () => void 0);
8023
+ return work;
8024
+ }
8025
+ /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
8026
+ hasStrictDrain() {
8027
+ const s = this.indexStrategy;
8028
+ return typeof s.drainPassagesStrict === "function" && typeof s.drainEntriesLedgerStrict === "function";
8029
+ }
8030
+ /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
8031
+ drainPassagesSurfaced() {
8032
+ const s = this.indexStrategy;
8033
+ if (!s.drainPassagesStrict) return this.chainSurfaced(async () => {
8034
+ });
8035
+ return this.chainSurfaced(() => s.drainPassagesStrict());
8036
+ }
8037
+ /** Erase step 4: listed retired FTS tables (empty for strategies without any). */
8038
+ async retiredTables() {
8039
+ const s = this.indexStrategy;
8040
+ return s.retiredTables ? s.retiredTables() : [];
8041
+ }
8042
+ /** True when the active strategy can DROP retired tables (FTS5); false for MiniSearch / Unavailable. */
8043
+ canReclaimRetired() {
8044
+ return typeof this.indexStrategy.reclaimRetiredToCompletion === "function";
8045
+ }
8046
+ /** Erase step 3: store-wide entries-side fts_pending drain on the sync chain, no deadline, errors surfaced. */
8047
+ drainEntriesLedgerSurfaced() {
8048
+ const s = this.indexStrategy;
8049
+ if (!s.drainEntriesLedgerStrict) return this.chainSurfaced(async () => {
8050
+ });
8051
+ return this.chainSurfaced(() => s.drainEntriesLedgerStrict());
8052
+ }
8053
+ /** Erase step 4: reclaim retired tables to completion; errors surfaced. */
8054
+ reclaimRetiredSurfaced() {
8055
+ const s = this.indexStrategy;
8056
+ if (!s.reclaimRetiredToCompletion) return this.chainSurfaced(async () => {
8057
+ });
8058
+ return this.chainSurfaced(() => s.reclaimRetiredToCompletion());
8059
+ }
8060
+ /** Erase step 7: FTS optimize on every FTS table that exists. */
8061
+ optimizeSurfaced() {
8062
+ const s = this.indexStrategy;
8063
+ if (!s.optimizeFts) return this.chainSurfaced(async () => {
8064
+ });
8065
+ return this.chainSurfaced(() => s.optimizeFts());
8066
+ }
8067
+ /** `erase({ rebuild: true })` wiring point; the orchestration (T6) calls it. */
8068
+ rebuildSurfaced() {
8069
+ const s = this.indexStrategy;
8070
+ if (!s.rebuildForErase) return this.chainSurfaced(async () => {
8071
+ });
8072
+ return this.chainSurfaced(() => s.rebuildForErase());
8073
+ }
8074
+ /**
8075
+ * Stored-source passage search for ONE entity (spec source-store section 7:
8076
+ * ranking and caps are per entity). Rides the active strategy; a strategy
8077
+ * without passage search yields none.
8078
+ */
8079
+ async searchPassages(query, entityId, limit) {
8080
+ if (!this.indexStrategy.searchPassages) return [];
8081
+ const hits = await this.indexStrategy.searchPassages(query, { entityIds: [entityId], limit });
8082
+ return hits.filter((h) => Number.isFinite(h.score) && h.entity_id === entityId).slice(0, limit);
8083
+ }
7019
8084
  /**
7020
8085
  * Pre-fetches keyword scores for candidate hydration, used during hybrid weighting.
7021
8086
  */
@@ -7161,7 +8226,7 @@ var JobManager = class {
7161
8226
  this.statusSubscribers = /* @__PURE__ */ new Map();
7162
8227
  /**
7163
8228
  * Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
7164
- * Excludes 'ingest' | 'global_reembed' | 'global_import', which those
8229
+ * Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
7165
8230
  * methods already handle via explicit if/else branches before reaching
7166
8231
  * this table.
7167
8232
  */
@@ -7172,7 +8237,8 @@ var JobManager = class {
7172
8237
  reembed: (id) => this._reembedKey(id),
7173
8238
  import: (id) => this._importKey(id),
7174
8239
  forget: (id) => this._forgetKey(id),
7175
- ontologyBackfill: (id) => this._ontologyBackfillKey(id)
8240
+ ontologyBackfill: (id) => this._ontologyBackfillKey(id),
8241
+ store: (id) => this._storeKey(id)
7176
8242
  };
7177
8243
  }
7178
8244
  _hashLockKey(entityId, sourceHash) {
@@ -7229,6 +8295,9 @@ var JobManager = class {
7229
8295
  _globalReembedKey() {
7230
8296
  return `${this.prefix}:reembed`;
7231
8297
  }
8298
+ _eraseKey() {
8299
+ return `${this.prefix}:erase`;
8300
+ }
7232
8301
  _importKey(entityId) {
7233
8302
  return `${this.prefix}:${entityId}:import`;
7234
8303
  }
@@ -7241,6 +8310,9 @@ var JobManager = class {
7241
8310
  _librarianKey(entityId) {
7242
8311
  return `${this.prefix}:${entityId}:librarian`;
7243
8312
  }
8313
+ _storeKey(entityId) {
8314
+ return `${this.prefix}:${entityId}:store`;
8315
+ }
7244
8316
  _healKey(entityId) {
7245
8317
  return `${this.prefix}:${entityId}:heal`;
7246
8318
  }
@@ -7269,6 +8341,9 @@ var JobManager = class {
7269
8341
  _isImportActiveFor(entityId) {
7270
8342
  return this.activeMaintenanceJobs.has(this._importKey(entityId)) || this.activeMaintenanceJobs.has(this._globalImportKey());
7271
8343
  }
8344
+ _isStoreActiveFor(entityId) {
8345
+ return this.activeMaintenanceJobs.has(this._storeKey(entityId));
8346
+ }
7272
8347
  _isForgetActiveFor(entityId) {
7273
8348
  return this.activeMaintenanceJobs.has(this._forgetKey(entityId));
7274
8349
  }
@@ -7303,11 +8378,19 @@ var JobManager = class {
7303
8378
  _isIngestActiveFor(entityId) {
7304
8379
  return this.activeIngestJobs.has(entityId);
7305
8380
  }
7306
- acquireLock(operation, entityId, sourceRef) {
8381
+ /**
8382
+ * `owner` is the fourth parameter (the third, `sourceRef`, is ingest-only).
8383
+ * `'erase'` marks the erase() pipeline's own per-entity prune, the only
8384
+ * operation exempt from the universal erase pre-check below.
8385
+ */
8386
+ acquireLock(operation, entityId, sourceRef, owner = "host") {
7307
8387
  let blockingOperation = null;
7308
8388
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
7309
8389
  throw new WikiBusyError("import", "*");
7310
8390
  }
8391
+ if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
8392
+ throw new WikiBusyError("erase", "*");
8393
+ }
7311
8394
  switch (operation) {
7312
8395
  case "prune":
7313
8396
  if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
@@ -7318,6 +8401,7 @@ var JobManager = class {
7318
8401
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
7319
8402
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7320
8403
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
8404
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7321
8405
  break;
7322
8406
  case "librarian":
7323
8407
  case "heal":
@@ -7328,6 +8412,7 @@ var JobManager = class {
7328
8412
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
7329
8413
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7330
8414
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
8415
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7331
8416
  break;
7332
8417
  }
7333
8418
  case "reembed":
@@ -7340,6 +8425,7 @@ var JobManager = class {
7340
8425
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
7341
8426
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7342
8427
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
8428
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7343
8429
  break;
7344
8430
  case "global_reembed":
7345
8431
  if (this.activeMaintenanceJobs.has(this._globalReembedKey())) blockingOperation = "reembed";
@@ -7351,6 +8437,19 @@ var JobManager = class {
7351
8437
  else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
7352
8438
  else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
7353
8439
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
8440
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
8441
+ break;
8442
+ case "erase":
8443
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) blockingOperation = "erase";
8444
+ else if (this._isAnyMaintenanceActiveWithSuffix(":reembed")) blockingOperation = "reembed";
8445
+ else if (this._isAnyMaintenanceActiveWithSuffix(":prune")) blockingOperation = "prune";
8446
+ else if (this._isAnyMaintenanceActiveWithSuffix(":librarian")) blockingOperation = "librarian";
8447
+ else if (this._isAnyMaintenanceActiveWithSuffix(":heal")) blockingOperation = "heal";
8448
+ else if (this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill")) blockingOperation = "ontologyBackfill";
8449
+ else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
8450
+ else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
8451
+ else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
8452
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7354
8453
  break;
7355
8454
  case "import":
7356
8455
  case "forget": {
@@ -7364,10 +8463,23 @@ var JobManager = class {
7364
8463
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
7365
8464
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7366
8465
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
8466
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7367
8467
  break;
7368
8468
  }
8469
+ case "store":
8470
+ if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
8471
+ else if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
8472
+ else if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) blockingOperation = "librarian";
8473
+ else if (this.activeMaintenanceJobs.has(this._healKey(entityId))) blockingOperation = "heal";
8474
+ else if (this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId))) blockingOperation = "ontologyBackfill";
8475
+ else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
8476
+ else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
8477
+ else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
8478
+ else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
8479
+ break;
7369
8480
  case "global_import":
7370
8481
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) blockingOperation = "import";
8482
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7371
8483
  break;
7372
8484
  case "ingest": {
7373
8485
  const sourceKey = sourceRef ?? "";
@@ -7376,13 +8488,14 @@ var JobManager = class {
7376
8488
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
7377
8489
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7378
8490
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
8491
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7379
8492
  break;
7380
8493
  }
7381
8494
  }
7382
8495
  if (blockingOperation) {
7383
8496
  throw new WikiBusyError(
7384
8497
  blockingOperation,
7385
- operation === "global_reembed" || operation === "global_import" ? "*" : entityId
8498
+ operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
7386
8499
  );
7387
8500
  }
7388
8501
  if (operation === "ingest") {
@@ -7391,6 +8504,8 @@ var JobManager = class {
7391
8504
  this.activeMaintenanceJobs.add(this._globalReembedKey());
7392
8505
  } else if (operation === "global_import") {
7393
8506
  this.activeMaintenanceJobs.add(this._globalImportKey());
8507
+ } else if (operation === "erase") {
8508
+ this.activeMaintenanceJobs.add(this._eraseKey());
7394
8509
  } else {
7395
8510
  this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
7396
8511
  }
@@ -7403,6 +8518,8 @@ var JobManager = class {
7403
8518
  this.activeMaintenanceJobs.delete(this._globalReembedKey());
7404
8519
  } else if (operation === "global_import") {
7405
8520
  this.activeMaintenanceJobs.delete(this._globalImportKey());
8521
+ } else if (operation === "erase") {
8522
+ this.activeMaintenanceJobs.delete(this._eraseKey());
7406
8523
  } else {
7407
8524
  this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
7408
8525
  }
@@ -7414,26 +8531,31 @@ var JobManager = class {
7414
8531
  */
7415
8532
  isBlocked(operation, entityId) {
7416
8533
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
8534
+ if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
7417
8535
  switch (operation) {
8536
+ case "erase":
8537
+ return this.activeMaintenanceJobs.has(this._eraseKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget") || this._isAnyMaintenanceActiveWithSuffix(":store");
7418
8538
  case "librarian":
7419
8539
  case "heal":
7420
8540
  case "ontologyBackfill":
7421
- return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
8541
+ return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
7422
8542
  case "prune":
7423
- return this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
8543
+ return this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
7424
8544
  case "reembed":
7425
- return this.activeMaintenanceJobs.has(this._reembedKey(entityId)) || this.activeMaintenanceJobs.has(this._globalReembedKey()) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
8545
+ return this.activeMaintenanceJobs.has(this._reembedKey(entityId)) || this.activeMaintenanceJobs.has(this._globalReembedKey()) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
7426
8546
  case "global_reembed":
7427
- return this.activeMaintenanceJobs.has(this._globalReembedKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget");
8547
+ return this.activeMaintenanceJobs.has(this._globalReembedKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget") || this._isAnyMaintenanceActiveWithSuffix(":store");
7428
8548
  case "import":
7429
8549
  case "forget": {
7430
8550
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
7431
- return this.activeMaintenanceJobs.has(selfKey) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
8551
+ return this.activeMaintenanceJobs.has(selfKey) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
7432
8552
  }
8553
+ case "store":
8554
+ return this._isStoreActiveFor(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
7433
8555
  case "global_import":
7434
- return this.activeMaintenanceJobs.has(this._globalImportKey());
8556
+ return this.activeMaintenanceJobs.has(this._globalImportKey()) || this._isAnyMaintenanceActiveWithSuffix(":store");
7435
8557
  case "ingest":
7436
- return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
8558
+ return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
7437
8559
  default:
7438
8560
  return false;
7439
8561
  }
@@ -7446,6 +8568,7 @@ var JobManager = class {
7446
8568
  */
7447
8569
  tryAcquireAutoHealLock(entityId) {
7448
8570
  if (this.isAnyReembedActive()) return false;
8571
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
7449
8572
  const healKey = this._healKey(entityId);
7450
8573
  if (this.activeMaintenanceJobs.has(healKey)) return false;
7451
8574
  this.activeMaintenanceJobs.add(healKey);
@@ -7489,6 +8612,7 @@ var JobManager = class {
7489
8612
  * Validates all entities before acquiring any lock (same as current importDump semantics).
7490
8613
  */
7491
8614
  acquireImportLocks(entityIds) {
8615
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
7492
8616
  for (const entityId of entityIds) {
7493
8617
  if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
7494
8618
  if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);
@@ -7498,6 +8622,7 @@ var JobManager = class {
7498
8622
  if (this._isReembedActive(entityId)) throw new WikiBusyError("reembed", entityId);
7499
8623
  if (this._isIngestActiveFor(entityId)) throw new WikiBusyError("ingest", entityId);
7500
8624
  if (this._isForgetActiveFor(entityId)) throw new WikiBusyError("forget", entityId);
8625
+ if (this._isStoreActiveFor(entityId)) throw new WikiBusyError("store", entityId);
7501
8626
  }
7502
8627
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) throw new WikiBusyError("import", "*");
7503
8628
  this.activeMaintenanceJobs.add(this._globalImportKey());