@equationalapplications/core-llm-wiki 8.1.0 → 8.3.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/README.md CHANGED
@@ -19,7 +19,7 @@ Platform-agnostic TypeScript engine for hybrid LLM memory. Features episodic fac
19
19
  - **Hybrid retrieval.** Vector cosine ranking with a keyword fallback (SQLite FTS5 or in-memory MiniSearch), [tunable](https://equationalapplications.github.io/expo-llm-wiki/guides/tune-retrieval/) per call.
20
20
  - **Multi-entity reads.** Search several namespaces in one pass with `tierWeights` and `tierFloors`.
21
21
  - **GraphRAG.** Per-entity [seeded ontologies](https://equationalapplications.github.io/expo-llm-wiki/guides/ontologies/) (Strict, Emergent or Off) and SQL-only [graph traversal](https://equationalapplications.github.io/expo-llm-wiki/guides/graphrag/).
22
- - **Background maintenance.** Librarian, heal, reembed and prune jobs, run inline or [deferred](https://equationalapplications.github.io/expo-llm-wiki/guides/maintenance/).
22
+ - **Maintenance.** Librarian, heal, reembed and prune jobs. By default you run them on your own schedule ([deferred](https://equationalapplications.github.io/expo-llm-wiki/guides/maintenance/)), or set `maintenance: 'auto'` to have `write()` start the librarian and heal (reembed and prune stay on your schedule).
23
23
  - **Temporal facts, drafts and grounding** for [trust and provenance](https://equationalapplications.github.io/expo-llm-wiki/concepts/trust-and-provenance/).
24
24
  - **OKF v0.1 and v0.2** [import and export](https://equationalapplications.github.io/expo-llm-wiki/guides/okf/).
25
25
  - **Diagnostics.** An optional `onDiagnostic` hook with typed, content-free reports.
@@ -2181,7 +2181,8 @@ var SEVERITY = {
2181
2181
  resolve_failed: "warn",
2182
2182
  read_budget: "info",
2183
2183
  event_retention_held: "info",
2184
- event_created_at_clamped: "warn"
2184
+ event_created_at_clamped: "warn",
2185
+ event_created_at_restamped: "info"
2185
2186
  };
2186
2187
  var MESSAGE = {
2187
2188
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2204,7 +2205,8 @@ var MESSAGE = {
2204
2205
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
2205
2206
  read_budget: "A read was packed to a token budget.",
2206
2207
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
2207
- 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."
2208
+ 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.",
2209
+ event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared."
2208
2210
  };
2209
2211
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2210
2212
  function copyDetail(detail) {
@@ -3107,6 +3109,201 @@ var BaseRepository = class {
3107
3109
  }
3108
3110
  };
3109
3111
 
3112
+ // src/utils/temporal.ts
3113
+ function liveAtSql(mode, alias = "") {
3114
+ const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
3115
+ return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
3116
+ }
3117
+ function isLiveAt(f, mode, t) {
3118
+ if (f.deleted_at != null) return false;
3119
+ const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
3120
+ if (from != null && from > t) return false;
3121
+ return f.valid_to == null || f.valid_to > t;
3122
+ }
3123
+ function assertEpochMs(name, v) {
3124
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3125
+ throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3126
+ }
3127
+ return Math.trunc(v);
3128
+ }
3129
+
3130
+ // src/repositories/EdgeRepository.ts
3131
+ var CONFIDENCE_RANK = {
3132
+ tentative: 0,
3133
+ inferred: 1,
3134
+ certain: 2
3135
+ };
3136
+ var EdgeRepository = class extends BaseRepository {
3137
+ /**
3138
+ * Insert an edge, silently skipping on primary-key or uniqueness conflicts.
3139
+ * Returns true when a row was inserted, false when skipped as a duplicate.
3140
+ * Throws when the insert was skipped due to an id collision with a different edge tuple.
3141
+ */
3142
+ async addIgnoreDuplicate(edge, tx) {
3143
+ const executor = this.getExecutor(tx);
3144
+ const result = await executor.runAsync(
3145
+ `INSERT OR IGNORE INTO ${this.prefix}edges (id, entity_id, source_id, target_id, edge_type, created_at)
3146
+ VALUES (?, ?, ?, ?, ?, ?)`,
3147
+ [edge.id, edge.entity_id, edge.source_id, edge.target_id, edge.edge_type, edge.created_at]
3148
+ );
3149
+ if (result.changes > 0) return true;
3150
+ const existing = await executor.getFirstAsync(
3151
+ `SELECT entity_id, source_id, target_id, edge_type FROM ${this.prefix}edges WHERE id = ?`,
3152
+ [edge.id]
3153
+ );
3154
+ if (!existing) return false;
3155
+ if (String(existing.entity_id) !== edge.entity_id || String(existing.source_id) !== edge.source_id || String(existing.target_id) !== edge.target_id || String(existing.edge_type) !== edge.edge_type) {
3156
+ throw new Error(
3157
+ `Edge id collision: ${JSON.stringify(edge.id)} already exists with a different (entity_id, source_id, target_id, edge_type) tuple`
3158
+ );
3159
+ }
3160
+ return false;
3161
+ }
3162
+ async getByEntityId(entityId, tx) {
3163
+ const executor = this.getExecutor(tx);
3164
+ const rows = await executor.getAllAsync(
3165
+ `SELECT * FROM ${this.prefix}edges WHERE entity_id = ? ORDER BY created_at ASC`,
3166
+ [entityId]
3167
+ );
3168
+ return rows.map(mapRowToEdge);
3169
+ }
3170
+ /** Hard delete — edges have no soft-delete concept, only presence/absence. `tx` is REQUIRED. */
3171
+ async bulkDeleteByEntityId(entityId, tx) {
3172
+ const executor = this.getExecutor(tx);
3173
+ await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);
3174
+ }
3175
+ /**
3176
+ * Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to
3177
+ * `entityId`. Returns the number of rows deleted. Edges have no soft-delete
3178
+ * concept; this method is named `softDeleteBySourceFactIds` for symmetry with
3179
+ * `EntryRepository.softDeleteBySource` (which IS a soft delete), but its
3180
+ * semantics are immediate presence/absence removal. Use ONLY inside an open
3181
+ * transaction — the method requires `tx` and performs no autocommit.
3182
+ *
3183
+ * Used by `IngestionService.upsertGraphCore` to retire the prior parse's
3184
+ * edges whose source facts are being superseded by `softDeleteBySource`.
3185
+ */
3186
+ async softDeleteBySourceFactIds(entityId, sourceFactIds, tx) {
3187
+ if (sourceFactIds.length === 0) return 0;
3188
+ const executor = this.getExecutor(tx);
3189
+ const chunkSize = 500;
3190
+ let totalChanges = 0;
3191
+ for (let i = 0; i < sourceFactIds.length; i += chunkSize) {
3192
+ const chunk = sourceFactIds.slice(i, i + chunkSize);
3193
+ const placeholders = chunk.map(() => "?").join(",");
3194
+ const result = await executor.runAsync(
3195
+ `DELETE FROM ${this.prefix}edges
3196
+ WHERE entity_id = ? AND source_id IN (${placeholders})`,
3197
+ [entityId, ...chunk]
3198
+ );
3199
+ totalChanges += result.changes;
3200
+ }
3201
+ return totalChanges;
3202
+ }
3203
+ /**
3204
+ * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
3205
+ * dead-ending, cycle-guarding, capping, and ordering happens in this one query.
3206
+ * The anchor is validated (exists, right entity, not soft-deleted) but never gated
3207
+ * by confidence/source_type — only nodes discovered beyond it are.
3208
+ */
3209
+ async getNeighborhood(entityId, sourceId, opts, tx) {
3210
+ const executor = this.getExecutor(tx);
3211
+ if (opts.edgeTypes && opts.edgeTypes.length === 0) {
3212
+ const anchor = await executor.getFirstAsync(
3213
+ `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
3214
+ [sourceId, entityId]
3215
+ );
3216
+ return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
3217
+ }
3218
+ const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
3219
+ const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
3220
+ const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
3221
+ const sql = `
3222
+ WITH RECURSIVE walk(node_id, depth, visited) AS (
3223
+ SELECT id, 0, ',' || id || ','
3224
+ FROM ${this.prefix}entries
3225
+ WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
3226
+
3227
+ UNION
3228
+
3229
+ SELECT
3230
+ CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
3231
+ w.depth + 1,
3232
+ w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
3233
+ FROM walk w
3234
+ JOIN ${this.prefix}edges e
3235
+ ON e.entity_id = ?
3236
+ AND (
3237
+ (? != 'inbound' AND e.source_id = w.node_id) OR
3238
+ (? != 'outbound' AND e.target_id = w.node_id)
3239
+ )
3240
+ AND (${edgeTypesClause})
3241
+ JOIN ${this.prefix}entries n
3242
+ ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
3243
+ AND n.entity_id = ?
3244
+ AND n.deleted_at IS NULL
3245
+ AND (
3246
+ CASE n.confidence
3247
+ WHEN 'tentative' THEN 0
3248
+ WHEN 'inferred' THEN 1
3249
+ WHEN 'certain' THEN 2
3250
+ ELSE -1
3251
+ END
3252
+ ) >= ?
3253
+ AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
3254
+ AND (? = 0 OR n.lifecycle_status != 'draft')
3255
+ AND ${liveAtSql(opts.live.mode, "n.")}
3256
+ WHERE w.depth < ?
3257
+ AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
3258
+ )
3259
+ SELECT node_id, MIN(depth) AS depth
3260
+ FROM walk
3261
+ GROUP BY node_id
3262
+ ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
3263
+ LIMIT ?
3264
+ `;
3265
+ const params = [
3266
+ sourceId,
3267
+ entityId,
3268
+ entityId,
3269
+ opts.direction,
3270
+ opts.direction,
3271
+ ...opts.edgeTypes ?? [],
3272
+ entityId,
3273
+ minConfidenceRank,
3274
+ ...opts.excludeSourceTypes,
3275
+ opts.excludeDrafts === true ? 1 : 0,
3276
+ opts.live.t,
3277
+ opts.live.t,
3278
+ opts.maxDepth,
3279
+ opts.maxNodes
3280
+ ];
3281
+ const rows = await executor.getAllAsync(sql, params);
3282
+ const nodeIds = rows.map((r) => r.node_id);
3283
+ if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
3284
+ const valueRows = nodeIds.map(() => "(?)").join(", ");
3285
+ const edgeRows = await executor.getAllAsync(
3286
+ `WITH neighborhood(node_id) AS (VALUES ${valueRows})
3287
+ SELECT e.* FROM ${this.prefix}edges e
3288
+ JOIN neighborhood ns ON e.source_id = ns.node_id
3289
+ JOIN neighborhood nt ON e.target_id = nt.node_id
3290
+ WHERE e.entity_id = ?`,
3291
+ [...nodeIds, entityId]
3292
+ );
3293
+ return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
3294
+ }
3295
+ };
3296
+ function mapRowToEdge(row) {
3297
+ return {
3298
+ id: String(row.id),
3299
+ entity_id: String(row.entity_id),
3300
+ source_id: String(row.source_id),
3301
+ target_id: String(row.target_id),
3302
+ edge_type: String(row.edge_type),
3303
+ created_at: Number(row.created_at)
3304
+ };
3305
+ }
3306
+
3110
3307
  // src/repositories/MetadataRepository.ts
3111
3308
  function entitySummaryMetaKey(entityId) {
3112
3309
  return `entity_summary:${entityId}`;
@@ -4470,7 +4667,9 @@ async function runExtract(deps, ctx, batch) {
4470
4667
  const base = { entityId, operation: "librarian", trigger };
4471
4668
  const diagnostics = [];
4472
4669
  const byLabel = new Map(batch.map((l) => [l.label, l]));
4473
- const newestAt = batch[batch.length - 1].at;
4670
+ let newestAt = batch[0].at;
4671
+ for (const l of batch) if (l.at > newestAt) newestAt = l.at;
4672
+ const defaultValidFrom = Math.min(newestAt, Date.now());
4474
4673
  const candidates = [];
4475
4674
  (Array.isArray(parsed.facts) ? parsed.facts : []).forEach((raw, index) => {
4476
4675
  const fact = validateFact(raw);
@@ -4480,7 +4679,7 @@ async function runExtract(deps, ctx, batch) {
4480
4679
  }
4481
4680
  const r = raw;
4482
4681
  const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
4483
- const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : newestAt);
4682
+ const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
4484
4683
  candidates.push({ index, fact, sourceLabel, validFrom });
4485
4684
  });
4486
4685
  const tasks = [];
@@ -4669,24 +4868,6 @@ async function runResolve(deps, ctx, ambiguous) {
4669
4868
  return out;
4670
4869
  }
4671
4870
 
4672
- // src/utils/temporal.ts
4673
- function liveAtSql(mode, alias = "") {
4674
- const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
4675
- return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
4676
- }
4677
- function isLiveAt(f, mode, t) {
4678
- if (f.deleted_at != null) return false;
4679
- const from = mode === "asOf" ? f.valid_from ?? f.created_at : f.valid_from;
4680
- if (from != null && from > t) return false;
4681
- return f.valid_to == null || f.valid_to > t;
4682
- }
4683
- function assertEpochMs(name, v) {
4684
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
4685
- throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
4686
- }
4687
- return Math.trunc(v);
4688
- }
4689
-
4690
4871
  // src/services/TemporalService.ts
4691
4872
  var HISTORY_MAX_DEPTH = 100;
4692
4873
  var TemporalService = class {
@@ -5068,7 +5249,7 @@ var formatSkipError = (err) => {
5068
5249
  return base;
5069
5250
  };
5070
5251
  var MaintenanceService = class {
5071
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
5252
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
5072
5253
  this.db = db;
5073
5254
  this.prefix = prefix;
5074
5255
  this.options = options;
@@ -5082,6 +5263,7 @@ var MaintenanceService = class {
5082
5263
  this.embeddingService = embeddingService;
5083
5264
  this.ontologyService = ontologyService;
5084
5265
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
5266
+ this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
5085
5267
  }
5086
5268
  async runPrune(entityId, options) {
5087
5269
  this.jobManager.acquireLock("prune", entityId);
@@ -5312,6 +5494,9 @@ var MaintenanceService = class {
5312
5494
  if (params.clearAll && (params.entryId !== void 0 || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
5313
5495
  throw new Error("forget() clearAll is mutually exclusive with entryId, taskId, sourceRef, and sourceHash");
5314
5496
  }
5497
+ if (params.includeEvents && !params.clearAll) {
5498
+ throw new Error("forget() includeEvents requires clearAll: true");
5499
+ }
5315
5500
  if (opts?.dryRun === true) {
5316
5501
  return this.forgetDryRun(entityId, params);
5317
5502
  }
@@ -5320,13 +5505,23 @@ var MaintenanceService = class {
5320
5505
  const now = Date.now();
5321
5506
  let deletedEntries = 0;
5322
5507
  let deletedTasks = 0;
5508
+ let deletedEvents = 0;
5323
5509
  const deletedEntryIds = [];
5324
5510
  await this.db.withTransactionAsync(async (tx) => {
5325
5511
  if (params.clearAll) {
5326
- deletedEntryIds.push(...await this.entryRepo.findIdsBySource(entityId, null, null, tx, true));
5512
+ for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
5327
5513
  deletedEntries = await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
5328
5514
  deletedTasks = await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
5329
- await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
5515
+ if (await this.sourceRefIndexPresent(tx)) {
5516
+ await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
5517
+ }
5518
+ await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
5519
+ if (params.includeEvents) {
5520
+ deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
5521
+ await this.metadataRepo.deleteCheckpoint(entityId, tx);
5522
+ } else {
5523
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
5524
+ }
5330
5525
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
5331
5526
  } else {
5332
5527
  const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
@@ -5344,7 +5539,7 @@ var MaintenanceService = class {
5344
5539
  if (entryId) deletedEntryIds.push(entryId);
5345
5540
  }
5346
5541
  if (sourceRef || sourceHash) {
5347
- deletedEntryIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true));
5542
+ for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
5348
5543
  }
5349
5544
  const entryPromise = params.entryId ? this.entryRepo.softDelete(params.entryId, entityId, tx).then((r) => r.changes > 0) : null;
5350
5545
  const taskDeletedPromise = params.taskId ? this.taskRepo.softDeleteById(params.taskId, entityId, tx).then((r) => r.changes > 0) : null;
@@ -5378,7 +5573,8 @@ var MaintenanceService = class {
5378
5573
  throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
5379
5574
  }
5380
5575
  }
5381
- return params.clearAll ? { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks } };
5576
+ if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
5577
+ return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
5382
5578
  } finally {
5383
5579
  this.jobManager.releaseLock("forget", entityId);
5384
5580
  }
@@ -5429,6 +5625,10 @@ var MaintenanceService = class {
5429
5625
  if (params.clearAll) {
5430
5626
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
5431
5627
  const tasks = await this.taskRepo.countLiveByEntityId(entityId);
5628
+ if (params.includeEvents) {
5629
+ const events = await this.eventRepo.count(entityId);
5630
+ return { deleted: { entries: entries2, tasks, events }, metadataReset: true };
5631
+ }
5432
5632
  return { deleted: { entries: entries2, tasks }, metadataReset: true };
5433
5633
  }
5434
5634
  const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
@@ -6142,22 +6342,68 @@ var MaintenanceService = class {
6142
6342
  return sanitizeRankerError(err, this.options.sanitizeRankerErrors);
6143
6343
  }
6144
6344
  };
6145
- var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6146
- var IMPORT_TITLE_MAX = 500;
6147
- var IMPORT_BODY_MAX = 8e3;
6345
+
6346
+ // src/services/importEventStamps.ts
6347
+ var DATE_MAX = 864e13;
6148
6348
  var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
6149
6349
  function createdAtValue(v) {
6150
6350
  if (typeof v === "number") return v;
6151
6351
  if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
6152
6352
  return NaN;
6153
6353
  }
6154
- function clampFutureCreatedAt(events, now, floor) {
6155
- 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));
6156
- if (future.length > 0 && floor + future.length > Number.MAX_SAFE_INTEGER) {
6157
- 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.`);
6158
- }
6159
- return new Map(future.map((x, i) => [x.e, floor + 1 + i]));
6354
+ function isUsableDate(v) {
6355
+ return Number.isFinite(v) && v >= -DATE_MAX && v <= DATE_MAX;
6356
+ }
6357
+ function parseSourceWatermark(raw) {
6358
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
6359
+ const { at, id } = raw;
6360
+ if (typeof at !== "number" || !Number.isFinite(at) || typeof id !== "string") return null;
6361
+ return { at, id };
6362
+ }
6363
+ var cmp = (a, b) => a === b ? 0 : a < b ? -1 : 1;
6364
+ function planEventStamps(events, ctx) {
6365
+ const { now, floor, merge, localWm, sourceWm } = ctx;
6366
+ const after = (v, id, wm) => v > wm.at || v === wm.at && id > wm.id;
6367
+ const plan = /* @__PURE__ */ new Map();
6368
+ const restamp = [];
6369
+ for (const e of events) {
6370
+ const v = createdAtValue(e.created_at);
6371
+ const o = createdAtValue(e.occurred_at);
6372
+ let occurredAt = null;
6373
+ let occurredInvalid = false;
6374
+ if (e.occurred_at != null) {
6375
+ if (isUsableDate(o)) occurredAt = Math.trunc(o);
6376
+ else occurredInvalid = true;
6377
+ }
6378
+ let reason = null;
6379
+ const invalidCreated = Number.isNaN(v) || v < -DATE_MAX;
6380
+ if (invalidCreated) reason = "invalid";
6381
+ else if (v > now) reason = "future";
6382
+ else if (merge && localWm !== null && Number.isFinite(localWm.at) && !after(v, e.id, localWm) && (sourceWm === null || after(v, e.id, sourceWm))) {
6383
+ reason = "behind_watermark";
6384
+ }
6385
+ if (reason === "behind_watermark" && occurredAt === null && Number.isFinite(v) && v >= 0) {
6386
+ occurredAt = Math.trunc(v);
6387
+ }
6388
+ const stamp = { createdAt: v, occurredAt, reason };
6389
+ if (reason === null && occurredInvalid) stamp.reason = "invalid";
6390
+ plan.set(e, stamp);
6391
+ if (reason !== null) restamp.push({ e, key: invalidCreated ? -Infinity : v, stamp });
6392
+ }
6393
+ restamp.sort((x, y) => cmp(x.key, y.key) || cmp(x.e.id, y.e.id));
6394
+ if (restamp.length > 0 && floor + restamp.length > Number.MAX_SAFE_INTEGER) {
6395
+ throw new RangeError(`importDump: cannot re-date ${restamp.length} event(s): the floor (${floor}) is too close to Number.MAX_SAFE_INTEGER to keep them ordered.`);
6396
+ }
6397
+ restamp.forEach((x, i) => {
6398
+ x.stamp.createdAt = floor + 1 + i;
6399
+ });
6400
+ return plan;
6160
6401
  }
6402
+
6403
+ // src/services/ImportExportService.ts
6404
+ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
6405
+ var IMPORT_TITLE_MAX = 500;
6406
+ var IMPORT_BODY_MAX = 8e3;
6161
6407
  var ImportExportService = class {
6162
6408
  constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
6163
6409
  this.db = db;
@@ -6210,6 +6456,7 @@ var ImportExportService = class {
6210
6456
  }
6211
6457
  }
6212
6458
  async getFullBundle(entityId, opts) {
6459
+ const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
6213
6460
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
6214
6461
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
6215
6462
  this.taskRepo.findAllByEntityId(entityId),
@@ -6239,7 +6486,8 @@ var ImportExportService = class {
6239
6486
  tasks,
6240
6487
  events,
6241
6488
  edges,
6242
- ...summaryValue != null ? { summary: summaryValue } : {}
6489
+ ...summaryValue != null ? { summary: summaryValue } : {},
6490
+ ...wm ? { librarian_watermark: wm } : {}
6243
6491
  };
6244
6492
  }
6245
6493
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
@@ -6251,6 +6499,7 @@ var ImportExportService = class {
6251
6499
  const softDeletedFactIds = [];
6252
6500
  const clippedTextByFactId = /* @__PURE__ */ new Map();
6253
6501
  let clampedEvents = 0;
6502
+ const restamped = { behind_watermark: 0, invalid: 0 };
6254
6503
  await this.db.withTransactionAsync(async (tx) => {
6255
6504
  if (!merge) {
6256
6505
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -6474,9 +6723,9 @@ var ImportExportService = class {
6474
6723
  const now = Date.now();
6475
6724
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
6476
6725
  const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
6477
- const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
6726
+ const planned = planEventStamps(bundle.events, { now, floor, merge, localWm: wm, sourceWm: parseSourceWatermark(bundle.librarian_watermark) });
6478
6727
  for (const event of bundle.events) {
6479
- const stamped = clampedAt.get(event);
6728
+ const stamp = planned.get(event);
6480
6729
  const inserted = await this.eventRepo.addIgnoreDuplicate(
6481
6730
  {
6482
6731
  id: event.id,
@@ -6484,12 +6733,14 @@ var ImportExportService = class {
6484
6733
  event_type: event.event_type,
6485
6734
  summary: event.summary,
6486
6735
  related_entry_id: event.related_entry_id ?? null,
6487
- created_at: stamped ?? event.created_at,
6488
- occurred_at: event.occurred_at ?? null
6736
+ created_at: stamp.createdAt,
6737
+ occurred_at: stamp.occurredAt
6489
6738
  },
6490
6739
  tx
6491
6740
  );
6492
- if (inserted && stamped !== void 0) clampedEvents++;
6741
+ if (!inserted || stamp.reason === null) continue;
6742
+ if (stamp.reason === "future") clampedEvents++;
6743
+ else restamped[stamp.reason]++;
6493
6744
  }
6494
6745
  for (const edge of bundle.edges ?? []) {
6495
6746
  await this.edgeRepo.addIgnoreDuplicate(
@@ -6514,6 +6765,17 @@ var ImportExportService = class {
6514
6765
  detail: { count: clampedEvents }
6515
6766
  });
6516
6767
  }
6768
+ for (const reason of ["behind_watermark", "invalid"]) {
6769
+ if (restamped[reason] > 0) {
6770
+ emitDiagnostic(this.options, {
6771
+ code: "event_created_at_restamped",
6772
+ operation: "importDump",
6773
+ trigger: "call",
6774
+ entityId,
6775
+ detail: { count: restamped[reason], reason }
6776
+ });
6777
+ }
6778
+ }
6517
6779
  if (merge) {
6518
6780
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
6519
6781
  } else {
@@ -6530,7 +6792,19 @@ var ImportExportService = class {
6530
6792
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
6531
6793
  }, { operation: "importDump", trigger: "call" });
6532
6794
  if (!embedded) {
6533
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
6795
+ try {
6796
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
6797
+ } catch (hookErr) {
6798
+ console.warn(
6799
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
6800
+ hookErr
6801
+ );
6802
+ this.embeddingService.reportHookFailed(
6803
+ { operation: "importDump", trigger: "call" },
6804
+ entityId,
6805
+ fact.id
6806
+ );
6807
+ }
6534
6808
  }
6535
6809
  }
6536
6810
  }
@@ -7290,7 +7564,7 @@ var RetrievalService = class {
7290
7564
  if (topK.length < maxBackfill) {
7291
7565
  let insertIdx = topK.length;
7292
7566
  for (let i = 0; i < topK.length; i++) {
7293
- const cmp = this._compareScoredRows(
7567
+ const cmp2 = this._compareScoredRows(
7294
7568
  {
7295
7569
  id: candidate.row.id,
7296
7570
  score: candidate.kwScore,
@@ -7304,7 +7578,7 @@ var RetrievalService = class {
7304
7578
  access_count: topK[i].row.access_count
7305
7579
  }
7306
7580
  );
7307
- if (cmp < 0) {
7581
+ if (cmp2 < 0) {
7308
7582
  insertIdx = i;
7309
7583
  break;
7310
7584
  }
@@ -7328,7 +7602,7 @@ var RetrievalService = class {
7328
7602
  if (cmpWorst < 0) {
7329
7603
  let insertIdx = maxBackfill - 1;
7330
7604
  for (let i = 0; i < topK.length; i++) {
7331
- const cmp = this._compareScoredRows(
7605
+ const cmp2 = this._compareScoredRows(
7332
7606
  {
7333
7607
  id: candidate.row.id,
7334
7608
  score: candidate.kwScore,
@@ -7342,7 +7616,7 @@ var RetrievalService = class {
7342
7616
  access_count: topK[i].row.access_count
7343
7617
  }
7344
7618
  );
7345
- if (cmp < 0) {
7619
+ if (cmp2 < 0) {
7346
7620
  insertIdx = i;
7347
7621
  break;
7348
7622
  }
@@ -7855,6 +8129,6 @@ var WriteService = class {
7855
8129
  }
7856
8130
  };
7857
8131
 
7858
- export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
7859
- //# sourceMappingURL=chunk-UJSUPVPH.mjs.map
7860
- //# sourceMappingURL=chunk-UJSUPVPH.mjs.map
8132
+ export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
8133
+ //# sourceMappingURL=chunk-V432RHCG.mjs.map
8134
+ //# sourceMappingURL=chunk-V432RHCG.mjs.map