@equationalapplications/core-llm-wiki 8.3.0 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -72,6 +72,17 @@ var WikiBusyError = class extends Error {
72
72
  this.entityId = entityId;
73
73
  }
74
74
  };
75
+ var WikiExternalDeletionError = class extends Error {
76
+ constructor(message, params) {
77
+ super(message, params.cause ? { cause: params.cause } : void 0);
78
+ this.code = "WIKI_EXTERNAL_DELETION";
79
+ this.name = "WikiExternalDeletionError";
80
+ this.entityId = params.entityId;
81
+ this.unconfirmedIds = params.unconfirmedIds;
82
+ this.unconfirmedCount = params.unconfirmedCount;
83
+ this.timedOut = params.timedOut;
84
+ }
85
+ };
75
86
  var WikiDuplicateHashError = class extends Error {
76
87
  constructor(params) {
77
88
  super(`Duplicate source hash for entity ${params.entityId}; another ref already holds this content`);
@@ -572,14 +583,14 @@ function chunkText(input, maxChunkLength, overlap) {
572
583
  if (!Number.isInteger(overlap) || overlap < 0 || overlap >= maxChunkLength) {
573
584
  throw new Error("overlap must be a non-negative integer < maxChunkLength");
574
585
  }
575
- const chunks = [];
586
+ const chunks2 = [];
576
587
  let truncated = false;
577
588
  let cursor = 0;
578
589
  const halfMax = Math.floor(maxChunkLength / 2);
579
590
  while (cursor < text.length) {
580
591
  const remaining = text.length - cursor;
581
592
  if (remaining <= maxChunkLength) {
582
- chunks.push(safeSlice(text, cursor, text.length));
593
+ chunks2.push(safeSlice(text, cursor, text.length));
583
594
  break;
584
595
  }
585
596
  const windowEnd = cursor + maxChunkLength;
@@ -611,11 +622,11 @@ function chunkText(input, maxChunkLength, overlap) {
611
622
  truncated = true;
612
623
  splitPoint = windowEnd;
613
624
  }
614
- chunks.push(safeSlice(text, cursor, splitPoint));
625
+ chunks2.push(safeSlice(text, cursor, splitPoint));
615
626
  const next = Math.max(splitPoint - overlap, cursor + 1);
616
627
  cursor = next;
617
628
  }
618
- return { chunks, truncated };
629
+ return { chunks: chunks2, truncated };
619
630
  }
620
631
  async function withConcurrency(tasks, limit) {
621
632
  const results = new Array(tasks.length);
@@ -2182,7 +2193,9 @@ var SEVERITY = {
2182
2193
  read_budget: "info",
2183
2194
  event_retention_held: "info",
2184
2195
  event_created_at_clamped: "warn",
2185
- event_created_at_restamped: "info"
2196
+ event_created_at_restamped: "info",
2197
+ external_deletion_pending: "warn",
2198
+ external_deletion_discarded: "warn"
2186
2199
  };
2187
2200
  var MESSAGE = {
2188
2201
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2206,7 +2219,9 @@ var MESSAGE = {
2206
2219
  read_budget: "A read was packed to a token budget.",
2207
2220
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
2208
2221
  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.",
2209
- 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."
2222
+ 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.",
2223
+ external_deletion_pending: "Removals owed to the external vector index are still pending.",
2224
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
2210
2225
  };
2211
2226
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2212
2227
  function copyDetail(detail) {
@@ -2387,7 +2402,7 @@ function zeroChunkResult(duplicateOf) {
2387
2402
  return result;
2388
2403
  }
2389
2404
  var IngestionService = class {
2390
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
2405
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
2391
2406
  this.db = db;
2392
2407
  this.prefix = prefix;
2393
2408
  this.options = options;
@@ -2399,6 +2414,7 @@ var IngestionService = class {
2399
2414
  this.jobManager = jobManager;
2400
2415
  this.embeddingService = embeddingService;
2401
2416
  this.ontologyService = ontologyService;
2417
+ this.vectorRemoval = vectorRemoval;
2402
2418
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
2403
2419
  }
2404
2420
  async ingestDocument(entityId, params, opts) {
@@ -2429,12 +2445,12 @@ var IngestionService = class {
2429
2445
  return zeroChunkResult(canonical);
2430
2446
  }
2431
2447
  }
2432
- const { chunks, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2433
- if (chunks.length === 0) return zeroChunkResult();
2448
+ const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2449
+ if (chunks2.length === 0) return zeroChunkResult();
2434
2450
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
2435
2451
  const ingestGrounding = this.promptService.groundingFor("ingest");
2436
2452
  const chunkResults = await withConcurrency(
2437
- chunks.map((chunk, chunkIndex) => async () => {
2453
+ chunks2.map((chunk, chunkIndex) => async () => {
2438
2454
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
2439
2455
  chunk,
2440
2456
  params.promptOverride,
@@ -2492,7 +2508,7 @@ var IngestionService = class {
2492
2508
  position: null,
2493
2509
  message: safeErrorToString(e)
2494
2510
  };
2495
- const total = chunks.length;
2511
+ const total = chunks2.length;
2496
2512
  const tags = [];
2497
2513
  if (failure.tier) tags.push(`tier=${failure.tier}`);
2498
2514
  if (failure.position !== null) tags.push(`position=${failure.position}`);
@@ -2569,11 +2585,11 @@ var IngestionService = class {
2569
2585
  }
2570
2586
  });
2571
2587
  }
2572
- if (failedChunks === chunks.length) {
2588
+ if (failedChunks === chunks2.length) {
2573
2589
  throw new WikiIngestEmptyError({
2574
2590
  parseFailures: failures,
2575
2591
  sourceRef,
2576
- chunks: chunks.length
2592
+ chunks: chunks2.length
2577
2593
  });
2578
2594
  }
2579
2595
  const insertedFacts = [];
@@ -2611,18 +2627,22 @@ var IngestionService = class {
2611
2627
  );
2612
2628
  if (failedChunks === 0) {
2613
2629
  const uniqueDeletedSourceFactIds = Array.from(new Set(deletedSourceFactIds));
2614
- for (const factId of uniqueDeletedSourceFactIds) {
2615
- try {
2616
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
2617
- } catch (hookErr) {
2618
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
2619
- emitDiagnostic(this.options, {
2620
- entityId,
2621
- operation: "ingest",
2622
- trigger: "call",
2623
- code: "hook_failed",
2624
- detail: { factId, reason: "on_embedding_persisted" }
2625
- });
2630
+ if (this.vectorRemoval) {
2631
+ await this.vectorRemoval.deliverRemovals(entityId, uniqueDeletedSourceFactIds, "ingest", "call");
2632
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
2633
+ for (const factId of uniqueDeletedSourceFactIds) {
2634
+ try {
2635
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
2636
+ } catch (hookErr) {
2637
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
2638
+ emitDiagnostic(this.options, {
2639
+ entityId,
2640
+ operation: "ingest",
2641
+ trigger: "call",
2642
+ code: "hook_failed",
2643
+ detail: { factId, reason: "on_embedding_persisted" }
2644
+ });
2645
+ }
2626
2646
  }
2627
2647
  }
2628
2648
  }
@@ -2632,7 +2652,7 @@ var IngestionService = class {
2632
2652
  this.searchService.evictCache(entityId);
2633
2653
  const result = {
2634
2654
  truncated,
2635
- chunks: chunks.length,
2655
+ chunks: chunks2.length,
2636
2656
  ingestedChunks,
2637
2657
  failedChunks
2638
2658
  };
@@ -3109,6 +3129,543 @@ var BaseRepository = class {
3109
3129
  }
3110
3130
  };
3111
3131
 
3132
+ // src/repositories/VectorRemovalRepository.ts
3133
+ var CHUNK = 500;
3134
+ function removalBackoffMs(attempts) {
3135
+ return Math.min(2 ** attempts, 3600) * 1e3;
3136
+ }
3137
+ function chunks(xs, n) {
3138
+ const out = [];
3139
+ for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n));
3140
+ return out;
3141
+ }
3142
+ var marks = (n) => new Array(n).fill("?").join(",");
3143
+ var VectorRemovalRepository = class extends BaseRepository {
3144
+ /** Name of the ledger table. */
3145
+ get ledgerTable() {
3146
+ return `${this.prefix}vector_removals`;
3147
+ }
3148
+ /** Whether `factId` exists and is not soft-deleted. */
3149
+ async isLive(factId) {
3150
+ const row = await this.db.getFirstAsync(
3151
+ `SELECT 1 AS x FROM ${this.prefix}entries WHERE id = ? AND deleted_at IS NULL`,
3152
+ [factId]
3153
+ );
3154
+ return !!row;
3155
+ }
3156
+ /**
3157
+ * Owe the host a removal for `factId` unless a live row exists (a missing row
3158
+ * counts as not live). The liveness test is part of the write, so it is
3159
+ * atomic. Returns whether a row was enqueued.
3160
+ */
3161
+ async enqueueIfNotLive(entityId, factId, now) {
3162
+ return this.db.withTransactionAsync(async (tx) => {
3163
+ const r = await tx.runAsync(
3164
+ `INSERT OR REPLACE INTO ${this.prefix}vector_removals (entity_id, fact_id, enqueued_at)
3165
+ SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM ${this.prefix}entries WHERE id = ? AND deleted_at IS NULL)`,
3166
+ [entityId, factId, now, factId]
3167
+ );
3168
+ return (r?.changes ?? 0) > 0;
3169
+ });
3170
+ }
3171
+ /** Unconfirmed rows after `cursor`, ordered by (attempts, seq). */
3172
+ async readPage(scope, cursor, limit, tx) {
3173
+ const executor = this.getExecutor(tx);
3174
+ const t = `${this.prefix}vector_removals`;
3175
+ const where = [
3176
+ "v.confirmed_at IS NULL",
3177
+ "v.seq <= ?",
3178
+ "(v.attempts > ? OR (v.attempts = ? AND v.seq > ?))"
3179
+ ];
3180
+ const args = [cursor.maxSeq, cursor.attempts, cursor.attempts, cursor.seq];
3181
+ if (scope.entityId !== void 0) {
3182
+ where.push(scope.ids !== void 0 ? "+v.entity_id = ?" : "v.entity_id = ?");
3183
+ args.push(scope.entityId);
3184
+ }
3185
+ if (scope.ids !== void 0) {
3186
+ if (scope.ids.length === 0) return [];
3187
+ where.push(`v.fact_id IN (${marks(scope.ids.length)})`);
3188
+ args.push(...scope.ids);
3189
+ }
3190
+ args.push(limit);
3191
+ return executor.getAllAsync(
3192
+ `SELECT v.seq AS seq, v.entity_id AS entity_id, v.fact_id AS fact_id,
3193
+ v.attempts AS attempts, v.last_attempt_at AS last_attempt_at,
3194
+ CASE WHEN e.id IS NULL THEN 'gone'
3195
+ WHEN e.deleted_at IS NULL THEN 'live'
3196
+ ELSE 'deleted' END AS fact_state
3197
+ FROM ${t} v
3198
+ LEFT JOIN ${this.prefix}entries e ON e.id = v.fact_id
3199
+ WHERE ${where.join(" AND ")}
3200
+ ORDER BY v.attempts, v.seq
3201
+ LIMIT ?`,
3202
+ args
3203
+ );
3204
+ }
3205
+ async maxSeq(tx) {
3206
+ const row = await this.getExecutor(tx).getFirstAsync(
3207
+ `SELECT MAX(seq) AS m FROM ${this.prefix}vector_removals`
3208
+ );
3209
+ return row?.m ?? 0;
3210
+ }
3211
+ /** Returns the number of rows changed. */
3212
+ async confirm(seqs, now, tx) {
3213
+ const executor = this.getExecutor(tx);
3214
+ let changed = 0;
3215
+ for (const c of chunks(seqs, CHUNK)) {
3216
+ const r = await executor.runAsync(
3217
+ `UPDATE ${this.prefix}vector_removals SET confirmed_at = ?
3218
+ WHERE confirmed_at IS NULL AND seq IN (${marks(c.length)})`,
3219
+ [now, ...c]
3220
+ );
3221
+ changed += r.changes;
3222
+ }
3223
+ return changed;
3224
+ }
3225
+ async bumpAttempts(seqs, now, tx) {
3226
+ const executor = this.getExecutor(tx);
3227
+ for (const c of chunks(seqs, CHUNK)) {
3228
+ await executor.runAsync(
3229
+ `UPDATE ${this.prefix}vector_removals
3230
+ SET attempts = attempts + 1, last_attempt_at = ?
3231
+ WHERE seq IN (${marks(c.length)})`,
3232
+ [now, ...c]
3233
+ );
3234
+ }
3235
+ }
3236
+ /** Delete the given rows when they are confirmed and their fact row is gone. */
3237
+ async deleteConfirmedGone(seqs, tx) {
3238
+ const executor = this.getExecutor(tx);
3239
+ for (const c of chunks(seqs, CHUNK)) {
3240
+ await executor.runAsync(
3241
+ `DELETE FROM ${this.prefix}vector_removals
3242
+ WHERE seq IN (${marks(c.length)}) AND confirmed_at IS NOT NULL
3243
+ AND NOT EXISTS (SELECT 1 FROM ${this.prefix}entries e WHERE e.id = ${this.prefix}vector_removals.fact_id)`,
3244
+ c
3245
+ );
3246
+ }
3247
+ }
3248
+ /** For stale, gone or resurrected rows. Applies to the given seqs only. */
3249
+ async deleteBySeq(seqs, tx) {
3250
+ const executor = this.getExecutor(tx);
3251
+ let changed = 0;
3252
+ for (const c of chunks(seqs, CHUNK)) {
3253
+ const r = await executor.runAsync(
3254
+ `DELETE FROM ${this.prefix}vector_removals WHERE seq IN (${marks(c.length)})`,
3255
+ c
3256
+ );
3257
+ changed += r.changes;
3258
+ }
3259
+ return changed;
3260
+ }
3261
+ /** Unconfirmed rows of `entityId` among `ids`. */
3262
+ async pendingCountForIds(entityId, ids) {
3263
+ let n = 0;
3264
+ for (const c of chunks(ids, CHUNK)) {
3265
+ const row = await this.db.getFirstAsync(
3266
+ `SELECT COUNT(*) AS c FROM ${this.prefix}vector_removals
3267
+ WHERE confirmed_at IS NULL AND +entity_id = ? AND fact_id IN (${marks(c.length)})`,
3268
+ [entityId, ...c]
3269
+ );
3270
+ n += row?.c ?? 0;
3271
+ }
3272
+ return n;
3273
+ }
3274
+ /** Enqueue ids that have no row yet. Returns the number inserted. */
3275
+ async backstopEnqueue(entityId, ids, now, tx) {
3276
+ const executor = this.getExecutor(tx);
3277
+ let inserted = 0;
3278
+ for (const c of chunks(ids, 300)) {
3279
+ const values = c.map(() => "(?, ?, ?)").join(",");
3280
+ const args = c.flatMap((id) => [entityId, id, now]);
3281
+ const r = await executor.runAsync(
3282
+ `INSERT OR IGNORE INTO ${this.prefix}vector_removals (entity_id, fact_id, enqueued_at)
3283
+ VALUES ${values}`,
3284
+ args
3285
+ );
3286
+ inserted += r.changes;
3287
+ }
3288
+ return inserted;
3289
+ }
3290
+ /**
3291
+ * Remove rows together with a hard delete of the facts. `'all'` drops every
3292
+ * row of those ids; `'confirmedGone'` drops only confirmed rows whose fact
3293
+ * row no longer exists, so a removal re-owed meanwhile is never erased.
3294
+ */
3295
+ async deleteForFacts(entityId, ids, tx, mode = "all") {
3296
+ const executor = this.getExecutor(tx);
3297
+ const extra = mode === "all" ? "" : ` AND confirmed_at IS NOT NULL
3298
+ AND NOT EXISTS (SELECT 1 FROM ${this.prefix}entries e WHERE e.id = ${this.prefix}vector_removals.fact_id)`;
3299
+ for (const c of chunks(ids, CHUNK)) {
3300
+ await executor.runAsync(
3301
+ `DELETE FROM ${this.prefix}vector_removals
3302
+ WHERE entity_id = ? AND fact_id IN (${marks(c.length)})${extra}`,
3303
+ [entityId, ...c]
3304
+ );
3305
+ }
3306
+ }
3307
+ /** Drop unconfirmed rows. Returns the count removed. */
3308
+ async discardPending(entityId, tx) {
3309
+ const executor = this.getExecutor(tx);
3310
+ const r = entityId === void 0 ? await executor.runAsync(
3311
+ `DELETE FROM ${this.prefix}vector_removals WHERE confirmed_at IS NULL`
3312
+ ) : await executor.runAsync(
3313
+ `DELETE FROM ${this.prefix}vector_removals WHERE confirmed_at IS NULL AND entity_id = ?`,
3314
+ [entityId]
3315
+ );
3316
+ return r.changes;
3317
+ }
3318
+ async pendingStats(entityId) {
3319
+ const row = await this.db.getFirstAsync(
3320
+ `SELECT COUNT(*) AS c, MIN(enqueued_at) AS o, MAX(attempts) AS m
3321
+ FROM ${this.prefix}vector_removals
3322
+ WHERE confirmed_at IS NULL${entityId === void 0 ? "" : " AND entity_id = ?"}`,
3323
+ entityId === void 0 ? [] : [entityId]
3324
+ );
3325
+ return { count: row?.c ?? 0, oldestEnqueuedAt: row?.o ?? null, maxAttempts: row?.m ?? 0 };
3326
+ }
3327
+ async entitiesWithPending() {
3328
+ const rows = await this.db.getAllAsync(
3329
+ `SELECT DISTINCT entity_id FROM ${this.prefix}vector_removals
3330
+ WHERE confirmed_at IS NULL ORDER BY entity_id`
3331
+ );
3332
+ return rows.map((r) => r.entity_id);
3333
+ }
3334
+ /**
3335
+ * Entities with at least one pending row outside backoff (never attempted,
3336
+ * or last attempted longer ago than removalBackoffMs). Same rule as the drain.
3337
+ */
3338
+ async entitiesWithDuePending(now) {
3339
+ const rows = await this.db.getAllAsync(
3340
+ `SELECT DISTINCT entity_id FROM ${this.prefix}vector_removals
3341
+ WHERE confirmed_at IS NULL
3342
+ AND (last_attempt_at IS NULL
3343
+ OR ? - last_attempt_at >= MIN(1 << MIN(attempts, 12), 3600) * 1000)
3344
+ ORDER BY entity_id`,
3345
+ [now]
3346
+ );
3347
+ return rows.map((r) => r.entity_id);
3348
+ }
3349
+ async statusFor(ids, tx) {
3350
+ const executor = this.getExecutor(tx);
3351
+ const out = /* @__PURE__ */ new Map();
3352
+ for (const c of chunks(ids, CHUNK)) {
3353
+ const rows = await executor.getAllAsync(
3354
+ `SELECT fact_id, confirmed_at FROM ${this.prefix}vector_removals
3355
+ WHERE fact_id IN (${marks(c.length)})`,
3356
+ c
3357
+ );
3358
+ for (const r of rows) out.set(r.fact_id, r.confirmed_at === null ? "pending" : "confirmed");
3359
+ }
3360
+ return out;
3361
+ }
3362
+ };
3363
+
3364
+ // src/services/VectorRemovalService.ts
3365
+ var MARKER_KEY = "external_index_in_use";
3366
+ var PAGE = 100;
3367
+ var ID_CHUNK = 500;
3368
+ var MAX_FAILED_IDS = 100;
3369
+ var MAX_CONSECUTIVE_REJECTIONS = 5;
3370
+ function removalGate(options) {
3371
+ if (options.forceDeleteIgnoreRankerHook === true) return "force";
3372
+ if (options.vectorRanker?.onEmbeddingPersisted) return "hook";
3373
+ return "none";
3374
+ }
3375
+ var VectorRemovalService = class {
3376
+ constructor(db, options, repo, embeddingService, metadataRepo) {
3377
+ this.db = db;
3378
+ this.options = options;
3379
+ this.repo = repo;
3380
+ this.embeddingService = embeddingService;
3381
+ this.metadataRepo = metadataRepo;
3382
+ this.inFlight = /* @__PURE__ */ new Map();
3383
+ this.ledgerSeen = false;
3384
+ }
3385
+ gate() {
3386
+ return removalGate(this.options);
3387
+ }
3388
+ async ledgerPresent() {
3389
+ if (this.ledgerSeen) return true;
3390
+ this.ledgerSeen = await this.metadataRepo.tableExists(this.repo.ledgerTable);
3391
+ return this.ledgerSeen;
3392
+ }
3393
+ /** One `hook_failed` diagnostic per id (the removal stays owed). */
3394
+ emitHookFailed(entityId, ids, operation, trigger) {
3395
+ for (const factId of ids) {
3396
+ emitDiagnostic(this.options, {
3397
+ entityId,
3398
+ operation,
3399
+ trigger,
3400
+ code: "hook_failed",
3401
+ detail: { factId, reason: "on_embedding_persisted" }
3402
+ });
3403
+ }
3404
+ }
3405
+ /**
3406
+ * Post-commit delivery for heal, ingest and import (spec §5.7). Never throws:
3407
+ * a failed id emits `hook_failed` and stays owed on the ledger. Without a
3408
+ * ledger table (setup never ran) it falls back to a best-effort call per id.
3409
+ * Under `forceDeleteIgnoreRankerHook` no removal call is made.
3410
+ */
3411
+ async deliverRemovals(entityId, ids, operation, trigger, fallbackIds = ids) {
3412
+ try {
3413
+ if (await this.ledgerPresent()) {
3414
+ if (ids.length === 0) return;
3415
+ const r2 = await this.drain({ entityId, ids }, { trigger });
3416
+ this.emitHookFailed(entityId, r2.failedIds, operation, trigger);
3417
+ if (r2.pending > 0 && this.gate() === "hook") await this.emitPending(entityId, trigger);
3418
+ return;
3419
+ }
3420
+ if (this.gate() !== "hook") return;
3421
+ const r = await this.embeddingService.callRemovalHookEach(entityId, [...new Set(fallbackIds)], { warn: true });
3422
+ this.emitHookFailed(entityId, r.failed, operation, trigger);
3423
+ } catch (err) {
3424
+ console.warn("[WikiMemory] removal delivery failed:", err);
3425
+ let stillPending = ids;
3426
+ try {
3427
+ const st = await this.repo.statusFor(ids);
3428
+ stillPending = ids.filter((id) => st.get(id) === "pending");
3429
+ } catch {
3430
+ }
3431
+ this.emitHookFailed(entityId, stillPending, operation, trigger);
3432
+ }
3433
+ }
3434
+ async markExternalIndexInUse(tx) {
3435
+ await this.metadataRepo.setMeta(MARKER_KEY, "1", tx);
3436
+ }
3437
+ async clearExternalIndexMarker() {
3438
+ await this.metadataRepo.deleteMeta(MARKER_KEY);
3439
+ }
3440
+ async externalIndexInUse() {
3441
+ return await this.metadataRepo.getMeta(MARKER_KEY) === "1";
3442
+ }
3443
+ async drain(scope, opts = {}) {
3444
+ const trigger = opts.trigger ?? "call";
3445
+ const entityId = "all" in scope ? void 0 : scope.entityId;
3446
+ const ids = "all" in scope ? void 0 : scope.ids;
3447
+ const gate = this.gate();
3448
+ if (gate === "none") {
3449
+ const pending = await this.pendingFor(entityId, ids);
3450
+ if (pending > 0 && await this.externalIndexInUse()) await this.emitPending(entityId, trigger);
3451
+ return { confirmed: 0, pending, failedIds: [], timedOut: false };
3452
+ }
3453
+ if (gate === "force") {
3454
+ const entities = entityId === void 0 ? await this.repo.entitiesWithPending() : [entityId];
3455
+ const counts = [];
3456
+ for (const e of entities) counts.push([e, (await this.repo.pendingStats(e)).count]);
3457
+ await this.repo.discardPending(entityId);
3458
+ await this.metadataRepo.deleteMeta(MARKER_KEY);
3459
+ for (const [e, count] of counts) {
3460
+ if (count === 0) continue;
3461
+ emitDiagnostic(this.options, {
3462
+ code: "external_deletion_discarded",
3463
+ operation: "externalDeletion",
3464
+ trigger,
3465
+ entityId: e,
3466
+ detail: { count }
3467
+ });
3468
+ }
3469
+ return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
3470
+ }
3471
+ const timeoutMs = this.embeddingService.validateDeletionTimeout();
3472
+ const result = { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
3473
+ let timeoutErr;
3474
+ let firstRejection;
3475
+ let consecutive = 0;
3476
+ let stop = false;
3477
+ let transient = false;
3478
+ const tried = /* @__PURE__ */ new Set();
3479
+ let scopes;
3480
+ let maxSeq;
3481
+ try {
3482
+ 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 }));
3483
+ maxSeq = await this.repo.maxSeq();
3484
+ } catch {
3485
+ result.transient = true;
3486
+ try {
3487
+ result.pending = await this.pendingFor(entityId, ids);
3488
+ } catch {
3489
+ }
3490
+ return result;
3491
+ }
3492
+ const perEntity = entityId === void 0;
3493
+ for (const sc of scopes) {
3494
+ if (stop || transient) break;
3495
+ let cursor = { maxSeq, attempts: -1, seq: 0 };
3496
+ let scopeDone = false;
3497
+ if (perEntity) consecutive = 0;
3498
+ while (!stop && !scopeDone) {
3499
+ let page;
3500
+ try {
3501
+ page = await this.db.withTransactionAsync(
3502
+ (tx) => this.repo.readPage(sc, cursor, PAGE, tx)
3503
+ );
3504
+ } catch {
3505
+ transient = true;
3506
+ result.transient = true;
3507
+ break;
3508
+ }
3509
+ if (page.length === 0) break;
3510
+ const last = page[page.length - 1];
3511
+ cursor = { maxSeq, attempts: last.attempts, seq: last.seq };
3512
+ const confirmSeqs = [];
3513
+ const bumpSeqs = [];
3514
+ const deleteSeqs = [];
3515
+ const goneSeqs = [];
3516
+ for (const row of page) {
3517
+ if (tried.has(row.seq)) continue;
3518
+ if (row.fact_state === "live") {
3519
+ tried.add(row.seq);
3520
+ deleteSeqs.push(row.seq);
3521
+ continue;
3522
+ }
3523
+ if (opts.backoff === true && row.last_attempt_at !== null) {
3524
+ if (Date.now() - row.last_attempt_at < removalBackoffMs(row.attempts)) continue;
3525
+ }
3526
+ let budget = timeoutMs;
3527
+ if (opts.deadlineAt !== void 0) {
3528
+ const left = opts.deadlineAt - Date.now();
3529
+ if (left <= 0) {
3530
+ stop = true;
3531
+ break;
3532
+ }
3533
+ budget = Math.min(timeoutMs, left);
3534
+ }
3535
+ tried.add(row.seq);
3536
+ const outcome = await this.callFor(row, budget);
3537
+ if (outcome.ok) {
3538
+ consecutive = 0;
3539
+ if (row.fact_state === "gone") goneSeqs.push(row.seq);
3540
+ else confirmSeqs.push(row.seq);
3541
+ } else {
3542
+ if (!outcome.joined) bumpSeqs.push(row.seq);
3543
+ if (result.failedIds.length < MAX_FAILED_IDS) result.failedIds.push(row.fact_id);
3544
+ if (outcome.timedOut) {
3545
+ result.timedOut = true;
3546
+ result.timedOutId ?? (result.timedOutId = row.fact_id);
3547
+ timeoutErr ?? (timeoutErr = outcome.cause);
3548
+ stop = true;
3549
+ break;
3550
+ }
3551
+ firstRejection ?? (firstRejection = outcome.cause);
3552
+ if (++consecutive >= MAX_CONSECUTIVE_REJECTIONS) {
3553
+ if (perEntity) scopeDone = true;
3554
+ else stop = true;
3555
+ break;
3556
+ }
3557
+ }
3558
+ }
3559
+ if (confirmSeqs.length || bumpSeqs.length || deleteSeqs.length || goneSeqs.length) {
3560
+ const now = Date.now();
3561
+ try {
3562
+ const changed = await this.db.withTransactionAsync(async (tx) => {
3563
+ let n = 0;
3564
+ if (confirmSeqs.length) {
3565
+ n += await this.repo.confirm(confirmSeqs, now, tx);
3566
+ await this.repo.deleteConfirmedGone(confirmSeqs, tx);
3567
+ }
3568
+ if (bumpSeqs.length) await this.repo.bumpAttempts(bumpSeqs, now, tx);
3569
+ if (goneSeqs.length) n += await this.repo.deleteBySeq(goneSeqs, tx);
3570
+ if (deleteSeqs.length) await this.repo.deleteBySeq(deleteSeqs, tx);
3571
+ return n;
3572
+ });
3573
+ result.confirmed += changed;
3574
+ } catch {
3575
+ transient = true;
3576
+ result.transient = true;
3577
+ break;
3578
+ }
3579
+ }
3580
+ if (page.length < PAGE) break;
3581
+ }
3582
+ }
3583
+ result.firstCause = timeoutErr ?? firstRejection;
3584
+ try {
3585
+ result.pending = await this.pendingFor(entityId, ids);
3586
+ } catch {
3587
+ result.transient = true;
3588
+ }
3589
+ return result;
3590
+ }
3591
+ /**
3592
+ * Makes the removal call for `row`, or joins another drain's call for the
3593
+ * same seq. Never throws: the outcome says whether it succeeded, whether
3594
+ * this drain joined (only the owner bumps attempts on failure), and whether
3595
+ * the failure was a timeout.
3596
+ */
3597
+ async callFor(row, budgetMs) {
3598
+ const end = Date.now() + budgetMs;
3599
+ const left = () => Math.max(1, end - Date.now());
3600
+ let joined = false;
3601
+ try {
3602
+ let existing = this.inFlight.get(row.fact_id);
3603
+ while (existing && existing.seq !== row.seq) {
3604
+ joined = true;
3605
+ await withBudget(existing.promise.catch(() => {
3606
+ }), left());
3607
+ const next = this.inFlight.get(row.fact_id);
3608
+ existing = next === existing ? void 0 : next;
3609
+ }
3610
+ if (existing) {
3611
+ joined = true;
3612
+ await withBudget(existing.promise, left());
3613
+ return { ok: true, joined: true };
3614
+ }
3615
+ joined = false;
3616
+ const p = this.embeddingService.callRemovalHook(row.entity_id, row.fact_id, left());
3617
+ const entry = { seq: row.seq, promise: p };
3618
+ this.inFlight.set(row.fact_id, entry);
3619
+ const clear = () => {
3620
+ if (this.inFlight.get(row.fact_id) === entry) this.inFlight.delete(row.fact_id);
3621
+ };
3622
+ p.then(clear, clear);
3623
+ await p;
3624
+ return { ok: true, joined: false };
3625
+ } catch (err) {
3626
+ const e = err instanceof Error ? err : new Error(String(err));
3627
+ return { ok: false, joined, timedOut: e[HOOK_TIMEOUT_MARKER] === true, cause: e };
3628
+ }
3629
+ }
3630
+ async pendingFor(entityId, ids) {
3631
+ if (entityId !== void 0 && ids !== void 0) {
3632
+ return this.repo.pendingCountForIds(entityId, ids);
3633
+ }
3634
+ return (await this.repo.pendingStats(entityId)).count;
3635
+ }
3636
+ async emitPending(entityId, trigger) {
3637
+ const entities = entityId === void 0 ? await this.repo.entitiesWithPending() : [entityId];
3638
+ for (const e of entities) {
3639
+ const st = await this.repo.pendingStats(e);
3640
+ if (st.count === 0) continue;
3641
+ emitDiagnostic(this.options, {
3642
+ code: "external_deletion_pending",
3643
+ operation: "externalDeletion",
3644
+ trigger,
3645
+ entityId: e,
3646
+ detail: {
3647
+ count: st.count,
3648
+ ...st.oldestEnqueuedAt !== null ? { oldestEnqueuedAt: st.oldestEnqueuedAt } : {},
3649
+ maxAttempts: st.maxAttempts
3650
+ }
3651
+ });
3652
+ }
3653
+ }
3654
+ };
3655
+ function withBudget(p, ms) {
3656
+ let handle;
3657
+ const timer = new Promise((_, reject) => {
3658
+ handle = setTimeout(() => {
3659
+ const e = new Error(`onEmbeddingPersisted timed out after ${ms}ms`);
3660
+ e[HOOK_TIMEOUT_MARKER] = true;
3661
+ reject(e);
3662
+ }, ms);
3663
+ });
3664
+ return Promise.race([p, timer]).finally(() => {
3665
+ if (handle) clearTimeout(handle);
3666
+ });
3667
+ }
3668
+
3112
3669
  // src/utils/temporal.ts
3113
3670
  function liveAtSql(mode, alias = "") {
3114
3671
  const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
@@ -3832,8 +4389,83 @@ async function setupDatabase(db, prefix) {
3832
4389
  CREATE INDEX IF NOT EXISTS ${prefix}outbox_created_at
3833
4390
  ON ${prefix}outbox (created_at);
3834
4391
  `);
4392
+ await db.execAsync(`
4393
+ CREATE TABLE IF NOT EXISTS ${prefix}vector_removals (
4394
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
4395
+ entity_id TEXT NOT NULL,
4396
+ fact_id TEXT NOT NULL UNIQUE,
4397
+ enqueued_at INTEGER NOT NULL,
4398
+ attempts INTEGER NOT NULL DEFAULT 0,
4399
+ last_attempt_at INTEGER,
4400
+ confirmed_at INTEGER
4401
+ );
4402
+ CREATE INDEX IF NOT EXISTS ${prefix}vector_removals_pending
4403
+ ON ${prefix}vector_removals (entity_id, attempts, seq) WHERE confirmed_at IS NULL;
4404
+
4405
+ CREATE TRIGGER IF NOT EXISTS ${prefix}vector_removals_enqueue
4406
+ AFTER UPDATE OF deleted_at ON ${prefix}entries
4407
+ WHEN OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL
4408
+ BEGIN
4409
+ -- DELETE then INSERT, not INSERT OR REPLACE: an outer UPSERT's conflict
4410
+ -- handling would override OR REPLACE and abort on fact_id (spec rev 5).
4411
+ DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
4412
+ INSERT INTO ${prefix}vector_removals (entity_id, fact_id, enqueued_at)
4413
+ VALUES (NEW.entity_id, NEW.id, CAST(strftime('%s','now') AS INTEGER) * 1000);
4414
+ END;
4415
+
4416
+ -- A hard delete outside prune (host SQL, an older engine after a
4417
+ -- downgrade). A live fact is owed only where an external index was in use;
4418
+ -- a soft-deleted one drops the rows nothing can owe (spec rev 5).
4419
+ CREATE TRIGGER IF NOT EXISTS ${prefix}vector_removals_hard_delete
4420
+ AFTER DELETE ON ${prefix}entries
4421
+ BEGIN
4422
+ DELETE FROM ${prefix}vector_removals
4423
+ WHERE fact_id = OLD.id
4424
+ AND (OLD.deleted_at IS NULL
4425
+ OR confirmed_at IS NOT NULL
4426
+ OR NOT EXISTS (SELECT 1 FROM ${prefix}meta WHERE key = 'external_index_in_use' AND value = '1'));
4427
+ INSERT INTO ${prefix}vector_removals (entity_id, fact_id, enqueued_at)
4428
+ SELECT OLD.entity_id, OLD.id, CAST(strftime('%s','now') AS INTEGER) * 1000
4429
+ WHERE OLD.deleted_at IS NULL
4430
+ AND EXISTS (SELECT 1 FROM ${prefix}meta WHERE key = 'external_index_in_use' AND value = '1');
4431
+ END;
4432
+ `);
3835
4433
  await createOkfV02IndexesIfColumnsExist(db, prefix);
3836
4434
  await createTemporalIndexesIfColumnsExist(db, prefix);
4435
+ await createResurrectTrigger(db, prefix);
4436
+ }
4437
+ var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
4438
+ function resurrectLevel(sql) {
4439
+ if (sql.includes("embedding_failed_at")) return 2;
4440
+ return sql.includes("embedding_blob") ? 1 : 0;
4441
+ }
4442
+ async function createResurrectTrigger(db, prefix) {
4443
+ const name = `${prefix}vector_removals_resurrect`;
4444
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
4445
+ const names = new Set(cols.map((c) => c.name));
4446
+ const want = !(names.has("embedding_blob") && names.has("embedding")) ? 0 : EMBED_MARKER_COLUMNS.every((c) => names.has(c)) ? 2 : 1;
4447
+ const existing = await db.getFirstAsync(
4448
+ `SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?`,
4449
+ [name]
4450
+ );
4451
+ if (existing) {
4452
+ if (resurrectLevel(existing.sql ?? "") >= want) return;
4453
+ await db.execAsync(`DROP TRIGGER IF EXISTS ${name};`);
4454
+ }
4455
+ const clearVector = want === 0 ? "" : `
4456
+ UPDATE ${prefix}entries
4457
+ SET embedding_blob = NULL, embedding = NULL${want === 2 ? `,
4458
+ embedding_failed_at = NULL, embedding_failure_kind = NULL, embedding_attempts = 0` : ""}
4459
+ WHERE id = NEW.id
4460
+ AND EXISTS (SELECT 1 FROM ${prefix}vector_removals WHERE fact_id = NEW.id AND confirmed_at IS NOT NULL);`;
4461
+ await db.execAsync(`
4462
+ CREATE TRIGGER IF NOT EXISTS ${name}
4463
+ AFTER UPDATE OF deleted_at ON ${prefix}entries
4464
+ WHEN OLD.deleted_at IS NOT NULL AND NEW.deleted_at IS NULL
4465
+ BEGIN${clearVector}
4466
+ DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
4467
+ END;
4468
+ `);
3837
4469
  }
3838
4470
  async function createOkfV02IndexesIfColumnsExist(db, prefix) {
3839
4471
  for (const table of ["entries", "tasks"]) {
@@ -4044,6 +4676,7 @@ var MIGRATIONS = [
4044
4676
  `ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`
4045
4677
  );
4046
4678
  }
4679
+ await createResurrectTrigger(db, prefix);
4047
4680
  }
4048
4681
  },
4049
4682
  {
@@ -4237,6 +4870,7 @@ var MIGRATIONS = [
4237
4870
  for (const [name, sql] of adds) {
4238
4871
  if (!existing.has(name)) await db.execAsync(sql);
4239
4872
  }
4873
+ await createResurrectTrigger(db, prefix);
4240
4874
  }
4241
4875
  },
4242
4876
  {
@@ -4317,7 +4951,7 @@ var NORMALIZE_STAMP_SCHEMA_VERSION = 14;
4317
4951
  var NORMALIZE_STAMP_KEY = "source_ref_normalize_stamp";
4318
4952
  var ENTRIES_WM_KEY = "normalize_v14_entries_wm";
4319
4953
  var SRI_WM_KEY = "normalize_v14_sri_wm";
4320
- var CHUNK = 500;
4954
+ var CHUNK2 = 500;
4321
4955
  function stampMatches(raw) {
4322
4956
  return parseJsonObject(raw)?.normalize_alg === SOURCE_REF_NORMALIZE_ALG;
4323
4957
  }
@@ -4350,7 +4984,7 @@ async function runPass(db, prefix, meta, table, key, stampOnCompletion) {
4350
4984
  let next = from;
4351
4985
  await db.withTransactionAsync(async (tx) => {
4352
4986
  const rows = await tx.getAllAsync(
4353
- `SELECT rowid, id, source_ref FROM ${prefix}${table} WHERE rowid > ? ORDER BY rowid LIMIT ${CHUNK}`,
4987
+ `SELECT rowid, id, source_ref FROM ${prefix}${table} WHERE rowid > ? ORDER BY rowid LIMIT ${CHUNK2}`,
4354
4988
  [from]
4355
4989
  );
4356
4990
  for (const r of rows) {
@@ -4365,7 +4999,7 @@ async function runPass(db, prefix, meta, table, key, stampOnCompletion) {
4365
4999
  await tx.runAsync(`UPDATE ${prefix}source_ref_index SET source_ref = ? WHERE rowid = ?`, [n, r.rowid]);
4366
5000
  }
4367
5001
  }
4368
- if (rows.length < CHUNK) {
5002
+ if (rows.length < CHUNK2) {
4369
5003
  await meta.deleteMeta(key, tx);
4370
5004
  if (stampOnCompletion) await writeNormalizeStamp(meta, tx);
4371
5005
  next = null;
@@ -5249,7 +5883,7 @@ var formatSkipError = (err) => {
5249
5883
  return base;
5250
5884
  };
5251
5885
  var MaintenanceService = class {
5252
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
5886
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
5253
5887
  this.db = db;
5254
5888
  this.prefix = prefix;
5255
5889
  this.options = options;
@@ -5262,6 +5896,8 @@ var MaintenanceService = class {
5262
5896
  this.jobManager = jobManager;
5263
5897
  this.embeddingService = embeddingService;
5264
5898
  this.ontologyService = ontologyService;
5899
+ this.vectorRemoval = vectorRemoval;
5900
+ this.vectorRemovalRepo = vectorRemovalRepo;
5265
5901
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
5266
5902
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
5267
5903
  }
@@ -5275,11 +5911,14 @@ var MaintenanceService = class {
5275
5911
  this._validatePruneDuration(retainEventsFor, "retainEventsFor");
5276
5912
  const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
5277
5913
  this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
5914
+ const gate = removalGate(this.options);
5915
+ if (gate === "hook") this.embeddingService.validateDeletionTimeout();
5278
5916
  const now = Date.now();
5279
5917
  let syncedIds = [];
5280
5918
  let deletedEntries = 0;
5281
5919
  let deletedTasks = 0;
5282
5920
  let deletedEvents = 0;
5921
+ let prunePartial = null;
5283
5922
  if (pruneSupersededAfter !== null) {
5284
5923
  const expiredCutoff = now - pruneSupersededAfter * 864e5;
5285
5924
  const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
@@ -5288,55 +5927,89 @@ var MaintenanceService = class {
5288
5927
  await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
5289
5928
  });
5290
5929
  syncedIds = [...expiredIds];
5930
+ if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
5931
+ await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
5932
+ }
5291
5933
  }
5292
5934
  }
5293
5935
  if (retainSoftDeletedFor !== null) {
5294
5936
  const cutoff = now - retainSoftDeletedFor * 864e5;
5295
5937
  const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
5296
- const succeeded = [];
5297
- let failure = null;
5298
- for (const row of entriesToDelete) {
5299
- try {
5300
- await this.embeddingService.notifyEmbeddingPersistedOrThrow(row.entity_id, row.id, null);
5301
- succeeded.push({ entity_id: row.entity_id, id: row.id });
5302
- } catch (err) {
5303
- failure = { factId: row.id, cause: err };
5304
- break;
5938
+ const prunableIds = entriesToDelete.map((r) => r.id);
5939
+ const vr = this.vectorRemoval;
5940
+ const vrRepo = this.vectorRemovalRepo;
5941
+ const ledgerOn = !!vr && !!vrRepo && await vr.ledgerPresent();
5942
+ let deletable = prunableIds;
5943
+ let removeLedger = false;
5944
+ let kept = [];
5945
+ let timedOut = false;
5946
+ let cause;
5947
+ let firstFailed;
5948
+ let failedOrder = [];
5949
+ if (ledgerOn && vr && vrRepo) {
5950
+ if (gate === "hook" && prunableIds.length > 0) {
5951
+ await this.db.withTransactionAsync(async (tx) => {
5952
+ await vrRepo.backstopEnqueue(entityId, prunableIds, now, tx);
5953
+ });
5954
+ }
5955
+ const result = prunableIds.length > 0 ? await vr.drain({ entityId, ids: prunableIds }) : { failedIds: [], timedOut: false, firstCause: void 0 };
5956
+ if (gate === "hook") {
5957
+ timedOut = result.timedOut;
5958
+ cause = result.firstCause;
5959
+ failedOrder = result.failedIds;
5960
+ } else if (gate === "force") {
5961
+ removeLedger = true;
5962
+ } else {
5963
+ removeLedger = !await vr.externalIndexInUse();
5305
5964
  }
5965
+ } else if (gate === "hook") {
5966
+ const r = await this.embeddingService.callRemovalHookEach(entityId, prunableIds);
5967
+ const failedSet = new Set(r.failed);
5968
+ kept = r.failed;
5969
+ deletable = prunableIds.filter((id) => !failedSet.has(id));
5970
+ timedOut = r.timedOut;
5971
+ cause = r.cause;
5972
+ firstFailed = kept[0];
5306
5973
  }
5307
- const succeededIds = succeeded.map((r) => r.id);
5308
- syncedIds = [...syncedIds, ...succeededIds];
5974
+ const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
5309
5975
  await this.db.withTransactionAsync(async (tx) => {
5310
- if (succeededIds.length > 0) {
5311
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, succeededIds, tx);
5976
+ if (hookLedger && vrRepo && prunableIds.length > 0) {
5977
+ const status = await vrRepo.statusFor(prunableIds, tx);
5978
+ deletable = prunableIds.filter((id) => status.get(id) !== "pending");
5979
+ kept = prunableIds.filter((id) => status.get(id) === "pending");
5980
+ }
5981
+ if (deletable.length > 0) {
5982
+ const deletedIds = [];
5983
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
5984
+ if (hookLedger) {
5985
+ const gone = new Set(deletedIds);
5986
+ const skipped = deletable.filter((id) => !gone.has(id));
5987
+ if (skipped.length > 0) {
5988
+ const after = await vrRepo.statusFor(skipped, tx);
5989
+ kept = [...kept, ...skipped.filter((id) => after.get(id) === "pending")];
5990
+ }
5991
+ deletable = deletedIds;
5992
+ }
5993
+ if (vrRepo && ledgerOn) {
5994
+ if (removeLedger) await vrRepo.deleteForFacts(entityId, deletable, tx, "all");
5995
+ else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
5996
+ }
5312
5997
  }
5313
5998
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
5314
5999
  });
5315
- if (failure) {
5316
- await this.searchService.syncEntries(entityId, syncedIds);
5317
- const remaining = entriesToDelete.length - succeeded.length - 1;
5318
- const isTimeout = failure.cause?.[HOOK_TIMEOUT_MARKER] === true;
5319
- if (isTimeout) {
5320
- throw new PrunePartialFailureError(
5321
- succeeded.length,
5322
- failure.factId,
5323
- remaining,
5324
- new Error("Deletion hook timed out"),
5325
- deletedTasks,
5326
- 0
5327
- );
6000
+ if (hookLedger) {
6001
+ const keptSet = new Set(kept);
6002
+ firstFailed = failedOrder.find((id) => keptSet.has(id)) ?? kept[0];
6003
+ }
6004
+ syncedIds = [...syncedIds, ...deletable];
6005
+ if (kept.length > 0) {
6006
+ if (timedOut) {
6007
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("Deletion hook timed out") };
6008
+ } else if (cause === void 0) {
6009
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("external removal not confirmed") };
6010
+ } else {
6011
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: this._sanitizeRankerError(cause) };
5328
6012
  }
5329
- const errMsg = failure.cause?.message ?? "";
5330
- const isValidationError = errMsg.startsWith("Invalid deletionHookTimeoutMs");
5331
- const sanitizedCause = isValidationError ? failure.cause : this._sanitizeRankerError(failure.cause);
5332
- throw new PrunePartialFailureError(
5333
- succeeded.length,
5334
- failure.factId,
5335
- remaining,
5336
- sanitizedCause,
5337
- deletedTasks,
5338
- 0
5339
- );
5340
6013
  }
5341
6014
  }
5342
6015
  if (retainEventsFor !== null) {
@@ -5373,6 +6046,16 @@ var MaintenanceService = class {
5373
6046
  await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5374
6047
  }
5375
6048
  await this.searchService.syncEntries(entityId, syncedIds);
6049
+ if (prunePartial) {
6050
+ throw new PrunePartialFailureError(
6051
+ deletedEntries,
6052
+ prunePartial.failedAt,
6053
+ prunePartial.remaining,
6054
+ prunePartial.cause,
6055
+ deletedTasks,
6056
+ deletedEvents
6057
+ );
6058
+ }
5376
6059
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
5377
6060
  } finally {
5378
6061
  this.jobManager.releaseLock("prune", entityId);
@@ -5477,6 +6160,7 @@ var MaintenanceService = class {
5477
6160
  }
5478
6161
  const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
5479
6162
  if (result.ok) embedded++;
6163
+ else if (result.kind === "fact_deleted") skipped++;
5480
6164
  else failed++;
5481
6165
  }
5482
6166
  if (embedded > 0) {
@@ -5507,6 +6191,7 @@ var MaintenanceService = class {
5507
6191
  let deletedTasks = 0;
5508
6192
  let deletedEvents = 0;
5509
6193
  const deletedEntryIds = [];
6194
+ const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
5510
6195
  await this.db.withTransactionAsync(async (tx) => {
5511
6196
  if (params.clearAll) {
5512
6197
  for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
@@ -5555,22 +6240,54 @@ var MaintenanceService = class {
5555
6240
  if (taskResult) deletedTasks++;
5556
6241
  deletedEntries += refResult;
5557
6242
  }
6243
+ if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
6244
+ await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
6245
+ }
5558
6246
  });
5559
6247
  const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
5560
6248
  await this.searchService.syncEntries(entityId, uniqueDeletedIds);
5561
- for (const factId of uniqueDeletedIds) {
6249
+ if (uniqueDeletedIds.length > 0) {
6250
+ const firstId = uniqueDeletedIds[0];
6251
+ const vr = this.vectorRemoval;
6252
+ const vrRepo = this.vectorRemovalRepo;
6253
+ let unconfirmed = [];
6254
+ let timedOut = false;
6255
+ let cause;
6256
+ let timedOutId;
5562
6257
  try {
5563
- await this.embeddingService.notifyEmbeddingPersistedOrThrow(entityId, factId, null);
5564
- } catch (hookErr) {
5565
- const isTimeout = hookErr?.[HOOK_TIMEOUT_MARKER] === true;
5566
- if (isTimeout) {
5567
- throw new Error(`forget(${entityId}/${factId}) failed: ${hookErr.message}`);
6258
+ if (vr && vrRepo && ledgerOn) {
6259
+ const result = await vr.drain({ entityId, ids: uniqueDeletedIds });
6260
+ if (vr.gate() === "hook") {
6261
+ const status = await vrRepo.statusFor(uniqueDeletedIds);
6262
+ unconfirmed = uniqueDeletedIds.filter((id) => status.get(id) === "pending");
6263
+ timedOut = result.timedOut;
6264
+ timedOutId = result.timedOutId;
6265
+ cause = result.firstCause;
6266
+ }
6267
+ } else if (this.options.vectorRanker?.onEmbeddingPersisted && this.options.forceDeleteIgnoreRankerHook !== true) {
6268
+ const r = await this.embeddingService.callRemovalHookEach(entityId, uniqueDeletedIds);
6269
+ unconfirmed = r.failed;
6270
+ timedOut = r.timedOut;
6271
+ timedOutId = r.timedOutId;
6272
+ cause = r.cause;
5568
6273
  }
6274
+ } catch (hookErr) {
5569
6275
  const errMsg = hookErr?.message ?? "";
5570
6276
  if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
5571
- throw new Error(`forget(${entityId}/${factId}) failed: ${errMsg}`, { cause: hookErr });
6277
+ throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
5572
6278
  }
5573
- throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
6279
+ throw hookErr;
6280
+ }
6281
+ if (unconfirmed.length > 0) {
6282
+ const head = `forget(${entityId}/${(timedOut ? timedOutId : void 0) ?? unconfirmed[0]}) failed: `;
6283
+ const message = timedOut ? head + (cause?.message ?? "onEmbeddingPersisted timed out") : cause === void 0 ? head + "ANN cleanup not confirmed" : head + "ANN cleanup hook rejected";
6284
+ throw new WikiExternalDeletionError(message, {
6285
+ entityId,
6286
+ unconfirmedIds: unconfirmed.slice(0, 100),
6287
+ unconfirmedCount: unconfirmed.length,
6288
+ timedOut,
6289
+ cause: timedOut || cause === void 0 ? void 0 : this._sanitizeRankerError(cause)
6290
+ });
5574
6291
  }
5575
6292
  }
5576
6293
  if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
@@ -5579,6 +6296,22 @@ var MaintenanceService = class {
5579
6296
  this.jobManager.releaseLock("forget", entityId);
5580
6297
  }
5581
6298
  }
6299
+ /** Heal's post-commit removal delivery (spec §5.7). Never throws. */
6300
+ async deliverHealRemovals(entityId, ids, trigger) {
6301
+ if (this.vectorRemoval) {
6302
+ await this.vectorRemoval.deliverRemovals(entityId, ids, "heal", trigger);
6303
+ return;
6304
+ }
6305
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
6306
+ for (const factId of ids) {
6307
+ try {
6308
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
6309
+ } catch (hookErr) {
6310
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
6311
+ emitDiagnostic(this.options, { entityId, operation: "heal", trigger, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
6312
+ }
6313
+ }
6314
+ }
5582
6315
  /**
5583
6316
  * Whether forget() should soft-delete in source_ref_index (#316,
5584
6317
  * specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
@@ -5776,14 +6509,7 @@ var MaintenanceService = class {
5776
6509
  staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
5777
6510
  }
5778
6511
  });
5779
- for (const factId of orphanedIds) {
5780
- try {
5781
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
5782
- } catch (hookErr) {
5783
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal orphan pass for ${factId}:`, hookErr);
5784
- emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
5785
- }
5786
- }
6512
+ await this.deliverHealRemovals(entityId, orphanedIds, trigger);
5787
6513
  const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
5788
6514
  const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
5789
6515
  if (healCandidates.length === 0 || keywordUnavailable) {
@@ -5972,14 +6698,7 @@ var MaintenanceService = class {
5972
6698
  ...insertedFacts.map((f) => f.id)
5973
6699
  ]));
5974
6700
  await this.searchService.syncEntries(entityId, healSyncIds);
5975
- for (const factId of uniqueDeletedFactIds) {
5976
- try {
5977
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
5978
- } catch (hookErr) {
5979
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
5980
- emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
5981
- }
5982
- }
6701
+ await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
5983
6702
  for (const fact of insertedFacts) {
5984
6703
  await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
5985
6704
  }
@@ -6405,7 +7124,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6405
7124
  var IMPORT_TITLE_MAX = 500;
6406
7125
  var IMPORT_BODY_MAX = 8e3;
6407
7126
  var ImportExportService = class {
6408
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
7127
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
6409
7128
  this.db = db;
6410
7129
  this.entryRepo = entryRepo;
6411
7130
  this.taskRepo = taskRepo;
@@ -6416,6 +7135,7 @@ var ImportExportService = class {
6416
7135
  this.jobManager = jobManager;
6417
7136
  this.embeddingService = embeddingService;
6418
7137
  this.options = options;
7138
+ this.vectorRemoval = vectorRemoval;
6419
7139
  }
6420
7140
  async exportDump(entityIds) {
6421
7141
  let ids;
@@ -6791,7 +7511,7 @@ var ImportExportService = class {
6791
7511
  body: clipped?.body ?? fact.body,
6792
7512
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
6793
7513
  }, { operation: "importDump", trigger: "call" });
6794
- if (!embedded) {
7514
+ if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
6795
7515
  try {
6796
7516
  await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
6797
7517
  } catch (hookErr) {
@@ -6833,16 +7553,26 @@ var ImportExportService = class {
6833
7553
  fact.id
6834
7554
  );
6835
7555
  }
7556
+ if (this.embeddingService.hasVectorHook()) {
7557
+ await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
7558
+ }
6836
7559
  }
6837
7560
  }
6838
- for (const factId of softDeletedFactIds) {
6839
- if (!upsertedFactIds.has(factId) || upsertedDeletedFactIds.has(factId)) {
7561
+ const removedIds = softDeletedFactIds.filter(
7562
+ (id) => !upsertedFactIds.has(id) || upsertedDeletedFactIds.has(id)
7563
+ );
7564
+ if (this.vectorRemoval) {
7565
+ await this.vectorRemoval.deliverRemovals(
7566
+ entityId,
7567
+ Array.from(/* @__PURE__ */ new Set([...removedIds, ...upsertedDeletedFactIds])),
7568
+ "importDump",
7569
+ "call",
7570
+ removedIds
7571
+ );
7572
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
7573
+ for (const factId of removedIds) {
6840
7574
  try {
6841
- await this.embeddingService.notifyEmbeddingPersisted(
6842
- entityId,
6843
- factId,
6844
- null
6845
- );
7575
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
6846
7576
  } catch (hookErr) {
6847
7577
  console.warn(
6848
7578
  `[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
@@ -7079,27 +7809,62 @@ var EmbeddingService = class {
7079
7809
  }
7080
7810
  /**
7081
7811
  * Storage half: persist the computed vector to the entry row, then fire the
7082
- * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` only — embed
7083
- * failures do not originate here, so they cannot be marked as such (spec §3.2, D3).
7812
+ * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` (a DB error) and
7813
+ * `fact_deleted` (the row was soft-deleted or gone: no blob, no vector call, no
7814
+ * marker). Embed failures do not originate here, so they cannot be marked as
7815
+ * such (spec §3.2, D3).
7084
7816
  */
7085
7817
  async storeFactVector(fact, float32Vector, ctx) {
7818
+ let stored = true;
7086
7819
  try {
7087
7820
  await this.storeEmbeddingDimension(float32Vector.length);
7088
7821
  const blob = new Uint8Array(float32Vector.buffer);
7089
- await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
7822
+ stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
7090
7823
  } catch (err) {
7091
7824
  console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
7092
7825
  this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
7093
7826
  return { ok: false, kind: "storage_error" };
7094
7827
  }
7828
+ if (!stored) return { ok: false, kind: "fact_deleted" };
7095
7829
  try {
7096
7830
  await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
7097
7831
  } catch (hookErr) {
7098
7832
  console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
7099
7833
  this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
7100
7834
  }
7835
+ if (this.hasVectorHook()) {
7836
+ await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
7837
+ }
7101
7838
  return { ok: true, dimension: float32Vector.length };
7102
7839
  }
7840
+ hasVectorHook() {
7841
+ return !!this.options.vectorRanker?.onEmbeddingPersisted;
7842
+ }
7843
+ /**
7844
+ * Run after a vector call (resolved or not) by every path that sends one.
7845
+ * Never throws: a failure here leaves the removal owed or unrecorded, as before.
7846
+ */
7847
+ async settleAfterVectorCall(entityId, factId, operation, trigger) {
7848
+ const vr = this.vectorRemoval;
7849
+ if (!vr) return;
7850
+ const outcome = await this.recordAfterVectorCall(entityId, factId);
7851
+ if (outcome === "enqueued") {
7852
+ try {
7853
+ await vr.service.deliverRemovals(entityId, [factId], operation, trigger, []);
7854
+ } catch (err) {
7855
+ console.warn(`[WikiMemory] post-embed removal delivery failed for ${factId}:`, err);
7856
+ }
7857
+ return;
7858
+ }
7859
+ if (outcome !== "write_failed") return;
7860
+ try {
7861
+ await this.callRemovalHook(entityId, factId, this.validateDeletionTimeout());
7862
+ } catch (hookErr) {
7863
+ console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
7864
+ this.reportHookFailed({ operation, trigger }, entityId, factId);
7865
+ await this.recordAfterVectorCall(entityId, factId);
7866
+ }
7867
+ }
7103
7868
  reportEmbed(ctx, fact, code, reason) {
7104
7869
  if (!ctx) return;
7105
7870
  emitDiagnostic(this.options, {
@@ -7131,6 +7896,48 @@ var EmbeddingService = class {
7131
7896
  const result = await this.tryEmbedFact(fact, ctx);
7132
7897
  return result.ok;
7133
7898
  }
7899
+ /** Wired by WikiMemory (VectorRemovalService itself depends on this class). */
7900
+ attachVectorRemoval(service, repo) {
7901
+ this.vectorRemoval = { service, repo };
7902
+ }
7903
+ /**
7904
+ * After an embed (and its vector call) settles: owe a removal if the fact is
7905
+ * no longer live, so a vector the host just received is taken back (§5.7, G10).
7906
+ * Never throws. `'enqueued'`: a ledger row was written. `'none'`: no
7907
+ * removal hook (or the hook gate is off). `'live'`: the fact is live. A row already pending is
7908
+ * replaced (attempts reset, spec §5.2), so it counts as `'enqueued'` and
7909
+ * is sent now: the last call the host sees after this vector is `null`.
7910
+ * `'owed'`: the write failed but a pending row already holds the removal.
7911
+ * `'write_failed'`: the fact is known not live, the write failed, and its
7912
+ * row is confirmed or missing; or the store has no ledger table and the
7913
+ * fact is known not live.
7914
+ * `'unknown'`: the liveness read and the guarded write both failed.
7915
+ */
7916
+ async recordAfterVectorCall(entityId, factId) {
7917
+ const vr = this.vectorRemoval;
7918
+ if (!vr || vr.service.gate() !== "hook") return "none";
7919
+ let live;
7920
+ try {
7921
+ if (!await vr.service.ledgerPresent()) {
7922
+ return await vr.repo.isLive(factId) ? "live" : "write_failed";
7923
+ }
7924
+ live = await vr.repo.isLive(factId);
7925
+ } catch (err) {
7926
+ console.warn(`[WikiMemory] post-embed liveness read failed for ${factId}:`, err);
7927
+ }
7928
+ if (live) return "live";
7929
+ try {
7930
+ return await vr.repo.enqueueIfNotLive(entityId, factId, Date.now()) ? "enqueued" : "live";
7931
+ } catch (err) {
7932
+ console.warn(`[WikiMemory] post-embed removal could not be recorded for ${factId}:`, err);
7933
+ if (live !== false) return "unknown";
7934
+ try {
7935
+ if ((await vr.repo.statusFor([factId])).get(factId) === "pending") return "owed";
7936
+ } catch {
7937
+ }
7938
+ return "write_failed";
7939
+ }
7940
+ }
7134
7941
  async notifyEmbeddingPersisted(entityId, factId, vector) {
7135
7942
  if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
7136
7943
  const vectorCopy = vector ? vector.slice() : null;
@@ -7140,15 +7947,72 @@ var EmbeddingService = class {
7140
7947
  vector: vectorCopy
7141
7948
  });
7142
7949
  }
7143
- async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
7144
- if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
7145
- if (this.options.forceDeleteIgnoreRankerHook === true) return;
7146
- const vectorCopy = vector ? vector.slice() : null;
7950
+ validateDeletionTimeout() {
7147
7951
  const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
7148
7952
  if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
7149
7953
  throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
7150
7954
  }
7151
- const timeoutMs = rawTimeout;
7955
+ return rawTimeout;
7956
+ }
7957
+ /** Send a removal (`vector: null`) to the hook. No gate check; the caller owns the gate. */
7958
+ async callRemovalHook(entityId, factId, timeoutMs) {
7959
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) {
7960
+ throw new Error("callRemovalHook requires vectorRanker.onEmbeddingPersisted");
7961
+ }
7962
+ let timeoutHandle;
7963
+ const timeoutPromise = new Promise((_, reject) => {
7964
+ timeoutHandle = setTimeout(() => {
7965
+ const timeoutError = new Error(`onEmbeddingPersisted timed out after ${timeoutMs}ms`);
7966
+ timeoutError[HOOK_TIMEOUT_MARKER] = true;
7967
+ reject(timeoutError);
7968
+ }, timeoutMs);
7969
+ });
7970
+ const hookPromise = Promise.resolve().then(
7971
+ () => this.options.vectorRanker.onEmbeddingPersisted({ entityId, factId, vector: null })
7972
+ );
7973
+ try {
7974
+ await Promise.race([hookPromise, timeoutPromise]);
7975
+ } catch (err) {
7976
+ hookPromise.catch(() => {
7977
+ });
7978
+ throw err;
7979
+ } finally {
7980
+ if (timeoutHandle) clearTimeout(timeoutHandle);
7981
+ }
7982
+ }
7983
+ /**
7984
+ * One removal call per id for a store with no ledger table (setup() never
7985
+ * ran), so nothing records what is owed (spec §5.5.5). Stops at the first
7986
+ * timeout: a dead index costs one timeout, as in a drain (spec rev 5).
7987
+ * `failed` lists the ids not confirmed, in order; after a timeout it ends
7988
+ * with the timed-out id and every id after it. Throws only for an invalid
7989
+ * `deletionHookTimeoutMs`.
7990
+ */
7991
+ async callRemovalHookEach(entityId, ids, opts = {}) {
7992
+ const timeoutMs = this.validateDeletionTimeout();
7993
+ const failed = [];
7994
+ let firstRejection;
7995
+ for (let i = 0; i < ids.length; i++) {
7996
+ const factId = ids[i];
7997
+ try {
7998
+ await this.callRemovalHook(entityId, factId, timeoutMs);
7999
+ } catch (hookErr) {
8000
+ if (opts.warn) console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
8001
+ if (hookErr?.[HOOK_TIMEOUT_MARKER] === true) {
8002
+ failed.push(...ids.slice(i));
8003
+ return { failed, timedOut: true, timedOutId: factId, cause: hookErr };
8004
+ }
8005
+ failed.push(factId);
8006
+ firstRejection ?? (firstRejection = hookErr);
8007
+ }
8008
+ }
8009
+ return { failed, timedOut: false, cause: firstRejection };
8010
+ }
8011
+ async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
8012
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
8013
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
8014
+ const vectorCopy = vector ? vector.slice() : null;
8015
+ const timeoutMs = this.validateDeletionTimeout();
7152
8016
  let timeoutHandle;
7153
8017
  const timeoutPromise = new Promise((_, reject) => {
7154
8018
  timeoutHandle = setTimeout(() => {
@@ -8129,6 +8993,6 @@ var WriteService = class {
8129
8993
  }
8130
8994
  };
8131
8995
 
8132
- export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
8133
- //# sourceMappingURL=chunk-V432RHCG.mjs.map
8134
- //# sourceMappingURL=chunk-V432RHCG.mjs.map
8996
+ export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
8997
+ //# sourceMappingURL=chunk-EKYWAR2E.mjs.map
8998
+ //# sourceMappingURL=chunk-EKYWAR2E.mjs.map