@equationalapplications/core-llm-wiki 8.0.5 → 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.
@@ -2180,7 +2180,9 @@ 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",
2185
+ event_created_at_restamped: "info"
2184
2186
  };
2185
2187
  var MESSAGE = {
2186
2188
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2202,7 +2204,9 @@ var MESSAGE = {
2202
2204
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
2203
2205
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
2204
2206
  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."
2207
+ event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
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."
2206
2210
  };
2207
2211
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2208
2212
  function copyDetail(detail) {
@@ -3308,6 +3312,28 @@ var MetadataRepository = class extends BaseRepository {
3308
3312
  }
3309
3313
  };
3310
3314
 
3315
+ // src/services/legacyWatermark.ts
3316
+ async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
3317
+ if (checkpoint <= 0 || total <= 0) return null;
3318
+ const ev = await eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
3319
+ if (!ev) return null;
3320
+ const wm = { at: ev.created_at, id: ev.id };
3321
+ await metadataRepo.setLibrarianWatermark(entityId, wm, db);
3322
+ return wm;
3323
+ }
3324
+ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
3325
+ const existing = await metadataRepo.getLibrarianWatermark(entityId, db);
3326
+ if (existing) return existing;
3327
+ const memory = (await metadataRepo.getCheckpoint(entityId, db)).memory ?? 0;
3328
+ if (memory <= 0) return null;
3329
+ const total = await eventRepo.count(entityId, db);
3330
+ if (memory > total) {
3331
+ await metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, db);
3332
+ return START_OF_LOG_WATERMARK;
3333
+ }
3334
+ return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
3335
+ }
3336
+
3311
3337
  // src/services/BoundedLlmCall.ts
3312
3338
  var DEFAULT_BATCH_SIZE = 10;
3313
3339
  var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
@@ -5496,13 +5522,8 @@ var MaintenanceService = class {
5496
5522
  * nothing and returns null when there is no legacy history or no such
5497
5523
  * event; each caller picks its own fallback.
5498
5524
  */
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;
5525
+ anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
5526
+ return anchorAtLegacyBoundary(this.metadataRepo, this.eventRepo, entityId, checkpoint, total, db);
5506
5527
  }
5507
5528
  /**
5508
5529
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
@@ -5512,16 +5533,7 @@ var MaintenanceService = class {
5512
5533
  * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
5513
5534
  */
5514
5535
  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);
5536
+ await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, this.db);
5525
5537
  }
5526
5538
  /**
5527
5539
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -6132,11 +6144,70 @@ var MaintenanceService = class {
6132
6144
  return sanitizeRankerError(err, this.options.sanitizeRankerErrors);
6133
6145
  }
6134
6146
  };
6147
+
6148
+ // src/services/importEventStamps.ts
6149
+ var DATE_MAX = 864e13;
6150
+ var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
6151
+ function createdAtValue(v) {
6152
+ if (typeof v === "number") return v;
6153
+ if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
6154
+ return NaN;
6155
+ }
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;
6203
+ }
6204
+
6205
+ // src/services/ImportExportService.ts
6135
6206
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6136
6207
  var IMPORT_TITLE_MAX = 500;
6137
6208
  var IMPORT_BODY_MAX = 8e3;
6138
6209
  var ImportExportService = class {
6139
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService) {
6210
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
6140
6211
  this.db = db;
6141
6212
  this.entryRepo = entryRepo;
6142
6213
  this.taskRepo = taskRepo;
@@ -6146,6 +6217,7 @@ var ImportExportService = class {
6146
6217
  this.searchService = searchService;
6147
6218
  this.jobManager = jobManager;
6148
6219
  this.embeddingService = embeddingService;
6220
+ this.options = options;
6149
6221
  }
6150
6222
  async exportDump(entityIds) {
6151
6223
  let ids;
@@ -6186,6 +6258,7 @@ var ImportExportService = class {
6186
6258
  }
6187
6259
  }
6188
6260
  async getFullBundle(entityId, opts) {
6261
+ const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
6189
6262
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
6190
6263
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
6191
6264
  this.taskRepo.findAllByEntityId(entityId),
@@ -6215,7 +6288,8 @@ var ImportExportService = class {
6215
6288
  tasks,
6216
6289
  events,
6217
6290
  edges,
6218
- ...summaryValue != null ? { summary: summaryValue } : {}
6291
+ ...summaryValue != null ? { summary: summaryValue } : {},
6292
+ ...wm ? { librarian_watermark: wm } : {}
6219
6293
  };
6220
6294
  }
6221
6295
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
@@ -6226,6 +6300,8 @@ var ImportExportService = class {
6226
6300
  const preservedBlobDims = /* @__PURE__ */ new Set();
6227
6301
  const softDeletedFactIds = [];
6228
6302
  const clippedTextByFactId = /* @__PURE__ */ new Map();
6303
+ let clampedEvents = 0;
6304
+ const restamped = { behind_watermark: 0, invalid: 0 };
6229
6305
  await this.db.withTransactionAsync(async (tx) => {
6230
6306
  if (!merge) {
6231
6307
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -6446,19 +6522,27 @@ var ImportExportService = class {
6446
6522
  updated_at: safeUpdatedAt
6447
6523
  });
6448
6524
  }
6525
+ const now = Date.now();
6526
+ const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
6527
+ const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
6528
+ const planned = planEventStamps(bundle.events, { now, floor, merge, localWm: wm, sourceWm: parseSourceWatermark(bundle.librarian_watermark) });
6449
6529
  for (const event of bundle.events) {
6450
- await this.eventRepo.addIgnoreDuplicate(
6530
+ const stamp = planned.get(event);
6531
+ const inserted = await this.eventRepo.addIgnoreDuplicate(
6451
6532
  {
6452
6533
  id: event.id,
6453
6534
  entity_id: entityId,
6454
6535
  event_type: event.event_type,
6455
6536
  summary: event.summary,
6456
6537
  related_entry_id: event.related_entry_id ?? null,
6457
- created_at: event.created_at,
6458
- occurred_at: event.occurred_at ?? null
6538
+ created_at: stamp.createdAt,
6539
+ occurred_at: stamp.occurredAt
6459
6540
  },
6460
6541
  tx
6461
6542
  );
6543
+ if (!inserted || stamp.reason === null) continue;
6544
+ if (stamp.reason === "future") clampedEvents++;
6545
+ else restamped[stamp.reason]++;
6462
6546
  }
6463
6547
  for (const edge of bundle.edges ?? []) {
6464
6548
  await this.edgeRepo.addIgnoreDuplicate(
@@ -6474,6 +6558,26 @@ var ImportExportService = class {
6474
6558
  );
6475
6559
  }
6476
6560
  });
6561
+ if (clampedEvents > 0) {
6562
+ emitDiagnostic(this.options, {
6563
+ code: "event_created_at_clamped",
6564
+ operation: "importDump",
6565
+ trigger: "call",
6566
+ entityId,
6567
+ detail: { count: clampedEvents }
6568
+ });
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
+ }
6477
6581
  if (merge) {
6478
6582
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
6479
6583
  } else {
@@ -7250,7 +7354,7 @@ var RetrievalService = class {
7250
7354
  if (topK.length < maxBackfill) {
7251
7355
  let insertIdx = topK.length;
7252
7356
  for (let i = 0; i < topK.length; i++) {
7253
- const cmp = this._compareScoredRows(
7357
+ const cmp2 = this._compareScoredRows(
7254
7358
  {
7255
7359
  id: candidate.row.id,
7256
7360
  score: candidate.kwScore,
@@ -7264,7 +7368,7 @@ var RetrievalService = class {
7264
7368
  access_count: topK[i].row.access_count
7265
7369
  }
7266
7370
  );
7267
- if (cmp < 0) {
7371
+ if (cmp2 < 0) {
7268
7372
  insertIdx = i;
7269
7373
  break;
7270
7374
  }
@@ -7288,7 +7392,7 @@ var RetrievalService = class {
7288
7392
  if (cmpWorst < 0) {
7289
7393
  let insertIdx = maxBackfill - 1;
7290
7394
  for (let i = 0; i < topK.length; i++) {
7291
- const cmp = this._compareScoredRows(
7395
+ const cmp2 = this._compareScoredRows(
7292
7396
  {
7293
7397
  id: candidate.row.id,
7294
7398
  score: candidate.kwScore,
@@ -7302,7 +7406,7 @@ var RetrievalService = class {
7302
7406
  access_count: topK[i].row.access_count
7303
7407
  }
7304
7408
  );
7305
- if (cmp < 0) {
7409
+ if (cmp2 < 0) {
7306
7410
  insertIdx = i;
7307
7411
  break;
7308
7412
  }
@@ -7815,6 +7919,6 @@ var WriteService = class {
7815
7919
  }
7816
7920
  };
7817
7921
 
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 };
7819
- //# sourceMappingURL=chunk-GYF5QLYK.mjs.map
7820
- //# sourceMappingURL=chunk-GYF5QLYK.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