@equationalapplications/core-llm-wiki 8.0.3 → 8.0.5

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.
@@ -3109,6 +3109,7 @@ var BaseRepository = class {
3109
3109
  function entitySummaryMetaKey(entityId) {
3110
3110
  return `entity_summary:${entityId}`;
3111
3111
  }
3112
+ var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
3112
3113
  var MetadataRepository = class extends BaseRepository {
3113
3114
  // CHECKPOINTS TABLE METHODS
3114
3115
  async getCheckpoint(entityId, tx) {
@@ -5135,16 +5136,29 @@ var MaintenanceService = class {
5135
5136
  if (retainEventsFor !== null) {
5136
5137
  const cutoff = now - retainEventsFor * 864e5;
5137
5138
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
5139
+ let wm = null;
5140
+ await this.db.withTransactionAsync(async (tx) => {
5141
+ if (guarded) {
5142
+ wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
5143
+ deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
5144
+ } else {
5145
+ deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
5146
+ }
5147
+ if (deletedEvents > 0) {
5148
+ const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
5149
+ const updates = {};
5150
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
5151
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
5152
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
5153
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
5154
+ }
5155
+ }
5156
+ });
5138
5157
  if (guarded) {
5139
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
5140
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm)).changes;
5141
5158
  const held = await this.eventRepo.countHeldBack(entityId, cutoff, wm);
5142
5159
  if (held > 0) {
5143
5160
  emitDiagnostic(this.options, { code: "event_retention_held", operation: "prune", trigger: "call", entityId, detail: { count: held } });
5144
5161
  }
5145
- } else {
5146
- const eventResult = await this.eventRepo.prune(entityId, cutoff);
5147
- deletedEvents = eventResult.changes;
5148
5162
  }
5149
5163
  }
5150
5164
  if (vacuum) {
@@ -5457,20 +5471,57 @@ var MaintenanceService = class {
5457
5471
  const newer = !current || next.at > current.at || next.at === current.at && next.id > current.id;
5458
5472
  if (newer) await this.metadataRepo.setLibrarianWatermark(entityId, next, this.db);
5459
5473
  }
5474
+ /**
5475
+ * Anchor the ops watermark before an auto trigger advances
5476
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
5477
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
5478
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
5479
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
5480
+ * event count, already read by the caller in the same transaction. All
5481
+ * reads and the write use the trigger's transaction. Returns the watermark
5482
+ * in force afterwards, so the caller need not read it again.
5483
+ * Package-internal.
5484
+ */
5485
+ async anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) {
5486
+ const existing = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
5487
+ if (existing) return existing;
5488
+ const wm = await this.anchorAtLegacyBoundary(entityId, preCheckpoint, total, tx);
5489
+ if (wm) return wm;
5490
+ await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, tx);
5491
+ return START_OF_LOG_WATERMARK;
5492
+ }
5493
+ /**
5494
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
5495
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
5496
+ * nothing and returns null when there is no legacy history or no such
5497
+ * event; each caller picks its own fallback.
5498
+ */
5499
+ async anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
5500
+ if (checkpoint <= 0 || total <= 0) return null;
5501
+ const ev = await this.eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
5502
+ if (!ev) return null;
5503
+ const wm = { at: ev.created_at, id: ev.id };
5504
+ await this.metadataRepo.setLibrarianWatermark(entityId, wm, db);
5505
+ return wm;
5506
+ }
5460
5507
  /**
5461
5508
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
5462
5509
  * checkpoint already covered. No-op when a watermark already exists or the
5463
5510
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
5464
- * offset `min(memory_checkpoint, totalEvents) - 1`.
5511
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
5512
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
5465
5513
  */
5466
5514
  async seedLibrarianWatermark(entityId) {
5467
5515
  if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
5468
5516
  const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
5469
5517
  const memory = cp.memory ?? 0;
5470
5518
  if (memory <= 0) return;
5471
- const total = await this.eventRepo.count(entityId);
5472
- const ev = await this.eventRepo.getAtOffset(entityId, Math.min(memory, total) - 1);
5473
- if (ev) await this.metadataRepo.setLibrarianWatermark(entityId, { at: ev.created_at, id: ev.id }, this.db);
5519
+ const total = await this.eventRepo.count(entityId, this.db);
5520
+ if (memory > total) {
5521
+ await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, this.db);
5522
+ return;
5523
+ }
5524
+ await this.anchorAtLegacyBoundary(entityId, memory, total, this.db);
5474
5525
  }
5475
5526
  /**
5476
5527
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -7633,16 +7684,30 @@ var WriteService = class {
7633
7684
  created_at: now,
7634
7685
  occurred_at: occurredAt
7635
7686
  };
7687
+ const stampCreatedAt = async (tx) => {
7688
+ const latest = await this.eventRepo.latestCreatedAt(entityId, tx);
7689
+ if (latest === null || latest < newEvent.created_at) return;
7690
+ if (latest >= Number.MAX_SAFE_INTEGER) {
7691
+ throw new RangeError(`Cannot stamp event created_at: the newest stored created_at (${latest}) is at Number.MAX_SAFE_INTEGER, so no later timestamp can be ordered safely.`);
7692
+ }
7693
+ newEvent.created_at = latest + 1;
7694
+ };
7636
7695
  const deferred = resolveMaintenanceMode(this.options.config) === "deferred";
7637
7696
  if (deferred) {
7638
- await this.eventRepo.add(newEvent);
7697
+ await this.db.withTransactionAsync(async (tx) => {
7698
+ await stampCreatedAt(tx);
7699
+ await this.eventRepo.add(newEvent, tx);
7700
+ });
7639
7701
  return;
7640
7702
  }
7641
7703
  let shouldRunLibrarian = false;
7642
7704
  let librarianCount = 0;
7643
7705
  let prevMemoryCheckpoint = 0;
7644
7706
  let eventCount = 0;
7707
+ const isOps = resolveLibrarianStrategy(this.options.config) === "ops";
7708
+ const anchorOps = async (preCheckpoint, total, tx) => isOps ? this.maintenanceService.anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) : this.metadataRepo.getLibrarianWatermark(entityId, tx);
7645
7709
  await this.db.withTransactionAsync(async (tx) => {
7710
+ await stampCreatedAt(tx);
7646
7711
  await this.eventRepo.add(newEvent, tx);
7647
7712
  const threshold = this.options.config?.autoLibrarianThreshold || 20;
7648
7713
  const [count, cp] = await Promise.all([
@@ -7651,18 +7716,19 @@ var WriteService = class {
7651
7716
  ]);
7652
7717
  eventCount = count;
7653
7718
  let memoryCheckpoint = cp.memory ?? 0;
7654
- if (memoryCheckpoint > count) memoryCheckpoint = 0;
7719
+ if (memoryCheckpoint >= count) memoryCheckpoint = 0;
7655
7720
  if (count - memoryCheckpoint >= threshold) {
7656
7721
  if (!this.jobManager.isBlocked("librarian", entityId)) {
7657
7722
  shouldRunLibrarian = true;
7658
7723
  librarianCount = count;
7659
7724
  prevMemoryCheckpoint = memoryCheckpoint;
7725
+ if (isOps) await anchorOps(memoryCheckpoint, count, tx);
7660
7726
  await this.metadataRepo.updateCheckpoint(entityId, { memory: count }, tx);
7661
7727
  }
7662
7728
  } else {
7663
7729
  const tokenThreshold = this.options.config?.autoLibrarianTokenThreshold;
7664
7730
  if (typeof tokenThreshold === "number" && tokenThreshold > 0 && !this.jobManager.isBlocked("librarian", entityId)) {
7665
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
7731
+ const wm = await anchorOps(memoryCheckpoint, count, tx);
7666
7732
  const chars = await this.eventRepo.sumSummaryCharsAfter(entityId, wm, tx);
7667
7733
  if (Math.ceil(chars / 4) >= tokenThreshold) {
7668
7734
  shouldRunLibrarian = true;
@@ -7685,7 +7751,11 @@ var WriteService = class {
7685
7751
  this.track(job);
7686
7752
  } catch (e) {
7687
7753
  if (!(e instanceof WikiBusyError)) throw e;
7688
- await this.metadataRepo.updateCheckpoint(entityId, { memory: prevMemoryCheckpoint }, this.db);
7754
+ const added = librarianCount - prevMemoryCheckpoint;
7755
+ await this.db.withTransactionAsync(async (tx) => {
7756
+ const memory = (await this.metadataRepo.getCheckpoint(entityId, tx)).memory ?? 0;
7757
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: Math.max(0, memory - added) }, tx);
7758
+ });
7689
7759
  }
7690
7760
  } else if (!this.jobManager.isBlocked("librarian", entityId)) {
7691
7761
  const healJob = this.maybeRunHeal(entityId, eventCount).catch((err) => {
@@ -7720,7 +7790,8 @@ var WriteService = class {
7720
7790
  try {
7721
7791
  const result = await this.maintenanceService.doRunHeal(entityId, { trigger: "auto" });
7722
7792
  if (result.remaining === 0) {
7723
- await this.metadataRepo.updateCheckpoint(entityId, { heal: currentEventCount }, this.db);
7793
+ const live = await this.eventRepo.count(entityId, this.db);
7794
+ await this.metadataRepo.updateCheckpoint(entityId, { heal: Math.min(currentEventCount, live) }, this.db);
7724
7795
  }
7725
7796
  } finally {
7726
7797
  this.jobManager.releaseLock("heal", entityId);
@@ -7745,5 +7816,5 @@ var WriteService = class {
7745
7816
  };
7746
7817
 
7747
7818
  export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, 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 };
7748
- //# sourceMappingURL=chunk-2N5SNDS3.mjs.map
7749
- //# sourceMappingURL=chunk-2N5SNDS3.mjs.map
7819
+ //# sourceMappingURL=chunk-GYF5QLYK.mjs.map
7820
+ //# sourceMappingURL=chunk-GYF5QLYK.mjs.map