@equationalapplications/core-llm-wiki 8.1.0 → 8.2.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.
@@ -2181,7 +2181,8 @@ var SEVERITY = {
2181
2181
  resolve_failed: "warn",
2182
2182
  read_budget: "info",
2183
2183
  event_retention_held: "info",
2184
- event_created_at_clamped: "warn"
2184
+ event_created_at_clamped: "warn",
2185
+ event_created_at_restamped: "info"
2185
2186
  };
2186
2187
  var MESSAGE = {
2187
2188
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2204,7 +2205,8 @@ var MESSAGE = {
2204
2205
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
2205
2206
  read_budget: "A read was packed to a token budget.",
2206
2207
  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."
2208
+ 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."
2208
2210
  };
2209
2211
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2210
2212
  function copyDetail(detail) {
@@ -6142,22 +6144,68 @@ var MaintenanceService = class {
6142
6144
  return sanitizeRankerError(err, this.options.sanitizeRankerErrors);
6143
6145
  }
6144
6146
  };
6145
- var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6146
- var IMPORT_TITLE_MAX = 500;
6147
- var IMPORT_BODY_MAX = 8e3;
6147
+
6148
+ // src/services/importEventStamps.ts
6149
+ var DATE_MAX = 864e13;
6148
6150
  var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
6149
6151
  function createdAtValue(v) {
6150
6152
  if (typeof v === "number") return v;
6151
6153
  if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
6152
6154
  return NaN;
6153
6155
  }
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]));
6156
+ function isUsableDate(v) {
6157
+ return Number.isFinite(v) && v >= -DATE_MAX && v <= DATE_MAX;
6158
+ }
6159
+ function parseSourceWatermark(raw) {
6160
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
6161
+ const { at, id } = raw;
6162
+ if (typeof at !== "number" || !Number.isFinite(at) || typeof id !== "string") return null;
6163
+ return { at, id };
6164
+ }
6165
+ var cmp = (a, b) => a === b ? 0 : a < b ? -1 : 1;
6166
+ function planEventStamps(events, ctx) {
6167
+ const { now, floor, merge, localWm, sourceWm } = ctx;
6168
+ const after = (v, id, wm) => v > wm.at || v === wm.at && id > wm.id;
6169
+ const plan = /* @__PURE__ */ new Map();
6170
+ const restamp = [];
6171
+ for (const e of events) {
6172
+ const v = createdAtValue(e.created_at);
6173
+ const o = createdAtValue(e.occurred_at);
6174
+ let occurredAt = null;
6175
+ let occurredInvalid = false;
6176
+ if (e.occurred_at != null) {
6177
+ if (isUsableDate(o)) occurredAt = Math.trunc(o);
6178
+ else occurredInvalid = true;
6179
+ }
6180
+ let reason = null;
6181
+ const invalidCreated = Number.isNaN(v) || v < -DATE_MAX;
6182
+ if (invalidCreated) reason = "invalid";
6183
+ else if (v > now) reason = "future";
6184
+ else if (merge && localWm !== null && Number.isFinite(localWm.at) && !after(v, e.id, localWm) && (sourceWm === null || after(v, e.id, sourceWm))) {
6185
+ reason = "behind_watermark";
6186
+ }
6187
+ if (reason === "behind_watermark" && occurredAt === null && Number.isFinite(v) && v >= 0) {
6188
+ occurredAt = Math.trunc(v);
6189
+ }
6190
+ const stamp = { createdAt: v, occurredAt, reason };
6191
+ if (reason === null && occurredInvalid) stamp.reason = "invalid";
6192
+ plan.set(e, stamp);
6193
+ if (reason !== null) restamp.push({ e, key: invalidCreated ? -Infinity : v, stamp });
6194
+ }
6195
+ restamp.sort((x, y) => cmp(x.key, y.key) || cmp(x.e.id, y.e.id));
6196
+ if (restamp.length > 0 && floor + restamp.length > Number.MAX_SAFE_INTEGER) {
6197
+ throw new RangeError(`importDump: cannot re-date ${restamp.length} event(s): the floor (${floor}) is too close to Number.MAX_SAFE_INTEGER to keep them ordered.`);
6198
+ }
6199
+ restamp.forEach((x, i) => {
6200
+ x.stamp.createdAt = floor + 1 + i;
6201
+ });
6202
+ return plan;
6160
6203
  }
6204
+
6205
+ // src/services/ImportExportService.ts
6206
+ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6207
+ var IMPORT_TITLE_MAX = 500;
6208
+ var IMPORT_BODY_MAX = 8e3;
6161
6209
  var ImportExportService = class {
6162
6210
  constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
6163
6211
  this.db = db;
@@ -6210,6 +6258,7 @@ var ImportExportService = class {
6210
6258
  }
6211
6259
  }
6212
6260
  async getFullBundle(entityId, opts) {
6261
+ const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
6213
6262
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
6214
6263
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
6215
6264
  this.taskRepo.findAllByEntityId(entityId),
@@ -6239,7 +6288,8 @@ var ImportExportService = class {
6239
6288
  tasks,
6240
6289
  events,
6241
6290
  edges,
6242
- ...summaryValue != null ? { summary: summaryValue } : {}
6291
+ ...summaryValue != null ? { summary: summaryValue } : {},
6292
+ ...wm ? { librarian_watermark: wm } : {}
6243
6293
  };
6244
6294
  }
6245
6295
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
@@ -6251,6 +6301,7 @@ var ImportExportService = class {
6251
6301
  const softDeletedFactIds = [];
6252
6302
  const clippedTextByFactId = /* @__PURE__ */ new Map();
6253
6303
  let clampedEvents = 0;
6304
+ const restamped = { behind_watermark: 0, invalid: 0 };
6254
6305
  await this.db.withTransactionAsync(async (tx) => {
6255
6306
  if (!merge) {
6256
6307
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -6474,9 +6525,9 @@ var ImportExportService = class {
6474
6525
  const now = Date.now();
6475
6526
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
6476
6527
  const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
6477
- const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
6528
+ const planned = planEventStamps(bundle.events, { now, floor, merge, localWm: wm, sourceWm: parseSourceWatermark(bundle.librarian_watermark) });
6478
6529
  for (const event of bundle.events) {
6479
- const stamped = clampedAt.get(event);
6530
+ const stamp = planned.get(event);
6480
6531
  const inserted = await this.eventRepo.addIgnoreDuplicate(
6481
6532
  {
6482
6533
  id: event.id,
@@ -6484,12 +6535,14 @@ var ImportExportService = class {
6484
6535
  event_type: event.event_type,
6485
6536
  summary: event.summary,
6486
6537
  related_entry_id: event.related_entry_id ?? null,
6487
- created_at: stamped ?? event.created_at,
6488
- occurred_at: event.occurred_at ?? null
6538
+ created_at: stamp.createdAt,
6539
+ occurred_at: stamp.occurredAt
6489
6540
  },
6490
6541
  tx
6491
6542
  );
6492
- if (inserted && stamped !== void 0) clampedEvents++;
6543
+ if (!inserted || stamp.reason === null) continue;
6544
+ if (stamp.reason === "future") clampedEvents++;
6545
+ else restamped[stamp.reason]++;
6493
6546
  }
6494
6547
  for (const edge of bundle.edges ?? []) {
6495
6548
  await this.edgeRepo.addIgnoreDuplicate(
@@ -6514,6 +6567,17 @@ var ImportExportService = class {
6514
6567
  detail: { count: clampedEvents }
6515
6568
  });
6516
6569
  }
6570
+ for (const reason of ["behind_watermark", "invalid"]) {
6571
+ if (restamped[reason] > 0) {
6572
+ emitDiagnostic(this.options, {
6573
+ code: "event_created_at_restamped",
6574
+ operation: "importDump",
6575
+ trigger: "call",
6576
+ entityId,
6577
+ detail: { count: restamped[reason], reason }
6578
+ });
6579
+ }
6580
+ }
6517
6581
  if (merge) {
6518
6582
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
6519
6583
  } else {
@@ -7290,7 +7354,7 @@ var RetrievalService = class {
7290
7354
  if (topK.length < maxBackfill) {
7291
7355
  let insertIdx = topK.length;
7292
7356
  for (let i = 0; i < topK.length; i++) {
7293
- const cmp = this._compareScoredRows(
7357
+ const cmp2 = this._compareScoredRows(
7294
7358
  {
7295
7359
  id: candidate.row.id,
7296
7360
  score: candidate.kwScore,
@@ -7304,7 +7368,7 @@ var RetrievalService = class {
7304
7368
  access_count: topK[i].row.access_count
7305
7369
  }
7306
7370
  );
7307
- if (cmp < 0) {
7371
+ if (cmp2 < 0) {
7308
7372
  insertIdx = i;
7309
7373
  break;
7310
7374
  }
@@ -7328,7 +7392,7 @@ var RetrievalService = class {
7328
7392
  if (cmpWorst < 0) {
7329
7393
  let insertIdx = maxBackfill - 1;
7330
7394
  for (let i = 0; i < topK.length; i++) {
7331
- const cmp = this._compareScoredRows(
7395
+ const cmp2 = this._compareScoredRows(
7332
7396
  {
7333
7397
  id: candidate.row.id,
7334
7398
  score: candidate.kwScore,
@@ -7342,7 +7406,7 @@ var RetrievalService = class {
7342
7406
  access_count: topK[i].row.access_count
7343
7407
  }
7344
7408
  );
7345
- if (cmp < 0) {
7409
+ if (cmp2 < 0) {
7346
7410
  insertIdx = i;
7347
7411
  break;
7348
7412
  }
@@ -7855,6 +7919,6 @@ var WriteService = class {
7855
7919
  }
7856
7920
  };
7857
7921
 
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 };
7859
- //# sourceMappingURL=chunk-UJSUPVPH.mjs.map
7860
- //# sourceMappingURL=chunk-UJSUPVPH.mjs.map
7922
+ 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, 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 };
7923
+ //# sourceMappingURL=chunk-FOX6TNFO.mjs.map
7924
+ //# sourceMappingURL=chunk-FOX6TNFO.mjs.map