@equationalapplications/core-llm-wiki 9.3.0 → 9.4.2

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.
@@ -189,8 +189,8 @@ var WikiDraftNotFound = class _WikiDraftNotFound extends Error {
189
189
  }
190
190
  };
191
191
  var WikiSupersedeError = class _WikiSupersedeError extends Error {
192
- constructor(reason) {
193
- super(`supersede() rejected: ${reason}`);
192
+ constructor(reason, verb = "supersede()") {
193
+ super(`${verb} rejected: ${reason}`);
194
194
  this.code = "WIKI_SUPERSEDE_REJECTED";
195
195
  this.name = "WikiSupersedeError";
196
196
  this.reason = reason;
@@ -1532,6 +1532,10 @@ var _SearchService = class _SearchService {
1532
1532
  this.syncChain = work.then(() => void 0, () => void 0);
1533
1533
  return work;
1534
1534
  }
1535
+ /** True when the active strategy is the transient outage placeholder (erase orphan remediation, D1: never drop under it). */
1536
+ isIndexUnavailable() {
1537
+ return this.indexStrategy instanceof UnavailableIndexStrategy;
1538
+ }
1535
1539
  /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
1536
1540
  hasStrictDrain() {
1537
1541
  const s = this.indexStrategy;
@@ -2695,6 +2699,7 @@ var SEVERITY = {
2695
2699
  erase_secure_delete_off: "error",
2696
2700
  erase_entity_skipped: "warn",
2697
2701
  erase_retired_vtab_undroppable: "warn",
2702
+ erase_fts_orphan_cleared: "info",
2698
2703
  erase_retired_remaining: "error",
2699
2704
  erase_tombstones_remaining: "error",
2700
2705
  erase_retired_read_failed: "error",
@@ -2737,7 +2742,8 @@ var MESSAGE = {
2737
2742
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
2738
2743
  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.",
2739
2744
  erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
2740
- 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.",
2745
+ erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow-table text rows were emptied (fts5 %_config and %_data ids 1 and 10 are intentionally kept) and the name stays listed until an FTS5-capable open drops it.",
2746
+ erase_fts_orphan_cleared: "An orphaned FTS5 surface (shadow or companion table, or a queryable vtab) was cleared during erase so forgotten text cannot survive in it.",
2741
2747
  erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
2742
2748
  erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
2743
2749
  erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
@@ -3660,6 +3666,7 @@ var TemporalService = class {
3660
3666
  if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
3661
3667
  if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3662
3668
  if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3669
+ if (old.valid_to != null && old.valid_to <= Math.max(now, Date.now())) throw new WikiSupersedeError("already_expired");
3663
3670
  if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
3664
3671
  if (newId === oldId) throw new WikiSupersedeError("cycle");
3665
3672
  const repl = await this.entryRepo.findTemporalRow(newId, tx);
@@ -3668,6 +3675,8 @@ var TemporalService = class {
3668
3675
  if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3669
3676
  const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
3670
3677
  if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
3678
+ const start = old.valid_from ?? old.created_at;
3679
+ if (t <= start) throw new WikiSupersedeError("invalid_interval");
3671
3680
  await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
3672
3681
  if (repl.valid_from == null) {
3673
3682
  await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
@@ -3719,6 +3728,27 @@ var TemporalService = class {
3719
3728
  this.searchService.evictCache(entityId);
3720
3729
  return { newId };
3721
3730
  }
3731
+ /**
3732
+ * End `factId`'s validity without a replacement — an archive, not a
3733
+ * deletion (INTENT rule 12, spec specs/expire). Sets `valid_to` only.
3734
+ */
3735
+ async expire(entityId, factId, options) {
3736
+ const t = options?.at === void 0 ? Date.now() : assertEpochMs("options.at", options.at);
3737
+ await this.db.withTransactionAsync(async (tx) => {
3738
+ const old = await this.entryRepo.findTemporalRow(factId, tx);
3739
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found", "expire()");
3740
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "expire()");
3741
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded", "expire()");
3742
+ if (old.valid_to != null) throw new WikiSupersedeError("already_expired", "expire()");
3743
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "expire()");
3744
+ const start = old.valid_from ?? old.created_at;
3745
+ if (t <= start) throw new WikiSupersedeError("invalid_interval", "expire()");
3746
+ const changes = await this.entryRepo.setTemporal(factId, entityId, { valid_to: t }, tx);
3747
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "expire()");
3748
+ });
3749
+ await this.searchService.syncEntries(entityId, [factId]);
3750
+ this.searchService.evictCache(entityId);
3751
+ }
3722
3752
  async history(entityId, factId) {
3723
3753
  const start = await this.entryRepo.findTemporalRow(factId);
3724
3754
  if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
@@ -6408,7 +6438,7 @@ var EraseStepError = class extends Error {
6408
6438
  if (cause !== void 0) this.cause = cause;
6409
6439
  }
6410
6440
  };
6411
- var MaintenanceService = class {
6441
+ var _MaintenanceService = class _MaintenanceService {
6412
6442
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
6413
6443
  this.db = db;
6414
6444
  this.prefix = prefix;
@@ -6637,6 +6667,7 @@ var MaintenanceService = class {
6637
6667
  syncedIds: [],
6638
6668
  registrySweep: { skipped: false, deleted: 0 },
6639
6669
  retiredUndroppable: [],
6670
+ ftsOrphansCleared: [],
6640
6671
  failedStep: null,
6641
6672
  runtime: eraseRuntime(),
6642
6673
  steps: []
@@ -6799,7 +6830,110 @@ var MaintenanceService = class {
6799
6830
  this.jobManager.releaseLock("erase", "*");
6800
6831
  }
6801
6832
  }
6802
- // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
6833
+ /**
6834
+ * Step 3 remediation (specs/erase-fts-remediation): on a runtime without
6835
+ * usable strict drains, clear orphaned FTS5 surfaces so erasure can
6836
+ * complete verified. Per surface: existence gate (vtab OR any shadow) →
6837
+ * strategy check → vtab probe → path body → companions → state write.
6838
+ * Dispatch order is D4; exact-name allowlist interpolation is D2.
6839
+ */
6840
+ async _eraseClearFtsOrphans(report) {
6841
+ const surfaces = [`${this.prefix}entries_fts`, `${this.prefix}source_passages_fts`];
6842
+ let remediationRequired = false;
6843
+ const pathBTargets = [];
6844
+ try {
6845
+ for (const surface of surfaces) {
6846
+ const vtabExists = await this.sourceTableExists(surface);
6847
+ const shadows = [];
6848
+ for (const sfx of _MaintenanceService.FTS_SHADOW_SUFFIXES) {
6849
+ const name = `${surface}${sfx}`;
6850
+ if (await this.sourceTableExists(name)) shadows.push(name);
6851
+ }
6852
+ if (!vtabExists && shadows.length === 0) continue;
6853
+ remediationRequired = true;
6854
+ if (this.searchService.isIndexUnavailable()) {
6855
+ report.failedStep = "index_sync";
6856
+ throw new EraseStepError("erase_fts_index_unavailable", "erase stopped at step 3: the index strategy is unavailable and orphaned FTS surfaces remain; erasure is unverified", report);
6857
+ }
6858
+ let moduleLess = false;
6859
+ if (vtabExists) {
6860
+ try {
6861
+ await this.db.getFirstAsync(`SELECT 1 AS x FROM ${surface} LIMIT 1`);
6862
+ } catch (err) {
6863
+ let absent = false;
6864
+ let cur = err;
6865
+ for (let depth = 0; depth < 3 && cur != null && !absent; depth++) {
6866
+ let msg = "";
6867
+ try {
6868
+ msg = String(cur.message ?? cur);
6869
+ } catch {
6870
+ break;
6871
+ }
6872
+ absent = /no such module/i.test(msg);
6873
+ try {
6874
+ cur = cur.cause;
6875
+ } catch {
6876
+ break;
6877
+ }
6878
+ }
6879
+ if (!absent) {
6880
+ report.failedStep = "index_sync";
6881
+ throw new EraseStepError("erase_fts_orphan_probe_failed", `erase stopped at step 3: could not classify orphaned vtab ${surface}`, report, err);
6882
+ }
6883
+ moduleLess = true;
6884
+ }
6885
+ }
6886
+ if (vtabExists && !moduleLess) {
6887
+ if (this.options.config?.indexStrategy !== "minisearch") {
6888
+ report.failedStep = "index_sync";
6889
+ throw new EraseStepError("erase_fts_index_unavailable", `erase stopped at step 3: ${surface} is live and queryable but MiniSearch is not the configured strategy; erasure is unverified`, report);
6890
+ }
6891
+ pathBTargets.push(surface);
6892
+ continue;
6893
+ }
6894
+ const cleared = [];
6895
+ for (const name of shadows) {
6896
+ if (name.endsWith("_config")) continue;
6897
+ const res = await this.db.runAsync(name.endsWith("_data") ? `DELETE FROM ${name} WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}`);
6898
+ if ((res?.changes ?? 0) > 0) cleared.push(name);
6899
+ }
6900
+ for (const name of cleared) {
6901
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
6902
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
6903
+ }
6904
+ }
6905
+ if (!remediationRequired) return;
6906
+ const tailCleared = [];
6907
+ await this.db.withTransactionAsync(async (tx) => {
6908
+ for (const companion of [`${this.prefix}fts_pending`, `${this.prefix}fts_map`, `${this.prefix}source_passages_fts_pending`, `${this.prefix}source_passages_fts_map`]) {
6909
+ if (await this.sourceTableExists(companion, tx)) {
6910
+ const res = await tx.runAsync(`DELETE FROM ${companion}`);
6911
+ if ((res?.changes ?? 0) > 0 && !tailCleared.includes(companion)) tailCleared.push(companion);
6912
+ }
6913
+ }
6914
+ for (const surface of pathBTargets) {
6915
+ await tx.execAsync(`DROP TABLE IF EXISTS ${surface}`);
6916
+ if (!tailCleared.includes(surface)) tailCleared.push(surface);
6917
+ }
6918
+ if (pathBTargets.length > 0) {
6919
+ const [ai, ad] = passageFtsTriggerNames(this.prefix);
6920
+ await tx.execAsync(fts5LedgerDropSql(this.prefix) + `
6921
+ DROP TRIGGER IF EXISTS ${ai};
6922
+ DROP TRIGGER IF EXISTS ${ad};`);
6923
+ }
6924
+ await this.metadataRepo.setMeta(FTS5_STATE_KEY, "detached", tx);
6925
+ });
6926
+ for (const name of tailCleared) {
6927
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
6928
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
6929
+ }
6930
+ report.steps.push({ step: "fts_orphan_clear", outcome: "ok" });
6931
+ } catch (err) {
6932
+ if (err instanceof EraseStepError) throw err;
6933
+ report.failedStep = "fts_orphan_clear";
6934
+ throw new EraseStepError("erase_fts_orphan_clear", "erase stopped at step 3: clearing an orphaned FTS surface failed; erasure is unverified", report, err);
6935
+ }
6936
+ }
6803
6937
  /**
6804
6938
  * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
6805
6939
  * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
@@ -6810,6 +6944,7 @@ var MaintenanceService = class {
6810
6944
  */
6811
6945
  async _eraseDrainPassages(report) {
6812
6946
  if (!this.searchService.hasStrictDrain()) {
6947
+ await this._eraseClearFtsOrphans(report);
6813
6948
  for (const [table, failedStep, code] of [
6814
6949
  [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
6815
6950
  [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
@@ -6826,19 +6961,6 @@ var MaintenanceService = class {
6826
6961
  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);
6827
6962
  }
6828
6963
  }
6829
- for (const suffix of ["entries_fts_content", "source_passages_fts_content"]) {
6830
- let orphaned = false;
6831
- try {
6832
- orphaned = await this.sourceTableExists(`${this.prefix}${suffix}`);
6833
- } catch (err) {
6834
- report.failedStep = "index_sync";
6835
- throw new EraseStepError("erase_orphaned_fts_content", `erase stopped: could not probe ${this.prefix}${suffix}`, report, err);
6836
- }
6837
- if (orphaned) {
6838
- report.failedStep = "index_sync";
6839
- throw new EraseStepError("erase_orphaned_fts_content", "erase stopped: orphaned full-text content tables may still hold forgotten text", report);
6840
- }
6841
- }
6842
6964
  }
6843
6965
  try {
6844
6966
  await this.searchService.drainEntriesLedgerSurfaced();
@@ -6874,7 +6996,10 @@ var MaintenanceService = class {
6874
6996
  try {
6875
6997
  for (const name of await this._retiredList()) {
6876
6998
  for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
6877
- if (await this.sourceTableExists(`${name}${sfx}`)) await this.db.runAsync(`DELETE FROM ${name}${sfx}`);
6999
+ if (sfx === "_config") continue;
7000
+ if (await this.sourceTableExists(`${name}${sfx}`)) {
7001
+ await this.db.runAsync(sfx === "_data" ? `DELETE FROM ${name}_data WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}${sfx}`);
7002
+ }
6878
7003
  }
6879
7004
  if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
6880
7005
  emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
@@ -6894,8 +7019,8 @@ var MaintenanceService = class {
6894
7019
  }
6895
7020
  return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
6896
7021
  }
6897
- sourceTableExists(name) {
6898
- return this.metadataRepo.tableExists(name);
7022
+ sourceTableExists(name, tx) {
7023
+ return this.metadataRepo.tableExists(name, tx);
6899
7024
  }
6900
7025
  /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
6901
7026
  async _eraseSyncEntries(entityId, ids, report) {
@@ -7990,6 +8115,9 @@ var MaintenanceService = class {
7990
8115
  return sanitizeRankerError(err, this.options.sanitizeRankerErrors);
7991
8116
  }
7992
8117
  };
8118
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
8119
+ _MaintenanceService.FTS_SHADOW_SUFFIXES = ["_content", "_data", "_idx", "_docsize", "_config"];
8120
+ var MaintenanceService = _MaintenanceService;
7993
8121
 
7994
8122
  // src/utils/passageCutter.ts
7995
8123
  var MAX_PASSAGE_UNITS = 12e3;
@@ -10569,5 +10697,5 @@ var WriteService = class {
10569
10697
  };
10570
10698
 
10571
10699
  export { BaseRepository, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
10572
- //# sourceMappingURL=chunk-H436I7OM.mjs.map
10573
- //# sourceMappingURL=chunk-H436I7OM.mjs.map
10700
+ //# sourceMappingURL=chunk-TJYITTAO.mjs.map
10701
+ //# sourceMappingURL=chunk-TJYITTAO.mjs.map