@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.
@@ -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' | 'event_created_at_clamped';
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' | 'event_created_at_restamped';
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. */
@@ -937,6 +937,14 @@ interface MemoryBundle {
937
937
  edges?: WikiEdge[];
938
938
  /** Entity summary prose for OKF profile ≥ 1 round-trip. Omitted = no summary (Clanker default). */
939
939
  summary?: string;
940
+ /**
941
+ * The source store's librarian position. Set by export only; the importer
942
+ * trusts events at or before it as consolidated at the source.
943
+ */
944
+ librarian_watermark?: {
945
+ at: number;
946
+ id: string;
947
+ };
940
948
  factScores?: Record<string, number>;
941
949
  metadata?: {
942
950
  query: string;
@@ -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' | 'event_created_at_clamped';
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' | 'event_created_at_restamped';
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. */
@@ -937,6 +937,14 @@ interface MemoryBundle {
937
937
  edges?: WikiEdge[];
938
938
  /** Entity summary prose for OKF profile ≥ 1 round-trip. Omitted = no summary (Clanker default). */
939
939
  summary?: string;
940
+ /**
941
+ * The source store's librarian position. Set by export only; the importer
942
+ * trusts events at or before it as consolidated at the source.
943
+ */
944
+ librarian_watermark?: {
945
+ at: number;
946
+ id: string;
947
+ };
940
948
  factScores?: Record<string, number>;
941
949
  metadata?: {
942
950
  query: string;
@@ -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-CG8Hw5Ph.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-D6So3dKX.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-CG8Hw5Ph.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-D6So3dKX.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -713,7 +713,8 @@ var SEVERITY = {
713
713
  resolve_failed: "warn",
714
714
  read_budget: "info",
715
715
  event_retention_held: "info",
716
- event_created_at_clamped: "warn"
716
+ event_created_at_clamped: "warn",
717
+ event_created_at_restamped: "info"
717
718
  };
718
719
  var MESSAGE = {
719
720
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -736,7 +737,8 @@ var MESSAGE = {
736
737
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
737
738
  read_budget: "A read was packed to a token budget.",
738
739
  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."
740
+ 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.",
741
+ 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."
740
742
  };
741
743
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
742
744
  function copyDetail(detail) {
@@ -1090,23 +1092,67 @@ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
1090
1092
  return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
1091
1093
  }
1092
1094
 
1093
- // src/services/ImportExportService.ts
1094
- var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1095
- var IMPORT_TITLE_MAX = 500;
1096
- var IMPORT_BODY_MAX = 8e3;
1095
+ // src/services/importEventStamps.ts
1096
+ var DATE_MAX = 864e13;
1097
1097
  var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
1098
1098
  function createdAtValue(v) {
1099
1099
  if (typeof v === "number") return v;
1100
1100
  if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
1101
1101
  return NaN;
1102
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]));
1103
+ function isUsableDate(v) {
1104
+ return Number.isFinite(v) && v >= -DATE_MAX && v <= DATE_MAX;
1109
1105
  }
1106
+ function parseSourceWatermark(raw) {
1107
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
1108
+ const { at, id } = raw;
1109
+ if (typeof at !== "number" || !Number.isFinite(at) || typeof id !== "string") return null;
1110
+ return { at, id };
1111
+ }
1112
+ var cmp = (a, b) => a === b ? 0 : a < b ? -1 : 1;
1113
+ function planEventStamps(events, ctx) {
1114
+ const { now, floor, merge, localWm, sourceWm } = ctx;
1115
+ const after = (v, id, wm) => v > wm.at || v === wm.at && id > wm.id;
1116
+ const plan = /* @__PURE__ */ new Map();
1117
+ const restamp = [];
1118
+ for (const e of events) {
1119
+ const v = createdAtValue(e.created_at);
1120
+ const o = createdAtValue(e.occurred_at);
1121
+ let occurredAt = null;
1122
+ let occurredInvalid = false;
1123
+ if (e.occurred_at != null) {
1124
+ if (isUsableDate(o)) occurredAt = Math.trunc(o);
1125
+ else occurredInvalid = true;
1126
+ }
1127
+ let reason = null;
1128
+ const invalidCreated = Number.isNaN(v) || v < -DATE_MAX;
1129
+ if (invalidCreated) reason = "invalid";
1130
+ else if (v > now) reason = "future";
1131
+ else if (merge && localWm !== null && Number.isFinite(localWm.at) && !after(v, e.id, localWm) && (sourceWm === null || after(v, e.id, sourceWm))) {
1132
+ reason = "behind_watermark";
1133
+ }
1134
+ if (reason === "behind_watermark" && occurredAt === null && Number.isFinite(v) && v >= 0) {
1135
+ occurredAt = Math.trunc(v);
1136
+ }
1137
+ const stamp = { createdAt: v, occurredAt, reason };
1138
+ if (reason === null && occurredInvalid) stamp.reason = "invalid";
1139
+ plan.set(e, stamp);
1140
+ if (reason !== null) restamp.push({ e, key: invalidCreated ? -Infinity : v, stamp });
1141
+ }
1142
+ restamp.sort((x, y) => cmp(x.key, y.key) || cmp(x.e.id, y.e.id));
1143
+ if (restamp.length > 0 && floor + restamp.length > Number.MAX_SAFE_INTEGER) {
1144
+ 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.`);
1145
+ }
1146
+ restamp.forEach((x, i) => {
1147
+ x.stamp.createdAt = floor + 1 + i;
1148
+ });
1149
+ return plan;
1150
+ }
1151
+
1152
+ // src/services/ImportExportService.ts
1153
+ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1154
+ var IMPORT_TITLE_MAX = 500;
1155
+ var IMPORT_BODY_MAX = 8e3;
1110
1156
  var ImportExportService = class {
1111
1157
  constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
1112
1158
  this.db = db;
@@ -1159,6 +1205,7 @@ var ImportExportService = class {
1159
1205
  }
1160
1206
  }
1161
1207
  async getFullBundle(entityId, opts) {
1208
+ const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
1162
1209
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
1163
1210
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
1164
1211
  this.taskRepo.findAllByEntityId(entityId),
@@ -1188,7 +1235,8 @@ var ImportExportService = class {
1188
1235
  tasks,
1189
1236
  events,
1190
1237
  edges,
1191
- ...summaryValue != null ? { summary: summaryValue } : {}
1238
+ ...summaryValue != null ? { summary: summaryValue } : {},
1239
+ ...wm ? { librarian_watermark: wm } : {}
1192
1240
  };
1193
1241
  }
1194
1242
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
@@ -1200,6 +1248,7 @@ var ImportExportService = class {
1200
1248
  const softDeletedFactIds = [];
1201
1249
  const clippedTextByFactId = /* @__PURE__ */ new Map();
1202
1250
  let clampedEvents = 0;
1251
+ const restamped = { behind_watermark: 0, invalid: 0 };
1203
1252
  await this.db.withTransactionAsync(async (tx) => {
1204
1253
  if (!merge) {
1205
1254
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -1423,9 +1472,9 @@ var ImportExportService = class {
1423
1472
  const now = Date.now();
1424
1473
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
1425
1474
  const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
1426
- const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
1475
+ const planned = planEventStamps(bundle.events, { now, floor, merge, localWm: wm, sourceWm: parseSourceWatermark(bundle.librarian_watermark) });
1427
1476
  for (const event of bundle.events) {
1428
- const stamped = clampedAt.get(event);
1477
+ const stamp = planned.get(event);
1429
1478
  const inserted = await this.eventRepo.addIgnoreDuplicate(
1430
1479
  {
1431
1480
  id: event.id,
@@ -1433,12 +1482,14 @@ var ImportExportService = class {
1433
1482
  event_type: event.event_type,
1434
1483
  summary: event.summary,
1435
1484
  related_entry_id: event.related_entry_id ?? null,
1436
- created_at: stamped ?? event.created_at,
1437
- occurred_at: event.occurred_at ?? null
1485
+ created_at: stamp.createdAt,
1486
+ occurred_at: stamp.occurredAt
1438
1487
  },
1439
1488
  tx
1440
1489
  );
1441
- if (inserted && stamped !== void 0) clampedEvents++;
1490
+ if (!inserted || stamp.reason === null) continue;
1491
+ if (stamp.reason === "future") clampedEvents++;
1492
+ else restamped[stamp.reason]++;
1442
1493
  }
1443
1494
  for (const edge of bundle.edges ?? []) {
1444
1495
  await this.edgeRepo.addIgnoreDuplicate(
@@ -1463,6 +1514,17 @@ var ImportExportService = class {
1463
1514
  detail: { count: clampedEvents }
1464
1515
  });
1465
1516
  }
1517
+ for (const reason of ["behind_watermark", "invalid"]) {
1518
+ if (restamped[reason] > 0) {
1519
+ emitDiagnostic(this.options, {
1520
+ code: "event_created_at_restamped",
1521
+ operation: "importDump",
1522
+ trigger: "call",
1523
+ entityId,
1524
+ detail: { count: restamped[reason], reason }
1525
+ });
1526
+ }
1527
+ }
1466
1528
  if (merge) {
1467
1529
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
1468
1530
  } else {
@@ -5585,7 +5647,7 @@ var RetrievalService = class {
5585
5647
  if (topK.length < maxBackfill) {
5586
5648
  let insertIdx = topK.length;
5587
5649
  for (let i = 0; i < topK.length; i++) {
5588
- const cmp = this._compareScoredRows(
5650
+ const cmp2 = this._compareScoredRows(
5589
5651
  {
5590
5652
  id: candidate.row.id,
5591
5653
  score: candidate.kwScore,
@@ -5599,7 +5661,7 @@ var RetrievalService = class {
5599
5661
  access_count: topK[i].row.access_count
5600
5662
  }
5601
5663
  );
5602
- if (cmp < 0) {
5664
+ if (cmp2 < 0) {
5603
5665
  insertIdx = i;
5604
5666
  break;
5605
5667
  }
@@ -5623,7 +5685,7 @@ var RetrievalService = class {
5623
5685
  if (cmpWorst < 0) {
5624
5686
  let insertIdx = maxBackfill - 1;
5625
5687
  for (let i = 0; i < topK.length; i++) {
5626
- const cmp = this._compareScoredRows(
5688
+ const cmp2 = this._compareScoredRows(
5627
5689
  {
5628
5690
  id: candidate.row.id,
5629
5691
  score: candidate.kwScore,
@@ -5637,7 +5699,7 @@ var RetrievalService = class {
5637
5699
  access_count: topK[i].row.access_count
5638
5700
  }
5639
5701
  );
5640
- if (cmp < 0) {
5702
+ if (cmp2 < 0) {
5641
5703
  insertIdx = i;
5642
5704
  break;
5643
5705
  }