@equationalapplications/core-llm-wiki 8.0.4 → 8.1.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.
@@ -2180,7 +2180,8 @@ var SEVERITY = {
2180
2180
  contradicts_document: "warn",
2181
2181
  resolve_failed: "warn",
2182
2182
  read_budget: "info",
2183
- event_retention_held: "info"
2183
+ event_retention_held: "info",
2184
+ event_created_at_clamped: "warn"
2184
2185
  };
2185
2186
  var MESSAGE = {
2186
2187
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2202,7 +2203,8 @@ var MESSAGE = {
2202
2203
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
2203
2204
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
2204
2205
  read_budget: "A read was packed to a token budget.",
2205
- event_retention_held: "Event pruning was held back because the librarian has not processed those events yet."
2206
+ event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
2207
+ 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."
2206
2208
  };
2207
2209
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2208
2210
  function copyDetail(detail) {
@@ -3109,6 +3111,7 @@ var BaseRepository = class {
3109
3111
  function entitySummaryMetaKey(entityId) {
3110
3112
  return `entity_summary:${entityId}`;
3111
3113
  }
3114
+ var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
3112
3115
  var MetadataRepository = class extends BaseRepository {
3113
3116
  // CHECKPOINTS TABLE METHODS
3114
3117
  async getCheckpoint(entityId, tx) {
@@ -3307,6 +3310,28 @@ var MetadataRepository = class extends BaseRepository {
3307
3310
  }
3308
3311
  };
3309
3312
 
3313
+ // src/services/legacyWatermark.ts
3314
+ async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
3315
+ if (checkpoint <= 0 || total <= 0) return null;
3316
+ const ev = await eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
3317
+ if (!ev) return null;
3318
+ const wm = { at: ev.created_at, id: ev.id };
3319
+ await metadataRepo.setLibrarianWatermark(entityId, wm, db);
3320
+ return wm;
3321
+ }
3322
+ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
3323
+ const existing = await metadataRepo.getLibrarianWatermark(entityId, db);
3324
+ if (existing) return existing;
3325
+ const memory = (await metadataRepo.getCheckpoint(entityId, db)).memory ?? 0;
3326
+ if (memory <= 0) return null;
3327
+ const total = await eventRepo.count(entityId, db);
3328
+ if (memory > total) {
3329
+ await metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, db);
3330
+ return START_OF_LOG_WATERMARK;
3331
+ }
3332
+ return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
3333
+ }
3334
+
3310
3335
  // src/services/BoundedLlmCall.ts
3311
3336
  var DEFAULT_BATCH_SIZE = 10;
3312
3337
  var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
@@ -5135,16 +5160,29 @@ var MaintenanceService = class {
5135
5160
  if (retainEventsFor !== null) {
5136
5161
  const cutoff = now - retainEventsFor * 864e5;
5137
5162
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
5163
+ let wm = null;
5164
+ await this.db.withTransactionAsync(async (tx) => {
5165
+ if (guarded) {
5166
+ wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
5167
+ deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
5168
+ } else {
5169
+ deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
5170
+ }
5171
+ if (deletedEvents > 0) {
5172
+ const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
5173
+ const updates = {};
5174
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
5175
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
5176
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
5177
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
5178
+ }
5179
+ }
5180
+ });
5138
5181
  if (guarded) {
5139
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
5140
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm)).changes;
5141
5182
  const held = await this.eventRepo.countHeldBack(entityId, cutoff, wm);
5142
5183
  if (held > 0) {
5143
5184
  emitDiagnostic(this.options, { code: "event_retention_held", operation: "prune", trigger: "call", entityId, detail: { count: held } });
5144
5185
  }
5145
- } else {
5146
- const eventResult = await this.eventRepo.prune(entityId, cutoff);
5147
- deletedEvents = eventResult.changes;
5148
5186
  }
5149
5187
  }
5150
5188
  if (vacuum) {
@@ -5457,20 +5495,43 @@ var MaintenanceService = class {
5457
5495
  const newer = !current || next.at > current.at || next.at === current.at && next.id > current.id;
5458
5496
  if (newer) await this.metadataRepo.setLibrarianWatermark(entityId, next, this.db);
5459
5497
  }
5498
+ /**
5499
+ * Anchor the ops watermark before an auto trigger advances
5500
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
5501
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
5502
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
5503
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
5504
+ * event count, already read by the caller in the same transaction. All
5505
+ * reads and the write use the trigger's transaction. Returns the watermark
5506
+ * in force afterwards, so the caller need not read it again.
5507
+ * Package-internal.
5508
+ */
5509
+ async anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) {
5510
+ const existing = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
5511
+ if (existing) return existing;
5512
+ const wm = await this.anchorAtLegacyBoundary(entityId, preCheckpoint, total, tx);
5513
+ if (wm) return wm;
5514
+ await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, tx);
5515
+ return START_OF_LOG_WATERMARK;
5516
+ }
5517
+ /**
5518
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
5519
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
5520
+ * nothing and returns null when there is no legacy history or no such
5521
+ * event; each caller picks its own fallback.
5522
+ */
5523
+ anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
5524
+ return anchorAtLegacyBoundary(this.metadataRepo, this.eventRepo, entityId, checkpoint, total, db);
5525
+ }
5460
5526
  /**
5461
5527
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
5462
5528
  * checkpoint already covered. No-op when a watermark already exists or the
5463
5529
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
5464
- * offset `min(memory_checkpoint, totalEvents) - 1`.
5530
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
5531
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
5465
5532
  */
5466
5533
  async seedLibrarianWatermark(entityId) {
5467
- if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
5468
- const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
5469
- const memory = cp.memory ?? 0;
5470
- 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);
5534
+ await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, this.db);
5474
5535
  }
5475
5536
  /**
5476
5537
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -6084,8 +6145,21 @@ var MaintenanceService = class {
6084
6145
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6085
6146
  var IMPORT_TITLE_MAX = 500;
6086
6147
  var IMPORT_BODY_MAX = 8e3;
6148
+ var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
6149
+ function createdAtValue(v) {
6150
+ if (typeof v === "number") return v;
6151
+ if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
6152
+ return NaN;
6153
+ }
6154
+ function clampFutureCreatedAt(events, now, floor) {
6155
+ const future = events.map((e) => ({ e, at: createdAtValue(e.created_at) })).filter((x) => x.at > now).sort((x, y) => (x.at === y.at ? 0 : x.at < y.at ? -1 : 1) || (x.e.id < y.e.id ? -1 : x.e.id > y.e.id ? 1 : 0));
6156
+ if (future.length > 0 && floor + future.length > Number.MAX_SAFE_INTEGER) {
6157
+ throw new RangeError(`importDump: cannot re-date ${future.length} future-dated event(s): the floor (${floor}) is too close to Number.MAX_SAFE_INTEGER to keep them ordered.`);
6158
+ }
6159
+ return new Map(future.map((x, i) => [x.e, floor + 1 + i]));
6160
+ }
6087
6161
  var ImportExportService = class {
6088
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService) {
6162
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
6089
6163
  this.db = db;
6090
6164
  this.entryRepo = entryRepo;
6091
6165
  this.taskRepo = taskRepo;
@@ -6095,6 +6169,7 @@ var ImportExportService = class {
6095
6169
  this.searchService = searchService;
6096
6170
  this.jobManager = jobManager;
6097
6171
  this.embeddingService = embeddingService;
6172
+ this.options = options;
6098
6173
  }
6099
6174
  async exportDump(entityIds) {
6100
6175
  let ids;
@@ -6175,6 +6250,7 @@ var ImportExportService = class {
6175
6250
  const preservedBlobDims = /* @__PURE__ */ new Set();
6176
6251
  const softDeletedFactIds = [];
6177
6252
  const clippedTextByFactId = /* @__PURE__ */ new Map();
6253
+ let clampedEvents = 0;
6178
6254
  await this.db.withTransactionAsync(async (tx) => {
6179
6255
  if (!merge) {
6180
6256
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -6395,19 +6471,25 @@ var ImportExportService = class {
6395
6471
  updated_at: safeUpdatedAt
6396
6472
  });
6397
6473
  }
6474
+ const now = Date.now();
6475
+ const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
6476
+ const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
6477
+ const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
6398
6478
  for (const event of bundle.events) {
6399
- await this.eventRepo.addIgnoreDuplicate(
6479
+ const stamped = clampedAt.get(event);
6480
+ const inserted = await this.eventRepo.addIgnoreDuplicate(
6400
6481
  {
6401
6482
  id: event.id,
6402
6483
  entity_id: entityId,
6403
6484
  event_type: event.event_type,
6404
6485
  summary: event.summary,
6405
6486
  related_entry_id: event.related_entry_id ?? null,
6406
- created_at: event.created_at,
6487
+ created_at: stamped ?? event.created_at,
6407
6488
  occurred_at: event.occurred_at ?? null
6408
6489
  },
6409
6490
  tx
6410
6491
  );
6492
+ if (inserted && stamped !== void 0) clampedEvents++;
6411
6493
  }
6412
6494
  for (const edge of bundle.edges ?? []) {
6413
6495
  await this.edgeRepo.addIgnoreDuplicate(
@@ -6423,6 +6505,15 @@ var ImportExportService = class {
6423
6505
  );
6424
6506
  }
6425
6507
  });
6508
+ if (clampedEvents > 0) {
6509
+ emitDiagnostic(this.options, {
6510
+ code: "event_created_at_clamped",
6511
+ operation: "importDump",
6512
+ trigger: "call",
6513
+ entityId,
6514
+ detail: { count: clampedEvents }
6515
+ });
6516
+ }
6426
6517
  if (merge) {
6427
6518
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
6428
6519
  } else {
@@ -7633,16 +7724,30 @@ var WriteService = class {
7633
7724
  created_at: now,
7634
7725
  occurred_at: occurredAt
7635
7726
  };
7727
+ const stampCreatedAt = async (tx) => {
7728
+ const latest = await this.eventRepo.latestCreatedAt(entityId, tx);
7729
+ if (latest === null || latest < newEvent.created_at) return;
7730
+ if (latest >= Number.MAX_SAFE_INTEGER) {
7731
+ 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.`);
7732
+ }
7733
+ newEvent.created_at = latest + 1;
7734
+ };
7636
7735
  const deferred = resolveMaintenanceMode(this.options.config) === "deferred";
7637
7736
  if (deferred) {
7638
- await this.eventRepo.add(newEvent);
7737
+ await this.db.withTransactionAsync(async (tx) => {
7738
+ await stampCreatedAt(tx);
7739
+ await this.eventRepo.add(newEvent, tx);
7740
+ });
7639
7741
  return;
7640
7742
  }
7641
7743
  let shouldRunLibrarian = false;
7642
7744
  let librarianCount = 0;
7643
7745
  let prevMemoryCheckpoint = 0;
7644
7746
  let eventCount = 0;
7747
+ const isOps = resolveLibrarianStrategy(this.options.config) === "ops";
7748
+ const anchorOps = async (preCheckpoint, total, tx) => isOps ? this.maintenanceService.anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) : this.metadataRepo.getLibrarianWatermark(entityId, tx);
7645
7749
  await this.db.withTransactionAsync(async (tx) => {
7750
+ await stampCreatedAt(tx);
7646
7751
  await this.eventRepo.add(newEvent, tx);
7647
7752
  const threshold = this.options.config?.autoLibrarianThreshold || 20;
7648
7753
  const [count, cp] = await Promise.all([
@@ -7651,18 +7756,19 @@ var WriteService = class {
7651
7756
  ]);
7652
7757
  eventCount = count;
7653
7758
  let memoryCheckpoint = cp.memory ?? 0;
7654
- if (memoryCheckpoint > count) memoryCheckpoint = 0;
7759
+ if (memoryCheckpoint >= count) memoryCheckpoint = 0;
7655
7760
  if (count - memoryCheckpoint >= threshold) {
7656
7761
  if (!this.jobManager.isBlocked("librarian", entityId)) {
7657
7762
  shouldRunLibrarian = true;
7658
7763
  librarianCount = count;
7659
7764
  prevMemoryCheckpoint = memoryCheckpoint;
7765
+ if (isOps) await anchorOps(memoryCheckpoint, count, tx);
7660
7766
  await this.metadataRepo.updateCheckpoint(entityId, { memory: count }, tx);
7661
7767
  }
7662
7768
  } else {
7663
7769
  const tokenThreshold = this.options.config?.autoLibrarianTokenThreshold;
7664
7770
  if (typeof tokenThreshold === "number" && tokenThreshold > 0 && !this.jobManager.isBlocked("librarian", entityId)) {
7665
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
7771
+ const wm = await anchorOps(memoryCheckpoint, count, tx);
7666
7772
  const chars = await this.eventRepo.sumSummaryCharsAfter(entityId, wm, tx);
7667
7773
  if (Math.ceil(chars / 4) >= tokenThreshold) {
7668
7774
  shouldRunLibrarian = true;
@@ -7685,7 +7791,11 @@ var WriteService = class {
7685
7791
  this.track(job);
7686
7792
  } catch (e) {
7687
7793
  if (!(e instanceof WikiBusyError)) throw e;
7688
- await this.metadataRepo.updateCheckpoint(entityId, { memory: prevMemoryCheckpoint }, this.db);
7794
+ const added = librarianCount - prevMemoryCheckpoint;
7795
+ await this.db.withTransactionAsync(async (tx) => {
7796
+ const memory = (await this.metadataRepo.getCheckpoint(entityId, tx)).memory ?? 0;
7797
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: Math.max(0, memory - added) }, tx);
7798
+ });
7689
7799
  }
7690
7800
  } else if (!this.jobManager.isBlocked("librarian", entityId)) {
7691
7801
  const healJob = this.maybeRunHeal(entityId, eventCount).catch((err) => {
@@ -7720,7 +7830,8 @@ var WriteService = class {
7720
7830
  try {
7721
7831
  const result = await this.maintenanceService.doRunHeal(entityId, { trigger: "auto" });
7722
7832
  if (result.remaining === 0) {
7723
- await this.metadataRepo.updateCheckpoint(entityId, { heal: currentEventCount }, this.db);
7833
+ const live = await this.eventRepo.count(entityId, this.db);
7834
+ await this.metadataRepo.updateCheckpoint(entityId, { heal: Math.min(currentEventCount, live) }, this.db);
7724
7835
  }
7725
7836
  } finally {
7726
7837
  this.jobManager.releaseLock("heal", entityId);
@@ -7745,5 +7856,5 @@ var WriteService = class {
7745
7856
  };
7746
7857
 
7747
7858
  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
7859
+ //# sourceMappingURL=chunk-UJSUPVPH.mjs.map
7860
+ //# sourceMappingURL=chunk-UJSUPVPH.mjs.map