@equationalapplications/core-llm-wiki 9.2.0 → 9.4.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.
@@ -189,8 +189,8 @@ var WikiDraftNotFound = class _WikiDraftNotFound extends Error {
189
189
  }
190
190
  };
191
191
  var WikiSupersedeError = class _WikiSupersedeError extends Error {
192
- constructor(reason) {
193
- super(`supersede() rejected: ${reason}`);
192
+ constructor(reason, verb = "supersede()") {
193
+ super(`${verb} rejected: ${reason}`);
194
194
  this.code = "WIKI_SUPERSEDE_REJECTED";
195
195
  this.name = "WikiSupersedeError";
196
196
  this.reason = reason;
@@ -935,6 +935,273 @@ function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
935
935
  return valid;
936
936
  }
937
937
 
938
+ // src/repositories/BaseRepository.ts
939
+ var BaseRepository = class {
940
+ constructor(db, prefix) {
941
+ this.db = db;
942
+ this.prefix = prefix;
943
+ }
944
+ /**
945
+ * Return the DB executor for a given transaction handle.
946
+ * If tx is provided, use it; otherwise fall back to this.db.
947
+ */
948
+ getExecutor(tx) {
949
+ return tx ?? this.db;
950
+ }
951
+ };
952
+
953
+ // src/repositories/MetadataRepository.ts
954
+ function entitySummaryMetaKey(entityId) {
955
+ return `entity_summary:${entityId}`;
956
+ }
957
+ var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
958
+ var CheckpointIncompleteError = class extends Error {
959
+ constructor() {
960
+ super(...arguments);
961
+ this.code = "erase_checkpoint_incomplete";
962
+ }
963
+ };
964
+ var MetadataRepository = class extends BaseRepository {
965
+ // CHECKPOINTS TABLE METHODS
966
+ async getCheckpoint(entityId, tx) {
967
+ const executor = this.getExecutor(tx);
968
+ const row = await executor.getFirstAsync(
969
+ `SELECT memory_checkpoint, heal_checkpoint FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
970
+ [entityId]
971
+ );
972
+ if (!row) return {};
973
+ return {
974
+ memory: row.memory_checkpoint ?? void 0,
975
+ heal: row.heal_checkpoint ?? void 0
976
+ };
977
+ }
978
+ async updateCheckpoint(entityId, updates, tx) {
979
+ const fields = [];
980
+ const values = [];
981
+ if (updates.memory !== void 0) {
982
+ fields.push("memory_checkpoint = ?");
983
+ values.push(updates.memory);
984
+ }
985
+ if (updates.heal !== void 0) {
986
+ fields.push("heal_checkpoint = ?");
987
+ values.push(updates.heal);
988
+ }
989
+ if (fields.length === 0) return;
990
+ const executor = this.getExecutor(tx);
991
+ await executor.runAsync(
992
+ `INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint)
993
+ VALUES (?, ?, ?)
994
+ ON CONFLICT(entity_id) DO UPDATE SET ${fields.join(", ")}`,
995
+ [entityId, updates.memory ?? 0, updates.heal ?? 0, ...values]
996
+ );
997
+ }
998
+ async deleteCheckpoint(entityId, tx) {
999
+ const executor = this.getExecutor(tx);
1000
+ await executor.runAsync(
1001
+ `DELETE FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
1002
+ [entityId]
1003
+ );
1004
+ }
1005
+ /**
1006
+ * Read the op-based librarian's high-water mark. Returns `null` when the
1007
+ * entity has never had its watermark set.
1008
+ */
1009
+ async getLibrarianWatermark(entityId, tx) {
1010
+ const executor = this.getExecutor(tx);
1011
+ const row = await executor.getFirstAsync(
1012
+ `SELECT librarian_watermark_at, librarian_watermark_id FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
1013
+ [entityId]
1014
+ );
1015
+ if (!row || row.librarian_watermark_at == null || row.librarian_watermark_id == null) {
1016
+ return null;
1017
+ }
1018
+ return { at: row.librarian_watermark_at, id: row.librarian_watermark_id };
1019
+ }
1020
+ /**
1021
+ * Write the op-based librarian's high-water mark. Uses `ON CONFLICT`
1022
+ * `DO UPDATE` so existing `memory_checkpoint` / `heal_checkpoint` rows
1023
+ * are preserved verbatim.
1024
+ */
1025
+ async setLibrarianWatermark(entityId, wm, tx) {
1026
+ const executor = this.getExecutor(tx);
1027
+ await executor.runAsync(
1028
+ `INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint, librarian_watermark_at, librarian_watermark_id)
1029
+ VALUES (?, 0, 0, ?, ?)
1030
+ ON CONFLICT(entity_id) DO UPDATE SET
1031
+ librarian_watermark_at = excluded.librarian_watermark_at,
1032
+ librarian_watermark_id = excluded.librarian_watermark_id`,
1033
+ [entityId, wm.at, wm.id]
1034
+ );
1035
+ }
1036
+ // META TABLE METHODS
1037
+ async getMeta(key, tx) {
1038
+ const executor = this.getExecutor(tx);
1039
+ const row = await executor.getFirstAsync(
1040
+ `SELECT value FROM ${this.prefix}meta WHERE key = ?`,
1041
+ [key]
1042
+ );
1043
+ return row ? row.value : null;
1044
+ }
1045
+ async setMeta(key, value, tx) {
1046
+ const executor = this.getExecutor(tx);
1047
+ await executor.runAsync(
1048
+ `INSERT INTO ${this.prefix}meta (key, value) VALUES (?, ?)
1049
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
1050
+ [key, value]
1051
+ );
1052
+ }
1053
+ async deleteMeta(key, tx) {
1054
+ const executor = this.getExecutor(tx);
1055
+ await executor.runAsync(
1056
+ `DELETE FROM ${this.prefix}meta WHERE key = ?`,
1057
+ [key]
1058
+ );
1059
+ }
1060
+ async clearDimensionMismatch(tx) {
1061
+ const executor = this.getExecutor(tx);
1062
+ await executor.runAsync(
1063
+ `DELETE FROM ${this.prefix}meta WHERE key = 'embedding_dimension_mismatch'`
1064
+ );
1065
+ }
1066
+ async tableExists(tableName, tx) {
1067
+ const executor = this.getExecutor(tx);
1068
+ const row = await executor.getFirstAsync(
1069
+ `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
1070
+ [tableName]
1071
+ );
1072
+ return row != null;
1073
+ }
1074
+ async getTableDdl(tableName, tx) {
1075
+ const executor = this.getExecutor(tx);
1076
+ const row = await executor.getFirstAsync(
1077
+ `SELECT sql FROM sqlite_master WHERE type='table' AND name=?`,
1078
+ [tableName]
1079
+ );
1080
+ return row?.sql ?? null;
1081
+ }
1082
+ /**
1083
+ * `PRAGMA wal_checkpoint(TRUNCATE)`, verified: `busy !== 0` or
1084
+ * `log !== checkpointed` means frames survive in the WAL, so a deleted
1085
+ * row's bytes may still be on disk. Non-WAL reports (0,-1,-1) = complete.
1086
+ */
1087
+ async checkpointTruncateVerified() {
1088
+ const row = await this.db.getFirstAsync(
1089
+ `PRAGMA wal_checkpoint(TRUNCATE)`
1090
+ );
1091
+ if (row && (row.busy !== 0 || row.log !== row.checkpointed)) {
1092
+ throw new CheckpointIncompleteError(
1093
+ `wal_checkpoint(TRUNCATE) incomplete (busy=${row?.busy}, log=${row?.log}, checkpointed=${row?.checkpointed})`
1094
+ );
1095
+ }
1096
+ }
1097
+ async vacuum() {
1098
+ await this.checkpointTruncateVerified();
1099
+ await this.db.execAsync(`VACUUM`);
1100
+ await this.checkpointTruncateVerified();
1101
+ }
1102
+ /**
1103
+ * Returns the set of distinct `entity_id` values across entries/tasks/events.
1104
+ *
1105
+ * Deliberately widened from a prior `WHERE deleted_at IS NULL` form: the
1106
+ * returned set intentionally includes entities whose only rows are
1107
+ * soft-deleted, so the host's maintenance sweep can visit such
1108
+ * "decommissioned-scope" namespaces and reap the soft-deleted rows. Sorting
1109
+ * is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
1110
+ *
1111
+ * With `opts.softDeletedAtOrBefore` the walk is narrowed to entities holding
1112
+ * at least one soft-deleted entry or task with `deleted_at` at or before
1113
+ * that cutoff (erase's hard-delete walk, forget-erasure spec §2). Without
1114
+ * the option the host-facing semantics above are unchanged.
1115
+ */
1116
+ async getDistinctEntityIds(tx, opts) {
1117
+ const executor = this.getExecutor(tx);
1118
+ if (opts?.softDeletedAll) {
1119
+ const rows2 = await executor.getAllAsync(
1120
+ `SELECT DISTINCT entity_id FROM (
1121
+ SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL
1122
+ UNION
1123
+ SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL
1124
+ ) ORDER BY entity_id COLLATE BINARY`
1125
+ );
1126
+ return rows2.map((r) => r.entity_id);
1127
+ }
1128
+ if (opts?.softDeletedAtOrBefore !== void 0) {
1129
+ const cutoff = opts.softDeletedAtOrBefore;
1130
+ const rows2 = await executor.getAllAsync(
1131
+ `SELECT DISTINCT entity_id FROM (
1132
+ SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL AND deleted_at <= ?
1133
+ UNION
1134
+ SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL AND deleted_at <= ?
1135
+ ) ORDER BY entity_id COLLATE BINARY`,
1136
+ [cutoff, cutoff]
1137
+ );
1138
+ return rows2.map((r) => r.entity_id);
1139
+ }
1140
+ const rows = await executor.getAllAsync(
1141
+ `SELECT DISTINCT entity_id FROM (
1142
+ SELECT entity_id FROM ${this.prefix}entries
1143
+ UNION
1144
+ SELECT entity_id FROM ${this.prefix}tasks
1145
+ UNION
1146
+ SELECT entity_id FROM ${this.prefix}events
1147
+ ) ORDER BY entity_id COLLATE BINARY`
1148
+ );
1149
+ return rows.map((r) => r.entity_id);
1150
+ }
1151
+ async getManifest(entityId, tx) {
1152
+ const executor = this.getExecutor(tx);
1153
+ const row = await executor.getFirstAsync(`SELECT mode, manifest_json FROM ${this.prefix}entity_manifests WHERE entity_id = ?`, [entityId]);
1154
+ if (!row) return null;
1155
+ if (row.mode !== "off" && row.mode !== "strict" && row.mode !== "emergent") {
1156
+ throw new Error(`Invalid ontology mode for entity ${entityId}: ${JSON.stringify(row.mode)}`);
1157
+ }
1158
+ let manifest;
1159
+ try {
1160
+ manifest = JSON.parse(row.manifest_json);
1161
+ } catch (error) {
1162
+ throw new Error(`Invalid manifest_json for entity ${entityId}: ${error.message}`);
1163
+ }
1164
+ validateManifest(manifest);
1165
+ return {
1166
+ mode: row.mode,
1167
+ manifest
1168
+ };
1169
+ }
1170
+ /**
1171
+ * Write an entity's manifest.
1172
+ *
1173
+ * `opts.ifAbsent` selects the conflict behaviour:
1174
+ * - omitted / `false` — upsert. An existing row is replaced.
1175
+ * - `true` — create-if-absent. An existing row is left exactly as it is.
1176
+ *
1177
+ * Returns whether this call actually wrote a row. Under `ifAbsent` a `false`
1178
+ * result means another writer got there first; the check and the write are one
1179
+ * statement, so there is no window between them.
1180
+ */
1181
+ async setManifest(entityId, data, tx, opts) {
1182
+ validateManifest(data.manifest);
1183
+ const executor = this.getExecutor(tx);
1184
+ const conflictClause = opts?.ifAbsent ? "ON CONFLICT(entity_id) DO NOTHING" : `ON CONFLICT(entity_id) DO UPDATE SET
1185
+ mode = excluded.mode, manifest_json = excluded.manifest_json, updated_at = excluded.updated_at`;
1186
+ const result = await executor.runAsync(
1187
+ `INSERT INTO ${this.prefix}entity_manifests (entity_id, mode, manifest_json, updated_at)
1188
+ VALUES (?, ?, ?, ?)
1189
+ ${conflictClause}`,
1190
+ [entityId, data.mode, JSON.stringify(data.manifest), Date.now()]
1191
+ );
1192
+ return result.changes > 0;
1193
+ }
1194
+ async mergeManifestUpdates(entityId, updates, tx) {
1195
+ const current = await this.getManifest(entityId, tx) ?? {
1196
+ mode: "emergent",
1197
+ manifest: emptyManifest()
1198
+ };
1199
+ const merged = mergeOntologyUpdates(current.manifest, updates);
1200
+ await this.setManifest(entityId, { mode: current.mode, manifest: merged }, tx);
1201
+ return merged;
1202
+ }
1203
+ };
1204
+
938
1205
  // src/utils/embedding.ts
939
1206
  function parseEmbedding(blob, text) {
940
1207
  if (blob && blob.byteLength > 0) {
@@ -1259,6 +1526,65 @@ var _SearchService = class _SearchService {
1259
1526
  this.syncChain = work;
1260
1527
  return work;
1261
1528
  }
1529
+ /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
1530
+ chainSurfaced(fn) {
1531
+ const work = this.syncChain.then(fn);
1532
+ this.syncChain = work.then(() => void 0, () => void 0);
1533
+ return work;
1534
+ }
1535
+ /** True when the active strategy is the transient outage placeholder (erase orphan remediation, D1: never drop under it). */
1536
+ isIndexUnavailable() {
1537
+ return this.indexStrategy instanceof UnavailableIndexStrategy;
1538
+ }
1539
+ /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
1540
+ hasStrictDrain() {
1541
+ const s = this.indexStrategy;
1542
+ return typeof s.drainPassagesStrict === "function" && typeof s.drainEntriesLedgerStrict === "function";
1543
+ }
1544
+ /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
1545
+ drainPassagesSurfaced() {
1546
+ const s = this.indexStrategy;
1547
+ if (!s.drainPassagesStrict) return this.chainSurfaced(async () => {
1548
+ });
1549
+ return this.chainSurfaced(() => s.drainPassagesStrict());
1550
+ }
1551
+ /** Erase step 4: listed retired FTS tables (empty for strategies without any). */
1552
+ async retiredTables() {
1553
+ const s = this.indexStrategy;
1554
+ return s.retiredTables ? s.retiredTables() : [];
1555
+ }
1556
+ /** True when the active strategy can DROP retired tables (FTS5); false for MiniSearch / Unavailable. */
1557
+ canReclaimRetired() {
1558
+ return typeof this.indexStrategy.reclaimRetiredToCompletion === "function";
1559
+ }
1560
+ /** Erase step 3: store-wide entries-side fts_pending drain on the sync chain, no deadline, errors surfaced. */
1561
+ drainEntriesLedgerSurfaced() {
1562
+ const s = this.indexStrategy;
1563
+ if (!s.drainEntriesLedgerStrict) return this.chainSurfaced(async () => {
1564
+ });
1565
+ return this.chainSurfaced(() => s.drainEntriesLedgerStrict());
1566
+ }
1567
+ /** Erase step 4: reclaim retired tables to completion; errors surfaced. */
1568
+ reclaimRetiredSurfaced() {
1569
+ const s = this.indexStrategy;
1570
+ if (!s.reclaimRetiredToCompletion) return this.chainSurfaced(async () => {
1571
+ });
1572
+ return this.chainSurfaced(() => s.reclaimRetiredToCompletion());
1573
+ }
1574
+ /** Erase step 7: FTS optimize on every FTS table that exists. */
1575
+ optimizeSurfaced() {
1576
+ const s = this.indexStrategy;
1577
+ if (!s.optimizeFts) return this.chainSurfaced(async () => {
1578
+ });
1579
+ return this.chainSurfaced(() => s.optimizeFts());
1580
+ }
1581
+ /** `erase({ rebuild: true })` wiring point; the orchestration (T6) calls it. */
1582
+ rebuildSurfaced() {
1583
+ const s = this.indexStrategy;
1584
+ if (!s.rebuildForErase) return this.chainSurfaced(async () => {
1585
+ });
1586
+ return this.chainSurfaced(() => s.rebuildForErase());
1587
+ }
1262
1588
  /**
1263
1589
  * Stored-source passage search for ONE entity (spec source-store section 7:
1264
1590
  * ranking and caps are per entity). Rides the active strategy; a strategy
@@ -1414,7 +1740,7 @@ var JobManager = class {
1414
1740
  this.statusSubscribers = /* @__PURE__ */ new Map();
1415
1741
  /**
1416
1742
  * Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
1417
- * Excludes 'ingest' | 'global_reembed' | 'global_import', which those
1743
+ * Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
1418
1744
  * methods already handle via explicit if/else branches before reaching
1419
1745
  * this table.
1420
1746
  */
@@ -1483,6 +1809,9 @@ var JobManager = class {
1483
1809
  _globalReembedKey() {
1484
1810
  return `${this.prefix}:reembed`;
1485
1811
  }
1812
+ _eraseKey() {
1813
+ return `${this.prefix}:erase`;
1814
+ }
1486
1815
  _importKey(entityId) {
1487
1816
  return `${this.prefix}:${entityId}:import`;
1488
1817
  }
@@ -1563,11 +1892,19 @@ var JobManager = class {
1563
1892
  _isIngestActiveFor(entityId) {
1564
1893
  return this.activeIngestJobs.has(entityId);
1565
1894
  }
1566
- acquireLock(operation, entityId, sourceRef) {
1895
+ /**
1896
+ * `owner` is the fourth parameter (the third, `sourceRef`, is ingest-only).
1897
+ * `'erase'` marks the erase() pipeline's own per-entity prune, the only
1898
+ * operation exempt from the universal erase pre-check below.
1899
+ */
1900
+ acquireLock(operation, entityId, sourceRef, owner = "host") {
1567
1901
  let blockingOperation = null;
1568
1902
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
1569
1903
  throw new WikiBusyError("import", "*");
1570
1904
  }
1905
+ if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
1906
+ throw new WikiBusyError("erase", "*");
1907
+ }
1571
1908
  switch (operation) {
1572
1909
  case "prune":
1573
1910
  if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
@@ -1616,6 +1953,18 @@ var JobManager = class {
1616
1953
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
1617
1954
  else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
1618
1955
  break;
1956
+ case "erase":
1957
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) blockingOperation = "erase";
1958
+ else if (this._isAnyMaintenanceActiveWithSuffix(":reembed")) blockingOperation = "reembed";
1959
+ else if (this._isAnyMaintenanceActiveWithSuffix(":prune")) blockingOperation = "prune";
1960
+ else if (this._isAnyMaintenanceActiveWithSuffix(":librarian")) blockingOperation = "librarian";
1961
+ else if (this._isAnyMaintenanceActiveWithSuffix(":heal")) blockingOperation = "heal";
1962
+ else if (this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill")) blockingOperation = "ontologyBackfill";
1963
+ else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
1964
+ else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
1965
+ else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
1966
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
1967
+ break;
1619
1968
  case "import":
1620
1969
  case "forget": {
1621
1970
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
@@ -1660,7 +2009,7 @@ var JobManager = class {
1660
2009
  if (blockingOperation) {
1661
2010
  throw new WikiBusyError(
1662
2011
  blockingOperation,
1663
- operation === "global_reembed" || operation === "global_import" ? "*" : entityId
2012
+ operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
1664
2013
  );
1665
2014
  }
1666
2015
  if (operation === "ingest") {
@@ -1669,6 +2018,8 @@ var JobManager = class {
1669
2018
  this.activeMaintenanceJobs.add(this._globalReembedKey());
1670
2019
  } else if (operation === "global_import") {
1671
2020
  this.activeMaintenanceJobs.add(this._globalImportKey());
2021
+ } else if (operation === "erase") {
2022
+ this.activeMaintenanceJobs.add(this._eraseKey());
1672
2023
  } else {
1673
2024
  this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
1674
2025
  }
@@ -1681,6 +2032,8 @@ var JobManager = class {
1681
2032
  this.activeMaintenanceJobs.delete(this._globalReembedKey());
1682
2033
  } else if (operation === "global_import") {
1683
2034
  this.activeMaintenanceJobs.delete(this._globalImportKey());
2035
+ } else if (operation === "erase") {
2036
+ this.activeMaintenanceJobs.delete(this._eraseKey());
1684
2037
  } else {
1685
2038
  this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
1686
2039
  }
@@ -1692,7 +2045,10 @@ var JobManager = class {
1692
2045
  */
1693
2046
  isBlocked(operation, entityId) {
1694
2047
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
2048
+ if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
1695
2049
  switch (operation) {
2050
+ case "erase":
2051
+ 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");
1696
2052
  case "librarian":
1697
2053
  case "heal":
1698
2054
  case "ontologyBackfill":
@@ -1726,6 +2082,7 @@ var JobManager = class {
1726
2082
  */
1727
2083
  tryAcquireAutoHealLock(entityId) {
1728
2084
  if (this.isAnyReembedActive()) return false;
2085
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
1729
2086
  const healKey = this._healKey(entityId);
1730
2087
  if (this.activeMaintenanceJobs.has(healKey)) return false;
1731
2088
  this.activeMaintenanceJobs.add(healKey);
@@ -1769,6 +2126,7 @@ var JobManager = class {
1769
2126
  * Validates all entities before acquiring any lock (same as current importDump semantics).
1770
2127
  */
1771
2128
  acquireImportLocks(entityIds) {
2129
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
1772
2130
  for (const entityId of entityIds) {
1773
2131
  if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
1774
2132
  if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);
@@ -2337,6 +2695,16 @@ var SEVERITY = {
2337
2695
  resolve_failed: "warn",
2338
2696
  read_budget: "info",
2339
2697
  event_retention_held: "info",
2698
+ prune_checkpoint_incomplete: "warn",
2699
+ erase_secure_delete_off: "error",
2700
+ erase_entity_skipped: "warn",
2701
+ erase_retired_vtab_undroppable: "warn",
2702
+ erase_fts_orphan_cleared: "info",
2703
+ erase_retired_remaining: "error",
2704
+ erase_tombstones_remaining: "error",
2705
+ erase_retired_read_failed: "error",
2706
+ erase_registry_sweep_skipped: "info",
2707
+ import_tombstone_skipped: "info",
2340
2708
  event_created_at_clamped: "warn",
2341
2709
  event_created_at_restamped: "info",
2342
2710
  external_deletion_pending: "warn",
@@ -2372,6 +2740,16 @@ var MESSAGE = {
2372
2740
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
2373
2741
  read_budget: "A read was packed to a token budget.",
2374
2742
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
2743
+ 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.",
2744
+ erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
2745
+ erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow-table text rows were emptied (fts5 %_config and %_data ids 1 and 10 are intentionally kept) and the name stays listed until an FTS5-capable open drops it.",
2746
+ erase_fts_orphan_cleared: "An orphaned FTS5 surface (shadow or companion table, or a queryable vtab) was cleared during erase so forgotten text cannot survive in it.",
2747
+ erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
2748
+ erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
2749
+ erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
2750
+ erase_entity_skipped: "Erase skipped an entity because another operation held its prune lock.",
2751
+ erase_registry_sweep_skipped: "Erase skipped the source_ref_index tombstone sweep because the table does not exist (pre-v9 store).",
2752
+ 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.",
2375
2753
  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.",
2376
2754
  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.",
2377
2755
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
@@ -3250,6 +3628,134 @@ function classifierStateForFact(fact) {
3250
3628
  return parts.join("\n\n");
3251
3629
  }
3252
3630
 
3631
+ // src/utils/temporal.ts
3632
+ function liveAtSql(mode, alias = "") {
3633
+ const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3634
+ return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3635
+ }
3636
+ function isLiveAt(f, mode, t) {
3637
+ if (f.deleted_at != null) return false;
3638
+ const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
3639
+ if (from != null && from > t) return false;
3640
+ return f.valid_to == null || f.valid_to > t;
3641
+ }
3642
+ function assertEpochMs(name, v) {
3643
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3644
+ throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3645
+ }
3646
+ return Math.trunc(v);
3647
+ }
3648
+
3649
+ // src/services/TemporalService.ts
3650
+ var HISTORY_MAX_DEPTH = 100;
3651
+ var TemporalService = class {
3652
+ constructor(db, options, entryRepo, searchService, embeddingService) {
3653
+ this.db = db;
3654
+ this.options = options;
3655
+ this.entryRepo = entryRepo;
3656
+ this.searchService = searchService;
3657
+ this.embeddingService = embeddingService;
3658
+ }
3659
+ /**
3660
+ * Link `oldId` → `newId` inside the caller's transaction. `newId` must
3661
+ * already exist. Throws WikiSupersedeError on any rule violation; the
3662
+ * caller's transaction then rolls back.
3663
+ */
3664
+ async supersedeInTx(tx, entityId, oldId, newId, t, now) {
3665
+ const old = await this.entryRepo.findTemporalRow(oldId, tx);
3666
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
3667
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3668
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3669
+ if (old.valid_to != null && old.valid_to <= Math.max(now, Date.now())) throw new WikiSupersedeError("already_expired");
3670
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
3671
+ if (newId === oldId) throw new WikiSupersedeError("cycle");
3672
+ const repl = await this.entryRepo.findTemporalRow(newId, tx);
3673
+ if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
3674
+ if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3675
+ if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3676
+ const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
3677
+ if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
3678
+ await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
3679
+ if (repl.valid_from == null) {
3680
+ await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
3681
+ }
3682
+ }
3683
+ async supersede(entityId, oldId, replacement, options) {
3684
+ const now = Date.now();
3685
+ const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
3686
+ let created = null;
3687
+ if (typeof replacement !== "string") {
3688
+ if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
3689
+ throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
3690
+ }
3691
+ created = {
3692
+ id: generateId("fact_"),
3693
+ entity_id: entityId,
3694
+ title: replacement.title,
3695
+ body: replacement.body,
3696
+ tags: Array.isArray(replacement.tags) ? replacement.tags : [],
3697
+ confidence: replacement.confidence ?? "certain",
3698
+ source_type: replacement.source_type ?? "user_stated",
3699
+ source_hash: null,
3700
+ source_ref: null,
3701
+ created_at: now,
3702
+ updated_at: now,
3703
+ last_accessed_at: null,
3704
+ access_count: 0,
3705
+ deleted_at: null
3706
+ };
3707
+ }
3708
+ const newId = typeof replacement === "string" ? replacement : created.id;
3709
+ const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
3710
+ await this.db.withTransactionAsync(async (tx) => {
3711
+ if (created) {
3712
+ await this.entryRepo.upsert(created, tx);
3713
+ if (newValidFrom !== void 0) {
3714
+ await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
3715
+ }
3716
+ }
3717
+ await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
3718
+ });
3719
+ await this.searchService.syncEntries(entityId, [oldId, newId]);
3720
+ if (created) {
3721
+ await this.embeddingService.embedFact(
3722
+ { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
3723
+ { operation: "supersede", trigger: "call" }
3724
+ );
3725
+ }
3726
+ this.searchService.evictCache(entityId);
3727
+ return { newId };
3728
+ }
3729
+ /**
3730
+ * End `factId`'s validity without a replacement — an archive, not a
3731
+ * deletion (INTENT rule 12, spec specs/expire). Sets `valid_to` only.
3732
+ */
3733
+ async expire(entityId, factId, options) {
3734
+ const t = options?.at === void 0 ? Date.now() : assertEpochMs("options.at", options.at);
3735
+ await this.db.withTransactionAsync(async (tx) => {
3736
+ const old = await this.entryRepo.findTemporalRow(factId, tx);
3737
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found", "expire()");
3738
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "expire()");
3739
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded", "expire()");
3740
+ if (old.valid_to != null) throw new WikiSupersedeError("already_expired", "expire()");
3741
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "expire()");
3742
+ const start = old.valid_from ?? old.created_at;
3743
+ if (t <= start) throw new WikiSupersedeError("invalid_interval", "expire()");
3744
+ const changes = await this.entryRepo.setTemporal(factId, entityId, { valid_to: t }, tx);
3745
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "expire()");
3746
+ });
3747
+ await this.searchService.syncEntries(entityId, [factId]);
3748
+ this.searchService.evictCache(entityId);
3749
+ }
3750
+ async history(entityId, factId) {
3751
+ const start = await this.entryRepo.findTemporalRow(factId);
3752
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
3753
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
3754
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
3755
+ 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));
3756
+ }
3757
+ };
3758
+
3253
3759
  // src/utils/engineDefaults.ts
3254
3760
  var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3255
3761
  var DEFAULT_MAINTENANCE_MODE = "deferred";
@@ -3288,21 +3794,6 @@ function warnChangedDefaultsOnce(config) {
3288
3794
  }
3289
3795
  }
3290
3796
 
3291
- // src/repositories/BaseRepository.ts
3292
- var BaseRepository = class {
3293
- constructor(db, prefix) {
3294
- this.db = db;
3295
- this.prefix = prefix;
3296
- }
3297
- /**
3298
- * Return the DB executor for a given transaction handle.
3299
- * If tx is provided, use it; otherwise fall back to this.db.
3300
- */
3301
- getExecutor(tx) {
3302
- return tx ?? this.db;
3303
- }
3304
- };
3305
-
3306
3797
  // src/repositories/VectorRemovalRepository.ts
3307
3798
  var CHUNK = 500;
3308
3799
  function removalBackoffMs(attempts) {
@@ -3840,24 +4331,6 @@ function withBudget(p, ms) {
3840
4331
  });
3841
4332
  }
3842
4333
 
3843
- // src/utils/temporal.ts
3844
- function liveAtSql(mode, alias = "") {
3845
- const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3846
- return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3847
- }
3848
- function isLiveAt(f, mode, t) {
3849
- if (f.deleted_at != null) return false;
3850
- const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
3851
- if (from != null && from > t) return false;
3852
- return f.valid_to == null || f.valid_to > t;
3853
- }
3854
- function assertEpochMs(name, v) {
3855
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3856
- throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3857
- }
3858
- return Math.trunc(v);
3859
- }
3860
-
3861
4334
  // src/repositories/EdgeRepository.ts
3862
4335
  var CONFIDENCE_RANK = {
3863
4336
  tentative: 0,
@@ -3901,342 +4374,139 @@ var EdgeRepository = class extends BaseRepository {
3901
4374
  /** Hard delete — edges have no soft-delete concept, only presence/absence. `tx` is REQUIRED. */
3902
4375
  async bulkDeleteByEntityId(entityId, tx) {
3903
4376
  const executor = this.getExecutor(tx);
3904
- await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);
3905
- }
3906
- /**
3907
- * Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to
3908
- * `entityId`. Returns the number of rows deleted. Edges have no soft-delete
3909
- * concept; this method is named `softDeleteBySourceFactIds` for symmetry with
3910
- * `EntryRepository.softDeleteBySource` (which IS a soft delete), but its
3911
- * semantics are immediate presence/absence removal. Use ONLY inside an open
3912
- * transaction — the method requires `tx` and performs no autocommit.
3913
- *
3914
- * Used by `IngestionService.upsertGraphCore` to retire the prior parse's
3915
- * edges whose source facts are being superseded by `softDeleteBySource`.
3916
- */
3917
- async softDeleteBySourceFactIds(entityId, sourceFactIds, tx) {
3918
- if (sourceFactIds.length === 0) return 0;
3919
- const executor = this.getExecutor(tx);
3920
- const chunkSize = 500;
3921
- let totalChanges = 0;
3922
- for (let i = 0; i < sourceFactIds.length; i += chunkSize) {
3923
- const chunk = sourceFactIds.slice(i, i + chunkSize);
3924
- const placeholders = chunk.map(() => "?").join(",");
3925
- const result = await executor.runAsync(
3926
- `DELETE FROM ${this.prefix}edges
3927
- WHERE entity_id = ? AND source_id IN (${placeholders})`,
3928
- [entityId, ...chunk]
3929
- );
3930
- totalChanges += result.changes;
3931
- }
3932
- return totalChanges;
3933
- }
3934
- /**
3935
- * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
3936
- * dead-ending, cycle-guarding, capping, and ordering happens in this one query.
3937
- * The anchor is validated (exists, right entity, not soft-deleted) but never gated
3938
- * by confidence/source_type — only nodes discovered beyond it are.
3939
- */
3940
- async getNeighborhood(entityId, sourceId, opts, tx) {
3941
- const executor = this.getExecutor(tx);
3942
- if (opts.edgeTypes && opts.edgeTypes.length === 0) {
3943
- const anchor = await executor.getFirstAsync(
3944
- `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
3945
- [sourceId, entityId]
3946
- );
3947
- return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
3948
- }
3949
- const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
3950
- const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
3951
- const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
3952
- const sql = `
3953
- WITH RECURSIVE walk(node_id, depth, visited) AS (
3954
- SELECT id, 0, ',' || id || ','
3955
- FROM ${this.prefix}entries
3956
- WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
3957
-
3958
- UNION
3959
-
3960
- SELECT
3961
- CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
3962
- w.depth + 1,
3963
- w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
3964
- FROM walk w
3965
- JOIN ${this.prefix}edges e
3966
- ON e.entity_id = ?
3967
- AND (
3968
- (? != 'inbound' AND e.source_id = w.node_id) OR
3969
- (? != 'outbound' AND e.target_id = w.node_id)
3970
- )
3971
- AND (${edgeTypesClause})
3972
- JOIN ${this.prefix}entries n
3973
- ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
3974
- AND n.entity_id = ?
3975
- AND n.deleted_at IS NULL
3976
- AND (
3977
- CASE n.confidence
3978
- WHEN 'tentative' THEN 0
3979
- WHEN 'inferred' THEN 1
3980
- WHEN 'certain' THEN 2
3981
- ELSE -1
3982
- END
3983
- ) >= ?
3984
- AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
3985
- AND (? = 0 OR n.lifecycle_status != 'draft')
3986
- AND ${liveAtSql(opts.live.mode, "n.")}
3987
- WHERE w.depth < ?
3988
- AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
3989
- )
3990
- SELECT node_id, MIN(depth) AS depth
3991
- FROM walk
3992
- GROUP BY node_id
3993
- ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
3994
- LIMIT ?
3995
- `;
3996
- const params = [
3997
- sourceId,
3998
- entityId,
3999
- entityId,
4000
- opts.direction,
4001
- opts.direction,
4002
- ...opts.edgeTypes ?? [],
4003
- entityId,
4004
- minConfidenceRank,
4005
- ...opts.excludeSourceTypes,
4006
- opts.excludeDrafts === true ? 1 : 0,
4007
- opts.live.t,
4008
- opts.live.t,
4009
- opts.maxDepth,
4010
- opts.maxNodes
4011
- ];
4012
- const rows = await executor.getAllAsync(sql, params);
4013
- const nodeIds = rows.map((r) => r.node_id);
4014
- if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
4015
- const valueRows = nodeIds.map(() => "(?)").join(", ");
4016
- const edgeRows = await executor.getAllAsync(
4017
- `WITH neighborhood(node_id) AS (VALUES ${valueRows})
4018
- SELECT e.* FROM ${this.prefix}edges e
4019
- JOIN neighborhood ns ON e.source_id = ns.node_id
4020
- JOIN neighborhood nt ON e.target_id = nt.node_id
4021
- WHERE e.entity_id = ?`,
4022
- [...nodeIds, entityId]
4023
- );
4024
- return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4025
- }
4026
- };
4027
- function mapRowToEdge(row) {
4028
- return {
4029
- id: String(row.id),
4030
- entity_id: String(row.entity_id),
4031
- source_id: String(row.source_id),
4032
- target_id: String(row.target_id),
4033
- edge_type: String(row.edge_type),
4034
- created_at: Number(row.created_at)
4035
- };
4036
- }
4037
-
4038
- // src/repositories/MetadataRepository.ts
4039
- function entitySummaryMetaKey(entityId) {
4040
- return `entity_summary:${entityId}`;
4041
- }
4042
- var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
4043
- var MetadataRepository = class extends BaseRepository {
4044
- // CHECKPOINTS TABLE METHODS
4045
- async getCheckpoint(entityId, tx) {
4046
- const executor = this.getExecutor(tx);
4047
- const row = await executor.getFirstAsync(
4048
- `SELECT memory_checkpoint, heal_checkpoint FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
4049
- [entityId]
4050
- );
4051
- if (!row) return {};
4052
- return {
4053
- memory: row.memory_checkpoint ?? void 0,
4054
- heal: row.heal_checkpoint ?? void 0
4055
- };
4056
- }
4057
- async updateCheckpoint(entityId, updates, tx) {
4058
- const fields = [];
4059
- const values = [];
4060
- if (updates.memory !== void 0) {
4061
- fields.push("memory_checkpoint = ?");
4062
- values.push(updates.memory);
4063
- }
4064
- if (updates.heal !== void 0) {
4065
- fields.push("heal_checkpoint = ?");
4066
- values.push(updates.heal);
4067
- }
4068
- if (fields.length === 0) return;
4069
- const executor = this.getExecutor(tx);
4070
- await executor.runAsync(
4071
- `INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint)
4072
- VALUES (?, ?, ?)
4073
- ON CONFLICT(entity_id) DO UPDATE SET ${fields.join(", ")}`,
4074
- [entityId, updates.memory ?? 0, updates.heal ?? 0, ...values]
4075
- );
4076
- }
4077
- async deleteCheckpoint(entityId, tx) {
4078
- const executor = this.getExecutor(tx);
4079
- await executor.runAsync(
4080
- `DELETE FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
4081
- [entityId]
4082
- );
4083
- }
4084
- /**
4085
- * Read the op-based librarian's high-water mark. Returns `null` when the
4086
- * entity has never had its watermark set.
4087
- */
4088
- async getLibrarianWatermark(entityId, tx) {
4089
- const executor = this.getExecutor(tx);
4090
- const row = await executor.getFirstAsync(
4091
- `SELECT librarian_watermark_at, librarian_watermark_id FROM ${this.prefix}checkpoints WHERE entity_id = ?`,
4092
- [entityId]
4093
- );
4094
- if (!row || row.librarian_watermark_at == null || row.librarian_watermark_id == null) {
4095
- return null;
4096
- }
4097
- return { at: row.librarian_watermark_at, id: row.librarian_watermark_id };
4098
- }
4099
- /**
4100
- * Write the op-based librarian's high-water mark. Uses `ON CONFLICT`
4101
- * `DO UPDATE` so existing `memory_checkpoint` / `heal_checkpoint` rows
4102
- * are preserved verbatim.
4103
- */
4104
- async setLibrarianWatermark(entityId, wm, tx) {
4105
- const executor = this.getExecutor(tx);
4106
- await executor.runAsync(
4107
- `INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint, heal_checkpoint, librarian_watermark_at, librarian_watermark_id)
4108
- VALUES (?, 0, 0, ?, ?)
4109
- ON CONFLICT(entity_id) DO UPDATE SET
4110
- librarian_watermark_at = excluded.librarian_watermark_at,
4111
- librarian_watermark_id = excluded.librarian_watermark_id`,
4112
- [entityId, wm.at, wm.id]
4113
- );
4114
- }
4115
- // META TABLE METHODS
4116
- async getMeta(key, tx) {
4117
- const executor = this.getExecutor(tx);
4118
- const row = await executor.getFirstAsync(
4119
- `SELECT value FROM ${this.prefix}meta WHERE key = ?`,
4120
- [key]
4121
- );
4122
- return row ? row.value : null;
4123
- }
4124
- async setMeta(key, value, tx) {
4125
- const executor = this.getExecutor(tx);
4126
- await executor.runAsync(
4127
- `INSERT INTO ${this.prefix}meta (key, value) VALUES (?, ?)
4128
- ON CONFLICT(key) DO UPDATE SET value = excluded.value`,
4129
- [key, value]
4130
- );
4131
- }
4132
- async deleteMeta(key, tx) {
4133
- const executor = this.getExecutor(tx);
4134
- await executor.runAsync(
4135
- `DELETE FROM ${this.prefix}meta WHERE key = ?`,
4136
- [key]
4137
- );
4138
- }
4139
- async clearDimensionMismatch(tx) {
4140
- const executor = this.getExecutor(tx);
4141
- await executor.runAsync(
4142
- `DELETE FROM ${this.prefix}meta WHERE key = 'embedding_dimension_mismatch'`
4143
- );
4144
- }
4145
- async tableExists(tableName, tx) {
4146
- const executor = this.getExecutor(tx);
4147
- const row = await executor.getFirstAsync(
4148
- `SELECT name FROM sqlite_master WHERE type='table' AND name=?`,
4149
- [tableName]
4150
- );
4151
- return row != null;
4152
- }
4153
- async getTableDdl(tableName, tx) {
4154
- const executor = this.getExecutor(tx);
4155
- const row = await executor.getFirstAsync(
4156
- `SELECT sql FROM sqlite_master WHERE type='table' AND name=?`,
4157
- [tableName]
4158
- );
4159
- return row?.sql ?? null;
4160
- }
4161
- async vacuum() {
4162
- await this.db.execAsync(`PRAGMA wal_checkpoint(TRUNCATE)`);
4163
- await this.db.execAsync(`VACUUM`);
4164
- }
4165
- /**
4166
- * Returns the set of distinct `entity_id` values across entries/tasks/events.
4167
- *
4168
- * Deliberately widened from a prior `WHERE deleted_at IS NULL` form: the
4169
- * returned set intentionally includes entities whose only rows are
4170
- * soft-deleted, so the host's maintenance sweep can visit such
4171
- * "decommissioned-scope" namespaces and reap the soft-deleted rows. Sorting
4172
- * is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
4173
- */
4174
- async getDistinctEntityIds(tx) {
4175
- const executor = this.getExecutor(tx);
4176
- const rows = await executor.getAllAsync(
4177
- `SELECT DISTINCT entity_id FROM (
4178
- SELECT entity_id FROM ${this.prefix}entries
4179
- UNION
4180
- SELECT entity_id FROM ${this.prefix}tasks
4181
- UNION
4182
- SELECT entity_id FROM ${this.prefix}events
4183
- ) ORDER BY entity_id COLLATE BINARY`
4184
- );
4185
- return rows.map((r) => r.entity_id);
4377
+ await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);
4186
4378
  }
4187
- async getManifest(entityId, tx) {
4379
+ /**
4380
+ * Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to
4381
+ * `entityId`. Returns the number of rows deleted. Edges have no soft-delete
4382
+ * concept; this method is named `softDeleteBySourceFactIds` for symmetry with
4383
+ * `EntryRepository.softDeleteBySource` (which IS a soft delete), but its
4384
+ * semantics are immediate presence/absence removal. Use ONLY inside an open
4385
+ * transaction — the method requires `tx` and performs no autocommit.
4386
+ *
4387
+ * Used by `IngestionService.upsertGraphCore` to retire the prior parse's
4388
+ * edges whose source facts are being superseded by `softDeleteBySource`.
4389
+ */
4390
+ async softDeleteBySourceFactIds(entityId, sourceFactIds, tx) {
4391
+ if (sourceFactIds.length === 0) return 0;
4188
4392
  const executor = this.getExecutor(tx);
4189
- const row = await executor.getFirstAsync(`SELECT mode, manifest_json FROM ${this.prefix}entity_manifests WHERE entity_id = ?`, [entityId]);
4190
- if (!row) return null;
4191
- if (row.mode !== "off" && row.mode !== "strict" && row.mode !== "emergent") {
4192
- throw new Error(`Invalid ontology mode for entity ${entityId}: ${JSON.stringify(row.mode)}`);
4193
- }
4194
- let manifest;
4195
- try {
4196
- manifest = JSON.parse(row.manifest_json);
4197
- } catch (error) {
4198
- throw new Error(`Invalid manifest_json for entity ${entityId}: ${error.message}`);
4393
+ const chunkSize = 500;
4394
+ let totalChanges = 0;
4395
+ for (let i = 0; i < sourceFactIds.length; i += chunkSize) {
4396
+ const chunk = sourceFactIds.slice(i, i + chunkSize);
4397
+ const placeholders = chunk.map(() => "?").join(",");
4398
+ const result = await executor.runAsync(
4399
+ `DELETE FROM ${this.prefix}edges
4400
+ WHERE entity_id = ? AND source_id IN (${placeholders})`,
4401
+ [entityId, ...chunk]
4402
+ );
4403
+ totalChanges += result.changes;
4199
4404
  }
4200
- validateManifest(manifest);
4201
- return {
4202
- mode: row.mode,
4203
- manifest
4204
- };
4405
+ return totalChanges;
4205
4406
  }
4206
4407
  /**
4207
- * Write an entity's manifest.
4208
- *
4209
- * `opts.ifAbsent` selects the conflict behaviour:
4210
- * - omitted / `false` — upsert. An existing row is replaced.
4211
- * - `true` — create-if-absent. An existing row is left exactly as it is.
4212
- *
4213
- * Returns whether this call actually wrote a row. Under `ifAbsent` a `false`
4214
- * result means another writer got there first; the check and the write are one
4215
- * statement, so there is no window between them.
4408
+ * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
4409
+ * dead-ending, cycle-guarding, capping, and ordering happens in this one query.
4410
+ * The anchor is validated (exists, right entity, not soft-deleted) but never gated
4411
+ * by confidence/source_type — only nodes discovered beyond it are.
4216
4412
  */
4217
- async setManifest(entityId, data, tx, opts) {
4218
- validateManifest(data.manifest);
4413
+ async getNeighborhood(entityId, sourceId, opts, tx) {
4219
4414
  const executor = this.getExecutor(tx);
4220
- const conflictClause = opts?.ifAbsent ? "ON CONFLICT(entity_id) DO NOTHING" : `ON CONFLICT(entity_id) DO UPDATE SET
4221
- mode = excluded.mode, manifest_json = excluded.manifest_json, updated_at = excluded.updated_at`;
4222
- const result = await executor.runAsync(
4223
- `INSERT INTO ${this.prefix}entity_manifests (entity_id, mode, manifest_json, updated_at)
4224
- VALUES (?, ?, ?, ?)
4225
- ${conflictClause}`,
4226
- [entityId, data.mode, JSON.stringify(data.manifest), Date.now()]
4415
+ if (opts.edgeTypes && opts.edgeTypes.length === 0) {
4416
+ const anchor = await executor.getFirstAsync(
4417
+ `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
4418
+ [sourceId, entityId]
4419
+ );
4420
+ return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
4421
+ }
4422
+ const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
4423
+ const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
4424
+ const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
4425
+ const sql = `
4426
+ WITH RECURSIVE walk(node_id, depth, visited) AS (
4427
+ SELECT id, 0, ',' || id || ','
4428
+ FROM ${this.prefix}entries
4429
+ WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
4430
+
4431
+ UNION
4432
+
4433
+ SELECT
4434
+ CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
4435
+ w.depth + 1,
4436
+ w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
4437
+ FROM walk w
4438
+ JOIN ${this.prefix}edges e
4439
+ ON e.entity_id = ?
4440
+ AND (
4441
+ (? != 'inbound' AND e.source_id = w.node_id) OR
4442
+ (? != 'outbound' AND e.target_id = w.node_id)
4443
+ )
4444
+ AND (${edgeTypesClause})
4445
+ JOIN ${this.prefix}entries n
4446
+ ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
4447
+ AND n.entity_id = ?
4448
+ AND n.deleted_at IS NULL
4449
+ AND (
4450
+ CASE n.confidence
4451
+ WHEN 'tentative' THEN 0
4452
+ WHEN 'inferred' THEN 1
4453
+ WHEN 'certain' THEN 2
4454
+ ELSE -1
4455
+ END
4456
+ ) >= ?
4457
+ AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
4458
+ AND (? = 0 OR n.lifecycle_status != 'draft')
4459
+ AND ${liveAtSql(opts.live.mode, "n.")}
4460
+ WHERE w.depth < ?
4461
+ AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
4462
+ )
4463
+ SELECT node_id, MIN(depth) AS depth
4464
+ FROM walk
4465
+ GROUP BY node_id
4466
+ ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
4467
+ LIMIT ?
4468
+ `;
4469
+ const params = [
4470
+ sourceId,
4471
+ entityId,
4472
+ entityId,
4473
+ opts.direction,
4474
+ opts.direction,
4475
+ ...opts.edgeTypes ?? [],
4476
+ entityId,
4477
+ minConfidenceRank,
4478
+ ...opts.excludeSourceTypes,
4479
+ opts.excludeDrafts === true ? 1 : 0,
4480
+ opts.live.t,
4481
+ opts.live.t,
4482
+ opts.maxDepth,
4483
+ opts.maxNodes
4484
+ ];
4485
+ const rows = await executor.getAllAsync(sql, params);
4486
+ const nodeIds = rows.map((r) => r.node_id);
4487
+ if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
4488
+ const valueRows = nodeIds.map(() => "(?)").join(", ");
4489
+ const edgeRows = await executor.getAllAsync(
4490
+ `WITH neighborhood(node_id) AS (VALUES ${valueRows})
4491
+ SELECT e.* FROM ${this.prefix}edges e
4492
+ JOIN neighborhood ns ON e.source_id = ns.node_id
4493
+ JOIN neighborhood nt ON e.target_id = nt.node_id
4494
+ WHERE e.entity_id = ?`,
4495
+ [...nodeIds, entityId]
4227
4496
  );
4228
- return result.changes > 0;
4229
- }
4230
- async mergeManifestUpdates(entityId, updates, tx) {
4231
- const current = await this.getManifest(entityId, tx) ?? {
4232
- mode: "emergent",
4233
- manifest: emptyManifest()
4234
- };
4235
- const merged = mergeOntologyUpdates(current.manifest, updates);
4236
- await this.setManifest(entityId, { mode: current.mode, manifest: merged }, tx);
4237
- return merged;
4497
+ return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
4238
4498
  }
4239
4499
  };
4500
+ function mapRowToEdge(row) {
4501
+ return {
4502
+ id: String(row.id),
4503
+ entity_id: String(row.entity_id),
4504
+ source_id: String(row.source_id),
4505
+ target_id: String(row.target_id),
4506
+ edge_type: String(row.edge_type),
4507
+ created_at: Number(row.created_at)
4508
+ };
4509
+ }
4240
4510
 
4241
4511
  // src/services/legacyWatermark.ts
4242
4512
  async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
@@ -5788,143 +6058,55 @@ function validateOp(raw, aliases) {
5788
6058
  if (typeof r.title === "string" && r.title.trim() !== "") update.title = clip(r.title, 80);
5789
6059
  if (typeof r.body === "string" && r.body.trim() !== "") update.body = clip(r.body, 800);
5790
6060
  return update;
5791
- }
5792
- var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
5793
- async function runResolve(deps, ctx, ambiguous) {
5794
- const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [] };
5795
- if (ambiguous.length === 0) return out;
5796
- const { entityId, trigger } = ctx;
5797
- const outcome = await runBatched({
5798
- items: ambiguous,
5799
- buildPrompt: (batch) => deps.promptService.buildOpsResolvePrompt(
5800
- batch.map((g, i) => ({
5801
- item: i,
5802
- candidate: { title: g.candidate.fact.title, body: g.candidate.fact.body },
5803
- existing: g.neighbours.map((n) => ({
5804
- ref: n.ref,
5805
- title: n.title,
5806
- body: safeSlice(n.body, 0, OPS_NEIGHBOUR_BODY_CHARS)
5807
- }))
5808
- }))
5809
- ),
5810
- call: (prompts) => callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompts),
5811
- parse: (text, batch) => {
5812
- const parsed = parseJsonResponse(text);
5813
- if (!Array.isArray(parsed.ops)) throw new Error("resolve: ops missing");
5814
- return { batch, ops: parsed.ops };
5815
- },
5816
- maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
5817
- maxOutputTokens: deps.options.llmProvider.maxOutputTokens
5818
- });
5819
- if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
5820
- for (const { batch, ops } of outcome.results) {
5821
- const byItem = /* @__PURE__ */ new Map();
5822
- for (const raw of ops) {
5823
- const item = raw?.item;
5824
- if (typeof item === "number" && Number.isInteger(item) && item >= 0 && item < batch.length && !byItem.has(item)) {
5825
- byItem.set(item, raw);
5826
- }
5827
- }
5828
- batch.forEach((g, i) => {
5829
- const op = validateOp(byItem.get(i), aliasMapOf(g));
5830
- if (op) out.ops.set(g, op);
5831
- else out.rejected.push(g);
5832
- });
5833
- }
5834
- if (outcome.skipped.some((s) => s.reason === "call_error")) {
5835
- throw new Error("resolve: transient provider error; retry the pass");
5836
- }
5837
- for (const s of outcome.skipped) out.failed.push(s.item);
5838
- return out;
5839
- }
5840
-
5841
- // src/services/TemporalService.ts
5842
- var HISTORY_MAX_DEPTH = 100;
5843
- var TemporalService = class {
5844
- constructor(db, options, entryRepo, searchService, embeddingService) {
5845
- this.db = db;
5846
- this.options = options;
5847
- this.entryRepo = entryRepo;
5848
- this.searchService = searchService;
5849
- this.embeddingService = embeddingService;
5850
- }
5851
- /**
5852
- * Link `oldId` → `newId` inside the caller's transaction. `newId` must
5853
- * already exist. Throws WikiSupersedeError on any rule violation; the
5854
- * caller's transaction then rolls back.
5855
- */
5856
- async supersedeInTx(tx, entityId, oldId, newId, t, now) {
5857
- const old = await this.entryRepo.findTemporalRow(oldId, tx);
5858
- if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
5859
- if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
5860
- if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
5861
- if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
5862
- if (newId === oldId) throw new WikiSupersedeError("cycle");
5863
- const repl = await this.entryRepo.findTemporalRow(newId, tx);
5864
- if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
5865
- if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
5866
- if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
5867
- const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
5868
- if (predecessors.includes(newId)) throw new WikiSupersedeError("cycle");
5869
- await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
5870
- if (repl.valid_from == null) {
5871
- await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
5872
- }
5873
- }
5874
- async supersede(entityId, oldId, replacement, options) {
5875
- const now = Date.now();
5876
- const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
5877
- let created = null;
5878
- if (typeof replacement !== "string") {
5879
- if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
5880
- throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
6061
+ }
6062
+ var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
6063
+ async function runResolve(deps, ctx, ambiguous) {
6064
+ const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [] };
6065
+ if (ambiguous.length === 0) return out;
6066
+ const { entityId, trigger } = ctx;
6067
+ const outcome = await runBatched({
6068
+ items: ambiguous,
6069
+ buildPrompt: (batch) => deps.promptService.buildOpsResolvePrompt(
6070
+ batch.map((g, i) => ({
6071
+ item: i,
6072
+ candidate: { title: g.candidate.fact.title, body: g.candidate.fact.body },
6073
+ existing: g.neighbours.map((n) => ({
6074
+ ref: n.ref,
6075
+ title: n.title,
6076
+ body: safeSlice(n.body, 0, OPS_NEIGHBOUR_BODY_CHARS)
6077
+ }))
6078
+ }))
6079
+ ),
6080
+ call: (prompts) => callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompts),
6081
+ parse: (text, batch) => {
6082
+ const parsed = parseJsonResponse(text);
6083
+ if (!Array.isArray(parsed.ops)) throw new Error("resolve: ops missing");
6084
+ return { batch, ops: parsed.ops };
6085
+ },
6086
+ maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
6087
+ maxOutputTokens: deps.options.llmProvider.maxOutputTokens
6088
+ });
6089
+ if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
6090
+ for (const { batch, ops } of outcome.results) {
6091
+ const byItem = /* @__PURE__ */ new Map();
6092
+ for (const raw of ops) {
6093
+ const item = raw?.item;
6094
+ if (typeof item === "number" && Number.isInteger(item) && item >= 0 && item < batch.length && !byItem.has(item)) {
6095
+ byItem.set(item, raw);
5881
6096
  }
5882
- created = {
5883
- id: generateId("fact_"),
5884
- entity_id: entityId,
5885
- title: replacement.title,
5886
- body: replacement.body,
5887
- tags: Array.isArray(replacement.tags) ? replacement.tags : [],
5888
- confidence: replacement.confidence ?? "certain",
5889
- source_type: replacement.source_type ?? "user_stated",
5890
- source_hash: null,
5891
- source_ref: null,
5892
- created_at: now,
5893
- updated_at: now,
5894
- last_accessed_at: null,
5895
- access_count: 0,
5896
- deleted_at: null
5897
- };
5898
6097
  }
5899
- const newId = typeof replacement === "string" ? replacement : created.id;
5900
- const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
5901
- await this.db.withTransactionAsync(async (tx) => {
5902
- if (created) {
5903
- await this.entryRepo.upsert(created, tx);
5904
- if (newValidFrom !== void 0) {
5905
- await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
5906
- }
5907
- }
5908
- await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
6098
+ batch.forEach((g, i) => {
6099
+ const op = validateOp(byItem.get(i), aliasMapOf(g));
6100
+ if (op) out.ops.set(g, op);
6101
+ else out.rejected.push(g);
5909
6102
  });
5910
- await this.searchService.syncEntries(entityId, [oldId, newId]);
5911
- if (created) {
5912
- await this.embeddingService.embedFact(
5913
- { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
5914
- { operation: "supersede", trigger: "call" }
5915
- );
5916
- }
5917
- this.searchService.evictCache(entityId);
5918
- return { newId };
5919
6103
  }
5920
- async history(entityId, factId) {
5921
- const start = await this.entryRepo.findTemporalRow(factId);
5922
- if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
5923
- const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
5924
- const facts = await this.entryRepo.findByIds([...predecessors, factId, ...successors], [entityId]);
5925
- 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));
6104
+ if (outcome.skipped.some((s) => s.reason === "call_error")) {
6105
+ throw new Error("resolve: transient provider error; retry the pass");
5926
6106
  }
5927
- };
6107
+ for (const s of outcome.skipped) out.failed.push(s.item);
6108
+ return out;
6109
+ }
5928
6110
 
5929
6111
  // src/services/librarian/ops/apply.ts
5930
6112
  function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
@@ -6191,6 +6373,7 @@ async function runLibrarianStrategy(deps, ctx) {
6191
6373
  }
6192
6374
 
6193
6375
  // src/services/MaintenanceService.ts
6376
+ 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.`;
6194
6377
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
6195
6378
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
6196
6379
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -6239,7 +6422,21 @@ var formatSkipError = (err) => {
6239
6422
  }
6240
6423
  return base;
6241
6424
  };
6242
- var MaintenanceService = class {
6425
+ function eraseRuntime() {
6426
+ const g = globalThis;
6427
+ if (g.process?.versions?.node) return `node ${g.process.versions.node}`;
6428
+ return g.HermesInternal ? "hermes" : "unknown";
6429
+ }
6430
+ var EraseStepError = class extends Error {
6431
+ constructor(code, message, report, cause) {
6432
+ super(message);
6433
+ this.code = code;
6434
+ this.report = report;
6435
+ this.name = "EraseStepError";
6436
+ if (cause !== void 0) this.cause = cause;
6437
+ }
6438
+ };
6439
+ var _MaintenanceService = class _MaintenanceService {
6243
6440
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
6244
6441
  this.db = db;
6245
6442
  this.prefix = prefix;
@@ -6259,7 +6456,15 @@ var MaintenanceService = class {
6259
6456
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
6260
6457
  }
6261
6458
  async runPrune(entityId, options) {
6262
- this.jobManager.acquireLock("prune", entityId);
6459
+ return this._runPrune(entityId, options, "host");
6460
+ }
6461
+ /**
6462
+ * Shared prune body. `owner: 'erase'` lets erase()'s own per-entity prune
6463
+ * through the universal erase fence in JobManager; the public `runPrune`
6464
+ * always passes `'host'`.
6465
+ */
6466
+ async _runPrune(entityId, options, owner) {
6467
+ this.jobManager.acquireLock("prune", entityId, void 0, owner);
6263
6468
  try {
6264
6469
  const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
6265
6470
  const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
@@ -6290,8 +6495,9 @@ var MaintenanceService = class {
6290
6495
  }
6291
6496
  }
6292
6497
  if (retainSoftDeletedFor !== null) {
6293
- const cutoff = now - retainSoftDeletedFor * 864e5;
6294
- const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
6498
+ const softDeletedAll = options?.softDeletedCutoff === "all";
6499
+ const cutoff = softDeletedAll ? 0 : options?.softDeletedCutoff ?? now - retainSoftDeletedFor * 864e5;
6500
+ const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff, void 0, { noCutoff: softDeletedAll });
6295
6501
  const prunableIds = entriesToDelete.map((r) => r.id);
6296
6502
  const vr = this.vectorRemoval;
6297
6503
  const vrRepo = this.vectorRemovalRepo;
@@ -6337,7 +6543,7 @@ var MaintenanceService = class {
6337
6543
  }
6338
6544
  if (deletable.length > 0) {
6339
6545
  const deletedIds = [];
6340
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
6546
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds, noCutoff: softDeletedAll });
6341
6547
  if (hookLedger) {
6342
6548
  const gone = new Set(deletedIds);
6343
6549
  const skipped = deletable.filter((id) => !gone.has(id));
@@ -6352,7 +6558,7 @@ var MaintenanceService = class {
6352
6558
  else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
6353
6559
  }
6354
6560
  }
6355
- deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
6561
+ deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
6356
6562
  });
6357
6563
  if (hookLedger) {
6358
6564
  const keptSet = new Set(kept);
@@ -6397,12 +6603,20 @@ var MaintenanceService = class {
6397
6603
  }
6398
6604
  }
6399
6605
  }
6606
+ let vacuumCheckpointErr;
6400
6607
  if (vacuum) {
6401
- await resetNormalizeWatermarks(this.metadataRepo);
6402
- await this.metadataRepo.vacuum();
6403
- await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
6608
+ try {
6609
+ await this._wrappedVacuum();
6610
+ } catch (err) {
6611
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
6612
+ vacuumCheckpointErr = err;
6613
+ }
6404
6614
  }
6615
+ if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
6405
6616
  await this.searchService.syncEntries(entityId, syncedIds);
6617
+ if (prunePartial && vacuumCheckpointErr) {
6618
+ emitDiagnostic(this.options, { code: "prune_checkpoint_incomplete", operation: "prune", trigger: "call", entityId, detail: { reason: vacuumCheckpointErr.message } });
6619
+ }
6406
6620
  if (prunePartial) {
6407
6621
  throw new PrunePartialFailureError(
6408
6622
  deletedEntries,
@@ -6413,11 +6627,422 @@ var MaintenanceService = class {
6413
6627
  deletedEvents
6414
6628
  );
6415
6629
  }
6630
+ if (vacuumCheckpointErr) throw vacuumCheckpointErr;
6416
6631
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
6417
6632
  } finally {
6418
6633
  this.jobManager.releaseLock("prune", entityId);
6419
6634
  }
6420
6635
  }
6636
+ /** Shared by runPrune and erase step 5. */
6637
+ async _wrappedVacuum() {
6638
+ await resetNormalizeWatermarks(this.metadataRepo);
6639
+ let checkpointErr;
6640
+ try {
6641
+ await this.metadataRepo.vacuum();
6642
+ } catch (err) {
6643
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
6644
+ checkpointErr = err;
6645
+ }
6646
+ await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
6647
+ if (checkpointErr) throw checkpointErr;
6648
+ }
6649
+ /**
6650
+ * Erase core (forget-erasure spec §2, steps 0 / 1 / 1b). Thin entry: T6
6651
+ * completes the pipeline (FTS, VACUUM, checkpoint, sync). Never reports a
6652
+ * success it cannot verify: a failed step throws {@link EraseStepError}
6653
+ * carrying the partial report with `verified: false`.
6654
+ */
6655
+ async erase(opts) {
6656
+ const rebuild = opts?.rebuild === true;
6657
+ this.jobManager.acquireLock("erase", "*");
6658
+ const report = {
6659
+ verified: false,
6660
+ secureDelete: null,
6661
+ sqliteVersion: "",
6662
+ entities: [],
6663
+ holds: [],
6664
+ skipped: [],
6665
+ syncedIds: [],
6666
+ registrySweep: { skipped: false, deleted: 0 },
6667
+ retiredUndroppable: [],
6668
+ ftsOrphansCleared: [],
6669
+ failedStep: null,
6670
+ runtime: eraseRuntime(),
6671
+ steps: []
6672
+ };
6673
+ const ok = (step, outcome = "ok") => {
6674
+ report.steps.push({ step, outcome });
6675
+ };
6676
+ try {
6677
+ const readPragma = async () => (await this.db.getFirstAsync("PRAGMA secure_delete"))?.secure_delete ?? null;
6678
+ let pragma;
6679
+ try {
6680
+ pragma = await readPragma();
6681
+ if (pragma !== 1) {
6682
+ await this.db.execAsync("PRAGMA secure_delete=ON");
6683
+ pragma = await readPragma();
6684
+ }
6685
+ report.secureDelete = pragma;
6686
+ report.sqliteVersion = (await this.db.getFirstAsync("SELECT sqlite_version() AS v"))?.v ?? "";
6687
+ } catch (err) {
6688
+ report.failedStep = "secure_delete";
6689
+ throw new EraseStepError("erase_secure_delete_read_failed", "erase stopped at step 0: secure_delete pragma read failed; erasure is unverified", report, err);
6690
+ }
6691
+ if (pragma !== 1) {
6692
+ emitDiagnostic(this.options, { code: "erase_secure_delete_off", operation: "erase", trigger: "call", entityId: "" });
6693
+ report.failedStep = "secure_delete";
6694
+ throw new EraseStepError("erase_secure_delete_off", "erase stopped at step 0: secure_delete is not ON; erasure is unverified", report);
6695
+ }
6696
+ ok("secure_delete");
6697
+ try {
6698
+ report.entities = await this.metadataRepo.getDistinctEntityIds(void 0, { softDeletedAll: true });
6699
+ } catch (err) {
6700
+ report.failedStep = "prune";
6701
+ throw new EraseStepError("erase_prune_failed", "erase stopped at step 1: the entity walk failed; erasure is unverified", report, err);
6702
+ }
6703
+ const syncedByEntity = /* @__PURE__ */ new Map();
6704
+ for (const entityId of report.entities) {
6705
+ const syncedIds = [];
6706
+ syncedByEntity.set(entityId, syncedIds);
6707
+ try {
6708
+ await this._runPrune(entityId, { retainSoftDeletedFor: 0, retainEventsFor: null, vacuum: false, syncedIds, softDeletedCutoff: "all" }, "erase");
6709
+ } catch (err) {
6710
+ if (err instanceof PrunePartialFailureError) {
6711
+ report.holds.push({ entityId, deleted: err.deleted, deletedTasks: err.deletedTasks, failedAt: err.failedAt, remaining: err.remaining });
6712
+ } else if (err instanceof WikiBusyError) {
6713
+ report.skipped.push(entityId);
6714
+ emitDiagnostic(this.options, { code: "erase_entity_skipped", operation: "erase", trigger: "call", entityId });
6715
+ } else {
6716
+ report.failedStep = "prune";
6717
+ throw new EraseStepError("erase_prune_failed", `erase stopped at step 1 (entity ${entityId})`, report, err);
6718
+ }
6719
+ }
6720
+ for (const id of syncedIds) report.syncedIds.push(id);
6721
+ }
6722
+ ok("prune", report.holds.length > 0 || report.skipped.length > 0 ? "partial" : "ok");
6723
+ try {
6724
+ await this.db.withTransactionAsync(async (tx) => {
6725
+ if (await this.sourceRefIndexPresent(tx)) {
6726
+ const r = await tx.runAsync(`DELETE FROM ${this.prefix}source_ref_index WHERE deleted_at IS NOT NULL`);
6727
+ report.registrySweep = { skipped: false, deleted: r.changes };
6728
+ } else {
6729
+ report.registrySweep = { skipped: true, deleted: 0 };
6730
+ }
6731
+ });
6732
+ } catch (err) {
6733
+ report.failedStep = "registry_sweep";
6734
+ throw new EraseStepError("erase_registry_sweep_failed", "erase stopped at step 1b", report, err);
6735
+ }
6736
+ if (report.registrySweep.skipped) {
6737
+ emitDiagnostic(this.options, { code: "erase_registry_sweep_skipped", operation: "erase", trigger: "call", entityId: "" });
6738
+ }
6739
+ ok("registry_sweep", report.registrySweep.skipped ? "partial" : "ok");
6740
+ await this._eraseDrainPassages(report);
6741
+ ok("passage_drain");
6742
+ await this._eraseReclaimRetired(report);
6743
+ ok("retired_reclaim");
6744
+ try {
6745
+ await this._wrappedVacuum();
6746
+ } catch (err) {
6747
+ if (err instanceof CheckpointIncompleteError) {
6748
+ report.failedStep = "checkpoint";
6749
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 5: WAL checkpoint incomplete; erasure is unverified", report, err);
6750
+ }
6751
+ report.failedStep = "vacuum";
6752
+ 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);
6753
+ }
6754
+ ok("vacuum");
6755
+ const byEntity = /* @__PURE__ */ new Map();
6756
+ for (const e of report.entities) byEntity.set(e, []);
6757
+ for (const [entityId, ids] of syncedByEntity) byEntity.set(entityId, ids);
6758
+ for (const [entityId, ids] of byEntity) {
6759
+ if (ids.length > 0) await this._eraseSyncEntries(entityId, ids, report);
6760
+ }
6761
+ ok("index_sync");
6762
+ if (rebuild) {
6763
+ try {
6764
+ await this.searchService.rebuildSurfaced();
6765
+ } catch (err) {
6766
+ report.failedStep = "rebuild";
6767
+ throw new EraseStepError("erase_rebuild_failed", "erase stopped at step 7: FTS rebuild failed", report, err);
6768
+ }
6769
+ ok("rebuild");
6770
+ }
6771
+ await this._eraseReclaimRetired(report);
6772
+ let present;
6773
+ try {
6774
+ present = await this.db.getAllAsync(
6775
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%entries_fts_retired_%'`
6776
+ );
6777
+ } catch (err) {
6778
+ report.failedStep = "retired_reclaim";
6779
+ emitDiagnostic(this.options, { code: "erase_retired_read_failed", operation: "erase", trigger: "call", entityId: "" });
6780
+ throw new EraseStepError("erase_retired_read_failed", "erase stopped after step 6: the retired-table read failed; erasure is unverified", report, err);
6781
+ }
6782
+ const left = present.map((r) => r.name).filter((n) => isRetiredTableName(this.prefix, n) && !report.retiredUndroppable.includes(n));
6783
+ if (left.length > 0) {
6784
+ report.failedStep = "retired_reclaim";
6785
+ emitDiagnostic(this.options, { code: "erase_retired_remaining", operation: "erase", trigger: "call", entityId: "", detail: { tables: left } });
6786
+ throw new EraseStepError("erase_retired_remaining", `erase stopped after step 6: retired FTS tables remain (${left.join(", ")})`, report);
6787
+ }
6788
+ ok("retired_reclaim_rerun");
6789
+ await this._eraseOptimize(report);
6790
+ ok("optimize");
6791
+ try {
6792
+ await this.metadataRepo.checkpointTruncateVerified();
6793
+ } catch (err) {
6794
+ report.failedStep = "checkpoint";
6795
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 8: WAL checkpoint incomplete; erasure is unverified", report, err);
6796
+ }
6797
+ ok("checkpoint");
6798
+ if (report.skipped.length === 0 && report.holds.length === 0) {
6799
+ let remainingTombstones;
6800
+ try {
6801
+ const row = await this.db.getFirstAsync(
6802
+ `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
6803
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
6804
+ );
6805
+ remainingTombstones = row?.n ?? 0;
6806
+ } catch (err) {
6807
+ report.failedStep = "tombstone_gate";
6808
+ throw new EraseStepError("erase_tombstone_gate_failed", "erase stopped at step 9: could not count remaining tombstones; erasure is unverified", report, err);
6809
+ }
6810
+ if (remainingTombstones > 0) {
6811
+ emitDiagnostic(this.options, { code: "erase_tombstones_remaining", operation: "erase", trigger: "call", entityId: "", detail: { count: remainingTombstones } });
6812
+ report.failedStep = "tombstone_gate";
6813
+ throw new EraseStepError("erase_tombstones_remaining", `erase stopped at step 9: ${remainingTombstones} soft-deleted row(s) remain; erasure is unverified`, report);
6814
+ }
6815
+ ok("tombstone_gate");
6816
+ } else {
6817
+ report.steps.push({ step: "tombstone_gate", outcome: "partial" });
6818
+ }
6819
+ report.verified = report.skipped.length === 0 && report.holds.length === 0;
6820
+ return report;
6821
+ } catch (err) {
6822
+ if (err instanceof EraseStepError && err.report === report && report.failedStep) {
6823
+ report.steps.push({ step: report.failedStep, outcome: "failed" });
6824
+ report.verified = false;
6825
+ }
6826
+ throw err;
6827
+ } finally {
6828
+ this.jobManager.releaseLock("erase", "*");
6829
+ }
6830
+ }
6831
+ /**
6832
+ * Step 3 remediation (specs/erase-fts-remediation): on a runtime without
6833
+ * usable strict drains, clear orphaned FTS5 surfaces so erasure can
6834
+ * complete verified. Per surface: existence gate (vtab OR any shadow) →
6835
+ * strategy check → vtab probe → path body → companions → state write.
6836
+ * Dispatch order is D4; exact-name allowlist interpolation is D2.
6837
+ */
6838
+ async _eraseClearFtsOrphans(report) {
6839
+ const surfaces = [`${this.prefix}entries_fts`, `${this.prefix}source_passages_fts`];
6840
+ let remediationRequired = false;
6841
+ const pathBTargets = [];
6842
+ try {
6843
+ for (const surface of surfaces) {
6844
+ const vtabExists = await this.sourceTableExists(surface);
6845
+ const shadows = [];
6846
+ for (const sfx of _MaintenanceService.FTS_SHADOW_SUFFIXES) {
6847
+ const name = `${surface}${sfx}`;
6848
+ if (await this.sourceTableExists(name)) shadows.push(name);
6849
+ }
6850
+ if (!vtabExists && shadows.length === 0) continue;
6851
+ remediationRequired = true;
6852
+ if (this.searchService.isIndexUnavailable()) {
6853
+ report.failedStep = "index_sync";
6854
+ throw new EraseStepError("erase_fts_index_unavailable", "erase stopped at step 3: the index strategy is unavailable and orphaned FTS surfaces remain; erasure is unverified", report);
6855
+ }
6856
+ let moduleLess = false;
6857
+ if (vtabExists) {
6858
+ try {
6859
+ await this.db.getFirstAsync(`SELECT 1 AS x FROM ${surface} LIMIT 1`);
6860
+ } catch (err) {
6861
+ let absent = false;
6862
+ let cur = err;
6863
+ for (let depth = 0; depth < 3 && cur != null && !absent; depth++) {
6864
+ let msg = "";
6865
+ try {
6866
+ msg = String(cur.message ?? cur);
6867
+ } catch {
6868
+ break;
6869
+ }
6870
+ absent = /no such module/i.test(msg);
6871
+ try {
6872
+ cur = cur.cause;
6873
+ } catch {
6874
+ break;
6875
+ }
6876
+ }
6877
+ if (!absent) {
6878
+ report.failedStep = "index_sync";
6879
+ throw new EraseStepError("erase_fts_orphan_probe_failed", `erase stopped at step 3: could not classify orphaned vtab ${surface}`, report, err);
6880
+ }
6881
+ moduleLess = true;
6882
+ }
6883
+ }
6884
+ if (vtabExists && !moduleLess) {
6885
+ if (this.options.config?.indexStrategy !== "minisearch") {
6886
+ report.failedStep = "index_sync";
6887
+ throw new EraseStepError("erase_fts_index_unavailable", `erase stopped at step 3: ${surface} is live and queryable but MiniSearch is not the configured strategy; erasure is unverified`, report);
6888
+ }
6889
+ pathBTargets.push(surface);
6890
+ continue;
6891
+ }
6892
+ const cleared = [];
6893
+ for (const name of shadows) {
6894
+ if (name.endsWith("_config")) continue;
6895
+ const res = await this.db.runAsync(name.endsWith("_data") ? `DELETE FROM ${name} WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}`);
6896
+ if ((res?.changes ?? 0) > 0) cleared.push(name);
6897
+ }
6898
+ for (const name of cleared) {
6899
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
6900
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
6901
+ }
6902
+ }
6903
+ if (!remediationRequired) return;
6904
+ const tailCleared = [];
6905
+ await this.db.withTransactionAsync(async (tx) => {
6906
+ for (const companion of [`${this.prefix}fts_pending`, `${this.prefix}fts_map`, `${this.prefix}source_passages_fts_pending`, `${this.prefix}source_passages_fts_map`]) {
6907
+ if (await this.sourceTableExists(companion, tx)) {
6908
+ const res = await tx.runAsync(`DELETE FROM ${companion}`);
6909
+ if ((res?.changes ?? 0) > 0 && !tailCleared.includes(companion)) tailCleared.push(companion);
6910
+ }
6911
+ }
6912
+ for (const surface of pathBTargets) {
6913
+ await tx.execAsync(`DROP TABLE IF EXISTS ${surface}`);
6914
+ if (!tailCleared.includes(surface)) tailCleared.push(surface);
6915
+ }
6916
+ if (pathBTargets.length > 0) {
6917
+ const [ai, ad] = passageFtsTriggerNames(this.prefix);
6918
+ await tx.execAsync(fts5LedgerDropSql(this.prefix) + `
6919
+ DROP TRIGGER IF EXISTS ${ai};
6920
+ DROP TRIGGER IF EXISTS ${ad};`);
6921
+ }
6922
+ await this.metadataRepo.setMeta(FTS5_STATE_KEY, "detached", tx);
6923
+ });
6924
+ for (const name of tailCleared) {
6925
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
6926
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
6927
+ }
6928
+ report.steps.push({ step: "fts_orphan_clear", outcome: "ok" });
6929
+ } catch (err) {
6930
+ if (err instanceof EraseStepError) throw err;
6931
+ report.failedStep = "fts_orphan_clear";
6932
+ throw new EraseStepError("erase_fts_orphan_clear", "erase stopped at step 3: clearing an orphaned FTS surface failed; erasure is unverified", report, err);
6933
+ }
6934
+ }
6935
+ /**
6936
+ * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
6937
+ * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
6938
+ * N2 guard (probe lives here, strategy-agnostic): a strategy without the strict
6939
+ * drains (Unavailable / MiniSearch) cannot drain, so rows in either FTS ledger
6940
+ * mean text was never drained -> the step fails and erasure is unverified.
6941
+ * Absent or empty ledgers proceed.
6942
+ */
6943
+ async _eraseDrainPassages(report) {
6944
+ if (!this.searchService.hasStrictDrain()) {
6945
+ await this._eraseClearFtsOrphans(report);
6946
+ for (const [table, failedStep, code] of [
6947
+ [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
6948
+ [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
6949
+ ]) {
6950
+ let rows = false;
6951
+ try {
6952
+ rows = await this.sourceTableExists(table) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${table} LIMIT 1`) != null;
6953
+ } catch (err) {
6954
+ report.failedStep = failedStep;
6955
+ throw new EraseStepError(code, `erase stopped at step 3: could not probe ${table}`, report, err);
6956
+ }
6957
+ if (rows) {
6958
+ report.failedStep = failedStep;
6959
+ 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);
6960
+ }
6961
+ }
6962
+ }
6963
+ try {
6964
+ await this.searchService.drainEntriesLedgerSurfaced();
6965
+ } catch (err) {
6966
+ report.failedStep = "index_sync";
6967
+ throw new EraseStepError("erase_index_sync_failed", "erase stopped at step 3: entries ledger drain failed", report, err);
6968
+ }
6969
+ try {
6970
+ await this.searchService.drainPassagesSurfaced();
6971
+ } catch (err) {
6972
+ report.failedStep = "passage_drain";
6973
+ throw new EraseStepError("erase_passage_drain_failed", "erase stopped at step 3: passage drain failed", report, err);
6974
+ }
6975
+ }
6976
+ /**
6977
+ * Step 4 (and its re-run after step 6): reclaim retired FTS tables to
6978
+ * completion. A module-less runtime cannot DROP a virtual table, so each
6979
+ * retired table's shadow tables are emptied under the pragma and the name
6980
+ * stays listed; a later FTS5-capable open's step 4 completes the DROP.
6981
+ */
6982
+ async _eraseReclaimRetired(report) {
6983
+ if (this.searchService.canReclaimRetired()) {
6984
+ try {
6985
+ await this.searchService.reclaimRetiredSurfaced();
6986
+ return;
6987
+ } catch (err) {
6988
+ if (!/no such module/i.test(err instanceof Error ? err.message : String(err))) {
6989
+ report.failedStep = "retired_reclaim";
6990
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: retired FTS table reclaim failed", report, err);
6991
+ }
6992
+ }
6993
+ }
6994
+ try {
6995
+ for (const name of await this._retiredList()) {
6996
+ for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
6997
+ if (sfx === "_config") continue;
6998
+ if (await this.sourceTableExists(`${name}${sfx}`)) {
6999
+ await this.db.runAsync(sfx === "_data" ? `DELETE FROM ${name}_data WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}${sfx}`);
7000
+ }
7001
+ }
7002
+ if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
7003
+ emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
7004
+ }
7005
+ } catch (err) {
7006
+ report.failedStep = "retired_reclaim";
7007
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: module-less shadow-table clear failed", report, err);
7008
+ }
7009
+ }
7010
+ /** Retired list straight from metadata (same key Fts5IndexStrategy maintains), independent of the active strategy. */
7011
+ async _retiredList() {
7012
+ let raw;
7013
+ try {
7014
+ raw = JSON.parse(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY) ?? "[]");
7015
+ } catch {
7016
+ return [];
7017
+ }
7018
+ return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
7019
+ }
7020
+ sourceTableExists(name, tx) {
7021
+ return this.metadataRepo.tableExists(name, tx);
7022
+ }
7023
+ /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
7024
+ async _eraseSyncEntries(entityId, ids, report) {
7025
+ let ok = false;
7026
+ try {
7027
+ ok = await this.searchService.syncEntries(entityId, ids);
7028
+ } catch (err) {
7029
+ report.failedStep = "index_sync";
7030
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId})`, report, err);
7031
+ }
7032
+ if (!ok) {
7033
+ report.failedStep = "index_sync";
7034
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId}): ledger drain failed`, report);
7035
+ }
7036
+ }
7037
+ /** Step 7: FTS optimize on both FTS tables, after syncEntries. */
7038
+ async _eraseOptimize(report) {
7039
+ try {
7040
+ await this.searchService.optimizeSurfaced();
7041
+ } catch (err) {
7042
+ report.failedStep = "optimize";
7043
+ throw new EraseStepError("erase_optimize_failed", "erase stopped at step 7: FTS optimize failed", report, err);
7044
+ }
7045
+ }
6421
7046
  async runLibrarian(entityId, options) {
6422
7047
  this.jobManager.acquireLock("librarian", entityId);
6423
7048
  try {
@@ -6538,6 +7163,9 @@ var MaintenanceService = class {
6538
7163
  if (params.includeEvents && !params.clearAll) {
6539
7164
  throw new Error("forget() includeEvents requires clearAll: true");
6540
7165
  }
7166
+ if (params.includeChain && (params.entryId === void 0 || params.clearAll || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
7167
+ throw new Error("forget() includeChain composes only with entryId");
7168
+ }
6541
7169
  if (opts?.dryRun === true) {
6542
7170
  return this.forgetDryRun(entityId, params);
6543
7171
  }
@@ -6547,6 +7175,8 @@ var MaintenanceService = class {
6547
7175
  let deletedEntries = 0;
6548
7176
  let deletedTasks = 0;
6549
7177
  let deletedEvents = 0;
7178
+ let chainIds = [];
7179
+ let chainTruncated = false;
6550
7180
  const deletedEntryIds = [];
6551
7181
  const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
6552
7182
  await this.db.withTransactionAsync(async (tx) => {
@@ -6583,6 +7213,12 @@ var MaintenanceService = class {
6583
7213
  if (params.entryId) {
6584
7214
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
6585
7215
  if (entryId) deletedEntryIds.push(entryId);
7216
+ if (entryId && params.includeChain) {
7217
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, entryId, HISTORY_MAX_DEPTH, tx);
7218
+ chainIds = walk.ids.filter((id) => id !== entryId);
7219
+ chainTruncated = walk.truncated;
7220
+ for (const id of chainIds) deletedEntryIds.push(id);
7221
+ }
6586
7222
  }
6587
7223
  if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
6588
7224
  const docs = `${this.prefix}source_documents`;
@@ -6608,6 +7244,9 @@ var MaintenanceService = class {
6608
7244
  sourceRefIndexPromise ?? Promise.resolve(void 0)
6609
7245
  ]);
6610
7246
  if (entryResult) deletedEntries++;
7247
+ for (const id of chainIds) {
7248
+ if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
7249
+ }
6611
7250
  if (taskResult) deletedTasks++;
6612
7251
  deletedEntries += refResult;
6613
7252
  }
@@ -6661,7 +7300,17 @@ var MaintenanceService = class {
6661
7300
  });
6662
7301
  }
6663
7302
  }
6664
- if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
7303
+ if (!params.clearAll) {
7304
+ const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
7305
+ if (params.includeChain) {
7306
+ base.chainEntryIds = chainIds;
7307
+ if (chainTruncated) {
7308
+ base.truncated = true;
7309
+ base.notice = CHAIN_TRUNCATED_NOTICE;
7310
+ }
7311
+ }
7312
+ return base;
7313
+ }
6665
7314
  return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
6666
7315
  } finally {
6667
7316
  this.jobManager.releaseLock("forget", entityId);
@@ -6727,8 +7376,25 @@ var MaintenanceService = class {
6727
7376
  * (the spec keeps dry-run narrow).
6728
7377
  */
6729
7378
  async forgetDryRun(entityId, params) {
7379
+ if (params.entryId !== void 0 && params.includeChain && params.taskId === void 0) {
7380
+ const id = await this.entryRepo.findIdById(params.entryId, entityId);
7381
+ if (!id) return { deleted: { entries: 0, tasks: 0 }, chainEntryIds: [] };
7382
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, id, HISTORY_MAX_DEPTH);
7383
+ const chainEntryIds = walk.ids.filter((c) => c !== id);
7384
+ const all = [id, ...chainEntryIds];
7385
+ const live = await this.db.getFirstAsync(
7386
+ `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND id IN (${all.map(() => "?").join(",")})`,
7387
+ [entityId, ...all]
7388
+ );
7389
+ const out = { deleted: { entries: live?.n ?? 0, tasks: 0 }, chainEntryIds };
7390
+ if (walk.truncated) {
7391
+ out.truncated = true;
7392
+ out.notice = CHAIN_TRUNCATED_NOTICE;
7393
+ }
7394
+ return out;
7395
+ }
6730
7396
  if (params.entryId !== void 0 || params.taskId !== void 0) {
6731
- throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors; use sourceRef/sourceHash or clearAll");
7397
+ throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors (entryId is accepted only with includeChain); use sourceRef/sourceHash or clearAll");
6732
7398
  }
6733
7399
  if (params.clearAll) {
6734
7400
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
@@ -7447,6 +8113,9 @@ var MaintenanceService = class {
7447
8113
  return sanitizeRankerError(err, this.options.sanitizeRankerErrors);
7448
8114
  }
7449
8115
  };
8116
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
8117
+ _MaintenanceService.FTS_SHADOW_SUFFIXES = ["_content", "_data", "_idx", "_docsize", "_config"];
8118
+ var MaintenanceService = _MaintenanceService;
7450
8119
 
7451
8120
  // src/utils/passageCutter.ts
7452
8121
  var MAX_PASSAGE_UNITS = 12e3;
@@ -7931,7 +8600,8 @@ var ImportExportService = class {
7931
8600
  this.vectorRemoval = vectorRemoval;
7932
8601
  this.prefix = prefix;
7933
8602
  }
7934
- async exportDump(entityIds) {
8603
+ async exportDump(entityIds, opts) {
8604
+ const includeForgotten = opts?.includeForgotten === true;
7935
8605
  let ids;
7936
8606
  if (entityIds && entityIds.length > 0) {
7937
8607
  ids = Array.from(new Set(entityIds));
@@ -7952,7 +8622,7 @@ var ImportExportService = class {
7952
8622
  const batchResults = await Promise.all(
7953
8623
  batch.map(
7954
8624
  async (id) => {
7955
- const bundle = await this.getFullBundle(id, { includeBlobs: true });
8625
+ const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
7956
8626
  const storedSources = await this.exportStoredSources(id);
7957
8627
  return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
7958
8628
  }
@@ -8058,10 +8728,11 @@ var ImportExportService = class {
8058
8728
  }
8059
8729
  }
8060
8730
  async getFullBundle(entityId, opts) {
8731
+ const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
8061
8732
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
8062
8733
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
8063
- opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
8064
- this.taskRepo.findAllByEntityId(entityId),
8734
+ opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
8735
+ this.taskRepo.findAllByEntityId(entityId, void 0, incl),
8065
8736
  this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
8066
8737
  this.edgeRepo.getByEntityId(entityId),
8067
8738
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
@@ -8097,12 +8768,15 @@ var ImportExportService = class {
8097
8768
  const skippedSources = [];
8098
8769
  const refusalDiagnostics = [];
8099
8770
  const upsertedFactIds = /* @__PURE__ */ new Set();
8771
+ const liveEmbedFactIds = /* @__PURE__ */ new Set();
8100
8772
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
8101
8773
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
8102
8774
  const preservedBlobDims = /* @__PURE__ */ new Set();
8103
8775
  const softDeletedFactIds = [];
8776
+ const softDeletedTaskIds = [];
8104
8777
  const clippedTextByFactId = /* @__PURE__ */ new Map();
8105
8778
  let clampedEvents = 0;
8779
+ let tombstoneSkipped = 0;
8106
8780
  const restamped = { behind_watermark: 0, invalid: 0 };
8107
8781
  await this.db.withTransactionAsync(async (tx) => {
8108
8782
  if (!merge) {
@@ -8113,8 +8787,9 @@ var ImportExportService = class {
8113
8787
  tx,
8114
8788
  false
8115
8789
  );
8116
- softDeletedFactIds.push(...deletedLiveFactIds);
8790
+ for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
8117
8791
  await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
8792
+ for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
8118
8793
  await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
8119
8794
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
8120
8795
  await this.metadataRepo.deleteCheckpoint(entityId, tx);
@@ -8124,6 +8799,8 @@ var ImportExportService = class {
8124
8799
  } else if (!merge) {
8125
8800
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
8126
8801
  }
8802
+ const wipedByThisImport = new Set(softDeletedFactIds);
8803
+ const wipedTasksByThisImport = new Set(softDeletedTaskIds);
8127
8804
  const factIds = bundle.facts.map((fact) => fact.id);
8128
8805
  const existingFactsById = /* @__PURE__ */ new Map();
8129
8806
  const existingFacts = await this.entryRepo.findExistingMetadataByIds(
@@ -8199,11 +8876,16 @@ var ImportExportService = class {
8199
8876
  );
8200
8877
  continue;
8201
8878
  }
8202
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
8879
+ if (existing.deleted_at != null && fact.deleted_at == null && !wipedByThisImport.has(fact.id)) {
8880
+ tombstoneSkipped++;
8881
+ continue;
8882
+ }
8883
+ if (merge && safeUpdatedAt <= existing.updated_at && fact.deleted_at == null) continue;
8203
8884
  }
8204
8885
  const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
8205
8886
  const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
8206
- clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody });
8887
+ const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
8888
+ clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
8207
8889
  let normalizedSourceRef = null;
8208
8890
  if (fact.source_ref !== null && fact.source_ref !== void 0) {
8209
8891
  normalizedSourceRef = normalizeSourceRef(fact.source_ref);
@@ -8270,15 +8952,22 @@ var ImportExportService = class {
8270
8952
  }, tx, { outbox: false });
8271
8953
  if (blobData != null) {
8272
8954
  factsWithPreservedBlob.set(fact.id, blobData);
8273
- if (!fact.deleted_at) preservedBlobDims.add(blobData.byteLength / 4);
8955
+ if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
8274
8956
  }
8275
8957
  existingFactsById.set(fact.id, {
8276
8958
  id: fact.id,
8277
8959
  entity_id: entityId,
8278
- updated_at: safeUpdatedAt
8960
+ updated_at: safeUpdatedAt,
8961
+ deleted_at: fact.deleted_at ?? null
8279
8962
  });
8963
+ wipedByThisImport.delete(fact.id);
8280
8964
  upsertedFactIds.add(fact.id);
8281
- if (fact.deleted_at) upsertedDeletedFactIds.add(fact.id);
8965
+ if (fact.deleted_at != null) {
8966
+ upsertedDeletedFactIds.add(fact.id);
8967
+ liveEmbedFactIds.delete(fact.id);
8968
+ } else {
8969
+ liveEmbedFactIds.add(fact.id);
8970
+ }
8282
8971
  }
8283
8972
  const taskIds = bundle.tasks.map((task) => task.id);
8284
8973
  const existingTasksById = /* @__PURE__ */ new Map();
@@ -8302,7 +8991,11 @@ var ImportExportService = class {
8302
8991
  );
8303
8992
  continue;
8304
8993
  }
8305
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
8994
+ if (existing.deleted_at != null && task.deleted_at == null && !wipedTasksByThisImport.has(task.id)) {
8995
+ tombstoneSkipped++;
8996
+ continue;
8997
+ }
8998
+ if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
8306
8999
  }
8307
9000
  await this.taskRepo.upsertForImport(
8308
9001
  {
@@ -8335,8 +9028,10 @@ var ImportExportService = class {
8335
9028
  existingTasksById.set(task.id, {
8336
9029
  id: task.id,
8337
9030
  entity_id: entityId,
8338
- updated_at: safeUpdatedAt
9031
+ updated_at: safeUpdatedAt,
9032
+ deleted_at: task.deleted_at ?? null
8339
9033
  });
9034
+ wipedTasksByThisImport.delete(task.id);
8340
9035
  }
8341
9036
  const now = Date.now();
8342
9037
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
@@ -8376,6 +9071,15 @@ var ImportExportService = class {
8376
9071
  await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
8377
9072
  });
8378
9073
  for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
9074
+ if (tombstoneSkipped > 0) {
9075
+ emitDiagnostic(this.options, {
9076
+ code: "import_tombstone_skipped",
9077
+ operation: "importDump",
9078
+ trigger: "call",
9079
+ entityId,
9080
+ detail: { count: tombstoneSkipped }
9081
+ });
9082
+ }
8379
9083
  if (clampedEvents > 0) {
8380
9084
  emitDiagnostic(this.options, {
8381
9085
  code: "event_created_at_clamped",
@@ -8401,28 +9105,28 @@ var ImportExportService = class {
8401
9105
  } else {
8402
9106
  await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
8403
9107
  }
8404
- for (const fact of bundle.facts) {
8405
- if (!fact.deleted_at && upsertedFactIds.has(fact.id) && !factsWithPreservedBlob.has(fact.id)) {
8406
- const clipped = clippedTextByFactId.get(fact.id);
9108
+ for (const id of liveEmbedFactIds) {
9109
+ if (!factsWithPreservedBlob.has(id)) {
9110
+ const clipped = clippedTextByFactId.get(id);
8407
9111
  const embedded = await this.embeddingService.embedFact({
8408
- id: fact.id,
9112
+ id,
8409
9113
  entity_id: entityId,
8410
- title: clipped?.title ?? fact.title,
8411
- body: clipped?.body ?? fact.body,
8412
- tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
9114
+ title: clipped?.title ?? "",
9115
+ body: clipped?.body ?? "",
9116
+ tags: clipped?.tags ?? []
8413
9117
  }, { operation: "importDump", trigger: "call" });
8414
9118
  if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
8415
9119
  try {
8416
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
9120
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
8417
9121
  } catch (hookErr) {
8418
9122
  console.warn(
8419
- `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
9123
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
8420
9124
  hookErr
8421
9125
  );
8422
9126
  this.embeddingService.reportHookFailed(
8423
9127
  { operation: "importDump", trigger: "call" },
8424
9128
  entityId,
8425
- fact.id
9129
+ id
8426
9130
  );
8427
9131
  }
8428
9132
  }
@@ -8430,7 +9134,7 @@ var ImportExportService = class {
8430
9134
  }
8431
9135
  for (const fact of bundle.facts) {
8432
9136
  const blobData = factsWithPreservedBlob.get(fact.id);
8433
- if (blobData && !fact.deleted_at && upsertedFactIds.has(fact.id)) {
9137
+ if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
8434
9138
  try {
8435
9139
  const float32Vector = new Float32Array(
8436
9140
  blobData.buffer,
@@ -9990,6 +10694,6 @@ var WriteService = class {
9990
10694
  }
9991
10695
  };
9992
10696
 
9993
- export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
9994
- //# sourceMappingURL=chunk-E3JCZMJL.mjs.map
9995
- //# sourceMappingURL=chunk-E3JCZMJL.mjs.map
10697
+ export { BaseRepository, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
10698
+ //# sourceMappingURL=chunk-T75YZCVX.mjs.map
10699
+ //# sourceMappingURL=chunk-T75YZCVX.mjs.map