@equationalapplications/core-llm-wiki 9.2.0 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/testing.js CHANGED
@@ -724,6 +724,15 @@ var SEVERITY = {
724
724
  resolve_failed: "warn",
725
725
  read_budget: "info",
726
726
  event_retention_held: "info",
727
+ prune_checkpoint_incomplete: "warn",
728
+ erase_secure_delete_off: "error",
729
+ erase_entity_skipped: "warn",
730
+ erase_retired_vtab_undroppable: "warn",
731
+ erase_retired_remaining: "error",
732
+ erase_tombstones_remaining: "error",
733
+ erase_retired_read_failed: "error",
734
+ erase_registry_sweep_skipped: "info",
735
+ import_tombstone_skipped: "info",
727
736
  event_created_at_clamped: "warn",
728
737
  event_created_at_restamped: "info",
729
738
  external_deletion_pending: "warn",
@@ -759,6 +768,15 @@ var MESSAGE = {
759
768
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
760
769
  read_budget: "A read was packed to a token budget.",
761
770
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
771
+ prune_checkpoint_incomplete: "The post-VACUUM WAL checkpoint was incomplete while a prune partial failure was also reported; deleted bytes may remain in the WAL.",
772
+ erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
773
+ erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow tables were emptied and the name stays listed until an FTS5-capable open drops it.",
774
+ erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
775
+ erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
776
+ erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
777
+ erase_entity_skipped: "Erase skipped an entity because another operation held its prune lock.",
778
+ erase_registry_sweep_skipped: "Erase skipped the source_ref_index tombstone sweep because the table does not exist (pre-v9 store).",
779
+ import_tombstone_skipped: "Import skipped live dump rows (facts and tasks) whose ids were forgotten locally. The protection holds while the tombstone is retained; once a prune hard-deletes the row, an old dump can import the fact again \u2014 see the OKF guide\u2019s restore caveat.",
762
780
  event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
763
781
  event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
764
782
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
@@ -1251,6 +1269,12 @@ function entitySummaryMetaKey(entityId) {
1251
1269
  return `entity_summary:${entityId}`;
1252
1270
  }
1253
1271
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1272
+ var CheckpointIncompleteError = class extends Error {
1273
+ constructor() {
1274
+ super(...arguments);
1275
+ this.code = "erase_checkpoint_incomplete";
1276
+ }
1277
+ };
1254
1278
  function generateId(prefix = "") {
1255
1279
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1256
1280
  return prefix + crypto.randomUUID().replace(/-/g, "").substring(0, 24);
@@ -1656,7 +1680,8 @@ var ImportExportService = class {
1656
1680
  this.vectorRemoval = vectorRemoval;
1657
1681
  this.prefix = prefix;
1658
1682
  }
1659
- async exportDump(entityIds) {
1683
+ async exportDump(entityIds, opts) {
1684
+ const includeForgotten = opts?.includeForgotten === true;
1660
1685
  let ids;
1661
1686
  if (entityIds && entityIds.length > 0) {
1662
1687
  ids = Array.from(new Set(entityIds));
@@ -1677,7 +1702,7 @@ var ImportExportService = class {
1677
1702
  const batchResults = await Promise.all(
1678
1703
  batch.map(
1679
1704
  async (id) => {
1680
- const bundle = await this.getFullBundle(id, { includeBlobs: true });
1705
+ const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
1681
1706
  const storedSources = await this.exportStoredSources(id);
1682
1707
  return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
1683
1708
  }
@@ -1783,10 +1808,11 @@ var ImportExportService = class {
1783
1808
  }
1784
1809
  }
1785
1810
  async getFullBundle(entityId, opts) {
1811
+ const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
1786
1812
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
1787
1813
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
1788
- opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
1789
- this.taskRepo.findAllByEntityId(entityId),
1814
+ opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
1815
+ this.taskRepo.findAllByEntityId(entityId, void 0, incl),
1790
1816
  this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
1791
1817
  this.edgeRepo.getByEntityId(entityId),
1792
1818
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
@@ -1822,12 +1848,15 @@ var ImportExportService = class {
1822
1848
  const skippedSources = [];
1823
1849
  const refusalDiagnostics = [];
1824
1850
  const upsertedFactIds = /* @__PURE__ */ new Set();
1851
+ const liveEmbedFactIds = /* @__PURE__ */ new Set();
1825
1852
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
1826
1853
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
1827
1854
  const preservedBlobDims = /* @__PURE__ */ new Set();
1828
1855
  const softDeletedFactIds = [];
1856
+ const softDeletedTaskIds = [];
1829
1857
  const clippedTextByFactId = /* @__PURE__ */ new Map();
1830
1858
  let clampedEvents = 0;
1859
+ let tombstoneSkipped = 0;
1831
1860
  const restamped = { behind_watermark: 0, invalid: 0 };
1832
1861
  await this.db.withTransactionAsync(async (tx) => {
1833
1862
  if (!merge) {
@@ -1838,8 +1867,9 @@ var ImportExportService = class {
1838
1867
  tx,
1839
1868
  false
1840
1869
  );
1841
- softDeletedFactIds.push(...deletedLiveFactIds);
1870
+ for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
1842
1871
  await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
1872
+ for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
1843
1873
  await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
1844
1874
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
1845
1875
  await this.metadataRepo.deleteCheckpoint(entityId, tx);
@@ -1849,6 +1879,8 @@ var ImportExportService = class {
1849
1879
  } else if (!merge) {
1850
1880
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
1851
1881
  }
1882
+ const wipedByThisImport = new Set(softDeletedFactIds);
1883
+ const wipedTasksByThisImport = new Set(softDeletedTaskIds);
1852
1884
  const factIds = bundle.facts.map((fact) => fact.id);
1853
1885
  const existingFactsById = /* @__PURE__ */ new Map();
1854
1886
  const existingFacts = await this.entryRepo.findExistingMetadataByIds(
@@ -1924,11 +1956,16 @@ var ImportExportService = class {
1924
1956
  );
1925
1957
  continue;
1926
1958
  }
1927
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
1959
+ if (existing.deleted_at != null && fact.deleted_at == null && !wipedByThisImport.has(fact.id)) {
1960
+ tombstoneSkipped++;
1961
+ continue;
1962
+ }
1963
+ if (merge && safeUpdatedAt <= existing.updated_at && fact.deleted_at == null) continue;
1928
1964
  }
1929
1965
  const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
1930
1966
  const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
1931
- clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody });
1967
+ const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
1968
+ clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
1932
1969
  let normalizedSourceRef = null;
1933
1970
  if (fact.source_ref !== null && fact.source_ref !== void 0) {
1934
1971
  normalizedSourceRef = normalizeSourceRef(fact.source_ref);
@@ -1995,15 +2032,22 @@ var ImportExportService = class {
1995
2032
  }, tx, { outbox: false });
1996
2033
  if (blobData != null) {
1997
2034
  factsWithPreservedBlob.set(fact.id, blobData);
1998
- if (!fact.deleted_at) preservedBlobDims.add(blobData.byteLength / 4);
2035
+ if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
1999
2036
  }
2000
2037
  existingFactsById.set(fact.id, {
2001
2038
  id: fact.id,
2002
2039
  entity_id: entityId,
2003
- updated_at: safeUpdatedAt
2040
+ updated_at: safeUpdatedAt,
2041
+ deleted_at: fact.deleted_at ?? null
2004
2042
  });
2043
+ wipedByThisImport.delete(fact.id);
2005
2044
  upsertedFactIds.add(fact.id);
2006
- if (fact.deleted_at) upsertedDeletedFactIds.add(fact.id);
2045
+ if (fact.deleted_at != null) {
2046
+ upsertedDeletedFactIds.add(fact.id);
2047
+ liveEmbedFactIds.delete(fact.id);
2048
+ } else {
2049
+ liveEmbedFactIds.add(fact.id);
2050
+ }
2007
2051
  }
2008
2052
  const taskIds = bundle.tasks.map((task) => task.id);
2009
2053
  const existingTasksById = /* @__PURE__ */ new Map();
@@ -2027,7 +2071,11 @@ var ImportExportService = class {
2027
2071
  );
2028
2072
  continue;
2029
2073
  }
2030
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
2074
+ if (existing.deleted_at != null && task.deleted_at == null && !wipedTasksByThisImport.has(task.id)) {
2075
+ tombstoneSkipped++;
2076
+ continue;
2077
+ }
2078
+ if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
2031
2079
  }
2032
2080
  await this.taskRepo.upsertForImport(
2033
2081
  {
@@ -2060,8 +2108,10 @@ var ImportExportService = class {
2060
2108
  existingTasksById.set(task.id, {
2061
2109
  id: task.id,
2062
2110
  entity_id: entityId,
2063
- updated_at: safeUpdatedAt
2111
+ updated_at: safeUpdatedAt,
2112
+ deleted_at: task.deleted_at ?? null
2064
2113
  });
2114
+ wipedTasksByThisImport.delete(task.id);
2065
2115
  }
2066
2116
  const now = Date.now();
2067
2117
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
@@ -2101,6 +2151,15 @@ var ImportExportService = class {
2101
2151
  await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
2102
2152
  });
2103
2153
  for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
2154
+ if (tombstoneSkipped > 0) {
2155
+ emitDiagnostic(this.options, {
2156
+ code: "import_tombstone_skipped",
2157
+ operation: "importDump",
2158
+ trigger: "call",
2159
+ entityId,
2160
+ detail: { count: tombstoneSkipped }
2161
+ });
2162
+ }
2104
2163
  if (clampedEvents > 0) {
2105
2164
  emitDiagnostic(this.options, {
2106
2165
  code: "event_created_at_clamped",
@@ -2126,28 +2185,28 @@ var ImportExportService = class {
2126
2185
  } else {
2127
2186
  await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
2128
2187
  }
2129
- for (const fact of bundle.facts) {
2130
- if (!fact.deleted_at && upsertedFactIds.has(fact.id) && !factsWithPreservedBlob.has(fact.id)) {
2131
- const clipped = clippedTextByFactId.get(fact.id);
2188
+ for (const id of liveEmbedFactIds) {
2189
+ if (!factsWithPreservedBlob.has(id)) {
2190
+ const clipped = clippedTextByFactId.get(id);
2132
2191
  const embedded = await this.embeddingService.embedFact({
2133
- id: fact.id,
2192
+ id,
2134
2193
  entity_id: entityId,
2135
- title: clipped?.title ?? fact.title,
2136
- body: clipped?.body ?? fact.body,
2137
- tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
2194
+ title: clipped?.title ?? "",
2195
+ body: clipped?.body ?? "",
2196
+ tags: clipped?.tags ?? []
2138
2197
  }, { operation: "importDump", trigger: "call" });
2139
2198
  if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
2140
2199
  try {
2141
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
2200
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
2142
2201
  } catch (hookErr) {
2143
2202
  console.warn(
2144
- `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
2203
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
2145
2204
  hookErr
2146
2205
  );
2147
2206
  this.embeddingService.reportHookFailed(
2148
2207
  { operation: "importDump", trigger: "call" },
2149
2208
  entityId,
2150
- fact.id
2209
+ id
2151
2210
  );
2152
2211
  }
2153
2212
  }
@@ -2155,7 +2214,7 @@ var ImportExportService = class {
2155
2214
  }
2156
2215
  for (const fact of bundle.facts) {
2157
2216
  const blobData = factsWithPreservedBlob.get(fact.id);
2158
- if (blobData && !fact.deleted_at && upsertedFactIds.has(fact.id)) {
2217
+ if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
2159
2218
  try {
2160
2219
  const float32Vector = new Float32Array(
2161
2220
  blobData.buffer,
@@ -3533,6 +3592,106 @@ function classifierStateForFact(fact) {
3533
3592
  return parts.join("\n\n");
3534
3593
  }
3535
3594
 
3595
+ // src/utils/temporal.ts
3596
+ function liveAtSql(mode, alias = "") {
3597
+ const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3598
+ return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3599
+ }
3600
+ function assertEpochMs(name, v) {
3601
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3602
+ throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3603
+ }
3604
+ return Math.trunc(v);
3605
+ }
3606
+
3607
+ // src/services/TemporalService.ts
3608
+ var HISTORY_MAX_DEPTH = 100;
3609
+ var TemporalService = class {
3610
+ constructor(db, options, entryRepo, searchService, embeddingService) {
3611
+ this.db = db;
3612
+ this.options = options;
3613
+ this.entryRepo = entryRepo;
3614
+ this.searchService = searchService;
3615
+ this.embeddingService = embeddingService;
3616
+ }
3617
+ /**
3618
+ * Link `oldId` → `newId` inside the caller's transaction. `newId` must
3619
+ * already exist. Throws WikiSupersedeError on any rule violation; the
3620
+ * caller's transaction then rolls back.
3621
+ */
3622
+ async supersedeInTx(tx, entityId, oldId, newId, t, now) {
3623
+ const old = await this.entryRepo.findTemporalRow(oldId, tx);
3624
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
3625
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3626
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3627
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
3628
+ if (newId === oldId) throw new WikiSupersedeError("cycle");
3629
+ const repl = await this.entryRepo.findTemporalRow(newId, tx);
3630
+ if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
3631
+ if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3632
+ if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3633
+ const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
3634
+ if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
3635
+ await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
3636
+ if (repl.valid_from == null) {
3637
+ await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
3638
+ }
3639
+ }
3640
+ async supersede(entityId, oldId, replacement, options) {
3641
+ const now = Date.now();
3642
+ const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
3643
+ let created = null;
3644
+ if (typeof replacement !== "string") {
3645
+ if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
3646
+ throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
3647
+ }
3648
+ created = {
3649
+ id: generateId("fact_"),
3650
+ entity_id: entityId,
3651
+ title: replacement.title,
3652
+ body: replacement.body,
3653
+ tags: Array.isArray(replacement.tags) ? replacement.tags : [],
3654
+ confidence: replacement.confidence ?? "certain",
3655
+ source_type: replacement.source_type ?? "user_stated",
3656
+ source_hash: null,
3657
+ source_ref: null,
3658
+ created_at: now,
3659
+ updated_at: now,
3660
+ last_accessed_at: null,
3661
+ access_count: 0,
3662
+ deleted_at: null
3663
+ };
3664
+ }
3665
+ const newId = typeof replacement === "string" ? replacement : created.id;
3666
+ const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
3667
+ await this.db.withTransactionAsync(async (tx) => {
3668
+ if (created) {
3669
+ await this.entryRepo.upsert(created, tx);
3670
+ if (newValidFrom !== void 0) {
3671
+ await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
3672
+ }
3673
+ }
3674
+ await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
3675
+ });
3676
+ await this.searchService.syncEntries(entityId, [oldId, newId]);
3677
+ if (created) {
3678
+ await this.embeddingService.embedFact(
3679
+ { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
3680
+ { operation: "supersede", trigger: "call" }
3681
+ );
3682
+ }
3683
+ this.searchService.evictCache(entityId);
3684
+ return { newId };
3685
+ }
3686
+ async history(entityId, factId) {
3687
+ const start = await this.entryRepo.findTemporalRow(factId);
3688
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
3689
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
3690
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
3691
+ return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
3692
+ }
3693
+ };
3694
+
3536
3695
  // src/utils/engineDefaults.ts
3537
3696
  var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3538
3697
  var DEFAULT_MAINTENANCE_MODE = "deferred";
@@ -3578,18 +3737,6 @@ function removalGate(options) {
3578
3737
  return "none";
3579
3738
  }
3580
3739
 
3581
- // src/utils/temporal.ts
3582
- function liveAtSql(mode, alias = "") {
3583
- const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3584
- return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3585
- }
3586
- function assertEpochMs(name, v) {
3587
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3588
- throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3589
- }
3590
- return Math.trunc(v);
3591
- }
3592
-
3593
3740
  // src/repositories/EdgeRepository.ts
3594
3741
  var CONFIDENCE_RANK = {
3595
3742
  tentative: 0,
@@ -3951,6 +4098,10 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
3951
4098
 
3952
4099
  // src/services/search/fts5Sql.ts
3953
4100
  var FTS5_STATE_KEY = "fts5_index_state";
4101
+ var FTS5_RETIRED_TABLES_KEY = "fts5_retired_tables";
4102
+ function isRetiredTableName(p, name) {
4103
+ return typeof name === "string" && name.startsWith(`${p}entries_fts_retired_`) && /^\d+$/.test(name.slice(`${p}entries_fts_retired_`.length));
4104
+ }
3954
4105
  var FTS5_REBUILD_WM_KEY = "fts5_rebuild_wm";
3955
4106
  var FTS5_REBUILD_SNAPSHOT_KEY = "fts5_rebuild_snapshot";
3956
4107
  var FTS5_SWEEP_CURSOR_KEY = "fts5_orphan_sweep_cursor";
@@ -4821,94 +4972,6 @@ async function runResolve(deps, ctx, ambiguous) {
4821
4972
  return out;
4822
4973
  }
4823
4974
 
4824
- // src/services/TemporalService.ts
4825
- var HISTORY_MAX_DEPTH = 100;
4826
- var TemporalService = class {
4827
- constructor(db, options, entryRepo, searchService, embeddingService) {
4828
- this.db = db;
4829
- this.options = options;
4830
- this.entryRepo = entryRepo;
4831
- this.searchService = searchService;
4832
- this.embeddingService = embeddingService;
4833
- }
4834
- /**
4835
- * Link `oldId` → `newId` inside the caller's transaction. `newId` must
4836
- * already exist. Throws WikiSupersedeError on any rule violation; the
4837
- * caller's transaction then rolls back.
4838
- */
4839
- async supersedeInTx(tx, entityId, oldId, newId, t, now) {
4840
- const old = await this.entryRepo.findTemporalRow(oldId, tx);
4841
- if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
4842
- if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
4843
- if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
4844
- if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
4845
- if (newId === oldId) throw new WikiSupersedeError("cycle");
4846
- const repl = await this.entryRepo.findTemporalRow(newId, tx);
4847
- if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
4848
- if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
4849
- if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
4850
- const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
4851
- if (predecessors.includes(newId)) throw new WikiSupersedeError("cycle");
4852
- await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
4853
- if (repl.valid_from == null) {
4854
- await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
4855
- }
4856
- }
4857
- async supersede(entityId, oldId, replacement, options) {
4858
- const now = Date.now();
4859
- const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
4860
- let created = null;
4861
- if (typeof replacement !== "string") {
4862
- if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
4863
- throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
4864
- }
4865
- created = {
4866
- id: generateId("fact_"),
4867
- entity_id: entityId,
4868
- title: replacement.title,
4869
- body: replacement.body,
4870
- tags: Array.isArray(replacement.tags) ? replacement.tags : [],
4871
- confidence: replacement.confidence ?? "certain",
4872
- source_type: replacement.source_type ?? "user_stated",
4873
- source_hash: null,
4874
- source_ref: null,
4875
- created_at: now,
4876
- updated_at: now,
4877
- last_accessed_at: null,
4878
- access_count: 0,
4879
- deleted_at: null
4880
- };
4881
- }
4882
- const newId = typeof replacement === "string" ? replacement : created.id;
4883
- const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
4884
- await this.db.withTransactionAsync(async (tx) => {
4885
- if (created) {
4886
- await this.entryRepo.upsert(created, tx);
4887
- if (newValidFrom !== void 0) {
4888
- await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
4889
- }
4890
- }
4891
- await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
4892
- });
4893
- await this.searchService.syncEntries(entityId, [oldId, newId]);
4894
- if (created) {
4895
- await this.embeddingService.embedFact(
4896
- { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
4897
- { operation: "supersede", trigger: "call" }
4898
- );
4899
- }
4900
- this.searchService.evictCache(entityId);
4901
- return { newId };
4902
- }
4903
- async history(entityId, factId) {
4904
- const start = await this.entryRepo.findTemporalRow(factId);
4905
- if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
4906
- const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
4907
- const facts = await this.entryRepo.findByIds([...predecessors, factId, ...successors], [entityId]);
4908
- 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));
4909
- }
4910
- };
4911
-
4912
4975
  // src/services/librarian/ops/apply.ts
4913
4976
  function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
4914
4977
  if (candidate.sourceEventId === null) return null;
@@ -5174,6 +5237,7 @@ async function runLibrarianStrategy(deps, ctx) {
5174
5237
  }
5175
5238
 
5176
5239
  // src/services/MaintenanceService.ts
5240
+ var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HISTORY_MAX_DEPTH} links per direction); the chain is longer than the ids listed. Run forget again on a remaining chain id to continue.`;
5177
5241
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
5178
5242
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
5179
5243
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -5222,6 +5286,20 @@ var formatSkipError = (err) => {
5222
5286
  }
5223
5287
  return base;
5224
5288
  };
5289
+ function eraseRuntime() {
5290
+ const g = globalThis;
5291
+ if (g.process?.versions?.node) return `node ${g.process.versions.node}`;
5292
+ return g.HermesInternal ? "hermes" : "unknown";
5293
+ }
5294
+ var EraseStepError = class extends Error {
5295
+ constructor(code, message, report, cause) {
5296
+ super(message);
5297
+ this.code = code;
5298
+ this.report = report;
5299
+ this.name = "EraseStepError";
5300
+ if (cause !== void 0) this.cause = cause;
5301
+ }
5302
+ };
5225
5303
  var MaintenanceService = class {
5226
5304
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
5227
5305
  this.db = db;
@@ -5242,7 +5320,15 @@ var MaintenanceService = class {
5242
5320
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
5243
5321
  }
5244
5322
  async runPrune(entityId, options) {
5245
- this.jobManager.acquireLock("prune", entityId);
5323
+ return this._runPrune(entityId, options, "host");
5324
+ }
5325
+ /**
5326
+ * Shared prune body. `owner: 'erase'` lets erase()'s own per-entity prune
5327
+ * through the universal erase fence in JobManager; the public `runPrune`
5328
+ * always passes `'host'`.
5329
+ */
5330
+ async _runPrune(entityId, options, owner) {
5331
+ this.jobManager.acquireLock("prune", entityId, void 0, owner);
5246
5332
  try {
5247
5333
  const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
5248
5334
  const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
@@ -5273,8 +5359,9 @@ var MaintenanceService = class {
5273
5359
  }
5274
5360
  }
5275
5361
  if (retainSoftDeletedFor !== null) {
5276
- const cutoff = now - retainSoftDeletedFor * 864e5;
5277
- const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
5362
+ const softDeletedAll = options?.softDeletedCutoff === "all";
5363
+ const cutoff = softDeletedAll ? 0 : options?.softDeletedCutoff ?? now - retainSoftDeletedFor * 864e5;
5364
+ const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff, void 0, { noCutoff: softDeletedAll });
5278
5365
  const prunableIds = entriesToDelete.map((r) => r.id);
5279
5366
  const vr = this.vectorRemoval;
5280
5367
  const vrRepo = this.vectorRemovalRepo;
@@ -5320,7 +5407,7 @@ var MaintenanceService = class {
5320
5407
  }
5321
5408
  if (deletable.length > 0) {
5322
5409
  const deletedIds = [];
5323
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
5410
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds, noCutoff: softDeletedAll });
5324
5411
  if (hookLedger) {
5325
5412
  const gone = new Set(deletedIds);
5326
5413
  const skipped = deletable.filter((id) => !gone.has(id));
@@ -5335,7 +5422,7 @@ var MaintenanceService = class {
5335
5422
  else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
5336
5423
  }
5337
5424
  }
5338
- deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
5425
+ deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
5339
5426
  });
5340
5427
  if (hookLedger) {
5341
5428
  const keptSet = new Set(kept);
@@ -5380,12 +5467,20 @@ var MaintenanceService = class {
5380
5467
  }
5381
5468
  }
5382
5469
  }
5470
+ let vacuumCheckpointErr;
5383
5471
  if (vacuum) {
5384
- await resetNormalizeWatermarks(this.metadataRepo);
5385
- await this.metadataRepo.vacuum();
5386
- await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5472
+ try {
5473
+ await this._wrappedVacuum();
5474
+ } catch (err) {
5475
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
5476
+ vacuumCheckpointErr = err;
5477
+ }
5387
5478
  }
5479
+ if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
5388
5480
  await this.searchService.syncEntries(entityId, syncedIds);
5481
+ if (prunePartial && vacuumCheckpointErr) {
5482
+ emitDiagnostic(this.options, { code: "prune_checkpoint_incomplete", operation: "prune", trigger: "call", entityId, detail: { reason: vacuumCheckpointErr.message } });
5483
+ }
5389
5484
  if (prunePartial) {
5390
5485
  throw new PrunePartialFailureError(
5391
5486
  deletedEntries,
@@ -5396,11 +5491,327 @@ var MaintenanceService = class {
5396
5491
  deletedEvents
5397
5492
  );
5398
5493
  }
5494
+ if (vacuumCheckpointErr) throw vacuumCheckpointErr;
5399
5495
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
5400
5496
  } finally {
5401
5497
  this.jobManager.releaseLock("prune", entityId);
5402
5498
  }
5403
5499
  }
5500
+ /** Shared by runPrune and erase step 5. */
5501
+ async _wrappedVacuum() {
5502
+ await resetNormalizeWatermarks(this.metadataRepo);
5503
+ let checkpointErr;
5504
+ try {
5505
+ await this.metadataRepo.vacuum();
5506
+ } catch (err) {
5507
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
5508
+ checkpointErr = err;
5509
+ }
5510
+ await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5511
+ if (checkpointErr) throw checkpointErr;
5512
+ }
5513
+ /**
5514
+ * Erase core (forget-erasure spec §2, steps 0 / 1 / 1b). Thin entry: T6
5515
+ * completes the pipeline (FTS, VACUUM, checkpoint, sync). Never reports a
5516
+ * success it cannot verify: a failed step throws {@link EraseStepError}
5517
+ * carrying the partial report with `verified: false`.
5518
+ */
5519
+ async erase(opts) {
5520
+ const rebuild = opts?.rebuild === true;
5521
+ this.jobManager.acquireLock("erase", "*");
5522
+ const report = {
5523
+ verified: false,
5524
+ secureDelete: null,
5525
+ sqliteVersion: "",
5526
+ entities: [],
5527
+ holds: [],
5528
+ skipped: [],
5529
+ syncedIds: [],
5530
+ registrySweep: { skipped: false, deleted: 0 },
5531
+ retiredUndroppable: [],
5532
+ failedStep: null,
5533
+ runtime: eraseRuntime(),
5534
+ steps: []
5535
+ };
5536
+ const ok = (step, outcome = "ok") => {
5537
+ report.steps.push({ step, outcome });
5538
+ };
5539
+ try {
5540
+ const readPragma = async () => (await this.db.getFirstAsync("PRAGMA secure_delete"))?.secure_delete ?? null;
5541
+ let pragma;
5542
+ try {
5543
+ pragma = await readPragma();
5544
+ if (pragma !== 1) {
5545
+ await this.db.execAsync("PRAGMA secure_delete=ON");
5546
+ pragma = await readPragma();
5547
+ }
5548
+ report.secureDelete = pragma;
5549
+ report.sqliteVersion = (await this.db.getFirstAsync("SELECT sqlite_version() AS v"))?.v ?? "";
5550
+ } catch (err) {
5551
+ report.failedStep = "secure_delete";
5552
+ throw new EraseStepError("erase_secure_delete_read_failed", "erase stopped at step 0: secure_delete pragma read failed; erasure is unverified", report, err);
5553
+ }
5554
+ if (pragma !== 1) {
5555
+ emitDiagnostic(this.options, { code: "erase_secure_delete_off", operation: "erase", trigger: "call", entityId: "" });
5556
+ report.failedStep = "secure_delete";
5557
+ throw new EraseStepError("erase_secure_delete_off", "erase stopped at step 0: secure_delete is not ON; erasure is unverified", report);
5558
+ }
5559
+ ok("secure_delete");
5560
+ try {
5561
+ report.entities = await this.metadataRepo.getDistinctEntityIds(void 0, { softDeletedAll: true });
5562
+ } catch (err) {
5563
+ report.failedStep = "prune";
5564
+ throw new EraseStepError("erase_prune_failed", "erase stopped at step 1: the entity walk failed; erasure is unverified", report, err);
5565
+ }
5566
+ const syncedByEntity = /* @__PURE__ */ new Map();
5567
+ for (const entityId of report.entities) {
5568
+ const syncedIds = [];
5569
+ syncedByEntity.set(entityId, syncedIds);
5570
+ try {
5571
+ await this._runPrune(entityId, { retainSoftDeletedFor: 0, retainEventsFor: null, vacuum: false, syncedIds, softDeletedCutoff: "all" }, "erase");
5572
+ } catch (err) {
5573
+ if (err instanceof PrunePartialFailureError) {
5574
+ report.holds.push({ entityId, deleted: err.deleted, deletedTasks: err.deletedTasks, failedAt: err.failedAt, remaining: err.remaining });
5575
+ } else if (err instanceof WikiBusyError) {
5576
+ report.skipped.push(entityId);
5577
+ emitDiagnostic(this.options, { code: "erase_entity_skipped", operation: "erase", trigger: "call", entityId });
5578
+ } else {
5579
+ report.failedStep = "prune";
5580
+ throw new EraseStepError("erase_prune_failed", `erase stopped at step 1 (entity ${entityId})`, report, err);
5581
+ }
5582
+ }
5583
+ for (const id of syncedIds) report.syncedIds.push(id);
5584
+ }
5585
+ ok("prune", report.holds.length > 0 || report.skipped.length > 0 ? "partial" : "ok");
5586
+ try {
5587
+ await this.db.withTransactionAsync(async (tx) => {
5588
+ if (await this.sourceRefIndexPresent(tx)) {
5589
+ const r = await tx.runAsync(`DELETE FROM ${this.prefix}source_ref_index WHERE deleted_at IS NOT NULL`);
5590
+ report.registrySweep = { skipped: false, deleted: r.changes };
5591
+ } else {
5592
+ report.registrySweep = { skipped: true, deleted: 0 };
5593
+ }
5594
+ });
5595
+ } catch (err) {
5596
+ report.failedStep = "registry_sweep";
5597
+ throw new EraseStepError("erase_registry_sweep_failed", "erase stopped at step 1b", report, err);
5598
+ }
5599
+ if (report.registrySweep.skipped) {
5600
+ emitDiagnostic(this.options, { code: "erase_registry_sweep_skipped", operation: "erase", trigger: "call", entityId: "" });
5601
+ }
5602
+ ok("registry_sweep", report.registrySweep.skipped ? "partial" : "ok");
5603
+ await this._eraseDrainPassages(report);
5604
+ ok("passage_drain");
5605
+ await this._eraseReclaimRetired(report);
5606
+ ok("retired_reclaim");
5607
+ try {
5608
+ await this._wrappedVacuum();
5609
+ } catch (err) {
5610
+ if (err instanceof CheckpointIncompleteError) {
5611
+ report.failedStep = "checkpoint";
5612
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 5: WAL checkpoint incomplete; erasure is unverified", report, err);
5613
+ }
5614
+ report.failedStep = "vacuum";
5615
+ throw new EraseStepError("erase_vacuum_failed", "erase stopped at step 5: VACUUM failed (commonly an unfenced writer holding the database \u2014 quiesce and retry; also any other VACUUM failure, e.g. disk-full or I/O errors)", report, err);
5616
+ }
5617
+ ok("vacuum");
5618
+ const byEntity = /* @__PURE__ */ new Map();
5619
+ for (const e of report.entities) byEntity.set(e, []);
5620
+ for (const [entityId, ids] of syncedByEntity) byEntity.set(entityId, ids);
5621
+ for (const [entityId, ids] of byEntity) {
5622
+ if (ids.length > 0) await this._eraseSyncEntries(entityId, ids, report);
5623
+ }
5624
+ ok("index_sync");
5625
+ if (rebuild) {
5626
+ try {
5627
+ await this.searchService.rebuildSurfaced();
5628
+ } catch (err) {
5629
+ report.failedStep = "rebuild";
5630
+ throw new EraseStepError("erase_rebuild_failed", "erase stopped at step 7: FTS rebuild failed", report, err);
5631
+ }
5632
+ ok("rebuild");
5633
+ }
5634
+ await this._eraseReclaimRetired(report);
5635
+ let present;
5636
+ try {
5637
+ present = await this.db.getAllAsync(
5638
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%entries_fts_retired_%'`
5639
+ );
5640
+ } catch (err) {
5641
+ report.failedStep = "retired_reclaim";
5642
+ emitDiagnostic(this.options, { code: "erase_retired_read_failed", operation: "erase", trigger: "call", entityId: "" });
5643
+ throw new EraseStepError("erase_retired_read_failed", "erase stopped after step 6: the retired-table read failed; erasure is unverified", report, err);
5644
+ }
5645
+ const left = present.map((r) => r.name).filter((n) => isRetiredTableName(this.prefix, n) && !report.retiredUndroppable.includes(n));
5646
+ if (left.length > 0) {
5647
+ report.failedStep = "retired_reclaim";
5648
+ emitDiagnostic(this.options, { code: "erase_retired_remaining", operation: "erase", trigger: "call", entityId: "", detail: { tables: left } });
5649
+ throw new EraseStepError("erase_retired_remaining", `erase stopped after step 6: retired FTS tables remain (${left.join(", ")})`, report);
5650
+ }
5651
+ ok("retired_reclaim_rerun");
5652
+ await this._eraseOptimize(report);
5653
+ ok("optimize");
5654
+ try {
5655
+ await this.metadataRepo.checkpointTruncateVerified();
5656
+ } catch (err) {
5657
+ report.failedStep = "checkpoint";
5658
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 8: WAL checkpoint incomplete; erasure is unverified", report, err);
5659
+ }
5660
+ ok("checkpoint");
5661
+ if (report.skipped.length === 0 && report.holds.length === 0) {
5662
+ let remainingTombstones;
5663
+ try {
5664
+ const row = await this.db.getFirstAsync(
5665
+ `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
5666
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
5667
+ );
5668
+ remainingTombstones = row?.n ?? 0;
5669
+ } catch (err) {
5670
+ report.failedStep = "tombstone_gate";
5671
+ throw new EraseStepError("erase_tombstone_gate_failed", "erase stopped at step 9: could not count remaining tombstones; erasure is unverified", report, err);
5672
+ }
5673
+ if (remainingTombstones > 0) {
5674
+ emitDiagnostic(this.options, { code: "erase_tombstones_remaining", operation: "erase", trigger: "call", entityId: "", detail: { count: remainingTombstones } });
5675
+ report.failedStep = "tombstone_gate";
5676
+ throw new EraseStepError("erase_tombstones_remaining", `erase stopped at step 9: ${remainingTombstones} soft-deleted row(s) remain; erasure is unverified`, report);
5677
+ }
5678
+ ok("tombstone_gate");
5679
+ } else {
5680
+ report.steps.push({ step: "tombstone_gate", outcome: "partial" });
5681
+ }
5682
+ report.verified = report.skipped.length === 0 && report.holds.length === 0;
5683
+ return report;
5684
+ } catch (err) {
5685
+ if (err instanceof EraseStepError && err.report === report && report.failedStep) {
5686
+ report.steps.push({ step: report.failedStep, outcome: "failed" });
5687
+ report.verified = false;
5688
+ }
5689
+ throw err;
5690
+ } finally {
5691
+ this.jobManager.releaseLock("erase", "*");
5692
+ }
5693
+ }
5694
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
5695
+ /**
5696
+ * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
5697
+ * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
5698
+ * N2 guard (probe lives here, strategy-agnostic): a strategy without the strict
5699
+ * drains (Unavailable / MiniSearch) cannot drain, so rows in either FTS ledger
5700
+ * mean text was never drained -> the step fails and erasure is unverified.
5701
+ * Absent or empty ledgers proceed.
5702
+ */
5703
+ async _eraseDrainPassages(report) {
5704
+ if (!this.searchService.hasStrictDrain()) {
5705
+ for (const [table, failedStep, code] of [
5706
+ [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
5707
+ [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
5708
+ ]) {
5709
+ let rows = false;
5710
+ try {
5711
+ rows = await this.sourceTableExists(table) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${table} LIMIT 1`) != null;
5712
+ } catch (err) {
5713
+ report.failedStep = failedStep;
5714
+ throw new EraseStepError(code, `erase stopped at step 3: could not probe ${table}`, report, err);
5715
+ }
5716
+ if (rows) {
5717
+ report.failedStep = failedStep;
5718
+ throw new EraseStepError(code, `erase stopped at step 3: ${table} holds undrained rows and the FTS index strategy cannot drain them; erasure is unverified`, report);
5719
+ }
5720
+ }
5721
+ for (const suffix of ["entries_fts_content", "source_passages_fts_content"]) {
5722
+ let orphaned = false;
5723
+ try {
5724
+ orphaned = await this.sourceTableExists(`${this.prefix}${suffix}`);
5725
+ } catch (err) {
5726
+ report.failedStep = "index_sync";
5727
+ throw new EraseStepError("erase_orphaned_fts_content", `erase stopped: could not probe ${this.prefix}${suffix}`, report, err);
5728
+ }
5729
+ if (orphaned) {
5730
+ report.failedStep = "index_sync";
5731
+ throw new EraseStepError("erase_orphaned_fts_content", "erase stopped: orphaned full-text content tables may still hold forgotten text", report);
5732
+ }
5733
+ }
5734
+ }
5735
+ try {
5736
+ await this.searchService.drainEntriesLedgerSurfaced();
5737
+ } catch (err) {
5738
+ report.failedStep = "index_sync";
5739
+ throw new EraseStepError("erase_index_sync_failed", "erase stopped at step 3: entries ledger drain failed", report, err);
5740
+ }
5741
+ try {
5742
+ await this.searchService.drainPassagesSurfaced();
5743
+ } catch (err) {
5744
+ report.failedStep = "passage_drain";
5745
+ throw new EraseStepError("erase_passage_drain_failed", "erase stopped at step 3: passage drain failed", report, err);
5746
+ }
5747
+ }
5748
+ /**
5749
+ * Step 4 (and its re-run after step 6): reclaim retired FTS tables to
5750
+ * completion. A module-less runtime cannot DROP a virtual table, so each
5751
+ * retired table's shadow tables are emptied under the pragma and the name
5752
+ * stays listed; a later FTS5-capable open's step 4 completes the DROP.
5753
+ */
5754
+ async _eraseReclaimRetired(report) {
5755
+ if (this.searchService.canReclaimRetired()) {
5756
+ try {
5757
+ await this.searchService.reclaimRetiredSurfaced();
5758
+ return;
5759
+ } catch (err) {
5760
+ if (!/no such module/i.test(err instanceof Error ? err.message : String(err))) {
5761
+ report.failedStep = "retired_reclaim";
5762
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: retired FTS table reclaim failed", report, err);
5763
+ }
5764
+ }
5765
+ }
5766
+ try {
5767
+ for (const name of await this._retiredList()) {
5768
+ for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
5769
+ if (await this.sourceTableExists(`${name}${sfx}`)) await this.db.runAsync(`DELETE FROM ${name}${sfx}`);
5770
+ }
5771
+ if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
5772
+ emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
5773
+ }
5774
+ } catch (err) {
5775
+ report.failedStep = "retired_reclaim";
5776
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: module-less shadow-table clear failed", report, err);
5777
+ }
5778
+ }
5779
+ /** Retired list straight from metadata (same key Fts5IndexStrategy maintains), independent of the active strategy. */
5780
+ async _retiredList() {
5781
+ let raw;
5782
+ try {
5783
+ raw = JSON.parse(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY) ?? "[]");
5784
+ } catch {
5785
+ return [];
5786
+ }
5787
+ return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
5788
+ }
5789
+ sourceTableExists(name) {
5790
+ return this.metadataRepo.tableExists(name);
5791
+ }
5792
+ /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
5793
+ async _eraseSyncEntries(entityId, ids, report) {
5794
+ let ok = false;
5795
+ try {
5796
+ ok = await this.searchService.syncEntries(entityId, ids);
5797
+ } catch (err) {
5798
+ report.failedStep = "index_sync";
5799
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId})`, report, err);
5800
+ }
5801
+ if (!ok) {
5802
+ report.failedStep = "index_sync";
5803
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId}): ledger drain failed`, report);
5804
+ }
5805
+ }
5806
+ /** Step 7: FTS optimize on both FTS tables, after syncEntries. */
5807
+ async _eraseOptimize(report) {
5808
+ try {
5809
+ await this.searchService.optimizeSurfaced();
5810
+ } catch (err) {
5811
+ report.failedStep = "optimize";
5812
+ throw new EraseStepError("erase_optimize_failed", "erase stopped at step 7: FTS optimize failed", report, err);
5813
+ }
5814
+ }
5404
5815
  async runLibrarian(entityId, options) {
5405
5816
  this.jobManager.acquireLock("librarian", entityId);
5406
5817
  try {
@@ -5521,6 +5932,9 @@ var MaintenanceService = class {
5521
5932
  if (params.includeEvents && !params.clearAll) {
5522
5933
  throw new Error("forget() includeEvents requires clearAll: true");
5523
5934
  }
5935
+ if (params.includeChain && (params.entryId === void 0 || params.clearAll || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
5936
+ throw new Error("forget() includeChain composes only with entryId");
5937
+ }
5524
5938
  if (opts?.dryRun === true) {
5525
5939
  return this.forgetDryRun(entityId, params);
5526
5940
  }
@@ -5530,6 +5944,8 @@ var MaintenanceService = class {
5530
5944
  let deletedEntries = 0;
5531
5945
  let deletedTasks = 0;
5532
5946
  let deletedEvents = 0;
5947
+ let chainIds = [];
5948
+ let chainTruncated = false;
5533
5949
  const deletedEntryIds = [];
5534
5950
  const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
5535
5951
  await this.db.withTransactionAsync(async (tx) => {
@@ -5566,6 +5982,12 @@ var MaintenanceService = class {
5566
5982
  if (params.entryId) {
5567
5983
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
5568
5984
  if (entryId) deletedEntryIds.push(entryId);
5985
+ if (entryId && params.includeChain) {
5986
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, entryId, HISTORY_MAX_DEPTH, tx);
5987
+ chainIds = walk.ids.filter((id) => id !== entryId);
5988
+ chainTruncated = walk.truncated;
5989
+ for (const id of chainIds) deletedEntryIds.push(id);
5990
+ }
5569
5991
  }
5570
5992
  if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
5571
5993
  const docs = `${this.prefix}source_documents`;
@@ -5591,6 +6013,9 @@ var MaintenanceService = class {
5591
6013
  sourceRefIndexPromise ?? Promise.resolve(void 0)
5592
6014
  ]);
5593
6015
  if (entryResult) deletedEntries++;
6016
+ for (const id of chainIds) {
6017
+ if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
6018
+ }
5594
6019
  if (taskResult) deletedTasks++;
5595
6020
  deletedEntries += refResult;
5596
6021
  }
@@ -5644,7 +6069,17 @@ var MaintenanceService = class {
5644
6069
  });
5645
6070
  }
5646
6071
  }
5647
- if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
6072
+ if (!params.clearAll) {
6073
+ const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
6074
+ if (params.includeChain) {
6075
+ base.chainEntryIds = chainIds;
6076
+ if (chainTruncated) {
6077
+ base.truncated = true;
6078
+ base.notice = CHAIN_TRUNCATED_NOTICE;
6079
+ }
6080
+ }
6081
+ return base;
6082
+ }
5648
6083
  return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
5649
6084
  } finally {
5650
6085
  this.jobManager.releaseLock("forget", entityId);
@@ -5710,8 +6145,25 @@ var MaintenanceService = class {
5710
6145
  * (the spec keeps dry-run narrow).
5711
6146
  */
5712
6147
  async forgetDryRun(entityId, params) {
6148
+ if (params.entryId !== void 0 && params.includeChain && params.taskId === void 0) {
6149
+ const id = await this.entryRepo.findIdById(params.entryId, entityId);
6150
+ if (!id) return { deleted: { entries: 0, tasks: 0 }, chainEntryIds: [] };
6151
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, id, HISTORY_MAX_DEPTH);
6152
+ const chainEntryIds = walk.ids.filter((c) => c !== id);
6153
+ const all = [id, ...chainEntryIds];
6154
+ const live = await this.db.getFirstAsync(
6155
+ `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND id IN (${all.map(() => "?").join(",")})`,
6156
+ [entityId, ...all]
6157
+ );
6158
+ const out = { deleted: { entries: live?.n ?? 0, tasks: 0 }, chainEntryIds };
6159
+ if (walk.truncated) {
6160
+ out.truncated = true;
6161
+ out.notice = CHAIN_TRUNCATED_NOTICE;
6162
+ }
6163
+ return out;
6164
+ }
5713
6165
  if (params.entryId !== void 0 || params.taskId !== void 0) {
5714
- throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors; use sourceRef/sourceHash or clearAll");
6166
+ throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors (entryId is accepted only with includeChain); use sourceRef/sourceHash or clearAll");
5715
6167
  }
5716
6168
  if (params.clearAll) {
5717
6169
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
@@ -7564,6 +8016,61 @@ var _SearchService = class _SearchService {
7564
8016
  this.syncChain = work;
7565
8017
  return work;
7566
8018
  }
8019
+ /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
8020
+ chainSurfaced(fn) {
8021
+ const work = this.syncChain.then(fn);
8022
+ this.syncChain = work.then(() => void 0, () => void 0);
8023
+ return work;
8024
+ }
8025
+ /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
8026
+ hasStrictDrain() {
8027
+ const s = this.indexStrategy;
8028
+ return typeof s.drainPassagesStrict === "function" && typeof s.drainEntriesLedgerStrict === "function";
8029
+ }
8030
+ /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
8031
+ drainPassagesSurfaced() {
8032
+ const s = this.indexStrategy;
8033
+ if (!s.drainPassagesStrict) return this.chainSurfaced(async () => {
8034
+ });
8035
+ return this.chainSurfaced(() => s.drainPassagesStrict());
8036
+ }
8037
+ /** Erase step 4: listed retired FTS tables (empty for strategies without any). */
8038
+ async retiredTables() {
8039
+ const s = this.indexStrategy;
8040
+ return s.retiredTables ? s.retiredTables() : [];
8041
+ }
8042
+ /** True when the active strategy can DROP retired tables (FTS5); false for MiniSearch / Unavailable. */
8043
+ canReclaimRetired() {
8044
+ return typeof this.indexStrategy.reclaimRetiredToCompletion === "function";
8045
+ }
8046
+ /** Erase step 3: store-wide entries-side fts_pending drain on the sync chain, no deadline, errors surfaced. */
8047
+ drainEntriesLedgerSurfaced() {
8048
+ const s = this.indexStrategy;
8049
+ if (!s.drainEntriesLedgerStrict) return this.chainSurfaced(async () => {
8050
+ });
8051
+ return this.chainSurfaced(() => s.drainEntriesLedgerStrict());
8052
+ }
8053
+ /** Erase step 4: reclaim retired tables to completion; errors surfaced. */
8054
+ reclaimRetiredSurfaced() {
8055
+ const s = this.indexStrategy;
8056
+ if (!s.reclaimRetiredToCompletion) return this.chainSurfaced(async () => {
8057
+ });
8058
+ return this.chainSurfaced(() => s.reclaimRetiredToCompletion());
8059
+ }
8060
+ /** Erase step 7: FTS optimize on every FTS table that exists. */
8061
+ optimizeSurfaced() {
8062
+ const s = this.indexStrategy;
8063
+ if (!s.optimizeFts) return this.chainSurfaced(async () => {
8064
+ });
8065
+ return this.chainSurfaced(() => s.optimizeFts());
8066
+ }
8067
+ /** `erase({ rebuild: true })` wiring point; the orchestration (T6) calls it. */
8068
+ rebuildSurfaced() {
8069
+ const s = this.indexStrategy;
8070
+ if (!s.rebuildForErase) return this.chainSurfaced(async () => {
8071
+ });
8072
+ return this.chainSurfaced(() => s.rebuildForErase());
8073
+ }
7567
8074
  /**
7568
8075
  * Stored-source passage search for ONE entity (spec source-store section 7:
7569
8076
  * ranking and caps are per entity). Rides the active strategy; a strategy
@@ -7719,7 +8226,7 @@ var JobManager = class {
7719
8226
  this.statusSubscribers = /* @__PURE__ */ new Map();
7720
8227
  /**
7721
8228
  * Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
7722
- * Excludes 'ingest' | 'global_reembed' | 'global_import', which those
8229
+ * Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
7723
8230
  * methods already handle via explicit if/else branches before reaching
7724
8231
  * this table.
7725
8232
  */
@@ -7788,6 +8295,9 @@ var JobManager = class {
7788
8295
  _globalReembedKey() {
7789
8296
  return `${this.prefix}:reembed`;
7790
8297
  }
8298
+ _eraseKey() {
8299
+ return `${this.prefix}:erase`;
8300
+ }
7791
8301
  _importKey(entityId) {
7792
8302
  return `${this.prefix}:${entityId}:import`;
7793
8303
  }
@@ -7868,11 +8378,19 @@ var JobManager = class {
7868
8378
  _isIngestActiveFor(entityId) {
7869
8379
  return this.activeIngestJobs.has(entityId);
7870
8380
  }
7871
- acquireLock(operation, entityId, sourceRef) {
8381
+ /**
8382
+ * `owner` is the fourth parameter (the third, `sourceRef`, is ingest-only).
8383
+ * `'erase'` marks the erase() pipeline's own per-entity prune, the only
8384
+ * operation exempt from the universal erase pre-check below.
8385
+ */
8386
+ acquireLock(operation, entityId, sourceRef, owner = "host") {
7872
8387
  let blockingOperation = null;
7873
8388
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
7874
8389
  throw new WikiBusyError("import", "*");
7875
8390
  }
8391
+ if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
8392
+ throw new WikiBusyError("erase", "*");
8393
+ }
7876
8394
  switch (operation) {
7877
8395
  case "prune":
7878
8396
  if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
@@ -7921,6 +8439,18 @@ var JobManager = class {
7921
8439
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
7922
8440
  else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7923
8441
  break;
8442
+ case "erase":
8443
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) blockingOperation = "erase";
8444
+ else if (this._isAnyMaintenanceActiveWithSuffix(":reembed")) blockingOperation = "reembed";
8445
+ else if (this._isAnyMaintenanceActiveWithSuffix(":prune")) blockingOperation = "prune";
8446
+ else if (this._isAnyMaintenanceActiveWithSuffix(":librarian")) blockingOperation = "librarian";
8447
+ else if (this._isAnyMaintenanceActiveWithSuffix(":heal")) blockingOperation = "heal";
8448
+ else if (this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill")) blockingOperation = "ontologyBackfill";
8449
+ else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
8450
+ else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
8451
+ else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
8452
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
8453
+ break;
7924
8454
  case "import":
7925
8455
  case "forget": {
7926
8456
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
@@ -7965,7 +8495,7 @@ var JobManager = class {
7965
8495
  if (blockingOperation) {
7966
8496
  throw new WikiBusyError(
7967
8497
  blockingOperation,
7968
- operation === "global_reembed" || operation === "global_import" ? "*" : entityId
8498
+ operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
7969
8499
  );
7970
8500
  }
7971
8501
  if (operation === "ingest") {
@@ -7974,6 +8504,8 @@ var JobManager = class {
7974
8504
  this.activeMaintenanceJobs.add(this._globalReembedKey());
7975
8505
  } else if (operation === "global_import") {
7976
8506
  this.activeMaintenanceJobs.add(this._globalImportKey());
8507
+ } else if (operation === "erase") {
8508
+ this.activeMaintenanceJobs.add(this._eraseKey());
7977
8509
  } else {
7978
8510
  this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
7979
8511
  }
@@ -7986,6 +8518,8 @@ var JobManager = class {
7986
8518
  this.activeMaintenanceJobs.delete(this._globalReembedKey());
7987
8519
  } else if (operation === "global_import") {
7988
8520
  this.activeMaintenanceJobs.delete(this._globalImportKey());
8521
+ } else if (operation === "erase") {
8522
+ this.activeMaintenanceJobs.delete(this._eraseKey());
7989
8523
  } else {
7990
8524
  this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
7991
8525
  }
@@ -7997,7 +8531,10 @@ var JobManager = class {
7997
8531
  */
7998
8532
  isBlocked(operation, entityId) {
7999
8533
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
8534
+ if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
8000
8535
  switch (operation) {
8536
+ case "erase":
8537
+ return this.activeMaintenanceJobs.has(this._eraseKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget") || this._isAnyMaintenanceActiveWithSuffix(":store");
8001
8538
  case "librarian":
8002
8539
  case "heal":
8003
8540
  case "ontologyBackfill":
@@ -8031,6 +8568,7 @@ var JobManager = class {
8031
8568
  */
8032
8569
  tryAcquireAutoHealLock(entityId) {
8033
8570
  if (this.isAnyReembedActive()) return false;
8571
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
8034
8572
  const healKey = this._healKey(entityId);
8035
8573
  if (this.activeMaintenanceJobs.has(healKey)) return false;
8036
8574
  this.activeMaintenanceJobs.add(healKey);
@@ -8074,6 +8612,7 @@ var JobManager = class {
8074
8612
  * Validates all entities before acquiring any lock (same as current importDump semantics).
8075
8613
  */
8076
8614
  acquireImportLocks(entityIds) {
8615
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
8077
8616
  for (const entityId of entityIds) {
8078
8617
  if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
8079
8618
  if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);