@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.
@@ -862,13 +862,15 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
862
862
  * Closed for this release series, but new codes are added in minor versions:
863
863
  * hosts must tolerate codes they do not recognize.
864
864
  */
865
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'prune_checkpoint_incomplete' | 'erase_secure_delete_off' | 'erase_entity_skipped' | 'erase_retired_vtab_undroppable' | 'erase_retired_remaining' | 'erase_tombstones_remaining' | 'erase_retired_read_failed' | 'erase_registry_sweep_skipped' | 'import_tombstone_skipped' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid' | 'source_store_source_too_large' | 'source_store_budget_exceeded' | 'source_store_hash_mismatch' | 'source_store_duplicate_hash' | 'source_store_text_not_storable';
865
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'prune_checkpoint_incomplete' | 'erase_secure_delete_off' | 'erase_entity_skipped' | 'erase_retired_vtab_undroppable' | 'erase_fts_orphan_cleared' | 'erase_retired_remaining' | 'erase_tombstones_remaining' | 'erase_retired_read_failed' | 'erase_registry_sweep_skipped' | 'import_tombstone_skipped' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid' | 'source_store_source_too_large' | 'source_store_budget_exceeded' | 'source_store_hash_mismatch' | 'source_store_duplicate_hash' | 'source_store_text_not_storable';
866
866
  /** The service run that emitted the diagnostic. */
867
867
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion' | 'sourceStore' | 'erase';
868
868
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
869
869
  type WikiDiagnosticTrigger = 'call' | 'auto';
870
870
  /** Identifiers only — never titles, bodies, quotes, LLM output, provider messages, or hashes of content. */
871
871
  interface WikiDiagnosticDetail {
872
+ /** The FTS5 surface the diagnostic names. */
873
+ table?: string;
872
874
  factId?: string;
873
875
  sourceRef?: string;
874
876
  chunkIndex?: number;
@@ -1446,12 +1448,12 @@ declare class WikiDraftNotFound extends Error {
1446
1448
  readonly code: "WIKI_DRAFT_NOT_FOUND";
1447
1449
  constructor();
1448
1450
  }
1449
- type WikiSupersedeReason = 'not_found' | 'already_superseded' | 'immutable_target' | 'cycle' | 'cross_entity';
1450
- /** Thrown by `supersede()` (spec §4.3). Contextless like {@link WikiDraftNotFound}. */
1451
+ type WikiSupersedeReason = 'not_found' | 'already_superseded' | 'immutable_target' | 'cycle' | 'cross_entity' | 'already_expired' | 'invalid_interval';
1452
+ /** Thrown by `supersede()` and `expire()` (spec §4.3). Contextless like {@link WikiDraftNotFound}. */
1451
1453
  declare class WikiSupersedeError extends Error {
1452
1454
  readonly code: "WIKI_SUPERSEDE_REJECTED";
1453
1455
  readonly reason: WikiSupersedeReason;
1454
- constructor(reason: WikiSupersedeReason);
1456
+ constructor(reason: WikiSupersedeReason, verb?: string);
1455
1457
  }
1456
1458
  /** A new fact to create as the replacement, or the id of an existing fact. */
1457
1459
  type SupersedeReplacement = string | {
@@ -2654,6 +2656,8 @@ declare class SearchService {
2654
2656
  syncPassages(db: SQLiteAdapter, prefix: string, entityId?: string, deadline?: number): Promise<void>;
2655
2657
  /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
2656
2658
  private chainSurfaced;
2659
+ /** True when the active strategy is the transient outage placeholder (erase orphan remediation, D1: never drop under it). */
2660
+ isIndexUnavailable(): boolean;
2657
2661
  /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
2658
2662
  hasStrictDrain(): boolean;
2659
2663
  /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
@@ -3828,7 +3832,9 @@ interface EraseReport {
3828
3832
  };
3829
3833
  /** Retired FTS tables left listed (module-less runtime): shadow tables emptied, DROP deferred to an FTS5-capable open. */
3830
3834
  retiredUndroppable: string[];
3831
- failedStep: 'secure_delete' | 'vacuum' | 'checkpoint' | 'prune' | 'registry_sweep' | 'passage_drain' | 'retired_reclaim' | 'index_sync' | 'optimize' | 'rebuild' | 'tombstone_gate' | null;
3835
+ /** FTS5 orphan surfaces cleared (Path A/C) or dropped (Path B) by the step-3 remediation (specs/erase-fts-remediation D3). Names are recorded only after the owning transaction commits. */
3836
+ ftsOrphansCleared: string[];
3837
+ failedStep: 'secure_delete' | 'vacuum' | 'checkpoint' | 'prune' | 'registry_sweep' | 'passage_drain' | 'retired_reclaim' | 'index_sync' | 'optimize' | 'rebuild' | 'tombstone_gate' | 'fts_orphan_clear' | null;
3832
3838
  /** JS runtime the erase ran on (no overclaiming: this is not a storage-layer guarantee). */
3833
3839
  runtime: string;
3834
3840
  /** Every step's outcome, in execution order; a failed step is last. `partial` = ran with skipped entities or holds, or was skipped by design (`registry_sweep` on a pre-v9 store; `tombstone_gate` when holds/skips already account for surviving rows). */
@@ -3888,6 +3894,15 @@ declare class MaintenanceService {
3888
3894
  erase(opts?: {
3889
3895
  rebuild?: boolean;
3890
3896
  }): Promise<EraseReport>;
3897
+ private static readonly FTS_SHADOW_SUFFIXES;
3898
+ /**
3899
+ * Step 3 remediation (specs/erase-fts-remediation): on a runtime without
3900
+ * usable strict drains, clear orphaned FTS5 surfaces so erasure can
3901
+ * complete verified. Per surface: existence gate (vtab OR any shadow) →
3902
+ * strategy check → vtab probe → path body → companions → state write.
3903
+ * Dispatch order is D4; exact-name allowlist interpolation is D2.
3904
+ */
3905
+ _eraseClearFtsOrphans(report: EraseReport): Promise<void>;
3891
3906
  /**
3892
3907
  * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
3893
3908
  * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
@@ -4297,6 +4312,13 @@ declare class TemporalService {
4297
4312
  }): Promise<{
4298
4313
  newId: string;
4299
4314
  }>;
4315
+ /**
4316
+ * End `factId`'s validity without a replacement — an archive, not a
4317
+ * deletion (INTENT rule 12, spec specs/expire). Sets `valid_to` only.
4318
+ */
4319
+ expire(entityId: string, factId: string, options?: {
4320
+ at?: number;
4321
+ }): Promise<void>;
4300
4322
  history(entityId: string, factId: string): Promise<WikiFact[]>;
4301
4323
  }
4302
4324
 
@@ -4741,13 +4763,26 @@ declare class WikiMemory {
4741
4763
  /**
4742
4764
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
4743
4765
  * transaction. Throws `WikiSupersedeError` for missing, foreign, already
4744
- * superseded, immutable-document, or cyclic targets.
4766
+ * superseded, already expired, immutable-document, or cyclic targets, and
4767
+ * for an inverted or empty interval (`invalid_interval`).
4745
4768
  */
4746
4769
  supersede(entityId: string, oldId: string, replacement: SupersedeReplacement, options?: {
4747
4770
  validFrom?: number;
4748
4771
  }): Promise<{
4749
4772
  newId: string;
4750
4773
  }>;
4774
+ /**
4775
+ * End `factId`'s validity without a replacement — an archive, not a
4776
+ * deletion (INTENT rule 12). Sets `valid_to` only: `superseded_by`,
4777
+ * `superseded_at` and `deleted_at` stay untouched, and an `asOf` read at
4778
+ * `T` with `COALESCE(valid_from, created_at) <= T < valid_to` still returns
4779
+ * the fact. Throws `WikiSupersedeError` for
4780
+ * a missing, foreign, already superseded, immutable-document, or already
4781
+ * expired target, and for an inverted or empty interval (`invalid_interval`).
4782
+ */
4783
+ expire(entityId: string, factId: string, options?: {
4784
+ at?: number;
4785
+ }): Promise<void>;
4751
4786
  /** The supersession chain containing `factId`, oldest first. [] when unknown. */
4752
4787
  history(entityId: string, factId: string): Promise<WikiFact[]>;
4753
4788
  /**
@@ -862,13 +862,15 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
862
862
  * Closed for this release series, but new codes are added in minor versions:
863
863
  * hosts must tolerate codes they do not recognize.
864
864
  */
865
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'prune_checkpoint_incomplete' | 'erase_secure_delete_off' | 'erase_entity_skipped' | 'erase_retired_vtab_undroppable' | 'erase_retired_remaining' | 'erase_tombstones_remaining' | 'erase_retired_read_failed' | 'erase_registry_sweep_skipped' | 'import_tombstone_skipped' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid' | 'source_store_source_too_large' | 'source_store_budget_exceeded' | 'source_store_hash_mismatch' | 'source_store_duplicate_hash' | 'source_store_text_not_storable';
865
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'prune_checkpoint_incomplete' | 'erase_secure_delete_off' | 'erase_entity_skipped' | 'erase_retired_vtab_undroppable' | 'erase_fts_orphan_cleared' | 'erase_retired_remaining' | 'erase_tombstones_remaining' | 'erase_retired_read_failed' | 'erase_registry_sweep_skipped' | 'import_tombstone_skipped' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded' | 'guidance_too_long' | 'guidance_resolver_failed' | 'source_pointer_unresolved' | 'source_pointer_invalid' | 'source_store_source_too_large' | 'source_store_budget_exceeded' | 'source_store_hash_mismatch' | 'source_store_duplicate_hash' | 'source_store_text_not_storable';
866
866
  /** The service run that emitted the diagnostic. */
867
867
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion' | 'sourceStore' | 'erase';
868
868
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
869
869
  type WikiDiagnosticTrigger = 'call' | 'auto';
870
870
  /** Identifiers only — never titles, bodies, quotes, LLM output, provider messages, or hashes of content. */
871
871
  interface WikiDiagnosticDetail {
872
+ /** The FTS5 surface the diagnostic names. */
873
+ table?: string;
872
874
  factId?: string;
873
875
  sourceRef?: string;
874
876
  chunkIndex?: number;
@@ -1446,12 +1448,12 @@ declare class WikiDraftNotFound extends Error {
1446
1448
  readonly code: "WIKI_DRAFT_NOT_FOUND";
1447
1449
  constructor();
1448
1450
  }
1449
- type WikiSupersedeReason = 'not_found' | 'already_superseded' | 'immutable_target' | 'cycle' | 'cross_entity';
1450
- /** Thrown by `supersede()` (spec §4.3). Contextless like {@link WikiDraftNotFound}. */
1451
+ type WikiSupersedeReason = 'not_found' | 'already_superseded' | 'immutable_target' | 'cycle' | 'cross_entity' | 'already_expired' | 'invalid_interval';
1452
+ /** Thrown by `supersede()` and `expire()` (spec §4.3). Contextless like {@link WikiDraftNotFound}. */
1451
1453
  declare class WikiSupersedeError extends Error {
1452
1454
  readonly code: "WIKI_SUPERSEDE_REJECTED";
1453
1455
  readonly reason: WikiSupersedeReason;
1454
- constructor(reason: WikiSupersedeReason);
1456
+ constructor(reason: WikiSupersedeReason, verb?: string);
1455
1457
  }
1456
1458
  /** A new fact to create as the replacement, or the id of an existing fact. */
1457
1459
  type SupersedeReplacement = string | {
@@ -2654,6 +2656,8 @@ declare class SearchService {
2654
2656
  syncPassages(db: SQLiteAdapter, prefix: string, entityId?: string, deadline?: number): Promise<void>;
2655
2657
  /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
2656
2658
  private chainSurfaced;
2659
+ /** True when the active strategy is the transient outage placeholder (erase orphan remediation, D1: never drop under it). */
2660
+ isIndexUnavailable(): boolean;
2657
2661
  /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
2658
2662
  hasStrictDrain(): boolean;
2659
2663
  /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
@@ -3828,7 +3832,9 @@ interface EraseReport {
3828
3832
  };
3829
3833
  /** Retired FTS tables left listed (module-less runtime): shadow tables emptied, DROP deferred to an FTS5-capable open. */
3830
3834
  retiredUndroppable: string[];
3831
- failedStep: 'secure_delete' | 'vacuum' | 'checkpoint' | 'prune' | 'registry_sweep' | 'passage_drain' | 'retired_reclaim' | 'index_sync' | 'optimize' | 'rebuild' | 'tombstone_gate' | null;
3835
+ /** FTS5 orphan surfaces cleared (Path A/C) or dropped (Path B) by the step-3 remediation (specs/erase-fts-remediation D3). Names are recorded only after the owning transaction commits. */
3836
+ ftsOrphansCleared: string[];
3837
+ failedStep: 'secure_delete' | 'vacuum' | 'checkpoint' | 'prune' | 'registry_sweep' | 'passage_drain' | 'retired_reclaim' | 'index_sync' | 'optimize' | 'rebuild' | 'tombstone_gate' | 'fts_orphan_clear' | null;
3832
3838
  /** JS runtime the erase ran on (no overclaiming: this is not a storage-layer guarantee). */
3833
3839
  runtime: string;
3834
3840
  /** Every step's outcome, in execution order; a failed step is last. `partial` = ran with skipped entities or holds, or was skipped by design (`registry_sweep` on a pre-v9 store; `tombstone_gate` when holds/skips already account for surviving rows). */
@@ -3888,6 +3894,15 @@ declare class MaintenanceService {
3888
3894
  erase(opts?: {
3889
3895
  rebuild?: boolean;
3890
3896
  }): Promise<EraseReport>;
3897
+ private static readonly FTS_SHADOW_SUFFIXES;
3898
+ /**
3899
+ * Step 3 remediation (specs/erase-fts-remediation): on a runtime without
3900
+ * usable strict drains, clear orphaned FTS5 surfaces so erasure can
3901
+ * complete verified. Per surface: existence gate (vtab OR any shadow) →
3902
+ * strategy check → vtab probe → path body → companions → state write.
3903
+ * Dispatch order is D4; exact-name allowlist interpolation is D2.
3904
+ */
3905
+ _eraseClearFtsOrphans(report: EraseReport): Promise<void>;
3891
3906
  /**
3892
3907
  * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
3893
3908
  * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
@@ -4297,6 +4312,13 @@ declare class TemporalService {
4297
4312
  }): Promise<{
4298
4313
  newId: string;
4299
4314
  }>;
4315
+ /**
4316
+ * End `factId`'s validity without a replacement — an archive, not a
4317
+ * deletion (INTENT rule 12, spec specs/expire). Sets `valid_to` only.
4318
+ */
4319
+ expire(entityId: string, factId: string, options?: {
4320
+ at?: number;
4321
+ }): Promise<void>;
4300
4322
  history(entityId: string, factId: string): Promise<WikiFact[]>;
4301
4323
  }
4302
4324
 
@@ -4741,13 +4763,26 @@ declare class WikiMemory {
4741
4763
  /**
4742
4764
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
4743
4765
  * transaction. Throws `WikiSupersedeError` for missing, foreign, already
4744
- * superseded, immutable-document, or cyclic targets.
4766
+ * superseded, already expired, immutable-document, or cyclic targets, and
4767
+ * for an inverted or empty interval (`invalid_interval`).
4745
4768
  */
4746
4769
  supersede(entityId: string, oldId: string, replacement: SupersedeReplacement, options?: {
4747
4770
  validFrom?: number;
4748
4771
  }): Promise<{
4749
4772
  newId: string;
4750
4773
  }>;
4774
+ /**
4775
+ * End `factId`'s validity without a replacement — an archive, not a
4776
+ * deletion (INTENT rule 12). Sets `valid_to` only: `superseded_by`,
4777
+ * `superseded_at` and `deleted_at` stay untouched, and an `asOf` read at
4778
+ * `T` with `COALESCE(valid_from, created_at) <= T < valid_to` still returns
4779
+ * the fact. Throws `WikiSupersedeError` for
4780
+ * a missing, foreign, already superseded, immutable-document, or already
4781
+ * expired target, and for an inverted or empty interval (`invalid_interval`).
4782
+ */
4783
+ expire(entityId: string, factId: string, options?: {
4784
+ at?: number;
4785
+ }): Promise<void>;
4751
4786
  /** The supersession chain containing `factId`, oldest first. [] when unknown. */
4752
4787
  history(entityId: string, factId: string): Promise<WikiFact[]>;
4753
4788
  /**
@@ -1,2 +1,2 @@
1
- export { aW as EmbeddingService, aX as ImportExportService, aY as IngestionService, aZ as JobManager, aZ as JobManagerType, a_ as MaintenanceService, a$ as RetrievalService, b0 as SearchService, b0 as SearchServiceType, aI as WikiMemoryTestAccess, b1 as WriteService } from './testing-DsD-idCv.mjs';
1
+ export { aW as EmbeddingService, aX as ImportExportService, aY as IngestionService, aZ as JobManager, aZ as JobManagerType, a_ as MaintenanceService, a$ as RetrievalService, b0 as SearchService, b0 as SearchServiceType, aI as WikiMemoryTestAccess, b1 as WriteService } from './testing-BVY5P6BS.mjs';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { aW as EmbeddingService, aX as ImportExportService, aY as IngestionService, aZ as JobManager, aZ as JobManagerType, a_ as MaintenanceService, a$ as RetrievalService, b0 as SearchService, b0 as SearchServiceType, aI as WikiMemoryTestAccess, b1 as WriteService } from './testing-DsD-idCv.js';
1
+ export { aW as EmbeddingService, aX as ImportExportService, aY as IngestionService, aZ as JobManager, aZ as JobManagerType, a_ as MaintenanceService, a$ as RetrievalService, b0 as SearchService, b0 as SearchServiceType, aI as WikiMemoryTestAccess, b1 as WriteService } from './testing-BVY5P6BS.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -162,8 +162,8 @@ var WikiInvalidReadOptions = class _WikiInvalidReadOptions extends Error {
162
162
  }
163
163
  };
164
164
  var WikiSupersedeError = class _WikiSupersedeError extends Error {
165
- constructor(reason) {
166
- super(`supersede() rejected: ${reason}`);
165
+ constructor(reason, verb = "supersede()") {
166
+ super(`${verb} rejected: ${reason}`);
167
167
  this.code = "WIKI_SUPERSEDE_REJECTED";
168
168
  this.name = "WikiSupersedeError";
169
169
  this.reason = reason;
@@ -728,6 +728,7 @@ var SEVERITY = {
728
728
  erase_secure_delete_off: "error",
729
729
  erase_entity_skipped: "warn",
730
730
  erase_retired_vtab_undroppable: "warn",
731
+ erase_fts_orphan_cleared: "info",
731
732
  erase_retired_remaining: "error",
732
733
  erase_tombstones_remaining: "error",
733
734
  erase_retired_read_failed: "error",
@@ -770,7 +771,8 @@ var MESSAGE = {
770
771
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
771
772
  prune_checkpoint_incomplete: "The post-VACUUM WAL checkpoint was incomplete while a prune partial failure was also reported; deleted bytes may remain in the WAL.",
772
773
  erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
773
- 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.",
774
+ erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow-table text rows were emptied (fts5 %_config and %_data ids 1 and 10 are intentionally kept) and the name stays listed until an FTS5-capable open drops it.",
775
+ erase_fts_orphan_cleared: "An orphaned FTS5 surface (shadow or companion table, or a queryable vtab) was cleared during erase so forgotten text cannot survive in it.",
774
776
  erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
775
777
  erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
776
778
  erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
@@ -3624,6 +3626,7 @@ var TemporalService = class {
3624
3626
  if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
3625
3627
  if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
3626
3628
  if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3629
+ if (old.valid_to != null && old.valid_to <= Math.max(now, Date.now())) throw new WikiSupersedeError("already_expired");
3627
3630
  if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
3628
3631
  if (newId === oldId) throw new WikiSupersedeError("cycle");
3629
3632
  const repl = await this.entryRepo.findTemporalRow(newId, tx);
@@ -3632,6 +3635,8 @@ var TemporalService = class {
3632
3635
  if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
3633
3636
  const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
3634
3637
  if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
3638
+ const start = old.valid_from ?? old.created_at;
3639
+ if (t <= start) throw new WikiSupersedeError("invalid_interval");
3635
3640
  await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
3636
3641
  if (repl.valid_from == null) {
3637
3642
  await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
@@ -3683,6 +3688,27 @@ var TemporalService = class {
3683
3688
  this.searchService.evictCache(entityId);
3684
3689
  return { newId };
3685
3690
  }
3691
+ /**
3692
+ * End `factId`'s validity without a replacement — an archive, not a
3693
+ * deletion (INTENT rule 12, spec specs/expire). Sets `valid_to` only.
3694
+ */
3695
+ async expire(entityId, factId, options) {
3696
+ const t = options?.at === void 0 ? Date.now() : assertEpochMs("options.at", options.at);
3697
+ await this.db.withTransactionAsync(async (tx) => {
3698
+ const old = await this.entryRepo.findTemporalRow(factId, tx);
3699
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found", "expire()");
3700
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity", "expire()");
3701
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded", "expire()");
3702
+ if (old.valid_to != null) throw new WikiSupersedeError("already_expired", "expire()");
3703
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target", "expire()");
3704
+ const start = old.valid_from ?? old.created_at;
3705
+ if (t <= start) throw new WikiSupersedeError("invalid_interval", "expire()");
3706
+ const changes = await this.entryRepo.setTemporal(factId, entityId, { valid_to: t }, tx);
3707
+ if (changes === 0) throw new WikiSupersedeError("cross_entity", "expire()");
3708
+ });
3709
+ await this.searchService.syncEntries(entityId, [factId]);
3710
+ this.searchService.evictCache(entityId);
3711
+ }
3686
3712
  async history(entityId, factId) {
3687
3713
  const start = await this.entryRepo.findTemporalRow(factId);
3688
3714
  if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
@@ -4105,11 +4131,24 @@ function isRetiredTableName(p, name) {
4105
4131
  var FTS5_REBUILD_WM_KEY = "fts5_rebuild_wm";
4106
4132
  var FTS5_REBUILD_SNAPSHOT_KEY = "fts5_rebuild_snapshot";
4107
4133
  var FTS5_SWEEP_CURSOR_KEY = "fts5_orphan_sweep_cursor";
4134
+ function fts5TriggerNames(prefix) {
4135
+ return [`${prefix}entries_fts_ai`, `${prefix}entries_fts_au`, `${prefix}entries_fts_ad`];
4136
+ }
4108
4137
  function fts5PendingIndexesDdl(p) {
4109
4138
  return `
4110
4139
  CREATE INDEX IF NOT EXISTS ${p}fts_pending_id ON ${p}fts_pending(id);
4111
4140
  CREATE INDEX IF NOT EXISTS ${p}fts_pending_entity ON ${p}fts_pending(entity_id);`;
4112
4141
  }
4142
+ function fts5LedgerDropSql(p) {
4143
+ return [
4144
+ ...fts5TriggerNames(p).map((n) => `DROP TRIGGER IF EXISTS ${n};`),
4145
+ `DROP TABLE IF EXISTS ${p}fts_pending;`,
4146
+ `DROP TABLE IF EXISTS ${p}fts_map;`
4147
+ ].join("\n");
4148
+ }
4149
+ function passageFtsTriggerNames(p) {
4150
+ return [`${p}source_passages_fts_ai`, `${p}source_passages_fts_ad`];
4151
+ }
4113
4152
 
4114
4153
  // src/db/migrations.ts
4115
4154
  var MIGRATIONS = [
@@ -5300,7 +5339,7 @@ var EraseStepError = class extends Error {
5300
5339
  if (cause !== void 0) this.cause = cause;
5301
5340
  }
5302
5341
  };
5303
- var MaintenanceService = class {
5342
+ var _MaintenanceService = class _MaintenanceService {
5304
5343
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
5305
5344
  this.db = db;
5306
5345
  this.prefix = prefix;
@@ -5529,6 +5568,7 @@ var MaintenanceService = class {
5529
5568
  syncedIds: [],
5530
5569
  registrySweep: { skipped: false, deleted: 0 },
5531
5570
  retiredUndroppable: [],
5571
+ ftsOrphansCleared: [],
5532
5572
  failedStep: null,
5533
5573
  runtime: eraseRuntime(),
5534
5574
  steps: []
@@ -5691,7 +5731,110 @@ var MaintenanceService = class {
5691
5731
  this.jobManager.releaseLock("erase", "*");
5692
5732
  }
5693
5733
  }
5694
- // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
5734
+ /**
5735
+ * Step 3 remediation (specs/erase-fts-remediation): on a runtime without
5736
+ * usable strict drains, clear orphaned FTS5 surfaces so erasure can
5737
+ * complete verified. Per surface: existence gate (vtab OR any shadow) →
5738
+ * strategy check → vtab probe → path body → companions → state write.
5739
+ * Dispatch order is D4; exact-name allowlist interpolation is D2.
5740
+ */
5741
+ async _eraseClearFtsOrphans(report) {
5742
+ const surfaces = [`${this.prefix}entries_fts`, `${this.prefix}source_passages_fts`];
5743
+ let remediationRequired = false;
5744
+ const pathBTargets = [];
5745
+ try {
5746
+ for (const surface of surfaces) {
5747
+ const vtabExists = await this.sourceTableExists(surface);
5748
+ const shadows = [];
5749
+ for (const sfx of _MaintenanceService.FTS_SHADOW_SUFFIXES) {
5750
+ const name = `${surface}${sfx}`;
5751
+ if (await this.sourceTableExists(name)) shadows.push(name);
5752
+ }
5753
+ if (!vtabExists && shadows.length === 0) continue;
5754
+ remediationRequired = true;
5755
+ if (this.searchService.isIndexUnavailable()) {
5756
+ report.failedStep = "index_sync";
5757
+ 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);
5758
+ }
5759
+ let moduleLess = false;
5760
+ if (vtabExists) {
5761
+ try {
5762
+ await this.db.getFirstAsync(`SELECT 1 AS x FROM ${surface} LIMIT 1`);
5763
+ } catch (err) {
5764
+ let absent = false;
5765
+ let cur = err;
5766
+ for (let depth = 0; depth < 3 && cur != null && !absent; depth++) {
5767
+ let msg = "";
5768
+ try {
5769
+ msg = String(cur.message ?? cur);
5770
+ } catch {
5771
+ break;
5772
+ }
5773
+ absent = /no such module/i.test(msg);
5774
+ try {
5775
+ cur = cur.cause;
5776
+ } catch {
5777
+ break;
5778
+ }
5779
+ }
5780
+ if (!absent) {
5781
+ report.failedStep = "index_sync";
5782
+ throw new EraseStepError("erase_fts_orphan_probe_failed", `erase stopped at step 3: could not classify orphaned vtab ${surface}`, report, err);
5783
+ }
5784
+ moduleLess = true;
5785
+ }
5786
+ }
5787
+ if (vtabExists && !moduleLess) {
5788
+ if (this.options.config?.indexStrategy !== "minisearch") {
5789
+ report.failedStep = "index_sync";
5790
+ 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);
5791
+ }
5792
+ pathBTargets.push(surface);
5793
+ continue;
5794
+ }
5795
+ const cleared = [];
5796
+ for (const name of shadows) {
5797
+ if (name.endsWith("_config")) continue;
5798
+ const res = await this.db.runAsync(name.endsWith("_data") ? `DELETE FROM ${name} WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}`);
5799
+ if ((res?.changes ?? 0) > 0) cleared.push(name);
5800
+ }
5801
+ for (const name of cleared) {
5802
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
5803
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
5804
+ }
5805
+ }
5806
+ if (!remediationRequired) return;
5807
+ const tailCleared = [];
5808
+ await this.db.withTransactionAsync(async (tx) => {
5809
+ for (const companion of [`${this.prefix}fts_pending`, `${this.prefix}fts_map`, `${this.prefix}source_passages_fts_pending`, `${this.prefix}source_passages_fts_map`]) {
5810
+ if (await this.sourceTableExists(companion, tx)) {
5811
+ const res = await tx.runAsync(`DELETE FROM ${companion}`);
5812
+ if ((res?.changes ?? 0) > 0 && !tailCleared.includes(companion)) tailCleared.push(companion);
5813
+ }
5814
+ }
5815
+ for (const surface of pathBTargets) {
5816
+ await tx.execAsync(`DROP TABLE IF EXISTS ${surface}`);
5817
+ if (!tailCleared.includes(surface)) tailCleared.push(surface);
5818
+ }
5819
+ if (pathBTargets.length > 0) {
5820
+ const [ai, ad] = passageFtsTriggerNames(this.prefix);
5821
+ await tx.execAsync(fts5LedgerDropSql(this.prefix) + `
5822
+ DROP TRIGGER IF EXISTS ${ai};
5823
+ DROP TRIGGER IF EXISTS ${ad};`);
5824
+ }
5825
+ await this.metadataRepo.setMeta(FTS5_STATE_KEY, "detached", tx);
5826
+ });
5827
+ for (const name of tailCleared) {
5828
+ if (!report.ftsOrphansCleared.includes(name)) report.ftsOrphansCleared.push(name);
5829
+ emitDiagnostic(this.options, { code: "erase_fts_orphan_cleared", operation: "erase", trigger: "call", entityId: "", detail: { table: name } });
5830
+ }
5831
+ report.steps.push({ step: "fts_orphan_clear", outcome: "ok" });
5832
+ } catch (err) {
5833
+ if (err instanceof EraseStepError) throw err;
5834
+ report.failedStep = "fts_orphan_clear";
5835
+ throw new EraseStepError("erase_fts_orphan_clear", "erase stopped at step 3: clearing an orphaned FTS surface failed; erasure is unverified", report, err);
5836
+ }
5837
+ }
5695
5838
  /**
5696
5839
  * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
5697
5840
  * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
@@ -5702,6 +5845,7 @@ var MaintenanceService = class {
5702
5845
  */
5703
5846
  async _eraseDrainPassages(report) {
5704
5847
  if (!this.searchService.hasStrictDrain()) {
5848
+ await this._eraseClearFtsOrphans(report);
5705
5849
  for (const [table, failedStep, code] of [
5706
5850
  [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
5707
5851
  [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
@@ -5718,19 +5862,6 @@ var MaintenanceService = class {
5718
5862
  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);
5719
5863
  }
5720
5864
  }
5721
- for (const suffix of ["entries_fts_content", "source_passages_fts_content"]) {
5722
- let orphaned = false;
5723
- try {
5724
- orphaned = await this.sourceTableExists(`${this.prefix}${suffix}`);
5725
- } catch (err) {
5726
- report.failedStep = "index_sync";
5727
- throw new EraseStepError("erase_orphaned_fts_content", `erase stopped: could not probe ${this.prefix}${suffix}`, report, err);
5728
- }
5729
- if (orphaned) {
5730
- report.failedStep = "index_sync";
5731
- throw new EraseStepError("erase_orphaned_fts_content", "erase stopped: orphaned full-text content tables may still hold forgotten text", report);
5732
- }
5733
- }
5734
5865
  }
5735
5866
  try {
5736
5867
  await this.searchService.drainEntriesLedgerSurfaced();
@@ -5766,7 +5897,10 @@ var MaintenanceService = class {
5766
5897
  try {
5767
5898
  for (const name of await this._retiredList()) {
5768
5899
  for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
5769
- if (await this.sourceTableExists(`${name}${sfx}`)) await this.db.runAsync(`DELETE FROM ${name}${sfx}`);
5900
+ if (sfx === "_config") continue;
5901
+ if (await this.sourceTableExists(`${name}${sfx}`)) {
5902
+ await this.db.runAsync(sfx === "_data" ? `DELETE FROM ${name}_data WHERE id NOT IN (1, 10)` : `DELETE FROM ${name}${sfx}`);
5903
+ }
5770
5904
  }
5771
5905
  if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
5772
5906
  emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
@@ -5786,8 +5920,8 @@ var MaintenanceService = class {
5786
5920
  }
5787
5921
  return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
5788
5922
  }
5789
- sourceTableExists(name) {
5790
- return this.metadataRepo.tableExists(name);
5923
+ sourceTableExists(name, tx) {
5924
+ return this.metadataRepo.tableExists(name, tx);
5791
5925
  }
5792
5926
  /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
5793
5927
  async _eraseSyncEntries(entityId, ids, report) {
@@ -6882,6 +7016,9 @@ var MaintenanceService = class {
6882
7016
  return sanitizeRankerError(err, this.options.sanitizeRankerErrors);
6883
7017
  }
6884
7018
  };
7019
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
7020
+ _MaintenanceService.FTS_SHADOW_SUFFIXES = ["_content", "_data", "_idx", "_docsize", "_config"];
7021
+ var MaintenanceService = _MaintenanceService;
6885
7022
 
6886
7023
  // src/readOptions.ts
6887
7024
  function normalizeEntityIds(entityId) {
@@ -8022,6 +8159,10 @@ var _SearchService = class _SearchService {
8022
8159
  this.syncChain = work.then(() => void 0, () => void 0);
8023
8160
  return work;
8024
8161
  }
8162
+ /** True when the active strategy is the transient outage placeholder (erase orphan remediation, D1: never drop under it). */
8163
+ isIndexUnavailable() {
8164
+ return this.indexStrategy instanceof UnavailableIndexStrategy;
8165
+ }
8025
8166
  /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
8026
8167
  hasStrictDrain() {
8027
8168
  const s = this.indexStrategy;