@equationalapplications/core-llm-wiki 8.3.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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);
@@ -1774,6 +1785,14 @@ var JobManager = class {
1774
1785
  };
1775
1786
 
1776
1787
  // src/prompts.ts
1788
+ var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
1789
+ var GUIDANCE_MAX_CHARS = 2e3;
1790
+ function guidanceSection(guidance) {
1791
+ return `--- Host guidance ---
1792
+ ${guidance}
1793
+ --- End host guidance ---
1794
+ ${LEAVE_OUT_RULE_SENTENCE}`;
1795
+ }
1777
1796
  var LIBRARIAN_SYSTEM_PROMPT = `You are a knowledge extraction agent. Your job is to analyze recent episodic events and extract stable facts and actionable tasks about the user or entity.
1778
1797
  Return ONLY a valid JSON object matching this schema:
1779
1798
  {
@@ -1897,6 +1916,64 @@ var PromptService = class {
1897
1916
  this.globalOverrides = globalOverrides;
1898
1917
  this.grounding = grounding;
1899
1918
  }
1919
+ /**
1920
+ * Specs/librarian-guidance: resolve the effective guidance for one pass
1921
+ * or call — default `config.prompts.guidance`, per-entity
1922
+ * `config.librarian.guidanceForEntity` winning when it returns a
1923
+ * non-empty (trimmed) string. Synchronous: a resolver that throws,
1924
+ * returns a thenable (its rejection is swallowed with a no-op handler;
1925
+ * a throwing `then` counts too), or returns any non-string value is
1926
+ * treated as "no value" and reported in `diagnostic`. Over-cap text
1927
+ * (UTF-16 units, verbatim) is not sent and reported in `diagnostic`.
1928
+ * Emits nothing itself; the caller emits, immediately at resolution.
1929
+ */
1930
+ static resolveGuidance(config, entityId) {
1931
+ let source = null;
1932
+ let effective;
1933
+ let resolverDiagnostic;
1934
+ const defaultValue = config?.prompts?.guidance;
1935
+ const resolver = config?.librarian?.guidanceForEntity;
1936
+ let entityValue;
1937
+ if (resolver) {
1938
+ try {
1939
+ entityValue = resolver(entityId);
1940
+ if (entityValue === void 0) {
1941
+ } else if (typeof entityValue === "string") {
1942
+ if (entityValue.trim() !== "") {
1943
+ source = "per_entity";
1944
+ effective = entityValue;
1945
+ }
1946
+ } else {
1947
+ try {
1948
+ entityValue?.then?.(() => void 0, () => void 0);
1949
+ } catch {
1950
+ }
1951
+ resolverDiagnostic = {
1952
+ code: "guidance_resolver_failed",
1953
+ detail: { reason: "non_string" }
1954
+ };
1955
+ }
1956
+ } catch {
1957
+ resolverDiagnostic = { code: "guidance_resolver_failed", detail: { reason: "threw" } };
1958
+ }
1959
+ }
1960
+ if (source === null && defaultValue !== void 0 && defaultValue.trim() !== "") {
1961
+ source = "default";
1962
+ effective = defaultValue;
1963
+ }
1964
+ if (source === null || effective === void 0) {
1965
+ return resolverDiagnostic ? { diagnostic: resolverDiagnostic } : {};
1966
+ }
1967
+ if (effective.length > GUIDANCE_MAX_CHARS) {
1968
+ return {
1969
+ diagnostic: {
1970
+ code: "guidance_too_long",
1971
+ detail: { guidanceLength: effective.length, guidanceSource: source }
1972
+ }
1973
+ };
1974
+ }
1975
+ return resolverDiagnostic ? { guidance: effective, diagnostic: resolverDiagnostic } : { guidance: effective };
1976
+ }
1900
1977
  /** The resolved grounding config when `writer` is in `grounding.writers`; otherwise null (spec §6.2). */
1901
1978
  groundingFor(writer) {
1902
1979
  return this.grounding?.writers.has(writer) ? this.grounding : null;
@@ -1907,6 +1984,19 @@ var PromptService = class {
1907
1984
  return cfg ? `${systemPrompt}
1908
1985
 
1909
1986
  ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
1987
+ }
1988
+ /**
1989
+ * Specs/librarian-guidance: append the marked guidance section (with the
1990
+ * general leave-out rule) to the ALREADY-HYDRATED system prompt — after
1991
+ * ontology, immediately before grounding. The guidance text is never
1992
+ * run through hydration, so `{{…}}` inside it cannot change a builder's
1993
+ * template branch or be expanded with data. No-op on empty input.
1994
+ */
1995
+ appendGuidance(systemPrompt, guidance) {
1996
+ if (!guidance) return systemPrompt;
1997
+ return `${systemPrompt}
1998
+
1999
+ ${guidanceSection(guidance)}`;
1910
2000
  }
1911
2001
  hydrate(template, variables) {
1912
2002
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_match, key) => {
@@ -1943,31 +2033,31 @@ ${groundingEvidenceBlock(writer, cfg)}` : systemPrompt;
1943
2033
 
1944
2034
  ${ctx.ontologyModeInstructions}`;
1945
2035
  }
1946
- buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext) {
2036
+ buildIngestPrompt(documentChunk, runtimeOverride, ontologyContext, guidance) {
1947
2037
  const template = runtimeOverride ?? this.globalOverrides?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT;
1948
2038
  const hasDocumentChunk = /\{\{\s*documentChunk\s*\}\}/.test(template);
1949
2039
  if (hasDocumentChunk || this.hasOntologyPlaceholders(template)) {
1950
2040
  return {
1951
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), "ingest"),
2041
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { documentChunk }, ontologyContext), guidance), "ingest"),
1952
2042
  userPrompt: hasDocumentChunk ? "Please extract the facts." : `Document Chunk:
1953
2043
  ${documentChunk}`
1954
2044
  };
1955
2045
  }
1956
2046
  return {
1957
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "ingest"),
2047
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "ingest"),
1958
2048
  userPrompt: `Document Chunk:
1959
2049
  ${documentChunk}`
1960
2050
  };
1961
2051
  }
1962
- buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext) {
1963
- const template = runtimeOverride ?? this.globalOverrides?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT;
2052
+ buildLibrarianPrompt(events, currentFacts, runtimeOverride, ontologyContext, guidance) {
2053
+ const template = runtimeOverride ?? LIBRARIAN_SYSTEM_PROMPT;
1964
2054
  const hasEvents = /\{\{\s*events\s*\}\}/.test(template);
1965
2055
  const hasCurrentFacts = /\{\{\s*currentFacts\s*\}\}/.test(template);
1966
2056
  const eventsShown = hasEvents || !hasCurrentFacts;
1967
2057
  const corpusField = this.groundingFor("librarian") ? { groundingCorpus: buildGroundingCorpus(eventsShown ? events.map(summaryOf) : []) } : {};
1968
2058
  if (hasEvents || hasCurrentFacts || this.hasOntologyPlaceholders(template)) {
1969
2059
  return {
1970
- systemPrompt: this.appendGrounding(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), "librarian"),
2060
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(template, { events, currentFacts }, ontologyContext), guidance), "librarian"),
1971
2061
  userPrompt: hasEvents || hasCurrentFacts ? "Please synthesize the context." : `Events:
1972
2062
  ${JSON.stringify(events, null, 2)}
1973
2063
 
@@ -1977,7 +2067,7 @@ ${JSON.stringify(currentFacts, null, 2)}`,
1977
2067
  };
1978
2068
  }
1979
2069
  return {
1980
- systemPrompt: this.appendGrounding(this.appendOntology(template, ontologyContext), "librarian"),
2070
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(template, ontologyContext), guidance), "librarian"),
1981
2071
  userPrompt: `Events:
1982
2072
  ${JSON.stringify(events, null, 2)}
1983
2073
 
@@ -2080,11 +2170,11 @@ ${JSON.stringify(facts, null, 2)}`
2080
2170
  };
2081
2171
  }
2082
2172
  /** Ops extract (spec §5.2): events only — no existing facts. */
2083
- buildOpsExtractPrompt(events, ontologyContext) {
2173
+ buildOpsExtractPrompt(events, ontologyContext, guidance) {
2084
2174
  const lines = events.map((l) => `${l.label} [${new Date(l.at).toISOString()}] (${l.event.event_type}) ${l.event.summary}`);
2085
2175
  const grounding = this.groundingFor("librarian");
2086
2176
  return {
2087
- systemPrompt: this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian"),
2177
+ systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2088
2178
  userPrompt: `Events:
2089
2179
  ${lines.join("\n")}`,
2090
2180
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
@@ -2101,11 +2191,11 @@ ${JSON.stringify({ items })}` };
2101
2191
  * placeholders and leaves data placeholders verbatim; heal never receives
2102
2192
  * ontology context, matching `buildHealPrompt`.
2103
2193
  */
2104
- buildInstructionTemplates(ontologyContext, librarianStrategy) {
2194
+ buildInstructionTemplates(ontologyContext, librarianStrategy, guidance) {
2105
2195
  const o = this.globalOverrides;
2106
2196
  return {
2107
- ingest: this.appendGrounding(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), "ingest"),
2108
- librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), "librarian") : this.appendGrounding(this.buildSystemPrompt(o?.librarianSystemPrompt ?? LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), "librarian"),
2197
+ ingest: this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(o?.ingestSystemPrompt ?? INGEST_SYSTEM_PROMPT, {}, ontologyContext), guidance), "ingest"),
2198
+ librarian: librarianStrategy === "ops" ? this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian") : this.appendGrounding(this.appendGuidance(this.buildSystemPrompt(LIBRARIAN_SYSTEM_PROMPT, {}, ontologyContext), guidance), "librarian"),
2109
2199
  heal: this.appendGrounding(o?.healSystemPrompt ?? HEAL_SYSTEM_PROMPT, "heal"),
2110
2200
  ontologyBackfill: this.buildSystemPrompt(o?.ontologyBackfillSystemPrompt ?? ONTOLOGY_BACKFILL_SYSTEM_PROMPT, {}, ontologyContext)
2111
2201
  };
@@ -2182,7 +2272,11 @@ var SEVERITY = {
2182
2272
  read_budget: "info",
2183
2273
  event_retention_held: "info",
2184
2274
  event_created_at_clamped: "warn",
2185
- event_created_at_restamped: "info"
2275
+ event_created_at_restamped: "info",
2276
+ external_deletion_pending: "warn",
2277
+ external_deletion_discarded: "warn",
2278
+ guidance_too_long: "warn",
2279
+ guidance_resolver_failed: "warn"
2186
2280
  };
2187
2281
  var MESSAGE = {
2188
2282
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2206,7 +2300,11 @@ var MESSAGE = {
2206
2300
  read_budget: "A read was packed to a token budget.",
2207
2301
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
2208
2302
  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."
2303
+ 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.",
2304
+ external_deletion_pending: "Removals owed to the external vector index are still pending.",
2305
+ external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
2306
+ guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
2307
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
2210
2308
  };
2211
2309
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2212
2310
  function copyDetail(detail) {
@@ -2387,7 +2485,7 @@ function zeroChunkResult(duplicateOf) {
2387
2485
  return result;
2388
2486
  }
2389
2487
  var IngestionService = class {
2390
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
2488
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
2391
2489
  this.db = db;
2392
2490
  this.prefix = prefix;
2393
2491
  this.options = options;
@@ -2399,6 +2497,7 @@ var IngestionService = class {
2399
2497
  this.jobManager = jobManager;
2400
2498
  this.embeddingService = embeddingService;
2401
2499
  this.ontologyService = ontologyService;
2500
+ this.vectorRemoval = vectorRemoval;
2402
2501
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
2403
2502
  }
2404
2503
  async ingestDocument(entityId, params, opts) {
@@ -2429,16 +2528,27 @@ var IngestionService = class {
2429
2528
  return zeroChunkResult(canonical);
2430
2529
  }
2431
2530
  }
2432
- const { chunks, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2433
- if (chunks.length === 0) return zeroChunkResult();
2531
+ const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
2532
+ if (chunks2.length === 0) return zeroChunkResult();
2434
2533
  const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
2534
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
2535
+ if (diagnostic) {
2536
+ emitDiagnostic(this.options, {
2537
+ code: diagnostic.code,
2538
+ operation: "ingest",
2539
+ trigger: "call",
2540
+ entityId,
2541
+ detail: diagnostic.detail
2542
+ });
2543
+ }
2435
2544
  const ingestGrounding = this.promptService.groundingFor("ingest");
2436
2545
  const chunkResults = await withConcurrency(
2437
- chunks.map((chunk, chunkIndex) => async () => {
2546
+ chunks2.map((chunk, chunkIndex) => async () => {
2438
2547
  const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
2439
2548
  chunk,
2440
2549
  params.promptOverride,
2441
- ontologyContext
2550
+ ontologyContext,
2551
+ guidance
2442
2552
  );
2443
2553
  try {
2444
2554
  const responseText = await callLlm(this.options, { operation: "ingest", entityId, trigger: "call" }, { systemPrompt, userPrompt });
@@ -2492,7 +2602,7 @@ var IngestionService = class {
2492
2602
  position: null,
2493
2603
  message: safeErrorToString(e)
2494
2604
  };
2495
- const total = chunks.length;
2605
+ const total = chunks2.length;
2496
2606
  const tags = [];
2497
2607
  if (failure.tier) tags.push(`tier=${failure.tier}`);
2498
2608
  if (failure.position !== null) tags.push(`position=${failure.position}`);
@@ -2569,11 +2679,11 @@ var IngestionService = class {
2569
2679
  }
2570
2680
  });
2571
2681
  }
2572
- if (failedChunks === chunks.length) {
2682
+ if (failedChunks === chunks2.length) {
2573
2683
  throw new WikiIngestEmptyError({
2574
2684
  parseFailures: failures,
2575
2685
  sourceRef,
2576
- chunks: chunks.length
2686
+ chunks: chunks2.length
2577
2687
  });
2578
2688
  }
2579
2689
  const insertedFacts = [];
@@ -2611,18 +2721,22 @@ var IngestionService = class {
2611
2721
  );
2612
2722
  if (failedChunks === 0) {
2613
2723
  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
- });
2724
+ if (this.vectorRemoval) {
2725
+ await this.vectorRemoval.deliverRemovals(entityId, uniqueDeletedSourceFactIds, "ingest", "call");
2726
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
2727
+ for (const factId of uniqueDeletedSourceFactIds) {
2728
+ try {
2729
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
2730
+ } catch (hookErr) {
2731
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
2732
+ emitDiagnostic(this.options, {
2733
+ entityId,
2734
+ operation: "ingest",
2735
+ trigger: "call",
2736
+ code: "hook_failed",
2737
+ detail: { factId, reason: "on_embedding_persisted" }
2738
+ });
2739
+ }
2626
2740
  }
2627
2741
  }
2628
2742
  }
@@ -2632,7 +2746,7 @@ var IngestionService = class {
2632
2746
  this.searchService.evictCache(entityId);
2633
2747
  const result = {
2634
2748
  truncated,
2635
- chunks: chunks.length,
2749
+ chunks: chunks2.length,
2636
2750
  ingestedChunks,
2637
2751
  failedChunks
2638
2752
  };
@@ -3073,9 +3187,9 @@ function changedDefaultWarnings(config) {
3073
3187
  "[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
3074
3188
  );
3075
3189
  }
3076
- if (config?.prompts?.librarianSystemPrompt !== void 0 && config?.librarian?.strategy === void 0) {
3190
+ if (config?.prompts?.librarianSystemPrompt !== void 0) {
3077
3191
  warnings.push(
3078
- "[core-llm-wiki] `prompts.librarianSystemPrompt` is set, but `librarian.strategy` now defaults to 'ops', which does not use it. Set `librarian: { strategy: 'legacy' }` to keep the override."
3192
+ "[core-llm-wiki] `prompts.librarianSystemPrompt` was removed in 9.0.0 and its value is ignored. Move the domain part of it to `prompts.guidance`, which works under both librarian strategies."
3079
3193
  );
3080
3194
  }
3081
3195
  if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
@@ -3109,6 +3223,543 @@ var BaseRepository = class {
3109
3223
  }
3110
3224
  };
3111
3225
 
3226
+ // src/repositories/VectorRemovalRepository.ts
3227
+ var CHUNK = 500;
3228
+ function removalBackoffMs(attempts) {
3229
+ return Math.min(2 ** attempts, 3600) * 1e3;
3230
+ }
3231
+ function chunks(xs, n) {
3232
+ const out = [];
3233
+ for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n));
3234
+ return out;
3235
+ }
3236
+ var marks = (n) => new Array(n).fill("?").join(",");
3237
+ var VectorRemovalRepository = class extends BaseRepository {
3238
+ /** Name of the ledger table. */
3239
+ get ledgerTable() {
3240
+ return `${this.prefix}vector_removals`;
3241
+ }
3242
+ /** Whether `factId` exists and is not soft-deleted. */
3243
+ async isLive(factId) {
3244
+ const row = await this.db.getFirstAsync(
3245
+ `SELECT 1 AS x FROM ${this.prefix}entries WHERE id = ? AND deleted_at IS NULL`,
3246
+ [factId]
3247
+ );
3248
+ return !!row;
3249
+ }
3250
+ /**
3251
+ * Owe the host a removal for `factId` unless a live row exists (a missing row
3252
+ * counts as not live). The liveness test is part of the write, so it is
3253
+ * atomic. Returns whether a row was enqueued.
3254
+ */
3255
+ async enqueueIfNotLive(entityId, factId, now) {
3256
+ return this.db.withTransactionAsync(async (tx) => {
3257
+ const r = await tx.runAsync(
3258
+ `INSERT OR REPLACE INTO ${this.prefix}vector_removals (entity_id, fact_id, enqueued_at)
3259
+ SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM ${this.prefix}entries WHERE id = ? AND deleted_at IS NULL)`,
3260
+ [entityId, factId, now, factId]
3261
+ );
3262
+ return (r?.changes ?? 0) > 0;
3263
+ });
3264
+ }
3265
+ /** Unconfirmed rows after `cursor`, ordered by (attempts, seq). */
3266
+ async readPage(scope, cursor, limit, tx) {
3267
+ const executor = this.getExecutor(tx);
3268
+ const t = `${this.prefix}vector_removals`;
3269
+ const where = [
3270
+ "v.confirmed_at IS NULL",
3271
+ "v.seq <= ?",
3272
+ "(v.attempts > ? OR (v.attempts = ? AND v.seq > ?))"
3273
+ ];
3274
+ const args = [cursor.maxSeq, cursor.attempts, cursor.attempts, cursor.seq];
3275
+ if (scope.entityId !== void 0) {
3276
+ where.push(scope.ids !== void 0 ? "+v.entity_id = ?" : "v.entity_id = ?");
3277
+ args.push(scope.entityId);
3278
+ }
3279
+ if (scope.ids !== void 0) {
3280
+ if (scope.ids.length === 0) return [];
3281
+ where.push(`v.fact_id IN (${marks(scope.ids.length)})`);
3282
+ args.push(...scope.ids);
3283
+ }
3284
+ args.push(limit);
3285
+ return executor.getAllAsync(
3286
+ `SELECT v.seq AS seq, v.entity_id AS entity_id, v.fact_id AS fact_id,
3287
+ v.attempts AS attempts, v.last_attempt_at AS last_attempt_at,
3288
+ CASE WHEN e.id IS NULL THEN 'gone'
3289
+ WHEN e.deleted_at IS NULL THEN 'live'
3290
+ ELSE 'deleted' END AS fact_state
3291
+ FROM ${t} v
3292
+ LEFT JOIN ${this.prefix}entries e ON e.id = v.fact_id
3293
+ WHERE ${where.join(" AND ")}
3294
+ ORDER BY v.attempts, v.seq
3295
+ LIMIT ?`,
3296
+ args
3297
+ );
3298
+ }
3299
+ async maxSeq(tx) {
3300
+ const row = await this.getExecutor(tx).getFirstAsync(
3301
+ `SELECT MAX(seq) AS m FROM ${this.prefix}vector_removals`
3302
+ );
3303
+ return row?.m ?? 0;
3304
+ }
3305
+ /** Returns the number of rows changed. */
3306
+ async confirm(seqs, now, tx) {
3307
+ const executor = this.getExecutor(tx);
3308
+ let changed = 0;
3309
+ for (const c of chunks(seqs, CHUNK)) {
3310
+ const r = await executor.runAsync(
3311
+ `UPDATE ${this.prefix}vector_removals SET confirmed_at = ?
3312
+ WHERE confirmed_at IS NULL AND seq IN (${marks(c.length)})`,
3313
+ [now, ...c]
3314
+ );
3315
+ changed += r.changes;
3316
+ }
3317
+ return changed;
3318
+ }
3319
+ async bumpAttempts(seqs, now, tx) {
3320
+ const executor = this.getExecutor(tx);
3321
+ for (const c of chunks(seqs, CHUNK)) {
3322
+ await executor.runAsync(
3323
+ `UPDATE ${this.prefix}vector_removals
3324
+ SET attempts = attempts + 1, last_attempt_at = ?
3325
+ WHERE seq IN (${marks(c.length)})`,
3326
+ [now, ...c]
3327
+ );
3328
+ }
3329
+ }
3330
+ /** Delete the given rows when they are confirmed and their fact row is gone. */
3331
+ async deleteConfirmedGone(seqs, tx) {
3332
+ const executor = this.getExecutor(tx);
3333
+ for (const c of chunks(seqs, CHUNK)) {
3334
+ await executor.runAsync(
3335
+ `DELETE FROM ${this.prefix}vector_removals
3336
+ WHERE seq IN (${marks(c.length)}) AND confirmed_at IS NOT NULL
3337
+ AND NOT EXISTS (SELECT 1 FROM ${this.prefix}entries e WHERE e.id = ${this.prefix}vector_removals.fact_id)`,
3338
+ c
3339
+ );
3340
+ }
3341
+ }
3342
+ /** For stale, gone or resurrected rows. Applies to the given seqs only. */
3343
+ async deleteBySeq(seqs, tx) {
3344
+ const executor = this.getExecutor(tx);
3345
+ let changed = 0;
3346
+ for (const c of chunks(seqs, CHUNK)) {
3347
+ const r = await executor.runAsync(
3348
+ `DELETE FROM ${this.prefix}vector_removals WHERE seq IN (${marks(c.length)})`,
3349
+ c
3350
+ );
3351
+ changed += r.changes;
3352
+ }
3353
+ return changed;
3354
+ }
3355
+ /** Unconfirmed rows of `entityId` among `ids`. */
3356
+ async pendingCountForIds(entityId, ids) {
3357
+ let n = 0;
3358
+ for (const c of chunks(ids, CHUNK)) {
3359
+ const row = await this.db.getFirstAsync(
3360
+ `SELECT COUNT(*) AS c FROM ${this.prefix}vector_removals
3361
+ WHERE confirmed_at IS NULL AND +entity_id = ? AND fact_id IN (${marks(c.length)})`,
3362
+ [entityId, ...c]
3363
+ );
3364
+ n += row?.c ?? 0;
3365
+ }
3366
+ return n;
3367
+ }
3368
+ /** Enqueue ids that have no row yet. Returns the number inserted. */
3369
+ async backstopEnqueue(entityId, ids, now, tx) {
3370
+ const executor = this.getExecutor(tx);
3371
+ let inserted = 0;
3372
+ for (const c of chunks(ids, 300)) {
3373
+ const values = c.map(() => "(?, ?, ?)").join(",");
3374
+ const args = c.flatMap((id) => [entityId, id, now]);
3375
+ const r = await executor.runAsync(
3376
+ `INSERT OR IGNORE INTO ${this.prefix}vector_removals (entity_id, fact_id, enqueued_at)
3377
+ VALUES ${values}`,
3378
+ args
3379
+ );
3380
+ inserted += r.changes;
3381
+ }
3382
+ return inserted;
3383
+ }
3384
+ /**
3385
+ * Remove rows together with a hard delete of the facts. `'all'` drops every
3386
+ * row of those ids; `'confirmedGone'` drops only confirmed rows whose fact
3387
+ * row no longer exists, so a removal re-owed meanwhile is never erased.
3388
+ */
3389
+ async deleteForFacts(entityId, ids, tx, mode = "all") {
3390
+ const executor = this.getExecutor(tx);
3391
+ const extra = mode === "all" ? "" : ` AND confirmed_at IS NOT NULL
3392
+ AND NOT EXISTS (SELECT 1 FROM ${this.prefix}entries e WHERE e.id = ${this.prefix}vector_removals.fact_id)`;
3393
+ for (const c of chunks(ids, CHUNK)) {
3394
+ await executor.runAsync(
3395
+ `DELETE FROM ${this.prefix}vector_removals
3396
+ WHERE entity_id = ? AND fact_id IN (${marks(c.length)})${extra}`,
3397
+ [entityId, ...c]
3398
+ );
3399
+ }
3400
+ }
3401
+ /** Drop unconfirmed rows. Returns the count removed. */
3402
+ async discardPending(entityId, tx) {
3403
+ const executor = this.getExecutor(tx);
3404
+ const r = entityId === void 0 ? await executor.runAsync(
3405
+ `DELETE FROM ${this.prefix}vector_removals WHERE confirmed_at IS NULL`
3406
+ ) : await executor.runAsync(
3407
+ `DELETE FROM ${this.prefix}vector_removals WHERE confirmed_at IS NULL AND entity_id = ?`,
3408
+ [entityId]
3409
+ );
3410
+ return r.changes;
3411
+ }
3412
+ async pendingStats(entityId) {
3413
+ const row = await this.db.getFirstAsync(
3414
+ `SELECT COUNT(*) AS c, MIN(enqueued_at) AS o, MAX(attempts) AS m
3415
+ FROM ${this.prefix}vector_removals
3416
+ WHERE confirmed_at IS NULL${entityId === void 0 ? "" : " AND entity_id = ?"}`,
3417
+ entityId === void 0 ? [] : [entityId]
3418
+ );
3419
+ return { count: row?.c ?? 0, oldestEnqueuedAt: row?.o ?? null, maxAttempts: row?.m ?? 0 };
3420
+ }
3421
+ async entitiesWithPending() {
3422
+ const rows = await this.db.getAllAsync(
3423
+ `SELECT DISTINCT entity_id FROM ${this.prefix}vector_removals
3424
+ WHERE confirmed_at IS NULL ORDER BY entity_id`
3425
+ );
3426
+ return rows.map((r) => r.entity_id);
3427
+ }
3428
+ /**
3429
+ * Entities with at least one pending row outside backoff (never attempted,
3430
+ * or last attempted longer ago than removalBackoffMs). Same rule as the drain.
3431
+ */
3432
+ async entitiesWithDuePending(now) {
3433
+ const rows = await this.db.getAllAsync(
3434
+ `SELECT DISTINCT entity_id FROM ${this.prefix}vector_removals
3435
+ WHERE confirmed_at IS NULL
3436
+ AND (last_attempt_at IS NULL
3437
+ OR ? - last_attempt_at >= MIN(1 << MIN(attempts, 12), 3600) * 1000)
3438
+ ORDER BY entity_id`,
3439
+ [now]
3440
+ );
3441
+ return rows.map((r) => r.entity_id);
3442
+ }
3443
+ async statusFor(ids, tx) {
3444
+ const executor = this.getExecutor(tx);
3445
+ const out = /* @__PURE__ */ new Map();
3446
+ for (const c of chunks(ids, CHUNK)) {
3447
+ const rows = await executor.getAllAsync(
3448
+ `SELECT fact_id, confirmed_at FROM ${this.prefix}vector_removals
3449
+ WHERE fact_id IN (${marks(c.length)})`,
3450
+ c
3451
+ );
3452
+ for (const r of rows) out.set(r.fact_id, r.confirmed_at === null ? "pending" : "confirmed");
3453
+ }
3454
+ return out;
3455
+ }
3456
+ };
3457
+
3458
+ // src/services/VectorRemovalService.ts
3459
+ var MARKER_KEY = "external_index_in_use";
3460
+ var PAGE = 100;
3461
+ var ID_CHUNK = 500;
3462
+ var MAX_FAILED_IDS = 100;
3463
+ var MAX_CONSECUTIVE_REJECTIONS = 5;
3464
+ function removalGate(options) {
3465
+ if (options.forceDeleteIgnoreRankerHook === true) return "force";
3466
+ if (options.vectorRanker?.onEmbeddingPersisted) return "hook";
3467
+ return "none";
3468
+ }
3469
+ var VectorRemovalService = class {
3470
+ constructor(db, options, repo, embeddingService, metadataRepo) {
3471
+ this.db = db;
3472
+ this.options = options;
3473
+ this.repo = repo;
3474
+ this.embeddingService = embeddingService;
3475
+ this.metadataRepo = metadataRepo;
3476
+ this.inFlight = /* @__PURE__ */ new Map();
3477
+ this.ledgerSeen = false;
3478
+ }
3479
+ gate() {
3480
+ return removalGate(this.options);
3481
+ }
3482
+ async ledgerPresent() {
3483
+ if (this.ledgerSeen) return true;
3484
+ this.ledgerSeen = await this.metadataRepo.tableExists(this.repo.ledgerTable);
3485
+ return this.ledgerSeen;
3486
+ }
3487
+ /** One `hook_failed` diagnostic per id (the removal stays owed). */
3488
+ emitHookFailed(entityId, ids, operation, trigger) {
3489
+ for (const factId of ids) {
3490
+ emitDiagnostic(this.options, {
3491
+ entityId,
3492
+ operation,
3493
+ trigger,
3494
+ code: "hook_failed",
3495
+ detail: { factId, reason: "on_embedding_persisted" }
3496
+ });
3497
+ }
3498
+ }
3499
+ /**
3500
+ * Post-commit delivery for heal, ingest and import (spec §5.7). Never throws:
3501
+ * a failed id emits `hook_failed` and stays owed on the ledger. Without a
3502
+ * ledger table (setup never ran) it falls back to a best-effort call per id.
3503
+ * Under `forceDeleteIgnoreRankerHook` no removal call is made.
3504
+ */
3505
+ async deliverRemovals(entityId, ids, operation, trigger, fallbackIds = ids) {
3506
+ try {
3507
+ if (await this.ledgerPresent()) {
3508
+ if (ids.length === 0) return;
3509
+ const r2 = await this.drain({ entityId, ids }, { trigger });
3510
+ this.emitHookFailed(entityId, r2.failedIds, operation, trigger);
3511
+ if (r2.pending > 0 && this.gate() === "hook") await this.emitPending(entityId, trigger);
3512
+ return;
3513
+ }
3514
+ if (this.gate() !== "hook") return;
3515
+ const r = await this.embeddingService.callRemovalHookEach(entityId, [...new Set(fallbackIds)], { warn: true });
3516
+ this.emitHookFailed(entityId, r.failed, operation, trigger);
3517
+ } catch (err) {
3518
+ console.warn("[WikiMemory] removal delivery failed:", err);
3519
+ let stillPending = ids;
3520
+ try {
3521
+ const st = await this.repo.statusFor(ids);
3522
+ stillPending = ids.filter((id) => st.get(id) === "pending");
3523
+ } catch {
3524
+ }
3525
+ this.emitHookFailed(entityId, stillPending, operation, trigger);
3526
+ }
3527
+ }
3528
+ async markExternalIndexInUse(tx) {
3529
+ await this.metadataRepo.setMeta(MARKER_KEY, "1", tx);
3530
+ }
3531
+ async clearExternalIndexMarker() {
3532
+ await this.metadataRepo.deleteMeta(MARKER_KEY);
3533
+ }
3534
+ async externalIndexInUse() {
3535
+ return await this.metadataRepo.getMeta(MARKER_KEY) === "1";
3536
+ }
3537
+ async drain(scope, opts = {}) {
3538
+ const trigger = opts.trigger ?? "call";
3539
+ const entityId = "all" in scope ? void 0 : scope.entityId;
3540
+ const ids = "all" in scope ? void 0 : scope.ids;
3541
+ const gate = this.gate();
3542
+ if (gate === "none") {
3543
+ const pending = await this.pendingFor(entityId, ids);
3544
+ if (pending > 0 && await this.externalIndexInUse()) await this.emitPending(entityId, trigger);
3545
+ return { confirmed: 0, pending, failedIds: [], timedOut: false };
3546
+ }
3547
+ if (gate === "force") {
3548
+ const entities = entityId === void 0 ? await this.repo.entitiesWithPending() : [entityId];
3549
+ const counts = [];
3550
+ for (const e of entities) counts.push([e, (await this.repo.pendingStats(e)).count]);
3551
+ await this.repo.discardPending(entityId);
3552
+ await this.metadataRepo.deleteMeta(MARKER_KEY);
3553
+ for (const [e, count] of counts) {
3554
+ if (count === 0) continue;
3555
+ emitDiagnostic(this.options, {
3556
+ code: "external_deletion_discarded",
3557
+ operation: "externalDeletion",
3558
+ trigger,
3559
+ entityId: e,
3560
+ detail: { count }
3561
+ });
3562
+ }
3563
+ return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
3564
+ }
3565
+ const timeoutMs = this.embeddingService.validateDeletionTimeout();
3566
+ const result = { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
3567
+ let timeoutErr;
3568
+ let firstRejection;
3569
+ let consecutive = 0;
3570
+ let stop = false;
3571
+ let transient = false;
3572
+ const tried = /* @__PURE__ */ new Set();
3573
+ let scopes;
3574
+ let maxSeq;
3575
+ try {
3576
+ 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 }));
3577
+ maxSeq = await this.repo.maxSeq();
3578
+ } catch {
3579
+ result.transient = true;
3580
+ try {
3581
+ result.pending = await this.pendingFor(entityId, ids);
3582
+ } catch {
3583
+ }
3584
+ return result;
3585
+ }
3586
+ const perEntity = entityId === void 0;
3587
+ for (const sc of scopes) {
3588
+ if (stop || transient) break;
3589
+ let cursor = { maxSeq, attempts: -1, seq: 0 };
3590
+ let scopeDone = false;
3591
+ if (perEntity) consecutive = 0;
3592
+ while (!stop && !scopeDone) {
3593
+ let page;
3594
+ try {
3595
+ page = await this.db.withTransactionAsync(
3596
+ (tx) => this.repo.readPage(sc, cursor, PAGE, tx)
3597
+ );
3598
+ } catch {
3599
+ transient = true;
3600
+ result.transient = true;
3601
+ break;
3602
+ }
3603
+ if (page.length === 0) break;
3604
+ const last = page[page.length - 1];
3605
+ cursor = { maxSeq, attempts: last.attempts, seq: last.seq };
3606
+ const confirmSeqs = [];
3607
+ const bumpSeqs = [];
3608
+ const deleteSeqs = [];
3609
+ const goneSeqs = [];
3610
+ for (const row of page) {
3611
+ if (tried.has(row.seq)) continue;
3612
+ if (row.fact_state === "live") {
3613
+ tried.add(row.seq);
3614
+ deleteSeqs.push(row.seq);
3615
+ continue;
3616
+ }
3617
+ if (opts.backoff === true && row.last_attempt_at !== null) {
3618
+ if (Date.now() - row.last_attempt_at < removalBackoffMs(row.attempts)) continue;
3619
+ }
3620
+ let budget = timeoutMs;
3621
+ if (opts.deadlineAt !== void 0) {
3622
+ const left = opts.deadlineAt - Date.now();
3623
+ if (left <= 0) {
3624
+ stop = true;
3625
+ break;
3626
+ }
3627
+ budget = Math.min(timeoutMs, left);
3628
+ }
3629
+ tried.add(row.seq);
3630
+ const outcome = await this.callFor(row, budget);
3631
+ if (outcome.ok) {
3632
+ consecutive = 0;
3633
+ if (row.fact_state === "gone") goneSeqs.push(row.seq);
3634
+ else confirmSeqs.push(row.seq);
3635
+ } else {
3636
+ if (!outcome.joined) bumpSeqs.push(row.seq);
3637
+ if (result.failedIds.length < MAX_FAILED_IDS) result.failedIds.push(row.fact_id);
3638
+ if (outcome.timedOut) {
3639
+ result.timedOut = true;
3640
+ result.timedOutId ?? (result.timedOutId = row.fact_id);
3641
+ timeoutErr ?? (timeoutErr = outcome.cause);
3642
+ stop = true;
3643
+ break;
3644
+ }
3645
+ firstRejection ?? (firstRejection = outcome.cause);
3646
+ if (++consecutive >= MAX_CONSECUTIVE_REJECTIONS) {
3647
+ if (perEntity) scopeDone = true;
3648
+ else stop = true;
3649
+ break;
3650
+ }
3651
+ }
3652
+ }
3653
+ if (confirmSeqs.length || bumpSeqs.length || deleteSeqs.length || goneSeqs.length) {
3654
+ const now = Date.now();
3655
+ try {
3656
+ const changed = await this.db.withTransactionAsync(async (tx) => {
3657
+ let n = 0;
3658
+ if (confirmSeqs.length) {
3659
+ n += await this.repo.confirm(confirmSeqs, now, tx);
3660
+ await this.repo.deleteConfirmedGone(confirmSeqs, tx);
3661
+ }
3662
+ if (bumpSeqs.length) await this.repo.bumpAttempts(bumpSeqs, now, tx);
3663
+ if (goneSeqs.length) n += await this.repo.deleteBySeq(goneSeqs, tx);
3664
+ if (deleteSeqs.length) await this.repo.deleteBySeq(deleteSeqs, tx);
3665
+ return n;
3666
+ });
3667
+ result.confirmed += changed;
3668
+ } catch {
3669
+ transient = true;
3670
+ result.transient = true;
3671
+ break;
3672
+ }
3673
+ }
3674
+ if (page.length < PAGE) break;
3675
+ }
3676
+ }
3677
+ result.firstCause = timeoutErr ?? firstRejection;
3678
+ try {
3679
+ result.pending = await this.pendingFor(entityId, ids);
3680
+ } catch {
3681
+ result.transient = true;
3682
+ }
3683
+ return result;
3684
+ }
3685
+ /**
3686
+ * Makes the removal call for `row`, or joins another drain's call for the
3687
+ * same seq. Never throws: the outcome says whether it succeeded, whether
3688
+ * this drain joined (only the owner bumps attempts on failure), and whether
3689
+ * the failure was a timeout.
3690
+ */
3691
+ async callFor(row, budgetMs) {
3692
+ const end = Date.now() + budgetMs;
3693
+ const left = () => Math.max(1, end - Date.now());
3694
+ let joined = false;
3695
+ try {
3696
+ let existing = this.inFlight.get(row.fact_id);
3697
+ while (existing && existing.seq !== row.seq) {
3698
+ joined = true;
3699
+ await withBudget(existing.promise.catch(() => {
3700
+ }), left());
3701
+ const next = this.inFlight.get(row.fact_id);
3702
+ existing = next === existing ? void 0 : next;
3703
+ }
3704
+ if (existing) {
3705
+ joined = true;
3706
+ await withBudget(existing.promise, left());
3707
+ return { ok: true, joined: true };
3708
+ }
3709
+ joined = false;
3710
+ const p = this.embeddingService.callRemovalHook(row.entity_id, row.fact_id, left());
3711
+ const entry = { seq: row.seq, promise: p };
3712
+ this.inFlight.set(row.fact_id, entry);
3713
+ const clear = () => {
3714
+ if (this.inFlight.get(row.fact_id) === entry) this.inFlight.delete(row.fact_id);
3715
+ };
3716
+ p.then(clear, clear);
3717
+ await p;
3718
+ return { ok: true, joined: false };
3719
+ } catch (err) {
3720
+ const e = err instanceof Error ? err : new Error(String(err));
3721
+ return { ok: false, joined, timedOut: e[HOOK_TIMEOUT_MARKER] === true, cause: e };
3722
+ }
3723
+ }
3724
+ async pendingFor(entityId, ids) {
3725
+ if (entityId !== void 0 && ids !== void 0) {
3726
+ return this.repo.pendingCountForIds(entityId, ids);
3727
+ }
3728
+ return (await this.repo.pendingStats(entityId)).count;
3729
+ }
3730
+ async emitPending(entityId, trigger) {
3731
+ const entities = entityId === void 0 ? await this.repo.entitiesWithPending() : [entityId];
3732
+ for (const e of entities) {
3733
+ const st = await this.repo.pendingStats(e);
3734
+ if (st.count === 0) continue;
3735
+ emitDiagnostic(this.options, {
3736
+ code: "external_deletion_pending",
3737
+ operation: "externalDeletion",
3738
+ trigger,
3739
+ entityId: e,
3740
+ detail: {
3741
+ count: st.count,
3742
+ ...st.oldestEnqueuedAt !== null ? { oldestEnqueuedAt: st.oldestEnqueuedAt } : {},
3743
+ maxAttempts: st.maxAttempts
3744
+ }
3745
+ });
3746
+ }
3747
+ }
3748
+ };
3749
+ function withBudget(p, ms) {
3750
+ let handle;
3751
+ const timer = new Promise((_, reject) => {
3752
+ handle = setTimeout(() => {
3753
+ const e = new Error(`onEmbeddingPersisted timed out after ${ms}ms`);
3754
+ e[HOOK_TIMEOUT_MARKER] = true;
3755
+ reject(e);
3756
+ }, ms);
3757
+ });
3758
+ return Promise.race([p, timer]).finally(() => {
3759
+ if (handle) clearTimeout(handle);
3760
+ });
3761
+ }
3762
+
3112
3763
  // src/utils/temporal.ts
3113
3764
  function liveAtSql(mode, alias = "") {
3114
3765
  const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
@@ -3832,8 +4483,83 @@ async function setupDatabase(db, prefix) {
3832
4483
  CREATE INDEX IF NOT EXISTS ${prefix}outbox_created_at
3833
4484
  ON ${prefix}outbox (created_at);
3834
4485
  `);
4486
+ await db.execAsync(`
4487
+ CREATE TABLE IF NOT EXISTS ${prefix}vector_removals (
4488
+ seq INTEGER PRIMARY KEY AUTOINCREMENT,
4489
+ entity_id TEXT NOT NULL,
4490
+ fact_id TEXT NOT NULL UNIQUE,
4491
+ enqueued_at INTEGER NOT NULL,
4492
+ attempts INTEGER NOT NULL DEFAULT 0,
4493
+ last_attempt_at INTEGER,
4494
+ confirmed_at INTEGER
4495
+ );
4496
+ CREATE INDEX IF NOT EXISTS ${prefix}vector_removals_pending
4497
+ ON ${prefix}vector_removals (entity_id, attempts, seq) WHERE confirmed_at IS NULL;
4498
+
4499
+ CREATE TRIGGER IF NOT EXISTS ${prefix}vector_removals_enqueue
4500
+ AFTER UPDATE OF deleted_at ON ${prefix}entries
4501
+ WHEN OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL
4502
+ BEGIN
4503
+ -- DELETE then INSERT, not INSERT OR REPLACE: an outer UPSERT's conflict
4504
+ -- handling would override OR REPLACE and abort on fact_id (spec rev 5).
4505
+ DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
4506
+ INSERT INTO ${prefix}vector_removals (entity_id, fact_id, enqueued_at)
4507
+ VALUES (NEW.entity_id, NEW.id, CAST(strftime('%s','now') AS INTEGER) * 1000);
4508
+ END;
4509
+
4510
+ -- A hard delete outside prune (host SQL, an older engine after a
4511
+ -- downgrade). A live fact is owed only where an external index was in use;
4512
+ -- a soft-deleted one drops the rows nothing can owe (spec rev 5).
4513
+ CREATE TRIGGER IF NOT EXISTS ${prefix}vector_removals_hard_delete
4514
+ AFTER DELETE ON ${prefix}entries
4515
+ BEGIN
4516
+ DELETE FROM ${prefix}vector_removals
4517
+ WHERE fact_id = OLD.id
4518
+ AND (OLD.deleted_at IS NULL
4519
+ OR confirmed_at IS NOT NULL
4520
+ OR NOT EXISTS (SELECT 1 FROM ${prefix}meta WHERE key = 'external_index_in_use' AND value = '1'));
4521
+ INSERT INTO ${prefix}vector_removals (entity_id, fact_id, enqueued_at)
4522
+ SELECT OLD.entity_id, OLD.id, CAST(strftime('%s','now') AS INTEGER) * 1000
4523
+ WHERE OLD.deleted_at IS NULL
4524
+ AND EXISTS (SELECT 1 FROM ${prefix}meta WHERE key = 'external_index_in_use' AND value = '1');
4525
+ END;
4526
+ `);
3835
4527
  await createOkfV02IndexesIfColumnsExist(db, prefix);
3836
4528
  await createTemporalIndexesIfColumnsExist(db, prefix);
4529
+ await createResurrectTrigger(db, prefix);
4530
+ }
4531
+ var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
4532
+ function resurrectLevel(sql) {
4533
+ if (sql.includes("embedding_failed_at")) return 2;
4534
+ return sql.includes("embedding_blob") ? 1 : 0;
4535
+ }
4536
+ async function createResurrectTrigger(db, prefix) {
4537
+ const name = `${prefix}vector_removals_resurrect`;
4538
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
4539
+ const names = new Set(cols.map((c) => c.name));
4540
+ const want = !(names.has("embedding_blob") && names.has("embedding")) ? 0 : EMBED_MARKER_COLUMNS.every((c) => names.has(c)) ? 2 : 1;
4541
+ const existing = await db.getFirstAsync(
4542
+ `SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?`,
4543
+ [name]
4544
+ );
4545
+ if (existing) {
4546
+ if (resurrectLevel(existing.sql ?? "") >= want) return;
4547
+ await db.execAsync(`DROP TRIGGER IF EXISTS ${name};`);
4548
+ }
4549
+ const clearVector = want === 0 ? "" : `
4550
+ UPDATE ${prefix}entries
4551
+ SET embedding_blob = NULL, embedding = NULL${want === 2 ? `,
4552
+ embedding_failed_at = NULL, embedding_failure_kind = NULL, embedding_attempts = 0` : ""}
4553
+ WHERE id = NEW.id
4554
+ AND EXISTS (SELECT 1 FROM ${prefix}vector_removals WHERE fact_id = NEW.id AND confirmed_at IS NOT NULL);`;
4555
+ await db.execAsync(`
4556
+ CREATE TRIGGER IF NOT EXISTS ${name}
4557
+ AFTER UPDATE OF deleted_at ON ${prefix}entries
4558
+ WHEN OLD.deleted_at IS NOT NULL AND NEW.deleted_at IS NULL
4559
+ BEGIN${clearVector}
4560
+ DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
4561
+ END;
4562
+ `);
3837
4563
  }
3838
4564
  async function createOkfV02IndexesIfColumnsExist(db, prefix) {
3839
4565
  for (const table of ["entries", "tasks"]) {
@@ -4044,6 +4770,7 @@ var MIGRATIONS = [
4044
4770
  `ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`
4045
4771
  );
4046
4772
  }
4773
+ await createResurrectTrigger(db, prefix);
4047
4774
  }
4048
4775
  },
4049
4776
  {
@@ -4237,6 +4964,7 @@ var MIGRATIONS = [
4237
4964
  for (const [name, sql] of adds) {
4238
4965
  if (!existing.has(name)) await db.execAsync(sql);
4239
4966
  }
4967
+ await createResurrectTrigger(db, prefix);
4240
4968
  }
4241
4969
  },
4242
4970
  {
@@ -4317,7 +5045,7 @@ var NORMALIZE_STAMP_SCHEMA_VERSION = 14;
4317
5045
  var NORMALIZE_STAMP_KEY = "source_ref_normalize_stamp";
4318
5046
  var ENTRIES_WM_KEY = "normalize_v14_entries_wm";
4319
5047
  var SRI_WM_KEY = "normalize_v14_sri_wm";
4320
- var CHUNK = 500;
5048
+ var CHUNK2 = 500;
4321
5049
  function stampMatches(raw) {
4322
5050
  return parseJsonObject(raw)?.normalize_alg === SOURCE_REF_NORMALIZE_ALG;
4323
5051
  }
@@ -4350,7 +5078,7 @@ async function runPass(db, prefix, meta, table, key, stampOnCompletion) {
4350
5078
  let next = from;
4351
5079
  await db.withTransactionAsync(async (tx) => {
4352
5080
  const rows = await tx.getAllAsync(
4353
- `SELECT rowid, id, source_ref FROM ${prefix}${table} WHERE rowid > ? ORDER BY rowid LIMIT ${CHUNK}`,
5081
+ `SELECT rowid, id, source_ref FROM ${prefix}${table} WHERE rowid > ? ORDER BY rowid LIMIT ${CHUNK2}`,
4354
5082
  [from]
4355
5083
  );
4356
5084
  for (const r of rows) {
@@ -4365,7 +5093,7 @@ async function runPass(db, prefix, meta, table, key, stampOnCompletion) {
4365
5093
  await tx.runAsync(`UPDATE ${prefix}source_ref_index SET source_ref = ? WHERE rowid = ?`, [n, r.rowid]);
4366
5094
  }
4367
5095
  }
4368
- if (rows.length < CHUNK) {
5096
+ if (rows.length < CHUNK2) {
4369
5097
  await meta.deleteMeta(key, tx);
4370
5098
  if (stampOnCompletion) await writeNormalizeStamp(meta, tx);
4371
5099
  next = null;
@@ -4464,7 +5192,8 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
4464
5192
  promptEvents,
4465
5193
  currentFacts,
4466
5194
  promptOverride,
4467
- ontologyContext
5195
+ ontologyContext,
5196
+ ctx.guidance
4468
5197
  );
4469
5198
  let responseText;
4470
5199
  try {
@@ -4636,7 +5365,7 @@ var OPS_MAX_EVENTS_PER_PASS = 50;
4636
5365
  var OPS_MAX_EXTRACT_CHARS = 24e3;
4637
5366
  var RESOLVE_RESERVE_FACTOR = 2;
4638
5367
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
4639
- async function selectBatch(deps, entityId, wm, meter) {
5368
+ async function selectBatch(deps, entityId, wm, meter, guidance) {
4640
5369
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
4641
5370
  if (events.length === 0) return { batch: [] };
4642
5371
  let n = 0;
@@ -4650,7 +5379,7 @@ async function selectBatch(deps, entityId, wm, meter) {
4650
5379
  if (meter && meter.budget !== void 0) {
4651
5380
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
4652
5381
  for (; ; ) {
4653
- const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext));
5382
+ const need = RESOLVE_RESERVE_FACTOR * estimatePrompt(deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, guidance));
4654
5383
  if (meter.fits(need)) break;
4655
5384
  if (batch.length === 1) return { budgetStop: { requiredEstimate: need } };
4656
5385
  batch = labelEvents(events.slice(0, Math.max(1, Math.floor(batch.length / 2))));
@@ -4661,7 +5390,7 @@ async function selectBatch(deps, entityId, wm, meter) {
4661
5390
  async function runExtract(deps, ctx, batch) {
4662
5391
  const { entityId, trigger } = ctx;
4663
5392
  const ontologyContext = await deps.ontologyService?.buildPromptContext(entityId) ?? null;
4664
- const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext);
5393
+ const prompt = deps.promptService.buildOpsExtractPrompt(batch, ontologyContext, ctx.guidance);
4665
5394
  const text = await callLlm(deps.options, { operation: "librarian", entityId, trigger, meter: ctx.meter }, prompt);
4666
5395
  const parsed = parseJsonResponse(text);
4667
5396
  const base = { entityId, operation: "librarian", trigger };
@@ -5119,7 +5848,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5119
5848
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
5120
5849
  await deps.seedWatermark(entityId);
5121
5850
  const wm = await deps.getWatermark(entityId);
5122
- const sel = await selectBatch(deps, entityId, wm, ctx.meter);
5851
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
5123
5852
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
5124
5853
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
5125
5854
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -5249,7 +5978,7 @@ var formatSkipError = (err) => {
5249
5978
  return base;
5250
5979
  };
5251
5980
  var MaintenanceService = class {
5252
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
5981
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
5253
5982
  this.db = db;
5254
5983
  this.prefix = prefix;
5255
5984
  this.options = options;
@@ -5262,6 +5991,8 @@ var MaintenanceService = class {
5262
5991
  this.jobManager = jobManager;
5263
5992
  this.embeddingService = embeddingService;
5264
5993
  this.ontologyService = ontologyService;
5994
+ this.vectorRemoval = vectorRemoval;
5995
+ this.vectorRemovalRepo = vectorRemovalRepo;
5265
5996
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
5266
5997
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
5267
5998
  }
@@ -5275,11 +6006,14 @@ var MaintenanceService = class {
5275
6006
  this._validatePruneDuration(retainEventsFor, "retainEventsFor");
5276
6007
  const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
5277
6008
  this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
6009
+ const gate = removalGate(this.options);
6010
+ if (gate === "hook") this.embeddingService.validateDeletionTimeout();
5278
6011
  const now = Date.now();
5279
6012
  let syncedIds = [];
5280
6013
  let deletedEntries = 0;
5281
6014
  let deletedTasks = 0;
5282
6015
  let deletedEvents = 0;
6016
+ let prunePartial = null;
5283
6017
  if (pruneSupersededAfter !== null) {
5284
6018
  const expiredCutoff = now - pruneSupersededAfter * 864e5;
5285
6019
  const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
@@ -5288,55 +6022,89 @@ var MaintenanceService = class {
5288
6022
  await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
5289
6023
  });
5290
6024
  syncedIds = [...expiredIds];
6025
+ if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
6026
+ await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
6027
+ }
5291
6028
  }
5292
6029
  }
5293
6030
  if (retainSoftDeletedFor !== null) {
5294
6031
  const cutoff = now - retainSoftDeletedFor * 864e5;
5295
6032
  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;
6033
+ const prunableIds = entriesToDelete.map((r) => r.id);
6034
+ const vr = this.vectorRemoval;
6035
+ const vrRepo = this.vectorRemovalRepo;
6036
+ const ledgerOn = !!vr && !!vrRepo && await vr.ledgerPresent();
6037
+ let deletable = prunableIds;
6038
+ let removeLedger = false;
6039
+ let kept = [];
6040
+ let timedOut = false;
6041
+ let cause;
6042
+ let firstFailed;
6043
+ let failedOrder = [];
6044
+ if (ledgerOn && vr && vrRepo) {
6045
+ if (gate === "hook" && prunableIds.length > 0) {
6046
+ await this.db.withTransactionAsync(async (tx) => {
6047
+ await vrRepo.backstopEnqueue(entityId, prunableIds, now, tx);
6048
+ });
5305
6049
  }
6050
+ const result = prunableIds.length > 0 ? await vr.drain({ entityId, ids: prunableIds }) : { failedIds: [], timedOut: false, firstCause: void 0 };
6051
+ if (gate === "hook") {
6052
+ timedOut = result.timedOut;
6053
+ cause = result.firstCause;
6054
+ failedOrder = result.failedIds;
6055
+ } else if (gate === "force") {
6056
+ removeLedger = true;
6057
+ } else {
6058
+ removeLedger = !await vr.externalIndexInUse();
6059
+ }
6060
+ } else if (gate === "hook") {
6061
+ const r = await this.embeddingService.callRemovalHookEach(entityId, prunableIds);
6062
+ const failedSet = new Set(r.failed);
6063
+ kept = r.failed;
6064
+ deletable = prunableIds.filter((id) => !failedSet.has(id));
6065
+ timedOut = r.timedOut;
6066
+ cause = r.cause;
6067
+ firstFailed = kept[0];
5306
6068
  }
5307
- const succeededIds = succeeded.map((r) => r.id);
5308
- syncedIds = [...syncedIds, ...succeededIds];
6069
+ const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
5309
6070
  await this.db.withTransactionAsync(async (tx) => {
5310
- if (succeededIds.length > 0) {
5311
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, succeededIds, tx);
6071
+ if (hookLedger && vrRepo && prunableIds.length > 0) {
6072
+ const status = await vrRepo.statusFor(prunableIds, tx);
6073
+ deletable = prunableIds.filter((id) => status.get(id) !== "pending");
6074
+ kept = prunableIds.filter((id) => status.get(id) === "pending");
6075
+ }
6076
+ if (deletable.length > 0) {
6077
+ const deletedIds = [];
6078
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
6079
+ if (hookLedger) {
6080
+ const gone = new Set(deletedIds);
6081
+ const skipped = deletable.filter((id) => !gone.has(id));
6082
+ if (skipped.length > 0) {
6083
+ const after = await vrRepo.statusFor(skipped, tx);
6084
+ kept = [...kept, ...skipped.filter((id) => after.get(id) === "pending")];
6085
+ }
6086
+ deletable = deletedIds;
6087
+ }
6088
+ if (vrRepo && ledgerOn) {
6089
+ if (removeLedger) await vrRepo.deleteForFacts(entityId, deletable, tx, "all");
6090
+ else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
6091
+ }
5312
6092
  }
5313
6093
  deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
5314
6094
  });
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
- );
6095
+ if (hookLedger) {
6096
+ const keptSet = new Set(kept);
6097
+ firstFailed = failedOrder.find((id) => keptSet.has(id)) ?? kept[0];
6098
+ }
6099
+ syncedIds = [...syncedIds, ...deletable];
6100
+ if (kept.length > 0) {
6101
+ if (timedOut) {
6102
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("Deletion hook timed out") };
6103
+ } else if (cause === void 0) {
6104
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("external removal not confirmed") };
6105
+ } else {
6106
+ prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: this._sanitizeRankerError(cause) };
5328
6107
  }
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
6108
  }
5341
6109
  }
5342
6110
  if (retainEventsFor !== null) {
@@ -5373,6 +6141,16 @@ var MaintenanceService = class {
5373
6141
  await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
5374
6142
  }
5375
6143
  await this.searchService.syncEntries(entityId, syncedIds);
6144
+ if (prunePartial) {
6145
+ throw new PrunePartialFailureError(
6146
+ deletedEntries,
6147
+ prunePartial.failedAt,
6148
+ prunePartial.remaining,
6149
+ prunePartial.cause,
6150
+ deletedTasks,
6151
+ deletedEvents
6152
+ );
6153
+ }
5376
6154
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
5377
6155
  } finally {
5378
6156
  this.jobManager.releaseLock("prune", entityId);
@@ -5477,6 +6255,7 @@ var MaintenanceService = class {
5477
6255
  }
5478
6256
  const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
5479
6257
  if (result.ok) embedded++;
6258
+ else if (result.kind === "fact_deleted") skipped++;
5480
6259
  else failed++;
5481
6260
  }
5482
6261
  if (embedded > 0) {
@@ -5507,6 +6286,7 @@ var MaintenanceService = class {
5507
6286
  let deletedTasks = 0;
5508
6287
  let deletedEvents = 0;
5509
6288
  const deletedEntryIds = [];
6289
+ const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
5510
6290
  await this.db.withTransactionAsync(async (tx) => {
5511
6291
  if (params.clearAll) {
5512
6292
  for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
@@ -5555,22 +6335,54 @@ var MaintenanceService = class {
5555
6335
  if (taskResult) deletedTasks++;
5556
6336
  deletedEntries += refResult;
5557
6337
  }
6338
+ if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
6339
+ await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
6340
+ }
5558
6341
  });
5559
6342
  const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
5560
6343
  await this.searchService.syncEntries(entityId, uniqueDeletedIds);
5561
- for (const factId of uniqueDeletedIds) {
6344
+ if (uniqueDeletedIds.length > 0) {
6345
+ const firstId = uniqueDeletedIds[0];
6346
+ const vr = this.vectorRemoval;
6347
+ const vrRepo = this.vectorRemovalRepo;
6348
+ let unconfirmed = [];
6349
+ let timedOut = false;
6350
+ let cause;
6351
+ let timedOutId;
5562
6352
  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}`);
6353
+ if (vr && vrRepo && ledgerOn) {
6354
+ const result = await vr.drain({ entityId, ids: uniqueDeletedIds });
6355
+ if (vr.gate() === "hook") {
6356
+ const status = await vrRepo.statusFor(uniqueDeletedIds);
6357
+ unconfirmed = uniqueDeletedIds.filter((id) => status.get(id) === "pending");
6358
+ timedOut = result.timedOut;
6359
+ timedOutId = result.timedOutId;
6360
+ cause = result.firstCause;
6361
+ }
6362
+ } else if (this.options.vectorRanker?.onEmbeddingPersisted && this.options.forceDeleteIgnoreRankerHook !== true) {
6363
+ const r = await this.embeddingService.callRemovalHookEach(entityId, uniqueDeletedIds);
6364
+ unconfirmed = r.failed;
6365
+ timedOut = r.timedOut;
6366
+ timedOutId = r.timedOutId;
6367
+ cause = r.cause;
5568
6368
  }
6369
+ } catch (hookErr) {
5569
6370
  const errMsg = hookErr?.message ?? "";
5570
6371
  if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
5571
- throw new Error(`forget(${entityId}/${factId}) failed: ${errMsg}`, { cause: hookErr });
6372
+ throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
5572
6373
  }
5573
- throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
6374
+ throw hookErr;
6375
+ }
6376
+ if (unconfirmed.length > 0) {
6377
+ const head = `forget(${entityId}/${(timedOut ? timedOutId : void 0) ?? unconfirmed[0]}) failed: `;
6378
+ const message = timedOut ? head + (cause?.message ?? "onEmbeddingPersisted timed out") : cause === void 0 ? head + "ANN cleanup not confirmed" : head + "ANN cleanup hook rejected";
6379
+ throw new WikiExternalDeletionError(message, {
6380
+ entityId,
6381
+ unconfirmedIds: unconfirmed.slice(0, 100),
6382
+ unconfirmedCount: unconfirmed.length,
6383
+ timedOut,
6384
+ cause: timedOut || cause === void 0 ? void 0 : this._sanitizeRankerError(cause)
6385
+ });
5574
6386
  }
5575
6387
  }
5576
6388
  if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
@@ -5579,6 +6391,22 @@ var MaintenanceService = class {
5579
6391
  this.jobManager.releaseLock("forget", entityId);
5580
6392
  }
5581
6393
  }
6394
+ /** Heal's post-commit removal delivery (spec §5.7). Never throws. */
6395
+ async deliverHealRemovals(entityId, ids, trigger) {
6396
+ if (this.vectorRemoval) {
6397
+ await this.vectorRemoval.deliverRemovals(entityId, ids, "heal", trigger);
6398
+ return;
6399
+ }
6400
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
6401
+ for (const factId of ids) {
6402
+ try {
6403
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
6404
+ } catch (hookErr) {
6405
+ console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
6406
+ emitDiagnostic(this.options, { entityId, operation: "heal", trigger, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
6407
+ }
6408
+ }
6409
+ }
5582
6410
  /**
5583
6411
  * Whether forget() should soft-delete in source_ref_index (#316,
5584
6412
  * specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
@@ -5658,7 +6486,17 @@ var MaintenanceService = class {
5658
6486
  * A budget-stopped pass wrote nothing and must not move the watermark.
5659
6487
  */
5660
6488
  async runLibrarianPass(ctx) {
5661
- const result = await runLibrarianStrategy(this.librarianDeps(), ctx);
6489
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, ctx.entityId);
6490
+ if (diagnostic) {
6491
+ emitDiagnostic(this.options, {
6492
+ code: diagnostic.code,
6493
+ operation: "librarian",
6494
+ trigger: ctx.trigger,
6495
+ entityId: ctx.entityId,
6496
+ detail: diagnostic.detail
6497
+ });
6498
+ }
6499
+ const result = await runLibrarianStrategy(this.librarianDeps(), { ...ctx, guidance });
5662
6500
  if (result.processedThrough && !result.budgetStop) {
5663
6501
  await this.advanceLibrarianWatermark(ctx.entityId, result.processedThrough);
5664
6502
  }
@@ -5776,14 +6614,7 @@ var MaintenanceService = class {
5776
6614
  staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
5777
6615
  }
5778
6616
  });
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
- }
6617
+ await this.deliverHealRemovals(entityId, orphanedIds, trigger);
5787
6618
  const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
5788
6619
  const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
5789
6620
  if (healCandidates.length === 0 || keywordUnavailable) {
@@ -5972,14 +6803,7 @@ var MaintenanceService = class {
5972
6803
  ...insertedFacts.map((f) => f.id)
5973
6804
  ]));
5974
6805
  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
- }
6806
+ await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
5983
6807
  for (const fact of insertedFacts) {
5984
6808
  await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
5985
6809
  }
@@ -6405,7 +7229,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6405
7229
  var IMPORT_TITLE_MAX = 500;
6406
7230
  var IMPORT_BODY_MAX = 8e3;
6407
7231
  var ImportExportService = class {
6408
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
7232
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
6409
7233
  this.db = db;
6410
7234
  this.entryRepo = entryRepo;
6411
7235
  this.taskRepo = taskRepo;
@@ -6416,6 +7240,7 @@ var ImportExportService = class {
6416
7240
  this.jobManager = jobManager;
6417
7241
  this.embeddingService = embeddingService;
6418
7242
  this.options = options;
7243
+ this.vectorRemoval = vectorRemoval;
6419
7244
  }
6420
7245
  async exportDump(entityIds) {
6421
7246
  let ids;
@@ -6791,7 +7616,7 @@ var ImportExportService = class {
6791
7616
  body: clipped?.body ?? fact.body,
6792
7617
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
6793
7618
  }, { operation: "importDump", trigger: "call" });
6794
- if (!embedded) {
7619
+ if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
6795
7620
  try {
6796
7621
  await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
6797
7622
  } catch (hookErr) {
@@ -6833,16 +7658,26 @@ var ImportExportService = class {
6833
7658
  fact.id
6834
7659
  );
6835
7660
  }
7661
+ if (this.embeddingService.hasVectorHook()) {
7662
+ await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
7663
+ }
6836
7664
  }
6837
7665
  }
6838
- for (const factId of softDeletedFactIds) {
6839
- if (!upsertedFactIds.has(factId) || upsertedDeletedFactIds.has(factId)) {
7666
+ const removedIds = softDeletedFactIds.filter(
7667
+ (id) => !upsertedFactIds.has(id) || upsertedDeletedFactIds.has(id)
7668
+ );
7669
+ if (this.vectorRemoval) {
7670
+ await this.vectorRemoval.deliverRemovals(
7671
+ entityId,
7672
+ Array.from(/* @__PURE__ */ new Set([...removedIds, ...upsertedDeletedFactIds])),
7673
+ "importDump",
7674
+ "call",
7675
+ removedIds
7676
+ );
7677
+ } else if (this.options.forceDeleteIgnoreRankerHook !== true) {
7678
+ for (const factId of removedIds) {
6840
7679
  try {
6841
- await this.embeddingService.notifyEmbeddingPersisted(
6842
- entityId,
6843
- factId,
6844
- null
6845
- );
7680
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
6846
7681
  } catch (hookErr) {
6847
7682
  console.warn(
6848
7683
  `[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
@@ -7079,27 +7914,62 @@ var EmbeddingService = class {
7079
7914
  }
7080
7915
  /**
7081
7916
  * 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).
7917
+ * `onEmbeddingPersisted` hook. Failure kinds: `storage_error` (a DB error) and
7918
+ * `fact_deleted` (the row was soft-deleted or gone: no blob, no vector call, no
7919
+ * marker). Embed failures do not originate here, so they cannot be marked as
7920
+ * such (spec §3.2, D3).
7084
7921
  */
7085
7922
  async storeFactVector(fact, float32Vector, ctx) {
7923
+ let stored = true;
7086
7924
  try {
7087
7925
  await this.storeEmbeddingDimension(float32Vector.length);
7088
7926
  const blob = new Uint8Array(float32Vector.buffer);
7089
- await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
7927
+ stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
7090
7928
  } catch (err) {
7091
7929
  console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
7092
7930
  this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
7093
7931
  return { ok: false, kind: "storage_error" };
7094
7932
  }
7933
+ if (!stored) return { ok: false, kind: "fact_deleted" };
7095
7934
  try {
7096
7935
  await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
7097
7936
  } catch (hookErr) {
7098
7937
  console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
7099
7938
  this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
7100
7939
  }
7940
+ if (this.hasVectorHook()) {
7941
+ await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
7942
+ }
7101
7943
  return { ok: true, dimension: float32Vector.length };
7102
7944
  }
7945
+ hasVectorHook() {
7946
+ return !!this.options.vectorRanker?.onEmbeddingPersisted;
7947
+ }
7948
+ /**
7949
+ * Run after a vector call (resolved or not) by every path that sends one.
7950
+ * Never throws: a failure here leaves the removal owed or unrecorded, as before.
7951
+ */
7952
+ async settleAfterVectorCall(entityId, factId, operation, trigger) {
7953
+ const vr = this.vectorRemoval;
7954
+ if (!vr) return;
7955
+ const outcome = await this.recordAfterVectorCall(entityId, factId);
7956
+ if (outcome === "enqueued") {
7957
+ try {
7958
+ await vr.service.deliverRemovals(entityId, [factId], operation, trigger, []);
7959
+ } catch (err) {
7960
+ console.warn(`[WikiMemory] post-embed removal delivery failed for ${factId}:`, err);
7961
+ }
7962
+ return;
7963
+ }
7964
+ if (outcome !== "write_failed") return;
7965
+ try {
7966
+ await this.callRemovalHook(entityId, factId, this.validateDeletionTimeout());
7967
+ } catch (hookErr) {
7968
+ console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
7969
+ this.reportHookFailed({ operation, trigger }, entityId, factId);
7970
+ await this.recordAfterVectorCall(entityId, factId);
7971
+ }
7972
+ }
7103
7973
  reportEmbed(ctx, fact, code, reason) {
7104
7974
  if (!ctx) return;
7105
7975
  emitDiagnostic(this.options, {
@@ -7131,6 +8001,48 @@ var EmbeddingService = class {
7131
8001
  const result = await this.tryEmbedFact(fact, ctx);
7132
8002
  return result.ok;
7133
8003
  }
8004
+ /** Wired by WikiMemory (VectorRemovalService itself depends on this class). */
8005
+ attachVectorRemoval(service, repo) {
8006
+ this.vectorRemoval = { service, repo };
8007
+ }
8008
+ /**
8009
+ * After an embed (and its vector call) settles: owe a removal if the fact is
8010
+ * no longer live, so a vector the host just received is taken back (§5.7, G10).
8011
+ * Never throws. `'enqueued'`: a ledger row was written. `'none'`: no
8012
+ * removal hook (or the hook gate is off). `'live'`: the fact is live. A row already pending is
8013
+ * replaced (attempts reset, spec §5.2), so it counts as `'enqueued'` and
8014
+ * is sent now: the last call the host sees after this vector is `null`.
8015
+ * `'owed'`: the write failed but a pending row already holds the removal.
8016
+ * `'write_failed'`: the fact is known not live, the write failed, and its
8017
+ * row is confirmed or missing; or the store has no ledger table and the
8018
+ * fact is known not live.
8019
+ * `'unknown'`: the liveness read and the guarded write both failed.
8020
+ */
8021
+ async recordAfterVectorCall(entityId, factId) {
8022
+ const vr = this.vectorRemoval;
8023
+ if (!vr || vr.service.gate() !== "hook") return "none";
8024
+ let live;
8025
+ try {
8026
+ if (!await vr.service.ledgerPresent()) {
8027
+ return await vr.repo.isLive(factId) ? "live" : "write_failed";
8028
+ }
8029
+ live = await vr.repo.isLive(factId);
8030
+ } catch (err) {
8031
+ console.warn(`[WikiMemory] post-embed liveness read failed for ${factId}:`, err);
8032
+ }
8033
+ if (live) return "live";
8034
+ try {
8035
+ return await vr.repo.enqueueIfNotLive(entityId, factId, Date.now()) ? "enqueued" : "live";
8036
+ } catch (err) {
8037
+ console.warn(`[WikiMemory] post-embed removal could not be recorded for ${factId}:`, err);
8038
+ if (live !== false) return "unknown";
8039
+ try {
8040
+ if ((await vr.repo.statusFor([factId])).get(factId) === "pending") return "owed";
8041
+ } catch {
8042
+ }
8043
+ return "write_failed";
8044
+ }
8045
+ }
7134
8046
  async notifyEmbeddingPersisted(entityId, factId, vector) {
7135
8047
  if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
7136
8048
  const vectorCopy = vector ? vector.slice() : null;
@@ -7140,15 +8052,72 @@ var EmbeddingService = class {
7140
8052
  vector: vectorCopy
7141
8053
  });
7142
8054
  }
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;
8055
+ validateDeletionTimeout() {
7147
8056
  const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
7148
8057
  if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
7149
8058
  throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
7150
8059
  }
7151
- const timeoutMs = rawTimeout;
8060
+ return rawTimeout;
8061
+ }
8062
+ /** Send a removal (`vector: null`) to the hook. No gate check; the caller owns the gate. */
8063
+ async callRemovalHook(entityId, factId, timeoutMs) {
8064
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) {
8065
+ throw new Error("callRemovalHook requires vectorRanker.onEmbeddingPersisted");
8066
+ }
8067
+ let timeoutHandle;
8068
+ const timeoutPromise = new Promise((_, reject) => {
8069
+ timeoutHandle = setTimeout(() => {
8070
+ const timeoutError = new Error(`onEmbeddingPersisted timed out after ${timeoutMs}ms`);
8071
+ timeoutError[HOOK_TIMEOUT_MARKER] = true;
8072
+ reject(timeoutError);
8073
+ }, timeoutMs);
8074
+ });
8075
+ const hookPromise = Promise.resolve().then(
8076
+ () => this.options.vectorRanker.onEmbeddingPersisted({ entityId, factId, vector: null })
8077
+ );
8078
+ try {
8079
+ await Promise.race([hookPromise, timeoutPromise]);
8080
+ } catch (err) {
8081
+ hookPromise.catch(() => {
8082
+ });
8083
+ throw err;
8084
+ } finally {
8085
+ if (timeoutHandle) clearTimeout(timeoutHandle);
8086
+ }
8087
+ }
8088
+ /**
8089
+ * One removal call per id for a store with no ledger table (setup() never
8090
+ * ran), so nothing records what is owed (spec §5.5.5). Stops at the first
8091
+ * timeout: a dead index costs one timeout, as in a drain (spec rev 5).
8092
+ * `failed` lists the ids not confirmed, in order; after a timeout it ends
8093
+ * with the timed-out id and every id after it. Throws only for an invalid
8094
+ * `deletionHookTimeoutMs`.
8095
+ */
8096
+ async callRemovalHookEach(entityId, ids, opts = {}) {
8097
+ const timeoutMs = this.validateDeletionTimeout();
8098
+ const failed = [];
8099
+ let firstRejection;
8100
+ for (let i = 0; i < ids.length; i++) {
8101
+ const factId = ids[i];
8102
+ try {
8103
+ await this.callRemovalHook(entityId, factId, timeoutMs);
8104
+ } catch (hookErr) {
8105
+ if (opts.warn) console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
8106
+ if (hookErr?.[HOOK_TIMEOUT_MARKER] === true) {
8107
+ failed.push(...ids.slice(i));
8108
+ return { failed, timedOut: true, timedOutId: factId, cause: hookErr };
8109
+ }
8110
+ failed.push(factId);
8111
+ firstRejection ?? (firstRejection = hookErr);
8112
+ }
8113
+ }
8114
+ return { failed, timedOut: false, cause: firstRejection };
8115
+ }
8116
+ async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
8117
+ if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
8118
+ if (this.options.forceDeleteIgnoreRankerHook === true) return;
8119
+ const vectorCopy = vector ? vector.slice() : null;
8120
+ const timeoutMs = this.validateDeletionTimeout();
7152
8121
  let timeoutHandle;
7153
8122
  const timeoutPromise = new Promise((_, reject) => {
7154
8123
  timeoutHandle = setTimeout(() => {
@@ -8129,6 +9098,6 @@ var WriteService = class {
8129
9098
  }
8130
9099
  };
8131
9100
 
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
9101
+ 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 };
9102
+ //# sourceMappingURL=chunk-G2H6TJUC.mjs.map
9103
+ //# sourceMappingURL=chunk-G2H6TJUC.mjs.map