@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.
package/dist/testing.js CHANGED
@@ -66,6 +66,17 @@ var WikiBusyError = class extends Error {
66
66
  this.entityId = entityId;
67
67
  }
68
68
  };
69
+ var WikiExternalDeletionError = class extends Error {
70
+ constructor(message, params) {
71
+ super(message, params.cause ? { cause: params.cause } : void 0);
72
+ this.code = "WIKI_EXTERNAL_DELETION";
73
+ this.name = "WikiExternalDeletionError";
74
+ this.entityId = params.entityId;
75
+ this.unconfirmedIds = params.unconfirmedIds;
76
+ this.unconfirmedCount = params.unconfirmedCount;
77
+ this.timedOut = params.timedOut;
78
+ }
79
+ };
69
80
  var WikiDuplicateHashError = class extends Error {
70
81
  constructor(params) {
71
82
  super(`Duplicate source hash for entity ${params.entityId}; another ref already holds this content`);
@@ -534,14 +545,14 @@ function chunkText(input, maxChunkLength, overlap) {
534
545
  if (!Number.isInteger(overlap) || overlap < 0 || overlap >= maxChunkLength) {
535
546
  throw new Error("overlap must be a non-negative integer < maxChunkLength");
536
547
  }
537
- const chunks = [];
548
+ const chunks2 = [];
538
549
  let truncated = false;
539
550
  let cursor = 0;
540
551
  const halfMax = Math.floor(maxChunkLength / 2);
541
552
  while (cursor < text.length) {
542
553
  const remaining = text.length - cursor;
543
554
  if (remaining <= maxChunkLength) {
544
- chunks.push(safeSlice(text, cursor, text.length));
555
+ chunks2.push(safeSlice(text, cursor, text.length));
545
556
  break;
546
557
  }
547
558
  const windowEnd = cursor + maxChunkLength;
@@ -573,11 +584,11 @@ function chunkText(input, maxChunkLength, overlap) {
573
584
  truncated = true;
574
585
  splitPoint = windowEnd;
575
586
  }
576
- chunks.push(safeSlice(text, cursor, splitPoint));
587
+ chunks2.push(safeSlice(text, cursor, splitPoint));
577
588
  const next = Math.max(splitPoint - overlap, cursor + 1);
578
589
  cursor = next;
579
590
  }
580
- return { chunks, truncated };
591
+ return { chunks: chunks2, truncated };
581
592
  }
582
593
  async function withConcurrency(tasks, limit) {
583
594
  const results = new Array(tasks.length);
@@ -714,7 +725,9 @@ var SEVERITY = {
714
725
  read_budget: "info",
715
726
  event_retention_held: "info",
716
727
  event_created_at_clamped: "warn",
717
- event_created_at_restamped: "info"
728
+ event_created_at_restamped: "info",
729
+ external_deletion_pending: "warn",
730
+ external_deletion_discarded: "warn"
718
731
  };
719
732
  var MESSAGE = {
720
733
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -738,7 +751,9 @@ var MESSAGE = {
738
751
  read_budget: "A read was packed to a token budget.",
739
752
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
740
753
  event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
741
- event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared."
754
+ event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
755
+ external_deletion_pending: "Removals owed to the external vector index are still pending.",
756
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
742
757
  };
743
758
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
744
759
  function copyDetail(detail) {
@@ -951,27 +966,62 @@ var EmbeddingService = class {
951
966
  }
952
967
  /**
953
968
  * Storage half: persist the computed vector to the entry row, then fire the
954
- * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` only — embed
955
- * failures do not originate here, so they cannot be marked as such (spec §3.2, D3).
969
+ * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` (a DB error) and
970
+ * `fact_deleted` (the row was soft-deleted or gone: no blob, no vector call, no
971
+ * marker). Embed failures do not originate here, so they cannot be marked as
972
+ * such (spec §3.2, D3).
956
973
  */
957
974
  async storeFactVector(fact, float32Vector, ctx) {
975
+ let stored = true;
958
976
  try {
959
977
  await this.storeEmbeddingDimension(float32Vector.length);
960
978
  const blob = new Uint8Array(float32Vector.buffer);
961
- await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
979
+ stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
962
980
  } catch (err) {
963
981
  console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
964
982
  this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
965
983
  return { ok: false, kind: "storage_error" };
966
984
  }
985
+ if (!stored) return { ok: false, kind: "fact_deleted" };
967
986
  try {
968
987
  await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
969
988
  } catch (hookErr) {
970
989
  console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
971
990
  this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
972
991
  }
992
+ if (this.hasVectorHook()) {
993
+ await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
994
+ }
973
995
  return { ok: true, dimension: float32Vector.length };
974
996
  }
997
+ hasVectorHook() {
998
+ return !!this.options.vectorRanker?.onEmbeddingPersisted;
999
+ }
1000
+ /**
1001
+ * Run after a vector call (resolved or not) by every path that sends one.
1002
+ * Never throws: a failure here leaves the removal owed or unrecorded, as before.
1003
+ */
1004
+ async settleAfterVectorCall(entityId, factId, operation, trigger) {
1005
+ const vr = this.vectorRemoval;
1006
+ if (!vr) return;
1007
+ const outcome = await this.recordAfterVectorCall(entityId, factId);
1008
+ if (outcome === "enqueued") {
1009
+ try {
1010
+ await vr.service.deliverRemovals(entityId, [factId], operation, trigger, []);
1011
+ } catch (err) {
1012
+ console.warn(`[WikiMemory] post-embed removal delivery failed for ${factId}:`, err);
1013
+ }
1014
+ return;
1015
+ }
1016
+ if (outcome !== "write_failed") return;
1017
+ try {
1018
+ await this.callRemovalHook(entityId, factId, this.validateDeletionTimeout());
1019
+ } catch (hookErr) {
1020
+ console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
1021
+ this.reportHookFailed({ operation, trigger }, entityId, factId);
1022
+ await this.recordAfterVectorCall(entityId, factId);
1023
+ }
1024
+ }
975
1025
  reportEmbed(ctx, fact, code, reason) {
976
1026
  if (!ctx) return;
977
1027
  emitDiagnostic(this.options, {
@@ -1003,6 +1053,48 @@ var EmbeddingService = class {
1003
1053
  const result = await this.tryEmbedFact(fact, ctx);
1004
1054
  return result.ok;
1005
1055
  }
1056
+ /** Wired by WikiMemory (VectorRemovalService itself depends on this class). */
1057
+ attachVectorRemoval(service, repo) {
1058
+ this.vectorRemoval = { service, repo };
1059
+ }
1060
+ /**
1061
+ * After an embed (and its vector call) settles: owe a removal if the fact is
1062
+ * no longer live, so a vector the host just received is taken back (§5.7, G10).
1063
+ * Never throws. `'enqueued'`: a ledger row was written. `'none'`: no
1064
+ * removal hook (or the hook gate is off). `'live'`: the fact is live. A row already pending is
1065
+ * replaced (attempts reset, spec §5.2), so it counts as `'enqueued'` and
1066
+ * is sent now: the last call the host sees after this vector is `null`.
1067
+ * `'owed'`: the write failed but a pending row already holds the removal.
1068
+ * `'write_failed'`: the fact is known not live, the write failed, and its
1069
+ * row is confirmed or missing; or the store has no ledger table and the
1070
+ * fact is known not live.
1071
+ * `'unknown'`: the liveness read and the guarded write both failed.
1072
+ */
1073
+ async recordAfterVectorCall(entityId, factId) {
1074
+ const vr = this.vectorRemoval;
1075
+ if (!vr || vr.service.gate() !== "hook") return "none";
1076
+ let live;
1077
+ try {
1078
+ if (!await vr.service.ledgerPresent()) {
1079
+ return await vr.repo.isLive(factId) ? "live" : "write_failed";
1080
+ }
1081
+ live = await vr.repo.isLive(factId);
1082
+ } catch (err) {
1083
+ console.warn(`[WikiMemory] post-embed liveness read failed for ${factId}:`, err);
1084
+ }
1085
+ if (live) return "live";
1086
+ try {
1087
+ return await vr.repo.enqueueIfNotLive(entityId, factId, Date.now()) ? "enqueued" : "live";
1088
+ } catch (err) {
1089
+ console.warn(`[WikiMemory] post-embed removal could not be recorded for ${factId}:`, err);
1090
+ if (live !== false) return "unknown";
1091
+ try {
1092
+ if ((await vr.repo.statusFor([factId])).get(factId) === "pending") return "owed";
1093
+ } catch {
1094
+ }
1095
+ return "write_failed";
1096
+ }
1097
+ }
1006
1098
  async notifyEmbeddingPersisted(entityId, factId, vector) {
1007
1099
  if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
1008
1100
  const vectorCopy = vector ? vector.slice() : null;
@@ -1012,15 +1104,72 @@ var EmbeddingService = class {
1012
1104
  vector: vectorCopy
1013
1105
  });
1014
1106
  }
1015
- async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
1016
- if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
1017
- if (this.options.forceDeleteIgnoreRankerHook === true) return;
1018
- const vectorCopy = vector ? vector.slice() : null;
1107
+ validateDeletionTimeout() {
1019
1108
  const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
1020
1109
  if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
1021
1110
  throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
1022
1111
  }
1023
- const timeoutMs = rawTimeout;
1112
+ return rawTimeout;
1113
+ }
1114
+ /** Send a removal (`vector: null`) to the hook. No gate check; the caller owns the gate. */
1115
+ async callRemovalHook(entityId, factId, timeoutMs) {
1116
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) {
1117
+ throw new Error("callRemovalHook requires vectorRanker.onEmbeddingPersisted");
1118
+ }
1119
+ let timeoutHandle;
1120
+ const timeoutPromise = new Promise((_, reject) => {
1121
+ timeoutHandle = setTimeout(() => {
1122
+ const timeoutError = new Error(`onEmbeddingPersisted timed out after ${timeoutMs}ms`);
1123
+ timeoutError[HOOK_TIMEOUT_MARKER] = true;
1124
+ reject(timeoutError);
1125
+ }, timeoutMs);
1126
+ });
1127
+ const hookPromise = Promise.resolve().then(
1128
+ () => this.options.vectorRanker.onEmbeddingPersisted({ entityId, factId, vector: null })
1129
+ );
1130
+ try {
1131
+ await Promise.race([hookPromise, timeoutPromise]);
1132
+ } catch (err) {
1133
+ hookPromise.catch(() => {
1134
+ });
1135
+ throw err;
1136
+ } finally {
1137
+ if (timeoutHandle) clearTimeout(timeoutHandle);
1138
+ }
1139
+ }
1140
+ /**
1141
+ * One removal call per id for a store with no ledger table (setup() never
1142
+ * ran), so nothing records what is owed (spec §5.5.5). Stops at the first
1143
+ * timeout: a dead index costs one timeout, as in a drain (spec rev 5).
1144
+ * `failed` lists the ids not confirmed, in order; after a timeout it ends
1145
+ * with the timed-out id and every id after it. Throws only for an invalid
1146
+ * `deletionHookTimeoutMs`.
1147
+ */
1148
+ async callRemovalHookEach(entityId, ids, opts = {}) {
1149
+ const timeoutMs = this.validateDeletionTimeout();
1150
+ const failed = [];
1151
+ let firstRejection;
1152
+ for (let i = 0; i < ids.length; i++) {
1153
+ const factId = ids[i];
1154
+ try {
1155
+ await this.callRemovalHook(entityId, factId, timeoutMs);
1156
+ } catch (hookErr) {
1157
+ if (opts.warn) console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
1158
+ if (hookErr?.[HOOK_TIMEOUT_MARKER] === true) {
1159
+ failed.push(...ids.slice(i));
1160
+ return { failed, timedOut: true, timedOutId: factId, cause: hookErr };
1161
+ }
1162
+ failed.push(factId);
1163
+ firstRejection ?? (firstRejection = hookErr);
1164
+ }
1165
+ }
1166
+ return { failed, timedOut: false, cause: firstRejection };
1167
+ }
1168
+ async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
1169
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
1170
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
1171
+ const vectorCopy = vector ? vector.slice() : null;
1172
+ const timeoutMs = this.validateDeletionTimeout();
1024
1173
  let timeoutHandle;
1025
1174
  const timeoutPromise = new Promise((_, reject) => {
1026
1175
  timeoutHandle = setTimeout(() => {
@@ -1169,7 +1318,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1169
1318
  var IMPORT_TITLE_MAX = 500;
1170
1319
  var IMPORT_BODY_MAX = 8e3;
1171
1320
  var ImportExportService = class {
1172
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
1321
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
1173
1322
  this.db = db;
1174
1323
  this.entryRepo = entryRepo;
1175
1324
  this.taskRepo = taskRepo;
@@ -1180,6 +1329,7 @@ var ImportExportService = class {
1180
1329
  this.jobManager = jobManager;
1181
1330
  this.embeddingService = embeddingService;
1182
1331
  this.options = options;
1332
+ this.vectorRemoval = vectorRemoval;
1183
1333
  }
1184
1334
  async exportDump(entityIds) {
1185
1335
  let ids;
@@ -1555,7 +1705,7 @@ var ImportExportService = class {
1555
1705
  body: clipped?.body ?? fact.body,
1556
1706
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
1557
1707
  }, { operation: "importDump", trigger: "call" });
1558
- if (!embedded) {
1708
+ if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
1559
1709
  try {
1560
1710
  await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
1561
1711
  } catch (hookErr) {
@@ -1597,16 +1747,26 @@ var ImportExportService = class {
1597
1747
  fact.id
1598
1748
  );
1599
1749
  }
1750
+ if (this.embeddingService.hasVectorHook()) {
1751
+ await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
1752
+ }
1600
1753
  }
1601
1754
  }
1602
- for (const factId of softDeletedFactIds) {
1603
- if (!upsertedFactIds.has(factId) || upsertedDeletedFactIds.has(factId)) {
1755
+ const removedIds = softDeletedFactIds.filter(
1756
+ (id) => !upsertedFactIds.has(id) || upsertedDeletedFactIds.has(id)
1757
+ );
1758
+ if (this.vectorRemoval) {
1759
+ await this.vectorRemoval.deliverRemovals(
1760
+ entityId,
1761
+ Array.from(/* @__PURE__ */ new Set([...removedIds, ...upsertedDeletedFactIds])),
1762
+ "importDump",
1763
+ "call",
1764
+ removedIds
1765
+ );
1766
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
1767
+ for (const factId of removedIds) {
1604
1768
  try {
1605
- await this.embeddingService.notifyEmbeddingPersisted(
1606
- entityId,
1607
- factId,
1608
- null
1609
- );
1769
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
1610
1770
  } catch (hookErr) {
1611
1771
  console.warn(
1612
1772
  `[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
@@ -2186,7 +2346,7 @@ function zeroChunkResult(duplicateOf) {
2186
2346
  return result;
2187
2347
  }
2188
2348
  var IngestionService = class {
2189
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
2349
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
2190
2350
  this.db = db;
2191
2351
  this.prefix = prefix;
2192
2352
  this.options = options;
@@ -2198,6 +2358,7 @@ var IngestionService = class {
2198
2358
  this.jobManager = jobManager;
2199
2359
  this.embeddingService = embeddingService;
2200
2360
  this.ontologyService = ontologyService;
2361
+ this.vectorRemoval = vectorRemoval;
2201
2362
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
2202
2363
  }
2203
2364
  async ingestDocument(entityId, params, opts) {
@@ -2228,12 +2389,12 @@ var IngestionService = class {
2228
2389
  return zeroChunkResult(canonical);
2229
2390
  }
2230
2391
  }
2231
- const { chunks, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2232
- if (chunks.length === 0) return zeroChunkResult();
2392
+ const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2393
+ if (chunks2.length === 0) return zeroChunkResult();
2233
2394
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
2234
2395
  const ingestGrounding = this.promptService.groundingFor("ingest");
2235
2396
  const chunkResults = await withConcurrency(
2236
- chunks.map((chunk, chunkIndex) => async () => {
2397
+ chunks2.map((chunk, chunkIndex) => async () => {
2237
2398
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
2238
2399
  chunk,
2239
2400
  params.promptOverride,
@@ -2291,7 +2452,7 @@ var IngestionService = class {
2291
2452
  position: null,
2292
2453
  message: safeErrorToString(e)
2293
2454
  };
2294
- const total = chunks.length;
2455
+ const total = chunks2.length;
2295
2456
  const tags = [];
2296
2457
  if (failure.tier) tags.push(`tier=${failure.tier}`);
2297
2458
  if (failure.position !== null) tags.push(`position=${failure.position}`);
@@ -2368,11 +2529,11 @@ var IngestionService = class {
2368
2529
  }
2369
2530
  });
2370
2531
  }
2371
- if (failedChunks === chunks.length) {
2532
+ if (failedChunks === chunks2.length) {
2372
2533
  throw new WikiIngestEmptyError({
2373
2534
  parseFailures: failures,
2374
2535
  sourceRef,
2375
- chunks: chunks.length
2536
+ chunks: chunks2.length
2376
2537
  });
2377
2538
  }
2378
2539
  const insertedFacts = [];
@@ -2410,18 +2571,22 @@ var IngestionService = class {
2410
2571
  );
2411
2572
  if (failedChunks === 0) {
2412
2573
  const uniqueDeletedSourceFactIds = Array.from(new Set(deletedSourceFactIds));
2413
- for (const factId of uniqueDeletedSourceFactIds) {
2414
- try {
2415
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
2416
- } catch (hookErr) {
2417
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
2418
- emitDiagnostic(this.options, {
2419
- entityId,
2420
- operation: "ingest",
2421
- trigger: "call",
2422
- code: "hook_failed",
2423
- detail: { factId, reason: "on_embedding_persisted" }
2424
- });
2574
+ if (this.vectorRemoval) {
2575
+ await this.vectorRemoval.deliverRemovals(entityId, uniqueDeletedSourceFactIds, "ingest", "call");
2576
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
2577
+ for (const factId of uniqueDeletedSourceFactIds) {
2578
+ try {
2579
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
2580
+ } catch (hookErr) {
2581
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
2582
+ emitDiagnostic(this.options, {
2583
+ entityId,
2584
+ operation: "ingest",
2585
+ trigger: "call",
2586
+ code: "hook_failed",
2587
+ detail: { factId, reason: "on_embedding_persisted" }
2588
+ });
2589
+ }
2425
2590
  }
2426
2591
  }
2427
2592
  }
@@ -2431,7 +2596,7 @@ var IngestionService = class {
2431
2596
  this.searchService.evictCache(entityId);
2432
2597
  const result = {
2433
2598
  truncated,
2434
- chunks: chunks.length,
2599
+ chunks: chunks2.length,
2435
2600
  ingestedChunks,
2436
2601
  failedChunks
2437
2602
  };
@@ -2893,6 +3058,13 @@ function parseEmbedding(blob, text) {
2893
3058
  return null;
2894
3059
  }
2895
3060
 
3061
+ // src/services/VectorRemovalService.ts
3062
+ function removalGate(options) {
3063
+ if (options.forceDeleteIgnoreRankerHook === true) return "force";
3064
+ if (options.vectorRanker?.onEmbeddingPersisted) return "hook";
3065
+ return "none";
3066
+ }
3067
+
2896
3068
  // src/utils/temporal.ts
2897
3069
  function liveAtSql(mode, alias = "") {
2898
3070
  const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
@@ -3216,6 +3388,39 @@ async function runBatched(args) {
3216
3388
  }
3217
3389
 
3218
3390
  // src/db/schema.ts
3391
+ var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
3392
+ function resurrectLevel(sql) {
3393
+ if (sql.includes("embedding_failed_at")) return 2;
3394
+ return sql.includes("embedding_blob") ? 1 : 0;
3395
+ }
3396
+ async function createResurrectTrigger(db, prefix) {
3397
+ const name = `${prefix}vector_removals_resurrect`;
3398
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
3399
+ const names = new Set(cols.map((c) => c.name));
3400
+ const want = !(names.has("embedding_blob") && names.has("embedding")) ? 0 : EMBED_MARKER_COLUMNS.every((c) => names.has(c)) ? 2 : 1;
3401
+ const existing = await db.getFirstAsync(
3402
+ `SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?`,
3403
+ [name]
3404
+ );
3405
+ if (existing) {
3406
+ if (resurrectLevel(existing.sql ?? "") >= want) return;
3407
+ await db.execAsync(`DROP TRIGGER IF EXISTS ${name};`);
3408
+ }
3409
+ const clearVector = want === 0 ? "" : `
3410
+ UPDATE ${prefix}entries
3411
+ SET embedding_blob = NULL, embedding = NULL${want === 2 ? `,
3412
+ embedding_failed_at = NULL, embedding_failure_kind = NULL, embedding_attempts = 0` : ""}
3413
+ WHERE id = NEW.id
3414
+ AND EXISTS (SELECT 1 FROM ${prefix}vector_removals WHERE fact_id = NEW.id AND confirmed_at IS NOT NULL);`;
3415
+ await db.execAsync(`
3416
+ CREATE TRIGGER IF NOT EXISTS ${name}
3417
+ AFTER UPDATE OF deleted_at ON ${prefix}entries
3418
+ WHEN OLD.deleted_at IS NOT NULL AND NEW.deleted_at IS NULL
3419
+ BEGIN${clearVector}
3420
+ DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
3421
+ END;
3422
+ `);
3423
+ }
3219
3424
  async function createTemporalIndexesIfColumnsExist(db, prefix) {
3220
3425
  const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
3221
3426
  const names = new Set(cols.map((c) => c.name));
@@ -3282,6 +3487,7 @@ var MIGRATIONS = [
3282
3487
  `ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`
3283
3488
  );
3284
3489
  }
3490
+ await createResurrectTrigger(db, prefix);
3285
3491
  }
3286
3492
  },
3287
3493
  {
@@ -3475,6 +3681,7 @@ var MIGRATIONS = [
3475
3681
  for (const [name, sql] of adds) {
3476
3682
  if (!existing.has(name)) await db.execAsync(sql);
3477
3683
  }
3684
+ await createResurrectTrigger(db, prefix);
3478
3685
  }
3479
3686
  },
3480
3687
  {
@@ -4394,7 +4601,7 @@ var formatSkipError = (err) => {
4394
4601
  return base;
4395
4602
  };
4396
4603
  var MaintenanceService = class {
4397
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
4604
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
4398
4605
  this.db = db;
4399
4606
  this.prefix = prefix;
4400
4607
  this.options = options;
@@ -4407,6 +4614,8 @@ var MaintenanceService = class {
4407
4614
  this.jobManager = jobManager;
4408
4615
  this.embeddingService = embeddingService;
4409
4616
  this.ontologyService = ontologyService;
4617
+ this.vectorRemoval = vectorRemoval;
4618
+ this.vectorRemovalRepo = vectorRemovalRepo;
4410
4619
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
4411
4620
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
4412
4621
  }
@@ -4420,11 +4629,14 @@ var MaintenanceService = class {
4420
4629
  this._validatePruneDuration(retainEventsFor, "retainEventsFor");
4421
4630
  const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
4422
4631
  this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
4632
+ const gate = removalGate(this.options);
4633
+ if (gate === "hook") this.embeddingService.validateDeletionTimeout();
4423
4634
  const now = Date.now();
4424
4635
  let syncedIds = [];
4425
4636
  let deletedEntries = 0;
4426
4637
  let deletedTasks = 0;
4427
4638
  let deletedEvents = 0;
4639
+ let prunePartial = null;
4428
4640
  if (pruneSupersededAfter !== null) {
4429
4641
  const expiredCutoff = now - pruneSupersededAfter * 864e5;
4430
4642
  const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
@@ -4433,55 +4645,89 @@ var MaintenanceService = class {
4433
4645
  await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
4434
4646
  });
4435
4647
  syncedIds = [...expiredIds];
4648
+ if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
4649
+ await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
4650
+ }
4436
4651
  }
4437
4652
  }
4438
4653
  if (retainSoftDeletedFor !== null) {
4439
4654
  const cutoff = now - retainSoftDeletedFor * 864e5;
4440
4655
  const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
4441
- const succeeded = [];
4442
- let failure = null;
4443
- for (const row of entriesToDelete) {
4444
- try {
4445
- await this.embeddingService.notifyEmbeddingPersistedOrThrow(row.entity_id, row.id, null);
4446
- succeeded.push({ entity_id: row.entity_id, id: row.id });
4447
- } catch (err) {
4448
- failure = { factId: row.id, cause: err };
4449
- break;
4656
+ const prunableIds = entriesToDelete.map((r) => r.id);
4657
+ const vr = this.vectorRemoval;
4658
+ const vrRepo = this.vectorRemovalRepo;
4659
+ const ledgerOn = !!vr && !!vrRepo && await vr.ledgerPresent();
4660
+ let deletable = prunableIds;
4661
+ let removeLedger = false;
4662
+ let kept = [];
4663
+ let timedOut = false;
4664
+ let cause;
4665
+ let firstFailed;
4666
+ let failedOrder = [];
4667
+ if (ledgerOn && vr && vrRepo) {
4668
+ if (gate === "hook" && prunableIds.length > 0) {
4669
+ await this.db.withTransactionAsync(async (tx) => {
4670
+ await vrRepo.backstopEnqueue(entityId, prunableIds, now, tx);
4671
+ });
4672
+ }
4673
+ const result = prunableIds.length > 0 ? await vr.drain({ entityId, ids: prunableIds }) : { failedIds: [], timedOut: false, firstCause: void 0 };
4674
+ if (gate === "hook") {
4675
+ timedOut = result.timedOut;
4676
+ cause = result.firstCause;
4677
+ failedOrder = result.failedIds;
4678
+ } else if (gate === "force") {
4679
+ removeLedger = true;
4680
+ } else {
4681
+ removeLedger = !await vr.externalIndexInUse();
4450
4682
  }
4683
+ } else if (gate === "hook") {
4684
+ const r = await this.embeddingService.callRemovalHookEach(entityId, prunableIds);
4685
+ const failedSet = new Set(r.failed);
4686
+ kept = r.failed;
4687
+ deletable = prunableIds.filter((id) => !failedSet.has(id));
4688
+ timedOut = r.timedOut;
4689
+ cause = r.cause;
4690
+ firstFailed = kept[0];
4451
4691
  }
4452
- const succeededIds = succeeded.map((r) => r.id);
4453
- syncedIds = [...syncedIds, ...succeededIds];
4692
+ const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
4454
4693
  await this.db.withTransactionAsync(async (tx) => {
4455
- if (succeededIds.length > 0) {
4456
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, succeededIds, tx);
4694
+ if (hookLedger && vrRepo && prunableIds.length > 0) {
4695
+ const status = await vrRepo.statusFor(prunableIds, tx);
4696
+ deletable = prunableIds.filter((id) => status.get(id) !== "pending");
4697
+ kept = prunableIds.filter((id) => status.get(id) === "pending");
4698
+ }
4699
+ if (deletable.length > 0) {
4700
+ const deletedIds = [];
4701
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
4702
+ if (hookLedger) {
4703
+ const gone = new Set(deletedIds);
4704
+ const skipped = deletable.filter((id) => !gone.has(id));
4705
+ if (skipped.length > 0) {
4706
+ const after = await vrRepo.statusFor(skipped, tx);
4707
+ kept = [...kept, ...skipped.filter((id) => after.get(id) === "pending")];
4708
+ }
4709
+ deletable = deletedIds;
4710
+ }
4711
+ if (vrRepo && ledgerOn) {
4712
+ if (removeLedger) await vrRepo.deleteForFacts(entityId, deletable, tx, "all");
4713
+ else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
4714
+ }
4457
4715
  }
4458
4716
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
4459
4717
  });
4460
- if (failure) {
4461
- await this.searchService.syncEntries(entityId, syncedIds);
4462
- const remaining = entriesToDelete.length - succeeded.length - 1;
4463
- const isTimeout = failure.cause?.[HOOK_TIMEOUT_MARKER] === true;
4464
- if (isTimeout) {
4465
- throw new PrunePartialFailureError(
4466
- succeeded.length,
4467
- failure.factId,
4468
- remaining,
4469
- new Error("Deletion hook timed out"),
4470
- deletedTasks,
4471
- 0
4472
- );
4718
+ if (hookLedger) {
4719
+ const keptSet = new Set(kept);
4720
+ firstFailed = failedOrder.find((id) => keptSet.has(id)) ?? kept[0];
4721
+ }
4722
+ syncedIds = [...syncedIds, ...deletable];
4723
+ if (kept.length > 0) {
4724
+ if (timedOut) {
4725
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("Deletion hook timed out") };
4726
+ } else if (cause === void 0) {
4727
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("external removal not confirmed") };
4728
+ } else {
4729
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: this._sanitizeRankerError(cause) };
4473
4730
  }
4474
- const errMsg = failure.cause?.message ?? "";
4475
- const isValidationError = errMsg.startsWith("Invalid deletionHookTimeoutMs");
4476
- const sanitizedCause = isValidationError ? failure.cause : this._sanitizeRankerError(failure.cause);
4477
- throw new PrunePartialFailureError(
4478
- succeeded.length,
4479
- failure.factId,
4480
- remaining,
4481
- sanitizedCause,
4482
- deletedTasks,
4483
- 0
4484
- );
4485
4731
  }
4486
4732
  }
4487
4733
  if (retainEventsFor !== null) {
@@ -4518,6 +4764,16 @@ var MaintenanceService = class {
4518
4764
  await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
4519
4765
  }
4520
4766
  await this.searchService.syncEntries(entityId, syncedIds);
4767
+ if (prunePartial) {
4768
+ throw new PrunePartialFailureError(
4769
+ deletedEntries,
4770
+ prunePartial.failedAt,
4771
+ prunePartial.remaining,
4772
+ prunePartial.cause,
4773
+ deletedTasks,
4774
+ deletedEvents
4775
+ );
4776
+ }
4521
4777
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
4522
4778
  } finally {
4523
4779
  this.jobManager.releaseLock("prune", entityId);
@@ -4622,6 +4878,7 @@ var MaintenanceService = class {
4622
4878
  }
4623
4879
  const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
4624
4880
  if (result.ok) embedded++;
4881
+ else if (result.kind === "fact_deleted") skipped++;
4625
4882
  else failed++;
4626
4883
  }
4627
4884
  if (embedded > 0) {
@@ -4652,6 +4909,7 @@ var MaintenanceService = class {
4652
4909
  let deletedTasks = 0;
4653
4910
  let deletedEvents = 0;
4654
4911
  const deletedEntryIds = [];
4912
+ const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
4655
4913
  await this.db.withTransactionAsync(async (tx) => {
4656
4914
  if (params.clearAll) {
4657
4915
  for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
@@ -4700,22 +4958,54 @@ var MaintenanceService = class {
4700
4958
  if (taskResult) deletedTasks++;
4701
4959
  deletedEntries += refResult;
4702
4960
  }
4961
+ if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
4962
+ await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
4963
+ }
4703
4964
  });
4704
4965
  const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
4705
4966
  await this.searchService.syncEntries(entityId, uniqueDeletedIds);
4706
- for (const factId of uniqueDeletedIds) {
4967
+ if (uniqueDeletedIds.length > 0) {
4968
+ const firstId = uniqueDeletedIds[0];
4969
+ const vr = this.vectorRemoval;
4970
+ const vrRepo = this.vectorRemovalRepo;
4971
+ let unconfirmed = [];
4972
+ let timedOut = false;
4973
+ let cause;
4974
+ let timedOutId;
4707
4975
  try {
4708
- await this.embeddingService.notifyEmbeddingPersistedOrThrow(entityId, factId, null);
4709
- } catch (hookErr) {
4710
- const isTimeout = hookErr?.[HOOK_TIMEOUT_MARKER] === true;
4711
- if (isTimeout) {
4712
- throw new Error(`forget(${entityId}/${factId}) failed: ${hookErr.message}`);
4976
+ if (vr && vrRepo && ledgerOn) {
4977
+ const result = await vr.drain({ entityId, ids: uniqueDeletedIds });
4978
+ if (vr.gate() === "hook") {
4979
+ const status = await vrRepo.statusFor(uniqueDeletedIds);
4980
+ unconfirmed = uniqueDeletedIds.filter((id) => status.get(id) === "pending");
4981
+ timedOut = result.timedOut;
4982
+ timedOutId = result.timedOutId;
4983
+ cause = result.firstCause;
4984
+ }
4985
+ } else if (this.options.vectorRanker?.onEmbeddingPersisted && this.options.forceDeleteIgnoreRankerHook !== true) {
4986
+ const r = await this.embeddingService.callRemovalHookEach(entityId, uniqueDeletedIds);
4987
+ unconfirmed = r.failed;
4988
+ timedOut = r.timedOut;
4989
+ timedOutId = r.timedOutId;
4990
+ cause = r.cause;
4713
4991
  }
4992
+ } catch (hookErr) {
4714
4993
  const errMsg = hookErr?.message ?? "";
4715
4994
  if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
4716
- throw new Error(`forget(${entityId}/${factId}) failed: ${errMsg}`, { cause: hookErr });
4995
+ throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
4717
4996
  }
4718
- throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
4997
+ throw hookErr;
4998
+ }
4999
+ if (unconfirmed.length > 0) {
5000
+ const head = `forget(${entityId}/${(timedOut ? timedOutId : void 0) ?? unconfirmed[0]}) failed: `;
5001
+ const message = timedOut ? head + (cause?.message ?? "onEmbeddingPersisted timed out") : cause === void 0 ? head + "ANN cleanup not confirmed" : head + "ANN cleanup hook rejected";
5002
+ throw new WikiExternalDeletionError(message, {
5003
+ entityId,
5004
+ unconfirmedIds: unconfirmed.slice(0, 100),
5005
+ unconfirmedCount: unconfirmed.length,
5006
+ timedOut,
5007
+ cause: timedOut || cause === void 0 ? void 0 : this._sanitizeRankerError(cause)
5008
+ });
4719
5009
  }
4720
5010
  }
4721
5011
  if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
@@ -4724,6 +5014,22 @@ var MaintenanceService = class {
4724
5014
  this.jobManager.releaseLock("forget", entityId);
4725
5015
  }
4726
5016
  }
5017
+ /** Heal's post-commit removal delivery (spec §5.7). Never throws. */
5018
+ async deliverHealRemovals(entityId, ids, trigger) {
5019
+ if (this.vectorRemoval) {
5020
+ await this.vectorRemoval.deliverRemovals(entityId, ids, "heal", trigger);
5021
+ return;
5022
+ }
5023
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
5024
+ for (const factId of ids) {
5025
+ try {
5026
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
5027
+ } catch (hookErr) {
5028
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
5029
+ emitDiagnostic(this.options, { entityId, operation: "heal", trigger, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
5030
+ }
5031
+ }
5032
+ }
4727
5033
  /**
4728
5034
  * Whether forget() should soft-delete in source_ref_index (#316,
4729
5035
  * specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
@@ -4921,14 +5227,7 @@ var MaintenanceService = class {
4921
5227
  staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
4922
5228
  }
4923
5229
  });
4924
- for (const factId of orphanedIds) {
4925
- try {
4926
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
4927
- } catch (hookErr) {
4928
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal orphan pass for ${factId}:`, hookErr);
4929
- emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
4930
- }
4931
- }
5230
+ await this.deliverHealRemovals(entityId, orphanedIds, trigger);
4932
5231
  const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
4933
5232
  const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
4934
5233
  if (healCandidates.length === 0 || keywordUnavailable) {
@@ -5117,14 +5416,7 @@ var MaintenanceService = class {
5117
5416
  ...insertedFacts.map((f) => f.id)
5118
5417
  ]));
5119
5418
  await this.searchService.syncEntries(entityId, healSyncIds);
5120
- for (const factId of uniqueDeletedFactIds) {
5121
- try {
5122
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
5123
- } catch (hookErr) {
5124
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
5125
- emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
5126
- }
5127
- }
5419
+ await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
5128
5420
  for (const fact of insertedFacts) {
5129
5421
  await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
5130
5422
  }