@equationalapplications/core-llm-wiki 8.0.5 → 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) {
@@ -3308,6 +3310,28 @@ var MetadataRepository = class extends BaseRepository {
3308
3310
  }
3309
3311
  };
3310
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
+
3311
3335
  // src/services/BoundedLlmCall.ts
3312
3336
  var DEFAULT_BATCH_SIZE = 10;
3313
3337
  var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
@@ -5496,13 +5520,8 @@ var MaintenanceService = class {
5496
5520
  * nothing and returns null when there is no legacy history or no such
5497
5521
  * event; each caller picks its own fallback.
5498
5522
  */
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;
5523
+ anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
5524
+ return anchorAtLegacyBoundary(this.metadataRepo, this.eventRepo, entityId, checkpoint, total, db);
5506
5525
  }
5507
5526
  /**
5508
5527
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
@@ -5512,16 +5531,7 @@ var MaintenanceService = class {
5512
5531
  * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
5513
5532
  */
5514
5533
  async seedLibrarianWatermark(entityId) {
5515
- if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
5516
- const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
5517
- const memory = cp.memory ?? 0;
5518
- if (memory <= 0) return;
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);
5534
+ await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, this.db);
5525
5535
  }
5526
5536
  /**
5527
5537
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -6135,8 +6145,21 @@ var MaintenanceService = class {
6135
6145
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6136
6146
  var IMPORT_TITLE_MAX = 500;
6137
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
+ }
6138
6161
  var ImportExportService = class {
6139
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService) {
6162
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
6140
6163
  this.db = db;
6141
6164
  this.entryRepo = entryRepo;
6142
6165
  this.taskRepo = taskRepo;
@@ -6146,6 +6169,7 @@ var ImportExportService = class {
6146
6169
  this.searchService = searchService;
6147
6170
  this.jobManager = jobManager;
6148
6171
  this.embeddingService = embeddingService;
6172
+ this.options = options;
6149
6173
  }
6150
6174
  async exportDump(entityIds) {
6151
6175
  let ids;
@@ -6226,6 +6250,7 @@ var ImportExportService = class {
6226
6250
  const preservedBlobDims = /* @__PURE__ */ new Set();
6227
6251
  const softDeletedFactIds = [];
6228
6252
  const clippedTextByFactId = /* @__PURE__ */ new Map();
6253
+ let clampedEvents = 0;
6229
6254
  await this.db.withTransactionAsync(async (tx) => {
6230
6255
  if (!merge) {
6231
6256
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -6446,19 +6471,25 @@ var ImportExportService = class {
6446
6471
  updated_at: safeUpdatedAt
6447
6472
  });
6448
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);
6449
6478
  for (const event of bundle.events) {
6450
- await this.eventRepo.addIgnoreDuplicate(
6479
+ const stamped = clampedAt.get(event);
6480
+ const inserted = await this.eventRepo.addIgnoreDuplicate(
6451
6481
  {
6452
6482
  id: event.id,
6453
6483
  entity_id: entityId,
6454
6484
  event_type: event.event_type,
6455
6485
  summary: event.summary,
6456
6486
  related_entry_id: event.related_entry_id ?? null,
6457
- created_at: event.created_at,
6487
+ created_at: stamped ?? event.created_at,
6458
6488
  occurred_at: event.occurred_at ?? null
6459
6489
  },
6460
6490
  tx
6461
6491
  );
6492
+ if (inserted && stamped !== void 0) clampedEvents++;
6462
6493
  }
6463
6494
  for (const edge of bundle.edges ?? []) {
6464
6495
  await this.edgeRepo.addIgnoreDuplicate(
@@ -6474,6 +6505,15 @@ var ImportExportService = class {
6474
6505
  );
6475
6506
  }
6476
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
+ }
6477
6517
  if (merge) {
6478
6518
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
6479
6519
  } else {
@@ -7816,5 +7856,5 @@ var WriteService = class {
7816
7856
  };
7817
7857
 
7818
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 };
7819
- //# sourceMappingURL=chunk-GYF5QLYK.mjs.map
7820
- //# sourceMappingURL=chunk-GYF5QLYK.mjs.map
7859
+ //# sourceMappingURL=chunk-UJSUPVPH.mjs.map
7860
+ //# sourceMappingURL=chunk-UJSUPVPH.mjs.map