@equationalapplications/core-llm-wiki 8.3.0 → 9.0.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,11 @@ 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",
731
+ guidance_too_long: "warn",
732
+ guidance_resolver_failed: "warn"
718
733
  };
719
734
  var MESSAGE = {
720
735
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -738,7 +753,11 @@ var MESSAGE = {
738
753
  read_budget: "A read was packed to a token budget.",
739
754
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
740
755
  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."
756
+ 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.",
757
+ external_deletion_pending: "Removals owed to the external vector index are still pending.",
758
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
759
+ guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
760
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
742
761
  };
743
762
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
744
763
  function copyDetail(detail) {
@@ -951,27 +970,62 @@ var EmbeddingService = class {
951
970
  }
952
971
  /**
953
972
  * 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).
973
+ * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` (a DB error) and
974
+ * `fact_deleted` (the row was soft-deleted or gone: no blob, no vector call, no
975
+ * marker). Embed failures do not originate here, so they cannot be marked as
976
+ * such (spec §3.2, D3).
956
977
  */
957
978
  async storeFactVector(fact, float32Vector, ctx) {
979
+ let stored = true;
958
980
  try {
959
981
  await this.storeEmbeddingDimension(float32Vector.length);
960
982
  const blob = new Uint8Array(float32Vector.buffer);
961
- await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
983
+ stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
962
984
  } catch (err) {
963
985
  console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
964
986
  this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
965
987
  return { ok: false, kind: "storage_error" };
966
988
  }
989
+ if (!stored) return { ok: false, kind: "fact_deleted" };
967
990
  try {
968
991
  await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
969
992
  } catch (hookErr) {
970
993
  console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
971
994
  this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
972
995
  }
996
+ if (this.hasVectorHook()) {
997
+ await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
998
+ }
973
999
  return { ok: true, dimension: float32Vector.length };
974
1000
  }
1001
+ hasVectorHook() {
1002
+ return !!this.options.vectorRanker?.onEmbeddingPersisted;
1003
+ }
1004
+ /**
1005
+ * Run after a vector call (resolved or not) by every path that sends one.
1006
+ * Never throws: a failure here leaves the removal owed or unrecorded, as before.
1007
+ */
1008
+ async settleAfterVectorCall(entityId, factId, operation, trigger) {
1009
+ const vr = this.vectorRemoval;
1010
+ if (!vr) return;
1011
+ const outcome = await this.recordAfterVectorCall(entityId, factId);
1012
+ if (outcome === "enqueued") {
1013
+ try {
1014
+ await vr.service.deliverRemovals(entityId, [factId], operation, trigger, []);
1015
+ } catch (err) {
1016
+ console.warn(`[WikiMemory] post-embed removal delivery failed for ${factId}:`, err);
1017
+ }
1018
+ return;
1019
+ }
1020
+ if (outcome !== "write_failed") return;
1021
+ try {
1022
+ await this.callRemovalHook(entityId, factId, this.validateDeletionTimeout());
1023
+ } catch (hookErr) {
1024
+ console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
1025
+ this.reportHookFailed({ operation, trigger }, entityId, factId);
1026
+ await this.recordAfterVectorCall(entityId, factId);
1027
+ }
1028
+ }
975
1029
  reportEmbed(ctx, fact, code, reason) {
976
1030
  if (!ctx) return;
977
1031
  emitDiagnostic(this.options, {
@@ -1003,6 +1057,48 @@ var EmbeddingService = class {
1003
1057
  const result = await this.tryEmbedFact(fact, ctx);
1004
1058
  return result.ok;
1005
1059
  }
1060
+ /** Wired by WikiMemory (VectorRemovalService itself depends on this class). */
1061
+ attachVectorRemoval(service, repo) {
1062
+ this.vectorRemoval = { service, repo };
1063
+ }
1064
+ /**
1065
+ * After an embed (and its vector call) settles: owe a removal if the fact is
1066
+ * no longer live, so a vector the host just received is taken back (§5.7, G10).
1067
+ * Never throws. `'enqueued'`: a ledger row was written. `'none'`: no
1068
+ * removal hook (or the hook gate is off). `'live'`: the fact is live. A row already pending is
1069
+ * replaced (attempts reset, spec §5.2), so it counts as `'enqueued'` and
1070
+ * is sent now: the last call the host sees after this vector is `null`.
1071
+ * `'owed'`: the write failed but a pending row already holds the removal.
1072
+ * `'write_failed'`: the fact is known not live, the write failed, and its
1073
+ * row is confirmed or missing; or the store has no ledger table and the
1074
+ * fact is known not live.
1075
+ * `'unknown'`: the liveness read and the guarded write both failed.
1076
+ */
1077
+ async recordAfterVectorCall(entityId, factId) {
1078
+ const vr = this.vectorRemoval;
1079
+ if (!vr || vr.service.gate() !== "hook") return "none";
1080
+ let live;
1081
+ try {
1082
+ if (!await vr.service.ledgerPresent()) {
1083
+ return await vr.repo.isLive(factId) ? "live" : "write_failed";
1084
+ }
1085
+ live = await vr.repo.isLive(factId);
1086
+ } catch (err) {
1087
+ console.warn(`[WikiMemory] post-embed liveness read failed for ${factId}:`, err);
1088
+ }
1089
+ if (live) return "live";
1090
+ try {
1091
+ return await vr.repo.enqueueIfNotLive(entityId, factId, Date.now()) ? "enqueued" : "live";
1092
+ } catch (err) {
1093
+ console.warn(`[WikiMemory] post-embed removal could not be recorded for ${factId}:`, err);
1094
+ if (live !== false) return "unknown";
1095
+ try {
1096
+ if ((await vr.repo.statusFor([factId])).get(factId) === "pending") return "owed";
1097
+ } catch {
1098
+ }
1099
+ return "write_failed";
1100
+ }
1101
+ }
1006
1102
  async notifyEmbeddingPersisted(entityId, factId, vector) {
1007
1103
  if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
1008
1104
  const vectorCopy = vector ? vector.slice() : null;
@@ -1012,15 +1108,72 @@ var EmbeddingService = class {
1012
1108
  vector: vectorCopy
1013
1109
  });
1014
1110
  }
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;
1111
+ validateDeletionTimeout() {
1019
1112
  const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
1020
1113
  if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
1021
1114
  throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
1022
1115
  }
1023
- const timeoutMs = rawTimeout;
1116
+ return rawTimeout;
1117
+ }
1118
+ /** Send a removal (`vector: null`) to the hook. No gate check; the caller owns the gate. */
1119
+ async callRemovalHook(entityId, factId, timeoutMs) {
1120
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) {
1121
+ throw new Error("callRemovalHook requires vectorRanker.onEmbeddingPersisted");
1122
+ }
1123
+ let timeoutHandle;
1124
+ const timeoutPromise = new Promise((_, reject) => {
1125
+ timeoutHandle = setTimeout(() => {
1126
+ const timeoutError = new Error(`onEmbeddingPersisted timed out after ${timeoutMs}ms`);
1127
+ timeoutError[HOOK_TIMEOUT_MARKER] = true;
1128
+ reject(timeoutError);
1129
+ }, timeoutMs);
1130
+ });
1131
+ const hookPromise = Promise.resolve().then(
1132
+ () => this.options.vectorRanker.onEmbeddingPersisted({ entityId, factId, vector: null })
1133
+ );
1134
+ try {
1135
+ await Promise.race([hookPromise, timeoutPromise]);
1136
+ } catch (err) {
1137
+ hookPromise.catch(() => {
1138
+ });
1139
+ throw err;
1140
+ } finally {
1141
+ if (timeoutHandle) clearTimeout(timeoutHandle);
1142
+ }
1143
+ }
1144
+ /**
1145
+ * One removal call per id for a store with no ledger table (setup() never
1146
+ * ran), so nothing records what is owed (spec §5.5.5). Stops at the first
1147
+ * timeout: a dead index costs one timeout, as in a drain (spec rev 5).
1148
+ * `failed` lists the ids not confirmed, in order; after a timeout it ends
1149
+ * with the timed-out id and every id after it. Throws only for an invalid
1150
+ * `deletionHookTimeoutMs`.
1151
+ */
1152
+ async callRemovalHookEach(entityId, ids, opts = {}) {
1153
+ const timeoutMs = this.validateDeletionTimeout();
1154
+ const failed = [];
1155
+ let firstRejection;
1156
+ for (let i = 0; i < ids.length; i++) {
1157
+ const factId = ids[i];
1158
+ try {
1159
+ await this.callRemovalHook(entityId, factId, timeoutMs);
1160
+ } catch (hookErr) {
1161
+ if (opts.warn) console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
1162
+ if (hookErr?.[HOOK_TIMEOUT_MARKER] === true) {
1163
+ failed.push(...ids.slice(i));
1164
+ return { failed, timedOut: true, timedOutId: factId, cause: hookErr };
1165
+ }
1166
+ failed.push(factId);
1167
+ firstRejection ?? (firstRejection = hookErr);
1168
+ }
1169
+ }
1170
+ return { failed, timedOut: false, cause: firstRejection };
1171
+ }
1172
+ async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
1173
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
1174
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
1175
+ const vectorCopy = vector ? vector.slice() : null;
1176
+ const timeoutMs = this.validateDeletionTimeout();
1024
1177
  let timeoutHandle;
1025
1178
  const timeoutPromise = new Promise((_, reject) => {
1026
1179
  timeoutHandle = setTimeout(() => {
@@ -1169,7 +1322,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1169
1322
  var IMPORT_TITLE_MAX = 500;
1170
1323
  var IMPORT_BODY_MAX = 8e3;
1171
1324
  var ImportExportService = class {
1172
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
1325
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
1173
1326
  this.db = db;
1174
1327
  this.entryRepo = entryRepo;
1175
1328
  this.taskRepo = taskRepo;
@@ -1180,6 +1333,7 @@ var ImportExportService = class {
1180
1333
  this.jobManager = jobManager;
1181
1334
  this.embeddingService = embeddingService;
1182
1335
  this.options = options;
1336
+ this.vectorRemoval = vectorRemoval;
1183
1337
  }
1184
1338
  async exportDump(entityIds) {
1185
1339
  let ids;
@@ -1555,7 +1709,7 @@ var ImportExportService = class {
1555
1709
  body: clipped?.body ?? fact.body,
1556
1710
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
1557
1711
  }, { operation: "importDump", trigger: "call" });
1558
- if (!embedded) {
1712
+ if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
1559
1713
  try {
1560
1714
  await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
1561
1715
  } catch (hookErr) {
@@ -1597,16 +1751,26 @@ var ImportExportService = class {
1597
1751
  fact.id
1598
1752
  );
1599
1753
  }
1754
+ if (this.embeddingService.hasVectorHook()) {
1755
+ await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
1756
+ }
1600
1757
  }
1601
1758
  }
1602
- for (const factId of softDeletedFactIds) {
1603
- if (!upsertedFactIds.has(factId) || upsertedDeletedFactIds.has(factId)) {
1759
+ const removedIds = softDeletedFactIds.filter(
1760
+ (id) => !upsertedFactIds.has(id) || upsertedDeletedFactIds.has(id)
1761
+ );
1762
+ if (this.vectorRemoval) {
1763
+ await this.vectorRemoval.deliverRemovals(
1764
+ entityId,
1765
+ Array.from(/* @__PURE__ */ new Set([...removedIds, ...upsertedDeletedFactIds])),
1766
+ "importDump",
1767
+ "call",
1768
+ removedIds
1769
+ );
1770
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
1771
+ for (const factId of removedIds) {
1604
1772
  try {
1605
- await this.embeddingService.notifyEmbeddingPersisted(
1606
- entityId,
1607
- factId,
1608
- null
1609
- );
1773
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
1610
1774
  } catch (hookErr) {
1611
1775
  console.warn(
1612
1776
  `[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
@@ -1726,6 +1890,14 @@ function generateId(prefix = "") {
1726
1890
  }
1727
1891
 
1728
1892
  // src/prompts.ts
1893
+ var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
1894
+ var GUIDANCE_MAX_CHARS = 2e3;
1895
+ function guidanceSection(guidance) {
1896
+ return `--- Host guidance ---
1897
+ ${guidance}
1898
+ --- End host guidance ---
1899
+ ${LEAVE_OUT_RULE_SENTENCE}`;
1900
+ }
1729
1901
  var LIBRARIAN_SYSTEM_PROMPT = `You are a knowledge extraction agent. Your job is to analyze recent episodic events and extract stable facts and actionable tasks about the user or entity.
1730
1902
  Return ONLY a valid JSON object matching this schema:
1731
1903
  {
@@ -1849,6 +2021,64 @@ var PromptService = class {
1849
2021
  this.globalOverrides = globalOverrides;
1850
2022
  this.grounding = grounding;
1851
2023
  }
2024
+ /**
2025
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
2026
+ * or call — default `config.prompts.guidance`, per-entity
2027
+ * `config.librarian.guidanceForEntity` winning when it returns a
2028
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
2029
+ * returns a thenable (its rejection is swallowed with a no-op handler;
2030
+ * a throwing `then` counts too), or returns any non-string value is
2031
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
2032
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
2033
+ * Emits nothing itself; the caller emits, immediately at resolution.
2034
+ */
2035
+ static resolveGuidance(config, entityId) {
2036
+ let source = null;
2037
+ let effective;
2038
+ let resolverDiagnostic;
2039
+ const defaultValue = config?.prompts?.guidance;
2040
+ const resolver = config?.librarian?.guidanceForEntity;
2041
+ let entityValue;
2042
+ if (resolver) {
2043
+ try {
2044
+ entityValue = resolver(entityId);
2045
+ if (entityValue === void 0) {
2046
+ } else if (typeof entityValue === "string") {
2047
+ if (entityValue.trim() !== "") {
2048
+ source = "per_entity";
2049
+ effective = entityValue;
2050
+ }
2051
+ } else {
2052
+ try {
2053
+ entityValue?.then?.(() => void 0, () => void 0);
2054
+ } catch {
2055
+ }
2056
+ resolverDiagnostic = {
2057
+ code: "guidance_resolver_failed",
2058
+ detail: { reason: "non_string" }
2059
+ };
2060
+ }
2061
+ } catch {
2062
+ resolverDiagnostic = { code: "guidance_resolver_failed", detail: { reason: "threw" } };
2063
+ }
2064
+ }
2065
+ if (source === null && defaultValue !== void 0 && defaultValue.trim() !== "") {
2066
+ source = "default";
2067
+ effective = defaultValue;
2068
+ }
2069
+ if (source === null || effective === void 0) {
2070
+ return resolverDiagnostic ? { diagnostic: resolverDiagnostic } : {};
2071
+ }
2072
+ if (effective.length > GUIDANCE_MAX_CHARS) {
2073
+ return {
2074
+ diagnostic: {
2075
+ code: "guidance_too_long",
2076
+ detail: { guidanceLength: effective.length, guidanceSource: source }
2077
+ }
2078
+ };
2079
+ }
2080
+ return resolverDiagnostic ? { guidance: effective, diagnostic: resolverDiagnostic } : { guidance: effective };
2081
+ }
1852
2082
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
1853
2083
  groundingFor(writer) {
1854
2084
  return this.grounding?.writers.has(writer) ? this.grounding : null;
@@ -1859,6 +2089,19 @@ var PromptService = class {
1859
2089
  return cfg ? `${systemPrompt}
1860
2090
 
1861
2091
  ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
2092
+ }
2093
+ /**
2094
+ * Specs/librarian-guidance: append the marked guidance section (with the
2095
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
2096
+ * ontology, immediately before grounding. The guidance text is never
2097
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
2098
+ * template branch or be expanded with data. No-op on empty input.
2099
+ */
2100
+ appendGuidance(systemPrompt, guidance) {
2101
+ if (!guidance) return systemPrompt;
2102
+ return `${systemPrompt}
2103
+
2104
+ ${guidanceSection(guidance)}`;
1862
2105
  }
1863
2106
  hydrate(template, variables) {
1864
2107
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, key) => {
@@ -1895,31 +2138,31 @@ ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
1895
2138
 
1896
2139
  ${ctx.ontologyModeInstructions}`;
1897
2140
  }
1898
- buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext) {
2141
+ buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext, guidance) {
1899
2142
  const template = runtimeOverride ?? this.globalOverrides?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT;
1900
2143
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
1901
2144
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
1902
2145
  return {
1903
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), "ingest"),
2146
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
1904
2147
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
1905
2148
  ${documentChunk}`
1906
2149
  };
1907
2150
  }
1908
2151
  return {
1909
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "ingest"),
2152
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
1910
2153
  userPrompt: `Document Chunk:
1911
2154
  ${documentChunk}`
1912
2155
  };
1913
2156
  }
1914
- buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext) {
1915
- const template = runtimeOverride ?? this.globalOverrides?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT;
2157
+ buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext, guidance) {
2158
+ const template = runtimeOverride ?? LIBRARIAN_SYSTEM_PROMPT;
1916
2159
  const hasEvents = /\{\{\s*events\s*\}\}/.test(template);
1917
2160
  const hasCurrentFacts = /\{\{\s*currentFacts\s*\}\}/.test(template);
1918
2161
  const eventsShown = hasEvents || !hasCurrentFacts;
1919
2162
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
1920
2163
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
1921
2164
  return {
1922
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), "librarian"),
2165
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
1923
2166
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
1924
2167
  ${JSON.stringify(events, null, 2)}
1925
2168
 
@@ -1929,7 +2172,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
1929
2172
  };
1930
2173
  }
1931
2174
  return {
1932
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "librarian"),
2175
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
1933
2176
  userPrompt: `Events:
1934
2177
  ${JSON.stringify(events, null, 2)}
1935
2178
 
@@ -2032,11 +2275,11 @@ ${JSON.stringify(facts, null, 2)}`
2032
2275
  };
2033
2276
  }
2034
2277
  /** Ops extract (spec §5.2): events only — no existing facts. */
2035
- buildOpsExtractPrompt(events, ontologyContext) {
2278
+ buildOpsExtractPrompt(events, ontologyContext, guidance) {
2036
2279
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
2037
2280
  const grounding = this.groundingFor("librarian");
2038
2281
  return {
2039
- systemPrompt: this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian"),
2282
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2040
2283
  userPrompt: `Events:
2041
2284
  ${lines.join("\n")}`,
2042
2285
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
@@ -2053,11 +2296,11 @@ ${JSON.stringify({ items })}` };
2053
2296
  * placeholders and leaves data placeholders verbatim; heal never receives
2054
2297
  * ontology context, matching `buildHealPrompt`.
2055
2298
  */
2056
- buildInstructionTemplates(ontologyContext, librarianStrategy) {
2299
+ buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
2057
2300
  const o = this.globalOverrides;
2058
2301
  return {
2059
- ingest: this.appendGrounding(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), "ingest"),
2060
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian") : this.appendGrounding(this.buildSystemPrompt(o?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), "librarian"),
2302
+ ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
2303
+ librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), guidance), "librarian"),
2061
2304
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
2062
2305
  ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
2063
2306
  };
@@ -2186,7 +2429,7 @@ function zeroChunkResult(duplicateOf) {
2186
2429
  return result;
2187
2430
  }
2188
2431
  var IngestionService = class {
2189
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
2432
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
2190
2433
  this.db = db;
2191
2434
  this.prefix = prefix;
2192
2435
  this.options = options;
@@ -2198,6 +2441,7 @@ var IngestionService = class {
2198
2441
  this.jobManager = jobManager;
2199
2442
  this.embeddingService = embeddingService;
2200
2443
  this.ontologyService = ontologyService;
2444
+ this.vectorRemoval = vectorRemoval;
2201
2445
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
2202
2446
  }
2203
2447
  async ingestDocument(entityId, params, opts) {
@@ -2228,16 +2472,27 @@ var IngestionService = class {
2228
2472
  return zeroChunkResult(canonical);
2229
2473
  }
2230
2474
  }
2231
- const { chunks, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2232
- if (chunks.length === 0) return zeroChunkResult();
2475
+ const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2476
+ if (chunks2.length === 0) return zeroChunkResult();
2233
2477
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
2478
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
2479
+ if (diagnostic) {
2480
+ emitDiagnostic(this.options, {
2481
+ code: diagnostic.code,
2482
+ operation: "ingest",
2483
+ trigger: "call",
2484
+ entityId,
2485
+ detail: diagnostic.detail
2486
+ });
2487
+ }
2234
2488
  const ingestGrounding = this.promptService.groundingFor("ingest");
2235
2489
  const chunkResults = await withConcurrency(
2236
- chunks.map((chunk, chunkIndex) => async () => {
2490
+ chunks2.map((chunk, chunkIndex) => async () => {
2237
2491
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
2238
2492
  chunk,
2239
2493
  params.promptOverride,
2240
- ontologyContext
2494
+ ontologyContext,
2495
+ guidance
2241
2496
  );
2242
2497
  try {
2243
2498
  const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
@@ -2291,7 +2546,7 @@ var IngestionService = class {
2291
2546
  position: null,
2292
2547
  message: safeErrorToString(e)
2293
2548
  };
2294
- const total = chunks.length;
2549
+ const total = chunks2.length;
2295
2550
  const tags = [];
2296
2551
  if (failure.tier) tags.push(`tier=${failure.tier}`);
2297
2552
  if (failure.position !== null) tags.push(`position=${failure.position}`);
@@ -2368,11 +2623,11 @@ var IngestionService = class {
2368
2623
  }
2369
2624
  });
2370
2625
  }
2371
- if (failedChunks === chunks.length) {
2626
+ if (failedChunks === chunks2.length) {
2372
2627
  throw new WikiIngestEmptyError({
2373
2628
  parseFailures: failures,
2374
2629
  sourceRef,
2375
- chunks: chunks.length
2630
+ chunks: chunks2.length
2376
2631
  });
2377
2632
  }
2378
2633
  const insertedFacts = [];
@@ -2410,18 +2665,22 @@ var IngestionService = class {
2410
2665
  );
2411
2666
  if (failedChunks === 0) {
2412
2667
  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
- });
2668
+ if (this.vectorRemoval) {
2669
+ await this.vectorRemoval.deliverRemovals(entityId, uniqueDeletedSourceFactIds, "ingest", "call");
2670
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
2671
+ for (const factId of uniqueDeletedSourceFactIds) {
2672
+ try {
2673
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
2674
+ } catch (hookErr) {
2675
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
2676
+ emitDiagnostic(this.options, {
2677
+ entityId,
2678
+ operation: "ingest",
2679
+ trigger: "call",
2680
+ code: "hook_failed",
2681
+ detail: { factId, reason: "on_embedding_persisted" }
2682
+ });
2683
+ }
2425
2684
  }
2426
2685
  }
2427
2686
  }
@@ -2431,7 +2690,7 @@ var IngestionService = class {
2431
2690
  this.searchService.evictCache(entityId);
2432
2691
  const result = {
2433
2692
  truncated,
2434
- chunks: chunks.length,
2693
+ chunks: chunks2.length,
2435
2694
  ingestedChunks,
2436
2695
  failedChunks
2437
2696
  };
@@ -2893,6 +3152,13 @@ function parseEmbedding(blob, text) {
2893
3152
  return null;
2894
3153
  }
2895
3154
 
3155
+ // src/services/VectorRemovalService.ts
3156
+ function removalGate(options) {
3157
+ if (options.forceDeleteIgnoreRankerHook === true) return "force";
3158
+ if (options.vectorRanker?.onEmbeddingPersisted) return "hook";
3159
+ return "none";
3160
+ }
3161
+
2896
3162
  // src/utils/temporal.ts
2897
3163
  function liveAtSql(mode, alias = "") {
2898
3164
  const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
@@ -3216,6 +3482,39 @@ async function runBatched(args) {
3216
3482
  }
3217
3483
 
3218
3484
  // src/db/schema.ts
3485
+ var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
3486
+ function resurrectLevel(sql) {
3487
+ if (sql.includes("embedding_failed_at")) return 2;
3488
+ return sql.includes("embedding_blob") ? 1 : 0;
3489
+ }
3490
+ async function createResurrectTrigger(db, prefix) {
3491
+ const name = `${prefix}vector_removals_resurrect`;
3492
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
3493
+ const names = new Set(cols.map((c) => c.name));
3494
+ const want = !(names.has("embedding_blob") && names.has("embedding")) ? 0 : EMBED_MARKER_COLUMNS.every((c) => names.has(c)) ? 2 : 1;
3495
+ const existing = await db.getFirstAsync(
3496
+ `SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?`,
3497
+ [name]
3498
+ );
3499
+ if (existing) {
3500
+ if (resurrectLevel(existing.sql ?? "") >= want) return;
3501
+ await db.execAsync(`DROP TRIGGER IF EXISTS ${name};`);
3502
+ }
3503
+ const clearVector = want === 0 ? "" : `
3504
+ UPDATE ${prefix}entries
3505
+ SET embedding_blob = NULL, embedding = NULL${want === 2 ? `,
3506
+ embedding_failed_at = NULL, embedding_failure_kind = NULL, embedding_attempts = 0` : ""}
3507
+ WHERE id = NEW.id
3508
+ AND EXISTS (SELECT 1 FROM ${prefix}vector_removals WHERE fact_id = NEW.id AND confirmed_at IS NOT NULL);`;
3509
+ await db.execAsync(`
3510
+ CREATE TRIGGER IF NOT EXISTS ${name}
3511
+ AFTER UPDATE OF deleted_at ON ${prefix}entries
3512
+ WHEN OLD.deleted_at IS NOT NULL AND NEW.deleted_at IS NULL
3513
+ BEGIN${clearVector}
3514
+ DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
3515
+ END;
3516
+ `);
3517
+ }
3219
3518
  async function createTemporalIndexesIfColumnsExist(db, prefix) {
3220
3519
  const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
3221
3520
  const names = new Set(cols.map((c) => c.name));
@@ -3282,6 +3581,7 @@ var MIGRATIONS = [
3282
3581
  `ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`
3283
3582
  );
3284
3583
  }
3584
+ await createResurrectTrigger(db, prefix);
3285
3585
  }
3286
3586
  },
3287
3587
  {
@@ -3475,6 +3775,7 @@ var MIGRATIONS = [
3475
3775
  for (const [name, sql] of adds) {
3476
3776
  if (!existing.has(name)) await db.execAsync(sql);
3477
3777
  }
3778
+ await createResurrectTrigger(db, prefix);
3478
3779
  }
3479
3780
  },
3480
3781
  {
@@ -3596,7 +3897,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
3596
3897
  promptEvents,
3597
3898
  currentFacts,
3598
3899
  promptOverride,
3599
- ontologyContext
3900
+ ontologyContext,
3901
+ ctx.guidance
3600
3902
  );
3601
3903
  let responseText;
3602
3904
  try {
@@ -3768,7 +4070,7 @@ var OPS_MAX_EVENTS_PER_PASS = 50;
3768
4070
  var OPS_MAX_EXTRACT_CHARS = 24e3;
3769
4071
  var RESOLVE_RESERVE_FACTOR = 2;
3770
4072
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
3771
- async function selectBatch(deps, entityId, wm, meter) {
4073
+ async function selectBatch(deps, entityId, wm, meter, guidance) {
3772
4074
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
3773
4075
  if (events.length === 0) return { batch: [] };
3774
4076
  let n = 0;
@@ -3782,7 +4084,7 @@ async function selectBatch(deps, entityId, wm, meter) {
3782
4084
  if (meter && meter.budget !== void 0) {
3783
4085
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
3784
4086
  for (; ; ) {
3785
- const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext));
4087
+ const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
3786
4088
  if (meter.fits(need)) break;
3787
4089
  if (batch.length === 1) return { budgetStop: { requiredEstimate: need } };
3788
4090
  batch = labelEvents(events.slice(0, Math.max(1, Math.floor(batch.length / 2))));
@@ -3793,7 +4095,7 @@ async function selectBatch(deps, entityId, wm, meter) {
3793
4095
  async function runExtract(deps, ctx, batch) {
3794
4096
  const { entityId, trigger } = ctx;
3795
4097
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
3796
- const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext);
4098
+ const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
3797
4099
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
3798
4100
  const parsed = parseJsonResponse(text);
3799
4101
  const base = { entityId, operation: "librarian", trigger };
@@ -4264,7 +4566,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
4264
4566
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
4265
4567
  await deps.seedWatermark(entityId);
4266
4568
  const wm = await deps.getWatermark(entityId);
4267
- const sel = await selectBatch(deps, entityId, wm, ctx.meter);
4569
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
4268
4570
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
4269
4571
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
4270
4572
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -4394,7 +4696,7 @@ var formatSkipError = (err) => {
4394
4696
  return base;
4395
4697
  };
4396
4698
  var MaintenanceService = class {
4397
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
4699
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
4398
4700
  this.db = db;
4399
4701
  this.prefix = prefix;
4400
4702
  this.options = options;
@@ -4407,6 +4709,8 @@ var MaintenanceService = class {
4407
4709
  this.jobManager = jobManager;
4408
4710
  this.embeddingService = embeddingService;
4409
4711
  this.ontologyService = ontologyService;
4712
+ this.vectorRemoval = vectorRemoval;
4713
+ this.vectorRemovalRepo = vectorRemovalRepo;
4410
4714
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
4411
4715
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
4412
4716
  }
@@ -4420,11 +4724,14 @@ var MaintenanceService = class {
4420
4724
  this._validatePruneDuration(retainEventsFor, "retainEventsFor");
4421
4725
  const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
4422
4726
  this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
4727
+ const gate = removalGate(this.options);
4728
+ if (gate === "hook") this.embeddingService.validateDeletionTimeout();
4423
4729
  const now = Date.now();
4424
4730
  let syncedIds = [];
4425
4731
  let deletedEntries = 0;
4426
4732
  let deletedTasks = 0;
4427
4733
  let deletedEvents = 0;
4734
+ let prunePartial = null;
4428
4735
  if (pruneSupersededAfter !== null) {
4429
4736
  const expiredCutoff = now - pruneSupersededAfter * 864e5;
4430
4737
  const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
@@ -4433,55 +4740,89 @@ var MaintenanceService = class {
4433
4740
  await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
4434
4741
  });
4435
4742
  syncedIds = [...expiredIds];
4743
+ if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
4744
+ await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
4745
+ }
4436
4746
  }
4437
4747
  }
4438
4748
  if (retainSoftDeletedFor !== null) {
4439
4749
  const cutoff = now - retainSoftDeletedFor * 864e5;
4440
4750
  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;
4751
+ const prunableIds = entriesToDelete.map((r) => r.id);
4752
+ const vr = this.vectorRemoval;
4753
+ const vrRepo = this.vectorRemovalRepo;
4754
+ const ledgerOn = !!vr && !!vrRepo && await vr.ledgerPresent();
4755
+ let deletable = prunableIds;
4756
+ let removeLedger = false;
4757
+ let kept = [];
4758
+ let timedOut = false;
4759
+ let cause;
4760
+ let firstFailed;
4761
+ let failedOrder = [];
4762
+ if (ledgerOn && vr && vrRepo) {
4763
+ if (gate === "hook" && prunableIds.length > 0) {
4764
+ await this.db.withTransactionAsync(async (tx) => {
4765
+ await vrRepo.backstopEnqueue(entityId, prunableIds, now, tx);
4766
+ });
4767
+ }
4768
+ const result = prunableIds.length > 0 ? await vr.drain({ entityId, ids: prunableIds }) : { failedIds: [], timedOut: false, firstCause: void 0 };
4769
+ if (gate === "hook") {
4770
+ timedOut = result.timedOut;
4771
+ cause = result.firstCause;
4772
+ failedOrder = result.failedIds;
4773
+ } else if (gate === "force") {
4774
+ removeLedger = true;
4775
+ } else {
4776
+ removeLedger = !await vr.externalIndexInUse();
4450
4777
  }
4778
+ } else if (gate === "hook") {
4779
+ const r = await this.embeddingService.callRemovalHookEach(entityId, prunableIds);
4780
+ const failedSet = new Set(r.failed);
4781
+ kept = r.failed;
4782
+ deletable = prunableIds.filter((id) => !failedSet.has(id));
4783
+ timedOut = r.timedOut;
4784
+ cause = r.cause;
4785
+ firstFailed = kept[0];
4451
4786
  }
4452
- const succeededIds = succeeded.map((r) => r.id);
4453
- syncedIds = [...syncedIds, ...succeededIds];
4787
+ const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
4454
4788
  await this.db.withTransactionAsync(async (tx) => {
4455
- if (succeededIds.length > 0) {
4456
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, succeededIds, tx);
4789
+ if (hookLedger && vrRepo && prunableIds.length > 0) {
4790
+ const status = await vrRepo.statusFor(prunableIds, tx);
4791
+ deletable = prunableIds.filter((id) => status.get(id) !== "pending");
4792
+ kept = prunableIds.filter((id) => status.get(id) === "pending");
4793
+ }
4794
+ if (deletable.length > 0) {
4795
+ const deletedIds = [];
4796
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
4797
+ if (hookLedger) {
4798
+ const gone = new Set(deletedIds);
4799
+ const skipped = deletable.filter((id) => !gone.has(id));
4800
+ if (skipped.length > 0) {
4801
+ const after = await vrRepo.statusFor(skipped, tx);
4802
+ kept = [...kept, ...skipped.filter((id) => after.get(id) === "pending")];
4803
+ }
4804
+ deletable = deletedIds;
4805
+ }
4806
+ if (vrRepo && ledgerOn) {
4807
+ if (removeLedger) await vrRepo.deleteForFacts(entityId, deletable, tx, "all");
4808
+ else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
4809
+ }
4457
4810
  }
4458
4811
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
4459
4812
  });
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
- );
4813
+ if (hookLedger) {
4814
+ const keptSet = new Set(kept);
4815
+ firstFailed = failedOrder.find((id) => keptSet.has(id)) ?? kept[0];
4816
+ }
4817
+ syncedIds = [...syncedIds, ...deletable];
4818
+ if (kept.length > 0) {
4819
+ if (timedOut) {
4820
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("Deletion hook timed out") };
4821
+ } else if (cause === void 0) {
4822
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("external removal not confirmed") };
4823
+ } else {
4824
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: this._sanitizeRankerError(cause) };
4473
4825
  }
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
4826
  }
4486
4827
  }
4487
4828
  if (retainEventsFor !== null) {
@@ -4518,6 +4859,16 @@ var MaintenanceService = class {
4518
4859
  await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
4519
4860
  }
4520
4861
  await this.searchService.syncEntries(entityId, syncedIds);
4862
+ if (prunePartial) {
4863
+ throw new PrunePartialFailureError(
4864
+ deletedEntries,
4865
+ prunePartial.failedAt,
4866
+ prunePartial.remaining,
4867
+ prunePartial.cause,
4868
+ deletedTasks,
4869
+ deletedEvents
4870
+ );
4871
+ }
4521
4872
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
4522
4873
  } finally {
4523
4874
  this.jobManager.releaseLock("prune", entityId);
@@ -4622,6 +4973,7 @@ var MaintenanceService = class {
4622
4973
  }
4623
4974
  const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
4624
4975
  if (result.ok) embedded++;
4976
+ else if (result.kind === "fact_deleted") skipped++;
4625
4977
  else failed++;
4626
4978
  }
4627
4979
  if (embedded > 0) {
@@ -4652,6 +5004,7 @@ var MaintenanceService = class {
4652
5004
  let deletedTasks = 0;
4653
5005
  let deletedEvents = 0;
4654
5006
  const deletedEntryIds = [];
5007
+ const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
4655
5008
  await this.db.withTransactionAsync(async (tx) => {
4656
5009
  if (params.clearAll) {
4657
5010
  for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
@@ -4700,22 +5053,54 @@ var MaintenanceService = class {
4700
5053
  if (taskResult) deletedTasks++;
4701
5054
  deletedEntries += refResult;
4702
5055
  }
5056
+ if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
5057
+ await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
5058
+ }
4703
5059
  });
4704
5060
  const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
4705
5061
  await this.searchService.syncEntries(entityId, uniqueDeletedIds);
4706
- for (const factId of uniqueDeletedIds) {
5062
+ if (uniqueDeletedIds.length > 0) {
5063
+ const firstId = uniqueDeletedIds[0];
5064
+ const vr = this.vectorRemoval;
5065
+ const vrRepo = this.vectorRemovalRepo;
5066
+ let unconfirmed = [];
5067
+ let timedOut = false;
5068
+ let cause;
5069
+ let timedOutId;
4707
5070
  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}`);
5071
+ if (vr && vrRepo && ledgerOn) {
5072
+ const result = await vr.drain({ entityId, ids: uniqueDeletedIds });
5073
+ if (vr.gate() === "hook") {
5074
+ const status = await vrRepo.statusFor(uniqueDeletedIds);
5075
+ unconfirmed = uniqueDeletedIds.filter((id) => status.get(id) === "pending");
5076
+ timedOut = result.timedOut;
5077
+ timedOutId = result.timedOutId;
5078
+ cause = result.firstCause;
5079
+ }
5080
+ } else if (this.options.vectorRanker?.onEmbeddingPersisted && this.options.forceDeleteIgnoreRankerHook !== true) {
5081
+ const r = await this.embeddingService.callRemovalHookEach(entityId, uniqueDeletedIds);
5082
+ unconfirmed = r.failed;
5083
+ timedOut = r.timedOut;
5084
+ timedOutId = r.timedOutId;
5085
+ cause = r.cause;
4713
5086
  }
5087
+ } catch (hookErr) {
4714
5088
  const errMsg = hookErr?.message ?? "";
4715
5089
  if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
4716
- throw new Error(`forget(${entityId}/${factId}) failed: ${errMsg}`, { cause: hookErr });
5090
+ throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
4717
5091
  }
4718
- throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
5092
+ throw hookErr;
5093
+ }
5094
+ if (unconfirmed.length > 0) {
5095
+ const head = `forget(${entityId}/${(timedOut ? timedOutId : void 0) ?? unconfirmed[0]}) failed: `;
5096
+ const message = timedOut ? head + (cause?.message ?? "onEmbeddingPersisted timed out") : cause === void 0 ? head + "ANN cleanup not confirmed" : head + "ANN cleanup hook rejected";
5097
+ throw new WikiExternalDeletionError(message, {
5098
+ entityId,
5099
+ unconfirmedIds: unconfirmed.slice(0, 100),
5100
+ unconfirmedCount: unconfirmed.length,
5101
+ timedOut,
5102
+ cause: timedOut || cause === void 0 ? void 0 : this._sanitizeRankerError(cause)
5103
+ });
4719
5104
  }
4720
5105
  }
4721
5106
  if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
@@ -4724,6 +5109,22 @@ var MaintenanceService = class {
4724
5109
  this.jobManager.releaseLock("forget", entityId);
4725
5110
  }
4726
5111
  }
5112
+ /** Heal's post-commit removal delivery (spec §5.7). Never throws. */
5113
+ async deliverHealRemovals(entityId, ids, trigger) {
5114
+ if (this.vectorRemoval) {
5115
+ await this.vectorRemoval.deliverRemovals(entityId, ids, "heal", trigger);
5116
+ return;
5117
+ }
5118
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
5119
+ for (const factId of ids) {
5120
+ try {
5121
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
5122
+ } catch (hookErr) {
5123
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
5124
+ emitDiagnostic(this.options, { entityId, operation: "heal", trigger, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
5125
+ }
5126
+ }
5127
+ }
4727
5128
  /**
4728
5129
  * Whether forget() should soft-delete in source_ref_index (#316,
4729
5130
  * specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
@@ -4803,7 +5204,17 @@ var MaintenanceService = class {
4803
5204
  * A budget-stopped pass wrote nothing and must not move the watermark.
4804
5205
  */
4805
5206
  async runLibrarianPass(ctx) {
4806
- const result = await runLibrarianStrategy(this.librarianDeps(), ctx);
5207
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, ctx.entityId);
5208
+ if (diagnostic) {
5209
+ emitDiagnostic(this.options, {
5210
+ code: diagnostic.code,
5211
+ operation: "librarian",
5212
+ trigger: ctx.trigger,
5213
+ entityId: ctx.entityId,
5214
+ detail: diagnostic.detail
5215
+ });
5216
+ }
5217
+ const result = await runLibrarianStrategy(this.librarianDeps(), { ...ctx, guidance });
4807
5218
  if (result.processedThrough && !result.budgetStop) {
4808
5219
  await this.advanceLibrarianWatermark(ctx.entityId, result.processedThrough);
4809
5220
  }
@@ -4921,14 +5332,7 @@ var MaintenanceService = class {
4921
5332
  staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
4922
5333
  }
4923
5334
  });
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
- }
5335
+ await this.deliverHealRemovals(entityId, orphanedIds, trigger);
4932
5336
  const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
4933
5337
  const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
4934
5338
  if (healCandidates.length === 0 || keywordUnavailable) {
@@ -5117,14 +5521,7 @@ var MaintenanceService = class {
5117
5521
  ...insertedFacts.map((f) => f.id)
5118
5522
  ]));
5119
5523
  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
- }
5524
+ await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
5128
5525
  for (const fact of insertedFacts) {
5129
5526
  await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
5130
5527
  }