@equationalapplications/core-llm-wiki 8.0.4 → 8.0.5

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-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';
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-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';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
package/dist/index.js CHANGED
@@ -3581,8 +3581,8 @@ var EventRepository = class extends BaseRepository {
3581
3581
  * Delete events for an entity that were created at or before the given cutoff timestamp.
3582
3582
  * Returns the number of deleted rows.
3583
3583
  */
3584
- async prune(entityId, cutoff) {
3585
- return this.db.runAsync(
3584
+ async prune(entityId, cutoff, tx) {
3585
+ return (tx ?? this.db).runAsync(
3586
3586
  `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ?`,
3587
3587
  [entityId, cutoff]
3588
3588
  );
@@ -3594,9 +3594,9 @@ var EventRepository = class extends BaseRepository {
3594
3594
  * deleted. `wm = null` (no watermark yet) deletes nothing.
3595
3595
  * Used by runPrune under the deferred/ops strategies.
3596
3596
  */
3597
- async pruneThrough(entityId, cutoff, wm) {
3597
+ async pruneThrough(entityId, cutoff, wm, tx) {
3598
3598
  if (!wm) return { changes: 0 };
3599
- return this.db.runAsync(
3599
+ return (tx ?? this.db).runAsync(
3600
3600
  `DELETE FROM ${this.prefix}events WHERE entity_id = ? AND created_at <= ? AND NOT ${AFTER_SQL}`,
3601
3601
  [entityId, cutoff, ...afterArgs(wm)]
3602
3602
  );
@@ -3614,6 +3614,18 @@ var EventRepository = class extends BaseRepository {
3614
3614
  );
3615
3615
  return Number(row?.n ?? 0);
3616
3616
  }
3617
+ /**
3618
+ * The newest `created_at` stored for an entity, or null when it has no
3619
+ * events. `write()` reads it inside its transaction to keep `created_at`
3620
+ * strictly increasing per entity (spec ops-auto-first-batch §5).
3621
+ */
3622
+ async latestCreatedAt(entityId, tx) {
3623
+ const row = await (tx ?? this.db).getFirstAsync(
3624
+ `SELECT MAX(created_at) AS at FROM ${this.prefix}events WHERE entity_id = ?`,
3625
+ [entityId]
3626
+ );
3627
+ return row?.at ?? null;
3628
+ }
3617
3629
  /**
3618
3630
  * Return the total number of events stored for an entity.
3619
3631
  * `tx` is optional — pass an active transaction handle for atomic reads.
@@ -4067,6 +4079,7 @@ function validateInlineEdges(sourceType, _targetType, edges, manifest, opts) {
4067
4079
  function entitySummaryMetaKey(entityId) {
4068
4080
  return `entity_summary:${entityId}`;
4069
4081
  }
4082
+ var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
4070
4083
  var MetadataRepository = class extends BaseRepository {
4071
4084
  // CHECKPOINTS TABLE METHODS
4072
4085
  async getCheckpoint(entityId, tx) {
@@ -8244,16 +8257,29 @@ var MaintenanceService = class {
8244
8257
  if (retainEventsFor !== null) {
8245
8258
  const cutoff = now - retainEventsFor * 864e5;
8246
8259
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
8260
+ let wm = null;
8261
+ await this.db.withTransactionAsync(async (tx) => {
8262
+ if (guarded) {
8263
+ wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
8264
+ deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
8265
+ } else {
8266
+ deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
8267
+ }
8268
+ if (deletedEvents > 0) {
8269
+ const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
8270
+ const updates = {};
8271
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
8272
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
8273
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
8274
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
8275
+ }
8276
+ }
8277
+ });
8247
8278
  if (guarded) {
8248
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
8249
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm)).changes;
8250
8279
  const held = await this.eventRepo.countHeldBack(entityId, cutoff, wm);
8251
8280
  if (held > 0) {
8252
8281
  emitDiagnostic(this.options, { code: "event_retention_held", operation: "prune", trigger: "call", entityId, detail: { count: held } });
8253
8282
  }
8254
- } else {
8255
- const eventResult = await this.eventRepo.prune(entityId, cutoff);
8256
- deletedEvents = eventResult.changes;
8257
8283
  }
8258
8284
  }
8259
8285
  if (vacuum) {
@@ -8566,20 +8592,57 @@ var MaintenanceService = class {
8566
8592
  const newer = !current || next.at > current.at || next.at === current.at && next.id > current.id;
8567
8593
  if (newer) await this.metadataRepo.setLibrarianWatermark(entityId, next, this.db);
8568
8594
  }
8595
+ /**
8596
+ * Anchor the ops watermark before an auto trigger advances
8597
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
8598
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
8599
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
8600
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
8601
+ * event count, already read by the caller in the same transaction. All
8602
+ * reads and the write use the trigger's transaction. Returns the watermark
8603
+ * in force afterwards, so the caller need not read it again.
8604
+ * Package-internal.
8605
+ */
8606
+ async anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) {
8607
+ const existing = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
8608
+ if (existing) return existing;
8609
+ const wm = await this.anchorAtLegacyBoundary(entityId, preCheckpoint, total, tx);
8610
+ if (wm) return wm;
8611
+ await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, tx);
8612
+ return START_OF_LOG_WATERMARK;
8613
+ }
8614
+ /**
8615
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
8616
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
8617
+ * nothing and returns null when there is no legacy history or no such
8618
+ * event; each caller picks its own fallback.
8619
+ */
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;
8627
+ }
8569
8628
  /**
8570
8629
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
8571
8630
  * checkpoint already covered. No-op when a watermark already exists or the
8572
8631
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
8573
- * offset `min(memory_checkpoint, totalEvents) - 1`.
8632
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
8633
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
8574
8634
  */
8575
8635
  async seedLibrarianWatermark(entityId) {
8576
8636
  if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
8577
8637
  const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
8578
8638
  const memory = cp.memory ?? 0;
8579
8639
  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);
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);
8583
8646
  }
8584
8647
  /**
8585
8648
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -9334,6 +9397,9 @@ var MaintenanceScheduler = class {
9334
9397
  let h;
9335
9398
  try {
9336
9399
  h = await this.maintenanceService.doRunHeal(entityId, { trigger: "call", meter });
9400
+ if (h.remaining === 0 && !(h.budgetStop && h.scanned === 0)) {
9401
+ await this.metadataRepo.updateCheckpoint(entityId, { heal: await this.eventRepo.count(entityId) }, this.db);
9402
+ }
9337
9403
  } finally {
9338
9404
  this.jobManager.releaseLock("heal", entityId);
9339
9405
  }
@@ -9352,10 +9418,7 @@ var MaintenanceScheduler = class {
9352
9418
  }
9353
9419
  st.report.healPasses++;
9354
9420
  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
- }
9421
+ if (h.remaining === 0) st.heal = false;
9359
9422
  if (h.budgetStop) {
9360
9423
  stopped = exhaustedStop();
9361
9424
  break rounds;
@@ -10938,16 +11001,30 @@ var WriteService = class {
10938
11001
  created_at: now,
10939
11002
  occurred_at: occurredAt
10940
11003
  };
11004
+ const stampCreatedAt = async (tx) => {
11005
+ const latest = await this.eventRepo.latestCreatedAt(entityId, tx);
11006
+ if (latest === null || latest < newEvent.created_at) return;
11007
+ if (latest >= Number.MAX_SAFE_INTEGER) {
11008
+ 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.`);
11009
+ }
11010
+ newEvent.created_at = latest + 1;
11011
+ };
10941
11012
  const deferred = resolveMaintenanceMode(this.options.config) === "deferred";
10942
11013
  if (deferred) {
10943
- await this.eventRepo.add(newEvent);
11014
+ await this.db.withTransactionAsync(async (tx) => {
11015
+ await stampCreatedAt(tx);
11016
+ await this.eventRepo.add(newEvent, tx);
11017
+ });
10944
11018
  return;
10945
11019
  }
10946
11020
  let shouldRunLibrarian = false;
10947
11021
  let librarianCount = 0;
10948
11022
  let prevMemoryCheckpoint = 0;
10949
11023
  let eventCount = 0;
11024
+ const isOps = resolveLibrarianStrategy(this.options.config) === "ops";
11025
+ const anchorOps = async (preCheckpoint, total, tx) => isOps ? this.maintenanceService.anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) : this.metadataRepo.getLibrarianWatermark(entityId, tx);
10950
11026
  await this.db.withTransactionAsync(async (tx) => {
11027
+ await stampCreatedAt(tx);
10951
11028
  await this.eventRepo.add(newEvent, tx);
10952
11029
  const threshold = this.options.config?.autoLibrarianThreshold || 20;
10953
11030
  const [count, cp] = await Promise.all([
@@ -10956,18 +11033,19 @@ var WriteService = class {
10956
11033
  ]);
10957
11034
  eventCount = count;
10958
11035
  let memoryCheckpoint = cp.memory ?? 0;
10959
- if (memoryCheckpoint > count) memoryCheckpoint = 0;
11036
+ if (memoryCheckpoint >= count) memoryCheckpoint = 0;
10960
11037
  if (count - memoryCheckpoint >= threshold) {
10961
11038
  if (!this.jobManager.isBlocked("librarian", entityId)) {
10962
11039
  shouldRunLibrarian = true;
10963
11040
  librarianCount = count;
10964
11041
  prevMemoryCheckpoint = memoryCheckpoint;
11042
+ if (isOps) await anchorOps(memoryCheckpoint, count, tx);
10965
11043
  await this.metadataRepo.updateCheckpoint(entityId, { memory: count }, tx);
10966
11044
  }
10967
11045
  } else {
10968
11046
  const tokenThreshold = this.options.config?.autoLibrarianTokenThreshold;
10969
11047
  if (typeof tokenThreshold === "number" && tokenThreshold > 0 && !this.jobManager.isBlocked("librarian", entityId)) {
10970
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
11048
+ const wm = await anchorOps(memoryCheckpoint, count, tx);
10971
11049
  const chars = await this.eventRepo.sumSummaryCharsAfter(entityId, wm, tx);
10972
11050
  if (Math.ceil(chars / 4) >= tokenThreshold) {
10973
11051
  shouldRunLibrarian = true;
@@ -10990,7 +11068,11 @@ var WriteService = class {
10990
11068
  this.track(job);
10991
11069
  } catch (e) {
10992
11070
  if (!(e instanceof WikiBusyError)) throw e;
10993
- await this.metadataRepo.updateCheckpoint(entityId, { memory: prevMemoryCheckpoint }, this.db);
11071
+ const added = librarianCount - prevMemoryCheckpoint;
11072
+ await this.db.withTransactionAsync(async (tx) => {
11073
+ const memory = (await this.metadataRepo.getCheckpoint(entityId, tx)).memory ?? 0;
11074
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: Math.max(0, memory - added) }, tx);
11075
+ });
10994
11076
  }
10995
11077
  } else if (!this.jobManager.isBlocked("librarian", entityId)) {
10996
11078
  const healJob = this.maybeRunHeal(entityId, eventCount).catch((err) => {
@@ -11025,7 +11107,8 @@ var WriteService = class {
11025
11107
  try {
11026
11108
  const result = await this.maintenanceService.doRunHeal(entityId, { trigger: "auto" });
11027
11109
  if (result.remaining === 0) {
11028
- await this.metadataRepo.updateCheckpoint(entityId, { heal: currentEventCount }, this.db);
11110
+ const live = await this.eventRepo.count(entityId, this.db);
11111
+ await this.metadataRepo.updateCheckpoint(entityId, { heal: Math.min(currentEventCount, live) }, this.db);
11029
11112
  }
11030
11113
  } finally {
11031
11114
  this.jobManager.releaseLock("heal", entityId);