@equationalapplications/core-llm-wiki 8.2.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,738 @@ 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
+
3669
+ // src/utils/temporal.ts
3670
+ function liveAtSql(mode, alias = "") {
3671
+ const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3672
+ return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3673
+ }
3674
+ function isLiveAt(f, mode, t) {
3675
+ if (f.deleted_at != null) return false;
3676
+ const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
3677
+ if (from != null && from > t) return false;
3678
+ return f.valid_to == null || f.valid_to > t;
3679
+ }
3680
+ function assertEpochMs(name, v) {
3681
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3682
+ throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3683
+ }
3684
+ return Math.trunc(v);
3685
+ }
3686
+
3687
+ // src/repositories/EdgeRepository.ts
3688
+ var CONFIDENCE_RANK = {
3689
+ tentative: 0,
3690
+ inferred: 1,
3691
+ certain: 2
3692
+ };
3693
+ var EdgeRepository = class extends BaseRepository {
3694
+ /**
3695
+ * Insert an edge, silently skipping on primary-key or uniqueness conflicts.
3696
+ * Returns true when a row was inserted, false when skipped as a duplicate.
3697
+ * Throws when the insert was skipped due to an id collision with a different edge tuple.
3698
+ */
3699
+ async addIgnoreDuplicate(edge, tx) {
3700
+ const executor = this.getExecutor(tx);
3701
+ const result = await executor.runAsync(
3702
+ `INSERT OR IGNORE INTO ${this.prefix}edges (id, entity_id, source_id, target_id, edge_type, created_at)
3703
+ VALUES (?, ?, ?, ?, ?, ?)`,
3704
+ [edge.id, edge.entity_id, edge.source_id, edge.target_id, edge.edge_type, edge.created_at]
3705
+ );
3706
+ if (result.changes > 0) return true;
3707
+ const existing = await executor.getFirstAsync(
3708
+ `SELECT entity_id, source_id, target_id, edge_type FROM ${this.prefix}edges WHERE id = ?`,
3709
+ [edge.id]
3710
+ );
3711
+ if (!existing) return false;
3712
+ if (String(existing.entity_id) !== edge.entity_id || String(existing.source_id) !== edge.source_id || String(existing.target_id) !== edge.target_id || String(existing.edge_type) !== edge.edge_type) {
3713
+ throw new Error(
3714
+ `Edge id collision: ${JSON.stringify(edge.id)} already exists with a different (entity_id, source_id, target_id, edge_type) tuple`
3715
+ );
3716
+ }
3717
+ return false;
3718
+ }
3719
+ async getByEntityId(entityId, tx) {
3720
+ const executor = this.getExecutor(tx);
3721
+ const rows = await executor.getAllAsync(
3722
+ `SELECT * FROM ${this.prefix}edges WHERE entity_id = ? ORDER BY created_at ASC`,
3723
+ [entityId]
3724
+ );
3725
+ return rows.map(mapRowToEdge);
3726
+ }
3727
+ /** Hard delete — edges have no soft-delete concept, only presence/absence. `tx` is REQUIRED. */
3728
+ async bulkDeleteByEntityId(entityId, tx) {
3729
+ const executor = this.getExecutor(tx);
3730
+ await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);
3731
+ }
3732
+ /**
3733
+ * Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to
3734
+ * `entityId`. Returns the number of rows deleted. Edges have no soft-delete
3735
+ * concept; this method is named `softDeleteBySourceFactIds` for symmetry with
3736
+ * `EntryRepository.softDeleteBySource` (which IS a soft delete), but its
3737
+ * semantics are immediate presence/absence removal. Use ONLY inside an open
3738
+ * transaction — the method requires `tx` and performs no autocommit.
3739
+ *
3740
+ * Used by `IngestionService.upsertGraphCore` to retire the prior parse's
3741
+ * edges whose source facts are being superseded by `softDeleteBySource`.
3742
+ */
3743
+ async softDeleteBySourceFactIds(entityId, sourceFactIds, tx) {
3744
+ if (sourceFactIds.length === 0) return 0;
3745
+ const executor = this.getExecutor(tx);
3746
+ const chunkSize = 500;
3747
+ let totalChanges = 0;
3748
+ for (let i = 0; i < sourceFactIds.length; i += chunkSize) {
3749
+ const chunk = sourceFactIds.slice(i, i + chunkSize);
3750
+ const placeholders = chunk.map(() => "?").join(",");
3751
+ const result = await executor.runAsync(
3752
+ `DELETE FROM ${this.prefix}edges
3753
+ WHERE entity_id = ? AND source_id IN (${placeholders})`,
3754
+ [entityId, ...chunk]
3755
+ );
3756
+ totalChanges += result.changes;
3757
+ }
3758
+ return totalChanges;
3759
+ }
3760
+ /**
3761
+ * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
3762
+ * dead-ending, cycle-guarding, capping, and ordering happens in this one query.
3763
+ * The anchor is validated (exists, right entity, not soft-deleted) but never gated
3764
+ * by confidence/source_type — only nodes discovered beyond it are.
3765
+ */
3766
+ async getNeighborhood(entityId, sourceId, opts, tx) {
3767
+ const executor = this.getExecutor(tx);
3768
+ if (opts.edgeTypes && opts.edgeTypes.length === 0) {
3769
+ const anchor = await executor.getFirstAsync(
3770
+ `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
3771
+ [sourceId, entityId]
3772
+ );
3773
+ return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
3774
+ }
3775
+ const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
3776
+ const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
3777
+ const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
3778
+ const sql = `
3779
+ WITH RECURSIVE walk(node_id, depth, visited) AS (
3780
+ SELECT id, 0, ',' || id || ','
3781
+ FROM ${this.prefix}entries
3782
+ WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
3783
+
3784
+ UNION
3785
+
3786
+ SELECT
3787
+ CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
3788
+ w.depth + 1,
3789
+ w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
3790
+ FROM walk w
3791
+ JOIN ${this.prefix}edges e
3792
+ ON e.entity_id = ?
3793
+ AND (
3794
+ (? != 'inbound' AND e.source_id = w.node_id) OR
3795
+ (? != 'outbound' AND e.target_id = w.node_id)
3796
+ )
3797
+ AND (${edgeTypesClause})
3798
+ JOIN ${this.prefix}entries n
3799
+ ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
3800
+ AND n.entity_id = ?
3801
+ AND n.deleted_at IS NULL
3802
+ AND (
3803
+ CASE n.confidence
3804
+ WHEN 'tentative' THEN 0
3805
+ WHEN 'inferred' THEN 1
3806
+ WHEN 'certain' THEN 2
3807
+ ELSE -1
3808
+ END
3809
+ ) >= ?
3810
+ AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
3811
+ AND (? = 0 OR n.lifecycle_status != 'draft')
3812
+ AND ${liveAtSql(opts.live.mode, "n.")}
3813
+ WHERE w.depth < ?
3814
+ AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
3815
+ )
3816
+ SELECT node_id, MIN(depth) AS depth
3817
+ FROM walk
3818
+ GROUP BY node_id
3819
+ ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
3820
+ LIMIT ?
3821
+ `;
3822
+ const params = [
3823
+ sourceId,
3824
+ entityId,
3825
+ entityId,
3826
+ opts.direction,
3827
+ opts.direction,
3828
+ ...opts.edgeTypes ?? [],
3829
+ entityId,
3830
+ minConfidenceRank,
3831
+ ...opts.excludeSourceTypes,
3832
+ opts.excludeDrafts === true ? 1 : 0,
3833
+ opts.live.t,
3834
+ opts.live.t,
3835
+ opts.maxDepth,
3836
+ opts.maxNodes
3837
+ ];
3838
+ const rows = await executor.getAllAsync(sql, params);
3839
+ const nodeIds = rows.map((r) => r.node_id);
3840
+ if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
3841
+ const valueRows = nodeIds.map(() => "(?)").join(", ");
3842
+ const edgeRows = await executor.getAllAsync(
3843
+ `WITH neighborhood(node_id) AS (VALUES ${valueRows})
3844
+ SELECT e.* FROM ${this.prefix}edges e
3845
+ JOIN neighborhood ns ON e.source_id = ns.node_id
3846
+ JOIN neighborhood nt ON e.target_id = nt.node_id
3847
+ WHERE e.entity_id = ?`,
3848
+ [...nodeIds, entityId]
3849
+ );
3850
+ return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
3851
+ }
3852
+ };
3853
+ function mapRowToEdge(row) {
3854
+ return {
3855
+ id: String(row.id),
3856
+ entity_id: String(row.entity_id),
3857
+ source_id: String(row.source_id),
3858
+ target_id: String(row.target_id),
3859
+ edge_type: String(row.edge_type),
3860
+ created_at: Number(row.created_at)
3861
+ };
3862
+ }
3863
+
3112
3864
  // src/repositories/MetadataRepository.ts
3113
3865
  function entitySummaryMetaKey(entityId) {
3114
3866
  return `entity_summary:${entityId}`;
@@ -3637,8 +4389,83 @@ async function setupDatabase(db, prefix) {
3637
4389
  CREATE INDEX IF NOT EXISTS ${prefix}outbox_created_at
3638
4390
  ON ${prefix}outbox (created_at);
3639
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
+ `);
3640
4433
  await createOkfV02IndexesIfColumnsExist(db, prefix);
3641
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
+ `);
3642
4469
  }
3643
4470
  async function createOkfV02IndexesIfColumnsExist(db, prefix) {
3644
4471
  for (const table of ["entries", "tasks"]) {
@@ -3849,6 +4676,7 @@ var MIGRATIONS = [
3849
4676
  `ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`
3850
4677
  );
3851
4678
  }
4679
+ await createResurrectTrigger(db, prefix);
3852
4680
  }
3853
4681
  },
3854
4682
  {
@@ -4042,6 +4870,7 @@ var MIGRATIONS = [
4042
4870
  for (const [name, sql] of adds) {
4043
4871
  if (!existing.has(name)) await db.execAsync(sql);
4044
4872
  }
4873
+ await createResurrectTrigger(db, prefix);
4045
4874
  }
4046
4875
  },
4047
4876
  {
@@ -4122,7 +4951,7 @@ var NORMALIZE_STAMP_SCHEMA_VERSION = 14;
4122
4951
  var NORMALIZE_STAMP_KEY = "source_ref_normalize_stamp";
4123
4952
  var ENTRIES_WM_KEY = "normalize_v14_entries_wm";
4124
4953
  var SRI_WM_KEY = "normalize_v14_sri_wm";
4125
- var CHUNK = 500;
4954
+ var CHUNK2 = 500;
4126
4955
  function stampMatches(raw) {
4127
4956
  return parseJsonObject(raw)?.normalize_alg === SOURCE_REF_NORMALIZE_ALG;
4128
4957
  }
@@ -4155,7 +4984,7 @@ async function runPass(db, prefix, meta, table, key, stampOnCompletion) {
4155
4984
  let next = from;
4156
4985
  await db.withTransactionAsync(async (tx) => {
4157
4986
  const rows = await tx.getAllAsync(
4158
- `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}`,
4159
4988
  [from]
4160
4989
  );
4161
4990
  for (const r of rows) {
@@ -4170,7 +4999,7 @@ async function runPass(db, prefix, meta, table, key, stampOnCompletion) {
4170
4999
  await tx.runAsync(`UPDATE ${prefix}source_ref_index SET source_ref = ? WHERE rowid = ?`, [n, r.rowid]);
4171
5000
  }
4172
5001
  }
4173
- if (rows.length < CHUNK) {
5002
+ if (rows.length < CHUNK2) {
4174
5003
  await meta.deleteMeta(key, tx);
4175
5004
  if (stampOnCompletion) await writeNormalizeStamp(meta, tx);
4176
5005
  next = null;
@@ -4472,7 +5301,9 @@ async function runExtract(deps, ctx, batch) {
4472
5301
  const base = { entityId, operation: "librarian", trigger };
4473
5302
  const diagnostics = [];
4474
5303
  const byLabel = new Map(batch.map((l) => [l.label, l]));
4475
- const newestAt = batch[batch.length - 1].at;
5304
+ let newestAt = batch[0].at;
5305
+ for (const l of batch) if (l.at > newestAt) newestAt = l.at;
5306
+ const defaultValidFrom = Math.min(newestAt, Date.now());
4476
5307
  const candidates = [];
4477
5308
  (Array.isArray(parsed.facts) ? parsed.facts : []).forEach((raw, index) => {
4478
5309
  const fact = validateFact(raw);
@@ -4482,7 +5313,7 @@ async function runExtract(deps, ctx, batch) {
4482
5313
  }
4483
5314
  const r = raw;
4484
5315
  const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
4485
- const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : newestAt);
5316
+ const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
4486
5317
  candidates.push({ index, fact, sourceLabel, validFrom });
4487
5318
  });
4488
5319
  const tasks = [];
@@ -4671,24 +5502,6 @@ async function runResolve(deps, ctx, ambiguous) {
4671
5502
  return out;
4672
5503
  }
4673
5504
 
4674
- // src/utils/temporal.ts
4675
- function liveAtSql(mode, alias = "") {
4676
- const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
4677
- return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
4678
- }
4679
- function isLiveAt(f, mode, t) {
4680
- if (f.deleted_at != null) return false;
4681
- const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
4682
- if (from != null && from > t) return false;
4683
- return f.valid_to == null || f.valid_to > t;
4684
- }
4685
- function assertEpochMs(name, v) {
4686
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
4687
- throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
4688
- }
4689
- return Math.trunc(v);
4690
- }
4691
-
4692
5505
  // src/services/TemporalService.ts
4693
5506
  var HISTORY_MAX_DEPTH = 100;
4694
5507
  var TemporalService = class {
@@ -5070,7 +5883,7 @@ var formatSkipError = (err) => {
5070
5883
  return base;
5071
5884
  };
5072
5885
  var MaintenanceService = class {
5073
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
5886
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
5074
5887
  this.db = db;
5075
5888
  this.prefix = prefix;
5076
5889
  this.options = options;
@@ -5083,7 +5896,10 @@ var MaintenanceService = class {
5083
5896
  this.jobManager = jobManager;
5084
5897
  this.embeddingService = embeddingService;
5085
5898
  this.ontologyService = ontologyService;
5899
+ this.vectorRemoval = vectorRemoval;
5900
+ this.vectorRemovalRepo = vectorRemovalRepo;
5086
5901
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
5902
+ this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
5087
5903
  }
5088
5904
  async runPrune(entityId, options) {
5089
5905
  this.jobManager.acquireLock("prune", entityId);
@@ -5095,11 +5911,14 @@ var MaintenanceService = class {
5095
5911
  this._validatePruneDuration(retainEventsFor, "retainEventsFor");
5096
5912
  const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
5097
5913
  this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
5914
+ const gate = removalGate(this.options);
5915
+ if (gate === "hook") this.embeddingService.validateDeletionTimeout();
5098
5916
  const now = Date.now();
5099
5917
  let syncedIds = [];
5100
5918
  let deletedEntries = 0;
5101
5919
  let deletedTasks = 0;
5102
5920
  let deletedEvents = 0;
5921
+ let prunePartial = null;
5103
5922
  if (pruneSupersededAfter !== null) {
5104
5923
  const expiredCutoff = now - pruneSupersededAfter * 864e5;
5105
5924
  const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
@@ -5108,55 +5927,89 @@ var MaintenanceService = class {
5108
5927
  await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
5109
5928
  });
5110
5929
  syncedIds = [...expiredIds];
5930
+ if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
5931
+ await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
5932
+ }
5111
5933
  }
5112
5934
  }
5113
5935
  if (retainSoftDeletedFor !== null) {
5114
5936
  const cutoff = now - retainSoftDeletedFor * 864e5;
5115
5937
  const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
5116
- const succeeded = [];
5117
- let failure = null;
5118
- for (const row of entriesToDelete) {
5119
- try {
5120
- await this.embeddingService.notifyEmbeddingPersistedOrThrow(row.entity_id, row.id, null);
5121
- succeeded.push({ entity_id: row.entity_id, id: row.id });
5122
- } catch (err) {
5123
- failure = { factId: row.id, cause: err };
5124
- 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();
5125
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];
5126
5973
  }
5127
- const succeededIds = succeeded.map((r) => r.id);
5128
- syncedIds = [...syncedIds, ...succeededIds];
5974
+ const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
5129
5975
  await this.db.withTransactionAsync(async (tx) => {
5130
- if (succeededIds.length > 0) {
5131
- 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
+ }
5132
5997
  }
5133
5998
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
5134
5999
  });
5135
- if (failure) {
5136
- await this.searchService.syncEntries(entityId, syncedIds);
5137
- const remaining = entriesToDelete.length - succeeded.length - 1;
5138
- const isTimeout = failure.cause?.[HOOK_TIMEOUT_MARKER] === true;
5139
- if (isTimeout) {
5140
- throw new PrunePartialFailureError(
5141
- succeeded.length,
5142
- failure.factId,
5143
- remaining,
5144
- new Error("Deletion hook timed out"),
5145
- deletedTasks,
5146
- 0
5147
- );
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) };
5148
6012
  }
5149
- const errMsg = failure.cause?.message ?? "";
5150
- const isValidationError = errMsg.startsWith("Invalid deletionHookTimeoutMs");
5151
- const sanitizedCause = isValidationError ? failure.cause : this._sanitizeRankerError(failure.cause);
5152
- throw new PrunePartialFailureError(
5153
- succeeded.length,
5154
- failure.factId,
5155
- remaining,
5156
- sanitizedCause,
5157
- deletedTasks,
5158
- 0
5159
- );
5160
6013
  }
5161
6014
  }
5162
6015
  if (retainEventsFor !== null) {
@@ -5193,6 +6046,16 @@ var MaintenanceService = class {
5193
6046
  await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5194
6047
  }
5195
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
+ }
5196
6059
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
5197
6060
  } finally {
5198
6061
  this.jobManager.releaseLock("prune", entityId);
@@ -5297,6 +6160,7 @@ var MaintenanceService = class {
5297
6160
  }
5298
6161
  const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
5299
6162
  if (result.ok) embedded++;
6163
+ else if (result.kind === "fact_deleted") skipped++;
5300
6164
  else failed++;
5301
6165
  }
5302
6166
  if (embedded > 0) {
@@ -5314,6 +6178,9 @@ var MaintenanceService = class {
5314
6178
  if (params.clearAll && (params.entryId !== void 0 || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
5315
6179
  throw new Error("forget() clearAll is mutually exclusive with entryId, taskId, sourceRef, and sourceHash");
5316
6180
  }
6181
+ if (params.includeEvents && !params.clearAll) {
6182
+ throw new Error("forget() includeEvents requires clearAll: true");
6183
+ }
5317
6184
  if (opts?.dryRun === true) {
5318
6185
  return this.forgetDryRun(entityId, params);
5319
6186
  }
@@ -5322,13 +6189,24 @@ var MaintenanceService = class {
5322
6189
  const now = Date.now();
5323
6190
  let deletedEntries = 0;
5324
6191
  let deletedTasks = 0;
6192
+ let deletedEvents = 0;
5325
6193
  const deletedEntryIds = [];
6194
+ const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
5326
6195
  await this.db.withTransactionAsync(async (tx) => {
5327
6196
  if (params.clearAll) {
5328
- deletedEntryIds.push(...await this.entryRepo.findIdsBySource(entityId, null, null, tx, true));
6197
+ for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
5329
6198
  deletedEntries = await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
5330
6199
  deletedTasks = await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
5331
- await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
6200
+ if (await this.sourceRefIndexPresent(tx)) {
6201
+ await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
6202
+ }
6203
+ await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
6204
+ if (params.includeEvents) {
6205
+ deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
6206
+ await this.metadataRepo.deleteCheckpoint(entityId, tx);
6207
+ } else {
6208
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
6209
+ }
5332
6210
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
5333
6211
  } else {
5334
6212
  const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
@@ -5346,7 +6224,7 @@ var MaintenanceService = class {
5346
6224
  if (entryId) deletedEntryIds.push(entryId);
5347
6225
  }
5348
6226
  if (sourceRef || sourceHash) {
5349
- deletedEntryIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true));
6227
+ for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
5350
6228
  }
5351
6229
  const entryPromise = params.entryId ? this.entryRepo.softDelete(params.entryId, entityId, tx).then((r) => r.changes > 0) : null;
5352
6230
  const taskDeletedPromise = params.taskId ? this.taskRepo.softDeleteById(params.taskId, entityId, tx).then((r) => r.changes > 0) : null;
@@ -5362,29 +6240,78 @@ var MaintenanceService = class {
5362
6240
  if (taskResult) deletedTasks++;
5363
6241
  deletedEntries += refResult;
5364
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
+ }
5365
6246
  });
5366
6247
  const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
5367
6248
  await this.searchService.syncEntries(entityId, uniqueDeletedIds);
5368
- 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;
5369
6257
  try {
5370
- await this.embeddingService.notifyEmbeddingPersistedOrThrow(entityId, factId, null);
5371
- } catch (hookErr) {
5372
- const isTimeout = hookErr?.[HOOK_TIMEOUT_MARKER] === true;
5373
- if (isTimeout) {
5374
- 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;
5375
6273
  }
6274
+ } catch (hookErr) {
5376
6275
  const errMsg = hookErr?.message ?? "";
5377
6276
  if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
5378
- throw new Error(`forget(${entityId}/${factId}) failed: ${errMsg}`, { cause: hookErr });
6277
+ throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
5379
6278
  }
5380
- 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
+ });
5381
6291
  }
5382
6292
  }
5383
- return params.clearAll ? { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks } };
6293
+ if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
6294
+ return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
5384
6295
  } finally {
5385
6296
  this.jobManager.releaseLock("forget", entityId);
5386
6297
  }
5387
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
+ }
5388
6315
  /**
5389
6316
  * Whether forget() should soft-delete in source_ref_index (#316,
5390
6317
  * specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
@@ -5431,6 +6358,10 @@ var MaintenanceService = class {
5431
6358
  if (params.clearAll) {
5432
6359
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
5433
6360
  const tasks = await this.taskRepo.countLiveByEntityId(entityId);
6361
+ if (params.includeEvents) {
6362
+ const events = await this.eventRepo.count(entityId);
6363
+ return { deleted: { entries: entries2, tasks, events }, metadataReset: true };
6364
+ }
5434
6365
  return { deleted: { entries: entries2, tasks }, metadataReset: true };
5435
6366
  }
5436
6367
  const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
@@ -5578,14 +6509,7 @@ var MaintenanceService = class {
5578
6509
  staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
5579
6510
  }
5580
6511
  });
5581
- for (const factId of orphanedIds) {
5582
- try {
5583
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
5584
- } catch (hookErr) {
5585
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal orphan pass for ${factId}:`, hookErr);
5586
- emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
5587
- }
5588
- }
6512
+ await this.deliverHealRemovals(entityId, orphanedIds, trigger);
5589
6513
  const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
5590
6514
  const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
5591
6515
  if (healCandidates.length === 0 || keywordUnavailable) {
@@ -5774,14 +6698,7 @@ var MaintenanceService = class {
5774
6698
  ...insertedFacts.map((f) => f.id)
5775
6699
  ]));
5776
6700
  await this.searchService.syncEntries(entityId, healSyncIds);
5777
- for (const factId of uniqueDeletedFactIds) {
5778
- try {
5779
- await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
5780
- } catch (hookErr) {
5781
- console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
5782
- emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
5783
- }
5784
- }
6701
+ await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
5785
6702
  for (const fact of insertedFacts) {
5786
6703
  await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
5787
6704
  }
@@ -6207,7 +7124,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6207
7124
  var IMPORT_TITLE_MAX = 500;
6208
7125
  var IMPORT_BODY_MAX = 8e3;
6209
7126
  var ImportExportService = class {
6210
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
7127
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
6211
7128
  this.db = db;
6212
7129
  this.entryRepo = entryRepo;
6213
7130
  this.taskRepo = taskRepo;
@@ -6218,6 +7135,7 @@ var ImportExportService = class {
6218
7135
  this.jobManager = jobManager;
6219
7136
  this.embeddingService = embeddingService;
6220
7137
  this.options = options;
7138
+ this.vectorRemoval = vectorRemoval;
6221
7139
  }
6222
7140
  async exportDump(entityIds) {
6223
7141
  let ids;
@@ -6593,8 +7511,20 @@ var ImportExportService = class {
6593
7511
  body: clipped?.body ?? fact.body,
6594
7512
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
6595
7513
  }, { operation: "importDump", trigger: "call" });
6596
- if (!embedded) {
6597
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
7514
+ if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
7515
+ try {
7516
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
7517
+ } catch (hookErr) {
7518
+ console.warn(
7519
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
7520
+ hookErr
7521
+ );
7522
+ this.embeddingService.reportHookFailed(
7523
+ { operation: "importDump", trigger: "call" },
7524
+ entityId,
7525
+ fact.id
7526
+ );
7527
+ }
6598
7528
  }
6599
7529
  }
6600
7530
  }
@@ -6623,16 +7553,26 @@ var ImportExportService = class {
6623
7553
  fact.id
6624
7554
  );
6625
7555
  }
7556
+ if (this.embeddingService.hasVectorHook()) {
7557
+ await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
7558
+ }
6626
7559
  }
6627
7560
  }
6628
- for (const factId of softDeletedFactIds) {
6629
- 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) {
6630
7574
  try {
6631
- await this.embeddingService.notifyEmbeddingPersisted(
6632
- entityId,
6633
- factId,
6634
- null
6635
- );
7575
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
6636
7576
  } catch (hookErr) {
6637
7577
  console.warn(
6638
7578
  `[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
@@ -6869,27 +7809,62 @@ var EmbeddingService = class {
6869
7809
  }
6870
7810
  /**
6871
7811
  * Storage half: persist the computed vector to the entry row, then fire the
6872
- * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` only — embed
6873
- * 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).
6874
7816
  */
6875
7817
  async storeFactVector(fact, float32Vector, ctx) {
7818
+ let stored = true;
6876
7819
  try {
6877
7820
  await this.storeEmbeddingDimension(float32Vector.length);
6878
7821
  const blob = new Uint8Array(float32Vector.buffer);
6879
- await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
7822
+ stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
6880
7823
  } catch (err) {
6881
7824
  console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
6882
7825
  this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
6883
7826
  return { ok: false, kind: "storage_error" };
6884
7827
  }
7828
+ if (!stored) return { ok: false, kind: "fact_deleted" };
6885
7829
  try {
6886
7830
  await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
6887
7831
  } catch (hookErr) {
6888
7832
  console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
6889
7833
  this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
6890
7834
  }
7835
+ if (this.hasVectorHook()) {
7836
+ await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
7837
+ }
6891
7838
  return { ok: true, dimension: float32Vector.length };
6892
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
+ }
6893
7868
  reportEmbed(ctx, fact, code, reason) {
6894
7869
  if (!ctx) return;
6895
7870
  emitDiagnostic(this.options, {
@@ -6921,6 +7896,48 @@ var EmbeddingService = class {
6921
7896
  const result = await this.tryEmbedFact(fact, ctx);
6922
7897
  return result.ok;
6923
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
+ }
6924
7941
  async notifyEmbeddingPersisted(entityId, factId, vector) {
6925
7942
  if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
6926
7943
  const vectorCopy = vector ? vector.slice() : null;
@@ -6930,15 +7947,72 @@ var EmbeddingService = class {
6930
7947
  vector: vectorCopy
6931
7948
  });
6932
7949
  }
6933
- async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
6934
- if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
6935
- if (this.options.forceDeleteIgnoreRankerHook === true) return;
6936
- const vectorCopy = vector ? vector.slice() : null;
7950
+ validateDeletionTimeout() {
6937
7951
  const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
6938
7952
  if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
6939
7953
  throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
6940
7954
  }
6941
- 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();
6942
8016
  let timeoutHandle;
6943
8017
  const timeoutPromise = new Promise((_, reject) => {
6944
8018
  timeoutHandle = setTimeout(() => {
@@ -7919,6 +8993,6 @@ var WriteService = class {
7919
8993
  }
7920
8994
  };
7921
8995
 
7922
- export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, 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 };
7923
- //# sourceMappingURL=chunk-FOX6TNFO.mjs.map
7924
- //# sourceMappingURL=chunk-FOX6TNFO.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