@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/index.js CHANGED
@@ -37,6 +37,16 @@ var SEVERITY = {
37
37
  resolve_failed: "warn",
38
38
  read_budget: "info",
39
39
  event_retention_held: "info",
40
+ prune_checkpoint_incomplete: "warn",
41
+ erase_secure_delete_off: "error",
42
+ erase_entity_skipped: "warn",
43
+ erase_retired_vtab_undroppable: "warn",
44
+ erase_fts_orphan_cleared: "info",
45
+ erase_retired_remaining: "error",
46
+ erase_tombstones_remaining: "error",
47
+ erase_retired_read_failed: "error",
48
+ erase_registry_sweep_skipped: "info",
49
+ import_tombstone_skipped: "info",
40
50
  event_created_at_clamped: "warn",
41
51
  event_created_at_restamped: "info",
42
52
  external_deletion_pending: "warn",
@@ -72,6 +82,16 @@ var MESSAGE = {
72
82
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
73
83
  read_budget: "A read was packed to a token budget.",
74
84
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
85
+ 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.",
86
+ erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
87
+ 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.",
88
+ 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.",
89
+ erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
90
+ erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
91
+ erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
92
+ erase_entity_skipped: "Erase skipped an entity because another operation held its prune lock.",
93
+ erase_registry_sweep_skipped: "Erase skipped the source_ref_index tombstone sweep because the table does not exist (pre-v9 store).",
94
+ 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.",
75
95
  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.",
76
96
  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.",
77
97
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
@@ -375,8 +395,8 @@ var WikiDraftNotFound = class _WikiDraftNotFound extends Error {
375
395
  }
376
396
  };
377
397
  var WikiSupersedeError = class _WikiSupersedeError extends Error {
378
- constructor(reason) {
379
- super(`supersede() rejected: ${reason}`);
398
+ constructor(reason, verb = "supersede()") {
399
+ super(`${verb} rejected: ${reason}`);
380
400
  this.code = "WIKI_SUPERSEDE_REJECTED";
381
401
  this.name = "WikiSupersedeError";
382
402
  this.reason = reason;
@@ -2322,10 +2342,15 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2322
2342
  const chunk = ids.slice(i, i + this.chunkSize);
2323
2343
  const placeholders = chunk.map(() => "?").join(",");
2324
2344
  const chunkRows = await executor.getAllAsync(
2325
- `SELECT id, entity_id, updated_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
2345
+ `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
2326
2346
  chunk
2327
2347
  );
2328
- rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));
2348
+ rows.push(...chunkRows.map((row) => ({
2349
+ id: row.id,
2350
+ entity_id: row.entity_id,
2351
+ updated_at: Number(row.updated_at),
2352
+ deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
2353
+ })));
2329
2354
  }
2330
2355
  return rows;
2331
2356
  }
@@ -2497,22 +2522,25 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2497
2522
  * Fetch IDs + entity_ids of soft-deleted rows older than cutoff for a given entity.
2498
2523
  * Used by runPrune().
2499
2524
  */
2500
- async getPrunableMetadata(entityId, cutoff, tx) {
2525
+ async getPrunableMetadata(entityId, cutoff, tx, opts) {
2501
2526
  const executor = this.getExecutor(tx);
2527
+ const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
2528
+ const args = opts?.noCutoff ? [entityId] : [entityId, cutoff];
2502
2529
  return executor.getAllAsync(
2503
2530
  `SELECT id, entity_id FROM ${this.prefix}entries
2504
- WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
2505
- [entityId, cutoff]
2531
+ WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
2532
+ args
2506
2533
  );
2507
2534
  }
2508
2535
  /**
2509
2536
  * Fetch all non-deleted entries for an entity, ordered by updated_at DESC.
2510
2537
  * Used by _getFullBundle().
2511
2538
  */
2512
- async findAllByEntityId(entityId, tx) {
2539
+ async findAllByEntityId(entityId, tx, opts) {
2513
2540
  const executor = this.getExecutor(tx);
2541
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
2514
2542
  const rows = await executor.getAllAsync(
2515
- `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,
2543
+ `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
2516
2544
  [entityId]
2517
2545
  );
2518
2546
  return rows.map(mapRowToFact);
@@ -2592,10 +2620,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2592
2620
  * Fetch all non-deleted entries for an entity with embedding blobs preserved.
2593
2621
  * Used by ImportExportService for export/import round-tripping.
2594
2622
  */
2595
- async findAllByEntityIdWithBlobs(entityId, tx) {
2623
+ async findAllByEntityIdWithBlobs(entityId, tx, opts) {
2596
2624
  const executor = this.getExecutor(tx);
2625
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
2597
2626
  const rows = await executor.getAllAsync(
2598
- `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,
2627
+ `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
2599
2628
  [entityId]
2600
2629
  );
2601
2630
  return rows.map(mapRowToFactWithBlobs);
@@ -2666,20 +2695,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2666
2695
  for (let i = 0; i < ids.length; i += chunkSize) {
2667
2696
  const chunk = ids.slice(i, i + chunkSize);
2668
2697
  const placeholders = chunk.map(() => "?").join(",");
2698
+ const cutoffPredicate = opts.noCutoff ? "" : " AND deleted_at <= ?";
2699
+ const delArgs = opts.noCutoff ? [entityId, ...chunk] : [entityId, cutoff, ...chunk];
2669
2700
  const deleted = (await executor.getAllAsync(
2670
- `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})${guard} RETURNING id`,
2671
- [entityId, cutoff, ...chunk]
2672
- )).map((r) => r.id);
2701
+ `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate} AND id IN (${placeholders})${guard} RETURNING id, deleted_at`,
2702
+ delArgs
2703
+ )).map((r) => ({ id: r.id, deleted_at: typeof r.deleted_at === "number" ? r.deleted_at : Number(r.deleted_at) }));
2673
2704
  totalChanges += deleted.length;
2674
- opts.deletedIds?.push(...deleted);
2705
+ opts.deletedIds?.push(...deleted.map((r) => r.id));
2675
2706
  if (deleted.length > 0) {
2676
- for (const id of deleted) {
2707
+ for (const row of deleted) {
2677
2708
  await this.outbox.push({
2678
2709
  entityId,
2679
2710
  tableName: "entries",
2680
- recordId: id,
2711
+ recordId: row.id,
2681
2712
  operation: "DELETE",
2682
- payload: { id, entity_id: entityId, deleted_at: cutoff }
2713
+ payload: { id: row.id, entity_id: entityId, deleted_at: row.deleted_at }
2683
2714
  }, tx);
2684
2715
  }
2685
2716
  }
@@ -2848,6 +2879,19 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2848
2879
  );
2849
2880
  return new Set(rows.map((r) => r.id));
2850
2881
  }
2882
+ /**
2883
+ * Depth-aware supersession walk for chain forget (spec forget-erasure §3).
2884
+ * Probes `maxDepth + 1` levels so a chain longer than the cap is detectable;
2885
+ * the returned ids are capped to `maxDepth` per direction (successors nearest first; predecessors are returned farthest-first).
2886
+ * No `deleted_at` filter: soft-deleted links still carry the chain.
2887
+ */
2888
+ async findSupersessionChainWalk(entityId, factId, maxDepth, tx) {
2889
+ const { predecessors, successors } = await this.findSupersessionChainIds(entityId, factId, maxDepth + 1, tx);
2890
+ const truncated = predecessors.some((r) => r.depth > maxDepth) || successors.some((r) => r.depth > maxDepth);
2891
+ const pred = predecessors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
2892
+ const succ = successors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
2893
+ return { ids: Array.from(/* @__PURE__ */ new Set([...succ, ...pred])), truncated };
2894
+ }
2851
2895
  async findSupersessionChainIds(entityId, factId, maxDepth, tx) {
2852
2896
  const executor = this.getExecutor(tx);
2853
2897
  const successors = await executor.getAllAsync(
@@ -2858,7 +2902,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2858
2902
  JOIN ${this.prefix}entries e ON e.id = fwd.id AND e.entity_id = ?
2859
2903
  WHERE e.superseded_by IS NOT NULL AND fwd.depth < ?
2860
2904
  )
2861
- SELECT id FROM fwd ORDER BY depth ASC`,
2905
+ SELECT id, depth FROM fwd ORDER BY depth ASC`,
2862
2906
  [factId, entityId, entityId, maxDepth]
2863
2907
  );
2864
2908
  const predecessors = await executor.getAllAsync(
@@ -2869,10 +2913,10 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2869
2913
  JOIN ${this.prefix}entries e ON e.entity_id = ? AND e.superseded_by = bwd.id
2870
2914
  WHERE bwd.depth < ?
2871
2915
  )
2872
- SELECT id FROM bwd ORDER BY depth DESC`,
2916
+ SELECT id, depth FROM bwd ORDER BY depth DESC`,
2873
2917
  [entityId, factId, entityId, maxDepth]
2874
2918
  );
2875
- const drop = (ids) => ids.map((r) => r.id).filter((id) => id !== factId);
2919
+ const drop = (rows) => rows.filter((r) => r.id !== factId);
2876
2920
  return { predecessors: drop(predecessors), successors: drop(successors) };
2877
2921
  }
2878
2922
  async findExpiredIds(entityId, cutoff, tx) {
@@ -3703,10 +3747,15 @@ var TaskRepository = class extends BaseRepository {
3703
3747
  const chunk = ids.slice(i, i + chunkSize);
3704
3748
  const placeholders = chunk.map(() => "?").join(",");
3705
3749
  const chunkRows = await executor.getAllAsync(
3706
- `SELECT id, entity_id, updated_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
3750
+ `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
3707
3751
  chunk
3708
3752
  );
3709
- rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));
3753
+ rows.push(...chunkRows.map((row) => ({
3754
+ id: row.id,
3755
+ entity_id: row.entity_id,
3756
+ updated_at: Number(row.updated_at),
3757
+ deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
3758
+ })));
3710
3759
  }
3711
3760
  return rows;
3712
3761
  }
@@ -3869,10 +3918,11 @@ var TaskRepository = class extends BaseRepository {
3869
3918
  * Fetch all non-deleted tasks for an entity, ordered by priority DESC, created_at ASC.
3870
3919
  * Used by _getFullBundle().
3871
3920
  */
3872
- async findAllByEntityId(entityId, tx) {
3921
+ async findAllByEntityId(entityId, tx, opts) {
3873
3922
  const executor = this.getExecutor(tx);
3923
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
3874
3924
  const rows = await executor.getAllAsync(
3875
- `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NULL ORDER BY priority DESC, created_at ASC`,
3925
+ `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ?${live} ORDER BY priority DESC, created_at ASC`,
3876
3926
  [entityId]
3877
3927
  );
3878
3928
  return rows.map(mapRowToTask);
@@ -3881,16 +3931,19 @@ var TaskRepository = class extends BaseRepository {
3881
3931
  * Bulk delete pruned tasks (already soft-deleted) by cutoff date.
3882
3932
  * Used by runPrune(). Returns number of deleted rows.
3883
3933
  */
3884
- async bulkDeletePruned(entityId, cutoff, tx) {
3934
+ async bulkDeletePruned(entityId, cutoff, tx, opts) {
3885
3935
  const executor = this.getExecutor(tx);
3936
+ const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
3937
+ const selectArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
3886
3938
  const rowsToDelete = await executor.getAllAsync(
3887
- `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
3888
- [entityId, cutoff]
3939
+ `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
3940
+ selectArgs
3889
3941
  );
3890
3942
  if (rowsToDelete.length === 0) return 0;
3943
+ const deleteArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
3891
3944
  const result = await executor.runAsync(
3892
- `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
3893
- [entityId, cutoff]
3945
+ `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
3946
+ deleteArgs
3894
3947
  );
3895
3948
  for (const row of rowsToDelete) {
3896
3949
  await this.outbox.push(
@@ -4556,6 +4609,12 @@ function entitySummaryMetaKey(entityId) {
4556
4609
  return `entity_summary:${entityId}`;
4557
4610
  }
4558
4611
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
4612
+ var CheckpointIncompleteError = class extends Error {
4613
+ constructor() {
4614
+ super(...arguments);
4615
+ this.code = "erase_checkpoint_incomplete";
4616
+ }
4617
+ };
4559
4618
  var MetadataRepository = class extends BaseRepository {
4560
4619
  // CHECKPOINTS TABLE METHODS
4561
4620
  async getCheckpoint(entityId, tx) {
@@ -4674,9 +4733,25 @@ var MetadataRepository = class extends BaseRepository {
4674
4733
  );
4675
4734
  return row?.sql ?? null;
4676
4735
  }
4736
+ /**
4737
+ * `PRAGMA wal_checkpoint(TRUNCATE)`, verified: `busy !== 0` or
4738
+ * `log !== checkpointed` means frames survive in the WAL, so a deleted
4739
+ * row's bytes may still be on disk. Non-WAL reports (0,-1,-1) = complete.
4740
+ */
4741
+ async checkpointTruncateVerified() {
4742
+ const row = await this.db.getFirstAsync(
4743
+ `PRAGMA wal_checkpoint(TRUNCATE)`
4744
+ );
4745
+ if (row && (row.busy !== 0 || row.log !== row.checkpointed)) {
4746
+ throw new CheckpointIncompleteError(
4747
+ `wal_checkpoint(TRUNCATE) incomplete (busy=${row?.busy}, log=${row?.log}, checkpointed=${row?.checkpointed})`
4748
+ );
4749
+ }
4750
+ }
4677
4751
  async vacuum() {
4678
- await this.db.execAsync(`PRAGMA wal_checkpoint(TRUNCATE)`);
4752
+ await this.checkpointTruncateVerified();
4679
4753
  await this.db.execAsync(`VACUUM`);
4754
+ await this.checkpointTruncateVerified();
4680
4755
  }
4681
4756
  /**
4682
4757
  * Returns the set of distinct `entity_id` values across entries/tasks/events.
@@ -4686,9 +4761,36 @@ var MetadataRepository = class extends BaseRepository {
4686
4761
  * soft-deleted, so the host's maintenance sweep can visit such
4687
4762
  * "decommissioned-scope" namespaces and reap the soft-deleted rows. Sorting
4688
4763
  * is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
4764
+ *
4765
+ * With `opts.softDeletedAtOrBefore` the walk is narrowed to entities holding
4766
+ * at least one soft-deleted entry or task with `deleted_at` at or before
4767
+ * that cutoff (erase's hard-delete walk, forget-erasure spec §2). Without
4768
+ * the option the host-facing semantics above are unchanged.
4689
4769
  */
4690
- async getDistinctEntityIds(tx) {
4770
+ async getDistinctEntityIds(tx, opts) {
4691
4771
  const executor = this.getExecutor(tx);
4772
+ if (opts?.softDeletedAll) {
4773
+ const rows2 = await executor.getAllAsync(
4774
+ `SELECT DISTINCT entity_id FROM (
4775
+ SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL
4776
+ UNION
4777
+ SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL
4778
+ ) ORDER BY entity_id COLLATE BINARY`
4779
+ );
4780
+ return rows2.map((r) => r.entity_id);
4781
+ }
4782
+ if (opts?.softDeletedAtOrBefore !== void 0) {
4783
+ const cutoff = opts.softDeletedAtOrBefore;
4784
+ const rows2 = await executor.getAllAsync(
4785
+ `SELECT DISTINCT entity_id FROM (
4786
+ SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL AND deleted_at <= ?
4787
+ UNION
4788
+ SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL AND deleted_at <= ?
4789
+ ) ORDER BY entity_id COLLATE BINARY`,
4790
+ [cutoff, cutoff]
4791
+ );
4792
+ return rows2.map((r) => r.entity_id);
4793
+ }
4692
4794
  const rows = await executor.getAllAsync(
4693
4795
  `SELECT DISTINCT entity_id FROM (
4694
4796
  SELECT entity_id FROM ${this.prefix}entries
@@ -5078,6 +5180,65 @@ var _SearchService = class _SearchService {
5078
5180
  this.syncChain = work;
5079
5181
  return work;
5080
5182
  }
5183
+ /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
5184
+ chainSurfaced(fn) {
5185
+ const work = this.syncChain.then(fn);
5186
+ this.syncChain = work.then(() => void 0, () => void 0);
5187
+ return work;
5188
+ }
5189
+ /** True when the active strategy is the transient outage placeholder (erase orphan remediation, D1: never drop under it). */
5190
+ isIndexUnavailable() {
5191
+ return this.indexStrategy instanceof UnavailableIndexStrategy;
5192
+ }
5193
+ /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
5194
+ hasStrictDrain() {
5195
+ const s = this.indexStrategy;
5196
+ return typeof s.drainPassagesStrict === "function" && typeof s.drainEntriesLedgerStrict === "function";
5197
+ }
5198
+ /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
5199
+ drainPassagesSurfaced() {
5200
+ const s = this.indexStrategy;
5201
+ if (!s.drainPassagesStrict) return this.chainSurfaced(async () => {
5202
+ });
5203
+ return this.chainSurfaced(() => s.drainPassagesStrict());
5204
+ }
5205
+ /** Erase step 4: listed retired FTS tables (empty for strategies without any). */
5206
+ async retiredTables() {
5207
+ const s = this.indexStrategy;
5208
+ return s.retiredTables ? s.retiredTables() : [];
5209
+ }
5210
+ /** True when the active strategy can DROP retired tables (FTS5); false for MiniSearch / Unavailable. */
5211
+ canReclaimRetired() {
5212
+ return typeof this.indexStrategy.reclaimRetiredToCompletion === "function";
5213
+ }
5214
+ /** Erase step 3: store-wide entries-side fts_pending drain on the sync chain, no deadline, errors surfaced. */
5215
+ drainEntriesLedgerSurfaced() {
5216
+ const s = this.indexStrategy;
5217
+ if (!s.drainEntriesLedgerStrict) return this.chainSurfaced(async () => {
5218
+ });
5219
+ return this.chainSurfaced(() => s.drainEntriesLedgerStrict());
5220
+ }
5221
+ /** Erase step 4: reclaim retired tables to completion; errors surfaced. */
5222
+ reclaimRetiredSurfaced() {
5223
+ const s = this.indexStrategy;
5224
+ if (!s.reclaimRetiredToCompletion) return this.chainSurfaced(async () => {
5225
+ });
5226
+ return this.chainSurfaced(() => s.reclaimRetiredToCompletion());
5227
+ }
5228
+ /** Erase step 7: FTS optimize on every FTS table that exists. */
5229
+ optimizeSurfaced() {
5230
+ const s = this.indexStrategy;
5231
+ if (!s.optimizeFts) return this.chainSurfaced(async () => {
5232
+ });
5233
+ return this.chainSurfaced(() => s.optimizeFts());
5234
+ }
5235
+ /** `erase({ rebuild: true })` wiring point; the orchestration (T6) calls it. */
5236
+ rebuildSurfaced() {
5237
+ const s = this.indexStrategy;
5238
+ if (!s.rebuildForErase) return this.chainSurfaced(async () => {
5239
+ });
5240
+ return this.chainSurfaced(() => s.rebuildForErase());
5241
+ }
5081
5242
  /**
5082
5243
  * Stored-source passage search for ONE entity (spec source-store section 7:
5083
5244
  * ranking and caps are per entity). Rides the active strategy; a strategy
@@ -5650,6 +5811,7 @@ var Fts5IndexStrategy = class {
5650
5811
  const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);
5651
5812
  if (mapped === null && queued === null) {
5652
5813
  await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);
5814
+ await tx.runAsync(`INSERT INTO ${p}source_passages_fts(${p}source_passages_fts) VALUES('rebuild')`);
5653
5815
  await tx.runAsync(
5654
5816
  `INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)
5655
5817
  SELECT entity_id, id FROM ${p}source_documents`
@@ -5915,6 +6077,53 @@ var Fts5IndexStrategy = class {
5915
6077
  if (!isSqliteError(err)) throw err;
5916
6078
  }
5917
6079
  }
6080
+ /** Listed retired table names (erase step 4 / module-less fallback). */
6081
+ async retiredTables() {
6082
+ return this.retiredList();
6083
+ }
6084
+ /**
6085
+ * Erase step 4: reclaim every retired table to completion (DROP + delist), no
6086
+ * deadline. Failures surface (unlike the best-effort quantum path); the
6087
+ * SQLITE_CORRUPT_VTAB hollowed-shell exit inside reclaimRetired is designed.
6088
+ */
6089
+ async reclaimRetiredToCompletion() {
6090
+ await this.reclaimRetired(Number.POSITIVE_INFINITY);
6091
+ }
6092
+ /**
6093
+ * Erase step 3: surfaced passage drain, no deadline. Fails only when passage
6094
+ * init was disabled AND the ledger still has rows; otherwise warns and continues.
6095
+ */
6096
+ async drainPassagesStrict() {
6097
+ if (this.passagesDisabled) {
6098
+ const p = this.prefix;
6099
+ const pending = await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`) !== null;
6100
+ if (pending) throw new Error("passage index disabled with pending ledger rows");
6101
+ console.warn("[WikiMemory] erase: passage index disabled; nothing pending, continuing");
6102
+ return;
6103
+ }
6104
+ await this.drainPassages({});
6105
+ }
6106
+ /**
6107
+ * Erase step 3 (entries side): drain the trigger-fed `fts_pending` ledger store-wide to
6108
+ * empty, no deadline, errors surfaced; throws if rows remain afterwards.
6109
+ */
6110
+ async drainEntriesLedgerStrict() {
6111
+ while (await this.drainLedgerChunk()) ;
6112
+ const left = await this.db.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}fts_pending LIMIT 1`);
6113
+ if (left !== null && left !== void 0) throw new Error("entries FTS ledger still has pending rows after drain");
6114
+ }
6115
+ /** Erase step 7: FTS 'optimize' on each FTS table that exists. */
6116
+ async optimizeFts() {
6117
+ const p = this.prefix;
6118
+ for (const t of [`${p}entries_fts`, `${p}source_passages_fts`]) {
6119
+ if (!await this.metadataRepo.tableExists(t)) continue;
6120
+ await this.db.runAsync(`INSERT INTO ${t}(${t}) VALUES('optimize')`);
6121
+ }
6122
+ }
6123
+ /** `erase({ rebuild: true })` surface: retire + recreate the entries index and re-arm the rebuild. */
6124
+ async rebuildForErase() {
6125
+ await this.resetAndRearm();
6126
+ }
5918
6127
  /** Bounded reclamation steps, each its own tx, until the deadline or nothing is retired. */
5919
6128
  async reclaimRetired(deadline) {
5920
6129
  while (monotonicNow() < deadline) {
@@ -6618,7 +6827,7 @@ var JobManager = class {
6618
6827
  this.statusSubscribers = /* @__PURE__ */ new Map();
6619
6828
  /**
6620
6829
  * Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
6621
- * Excludes 'ingest' | 'global_reembed' | 'global_import', which those
6830
+ * Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
6622
6831
  * methods already handle via explicit if/else branches before reaching
6623
6832
  * this table.
6624
6833
  */
@@ -6687,6 +6896,9 @@ var JobManager = class {
6687
6896
  _globalReembedKey() {
6688
6897
  return `${this.prefix}:reembed`;
6689
6898
  }
6899
+ _eraseKey() {
6900
+ return `${this.prefix}:erase`;
6901
+ }
6690
6902
  _importKey(entityId) {
6691
6903
  return `${this.prefix}:${entityId}:import`;
6692
6904
  }
@@ -6767,11 +6979,19 @@ var JobManager = class {
6767
6979
  _isIngestActiveFor(entityId) {
6768
6980
  return this.activeIngestJobs.has(entityId);
6769
6981
  }
6770
- acquireLock(operation, entityId, sourceRef) {
6982
+ /**
6983
+ * `owner` is the fourth parameter (the third, `sourceRef`, is ingest-only).
6984
+ * `'erase'` marks the erase() pipeline's own per-entity prune, the only
6985
+ * operation exempt from the universal erase pre-check below.
6986
+ */
6987
+ acquireLock(operation, entityId, sourceRef, owner = "host") {
6771
6988
  let blockingOperation = null;
6772
6989
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
6773
6990
  throw new WikiBusyError("import", "*");
6774
6991
  }
6992
+ if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
6993
+ throw new WikiBusyError("erase", "*");
6994
+ }
6775
6995
  switch (operation) {
6776
6996
  case "prune":
6777
6997
  if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
@@ -6820,6 +7040,18 @@ var JobManager = class {
6820
7040
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
6821
7041
  else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
6822
7042
  break;
7043
+ case "erase":
7044
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) blockingOperation = "erase";
7045
+ else if (this._isAnyMaintenanceActiveWithSuffix(":reembed")) blockingOperation = "reembed";
7046
+ else if (this._isAnyMaintenanceActiveWithSuffix(":prune")) blockingOperation = "prune";
7047
+ else if (this._isAnyMaintenanceActiveWithSuffix(":librarian")) blockingOperation = "librarian";
7048
+ else if (this._isAnyMaintenanceActiveWithSuffix(":heal")) blockingOperation = "heal";
7049
+ else if (this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill")) blockingOperation = "ontologyBackfill";
7050
+ else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
7051
+ else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
7052
+ else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
7053
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7054
+ break;
6823
7055
  case "import":
6824
7056
  case "forget": {
6825
7057
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
@@ -6864,7 +7096,7 @@ var JobManager = class {
6864
7096
  if (blockingOperation) {
6865
7097
  throw new WikiBusyError(
6866
7098
  blockingOperation,
6867
- operation === "global_reembed" || operation === "global_import" ? "*" : entityId
7099
+ operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
6868
7100
  );
6869
7101
  }
6870
7102
  if (operation === "ingest") {
@@ -6873,6 +7105,8 @@ var JobManager = class {
6873
7105
  this.activeMaintenanceJobs.add(this._globalReembedKey());
6874
7106
  } else if (operation === "global_import") {
6875
7107
  this.activeMaintenanceJobs.add(this._globalImportKey());
7108
+ } else if (operation === "erase") {
7109
+ this.activeMaintenanceJobs.add(this._eraseKey());
6876
7110
  } else {
6877
7111
  this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
6878
7112
  }
@@ -6885,6 +7119,8 @@ var JobManager = class {
6885
7119
  this.activeMaintenanceJobs.delete(this._globalReembedKey());
6886
7120
  } else if (operation === "global_import") {
6887
7121
  this.activeMaintenanceJobs.delete(this._globalImportKey());
7122
+ } else if (operation === "erase") {
7123
+ this.activeMaintenanceJobs.delete(this._eraseKey());
6888
7124
  } else {
6889
7125
  this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
6890
7126
  }
@@ -6896,7 +7132,10 @@ var JobManager = class {
6896
7132
  */
6897
7133
  isBlocked(operation, entityId) {
6898
7134
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
7135
+ if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
6899
7136
  switch (operation) {
7137
+ case "erase":
7138
+ 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");
6900
7139
  case "librarian":
6901
7140
  case "heal":
6902
7141
  case "ontologyBackfill":
@@ -6930,6 +7169,7 @@ var JobManager = class {
6930
7169
  */
6931
7170
  tryAcquireAutoHealLock(entityId) {
6932
7171
  if (this.isAnyReembedActive()) return false;
7172
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
6933
7173
  const healKey = this._healKey(entityId);
6934
7174
  if (this.activeMaintenanceJobs.has(healKey)) return false;
6935
7175
  this.activeMaintenanceJobs.add(healKey);
@@ -6973,6 +7213,7 @@ var JobManager = class {
6973
7213
  * Validates all entities before acquiring any lock (same as current importDump semantics).
6974
7214
  */
6975
7215
  acquireImportLocks(entityIds) {
7216
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
6976
7217
  for (const entityId of entityIds) {
6977
7218
  if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
6978
7219
  if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);
@@ -8299,6 +8540,116 @@ function classifierStateForFact(fact) {
8299
8540
  return parts.join("\n\n");
8300
8541
  }
8301
8542
 
8543
+ // src/services/TemporalService.ts
8544
+ var HISTORY_MAX_DEPTH = 100;
8545
+ var TemporalService = class {
8546
+ constructor(db, options, entryRepo, searchService, embeddingService) {
8547
+ this.db = db;
8548
+ this.options = options;
8549
+ this.entryRepo = entryRepo;
8550
+ this.searchService = searchService;
8551
+ this.embeddingService = embeddingService;
8552
+ }
8553
+ /**
8554
+ * Link `oldId` → `newId` inside the caller's transaction. `newId` must
8555
+ * already exist. Throws WikiSupersedeError on any rule violation; the
8556
+ * caller's transaction then rolls back.
8557
+ */
8558
+ async supersedeInTx(tx, entityId, oldId, newId, t, now) {
8559
+ const old = await this.entryRepo.findTemporalRow(oldId, tx);
8560
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
8561
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
8562
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
8563
+ if (old.valid_to != null && old.valid_to <= Math.max(now, Date.now())) throw new WikiSupersedeError("already_expired");
8564
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
8565
+ if (newId === oldId) throw new WikiSupersedeError("cycle");
8566
+ const repl = await this.entryRepo.findTemporalRow(newId, tx);
8567
+ if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
8568
+ if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
8569
+ if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
8570
+ const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
8571
+ if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
8572
+ await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
8573
+ if (repl.valid_from == null) {
8574
+ await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
8575
+ }
8576
+ }
8577
+ async supersede(entityId, oldId, replacement, options) {
8578
+ const now = Date.now();
8579
+ const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
8580
+ let created = null;
8581
+ if (typeof replacement !== "string") {
8582
+ if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
8583
+ throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
8584
+ }
8585
+ created = {
8586
+ id: generateId("fact_"),
8587
+ entity_id: entityId,
8588
+ title: replacement.title,
8589
+ body: replacement.body,
8590
+ tags: Array.isArray(replacement.tags) ? replacement.tags : [],
8591
+ confidence: replacement.confidence ?? "certain",
8592
+ source_type: replacement.source_type ?? "user_stated",
8593
+ source_hash: null,
8594
+ source_ref: null,
8595
+ created_at: now,
8596
+ updated_at: now,
8597
+ last_accessed_at: null,
8598
+ access_count: 0,
8599
+ deleted_at: null
8600
+ };
8601
+ }
8602
+ const newId = typeof replacement === "string" ? replacement : created.id;
8603
+ const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
8604
+ await this.db.withTransactionAsync(async (tx) => {
8605
+ if (created) {
8606
+ await this.entryRepo.upsert(created, tx);
8607
+ if (newValidFrom !== void 0) {
8608
+ await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
8609
+ }
8610
+ }
8611
+ await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
8612
+ });
8613
+ await this.searchService.syncEntries(entityId, [oldId, newId]);
8614
+ if (created) {
8615
+ await this.embeddingService.embedFact(
8616
+ { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
8617
+ { operation: "supersede", trigger: "call" }
8618
+ );
8619
+ }
8620
+ this.searchService.evictCache(entityId);
8621
+ return { newId };
8622
+ }
8623
+ /**
8624
+ * End `factId`'s validity without a replacement — an archive, not a
8625
+ * deletion (INTENT rule 12, spec specs/expire). Sets `valid_to` only.
8626
+ */
8627
+ async expire(entityId, factId, options) {
8628
+ const t = options?.at === void 0 ? Date.now() : assertEpochMs("options.at", options.at);
8629
+ await this.db.withTransactionAsync(async (tx) => {
8630
+ const old = await this.entryRepo.findTemporalRow(factId, tx);
8631
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found", "expire()");
8632
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "expire()");
8633
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded", "expire()");
8634
+ if (old.valid_to != null) throw new WikiSupersedeError("already_expired", "expire()");
8635
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "expire()");
8636
+ const start = old.valid_from ?? old.created_at;
8637
+ if (t <= start) throw new WikiSupersedeError("invalid_interval", "expire()");
8638
+ const changes = await this.entryRepo.setTemporal(factId, entityId, { valid_to: t }, tx);
8639
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "expire()");
8640
+ });
8641
+ await this.searchService.syncEntries(entityId, [factId]);
8642
+ this.searchService.evictCache(entityId);
8643
+ }
8644
+ async history(entityId, factId) {
8645
+ const start = await this.entryRepo.findTemporalRow(factId);
8646
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
8647
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
8648
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
8649
+ 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));
8650
+ }
8651
+ };
8652
+
8302
8653
  // src/utils/engineDefaults.ts
8303
8654
  var DEFAULT_LIBRARIAN_STRATEGY = "ops";
8304
8655
  var DEFAULT_MAINTENANCE_MODE = "deferred";
@@ -9483,94 +9834,6 @@ async function runResolve(deps, ctx, ambiguous) {
9483
9834
  return out;
9484
9835
  }
9485
9836
 
9486
- // src/services/TemporalService.ts
9487
- var HISTORY_MAX_DEPTH = 100;
9488
- var TemporalService = class {
9489
- constructor(db, options, entryRepo, searchService, embeddingService) {
9490
- this.db = db;
9491
- this.options = options;
9492
- this.entryRepo = entryRepo;
9493
- this.searchService = searchService;
9494
- this.embeddingService = embeddingService;
9495
- }
9496
- /**
9497
- * Link `oldId` → `newId` inside the caller's transaction. `newId` must
9498
- * already exist. Throws WikiSupersedeError on any rule violation; the
9499
- * caller's transaction then rolls back.
9500
- */
9501
- async supersedeInTx(tx, entityId, oldId, newId, t, now) {
9502
- const old = await this.entryRepo.findTemporalRow(oldId, tx);
9503
- if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
9504
- if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
9505
- if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
9506
- if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
9507
- if (newId === oldId) throw new WikiSupersedeError("cycle");
9508
- const repl = await this.entryRepo.findTemporalRow(newId, tx);
9509
- if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
9510
- if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
9511
- if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
9512
- const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
9513
- if (predecessors.includes(newId)) throw new WikiSupersedeError("cycle");
9514
- await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
9515
- if (repl.valid_from == null) {
9516
- await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
9517
- }
9518
- }
9519
- async supersede(entityId, oldId, replacement, options) {
9520
- const now = Date.now();
9521
- const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
9522
- let created = null;
9523
- if (typeof replacement !== "string") {
9524
- if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
9525
- throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
9526
- }
9527
- created = {
9528
- id: generateId("fact_"),
9529
- entity_id: entityId,
9530
- title: replacement.title,
9531
- body: replacement.body,
9532
- tags: Array.isArray(replacement.tags) ? replacement.tags : [],
9533
- confidence: replacement.confidence ?? "certain",
9534
- source_type: replacement.source_type ?? "user_stated",
9535
- source_hash: null,
9536
- source_ref: null,
9537
- created_at: now,
9538
- updated_at: now,
9539
- last_accessed_at: null,
9540
- access_count: 0,
9541
- deleted_at: null
9542
- };
9543
- }
9544
- const newId = typeof replacement === "string" ? replacement : created.id;
9545
- const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
9546
- await this.db.withTransactionAsync(async (tx) => {
9547
- if (created) {
9548
- await this.entryRepo.upsert(created, tx);
9549
- if (newValidFrom !== void 0) {
9550
- await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
9551
- }
9552
- }
9553
- await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
9554
- });
9555
- await this.searchService.syncEntries(entityId, [oldId, newId]);
9556
- if (created) {
9557
- await this.embeddingService.embedFact(
9558
- { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
9559
- { operation: "supersede", trigger: "call" }
9560
- );
9561
- }
9562
- this.searchService.evictCache(entityId);
9563
- return { newId };
9564
- }
9565
- async history(entityId, factId) {
9566
- const start = await this.entryRepo.findTemporalRow(factId);
9567
- if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
9568
- const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
9569
- const facts = await this.entryRepo.findByIds([...predecessors, factId, ...successors], [entityId]);
9570
- 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));
9571
- }
9572
- };
9573
-
9574
9837
  // src/services/librarian/ops/apply.ts
9575
9838
  function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
9576
9839
  if (candidate.sourceEventId === null) return null;
@@ -9836,6 +10099,7 @@ async function runLibrarianStrategy(deps, ctx) {
9836
10099
  }
9837
10100
 
9838
10101
  // src/services/MaintenanceService.ts
10102
+ 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.`;
9839
10103
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
9840
10104
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
9841
10105
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -9884,7 +10148,21 @@ var formatSkipError = (err) => {
9884
10148
  }
9885
10149
  return base;
9886
10150
  };
9887
- var MaintenanceService = class {
10151
+ function eraseRuntime() {
10152
+ const g = globalThis;
10153
+ if (g.process?.versions?.node) return `node ${g.process.versions.node}`;
10154
+ return g.HermesInternal ? "hermes" : "unknown";
10155
+ }
10156
+ var EraseStepError = class extends Error {
10157
+ constructor(code, message, report, cause) {
10158
+ super(message);
10159
+ this.code = code;
10160
+ this.report = report;
10161
+ this.name = "EraseStepError";
10162
+ if (cause !== void 0) this.cause = cause;
10163
+ }
10164
+ };
10165
+ var _MaintenanceService = class _MaintenanceService {
9888
10166
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
9889
10167
  this.db = db;
9890
10168
  this.prefix = prefix;
@@ -9904,7 +10182,15 @@ var MaintenanceService = class {
9904
10182
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
9905
10183
  }
9906
10184
  async runPrune(entityId, options) {
9907
- this.jobManager.acquireLock("prune", entityId);
10185
+ return this._runPrune(entityId, options, "host");
10186
+ }
10187
+ /**
10188
+ * Shared prune body. `owner: 'erase'` lets erase()'s own per-entity prune
10189
+ * through the universal erase fence in JobManager; the public `runPrune`
10190
+ * always passes `'host'`.
10191
+ */
10192
+ async _runPrune(entityId, options, owner) {
10193
+ this.jobManager.acquireLock("prune", entityId, void 0, owner);
9908
10194
  try {
9909
10195
  const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
9910
10196
  const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
@@ -9935,8 +10221,9 @@ var MaintenanceService = class {
9935
10221
  }
9936
10222
  }
9937
10223
  if (retainSoftDeletedFor !== null) {
9938
- const cutoff = now - retainSoftDeletedFor * 864e5;
9939
- const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
10224
+ const softDeletedAll = options?.softDeletedCutoff === "all";
10225
+ const cutoff = softDeletedAll ? 0 : options?.softDeletedCutoff ?? now - retainSoftDeletedFor * 864e5;
10226
+ const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff, void 0, { noCutoff: softDeletedAll });
9940
10227
  const prunableIds = entriesToDelete.map((r) => r.id);
9941
10228
  const vr = this.vectorRemoval;
9942
10229
  const vrRepo = this.vectorRemovalRepo;
@@ -9982,7 +10269,7 @@ var MaintenanceService = class {
9982
10269
  }
9983
10270
  if (deletable.length > 0) {
9984
10271
  const deletedIds = [];
9985
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
10272
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds, noCutoff: softDeletedAll });
9986
10273
  if (hookLedger) {
9987
10274
  const gone = new Set(deletedIds);
9988
10275
  const skipped = deletable.filter((id) => !gone.has(id));
@@ -9997,7 +10284,7 @@ var MaintenanceService = class {
9997
10284
  else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
9998
10285
  }
9999
10286
  }
10000
- deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
10287
+ deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
10001
10288
  });
10002
10289
  if (hookLedger) {
10003
10290
  const keptSet = new Set(kept);
@@ -10042,12 +10329,20 @@ var MaintenanceService = class {
10042
10329
  }
10043
10330
  }
10044
10331
  }
10332
+ let vacuumCheckpointErr;
10045
10333
  if (vacuum) {
10046
- await resetNormalizeWatermarks(this.metadataRepo);
10047
- await this.metadataRepo.vacuum();
10048
- await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
10334
+ try {
10335
+ await this._wrappedVacuum();
10336
+ } catch (err) {
10337
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
10338
+ vacuumCheckpointErr = err;
10339
+ }
10049
10340
  }
10341
+ if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
10050
10342
  await this.searchService.syncEntries(entityId, syncedIds);
10343
+ if (prunePartial && vacuumCheckpointErr) {
10344
+ emitDiagnostic(this.options, { code: "prune_checkpoint_incomplete", operation: "prune", trigger: "call", entityId, detail: { reason: vacuumCheckpointErr.message } });
10345
+ }
10051
10346
  if (prunePartial) {
10052
10347
  throw new PrunePartialFailureError(
10053
10348
  deletedEntries,
@@ -10058,11 +10353,422 @@ var MaintenanceService = class {
10058
10353
  deletedEvents
10059
10354
  );
10060
10355
  }
10356
+ if (vacuumCheckpointErr) throw vacuumCheckpointErr;
10061
10357
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
10062
10358
  } finally {
10063
10359
  this.jobManager.releaseLock("prune", entityId);
10064
10360
  }
10065
10361
  }
10362
+ /** Shared by runPrune and erase step 5. */
10363
+ async _wrappedVacuum() {
10364
+ await resetNormalizeWatermarks(this.metadataRepo);
10365
+ let checkpointErr;
10366
+ try {
10367
+ await this.metadataRepo.vacuum();
10368
+ } catch (err) {
10369
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
10370
+ checkpointErr = err;
10371
+ }
10372
+ await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
10373
+ if (checkpointErr) throw checkpointErr;
10374
+ }
10375
+ /**
10376
+ * Erase core (forget-erasure spec §2, steps 0 / 1 / 1b). Thin entry: T6
10377
+ * completes the pipeline (FTS, VACUUM, checkpoint, sync). Never reports a
10378
+ * success it cannot verify: a failed step throws {@link EraseStepError}
10379
+ * carrying the partial report with `verified: false`.
10380
+ */
10381
+ async erase(opts) {
10382
+ const rebuild = opts?.rebuild === true;
10383
+ this.jobManager.acquireLock("erase", "*");
10384
+ const report = {
10385
+ verified: false,
10386
+ secureDelete: null,
10387
+ sqliteVersion: "",
10388
+ entities: [],
10389
+ holds: [],
10390
+ skipped: [],
10391
+ syncedIds: [],
10392
+ registrySweep: { skipped: false, deleted: 0 },
10393
+ retiredUndroppable: [],
10394
+ ftsOrphansCleared: [],
10395
+ failedStep: null,
10396
+ runtime: eraseRuntime(),
10397
+ steps: []
10398
+ };
10399
+ const ok = (step, outcome = "ok") => {
10400
+ report.steps.push({ step, outcome });
10401
+ };
10402
+ try {
10403
+ const readPragma = async () => (await this.db.getFirstAsync("PRAGMA secure_delete"))?.secure_delete ?? null;
10404
+ let pragma;
10405
+ try {
10406
+ pragma = await readPragma();
10407
+ if (pragma !== 1) {
10408
+ await this.db.execAsync("PRAGMA secure_delete=ON");
10409
+ pragma = await readPragma();
10410
+ }
10411
+ report.secureDelete = pragma;
10412
+ report.sqliteVersion = (await this.db.getFirstAsync("SELECT sqlite_version() AS v"))?.v ?? "";
10413
+ } catch (err) {
10414
+ report.failedStep = "secure_delete";
10415
+ throw new EraseStepError("erase_secure_delete_read_failed", "erase stopped at step 0: secure_delete pragma read failed; erasure is unverified", report, err);
10416
+ }
10417
+ if (pragma !== 1) {
10418
+ emitDiagnostic(this.options, { code: "erase_secure_delete_off", operation: "erase", trigger: "call", entityId: "" });
10419
+ report.failedStep = "secure_delete";
10420
+ throw new EraseStepError("erase_secure_delete_off", "erase stopped at step 0: secure_delete is not ON; erasure is unverified", report);
10421
+ }
10422
+ ok("secure_delete");
10423
+ try {
10424
+ report.entities = await this.metadataRepo.getDistinctEntityIds(void 0, { softDeletedAll: true });
10425
+ } catch (err) {
10426
+ report.failedStep = "prune";
10427
+ throw new EraseStepError("erase_prune_failed", "erase stopped at step 1: the entity walk failed; erasure is unverified", report, err);
10428
+ }
10429
+ const syncedByEntity = /* @__PURE__ */ new Map();
10430
+ for (const entityId of report.entities) {
10431
+ const syncedIds = [];
10432
+ syncedByEntity.set(entityId, syncedIds);
10433
+ try {
10434
+ await this._runPrune(entityId, { retainSoftDeletedFor: 0, retainEventsFor: null, vacuum: false, syncedIds, softDeletedCutoff: "all" }, "erase");
10435
+ } catch (err) {
10436
+ if (err instanceof PrunePartialFailureError) {
10437
+ report.holds.push({ entityId, deleted: err.deleted, deletedTasks: err.deletedTasks, failedAt: err.failedAt, remaining: err.remaining });
10438
+ } else if (err instanceof WikiBusyError) {
10439
+ report.skipped.push(entityId);
10440
+ emitDiagnostic(this.options, { code: "erase_entity_skipped", operation: "erase", trigger: "call", entityId });
10441
+ } else {
10442
+ report.failedStep = "prune";
10443
+ throw new EraseStepError("erase_prune_failed", `erase stopped at step 1 (entity ${entityId})`, report, err);
10444
+ }
10445
+ }
10446
+ for (const id of syncedIds) report.syncedIds.push(id);
10447
+ }
10448
+ ok("prune", report.holds.length > 0 || report.skipped.length > 0 ? "partial" : "ok");
10449
+ try {
10450
+ await this.db.withTransactionAsync(async (tx) => {
10451
+ if (await this.sourceRefIndexPresent(tx)) {
10452
+ const r = await tx.runAsync(`DELETE FROM ${this.prefix}source_ref_index WHERE deleted_at IS NOT NULL`);
10453
+ report.registrySweep = { skipped: false, deleted: r.changes };
10454
+ } else {
10455
+ report.registrySweep = { skipped: true, deleted: 0 };
10456
+ }
10457
+ });
10458
+ } catch (err) {
10459
+ report.failedStep = "registry_sweep";
10460
+ throw new EraseStepError("erase_registry_sweep_failed", "erase stopped at step 1b", report, err);
10461
+ }
10462
+ if (report.registrySweep.skipped) {
10463
+ emitDiagnostic(this.options, { code: "erase_registry_sweep_skipped", operation: "erase", trigger: "call", entityId: "" });
10464
+ }
10465
+ ok("registry_sweep", report.registrySweep.skipped ? "partial" : "ok");
10466
+ await this._eraseDrainPassages(report);
10467
+ ok("passage_drain");
10468
+ await this._eraseReclaimRetired(report);
10469
+ ok("retired_reclaim");
10470
+ try {
10471
+ await this._wrappedVacuum();
10472
+ } catch (err) {
10473
+ if (err instanceof CheckpointIncompleteError) {
10474
+ report.failedStep = "checkpoint";
10475
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 5: WAL checkpoint incomplete; erasure is unverified", report, err);
10476
+ }
10477
+ report.failedStep = "vacuum";
10478
+ 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);
10479
+ }
10480
+ ok("vacuum");
10481
+ const byEntity = /* @__PURE__ */ new Map();
10482
+ for (const e of report.entities) byEntity.set(e, []);
10483
+ for (const [entityId, ids] of syncedByEntity) byEntity.set(entityId, ids);
10484
+ for (const [entityId, ids] of byEntity) {
10485
+ if (ids.length > 0) await this._eraseSyncEntries(entityId, ids, report);
10486
+ }
10487
+ ok("index_sync");
10488
+ if (rebuild) {
10489
+ try {
10490
+ await this.searchService.rebuildSurfaced();
10491
+ } catch (err) {
10492
+ report.failedStep = "rebuild";
10493
+ throw new EraseStepError("erase_rebuild_failed", "erase stopped at step 7: FTS rebuild failed", report, err);
10494
+ }
10495
+ ok("rebuild");
10496
+ }
10497
+ await this._eraseReclaimRetired(report);
10498
+ let present;
10499
+ try {
10500
+ present = await this.db.getAllAsync(
10501
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%entries_fts_retired_%'`
10502
+ );
10503
+ } catch (err) {
10504
+ report.failedStep = "retired_reclaim";
10505
+ emitDiagnostic(this.options, { code: "erase_retired_read_failed", operation: "erase", trigger: "call", entityId: "" });
10506
+ throw new EraseStepError("erase_retired_read_failed", "erase stopped after step 6: the retired-table read failed; erasure is unverified", report, err);
10507
+ }
10508
+ const left = present.map((r) => r.name).filter((n) => isRetiredTableName(this.prefix, n) && !report.retiredUndroppable.includes(n));
10509
+ if (left.length > 0) {
10510
+ report.failedStep = "retired_reclaim";
10511
+ emitDiagnostic(this.options, { code: "erase_retired_remaining", operation: "erase", trigger: "call", entityId: "", detail: { tables: left } });
10512
+ throw new EraseStepError("erase_retired_remaining", `erase stopped after step 6: retired FTS tables remain (${left.join(", ")})`, report);
10513
+ }
10514
+ ok("retired_reclaim_rerun");
10515
+ await this._eraseOptimize(report);
10516
+ ok("optimize");
10517
+ try {
10518
+ await this.metadataRepo.checkpointTruncateVerified();
10519
+ } catch (err) {
10520
+ report.failedStep = "checkpoint";
10521
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 8: WAL checkpoint incomplete; erasure is unverified", report, err);
10522
+ }
10523
+ ok("checkpoint");
10524
+ if (report.skipped.length === 0 && report.holds.length === 0) {
10525
+ let remainingTombstones;
10526
+ try {
10527
+ const row = await this.db.getFirstAsync(
10528
+ `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
10529
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
10530
+ );
10531
+ remainingTombstones = row?.n ?? 0;
10532
+ } catch (err) {
10533
+ report.failedStep = "tombstone_gate";
10534
+ throw new EraseStepError("erase_tombstone_gate_failed", "erase stopped at step 9: could not count remaining tombstones; erasure is unverified", report, err);
10535
+ }
10536
+ if (remainingTombstones > 0) {
10537
+ emitDiagnostic(this.options, { code: "erase_tombstones_remaining", operation: "erase", trigger: "call", entityId: "", detail: { count: remainingTombstones } });
10538
+ report.failedStep = "tombstone_gate";
10539
+ throw new EraseStepError("erase_tombstones_remaining", `erase stopped at step 9: ${remainingTombstones} soft-deleted row(s) remain; erasure is unverified`, report);
10540
+ }
10541
+ ok("tombstone_gate");
10542
+ } else {
10543
+ report.steps.push({ step: "tombstone_gate", outcome: "partial" });
10544
+ }
10545
+ report.verified = report.skipped.length === 0 && report.holds.length === 0;
10546
+ return report;
10547
+ } catch (err) {
10548
+ if (err instanceof EraseStepError && err.report === report && report.failedStep) {
10549
+ report.steps.push({ step: report.failedStep, outcome: "failed" });
10550
+ report.verified = false;
10551
+ }
10552
+ throw err;
10553
+ } finally {
10554
+ this.jobManager.releaseLock("erase", "*");
10555
+ }
10556
+ }
10557
+ /**
10558
+ * Step 3 remediation (specs/erase-fts-remediation): on a runtime without
10559
+ * usable strict drains, clear orphaned FTS5 surfaces so erasure can
10560
+ * complete verified. Per surface: existence gate (vtab OR any shadow) →
10561
+ * strategy check → vtab probe → path body → companions → state write.
10562
+ * Dispatch order is D4; exact-name allowlist interpolation is D2.
10563
+ */
10564
+ async _eraseClearFtsOrphans(report) {
10565
+ const surfaces = [`${this.prefix}entries_fts`, `${this.prefix}source_passages_fts`];
10566
+ let remediationRequired = false;
10567
+ const pathBTargets = [];
10568
+ try {
10569
+ for (const surface of surfaces) {
10570
+ const vtabExists = await this.sourceTableExists(surface);
10571
+ const shadows = [];
10572
+ for (const sfx of _MaintenanceService.FTS_SHADOW_SUFFIXES) {
10573
+ const name = `${surface}${sfx}`;
10574
+ if (await this.sourceTableExists(name)) shadows.push(name);
10575
+ }
10576
+ if (!vtabExists && shadows.length === 0) continue;
10577
+ remediationRequired = true;
10578
+ if (this.searchService.isIndexUnavailable()) {
10579
+ report.failedStep = "index_sync";
10580
+ 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);
10581
+ }
10582
+ let moduleLess = false;
10583
+ if (vtabExists) {
10584
+ try {
10585
+ await this.db.getFirstAsync(`SELECT 1 AS x FROM ${surface} LIMIT 1`);
10586
+ } catch (err) {
10587
+ let absent = false;
10588
+ let cur = err;
10589
+ for (let depth = 0; depth < 3 && cur != null && !absent; depth++) {
10590
+ let msg = "";
10591
+ try {
10592
+ msg = String(cur.message ?? cur);
10593
+ } catch {
10594
+ break;
10595
+ }
10596
+ absent = /no such module/i.test(msg);
10597
+ try {
10598
+ cur = cur.cause;
10599
+ } catch {
10600
+ break;
10601
+ }
10602
+ }
10603
+ if (!absent) {
10604
+ report.failedStep = "index_sync";
10605
+ throw new EraseStepError("erase_fts_orphan_probe_failed", `erase stopped at step 3: could not classify orphaned vtab ${surface}`, report, err);
10606
+ }
10607
+ moduleLess = true;
10608
+ }
10609
+ }
10610
+ if (vtabExists && !moduleLess) {
10611
+ if (this.options.config?.indexStrategy !== "minisearch") {
10612
+ report.failedStep = "index_sync";
10613
+ 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);
10614
+ }
10615
+ pathBTargets.push(surface);
10616
+ continue;
10617
+ }
10618
+ const cleared = [];
10619
+ for (const name of shadows) {
10620
+ if (name.endsWith("_config")) continue;
10621
+ const res = await this.db.runAsync(name.endsWith("_data") ? `DELETE FROM ${name} WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}`);
10622
+ if ((res?.changes ?? 0) > 0) cleared.push(name);
10623
+ }
10624
+ for (const name of cleared) {
10625
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
10626
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
10627
+ }
10628
+ }
10629
+ if (!remediationRequired) return;
10630
+ const tailCleared = [];
10631
+ await this.db.withTransactionAsync(async (tx) => {
10632
+ for (const companion of [`${this.prefix}fts_pending`, `${this.prefix}fts_map`, `${this.prefix}source_passages_fts_pending`, `${this.prefix}source_passages_fts_map`]) {
10633
+ if (await this.sourceTableExists(companion, tx)) {
10634
+ const res = await tx.runAsync(`DELETE FROM ${companion}`);
10635
+ if ((res?.changes ?? 0) > 0 && !tailCleared.includes(companion)) tailCleared.push(companion);
10636
+ }
10637
+ }
10638
+ for (const surface of pathBTargets) {
10639
+ await tx.execAsync(`DROP TABLE IF EXISTS ${surface}`);
10640
+ if (!tailCleared.includes(surface)) tailCleared.push(surface);
10641
+ }
10642
+ if (pathBTargets.length > 0) {
10643
+ const [ai, ad] = passageFtsTriggerNames(this.prefix);
10644
+ await tx.execAsync(fts5LedgerDropSql(this.prefix) + `
10645
+ DROP TRIGGER IF EXISTS ${ai};
10646
+ DROP TRIGGER IF EXISTS ${ad};`);
10647
+ }
10648
+ await this.metadataRepo.setMeta(FTS5_STATE_KEY, "detached", tx);
10649
+ });
10650
+ for (const name of tailCleared) {
10651
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
10652
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
10653
+ }
10654
+ report.steps.push({ step: "fts_orphan_clear", outcome: "ok" });
10655
+ } catch (err) {
10656
+ if (err instanceof EraseStepError) throw err;
10657
+ report.failedStep = "fts_orphan_clear";
10658
+ throw new EraseStepError("erase_fts_orphan_clear", "erase stopped at step 3: clearing an orphaned FTS surface failed; erasure is unverified", report, err);
10659
+ }
10660
+ }
10661
+ /**
10662
+ * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
10663
+ * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
10664
+ * N2 guard (probe lives here, strategy-agnostic): a strategy without the strict
10665
+ * drains (Unavailable / MiniSearch) cannot drain, so rows in either FTS ledger
10666
+ * mean text was never drained -> the step fails and erasure is unverified.
10667
+ * Absent or empty ledgers proceed.
10668
+ */
10669
+ async _eraseDrainPassages(report) {
10670
+ if (!this.searchService.hasStrictDrain()) {
10671
+ await this._eraseClearFtsOrphans(report);
10672
+ for (const [table, failedStep, code] of [
10673
+ [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
10674
+ [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
10675
+ ]) {
10676
+ let rows = false;
10677
+ try {
10678
+ rows = await this.sourceTableExists(table) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${table} LIMIT 1`) != null;
10679
+ } catch (err) {
10680
+ report.failedStep = failedStep;
10681
+ throw new EraseStepError(code, `erase stopped at step 3: could not probe ${table}`, report, err);
10682
+ }
10683
+ if (rows) {
10684
+ report.failedStep = failedStep;
10685
+ 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);
10686
+ }
10687
+ }
10688
+ }
10689
+ try {
10690
+ await this.searchService.drainEntriesLedgerSurfaced();
10691
+ } catch (err) {
10692
+ report.failedStep = "index_sync";
10693
+ throw new EraseStepError("erase_index_sync_failed", "erase stopped at step 3: entries ledger drain failed", report, err);
10694
+ }
10695
+ try {
10696
+ await this.searchService.drainPassagesSurfaced();
10697
+ } catch (err) {
10698
+ report.failedStep = "passage_drain";
10699
+ throw new EraseStepError("erase_passage_drain_failed", "erase stopped at step 3: passage drain failed", report, err);
10700
+ }
10701
+ }
10702
+ /**
10703
+ * Step 4 (and its re-run after step 6): reclaim retired FTS tables to
10704
+ * completion. A module-less runtime cannot DROP a virtual table, so each
10705
+ * retired table's shadow tables are emptied under the pragma and the name
10706
+ * stays listed; a later FTS5-capable open's step 4 completes the DROP.
10707
+ */
10708
+ async _eraseReclaimRetired(report) {
10709
+ if (this.searchService.canReclaimRetired()) {
10710
+ try {
10711
+ await this.searchService.reclaimRetiredSurfaced();
10712
+ return;
10713
+ } catch (err) {
10714
+ if (!/no such module/i.test(err instanceof Error ? err.message : String(err))) {
10715
+ report.failedStep = "retired_reclaim";
10716
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: retired FTS table reclaim failed", report, err);
10717
+ }
10718
+ }
10719
+ }
10720
+ try {
10721
+ for (const name of await this._retiredList()) {
10722
+ for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
10723
+ if (sfx === "_config") continue;
10724
+ if (await this.sourceTableExists(`${name}${sfx}`)) {
10725
+ await this.db.runAsync(sfx === "_data" ? `DELETE FROM ${name}_data WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}${sfx}`);
10726
+ }
10727
+ }
10728
+ if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
10729
+ emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
10730
+ }
10731
+ } catch (err) {
10732
+ report.failedStep = "retired_reclaim";
10733
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: module-less shadow-table clear failed", report, err);
10734
+ }
10735
+ }
10736
+ /** Retired list straight from metadata (same key Fts5IndexStrategy maintains), independent of the active strategy. */
10737
+ async _retiredList() {
10738
+ let raw;
10739
+ try {
10740
+ raw = JSON.parse(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY) ?? "[]");
10741
+ } catch {
10742
+ return [];
10743
+ }
10744
+ return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
10745
+ }
10746
+ sourceTableExists(name, tx) {
10747
+ return this.metadataRepo.tableExists(name, tx);
10748
+ }
10749
+ /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
10750
+ async _eraseSyncEntries(entityId, ids, report) {
10751
+ let ok = false;
10752
+ try {
10753
+ ok = await this.searchService.syncEntries(entityId, ids);
10754
+ } catch (err) {
10755
+ report.failedStep = "index_sync";
10756
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId})`, report, err);
10757
+ }
10758
+ if (!ok) {
10759
+ report.failedStep = "index_sync";
10760
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId}): ledger drain failed`, report);
10761
+ }
10762
+ }
10763
+ /** Step 7: FTS optimize on both FTS tables, after syncEntries. */
10764
+ async _eraseOptimize(report) {
10765
+ try {
10766
+ await this.searchService.optimizeSurfaced();
10767
+ } catch (err) {
10768
+ report.failedStep = "optimize";
10769
+ throw new EraseStepError("erase_optimize_failed", "erase stopped at step 7: FTS optimize failed", report, err);
10770
+ }
10771
+ }
10066
10772
  async runLibrarian(entityId, options) {
10067
10773
  this.jobManager.acquireLock("librarian", entityId);
10068
10774
  try {
@@ -10183,6 +10889,9 @@ var MaintenanceService = class {
10183
10889
  if (params.includeEvents && !params.clearAll) {
10184
10890
  throw new Error("forget() includeEvents requires clearAll: true");
10185
10891
  }
10892
+ if (params.includeChain && (params.entryId === void 0 || params.clearAll || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
10893
+ throw new Error("forget() includeChain composes only with entryId");
10894
+ }
10186
10895
  if (opts?.dryRun === true) {
10187
10896
  return this.forgetDryRun(entityId, params);
10188
10897
  }
@@ -10192,6 +10901,8 @@ var MaintenanceService = class {
10192
10901
  let deletedEntries = 0;
10193
10902
  let deletedTasks = 0;
10194
10903
  let deletedEvents = 0;
10904
+ let chainIds = [];
10905
+ let chainTruncated = false;
10195
10906
  const deletedEntryIds = [];
10196
10907
  const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
10197
10908
  await this.db.withTransactionAsync(async (tx) => {
@@ -10228,6 +10939,12 @@ var MaintenanceService = class {
10228
10939
  if (params.entryId) {
10229
10940
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
10230
10941
  if (entryId) deletedEntryIds.push(entryId);
10942
+ if (entryId && params.includeChain) {
10943
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, entryId, HISTORY_MAX_DEPTH, tx);
10944
+ chainIds = walk.ids.filter((id) => id !== entryId);
10945
+ chainTruncated = walk.truncated;
10946
+ for (const id of chainIds) deletedEntryIds.push(id);
10947
+ }
10231
10948
  }
10232
10949
  if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
10233
10950
  const docs = `${this.prefix}source_documents`;
@@ -10253,6 +10970,9 @@ var MaintenanceService = class {
10253
10970
  sourceRefIndexPromise ?? Promise.resolve(void 0)
10254
10971
  ]);
10255
10972
  if (entryResult) deletedEntries++;
10973
+ for (const id of chainIds) {
10974
+ if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
10975
+ }
10256
10976
  if (taskResult) deletedTasks++;
10257
10977
  deletedEntries += refResult;
10258
10978
  }
@@ -10306,7 +11026,17 @@ var MaintenanceService = class {
10306
11026
  });
10307
11027
  }
10308
11028
  }
10309
- if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
11029
+ if (!params.clearAll) {
11030
+ const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
11031
+ if (params.includeChain) {
11032
+ base.chainEntryIds = chainIds;
11033
+ if (chainTruncated) {
11034
+ base.truncated = true;
11035
+ base.notice = CHAIN_TRUNCATED_NOTICE;
11036
+ }
11037
+ }
11038
+ return base;
11039
+ }
10310
11040
  return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
10311
11041
  } finally {
10312
11042
  this.jobManager.releaseLock("forget", entityId);
@@ -10372,8 +11102,25 @@ var MaintenanceService = class {
10372
11102
  * (the spec keeps dry-run narrow).
10373
11103
  */
10374
11104
  async forgetDryRun(entityId, params) {
11105
+ if (params.entryId !== void 0 && params.includeChain && params.taskId === void 0) {
11106
+ const id = await this.entryRepo.findIdById(params.entryId, entityId);
11107
+ if (!id) return { deleted: { entries: 0, tasks: 0 }, chainEntryIds: [] };
11108
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, id, HISTORY_MAX_DEPTH);
11109
+ const chainEntryIds = walk.ids.filter((c) => c !== id);
11110
+ const all = [id, ...chainEntryIds];
11111
+ const live = await this.db.getFirstAsync(
11112
+ `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND id IN (${all.map(() => "?").join(",")})`,
11113
+ [entityId, ...all]
11114
+ );
11115
+ const out = { deleted: { entries: live?.n ?? 0, tasks: 0 }, chainEntryIds };
11116
+ if (walk.truncated) {
11117
+ out.truncated = true;
11118
+ out.notice = CHAIN_TRUNCATED_NOTICE;
11119
+ }
11120
+ return out;
11121
+ }
10375
11122
  if (params.entryId !== void 0 || params.taskId !== void 0) {
10376
- throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors; use sourceRef/sourceHash or clearAll");
11123
+ throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors (entryId is accepted only with includeChain); use sourceRef/sourceHash or clearAll");
10377
11124
  }
10378
11125
  if (params.clearAll) {
10379
11126
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
@@ -11092,6 +11839,9 @@ var MaintenanceService = class {
11092
11839
  return sanitizeRankerError(err, this.options.sanitizeRankerErrors);
11093
11840
  }
11094
11841
  };
11842
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
11843
+ _MaintenanceService.FTS_SHADOW_SUFFIXES = ["_content", "_data", "_idx", "_docsize", "_config"];
11844
+ var MaintenanceService = _MaintenanceService;
11095
11845
 
11096
11846
  // src/services/MaintenanceScheduler.ts
11097
11847
  var MaintenanceScheduler = class {
@@ -11420,7 +12170,8 @@ var ImportExportService = class {
11420
12170
  this.vectorRemoval = vectorRemoval;
11421
12171
  this.prefix = prefix;
11422
12172
  }
11423
- async exportDump(entityIds) {
12173
+ async exportDump(entityIds, opts) {
12174
+ const includeForgotten = opts?.includeForgotten === true;
11424
12175
  let ids;
11425
12176
  if (entityIds && entityIds.length > 0) {
11426
12177
  ids = Array.from(new Set(entityIds));
@@ -11441,7 +12192,7 @@ var ImportExportService = class {
11441
12192
  const batchResults = await Promise.all(
11442
12193
  batch.map(
11443
12194
  async (id) => {
11444
- const bundle = await this.getFullBundle(id, { includeBlobs: true });
12195
+ const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
11445
12196
  const storedSources = await this.exportStoredSources(id);
11446
12197
  return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
11447
12198
  }
@@ -11547,10 +12298,11 @@ var ImportExportService = class {
11547
12298
  }
11548
12299
  }
11549
12300
  async getFullBundle(entityId, opts) {
12301
+ const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
11550
12302
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
11551
12303
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
11552
- opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
11553
- this.taskRepo.findAllByEntityId(entityId),
12304
+ opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
12305
+ this.taskRepo.findAllByEntityId(entityId, void 0, incl),
11554
12306
  this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
11555
12307
  this.edgeRepo.getByEntityId(entityId),
11556
12308
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
@@ -11586,12 +12338,15 @@ var ImportExportService = class {
11586
12338
  const skippedSources = [];
11587
12339
  const refusalDiagnostics = [];
11588
12340
  const upsertedFactIds = /* @__PURE__ */ new Set();
12341
+ const liveEmbedFactIds = /* @__PURE__ */ new Set();
11589
12342
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
11590
12343
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
11591
12344
  const preservedBlobDims = /* @__PURE__ */ new Set();
11592
12345
  const softDeletedFactIds = [];
12346
+ const softDeletedTaskIds = [];
11593
12347
  const clippedTextByFactId = /* @__PURE__ */ new Map();
11594
12348
  let clampedEvents = 0;
12349
+ let tombstoneSkipped = 0;
11595
12350
  const restamped = { behind_watermark: 0, invalid: 0 };
11596
12351
  await this.db.withTransactionAsync(async (tx) => {
11597
12352
  if (!merge) {
@@ -11602,8 +12357,9 @@ var ImportExportService = class {
11602
12357
  tx,
11603
12358
  false
11604
12359
  );
11605
- softDeletedFactIds.push(...deletedLiveFactIds);
12360
+ for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
11606
12361
  await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
12362
+ for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
11607
12363
  await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
11608
12364
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
11609
12365
  await this.metadataRepo.deleteCheckpoint(entityId, tx);
@@ -11613,6 +12369,8 @@ var ImportExportService = class {
11613
12369
  } else if (!merge) {
11614
12370
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
11615
12371
  }
12372
+ const wipedByThisImport = new Set(softDeletedFactIds);
12373
+ const wipedTasksByThisImport = new Set(softDeletedTaskIds);
11616
12374
  const factIds = bundle.facts.map((fact) => fact.id);
11617
12375
  const existingFactsById = /* @__PURE__ */ new Map();
11618
12376
  const existingFacts = await this.entryRepo.findExistingMetadataByIds(
@@ -11688,11 +12446,16 @@ var ImportExportService = class {
11688
12446
  );
11689
12447
  continue;
11690
12448
  }
11691
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
12449
+ if (existing.deleted_at != null && fact.deleted_at == null && !wipedByThisImport.has(fact.id)) {
12450
+ tombstoneSkipped++;
12451
+ continue;
12452
+ }
12453
+ if (merge && safeUpdatedAt <= existing.updated_at && fact.deleted_at == null) continue;
11692
12454
  }
11693
12455
  const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
11694
12456
  const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
11695
- clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody });
12457
+ const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
12458
+ clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
11696
12459
  let normalizedSourceRef = null;
11697
12460
  if (fact.source_ref !== null && fact.source_ref !== void 0) {
11698
12461
  normalizedSourceRef = normalizeSourceRef(fact.source_ref);
@@ -11759,15 +12522,22 @@ var ImportExportService = class {
11759
12522
  }, tx, { outbox: false });
11760
12523
  if (blobData != null) {
11761
12524
  factsWithPreservedBlob.set(fact.id, blobData);
11762
- if (!fact.deleted_at) preservedBlobDims.add(blobData.byteLength / 4);
12525
+ if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
11763
12526
  }
11764
12527
  existingFactsById.set(fact.id, {
11765
12528
  id: fact.id,
11766
12529
  entity_id: entityId,
11767
- updated_at: safeUpdatedAt
12530
+ updated_at: safeUpdatedAt,
12531
+ deleted_at: fact.deleted_at ?? null
11768
12532
  });
12533
+ wipedByThisImport.delete(fact.id);
11769
12534
  upsertedFactIds.add(fact.id);
11770
- if (fact.deleted_at) upsertedDeletedFactIds.add(fact.id);
12535
+ if (fact.deleted_at != null) {
12536
+ upsertedDeletedFactIds.add(fact.id);
12537
+ liveEmbedFactIds.delete(fact.id);
12538
+ } else {
12539
+ liveEmbedFactIds.add(fact.id);
12540
+ }
11771
12541
  }
11772
12542
  const taskIds = bundle.tasks.map((task) => task.id);
11773
12543
  const existingTasksById = /* @__PURE__ */ new Map();
@@ -11791,7 +12561,11 @@ var ImportExportService = class {
11791
12561
  );
11792
12562
  continue;
11793
12563
  }
11794
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
12564
+ if (existing.deleted_at != null && task.deleted_at == null && !wipedTasksByThisImport.has(task.id)) {
12565
+ tombstoneSkipped++;
12566
+ continue;
12567
+ }
12568
+ if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
11795
12569
  }
11796
12570
  await this.taskRepo.upsertForImport(
11797
12571
  {
@@ -11824,8 +12598,10 @@ var ImportExportService = class {
11824
12598
  existingTasksById.set(task.id, {
11825
12599
  id: task.id,
11826
12600
  entity_id: entityId,
11827
- updated_at: safeUpdatedAt
12601
+ updated_at: safeUpdatedAt,
12602
+ deleted_at: task.deleted_at ?? null
11828
12603
  });
12604
+ wipedTasksByThisImport.delete(task.id);
11829
12605
  }
11830
12606
  const now = Date.now();
11831
12607
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
@@ -11865,6 +12641,15 @@ var ImportExportService = class {
11865
12641
  await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
11866
12642
  });
11867
12643
  for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
12644
+ if (tombstoneSkipped > 0) {
12645
+ emitDiagnostic(this.options, {
12646
+ code: "import_tombstone_skipped",
12647
+ operation: "importDump",
12648
+ trigger: "call",
12649
+ entityId,
12650
+ detail: { count: tombstoneSkipped }
12651
+ });
12652
+ }
11868
12653
  if (clampedEvents > 0) {
11869
12654
  emitDiagnostic(this.options, {
11870
12655
  code: "event_created_at_clamped",
@@ -11890,28 +12675,28 @@ var ImportExportService = class {
11890
12675
  } else {
11891
12676
  await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
11892
12677
  }
11893
- for (const fact of bundle.facts) {
11894
- if (!fact.deleted_at && upsertedFactIds.has(fact.id) && !factsWithPreservedBlob.has(fact.id)) {
11895
- const clipped = clippedTextByFactId.get(fact.id);
12678
+ for (const id of liveEmbedFactIds) {
12679
+ if (!factsWithPreservedBlob.has(id)) {
12680
+ const clipped = clippedTextByFactId.get(id);
11896
12681
  const embedded = await this.embeddingService.embedFact({
11897
- id: fact.id,
12682
+ id,
11898
12683
  entity_id: entityId,
11899
- title: clipped?.title ?? fact.title,
11900
- body: clipped?.body ?? fact.body,
11901
- tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
12684
+ title: clipped?.title ?? "",
12685
+ body: clipped?.body ?? "",
12686
+ tags: clipped?.tags ?? []
11902
12687
  }, { operation: "importDump", trigger: "call" });
11903
12688
  if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
11904
12689
  try {
11905
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
12690
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
11906
12691
  } catch (hookErr) {
11907
12692
  console.warn(
11908
- `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
12693
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
11909
12694
  hookErr
11910
12695
  );
11911
12696
  this.embeddingService.reportHookFailed(
11912
12697
  { operation: "importDump", trigger: "call" },
11913
12698
  entityId,
11914
- fact.id
12699
+ id
11915
12700
  );
11916
12701
  }
11917
12702
  }
@@ -11919,7 +12704,7 @@ var ImportExportService = class {
11919
12704
  }
11920
12705
  for (const fact of bundle.facts) {
11921
12706
  const blobData = factsWithPreservedBlob.get(fact.id);
11922
- if (blobData && !fact.deleted_at && upsertedFactIds.has(fact.id)) {
12707
+ if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
11923
12708
  try {
11924
12709
  const float32Vector = new Float32Array(
11925
12710
  blobData.buffer,
@@ -14345,6 +15130,13 @@ var WikiMemory = class {
14345
15130
  * transaction.
14346
15131
  */
14347
15132
  async setup(opts) {
15133
+ await this.db.execAsync("PRAGMA secure_delete=ON");
15134
+ const secureDelete = await this.db.getFirstAsync("PRAGMA secure_delete");
15135
+ if (!secureDelete || Number(secureDelete.secure_delete) !== 1) {
15136
+ console.warn(
15137
+ "[WikiMemory] PRAGMA secure_delete=ON (full zeroing) was not honored by this SQLite runtime; deleted content may remain recoverable in the database file until erase() verifies it."
15138
+ );
15139
+ }
14348
15140
  const setupBudgetMs = this.setupBudgetMs();
14349
15141
  const openDeadline = monotonicNow() + setupBudgetMs;
14350
15142
  const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);
@@ -14627,6 +15419,15 @@ var WikiMemory = class {
14627
15419
  if (options?.prefix === void 0) return ids;
14628
15420
  return ids.filter((id) => id.startsWith(options.prefix));
14629
15421
  }
15422
+ /**
15423
+ * Erase everything soft-deleted, store-wide, and verify it (forget-erasure
15424
+ * spec §2). Throws `EraseStepError` (partial report, `verified: false`) when
15425
+ * a step fails; skipped entities report `verified: false`.
15426
+ * `{ rebuild: true }` additionally restarts the FTS rebuild.
15427
+ */
15428
+ async erase(options) {
15429
+ return this.maintenanceService.erase(options);
15430
+ }
14630
15431
  async runPrune(entityId, options) {
14631
15432
  return this.maintenanceService.runPrune(entityId, options);
14632
15433
  }
@@ -14844,8 +15645,22 @@ var WikiMemory = class {
14844
15645
  async syncDrained(sync) {
14845
15646
  return await sync && this.searchService.isKeywordAvailable();
14846
15647
  }
14847
- async exportDump(entityIds) {
14848
- return this.importExportService.exportDump(entityIds);
15648
+ async exportDump(entityIds, opts) {
15649
+ return this.importExportService.exportDump(entityIds, opts);
15650
+ }
15651
+ /**
15652
+ * The retention windows `runPrune()` uses when the host runs it (shipped
15653
+ * defaults plus host overrides), for GDPR disclosure. Nothing prunes
15654
+ * automatically; `erase()` ignores `retainSoftDeletedFor`. Days; `null`
15655
+ * means "keep forever". Read-only.
15656
+ */
15657
+ getRetentionPolicy() {
15658
+ const c = this.options.config;
15659
+ return {
15660
+ retainSoftDeletedFor: c?.pruneRetainSoftDeletedFor ?? 7,
15661
+ retainEventsFor: c?.pruneEventsAfter ?? 30,
15662
+ pruneSupersededAfter: c?.pruneSupersededAfter ?? null
15663
+ };
14849
15664
  }
14850
15665
  /** Entity summary prose persisted from an OKF profile ≥ 1 import; null when none stored. */
14851
15666
  async getEntitySummary(entityId) {
@@ -14905,11 +15720,23 @@ var WikiMemory = class {
14905
15720
  /**
14906
15721
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
14907
15722
  * transaction. Throws `WikiSupersedeError` for missing, foreign, already
14908
- * superseded, immutable-document, or cyclic targets.
15723
+ * superseded, already expired, immutable-document, or cyclic targets.
14909
15724
  */
14910
15725
  async supersede(entityId, oldId, replacement, options) {
14911
15726
  return this.temporalService.supersede(entityId, oldId, replacement, options);
14912
15727
  }
15728
+ /**
15729
+ * End `factId`'s validity without a replacement — an archive, not a
15730
+ * deletion (INTENT rule 12). Sets `valid_to` only: `superseded_by`,
15731
+ * `superseded_at` and `deleted_at` stay untouched, and an `asOf` read at
15732
+ * `T` with `COALESCE(valid_from, created_at) <= T < valid_to` still returns
15733
+ * the fact. Throws `WikiSupersedeError` for
15734
+ * a missing, foreign, already superseded, immutable-document, or already
15735
+ * expired target, and for an inverted or empty interval (`invalid_interval`).
15736
+ */
15737
+ async expire(entityId, factId, options) {
15738
+ return this.temporalService.expire(entityId, factId, options);
15739
+ }
14913
15740
  /** The supersession chain containing `factId`, oldest first. [] when unknown. */
14914
15741
  async history(entityId, factId) {
14915
15742
  return this.temporalService.history(entityId, factId);
@@ -16219,12 +17046,14 @@ function createWiki(db, options) {
16219
17046
  return new WikiMemory(db, options);
16220
17047
  }
16221
17048
 
17049
+ exports.CheckpointIncompleteError = CheckpointIncompleteError;
16222
17050
  exports.DEFAULT_CHUNK_OVERLAP = DEFAULT_CHUNK_OVERLAP;
16223
17051
  exports.DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT;
16224
17052
  exports.DEFAULT_MAX_CHUNK_LENGTH = DEFAULT_MAX_CHUNK_LENGTH;
16225
17053
  exports.DEFAULT_MAX_EMBED_CHARS = DEFAULT_MAX_EMBED_CHARS;
16226
17054
  exports.DEFAULT_SETUP_BUDGET_MS = DEFAULT_SETUP_BUDGET_MS;
16227
17055
  exports.EMBED_CHARS_CEILING = EMBED_CHARS_CEILING;
17056
+ exports.EraseStepError = EraseStepError;
16228
17057
  exports.HEAL_ANCHORS_PER_CANDIDATE = HEAL_ANCHORS_PER_CANDIDATE;
16229
17058
  exports.HEAL_BATCH_SIZE = HEAL_BATCH_SIZE;
16230
17059
  exports.HEAL_MAX_FACT_BODY_CHARS_L3 = HEAL_MAX_FACT_BODY_CHARS_L3;