@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.
@@ -802,7 +802,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
802
802
  * Closed for this release series, but new codes are added in minor versions:
803
803
  * hosts must tolerate codes they do not recognize.
804
804
  */
805
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held';
805
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'event_created_at_clamped';
806
806
  /** The service run that emitted the diagnostic. */
807
807
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune';
808
808
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -3034,7 +3034,8 @@ declare class EventRepository extends BaseRepository {
3034
3034
  * Pass `tx` to participate in a caller-owned transaction; omit to run against the default db.
3035
3035
  */
3036
3036
  add(event: WikiEvent, tx?: SQLiteAdapter): Promise<void>;
3037
- addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<void>;
3037
+ /** Insert unless the id already exists. Returns true when a row was inserted. */
3038
+ addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<boolean>;
3038
3039
  /**
3039
3040
  * Return the most recent events for an entity, newest first.
3040
3041
  * Defaults to a limit of 50.
@@ -3049,7 +3050,7 @@ declare class EventRepository extends BaseRepository {
3049
3050
  * Delete events for an entity that were created at or before the given cutoff timestamp.
3050
3051
  * Returns the number of deleted rows.
3051
3052
  */
3052
- prune(entityId: string, cutoff: number): Promise<{
3053
+ prune(entityId: string, cutoff: number, tx?: SQLiteAdapter): Promise<{
3053
3054
  changes: number;
3054
3055
  }>;
3055
3056
  /**
@@ -3059,7 +3060,7 @@ declare class EventRepository extends BaseRepository {
3059
3060
  * deleted. `wm = null` (no watermark yet) deletes nothing.
3060
3061
  * Used by runPrune under the deferred/ops strategies.
3061
3062
  */
3062
- pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<{
3063
+ pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null, tx?: SQLiteAdapter): Promise<{
3063
3064
  changes: number;
3064
3065
  }>;
3065
3066
  /**
@@ -3068,6 +3069,12 @@ declare class EventRepository extends BaseRepository {
3068
3069
  * events at or before `cutoff` (every one of them is held back).
3069
3070
  */
3070
3071
  countHeldBack(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<number>;
3072
+ /**
3073
+ * The newest `created_at` stored for an entity, or null when it has no
3074
+ * events. `write()` reads it inside its transaction to keep `created_at`
3075
+ * strictly increasing per entity (spec ops-auto-first-batch §5).
3076
+ */
3077
+ latestCreatedAt(entityId: string, tx?: SQLiteAdapter): Promise<number | null>;
3071
3078
  /**
3072
3079
  * Return the total number of events stored for an entity.
3073
3080
  * `tx` is optional — pass an active transaction handle for atomic reads.
@@ -3331,11 +3338,31 @@ declare class MaintenanceService {
3331
3338
  * the op-based librarian (spec §10.3). Never moves backwards.
3332
3339
  */
3333
3340
  private advanceLibrarianWatermark;
3341
+ /**
3342
+ * Anchor the ops watermark before an auto trigger advances
3343
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
3344
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
3345
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
3346
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
3347
+ * event count, already read by the caller in the same transaction. All
3348
+ * reads and the write use the trigger's transaction. Returns the watermark
3349
+ * in force afterwards, so the caller need not read it again.
3350
+ * Package-internal.
3351
+ */
3352
+ anchorWatermarkBeforeTrigger(entityId: string, preCheckpoint: number, total: number, tx: SQLiteAdapter): Promise<LibrarianWatermark>;
3353
+ /**
3354
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
3355
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
3356
+ * nothing and returns null when there is no legacy history or no such
3357
+ * event; each caller picks its own fallback.
3358
+ */
3359
+ private anchorAtLegacyBoundary;
3334
3360
  /**
3335
3361
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
3336
3362
  * checkpoint already covered. No-op when a watermark already exists or the
3337
3363
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
3338
- * offset `min(memory_checkpoint, totalEvents) - 1`.
3364
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
3365
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
3339
3366
  */
3340
3367
  seedLibrarianWatermark(entityId: string): Promise<void>;
3341
3368
  /**
@@ -3445,7 +3472,8 @@ declare class ImportExportService {
3445
3472
  private searchService;
3446
3473
  private jobManager;
3447
3474
  private embeddingService;
3448
- constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService);
3475
+ private options;
3476
+ constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, options?: Pick<WikiOptions, 'onDiagnostic'>);
3449
3477
  exportDump(entityIds?: string[]): Promise<MemoryDump>;
3450
3478
  importDump(dump: MemoryDump, opts?: {
3451
3479
  merge?: boolean;
@@ -802,7 +802,7 @@ type WikiDiagnosticSeverity = 'info' | 'warn' | 'error';
802
802
  * Closed for this release series, but new codes are added in minor versions:
803
803
  * hosts must tolerate codes they do not recognize.
804
804
  */
805
- type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held';
805
+ type WikiDiagnosticCode = 'ingest_chunk_failed' | 'fact_rejected' | 'task_rejected' | 'fact_deduplicated' | 'edge_dropped' | 'embedding_failed' | 'hook_failed' | 'background_job_failed' | 'heal_skipped' | 'grounding_missing' | 'grounding_failed' | 'classification_low_confidence' | 'classification_invalid' | 'llm_usage' | 'librarian_gate' | 'librarian_op_rejected' | 'contradicts_document' | 'resolve_failed' | 'read_budget' | 'event_retention_held' | 'event_created_at_clamped';
806
806
  /** The service run that emitted the diagnostic. */
807
807
  type WikiDiagnosticOperation = 'ingest' | 'upsertGraph' | 'librarian' | 'heal' | 'ontologyBackfill' | 'reembed' | 'importDump' | 'write' | 'supersede' | 'remember' | 'read' | 'prune';
808
808
  /** `'auto'` when a write threshold started the run (auto-librarian / auto-heal); `'call'` when the host did. */
@@ -3034,7 +3034,8 @@ declare class EventRepository extends BaseRepository {
3034
3034
  * Pass `tx` to participate in a caller-owned transaction; omit to run against the default db.
3035
3035
  */
3036
3036
  add(event: WikiEvent, tx?: SQLiteAdapter): Promise<void>;
3037
- addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<void>;
3037
+ /** Insert unless the id already exists. Returns true when a row was inserted. */
3038
+ addIgnoreDuplicate(event: WikiEvent, tx?: SQLiteAdapter): Promise<boolean>;
3038
3039
  /**
3039
3040
  * Return the most recent events for an entity, newest first.
3040
3041
  * Defaults to a limit of 50.
@@ -3049,7 +3050,7 @@ declare class EventRepository extends BaseRepository {
3049
3050
  * Delete events for an entity that were created at or before the given cutoff timestamp.
3050
3051
  * Returns the number of deleted rows.
3051
3052
  */
3052
- prune(entityId: string, cutoff: number): Promise<{
3053
+ prune(entityId: string, cutoff: number, tx?: SQLiteAdapter): Promise<{
3053
3054
  changes: number;
3054
3055
  }>;
3055
3056
  /**
@@ -3059,7 +3060,7 @@ declare class EventRepository extends BaseRepository {
3059
3060
  * deleted. `wm = null` (no watermark yet) deletes nothing.
3060
3061
  * Used by runPrune under the deferred/ops strategies.
3061
3062
  */
3062
- pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<{
3063
+ pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null, tx?: SQLiteAdapter): Promise<{
3063
3064
  changes: number;
3064
3065
  }>;
3065
3066
  /**
@@ -3068,6 +3069,12 @@ declare class EventRepository extends BaseRepository {
3068
3069
  * events at or before `cutoff` (every one of them is held back).
3069
3070
  */
3070
3071
  countHeldBack(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<number>;
3072
+ /**
3073
+ * The newest `created_at` stored for an entity, or null when it has no
3074
+ * events. `write()` reads it inside its transaction to keep `created_at`
3075
+ * strictly increasing per entity (spec ops-auto-first-batch §5).
3076
+ */
3077
+ latestCreatedAt(entityId: string, tx?: SQLiteAdapter): Promise<number | null>;
3071
3078
  /**
3072
3079
  * Return the total number of events stored for an entity.
3073
3080
  * `tx` is optional — pass an active transaction handle for atomic reads.
@@ -3331,11 +3338,31 @@ declare class MaintenanceService {
3331
3338
  * the op-based librarian (spec §10.3). Never moves backwards.
3332
3339
  */
3333
3340
  private advanceLibrarianWatermark;
3341
+ /**
3342
+ * Anchor the ops watermark before an auto trigger advances
3343
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
3344
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
3345
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
3346
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
3347
+ * event count, already read by the caller in the same transaction. All
3348
+ * reads and the write use the trigger's transaction. Returns the watermark
3349
+ * in force afterwards, so the caller need not read it again.
3350
+ * Package-internal.
3351
+ */
3352
+ anchorWatermarkBeforeTrigger(entityId: string, preCheckpoint: number, total: number, tx: SQLiteAdapter): Promise<LibrarianWatermark>;
3353
+ /**
3354
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
3355
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
3356
+ * nothing and returns null when there is no legacy history or no such
3357
+ * event; each caller picks its own fallback.
3358
+ */
3359
+ private anchorAtLegacyBoundary;
3334
3360
  /**
3335
3361
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
3336
3362
  * checkpoint already covered. No-op when a watermark already exists or the
3337
3363
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
3338
- * offset `min(memory_checkpoint, totalEvents) - 1`.
3364
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
3365
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
3339
3366
  */
3340
3367
  seedLibrarianWatermark(entityId: string): Promise<void>;
3341
3368
  /**
@@ -3445,7 +3472,8 @@ declare class ImportExportService {
3445
3472
  private searchService;
3446
3473
  private jobManager;
3447
3474
  private embeddingService;
3448
- constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService);
3475
+ private options;
3476
+ constructor(db: SQLiteAdapter, entryRepo: EntryRepository, taskRepo: TaskRepository, eventRepo: EventRepository, edgeRepo: EdgeRepository, metadataRepo: MetadataRepository, searchService: SearchService, jobManager: JobManager, embeddingService: EmbeddingService, options?: Pick<WikiOptions, 'onDiagnostic'>);
3449
3477
  exportDump(entityIds?: string[]): Promise<MemoryDump>;
3450
3478
  importDump(dump: MemoryDump, opts?: {
3451
3479
  merge?: boolean;
@@ -1,2 +1,2 @@
1
- export { aH as EmbeddingService, aI as ImportExportService, aJ as IngestionService, aK as JobManager, aK as JobManagerType, aL as MaintenanceService, aM as RetrievalService, aN as SearchService, aN as SearchServiceType, au as WikiMemoryTestAccess, aO as WriteService } from './testing-De-WJ7xh.mjs';
1
+ export { aH as EmbeddingService, aI as ImportExportService, aJ as IngestionService, aK as JobManager, aK as JobManagerType, aL as MaintenanceService, aM as RetrievalService, aN as SearchService, aN as SearchServiceType, au as WikiMemoryTestAccess, aO as WriteService } from './testing-CG8Hw5Ph.mjs';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { aH as EmbeddingService, aI as ImportExportService, aJ as IngestionService, aK as JobManager, aK as JobManagerType, aL as MaintenanceService, aM as RetrievalService, aN as SearchService, aN as SearchServiceType, au as WikiMemoryTestAccess, aO as WriteService } from './testing-De-WJ7xh.js';
1
+ export { aH as EmbeddingService, aI as ImportExportService, aJ as IngestionService, aK as JobManager, aK as JobManagerType, aL as MaintenanceService, aM as RetrievalService, aN as SearchService, aN as SearchServiceType, au as WikiMemoryTestAccess, aO as WriteService } from './testing-CG8Hw5Ph.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -712,7 +712,8 @@ var SEVERITY = {
712
712
  contradicts_document: "warn",
713
713
  resolve_failed: "warn",
714
714
  read_budget: "info",
715
- event_retention_held: "info"
715
+ event_retention_held: "info",
716
+ event_created_at_clamped: "warn"
716
717
  };
717
718
  var MESSAGE = {
718
719
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -734,7 +735,8 @@ var MESSAGE = {
734
735
  contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
735
736
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
736
737
  read_budget: "A read was packed to a token budget.",
737
- event_retention_held: "Event pruning was held back because the librarian has not processed those events yet."
738
+ event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
739
+ event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order."
738
740
  };
739
741
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
740
742
  function copyDetail(detail) {
@@ -1064,11 +1066,49 @@ function typeSatisfies(declaredType, concreteType, manifest) {
1064
1066
  function entitySummaryMetaKey(entityId) {
1065
1067
  return `entity_summary:${entityId}`;
1066
1068
  }
1069
+ var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1070
+
1071
+ // src/services/legacyWatermark.ts
1072
+ async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
1073
+ if (checkpoint <= 0 || total <= 0) return null;
1074
+ const ev = await eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
1075
+ if (!ev) return null;
1076
+ const wm = { at: ev.created_at, id: ev.id };
1077
+ await metadataRepo.setLibrarianWatermark(entityId, wm, db);
1078
+ return wm;
1079
+ }
1080
+ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
1081
+ const existing = await metadataRepo.getLibrarianWatermark(entityId, db);
1082
+ if (existing) return existing;
1083
+ const memory = (await metadataRepo.getCheckpoint(entityId, db)).memory ?? 0;
1084
+ if (memory <= 0) return null;
1085
+ const total = await eventRepo.count(entityId, db);
1086
+ if (memory > total) {
1087
+ await metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, db);
1088
+ return START_OF_LOG_WATERMARK;
1089
+ }
1090
+ return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
1091
+ }
1092
+
1093
+ // src/services/ImportExportService.ts
1067
1094
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1068
1095
  var IMPORT_TITLE_MAX = 500;
1069
1096
  var IMPORT_BODY_MAX = 8e3;
1097
+ var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
1098
+ function createdAtValue(v) {
1099
+ if (typeof v === "number") return v;
1100
+ if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
1101
+ return NaN;
1102
+ }
1103
+ function clampFutureCreatedAt(events, now, floor) {
1104
+ const future = events.map((e) => ({ e, at: createdAtValue(e.created_at) })).filter((x) => x.at > now).sort((x, y) => (x.at === y.at ? 0 : x.at < y.at ? -1 : 1) || (x.e.id < y.e.id ? -1 : x.e.id > y.e.id ? 1 : 0));
1105
+ if (future.length > 0 && floor + future.length > Number.MAX_SAFE_INTEGER) {
1106
+ throw new RangeError(`importDump: cannot re-date ${future.length} future-dated event(s): the floor (${floor}) is too close to Number.MAX_SAFE_INTEGER to keep them ordered.`);
1107
+ }
1108
+ return new Map(future.map((x, i) => [x.e, floor + 1 + i]));
1109
+ }
1070
1110
  var ImportExportService = class {
1071
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService) {
1111
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
1072
1112
  this.db = db;
1073
1113
  this.entryRepo = entryRepo;
1074
1114
  this.taskRepo = taskRepo;
@@ -1078,6 +1118,7 @@ var ImportExportService = class {
1078
1118
  this.searchService = searchService;
1079
1119
  this.jobManager = jobManager;
1080
1120
  this.embeddingService = embeddingService;
1121
+ this.options = options;
1081
1122
  }
1082
1123
  async exportDump(entityIds) {
1083
1124
  let ids;
@@ -1158,6 +1199,7 @@ var ImportExportService = class {
1158
1199
  const preservedBlobDims = /* @__PURE__ */ new Set();
1159
1200
  const softDeletedFactIds = [];
1160
1201
  const clippedTextByFactId = /* @__PURE__ */ new Map();
1202
+ let clampedEvents = 0;
1161
1203
  await this.db.withTransactionAsync(async (tx) => {
1162
1204
  if (!merge) {
1163
1205
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -1378,19 +1420,25 @@ var ImportExportService = class {
1378
1420
  updated_at: safeUpdatedAt
1379
1421
  });
1380
1422
  }
1423
+ const now = Date.now();
1424
+ const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
1425
+ const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
1426
+ const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
1381
1427
  for (const event of bundle.events) {
1382
- await this.eventRepo.addIgnoreDuplicate(
1428
+ const stamped = clampedAt.get(event);
1429
+ const inserted = await this.eventRepo.addIgnoreDuplicate(
1383
1430
  {
1384
1431
  id: event.id,
1385
1432
  entity_id: entityId,
1386
1433
  event_type: event.event_type,
1387
1434
  summary: event.summary,
1388
1435
  related_entry_id: event.related_entry_id ?? null,
1389
- created_at: event.created_at,
1436
+ created_at: stamped ?? event.created_at,
1390
1437
  occurred_at: event.occurred_at ?? null
1391
1438
  },
1392
1439
  tx
1393
1440
  );
1441
+ if (inserted && stamped !== void 0) clampedEvents++;
1394
1442
  }
1395
1443
  for (const edge of bundle.edges ?? []) {
1396
1444
  await this.edgeRepo.addIgnoreDuplicate(
@@ -1406,6 +1454,15 @@ var ImportExportService = class {
1406
1454
  );
1407
1455
  }
1408
1456
  });
1457
+ if (clampedEvents > 0) {
1458
+ emitDiagnostic(this.options, {
1459
+ code: "event_created_at_clamped",
1460
+ operation: "importDump",
1461
+ trigger: "call",
1462
+ entityId,
1463
+ detail: { count: clampedEvents }
1464
+ });
1465
+ }
1409
1466
  if (merge) {
1410
1467
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
1411
1468
  } else {
@@ -4157,16 +4214,29 @@ var MaintenanceService = class {
4157
4214
  if (retainEventsFor !== null) {
4158
4215
  const cutoff = now - retainEventsFor * 864e5;
4159
4216
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
4217
+ let wm = null;
4218
+ await this.db.withTransactionAsync(async (tx) => {
4219
+ if (guarded) {
4220
+ wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
4221
+ deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
4222
+ } else {
4223
+ deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
4224
+ }
4225
+ if (deletedEvents > 0) {
4226
+ const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
4227
+ const updates = {};
4228
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
4229
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
4230
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
4231
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
4232
+ }
4233
+ }
4234
+ });
4160
4235
  if (guarded) {
4161
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
4162
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm)).changes;
4163
4236
  const held = await this.eventRepo.countHeldBack(entityId, cutoff, wm);
4164
4237
  if (held > 0) {
4165
4238
  emitDiagnostic(this.options, { code: "event_retention_held", operation: "prune", trigger: "call", entityId, detail: { count: held } });
4166
4239
  }
4167
- } else {
4168
- const eventResult = await this.eventRepo.prune(entityId, cutoff);
4169
- deletedEvents = eventResult.changes;
4170
4240
  }
4171
4241
  }
4172
4242
  if (vacuum) {
@@ -4479,20 +4549,43 @@ var MaintenanceService = class {
4479
4549
  const newer = !current || next.at > current.at || next.at === current.at && next.id > current.id;
4480
4550
  if (newer) await this.metadataRepo.setLibrarianWatermark(entityId, next, this.db);
4481
4551
  }
4552
+ /**
4553
+ * Anchor the ops watermark before an auto trigger advances
4554
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
4555
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
4556
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
4557
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
4558
+ * event count, already read by the caller in the same transaction. All
4559
+ * reads and the write use the trigger's transaction. Returns the watermark
4560
+ * in force afterwards, so the caller need not read it again.
4561
+ * Package-internal.
4562
+ */
4563
+ async anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) {
4564
+ const existing = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
4565
+ if (existing) return existing;
4566
+ const wm = await this.anchorAtLegacyBoundary(entityId, preCheckpoint, total, tx);
4567
+ if (wm) return wm;
4568
+ await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, tx);
4569
+ return START_OF_LOG_WATERMARK;
4570
+ }
4571
+ /**
4572
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
4573
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
4574
+ * nothing and returns null when there is no legacy history or no such
4575
+ * event; each caller picks its own fallback.
4576
+ */
4577
+ anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
4578
+ return anchorAtLegacyBoundary(this.metadataRepo, this.eventRepo, entityId, checkpoint, total, db);
4579
+ }
4482
4580
  /**
4483
4581
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
4484
4582
  * checkpoint already covered. No-op when a watermark already exists or the
4485
4583
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
4486
- * offset `min(memory_checkpoint, totalEvents) - 1`.
4584
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
4585
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
4487
4586
  */
4488
4587
  async seedLibrarianWatermark(entityId) {
4489
- if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
4490
- const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
4491
- const memory = cp.memory ?? 0;
4492
- if (memory <= 0) return;
4493
- const total = await this.eventRepo.count(entityId);
4494
- const ev = await this.eventRepo.getAtOffset(entityId, Math.min(memory, total) - 1);
4495
- if (ev) await this.metadataRepo.setLibrarianWatermark(entityId, { at: ev.created_at, id: ev.id }, this.db);
4588
+ await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, this.db);
4496
4589
  }
4497
4590
  /**
4498
4591
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -6734,16 +6827,30 @@ var WriteService = class {
6734
6827
  created_at: now,
6735
6828
  occurred_at: occurredAt
6736
6829
  };
6830
+ const stampCreatedAt = async (tx) => {
6831
+ const latest = await this.eventRepo.latestCreatedAt(entityId, tx);
6832
+ if (latest === null || latest < newEvent.created_at) return;
6833
+ if (latest >= Number.MAX_SAFE_INTEGER) {
6834
+ 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.`);
6835
+ }
6836
+ newEvent.created_at = latest + 1;
6837
+ };
6737
6838
  const deferred = resolveMaintenanceMode(this.options.config) === "deferred";
6738
6839
  if (deferred) {
6739
- await this.eventRepo.add(newEvent);
6840
+ await this.db.withTransactionAsync(async (tx) => {
6841
+ await stampCreatedAt(tx);
6842
+ await this.eventRepo.add(newEvent, tx);
6843
+ });
6740
6844
  return;
6741
6845
  }
6742
6846
  let shouldRunLibrarian = false;
6743
6847
  let librarianCount = 0;
6744
6848
  let prevMemoryCheckpoint = 0;
6745
6849
  let eventCount = 0;
6850
+ const isOps = resolveLibrarianStrategy(this.options.config) === "ops";
6851
+ const anchorOps = async (preCheckpoint, total, tx) => isOps ? this.maintenanceService.anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) : this.metadataRepo.getLibrarianWatermark(entityId, tx);
6746
6852
  await this.db.withTransactionAsync(async (tx) => {
6853
+ await stampCreatedAt(tx);
6747
6854
  await this.eventRepo.add(newEvent, tx);
6748
6855
  const threshold = this.options.config?.autoLibrarianThreshold || 20;
6749
6856
  const [count, cp] = await Promise.all([
@@ -6752,18 +6859,19 @@ var WriteService = class {
6752
6859
  ]);
6753
6860
  eventCount = count;
6754
6861
  let memoryCheckpoint = cp.memory ?? 0;
6755
- if (memoryCheckpoint > count) memoryCheckpoint = 0;
6862
+ if (memoryCheckpoint >= count) memoryCheckpoint = 0;
6756
6863
  if (count - memoryCheckpoint >= threshold) {
6757
6864
  if (!this.jobManager.isBlocked("librarian", entityId)) {
6758
6865
  shouldRunLibrarian = true;
6759
6866
  librarianCount = count;
6760
6867
  prevMemoryCheckpoint = memoryCheckpoint;
6868
+ if (isOps) await anchorOps(memoryCheckpoint, count, tx);
6761
6869
  await this.metadataRepo.updateCheckpoint(entityId, { memory: count }, tx);
6762
6870
  }
6763
6871
  } else {
6764
6872
  const tokenThreshold = this.options.config?.autoLibrarianTokenThreshold;
6765
6873
  if (typeof tokenThreshold === "number" && tokenThreshold > 0 && !this.jobManager.isBlocked("librarian", entityId)) {
6766
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
6874
+ const wm = await anchorOps(memoryCheckpoint, count, tx);
6767
6875
  const chars = await this.eventRepo.sumSummaryCharsAfter(entityId, wm, tx);
6768
6876
  if (Math.ceil(chars / 4) >= tokenThreshold) {
6769
6877
  shouldRunLibrarian = true;
@@ -6786,7 +6894,11 @@ var WriteService = class {
6786
6894
  this.track(job);
6787
6895
  } catch (e) {
6788
6896
  if (!(e instanceof WikiBusyError)) throw e;
6789
- await this.metadataRepo.updateCheckpoint(entityId, { memory: prevMemoryCheckpoint }, this.db);
6897
+ const added = librarianCount - prevMemoryCheckpoint;
6898
+ await this.db.withTransactionAsync(async (tx) => {
6899
+ const memory = (await this.metadataRepo.getCheckpoint(entityId, tx)).memory ?? 0;
6900
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: Math.max(0, memory - added) }, tx);
6901
+ });
6790
6902
  }
6791
6903
  } else if (!this.jobManager.isBlocked("librarian", entityId)) {
6792
6904
  const healJob = this.maybeRunHeal(entityId, eventCount).catch((err) => {
@@ -6821,7 +6933,8 @@ var WriteService = class {
6821
6933
  try {
6822
6934
  const result = await this.maintenanceService.doRunHeal(entityId, { trigger: "auto" });
6823
6935
  if (result.remaining === 0) {
6824
- await this.metadataRepo.updateCheckpoint(entityId, { heal: currentEventCount }, this.db);
6936
+ const live = await this.eventRepo.count(entityId, this.db);
6937
+ await this.metadataRepo.updateCheckpoint(entityId, { heal: Math.min(currentEventCount, live) }, this.db);
6825
6938
  }
6826
6939
  } finally {
6827
6940
  this.jobManager.releaseLock("heal", entityId);