@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/index.js CHANGED
@@ -15,6 +15,147 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
15
15
  var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
16
16
  var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
17
17
 
18
+ // src/utils/diagnostics.ts
19
+ var SEVERITY = {
20
+ ingest_chunk_failed: "warn",
21
+ fact_rejected: "warn",
22
+ task_rejected: "warn",
23
+ fact_deduplicated: "info",
24
+ edge_dropped: "warn",
25
+ embedding_failed: "warn",
26
+ hook_failed: "warn",
27
+ background_job_failed: "error",
28
+ heal_skipped: "warn",
29
+ grounding_missing: "warn",
30
+ grounding_failed: "warn",
31
+ classification_low_confidence: "info",
32
+ classification_invalid: "warn",
33
+ llm_usage: "info",
34
+ librarian_gate: "info",
35
+ librarian_op_rejected: "warn",
36
+ contradicts_document: "warn",
37
+ resolve_failed: "warn",
38
+ read_budget: "info",
39
+ event_retention_held: "info",
40
+ event_created_at_clamped: "warn",
41
+ event_created_at_restamped: "info",
42
+ external_deletion_pending: "warn",
43
+ external_deletion_discarded: "warn",
44
+ guidance_too_long: "warn",
45
+ guidance_resolver_failed: "warn"
46
+ };
47
+ var MESSAGE = {
48
+ ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
49
+ fact_rejected: "An extracted fact failed validation and was not written.",
50
+ task_rejected: "An extracted task failed validation and was not written.",
51
+ fact_deduplicated: "An extracted fact duplicated an existing fact and was not written.",
52
+ edge_dropped: "An extracted edge could not be resolved against the ontology and was not written.",
53
+ embedding_failed: "A fact could not be embedded.",
54
+ hook_failed: "A host hook threw or rejected.",
55
+ background_job_failed: "A background maintenance job failed.",
56
+ heal_skipped: "Heal skipped a candidate fact, or the whole LLM pass when keyword search is unavailable.",
57
+ grounding_missing: "A fact carried no qualifying evidence and was stored as a draft.",
58
+ grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
59
+ classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
60
+ classification_invalid: "A classifier answer was invalid and was not applied.",
61
+ llm_usage: "An LLM call completed; token usage attached.",
62
+ librarian_gate: "Librarian gate outcome counts for one pass.",
63
+ librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
64
+ contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
65
+ resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
66
+ read_budget: "A read was packed to a token budget.",
67
+ event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
68
+ 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.",
69
+ 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.",
70
+ external_deletion_pending: "Removals owed to the external vector index are still pending.",
71
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
72
+ guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
73
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
74
+ };
75
+ var warnedNonFunction = /* @__PURE__ */ new WeakSet();
76
+ function copyDetail(detail) {
77
+ const copy = { ...detail };
78
+ if (detail.chunkIndexes) copy.chunkIndexes = detail.chunkIndexes.slice();
79
+ return copy;
80
+ }
81
+ function emitDiagnostic(options, input) {
82
+ const hook = options.onDiagnostic;
83
+ if (hook === void 0 || hook === null) return;
84
+ if (typeof hook !== "function") {
85
+ if (!warnedNonFunction.has(options)) {
86
+ warnedNonFunction.add(options);
87
+ console.warn("[WikiMemory] onDiagnostic is not a function; diagnostics are disabled.");
88
+ }
89
+ return;
90
+ }
91
+ const diagnostic = {
92
+ code: input.code,
93
+ severity: SEVERITY[input.code],
94
+ operation: input.operation,
95
+ trigger: input.trigger,
96
+ entityId: input.entityId,
97
+ at: Date.now(),
98
+ message: MESSAGE[input.code],
99
+ ...input.detail ? { detail: copyDetail(input.detail) } : {}
100
+ };
101
+ try {
102
+ const returned = hook(diagnostic);
103
+ if (returned !== void 0) {
104
+ Promise.resolve(returned).catch((err) => {
105
+ console.warn("[WikiMemory] onDiagnostic hook rejected:", err);
106
+ });
107
+ }
108
+ } catch (err) {
109
+ console.warn("[WikiMemory] onDiagnostic hook threw:", err);
110
+ }
111
+ }
112
+ var DiagnosticBuffer = class {
113
+ constructor() {
114
+ this.items = [];
115
+ }
116
+ push(input) {
117
+ this.items.push(input);
118
+ }
119
+ get size() {
120
+ return this.items.length;
121
+ }
122
+ flush(options) {
123
+ const pending = this.items;
124
+ this.items = [];
125
+ for (const input of pending) emitDiagnostic(options, input);
126
+ }
127
+ /**
128
+ * Emit only the buffered diagnostics whose code is in `codes` and discard
129
+ * the rest. The buffer is empty afterwards either way.
130
+ *
131
+ * For an operation that did real work before its write was rolled back:
132
+ * some buffered diagnostics describe that work and are still true, while
133
+ * others describe rows that no longer exist (anything carrying a `factId`
134
+ * minted inside the aborted transaction). `flush` would emit both and
135
+ * `discard` would drop both; this emits the first set only.
136
+ */
137
+ flushOnly(options, codes) {
138
+ const pending = this.items;
139
+ this.items = [];
140
+ for (const input of pending) {
141
+ if (codes.includes(input.code)) emitDiagnostic(options, input);
142
+ }
143
+ }
144
+ discard() {
145
+ this.items = [];
146
+ }
147
+ };
148
+ function edgeDropDiagnostic(drop, ctx) {
149
+ const detail = { reason: drop.reason };
150
+ const factId = ctx.factId ?? drop.sourceId;
151
+ if (factId) detail.factId = factId;
152
+ if (drop.edgeType) detail.edgeType = drop.edgeType;
153
+ if (drop.sourceNodeType) detail.sourceNodeType = drop.sourceNodeType;
154
+ if (drop.targetNodeType) detail.targetNodeType = drop.targetNodeType;
155
+ if (ctx.sourceRef) detail.sourceRef = ctx.sourceRef;
156
+ return { code: "edge_dropped", operation: ctx.operation, trigger: ctx.trigger, entityId: ctx.entityId, detail };
157
+ }
158
+
18
159
  // src/repositories/rowMappers.ts
19
160
  function parseJsonArray(s, fallback) {
20
161
  if (Array.isArray(s)) return s;
@@ -103,6 +244,17 @@ var WikiBusyError = class extends Error {
103
244
  this.entityId = entityId;
104
245
  }
105
246
  };
247
+ var WikiExternalDeletionError = class extends Error {
248
+ constructor(message, params) {
249
+ super(message, params.cause ? { cause: params.cause } : void 0);
250
+ this.code = "WIKI_EXTERNAL_DELETION";
251
+ this.name = "WikiExternalDeletionError";
252
+ this.entityId = params.entityId;
253
+ this.unconfirmedIds = params.unconfirmedIds;
254
+ this.unconfirmedCount = params.unconfirmedCount;
255
+ this.timedOut = params.timedOut;
256
+ }
257
+ };
106
258
  var WikiDuplicateHashError = class extends Error {
107
259
  constructor(params) {
108
260
  super(`Duplicate source hash for entity ${params.entityId}; another ref already holds this content`);
@@ -603,14 +755,14 @@ function chunkText(input, maxChunkLength, overlap) {
603
755
  if (!Number.isInteger(overlap) || overlap < 0 || overlap >= maxChunkLength) {
604
756
  throw new Error("overlap must be a non-negative integer < maxChunkLength");
605
757
  }
606
- const chunks = [];
758
+ const chunks2 = [];
607
759
  let truncated = false;
608
760
  let cursor = 0;
609
761
  const halfMax = Math.floor(maxChunkLength / 2);
610
762
  while (cursor < text.length) {
611
763
  const remaining = text.length - cursor;
612
764
  if (remaining <= maxChunkLength) {
613
- chunks.push(safeSlice(text, cursor, text.length));
765
+ chunks2.push(safeSlice(text, cursor, text.length));
614
766
  break;
615
767
  }
616
768
  const windowEnd = cursor + maxChunkLength;
@@ -642,11 +794,11 @@ function chunkText(input, maxChunkLength, overlap) {
642
794
  truncated = true;
643
795
  splitPoint = windowEnd;
644
796
  }
645
- chunks.push(safeSlice(text, cursor, splitPoint));
797
+ chunks2.push(safeSlice(text, cursor, splitPoint));
646
798
  const next = Math.max(splitPoint - overlap, cursor + 1);
647
799
  cursor = next;
648
800
  }
649
- return { chunks, truncated };
801
+ return { chunks: chunks2, truncated };
650
802
  }
651
803
  async function withConcurrency(tasks, limit) {
652
804
  const results = new Array(tasks.length);
@@ -902,8 +1054,83 @@ async function setupDatabase(db, prefix) {
902
1054
  CREATE INDEX IF NOT EXISTS ${prefix}outbox_created_at
903
1055
  ON ${prefix}outbox (created_at);
904
1056
  `);
1057
+ await db.execAsync(`
1058
+ CREATE TABLE IF NOT EXISTS ${prefix}vector_removals (
1059
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
1060
+ entity_id TEXT NOT NULL,
1061
+ fact_id TEXT NOT NULL UNIQUE,
1062
+ enqueued_at INTEGER NOT NULL,
1063
+ attempts INTEGER NOT NULL DEFAULT 0,
1064
+ last_attempt_at INTEGER,
1065
+ confirmed_at INTEGER
1066
+ );
1067
+ CREATE INDEX IF NOT EXISTS ${prefix}vector_removals_pending
1068
+ ON ${prefix}vector_removals (entity_id, attempts, seq) WHERE confirmed_at IS NULL;
1069
+
1070
+ CREATE TRIGGER IF NOT EXISTS ${prefix}vector_removals_enqueue
1071
+ AFTER UPDATE OF deleted_at ON ${prefix}entries
1072
+ WHEN OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL
1073
+ BEGIN
1074
+ -- DELETE then INSERT, not INSERT OR REPLACE: an outer UPSERT's conflict
1075
+ -- handling would override OR REPLACE and abort on fact_id (spec rev 5).
1076
+ DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
1077
+ INSERT INTO ${prefix}vector_removals (entity_id, fact_id, enqueued_at)
1078
+ VALUES (NEW.entity_id, NEW.id, CAST(strftime('%s','now') AS INTEGER) * 1000);
1079
+ END;
1080
+
1081
+ -- A hard delete outside prune (host SQL, an older engine after a
1082
+ -- downgrade). A live fact is owed only where an external index was in use;
1083
+ -- a soft-deleted one drops the rows nothing can owe (spec rev 5).
1084
+ CREATE TRIGGER IF NOT EXISTS ${prefix}vector_removals_hard_delete
1085
+ AFTER DELETE ON ${prefix}entries
1086
+ BEGIN
1087
+ DELETE FROM ${prefix}vector_removals
1088
+ WHERE fact_id = OLD.id
1089
+ AND (OLD.deleted_at IS NULL
1090
+ OR confirmed_at IS NOT NULL
1091
+ OR NOT EXISTS (SELECT 1 FROM ${prefix}meta WHERE key = 'external_index_in_use' AND value = '1'));
1092
+ INSERT INTO ${prefix}vector_removals (entity_id, fact_id, enqueued_at)
1093
+ SELECT OLD.entity_id, OLD.id, CAST(strftime('%s','now') AS INTEGER) * 1000
1094
+ WHERE OLD.deleted_at IS NULL
1095
+ AND EXISTS (SELECT 1 FROM ${prefix}meta WHERE key = 'external_index_in_use' AND value = '1');
1096
+ END;
1097
+ `);
905
1098
  await createOkfV02IndexesIfColumnsExist(db, prefix);
906
1099
  await createTemporalIndexesIfColumnsExist(db, prefix);
1100
+ await createResurrectTrigger(db, prefix);
1101
+ }
1102
+ var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
1103
+ function resurrectLevel(sql) {
1104
+ if (sql.includes("embedding_failed_at")) return 2;
1105
+ return sql.includes("embedding_blob") ? 1 : 0;
1106
+ }
1107
+ async function createResurrectTrigger(db, prefix) {
1108
+ const name = `${prefix}vector_removals_resurrect`;
1109
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
1110
+ const names = new Set(cols.map((c) => c.name));
1111
+ const want = !(names.has("embedding_blob") && names.has("embedding")) ? 0 : EMBED_MARKER_COLUMNS.every((c) => names.has(c)) ? 2 : 1;
1112
+ const existing = await db.getFirstAsync(
1113
+ `SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?`,
1114
+ [name]
1115
+ );
1116
+ if (existing) {
1117
+ if (resurrectLevel(existing.sql ?? "") >= want) return;
1118
+ await db.execAsync(`DROP TRIGGER IF EXISTS ${name};`);
1119
+ }
1120
+ const clearVector = want === 0 ? "" : `
1121
+ UPDATE ${prefix}entries
1122
+ SET embedding_blob = NULL, embedding = NULL${want === 2 ? `,
1123
+ embedding_failed_at = NULL, embedding_failure_kind = NULL, embedding_attempts = 0` : ""}
1124
+ WHERE id = NEW.id
1125
+ AND EXISTS (SELECT 1 FROM ${prefix}vector_removals WHERE fact_id = NEW.id AND confirmed_at IS NOT NULL);`;
1126
+ await db.execAsync(`
1127
+ CREATE TRIGGER IF NOT EXISTS ${name}
1128
+ AFTER UPDATE OF deleted_at ON ${prefix}entries
1129
+ WHEN OLD.deleted_at IS NOT NULL AND NEW.deleted_at IS NULL
1130
+ BEGIN${clearVector}
1131
+ DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
1132
+ END;
1133
+ `);
907
1134
  }
908
1135
  async function createOkfV02IndexesIfColumnsExist(db, prefix) {
909
1136
  for (const table of ["entries", "tasks"]) {
@@ -1114,6 +1341,7 @@ var MIGRATIONS = [
1114
1341
  `ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`
1115
1342
  );
1116
1343
  }
1344
+ await createResurrectTrigger(db, prefix);
1117
1345
  }
1118
1346
  },
1119
1347
  {
@@ -1307,6 +1535,7 @@ var MIGRATIONS = [
1307
1535
  for (const [name, sql] of adds) {
1308
1536
  if (!existing.has(name)) await db.execAsync(sql);
1309
1537
  }
1538
+ await createResurrectTrigger(db, prefix);
1310
1539
  }
1311
1540
  },
1312
1541
  {
@@ -2211,20 +2440,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2211
2440
  * Used by runPrune(). Returns total number of deleted rows.
2212
2441
  * `tx` is REQUIRED so outbox deletion events are staged atomically.
2213
2442
  */
2214
- async bulkDeletePruned(entityId, cutoff, ids, tx) {
2443
+ async bulkDeletePruned(entityId, cutoff, ids, tx, opts = {}) {
2215
2444
  const executor = this.getExecutor(tx);
2445
+ const guard = opts.keepUnconfirmedRemovals ? ` AND NOT EXISTS (SELECT 1 FROM ${this.prefix}vector_removals v WHERE v.fact_id = ${this.prefix}entries.id AND v.confirmed_at IS NULL)` : "";
2216
2446
  let totalChanges = 0;
2217
2447
  const chunkSize = 500;
2218
2448
  for (let i = 0; i < ids.length; i += chunkSize) {
2219
2449
  const chunk = ids.slice(i, i + chunkSize);
2220
2450
  const placeholders = chunk.map(() => "?").join(",");
2221
- const result = await executor.runAsync(
2222
- `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})`,
2451
+ const deleted = (await executor.getAllAsync(
2452
+ `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})${guard} RETURNING id`,
2223
2453
  [entityId, cutoff, ...chunk]
2224
- );
2225
- totalChanges += result.changes;
2226
- if (result.changes > 0) {
2227
- for (const id of chunk) {
2454
+ )).map((r) => r.id);
2455
+ totalChanges += deleted.length;
2456
+ opts.deletedIds?.push(...deleted);
2457
+ if (deleted.length > 0) {
2458
+ for (const id of deleted) {
2228
2459
  await this.outbox.push({
2229
2460
  entityId,
2230
2461
  tableName: "entries",
@@ -2331,11 +2562,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2331
2562
  const executor = this.getExecutor(tx);
2332
2563
  const now = Date.now();
2333
2564
  const placeholders = ids.map(() => "?").join(",");
2334
- await executor.runAsync(
2335
- `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ?`,
2565
+ const updated = await executor.getAllAsync(
2566
+ `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL RETURNING id`,
2336
2567
  [now, now, ...ids, entityId]
2337
2568
  );
2338
- for (const id of ids) {
2569
+ for (const { id } of updated) {
2339
2570
  await this.outbox.push({
2340
2571
  entityId,
2341
2572
  tableName: "entries",
@@ -2495,18 +2726,20 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2495
2726
  }
2496
2727
  return rows;
2497
2728
  }
2729
+ /** Returns `changes: 0` when the row is soft-deleted or gone (spec durable-vector-removal §5.7, G10). */
2498
2730
  async updateEmbeddingBlob(id, blob, tx) {
2499
2731
  const executor = this.getExecutor(tx);
2500
- await executor.runAsync(
2732
+ const r = await executor.runAsync(
2501
2733
  `UPDATE ${this.prefix}entries
2502
2734
  SET embedding_blob = ?,
2503
2735
  embedding = NULL,
2504
2736
  embedding_failed_at = NULL,
2505
2737
  embedding_failure_kind = NULL,
2506
2738
  embedding_attempts = 0
2507
- WHERE id = ?`,
2739
+ WHERE id = ? AND deleted_at IS NULL`,
2508
2740
  [blob, id]
2509
2741
  );
2742
+ return { changes: r?.changes ?? 0 };
2510
2743
  }
2511
2744
  /**
2512
2745
  * Record a failed embedding attempt. Deliberately does NOT touch updated_at
@@ -5981,145 +6214,20 @@ function groundingOutcome(verdict, now) {
5981
6214
  };
5982
6215
  }
5983
6216
 
5984
- // src/utils/diagnostics.ts
5985
- var SEVERITY = {
5986
- ingest_chunk_failed: "warn",
5987
- fact_rejected: "warn",
5988
- task_rejected: "warn",
5989
- fact_deduplicated: "info",
5990
- edge_dropped: "warn",
5991
- embedding_failed: "warn",
5992
- hook_failed: "warn",
5993
- background_job_failed: "error",
5994
- heal_skipped: "warn",
5995
- grounding_missing: "warn",
5996
- grounding_failed: "warn",
5997
- classification_low_confidence: "info",
5998
- classification_invalid: "warn",
5999
- llm_usage: "info",
6000
- librarian_gate: "info",
6001
- librarian_op_rejected: "warn",
6002
- contradicts_document: "warn",
6003
- resolve_failed: "warn",
6004
- read_budget: "info",
6005
- event_retention_held: "info",
6006
- event_created_at_clamped: "warn",
6007
- event_created_at_restamped: "info"
6008
- };
6009
- var MESSAGE = {
6010
- ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
6011
- fact_rejected: "An extracted fact failed validation and was not written.",
6012
- task_rejected: "An extracted task failed validation and was not written.",
6013
- fact_deduplicated: "An extracted fact duplicated an existing fact and was not written.",
6014
- edge_dropped: "An extracted edge could not be resolved against the ontology and was not written.",
6015
- embedding_failed: "A fact could not be embedded.",
6016
- hook_failed: "A host hook threw or rejected.",
6017
- background_job_failed: "A background maintenance job failed.",
6018
- heal_skipped: "Heal skipped a candidate fact, or the whole LLM pass when keyword search is unavailable.",
6019
- grounding_missing: "A fact carried no qualifying evidence and was stored as a draft.",
6020
- grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
6021
- classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
6022
- classification_invalid: "A classifier answer was invalid and was not applied.",
6023
- llm_usage: "An LLM call completed; token usage attached.",
6024
- librarian_gate: "Librarian gate outcome counts for one pass.",
6025
- librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
6026
- contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
6027
- resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
6028
- read_budget: "A read was packed to a token budget.",
6029
- event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
6030
- 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.",
6031
- 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."
6032
- };
6033
- var warnedNonFunction = /* @__PURE__ */ new WeakSet();
6034
- function copyDetail(detail) {
6035
- const copy = { ...detail };
6036
- if (detail.chunkIndexes) copy.chunkIndexes = detail.chunkIndexes.slice();
6037
- return copy;
6217
+ // src/prompts.ts
6218
+ var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
6219
+ var GUIDANCE_MAX_CHARS = 2e3;
6220
+ function guidanceSection(guidance) {
6221
+ return `--- Host guidance ---
6222
+ ${guidance}
6223
+ --- End host guidance ---
6224
+ ${LEAVE_OUT_RULE_SENTENCE}`;
6038
6225
  }
6039
- function emitDiagnostic(options, input) {
6040
- const hook = options.onDiagnostic;
6041
- if (hook === void 0 || hook === null) return;
6042
- if (typeof hook !== "function") {
6043
- if (!warnedNonFunction.has(options)) {
6044
- warnedNonFunction.add(options);
6045
- console.warn("[WikiMemory] onDiagnostic is not a function; diagnostics are disabled.");
6046
- }
6047
- return;
6048
- }
6049
- const diagnostic = {
6050
- code: input.code,
6051
- severity: SEVERITY[input.code],
6052
- operation: input.operation,
6053
- trigger: input.trigger,
6054
- entityId: input.entityId,
6055
- at: Date.now(),
6056
- message: MESSAGE[input.code],
6057
- ...input.detail ? { detail: copyDetail(input.detail) } : {}
6058
- };
6059
- try {
6060
- const returned = hook(diagnostic);
6061
- if (returned !== void 0) {
6062
- Promise.resolve(returned).catch((err) => {
6063
- console.warn("[WikiMemory] onDiagnostic hook rejected:", err);
6064
- });
6065
- }
6066
- } catch (err) {
6067
- console.warn("[WikiMemory] onDiagnostic hook threw:", err);
6068
- }
6069
- }
6070
- var DiagnosticBuffer = class {
6071
- constructor() {
6072
- this.items = [];
6073
- }
6074
- push(input) {
6075
- this.items.push(input);
6076
- }
6077
- get size() {
6078
- return this.items.length;
6079
- }
6080
- flush(options) {
6081
- const pending = this.items;
6082
- this.items = [];
6083
- for (const input of pending) emitDiagnostic(options, input);
6084
- }
6085
- /**
6086
- * Emit only the buffered diagnostics whose code is in `codes` and discard
6087
- * the rest. The buffer is empty afterwards either way.
6088
- *
6089
- * For an operation that did real work before its write was rolled back:
6090
- * some buffered diagnostics describe that work and are still true, while
6091
- * others describe rows that no longer exist (anything carrying a `factId`
6092
- * minted inside the aborted transaction). `flush` would emit both and
6093
- * `discard` would drop both; this emits the first set only.
6094
- */
6095
- flushOnly(options, codes) {
6096
- const pending = this.items;
6097
- this.items = [];
6098
- for (const input of pending) {
6099
- if (codes.includes(input.code)) emitDiagnostic(options, input);
6100
- }
6101
- }
6102
- discard() {
6103
- this.items = [];
6104
- }
6105
- };
6106
- function edgeDropDiagnostic(drop, ctx) {
6107
- const detail = { reason: drop.reason };
6108
- const factId = ctx.factId ?? drop.sourceId;
6109
- if (factId) detail.factId = factId;
6110
- if (drop.edgeType) detail.edgeType = drop.edgeType;
6111
- if (drop.sourceNodeType) detail.sourceNodeType = drop.sourceNodeType;
6112
- if (drop.targetNodeType) detail.targetNodeType = drop.targetNodeType;
6113
- if (ctx.sourceRef) detail.sourceRef = ctx.sourceRef;
6114
- return { code: "edge_dropped", operation: ctx.operation, trigger: ctx.trigger, entityId: ctx.entityId, detail };
6115
- }
6116
-
6117
- // src/prompts.ts
6118
- 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.
6119
- Return ONLY a valid JSON object matching this schema:
6120
- {
6121
- "facts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }],
6122
- "tasks": [{ "description": "string", "priority": "number (0-10)" }]
6226
+ 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.
6227
+ Return ONLY a valid JSON object matching this schema:
6228
+ {
6229
+ "facts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }],
6230
+ "tasks": [{ "description": "string", "priority": "number (0-10)" }]
6123
6231
  }
6124
6232
  Keep facts concise. Do not return markdown, just raw JSON.`;
6125
6233
  var HEAL_SYSTEM_PROMPT = `You are a memory grooming agent. Your job is to review a full dump of facts and recent events to resolve contradictions, downgrade stale claims, and flag obsolete facts for deletion.
@@ -6184,6 +6292,64 @@ var PromptService = class {
6184
6292
  this.globalOverrides = globalOverrides;
6185
6293
  this.grounding = grounding;
6186
6294
  }
6295
+ /**
6296
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
6297
+ * or call — default `config.prompts.guidance`, per-entity
6298
+ * `config.librarian.guidanceForEntity` winning when it returns a
6299
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
6300
+ * returns a thenable (its rejection is swallowed with a no-op handler;
6301
+ * a throwing `then` counts too), or returns any non-string value is
6302
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
6303
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
6304
+ * Emits nothing itself; the caller emits, immediately at resolution.
6305
+ */
6306
+ static resolveGuidance(config, entityId) {
6307
+ let source = null;
6308
+ let effective;
6309
+ let resolverDiagnostic;
6310
+ const defaultValue = config?.prompts?.guidance;
6311
+ const resolver = config?.librarian?.guidanceForEntity;
6312
+ let entityValue;
6313
+ if (resolver) {
6314
+ try {
6315
+ entityValue = resolver(entityId);
6316
+ if (entityValue === void 0) {
6317
+ } else if (typeof entityValue === "string") {
6318
+ if (entityValue.trim() !== "") {
6319
+ source = "per_entity";
6320
+ effective = entityValue;
6321
+ }
6322
+ } else {
6323
+ try {
6324
+ entityValue?.then?.(() => void 0, () => void 0);
6325
+ } catch {
6326
+ }
6327
+ resolverDiagnostic = {
6328
+ code: "guidance_resolver_failed",
6329
+ detail: { reason: "non_string" }
6330
+ };
6331
+ }
6332
+ } catch {
6333
+ resolverDiagnostic = { code: "guidance_resolver_failed", detail: { reason: "threw" } };
6334
+ }
6335
+ }
6336
+ if (source === null && defaultValue !== void 0 && defaultValue.trim() !== "") {
6337
+ source = "default";
6338
+ effective = defaultValue;
6339
+ }
6340
+ if (source === null || effective === void 0) {
6341
+ return resolverDiagnostic ? { diagnostic: resolverDiagnostic } : {};
6342
+ }
6343
+ if (effective.length > GUIDANCE_MAX_CHARS) {
6344
+ return {
6345
+ diagnostic: {
6346
+ code: "guidance_too_long",
6347
+ detail: { guidanceLength: effective.length, guidanceSource: source }
6348
+ }
6349
+ };
6350
+ }
6351
+ return resolverDiagnostic ? { guidance: effective, diagnostic: resolverDiagnostic } : { guidance: effective };
6352
+ }
6187
6353
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
6188
6354
  groundingFor(writer) {
6189
6355
  return this.grounding?.writers.has(writer) ? this.grounding : null;
@@ -6194,6 +6360,19 @@ var PromptService = class {
6194
6360
  return cfg ? `${systemPrompt}
6195
6361
 
6196
6362
  ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
6363
+ }
6364
+ /**
6365
+ * Specs/librarian-guidance: append the marked guidance section (with the
6366
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
6367
+ * ontology, immediately before grounding. The guidance text is never
6368
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
6369
+ * template branch or be expanded with data. No-op on empty input.
6370
+ */
6371
+ appendGuidance(systemPrompt, guidance) {
6372
+ if (!guidance) return systemPrompt;
6373
+ return `${systemPrompt}
6374
+
6375
+ ${guidanceSection(guidance)}`;
6197
6376
  }
6198
6377
  hydrate(template, variables) {
6199
6378
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, key) => {
@@ -6230,31 +6409,31 @@ ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
6230
6409
 
6231
6410
  ${ctx.ontologyModeInstructions}`;
6232
6411
  }
6233
- buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext) {
6412
+ buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext, guidance) {
6234
6413
  const template = runtimeOverride ?? this.globalOverrides?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT;
6235
6414
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
6236
6415
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
6237
6416
  return {
6238
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), "ingest"),
6417
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
6239
6418
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
6240
6419
  ${documentChunk}`
6241
6420
  };
6242
6421
  }
6243
6422
  return {
6244
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "ingest"),
6423
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
6245
6424
  userPrompt: `Document Chunk:
6246
6425
  ${documentChunk}`
6247
6426
  };
6248
6427
  }
6249
- buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext) {
6250
- const template = runtimeOverride ?? this.globalOverrides?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT;
6428
+ buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext, guidance) {
6429
+ const template = runtimeOverride ?? LIBRARIAN_SYSTEM_PROMPT;
6251
6430
  const hasEvents = /\{\{\s*events\s*\}\}/.test(template);
6252
6431
  const hasCurrentFacts = /\{\{\s*currentFacts\s*\}\}/.test(template);
6253
6432
  const eventsShown = hasEvents || !hasCurrentFacts;
6254
6433
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
6255
6434
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
6256
6435
  return {
6257
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), "librarian"),
6436
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
6258
6437
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
6259
6438
  ${JSON.stringify(events, null, 2)}
6260
6439
 
@@ -6264,7 +6443,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
6264
6443
  };
6265
6444
  }
6266
6445
  return {
6267
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "librarian"),
6446
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
6268
6447
  userPrompt: `Events:
6269
6448
  ${JSON.stringify(events, null, 2)}
6270
6449
 
@@ -6367,11 +6546,11 @@ ${JSON.stringify(facts, null, 2)}`
6367
6546
  };
6368
6547
  }
6369
6548
  /** Ops extract (spec §5.2): events only — no existing facts. */
6370
- buildOpsExtractPrompt(events, ontologyContext) {
6549
+ buildOpsExtractPrompt(events, ontologyContext, guidance) {
6371
6550
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
6372
6551
  const grounding = this.groundingFor("librarian");
6373
6552
  return {
6374
- systemPrompt: this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian"),
6553
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
6375
6554
  userPrompt: `Events:
6376
6555
  ${lines.join("\n")}`,
6377
6556
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
@@ -6388,11 +6567,11 @@ ${JSON.stringify({ items })}` };
6388
6567
  * placeholders and leaves data placeholders verbatim; heal never receives
6389
6568
  * ontology context, matching `buildHealPrompt`.
6390
6569
  */
6391
- buildInstructionTemplates(ontologyContext, librarianStrategy) {
6570
+ buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
6392
6571
  const o = this.globalOverrides;
6393
6572
  return {
6394
- ingest: this.appendGrounding(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), "ingest"),
6395
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian") : this.appendGrounding(this.buildSystemPrompt(o?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), "librarian"),
6573
+ ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
6574
+ 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"),
6396
6575
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
6397
6576
  ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
6398
6577
  };
@@ -6541,7 +6720,7 @@ function zeroChunkResult(duplicateOf) {
6541
6720
  return result;
6542
6721
  }
6543
6722
  var IngestionService = class {
6544
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
6723
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
6545
6724
  this.db = db;
6546
6725
  this.prefix = prefix;
6547
6726
  this.options = options;
@@ -6553,6 +6732,7 @@ var IngestionService = class {
6553
6732
  this.jobManager = jobManager;
6554
6733
  this.embeddingService = embeddingService;
6555
6734
  this.ontologyService = ontologyService;
6735
+ this.vectorRemoval = vectorRemoval;
6556
6736
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
6557
6737
  }
6558
6738
  async ingestDocument(entityId, params, opts) {
@@ -6583,16 +6763,27 @@ var IngestionService = class {
6583
6763
  return zeroChunkResult(canonical);
6584
6764
  }
6585
6765
  }
6586
- const { chunks, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
6587
- if (chunks.length === 0) return zeroChunkResult();
6766
+ const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
6767
+ if (chunks2.length === 0) return zeroChunkResult();
6588
6768
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
6769
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
6770
+ if (diagnostic) {
6771
+ emitDiagnostic(this.options, {
6772
+ code: diagnostic.code,
6773
+ operation: "ingest",
6774
+ trigger: "call",
6775
+ entityId,
6776
+ detail: diagnostic.detail
6777
+ });
6778
+ }
6589
6779
  const ingestGrounding = this.promptService.groundingFor("ingest");
6590
6780
  const chunkResults = await withConcurrency(
6591
- chunks.map((chunk, chunkIndex) => async () => {
6781
+ chunks2.map((chunk, chunkIndex) => async () => {
6592
6782
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
6593
6783
  chunk,
6594
6784
  params.promptOverride,
6595
- ontologyContext
6785
+ ontologyContext,
6786
+ guidance
6596
6787
  );
6597
6788
  try {
6598
6789
  const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
@@ -6646,7 +6837,7 @@ var IngestionService = class {
6646
6837
  position: null,
6647
6838
  message: safeErrorToString(e)
6648
6839
  };
6649
- const total = chunks.length;
6840
+ const total = chunks2.length;
6650
6841
  const tags = [];
6651
6842
  if (failure.tier) tags.push(`tier=${failure.tier}`);
6652
6843
  if (failure.position !== null) tags.push(`position=${failure.position}`);
@@ -6723,11 +6914,11 @@ var IngestionService = class {
6723
6914
  }
6724
6915
  });
6725
6916
  }
6726
- if (failedChunks === chunks.length) {
6917
+ if (failedChunks === chunks2.length) {
6727
6918
  throw new WikiIngestEmptyError({
6728
6919
  parseFailures: failures,
6729
6920
  sourceRef,
6730
- chunks: chunks.length
6921
+ chunks: chunks2.length
6731
6922
  });
6732
6923
  }
6733
6924
  const insertedFacts = [];
@@ -6765,18 +6956,22 @@ var IngestionService = class {
6765
6956
  );
6766
6957
  if (failedChunks === 0) {
6767
6958
  const uniqueDeletedSourceFactIds = Array.from(new Set(deletedSourceFactIds));
6768
- for (const factId of uniqueDeletedSourceFactIds) {
6769
- try {
6770
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
6771
- } catch (hookErr) {
6772
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
6773
- emitDiagnostic(this.options, {
6774
- entityId,
6775
- operation: "ingest",
6776
- trigger: "call",
6777
- code: "hook_failed",
6778
- detail: { factId, reason: "on_embedding_persisted" }
6779
- });
6959
+ if (this.vectorRemoval) {
6960
+ await this.vectorRemoval.deliverRemovals(entityId, uniqueDeletedSourceFactIds, "ingest", "call");
6961
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
6962
+ for (const factId of uniqueDeletedSourceFactIds) {
6963
+ try {
6964
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
6965
+ } catch (hookErr) {
6966
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
6967
+ emitDiagnostic(this.options, {
6968
+ entityId,
6969
+ operation: "ingest",
6970
+ trigger: "call",
6971
+ code: "hook_failed",
6972
+ detail: { factId, reason: "on_embedding_persisted" }
6973
+ });
6974
+ }
6780
6975
  }
6781
6976
  }
6782
6977
  }
@@ -6786,7 +6981,7 @@ var IngestionService = class {
6786
6981
  this.searchService.evictCache(entityId);
6787
6982
  const result = {
6788
6983
  truncated,
6789
- chunks: chunks.length,
6984
+ chunks: chunks2.length,
6790
6985
  ingestedChunks,
6791
6986
  failedChunks
6792
6987
  };
@@ -7227,9 +7422,9 @@ function changedDefaultWarnings(config) {
7227
7422
  "[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
7228
7423
  );
7229
7424
  }
7230
- if (config?.prompts?.librarianSystemPrompt !== void 0 && config?.librarian?.strategy === void 0) {
7425
+ if (config?.prompts?.librarianSystemPrompt !== void 0) {
7231
7426
  warnings.push(
7232
- "[core-llm-wiki] `prompts.librarianSystemPrompt` is set, but `librarian.strategy` now defaults to 'ops', which does not use it. Set `librarian: { strategy: 'legacy' }` to keep the override."
7427
+ "[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
7233
7428
  );
7234
7429
  }
7235
7430
  if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
@@ -7248,6 +7443,543 @@ function warnChangedDefaultsOnce(config) {
7248
7443
  }
7249
7444
  }
7250
7445
 
7446
+ // src/repositories/VectorRemovalRepository.ts
7447
+ var CHUNK2 = 500;
7448
+ function removalBackoffMs(attempts) {
7449
+ return Math.min(2 ** attempts, 3600) * 1e3;
7450
+ }
7451
+ function chunks(xs, n) {
7452
+ const out = [];
7453
+ for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n));
7454
+ return out;
7455
+ }
7456
+ var marks = (n) => new Array(n).fill("?").join(",");
7457
+ var VectorRemovalRepository = class extends BaseRepository {
7458
+ /** Name of the ledger table. */
7459
+ get ledgerTable() {
7460
+ return `${this.prefix}vector_removals`;
7461
+ }
7462
+ /** Whether `factId` exists and is not soft-deleted. */
7463
+ async isLive(factId) {
7464
+ const row = await this.db.getFirstAsync(
7465
+ `SELECT 1 AS x FROM ${this.prefix}entries WHERE id = ? AND deleted_at IS NULL`,
7466
+ [factId]
7467
+ );
7468
+ return !!row;
7469
+ }
7470
+ /**
7471
+ * Owe the host a removal for `factId` unless a live row exists (a missing row
7472
+ * counts as not live). The liveness test is part of the write, so it is
7473
+ * atomic. Returns whether a row was enqueued.
7474
+ */
7475
+ async enqueueIfNotLive(entityId, factId, now) {
7476
+ return this.db.withTransactionAsync(async (tx) => {
7477
+ const r = await tx.runAsync(
7478
+ `INSERT OR REPLACE INTO ${this.prefix}vector_removals (entity_id, fact_id, enqueued_at)
7479
+ SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM ${this.prefix}entries WHERE id = ? AND deleted_at IS NULL)`,
7480
+ [entityId, factId, now, factId]
7481
+ );
7482
+ return (r?.changes ?? 0) > 0;
7483
+ });
7484
+ }
7485
+ /** Unconfirmed rows after `cursor`, ordered by (attempts, seq). */
7486
+ async readPage(scope, cursor, limit, tx) {
7487
+ const executor = this.getExecutor(tx);
7488
+ const t = `${this.prefix}vector_removals`;
7489
+ const where = [
7490
+ "v.confirmed_at IS NULL",
7491
+ "v.seq <= ?",
7492
+ "(v.attempts > ? OR (v.attempts = ? AND v.seq > ?))"
7493
+ ];
7494
+ const args = [cursor.maxSeq, cursor.attempts, cursor.attempts, cursor.seq];
7495
+ if (scope.entityId !== void 0) {
7496
+ where.push(scope.ids !== void 0 ? "+v.entity_id = ?" : "v.entity_id = ?");
7497
+ args.push(scope.entityId);
7498
+ }
7499
+ if (scope.ids !== void 0) {
7500
+ if (scope.ids.length === 0) return [];
7501
+ where.push(`v.fact_id IN (${marks(scope.ids.length)})`);
7502
+ args.push(...scope.ids);
7503
+ }
7504
+ args.push(limit);
7505
+ return executor.getAllAsync(
7506
+ `SELECT v.seq AS seq, v.entity_id AS entity_id, v.fact_id AS fact_id,
7507
+ v.attempts AS attempts, v.last_attempt_at AS last_attempt_at,
7508
+ CASE WHEN e.id IS NULL THEN 'gone'
7509
+ WHEN e.deleted_at IS NULL THEN 'live'
7510
+ ELSE 'deleted' END AS fact_state
7511
+ FROM ${t} v
7512
+ LEFT JOIN ${this.prefix}entries e ON e.id = v.fact_id
7513
+ WHERE ${where.join(" AND ")}
7514
+ ORDER BY v.attempts, v.seq
7515
+ LIMIT ?`,
7516
+ args
7517
+ );
7518
+ }
7519
+ async maxSeq(tx) {
7520
+ const row = await this.getExecutor(tx).getFirstAsync(
7521
+ `SELECT MAX(seq) AS m FROM ${this.prefix}vector_removals`
7522
+ );
7523
+ return row?.m ?? 0;
7524
+ }
7525
+ /** Returns the number of rows changed. */
7526
+ async confirm(seqs, now, tx) {
7527
+ const executor = this.getExecutor(tx);
7528
+ let changed = 0;
7529
+ for (const c of chunks(seqs, CHUNK2)) {
7530
+ const r = await executor.runAsync(
7531
+ `UPDATE ${this.prefix}vector_removals SET confirmed_at = ?
7532
+ WHERE confirmed_at IS NULL AND seq IN (${marks(c.length)})`,
7533
+ [now, ...c]
7534
+ );
7535
+ changed += r.changes;
7536
+ }
7537
+ return changed;
7538
+ }
7539
+ async bumpAttempts(seqs, now, tx) {
7540
+ const executor = this.getExecutor(tx);
7541
+ for (const c of chunks(seqs, CHUNK2)) {
7542
+ await executor.runAsync(
7543
+ `UPDATE ${this.prefix}vector_removals
7544
+ SET attempts = attempts + 1, last_attempt_at = ?
7545
+ WHERE seq IN (${marks(c.length)})`,
7546
+ [now, ...c]
7547
+ );
7548
+ }
7549
+ }
7550
+ /** Delete the given rows when they are confirmed and their fact row is gone. */
7551
+ async deleteConfirmedGone(seqs, tx) {
7552
+ const executor = this.getExecutor(tx);
7553
+ for (const c of chunks(seqs, CHUNK2)) {
7554
+ await executor.runAsync(
7555
+ `DELETE FROM ${this.prefix}vector_removals
7556
+ WHERE seq IN (${marks(c.length)}) AND confirmed_at IS NOT NULL
7557
+ AND NOT EXISTS (SELECT 1 FROM ${this.prefix}entries e WHERE e.id = ${this.prefix}vector_removals.fact_id)`,
7558
+ c
7559
+ );
7560
+ }
7561
+ }
7562
+ /** For stale, gone or resurrected rows. Applies to the given seqs only. */
7563
+ async deleteBySeq(seqs, tx) {
7564
+ const executor = this.getExecutor(tx);
7565
+ let changed = 0;
7566
+ for (const c of chunks(seqs, CHUNK2)) {
7567
+ const r = await executor.runAsync(
7568
+ `DELETE FROM ${this.prefix}vector_removals WHERE seq IN (${marks(c.length)})`,
7569
+ c
7570
+ );
7571
+ changed += r.changes;
7572
+ }
7573
+ return changed;
7574
+ }
7575
+ /** Unconfirmed rows of `entityId` among `ids`. */
7576
+ async pendingCountForIds(entityId, ids) {
7577
+ let n = 0;
7578
+ for (const c of chunks(ids, CHUNK2)) {
7579
+ const row = await this.db.getFirstAsync(
7580
+ `SELECT COUNT(*) AS c FROM ${this.prefix}vector_removals
7581
+ WHERE confirmed_at IS NULL AND +entity_id = ? AND fact_id IN (${marks(c.length)})`,
7582
+ [entityId, ...c]
7583
+ );
7584
+ n += row?.c ?? 0;
7585
+ }
7586
+ return n;
7587
+ }
7588
+ /** Enqueue ids that have no row yet. Returns the number inserted. */
7589
+ async backstopEnqueue(entityId, ids, now, tx) {
7590
+ const executor = this.getExecutor(tx);
7591
+ let inserted = 0;
7592
+ for (const c of chunks(ids, 300)) {
7593
+ const values = c.map(() => "(?, ?, ?)").join(",");
7594
+ const args = c.flatMap((id) => [entityId, id, now]);
7595
+ const r = await executor.runAsync(
7596
+ `INSERT OR IGNORE INTO ${this.prefix}vector_removals (entity_id, fact_id, enqueued_at)
7597
+ VALUES ${values}`,
7598
+ args
7599
+ );
7600
+ inserted += r.changes;
7601
+ }
7602
+ return inserted;
7603
+ }
7604
+ /**
7605
+ * Remove rows together with a hard delete of the facts. `'all'` drops every
7606
+ * row of those ids; `'confirmedGone'` drops only confirmed rows whose fact
7607
+ * row no longer exists, so a removal re-owed meanwhile is never erased.
7608
+ */
7609
+ async deleteForFacts(entityId, ids, tx, mode = "all") {
7610
+ const executor = this.getExecutor(tx);
7611
+ const extra = mode === "all" ? "" : ` AND confirmed_at IS NOT NULL
7612
+ AND NOT EXISTS (SELECT 1 FROM ${this.prefix}entries e WHERE e.id = ${this.prefix}vector_removals.fact_id)`;
7613
+ for (const c of chunks(ids, CHUNK2)) {
7614
+ await executor.runAsync(
7615
+ `DELETE FROM ${this.prefix}vector_removals
7616
+ WHERE entity_id = ? AND fact_id IN (${marks(c.length)})${extra}`,
7617
+ [entityId, ...c]
7618
+ );
7619
+ }
7620
+ }
7621
+ /** Drop unconfirmed rows. Returns the count removed. */
7622
+ async discardPending(entityId, tx) {
7623
+ const executor = this.getExecutor(tx);
7624
+ const r = entityId === void 0 ? await executor.runAsync(
7625
+ `DELETE FROM ${this.prefix}vector_removals WHERE confirmed_at IS NULL`
7626
+ ) : await executor.runAsync(
7627
+ `DELETE FROM ${this.prefix}vector_removals WHERE confirmed_at IS NULL AND entity_id = ?`,
7628
+ [entityId]
7629
+ );
7630
+ return r.changes;
7631
+ }
7632
+ async pendingStats(entityId) {
7633
+ const row = await this.db.getFirstAsync(
7634
+ `SELECT COUNT(*) AS c, MIN(enqueued_at) AS o, MAX(attempts) AS m
7635
+ FROM ${this.prefix}vector_removals
7636
+ WHERE confirmed_at IS NULL${entityId === void 0 ? "" : " AND entity_id = ?"}`,
7637
+ entityId === void 0 ? [] : [entityId]
7638
+ );
7639
+ return { count: row?.c ?? 0, oldestEnqueuedAt: row?.o ?? null, maxAttempts: row?.m ?? 0 };
7640
+ }
7641
+ async entitiesWithPending() {
7642
+ const rows = await this.db.getAllAsync(
7643
+ `SELECT DISTINCT entity_id FROM ${this.prefix}vector_removals
7644
+ WHERE confirmed_at IS NULL ORDER BY entity_id`
7645
+ );
7646
+ return rows.map((r) => r.entity_id);
7647
+ }
7648
+ /**
7649
+ * Entities with at least one pending row outside backoff (never attempted,
7650
+ * or last attempted longer ago than removalBackoffMs). Same rule as the drain.
7651
+ */
7652
+ async entitiesWithDuePending(now) {
7653
+ const rows = await this.db.getAllAsync(
7654
+ `SELECT DISTINCT entity_id FROM ${this.prefix}vector_removals
7655
+ WHERE confirmed_at IS NULL
7656
+ AND (last_attempt_at IS NULL
7657
+ OR ? - last_attempt_at >= MIN(1 << MIN(attempts, 12), 3600) * 1000)
7658
+ ORDER BY entity_id`,
7659
+ [now]
7660
+ );
7661
+ return rows.map((r) => r.entity_id);
7662
+ }
7663
+ async statusFor(ids, tx) {
7664
+ const executor = this.getExecutor(tx);
7665
+ const out = /* @__PURE__ */ new Map();
7666
+ for (const c of chunks(ids, CHUNK2)) {
7667
+ const rows = await executor.getAllAsync(
7668
+ `SELECT fact_id, confirmed_at FROM ${this.prefix}vector_removals
7669
+ WHERE fact_id IN (${marks(c.length)})`,
7670
+ c
7671
+ );
7672
+ for (const r of rows) out.set(r.fact_id, r.confirmed_at === null ? "pending" : "confirmed");
7673
+ }
7674
+ return out;
7675
+ }
7676
+ };
7677
+
7678
+ // src/services/VectorRemovalService.ts
7679
+ var MARKER_KEY = "external_index_in_use";
7680
+ var PAGE = 100;
7681
+ var ID_CHUNK = 500;
7682
+ var MAX_FAILED_IDS = 100;
7683
+ var MAX_CONSECUTIVE_REJECTIONS = 5;
7684
+ function removalGate(options) {
7685
+ if (options.forceDeleteIgnoreRankerHook === true) return "force";
7686
+ if (options.vectorRanker?.onEmbeddingPersisted) return "hook";
7687
+ return "none";
7688
+ }
7689
+ var VectorRemovalService = class {
7690
+ constructor(db, options, repo, embeddingService, metadataRepo) {
7691
+ this.db = db;
7692
+ this.options = options;
7693
+ this.repo = repo;
7694
+ this.embeddingService = embeddingService;
7695
+ this.metadataRepo = metadataRepo;
7696
+ this.inFlight = /* @__PURE__ */ new Map();
7697
+ this.ledgerSeen = false;
7698
+ }
7699
+ gate() {
7700
+ return removalGate(this.options);
7701
+ }
7702
+ async ledgerPresent() {
7703
+ if (this.ledgerSeen) return true;
7704
+ this.ledgerSeen = await this.metadataRepo.tableExists(this.repo.ledgerTable);
7705
+ return this.ledgerSeen;
7706
+ }
7707
+ /** One `hook_failed` diagnostic per id (the removal stays owed). */
7708
+ emitHookFailed(entityId, ids, operation, trigger) {
7709
+ for (const factId of ids) {
7710
+ emitDiagnostic(this.options, {
7711
+ entityId,
7712
+ operation,
7713
+ trigger,
7714
+ code: "hook_failed",
7715
+ detail: { factId, reason: "on_embedding_persisted" }
7716
+ });
7717
+ }
7718
+ }
7719
+ /**
7720
+ * Post-commit delivery for heal, ingest and import (spec §5.7). Never throws:
7721
+ * a failed id emits `hook_failed` and stays owed on the ledger. Without a
7722
+ * ledger table (setup never ran) it falls back to a best-effort call per id.
7723
+ * Under `forceDeleteIgnoreRankerHook` no removal call is made.
7724
+ */
7725
+ async deliverRemovals(entityId, ids, operation, trigger, fallbackIds = ids) {
7726
+ try {
7727
+ if (await this.ledgerPresent()) {
7728
+ if (ids.length === 0) return;
7729
+ const r2 = await this.drain({ entityId, ids }, { trigger });
7730
+ this.emitHookFailed(entityId, r2.failedIds, operation, trigger);
7731
+ if (r2.pending > 0 && this.gate() === "hook") await this.emitPending(entityId, trigger);
7732
+ return;
7733
+ }
7734
+ if (this.gate() !== "hook") return;
7735
+ const r = await this.embeddingService.callRemovalHookEach(entityId, [...new Set(fallbackIds)], { warn: true });
7736
+ this.emitHookFailed(entityId, r.failed, operation, trigger);
7737
+ } catch (err) {
7738
+ console.warn("[WikiMemory] removal delivery failed:", err);
7739
+ let stillPending = ids;
7740
+ try {
7741
+ const st = await this.repo.statusFor(ids);
7742
+ stillPending = ids.filter((id) => st.get(id) === "pending");
7743
+ } catch {
7744
+ }
7745
+ this.emitHookFailed(entityId, stillPending, operation, trigger);
7746
+ }
7747
+ }
7748
+ async markExternalIndexInUse(tx) {
7749
+ await this.metadataRepo.setMeta(MARKER_KEY, "1", tx);
7750
+ }
7751
+ async clearExternalIndexMarker() {
7752
+ await this.metadataRepo.deleteMeta(MARKER_KEY);
7753
+ }
7754
+ async externalIndexInUse() {
7755
+ return await this.metadataRepo.getMeta(MARKER_KEY) === "1";
7756
+ }
7757
+ async drain(scope, opts = {}) {
7758
+ const trigger = opts.trigger ?? "call";
7759
+ const entityId = "all" in scope ? void 0 : scope.entityId;
7760
+ const ids = "all" in scope ? void 0 : scope.ids;
7761
+ const gate = this.gate();
7762
+ if (gate === "none") {
7763
+ const pending = await this.pendingFor(entityId, ids);
7764
+ if (pending > 0 && await this.externalIndexInUse()) await this.emitPending(entityId, trigger);
7765
+ return { confirmed: 0, pending, failedIds: [], timedOut: false };
7766
+ }
7767
+ if (gate === "force") {
7768
+ const entities = entityId === void 0 ? await this.repo.entitiesWithPending() : [entityId];
7769
+ const counts = [];
7770
+ for (const e of entities) counts.push([e, (await this.repo.pendingStats(e)).count]);
7771
+ await this.repo.discardPending(entityId);
7772
+ await this.metadataRepo.deleteMeta(MARKER_KEY);
7773
+ for (const [e, count] of counts) {
7774
+ if (count === 0) continue;
7775
+ emitDiagnostic(this.options, {
7776
+ code: "external_deletion_discarded",
7777
+ operation: "externalDeletion",
7778
+ trigger,
7779
+ entityId: e,
7780
+ detail: { count }
7781
+ });
7782
+ }
7783
+ return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
7784
+ }
7785
+ const timeoutMs = this.embeddingService.validateDeletionTimeout();
7786
+ const result = { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
7787
+ let timeoutErr;
7788
+ let firstRejection;
7789
+ let consecutive = 0;
7790
+ let stop = false;
7791
+ let transient = false;
7792
+ const tried = /* @__PURE__ */ new Set();
7793
+ let scopes;
7794
+ let maxSeq;
7795
+ try {
7796
+ scopes = entityId === void 0 ? (await this.repo.entitiesWithPending()).map((e) => ({ entityId: e })) : ids === void 0 ? [{ entityId }] : chunks(ids, ID_CHUNK).map((c) => ({ entityId, ids: c }));
7797
+ maxSeq = await this.repo.maxSeq();
7798
+ } catch {
7799
+ result.transient = true;
7800
+ try {
7801
+ result.pending = await this.pendingFor(entityId, ids);
7802
+ } catch {
7803
+ }
7804
+ return result;
7805
+ }
7806
+ const perEntity = entityId === void 0;
7807
+ for (const sc of scopes) {
7808
+ if (stop || transient) break;
7809
+ let cursor = { maxSeq, attempts: -1, seq: 0 };
7810
+ let scopeDone = false;
7811
+ if (perEntity) consecutive = 0;
7812
+ while (!stop && !scopeDone) {
7813
+ let page;
7814
+ try {
7815
+ page = await this.db.withTransactionAsync(
7816
+ (tx) => this.repo.readPage(sc, cursor, PAGE, tx)
7817
+ );
7818
+ } catch {
7819
+ transient = true;
7820
+ result.transient = true;
7821
+ break;
7822
+ }
7823
+ if (page.length === 0) break;
7824
+ const last = page[page.length - 1];
7825
+ cursor = { maxSeq, attempts: last.attempts, seq: last.seq };
7826
+ const confirmSeqs = [];
7827
+ const bumpSeqs = [];
7828
+ const deleteSeqs = [];
7829
+ const goneSeqs = [];
7830
+ for (const row of page) {
7831
+ if (tried.has(row.seq)) continue;
7832
+ if (row.fact_state === "live") {
7833
+ tried.add(row.seq);
7834
+ deleteSeqs.push(row.seq);
7835
+ continue;
7836
+ }
7837
+ if (opts.backoff === true && row.last_attempt_at !== null) {
7838
+ if (Date.now() - row.last_attempt_at < removalBackoffMs(row.attempts)) continue;
7839
+ }
7840
+ let budget = timeoutMs;
7841
+ if (opts.deadlineAt !== void 0) {
7842
+ const left = opts.deadlineAt - Date.now();
7843
+ if (left <= 0) {
7844
+ stop = true;
7845
+ break;
7846
+ }
7847
+ budget = Math.min(timeoutMs, left);
7848
+ }
7849
+ tried.add(row.seq);
7850
+ const outcome = await this.callFor(row, budget);
7851
+ if (outcome.ok) {
7852
+ consecutive = 0;
7853
+ if (row.fact_state === "gone") goneSeqs.push(row.seq);
7854
+ else confirmSeqs.push(row.seq);
7855
+ } else {
7856
+ if (!outcome.joined) bumpSeqs.push(row.seq);
7857
+ if (result.failedIds.length < MAX_FAILED_IDS) result.failedIds.push(row.fact_id);
7858
+ if (outcome.timedOut) {
7859
+ result.timedOut = true;
7860
+ result.timedOutId ?? (result.timedOutId = row.fact_id);
7861
+ timeoutErr ?? (timeoutErr = outcome.cause);
7862
+ stop = true;
7863
+ break;
7864
+ }
7865
+ firstRejection ?? (firstRejection = outcome.cause);
7866
+ if (++consecutive >= MAX_CONSECUTIVE_REJECTIONS) {
7867
+ if (perEntity) scopeDone = true;
7868
+ else stop = true;
7869
+ break;
7870
+ }
7871
+ }
7872
+ }
7873
+ if (confirmSeqs.length || bumpSeqs.length || deleteSeqs.length || goneSeqs.length) {
7874
+ const now = Date.now();
7875
+ try {
7876
+ const changed = await this.db.withTransactionAsync(async (tx) => {
7877
+ let n = 0;
7878
+ if (confirmSeqs.length) {
7879
+ n += await this.repo.confirm(confirmSeqs, now, tx);
7880
+ await this.repo.deleteConfirmedGone(confirmSeqs, tx);
7881
+ }
7882
+ if (bumpSeqs.length) await this.repo.bumpAttempts(bumpSeqs, now, tx);
7883
+ if (goneSeqs.length) n += await this.repo.deleteBySeq(goneSeqs, tx);
7884
+ if (deleteSeqs.length) await this.repo.deleteBySeq(deleteSeqs, tx);
7885
+ return n;
7886
+ });
7887
+ result.confirmed += changed;
7888
+ } catch {
7889
+ transient = true;
7890
+ result.transient = true;
7891
+ break;
7892
+ }
7893
+ }
7894
+ if (page.length < PAGE) break;
7895
+ }
7896
+ }
7897
+ result.firstCause = timeoutErr ?? firstRejection;
7898
+ try {
7899
+ result.pending = await this.pendingFor(entityId, ids);
7900
+ } catch {
7901
+ result.transient = true;
7902
+ }
7903
+ return result;
7904
+ }
7905
+ /**
7906
+ * Makes the removal call for `row`, or joins another drain's call for the
7907
+ * same seq. Never throws: the outcome says whether it succeeded, whether
7908
+ * this drain joined (only the owner bumps attempts on failure), and whether
7909
+ * the failure was a timeout.
7910
+ */
7911
+ async callFor(row, budgetMs) {
7912
+ const end = Date.now() + budgetMs;
7913
+ const left = () => Math.max(1, end - Date.now());
7914
+ let joined = false;
7915
+ try {
7916
+ let existing = this.inFlight.get(row.fact_id);
7917
+ while (existing && existing.seq !== row.seq) {
7918
+ joined = true;
7919
+ await withBudget(existing.promise.catch(() => {
7920
+ }), left());
7921
+ const next = this.inFlight.get(row.fact_id);
7922
+ existing = next === existing ? void 0 : next;
7923
+ }
7924
+ if (existing) {
7925
+ joined = true;
7926
+ await withBudget(existing.promise, left());
7927
+ return { ok: true, joined: true };
7928
+ }
7929
+ joined = false;
7930
+ const p = this.embeddingService.callRemovalHook(row.entity_id, row.fact_id, left());
7931
+ const entry = { seq: row.seq, promise: p };
7932
+ this.inFlight.set(row.fact_id, entry);
7933
+ const clear = () => {
7934
+ if (this.inFlight.get(row.fact_id) === entry) this.inFlight.delete(row.fact_id);
7935
+ };
7936
+ p.then(clear, clear);
7937
+ await p;
7938
+ return { ok: true, joined: false };
7939
+ } catch (err) {
7940
+ const e = err instanceof Error ? err : new Error(String(err));
7941
+ return { ok: false, joined, timedOut: e[HOOK_TIMEOUT_MARKER] === true, cause: e };
7942
+ }
7943
+ }
7944
+ async pendingFor(entityId, ids) {
7945
+ if (entityId !== void 0 && ids !== void 0) {
7946
+ return this.repo.pendingCountForIds(entityId, ids);
7947
+ }
7948
+ return (await this.repo.pendingStats(entityId)).count;
7949
+ }
7950
+ async emitPending(entityId, trigger) {
7951
+ const entities = entityId === void 0 ? await this.repo.entitiesWithPending() : [entityId];
7952
+ for (const e of entities) {
7953
+ const st = await this.repo.pendingStats(e);
7954
+ if (st.count === 0) continue;
7955
+ emitDiagnostic(this.options, {
7956
+ code: "external_deletion_pending",
7957
+ operation: "externalDeletion",
7958
+ trigger,
7959
+ entityId: e,
7960
+ detail: {
7961
+ count: st.count,
7962
+ ...st.oldestEnqueuedAt !== null ? { oldestEnqueuedAt: st.oldestEnqueuedAt } : {},
7963
+ maxAttempts: st.maxAttempts
7964
+ }
7965
+ });
7966
+ }
7967
+ }
7968
+ };
7969
+ function withBudget(p, ms) {
7970
+ let handle;
7971
+ const timer = new Promise((_, reject) => {
7972
+ handle = setTimeout(() => {
7973
+ const e = new Error(`onEmbeddingPersisted timed out after ${ms}ms`);
7974
+ e[HOOK_TIMEOUT_MARKER] = true;
7975
+ reject(e);
7976
+ }, ms);
7977
+ });
7978
+ return Promise.race([p, timer]).finally(() => {
7979
+ if (handle) clearTimeout(handle);
7980
+ });
7981
+ }
7982
+
7251
7983
  // src/services/legacyWatermark.ts
7252
7984
  async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
7253
7985
  if (checkpoint <= 0 || total <= 0) return null;
@@ -7427,7 +8159,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
7427
8159
  promptEvents,
7428
8160
  currentFacts,
7429
8161
  promptOverride,
7430
- ontologyContext
8162
+ ontologyContext,
8163
+ ctx.guidance
7431
8164
  );
7432
8165
  let responseText;
7433
8166
  try {
@@ -7599,7 +8332,7 @@ var OPS_MAX_EVENTS_PER_PASS = 50;
7599
8332
  var OPS_MAX_EXTRACT_CHARS = 24e3;
7600
8333
  var RESOLVE_RESERVE_FACTOR = 2;
7601
8334
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
7602
- async function selectBatch(deps, entityId, wm, meter) {
8335
+ async function selectBatch(deps, entityId, wm, meter, guidance) {
7603
8336
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
7604
8337
  if (events.length === 0) return { batch: [] };
7605
8338
  let n = 0;
@@ -7613,7 +8346,7 @@ async function selectBatch(deps, entityId, wm, meter) {
7613
8346
  if (meter && meter.budget !== void 0) {
7614
8347
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
7615
8348
  for (; ; ) {
7616
- const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext));
8349
+ const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
7617
8350
  if (meter.fits(need)) break;
7618
8351
  if (batch.length === 1) return { budgetStop: { requiredEstimate: need } };
7619
8352
  batch = labelEvents(events.slice(0, Math.max(1, Math.floor(batch.length / 2))));
@@ -7624,7 +8357,7 @@ async function selectBatch(deps, entityId, wm, meter) {
7624
8357
  async function runExtract(deps, ctx, batch) {
7625
8358
  const { entityId, trigger } = ctx;
7626
8359
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
7627
- const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext);
8360
+ const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
7628
8361
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
7629
8362
  const parsed = parseJsonResponse(text);
7630
8363
  const base = { entityId, operation: "librarian", trigger };
@@ -8082,7 +8815,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
8082
8815
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
8083
8816
  await deps.seedWatermark(entityId);
8084
8817
  const wm = await deps.getWatermark(entityId);
8085
- const sel = await selectBatch(deps, entityId, wm, ctx.meter);
8818
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
8086
8819
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
8087
8820
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
8088
8821
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -8212,7 +8945,7 @@ var formatSkipError = (err) => {
8212
8945
  return base;
8213
8946
  };
8214
8947
  var MaintenanceService = class {
8215
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
8948
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
8216
8949
  this.db = db;
8217
8950
  this.prefix = prefix;
8218
8951
  this.options = options;
@@ -8225,6 +8958,8 @@ var MaintenanceService = class {
8225
8958
  this.jobManager = jobManager;
8226
8959
  this.embeddingService = embeddingService;
8227
8960
  this.ontologyService = ontologyService;
8961
+ this.vectorRemoval = vectorRemoval;
8962
+ this.vectorRemovalRepo = vectorRemovalRepo;
8228
8963
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
8229
8964
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
8230
8965
  }
@@ -8238,11 +8973,14 @@ var MaintenanceService = class {
8238
8973
  this._validatePruneDuration(retainEventsFor, "retainEventsFor");
8239
8974
  const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
8240
8975
  this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
8976
+ const gate = removalGate(this.options);
8977
+ if (gate === "hook") this.embeddingService.validateDeletionTimeout();
8241
8978
  const now = Date.now();
8242
8979
  let syncedIds = [];
8243
8980
  let deletedEntries = 0;
8244
8981
  let deletedTasks = 0;
8245
8982
  let deletedEvents = 0;
8983
+ let prunePartial = null;
8246
8984
  if (pruneSupersededAfter !== null) {
8247
8985
  const expiredCutoff = now - pruneSupersededAfter * 864e5;
8248
8986
  const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
@@ -8251,55 +8989,89 @@ var MaintenanceService = class {
8251
8989
  await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
8252
8990
  });
8253
8991
  syncedIds = [...expiredIds];
8992
+ if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
8993
+ await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
8994
+ }
8254
8995
  }
8255
8996
  }
8256
8997
  if (retainSoftDeletedFor !== null) {
8257
8998
  const cutoff = now - retainSoftDeletedFor * 864e5;
8258
8999
  const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
8259
- const succeeded = [];
8260
- let failure = null;
8261
- for (const row of entriesToDelete) {
8262
- try {
8263
- await this.embeddingService.notifyEmbeddingPersistedOrThrow(row.entity_id, row.id, null);
8264
- succeeded.push({ entity_id: row.entity_id, id: row.id });
8265
- } catch (err) {
8266
- failure = { factId: row.id, cause: err };
8267
- break;
9000
+ const prunableIds = entriesToDelete.map((r) => r.id);
9001
+ const vr = this.vectorRemoval;
9002
+ const vrRepo = this.vectorRemovalRepo;
9003
+ const ledgerOn = !!vr && !!vrRepo && await vr.ledgerPresent();
9004
+ let deletable = prunableIds;
9005
+ let removeLedger = false;
9006
+ let kept = [];
9007
+ let timedOut = false;
9008
+ let cause;
9009
+ let firstFailed;
9010
+ let failedOrder = [];
9011
+ if (ledgerOn && vr && vrRepo) {
9012
+ if (gate === "hook" && prunableIds.length > 0) {
9013
+ await this.db.withTransactionAsync(async (tx) => {
9014
+ await vrRepo.backstopEnqueue(entityId, prunableIds, now, tx);
9015
+ });
9016
+ }
9017
+ const result = prunableIds.length > 0 ? await vr.drain({ entityId, ids: prunableIds }) : { failedIds: [], timedOut: false, firstCause: void 0 };
9018
+ if (gate === "hook") {
9019
+ timedOut = result.timedOut;
9020
+ cause = result.firstCause;
9021
+ failedOrder = result.failedIds;
9022
+ } else if (gate === "force") {
9023
+ removeLedger = true;
9024
+ } else {
9025
+ removeLedger = !await vr.externalIndexInUse();
8268
9026
  }
9027
+ } else if (gate === "hook") {
9028
+ const r = await this.embeddingService.callRemovalHookEach(entityId, prunableIds);
9029
+ const failedSet = new Set(r.failed);
9030
+ kept = r.failed;
9031
+ deletable = prunableIds.filter((id) => !failedSet.has(id));
9032
+ timedOut = r.timedOut;
9033
+ cause = r.cause;
9034
+ firstFailed = kept[0];
8269
9035
  }
8270
- const succeededIds = succeeded.map((r) => r.id);
8271
- syncedIds = [...syncedIds, ...succeededIds];
9036
+ const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
8272
9037
  await this.db.withTransactionAsync(async (tx) => {
8273
- if (succeededIds.length > 0) {
8274
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, succeededIds, tx);
9038
+ if (hookLedger && vrRepo && prunableIds.length > 0) {
9039
+ const status = await vrRepo.statusFor(prunableIds, tx);
9040
+ deletable = prunableIds.filter((id) => status.get(id) !== "pending");
9041
+ kept = prunableIds.filter((id) => status.get(id) === "pending");
9042
+ }
9043
+ if (deletable.length > 0) {
9044
+ const deletedIds = [];
9045
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
9046
+ if (hookLedger) {
9047
+ const gone = new Set(deletedIds);
9048
+ const skipped = deletable.filter((id) => !gone.has(id));
9049
+ if (skipped.length > 0) {
9050
+ const after = await vrRepo.statusFor(skipped, tx);
9051
+ kept = [...kept, ...skipped.filter((id) => after.get(id) === "pending")];
9052
+ }
9053
+ deletable = deletedIds;
9054
+ }
9055
+ if (vrRepo && ledgerOn) {
9056
+ if (removeLedger) await vrRepo.deleteForFacts(entityId, deletable, tx, "all");
9057
+ else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
9058
+ }
8275
9059
  }
8276
9060
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
8277
9061
  });
8278
- if (failure) {
8279
- await this.searchService.syncEntries(entityId, syncedIds);
8280
- const remaining = entriesToDelete.length - succeeded.length - 1;
8281
- const isTimeout = failure.cause?.[HOOK_TIMEOUT_MARKER] === true;
8282
- if (isTimeout) {
8283
- throw new PrunePartialFailureError(
8284
- succeeded.length,
8285
- failure.factId,
8286
- remaining,
8287
- new Error("Deletion hook timed out"),
8288
- deletedTasks,
8289
- 0
8290
- );
9062
+ if (hookLedger) {
9063
+ const keptSet = new Set(kept);
9064
+ firstFailed = failedOrder.find((id) => keptSet.has(id)) ?? kept[0];
9065
+ }
9066
+ syncedIds = [...syncedIds, ...deletable];
9067
+ if (kept.length > 0) {
9068
+ if (timedOut) {
9069
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("Deletion hook timed out") };
9070
+ } else if (cause === void 0) {
9071
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("external removal not confirmed") };
9072
+ } else {
9073
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: this._sanitizeRankerError(cause) };
8291
9074
  }
8292
- const errMsg = failure.cause?.message ?? "";
8293
- const isValidationError = errMsg.startsWith("Invalid deletionHookTimeoutMs");
8294
- const sanitizedCause = isValidationError ? failure.cause : this._sanitizeRankerError(failure.cause);
8295
- throw new PrunePartialFailureError(
8296
- succeeded.length,
8297
- failure.factId,
8298
- remaining,
8299
- sanitizedCause,
8300
- deletedTasks,
8301
- 0
8302
- );
8303
9075
  }
8304
9076
  }
8305
9077
  if (retainEventsFor !== null) {
@@ -8336,6 +9108,16 @@ var MaintenanceService = class {
8336
9108
  await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
8337
9109
  }
8338
9110
  await this.searchService.syncEntries(entityId, syncedIds);
9111
+ if (prunePartial) {
9112
+ throw new PrunePartialFailureError(
9113
+ deletedEntries,
9114
+ prunePartial.failedAt,
9115
+ prunePartial.remaining,
9116
+ prunePartial.cause,
9117
+ deletedTasks,
9118
+ deletedEvents
9119
+ );
9120
+ }
8339
9121
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
8340
9122
  } finally {
8341
9123
  this.jobManager.releaseLock("prune", entityId);
@@ -8440,6 +9222,7 @@ var MaintenanceService = class {
8440
9222
  }
8441
9223
  const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
8442
9224
  if (result.ok) embedded++;
9225
+ else if (result.kind === "fact_deleted") skipped++;
8443
9226
  else failed++;
8444
9227
  }
8445
9228
  if (embedded > 0) {
@@ -8470,6 +9253,7 @@ var MaintenanceService = class {
8470
9253
  let deletedTasks = 0;
8471
9254
  let deletedEvents = 0;
8472
9255
  const deletedEntryIds = [];
9256
+ const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
8473
9257
  await this.db.withTransactionAsync(async (tx) => {
8474
9258
  if (params.clearAll) {
8475
9259
  for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
@@ -8518,22 +9302,54 @@ var MaintenanceService = class {
8518
9302
  if (taskResult) deletedTasks++;
8519
9303
  deletedEntries += refResult;
8520
9304
  }
9305
+ if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
9306
+ await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
9307
+ }
8521
9308
  });
8522
9309
  const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
8523
9310
  await this.searchService.syncEntries(entityId, uniqueDeletedIds);
8524
- for (const factId of uniqueDeletedIds) {
9311
+ if (uniqueDeletedIds.length > 0) {
9312
+ const firstId = uniqueDeletedIds[0];
9313
+ const vr = this.vectorRemoval;
9314
+ const vrRepo = this.vectorRemovalRepo;
9315
+ let unconfirmed = [];
9316
+ let timedOut = false;
9317
+ let cause;
9318
+ let timedOutId;
8525
9319
  try {
8526
- await this.embeddingService.notifyEmbeddingPersistedOrThrow(entityId, factId, null);
8527
- } catch (hookErr) {
8528
- const isTimeout = hookErr?.[HOOK_TIMEOUT_MARKER] === true;
8529
- if (isTimeout) {
8530
- throw new Error(`forget(${entityId}/${factId}) failed: ${hookErr.message}`);
9320
+ if (vr && vrRepo && ledgerOn) {
9321
+ const result = await vr.drain({ entityId, ids: uniqueDeletedIds });
9322
+ if (vr.gate() === "hook") {
9323
+ const status = await vrRepo.statusFor(uniqueDeletedIds);
9324
+ unconfirmed = uniqueDeletedIds.filter((id) => status.get(id) === "pending");
9325
+ timedOut = result.timedOut;
9326
+ timedOutId = result.timedOutId;
9327
+ cause = result.firstCause;
9328
+ }
9329
+ } else if (this.options.vectorRanker?.onEmbeddingPersisted && this.options.forceDeleteIgnoreRankerHook !== true) {
9330
+ const r = await this.embeddingService.callRemovalHookEach(entityId, uniqueDeletedIds);
9331
+ unconfirmed = r.failed;
9332
+ timedOut = r.timedOut;
9333
+ timedOutId = r.timedOutId;
9334
+ cause = r.cause;
8531
9335
  }
9336
+ } catch (hookErr) {
8532
9337
  const errMsg = hookErr?.message ?? "";
8533
9338
  if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
8534
- throw new Error(`forget(${entityId}/${factId}) failed: ${errMsg}`, { cause: hookErr });
9339
+ throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
8535
9340
  }
8536
- throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
9341
+ throw hookErr;
9342
+ }
9343
+ if (unconfirmed.length > 0) {
9344
+ const head = `forget(${entityId}/${(timedOut ? timedOutId : void 0) ?? unconfirmed[0]}) failed: `;
9345
+ const message = timedOut ? head + (cause?.message ?? "onEmbeddingPersisted timed out") : cause === void 0 ? head + "ANN cleanup not confirmed" : head + "ANN cleanup hook rejected";
9346
+ throw new WikiExternalDeletionError(message, {
9347
+ entityId,
9348
+ unconfirmedIds: unconfirmed.slice(0, 100),
9349
+ unconfirmedCount: unconfirmed.length,
9350
+ timedOut,
9351
+ cause: timedOut || cause === void 0 ? void 0 : this._sanitizeRankerError(cause)
9352
+ });
8537
9353
  }
8538
9354
  }
8539
9355
  if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
@@ -8542,6 +9358,22 @@ var MaintenanceService = class {
8542
9358
  this.jobManager.releaseLock("forget", entityId);
8543
9359
  }
8544
9360
  }
9361
+ /** Heal's post-commit removal delivery (spec §5.7). Never throws. */
9362
+ async deliverHealRemovals(entityId, ids, trigger) {
9363
+ if (this.vectorRemoval) {
9364
+ await this.vectorRemoval.deliverRemovals(entityId, ids, "heal", trigger);
9365
+ return;
9366
+ }
9367
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
9368
+ for (const factId of ids) {
9369
+ try {
9370
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
9371
+ } catch (hookErr) {
9372
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
9373
+ emitDiagnostic(this.options, { entityId, operation: "heal", trigger, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
9374
+ }
9375
+ }
9376
+ }
8545
9377
  /**
8546
9378
  * Whether forget() should soft-delete in source_ref_index (#316,
8547
9379
  * specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
@@ -8621,7 +9453,17 @@ var MaintenanceService = class {
8621
9453
  * A budget-stopped pass wrote nothing and must not move the watermark.
8622
9454
  */
8623
9455
  async runLibrarianPass(ctx) {
8624
- const result = await runLibrarianStrategy(this.librarianDeps(), ctx);
9456
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, ctx.entityId);
9457
+ if (diagnostic) {
9458
+ emitDiagnostic(this.options, {
9459
+ code: diagnostic.code,
9460
+ operation: "librarian",
9461
+ trigger: ctx.trigger,
9462
+ entityId: ctx.entityId,
9463
+ detail: diagnostic.detail
9464
+ });
9465
+ }
9466
+ const result = await runLibrarianStrategy(this.librarianDeps(), { ...ctx, guidance });
8625
9467
  if (result.processedThrough && !result.budgetStop) {
8626
9468
  await this.advanceLibrarianWatermark(ctx.entityId, result.processedThrough);
8627
9469
  }
@@ -8739,14 +9581,7 @@ var MaintenanceService = class {
8739
9581
  staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
8740
9582
  }
8741
9583
  });
8742
- for (const factId of orphanedIds) {
8743
- try {
8744
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
8745
- } catch (hookErr) {
8746
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal orphan pass for ${factId}:`, hookErr);
8747
- emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
8748
- }
8749
- }
9584
+ await this.deliverHealRemovals(entityId, orphanedIds, trigger);
8750
9585
  const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
8751
9586
  const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
8752
9587
  if (healCandidates.length === 0 || keywordUnavailable) {
@@ -8935,14 +9770,7 @@ var MaintenanceService = class {
8935
9770
  ...insertedFacts.map((f) => f.id)
8936
9771
  ]));
8937
9772
  await this.searchService.syncEntries(entityId, healSyncIds);
8938
- for (const factId of uniqueDeletedFactIds) {
8939
- try {
8940
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
8941
- } catch (hookErr) {
8942
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
8943
- emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
8944
- }
8945
- }
9773
+ await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
8946
9774
  for (const fact of insertedFacts) {
8947
9775
  await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
8948
9776
  }
@@ -9308,7 +10136,7 @@ var MaintenanceService = class {
9308
10136
 
9309
10137
  // src/services/MaintenanceScheduler.ts
9310
10138
  var MaintenanceScheduler = class {
9311
- constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager) {
10139
+ constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager, vectorRemovalService, vectorRemovalRepo) {
9312
10140
  this.db = db;
9313
10141
  this.options = options;
9314
10142
  this.maintenanceService = maintenanceService;
@@ -9316,6 +10144,8 @@ var MaintenanceScheduler = class {
9316
10144
  this.eventRepo = eventRepo;
9317
10145
  this.entryRepo = entryRepo;
9318
10146
  this.jobManager = jobManager;
10147
+ this.vectorRemovalService = vectorRemovalService;
10148
+ this.vectorRemovalRepo = vectorRemovalRepo;
9319
10149
  }
9320
10150
  /**
9321
10151
  * Entities with **any** pending work only, sorted by `pendingEvents` desc
@@ -9327,7 +10157,17 @@ var MaintenanceScheduler = class {
9327
10157
  const autoHealThreshold = this.options.config?.autoHealThreshold || 100;
9328
10158
  const canEmbed = typeof this.options.llmProvider.embed === "function";
9329
10159
  const out = [];
9330
- for (const entityId of ids) {
10160
+ const owed = /* @__PURE__ */ new Map();
10161
+ if (this.vectorRemovalService.gate() !== "none" && await this.vectorRemovalService.ledgerPresent()) {
10162
+ const scope = entityIds === void 0 ? void 0 : new Set(entityIds);
10163
+ for (const e of await this.vectorRemovalRepo.entitiesWithDuePending(Date.now())) {
10164
+ if (scope !== void 0 && !scope.has(e)) continue;
10165
+ owed.set(e, (await this.vectorRemovalRepo.pendingStats(e)).count);
10166
+ }
10167
+ }
10168
+ const listed = new Set(ids);
10169
+ const scan = [...ids, ...[...owed.keys()].filter((e) => !listed.has(e))];
10170
+ for (const entityId of scan) {
9331
10171
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
9332
10172
  const pendingEvents = await this.eventRepo.countAfter(entityId, wm);
9333
10173
  const chars = pendingEvents > 0 ? await this.eventRepo.sumSummaryCharsAfter(entityId, wm) : 0;
@@ -9337,8 +10177,16 @@ var MaintenanceScheduler = class {
9337
10177
  if (healCheckpoint > eventCount) healCheckpoint = 0;
9338
10178
  const healDue = eventCount - healCheckpoint >= autoHealThreshold;
9339
10179
  const reembedPending = canEmbed && await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS) > 0;
9340
- if (pendingEvents > 0 || healDue || reembedPending) {
9341
- out.push({ entityId, pendingEvents, pendingTokensEstimate: Math.ceil(chars / 4), healDue, reembedPending });
10180
+ const owedCount = owed.get(entityId) ?? 0;
10181
+ if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0) {
10182
+ out.push({
10183
+ entityId,
10184
+ pendingEvents,
10185
+ pendingTokensEstimate: Math.ceil(chars / 4),
10186
+ healDue,
10187
+ reembedPending,
10188
+ ...owedCount > 0 ? { pendingExternalDeletions: owedCount } : {}
10189
+ });
9342
10190
  }
9343
10191
  }
9344
10192
  return out.sort((x, y) => y.pendingEvents - x.pendingEvents || (x.entityId < y.entityId ? -1 : x.entityId > y.entityId ? 1 : 0));
@@ -9364,8 +10212,9 @@ var MaintenanceScheduler = class {
9364
10212
  const meter = new UsageMeter(opts.tokenBudget);
9365
10213
  const budget = opts.tokenBudget;
9366
10214
  const deadline = opts.deadlineMs !== void 0 ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;
9367
- const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed"]);
9368
- const pending = await this.getPending(opts.entityIds);
10215
+ const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed", "externalDeletions"]);
10216
+ const externalDeletions = await this.runExternalDeletions(opts.entityIds, jobs.has("externalDeletions"), deadline);
10217
+ const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending);
9369
10218
  const states = pending.map((p) => ({
9370
10219
  p,
9371
10220
  report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false },
@@ -9497,9 +10346,43 @@ var MaintenanceScheduler = class {
9497
10346
  tokensUsed: meter.used,
9498
10347
  estimated: meter.estimated,
9499
10348
  remaining: budget === void 0 ? null : meter.remaining,
9500
- stoppedReason: stopped
10349
+ stoppedReason: stopped,
10350
+ externalDeletions
9501
10351
  };
9502
10352
  }
10353
+ /**
10354
+ * Runs first and outside the token budget: delivers owed vector-index
10355
+ * removals per entity (wiped entities included), without backoff. Pending is
10356
+ * reported even when the job is not listed or no hook is configured.
10357
+ */
10358
+ async runExternalDeletions(entityIds, enabled, deadline) {
10359
+ if (!await this.vectorRemovalService.ledgerPresent()) return { confirmed: 0, pending: 0 };
10360
+ const all = await this.vectorRemovalRepo.entitiesWithPending();
10361
+ const scope = entityIds === void 0 ? void 0 : new Set(entityIds);
10362
+ const entities = scope === void 0 ? all : all.filter((e) => scope.has(e));
10363
+ let confirmed = 0;
10364
+ let pending = 0;
10365
+ const counted = /* @__PURE__ */ new Set();
10366
+ if (enabled) {
10367
+ for (const e of entities) {
10368
+ if (Date.now() >= deadline) break;
10369
+ const r = await this.vectorRemovalService.drain(
10370
+ { entityId: e },
10371
+ { trigger: "call", ...deadline === Infinity ? {} : { deadlineAt: deadline } }
10372
+ );
10373
+ confirmed += r.confirmed;
10374
+ if (!r.transient) {
10375
+ pending += r.pending;
10376
+ counted.add(e);
10377
+ }
10378
+ if (r.timedOut) break;
10379
+ }
10380
+ }
10381
+ for (const e of entities) {
10382
+ if (!counted.has(e)) pending += (await this.vectorRemovalRepo.pendingStats(e)).count;
10383
+ }
10384
+ return { confirmed, pending };
10385
+ }
9503
10386
  };
9504
10387
 
9505
10388
  // src/services/importEventStamps.ts
@@ -9564,7 +10447,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
9564
10447
  var IMPORT_TITLE_MAX = 500;
9565
10448
  var IMPORT_BODY_MAX = 8e3;
9566
10449
  var ImportExportService = class {
9567
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
10450
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
9568
10451
  this.db = db;
9569
10452
  this.entryRepo = entryRepo;
9570
10453
  this.taskRepo = taskRepo;
@@ -9575,6 +10458,7 @@ var ImportExportService = class {
9575
10458
  this.jobManager = jobManager;
9576
10459
  this.embeddingService = embeddingService;
9577
10460
  this.options = options;
10461
+ this.vectorRemoval = vectorRemoval;
9578
10462
  }
9579
10463
  async exportDump(entityIds) {
9580
10464
  let ids;
@@ -9950,7 +10834,7 @@ var ImportExportService = class {
9950
10834
  body: clipped?.body ?? fact.body,
9951
10835
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
9952
10836
  }, { operation: "importDump", trigger: "call" });
9953
- if (!embedded) {
10837
+ if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
9954
10838
  try {
9955
10839
  await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
9956
10840
  } catch (hookErr) {
@@ -9992,16 +10876,26 @@ var ImportExportService = class {
9992
10876
  fact.id
9993
10877
  );
9994
10878
  }
10879
+ if (this.embeddingService.hasVectorHook()) {
10880
+ await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
10881
+ }
9995
10882
  }
9996
10883
  }
9997
- for (const factId of softDeletedFactIds) {
9998
- if (!upsertedFactIds.has(factId) || upsertedDeletedFactIds.has(factId)) {
10884
+ const removedIds = softDeletedFactIds.filter(
10885
+ (id) => !upsertedFactIds.has(id) || upsertedDeletedFactIds.has(id)
10886
+ );
10887
+ if (this.vectorRemoval) {
10888
+ await this.vectorRemoval.deliverRemovals(
10889
+ entityId,
10890
+ Array.from(/* @__PURE__ */ new Set([...removedIds, ...upsertedDeletedFactIds])),
10891
+ "importDump",
10892
+ "call",
10893
+ removedIds
10894
+ );
10895
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
10896
+ for (const factId of removedIds) {
9999
10897
  try {
10000
- await this.embeddingService.notifyEmbeddingPersisted(
10001
- entityId,
10002
- factId,
10003
- null
10004
- );
10898
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
10005
10899
  } catch (hookErr) {
10006
10900
  console.warn(
10007
10901
  `[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
@@ -10238,27 +11132,62 @@ var EmbeddingService = class {
10238
11132
  }
10239
11133
  /**
10240
11134
  * Storage half: persist the computed vector to the entry row, then fire the
10241
- * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` only — embed
10242
- * failures do not originate here, so they cannot be marked as such (spec §3.2, D3).
11135
+ * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` (a DB error) and
11136
+ * `fact_deleted` (the row was soft-deleted or gone: no blob, no vector call, no
11137
+ * marker). Embed failures do not originate here, so they cannot be marked as
11138
+ * such (spec §3.2, D3).
10243
11139
  */
10244
11140
  async storeFactVector(fact, float32Vector, ctx) {
11141
+ let stored = true;
10245
11142
  try {
10246
11143
  await this.storeEmbeddingDimension(float32Vector.length);
10247
11144
  const blob = new Uint8Array(float32Vector.buffer);
10248
- await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
11145
+ stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
10249
11146
  } catch (err) {
10250
11147
  console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
10251
11148
  this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
10252
11149
  return { ok: false, kind: "storage_error" };
10253
11150
  }
11151
+ if (!stored) return { ok: false, kind: "fact_deleted" };
10254
11152
  try {
10255
11153
  await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
10256
11154
  } catch (hookErr) {
10257
11155
  console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
10258
11156
  this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
10259
11157
  }
11158
+ if (this.hasVectorHook()) {
11159
+ await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
11160
+ }
10260
11161
  return { ok: true, dimension: float32Vector.length };
10261
11162
  }
11163
+ hasVectorHook() {
11164
+ return !!this.options.vectorRanker?.onEmbeddingPersisted;
11165
+ }
11166
+ /**
11167
+ * Run after a vector call (resolved or not) by every path that sends one.
11168
+ * Never throws: a failure here leaves the removal owed or unrecorded, as before.
11169
+ */
11170
+ async settleAfterVectorCall(entityId, factId, operation, trigger) {
11171
+ const vr = this.vectorRemoval;
11172
+ if (!vr) return;
11173
+ const outcome = await this.recordAfterVectorCall(entityId, factId);
11174
+ if (outcome === "enqueued") {
11175
+ try {
11176
+ await vr.service.deliverRemovals(entityId, [factId], operation, trigger, []);
11177
+ } catch (err) {
11178
+ console.warn(`[WikiMemory] post-embed removal delivery failed for ${factId}:`, err);
11179
+ }
11180
+ return;
11181
+ }
11182
+ if (outcome !== "write_failed") return;
11183
+ try {
11184
+ await this.callRemovalHook(entityId, factId, this.validateDeletionTimeout());
11185
+ } catch (hookErr) {
11186
+ console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
11187
+ this.reportHookFailed({ operation, trigger }, entityId, factId);
11188
+ await this.recordAfterVectorCall(entityId, factId);
11189
+ }
11190
+ }
10262
11191
  reportEmbed(ctx, fact, code, reason) {
10263
11192
  if (!ctx) return;
10264
11193
  emitDiagnostic(this.options, {
@@ -10290,6 +11219,48 @@ var EmbeddingService = class {
10290
11219
  const result = await this.tryEmbedFact(fact, ctx);
10291
11220
  return result.ok;
10292
11221
  }
11222
+ /** Wired by WikiMemory (VectorRemovalService itself depends on this class). */
11223
+ attachVectorRemoval(service, repo) {
11224
+ this.vectorRemoval = { service, repo };
11225
+ }
11226
+ /**
11227
+ * After an embed (and its vector call) settles: owe a removal if the fact is
11228
+ * no longer live, so a vector the host just received is taken back (§5.7, G10).
11229
+ * Never throws. `'enqueued'`: a ledger row was written. `'none'`: no
11230
+ * removal hook (or the hook gate is off). `'live'`: the fact is live. A row already pending is
11231
+ * replaced (attempts reset, spec §5.2), so it counts as `'enqueued'` and
11232
+ * is sent now: the last call the host sees after this vector is `null`.
11233
+ * `'owed'`: the write failed but a pending row already holds the removal.
11234
+ * `'write_failed'`: the fact is known not live, the write failed, and its
11235
+ * row is confirmed or missing; or the store has no ledger table and the
11236
+ * fact is known not live.
11237
+ * `'unknown'`: the liveness read and the guarded write both failed.
11238
+ */
11239
+ async recordAfterVectorCall(entityId, factId) {
11240
+ const vr = this.vectorRemoval;
11241
+ if (!vr || vr.service.gate() !== "hook") return "none";
11242
+ let live;
11243
+ try {
11244
+ if (!await vr.service.ledgerPresent()) {
11245
+ return await vr.repo.isLive(factId) ? "live" : "write_failed";
11246
+ }
11247
+ live = await vr.repo.isLive(factId);
11248
+ } catch (err) {
11249
+ console.warn(`[WikiMemory] post-embed liveness read failed for ${factId}:`, err);
11250
+ }
11251
+ if (live) return "live";
11252
+ try {
11253
+ return await vr.repo.enqueueIfNotLive(entityId, factId, Date.now()) ? "enqueued" : "live";
11254
+ } catch (err) {
11255
+ console.warn(`[WikiMemory] post-embed removal could not be recorded for ${factId}:`, err);
11256
+ if (live !== false) return "unknown";
11257
+ try {
11258
+ if ((await vr.repo.statusFor([factId])).get(factId) === "pending") return "owed";
11259
+ } catch {
11260
+ }
11261
+ return "write_failed";
11262
+ }
11263
+ }
10293
11264
  async notifyEmbeddingPersisted(entityId, factId, vector) {
10294
11265
  if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
10295
11266
  const vectorCopy = vector ? vector.slice() : null;
@@ -10299,15 +11270,72 @@ var EmbeddingService = class {
10299
11270
  vector: vectorCopy
10300
11271
  });
10301
11272
  }
10302
- async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
10303
- if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
10304
- if (this.options.forceDeleteIgnoreRankerHook === true) return;
10305
- const vectorCopy = vector ? vector.slice() : null;
11273
+ validateDeletionTimeout() {
10306
11274
  const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
10307
11275
  if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
10308
11276
  throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
10309
11277
  }
10310
- const timeoutMs = rawTimeout;
11278
+ return rawTimeout;
11279
+ }
11280
+ /** Send a removal (`vector: null`) to the hook. No gate check; the caller owns the gate. */
11281
+ async callRemovalHook(entityId, factId, timeoutMs) {
11282
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) {
11283
+ throw new Error("callRemovalHook requires vectorRanker.onEmbeddingPersisted");
11284
+ }
11285
+ let timeoutHandle;
11286
+ const timeoutPromise = new Promise((_, reject) => {
11287
+ timeoutHandle = setTimeout(() => {
11288
+ const timeoutError = new Error(`onEmbeddingPersisted timed out after ${timeoutMs}ms`);
11289
+ timeoutError[HOOK_TIMEOUT_MARKER] = true;
11290
+ reject(timeoutError);
11291
+ }, timeoutMs);
11292
+ });
11293
+ const hookPromise = Promise.resolve().then(
11294
+ () => this.options.vectorRanker.onEmbeddingPersisted({ entityId, factId, vector: null })
11295
+ );
11296
+ try {
11297
+ await Promise.race([hookPromise, timeoutPromise]);
11298
+ } catch (err) {
11299
+ hookPromise.catch(() => {
11300
+ });
11301
+ throw err;
11302
+ } finally {
11303
+ if (timeoutHandle) clearTimeout(timeoutHandle);
11304
+ }
11305
+ }
11306
+ /**
11307
+ * One removal call per id for a store with no ledger table (setup() never
11308
+ * ran), so nothing records what is owed (spec §5.5.5). Stops at the first
11309
+ * timeout: a dead index costs one timeout, as in a drain (spec rev 5).
11310
+ * `failed` lists the ids not confirmed, in order; after a timeout it ends
11311
+ * with the timed-out id and every id after it. Throws only for an invalid
11312
+ * `deletionHookTimeoutMs`.
11313
+ */
11314
+ async callRemovalHookEach(entityId, ids, opts = {}) {
11315
+ const timeoutMs = this.validateDeletionTimeout();
11316
+ const failed = [];
11317
+ let firstRejection;
11318
+ for (let i = 0; i < ids.length; i++) {
11319
+ const factId = ids[i];
11320
+ try {
11321
+ await this.callRemovalHook(entityId, factId, timeoutMs);
11322
+ } catch (hookErr) {
11323
+ if (opts.warn) console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
11324
+ if (hookErr?.[HOOK_TIMEOUT_MARKER] === true) {
11325
+ failed.push(...ids.slice(i));
11326
+ return { failed, timedOut: true, timedOutId: factId, cause: hookErr };
11327
+ }
11328
+ failed.push(factId);
11329
+ firstRejection ?? (firstRejection = hookErr);
11330
+ }
11331
+ }
11332
+ return { failed, timedOut: false, cause: firstRejection };
11333
+ }
11334
+ async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
11335
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
11336
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
11337
+ const vectorCopy = vector ? vector.slice() : null;
11338
+ const timeoutMs = this.validateDeletionTimeout();
10311
11339
  let timeoutHandle;
10312
11340
  const timeoutPromise = new Promise((_, reject) => {
10313
11341
  timeoutHandle = setTimeout(() => {
@@ -11907,11 +12935,15 @@ var WikiMemory = class {
11907
12935
  this.upsertIdStashSize = 0;
11908
12936
  /** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */
11909
12937
  this.upsertIdStashGen = 0;
12938
+ /** Superseded fact ids per entity awaiting a post-commit delivery from syncSearchIndex(). */
12939
+ this.removalStash = /* @__PURE__ */ new Map();
12940
+ this.removalStashSize = 0;
11910
12941
  this.reinitSearch = null;
11911
12942
  /** Monotonic time before which a no-arg syncSearchIndex() skips the re-init (0 = no cooldown). */
11912
12943
  this.reinitRetryAt = 0;
11913
12944
  /** Consecutive failed re-inits; drives the exponential backoff. */
11914
12945
  this.reinitFailures = 0;
12946
+ this.setupRemovalDrain = null;
11915
12947
  this.db = withSerializedTransactions(db);
11916
12948
  this.options = options;
11917
12949
  warnChangedDefaultsOnce(options.config);
@@ -11936,6 +12968,9 @@ var WikiMemory = class {
11936
12968
  );
11937
12969
  this.lintService = new LintService(this.lintRepo, this.ontologyService);
11938
12970
  this.embeddingService = new EmbeddingService(this.db, this.options, this.entryRepo, this.metadataRepo);
12971
+ this.vectorRemovalRepo = new VectorRemovalRepository(this.db, this.prefix);
12972
+ this.vectorRemovalService = new VectorRemovalService(this.db, this.options, this.vectorRemovalRepo, this.embeddingService, this.metadataRepo);
12973
+ this.embeddingService.attachVectorRemoval(this.vectorRemovalService, this.vectorRemovalRepo);
11939
12974
  this.searchService = new SearchService(
11940
12975
  this.entryRepo,
11941
12976
  new MiniSearchIndexStrategy()
@@ -11956,7 +12991,8 @@ var WikiMemory = class {
11956
12991
  this.jobManager,
11957
12992
  this.embeddingService,
11958
12993
  this.promptService,
11959
- this.ontologyService
12994
+ this.ontologyService,
12995
+ this.vectorRemovalService
11960
12996
  );
11961
12997
  this.maintenanceService = new MaintenanceService(
11962
12998
  this.db,
@@ -11972,7 +13008,9 @@ var WikiMemory = class {
11972
13008
  this.embeddingService,
11973
13009
  this.promptService,
11974
13010
  this.ontologyService,
11975
- this.edgeRepo
13011
+ this.edgeRepo,
13012
+ this.vectorRemovalService,
13013
+ this.vectorRemovalRepo
11976
13014
  );
11977
13015
  this.maintenanceScheduler = new MaintenanceScheduler(
11978
13016
  this.db,
@@ -11981,7 +13019,9 @@ var WikiMemory = class {
11981
13019
  this.metadataRepo,
11982
13020
  this.eventRepo,
11983
13021
  this.entryRepo,
11984
- this.jobManager
13022
+ this.jobManager,
13023
+ this.vectorRemovalService,
13024
+ this.vectorRemovalRepo
11985
13025
  );
11986
13026
  this.importExportService = new ImportExportService(
11987
13027
  this.db,
@@ -11993,7 +13033,8 @@ var WikiMemory = class {
11993
13033
  this.searchService,
11994
13034
  this.jobManager,
11995
13035
  this.embeddingService,
11996
- this.options
13036
+ this.options,
13037
+ this.vectorRemovalService
11997
13038
  );
11998
13039
  this.retrievalService = new RetrievalService(
11999
13040
  this.options,
@@ -12061,6 +13102,33 @@ var WikiMemory = class {
12061
13102
  }
12062
13103
  if (stash.size > 0) this.upsertIdStash.set(entityId, stash);
12063
13104
  }
13105
+ /**
13106
+ * Overflow past the cap drops the id from the stash only: the trigger already
13107
+ * put it on the ledger, so it stays owed and runExternalDeletions or
13108
+ * runPendingMaintenance delivers it later.
13109
+ */
13110
+ stashRemovalIds(entityId, ids) {
13111
+ const cap = this.constructor.REMOVAL_STASH_CAP;
13112
+ const stash = this.removalStash.get(entityId) ?? /* @__PURE__ */ new Set();
13113
+ for (const id of ids) {
13114
+ if (stash.has(id)) continue;
13115
+ if (this.removalStashSize >= cap) continue;
13116
+ stash.add(id);
13117
+ this.removalStashSize++;
13118
+ }
13119
+ if (stash.size > 0) this.removalStash.set(entityId, stash);
13120
+ }
13121
+ /** Removes and returns the stashed removal ids (one entity, or all). */
13122
+ takeRemovalIds(entityId) {
13123
+ const out = /* @__PURE__ */ new Map();
13124
+ for (const [e, set] of [...this.removalStash]) {
13125
+ if (entityId !== void 0 && e !== entityId) continue;
13126
+ out.set(e, [...set]);
13127
+ this.removalStashSize -= set.size;
13128
+ this.removalStash.delete(e);
13129
+ }
13130
+ return out;
13131
+ }
12064
13132
  /** Snapshot of the stash (one entity, or all) with generations, without removing anything. */
12065
13133
  peekStashedIds(entityId) {
12066
13134
  const snapshot = /* @__PURE__ */ new Map();
@@ -12149,6 +13217,84 @@ var WikiMemory = class {
12149
13217
  )
12150
13218
  );
12151
13219
  await this.searchService.sync(void 0, { deadline: openDeadline });
13220
+ await this.startSetupRemovalDrain();
13221
+ }
13222
+ /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
13223
+ async startSetupRemovalDrain() {
13224
+ if (this.setupRemovalDrain) return;
13225
+ const gate = this.vectorRemovalService.gate();
13226
+ if (gate === "none") return;
13227
+ const prelude = (async () => {
13228
+ if (gate === "hook" && !await this.vectorRemovalService.externalIndexInUse()) {
13229
+ await this.db.withTransactionAsync((tx) => this.vectorRemovalService.markExternalIndexInUse(tx));
13230
+ }
13231
+ if ((await this.vectorRemovalRepo.pendingStats()).count === 0) {
13232
+ if (gate === "force") await this.vectorRemovalService.clearExternalIndexMarker();
13233
+ return { drain: null };
13234
+ }
13235
+ if (this.options.drainExternalDeletionsOnSetup !== true) {
13236
+ if (gate === "hook") await this.vectorRemovalService.emitPending(void 0, "auto");
13237
+ return { drain: null };
13238
+ }
13239
+ const drain = (async () => {
13240
+ try {
13241
+ const r = await this.vectorRemovalService.drain(
13242
+ { all: true },
13243
+ { backoff: true, deadlineAt: Date.now() + 1e4, trigger: "auto" }
13244
+ );
13245
+ if (r.pending > 0) await this.vectorRemovalService.emitPending(void 0, "auto");
13246
+ } catch {
13247
+ emitDiagnostic(this.options, {
13248
+ code: "background_job_failed",
13249
+ operation: "externalDeletion",
13250
+ trigger: "auto",
13251
+ entityId: "",
13252
+ // store-wide drain
13253
+ detail: { reason: "unhandled_rejection" }
13254
+ });
13255
+ }
13256
+ })();
13257
+ return { drain };
13258
+ })();
13259
+ const joined = prelude.then((r) => r.drain ?? void 0, () => void 0);
13260
+ this.setupRemovalDrain = joined;
13261
+ void joined.then(() => {
13262
+ if (this.setupRemovalDrain === joined) this.setupRemovalDrain = null;
13263
+ });
13264
+ await prelude;
13265
+ }
13266
+ /**
13267
+ * Delivers owed vector-index removals now (spec §5.9). No backoff. With an
13268
+ * entity id only that entity's rows; otherwise all. `deadlineMs` is a duration.
13269
+ * `transient: true` means a ledger read or write could not run (for example,
13270
+ * you held a transaction open on the connection); the rows stay pending.
13271
+ */
13272
+ async runExternalDeletions(entityId, opts) {
13273
+ if (entityId !== void 0) assertEntityId2(entityId);
13274
+ const ms = opts?.deadlineMs;
13275
+ if (ms !== void 0 && (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)) {
13276
+ throw new TypeError("deadlineMs must be a finite number >= 0");
13277
+ }
13278
+ if (!await this.vectorRemovalService.ledgerPresent()) {
13279
+ return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
13280
+ }
13281
+ const r = await this.vectorRemovalService.drain(
13282
+ entityId === void 0 ? { all: true } : { entityId },
13283
+ { trigger: "call", ...ms !== void 0 ? { deadlineAt: Date.now() + ms } : {} }
13284
+ );
13285
+ return {
13286
+ confirmed: r.confirmed,
13287
+ pending: r.pending,
13288
+ failedIds: r.failedIds,
13289
+ timedOut: r.timedOut,
13290
+ ...r.transient ? { transient: true } : {}
13291
+ };
13292
+ }
13293
+ /** Removals still owed to the host's vector index (all entities, or one). */
13294
+ async getPendingExternalDeletions(entityId) {
13295
+ if (entityId !== void 0) assertEntityId2(entityId);
13296
+ if (!await this.vectorRemovalService.ledgerPresent()) return { count: 0, oldestEnqueuedAt: null, maxAttempts: 0 };
13297
+ return this.vectorRemovalRepo.pendingStats(entityId);
12152
13298
  }
12153
13299
  async hasChanged(entityId, sourceRefOrEntries, sourceHashArg) {
12154
13300
  if (typeof sourceRefOrEntries === "string") {
@@ -12246,7 +13392,17 @@ var WikiMemory = class {
12246
13392
  async getInstructions(entityId) {
12247
13393
  assertEntityId2(entityId);
12248
13394
  const ontologyContext = await this.ontologyService.buildPromptContext(entityId);
12249
- return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config));
13395
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
13396
+ if (diagnostic) {
13397
+ emitDiagnostic(this.options, {
13398
+ code: diagnostic.code,
13399
+ operation: "read",
13400
+ trigger: "call",
13401
+ entityId,
13402
+ detail: diagnostic.detail
13403
+ });
13404
+ }
13405
+ return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config), guidance);
12250
13406
  }
12251
13407
  /**
12252
13408
  * Returns the live source_refs for an entity, one row per ref, with the most
@@ -12316,8 +13472,9 @@ var WikiMemory = class {
12316
13472
  async write(entityId, event) {
12317
13473
  return this.writeService.write(entityId, event);
12318
13474
  }
12319
- /** Await auto-mode background librarian/heal jobs started by write(). No-op in 'deferred' mode. */
13475
+ /** Await auto-mode background librarian/heal jobs started by write(), and the removal drain `setup()` started under `drainExternalDeletionsOnSetup`. */
12320
13476
  async drain() {
13477
+ await this.setupRemovalDrain;
12321
13478
  return this.writeService.drain();
12322
13479
  }
12323
13480
  /**
@@ -12329,14 +13486,37 @@ var WikiMemory = class {
12329
13486
  async getPendingMaintenance(entityIds) {
12330
13487
  return this.maintenanceScheduler.getPending(entityIds);
12331
13488
  }
12332
- /** Run pending librarian/heal/reembed work under an optional token budget and deadline (spec §6.2). Nothing runs after it resolves. */
13489
+ /** Run pending removals, librarian, heal and reembed work under an optional token budget and deadline (spec §6.2). Awaits the setup removal drain first, when `drainExternalDeletionsOnSetup` started one. */
12333
13490
  async runPendingMaintenance(options) {
12334
- return this.maintenanceScheduler.run(options);
13491
+ let opts = options;
13492
+ const ms = options?.deadlineMs;
13493
+ if (ms !== void 0 && (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)) {
13494
+ throw new TypeError("deadlineMs must be a finite number >= 0");
13495
+ }
13496
+ const setupDrain = this.setupRemovalDrain;
13497
+ if (setupDrain) {
13498
+ if (ms !== void 0) {
13499
+ const started = Date.now();
13500
+ let handle;
13501
+ await Promise.race([
13502
+ setupDrain,
13503
+ new Promise((resolve) => {
13504
+ handle = setTimeout(resolve, ms);
13505
+ })
13506
+ ]).finally(() => {
13507
+ if (handle) clearTimeout(handle);
13508
+ });
13509
+ opts = { ...options, deadlineMs: Math.max(0, ms - (Date.now() - started)) };
13510
+ } else {
13511
+ await setupDrain;
13512
+ }
13513
+ }
13514
+ return this.maintenanceScheduler.run(opts);
12335
13515
  }
12336
13516
  /**
12337
13517
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
12338
13518
  * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
12339
- * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.
13519
+ * set `options.config.prompts.guidance` at WikiMemory construction time.
12340
13520
  */
12341
13521
  async runLibrarian(entityId, options) {
12342
13522
  return this.maintenanceService.runLibrarian(entityId, options);
@@ -12412,6 +13592,11 @@ var WikiMemory = class {
12412
13592
  * waits at least 5 s, doubling per consecutive failure up to 5 min (longer
12413
13593
  * when an attempt is itself slow), before retrying again.
12414
13594
  *
13595
+ * It also calls the host's removal hook (`onEmbeddingPersisted(…, null)`) for
13596
+ * the stashed ids that `upsertGraph` superseded, and can take up to
13597
+ * `deletionHookTimeoutMs` per id when the host's index is slow. It never
13598
+ * drains an entity's wider removal backlog.
13599
+ *
12415
13600
  * Call only after the host's transaction commits: called inside it, the
12416
13601
  * rebuild may index rows that later roll back, or miss them and clear the
12417
13602
  * stale flag anyway. Serialized with core's internal index syncs and takes
@@ -12427,6 +13612,19 @@ var WikiMemory = class {
12427
13612
  * @throws {TypeError} when `entityId` is given but is not a non-empty string.
12428
13613
  */
12429
13614
  async syncSearchIndex(entityId) {
13615
+ if (entityId !== void 0) assertEntityId2(entityId);
13616
+ const removals = this.takeRemovalIds(entityId);
13617
+ try {
13618
+ await this.syncSearchIndexCore(entityId);
13619
+ } catch (err) {
13620
+ for (const [e, ids] of removals) this.stashRemovalIds(e, ids);
13621
+ throw err;
13622
+ }
13623
+ for (const [e, ids] of removals) {
13624
+ await this.vectorRemovalService.deliverRemovals(e, ids, "upsertGraph", "call");
13625
+ }
13626
+ }
13627
+ async syncSearchIndexCore(entityId) {
12430
13628
  if (entityId === void 0) {
12431
13629
  if (!this.searchService.isKeywordAvailable() && monotonicNow() >= this.reinitRetryAt) {
12432
13630
  this.reinitSearch ?? (this.reinitSearch = (async () => {
@@ -12494,6 +13692,14 @@ var WikiMemory = class {
12494
13692
  * hard-deletes the soft-deleted rows once they are older than
12495
13693
  * `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).
12496
13694
  * `dryRun` previews the counts.
13695
+ *
13696
+ * With a removal hook (`vectorRanker.onEmbeddingPersisted`), the deleted
13697
+ * facts are recorded as owed in the same transaction and then delivered to
13698
+ * the hook before this resolves.
13699
+ *
13700
+ * @throws {WikiExternalDeletionError} when the hook didn't confirm every
13701
+ * removal. The local delete stays committed and the rest stay owed; retry,
13702
+ * or call `runExternalDeletions()`.
12497
13703
  */
12498
13704
  async forget(entityId, params, opts) {
12499
13705
  return this.maintenanceService.forget(entityId, params, opts);
@@ -12546,12 +13752,15 @@ var WikiMemory = class {
12546
13752
  * semantics identical to `ingestDocument`, minus the LLM extraction step.
12547
13753
  *
12548
13754
  * MUST be called from inside an open `db.withTransactionAsync` callback —
12549
- * the third argument is the caller's `tx`. The method does not open a
13755
+ * the third argument is the caller's `tx`, and that transaction must be
13756
+ * opened through the adapter given to `createWiki` (the removal ledger is
13757
+ * filled by triggers inside it, and a rollback discards the rows). The method does not open a
12550
13758
  * nested transaction, does not acquire any lock, and does not perform
12551
13759
  * post-commit work (search sync, embedding, cache eviction). After the
12552
13760
  * transaction commits, call `syncSearchIndex(entityId)` — or
12553
13761
  * `syncSearchIndex()` after writing several entities in one transaction —
12554
- * to make the new nodes keyword-searchable: both forms drain this call's node ids
13762
+ * to make the new nodes keyword-searchable and to deliver, through the
13763
+ * host's removal hook, the vectors of any facts the call superseded: both forms drain this call's node ids
12555
13764
  * first, to completion, so the nodes are searchable under any backlog (up to
12556
13765
  * `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with
12557
13766
  * the backlog). Embeddings still come from the maintenance
@@ -12611,6 +13820,7 @@ var WikiMemory = class {
12611
13820
  { diag: { buffer: diagBuffer, operation: "upsertGraph" } }
12612
13821
  );
12613
13822
  this.stashUpsertIds(entityId, [...supersededFactIds, ...params.nodes.map((n) => n.id)]);
13823
+ this.stashRemovalIds(entityId, supersededFactIds);
12614
13824
  this.searchService.markStale(entityId);
12615
13825
  diagBuffer.flush(this.options);
12616
13826
  return result;
@@ -12793,8 +14003,10 @@ var WikiMemory = class {
12793
14003
  }
12794
14004
  };
12795
14005
  _testAccessNonTestEnvWarned = new WeakMap();
12796
- /** Max upsertGraph node ids held for their post-commit sync (spec #280 id threading). */
14006
+ /** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */
12797
14007
  WikiMemory.UPSERT_ID_STASH_CAP = 1e4;
14008
+ /** Max superseded-fact ids held for post-commit removal delivery. */
14009
+ WikiMemory.REMOVAL_STASH_CAP = 1e4;
12798
14010
  function assertEntityId2(entityId) {
12799
14011
  if (typeof entityId !== "string" || entityId.length === 0) {
12800
14012
  throw new TypeError("Invalid entityId: must be a non-empty string.");
@@ -13781,6 +14993,7 @@ exports.PrunePartialFailureError = PrunePartialFailureError;
13781
14993
  exports.WikiBusyError = WikiBusyError;
13782
14994
  exports.WikiDraftNotFound = WikiDraftNotFound;
13783
14995
  exports.WikiDuplicateHashError = WikiDuplicateHashError;
14996
+ exports.WikiExternalDeletionError = WikiExternalDeletionError;
13784
14997
  exports.WikiGraphNodeOwnershipConflict = WikiGraphNodeOwnershipConflict;
13785
14998
  exports.WikiIngestEmptyError = WikiIngestEmptyError;
13786
14999
  exports.WikiInvalidReadOptions = WikiInvalidReadOptions;
@@ -13792,6 +15005,7 @@ exports.WikiSourceRefHashCollision = WikiSourceRefHashCollision;
13792
15005
  exports.WikiStrictOntologyViolation = WikiStrictOntologyViolation;
13793
15006
  exports.WikiSupersedeError = WikiSupersedeError;
13794
15007
  exports.WikiTransactionError = WikiTransactionError;
15008
+ exports.buildOntologyPromptAppendix = buildOntologyPromptAppendix;
13795
15009
  exports.chunkText = chunkText;
13796
15010
  exports.configureRandomSource = configureRandomSource;
13797
15011
  exports.createWiki = createWiki;