@equationalapplications/core-llm-wiki 8.0.4 → 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.
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-De-WJ7xh.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-De-WJ7xh.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-CG8Hw5Ph.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-CG8Hw5Ph.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-De-WJ7xh.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-De-WJ7xh.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-CG8Hw5Ph.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-CG8Hw5Ph.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.
@@ -3581,8 +3583,8 @@ var EventRepository = class extends BaseRepository {
3581
3583
  * Delete events for an entity that were created at or before the given cutoff timestamp.
3582
3584
  * Returns the number of deleted rows.
3583
3585
  */
3584
- async prune(entityId, cutoff) {
3585
- return this.db.runAsync(
3586
+ async prune(entityId, cutoff, tx) {
3587
+ return (tx ?? this.db).runAsync(
3586
3588
  `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?`,
3587
3589
  [entityId, cutoff]
3588
3590
  );
@@ -3594,9 +3596,9 @@ var EventRepository = class extends BaseRepository {
3594
3596
  * deleted. `wm = null` (no watermark yet) deletes nothing.
3595
3597
  * Used by runPrune under the deferred/ops strategies.
3596
3598
  */
3597
- async pruneThrough(entityId, cutoff, wm) {
3599
+ async pruneThrough(entityId, cutoff, wm, tx) {
3598
3600
  if (!wm) return { changes: 0 };
3599
- return this.db.runAsync(
3601
+ return (tx ?? this.db).runAsync(
3600
3602
  `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ? AND NOT ${AFTER_SQL}`,
3601
3603
  [entityId, cutoff, ...afterArgs(wm)]
3602
3604
  );
@@ -3614,6 +3616,18 @@ var EventRepository = class extends BaseRepository {
3614
3616
  );
3615
3617
  return Number(row?.n ?? 0);
3616
3618
  }
3619
+ /**
3620
+ * The newest `created_at` stored for an entity, or null when it has no
3621
+ * events. `write()` reads it inside its transaction to keep `created_at`
3622
+ * strictly increasing per entity (spec ops-auto-first-batch §5).
3623
+ */
3624
+ async latestCreatedAt(entityId, tx) {
3625
+ const row = await (tx ?? this.db).getFirstAsync(
3626
+ `SELECT MAX(created_at) AS at FROM ${this.prefix}events WHERE entity_id = ?`,
3627
+ [entityId]
3628
+ );
3629
+ return row?.at ?? null;
3630
+ }
3617
3631
  /**
3618
3632
  * Return the total number of events stored for an entity.
3619
3633
  * `tx` is optional — pass an active transaction handle for atomic reads.
@@ -4067,6 +4081,7 @@ function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
4067
4081
  function entitySummaryMetaKey(entityId) {
4068
4082
  return `entity_summary:${entityId}`;
4069
4083
  }
4084
+ var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
4070
4085
  var MetadataRepository = class extends BaseRepository {
4071
4086
  // CHECKPOINTS TABLE METHODS
4072
4087
  async getCheckpoint(entityId, tx) {
@@ -5970,7 +5985,8 @@ var SEVERITY = {
5970
5985
  contradicts_document: "warn",
5971
5986
  resolve_failed: "warn",
5972
5987
  read_budget: "info",
5973
- event_retention_held: "info"
5988
+ event_retention_held: "info",
5989
+ event_created_at_clamped: "warn"
5974
5990
  };
5975
5991
  var MESSAGE = {
5976
5992
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -5992,7 +6008,8 @@ var MESSAGE = {
5992
6008
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
5993
6009
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
5994
6010
  read_budget: "A read was packed to a token budget.",
5995
- event_retention_held: "Event pruning was held back because the librarian has not processed those events yet."
6011
+ event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
6012
+ 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."
5996
6013
  };
5997
6014
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
5998
6015
  function copyDetail(detail) {
@@ -7212,6 +7229,28 @@ function warnChangedDefaultsOnce(config) {
7212
7229
  }
7213
7230
  }
7214
7231
 
7232
+ // src/services/legacyWatermark.ts
7233
+ async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
7234
+ if (checkpoint <= 0 || total <= 0) return null;
7235
+ const ev = await eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
7236
+ if (!ev) return null;
7237
+ const wm = { at: ev.created_at, id: ev.id };
7238
+ await metadataRepo.setLibrarianWatermark(entityId, wm, db);
7239
+ return wm;
7240
+ }
7241
+ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
7242
+ const existing = await metadataRepo.getLibrarianWatermark(entityId, db);
7243
+ if (existing) return existing;
7244
+ const memory = (await metadataRepo.getCheckpoint(entityId, db)).memory ?? 0;
7245
+ if (memory <= 0) return null;
7246
+ const total = await eventRepo.count(entityId, db);
7247
+ if (memory > total) {
7248
+ await metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, db);
7249
+ return START_OF_LOG_WATERMARK;
7250
+ }
7251
+ return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
7252
+ }
7253
+
7215
7254
  // src/services/BoundedLlmCall.ts
7216
7255
  var DEFAULT_BATCH_SIZE = 10;
7217
7256
  var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
@@ -8244,16 +8283,29 @@ var MaintenanceService = class {
8244
8283
  if (retainEventsFor !== null) {
8245
8284
  const cutoff = now - retainEventsFor * 864e5;
8246
8285
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
8286
+ let wm = null;
8287
+ await this.db.withTransactionAsync(async (tx) => {
8288
+ if (guarded) {
8289
+ wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
8290
+ deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
8291
+ } else {
8292
+ deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
8293
+ }
8294
+ if (deletedEvents > 0) {
8295
+ const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
8296
+ const updates = {};
8297
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
8298
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
8299
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
8300
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
8301
+ }
8302
+ }
8303
+ });
8247
8304
  if (guarded) {
8248
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
8249
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm)).changes;
8250
8305
  const held = await this.eventRepo.countHeldBack(entityId, cutoff, wm);
8251
8306
  if (held > 0) {
8252
8307
  emitDiagnostic(this.options, { code: "event_retention_held", operation: "prune", trigger: "call", entityId, detail: { count: held } });
8253
8308
  }
8254
- } else {
8255
- const eventResult = await this.eventRepo.prune(entityId, cutoff);
8256
- deletedEvents = eventResult.changes;
8257
8309
  }
8258
8310
  }
8259
8311
  if (vacuum) {
@@ -8566,20 +8618,43 @@ var MaintenanceService = class {
8566
8618
  const newer = !current || next.at > current.at || next.at === current.at && next.id > current.id;
8567
8619
  if (newer) await this.metadataRepo.setLibrarianWatermark(entityId, next, this.db);
8568
8620
  }
8621
+ /**
8622
+ * Anchor the ops watermark before an auto trigger advances
8623
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
8624
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
8625
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
8626
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
8627
+ * event count, already read by the caller in the same transaction. All
8628
+ * reads and the write use the trigger's transaction. Returns the watermark
8629
+ * in force afterwards, so the caller need not read it again.
8630
+ * Package-internal.
8631
+ */
8632
+ async anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) {
8633
+ const existing = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
8634
+ if (existing) return existing;
8635
+ const wm = await this.anchorAtLegacyBoundary(entityId, preCheckpoint, total, tx);
8636
+ if (wm) return wm;
8637
+ await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, tx);
8638
+ return START_OF_LOG_WATERMARK;
8639
+ }
8640
+ /**
8641
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
8642
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
8643
+ * nothing and returns null when there is no legacy history or no such
8644
+ * event; each caller picks its own fallback.
8645
+ */
8646
+ anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
8647
+ return anchorAtLegacyBoundary(this.metadataRepo, this.eventRepo, entityId, checkpoint, total, db);
8648
+ }
8569
8649
  /**
8570
8650
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
8571
8651
  * checkpoint already covered. No-op when a watermark already exists or the
8572
8652
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
8573
- * offset `min(memory_checkpoint, totalEvents) - 1`.
8653
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
8654
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
8574
8655
  */
8575
8656
  async seedLibrarianWatermark(entityId) {
8576
- if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
8577
- const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
8578
- const memory = cp.memory ?? 0;
8579
- if (memory <= 0) return;
8580
- const total = await this.eventRepo.count(entityId);
8581
- const ev = await this.eventRepo.getAtOffset(entityId, Math.min(memory, total) - 1);
8582
- if (ev) await this.metadataRepo.setLibrarianWatermark(entityId, { at: ev.created_at, id: ev.id }, this.db);
8657
+ await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, this.db);
8583
8658
  }
8584
8659
  /**
8585
8660
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -9334,6 +9409,9 @@ var MaintenanceScheduler = class {
9334
9409
  let h;
9335
9410
  try {
9336
9411
  h = await this.maintenanceService.doRunHeal(entityId, { trigger: "call", meter });
9412
+ if (h.remaining === 0 && !(h.budgetStop && h.scanned === 0)) {
9413
+ await this.metadataRepo.updateCheckpoint(entityId, { heal: await this.eventRepo.count(entityId) }, this.db);
9414
+ }
9337
9415
  } finally {
9338
9416
  this.jobManager.releaseLock("heal", entityId);
9339
9417
  }
@@ -9352,10 +9430,7 @@ var MaintenanceScheduler = class {
9352
9430
  }
9353
9431
  st.report.healPasses++;
9354
9432
  progressed = true;
9355
- if (h.remaining === 0) {
9356
- st.heal = false;
9357
- await this.metadataRepo.updateCheckpoint(entityId, { heal: await this.eventRepo.count(entityId) }, this.db);
9358
- }
9433
+ if (h.remaining === 0) st.heal = false;
9359
9434
  if (h.budgetStop) {
9360
9435
  stopped = exhaustedStop();
9361
9436
  break rounds;
@@ -9389,8 +9464,21 @@ var MaintenanceScheduler = class {
9389
9464
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
9390
9465
  var IMPORT_TITLE_MAX = 500;
9391
9466
  var IMPORT_BODY_MAX = 8e3;
9467
+ var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
9468
+ function createdAtValue(v) {
9469
+ if (typeof v === "number") return v;
9470
+ if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
9471
+ return NaN;
9472
+ }
9473
+ function clampFutureCreatedAt(events, now, floor) {
9474
+ 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));
9475
+ if (future.length > 0 && floor + future.length > Number.MAX_SAFE_INTEGER) {
9476
+ 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.`);
9477
+ }
9478
+ return new Map(future.map((x, i) => [x.e, floor + 1 + i]));
9479
+ }
9392
9480
  var ImportExportService = class {
9393
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService) {
9481
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
9394
9482
  this.db = db;
9395
9483
  this.entryRepo = entryRepo;
9396
9484
  this.taskRepo = taskRepo;
@@ -9400,6 +9488,7 @@ var ImportExportService = class {
9400
9488
  this.searchService = searchService;
9401
9489
  this.jobManager = jobManager;
9402
9490
  this.embeddingService = embeddingService;
9491
+ this.options = options;
9403
9492
  }
9404
9493
  async exportDump(entityIds) {
9405
9494
  let ids;
@@ -9480,6 +9569,7 @@ var ImportExportService = class {
9480
9569
  const preservedBlobDims = /* @__PURE__ */ new Set();
9481
9570
  const softDeletedFactIds = [];
9482
9571
  const clippedTextByFactId = /* @__PURE__ */ new Map();
9572
+ let clampedEvents = 0;
9483
9573
  await this.db.withTransactionAsync(async (tx) => {
9484
9574
  if (!merge) {
9485
9575
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -9700,19 +9790,25 @@ var ImportExportService = class {
9700
9790
  updated_at: safeUpdatedAt
9701
9791
  });
9702
9792
  }
9793
+ const now = Date.now();
9794
+ const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
9795
+ const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
9796
+ const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
9703
9797
  for (const event of bundle.events) {
9704
- await this.eventRepo.addIgnoreDuplicate(
9798
+ const stamped = clampedAt.get(event);
9799
+ const inserted = await this.eventRepo.addIgnoreDuplicate(
9705
9800
  {
9706
9801
  id: event.id,
9707
9802
  entity_id: entityId,
9708
9803
  event_type: event.event_type,
9709
9804
  summary: event.summary,
9710
9805
  related_entry_id: event.related_entry_id ?? null,
9711
- created_at: event.created_at,
9806
+ created_at: stamped ?? event.created_at,
9712
9807
  occurred_at: event.occurred_at ?? null
9713
9808
  },
9714
9809
  tx
9715
9810
  );
9811
+ if (inserted && stamped !== void 0) clampedEvents++;
9716
9812
  }
9717
9813
  for (const edge of bundle.edges ?? []) {
9718
9814
  await this.edgeRepo.addIgnoreDuplicate(
@@ -9728,6 +9824,15 @@ var ImportExportService = class {
9728
9824
  );
9729
9825
  }
9730
9826
  });
9827
+ if (clampedEvents > 0) {
9828
+ emitDiagnostic(this.options, {
9829
+ code: "event_created_at_clamped",
9830
+ operation: "importDump",
9831
+ trigger: "call",
9832
+ entityId,
9833
+ detail: { count: clampedEvents }
9834
+ });
9835
+ }
9731
9836
  if (merge) {
9732
9837
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
9733
9838
  } else {
@@ -10938,16 +11043,30 @@ var WriteService = class {
10938
11043
  created_at: now,
10939
11044
  occurred_at: occurredAt
10940
11045
  };
11046
+ const stampCreatedAt = async (tx) => {
11047
+ const latest = await this.eventRepo.latestCreatedAt(entityId, tx);
11048
+ if (latest === null || latest < newEvent.created_at) return;
11049
+ if (latest >= Number.MAX_SAFE_INTEGER) {
11050
+ throw new RangeError(`Cannot stamp event created_at: the newest stored created_at (${latest}) is at Number.MAX_SAFE_INTEGER, so no later timestamp can be ordered safely.`);
11051
+ }
11052
+ newEvent.created_at = latest + 1;
11053
+ };
10941
11054
  const deferred = resolveMaintenanceMode(this.options.config) === "deferred";
10942
11055
  if (deferred) {
10943
- await this.eventRepo.add(newEvent);
11056
+ await this.db.withTransactionAsync(async (tx) => {
11057
+ await stampCreatedAt(tx);
11058
+ await this.eventRepo.add(newEvent, tx);
11059
+ });
10944
11060
  return;
10945
11061
  }
10946
11062
  let shouldRunLibrarian = false;
10947
11063
  let librarianCount = 0;
10948
11064
  let prevMemoryCheckpoint = 0;
10949
11065
  let eventCount = 0;
11066
+ const isOps = resolveLibrarianStrategy(this.options.config) === "ops";
11067
+ const anchorOps = async (preCheckpoint, total, tx) => isOps ? this.maintenanceService.anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) : this.metadataRepo.getLibrarianWatermark(entityId, tx);
10950
11068
  await this.db.withTransactionAsync(async (tx) => {
11069
+ await stampCreatedAt(tx);
10951
11070
  await this.eventRepo.add(newEvent, tx);
10952
11071
  const threshold = this.options.config?.autoLibrarianThreshold || 20;
10953
11072
  const [count, cp] = await Promise.all([
@@ -10956,18 +11075,19 @@ var WriteService = class {
10956
11075
  ]);
10957
11076
  eventCount = count;
10958
11077
  let memoryCheckpoint = cp.memory ?? 0;
10959
- if (memoryCheckpoint > count) memoryCheckpoint = 0;
11078
+ if (memoryCheckpoint >= count) memoryCheckpoint = 0;
10960
11079
  if (count - memoryCheckpoint >= threshold) {
10961
11080
  if (!this.jobManager.isBlocked("librarian", entityId)) {
10962
11081
  shouldRunLibrarian = true;
10963
11082
  librarianCount = count;
10964
11083
  prevMemoryCheckpoint = memoryCheckpoint;
11084
+ if (isOps) await anchorOps(memoryCheckpoint, count, tx);
10965
11085
  await this.metadataRepo.updateCheckpoint(entityId, { memory: count }, tx);
10966
11086
  }
10967
11087
  } else {
10968
11088
  const tokenThreshold = this.options.config?.autoLibrarianTokenThreshold;
10969
11089
  if (typeof tokenThreshold === "number" && tokenThreshold > 0 && !this.jobManager.isBlocked("librarian", entityId)) {
10970
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
11090
+ const wm = await anchorOps(memoryCheckpoint, count, tx);
10971
11091
  const chars = await this.eventRepo.sumSummaryCharsAfter(entityId, wm, tx);
10972
11092
  if (Math.ceil(chars / 4) >= tokenThreshold) {
10973
11093
  shouldRunLibrarian = true;
@@ -10990,7 +11110,11 @@ var WriteService = class {
10990
11110
  this.track(job);
10991
11111
  } catch (e) {
10992
11112
  if (!(e instanceof WikiBusyError)) throw e;
10993
- await this.metadataRepo.updateCheckpoint(entityId, { memory: prevMemoryCheckpoint }, this.db);
11113
+ const added = librarianCount - prevMemoryCheckpoint;
11114
+ await this.db.withTransactionAsync(async (tx) => {
11115
+ const memory = (await this.metadataRepo.getCheckpoint(entityId, tx)).memory ?? 0;
11116
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: Math.max(0, memory - added) }, tx);
11117
+ });
10994
11118
  }
10995
11119
  } else if (!this.jobManager.isBlocked("librarian", entityId)) {
10996
11120
  const healJob = this.maybeRunHeal(entityId, eventCount).catch((err) => {
@@ -11025,7 +11149,8 @@ var WriteService = class {
11025
11149
  try {
11026
11150
  const result = await this.maintenanceService.doRunHeal(entityId, { trigger: "auto" });
11027
11151
  if (result.remaining === 0) {
11028
- await this.metadataRepo.updateCheckpoint(entityId, { heal: currentEventCount }, this.db);
11152
+ const live = await this.eventRepo.count(entityId, this.db);
11153
+ await this.metadataRepo.updateCheckpoint(entityId, { heal: Math.min(currentEventCount, live) }, this.db);
11029
11154
  }
11030
11155
  } finally {
11031
11156
  this.jobManager.releaseLock("heal", entityId);
@@ -11752,7 +11877,8 @@ var WikiMemory = class {
11752
11877
  this.metadataRepo,
11753
11878
  this.searchService,
11754
11879
  this.jobManager,
11755
- this.embeddingService
11880
+ this.embeddingService,
11881
+ this.options
11756
11882
  );
11757
11883
  this.retrievalService = new RetrievalService(
11758
11884
  this.options,