@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.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-E3JCZMJL.mjs';
2
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-E3JCZMJL.mjs';
1
+ import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-T75YZCVX.mjs';
2
+ export { CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, EraseStepError, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-T75YZCVX.mjs';
3
3
  import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, createEventIdDeriver, latestVerified, formatSourcesJson, appendEventIdComment, parseVerifiedFlexible, parseCitationsList } from '@equationalapplications/core-okf';
4
4
  import MiniSearch from 'minisearch';
5
5
 
@@ -348,10 +348,15 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
348
348
  const chunk = ids.slice(i, i + this.chunkSize);
349
349
  const placeholders = chunk.map(() => "?").join(",");
350
350
  const chunkRows = await executor.getAllAsync(
351
- `SELECT id, entity_id, updated_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
351
+ `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
352
352
  chunk
353
353
  );
354
- rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));
354
+ rows.push(...chunkRows.map((row) => ({
355
+ id: row.id,
356
+ entity_id: row.entity_id,
357
+ updated_at: Number(row.updated_at),
358
+ deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
359
+ })));
355
360
  }
356
361
  return rows;
357
362
  }
@@ -523,22 +528,25 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
523
528
  * Fetch IDs + entity_ids of soft-deleted rows older than cutoff for a given entity.
524
529
  * Used by runPrune().
525
530
  */
526
- async getPrunableMetadata(entityId, cutoff, tx) {
531
+ async getPrunableMetadata(entityId, cutoff, tx, opts) {
527
532
  const executor = this.getExecutor(tx);
533
+ const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
534
+ const args = opts?.noCutoff ? [entityId] : [entityId, cutoff];
528
535
  return executor.getAllAsync(
529
536
  `SELECT id, entity_id FROM ${this.prefix}entries
530
- WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
531
- [entityId, cutoff]
537
+ WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
538
+ args
532
539
  );
533
540
  }
534
541
  /**
535
542
  * Fetch all non-deleted entries for an entity, ordered by updated_at DESC.
536
543
  * Used by _getFullBundle().
537
544
  */
538
- async findAllByEntityId(entityId, tx) {
545
+ async findAllByEntityId(entityId, tx, opts) {
539
546
  const executor = this.getExecutor(tx);
547
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
540
548
  const rows = await executor.getAllAsync(
541
- `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,
549
+ `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
542
550
  [entityId]
543
551
  );
544
552
  return rows.map(mapRowToFact);
@@ -618,10 +626,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
618
626
  * Fetch all non-deleted entries for an entity with embedding blobs preserved.
619
627
  * Used by ImportExportService for export/import round-tripping.
620
628
  */
621
- async findAllByEntityIdWithBlobs(entityId, tx) {
629
+ async findAllByEntityIdWithBlobs(entityId, tx, opts) {
622
630
  const executor = this.getExecutor(tx);
631
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
623
632
  const rows = await executor.getAllAsync(
624
- `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,
633
+ `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
625
634
  [entityId]
626
635
  );
627
636
  return rows.map(mapRowToFactWithBlobs);
@@ -692,20 +701,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
692
701
  for (let i = 0; i < ids.length; i += chunkSize) {
693
702
  const chunk = ids.slice(i, i + chunkSize);
694
703
  const placeholders = chunk.map(() => "?").join(",");
704
+ const cutoffPredicate = opts.noCutoff ? "" : " AND deleted_at <= ?";
705
+ const delArgs = opts.noCutoff ? [entityId, ...chunk] : [entityId, cutoff, ...chunk];
695
706
  const deleted = (await executor.getAllAsync(
696
- `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})${guard} RETURNING id`,
697
- [entityId, cutoff, ...chunk]
698
- )).map((r) => r.id);
707
+ `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate} AND id IN (${placeholders})${guard} RETURNING id, deleted_at`,
708
+ delArgs
709
+ )).map((r) => ({ id: r.id, deleted_at: typeof r.deleted_at === "number" ? r.deleted_at : Number(r.deleted_at) }));
699
710
  totalChanges += deleted.length;
700
- opts.deletedIds?.push(...deleted);
711
+ opts.deletedIds?.push(...deleted.map((r) => r.id));
701
712
  if (deleted.length > 0) {
702
- for (const id of deleted) {
713
+ for (const row of deleted) {
703
714
  await this.outbox.push({
704
715
  entityId,
705
716
  tableName: "entries",
706
- recordId: id,
717
+ recordId: row.id,
707
718
  operation: "DELETE",
708
- payload: { id, entity_id: entityId, deleted_at: cutoff }
719
+ payload: { id: row.id, entity_id: entityId, deleted_at: row.deleted_at }
709
720
  }, tx);
710
721
  }
711
722
  }
@@ -874,6 +885,19 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
874
885
  );
875
886
  return new Set(rows.map((r) => r.id));
876
887
  }
888
+ /**
889
+ * Depth-aware supersession walk for chain forget (spec forget-erasure §3).
890
+ * Probes `maxDepth + 1` levels so a chain longer than the cap is detectable;
891
+ * the returned ids are capped to `maxDepth` per direction (successors nearest first; predecessors are returned farthest-first).
892
+ * No `deleted_at` filter: soft-deleted links still carry the chain.
893
+ */
894
+ async findSupersessionChainWalk(entityId, factId, maxDepth, tx) {
895
+ const { predecessors, successors } = await this.findSupersessionChainIds(entityId, factId, maxDepth + 1, tx);
896
+ const truncated = predecessors.some((r) => r.depth > maxDepth) || successors.some((r) => r.depth > maxDepth);
897
+ const pred = predecessors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
898
+ const succ = successors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
899
+ return { ids: Array.from(/* @__PURE__ */ new Set([...succ, ...pred])), truncated };
900
+ }
877
901
  async findSupersessionChainIds(entityId, factId, maxDepth, tx) {
878
902
  const executor = this.getExecutor(tx);
879
903
  const successors = await executor.getAllAsync(
@@ -884,7 +908,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
884
908
  JOIN ${this.prefix}entries e ON e.id = fwd.id AND e.entity_id = ?
885
909
  WHERE e.superseded_by IS NOT NULL AND fwd.depth < ?
886
910
  )
887
- SELECT id FROM fwd ORDER BY depth ASC`,
911
+ SELECT id, depth FROM fwd ORDER BY depth ASC`,
888
912
  [factId, entityId, entityId, maxDepth]
889
913
  );
890
914
  const predecessors = await executor.getAllAsync(
@@ -895,10 +919,10 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
895
919
  JOIN ${this.prefix}entries e ON e.entity_id = ? AND e.superseded_by = bwd.id
896
920
  WHERE bwd.depth < ?
897
921
  )
898
- SELECT id FROM bwd ORDER BY depth DESC`,
922
+ SELECT id, depth FROM bwd ORDER BY depth DESC`,
899
923
  [entityId, factId, entityId, maxDepth]
900
924
  );
901
- const drop = (ids) => ids.map((r) => r.id).filter((id) => id !== factId);
925
+ const drop = (rows) => rows.filter((r) => r.id !== factId);
902
926
  return { predecessors: drop(predecessors), successors: drop(successors) };
903
927
  }
904
928
  async findExpiredIds(entityId, cutoff, tx) {
@@ -1705,10 +1729,15 @@ var TaskRepository = class extends BaseRepository {
1705
1729
  const chunk = ids.slice(i, i + chunkSize);
1706
1730
  const placeholders = chunk.map(() => "?").join(",");
1707
1731
  const chunkRows = await executor.getAllAsync(
1708
- `SELECT id, entity_id, updated_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
1732
+ `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
1709
1733
  chunk
1710
1734
  );
1711
- rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));
1735
+ rows.push(...chunkRows.map((row) => ({
1736
+ id: row.id,
1737
+ entity_id: row.entity_id,
1738
+ updated_at: Number(row.updated_at),
1739
+ deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
1740
+ })));
1712
1741
  }
1713
1742
  return rows;
1714
1743
  }
@@ -1871,10 +1900,11 @@ var TaskRepository = class extends BaseRepository {
1871
1900
  * Fetch all non-deleted tasks for an entity, ordered by priority DESC, created_at ASC.
1872
1901
  * Used by _getFullBundle().
1873
1902
  */
1874
- async findAllByEntityId(entityId, tx) {
1903
+ async findAllByEntityId(entityId, tx, opts) {
1875
1904
  const executor = this.getExecutor(tx);
1905
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
1876
1906
  const rows = await executor.getAllAsync(
1877
- `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NULL ORDER BY priority DESC, created_at ASC`,
1907
+ `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ?${live} ORDER BY priority DESC, created_at ASC`,
1878
1908
  [entityId]
1879
1909
  );
1880
1910
  return rows.map(mapRowToTask);
@@ -1883,16 +1913,19 @@ var TaskRepository = class extends BaseRepository {
1883
1913
  * Bulk delete pruned tasks (already soft-deleted) by cutoff date.
1884
1914
  * Used by runPrune(). Returns number of deleted rows.
1885
1915
  */
1886
- async bulkDeletePruned(entityId, cutoff, tx) {
1916
+ async bulkDeletePruned(entityId, cutoff, tx, opts) {
1887
1917
  const executor = this.getExecutor(tx);
1918
+ const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
1919
+ const selectArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
1888
1920
  const rowsToDelete = await executor.getAllAsync(
1889
- `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
1890
- [entityId, cutoff]
1921
+ `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
1922
+ selectArgs
1891
1923
  );
1892
1924
  if (rowsToDelete.length === 0) return 0;
1925
+ const deleteArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
1893
1926
  const result = await executor.runAsync(
1894
- `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
1895
- [entityId, cutoff]
1927
+ `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
1928
+ deleteArgs
1896
1929
  );
1897
1930
  for (const row of rowsToDelete) {
1898
1931
  await this.outbox.push(
@@ -2286,6 +2319,7 @@ var Fts5IndexStrategy = class {
2286
2319
  const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);
2287
2320
  if (mapped === null && queued === null) {
2288
2321
  await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);
2322
+ await tx.runAsync(`INSERT INTO ${p}source_passages_fts(${p}source_passages_fts) VALUES('rebuild')`);
2289
2323
  await tx.runAsync(
2290
2324
  `INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)
2291
2325
  SELECT entity_id, id FROM ${p}source_documents`
@@ -2551,6 +2585,53 @@ var Fts5IndexStrategy = class {
2551
2585
  if (!isSqliteError(err)) throw err;
2552
2586
  }
2553
2587
  }
2588
+ /** Listed retired table names (erase step 4 / module-less fallback). */
2589
+ async retiredTables() {
2590
+ return this.retiredList();
2591
+ }
2592
+ /**
2593
+ * Erase step 4: reclaim every retired table to completion (DROP + delist), no
2594
+ * deadline. Failures surface (unlike the best-effort quantum path); the
2595
+ * SQLITE_CORRUPT_VTAB hollowed-shell exit inside reclaimRetired is designed.
2596
+ */
2597
+ async reclaimRetiredToCompletion() {
2598
+ await this.reclaimRetired(Number.POSITIVE_INFINITY);
2599
+ }
2600
+ /**
2601
+ * Erase step 3: surfaced passage drain, no deadline. Fails only when passage
2602
+ * init was disabled AND the ledger still has rows; otherwise warns and continues.
2603
+ */
2604
+ async drainPassagesStrict() {
2605
+ if (this.passagesDisabled) {
2606
+ const p = this.prefix;
2607
+ 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;
2608
+ if (pending) throw new Error("passage index disabled with pending ledger rows");
2609
+ console.warn("[WikiMemory] erase: passage index disabled; nothing pending, continuing");
2610
+ return;
2611
+ }
2612
+ await this.drainPassages({});
2613
+ }
2614
+ /**
2615
+ * Erase step 3 (entries side): drain the trigger-fed `fts_pending` ledger store-wide to
2616
+ * empty, no deadline, errors surfaced; throws if rows remain afterwards.
2617
+ */
2618
+ async drainEntriesLedgerStrict() {
2619
+ while (await this.drainLedgerChunk()) ;
2620
+ const left = await this.db.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}fts_pending LIMIT 1`);
2621
+ if (left !== null && left !== void 0) throw new Error("entries FTS ledger still has pending rows after drain");
2622
+ }
2623
+ /** Erase step 7: FTS 'optimize' on each FTS table that exists. */
2624
+ async optimizeFts() {
2625
+ const p = this.prefix;
2626
+ for (const t of [`${p}entries_fts`, `${p}source_passages_fts`]) {
2627
+ if (!await this.metadataRepo.tableExists(t)) continue;
2628
+ await this.db.runAsync(`INSERT INTO ${t}(${t}) VALUES('optimize')`);
2629
+ }
2630
+ }
2631
+ /** `erase({ rebuild: true })` surface: retire + recreate the entries index and re-arm the rebuild. */
2632
+ async rebuildForErase() {
2633
+ await this.resetAndRearm();
2634
+ }
2554
2635
  /** Bounded reclamation steps, each its own tx, until the deadline or nothing is retired. */
2555
2636
  async reclaimRetired(deadline) {
2556
2637
  while (monotonicNow() < deadline) {
@@ -4349,6 +4430,13 @@ var WikiMemory = class {
4349
4430
  * transaction.
4350
4431
  */
4351
4432
  async setup(opts) {
4433
+ await this.db.execAsync("PRAGMA secure_delete=ON");
4434
+ const secureDelete = await this.db.getFirstAsync("PRAGMA secure_delete");
4435
+ if (!secureDelete || Number(secureDelete.secure_delete) !== 1) {
4436
+ console.warn(
4437
+ "[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."
4438
+ );
4439
+ }
4352
4440
  const setupBudgetMs = this.setupBudgetMs();
4353
4441
  const openDeadline = monotonicNow() + setupBudgetMs;
4354
4442
  const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);
@@ -4631,6 +4719,15 @@ var WikiMemory = class {
4631
4719
  if (options?.prefix === void 0) return ids;
4632
4720
  return ids.filter((id) => id.startsWith(options.prefix));
4633
4721
  }
4722
+ /**
4723
+ * Erase everything soft-deleted, store-wide, and verify it (forget-erasure
4724
+ * spec §2). Throws `EraseStepError` (partial report, `verified: false`) when
4725
+ * a step fails; skipped entities report `verified: false`.
4726
+ * `{ rebuild: true }` additionally restarts the FTS rebuild.
4727
+ */
4728
+ async erase(options) {
4729
+ return this.maintenanceService.erase(options);
4730
+ }
4634
4731
  async runPrune(entityId, options) {
4635
4732
  return this.maintenanceService.runPrune(entityId, options);
4636
4733
  }
@@ -4848,8 +4945,22 @@ var WikiMemory = class {
4848
4945
  async syncDrained(sync) {
4849
4946
  return await sync && this.searchService.isKeywordAvailable();
4850
4947
  }
4851
- async exportDump(entityIds) {
4852
- return this.importExportService.exportDump(entityIds);
4948
+ async exportDump(entityIds, opts) {
4949
+ return this.importExportService.exportDump(entityIds, opts);
4950
+ }
4951
+ /**
4952
+ * The retention windows `runPrune()` uses when the host runs it (shipped
4953
+ * defaults plus host overrides), for GDPR disclosure. Nothing prunes
4954
+ * automatically; `erase()` ignores `retainSoftDeletedFor`. Days; `null`
4955
+ * means "keep forever". Read-only.
4956
+ */
4957
+ getRetentionPolicy() {
4958
+ const c = this.options.config;
4959
+ return {
4960
+ retainSoftDeletedFor: c?.pruneRetainSoftDeletedFor ?? 7,
4961
+ retainEventsFor: c?.pruneEventsAfter ?? 30,
4962
+ pruneSupersededAfter: c?.pruneSupersededAfter ?? null
4963
+ };
4853
4964
  }
4854
4965
  /** Entity summary prose persisted from an OKF profile ≥ 1 import; null when none stored. */
4855
4966
  async getEntitySummary(entityId) {
@@ -4909,11 +5020,23 @@ var WikiMemory = class {
4909
5020
  /**
4910
5021
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
4911
5022
  * transaction. Throws `WikiSupersedeError` for missing, foreign, already
4912
- * superseded, immutable-document, or cyclic targets.
5023
+ * superseded, already expired, immutable-document, or cyclic targets.
4913
5024
  */
4914
5025
  async supersede(entityId, oldId, replacement, options) {
4915
5026
  return this.temporalService.supersede(entityId, oldId, replacement, options);
4916
5027
  }
5028
+ /**
5029
+ * End `factId`'s validity without a replacement — an archive, not a
5030
+ * deletion (INTENT rule 12). Sets `valid_to` only: `superseded_by`,
5031
+ * `superseded_at` and `deleted_at` stay untouched, and an `asOf` read at
5032
+ * `T` with `COALESCE(valid_from, created_at) <= T < valid_to` still returns
5033
+ * the fact. Throws `WikiSupersedeError` for
5034
+ * a missing, foreign, already superseded, immutable-document, or already
5035
+ * expired target, and for an inverted or empty interval (`invalid_interval`).
5036
+ */
5037
+ async expire(entityId, factId, options) {
5038
+ return this.temporalService.expire(entityId, factId, options);
5039
+ }
4917
5040
  /** The supersession chain containing `factId`, oldest first. [] when unknown. */
4918
5041
  async history(entityId, factId) {
4919
5042
  return this.temporalService.history(entityId, factId);