@equationalapplications/core-llm-wiki 9.2.0 → 9.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -37,6 +37,15 @@ 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_retired_remaining: "error",
45
+ erase_tombstones_remaining: "error",
46
+ erase_retired_read_failed: "error",
47
+ erase_registry_sweep_skipped: "info",
48
+ import_tombstone_skipped: "info",
40
49
  event_created_at_clamped: "warn",
41
50
  event_created_at_restamped: "info",
42
51
  external_deletion_pending: "warn",
@@ -72,6 +81,15 @@ var MESSAGE = {
72
81
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
73
82
  read_budget: "A read was packed to a token budget.",
74
83
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
84
+ 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.",
85
+ erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
86
+ erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow tables were emptied and the name stays listed until an FTS5-capable open drops it.",
87
+ erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
88
+ erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
89
+ erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
90
+ erase_entity_skipped: "Erase skipped an entity because another operation held its prune lock.",
91
+ erase_registry_sweep_skipped: "Erase skipped the source_ref_index tombstone sweep because the table does not exist (pre-v9 store).",
92
+ 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
93
  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
94
  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
95
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
@@ -2322,10 +2340,15 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2322
2340
  const chunk = ids.slice(i, i + this.chunkSize);
2323
2341
  const placeholders = chunk.map(() => "?").join(",");
2324
2342
  const chunkRows = await executor.getAllAsync(
2325
- `SELECT id, entity_id, updated_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
2343
+ `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
2326
2344
  chunk
2327
2345
  );
2328
- rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));
2346
+ rows.push(...chunkRows.map((row) => ({
2347
+ id: row.id,
2348
+ entity_id: row.entity_id,
2349
+ updated_at: Number(row.updated_at),
2350
+ deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
2351
+ })));
2329
2352
  }
2330
2353
  return rows;
2331
2354
  }
@@ -2497,22 +2520,25 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2497
2520
  * Fetch IDs + entity_ids of soft-deleted rows older than cutoff for a given entity.
2498
2521
  * Used by runPrune().
2499
2522
  */
2500
- async getPrunableMetadata(entityId, cutoff, tx) {
2523
+ async getPrunableMetadata(entityId, cutoff, tx, opts) {
2501
2524
  const executor = this.getExecutor(tx);
2525
+ const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
2526
+ const args = opts?.noCutoff ? [entityId] : [entityId, cutoff];
2502
2527
  return executor.getAllAsync(
2503
2528
  `SELECT id, entity_id FROM ${this.prefix}entries
2504
- WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
2505
- [entityId, cutoff]
2529
+ WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
2530
+ args
2506
2531
  );
2507
2532
  }
2508
2533
  /**
2509
2534
  * Fetch all non-deleted entries for an entity, ordered by updated_at DESC.
2510
2535
  * Used by _getFullBundle().
2511
2536
  */
2512
- async findAllByEntityId(entityId, tx) {
2537
+ async findAllByEntityId(entityId, tx, opts) {
2513
2538
  const executor = this.getExecutor(tx);
2539
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
2514
2540
  const rows = await executor.getAllAsync(
2515
- `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,
2541
+ `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
2516
2542
  [entityId]
2517
2543
  );
2518
2544
  return rows.map(mapRowToFact);
@@ -2592,10 +2618,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2592
2618
  * Fetch all non-deleted entries for an entity with embedding blobs preserved.
2593
2619
  * Used by ImportExportService for export/import round-tripping.
2594
2620
  */
2595
- async findAllByEntityIdWithBlobs(entityId, tx) {
2621
+ async findAllByEntityIdWithBlobs(entityId, tx, opts) {
2596
2622
  const executor = this.getExecutor(tx);
2623
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
2597
2624
  const rows = await executor.getAllAsync(
2598
- `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,
2625
+ `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
2599
2626
  [entityId]
2600
2627
  );
2601
2628
  return rows.map(mapRowToFactWithBlobs);
@@ -2666,20 +2693,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2666
2693
  for (let i = 0; i < ids.length; i += chunkSize) {
2667
2694
  const chunk = ids.slice(i, i + chunkSize);
2668
2695
  const placeholders = chunk.map(() => "?").join(",");
2696
+ const cutoffPredicate = opts.noCutoff ? "" : " AND deleted_at <= ?";
2697
+ const delArgs = opts.noCutoff ? [entityId, ...chunk] : [entityId, cutoff, ...chunk];
2669
2698
  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);
2699
+ `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate} AND id IN (${placeholders})${guard} RETURNING id, deleted_at`,
2700
+ delArgs
2701
+ )).map((r) => ({ id: r.id, deleted_at: typeof r.deleted_at === "number" ? r.deleted_at : Number(r.deleted_at) }));
2673
2702
  totalChanges += deleted.length;
2674
- opts.deletedIds?.push(...deleted);
2703
+ opts.deletedIds?.push(...deleted.map((r) => r.id));
2675
2704
  if (deleted.length > 0) {
2676
- for (const id of deleted) {
2705
+ for (const row of deleted) {
2677
2706
  await this.outbox.push({
2678
2707
  entityId,
2679
2708
  tableName: "entries",
2680
- recordId: id,
2709
+ recordId: row.id,
2681
2710
  operation: "DELETE",
2682
- payload: { id, entity_id: entityId, deleted_at: cutoff }
2711
+ payload: { id: row.id, entity_id: entityId, deleted_at: row.deleted_at }
2683
2712
  }, tx);
2684
2713
  }
2685
2714
  }
@@ -2848,6 +2877,19 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2848
2877
  );
2849
2878
  return new Set(rows.map((r) => r.id));
2850
2879
  }
2880
+ /**
2881
+ * Depth-aware supersession walk for chain forget (spec forget-erasure §3).
2882
+ * Probes `maxDepth + 1` levels so a chain longer than the cap is detectable;
2883
+ * the returned ids are capped to `maxDepth` per direction (successors nearest first; predecessors are returned farthest-first).
2884
+ * No `deleted_at` filter: soft-deleted links still carry the chain.
2885
+ */
2886
+ async findSupersessionChainWalk(entityId, factId, maxDepth, tx) {
2887
+ const { predecessors, successors } = await this.findSupersessionChainIds(entityId, factId, maxDepth + 1, tx);
2888
+ const truncated = predecessors.some((r) => r.depth > maxDepth) || successors.some((r) => r.depth > maxDepth);
2889
+ const pred = predecessors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
2890
+ const succ = successors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
2891
+ return { ids: Array.from(/* @__PURE__ */ new Set([...succ, ...pred])), truncated };
2892
+ }
2851
2893
  async findSupersessionChainIds(entityId, factId, maxDepth, tx) {
2852
2894
  const executor = this.getExecutor(tx);
2853
2895
  const successors = await executor.getAllAsync(
@@ -2858,7 +2900,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2858
2900
  JOIN ${this.prefix}entries e ON e.id = fwd.id AND e.entity_id = ?
2859
2901
  WHERE e.superseded_by IS NOT NULL AND fwd.depth < ?
2860
2902
  )
2861
- SELECT id FROM fwd ORDER BY depth ASC`,
2903
+ SELECT id, depth FROM fwd ORDER BY depth ASC`,
2862
2904
  [factId, entityId, entityId, maxDepth]
2863
2905
  );
2864
2906
  const predecessors = await executor.getAllAsync(
@@ -2869,10 +2911,10 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2869
2911
  JOIN ${this.prefix}entries e ON e.entity_id = ? AND e.superseded_by = bwd.id
2870
2912
  WHERE bwd.depth < ?
2871
2913
  )
2872
- SELECT id FROM bwd ORDER BY depth DESC`,
2914
+ SELECT id, depth FROM bwd ORDER BY depth DESC`,
2873
2915
  [entityId, factId, entityId, maxDepth]
2874
2916
  );
2875
- const drop = (ids) => ids.map((r) => r.id).filter((id) => id !== factId);
2917
+ const drop = (rows) => rows.filter((r) => r.id !== factId);
2876
2918
  return { predecessors: drop(predecessors), successors: drop(successors) };
2877
2919
  }
2878
2920
  async findExpiredIds(entityId, cutoff, tx) {
@@ -3703,10 +3745,15 @@ var TaskRepository = class extends BaseRepository {
3703
3745
  const chunk = ids.slice(i, i + chunkSize);
3704
3746
  const placeholders = chunk.map(() => "?").join(",");
3705
3747
  const chunkRows = await executor.getAllAsync(
3706
- `SELECT id, entity_id, updated_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
3748
+ `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
3707
3749
  chunk
3708
3750
  );
3709
- rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));
3751
+ rows.push(...chunkRows.map((row) => ({
3752
+ id: row.id,
3753
+ entity_id: row.entity_id,
3754
+ updated_at: Number(row.updated_at),
3755
+ deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
3756
+ })));
3710
3757
  }
3711
3758
  return rows;
3712
3759
  }
@@ -3869,10 +3916,11 @@ var TaskRepository = class extends BaseRepository {
3869
3916
  * Fetch all non-deleted tasks for an entity, ordered by priority DESC, created_at ASC.
3870
3917
  * Used by _getFullBundle().
3871
3918
  */
3872
- async findAllByEntityId(entityId, tx) {
3919
+ async findAllByEntityId(entityId, tx, opts) {
3873
3920
  const executor = this.getExecutor(tx);
3921
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
3874
3922
  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`,
3923
+ `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ?${live} ORDER BY priority DESC, created_at ASC`,
3876
3924
  [entityId]
3877
3925
  );
3878
3926
  return rows.map(mapRowToTask);
@@ -3881,16 +3929,19 @@ var TaskRepository = class extends BaseRepository {
3881
3929
  * Bulk delete pruned tasks (already soft-deleted) by cutoff date.
3882
3930
  * Used by runPrune(). Returns number of deleted rows.
3883
3931
  */
3884
- async bulkDeletePruned(entityId, cutoff, tx) {
3932
+ async bulkDeletePruned(entityId, cutoff, tx, opts) {
3885
3933
  const executor = this.getExecutor(tx);
3934
+ const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
3935
+ const selectArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
3886
3936
  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]
3937
+ `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
3938
+ selectArgs
3889
3939
  );
3890
3940
  if (rowsToDelete.length === 0) return 0;
3941
+ const deleteArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
3891
3942
  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]
3943
+ `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
3944
+ deleteArgs
3894
3945
  );
3895
3946
  for (const row of rowsToDelete) {
3896
3947
  await this.outbox.push(
@@ -4556,6 +4607,12 @@ function entitySummaryMetaKey(entityId) {
4556
4607
  return `entity_summary:${entityId}`;
4557
4608
  }
4558
4609
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
4610
+ var CheckpointIncompleteError = class extends Error {
4611
+ constructor() {
4612
+ super(...arguments);
4613
+ this.code = "erase_checkpoint_incomplete";
4614
+ }
4615
+ };
4559
4616
  var MetadataRepository = class extends BaseRepository {
4560
4617
  // CHECKPOINTS TABLE METHODS
4561
4618
  async getCheckpoint(entityId, tx) {
@@ -4674,9 +4731,25 @@ var MetadataRepository = class extends BaseRepository {
4674
4731
  );
4675
4732
  return row?.sql ?? null;
4676
4733
  }
4734
+ /**
4735
+ * `PRAGMA wal_checkpoint(TRUNCATE)`, verified: `busy !== 0` or
4736
+ * `log !== checkpointed` means frames survive in the WAL, so a deleted
4737
+ * row's bytes may still be on disk. Non-WAL reports (0,-1,-1) = complete.
4738
+ */
4739
+ async checkpointTruncateVerified() {
4740
+ const row = await this.db.getFirstAsync(
4741
+ `PRAGMA wal_checkpoint(TRUNCATE)`
4742
+ );
4743
+ if (row && (row.busy !== 0 || row.log !== row.checkpointed)) {
4744
+ throw new CheckpointIncompleteError(
4745
+ `wal_checkpoint(TRUNCATE) incomplete (busy=${row?.busy}, log=${row?.log}, checkpointed=${row?.checkpointed})`
4746
+ );
4747
+ }
4748
+ }
4677
4749
  async vacuum() {
4678
- await this.db.execAsync(`PRAGMA wal_checkpoint(TRUNCATE)`);
4750
+ await this.checkpointTruncateVerified();
4679
4751
  await this.db.execAsync(`VACUUM`);
4752
+ await this.checkpointTruncateVerified();
4680
4753
  }
4681
4754
  /**
4682
4755
  * Returns the set of distinct `entity_id` values across entries/tasks/events.
@@ -4686,9 +4759,36 @@ var MetadataRepository = class extends BaseRepository {
4686
4759
  * soft-deleted, so the host's maintenance sweep can visit such
4687
4760
  * "decommissioned-scope" namespaces and reap the soft-deleted rows. Sorting
4688
4761
  * is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
4762
+ *
4763
+ * With `opts.softDeletedAtOrBefore` the walk is narrowed to entities holding
4764
+ * at least one soft-deleted entry or task with `deleted_at` at or before
4765
+ * that cutoff (erase's hard-delete walk, forget-erasure spec §2). Without
4766
+ * the option the host-facing semantics above are unchanged.
4689
4767
  */
4690
- async getDistinctEntityIds(tx) {
4768
+ async getDistinctEntityIds(tx, opts) {
4691
4769
  const executor = this.getExecutor(tx);
4770
+ if (opts?.softDeletedAll) {
4771
+ const rows2 = await executor.getAllAsync(
4772
+ `SELECT DISTINCT entity_id FROM (
4773
+ SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL
4774
+ UNION
4775
+ SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL
4776
+ ) ORDER BY entity_id COLLATE BINARY`
4777
+ );
4778
+ return rows2.map((r) => r.entity_id);
4779
+ }
4780
+ if (opts?.softDeletedAtOrBefore !== void 0) {
4781
+ const cutoff = opts.softDeletedAtOrBefore;
4782
+ const rows2 = await executor.getAllAsync(
4783
+ `SELECT DISTINCT entity_id FROM (
4784
+ SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL AND deleted_at <= ?
4785
+ UNION
4786
+ SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL AND deleted_at <= ?
4787
+ ) ORDER BY entity_id COLLATE BINARY`,
4788
+ [cutoff, cutoff]
4789
+ );
4790
+ return rows2.map((r) => r.entity_id);
4791
+ }
4692
4792
  const rows = await executor.getAllAsync(
4693
4793
  `SELECT DISTINCT entity_id FROM (
4694
4794
  SELECT entity_id FROM ${this.prefix}entries
@@ -5078,6 +5178,61 @@ var _SearchService = class _SearchService {
5078
5178
  this.syncChain = work;
5079
5179
  return work;
5080
5180
  }
5181
+ /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
5182
+ chainSurfaced(fn) {
5183
+ const work = this.syncChain.then(fn);
5184
+ this.syncChain = work.then(() => void 0, () => void 0);
5185
+ return work;
5186
+ }
5187
+ /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
5188
+ hasStrictDrain() {
5189
+ const s = this.indexStrategy;
5190
+ return typeof s.drainPassagesStrict === "function" && typeof s.drainEntriesLedgerStrict === "function";
5191
+ }
5192
+ /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
5193
+ drainPassagesSurfaced() {
5194
+ const s = this.indexStrategy;
5195
+ if (!s.drainPassagesStrict) return this.chainSurfaced(async () => {
5196
+ });
5197
+ return this.chainSurfaced(() => s.drainPassagesStrict());
5198
+ }
5199
+ /** Erase step 4: listed retired FTS tables (empty for strategies without any). */
5200
+ async retiredTables() {
5201
+ const s = this.indexStrategy;
5202
+ return s.retiredTables ? s.retiredTables() : [];
5203
+ }
5204
+ /** True when the active strategy can DROP retired tables (FTS5); false for MiniSearch / Unavailable. */
5205
+ canReclaimRetired() {
5206
+ return typeof this.indexStrategy.reclaimRetiredToCompletion === "function";
5207
+ }
5208
+ /** Erase step 3: store-wide entries-side fts_pending drain on the sync chain, no deadline, errors surfaced. */
5209
+ drainEntriesLedgerSurfaced() {
5210
+ const s = this.indexStrategy;
5211
+ if (!s.drainEntriesLedgerStrict) return this.chainSurfaced(async () => {
5212
+ });
5213
+ return this.chainSurfaced(() => s.drainEntriesLedgerStrict());
5214
+ }
5215
+ /** Erase step 4: reclaim retired tables to completion; errors surfaced. */
5216
+ reclaimRetiredSurfaced() {
5217
+ const s = this.indexStrategy;
5218
+ if (!s.reclaimRetiredToCompletion) return this.chainSurfaced(async () => {
5219
+ });
5220
+ return this.chainSurfaced(() => s.reclaimRetiredToCompletion());
5221
+ }
5222
+ /** Erase step 7: FTS optimize on every FTS table that exists. */
5223
+ optimizeSurfaced() {
5224
+ const s = this.indexStrategy;
5225
+ if (!s.optimizeFts) return this.chainSurfaced(async () => {
5226
+ });
5227
+ return this.chainSurfaced(() => s.optimizeFts());
5228
+ }
5229
+ /** `erase({ rebuild: true })` wiring point; the orchestration (T6) calls it. */
5230
+ rebuildSurfaced() {
5231
+ const s = this.indexStrategy;
5232
+ if (!s.rebuildForErase) return this.chainSurfaced(async () => {
5233
+ });
5234
+ return this.chainSurfaced(() => s.rebuildForErase());
5235
+ }
5081
5236
  /**
5082
5237
  * Stored-source passage search for ONE entity (spec source-store section 7:
5083
5238
  * ranking and caps are per entity). Rides the active strategy; a strategy
@@ -5915,6 +6070,53 @@ var Fts5IndexStrategy = class {
5915
6070
  if (!isSqliteError(err)) throw err;
5916
6071
  }
5917
6072
  }
6073
+ /** Listed retired table names (erase step 4 / module-less fallback). */
6074
+ async retiredTables() {
6075
+ return this.retiredList();
6076
+ }
6077
+ /**
6078
+ * Erase step 4: reclaim every retired table to completion (DROP + delist), no
6079
+ * deadline. Failures surface (unlike the best-effort quantum path); the
6080
+ * SQLITE_CORRUPT_VTAB hollowed-shell exit inside reclaimRetired is designed.
6081
+ */
6082
+ async reclaimRetiredToCompletion() {
6083
+ await this.reclaimRetired(Number.POSITIVE_INFINITY);
6084
+ }
6085
+ /**
6086
+ * Erase step 3: surfaced passage drain, no deadline. Fails only when passage
6087
+ * init was disabled AND the ledger still has rows; otherwise warns and continues.
6088
+ */
6089
+ async drainPassagesStrict() {
6090
+ if (this.passagesDisabled) {
6091
+ const p = this.prefix;
6092
+ 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;
6093
+ if (pending) throw new Error("passage index disabled with pending ledger rows");
6094
+ console.warn("[WikiMemory] erase: passage index disabled; nothing pending, continuing");
6095
+ return;
6096
+ }
6097
+ await this.drainPassages({});
6098
+ }
6099
+ /**
6100
+ * Erase step 3 (entries side): drain the trigger-fed `fts_pending` ledger store-wide to
6101
+ * empty, no deadline, errors surfaced; throws if rows remain afterwards.
6102
+ */
6103
+ async drainEntriesLedgerStrict() {
6104
+ while (await this.drainLedgerChunk()) ;
6105
+ const left = await this.db.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}fts_pending LIMIT 1`);
6106
+ if (left !== null && left !== void 0) throw new Error("entries FTS ledger still has pending rows after drain");
6107
+ }
6108
+ /** Erase step 7: FTS 'optimize' on each FTS table that exists. */
6109
+ async optimizeFts() {
6110
+ const p = this.prefix;
6111
+ for (const t of [`${p}entries_fts`, `${p}source_passages_fts`]) {
6112
+ if (!await this.metadataRepo.tableExists(t)) continue;
6113
+ await this.db.runAsync(`INSERT INTO ${t}(${t}) VALUES('optimize')`);
6114
+ }
6115
+ }
6116
+ /** `erase({ rebuild: true })` surface: retire + recreate the entries index and re-arm the rebuild. */
6117
+ async rebuildForErase() {
6118
+ await this.resetAndRearm();
6119
+ }
5918
6120
  /** Bounded reclamation steps, each its own tx, until the deadline or nothing is retired. */
5919
6121
  async reclaimRetired(deadline) {
5920
6122
  while (monotonicNow() < deadline) {
@@ -6618,7 +6820,7 @@ var JobManager = class {
6618
6820
  this.statusSubscribers = /* @__PURE__ */ new Map();
6619
6821
  /**
6620
6822
  * Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
6621
- * Excludes 'ingest' | 'global_reembed' | 'global_import', which those
6823
+ * Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
6622
6824
  * methods already handle via explicit if/else branches before reaching
6623
6825
  * this table.
6624
6826
  */
@@ -6687,6 +6889,9 @@ var JobManager = class {
6687
6889
  _globalReembedKey() {
6688
6890
  return `${this.prefix}:reembed`;
6689
6891
  }
6892
+ _eraseKey() {
6893
+ return `${this.prefix}:erase`;
6894
+ }
6690
6895
  _importKey(entityId) {
6691
6896
  return `${this.prefix}:${entityId}:import`;
6692
6897
  }
@@ -6767,11 +6972,19 @@ var JobManager = class {
6767
6972
  _isIngestActiveFor(entityId) {
6768
6973
  return this.activeIngestJobs.has(entityId);
6769
6974
  }
6770
- acquireLock(operation, entityId, sourceRef) {
6975
+ /**
6976
+ * `owner` is the fourth parameter (the third, `sourceRef`, is ingest-only).
6977
+ * `'erase'` marks the erase() pipeline's own per-entity prune, the only
6978
+ * operation exempt from the universal erase pre-check below.
6979
+ */
6980
+ acquireLock(operation, entityId, sourceRef, owner = "host") {
6771
6981
  let blockingOperation = null;
6772
6982
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
6773
6983
  throw new WikiBusyError("import", "*");
6774
6984
  }
6985
+ if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
6986
+ throw new WikiBusyError("erase", "*");
6987
+ }
6775
6988
  switch (operation) {
6776
6989
  case "prune":
6777
6990
  if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
@@ -6820,6 +7033,18 @@ var JobManager = class {
6820
7033
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
6821
7034
  else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
6822
7035
  break;
7036
+ case "erase":
7037
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) blockingOperation = "erase";
7038
+ else if (this._isAnyMaintenanceActiveWithSuffix(":reembed")) blockingOperation = "reembed";
7039
+ else if (this._isAnyMaintenanceActiveWithSuffix(":prune")) blockingOperation = "prune";
7040
+ else if (this._isAnyMaintenanceActiveWithSuffix(":librarian")) blockingOperation = "librarian";
7041
+ else if (this._isAnyMaintenanceActiveWithSuffix(":heal")) blockingOperation = "heal";
7042
+ else if (this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill")) blockingOperation = "ontologyBackfill";
7043
+ else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
7044
+ else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
7045
+ else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
7046
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7047
+ break;
6823
7048
  case "import":
6824
7049
  case "forget": {
6825
7050
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
@@ -6864,7 +7089,7 @@ var JobManager = class {
6864
7089
  if (blockingOperation) {
6865
7090
  throw new WikiBusyError(
6866
7091
  blockingOperation,
6867
- operation === "global_reembed" || operation === "global_import" ? "*" : entityId
7092
+ operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
6868
7093
  );
6869
7094
  }
6870
7095
  if (operation === "ingest") {
@@ -6873,6 +7098,8 @@ var JobManager = class {
6873
7098
  this.activeMaintenanceJobs.add(this._globalReembedKey());
6874
7099
  } else if (operation === "global_import") {
6875
7100
  this.activeMaintenanceJobs.add(this._globalImportKey());
7101
+ } else if (operation === "erase") {
7102
+ this.activeMaintenanceJobs.add(this._eraseKey());
6876
7103
  } else {
6877
7104
  this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
6878
7105
  }
@@ -6885,6 +7112,8 @@ var JobManager = class {
6885
7112
  this.activeMaintenanceJobs.delete(this._globalReembedKey());
6886
7113
  } else if (operation === "global_import") {
6887
7114
  this.activeMaintenanceJobs.delete(this._globalImportKey());
7115
+ } else if (operation === "erase") {
7116
+ this.activeMaintenanceJobs.delete(this._eraseKey());
6888
7117
  } else {
6889
7118
  this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
6890
7119
  }
@@ -6896,7 +7125,10 @@ var JobManager = class {
6896
7125
  */
6897
7126
  isBlocked(operation, entityId) {
6898
7127
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
7128
+ if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
6899
7129
  switch (operation) {
7130
+ case "erase":
7131
+ 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
7132
  case "librarian":
6901
7133
  case "heal":
6902
7134
  case "ontologyBackfill":
@@ -6930,6 +7162,7 @@ var JobManager = class {
6930
7162
  */
6931
7163
  tryAcquireAutoHealLock(entityId) {
6932
7164
  if (this.isAnyReembedActive()) return false;
7165
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
6933
7166
  const healKey = this._healKey(entityId);
6934
7167
  if (this.activeMaintenanceJobs.has(healKey)) return false;
6935
7168
  this.activeMaintenanceJobs.add(healKey);
@@ -6973,6 +7206,7 @@ var JobManager = class {
6973
7206
  * Validates all entities before acquiring any lock (same as current importDump semantics).
6974
7207
  */
6975
7208
  acquireImportLocks(entityIds) {
7209
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
6976
7210
  for (const entityId of entityIds) {
6977
7211
  if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
6978
7212
  if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);
@@ -8299,6 +8533,94 @@ function classifierStateForFact(fact) {
8299
8533
  return parts.join("\n\n");
8300
8534
  }
8301
8535
 
8536
+ // src/services/TemporalService.ts
8537
+ var HISTORY_MAX_DEPTH = 100;
8538
+ var TemporalService = class {
8539
+ constructor(db, options, entryRepo, searchService, embeddingService) {
8540
+ this.db = db;
8541
+ this.options = options;
8542
+ this.entryRepo = entryRepo;
8543
+ this.searchService = searchService;
8544
+ this.embeddingService = embeddingService;
8545
+ }
8546
+ /**
8547
+ * Link `oldId` → `newId` inside the caller's transaction. `newId` must
8548
+ * already exist. Throws WikiSupersedeError on any rule violation; the
8549
+ * caller's transaction then rolls back.
8550
+ */
8551
+ async supersedeInTx(tx, entityId, oldId, newId, t, now) {
8552
+ const old = await this.entryRepo.findTemporalRow(oldId, tx);
8553
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
8554
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
8555
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
8556
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
8557
+ if (newId === oldId) throw new WikiSupersedeError("cycle");
8558
+ const repl = await this.entryRepo.findTemporalRow(newId, tx);
8559
+ if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
8560
+ if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
8561
+ if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
8562
+ const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
8563
+ if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
8564
+ await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
8565
+ if (repl.valid_from == null) {
8566
+ await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
8567
+ }
8568
+ }
8569
+ async supersede(entityId, oldId, replacement, options) {
8570
+ const now = Date.now();
8571
+ const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
8572
+ let created = null;
8573
+ if (typeof replacement !== "string") {
8574
+ if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
8575
+ throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
8576
+ }
8577
+ created = {
8578
+ id: generateId("fact_"),
8579
+ entity_id: entityId,
8580
+ title: replacement.title,
8581
+ body: replacement.body,
8582
+ tags: Array.isArray(replacement.tags) ? replacement.tags : [],
8583
+ confidence: replacement.confidence ?? "certain",
8584
+ source_type: replacement.source_type ?? "user_stated",
8585
+ source_hash: null,
8586
+ source_ref: null,
8587
+ created_at: now,
8588
+ updated_at: now,
8589
+ last_accessed_at: null,
8590
+ access_count: 0,
8591
+ deleted_at: null
8592
+ };
8593
+ }
8594
+ const newId = typeof replacement === "string" ? replacement : created.id;
8595
+ const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
8596
+ await this.db.withTransactionAsync(async (tx) => {
8597
+ if (created) {
8598
+ await this.entryRepo.upsert(created, tx);
8599
+ if (newValidFrom !== void 0) {
8600
+ await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
8601
+ }
8602
+ }
8603
+ await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
8604
+ });
8605
+ await this.searchService.syncEntries(entityId, [oldId, newId]);
8606
+ if (created) {
8607
+ await this.embeddingService.embedFact(
8608
+ { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
8609
+ { operation: "supersede", trigger: "call" }
8610
+ );
8611
+ }
8612
+ this.searchService.evictCache(entityId);
8613
+ return { newId };
8614
+ }
8615
+ async history(entityId, factId) {
8616
+ const start = await this.entryRepo.findTemporalRow(factId);
8617
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
8618
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
8619
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
8620
+ 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));
8621
+ }
8622
+ };
8623
+
8302
8624
  // src/utils/engineDefaults.ts
8303
8625
  var DEFAULT_LIBRARIAN_STRATEGY = "ops";
8304
8626
  var DEFAULT_MAINTENANCE_MODE = "deferred";
@@ -9483,94 +9805,6 @@ async function runResolve(deps, ctx, ambiguous) {
9483
9805
  return out;
9484
9806
  }
9485
9807
 
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
9808
  // src/services/librarian/ops/apply.ts
9575
9809
  function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
9576
9810
  if (candidate.sourceEventId === null) return null;
@@ -9836,6 +10070,7 @@ async function runLibrarianStrategy(deps, ctx) {
9836
10070
  }
9837
10071
 
9838
10072
  // src/services/MaintenanceService.ts
10073
+ 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
10074
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
9840
10075
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
9841
10076
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -9884,6 +10119,20 @@ var formatSkipError = (err) => {
9884
10119
  }
9885
10120
  return base;
9886
10121
  };
10122
+ function eraseRuntime() {
10123
+ const g = globalThis;
10124
+ if (g.process?.versions?.node) return `node ${g.process.versions.node}`;
10125
+ return g.HermesInternal ? "hermes" : "unknown";
10126
+ }
10127
+ var EraseStepError = class extends Error {
10128
+ constructor(code, message, report, cause) {
10129
+ super(message);
10130
+ this.code = code;
10131
+ this.report = report;
10132
+ this.name = "EraseStepError";
10133
+ if (cause !== void 0) this.cause = cause;
10134
+ }
10135
+ };
9887
10136
  var MaintenanceService = class {
9888
10137
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
9889
10138
  this.db = db;
@@ -9904,7 +10153,15 @@ var MaintenanceService = class {
9904
10153
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
9905
10154
  }
9906
10155
  async runPrune(entityId, options) {
9907
- this.jobManager.acquireLock("prune", entityId);
10156
+ return this._runPrune(entityId, options, "host");
10157
+ }
10158
+ /**
10159
+ * Shared prune body. `owner: 'erase'` lets erase()'s own per-entity prune
10160
+ * through the universal erase fence in JobManager; the public `runPrune`
10161
+ * always passes `'host'`.
10162
+ */
10163
+ async _runPrune(entityId, options, owner) {
10164
+ this.jobManager.acquireLock("prune", entityId, void 0, owner);
9908
10165
  try {
9909
10166
  const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
9910
10167
  const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
@@ -9935,8 +10192,9 @@ var MaintenanceService = class {
9935
10192
  }
9936
10193
  }
9937
10194
  if (retainSoftDeletedFor !== null) {
9938
- const cutoff = now - retainSoftDeletedFor * 864e5;
9939
- const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
10195
+ const softDeletedAll = options?.softDeletedCutoff === "all";
10196
+ const cutoff = softDeletedAll ? 0 : options?.softDeletedCutoff ?? now - retainSoftDeletedFor * 864e5;
10197
+ const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff, void 0, { noCutoff: softDeletedAll });
9940
10198
  const prunableIds = entriesToDelete.map((r) => r.id);
9941
10199
  const vr = this.vectorRemoval;
9942
10200
  const vrRepo = this.vectorRemovalRepo;
@@ -9982,7 +10240,7 @@ var MaintenanceService = class {
9982
10240
  }
9983
10241
  if (deletable.length > 0) {
9984
10242
  const deletedIds = [];
9985
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
10243
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds, noCutoff: softDeletedAll });
9986
10244
  if (hookLedger) {
9987
10245
  const gone = new Set(deletedIds);
9988
10246
  const skipped = deletable.filter((id) => !gone.has(id));
@@ -9997,7 +10255,7 @@ var MaintenanceService = class {
9997
10255
  else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
9998
10256
  }
9999
10257
  }
10000
- deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
10258
+ deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
10001
10259
  });
10002
10260
  if (hookLedger) {
10003
10261
  const keptSet = new Set(kept);
@@ -10042,12 +10300,20 @@ var MaintenanceService = class {
10042
10300
  }
10043
10301
  }
10044
10302
  }
10303
+ let vacuumCheckpointErr;
10045
10304
  if (vacuum) {
10046
- await resetNormalizeWatermarks(this.metadataRepo);
10047
- await this.metadataRepo.vacuum();
10048
- await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
10305
+ try {
10306
+ await this._wrappedVacuum();
10307
+ } catch (err) {
10308
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
10309
+ vacuumCheckpointErr = err;
10310
+ }
10049
10311
  }
10312
+ if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
10050
10313
  await this.searchService.syncEntries(entityId, syncedIds);
10314
+ if (prunePartial && vacuumCheckpointErr) {
10315
+ emitDiagnostic(this.options, { code: "prune_checkpoint_incomplete", operation: "prune", trigger: "call", entityId, detail: { reason: vacuumCheckpointErr.message } });
10316
+ }
10051
10317
  if (prunePartial) {
10052
10318
  throw new PrunePartialFailureError(
10053
10319
  deletedEntries,
@@ -10058,11 +10324,327 @@ var MaintenanceService = class {
10058
10324
  deletedEvents
10059
10325
  );
10060
10326
  }
10327
+ if (vacuumCheckpointErr) throw vacuumCheckpointErr;
10061
10328
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
10062
10329
  } finally {
10063
10330
  this.jobManager.releaseLock("prune", entityId);
10064
10331
  }
10065
10332
  }
10333
+ /** Shared by runPrune and erase step 5. */
10334
+ async _wrappedVacuum() {
10335
+ await resetNormalizeWatermarks(this.metadataRepo);
10336
+ let checkpointErr;
10337
+ try {
10338
+ await this.metadataRepo.vacuum();
10339
+ } catch (err) {
10340
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
10341
+ checkpointErr = err;
10342
+ }
10343
+ await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
10344
+ if (checkpointErr) throw checkpointErr;
10345
+ }
10346
+ /**
10347
+ * Erase core (forget-erasure spec §2, steps 0 / 1 / 1b). Thin entry: T6
10348
+ * completes the pipeline (FTS, VACUUM, checkpoint, sync). Never reports a
10349
+ * success it cannot verify: a failed step throws {@link EraseStepError}
10350
+ * carrying the partial report with `verified: false`.
10351
+ */
10352
+ async erase(opts) {
10353
+ const rebuild = opts?.rebuild === true;
10354
+ this.jobManager.acquireLock("erase", "*");
10355
+ const report = {
10356
+ verified: false,
10357
+ secureDelete: null,
10358
+ sqliteVersion: "",
10359
+ entities: [],
10360
+ holds: [],
10361
+ skipped: [],
10362
+ syncedIds: [],
10363
+ registrySweep: { skipped: false, deleted: 0 },
10364
+ retiredUndroppable: [],
10365
+ failedStep: null,
10366
+ runtime: eraseRuntime(),
10367
+ steps: []
10368
+ };
10369
+ const ok = (step, outcome = "ok") => {
10370
+ report.steps.push({ step, outcome });
10371
+ };
10372
+ try {
10373
+ const readPragma = async () => (await this.db.getFirstAsync("PRAGMA secure_delete"))?.secure_delete ?? null;
10374
+ let pragma;
10375
+ try {
10376
+ pragma = await readPragma();
10377
+ if (pragma !== 1) {
10378
+ await this.db.execAsync("PRAGMA secure_delete=ON");
10379
+ pragma = await readPragma();
10380
+ }
10381
+ report.secureDelete = pragma;
10382
+ report.sqliteVersion = (await this.db.getFirstAsync("SELECT sqlite_version() AS v"))?.v ?? "";
10383
+ } catch (err) {
10384
+ report.failedStep = "secure_delete";
10385
+ throw new EraseStepError("erase_secure_delete_read_failed", "erase stopped at step 0: secure_delete pragma read failed; erasure is unverified", report, err);
10386
+ }
10387
+ if (pragma !== 1) {
10388
+ emitDiagnostic(this.options, { code: "erase_secure_delete_off", operation: "erase", trigger: "call", entityId: "" });
10389
+ report.failedStep = "secure_delete";
10390
+ throw new EraseStepError("erase_secure_delete_off", "erase stopped at step 0: secure_delete is not ON; erasure is unverified", report);
10391
+ }
10392
+ ok("secure_delete");
10393
+ try {
10394
+ report.entities = await this.metadataRepo.getDistinctEntityIds(void 0, { softDeletedAll: true });
10395
+ } catch (err) {
10396
+ report.failedStep = "prune";
10397
+ throw new EraseStepError("erase_prune_failed", "erase stopped at step 1: the entity walk failed; erasure is unverified", report, err);
10398
+ }
10399
+ const syncedByEntity = /* @__PURE__ */ new Map();
10400
+ for (const entityId of report.entities) {
10401
+ const syncedIds = [];
10402
+ syncedByEntity.set(entityId, syncedIds);
10403
+ try {
10404
+ await this._runPrune(entityId, { retainSoftDeletedFor: 0, retainEventsFor: null, vacuum: false, syncedIds, softDeletedCutoff: "all" }, "erase");
10405
+ } catch (err) {
10406
+ if (err instanceof PrunePartialFailureError) {
10407
+ report.holds.push({ entityId, deleted: err.deleted, deletedTasks: err.deletedTasks, failedAt: err.failedAt, remaining: err.remaining });
10408
+ } else if (err instanceof WikiBusyError) {
10409
+ report.skipped.push(entityId);
10410
+ emitDiagnostic(this.options, { code: "erase_entity_skipped", operation: "erase", trigger: "call", entityId });
10411
+ } else {
10412
+ report.failedStep = "prune";
10413
+ throw new EraseStepError("erase_prune_failed", `erase stopped at step 1 (entity ${entityId})`, report, err);
10414
+ }
10415
+ }
10416
+ for (const id of syncedIds) report.syncedIds.push(id);
10417
+ }
10418
+ ok("prune", report.holds.length > 0 || report.skipped.length > 0 ? "partial" : "ok");
10419
+ try {
10420
+ await this.db.withTransactionAsync(async (tx) => {
10421
+ if (await this.sourceRefIndexPresent(tx)) {
10422
+ const r = await tx.runAsync(`DELETE FROM ${this.prefix}source_ref_index WHERE deleted_at IS NOT NULL`);
10423
+ report.registrySweep = { skipped: false, deleted: r.changes };
10424
+ } else {
10425
+ report.registrySweep = { skipped: true, deleted: 0 };
10426
+ }
10427
+ });
10428
+ } catch (err) {
10429
+ report.failedStep = "registry_sweep";
10430
+ throw new EraseStepError("erase_registry_sweep_failed", "erase stopped at step 1b", report, err);
10431
+ }
10432
+ if (report.registrySweep.skipped) {
10433
+ emitDiagnostic(this.options, { code: "erase_registry_sweep_skipped", operation: "erase", trigger: "call", entityId: "" });
10434
+ }
10435
+ ok("registry_sweep", report.registrySweep.skipped ? "partial" : "ok");
10436
+ await this._eraseDrainPassages(report);
10437
+ ok("passage_drain");
10438
+ await this._eraseReclaimRetired(report);
10439
+ ok("retired_reclaim");
10440
+ try {
10441
+ await this._wrappedVacuum();
10442
+ } catch (err) {
10443
+ if (err instanceof CheckpointIncompleteError) {
10444
+ report.failedStep = "checkpoint";
10445
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 5: WAL checkpoint incomplete; erasure is unverified", report, err);
10446
+ }
10447
+ report.failedStep = "vacuum";
10448
+ 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);
10449
+ }
10450
+ ok("vacuum");
10451
+ const byEntity = /* @__PURE__ */ new Map();
10452
+ for (const e of report.entities) byEntity.set(e, []);
10453
+ for (const [entityId, ids] of syncedByEntity) byEntity.set(entityId, ids);
10454
+ for (const [entityId, ids] of byEntity) {
10455
+ if (ids.length > 0) await this._eraseSyncEntries(entityId, ids, report);
10456
+ }
10457
+ ok("index_sync");
10458
+ if (rebuild) {
10459
+ try {
10460
+ await this.searchService.rebuildSurfaced();
10461
+ } catch (err) {
10462
+ report.failedStep = "rebuild";
10463
+ throw new EraseStepError("erase_rebuild_failed", "erase stopped at step 7: FTS rebuild failed", report, err);
10464
+ }
10465
+ ok("rebuild");
10466
+ }
10467
+ await this._eraseReclaimRetired(report);
10468
+ let present;
10469
+ try {
10470
+ present = await this.db.getAllAsync(
10471
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%entries_fts_retired_%'`
10472
+ );
10473
+ } catch (err) {
10474
+ report.failedStep = "retired_reclaim";
10475
+ emitDiagnostic(this.options, { code: "erase_retired_read_failed", operation: "erase", trigger: "call", entityId: "" });
10476
+ throw new EraseStepError("erase_retired_read_failed", "erase stopped after step 6: the retired-table read failed; erasure is unverified", report, err);
10477
+ }
10478
+ const left = present.map((r) => r.name).filter((n) => isRetiredTableName(this.prefix, n) && !report.retiredUndroppable.includes(n));
10479
+ if (left.length > 0) {
10480
+ report.failedStep = "retired_reclaim";
10481
+ emitDiagnostic(this.options, { code: "erase_retired_remaining", operation: "erase", trigger: "call", entityId: "", detail: { tables: left } });
10482
+ throw new EraseStepError("erase_retired_remaining", `erase stopped after step 6: retired FTS tables remain (${left.join(", ")})`, report);
10483
+ }
10484
+ ok("retired_reclaim_rerun");
10485
+ await this._eraseOptimize(report);
10486
+ ok("optimize");
10487
+ try {
10488
+ await this.metadataRepo.checkpointTruncateVerified();
10489
+ } catch (err) {
10490
+ report.failedStep = "checkpoint";
10491
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 8: WAL checkpoint incomplete; erasure is unverified", report, err);
10492
+ }
10493
+ ok("checkpoint");
10494
+ if (report.skipped.length === 0 && report.holds.length === 0) {
10495
+ let remainingTombstones;
10496
+ try {
10497
+ const row = await this.db.getFirstAsync(
10498
+ `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
10499
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
10500
+ );
10501
+ remainingTombstones = row?.n ?? 0;
10502
+ } catch (err) {
10503
+ report.failedStep = "tombstone_gate";
10504
+ throw new EraseStepError("erase_tombstone_gate_failed", "erase stopped at step 9: could not count remaining tombstones; erasure is unverified", report, err);
10505
+ }
10506
+ if (remainingTombstones > 0) {
10507
+ emitDiagnostic(this.options, { code: "erase_tombstones_remaining", operation: "erase", trigger: "call", entityId: "", detail: { count: remainingTombstones } });
10508
+ report.failedStep = "tombstone_gate";
10509
+ throw new EraseStepError("erase_tombstones_remaining", `erase stopped at step 9: ${remainingTombstones} soft-deleted row(s) remain; erasure is unverified`, report);
10510
+ }
10511
+ ok("tombstone_gate");
10512
+ } else {
10513
+ report.steps.push({ step: "tombstone_gate", outcome: "partial" });
10514
+ }
10515
+ report.verified = report.skipped.length === 0 && report.holds.length === 0;
10516
+ return report;
10517
+ } catch (err) {
10518
+ if (err instanceof EraseStepError && err.report === report && report.failedStep) {
10519
+ report.steps.push({ step: report.failedStep, outcome: "failed" });
10520
+ report.verified = false;
10521
+ }
10522
+ throw err;
10523
+ } finally {
10524
+ this.jobManager.releaseLock("erase", "*");
10525
+ }
10526
+ }
10527
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
10528
+ /**
10529
+ * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
10530
+ * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
10531
+ * N2 guard (probe lives here, strategy-agnostic): a strategy without the strict
10532
+ * drains (Unavailable / MiniSearch) cannot drain, so rows in either FTS ledger
10533
+ * mean text was never drained -> the step fails and erasure is unverified.
10534
+ * Absent or empty ledgers proceed.
10535
+ */
10536
+ async _eraseDrainPassages(report) {
10537
+ if (!this.searchService.hasStrictDrain()) {
10538
+ for (const [table, failedStep, code] of [
10539
+ [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
10540
+ [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
10541
+ ]) {
10542
+ let rows = false;
10543
+ try {
10544
+ rows = await this.sourceTableExists(table) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${table} LIMIT 1`) != null;
10545
+ } catch (err) {
10546
+ report.failedStep = failedStep;
10547
+ throw new EraseStepError(code, `erase stopped at step 3: could not probe ${table}`, report, err);
10548
+ }
10549
+ if (rows) {
10550
+ report.failedStep = failedStep;
10551
+ 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);
10552
+ }
10553
+ }
10554
+ for (const suffix of ["entries_fts_content", "source_passages_fts_content"]) {
10555
+ let orphaned = false;
10556
+ try {
10557
+ orphaned = await this.sourceTableExists(`${this.prefix}${suffix}`);
10558
+ } catch (err) {
10559
+ report.failedStep = "index_sync";
10560
+ throw new EraseStepError("erase_orphaned_fts_content", `erase stopped: could not probe ${this.prefix}${suffix}`, report, err);
10561
+ }
10562
+ if (orphaned) {
10563
+ report.failedStep = "index_sync";
10564
+ throw new EraseStepError("erase_orphaned_fts_content", "erase stopped: orphaned full-text content tables may still hold forgotten text", report);
10565
+ }
10566
+ }
10567
+ }
10568
+ try {
10569
+ await this.searchService.drainEntriesLedgerSurfaced();
10570
+ } catch (err) {
10571
+ report.failedStep = "index_sync";
10572
+ throw new EraseStepError("erase_index_sync_failed", "erase stopped at step 3: entries ledger drain failed", report, err);
10573
+ }
10574
+ try {
10575
+ await this.searchService.drainPassagesSurfaced();
10576
+ } catch (err) {
10577
+ report.failedStep = "passage_drain";
10578
+ throw new EraseStepError("erase_passage_drain_failed", "erase stopped at step 3: passage drain failed", report, err);
10579
+ }
10580
+ }
10581
+ /**
10582
+ * Step 4 (and its re-run after step 6): reclaim retired FTS tables to
10583
+ * completion. A module-less runtime cannot DROP a virtual table, so each
10584
+ * retired table's shadow tables are emptied under the pragma and the name
10585
+ * stays listed; a later FTS5-capable open's step 4 completes the DROP.
10586
+ */
10587
+ async _eraseReclaimRetired(report) {
10588
+ if (this.searchService.canReclaimRetired()) {
10589
+ try {
10590
+ await this.searchService.reclaimRetiredSurfaced();
10591
+ return;
10592
+ } catch (err) {
10593
+ if (!/no such module/i.test(err instanceof Error ? err.message : String(err))) {
10594
+ report.failedStep = "retired_reclaim";
10595
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: retired FTS table reclaim failed", report, err);
10596
+ }
10597
+ }
10598
+ }
10599
+ try {
10600
+ for (const name of await this._retiredList()) {
10601
+ for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
10602
+ if (await this.sourceTableExists(`${name}${sfx}`)) await this.db.runAsync(`DELETE FROM ${name}${sfx}`);
10603
+ }
10604
+ if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
10605
+ emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
10606
+ }
10607
+ } catch (err) {
10608
+ report.failedStep = "retired_reclaim";
10609
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: module-less shadow-table clear failed", report, err);
10610
+ }
10611
+ }
10612
+ /** Retired list straight from metadata (same key Fts5IndexStrategy maintains), independent of the active strategy. */
10613
+ async _retiredList() {
10614
+ let raw;
10615
+ try {
10616
+ raw = JSON.parse(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY) ?? "[]");
10617
+ } catch {
10618
+ return [];
10619
+ }
10620
+ return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
10621
+ }
10622
+ sourceTableExists(name) {
10623
+ return this.metadataRepo.tableExists(name);
10624
+ }
10625
+ /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
10626
+ async _eraseSyncEntries(entityId, ids, report) {
10627
+ let ok = false;
10628
+ try {
10629
+ ok = await this.searchService.syncEntries(entityId, ids);
10630
+ } catch (err) {
10631
+ report.failedStep = "index_sync";
10632
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId})`, report, err);
10633
+ }
10634
+ if (!ok) {
10635
+ report.failedStep = "index_sync";
10636
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId}): ledger drain failed`, report);
10637
+ }
10638
+ }
10639
+ /** Step 7: FTS optimize on both FTS tables, after syncEntries. */
10640
+ async _eraseOptimize(report) {
10641
+ try {
10642
+ await this.searchService.optimizeSurfaced();
10643
+ } catch (err) {
10644
+ report.failedStep = "optimize";
10645
+ throw new EraseStepError("erase_optimize_failed", "erase stopped at step 7: FTS optimize failed", report, err);
10646
+ }
10647
+ }
10066
10648
  async runLibrarian(entityId, options) {
10067
10649
  this.jobManager.acquireLock("librarian", entityId);
10068
10650
  try {
@@ -10183,6 +10765,9 @@ var MaintenanceService = class {
10183
10765
  if (params.includeEvents && !params.clearAll) {
10184
10766
  throw new Error("forget() includeEvents requires clearAll: true");
10185
10767
  }
10768
+ if (params.includeChain && (params.entryId === void 0 || params.clearAll || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
10769
+ throw new Error("forget() includeChain composes only with entryId");
10770
+ }
10186
10771
  if (opts?.dryRun === true) {
10187
10772
  return this.forgetDryRun(entityId, params);
10188
10773
  }
@@ -10192,6 +10777,8 @@ var MaintenanceService = class {
10192
10777
  let deletedEntries = 0;
10193
10778
  let deletedTasks = 0;
10194
10779
  let deletedEvents = 0;
10780
+ let chainIds = [];
10781
+ let chainTruncated = false;
10195
10782
  const deletedEntryIds = [];
10196
10783
  const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
10197
10784
  await this.db.withTransactionAsync(async (tx) => {
@@ -10228,6 +10815,12 @@ var MaintenanceService = class {
10228
10815
  if (params.entryId) {
10229
10816
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
10230
10817
  if (entryId) deletedEntryIds.push(entryId);
10818
+ if (entryId && params.includeChain) {
10819
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, entryId, HISTORY_MAX_DEPTH, tx);
10820
+ chainIds = walk.ids.filter((id) => id !== entryId);
10821
+ chainTruncated = walk.truncated;
10822
+ for (const id of chainIds) deletedEntryIds.push(id);
10823
+ }
10231
10824
  }
10232
10825
  if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
10233
10826
  const docs = `${this.prefix}source_documents`;
@@ -10253,6 +10846,9 @@ var MaintenanceService = class {
10253
10846
  sourceRefIndexPromise ?? Promise.resolve(void 0)
10254
10847
  ]);
10255
10848
  if (entryResult) deletedEntries++;
10849
+ for (const id of chainIds) {
10850
+ if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
10851
+ }
10256
10852
  if (taskResult) deletedTasks++;
10257
10853
  deletedEntries += refResult;
10258
10854
  }
@@ -10306,7 +10902,17 @@ var MaintenanceService = class {
10306
10902
  });
10307
10903
  }
10308
10904
  }
10309
- if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
10905
+ if (!params.clearAll) {
10906
+ const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
10907
+ if (params.includeChain) {
10908
+ base.chainEntryIds = chainIds;
10909
+ if (chainTruncated) {
10910
+ base.truncated = true;
10911
+ base.notice = CHAIN_TRUNCATED_NOTICE;
10912
+ }
10913
+ }
10914
+ return base;
10915
+ }
10310
10916
  return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
10311
10917
  } finally {
10312
10918
  this.jobManager.releaseLock("forget", entityId);
@@ -10372,8 +10978,25 @@ var MaintenanceService = class {
10372
10978
  * (the spec keeps dry-run narrow).
10373
10979
  */
10374
10980
  async forgetDryRun(entityId, params) {
10981
+ if (params.entryId !== void 0 && params.includeChain && params.taskId === void 0) {
10982
+ const id = await this.entryRepo.findIdById(params.entryId, entityId);
10983
+ if (!id) return { deleted: { entries: 0, tasks: 0 }, chainEntryIds: [] };
10984
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, id, HISTORY_MAX_DEPTH);
10985
+ const chainEntryIds = walk.ids.filter((c) => c !== id);
10986
+ const all = [id, ...chainEntryIds];
10987
+ const live = await this.db.getFirstAsync(
10988
+ `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND id IN (${all.map(() => "?").join(",")})`,
10989
+ [entityId, ...all]
10990
+ );
10991
+ const out = { deleted: { entries: live?.n ?? 0, tasks: 0 }, chainEntryIds };
10992
+ if (walk.truncated) {
10993
+ out.truncated = true;
10994
+ out.notice = CHAIN_TRUNCATED_NOTICE;
10995
+ }
10996
+ return out;
10997
+ }
10375
10998
  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");
10999
+ throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors (entryId is accepted only with includeChain); use sourceRef/sourceHash or clearAll");
10377
11000
  }
10378
11001
  if (params.clearAll) {
10379
11002
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
@@ -11420,7 +12043,8 @@ var ImportExportService = class {
11420
12043
  this.vectorRemoval = vectorRemoval;
11421
12044
  this.prefix = prefix;
11422
12045
  }
11423
- async exportDump(entityIds) {
12046
+ async exportDump(entityIds, opts) {
12047
+ const includeForgotten = opts?.includeForgotten === true;
11424
12048
  let ids;
11425
12049
  if (entityIds && entityIds.length > 0) {
11426
12050
  ids = Array.from(new Set(entityIds));
@@ -11441,7 +12065,7 @@ var ImportExportService = class {
11441
12065
  const batchResults = await Promise.all(
11442
12066
  batch.map(
11443
12067
  async (id) => {
11444
- const bundle = await this.getFullBundle(id, { includeBlobs: true });
12068
+ const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
11445
12069
  const storedSources = await this.exportStoredSources(id);
11446
12070
  return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
11447
12071
  }
@@ -11547,10 +12171,11 @@ var ImportExportService = class {
11547
12171
  }
11548
12172
  }
11549
12173
  async getFullBundle(entityId, opts) {
12174
+ const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
11550
12175
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
11551
12176
  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),
12177
+ opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
12178
+ this.taskRepo.findAllByEntityId(entityId, void 0, incl),
11554
12179
  this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
11555
12180
  this.edgeRepo.getByEntityId(entityId),
11556
12181
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
@@ -11586,12 +12211,15 @@ var ImportExportService = class {
11586
12211
  const skippedSources = [];
11587
12212
  const refusalDiagnostics = [];
11588
12213
  const upsertedFactIds = /* @__PURE__ */ new Set();
12214
+ const liveEmbedFactIds = /* @__PURE__ */ new Set();
11589
12215
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
11590
12216
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
11591
12217
  const preservedBlobDims = /* @__PURE__ */ new Set();
11592
12218
  const softDeletedFactIds = [];
12219
+ const softDeletedTaskIds = [];
11593
12220
  const clippedTextByFactId = /* @__PURE__ */ new Map();
11594
12221
  let clampedEvents = 0;
12222
+ let tombstoneSkipped = 0;
11595
12223
  const restamped = { behind_watermark: 0, invalid: 0 };
11596
12224
  await this.db.withTransactionAsync(async (tx) => {
11597
12225
  if (!merge) {
@@ -11602,8 +12230,9 @@ var ImportExportService = class {
11602
12230
  tx,
11603
12231
  false
11604
12232
  );
11605
- softDeletedFactIds.push(...deletedLiveFactIds);
12233
+ for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
11606
12234
  await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
12235
+ for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
11607
12236
  await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
11608
12237
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
11609
12238
  await this.metadataRepo.deleteCheckpoint(entityId, tx);
@@ -11613,6 +12242,8 @@ var ImportExportService = class {
11613
12242
  } else if (!merge) {
11614
12243
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
11615
12244
  }
12245
+ const wipedByThisImport = new Set(softDeletedFactIds);
12246
+ const wipedTasksByThisImport = new Set(softDeletedTaskIds);
11616
12247
  const factIds = bundle.facts.map((fact) => fact.id);
11617
12248
  const existingFactsById = /* @__PURE__ */ new Map();
11618
12249
  const existingFacts = await this.entryRepo.findExistingMetadataByIds(
@@ -11688,11 +12319,16 @@ var ImportExportService = class {
11688
12319
  );
11689
12320
  continue;
11690
12321
  }
11691
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
12322
+ if (existing.deleted_at != null && fact.deleted_at == null && !wipedByThisImport.has(fact.id)) {
12323
+ tombstoneSkipped++;
12324
+ continue;
12325
+ }
12326
+ if (merge && safeUpdatedAt <= existing.updated_at && fact.deleted_at == null) continue;
11692
12327
  }
11693
12328
  const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
11694
12329
  const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
11695
- clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody });
12330
+ const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
12331
+ clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
11696
12332
  let normalizedSourceRef = null;
11697
12333
  if (fact.source_ref !== null && fact.source_ref !== void 0) {
11698
12334
  normalizedSourceRef = normalizeSourceRef(fact.source_ref);
@@ -11759,15 +12395,22 @@ var ImportExportService = class {
11759
12395
  }, tx, { outbox: false });
11760
12396
  if (blobData != null) {
11761
12397
  factsWithPreservedBlob.set(fact.id, blobData);
11762
- if (!fact.deleted_at) preservedBlobDims.add(blobData.byteLength / 4);
12398
+ if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
11763
12399
  }
11764
12400
  existingFactsById.set(fact.id, {
11765
12401
  id: fact.id,
11766
12402
  entity_id: entityId,
11767
- updated_at: safeUpdatedAt
12403
+ updated_at: safeUpdatedAt,
12404
+ deleted_at: fact.deleted_at ?? null
11768
12405
  });
12406
+ wipedByThisImport.delete(fact.id);
11769
12407
  upsertedFactIds.add(fact.id);
11770
- if (fact.deleted_at) upsertedDeletedFactIds.add(fact.id);
12408
+ if (fact.deleted_at != null) {
12409
+ upsertedDeletedFactIds.add(fact.id);
12410
+ liveEmbedFactIds.delete(fact.id);
12411
+ } else {
12412
+ liveEmbedFactIds.add(fact.id);
12413
+ }
11771
12414
  }
11772
12415
  const taskIds = bundle.tasks.map((task) => task.id);
11773
12416
  const existingTasksById = /* @__PURE__ */ new Map();
@@ -11791,7 +12434,11 @@ var ImportExportService = class {
11791
12434
  );
11792
12435
  continue;
11793
12436
  }
11794
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
12437
+ if (existing.deleted_at != null && task.deleted_at == null && !wipedTasksByThisImport.has(task.id)) {
12438
+ tombstoneSkipped++;
12439
+ continue;
12440
+ }
12441
+ if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
11795
12442
  }
11796
12443
  await this.taskRepo.upsertForImport(
11797
12444
  {
@@ -11824,8 +12471,10 @@ var ImportExportService = class {
11824
12471
  existingTasksById.set(task.id, {
11825
12472
  id: task.id,
11826
12473
  entity_id: entityId,
11827
- updated_at: safeUpdatedAt
12474
+ updated_at: safeUpdatedAt,
12475
+ deleted_at: task.deleted_at ?? null
11828
12476
  });
12477
+ wipedTasksByThisImport.delete(task.id);
11829
12478
  }
11830
12479
  const now = Date.now();
11831
12480
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
@@ -11865,6 +12514,15 @@ var ImportExportService = class {
11865
12514
  await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
11866
12515
  });
11867
12516
  for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
12517
+ if (tombstoneSkipped > 0) {
12518
+ emitDiagnostic(this.options, {
12519
+ code: "import_tombstone_skipped",
12520
+ operation: "importDump",
12521
+ trigger: "call",
12522
+ entityId,
12523
+ detail: { count: tombstoneSkipped }
12524
+ });
12525
+ }
11868
12526
  if (clampedEvents > 0) {
11869
12527
  emitDiagnostic(this.options, {
11870
12528
  code: "event_created_at_clamped",
@@ -11890,28 +12548,28 @@ var ImportExportService = class {
11890
12548
  } else {
11891
12549
  await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
11892
12550
  }
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);
12551
+ for (const id of liveEmbedFactIds) {
12552
+ if (!factsWithPreservedBlob.has(id)) {
12553
+ const clipped = clippedTextByFactId.get(id);
11896
12554
  const embedded = await this.embeddingService.embedFact({
11897
- id: fact.id,
12555
+ id,
11898
12556
  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 : []
12557
+ title: clipped?.title ?? "",
12558
+ body: clipped?.body ?? "",
12559
+ tags: clipped?.tags ?? []
11902
12560
  }, { operation: "importDump", trigger: "call" });
11903
12561
  if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
11904
12562
  try {
11905
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
12563
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
11906
12564
  } catch (hookErr) {
11907
12565
  console.warn(
11908
- `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
12566
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
11909
12567
  hookErr
11910
12568
  );
11911
12569
  this.embeddingService.reportHookFailed(
11912
12570
  { operation: "importDump", trigger: "call" },
11913
12571
  entityId,
11914
- fact.id
12572
+ id
11915
12573
  );
11916
12574
  }
11917
12575
  }
@@ -11919,7 +12577,7 @@ var ImportExportService = class {
11919
12577
  }
11920
12578
  for (const fact of bundle.facts) {
11921
12579
  const blobData = factsWithPreservedBlob.get(fact.id);
11922
- if (blobData && !fact.deleted_at && upsertedFactIds.has(fact.id)) {
12580
+ if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
11923
12581
  try {
11924
12582
  const float32Vector = new Float32Array(
11925
12583
  blobData.buffer,
@@ -14345,6 +15003,13 @@ var WikiMemory = class {
14345
15003
  * transaction.
14346
15004
  */
14347
15005
  async setup(opts) {
15006
+ await this.db.execAsync("PRAGMA secure_delete=ON");
15007
+ const secureDelete = await this.db.getFirstAsync("PRAGMA secure_delete");
15008
+ if (!secureDelete || Number(secureDelete.secure_delete) !== 1) {
15009
+ console.warn(
15010
+ "[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."
15011
+ );
15012
+ }
14348
15013
  const setupBudgetMs = this.setupBudgetMs();
14349
15014
  const openDeadline = monotonicNow() + setupBudgetMs;
14350
15015
  const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);
@@ -14627,6 +15292,15 @@ var WikiMemory = class {
14627
15292
  if (options?.prefix === void 0) return ids;
14628
15293
  return ids.filter((id) => id.startsWith(options.prefix));
14629
15294
  }
15295
+ /**
15296
+ * Erase everything soft-deleted, store-wide, and verify it (forget-erasure
15297
+ * spec §2). Throws `EraseStepError` (partial report, `verified: false`) when
15298
+ * a step fails; skipped entities report `verified: false`.
15299
+ * `{ rebuild: true }` additionally restarts the FTS rebuild.
15300
+ */
15301
+ async erase(options) {
15302
+ return this.maintenanceService.erase(options);
15303
+ }
14630
15304
  async runPrune(entityId, options) {
14631
15305
  return this.maintenanceService.runPrune(entityId, options);
14632
15306
  }
@@ -14844,8 +15518,22 @@ var WikiMemory = class {
14844
15518
  async syncDrained(sync) {
14845
15519
  return await sync && this.searchService.isKeywordAvailable();
14846
15520
  }
14847
- async exportDump(entityIds) {
14848
- return this.importExportService.exportDump(entityIds);
15521
+ async exportDump(entityIds, opts) {
15522
+ return this.importExportService.exportDump(entityIds, opts);
15523
+ }
15524
+ /**
15525
+ * The retention windows `runPrune()` uses when the host runs it (shipped
15526
+ * defaults plus host overrides), for GDPR disclosure. Nothing prunes
15527
+ * automatically; `erase()` ignores `retainSoftDeletedFor`. Days; `null`
15528
+ * means "keep forever". Read-only.
15529
+ */
15530
+ getRetentionPolicy() {
15531
+ const c = this.options.config;
15532
+ return {
15533
+ retainSoftDeletedFor: c?.pruneRetainSoftDeletedFor ?? 7,
15534
+ retainEventsFor: c?.pruneEventsAfter ?? 30,
15535
+ pruneSupersededAfter: c?.pruneSupersededAfter ?? null
15536
+ };
14849
15537
  }
14850
15538
  /** Entity summary prose persisted from an OKF profile ≥ 1 import; null when none stored. */
14851
15539
  async getEntitySummary(entityId) {
@@ -16219,12 +16907,14 @@ function createWiki(db, options) {
16219
16907
  return new WikiMemory(db, options);
16220
16908
  }
16221
16909
 
16910
+ exports.CheckpointIncompleteError = CheckpointIncompleteError;
16222
16911
  exports.DEFAULT_CHUNK_OVERLAP = DEFAULT_CHUNK_OVERLAP;
16223
16912
  exports.DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT;
16224
16913
  exports.DEFAULT_MAX_CHUNK_LENGTH = DEFAULT_MAX_CHUNK_LENGTH;
16225
16914
  exports.DEFAULT_MAX_EMBED_CHARS = DEFAULT_MAX_EMBED_CHARS;
16226
16915
  exports.DEFAULT_SETUP_BUDGET_MS = DEFAULT_SETUP_BUDGET_MS;
16227
16916
  exports.EMBED_CHARS_CEILING = EMBED_CHARS_CEILING;
16917
+ exports.EraseStepError = EraseStepError;
16228
16918
  exports.HEAL_ANCHORS_PER_CANDIDATE = HEAL_ANCHORS_PER_CANDIDATE;
16229
16919
  exports.HEAL_BATCH_SIZE = HEAL_BATCH_SIZE;
16230
16920
  exports.HEAL_MAX_FACT_BODY_CHARS_L3 = HEAL_MAX_FACT_BODY_CHARS_L3;