@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.
package/dist/testing.js CHANGED
@@ -162,8 +162,8 @@ var WikiInvalidReadOptions = class _WikiInvalidReadOptions extends Error {
162
162
  }
163
163
  };
164
164
  var WikiSupersedeError = class _WikiSupersedeError extends Error {
165
- constructor(reason) {
166
- super(`supersede() rejected: ${reason}`);
165
+ constructor(reason, verb = "supersede()") {
166
+ super(`${verb} rejected: ${reason}`);
167
167
  this.code = "WIKI_SUPERSEDE_REJECTED";
168
168
  this.name = "WikiSupersedeError";
169
169
  this.reason = reason;
@@ -724,6 +724,16 @@ 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_fts_orphan_cleared: "info",
732
+ erase_retired_remaining: "error",
733
+ erase_tombstones_remaining: "error",
734
+ erase_retired_read_failed: "error",
735
+ erase_registry_sweep_skipped: "info",
736
+ import_tombstone_skipped: "info",
727
737
  event_created_at_clamped: "warn",
728
738
  event_created_at_restamped: "info",
729
739
  external_deletion_pending: "warn",
@@ -759,6 +769,16 @@ var MESSAGE = {
759
769
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
760
770
  read_budget: "A read was packed to a token budget.",
761
771
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
772
+ 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.",
773
+ erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
774
+ 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.",
775
+ 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.",
776
+ erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
777
+ erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
778
+ erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
779
+ erase_entity_skipped: "Erase skipped an entity because another operation held its prune lock.",
780
+ erase_registry_sweep_skipped: "Erase skipped the source_ref_index tombstone sweep because the table does not exist (pre-v9 store).",
781
+ 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
782
  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
783
  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
784
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
@@ -1251,6 +1271,12 @@ function entitySummaryMetaKey(entityId) {
1251
1271
  return `entity_summary:${entityId}`;
1252
1272
  }
1253
1273
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1274
+ var CheckpointIncompleteError = class extends Error {
1275
+ constructor() {
1276
+ super(...arguments);
1277
+ this.code = "erase_checkpoint_incomplete";
1278
+ }
1279
+ };
1254
1280
  function generateId(prefix = "") {
1255
1281
  if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1256
1282
  return prefix + crypto.randomUUID().replace(/-/g, "").substring(0, 24);
@@ -1656,7 +1682,8 @@ var ImportExportService = class {
1656
1682
  this.vectorRemoval = vectorRemoval;
1657
1683
  this.prefix = prefix;
1658
1684
  }
1659
- async exportDump(entityIds) {
1685
+ async exportDump(entityIds, opts) {
1686
+ const includeForgotten = opts?.includeForgotten === true;
1660
1687
  let ids;
1661
1688
  if (entityIds && entityIds.length > 0) {
1662
1689
  ids = Array.from(new Set(entityIds));
@@ -1677,7 +1704,7 @@ var ImportExportService = class {
1677
1704
  const batchResults = await Promise.all(
1678
1705
  batch.map(
1679
1706
  async (id) => {
1680
- const bundle = await this.getFullBundle(id, { includeBlobs: true });
1707
+ const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
1681
1708
  const storedSources = await this.exportStoredSources(id);
1682
1709
  return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
1683
1710
  }
@@ -1783,10 +1810,11 @@ var ImportExportService = class {
1783
1810
  }
1784
1811
  }
1785
1812
  async getFullBundle(entityId, opts) {
1813
+ const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
1786
1814
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
1787
1815
  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),
1816
+ opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
1817
+ this.taskRepo.findAllByEntityId(entityId, void 0, incl),
1790
1818
  this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
1791
1819
  this.edgeRepo.getByEntityId(entityId),
1792
1820
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
@@ -1822,12 +1850,15 @@ var ImportExportService = class {
1822
1850
  const skippedSources = [];
1823
1851
  const refusalDiagnostics = [];
1824
1852
  const upsertedFactIds = /* @__PURE__ */ new Set();
1853
+ const liveEmbedFactIds = /* @__PURE__ */ new Set();
1825
1854
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
1826
1855
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
1827
1856
  const preservedBlobDims = /* @__PURE__ */ new Set();
1828
1857
  const softDeletedFactIds = [];
1858
+ const softDeletedTaskIds = [];
1829
1859
  const clippedTextByFactId = /* @__PURE__ */ new Map();
1830
1860
  let clampedEvents = 0;
1861
+ let tombstoneSkipped = 0;
1831
1862
  const restamped = { behind_watermark: 0, invalid: 0 };
1832
1863
  await this.db.withTransactionAsync(async (tx) => {
1833
1864
  if (!merge) {
@@ -1838,8 +1869,9 @@ var ImportExportService = class {
1838
1869
  tx,
1839
1870
  false
1840
1871
  );
1841
- softDeletedFactIds.push(...deletedLiveFactIds);
1872
+ for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
1842
1873
  await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
1874
+ for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
1843
1875
  await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
1844
1876
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
1845
1877
  await this.metadataRepo.deleteCheckpoint(entityId, tx);
@@ -1849,6 +1881,8 @@ var ImportExportService = class {
1849
1881
  } else if (!merge) {
1850
1882
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
1851
1883
  }
1884
+ const wipedByThisImport = new Set(softDeletedFactIds);
1885
+ const wipedTasksByThisImport = new Set(softDeletedTaskIds);
1852
1886
  const factIds = bundle.facts.map((fact) => fact.id);
1853
1887
  const existingFactsById = /* @__PURE__ */ new Map();
1854
1888
  const existingFacts = await this.entryRepo.findExistingMetadataByIds(
@@ -1924,11 +1958,16 @@ var ImportExportService = class {
1924
1958
  );
1925
1959
  continue;
1926
1960
  }
1927
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
1961
+ if (existing.deleted_at != null && fact.deleted_at == null && !wipedByThisImport.has(fact.id)) {
1962
+ tombstoneSkipped++;
1963
+ continue;
1964
+ }
1965
+ if (merge && safeUpdatedAt <= existing.updated_at && fact.deleted_at == null) continue;
1928
1966
  }
1929
1967
  const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
1930
1968
  const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
1931
- clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody });
1969
+ const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
1970
+ clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
1932
1971
  let normalizedSourceRef = null;
1933
1972
  if (fact.source_ref !== null && fact.source_ref !== void 0) {
1934
1973
  normalizedSourceRef = normalizeSourceRef(fact.source_ref);
@@ -1995,15 +2034,22 @@ var ImportExportService = class {
1995
2034
  }, tx, { outbox: false });
1996
2035
  if (blobData != null) {
1997
2036
  factsWithPreservedBlob.set(fact.id, blobData);
1998
- if (!fact.deleted_at) preservedBlobDims.add(blobData.byteLength / 4);
2037
+ if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
1999
2038
  }
2000
2039
  existingFactsById.set(fact.id, {
2001
2040
  id: fact.id,
2002
2041
  entity_id: entityId,
2003
- updated_at: safeUpdatedAt
2042
+ updated_at: safeUpdatedAt,
2043
+ deleted_at: fact.deleted_at ?? null
2004
2044
  });
2045
+ wipedByThisImport.delete(fact.id);
2005
2046
  upsertedFactIds.add(fact.id);
2006
- if (fact.deleted_at) upsertedDeletedFactIds.add(fact.id);
2047
+ if (fact.deleted_at != null) {
2048
+ upsertedDeletedFactIds.add(fact.id);
2049
+ liveEmbedFactIds.delete(fact.id);
2050
+ } else {
2051
+ liveEmbedFactIds.add(fact.id);
2052
+ }
2007
2053
  }
2008
2054
  const taskIds = bundle.tasks.map((task) => task.id);
2009
2055
  const existingTasksById = /* @__PURE__ */ new Map();
@@ -2027,7 +2073,11 @@ var ImportExportService = class {
2027
2073
  );
2028
2074
  continue;
2029
2075
  }
2030
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
2076
+ if (existing.deleted_at != null && task.deleted_at == null && !wipedTasksByThisImport.has(task.id)) {
2077
+ tombstoneSkipped++;
2078
+ continue;
2079
+ }
2080
+ if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
2031
2081
  }
2032
2082
  await this.taskRepo.upsertForImport(
2033
2083
  {
@@ -2060,8 +2110,10 @@ var ImportExportService = class {
2060
2110
  existingTasksById.set(task.id, {
2061
2111
  id: task.id,
2062
2112
  entity_id: entityId,
2063
- updated_at: safeUpdatedAt
2113
+ updated_at: safeUpdatedAt,
2114
+ deleted_at: task.deleted_at ?? null
2064
2115
  });
2116
+ wipedTasksByThisImport.delete(task.id);
2065
2117
  }
2066
2118
  const now = Date.now();
2067
2119
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
@@ -2101,6 +2153,15 @@ var ImportExportService = class {
2101
2153
  await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
2102
2154
  });
2103
2155
  for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
2156
+ if (tombstoneSkipped > 0) {
2157
+ emitDiagnostic(this.options, {
2158
+ code: "import_tombstone_skipped",
2159
+ operation: "importDump",
2160
+ trigger: "call",
2161
+ entityId,
2162
+ detail: { count: tombstoneSkipped }
2163
+ });
2164
+ }
2104
2165
  if (clampedEvents > 0) {
2105
2166
  emitDiagnostic(this.options, {
2106
2167
  code: "event_created_at_clamped",
@@ -2126,28 +2187,28 @@ var ImportExportService = class {
2126
2187
  } else {
2127
2188
  await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
2128
2189
  }
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);
2190
+ for (const id of liveEmbedFactIds) {
2191
+ if (!factsWithPreservedBlob.has(id)) {
2192
+ const clipped = clippedTextByFactId.get(id);
2132
2193
  const embedded = await this.embeddingService.embedFact({
2133
- id: fact.id,
2194
+ id,
2134
2195
  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 : []
2196
+ title: clipped?.title ?? "",
2197
+ body: clipped?.body ?? "",
2198
+ tags: clipped?.tags ?? []
2138
2199
  }, { operation: "importDump", trigger: "call" });
2139
2200
  if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
2140
2201
  try {
2141
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
2202
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
2142
2203
  } catch (hookErr) {
2143
2204
  console.warn(
2144
- `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
2205
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
2145
2206
  hookErr
2146
2207
  );
2147
2208
  this.embeddingService.reportHookFailed(
2148
2209
  { operation: "importDump", trigger: "call" },
2149
2210
  entityId,
2150
- fact.id
2211
+ id
2151
2212
  );
2152
2213
  }
2153
2214
  }
@@ -2155,7 +2216,7 @@ var ImportExportService = class {
2155
2216
  }
2156
2217
  for (const fact of bundle.facts) {
2157
2218
  const blobData = factsWithPreservedBlob.get(fact.id);
2158
- if (blobData && !fact.deleted_at && upsertedFactIds.has(fact.id)) {
2219
+ if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
2159
2220
  try {
2160
2221
  const float32Vector = new Float32Array(
2161
2222
  blobData.buffer,
@@ -3533,6 +3594,128 @@ function classifierStateForFact(fact) {
3533
3594
  return parts.join("\n\n");
3534
3595
  }
3535
3596
 
3597
+ // src/utils/temporal.ts
3598
+ function liveAtSql(mode, alias = "") {
3599
+ const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3600
+ return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3601
+ }
3602
+ function assertEpochMs(name, v) {
3603
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3604
+ throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3605
+ }
3606
+ return Math.trunc(v);
3607
+ }
3608
+
3609
+ // src/services/TemporalService.ts
3610
+ var HISTORY_MAX_DEPTH = 100;
3611
+ var TemporalService = class {
3612
+ constructor(db, options, entryRepo, searchService, embeddingService) {
3613
+ this.db = db;
3614
+ this.options = options;
3615
+ this.entryRepo = entryRepo;
3616
+ this.searchService = searchService;
3617
+ this.embeddingService = embeddingService;
3618
+ }
3619
+ /**
3620
+ * Link `oldId` → `newId` inside the caller's transaction. `newId` must
3621
+ * already exist. Throws WikiSupersedeError on any rule violation; the
3622
+ * caller's transaction then rolls back.
3623
+ */
3624
+ async supersedeInTx(tx, entityId, oldId, newId, t, now) {
3625
+ const old = await this.entryRepo.findTemporalRow(oldId, tx);
3626
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
3627
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3628
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3629
+ if (old.valid_to != null && old.valid_to <= Math.max(now, Date.now())) throw new WikiSupersedeError("already_expired");
3630
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
3631
+ if (newId === oldId) throw new WikiSupersedeError("cycle");
3632
+ const repl = await this.entryRepo.findTemporalRow(newId, tx);
3633
+ if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
3634
+ if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3635
+ if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3636
+ const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
3637
+ if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
3638
+ await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
3639
+ if (repl.valid_from == null) {
3640
+ await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
3641
+ }
3642
+ }
3643
+ async supersede(entityId, oldId, replacement, options) {
3644
+ const now = Date.now();
3645
+ const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
3646
+ let created = null;
3647
+ if (typeof replacement !== "string") {
3648
+ if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
3649
+ throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
3650
+ }
3651
+ created = {
3652
+ id: generateId("fact_"),
3653
+ entity_id: entityId,
3654
+ title: replacement.title,
3655
+ body: replacement.body,
3656
+ tags: Array.isArray(replacement.tags) ? replacement.tags : [],
3657
+ confidence: replacement.confidence ?? "certain",
3658
+ source_type: replacement.source_type ?? "user_stated",
3659
+ source_hash: null,
3660
+ source_ref: null,
3661
+ created_at: now,
3662
+ updated_at: now,
3663
+ last_accessed_at: null,
3664
+ access_count: 0,
3665
+ deleted_at: null
3666
+ };
3667
+ }
3668
+ const newId = typeof replacement === "string" ? replacement : created.id;
3669
+ const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
3670
+ await this.db.withTransactionAsync(async (tx) => {
3671
+ if (created) {
3672
+ await this.entryRepo.upsert(created, tx);
3673
+ if (newValidFrom !== void 0) {
3674
+ await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
3675
+ }
3676
+ }
3677
+ await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
3678
+ });
3679
+ await this.searchService.syncEntries(entityId, [oldId, newId]);
3680
+ if (created) {
3681
+ await this.embeddingService.embedFact(
3682
+ { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
3683
+ { operation: "supersede", trigger: "call" }
3684
+ );
3685
+ }
3686
+ this.searchService.evictCache(entityId);
3687
+ return { newId };
3688
+ }
3689
+ /**
3690
+ * End `factId`'s validity without a replacement — an archive, not a
3691
+ * deletion (INTENT rule 12, spec specs/expire). Sets `valid_to` only.
3692
+ */
3693
+ async expire(entityId, factId, options) {
3694
+ const t = options?.at === void 0 ? Date.now() : assertEpochMs("options.at", options.at);
3695
+ await this.db.withTransactionAsync(async (tx) => {
3696
+ const old = await this.entryRepo.findTemporalRow(factId, tx);
3697
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found", "expire()");
3698
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "expire()");
3699
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded", "expire()");
3700
+ if (old.valid_to != null) throw new WikiSupersedeError("already_expired", "expire()");
3701
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "expire()");
3702
+ const start = old.valid_from ?? old.created_at;
3703
+ if (t <= start) throw new WikiSupersedeError("invalid_interval", "expire()");
3704
+ const changes = await this.entryRepo.setTemporal(factId, entityId, { valid_to: t }, tx);
3705
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "expire()");
3706
+ });
3707
+ await this.searchService.syncEntries(entityId, [factId]);
3708
+ this.searchService.evictCache(entityId);
3709
+ }
3710
+ async history(entityId, factId) {
3711
+ const start = await this.entryRepo.findTemporalRow(factId);
3712
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
3713
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
3714
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
3715
+ 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));
3716
+ }
3717
+ };
3718
+
3536
3719
  // src/utils/engineDefaults.ts
3537
3720
  var DEFAULT_LIBRARIAN_STRATEGY = "ops";
3538
3721
  var DEFAULT_MAINTENANCE_MODE = "deferred";
@@ -3578,18 +3761,6 @@ function removalGate(options) {
3578
3761
  return "none";
3579
3762
  }
3580
3763
 
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
3764
  // src/repositories/EdgeRepository.ts
3594
3765
  var CONFIDENCE_RANK = {
3595
3766
  tentative: 0,
@@ -3951,14 +4122,31 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
3951
4122
 
3952
4123
  // src/services/search/fts5Sql.ts
3953
4124
  var FTS5_STATE_KEY = "fts5_index_state";
4125
+ var FTS5_RETIRED_TABLES_KEY = "fts5_retired_tables";
4126
+ function isRetiredTableName(p, name) {
4127
+ return typeof name === "string" && name.startsWith(`${p}entries_fts_retired_`) && /^\d+$/.test(name.slice(`${p}entries_fts_retired_`.length));
4128
+ }
3954
4129
  var FTS5_REBUILD_WM_KEY = "fts5_rebuild_wm";
3955
4130
  var FTS5_REBUILD_SNAPSHOT_KEY = "fts5_rebuild_snapshot";
3956
4131
  var FTS5_SWEEP_CURSOR_KEY = "fts5_orphan_sweep_cursor";
4132
+ function fts5TriggerNames(prefix) {
4133
+ return [`${prefix}entries_fts_ai`, `${prefix}entries_fts_au`, `${prefix}entries_fts_ad`];
4134
+ }
3957
4135
  function fts5PendingIndexesDdl(p) {
3958
4136
  return `
3959
4137
  CREATE INDEX IF NOT EXISTS ${p}fts_pending_id ON ${p}fts_pending(id);
3960
4138
  CREATE INDEX IF NOT EXISTS ${p}fts_pending_entity ON ${p}fts_pending(entity_id);`;
3961
4139
  }
4140
+ function fts5LedgerDropSql(p) {
4141
+ return [
4142
+ ...fts5TriggerNames(p).map((n) => `DROP TRIGGER IF EXISTS ${n};`),
4143
+ `DROP TABLE IF EXISTS ${p}fts_pending;`,
4144
+ `DROP TABLE IF EXISTS ${p}fts_map;`
4145
+ ].join("\n");
4146
+ }
4147
+ function passageFtsTriggerNames(p) {
4148
+ return [`${p}source_passages_fts_ai`, `${p}source_passages_fts_ad`];
4149
+ }
3962
4150
 
3963
4151
  // src/db/migrations.ts
3964
4152
  var MIGRATIONS = [
@@ -4821,94 +5009,6 @@ async function runResolve(deps, ctx, ambiguous) {
4821
5009
  return out;
4822
5010
  }
4823
5011
 
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
5012
  // src/services/librarian/ops/apply.ts
4913
5013
  function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
4914
5014
  if (candidate.sourceEventId === null) return null;
@@ -5174,6 +5274,7 @@ async function runLibrarianStrategy(deps, ctx) {
5174
5274
  }
5175
5275
 
5176
5276
  // src/services/MaintenanceService.ts
5277
+ 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
5278
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
5178
5279
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
5179
5280
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -5222,7 +5323,21 @@ var formatSkipError = (err) => {
5222
5323
  }
5223
5324
  return base;
5224
5325
  };
5225
- var MaintenanceService = class {
5326
+ function eraseRuntime() {
5327
+ const g = globalThis;
5328
+ if (g.process?.versions?.node) return `node ${g.process.versions.node}`;
5329
+ return g.HermesInternal ? "hermes" : "unknown";
5330
+ }
5331
+ var EraseStepError = class extends Error {
5332
+ constructor(code, message, report, cause) {
5333
+ super(message);
5334
+ this.code = code;
5335
+ this.report = report;
5336
+ this.name = "EraseStepError";
5337
+ if (cause !== void 0) this.cause = cause;
5338
+ }
5339
+ };
5340
+ var _MaintenanceService = class _MaintenanceService {
5226
5341
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
5227
5342
  this.db = db;
5228
5343
  this.prefix = prefix;
@@ -5242,7 +5357,15 @@ var MaintenanceService = class {
5242
5357
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
5243
5358
  }
5244
5359
  async runPrune(entityId, options) {
5245
- this.jobManager.acquireLock("prune", entityId);
5360
+ return this._runPrune(entityId, options, "host");
5361
+ }
5362
+ /**
5363
+ * Shared prune body. `owner: 'erase'` lets erase()'s own per-entity prune
5364
+ * through the universal erase fence in JobManager; the public `runPrune`
5365
+ * always passes `'host'`.
5366
+ */
5367
+ async _runPrune(entityId, options, owner) {
5368
+ this.jobManager.acquireLock("prune", entityId, void 0, owner);
5246
5369
  try {
5247
5370
  const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
5248
5371
  const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
@@ -5273,8 +5396,9 @@ var MaintenanceService = class {
5273
5396
  }
5274
5397
  }
5275
5398
  if (retainSoftDeletedFor !== null) {
5276
- const cutoff = now - retainSoftDeletedFor * 864e5;
5277
- const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
5399
+ const softDeletedAll = options?.softDeletedCutoff === "all";
5400
+ const cutoff = softDeletedAll ? 0 : options?.softDeletedCutoff ?? now - retainSoftDeletedFor * 864e5;
5401
+ const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff, void 0, { noCutoff: softDeletedAll });
5278
5402
  const prunableIds = entriesToDelete.map((r) => r.id);
5279
5403
  const vr = this.vectorRemoval;
5280
5404
  const vrRepo = this.vectorRemovalRepo;
@@ -5320,7 +5444,7 @@ var MaintenanceService = class {
5320
5444
  }
5321
5445
  if (deletable.length > 0) {
5322
5446
  const deletedIds = [];
5323
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
5447
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds, noCutoff: softDeletedAll });
5324
5448
  if (hookLedger) {
5325
5449
  const gone = new Set(deletedIds);
5326
5450
  const skipped = deletable.filter((id) => !gone.has(id));
@@ -5335,7 +5459,7 @@ var MaintenanceService = class {
5335
5459
  else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
5336
5460
  }
5337
5461
  }
5338
- deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
5462
+ deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
5339
5463
  });
5340
5464
  if (hookLedger) {
5341
5465
  const keptSet = new Set(kept);
@@ -5380,12 +5504,20 @@ var MaintenanceService = class {
5380
5504
  }
5381
5505
  }
5382
5506
  }
5507
+ let vacuumCheckpointErr;
5383
5508
  if (vacuum) {
5384
- await resetNormalizeWatermarks(this.metadataRepo);
5385
- await this.metadataRepo.vacuum();
5386
- await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5509
+ try {
5510
+ await this._wrappedVacuum();
5511
+ } catch (err) {
5512
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
5513
+ vacuumCheckpointErr = err;
5514
+ }
5387
5515
  }
5516
+ if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
5388
5517
  await this.searchService.syncEntries(entityId, syncedIds);
5518
+ if (prunePartial && vacuumCheckpointErr) {
5519
+ emitDiagnostic(this.options, { code: "prune_checkpoint_incomplete", operation: "prune", trigger: "call", entityId, detail: { reason: vacuumCheckpointErr.message } });
5520
+ }
5389
5521
  if (prunePartial) {
5390
5522
  throw new PrunePartialFailureError(
5391
5523
  deletedEntries,
@@ -5396,11 +5528,422 @@ var MaintenanceService = class {
5396
5528
  deletedEvents
5397
5529
  );
5398
5530
  }
5531
+ if (vacuumCheckpointErr) throw vacuumCheckpointErr;
5399
5532
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
5400
5533
  } finally {
5401
5534
  this.jobManager.releaseLock("prune", entityId);
5402
5535
  }
5403
5536
  }
5537
+ /** Shared by runPrune and erase step 5. */
5538
+ async _wrappedVacuum() {
5539
+ await resetNormalizeWatermarks(this.metadataRepo);
5540
+ let checkpointErr;
5541
+ try {
5542
+ await this.metadataRepo.vacuum();
5543
+ } catch (err) {
5544
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
5545
+ checkpointErr = err;
5546
+ }
5547
+ await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5548
+ if (checkpointErr) throw checkpointErr;
5549
+ }
5550
+ /**
5551
+ * Erase core (forget-erasure spec §2, steps 0 / 1 / 1b). Thin entry: T6
5552
+ * completes the pipeline (FTS, VACUUM, checkpoint, sync). Never reports a
5553
+ * success it cannot verify: a failed step throws {@link EraseStepError}
5554
+ * carrying the partial report with `verified: false`.
5555
+ */
5556
+ async erase(opts) {
5557
+ const rebuild = opts?.rebuild === true;
5558
+ this.jobManager.acquireLock("erase", "*");
5559
+ const report = {
5560
+ verified: false,
5561
+ secureDelete: null,
5562
+ sqliteVersion: "",
5563
+ entities: [],
5564
+ holds: [],
5565
+ skipped: [],
5566
+ syncedIds: [],
5567
+ registrySweep: { skipped: false, deleted: 0 },
5568
+ retiredUndroppable: [],
5569
+ ftsOrphansCleared: [],
5570
+ failedStep: null,
5571
+ runtime: eraseRuntime(),
5572
+ steps: []
5573
+ };
5574
+ const ok = (step, outcome = "ok") => {
5575
+ report.steps.push({ step, outcome });
5576
+ };
5577
+ try {
5578
+ const readPragma = async () => (await this.db.getFirstAsync("PRAGMA secure_delete"))?.secure_delete ?? null;
5579
+ let pragma;
5580
+ try {
5581
+ pragma = await readPragma();
5582
+ if (pragma !== 1) {
5583
+ await this.db.execAsync("PRAGMA secure_delete=ON");
5584
+ pragma = await readPragma();
5585
+ }
5586
+ report.secureDelete = pragma;
5587
+ report.sqliteVersion = (await this.db.getFirstAsync("SELECT sqlite_version() AS v"))?.v ?? "";
5588
+ } catch (err) {
5589
+ report.failedStep = "secure_delete";
5590
+ throw new EraseStepError("erase_secure_delete_read_failed", "erase stopped at step 0: secure_delete pragma read failed; erasure is unverified", report, err);
5591
+ }
5592
+ if (pragma !== 1) {
5593
+ emitDiagnostic(this.options, { code: "erase_secure_delete_off", operation: "erase", trigger: "call", entityId: "" });
5594
+ report.failedStep = "secure_delete";
5595
+ throw new EraseStepError("erase_secure_delete_off", "erase stopped at step 0: secure_delete is not ON; erasure is unverified", report);
5596
+ }
5597
+ ok("secure_delete");
5598
+ try {
5599
+ report.entities = await this.metadataRepo.getDistinctEntityIds(void 0, { softDeletedAll: true });
5600
+ } catch (err) {
5601
+ report.failedStep = "prune";
5602
+ throw new EraseStepError("erase_prune_failed", "erase stopped at step 1: the entity walk failed; erasure is unverified", report, err);
5603
+ }
5604
+ const syncedByEntity = /* @__PURE__ */ new Map();
5605
+ for (const entityId of report.entities) {
5606
+ const syncedIds = [];
5607
+ syncedByEntity.set(entityId, syncedIds);
5608
+ try {
5609
+ await this._runPrune(entityId, { retainSoftDeletedFor: 0, retainEventsFor: null, vacuum: false, syncedIds, softDeletedCutoff: "all" }, "erase");
5610
+ } catch (err) {
5611
+ if (err instanceof PrunePartialFailureError) {
5612
+ report.holds.push({ entityId, deleted: err.deleted, deletedTasks: err.deletedTasks, failedAt: err.failedAt, remaining: err.remaining });
5613
+ } else if (err instanceof WikiBusyError) {
5614
+ report.skipped.push(entityId);
5615
+ emitDiagnostic(this.options, { code: "erase_entity_skipped", operation: "erase", trigger: "call", entityId });
5616
+ } else {
5617
+ report.failedStep = "prune";
5618
+ throw new EraseStepError("erase_prune_failed", `erase stopped at step 1 (entity ${entityId})`, report, err);
5619
+ }
5620
+ }
5621
+ for (const id of syncedIds) report.syncedIds.push(id);
5622
+ }
5623
+ ok("prune", report.holds.length > 0 || report.skipped.length > 0 ? "partial" : "ok");
5624
+ try {
5625
+ await this.db.withTransactionAsync(async (tx) => {
5626
+ if (await this.sourceRefIndexPresent(tx)) {
5627
+ const r = await tx.runAsync(`DELETE FROM ${this.prefix}source_ref_index WHERE deleted_at IS NOT NULL`);
5628
+ report.registrySweep = { skipped: false, deleted: r.changes };
5629
+ } else {
5630
+ report.registrySweep = { skipped: true, deleted: 0 };
5631
+ }
5632
+ });
5633
+ } catch (err) {
5634
+ report.failedStep = "registry_sweep";
5635
+ throw new EraseStepError("erase_registry_sweep_failed", "erase stopped at step 1b", report, err);
5636
+ }
5637
+ if (report.registrySweep.skipped) {
5638
+ emitDiagnostic(this.options, { code: "erase_registry_sweep_skipped", operation: "erase", trigger: "call", entityId: "" });
5639
+ }
5640
+ ok("registry_sweep", report.registrySweep.skipped ? "partial" : "ok");
5641
+ await this._eraseDrainPassages(report);
5642
+ ok("passage_drain");
5643
+ await this._eraseReclaimRetired(report);
5644
+ ok("retired_reclaim");
5645
+ try {
5646
+ await this._wrappedVacuum();
5647
+ } catch (err) {
5648
+ if (err instanceof CheckpointIncompleteError) {
5649
+ report.failedStep = "checkpoint";
5650
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 5: WAL checkpoint incomplete; erasure is unverified", report, err);
5651
+ }
5652
+ report.failedStep = "vacuum";
5653
+ 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);
5654
+ }
5655
+ ok("vacuum");
5656
+ const byEntity = /* @__PURE__ */ new Map();
5657
+ for (const e of report.entities) byEntity.set(e, []);
5658
+ for (const [entityId, ids] of syncedByEntity) byEntity.set(entityId, ids);
5659
+ for (const [entityId, ids] of byEntity) {
5660
+ if (ids.length > 0) await this._eraseSyncEntries(entityId, ids, report);
5661
+ }
5662
+ ok("index_sync");
5663
+ if (rebuild) {
5664
+ try {
5665
+ await this.searchService.rebuildSurfaced();
5666
+ } catch (err) {
5667
+ report.failedStep = "rebuild";
5668
+ throw new EraseStepError("erase_rebuild_failed", "erase stopped at step 7: FTS rebuild failed", report, err);
5669
+ }
5670
+ ok("rebuild");
5671
+ }
5672
+ await this._eraseReclaimRetired(report);
5673
+ let present;
5674
+ try {
5675
+ present = await this.db.getAllAsync(
5676
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%entries_fts_retired_%'`
5677
+ );
5678
+ } catch (err) {
5679
+ report.failedStep = "retired_reclaim";
5680
+ emitDiagnostic(this.options, { code: "erase_retired_read_failed", operation: "erase", trigger: "call", entityId: "" });
5681
+ throw new EraseStepError("erase_retired_read_failed", "erase stopped after step 6: the retired-table read failed; erasure is unverified", report, err);
5682
+ }
5683
+ const left = present.map((r) => r.name).filter((n) => isRetiredTableName(this.prefix, n) && !report.retiredUndroppable.includes(n));
5684
+ if (left.length > 0) {
5685
+ report.failedStep = "retired_reclaim";
5686
+ emitDiagnostic(this.options, { code: "erase_retired_remaining", operation: "erase", trigger: "call", entityId: "", detail: { tables: left } });
5687
+ throw new EraseStepError("erase_retired_remaining", `erase stopped after step 6: retired FTS tables remain (${left.join(", ")})`, report);
5688
+ }
5689
+ ok("retired_reclaim_rerun");
5690
+ await this._eraseOptimize(report);
5691
+ ok("optimize");
5692
+ try {
5693
+ await this.metadataRepo.checkpointTruncateVerified();
5694
+ } catch (err) {
5695
+ report.failedStep = "checkpoint";
5696
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 8: WAL checkpoint incomplete; erasure is unverified", report, err);
5697
+ }
5698
+ ok("checkpoint");
5699
+ if (report.skipped.length === 0 && report.holds.length === 0) {
5700
+ let remainingTombstones;
5701
+ try {
5702
+ const row = await this.db.getFirstAsync(
5703
+ `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
5704
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
5705
+ );
5706
+ remainingTombstones = row?.n ?? 0;
5707
+ } catch (err) {
5708
+ report.failedStep = "tombstone_gate";
5709
+ throw new EraseStepError("erase_tombstone_gate_failed", "erase stopped at step 9: could not count remaining tombstones; erasure is unverified", report, err);
5710
+ }
5711
+ if (remainingTombstones > 0) {
5712
+ emitDiagnostic(this.options, { code: "erase_tombstones_remaining", operation: "erase", trigger: "call", entityId: "", detail: { count: remainingTombstones } });
5713
+ report.failedStep = "tombstone_gate";
5714
+ throw new EraseStepError("erase_tombstones_remaining", `erase stopped at step 9: ${remainingTombstones} soft-deleted row(s) remain; erasure is unverified`, report);
5715
+ }
5716
+ ok("tombstone_gate");
5717
+ } else {
5718
+ report.steps.push({ step: "tombstone_gate", outcome: "partial" });
5719
+ }
5720
+ report.verified = report.skipped.length === 0 && report.holds.length === 0;
5721
+ return report;
5722
+ } catch (err) {
5723
+ if (err instanceof EraseStepError && err.report === report && report.failedStep) {
5724
+ report.steps.push({ step: report.failedStep, outcome: "failed" });
5725
+ report.verified = false;
5726
+ }
5727
+ throw err;
5728
+ } finally {
5729
+ this.jobManager.releaseLock("erase", "*");
5730
+ }
5731
+ }
5732
+ /**
5733
+ * Step 3 remediation (specs/erase-fts-remediation): on a runtime without
5734
+ * usable strict drains, clear orphaned FTS5 surfaces so erasure can
5735
+ * complete verified. Per surface: existence gate (vtab OR any shadow) →
5736
+ * strategy check → vtab probe → path body → companions → state write.
5737
+ * Dispatch order is D4; exact-name allowlist interpolation is D2.
5738
+ */
5739
+ async _eraseClearFtsOrphans(report) {
5740
+ const surfaces = [`${this.prefix}entries_fts`, `${this.prefix}source_passages_fts`];
5741
+ let remediationRequired = false;
5742
+ const pathBTargets = [];
5743
+ try {
5744
+ for (const surface of surfaces) {
5745
+ const vtabExists = await this.sourceTableExists(surface);
5746
+ const shadows = [];
5747
+ for (const sfx of _MaintenanceService.FTS_SHADOW_SUFFIXES) {
5748
+ const name = `${surface}${sfx}`;
5749
+ if (await this.sourceTableExists(name)) shadows.push(name);
5750
+ }
5751
+ if (!vtabExists && shadows.length === 0) continue;
5752
+ remediationRequired = true;
5753
+ if (this.searchService.isIndexUnavailable()) {
5754
+ report.failedStep = "index_sync";
5755
+ 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);
5756
+ }
5757
+ let moduleLess = false;
5758
+ if (vtabExists) {
5759
+ try {
5760
+ await this.db.getFirstAsync(`SELECT 1 AS x FROM ${surface} LIMIT 1`);
5761
+ } catch (err) {
5762
+ let absent = false;
5763
+ let cur = err;
5764
+ for (let depth = 0; depth < 3 && cur != null && !absent; depth++) {
5765
+ let msg = "";
5766
+ try {
5767
+ msg = String(cur.message ?? cur);
5768
+ } catch {
5769
+ break;
5770
+ }
5771
+ absent = /no such module/i.test(msg);
5772
+ try {
5773
+ cur = cur.cause;
5774
+ } catch {
5775
+ break;
5776
+ }
5777
+ }
5778
+ if (!absent) {
5779
+ report.failedStep = "index_sync";
5780
+ throw new EraseStepError("erase_fts_orphan_probe_failed", `erase stopped at step 3: could not classify orphaned vtab ${surface}`, report, err);
5781
+ }
5782
+ moduleLess = true;
5783
+ }
5784
+ }
5785
+ if (vtabExists && !moduleLess) {
5786
+ if (this.options.config?.indexStrategy !== "minisearch") {
5787
+ report.failedStep = "index_sync";
5788
+ 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);
5789
+ }
5790
+ pathBTargets.push(surface);
5791
+ continue;
5792
+ }
5793
+ const cleared = [];
5794
+ for (const name of shadows) {
5795
+ if (name.endsWith("_config")) continue;
5796
+ const res = await this.db.runAsync(name.endsWith("_data") ? `DELETE FROM ${name} WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}`);
5797
+ if ((res?.changes ?? 0) > 0) cleared.push(name);
5798
+ }
5799
+ for (const name of cleared) {
5800
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
5801
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
5802
+ }
5803
+ }
5804
+ if (!remediationRequired) return;
5805
+ const tailCleared = [];
5806
+ await this.db.withTransactionAsync(async (tx) => {
5807
+ for (const companion of [`${this.prefix}fts_pending`, `${this.prefix}fts_map`, `${this.prefix}source_passages_fts_pending`, `${this.prefix}source_passages_fts_map`]) {
5808
+ if (await this.sourceTableExists(companion, tx)) {
5809
+ const res = await tx.runAsync(`DELETE FROM ${companion}`);
5810
+ if ((res?.changes ?? 0) > 0 && !tailCleared.includes(companion)) tailCleared.push(companion);
5811
+ }
5812
+ }
5813
+ for (const surface of pathBTargets) {
5814
+ await tx.execAsync(`DROP TABLE IF EXISTS ${surface}`);
5815
+ if (!tailCleared.includes(surface)) tailCleared.push(surface);
5816
+ }
5817
+ if (pathBTargets.length > 0) {
5818
+ const [ai, ad] = passageFtsTriggerNames(this.prefix);
5819
+ await tx.execAsync(fts5LedgerDropSql(this.prefix) + `
5820
+ DROP TRIGGER IF EXISTS ${ai};
5821
+ DROP TRIGGER IF EXISTS ${ad};`);
5822
+ }
5823
+ await this.metadataRepo.setMeta(FTS5_STATE_KEY, "detached", tx);
5824
+ });
5825
+ for (const name of tailCleared) {
5826
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
5827
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
5828
+ }
5829
+ report.steps.push({ step: "fts_orphan_clear", outcome: "ok" });
5830
+ } catch (err) {
5831
+ if (err instanceof EraseStepError) throw err;
5832
+ report.failedStep = "fts_orphan_clear";
5833
+ throw new EraseStepError("erase_fts_orphan_clear", "erase stopped at step 3: clearing an orphaned FTS surface failed; erasure is unverified", report, err);
5834
+ }
5835
+ }
5836
+ /**
5837
+ * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
5838
+ * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
5839
+ * N2 guard (probe lives here, strategy-agnostic): a strategy without the strict
5840
+ * drains (Unavailable / MiniSearch) cannot drain, so rows in either FTS ledger
5841
+ * mean text was never drained -> the step fails and erasure is unverified.
5842
+ * Absent or empty ledgers proceed.
5843
+ */
5844
+ async _eraseDrainPassages(report) {
5845
+ if (!this.searchService.hasStrictDrain()) {
5846
+ await this._eraseClearFtsOrphans(report);
5847
+ for (const [table, failedStep, code] of [
5848
+ [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
5849
+ [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
5850
+ ]) {
5851
+ let rows = false;
5852
+ try {
5853
+ rows = await this.sourceTableExists(table) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${table} LIMIT 1`) != null;
5854
+ } catch (err) {
5855
+ report.failedStep = failedStep;
5856
+ throw new EraseStepError(code, `erase stopped at step 3: could not probe ${table}`, report, err);
5857
+ }
5858
+ if (rows) {
5859
+ report.failedStep = failedStep;
5860
+ 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);
5861
+ }
5862
+ }
5863
+ }
5864
+ try {
5865
+ await this.searchService.drainEntriesLedgerSurfaced();
5866
+ } catch (err) {
5867
+ report.failedStep = "index_sync";
5868
+ throw new EraseStepError("erase_index_sync_failed", "erase stopped at step 3: entries ledger drain failed", report, err);
5869
+ }
5870
+ try {
5871
+ await this.searchService.drainPassagesSurfaced();
5872
+ } catch (err) {
5873
+ report.failedStep = "passage_drain";
5874
+ throw new EraseStepError("erase_passage_drain_failed", "erase stopped at step 3: passage drain failed", report, err);
5875
+ }
5876
+ }
5877
+ /**
5878
+ * Step 4 (and its re-run after step 6): reclaim retired FTS tables to
5879
+ * completion. A module-less runtime cannot DROP a virtual table, so each
5880
+ * retired table's shadow tables are emptied under the pragma and the name
5881
+ * stays listed; a later FTS5-capable open's step 4 completes the DROP.
5882
+ */
5883
+ async _eraseReclaimRetired(report) {
5884
+ if (this.searchService.canReclaimRetired()) {
5885
+ try {
5886
+ await this.searchService.reclaimRetiredSurfaced();
5887
+ return;
5888
+ } catch (err) {
5889
+ if (!/no such module/i.test(err instanceof Error ? err.message : String(err))) {
5890
+ report.failedStep = "retired_reclaim";
5891
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: retired FTS table reclaim failed", report, err);
5892
+ }
5893
+ }
5894
+ }
5895
+ try {
5896
+ for (const name of await this._retiredList()) {
5897
+ for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
5898
+ if (sfx === "_config") continue;
5899
+ if (await this.sourceTableExists(`${name}${sfx}`)) {
5900
+ await this.db.runAsync(sfx === "_data" ? `DELETE FROM ${name}_data WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}${sfx}`);
5901
+ }
5902
+ }
5903
+ if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
5904
+ emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
5905
+ }
5906
+ } catch (err) {
5907
+ report.failedStep = "retired_reclaim";
5908
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: module-less shadow-table clear failed", report, err);
5909
+ }
5910
+ }
5911
+ /** Retired list straight from metadata (same key Fts5IndexStrategy maintains), independent of the active strategy. */
5912
+ async _retiredList() {
5913
+ let raw;
5914
+ try {
5915
+ raw = JSON.parse(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY) ?? "[]");
5916
+ } catch {
5917
+ return [];
5918
+ }
5919
+ return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
5920
+ }
5921
+ sourceTableExists(name, tx) {
5922
+ return this.metadataRepo.tableExists(name, tx);
5923
+ }
5924
+ /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
5925
+ async _eraseSyncEntries(entityId, ids, report) {
5926
+ let ok = false;
5927
+ try {
5928
+ ok = await this.searchService.syncEntries(entityId, ids);
5929
+ } catch (err) {
5930
+ report.failedStep = "index_sync";
5931
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId})`, report, err);
5932
+ }
5933
+ if (!ok) {
5934
+ report.failedStep = "index_sync";
5935
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId}): ledger drain failed`, report);
5936
+ }
5937
+ }
5938
+ /** Step 7: FTS optimize on both FTS tables, after syncEntries. */
5939
+ async _eraseOptimize(report) {
5940
+ try {
5941
+ await this.searchService.optimizeSurfaced();
5942
+ } catch (err) {
5943
+ report.failedStep = "optimize";
5944
+ throw new EraseStepError("erase_optimize_failed", "erase stopped at step 7: FTS optimize failed", report, err);
5945
+ }
5946
+ }
5404
5947
  async runLibrarian(entityId, options) {
5405
5948
  this.jobManager.acquireLock("librarian", entityId);
5406
5949
  try {
@@ -5521,6 +6064,9 @@ var MaintenanceService = class {
5521
6064
  if (params.includeEvents && !params.clearAll) {
5522
6065
  throw new Error("forget() includeEvents requires clearAll: true");
5523
6066
  }
6067
+ if (params.includeChain && (params.entryId === void 0 || params.clearAll || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
6068
+ throw new Error("forget() includeChain composes only with entryId");
6069
+ }
5524
6070
  if (opts?.dryRun === true) {
5525
6071
  return this.forgetDryRun(entityId, params);
5526
6072
  }
@@ -5530,6 +6076,8 @@ var MaintenanceService = class {
5530
6076
  let deletedEntries = 0;
5531
6077
  let deletedTasks = 0;
5532
6078
  let deletedEvents = 0;
6079
+ let chainIds = [];
6080
+ let chainTruncated = false;
5533
6081
  const deletedEntryIds = [];
5534
6082
  const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
5535
6083
  await this.db.withTransactionAsync(async (tx) => {
@@ -5566,6 +6114,12 @@ var MaintenanceService = class {
5566
6114
  if (params.entryId) {
5567
6115
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
5568
6116
  if (entryId) deletedEntryIds.push(entryId);
6117
+ if (entryId && params.includeChain) {
6118
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, entryId, HISTORY_MAX_DEPTH, tx);
6119
+ chainIds = walk.ids.filter((id) => id !== entryId);
6120
+ chainTruncated = walk.truncated;
6121
+ for (const id of chainIds) deletedEntryIds.push(id);
6122
+ }
5569
6123
  }
5570
6124
  if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
5571
6125
  const docs = `${this.prefix}source_documents`;
@@ -5591,6 +6145,9 @@ var MaintenanceService = class {
5591
6145
  sourceRefIndexPromise ?? Promise.resolve(void 0)
5592
6146
  ]);
5593
6147
  if (entryResult) deletedEntries++;
6148
+ for (const id of chainIds) {
6149
+ if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
6150
+ }
5594
6151
  if (taskResult) deletedTasks++;
5595
6152
  deletedEntries += refResult;
5596
6153
  }
@@ -5644,7 +6201,17 @@ var MaintenanceService = class {
5644
6201
  });
5645
6202
  }
5646
6203
  }
5647
- if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
6204
+ if (!params.clearAll) {
6205
+ const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
6206
+ if (params.includeChain) {
6207
+ base.chainEntryIds = chainIds;
6208
+ if (chainTruncated) {
6209
+ base.truncated = true;
6210
+ base.notice = CHAIN_TRUNCATED_NOTICE;
6211
+ }
6212
+ }
6213
+ return base;
6214
+ }
5648
6215
  return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
5649
6216
  } finally {
5650
6217
  this.jobManager.releaseLock("forget", entityId);
@@ -5710,8 +6277,25 @@ var MaintenanceService = class {
5710
6277
  * (the spec keeps dry-run narrow).
5711
6278
  */
5712
6279
  async forgetDryRun(entityId, params) {
6280
+ if (params.entryId !== void 0 && params.includeChain && params.taskId === void 0) {
6281
+ const id = await this.entryRepo.findIdById(params.entryId, entityId);
6282
+ if (!id) return { deleted: { entries: 0, tasks: 0 }, chainEntryIds: [] };
6283
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, id, HISTORY_MAX_DEPTH);
6284
+ const chainEntryIds = walk.ids.filter((c) => c !== id);
6285
+ const all = [id, ...chainEntryIds];
6286
+ const live = await this.db.getFirstAsync(
6287
+ `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND id IN (${all.map(() => "?").join(",")})`,
6288
+ [entityId, ...all]
6289
+ );
6290
+ const out = { deleted: { entries: live?.n ?? 0, tasks: 0 }, chainEntryIds };
6291
+ if (walk.truncated) {
6292
+ out.truncated = true;
6293
+ out.notice = CHAIN_TRUNCATED_NOTICE;
6294
+ }
6295
+ return out;
6296
+ }
5713
6297
  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");
6298
+ throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors (entryId is accepted only with includeChain); use sourceRef/sourceHash or clearAll");
5715
6299
  }
5716
6300
  if (params.clearAll) {
5717
6301
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
@@ -6430,6 +7014,9 @@ var MaintenanceService = class {
6430
7014
  return sanitizeRankerError(err, this.options.sanitizeRankerErrors);
6431
7015
  }
6432
7016
  };
7017
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
7018
+ _MaintenanceService.FTS_SHADOW_SUFFIXES = ["_content", "_data", "_idx", "_docsize", "_config"];
7019
+ var MaintenanceService = _MaintenanceService;
6433
7020
 
6434
7021
  // src/readOptions.ts
6435
7022
  function normalizeEntityIds(entityId) {
@@ -7564,6 +8151,65 @@ var _SearchService = class _SearchService {
7564
8151
  this.syncChain = work;
7565
8152
  return work;
7566
8153
  }
8154
+ /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
8155
+ chainSurfaced(fn) {
8156
+ const work = this.syncChain.then(fn);
8157
+ this.syncChain = work.then(() => void 0, () => void 0);
8158
+ return work;
8159
+ }
8160
+ /** True when the active strategy is the transient outage placeholder (erase orphan remediation, D1: never drop under it). */
8161
+ isIndexUnavailable() {
8162
+ return this.indexStrategy instanceof UnavailableIndexStrategy;
8163
+ }
8164
+ /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
8165
+ hasStrictDrain() {
8166
+ const s = this.indexStrategy;
8167
+ return typeof s.drainPassagesStrict === "function" && typeof s.drainEntriesLedgerStrict === "function";
8168
+ }
8169
+ /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
8170
+ drainPassagesSurfaced() {
8171
+ const s = this.indexStrategy;
8172
+ if (!s.drainPassagesStrict) return this.chainSurfaced(async () => {
8173
+ });
8174
+ return this.chainSurfaced(() => s.drainPassagesStrict());
8175
+ }
8176
+ /** Erase step 4: listed retired FTS tables (empty for strategies without any). */
8177
+ async retiredTables() {
8178
+ const s = this.indexStrategy;
8179
+ return s.retiredTables ? s.retiredTables() : [];
8180
+ }
8181
+ /** True when the active strategy can DROP retired tables (FTS5); false for MiniSearch / Unavailable. */
8182
+ canReclaimRetired() {
8183
+ return typeof this.indexStrategy.reclaimRetiredToCompletion === "function";
8184
+ }
8185
+ /** Erase step 3: store-wide entries-side fts_pending drain on the sync chain, no deadline, errors surfaced. */
8186
+ drainEntriesLedgerSurfaced() {
8187
+ const s = this.indexStrategy;
8188
+ if (!s.drainEntriesLedgerStrict) return this.chainSurfaced(async () => {
8189
+ });
8190
+ return this.chainSurfaced(() => s.drainEntriesLedgerStrict());
8191
+ }
8192
+ /** Erase step 4: reclaim retired tables to completion; errors surfaced. */
8193
+ reclaimRetiredSurfaced() {
8194
+ const s = this.indexStrategy;
8195
+ if (!s.reclaimRetiredToCompletion) return this.chainSurfaced(async () => {
8196
+ });
8197
+ return this.chainSurfaced(() => s.reclaimRetiredToCompletion());
8198
+ }
8199
+ /** Erase step 7: FTS optimize on every FTS table that exists. */
8200
+ optimizeSurfaced() {
8201
+ const s = this.indexStrategy;
8202
+ if (!s.optimizeFts) return this.chainSurfaced(async () => {
8203
+ });
8204
+ return this.chainSurfaced(() => s.optimizeFts());
8205
+ }
8206
+ /** `erase({ rebuild: true })` wiring point; the orchestration (T6) calls it. */
8207
+ rebuildSurfaced() {
8208
+ const s = this.indexStrategy;
8209
+ if (!s.rebuildForErase) return this.chainSurfaced(async () => {
8210
+ });
8211
+ return this.chainSurfaced(() => s.rebuildForErase());
8212
+ }
7567
8213
  /**
7568
8214
  * Stored-source passage search for ONE entity (spec source-store section 7:
7569
8215
  * ranking and caps are per entity). Rides the active strategy; a strategy
@@ -7719,7 +8365,7 @@ var JobManager = class {
7719
8365
  this.statusSubscribers = /* @__PURE__ */ new Map();
7720
8366
  /**
7721
8367
  * Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
7722
- * Excludes 'ingest' | 'global_reembed' | 'global_import', which those
8368
+ * Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
7723
8369
  * methods already handle via explicit if/else branches before reaching
7724
8370
  * this table.
7725
8371
  */
@@ -7788,6 +8434,9 @@ var JobManager = class {
7788
8434
  _globalReembedKey() {
7789
8435
  return `${this.prefix}:reembed`;
7790
8436
  }
8437
+ _eraseKey() {
8438
+ return `${this.prefix}:erase`;
8439
+ }
7791
8440
  _importKey(entityId) {
7792
8441
  return `${this.prefix}:${entityId}:import`;
7793
8442
  }
@@ -7868,11 +8517,19 @@ var JobManager = class {
7868
8517
  _isIngestActiveFor(entityId) {
7869
8518
  return this.activeIngestJobs.has(entityId);
7870
8519
  }
7871
- acquireLock(operation, entityId, sourceRef) {
8520
+ /**
8521
+ * `owner` is the fourth parameter (the third, `sourceRef`, is ingest-only).
8522
+ * `'erase'` marks the erase() pipeline's own per-entity prune, the only
8523
+ * operation exempt from the universal erase pre-check below.
8524
+ */
8525
+ acquireLock(operation, entityId, sourceRef, owner = "host") {
7872
8526
  let blockingOperation = null;
7873
8527
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
7874
8528
  throw new WikiBusyError("import", "*");
7875
8529
  }
8530
+ if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
8531
+ throw new WikiBusyError("erase", "*");
8532
+ }
7876
8533
  switch (operation) {
7877
8534
  case "prune":
7878
8535
  if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
@@ -7921,6 +8578,18 @@ var JobManager = class {
7921
8578
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
7922
8579
  else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7923
8580
  break;
8581
+ case "erase":
8582
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) blockingOperation = "erase";
8583
+ else if (this._isAnyMaintenanceActiveWithSuffix(":reembed")) blockingOperation = "reembed";
8584
+ else if (this._isAnyMaintenanceActiveWithSuffix(":prune")) blockingOperation = "prune";
8585
+ else if (this._isAnyMaintenanceActiveWithSuffix(":librarian")) blockingOperation = "librarian";
8586
+ else if (this._isAnyMaintenanceActiveWithSuffix(":heal")) blockingOperation = "heal";
8587
+ else if (this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill")) blockingOperation = "ontologyBackfill";
8588
+ else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
8589
+ else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
8590
+ else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
8591
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
8592
+ break;
7924
8593
  case "import":
7925
8594
  case "forget": {
7926
8595
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
@@ -7965,7 +8634,7 @@ var JobManager = class {
7965
8634
  if (blockingOperation) {
7966
8635
  throw new WikiBusyError(
7967
8636
  blockingOperation,
7968
- operation === "global_reembed" || operation === "global_import" ? "*" : entityId
8637
+ operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
7969
8638
  );
7970
8639
  }
7971
8640
  if (operation === "ingest") {
@@ -7974,6 +8643,8 @@ var JobManager = class {
7974
8643
  this.activeMaintenanceJobs.add(this._globalReembedKey());
7975
8644
  } else if (operation === "global_import") {
7976
8645
  this.activeMaintenanceJobs.add(this._globalImportKey());
8646
+ } else if (operation === "erase") {
8647
+ this.activeMaintenanceJobs.add(this._eraseKey());
7977
8648
  } else {
7978
8649
  this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
7979
8650
  }
@@ -7986,6 +8657,8 @@ var JobManager = class {
7986
8657
  this.activeMaintenanceJobs.delete(this._globalReembedKey());
7987
8658
  } else if (operation === "global_import") {
7988
8659
  this.activeMaintenanceJobs.delete(this._globalImportKey());
8660
+ } else if (operation === "erase") {
8661
+ this.activeMaintenanceJobs.delete(this._eraseKey());
7989
8662
  } else {
7990
8663
  this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
7991
8664
  }
@@ -7997,7 +8670,10 @@ var JobManager = class {
7997
8670
  */
7998
8671
  isBlocked(operation, entityId) {
7999
8672
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
8673
+ if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
8000
8674
  switch (operation) {
8675
+ case "erase":
8676
+ 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
8677
  case "librarian":
8002
8678
  case "heal":
8003
8679
  case "ontologyBackfill":
@@ -8031,6 +8707,7 @@ var JobManager = class {
8031
8707
  */
8032
8708
  tryAcquireAutoHealLock(entityId) {
8033
8709
  if (this.isAnyReembedActive()) return false;
8710
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
8034
8711
  const healKey = this._healKey(entityId);
8035
8712
  if (this.activeMaintenanceJobs.has(healKey)) return false;
8036
8713
  this.activeMaintenanceJobs.add(healKey);
@@ -8074,6 +8751,7 @@ var JobManager = class {
8074
8751
  * Validates all entities before acquiring any lock (same as current importDump semantics).
8075
8752
  */
8076
8753
  acquireImportLocks(entityIds) {
8754
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
8077
8755
  for (const entityId of entityIds) {
8078
8756
  if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
8079
8757
  if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);