@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.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-BPddGTkl.mjs';
2
- export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as GraphTraversalOptions, r as GroundingConfig, H as HEAL_BATCH_SIZE, s as HEAL_RECHECK_MS, t as HOOK_TIMEOUT_MARKER, u as HealResult, I as IngestDocumentResult, L as LLMProvider, v as LibrarianConfig, w as LibrarianGateConfig, x as MaintenanceJob, y as MaintenanceStopReason, z as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, A as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, B as ONTOLOGY_BACKFILL_RECHECK_MS, J as OntologyBackfillResult, K as OntologyConfig, N as OntologyEdgeType, P as OntologyManifest, Q as OntologyMode, T as OntologyNodeType, U as OntologyPromptContext, V as OntologyUpdates, X as PendingMaintenance, Y as PendingMigrationWork, Z as PendingSourceStatus, _ as PromptOverrides, $ as PromptService, a0 as PrunePartialFailureError, a1 as ReembedResult, a2 as RememberInput, a3 as RunPendingMaintenanceOptions, a4 as RunPendingMaintenanceResult, a5 as SupersedeReplacement, a6 as VectorRanker, a7 as VectorRankerFallback, a8 as VectorRankerRankArgs, a9 as VectorRankerSemanticResult, aa as WikiBusyError, ab as WikiBusyOperation, ac as WikiCheckpoint, ad as WikiConfig, ae as WikiDiagnostic, af as WikiDiagnosticCode, ag as WikiDiagnosticDetail, ah as WikiDiagnosticOperation, ai as WikiDiagnosticSeverity, aj as WikiDiagnosticTrigger, ak as WikiDraftNotFound, al as WikiDuplicateHashError, am as WikiEdge, an as WikiEvent, ao as WikiFact, ap as WikiGraphNodeOwnershipConflict, aq as WikiIngestEmptyError, ar as WikiInstructions, as as WikiInvalidReadOptions, at as WikiLintReport, au as WikiMemoryTestAccess, av as WikiMigrationRequiredError, aw as WikiOutboxEvent, ax as WikiParseError, ay as WikiSearchUnavailableError, az as WikiSourceRefHashCollision, aA as WikiStrictOntologyViolation, aB as WikiSupersedeError, aC as WikiSupersedeReason, aD as WikiTask, aE as WikiTransactionError, aF as isWikiSearchUnavailableError, aG as validateManifest } from './testing-BPddGTkl.mjs';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-D6So3dKX.mjs';
2
+ export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as GraphTraversalOptions, r as GroundingConfig, H as HEAL_BATCH_SIZE, s as HEAL_RECHECK_MS, t as HOOK_TIMEOUT_MARKER, u as HealResult, I as IngestDocumentResult, L as LLMProvider, v as LibrarianConfig, w as LibrarianGateConfig, x as MaintenanceJob, y as MaintenanceStopReason, z as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, A as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, B as ONTOLOGY_BACKFILL_RECHECK_MS, J as OntologyBackfillResult, K as OntologyConfig, N as OntologyEdgeType, P as OntologyManifest, Q as OntologyMode, T as OntologyNodeType, U as OntologyPromptContext, V as OntologyUpdates, X as PendingMaintenance, Y as PendingMigrationWork, Z as PendingSourceStatus, _ as PromptOverrides, $ as PromptService, a0 as PrunePartialFailureError, a1 as ReembedResult, a2 as RememberInput, a3 as RunPendingMaintenanceOptions, a4 as RunPendingMaintenanceResult, a5 as SupersedeReplacement, a6 as VectorRanker, a7 as VectorRankerFallback, a8 as VectorRankerRankArgs, a9 as VectorRankerSemanticResult, aa as WikiBusyError, ab as WikiBusyOperation, ac as WikiCheckpoint, ad as WikiConfig, ae as WikiDiagnostic, af as WikiDiagnosticCode, ag as WikiDiagnosticDetail, ah as WikiDiagnosticOperation, ai as WikiDiagnosticSeverity, aj as WikiDiagnosticTrigger, ak as WikiDraftNotFound, al as WikiDuplicateHashError, am as WikiEdge, an as WikiEvent, ao as WikiFact, ap as WikiGraphNodeOwnershipConflict, aq as WikiIngestEmptyError, ar as WikiInstructions, as as WikiInvalidReadOptions, at as WikiLintReport, au as WikiMemoryTestAccess, av as WikiMigrationRequiredError, aw as WikiOutboxEvent, ax as WikiParseError, ay as WikiSearchUnavailableError, az as WikiSourceRefHashCollision, aA as WikiStrictOntologyViolation, aB as WikiSupersedeError, aC as WikiSupersedeReason, aD as WikiTask, aE as WikiTransactionError, aF as isWikiSearchUnavailableError, aG as validateManifest } from './testing-D6So3dKX.mjs';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-BPddGTkl.js';
2
- export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as GraphTraversalOptions, r as GroundingConfig, H as HEAL_BATCH_SIZE, s as HEAL_RECHECK_MS, t as HOOK_TIMEOUT_MARKER, u as HealResult, I as IngestDocumentResult, L as LLMProvider, v as LibrarianConfig, w as LibrarianGateConfig, x as MaintenanceJob, y as MaintenanceStopReason, z as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, A as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, B as ONTOLOGY_BACKFILL_RECHECK_MS, J as OntologyBackfillResult, K as OntologyConfig, N as OntologyEdgeType, P as OntologyManifest, Q as OntologyMode, T as OntologyNodeType, U as OntologyPromptContext, V as OntologyUpdates, X as PendingMaintenance, Y as PendingMigrationWork, Z as PendingSourceStatus, _ as PromptOverrides, $ as PromptService, a0 as PrunePartialFailureError, a1 as ReembedResult, a2 as RememberInput, a3 as RunPendingMaintenanceOptions, a4 as RunPendingMaintenanceResult, a5 as SupersedeReplacement, a6 as VectorRanker, a7 as VectorRankerFallback, a8 as VectorRankerRankArgs, a9 as VectorRankerSemanticResult, aa as WikiBusyError, ab as WikiBusyOperation, ac as WikiCheckpoint, ad as WikiConfig, ae as WikiDiagnostic, af as WikiDiagnosticCode, ag as WikiDiagnosticDetail, ah as WikiDiagnosticOperation, ai as WikiDiagnosticSeverity, aj as WikiDiagnosticTrigger, ak as WikiDraftNotFound, al as WikiDuplicateHashError, am as WikiEdge, an as WikiEvent, ao as WikiFact, ap as WikiGraphNodeOwnershipConflict, aq as WikiIngestEmptyError, ar as WikiInstructions, as as WikiInvalidReadOptions, at as WikiLintReport, au as WikiMemoryTestAccess, av as WikiMigrationRequiredError, aw as WikiOutboxEvent, ax as WikiParseError, ay as WikiSearchUnavailableError, az as WikiSourceRefHashCollision, aA as WikiStrictOntologyViolation, aB as WikiSupersedeError, aC as WikiSupersedeReason, aD as WikiTask, aE as WikiTransactionError, aF as isWikiSearchUnavailableError, aG as validateManifest } from './testing-BPddGTkl.js';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, R as ReadOptions, S as SQLiteAdapter, W as WikiOptions, c as WikiMemory } from './testing-D6So3dKX.js';
2
+ export { C as ChunkFailure, d as ClassifierAnswer, e as ClassifierQuestion, f as ClassifyRequest, g as ClassifyResponse, D as DegradedRecord, h as DraftPage, E as EmbedFactResult, i as EmbedFailureKind, j as EmbeddingMarkerKind, k as EntityMaintenanceReport, l as EntityStatus, m as ExtractedFact, n as ExtractedFactEdge, o as ExtractedFactWithOntology, p as ExtractedTask, q as GraphTraversalOptions, r as GroundingConfig, H as HEAL_BATCH_SIZE, s as HEAL_RECHECK_MS, t as HOOK_TIMEOUT_MARKER, u as HealResult, I as IngestDocumentResult, L as LLMProvider, v as LibrarianConfig, w as LibrarianGateConfig, x as MaintenanceJob, y as MaintenanceStopReason, z as MigrationPolicy, O as ONTOLOGY_BACKFILL_BATCH_SIZE, A as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, B as ONTOLOGY_BACKFILL_RECHECK_MS, J as OntologyBackfillResult, K as OntologyConfig, N as OntologyEdgeType, P as OntologyManifest, Q as OntologyMode, T as OntologyNodeType, U as OntologyPromptContext, V as OntologyUpdates, X as PendingMaintenance, Y as PendingMigrationWork, Z as PendingSourceStatus, _ as PromptOverrides, $ as PromptService, a0 as PrunePartialFailureError, a1 as ReembedResult, a2 as RememberInput, a3 as RunPendingMaintenanceOptions, a4 as RunPendingMaintenanceResult, a5 as SupersedeReplacement, a6 as VectorRanker, a7 as VectorRankerFallback, a8 as VectorRankerRankArgs, a9 as VectorRankerSemanticResult, aa as WikiBusyError, ab as WikiBusyOperation, ac as WikiCheckpoint, ad as WikiConfig, ae as WikiDiagnostic, af as WikiDiagnosticCode, ag as WikiDiagnosticDetail, ah as WikiDiagnosticOperation, ai as WikiDiagnosticSeverity, aj as WikiDiagnosticTrigger, ak as WikiDraftNotFound, al as WikiDuplicateHashError, am as WikiEdge, an as WikiEvent, ao as WikiFact, ap as WikiGraphNodeOwnershipConflict, aq as WikiIngestEmptyError, ar as WikiInstructions, as as WikiInvalidReadOptions, at as WikiLintReport, au as WikiMemoryTestAccess, av as WikiMigrationRequiredError, aw as WikiOutboxEvent, ax as WikiParseError, ay as WikiSearchUnavailableError, az as WikiSourceRefHashCollision, aA as WikiStrictOntologyViolation, aB as WikiSupersedeError, aC as WikiSupersedeReason, aD as WikiTask, aE as WikiTransactionError, aF as isWikiSearchUnavailableError, aG as validateManifest } from './testing-D6So3dKX.js';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.js CHANGED
@@ -3537,9 +3537,10 @@ var EventRepository = class extends BaseRepository {
3537
3537
  ]
3538
3538
  );
3539
3539
  }
3540
+ /** Insert unless the id already exists. Returns true when a row was inserted. */
3540
3541
  async addIgnoreDuplicate(event, tx) {
3541
3542
  const executor = this.getExecutor(tx);
3542
- await executor.runAsync(
3543
+ const result = await executor.runAsync(
3543
3544
  `INSERT OR IGNORE INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at, occurred_at)
3544
3545
  VALUES (?, ?, ?, ?, ?, ?, ?)`,
3545
3546
  [
@@ -3552,6 +3553,7 @@ var EventRepository = class extends BaseRepository {
3552
3553
  event.occurred_at ?? null
3553
3554
  ]
3554
3555
  );
3556
+ return result.changes > 0;
3555
3557
  }
3556
3558
  /**
3557
3559
  * Return the most recent events for an entity, newest first.
@@ -5983,7 +5985,9 @@ var SEVERITY = {
5983
5985
  contradicts_document: "warn",
5984
5986
  resolve_failed: "warn",
5985
5987
  read_budget: "info",
5986
- event_retention_held: "info"
5988
+ event_retention_held: "info",
5989
+ event_created_at_clamped: "warn",
5990
+ event_created_at_restamped: "info"
5987
5991
  };
5988
5992
  var MESSAGE = {
5989
5993
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -6005,7 +6009,9 @@ var MESSAGE = {
6005
6009
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
6006
6010
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
6007
6011
  read_budget: "A read was packed to a token budget.",
6008
- event_retention_held: "Event pruning was held back because the librarian has not processed those events yet."
6012
+ event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
6013
+ 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.",
6014
+ 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."
6009
6015
  };
6010
6016
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
6011
6017
  function copyDetail(detail) {
@@ -7225,6 +7231,28 @@ function warnChangedDefaultsOnce(config) {
7225
7231
  }
7226
7232
  }
7227
7233
 
7234
+ // src/services/legacyWatermark.ts
7235
+ async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
7236
+ if (checkpoint <= 0 || total <= 0) return null;
7237
+ const ev = await eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
7238
+ if (!ev) return null;
7239
+ const wm = { at: ev.created_at, id: ev.id };
7240
+ await metadataRepo.setLibrarianWatermark(entityId, wm, db);
7241
+ return wm;
7242
+ }
7243
+ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
7244
+ const existing = await metadataRepo.getLibrarianWatermark(entityId, db);
7245
+ if (existing) return existing;
7246
+ const memory = (await metadataRepo.getCheckpoint(entityId, db)).memory ?? 0;
7247
+ if (memory <= 0) return null;
7248
+ const total = await eventRepo.count(entityId, db);
7249
+ if (memory > total) {
7250
+ await metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, db);
7251
+ return START_OF_LOG_WATERMARK;
7252
+ }
7253
+ return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
7254
+ }
7255
+
7228
7256
  // src/services/BoundedLlmCall.ts
7229
7257
  var DEFAULT_BATCH_SIZE = 10;
7230
7258
  var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
@@ -8617,13 +8645,8 @@ var MaintenanceService = class {
8617
8645
  * nothing and returns null when there is no legacy history or no such
8618
8646
  * event; each caller picks its own fallback.
8619
8647
  */
8620
- async anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
8621
- if (checkpoint <= 0 || total <= 0) return null;
8622
- const ev = await this.eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
8623
- if (!ev) return null;
8624
- const wm = { at: ev.created_at, id: ev.id };
8625
- await this.metadataRepo.setLibrarianWatermark(entityId, wm, db);
8626
- return wm;
8648
+ anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
8649
+ return anchorAtLegacyBoundary(this.metadataRepo, this.eventRepo, entityId, checkpoint, total, db);
8627
8650
  }
8628
8651
  /**
8629
8652
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
@@ -8633,16 +8656,7 @@ var MaintenanceService = class {
8633
8656
  * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
8634
8657
  */
8635
8658
  async seedLibrarianWatermark(entityId) {
8636
- if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
8637
- const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
8638
- const memory = cp.memory ?? 0;
8639
- if (memory <= 0) return;
8640
- const total = await this.eventRepo.count(entityId, this.db);
8641
- if (memory > total) {
8642
- await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, this.db);
8643
- return;
8644
- }
8645
- await this.anchorAtLegacyBoundary(entityId, memory, total, this.db);
8659
+ await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, this.db);
8646
8660
  }
8647
8661
  /**
8648
8662
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -9449,11 +9463,70 @@ var MaintenanceScheduler = class {
9449
9463
  };
9450
9464
  }
9451
9465
  };
9466
+
9467
+ // src/services/importEventStamps.ts
9468
+ var DATE_MAX = 864e13;
9469
+ var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
9470
+ function createdAtValue(v) {
9471
+ if (typeof v === "number") return v;
9472
+ if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
9473
+ return NaN;
9474
+ }
9475
+ function isUsableDate(v) {
9476
+ return Number.isFinite(v) && v >= -DATE_MAX && v <= DATE_MAX;
9477
+ }
9478
+ function parseSourceWatermark(raw) {
9479
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
9480
+ const { at, id } = raw;
9481
+ if (typeof at !== "number" || !Number.isFinite(at) || typeof id !== "string") return null;
9482
+ return { at, id };
9483
+ }
9484
+ var cmp = (a, b) => a === b ? 0 : a < b ? -1 : 1;
9485
+ function planEventStamps(events, ctx) {
9486
+ const { now, floor, merge, localWm, sourceWm } = ctx;
9487
+ const after = (v, id, wm) => v > wm.at || v === wm.at && id > wm.id;
9488
+ const plan = /* @__PURE__ */ new Map();
9489
+ const restamp = [];
9490
+ for (const e of events) {
9491
+ const v = createdAtValue(e.created_at);
9492
+ const o = createdAtValue(e.occurred_at);
9493
+ let occurredAt = null;
9494
+ let occurredInvalid = false;
9495
+ if (e.occurred_at != null) {
9496
+ if (isUsableDate(o)) occurredAt = Math.trunc(o);
9497
+ else occurredInvalid = true;
9498
+ }
9499
+ let reason = null;
9500
+ const invalidCreated = Number.isNaN(v) || v < -DATE_MAX;
9501
+ if (invalidCreated) reason = "invalid";
9502
+ else if (v > now) reason = "future";
9503
+ else if (merge && localWm !== null && Number.isFinite(localWm.at) && !after(v, e.id, localWm) && (sourceWm === null || after(v, e.id, sourceWm))) {
9504
+ reason = "behind_watermark";
9505
+ }
9506
+ if (reason === "behind_watermark" && occurredAt === null && Number.isFinite(v) && v >= 0) {
9507
+ occurredAt = Math.trunc(v);
9508
+ }
9509
+ const stamp = { createdAt: v, occurredAt, reason };
9510
+ if (reason === null && occurredInvalid) stamp.reason = "invalid";
9511
+ plan.set(e, stamp);
9512
+ if (reason !== null) restamp.push({ e, key: invalidCreated ? -Infinity : v, stamp });
9513
+ }
9514
+ restamp.sort((x, y) => cmp(x.key, y.key) || cmp(x.e.id, y.e.id));
9515
+ if (restamp.length > 0 && floor + restamp.length > Number.MAX_SAFE_INTEGER) {
9516
+ 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.`);
9517
+ }
9518
+ restamp.forEach((x, i) => {
9519
+ x.stamp.createdAt = floor + 1 + i;
9520
+ });
9521
+ return plan;
9522
+ }
9523
+
9524
+ // src/services/ImportExportService.ts
9452
9525
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
9453
9526
  var IMPORT_TITLE_MAX = 500;
9454
9527
  var IMPORT_BODY_MAX = 8e3;
9455
9528
  var ImportExportService = class {
9456
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService) {
9529
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
9457
9530
  this.db = db;
9458
9531
  this.entryRepo = entryRepo;
9459
9532
  this.taskRepo = taskRepo;
@@ -9463,6 +9536,7 @@ var ImportExportService = class {
9463
9536
  this.searchService = searchService;
9464
9537
  this.jobManager = jobManager;
9465
9538
  this.embeddingService = embeddingService;
9539
+ this.options = options;
9466
9540
  }
9467
9541
  async exportDump(entityIds) {
9468
9542
  let ids;
@@ -9503,6 +9577,7 @@ var ImportExportService = class {
9503
9577
  }
9504
9578
  }
9505
9579
  async getFullBundle(entityId, opts) {
9580
+ const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
9506
9581
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
9507
9582
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
9508
9583
  this.taskRepo.findAllByEntityId(entityId),
@@ -9532,7 +9607,8 @@ var ImportExportService = class {
9532
9607
  tasks,
9533
9608
  events,
9534
9609
  edges,
9535
- ...summaryValue != null ? { summary: summaryValue } : {}
9610
+ ...summaryValue != null ? { summary: summaryValue } : {},
9611
+ ...wm ? { librarian_watermark: wm } : {}
9536
9612
  };
9537
9613
  }
9538
9614
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
@@ -9543,6 +9619,8 @@ var ImportExportService = class {
9543
9619
  const preservedBlobDims = /* @__PURE__ */ new Set();
9544
9620
  const softDeletedFactIds = [];
9545
9621
  const clippedTextByFactId = /* @__PURE__ */ new Map();
9622
+ let clampedEvents = 0;
9623
+ const restamped = { behind_watermark: 0, invalid: 0 };
9546
9624
  await this.db.withTransactionAsync(async (tx) => {
9547
9625
  if (!merge) {
9548
9626
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -9763,19 +9841,27 @@ var ImportExportService = class {
9763
9841
  updated_at: safeUpdatedAt
9764
9842
  });
9765
9843
  }
9844
+ const now = Date.now();
9845
+ const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
9846
+ const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
9847
+ const planned = planEventStamps(bundle.events, { now, floor, merge, localWm: wm, sourceWm: parseSourceWatermark(bundle.librarian_watermark) });
9766
9848
  for (const event of bundle.events) {
9767
- await this.eventRepo.addIgnoreDuplicate(
9849
+ const stamp = planned.get(event);
9850
+ const inserted = await this.eventRepo.addIgnoreDuplicate(
9768
9851
  {
9769
9852
  id: event.id,
9770
9853
  entity_id: entityId,
9771
9854
  event_type: event.event_type,
9772
9855
  summary: event.summary,
9773
9856
  related_entry_id: event.related_entry_id ?? null,
9774
- created_at: event.created_at,
9775
- occurred_at: event.occurred_at ?? null
9857
+ created_at: stamp.createdAt,
9858
+ occurred_at: stamp.occurredAt
9776
9859
  },
9777
9860
  tx
9778
9861
  );
9862
+ if (!inserted || stamp.reason === null) continue;
9863
+ if (stamp.reason === "future") clampedEvents++;
9864
+ else restamped[stamp.reason]++;
9779
9865
  }
9780
9866
  for (const edge of bundle.edges ?? []) {
9781
9867
  await this.edgeRepo.addIgnoreDuplicate(
@@ -9791,6 +9877,26 @@ var ImportExportService = class {
9791
9877
  );
9792
9878
  }
9793
9879
  });
9880
+ if (clampedEvents > 0) {
9881
+ emitDiagnostic(this.options, {
9882
+ code: "event_created_at_clamped",
9883
+ operation: "importDump",
9884
+ trigger: "call",
9885
+ entityId,
9886
+ detail: { count: clampedEvents }
9887
+ });
9888
+ }
9889
+ for (const reason of ["behind_watermark", "invalid"]) {
9890
+ if (restamped[reason] > 0) {
9891
+ emitDiagnostic(this.options, {
9892
+ code: "event_created_at_restamped",
9893
+ operation: "importDump",
9894
+ trigger: "call",
9895
+ entityId,
9896
+ detail: { count: restamped[reason], reason }
9897
+ });
9898
+ }
9899
+ }
9794
9900
  if (merge) {
9795
9901
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
9796
9902
  } else {
@@ -10567,7 +10673,7 @@ var RetrievalService = class {
10567
10673
  if (topK.length < maxBackfill) {
10568
10674
  let insertIdx = topK.length;
10569
10675
  for (let i = 0; i < topK.length; i++) {
10570
- const cmp = this._compareScoredRows(
10676
+ const cmp2 = this._compareScoredRows(
10571
10677
  {
10572
10678
  id: candidate.row.id,
10573
10679
  score: candidate.kwScore,
@@ -10581,7 +10687,7 @@ var RetrievalService = class {
10581
10687
  access_count: topK[i].row.access_count
10582
10688
  }
10583
10689
  );
10584
- if (cmp < 0) {
10690
+ if (cmp2 < 0) {
10585
10691
  insertIdx = i;
10586
10692
  break;
10587
10693
  }
@@ -10605,7 +10711,7 @@ var RetrievalService = class {
10605
10711
  if (cmpWorst < 0) {
10606
10712
  let insertIdx = maxBackfill - 1;
10607
10713
  for (let i = 0; i < topK.length; i++) {
10608
- const cmp = this._compareScoredRows(
10714
+ const cmp2 = this._compareScoredRows(
10609
10715
  {
10610
10716
  id: candidate.row.id,
10611
10717
  score: candidate.kwScore,
@@ -10619,7 +10725,7 @@ var RetrievalService = class {
10619
10725
  access_count: topK[i].row.access_count
10620
10726
  }
10621
10727
  );
10622
- if (cmp < 0) {
10728
+ if (cmp2 < 0) {
10623
10729
  insertIdx = i;
10624
10730
  break;
10625
10731
  }
@@ -11835,7 +11941,8 @@ var WikiMemory = class {
11835
11941
  this.metadataRepo,
11836
11942
  this.searchService,
11837
11943
  this.jobManager,
11838
- this.embeddingService
11944
+ this.embeddingService,
11945
+ this.options
11839
11946
  );
11840
11947
  this.retrievalService = new RetrievalService(
11841
11948
  this.options,
@@ -13063,9 +13170,13 @@ function buildEventLogEntries(events, factIdToFilename) {
13063
13170
  const factFilename = e.related_entry_id ? factIdToFilename.get(e.related_entry_id) : void 0;
13064
13171
  const summary = e.summary.replace(/\\/g, "\\\\").replace(/\[/g, "\\[").replace(/\]/g, "\\]").replace(/\r?\n/g, " ");
13065
13172
  const text = factFilename ? `(${e.event_type}) [${summary}](./facts/${factFilename}.md)` : `(${e.event_type}) ${summary}`;
13066
- return { date: formatLogDate(e.created_at), text: coreOkf.appendEventIdComment(text, e.id) };
13173
+ const occurred = createdAtValue(e.occurred_at);
13174
+ const logTime = e.occurred_at != null && isUsableDate(occurred) && occurred >= OKF_DATE_MIN && occurred <= OKF_DATE_MAX && occurred <= e.created_at ? occurred : e.created_at;
13175
+ return { date: formatLogDate(logTime), text: coreOkf.appendEventIdComment(text, e.id) };
13067
13176
  });
13068
13177
  }
13178
+ var OKF_DATE_MIN = -621672192e5;
13179
+ var OKF_DATE_MAX = 253402300799999;
13069
13180
  function formatOkfBundle(dump, options) {
13070
13181
  const profile = options?.profile ?? DEFAULT_PROFILE;
13071
13182
  const okfVersion = profile === "llm-wiki/2" ? "0.2" : "0.1";