@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.
@@ -802,7 +802,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
802
802
  * Closed for this release series, but new codes are added in minor versions:
803
803
  * hosts must tolerate codes they do not recognize.
804
804
  */
805
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held';
805
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'event_created_at_clamped';
806
806
  /** The service run that emitted the diagnostic. */
807
807
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune';
808
808
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -3034,7 +3034,8 @@ declare class EventRepository extends BaseRepository {
3034
3034
  * Pass `tx` to participate in a caller-owned transaction; omit to run against the default db.
3035
3035
  */
3036
3036
  add(event: WikiEvent, tx?: SQLiteAdapter): Promise<void>;
3037
- addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<void>;
3037
+ /** Insert unless the id already exists. Returns true when a row was inserted. */
3038
+ addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<boolean>;
3038
3039
  /**
3039
3040
  * Return the most recent events for an entity, newest first.
3040
3041
  * Defaults to a limit of 50.
@@ -3471,7 +3472,8 @@ declare class ImportExportService {
3471
3472
  private searchService;
3472
3473
  private jobManager;
3473
3474
  private embeddingService;
3474
- constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService);
3475
+ private options;
3476
+ constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, options?: Pick<WikiOptions, 'onDiagnostic'>);
3475
3477
  exportDump(entityIds?: string[]): Promise<MemoryDump>;
3476
3478
  importDump(dump: MemoryDump, opts?: {
3477
3479
  merge?: boolean;
@@ -802,7 +802,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
802
802
  * Closed for this release series, but new codes are added in minor versions:
803
803
  * hosts must tolerate codes they do not recognize.
804
804
  */
805
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held';
805
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'event_created_at_clamped';
806
806
  /** The service run that emitted the diagnostic. */
807
807
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune';
808
808
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -3034,7 +3034,8 @@ declare class EventRepository extends BaseRepository {
3034
3034
  * Pass `tx` to participate in a caller-owned transaction; omit to run against the default db.
3035
3035
  */
3036
3036
  add(event: WikiEvent, tx?: SQLiteAdapter): Promise<void>;
3037
- addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<void>;
3037
+ /** Insert unless the id already exists. Returns true when a row was inserted. */
3038
+ addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<boolean>;
3038
3039
  /**
3039
3040
  * Return the most recent events for an entity, newest first.
3040
3041
  * Defaults to a limit of 50.
@@ -3471,7 +3472,8 @@ declare class ImportExportService {
3471
3472
  private searchService;
3472
3473
  private jobManager;
3473
3474
  private embeddingService;
3474
- constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService);
3475
+ private options;
3476
+ constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, options?: Pick<WikiOptions, 'onDiagnostic'>);
3475
3477
  exportDump(entityIds?: string[]): Promise<MemoryDump>;
3476
3478
  importDump(dump: MemoryDump, opts?: {
3477
3479
  merge?: boolean;
@@ -1,2 +1,2 @@
1
- export { aH as EmbeddingService, aI as ImportExportService, aJ as IngestionService, aK as JobManager, aK as JobManagerType, aL as MaintenanceService, aM as RetrievalService, aN as SearchService, aN as SearchServiceType, au as WikiMemoryTestAccess, aO as WriteService } from './testing-BPddGTkl.mjs';
1
+ export { aH as EmbeddingService, aI as ImportExportService, aJ as IngestionService, aK as JobManager, aK as JobManagerType, aL as MaintenanceService, aM as RetrievalService, aN as SearchService, aN as SearchServiceType, au as WikiMemoryTestAccess, aO as WriteService } from './testing-CG8Hw5Ph.mjs';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { aH as EmbeddingService, aI as ImportExportService, aJ as IngestionService, aK as JobManager, aK as JobManagerType, aL as MaintenanceService, aM as RetrievalService, aN as SearchService, aN as SearchServiceType, au as WikiMemoryTestAccess, aO as WriteService } from './testing-BPddGTkl.js';
1
+ export { aH as EmbeddingService, aI as ImportExportService, aJ as IngestionService, aK as JobManager, aK as JobManagerType, aL as MaintenanceService, aM as RetrievalService, aN as SearchService, aN as SearchServiceType, au as WikiMemoryTestAccess, aO as WriteService } from './testing-CG8Hw5Ph.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -712,7 +712,8 @@ var SEVERITY = {
712
712
  contradicts_document: "warn",
713
713
  resolve_failed: "warn",
714
714
  read_budget: "info",
715
- event_retention_held: "info"
715
+ event_retention_held: "info",
716
+ event_created_at_clamped: "warn"
716
717
  };
717
718
  var MESSAGE = {
718
719
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -734,7 +735,8 @@ var MESSAGE = {
734
735
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
735
736
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
736
737
  read_budget: "A read was packed to a token budget.",
737
- event_retention_held: "Event pruning was held back because the librarian has not processed those events yet."
738
+ event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
739
+ 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."
738
740
  };
739
741
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
740
742
  function copyDetail(detail) {
@@ -1065,11 +1067,48 @@ function entitySummaryMetaKey(entityId) {
1065
1067
  return `entity_summary:${entityId}`;
1066
1068
  }
1067
1069
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1070
+
1071
+ // src/services/legacyWatermark.ts
1072
+ async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
1073
+ if (checkpoint <= 0 || total <= 0) return null;
1074
+ const ev = await eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
1075
+ if (!ev) return null;
1076
+ const wm = { at: ev.created_at, id: ev.id };
1077
+ await metadataRepo.setLibrarianWatermark(entityId, wm, db);
1078
+ return wm;
1079
+ }
1080
+ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
1081
+ const existing = await metadataRepo.getLibrarianWatermark(entityId, db);
1082
+ if (existing) return existing;
1083
+ const memory = (await metadataRepo.getCheckpoint(entityId, db)).memory ?? 0;
1084
+ if (memory <= 0) return null;
1085
+ const total = await eventRepo.count(entityId, db);
1086
+ if (memory > total) {
1087
+ await metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, db);
1088
+ return START_OF_LOG_WATERMARK;
1089
+ }
1090
+ return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
1091
+ }
1092
+
1093
+ // src/services/ImportExportService.ts
1068
1094
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1069
1095
  var IMPORT_TITLE_MAX = 500;
1070
1096
  var IMPORT_BODY_MAX = 8e3;
1097
+ var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
1098
+ function createdAtValue(v) {
1099
+ if (typeof v === "number") return v;
1100
+ if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
1101
+ return NaN;
1102
+ }
1103
+ function clampFutureCreatedAt(events, now, floor) {
1104
+ 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));
1105
+ if (future.length > 0 && floor + future.length > Number.MAX_SAFE_INTEGER) {
1106
+ 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.`);
1107
+ }
1108
+ return new Map(future.map((x, i) => [x.e, floor + 1 + i]));
1109
+ }
1071
1110
  var ImportExportService = class {
1072
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService) {
1111
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
1073
1112
  this.db = db;
1074
1113
  this.entryRepo = entryRepo;
1075
1114
  this.taskRepo = taskRepo;
@@ -1079,6 +1118,7 @@ var ImportExportService = class {
1079
1118
  this.searchService = searchService;
1080
1119
  this.jobManager = jobManager;
1081
1120
  this.embeddingService = embeddingService;
1121
+ this.options = options;
1082
1122
  }
1083
1123
  async exportDump(entityIds) {
1084
1124
  let ids;
@@ -1159,6 +1199,7 @@ var ImportExportService = class {
1159
1199
  const preservedBlobDims = /* @__PURE__ */ new Set();
1160
1200
  const softDeletedFactIds = [];
1161
1201
  const clippedTextByFactId = /* @__PURE__ */ new Map();
1202
+ let clampedEvents = 0;
1162
1203
  await this.db.withTransactionAsync(async (tx) => {
1163
1204
  if (!merge) {
1164
1205
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -1379,19 +1420,25 @@ var ImportExportService = class {
1379
1420
  updated_at: safeUpdatedAt
1380
1421
  });
1381
1422
  }
1423
+ const now = Date.now();
1424
+ const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
1425
+ const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
1426
+ const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
1382
1427
  for (const event of bundle.events) {
1383
- await this.eventRepo.addIgnoreDuplicate(
1428
+ const stamped = clampedAt.get(event);
1429
+ const inserted = await this.eventRepo.addIgnoreDuplicate(
1384
1430
  {
1385
1431
  id: event.id,
1386
1432
  entity_id: entityId,
1387
1433
  event_type: event.event_type,
1388
1434
  summary: event.summary,
1389
1435
  related_entry_id: event.related_entry_id ?? null,
1390
- created_at: event.created_at,
1436
+ created_at: stamped ?? event.created_at,
1391
1437
  occurred_at: event.occurred_at ?? null
1392
1438
  },
1393
1439
  tx
1394
1440
  );
1441
+ if (inserted && stamped !== void 0) clampedEvents++;
1395
1442
  }
1396
1443
  for (const edge of bundle.edges ?? []) {
1397
1444
  await this.edgeRepo.addIgnoreDuplicate(
@@ -1407,6 +1454,15 @@ var ImportExportService = class {
1407
1454
  );
1408
1455
  }
1409
1456
  });
1457
+ if (clampedEvents > 0) {
1458
+ emitDiagnostic(this.options, {
1459
+ code: "event_created_at_clamped",
1460
+ operation: "importDump",
1461
+ trigger: "call",
1462
+ entityId,
1463
+ detail: { count: clampedEvents }
1464
+ });
1465
+ }
1410
1466
  if (merge) {
1411
1467
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
1412
1468
  } else {
@@ -4518,13 +4574,8 @@ var MaintenanceService = class {
4518
4574
  * nothing and returns null when there is no legacy history or no such
4519
4575
  * event; each caller picks its own fallback.
4520
4576
  */
4521
- async anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
4522
- if (checkpoint <= 0 || total <= 0) return null;
4523
- const ev = await this.eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
4524
- if (!ev) return null;
4525
- const wm = { at: ev.created_at, id: ev.id };
4526
- await this.metadataRepo.setLibrarianWatermark(entityId, wm, db);
4527
- return wm;
4577
+ anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
4578
+ return anchorAtLegacyBoundary(this.metadataRepo, this.eventRepo, entityId, checkpoint, total, db);
4528
4579
  }
4529
4580
  /**
4530
4581
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
@@ -4534,16 +4585,7 @@ var MaintenanceService = class {
4534
4585
  * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
4535
4586
  */
4536
4587
  async seedLibrarianWatermark(entityId) {
4537
- if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
4538
- const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
4539
- const memory = cp.memory ?? 0;
4540
- if (memory <= 0) return;
4541
- const total = await this.eventRepo.count(entityId, this.db);
4542
- if (memory > total) {
4543
- await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, this.db);
4544
- return;
4545
- }
4546
- await this.anchorAtLegacyBoundary(entityId, memory, total, this.db);
4588
+ await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, this.db);
4547
4589
  }
4548
4590
  /**
4549
4591
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.