@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.
@@ -3049,7 +3049,7 @@ declare class EventRepository extends BaseRepository {
3049
3049
  * Delete events for an entity that were created at or before the given cutoff timestamp.
3050
3050
  * Returns the number of deleted rows.
3051
3051
  */
3052
- prune(entityId: string, cutoff: number): Promise<{
3052
+ prune(entityId: string, cutoff: number, tx?: SQLiteAdapter): Promise<{
3053
3053
  changes: number;
3054
3054
  }>;
3055
3055
  /**
@@ -3059,7 +3059,7 @@ declare class EventRepository extends BaseRepository {
3059
3059
  * deleted. `wm = null` (no watermark yet) deletes nothing.
3060
3060
  * Used by runPrune under the deferred/ops strategies.
3061
3061
  */
3062
- pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<{
3062
+ pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null, tx?: SQLiteAdapter): Promise<{
3063
3063
  changes: number;
3064
3064
  }>;
3065
3065
  /**
@@ -3068,6 +3068,12 @@ declare class EventRepository extends BaseRepository {
3068
3068
  * events at or before `cutoff` (every one of them is held back).
3069
3069
  */
3070
3070
  countHeldBack(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<number>;
3071
+ /**
3072
+ * The newest `created_at` stored for an entity, or null when it has no
3073
+ * events. `write()` reads it inside its transaction to keep `created_at`
3074
+ * strictly increasing per entity (spec ops-auto-first-batch §5).
3075
+ */
3076
+ latestCreatedAt(entityId: string, tx?: SQLiteAdapter): Promise<number | null>;
3071
3077
  /**
3072
3078
  * Return the total number of events stored for an entity.
3073
3079
  * `tx` is optional — pass an active transaction handle for atomic reads.
@@ -3331,11 +3337,31 @@ declare class MaintenanceService {
3331
3337
  * the op-based librarian (spec §10.3). Never moves backwards.
3332
3338
  */
3333
3339
  private advanceLibrarianWatermark;
3340
+ /**
3341
+ * Anchor the ops watermark before an auto trigger advances
3342
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
3343
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
3344
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
3345
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
3346
+ * event count, already read by the caller in the same transaction. All
3347
+ * reads and the write use the trigger's transaction. Returns the watermark
3348
+ * in force afterwards, so the caller need not read it again.
3349
+ * Package-internal.
3350
+ */
3351
+ anchorWatermarkBeforeTrigger(entityId: string, preCheckpoint: number, total: number, tx: SQLiteAdapter): Promise<LibrarianWatermark>;
3352
+ /**
3353
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
3354
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
3355
+ * nothing and returns null when there is no legacy history or no such
3356
+ * event; each caller picks its own fallback.
3357
+ */
3358
+ private anchorAtLegacyBoundary;
3334
3359
  /**
3335
3360
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
3336
3361
  * checkpoint already covered. No-op when a watermark already exists or the
3337
3362
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
3338
- * offset `min(memory_checkpoint, totalEvents) - 1`.
3363
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
3364
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
3339
3365
  */
3340
3366
  seedLibrarianWatermark(entityId: string): Promise<void>;
3341
3367
  /**
@@ -3049,7 +3049,7 @@ declare class EventRepository extends BaseRepository {
3049
3049
  * Delete events for an entity that were created at or before the given cutoff timestamp.
3050
3050
  * Returns the number of deleted rows.
3051
3051
  */
3052
- prune(entityId: string, cutoff: number): Promise<{
3052
+ prune(entityId: string, cutoff: number, tx?: SQLiteAdapter): Promise<{
3053
3053
  changes: number;
3054
3054
  }>;
3055
3055
  /**
@@ -3059,7 +3059,7 @@ declare class EventRepository extends BaseRepository {
3059
3059
  * deleted. `wm = null` (no watermark yet) deletes nothing.
3060
3060
  * Used by runPrune under the deferred/ops strategies.
3061
3061
  */
3062
- pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<{
3062
+ pruneThrough(entityId: string, cutoff: number, wm: LibrarianWatermark | null, tx?: SQLiteAdapter): Promise<{
3063
3063
  changes: number;
3064
3064
  }>;
3065
3065
  /**
@@ -3068,6 +3068,12 @@ declare class EventRepository extends BaseRepository {
3068
3068
  * events at or before `cutoff` (every one of them is held back).
3069
3069
  */
3070
3070
  countHeldBack(entityId: string, cutoff: number, wm: LibrarianWatermark | null): Promise<number>;
3071
+ /**
3072
+ * The newest `created_at` stored for an entity, or null when it has no
3073
+ * events. `write()` reads it inside its transaction to keep `created_at`
3074
+ * strictly increasing per entity (spec ops-auto-first-batch §5).
3075
+ */
3076
+ latestCreatedAt(entityId: string, tx?: SQLiteAdapter): Promise<number | null>;
3071
3077
  /**
3072
3078
  * Return the total number of events stored for an entity.
3073
3079
  * `tx` is optional — pass an active transaction handle for atomic reads.
@@ -3331,11 +3337,31 @@ declare class MaintenanceService {
3331
3337
  * the op-based librarian (spec §10.3). Never moves backwards.
3332
3338
  */
3333
3339
  private advanceLibrarianWatermark;
3340
+ /**
3341
+ * Anchor the ops watermark before an auto trigger advances
3342
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
3343
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
3344
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
3345
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
3346
+ * event count, already read by the caller in the same transaction. All
3347
+ * reads and the write use the trigger's transaction. Returns the watermark
3348
+ * in force afterwards, so the caller need not read it again.
3349
+ * Package-internal.
3350
+ */
3351
+ anchorWatermarkBeforeTrigger(entityId: string, preCheckpoint: number, total: number, tx: SQLiteAdapter): Promise<LibrarianWatermark>;
3352
+ /**
3353
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
3354
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
3355
+ * nothing and returns null when there is no legacy history or no such
3356
+ * event; each caller picks its own fallback.
3357
+ */
3358
+ private anchorAtLegacyBoundary;
3334
3359
  /**
3335
3360
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
3336
3361
  * checkpoint already covered. No-op when a watermark already exists or the
3337
3362
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
3338
- * offset `min(memory_checkpoint, totalEvents) - 1`.
3363
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
3364
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
3339
3365
  */
3340
3366
  seedLibrarianWatermark(entityId: string): Promise<void>;
3341
3367
  /**
@@ -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-BPddGTkl.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-BPddGTkl.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -1064,6 +1064,7 @@ function typeSatisfies(declaredType, concreteType, manifest) {
1064
1064
  function entitySummaryMetaKey(entityId) {
1065
1065
  return `entity_summary:${entityId}`;
1066
1066
  }
1067
+ var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
1067
1068
  var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1068
1069
  var IMPORT_TITLE_MAX = 500;
1069
1070
  var IMPORT_BODY_MAX = 8e3;
@@ -4157,16 +4158,29 @@ var MaintenanceService = class {
4157
4158
  if (retainEventsFor !== null) {
4158
4159
  const cutoff = now - retainEventsFor * 864e5;
4159
4160
  const guarded = resolveMaintenanceMode(this.options.config) === "deferred" || resolveLibrarianStrategy(this.options.config) === "ops";
4161
+ let wm = null;
4162
+ await this.db.withTransactionAsync(async (tx) => {
4163
+ if (guarded) {
4164
+ wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
4165
+ deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm, tx)).changes;
4166
+ } else {
4167
+ deletedEvents = (await this.eventRepo.prune(entityId, cutoff, tx)).changes;
4168
+ }
4169
+ if (deletedEvents > 0) {
4170
+ const cp = await this.metadataRepo.getCheckpoint(entityId, tx);
4171
+ const updates = {};
4172
+ if ((cp.memory ?? 0) > 0) updates.memory = Math.max(0, cp.memory - deletedEvents);
4173
+ if ((cp.heal ?? 0) > 0) updates.heal = Math.max(0, cp.heal - deletedEvents);
4174
+ if (updates.memory !== void 0 || updates.heal !== void 0) {
4175
+ await this.metadataRepo.updateCheckpoint(entityId, updates, tx);
4176
+ }
4177
+ }
4178
+ });
4160
4179
  if (guarded) {
4161
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
4162
- deletedEvents = (await this.eventRepo.pruneThrough(entityId, cutoff, wm)).changes;
4163
4180
  const held = await this.eventRepo.countHeldBack(entityId, cutoff, wm);
4164
4181
  if (held > 0) {
4165
4182
  emitDiagnostic(this.options, { code: "event_retention_held", operation: "prune", trigger: "call", entityId, detail: { count: held } });
4166
4183
  }
4167
- } else {
4168
- const eventResult = await this.eventRepo.prune(entityId, cutoff);
4169
- deletedEvents = eventResult.changes;
4170
4184
  }
4171
4185
  }
4172
4186
  if (vacuum) {
@@ -4479,20 +4493,57 @@ var MaintenanceService = class {
4479
4493
  const newer = !current || next.at > current.at || next.at === current.at && next.id > current.id;
4480
4494
  if (newer) await this.metadataRepo.setLibrarianWatermark(entityId, next, this.db);
4481
4495
  }
4496
+ /**
4497
+ * Anchor the ops watermark before an auto trigger advances
4498
+ * `memory_checkpoint` (spec ops-auto-first-batch §1). No-op when a
4499
+ * watermark exists. With legacy history (`preCheckpoint > 0`) it anchors
4500
+ * where legacy stopped, as {@link seedLibrarianWatermark} does; without
4501
+ * it, it writes {@link START_OF_LOG_WATERMARK}. `total` is the entity's
4502
+ * event count, already read by the caller in the same transaction. All
4503
+ * reads and the write use the trigger's transaction. Returns the watermark
4504
+ * in force afterwards, so the caller need not read it again.
4505
+ * Package-internal.
4506
+ */
4507
+ async anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) {
4508
+ const existing = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
4509
+ if (existing) return existing;
4510
+ const wm = await this.anchorAtLegacyBoundary(entityId, preCheckpoint, total, tx);
4511
+ if (wm) return wm;
4512
+ await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, tx);
4513
+ return START_OF_LOG_WATERMARK;
4514
+ }
4515
+ /**
4516
+ * The one definition of "where legacy stopped" (spec §10.3): anchor the
4517
+ * watermark at the event at offset `min(checkpoint, total) - 1`. Writes
4518
+ * nothing and returns null when there is no legacy history or no such
4519
+ * event; each caller picks its own fallback.
4520
+ */
4521
+ async anchorAtLegacyBoundary(entityId, checkpoint, total, db) {
4522
+ if (checkpoint <= 0 || total <= 0) return null;
4523
+ const ev = await this.eventRepo.getAtOffset(entityId, Math.min(checkpoint, total) - 1, db);
4524
+ if (!ev) return null;
4525
+ const wm = { at: ev.created_at, id: ev.id };
4526
+ await this.metadataRepo.setLibrarianWatermark(entityId, wm, db);
4527
+ return wm;
4528
+ }
4482
4529
  /**
4483
4530
  * Spec §10.3: first ops pass on a legacy DB starts after what the count
4484
4531
  * checkpoint already covered. No-op when a watermark already exists or the
4485
4532
  * memory checkpoint is 0; otherwise anchor the watermark to the event at
4486
- * offset `min(memory_checkpoint, totalEvents) - 1`.
4533
+ * offset `memory_checkpoint - 1`. A checkpoint above the event count is
4534
+ * drift and gets {@link START_OF_LOG_WATERMARK} (spec ops-auto-first-batch §2).
4487
4535
  */
4488
4536
  async seedLibrarianWatermark(entityId) {
4489
4537
  if (await this.metadataRepo.getLibrarianWatermark(entityId, this.db)) return;
4490
4538
  const cp = await this.metadataRepo.getCheckpoint(entityId, this.db);
4491
4539
  const memory = cp.memory ?? 0;
4492
4540
  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);
4541
+ const total = await this.eventRepo.count(entityId, this.db);
4542
+ if (memory > total) {
4543
+ await this.metadataRepo.setLibrarianWatermark(entityId, START_OF_LOG_WATERMARK, this.db);
4544
+ return;
4545
+ }
4546
+ await this.anchorAtLegacyBoundary(entityId, memory, total, this.db);
4496
4547
  }
4497
4548
  /**
4498
4549
  * Core heal pass (locks handled by {@link runHeal}). Package-internal orchestration hook.
@@ -6734,16 +6785,30 @@ var WriteService = class {
6734
6785
  created_at: now,
6735
6786
  occurred_at: occurredAt
6736
6787
  };
6788
+ const stampCreatedAt = async (tx) => {
6789
+ const latest = await this.eventRepo.latestCreatedAt(entityId, tx);
6790
+ if (latest === null || latest < newEvent.created_at) return;
6791
+ if (latest >= Number.MAX_SAFE_INTEGER) {
6792
+ 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.`);
6793
+ }
6794
+ newEvent.created_at = latest + 1;
6795
+ };
6737
6796
  const deferred = resolveMaintenanceMode(this.options.config) === "deferred";
6738
6797
  if (deferred) {
6739
- await this.eventRepo.add(newEvent);
6798
+ await this.db.withTransactionAsync(async (tx) => {
6799
+ await stampCreatedAt(tx);
6800
+ await this.eventRepo.add(newEvent, tx);
6801
+ });
6740
6802
  return;
6741
6803
  }
6742
6804
  let shouldRunLibrarian = false;
6743
6805
  let librarianCount = 0;
6744
6806
  let prevMemoryCheckpoint = 0;
6745
6807
  let eventCount = 0;
6808
+ const isOps = resolveLibrarianStrategy(this.options.config) === "ops";
6809
+ const anchorOps = async (preCheckpoint, total, tx) => isOps ? this.maintenanceService.anchorWatermarkBeforeTrigger(entityId, preCheckpoint, total, tx) : this.metadataRepo.getLibrarianWatermark(entityId, tx);
6746
6810
  await this.db.withTransactionAsync(async (tx) => {
6811
+ await stampCreatedAt(tx);
6747
6812
  await this.eventRepo.add(newEvent, tx);
6748
6813
  const threshold = this.options.config?.autoLibrarianThreshold || 20;
6749
6814
  const [count, cp] = await Promise.all([
@@ -6752,18 +6817,19 @@ var WriteService = class {
6752
6817
  ]);
6753
6818
  eventCount = count;
6754
6819
  let memoryCheckpoint = cp.memory ?? 0;
6755
- if (memoryCheckpoint > count) memoryCheckpoint = 0;
6820
+ if (memoryCheckpoint >= count) memoryCheckpoint = 0;
6756
6821
  if (count - memoryCheckpoint >= threshold) {
6757
6822
  if (!this.jobManager.isBlocked("librarian", entityId)) {
6758
6823
  shouldRunLibrarian = true;
6759
6824
  librarianCount = count;
6760
6825
  prevMemoryCheckpoint = memoryCheckpoint;
6826
+ if (isOps) await anchorOps(memoryCheckpoint, count, tx);
6761
6827
  await this.metadataRepo.updateCheckpoint(entityId, { memory: count }, tx);
6762
6828
  }
6763
6829
  } else {
6764
6830
  const tokenThreshold = this.options.config?.autoLibrarianTokenThreshold;
6765
6831
  if (typeof tokenThreshold === "number" && tokenThreshold > 0 && !this.jobManager.isBlocked("librarian", entityId)) {
6766
- const wm = await this.metadataRepo.getLibrarianWatermark(entityId, tx);
6832
+ const wm = await anchorOps(memoryCheckpoint, count, tx);
6767
6833
  const chars = await this.eventRepo.sumSummaryCharsAfter(entityId, wm, tx);
6768
6834
  if (Math.ceil(chars / 4) >= tokenThreshold) {
6769
6835
  shouldRunLibrarian = true;
@@ -6786,7 +6852,11 @@ var WriteService = class {
6786
6852
  this.track(job);
6787
6853
  } catch (e) {
6788
6854
  if (!(e instanceof WikiBusyError)) throw e;
6789
- await this.metadataRepo.updateCheckpoint(entityId, { memory: prevMemoryCheckpoint }, this.db);
6855
+ const added = librarianCount - prevMemoryCheckpoint;
6856
+ await this.db.withTransactionAsync(async (tx) => {
6857
+ const memory = (await this.metadataRepo.getCheckpoint(entityId, tx)).memory ?? 0;
6858
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: Math.max(0, memory - added) }, tx);
6859
+ });
6790
6860
  }
6791
6861
  } else if (!this.jobManager.isBlocked("librarian", entityId)) {
6792
6862
  const healJob = this.maybeRunHeal(entityId, eventCount).catch((err) => {
@@ -6821,7 +6891,8 @@ var WriteService = class {
6821
6891
  try {
6822
6892
  const result = await this.maintenanceService.doRunHeal(entityId, { trigger: "auto" });
6823
6893
  if (result.remaining === 0) {
6824
- await this.metadataRepo.updateCheckpoint(entityId, { heal: currentEventCount }, this.db);
6894
+ const live = await this.eventRepo.count(entityId, this.db);
6895
+ await this.metadataRepo.updateCheckpoint(entityId, { heal: Math.min(currentEventCount, live) }, this.db);
6825
6896
  }
6826
6897
  } finally {
6827
6898
  this.jobManager.releaseLock("heal", entityId);