@equationalapplications/core-llm-wiki 8.3.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { BaseRepository, WikiGraphNodeOwnershipConflict, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, assertEntityId, assertEpochMs, FTS5_STATE_KEY, fts5LedgerDropSql, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-V432RHCG.mjs';
2
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-V432RHCG.mjs';
1
+ import { BaseRepository, WikiGraphNodeOwnershipConflict, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, assertEntityId, assertEpochMs, FTS5_STATE_KEY, fts5LedgerDropSql, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-G2H6TJUC.mjs';
2
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-G2H6TJUC.mjs';
3
3
  import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, createEventIdDeriver, latestVerified, formatSourcesJson, appendEventIdComment, parseVerifiedFlexible, parseCitationsList } from '@equationalapplications/core-okf';
4
4
  import MiniSearch from 'minisearch';
5
5
 
@@ -671,20 +671,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
671
671
  * Used by runPrune(). Returns total number of deleted rows.
672
672
  * `tx` is REQUIRED so outbox deletion events are staged atomically.
673
673
  */
674
- async bulkDeletePruned(entityId, cutoff, ids, tx) {
674
+ async bulkDeletePruned(entityId, cutoff, ids, tx, opts = {}) {
675
675
  const executor = this.getExecutor(tx);
676
+ const guard = opts.keepUnconfirmedRemovals ? ` AND NOT EXISTS (SELECT 1 FROM ${this.prefix}vector_removals v WHERE v.fact_id = ${this.prefix}entries.id AND v.confirmed_at IS NULL)` : "";
676
677
  let totalChanges = 0;
677
678
  const chunkSize = 500;
678
679
  for (let i = 0; i < ids.length; i += chunkSize) {
679
680
  const chunk = ids.slice(i, i + chunkSize);
680
681
  const placeholders = chunk.map(() => "?").join(",");
681
- const result = await executor.runAsync(
682
- `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})`,
682
+ const deleted = (await executor.getAllAsync(
683
+ `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})${guard} RETURNING id`,
683
684
  [entityId, cutoff, ...chunk]
684
- );
685
- totalChanges += result.changes;
686
- if (result.changes > 0) {
687
- for (const id of chunk) {
685
+ )).map((r) => r.id);
686
+ totalChanges += deleted.length;
687
+ opts.deletedIds?.push(...deleted);
688
+ if (deleted.length > 0) {
689
+ for (const id of deleted) {
688
690
  await this.outbox.push({
689
691
  entityId,
690
692
  tableName: "entries",
@@ -791,11 +793,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
791
793
  const executor = this.getExecutor(tx);
792
794
  const now = Date.now();
793
795
  const placeholders = ids.map(() => "?").join(",");
794
- await executor.runAsync(
795
- `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ?`,
796
+ const updated = await executor.getAllAsync(
797
+ `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL RETURNING id`,
796
798
  [now, now, ...ids, entityId]
797
799
  );
798
- for (const id of ids) {
800
+ for (const { id } of updated) {
799
801
  await this.outbox.push({
800
802
  entityId,
801
803
  tableName: "entries",
@@ -955,18 +957,20 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
955
957
  }
956
958
  return rows;
957
959
  }
960
+ /** Returns `changes: 0` when the row is soft-deleted or gone (spec durable-vector-removal §5.7, G10). */
958
961
  async updateEmbeddingBlob(id, blob, tx) {
959
962
  const executor = this.getExecutor(tx);
960
- await executor.runAsync(
963
+ const r = await executor.runAsync(
961
964
  `UPDATE ${this.prefix}entries
962
965
  SET embedding_blob = ?,
963
966
  embedding = NULL,
964
967
  embedding_failed_at = NULL,
965
968
  embedding_failure_kind = NULL,
966
969
  embedding_attempts = 0
967
- WHERE id = ?`,
970
+ WHERE id = ? AND deleted_at IS NULL`,
968
971
  [blob, id]
969
972
  );
973
+ return { changes: r?.changes ?? 0 };
970
974
  }
971
975
  /**
972
976
  * Record a failed embedding attempt. Deliberately does NOT touch updated_at
@@ -2961,7 +2965,7 @@ async function createIndexStrategy(db, prefix, metadataRepo, preferred, opts = {
2961
2965
 
2962
2966
  // src/services/MaintenanceScheduler.ts
2963
2967
  var MaintenanceScheduler = class {
2964
- constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager) {
2968
+ constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager, vectorRemovalService, vectorRemovalRepo) {
2965
2969
  this.db = db;
2966
2970
  this.options = options;
2967
2971
  this.maintenanceService = maintenanceService;
@@ -2969,6 +2973,8 @@ var MaintenanceScheduler = class {
2969
2973
  this.eventRepo = eventRepo;
2970
2974
  this.entryRepo = entryRepo;
2971
2975
  this.jobManager = jobManager;
2976
+ this.vectorRemovalService = vectorRemovalService;
2977
+ this.vectorRemovalRepo = vectorRemovalRepo;
2972
2978
  }
2973
2979
  /**
2974
2980
  * Entities with **any** pending work only, sorted by `pendingEvents` desc
@@ -2980,7 +2986,17 @@ var MaintenanceScheduler = class {
2980
2986
  const autoHealThreshold = this.options.config?.autoHealThreshold || 100;
2981
2987
  const canEmbed = typeof this.options.llmProvider.embed === "function";
2982
2988
  const out = [];
2983
- for (const entityId of ids) {
2989
+ const owed = /* @__PURE__ */ new Map();
2990
+ if (this.vectorRemovalService.gate() !== "none" && await this.vectorRemovalService.ledgerPresent()) {
2991
+ const scope = entityIds === void 0 ? void 0 : new Set(entityIds);
2992
+ for (const e of await this.vectorRemovalRepo.entitiesWithDuePending(Date.now())) {
2993
+ if (scope !== void 0 && !scope.has(e)) continue;
2994
+ owed.set(e, (await this.vectorRemovalRepo.pendingStats(e)).count);
2995
+ }
2996
+ }
2997
+ const listed = new Set(ids);
2998
+ const scan = [...ids, ...[...owed.keys()].filter((e) => !listed.has(e))];
2999
+ for (const entityId of scan) {
2984
3000
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
2985
3001
  const pendingEvents = await this.eventRepo.countAfter(entityId, wm);
2986
3002
  const chars = pendingEvents > 0 ? await this.eventRepo.sumSummaryCharsAfter(entityId, wm) : 0;
@@ -2990,8 +3006,16 @@ var MaintenanceScheduler = class {
2990
3006
  if (healCheckpoint > eventCount) healCheckpoint = 0;
2991
3007
  const healDue = eventCount - healCheckpoint >= autoHealThreshold;
2992
3008
  const reembedPending = canEmbed && await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS) > 0;
2993
- if (pendingEvents > 0 || healDue || reembedPending) {
2994
- out.push({ entityId, pendingEvents, pendingTokensEstimate: Math.ceil(chars / 4), healDue, reembedPending });
3009
+ const owedCount = owed.get(entityId) ?? 0;
3010
+ if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0) {
3011
+ out.push({
3012
+ entityId,
3013
+ pendingEvents,
3014
+ pendingTokensEstimate: Math.ceil(chars / 4),
3015
+ healDue,
3016
+ reembedPending,
3017
+ ...owedCount > 0 ? { pendingExternalDeletions: owedCount } : {}
3018
+ });
2995
3019
  }
2996
3020
  }
2997
3021
  return out.sort((x, y) => y.pendingEvents - x.pendingEvents || (x.entityId < y.entityId ? -1 : x.entityId > y.entityId ? 1 : 0));
@@ -3017,8 +3041,9 @@ var MaintenanceScheduler = class {
3017
3041
  const meter = new UsageMeter(opts.tokenBudget);
3018
3042
  const budget = opts.tokenBudget;
3019
3043
  const deadline = opts.deadlineMs !== void 0 ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;
3020
- const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed"]);
3021
- const pending = await this.getPending(opts.entityIds);
3044
+ const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed", "externalDeletions"]);
3045
+ const externalDeletions = await this.runExternalDeletions(opts.entityIds, jobs.has("externalDeletions"), deadline);
3046
+ const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending);
3022
3047
  const states = pending.map((p) => ({
3023
3048
  p,
3024
3049
  report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false },
@@ -3150,9 +3175,43 @@ var MaintenanceScheduler = class {
3150
3175
  tokensUsed: meter.used,
3151
3176
  estimated: meter.estimated,
3152
3177
  remaining: budget === void 0 ? null : meter.remaining,
3153
- stoppedReason: stopped
3178
+ stoppedReason: stopped,
3179
+ externalDeletions
3154
3180
  };
3155
3181
  }
3182
+ /**
3183
+ * Runs first and outside the token budget: delivers owed vector-index
3184
+ * removals per entity (wiped entities included), without backoff. Pending is
3185
+ * reported even when the job is not listed or no hook is configured.
3186
+ */
3187
+ async runExternalDeletions(entityIds, enabled, deadline) {
3188
+ if (!await this.vectorRemovalService.ledgerPresent()) return { confirmed: 0, pending: 0 };
3189
+ const all = await this.vectorRemovalRepo.entitiesWithPending();
3190
+ const scope = entityIds === void 0 ? void 0 : new Set(entityIds);
3191
+ const entities = scope === void 0 ? all : all.filter((e) => scope.has(e));
3192
+ let confirmed = 0;
3193
+ let pending = 0;
3194
+ const counted = /* @__PURE__ */ new Set();
3195
+ if (enabled) {
3196
+ for (const e of entities) {
3197
+ if (Date.now() >= deadline) break;
3198
+ const r = await this.vectorRemovalService.drain(
3199
+ { entityId: e },
3200
+ { trigger: "call", ...deadline === Infinity ? {} : { deadlineAt: deadline } }
3201
+ );
3202
+ confirmed += r.confirmed;
3203
+ if (!r.transient) {
3204
+ pending += r.pending;
3205
+ counted.add(e);
3206
+ }
3207
+ if (r.timedOut) break;
3208
+ }
3209
+ }
3210
+ for (const e of entities) {
3211
+ if (!counted.has(e)) pending += (await this.vectorRemovalRepo.pendingStats(e)).count;
3212
+ }
3213
+ return { confirmed, pending };
3214
+ }
3156
3215
  };
3157
3216
 
3158
3217
  // src/prompts/ontology.ts
@@ -3774,11 +3833,15 @@ var WikiMemory = class {
3774
3833
  this.upsertIdStashSize = 0;
3775
3834
  /** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */
3776
3835
  this.upsertIdStashGen = 0;
3836
+ /** Superseded fact ids per entity awaiting a post-commit delivery from syncSearchIndex(). */
3837
+ this.removalStash = /* @__PURE__ */ new Map();
3838
+ this.removalStashSize = 0;
3777
3839
  this.reinitSearch = null;
3778
3840
  /** Monotonic time before which a no-arg syncSearchIndex() skips the re-init (0 = no cooldown). */
3779
3841
  this.reinitRetryAt = 0;
3780
3842
  /** Consecutive failed re-inits; drives the exponential backoff. */
3781
3843
  this.reinitFailures = 0;
3844
+ this.setupRemovalDrain = null;
3782
3845
  this.db = withSerializedTransactions(db);
3783
3846
  this.options = options;
3784
3847
  warnChangedDefaultsOnce(options.config);
@@ -3803,6 +3866,9 @@ var WikiMemory = class {
3803
3866
  );
3804
3867
  this.lintService = new LintService(this.lintRepo, this.ontologyService);
3805
3868
  this.embeddingService = new EmbeddingService(this.db, this.options, this.entryRepo, this.metadataRepo);
3869
+ this.vectorRemovalRepo = new VectorRemovalRepository(this.db, this.prefix);
3870
+ this.vectorRemovalService = new VectorRemovalService(this.db, this.options, this.vectorRemovalRepo, this.embeddingService, this.metadataRepo);
3871
+ this.embeddingService.attachVectorRemoval(this.vectorRemovalService, this.vectorRemovalRepo);
3806
3872
  this.searchService = new SearchService(
3807
3873
  this.entryRepo,
3808
3874
  new MiniSearchIndexStrategy()
@@ -3823,7 +3889,8 @@ var WikiMemory = class {
3823
3889
  this.jobManager,
3824
3890
  this.embeddingService,
3825
3891
  this.promptService,
3826
- this.ontologyService
3892
+ this.ontologyService,
3893
+ this.vectorRemovalService
3827
3894
  );
3828
3895
  this.maintenanceService = new MaintenanceService(
3829
3896
  this.db,
@@ -3839,7 +3906,9 @@ var WikiMemory = class {
3839
3906
  this.embeddingService,
3840
3907
  this.promptService,
3841
3908
  this.ontologyService,
3842
- this.edgeRepo
3909
+ this.edgeRepo,
3910
+ this.vectorRemovalService,
3911
+ this.vectorRemovalRepo
3843
3912
  );
3844
3913
  this.maintenanceScheduler = new MaintenanceScheduler(
3845
3914
  this.db,
@@ -3848,7 +3917,9 @@ var WikiMemory = class {
3848
3917
  this.metadataRepo,
3849
3918
  this.eventRepo,
3850
3919
  this.entryRepo,
3851
- this.jobManager
3920
+ this.jobManager,
3921
+ this.vectorRemovalService,
3922
+ this.vectorRemovalRepo
3852
3923
  );
3853
3924
  this.importExportService = new ImportExportService(
3854
3925
  this.db,
@@ -3860,7 +3931,8 @@ var WikiMemory = class {
3860
3931
  this.searchService,
3861
3932
  this.jobManager,
3862
3933
  this.embeddingService,
3863
- this.options
3934
+ this.options,
3935
+ this.vectorRemovalService
3864
3936
  );
3865
3937
  this.retrievalService = new RetrievalService(
3866
3938
  this.options,
@@ -3928,6 +4000,33 @@ var WikiMemory = class {
3928
4000
  }
3929
4001
  if (stash.size > 0) this.upsertIdStash.set(entityId, stash);
3930
4002
  }
4003
+ /**
4004
+ * Overflow past the cap drops the id from the stash only: the trigger already
4005
+ * put it on the ledger, so it stays owed and runExternalDeletions or
4006
+ * runPendingMaintenance delivers it later.
4007
+ */
4008
+ stashRemovalIds(entityId, ids) {
4009
+ const cap = this.constructor.REMOVAL_STASH_CAP;
4010
+ const stash = this.removalStash.get(entityId) ?? /* @__PURE__ */ new Set();
4011
+ for (const id of ids) {
4012
+ if (stash.has(id)) continue;
4013
+ if (this.removalStashSize >= cap) continue;
4014
+ stash.add(id);
4015
+ this.removalStashSize++;
4016
+ }
4017
+ if (stash.size > 0) this.removalStash.set(entityId, stash);
4018
+ }
4019
+ /** Removes and returns the stashed removal ids (one entity, or all). */
4020
+ takeRemovalIds(entityId) {
4021
+ const out = /* @__PURE__ */ new Map();
4022
+ for (const [e, set] of [...this.removalStash]) {
4023
+ if (entityId !== void 0 && e !== entityId) continue;
4024
+ out.set(e, [...set]);
4025
+ this.removalStashSize -= set.size;
4026
+ this.removalStash.delete(e);
4027
+ }
4028
+ return out;
4029
+ }
3931
4030
  /** Snapshot of the stash (one entity, or all) with generations, without removing anything. */
3932
4031
  peekStashedIds(entityId) {
3933
4032
  const snapshot = /* @__PURE__ */ new Map();
@@ -4016,6 +4115,84 @@ var WikiMemory = class {
4016
4115
  )
4017
4116
  );
4018
4117
  await this.searchService.sync(void 0, { deadline: openDeadline });
4118
+ await this.startSetupRemovalDrain();
4119
+ }
4120
+ /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
4121
+ async startSetupRemovalDrain() {
4122
+ if (this.setupRemovalDrain) return;
4123
+ const gate = this.vectorRemovalService.gate();
4124
+ if (gate === "none") return;
4125
+ const prelude = (async () => {
4126
+ if (gate === "hook" && !await this.vectorRemovalService.externalIndexInUse()) {
4127
+ await this.db.withTransactionAsync((tx) => this.vectorRemovalService.markExternalIndexInUse(tx));
4128
+ }
4129
+ if ((await this.vectorRemovalRepo.pendingStats()).count === 0) {
4130
+ if (gate === "force") await this.vectorRemovalService.clearExternalIndexMarker();
4131
+ return { drain: null };
4132
+ }
4133
+ if (this.options.drainExternalDeletionsOnSetup !== true) {
4134
+ if (gate === "hook") await this.vectorRemovalService.emitPending(void 0, "auto");
4135
+ return { drain: null };
4136
+ }
4137
+ const drain = (async () => {
4138
+ try {
4139
+ const r = await this.vectorRemovalService.drain(
4140
+ { all: true },
4141
+ { backoff: true, deadlineAt: Date.now() + 1e4, trigger: "auto" }
4142
+ );
4143
+ if (r.pending > 0) await this.vectorRemovalService.emitPending(void 0, "auto");
4144
+ } catch {
4145
+ emitDiagnostic(this.options, {
4146
+ code: "background_job_failed",
4147
+ operation: "externalDeletion",
4148
+ trigger: "auto",
4149
+ entityId: "",
4150
+ // store-wide drain
4151
+ detail: { reason: "unhandled_rejection" }
4152
+ });
4153
+ }
4154
+ })();
4155
+ return { drain };
4156
+ })();
4157
+ const joined = prelude.then((r) => r.drain ?? void 0, () => void 0);
4158
+ this.setupRemovalDrain = joined;
4159
+ void joined.then(() => {
4160
+ if (this.setupRemovalDrain === joined) this.setupRemovalDrain = null;
4161
+ });
4162
+ await prelude;
4163
+ }
4164
+ /**
4165
+ * Delivers owed vector-index removals now (spec §5.9). No backoff. With an
4166
+ * entity id only that entity's rows; otherwise all. `deadlineMs` is a duration.
4167
+ * `transient: true` means a ledger read or write could not run (for example,
4168
+ * you held a transaction open on the connection); the rows stay pending.
4169
+ */
4170
+ async runExternalDeletions(entityId, opts) {
4171
+ if (entityId !== void 0) assertEntityId2(entityId);
4172
+ const ms = opts?.deadlineMs;
4173
+ if (ms !== void 0 && (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)) {
4174
+ throw new TypeError("deadlineMs must be a finite number >= 0");
4175
+ }
4176
+ if (!await this.vectorRemovalService.ledgerPresent()) {
4177
+ return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
4178
+ }
4179
+ const r = await this.vectorRemovalService.drain(
4180
+ entityId === void 0 ? { all: true } : { entityId },
4181
+ { trigger: "call", ...ms !== void 0 ? { deadlineAt: Date.now() + ms } : {} }
4182
+ );
4183
+ return {
4184
+ confirmed: r.confirmed,
4185
+ pending: r.pending,
4186
+ failedIds: r.failedIds,
4187
+ timedOut: r.timedOut,
4188
+ ...r.transient ? { transient: true } : {}
4189
+ };
4190
+ }
4191
+ /** Removals still owed to the host's vector index (all entities, or one). */
4192
+ async getPendingExternalDeletions(entityId) {
4193
+ if (entityId !== void 0) assertEntityId2(entityId);
4194
+ if (!await this.vectorRemovalService.ledgerPresent()) return { count: 0, oldestEnqueuedAt: null, maxAttempts: 0 };
4195
+ return this.vectorRemovalRepo.pendingStats(entityId);
4019
4196
  }
4020
4197
  async hasChanged(entityId, sourceRefOrEntries, sourceHashArg) {
4021
4198
  if (typeof sourceRefOrEntries === "string") {
@@ -4113,7 +4290,17 @@ var WikiMemory = class {
4113
4290
  async getInstructions(entityId) {
4114
4291
  assertEntityId2(entityId);
4115
4292
  const ontologyContext = await this.ontologyService.buildPromptContext(entityId);
4116
- return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config));
4293
+ const { guidance, diagnostic } = PromptService.resolveGuidance(this.options.config, entityId);
4294
+ if (diagnostic) {
4295
+ emitDiagnostic(this.options, {
4296
+ code: diagnostic.code,
4297
+ operation: "read",
4298
+ trigger: "call",
4299
+ entityId,
4300
+ detail: diagnostic.detail
4301
+ });
4302
+ }
4303
+ return this.promptService.buildInstructionTemplates(ontologyContext, resolveLibrarianStrategy(this.options.config), guidance);
4117
4304
  }
4118
4305
  /**
4119
4306
  * Returns the live source_refs for an entity, one row per ref, with the most
@@ -4183,8 +4370,9 @@ var WikiMemory = class {
4183
4370
  async write(entityId, event) {
4184
4371
  return this.writeService.write(entityId, event);
4185
4372
  }
4186
- /** Await auto-mode background librarian/heal jobs started by write(). No-op in 'deferred' mode. */
4373
+ /** Await auto-mode background librarian/heal jobs started by write(), and the removal drain `setup()` started under `drainExternalDeletionsOnSetup`. */
4187
4374
  async drain() {
4375
+ await this.setupRemovalDrain;
4188
4376
  return this.writeService.drain();
4189
4377
  }
4190
4378
  /**
@@ -4196,14 +4384,37 @@ var WikiMemory = class {
4196
4384
  async getPendingMaintenance(entityIds) {
4197
4385
  return this.maintenanceScheduler.getPending(entityIds);
4198
4386
  }
4199
- /** Run pending librarian/heal/reembed work under an optional token budget and deadline (spec §6.2). Nothing runs after it resolves. */
4387
+ /** Run pending removals, librarian, heal and reembed work under an optional token budget and deadline (spec §6.2). Awaits the setup removal drain first, when `drainExternalDeletionsOnSetup` started one. */
4200
4388
  async runPendingMaintenance(options) {
4201
- return this.maintenanceScheduler.run(options);
4389
+ let opts = options;
4390
+ const ms = options?.deadlineMs;
4391
+ if (ms !== void 0 && (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)) {
4392
+ throw new TypeError("deadlineMs must be a finite number >= 0");
4393
+ }
4394
+ const setupDrain = this.setupRemovalDrain;
4395
+ if (setupDrain) {
4396
+ if (ms !== void 0) {
4397
+ const started = Date.now();
4398
+ let handle;
4399
+ await Promise.race([
4400
+ setupDrain,
4401
+ new Promise((resolve) => {
4402
+ handle = setTimeout(resolve, ms);
4403
+ })
4404
+ ]).finally(() => {
4405
+ if (handle) clearTimeout(handle);
4406
+ });
4407
+ opts = { ...options, deadlineMs: Math.max(0, ms - (Date.now() - started)) };
4408
+ } else {
4409
+ await setupDrain;
4410
+ }
4411
+ }
4412
+ return this.maintenanceScheduler.run(opts);
4202
4413
  }
4203
4414
  /**
4204
4415
  * @param options.promptOverride - Applies only to this manual call. Does NOT affect
4205
4416
  * WriteService-triggered auto-runs. For persistent prompt customization across auto-runs,
4206
- * set `options.config.prompts.librarianSystemPrompt` at WikiMemory construction time.
4417
+ * set `options.config.prompts.guidance` at WikiMemory construction time.
4207
4418
  */
4208
4419
  async runLibrarian(entityId, options) {
4209
4420
  return this.maintenanceService.runLibrarian(entityId, options);
@@ -4279,6 +4490,11 @@ var WikiMemory = class {
4279
4490
  * waits at least 5 s, doubling per consecutive failure up to 5 min (longer
4280
4491
  * when an attempt is itself slow), before retrying again.
4281
4492
  *
4493
+ * It also calls the host's removal hook (`onEmbeddingPersisted(…, null)`) for
4494
+ * the stashed ids that `upsertGraph` superseded, and can take up to
4495
+ * `deletionHookTimeoutMs` per id when the host's index is slow. It never
4496
+ * drains an entity's wider removal backlog.
4497
+ *
4282
4498
  * Call only after the host's transaction commits: called inside it, the
4283
4499
  * rebuild may index rows that later roll back, or miss them and clear the
4284
4500
  * stale flag anyway. Serialized with core's internal index syncs and takes
@@ -4294,6 +4510,19 @@ var WikiMemory = class {
4294
4510
  * @throws {TypeError} when `entityId` is given but is not a non-empty string.
4295
4511
  */
4296
4512
  async syncSearchIndex(entityId) {
4513
+ if (entityId !== void 0) assertEntityId2(entityId);
4514
+ const removals = this.takeRemovalIds(entityId);
4515
+ try {
4516
+ await this.syncSearchIndexCore(entityId);
4517
+ } catch (err) {
4518
+ for (const [e, ids] of removals) this.stashRemovalIds(e, ids);
4519
+ throw err;
4520
+ }
4521
+ for (const [e, ids] of removals) {
4522
+ await this.vectorRemovalService.deliverRemovals(e, ids, "upsertGraph", "call");
4523
+ }
4524
+ }
4525
+ async syncSearchIndexCore(entityId) {
4297
4526
  if (entityId === void 0) {
4298
4527
  if (!this.searchService.isKeywordAvailable() && monotonicNow() >= this.reinitRetryAt) {
4299
4528
  this.reinitSearch ?? (this.reinitSearch = (async () => {
@@ -4361,6 +4590,14 @@ var WikiMemory = class {
4361
4590
  * hard-deletes the soft-deleted rows once they are older than
4362
4591
  * `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).
4363
4592
  * `dryRun` previews the counts.
4593
+ *
4594
+ * With a removal hook (`vectorRanker.onEmbeddingPersisted`), the deleted
4595
+ * facts are recorded as owed in the same transaction and then delivered to
4596
+ * the hook before this resolves.
4597
+ *
4598
+ * @throws {WikiExternalDeletionError} when the hook didn't confirm every
4599
+ * removal. The local delete stays committed and the rest stay owed; retry,
4600
+ * or call `runExternalDeletions()`.
4364
4601
  */
4365
4602
  async forget(entityId, params, opts) {
4366
4603
  return this.maintenanceService.forget(entityId, params, opts);
@@ -4413,12 +4650,15 @@ var WikiMemory = class {
4413
4650
  * semantics identical to `ingestDocument`, minus the LLM extraction step.
4414
4651
  *
4415
4652
  * MUST be called from inside an open `db.withTransactionAsync` callback —
4416
- * the third argument is the caller's `tx`. The method does not open a
4653
+ * the third argument is the caller's `tx`, and that transaction must be
4654
+ * opened through the adapter given to `createWiki` (the removal ledger is
4655
+ * filled by triggers inside it, and a rollback discards the rows). The method does not open a
4417
4656
  * nested transaction, does not acquire any lock, and does not perform
4418
4657
  * post-commit work (search sync, embedding, cache eviction). After the
4419
4658
  * transaction commits, call `syncSearchIndex(entityId)` — or
4420
4659
  * `syncSearchIndex()` after writing several entities in one transaction —
4421
- * to make the new nodes keyword-searchable: both forms drain this call's node ids
4660
+ * to make the new nodes keyword-searchable and to deliver, through the
4661
+ * host's removal hook, the vectors of any facts the call superseded: both forms drain this call's node ids
4422
4662
  * first, to completion, so the nodes are searchable under any backlog (up to
4423
4663
  * `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with
4424
4664
  * the backlog). Embeddings still come from the maintenance
@@ -4478,6 +4718,7 @@ var WikiMemory = class {
4478
4718
  { diag: { buffer: diagBuffer, operation: "upsertGraph" } }
4479
4719
  );
4480
4720
  this.stashUpsertIds(entityId, [...supersededFactIds, ...params.nodes.map((n) => n.id)]);
4721
+ this.stashRemovalIds(entityId, supersededFactIds);
4481
4722
  this.searchService.markStale(entityId);
4482
4723
  diagBuffer.flush(this.options);
4483
4724
  return result;
@@ -4660,8 +4901,10 @@ var WikiMemory = class {
4660
4901
  }
4661
4902
  };
4662
4903
  _testAccessNonTestEnvWarned = new WeakMap();
4663
- /** Max upsertGraph node ids held for their post-commit sync (spec #280 id threading). */
4904
+ /** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */
4664
4905
  WikiMemory.UPSERT_ID_STASH_CAP = 1e4;
4906
+ /** Max superseded-fact ids held for post-commit removal delivery. */
4907
+ WikiMemory.REMOVAL_STASH_CAP = 1e4;
4665
4908
  function assertEntityId2(entityId) {
4666
4909
  if (typeof entityId !== "string" || entityId.length === 0) {
4667
4910
  throw new TypeError("Invalid entityId: must be a non-empty string.");
@@ -5627,6 +5870,6 @@ function createWiki(db, options) {
5627
5870
  return new WikiMemory(db, options);
5628
5871
  }
5629
5872
 
5630
- export { DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_SETUP_BUDGET_MS, WikiMemory, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseOkfBundle, validateLibrarianPromptTemplate };
5873
+ export { DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_SETUP_BUDGET_MS, WikiMemory, buildOntologyPromptAppendix, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseOkfBundle, validateLibrarianPromptTemplate };
5631
5874
  //# sourceMappingURL=index.mjs.map
5632
5875
  //# sourceMappingURL=index.mjs.map