@equationalapplications/core-llm-wiki 8.3.0 → 8.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.
@@ -778,11 +778,11 @@ interface VectorRanker {
778
778
  * Called after a fact's embedding is successfully persisted to embedding_blob (or cleared).
779
779
  * Hosts use this to keep sqlite-vec / external indexes consistent with SQLite as source of truth.
780
780
  *
781
- * On forget and prune, core awaits this hook with `vector: null` after the delete commits, and
782
- * a failure or timeout rejects the call. Cleanup is not yet durable: the loop stops at the
783
- * first failing id, a retry re-sends ids already removed (make deletes idempotent), and a crash
784
- * after commit loses the pending calls. Heal, re-ingest and replace-mode import only report
785
- * failures (`hook_failed`). See the "Deleting data" guide.
781
+ * When a fact is deleted, core records it and calls this hook with `vector: null` until it
782
+ * resolves once for that id, across retries, restarts and crashes. Delivery is at least once:
783
+ * make removal idempotent (a missing id must succeed) and do not resolve without removing.
784
+ * One failing id does not block the others. `forget()` throws `WikiExternalDeletionError` for
785
+ * ids not confirmed; `runPrune()` keeps unconfirmed rows. See the "Deleting data" guide.
786
786
  *
787
787
  * Treat `vector` as readonly — core provides a defensive copy, but adapters MUST NOT mutate.
788
788
  *
@@ -804,9 +804,9 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
804
804
  * Closed for this release series, but new codes are added in minor versions:
805
805
  * hosts must tolerate codes they do not recognize.
806
806
  */
807
- 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' | 'event_created_at_clamped' | 'event_created_at_restamped';
807
+ 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' | 'event_created_at_clamped' | 'event_created_at_restamped' | 'external_deletion_pending' | 'external_deletion_discarded';
808
808
  /** The service run that emitted the diagnostic. */
809
- type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune';
809
+ type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune' | 'externalDeletion';
810
810
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
811
811
  type WikiDiagnosticTrigger = 'call' | 'auto';
812
812
  /** Identifiers only — never titles, bodies, quotes, LLM output, provider messages, or hashes of content. */
@@ -845,12 +845,17 @@ interface WikiDiagnosticDetail {
845
845
  packed?: number;
846
846
  /** read_budget only. */
847
847
  tokensUsed?: number;
848
+ /** external_deletion_pending only: epoch milliseconds (second resolution) of the oldest pending row. */
849
+ oldestEnqueuedAt?: number;
850
+ /** external_deletion_pending only: highest attempt count among pending rows. */
851
+ maxAttempts?: number;
848
852
  }
849
853
  interface WikiDiagnostic {
850
854
  code: WikiDiagnosticCode;
851
855
  severity: WikiDiagnosticSeverity;
852
856
  operation: WikiDiagnosticOperation;
853
857
  trigger: WikiDiagnosticTrigger;
858
+ /** Entity the diagnostic concerns; `''` means store-wide (e.g. the setup removal drain's `background_job_failed`). */
854
859
  entityId: string;
855
860
  /** Epoch ms, sampled at emission. */
856
861
  at: number;
@@ -920,9 +925,26 @@ interface WikiOptions {
920
925
  * Escape hatch: skip onEmbeddingPersisted on deletion paths entirely.
921
926
  * Use ONLY when the ANN backend is permanently decommissioned. Vectors
922
927
  * orphaned in the (unreachable) external index are accepted as a tradeoff.
923
- * NOT GDPR-safe for live indexes. Default false.
928
+ * Means the index is decommissioned: no removal call is made on any path
929
+ * (forget, prune, heal, ingest, import), and owed removals are discarded
930
+ * (`external_deletion_discarded`). NOT GDPR-safe for live indexes. Default false.
924
931
  */
925
932
  forceDeleteIgnoreRankerHook?: boolean;
933
+ /**
934
+ * Opt in to a background drain of owed removals after `setup()`: when a
935
+ * removal hook is configured and removals are owed, `setup()` starts one
936
+ * drain (not awaited; `drain()` joins it, 10 s deadline, backoff).
937
+ *
938
+ * Default false. The drain opens short transactions on the connection you
939
+ * gave `createWiki`; a transaction you open on that connection yourself (for
940
+ * example `db.withTransactionAsync(tx => wiki.upsertGraph(…, tx))`) throws
941
+ * "cannot start a transaction within a transaction" while one of them is
942
+ * open. Turn it on only if you never open your own transactions on it.
943
+ * When off, `setup()` emits `external_deletion_pending` per entity with
944
+ * owed removals. `runPendingMaintenance()` and `runExternalDeletions()`
945
+ * deliver them; `forget()` and `runPrune()` deliver the ids they touch.
946
+ */
947
+ drainExternalDeletionsOnSetup?: boolean;
926
948
  /**
927
949
  * Receives typed, content-free diagnostics for events core previously
928
950
  * dropped silently or only logged (spec §4). Synchronous; a returned promise
@@ -1007,6 +1029,26 @@ declare class WikiBusyError extends Error {
1007
1029
  readonly entityId: string;
1008
1030
  constructor(operation: WikiBusyOperation, entityId: string);
1009
1031
  }
1032
+ /**
1033
+ * Thrown by forget() when the external vector index has not confirmed the
1034
+ * removal of every selected id. The local delete stays committed and the
1035
+ * unconfirmed ids stay owed in the ledger.
1036
+ */
1037
+ declare class WikiExternalDeletionError extends Error {
1038
+ readonly code: "WIKI_EXTERNAL_DELETION";
1039
+ readonly entityId: string;
1040
+ /** At most 100 ids; see unconfirmedCount for the full count. */
1041
+ readonly unconfirmedIds: string[];
1042
+ readonly unconfirmedCount: number;
1043
+ readonly timedOut: boolean;
1044
+ constructor(message: string, params: {
1045
+ entityId: string;
1046
+ unconfirmedIds: string[];
1047
+ unconfirmedCount: number;
1048
+ timedOut: boolean;
1049
+ cause?: Error;
1050
+ });
1051
+ }
1010
1052
  /**
1011
1053
  * Thrown by `ingestDocument({ onDuplicateHash: 'throw' })` when a different
1012
1054
  * source_ref in the same entity already holds the supplied source_hash against
@@ -1123,6 +1165,13 @@ interface ForgetResult {
1123
1165
  };
1124
1166
  metadataReset?: boolean;
1125
1167
  }
1168
+ /**
1169
+ * Thrown by `runPrune()` after it has finished its other work, when the host's
1170
+ * removal hook did not confirm some prunable facts. Those rows are kept, every
1171
+ * other prunable row is hard-deleted. The deleted and kept rows are not
1172
+ * contiguous: `deleted` counts rows hard-deleted, `remaining` counts rows kept,
1173
+ * and `failedAt` names the first unconfirmed id in drain order.
1174
+ */
1126
1175
  declare class PrunePartialFailureError extends Error {
1127
1176
  readonly deleted: number;
1128
1177
  readonly failedAt: string;
@@ -1313,7 +1362,9 @@ interface WikiInstructions {
1313
1362
  heal: string;
1314
1363
  ontologyBackfill: string;
1315
1364
  }
1316
- type MaintenanceJob = 'librarian' | 'heal' | 'reembed';
1365
+ type MaintenanceJob = 'librarian' | 'heal' | 'reembed' | 'externalDeletions';
1366
+ /** The jobs that hold a per-entity lock (everything but `externalDeletions`). */
1367
+ type LockedMaintenanceJob = Exclude<MaintenanceJob, 'externalDeletions'>;
1317
1368
  interface PendingMaintenance {
1318
1369
  entityId: string;
1319
1370
  /** Events after the librarian watermark. */
@@ -1328,6 +1379,8 @@ interface PendingMaintenance {
1328
1379
  * Always false without `embed`.
1329
1380
  */
1330
1381
  reembedPending: boolean;
1382
+ /** Removals still owed to the host's vector index for this entity (absent when none). */
1383
+ pendingExternalDeletions?: number;
1331
1384
  }
1332
1385
  interface RunPendingMaintenanceOptions {
1333
1386
  /** Default: every entity with pending work. */
@@ -1336,7 +1389,7 @@ interface RunPendingMaintenanceOptions {
1336
1389
  tokenBudget?: number;
1337
1390
  /** Wall-clock milliseconds from the call. Checked between units; a unit in flight is never interrupted. */
1338
1391
  deadlineMs?: number;
1339
- /** Default all three. */
1392
+ /** Default all four. `externalDeletions` runs first and is not metered by `tokenBudget`. */
1340
1393
  jobs?: MaintenanceJob[];
1341
1394
  }
1342
1395
  type MaintenanceStopReason = {
@@ -1358,13 +1411,13 @@ interface EntityMaintenanceReport {
1358
1411
  healPasses: number;
1359
1412
  reembedded: boolean;
1360
1413
  /** Set when a lock was held elsewhere; nothing ran for that job. */
1361
- busy?: MaintenanceJob[];
1414
+ busy?: LockedMaintenanceJob[];
1362
1415
  /**
1363
1416
  * Set when keyword search is unavailable and the job could not run for this
1364
1417
  * entity (spec #280). Its watermark/checkpoint is kept; retry after
1365
1418
  * `syncSearchIndex()` restores keyword search.
1366
1419
  */
1367
- searchUnavailable?: MaintenanceJob[];
1420
+ searchUnavailable?: LockedMaintenanceJob[];
1368
1421
  }
1369
1422
  interface RunPendingMaintenanceResult {
1370
1423
  perEntity: EntityMaintenanceReport[];
@@ -1374,6 +1427,11 @@ interface RunPendingMaintenanceResult {
1374
1427
  /** null when no tokenBudget was given. */
1375
1428
  remaining: number | null;
1376
1429
  stoppedReason: MaintenanceStopReason;
1430
+ /** Vector-index removals this run confirmed, and those still owed (all entities in scope). */
1431
+ externalDeletions: {
1432
+ confirmed: number;
1433
+ pending: number;
1434
+ };
1377
1435
  }
1378
1436
  type MigrationPolicy = 'allow' | 'refuse' | 'auto';
1379
1437
  /** Work the migration gate found pending on an existing store. Watermarks are resume rowids (0 = not started). */
@@ -1687,7 +1745,10 @@ declare class EntryRepository extends BaseRepository {
1687
1745
  * Used by runPrune(). Returns total number of deleted rows.
1688
1746
  * `tx` is REQUIRED so outbox deletion events are staged atomically.
1689
1747
  */
1690
- bulkDeletePruned(entityId: string, cutoff: number, ids: string[], tx: SQLiteAdapter): Promise<number>;
1748
+ bulkDeletePruned(entityId: string, cutoff: number, ids: string[], tx: SQLiteAdapter, opts?: {
1749
+ keepUnconfirmedRemovals?: boolean;
1750
+ deletedIds?: string[];
1751
+ }): Promise<number>;
1691
1752
  /**
1692
1753
  * Mark orphaned entries (never accessed, old) as deleted.
1693
1754
  * Used by MaintenanceService.doRunHeal().
@@ -1755,7 +1816,10 @@ declare class EntryRepository extends BaseRepository {
1755
1816
  body: string;
1756
1817
  tags: string;
1757
1818
  }>>;
1758
- updateEmbeddingBlob(id: string, blob: Uint8Array, tx?: SQLiteAdapter): Promise<void>;
1819
+ /** Returns `changes: 0` when the row is soft-deleted or gone (spec durable-vector-removal §5.7, G10). */
1820
+ updateEmbeddingBlob(id: string, blob: Uint8Array, tx?: SQLiteAdapter): Promise<{
1821
+ changes: number;
1822
+ }>;
1759
1823
  /**
1760
1824
  * Record a failed embedding attempt. Deliberately does NOT touch updated_at
1761
1825
  * (import merge is last-write-wins on it) and pushes no outbox event —
@@ -2102,7 +2166,7 @@ interface IndexSearchResult {
2102
2166
  entity_id: string;
2103
2167
  }
2104
2168
  /** One drain turn's shape (spec #280 Change 3 "drain interface"). */
2105
- interface DrainOptions {
2169
+ interface DrainOptions$1 {
2106
2170
  /** `monotonicNow()` timestamp, checked between chunk transactions. Full mode only; default now + the strategy's budget. */
2107
2171
  deadline?: number;
2108
2172
  /**
@@ -2199,7 +2263,7 @@ interface IndexStrategy {
2199
2263
  * called from inside a `withTransactionAsync` callback; it opens its own
2200
2264
  * transactions.
2201
2265
  */
2202
- drain?(opts?: DrainOptions): Promise<void>;
2266
+ drain?(opts?: DrainOptions$1): Promise<void>;
2203
2267
  }
2204
2268
 
2205
2269
  interface ScoredRow {
@@ -2592,7 +2656,135 @@ declare class EdgeRepository extends BaseRepository {
2592
2656
  }>;
2593
2657
  }
2594
2658
 
2595
- type EmbedFailureKind = EmbeddingMarkerKind | 'no_provider' | 'storage_error';
2659
+ interface LedgerRow {
2660
+ seq: number;
2661
+ entity_id: string;
2662
+ fact_id: string;
2663
+ attempts: number;
2664
+ last_attempt_at: number | null;
2665
+ fact_state: 'live' | 'deleted' | 'gone';
2666
+ }
2667
+ interface VectorRemovalScope {
2668
+ entityId?: string;
2669
+ ids?: string[];
2670
+ }
2671
+ interface VectorRemovalCursor {
2672
+ maxSeq: number;
2673
+ attempts: number;
2674
+ seq: number;
2675
+ }
2676
+ /**
2677
+ * Ledger of facts whose vectors the host's external index still owes a
2678
+ * removal for (spec durable-vector-removal §5.1). Rows are enqueued by
2679
+ * triggers on `entries`; this class reads and settles them.
2680
+ */
2681
+ declare class VectorRemovalRepository extends BaseRepository {
2682
+ /** Name of the ledger table. */
2683
+ get ledgerTable(): string;
2684
+ /** Whether `factId` exists and is not soft-deleted. */
2685
+ isLive(factId: string): Promise<boolean>;
2686
+ /**
2687
+ * Owe the host a removal for `factId` unless a live row exists (a missing row
2688
+ * counts as not live). The liveness test is part of the write, so it is
2689
+ * atomic. Returns whether a row was enqueued.
2690
+ */
2691
+ enqueueIfNotLive(entityId: string, factId: string, now: number): Promise<boolean>;
2692
+ /** Unconfirmed rows after `cursor`, ordered by (attempts, seq). */
2693
+ readPage(scope: VectorRemovalScope, cursor: VectorRemovalCursor, limit: number, tx: SQLiteAdapter): Promise<LedgerRow[]>;
2694
+ maxSeq(tx?: SQLiteAdapter): Promise<number>;
2695
+ /** Returns the number of rows changed. */
2696
+ confirm(seqs: number[], now: number, tx: SQLiteAdapter): Promise<number>;
2697
+ bumpAttempts(seqs: number[], now: number, tx: SQLiteAdapter): Promise<void>;
2698
+ /** Delete the given rows when they are confirmed and their fact row is gone. */
2699
+ deleteConfirmedGone(seqs: number[], tx: SQLiteAdapter): Promise<void>;
2700
+ /** For stale, gone or resurrected rows. Applies to the given seqs only. */
2701
+ deleteBySeq(seqs: number[], tx: SQLiteAdapter): Promise<number>;
2702
+ /** Unconfirmed rows of `entityId` among `ids`. */
2703
+ pendingCountForIds(entityId: string, ids: string[]): Promise<number>;
2704
+ /** Enqueue ids that have no row yet. Returns the number inserted. */
2705
+ backstopEnqueue(entityId: string, ids: string[], now: number, tx: SQLiteAdapter): Promise<number>;
2706
+ /**
2707
+ * Remove rows together with a hard delete of the facts. `'all'` drops every
2708
+ * row of those ids; `'confirmedGone'` drops only confirmed rows whose fact
2709
+ * row no longer exists, so a removal re-owed meanwhile is never erased.
2710
+ */
2711
+ deleteForFacts(entityId: string, ids: string[], tx: SQLiteAdapter, mode?: 'all' | 'confirmedGone'): Promise<void>;
2712
+ /** Drop unconfirmed rows. Returns the count removed. */
2713
+ discardPending(entityId?: string, tx?: SQLiteAdapter): Promise<number>;
2714
+ pendingStats(entityId?: string): Promise<{
2715
+ count: number;
2716
+ oldestEnqueuedAt: number | null;
2717
+ maxAttempts: number;
2718
+ }>;
2719
+ entitiesWithPending(): Promise<string[]>;
2720
+ /**
2721
+ * Entities with at least one pending row outside backoff (never attempted,
2722
+ * or last attempted longer ago than removalBackoffMs). Same rule as the drain.
2723
+ */
2724
+ entitiesWithDuePending(now: number): Promise<string[]>;
2725
+ statusFor(ids: string[], tx?: SQLiteAdapter): Promise<Map<string, 'pending' | 'confirmed'>>;
2726
+ }
2727
+
2728
+ type DrainScope = {
2729
+ entityId: string;
2730
+ ids?: string[];
2731
+ } | {
2732
+ all: true;
2733
+ };
2734
+ interface DrainResult {
2735
+ confirmed: number;
2736
+ pending: number;
2737
+ failedIds: string[];
2738
+ timedOut: boolean;
2739
+ /** Fact id of the call that timed out, when known. */
2740
+ timedOutId?: string;
2741
+ /** True when a page read or a settling write failed; rows stay pending. */
2742
+ transient?: boolean;
2743
+ firstCause?: Error;
2744
+ }
2745
+ interface DrainOptions {
2746
+ /** Absolute `Date.now()` time after which no further calls are made. */
2747
+ deadlineAt?: number;
2748
+ backoff?: boolean;
2749
+ trigger?: WikiDiagnosticTrigger;
2750
+ }
2751
+ /** Drains the vector_removals ledger through the host's removal hook (spec §5.3-5.4). */
2752
+ declare class VectorRemovalService {
2753
+ private db;
2754
+ private options;
2755
+ private repo;
2756
+ private embeddingService;
2757
+ private metadataRepo;
2758
+ private inFlight;
2759
+ constructor(db: SQLiteAdapter, options: WikiOptions, repo: VectorRemovalRepository, embeddingService: EmbeddingService, metadataRepo: MetadataRepository);
2760
+ gate(): 'hook' | 'none' | 'force';
2761
+ private ledgerSeen;
2762
+ ledgerPresent(): Promise<boolean>;
2763
+ /** One `hook_failed` diagnostic per id (the removal stays owed). */
2764
+ emitHookFailed(entityId: string, ids: string[], operation: WikiDiagnosticOperation, trigger: WikiDiagnosticTrigger): void;
2765
+ /**
2766
+ * Post-commit delivery for heal, ingest and import (spec §5.7). Never throws:
2767
+ * a failed id emits `hook_failed` and stays owed on the ledger. Without a
2768
+ * ledger table (setup never ran) it falls back to a best-effort call per id.
2769
+ * Under `forceDeleteIgnoreRankerHook` no removal call is made.
2770
+ */
2771
+ deliverRemovals(entityId: string, ids: string[], operation: WikiDiagnosticOperation, trigger: WikiDiagnosticTrigger, fallbackIds?: string[]): Promise<void>;
2772
+ markExternalIndexInUse(tx: SQLiteAdapter): Promise<void>;
2773
+ clearExternalIndexMarker(): Promise<void>;
2774
+ externalIndexInUse(): Promise<boolean>;
2775
+ drain(scope: DrainScope, opts?: DrainOptions): Promise<DrainResult>;
2776
+ /**
2777
+ * Makes the removal call for `row`, or joins another drain's call for the
2778
+ * same seq. Never throws: the outcome says whether it succeeded, whether
2779
+ * this drain joined (only the owner bumps attempts on failure), and whether
2780
+ * the failure was a timeout.
2781
+ */
2782
+ private callFor;
2783
+ private pendingFor;
2784
+ emitPending(entityId: string | undefined, trigger: WikiDiagnosticTrigger): Promise<void>;
2785
+ }
2786
+
2787
+ type EmbedFailureKind = EmbeddingMarkerKind | 'no_provider' | 'storage_error' | 'fact_deleted';
2596
2788
  type EmbedFactResult = {
2597
2789
  ok: true;
2598
2790
  dimension: number;
@@ -2674,13 +2866,21 @@ declare class EmbeddingService {
2674
2866
  }>;
2675
2867
  /**
2676
2868
  * Storage half: persist the computed vector to the entry row, then fire the
2677
- * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` only — embed
2678
- * failures do not originate here, so they cannot be marked as such (spec §3.2, D3).
2869
+ * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` (a DB error) and
2870
+ * `fact_deleted` (the row was soft-deleted or gone: no blob, no vector call, no
2871
+ * marker). Embed failures do not originate here, so they cannot be marked as
2872
+ * such (spec §3.2, D3).
2679
2873
  */
2680
2874
  storeFactVector(fact: {
2681
2875
  id: string;
2682
2876
  entity_id: string;
2683
2877
  }, float32Vector: Float32Array, ctx?: EmbedDiagnosticContext): Promise<EmbedFactResult>;
2878
+ hasVectorHook(): boolean;
2879
+ /**
2880
+ * Run after a vector call (resolved or not) by every path that sends one.
2881
+ * Never throws: a failure here leaves the removal owed or unrecorded, as before.
2882
+ */
2883
+ settleAfterVectorCall(entityId: string, factId: string, operation: WikiDiagnosticOperation, trigger: WikiDiagnosticTrigger): Promise<void>;
2684
2884
  private reportEmbed;
2685
2885
  /** For callers that invoke `notifyEmbeddingPersisted` directly and catch its failure. */
2686
2886
  reportHookFailed(ctx: EmbedDiagnosticContext, entityId: string, factId: string): void;
@@ -2698,7 +2898,43 @@ declare class EmbeddingService {
2698
2898
  body: string;
2699
2899
  tags: string | string[];
2700
2900
  }, ctx?: EmbedDiagnosticContext): Promise<boolean>;
2901
+ private vectorRemoval?;
2902
+ /** Wired by WikiMemory (VectorRemovalService itself depends on this class). */
2903
+ attachVectorRemoval(service: VectorRemovalService, repo: VectorRemovalRepository): void;
2904
+ /**
2905
+ * After an embed (and its vector call) settles: owe a removal if the fact is
2906
+ * no longer live, so a vector the host just received is taken back (§5.7, G10).
2907
+ * Never throws. `'enqueued'`: a ledger row was written. `'none'`: no
2908
+ * removal hook (or the hook gate is off). `'live'`: the fact is live. A row already pending is
2909
+ * replaced (attempts reset, spec §5.2), so it counts as `'enqueued'` and
2910
+ * is sent now: the last call the host sees after this vector is `null`.
2911
+ * `'owed'`: the write failed but a pending row already holds the removal.
2912
+ * `'write_failed'`: the fact is known not live, the write failed, and its
2913
+ * row is confirmed or missing; or the store has no ledger table and the
2914
+ * fact is known not live.
2915
+ * `'unknown'`: the liveness read and the guarded write both failed.
2916
+ */
2917
+ private recordAfterVectorCall;
2701
2918
  notifyEmbeddingPersisted(entityId: string, factId: string, vector: Float32Array | null): Promise<void>;
2919
+ validateDeletionTimeout(): number;
2920
+ /** Send a removal (`vector: null`) to the hook. No gate check; the caller owns the gate. */
2921
+ callRemovalHook(entityId: string, factId: string, timeoutMs: number): Promise<void>;
2922
+ /**
2923
+ * One removal call per id for a store with no ledger table (setup() never
2924
+ * ran), so nothing records what is owed (spec §5.5.5). Stops at the first
2925
+ * timeout: a dead index costs one timeout, as in a drain (spec rev 5).
2926
+ * `failed` lists the ids not confirmed, in order; after a timeout it ends
2927
+ * with the timed-out id and every id after it. Throws only for an invalid
2928
+ * `deletionHookTimeoutMs`.
2929
+ */
2930
+ callRemovalHookEach(entityId: string, ids: readonly string[], opts?: {
2931
+ warn?: boolean;
2932
+ }): Promise<{
2933
+ failed: string[];
2934
+ timedOut: boolean;
2935
+ timedOutId?: string;
2936
+ cause?: unknown;
2937
+ }>;
2702
2938
  notifyEmbeddingPersistedOrThrow(entityId: string, factId: string, vector: Float32Array | null): Promise<void>;
2703
2939
  }
2704
2940
 
@@ -2871,8 +3107,9 @@ declare class IngestionService {
2871
3107
  private jobManager;
2872
3108
  private embeddingService;
2873
3109
  private ontologyService?;
3110
+ private vectorRemoval?;
2874
3111
  private promptService;
2875
- constructor(db: SQLiteAdapter, prefix: string, options: WikiOptions, entryRepo: EntryRepository, sourceRefIndexRepo: SourceRefIndexRepository, metadataRepo: MetadataRepository, edgeRepo: EdgeRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, promptService?: PromptService, ontologyService?: OntologyService | undefined);
3112
+ constructor(db: SQLiteAdapter, prefix: string, options: WikiOptions, entryRepo: EntryRepository, sourceRefIndexRepo: SourceRefIndexRepository, metadataRepo: MetadataRepository, edgeRepo: EdgeRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, promptService?: PromptService, ontologyService?: OntologyService | undefined, vectorRemoval?: VectorRemovalService | undefined);
2876
3113
  ingestDocument(entityId: string, params: {
2877
3114
  sourceRef: string;
2878
3115
  sourceHash: string;
@@ -3256,8 +3493,10 @@ declare class MaintenanceService {
3256
3493
  private jobManager;
3257
3494
  private embeddingService;
3258
3495
  private ontologyService?;
3496
+ private vectorRemoval?;
3497
+ private vectorRemovalRepo?;
3259
3498
  private promptService;
3260
- constructor(db: SQLiteAdapter, prefix: string, options: WikiOptions, entryRepo: EntryRepository, sourceRefIndexRepo: SourceRefIndexRepository, taskRepo: TaskRepository, eventRepo: EventRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, promptService?: PromptService, ontologyService?: OntologyService | undefined, edgeRepo?: EdgeRepository);
3499
+ constructor(db: SQLiteAdapter, prefix: string, options: WikiOptions, entryRepo: EntryRepository, sourceRefIndexRepo: SourceRefIndexRepository, taskRepo: TaskRepository, eventRepo: EventRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, promptService?: PromptService, ontologyService?: OntologyService | undefined, edgeRepo?: EdgeRepository, vectorRemoval?: VectorRemovalService | undefined, vectorRemovalRepo?: VectorRemovalRepository | undefined);
3261
3500
  private edgeRepo;
3262
3501
  runPrune(entityId: string, options?: {
3263
3502
  retainSoftDeletedFor?: number | null;
@@ -3310,6 +3549,8 @@ declare class MaintenanceService {
3310
3549
  forget(entityId: string, params: ForgetParams, opts?: {
3311
3550
  dryRun?: boolean;
3312
3551
  }): Promise<ForgetResult>;
3552
+ /** Heal's post-commit removal delivery (spec §5.7). Never throws. */
3553
+ private deliverHealRemovals;
3313
3554
  /**
3314
3555
  * Whether forget() should soft-delete in source_ref_index (#316,
3315
3556
  * specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
@@ -3471,7 +3712,9 @@ declare class MaintenanceScheduler {
3471
3712
  private eventRepo;
3472
3713
  private entryRepo;
3473
3714
  private jobManager;
3474
- constructor(db: SQLiteAdapter, options: WikiOptions, maintenanceService: MaintenanceService, metadataRepo: MetadataRepository, eventRepo: EventRepository, entryRepo: EntryRepository, jobManager: JobManager);
3715
+ private vectorRemovalService;
3716
+ private vectorRemovalRepo;
3717
+ constructor(db: SQLiteAdapter, options: WikiOptions, maintenanceService: MaintenanceService, metadataRepo: MetadataRepository, eventRepo: EventRepository, entryRepo: EntryRepository, jobManager: JobManager, vectorRemovalService: VectorRemovalService, vectorRemovalRepo: VectorRemovalRepository);
3475
3718
  /**
3476
3719
  * Entities with **any** pending work only, sorted by `pendingEvents` desc
3477
3720
  * then `entityId` asc. Token estimate is ceil(pending summary chars / 4),
@@ -3493,6 +3736,12 @@ declare class MaintenanceScheduler {
3493
3736
  * only; embeddings are never metered.
3494
3737
  */
3495
3738
  run(opts?: RunPendingMaintenanceOptions): Promise<RunPendingMaintenanceResult>;
3739
+ /**
3740
+ * Runs first and outside the token budget: delivers owed vector-index
3741
+ * removals per entity (wiped entities included), without backoff. Pending is
3742
+ * reported even when the job is not listed or no hook is configured.
3743
+ */
3744
+ private runExternalDeletions;
3496
3745
  }
3497
3746
 
3498
3747
  declare class ImportExportService {
@@ -3506,7 +3755,8 @@ declare class ImportExportService {
3506
3755
  private jobManager;
3507
3756
  private embeddingService;
3508
3757
  private options;
3509
- constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, options?: Pick<WikiOptions, 'onDiagnostic'>);
3758
+ private vectorRemoval?;
3759
+ constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, options?: Pick<WikiOptions, 'onDiagnostic' | 'forceDeleteIgnoreRankerHook'>, vectorRemoval?: VectorRemovalService | undefined);
3510
3760
  exportDump(entityIds?: string[]): Promise<MemoryDump>;
3511
3761
  importDump(dump: MemoryDump, opts?: {
3512
3762
  merge?: boolean;
@@ -3662,6 +3912,8 @@ declare class WikiMemory {
3662
3912
  private edgeRepo;
3663
3913
  private metadataRepo;
3664
3914
  private embeddingService;
3915
+ private vectorRemovalRepo;
3916
+ private vectorRemovalService;
3665
3917
  private searchService;
3666
3918
  private jobManager;
3667
3919
  private ingestionService;
@@ -3684,7 +3936,7 @@ declare class WikiMemory {
3684
3936
  * If `NODE_ENV` is not `"test"`, emits a single `console.warn` per instance (skipped when `process` is undefined).
3685
3937
  */
3686
3938
  get __testAccess(): WikiMemoryTestAccess;
3687
- /** Max upsertGraph node ids held for their post-commit sync (spec #280 id threading). */
3939
+ /** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */
3688
3940
  static readonly UPSERT_ID_STASH_CAP = 10000;
3689
3941
  /**
3690
3942
  * upsertGraph node and superseded-fact ids per entity, awaiting syncSearchIndex(), each with the
@@ -3697,6 +3949,19 @@ declare class WikiMemory {
3697
3949
  /** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */
3698
3950
  private upsertIdStashGen;
3699
3951
  private stashUpsertIds;
3952
+ /** Max superseded-fact ids held for post-commit removal delivery. */
3953
+ static readonly REMOVAL_STASH_CAP = 10000;
3954
+ /** Superseded fact ids per entity awaiting a post-commit delivery from syncSearchIndex(). */
3955
+ private removalStash;
3956
+ private removalStashSize;
3957
+ /**
3958
+ * Overflow past the cap drops the id from the stash only: the trigger already
3959
+ * put it on the ledger, so it stays owed and runExternalDeletions or
3960
+ * runPendingMaintenance delivers it later.
3961
+ */
3962
+ private stashRemovalIds;
3963
+ /** Removes and returns the stashed removal ids (one entity, or all). */
3964
+ private takeRemovalIds;
3700
3965
  /** Snapshot of the stash (one entity, or all) with generations, without removing anything. */
3701
3966
  private peekStashedIds;
3702
3967
  /**
@@ -3730,6 +3995,30 @@ declare class WikiMemory {
3730
3995
  setup(opts?: {
3731
3996
  migrations?: MigrationPolicy;
3732
3997
  }): Promise<void>;
3998
+ private setupRemovalDrain;
3999
+ /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
4000
+ private startSetupRemovalDrain;
4001
+ /**
4002
+ * Delivers owed vector-index removals now (spec §5.9). No backoff. With an
4003
+ * entity id only that entity's rows; otherwise all. `deadlineMs` is a duration.
4004
+ * `transient: true` means a ledger read or write could not run (for example,
4005
+ * you held a transaction open on the connection); the rows stay pending.
4006
+ */
4007
+ runExternalDeletions(entityId?: string, opts?: {
4008
+ deadlineMs?: number;
4009
+ }): Promise<{
4010
+ confirmed: number;
4011
+ pending: number;
4012
+ failedIds: string[];
4013
+ timedOut: boolean;
4014
+ transient?: boolean;
4015
+ }>;
4016
+ /** Removals still owed to the host's vector index (all entities, or one). */
4017
+ getPendingExternalDeletions(entityId?: string): Promise<{
4018
+ count: number;
4019
+ oldestEnqueuedAt: number | null;
4020
+ maxAttempts: number;
4021
+ }>;
3733
4022
  hasChanged(entityId: string, sourceRef: string, sourceHash: string): Promise<boolean>;
3734
4023
  /**
3735
4024
  * Batched overload.
@@ -3837,7 +4126,7 @@ declare class WikiMemory {
3837
4126
  traverseGraph(entityId: string, options: GraphTraversalOptions): Promise<GraphNeighborhood>;
3838
4127
  getMemoryBundle(entityId: string): Promise<MemoryBundle>;
3839
4128
  write(entityId: string, event: Omit<WikiEvent, 'id' | 'entity_id' | 'created_at'>): Promise<void>;
3840
- /** Await auto-mode background librarian/heal jobs started by write(). No-op in 'deferred' mode. */
4129
+ /** Await auto-mode background librarian/heal jobs started by write(), and the removal drain `setup()` started under `drainExternalDeletionsOnSetup`. */
3841
4130
  drain(): Promise<void>;
3842
4131
  /**
3843
4132
  * Report which entities have pending maintenance work (librarian events
@@ -3846,7 +4135,7 @@ declare class WikiMemory {
3846
4135
  * `pendingEvents` desc then `entityId` asc.
3847
4136
  */
3848
4137
  getPendingMaintenance(entityIds?: string[]): Promise<PendingMaintenance[]>;
3849
- /** Run pending librarian/heal/reembed work under an optional token budget and deadline (spec §6.2). Nothing runs after it resolves. */
4138
+ /** Run pending removals, librarian, heal and reembed work under an optional token budget and deadline (spec §6.2). Awaits the setup removal drain first, when `drainExternalDeletionsOnSetup` started one. */
3850
4139
  runPendingMaintenance(options?: RunPendingMaintenanceOptions): Promise<RunPendingMaintenanceResult>;
3851
4140
  /**
3852
4141
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
@@ -3925,6 +4214,11 @@ declare class WikiMemory {
3925
4214
  * waits at least 5 s, doubling per consecutive failure up to 5 min (longer
3926
4215
  * when an attempt is itself slow), before retrying again.
3927
4216
  *
4217
+ * It also calls the host's removal hook (`onEmbeddingPersisted(…, null)`) for
4218
+ * the stashed ids that `upsertGraph` superseded, and can take up to
4219
+ * `deletionHookTimeoutMs` per id when the host's index is slow. It never
4220
+ * drains an entity's wider removal backlog.
4221
+ *
3928
4222
  * Call only after the host's transaction commits: called inside it, the
3929
4223
  * rebuild may index rows that later roll back, or miss them and clear the
3930
4224
  * stale flag anyway. Serialized with core's internal index syncs and takes
@@ -3940,6 +4234,7 @@ declare class WikiMemory {
3940
4234
  * @throws {TypeError} when `entityId` is given but is not a non-empty string.
3941
4235
  */
3942
4236
  syncSearchIndex(entityId?: string): Promise<void>;
4237
+ private syncSearchIndexCore;
3943
4238
  /**
3944
4239
  * True when a sync applied the stashed ids. While keyword search is
3945
4240
  * unavailable the stand-in strategy's drain is a no-op that reports success,
@@ -3961,6 +4256,14 @@ declare class WikiMemory {
3961
4256
  * hard-deletes the soft-deleted rows once they are older than
3962
4257
  * `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).
3963
4258
  * `dryRun` previews the counts.
4259
+ *
4260
+ * With a removal hook (`vectorRanker.onEmbeddingPersisted`), the deleted
4261
+ * facts are recorded as owed in the same transaction and then delivered to
4262
+ * the hook before this resolves.
4263
+ *
4264
+ * @throws {WikiExternalDeletionError} when the hook didn't confirm every
4265
+ * removal. The local delete stays committed and the rest stay owed; retry,
4266
+ * or call `runExternalDeletions()`.
3964
4267
  */
3965
4268
  forget(entityId: string, params: ForgetParams, opts?: {
3966
4269
  dryRun?: boolean;
@@ -4019,12 +4322,15 @@ declare class WikiMemory {
4019
4322
  * semantics identical to `ingestDocument`, minus the LLM extraction step.
4020
4323
  *
4021
4324
  * MUST be called from inside an open `db.withTransactionAsync` callback —
4022
- * the third argument is the caller's `tx`. The method does not open a
4325
+ * the third argument is the caller's `tx`, and that transaction must be
4326
+ * opened through the adapter given to `createWiki` (the removal ledger is
4327
+ * filled by triggers inside it, and a rollback discards the rows). The method does not open a
4023
4328
  * nested transaction, does not acquire any lock, and does not perform
4024
4329
  * post-commit work (search sync, embedding, cache eviction). After the
4025
4330
  * transaction commits, call `syncSearchIndex(entityId)` — or
4026
4331
  * `syncSearchIndex()` after writing several entities in one transaction —
4027
- * to make the new nodes keyword-searchable: both forms drain this call's node ids
4332
+ * to make the new nodes keyword-searchable and to deliver, through the
4333
+ * host's removal hook, the vectors of any facts the call superseded: both forms drain this call's node ids
4028
4334
  * first, to completion, so the nodes are searchable under any backlog (up to
4029
4335
  * `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with
4030
4336
  * the backlog). Embeddings still come from the maintenance
@@ -4188,5 +4494,5 @@ declare class WikiMemory {
4188
4494
  setGeneratedByTask(taskId: string, entityId: string, actor: string): Promise<void>;
4189
4495
  }
4190
4496
 
4191
- export { HEAL_BATCH_SIZE as H, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS as J, ONTOLOGY_BACKFILL_RECHECK_MS as K, ONTOLOGY_BACKFILL_BATCH_SIZE as O, PromptService as a1, PrunePartialFailureError as a2, WikiSearchUnavailableError as aA, WikiSourceRefHashCollision as aB, WikiStrictOntologyViolation as aC, WikiSupersedeError as aD, WikiTransactionError as aG, isWikiSearchUnavailableError as aH, validateManifest as aI, EmbeddingService as aJ, ImportExportService as aK, IngestionService as aL, JobManager as aM, MaintenanceService as aN, RetrievalService as aO, SearchService as aP, WriteService as aQ, WikiBusyError as ac, WikiDraftNotFound as am, WikiDuplicateHashError as an, WikiGraphNodeOwnershipConflict as ar, WikiIngestEmptyError as as, WikiInvalidReadOptions as au, WikiMigrationRequiredError as ax, WikiParseError as az, WikiMemory as c, HEAL_RECHECK_MS as u, HOOK_TIMEOUT_MARKER as v };
4192
- export type { PendingSourceStatus as $, MaintenanceStopReason as A, MigrationPolicy as B, ChunkFailure as C, DegradedRecord as D, EmbedFactResult as E, FormatContextOptions as F, GraphNeighborhood as G, IngestDocumentResult as I, LLMProvider as L, MemoryBundle as M, OntologyBackfillResult as N, OntologyConfig as P, OntologyEdgeType as Q, ReadOptions as R, SQLiteAdapter as S, OntologyManifest as T, OntologyMode as U, OntologyNodeType as V, WikiOptions as W, OntologyPromptContext as X, OntologyUpdates as Y, PendingMaintenance as Z, PendingMigrationWork as _, MemoryDump as a, PromptOverrides as a0, ReembedResult as a3, RememberInput as a4, RunPendingMaintenanceOptions as a5, RunPendingMaintenanceResult as a6, SupersedeReplacement as a7, VectorRanker as a8, VectorRankerFallback as a9, WikiSupersedeReason as aE, WikiTask as aF, VectorRankerRankArgs as aa, VectorRankerSemanticResult as ab, WikiBusyOperation as ad, WikiCheckpoint as ae, WikiConfig as af, WikiDiagnostic as ag, WikiDiagnosticCode as ah, WikiDiagnosticDetail as ai, WikiDiagnosticOperation as aj, WikiDiagnosticSeverity as ak, WikiDiagnosticTrigger as al, WikiEdge as ao, WikiEvent as ap, WikiFact as aq, WikiInstructions as at, WikiLintReport as av, WikiMemoryTestAccess as aw, WikiOutboxEvent as ay, FormattedMemoryDump as b, ClassifierAnswer as d, ClassifierQuestion as e, ClassifyRequest as f, ClassifyResponse as g, DraftPage as h, EmbedFailureKind as i, EmbeddingMarkerKind as j, EntityMaintenanceReport as k, EntityStatus as l, ExtractedFact as m, ExtractedFactEdge as n, ExtractedFactWithOntology as o, ExtractedTask as p, ForgetParams as q, ForgetResult as r, GraphTraversalOptions as s, GroundingConfig as t, HealResult as w, LibrarianConfig as x, LibrarianGateConfig as y, MaintenanceJob as z };
4497
+ export { HEAL_BATCH_SIZE as H, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS as K, ONTOLOGY_BACKFILL_RECHECK_MS as N, ONTOLOGY_BACKFILL_BATCH_SIZE as O, PromptService as a2, PrunePartialFailureError as a3, WikiParseError as aB, WikiSearchUnavailableError as aC, WikiSourceRefHashCollision as aD, WikiStrictOntologyViolation as aE, WikiSupersedeError as aF, WikiTransactionError as aI, isWikiSearchUnavailableError as aJ, validateManifest as aK, EmbeddingService as aL, ImportExportService as aM, IngestionService as aN, JobManager as aO, MaintenanceService as aP, RetrievalService as aQ, SearchService as aR, WriteService as aS, WikiBusyError as ad, WikiDraftNotFound as an, WikiDuplicateHashError as ao, WikiExternalDeletionError as ar, WikiGraphNodeOwnershipConflict as at, WikiIngestEmptyError as au, WikiInvalidReadOptions as aw, WikiMigrationRequiredError as az, WikiMemory as c, HEAL_RECHECK_MS as u, HOOK_TIMEOUT_MARKER as v };
4498
+ export type { PendingMigrationWork as $, MaintenanceJob as A, MaintenanceStopReason as B, ChunkFailure as C, DegradedRecord as D, EmbedFactResult as E, FormatContextOptions as F, GraphNeighborhood as G, IngestDocumentResult as I, MigrationPolicy as J, LLMProvider as L, MemoryBundle as M, OntologyBackfillResult as P, OntologyConfig as Q, ReadOptions as R, SQLiteAdapter as S, OntologyEdgeType as T, OntologyManifest as U, OntologyMode as V, WikiOptions as W, OntologyNodeType as X, OntologyPromptContext as Y, OntologyUpdates as Z, PendingMaintenance as _, MemoryDump as a, PendingSourceStatus as a0, PromptOverrides as a1, ReembedResult as a4, RememberInput as a5, RunPendingMaintenanceOptions as a6, RunPendingMaintenanceResult as a7, SupersedeReplacement as a8, VectorRanker as a9, WikiOutboxEvent as aA, WikiSupersedeReason as aG, WikiTask as aH, VectorRankerFallback as aa, VectorRankerRankArgs as ab, VectorRankerSemanticResult as ac, WikiBusyOperation as ae, WikiCheckpoint as af, WikiConfig as ag, WikiDiagnostic as ah, WikiDiagnosticCode as ai, WikiDiagnosticDetail as aj, WikiDiagnosticOperation as ak, WikiDiagnosticSeverity as al, WikiDiagnosticTrigger as am, WikiEdge as ap, WikiEvent as aq, WikiFact as as, WikiInstructions as av, WikiLintReport as ax, WikiMemoryTestAccess as ay, FormattedMemoryDump as b, ClassifierAnswer as d, ClassifierQuestion as e, ClassifyRequest as f, ClassifyResponse as g, DraftPage as h, EmbedFailureKind as i, EmbeddingMarkerKind as j, EntityMaintenanceReport as k, EntityStatus as l, ExtractedFact as m, ExtractedFactEdge as n, ExtractedFactWithOntology as o, ExtractedTask as p, ForgetParams as q, ForgetResult as r, GraphTraversalOptions as s, GroundingConfig as t, HealResult as w, LibrarianConfig as x, LibrarianGateConfig as y, LockedMaintenanceJob as z };