@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/dist/testing.js CHANGED
@@ -713,7 +713,8 @@ var SEVERITY = {
713
713
  resolve_failed: "warn",
714
714
  read_budget: "info",
715
715
  event_retention_held: "info",
716
- event_created_at_clamped: "warn"
716
+ event_created_at_clamped: "warn",
717
+ event_created_at_restamped: "info"
717
718
  };
718
719
  var MESSAGE = {
719
720
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -736,7 +737,8 @@ var MESSAGE = {
736
737
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
737
738
  read_budget: "A read was packed to a token budget.",
738
739
  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."
740
+ 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.",
741
+ 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."
740
742
  };
741
743
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
742
744
  function copyDetail(detail) {
@@ -1046,6 +1048,21 @@ var EmbeddingService = class {
1046
1048
  }
1047
1049
  };
1048
1050
 
1051
+ // src/repositories/BaseRepository.ts
1052
+ var BaseRepository = class {
1053
+ constructor(db, prefix) {
1054
+ this.db = db;
1055
+ this.prefix = prefix;
1056
+ }
1057
+ /**
1058
+ * Return the DB executor for a given transaction handle.
1059
+ * If tx is provided, use it; otherwise fall back to this.db.
1060
+ */
1061
+ getExecutor(tx) {
1062
+ return tx ?? this.db;
1063
+ }
1064
+ };
1065
+
1049
1066
  // src/utils/ontology.ts
1050
1067
  function normalizeTitleKey(title) {
1051
1068
  return title.trim().toLowerCase().replace(/\s+/g, " ");
@@ -1090,23 +1107,67 @@ async function seedLegacyWatermark(metadataRepo, eventRepo, entityId, db) {
1090
1107
  return anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, memory, total, db);
1091
1108
  }
1092
1109
 
1093
- // src/services/ImportExportService.ts
1094
- var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1095
- var IMPORT_TITLE_MAX = 500;
1096
- var IMPORT_BODY_MAX = 8e3;
1110
+ // src/services/importEventStamps.ts
1111
+ var DATE_MAX = 864e13;
1097
1112
  var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
1098
1113
  function createdAtValue(v) {
1099
1114
  if (typeof v === "number") return v;
1100
1115
  if (typeof v === "string" && DECIMAL_TEXT.test(v)) return Number(v);
1101
1116
  return NaN;
1102
1117
  }
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]));
1118
+ function isUsableDate(v) {
1119
+ return Number.isFinite(v) && v >= -DATE_MAX && v <= DATE_MAX;
1120
+ }
1121
+ function parseSourceWatermark(raw) {
1122
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
1123
+ const { at, id } = raw;
1124
+ if (typeof at !== "number" || !Number.isFinite(at) || typeof id !== "string") return null;
1125
+ return { at, id };
1126
+ }
1127
+ var cmp = (a, b) => a === b ? 0 : a < b ? -1 : 1;
1128
+ function planEventStamps(events, ctx) {
1129
+ const { now, floor, merge, localWm, sourceWm } = ctx;
1130
+ const after = (v, id, wm) => v > wm.at || v === wm.at && id > wm.id;
1131
+ const plan = /* @__PURE__ */ new Map();
1132
+ const restamp = [];
1133
+ for (const e of events) {
1134
+ const v = createdAtValue(e.created_at);
1135
+ const o = createdAtValue(e.occurred_at);
1136
+ let occurredAt = null;
1137
+ let occurredInvalid = false;
1138
+ if (e.occurred_at != null) {
1139
+ if (isUsableDate(o)) occurredAt = Math.trunc(o);
1140
+ else occurredInvalid = true;
1141
+ }
1142
+ let reason = null;
1143
+ const invalidCreated = Number.isNaN(v) || v < -DATE_MAX;
1144
+ if (invalidCreated) reason = "invalid";
1145
+ else if (v > now) reason = "future";
1146
+ else if (merge && localWm !== null && Number.isFinite(localWm.at) && !after(v, e.id, localWm) && (sourceWm === null || after(v, e.id, sourceWm))) {
1147
+ reason = "behind_watermark";
1148
+ }
1149
+ if (reason === "behind_watermark" && occurredAt === null && Number.isFinite(v) && v >= 0) {
1150
+ occurredAt = Math.trunc(v);
1151
+ }
1152
+ const stamp = { createdAt: v, occurredAt, reason };
1153
+ if (reason === null && occurredInvalid) stamp.reason = "invalid";
1154
+ plan.set(e, stamp);
1155
+ if (reason !== null) restamp.push({ e, key: invalidCreated ? -Infinity : v, stamp });
1156
+ }
1157
+ restamp.sort((x, y) => cmp(x.key, y.key) || cmp(x.e.id, y.e.id));
1158
+ if (restamp.length > 0 && floor + restamp.length > Number.MAX_SAFE_INTEGER) {
1159
+ 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.`);
1160
+ }
1161
+ restamp.forEach((x, i) => {
1162
+ x.stamp.createdAt = floor + 1 + i;
1163
+ });
1164
+ return plan;
1109
1165
  }
1166
+
1167
+ // src/services/ImportExportService.ts
1168
+ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1169
+ var IMPORT_TITLE_MAX = 500;
1170
+ var IMPORT_BODY_MAX = 8e3;
1110
1171
  var ImportExportService = class {
1111
1172
  constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
1112
1173
  this.db = db;
@@ -1159,6 +1220,7 @@ var ImportExportService = class {
1159
1220
  }
1160
1221
  }
1161
1222
  async getFullBundle(entityId, opts) {
1223
+ const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
1162
1224
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
1163
1225
  opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
1164
1226
  this.taskRepo.findAllByEntityId(entityId),
@@ -1188,7 +1250,8 @@ var ImportExportService = class {
1188
1250
  tasks,
1189
1251
  events,
1190
1252
  edges,
1191
- ...summaryValue != null ? { summary: summaryValue } : {}
1253
+ ...summaryValue != null ? { summary: summaryValue } : {},
1254
+ ...wm ? { librarian_watermark: wm } : {}
1192
1255
  };
1193
1256
  }
1194
1257
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
@@ -1200,6 +1263,7 @@ var ImportExportService = class {
1200
1263
  const softDeletedFactIds = [];
1201
1264
  const clippedTextByFactId = /* @__PURE__ */ new Map();
1202
1265
  let clampedEvents = 0;
1266
+ const restamped = { behind_watermark: 0, invalid: 0 };
1203
1267
  await this.db.withTransactionAsync(async (tx) => {
1204
1268
  if (!merge) {
1205
1269
  const deletedLiveFactIds = await this.entryRepo.findIdsBySource(
@@ -1423,9 +1487,9 @@ var ImportExportService = class {
1423
1487
  const now = Date.now();
1424
1488
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
1425
1489
  const floor = wm && Number.isFinite(wm.at) && wm.at > now ? wm.at : now;
1426
- const clampedAt = clampFutureCreatedAt(bundle.events, now, floor);
1490
+ const planned = planEventStamps(bundle.events, { now, floor, merge, localWm: wm, sourceWm: parseSourceWatermark(bundle.librarian_watermark) });
1427
1491
  for (const event of bundle.events) {
1428
- const stamped = clampedAt.get(event);
1492
+ const stamp = planned.get(event);
1429
1493
  const inserted = await this.eventRepo.addIgnoreDuplicate(
1430
1494
  {
1431
1495
  id: event.id,
@@ -1433,12 +1497,14 @@ var ImportExportService = class {
1433
1497
  event_type: event.event_type,
1434
1498
  summary: event.summary,
1435
1499
  related_entry_id: event.related_entry_id ?? null,
1436
- created_at: stamped ?? event.created_at,
1437
- occurred_at: event.occurred_at ?? null
1500
+ created_at: stamp.createdAt,
1501
+ occurred_at: stamp.occurredAt
1438
1502
  },
1439
1503
  tx
1440
1504
  );
1441
- if (inserted && stamped !== void 0) clampedEvents++;
1505
+ if (!inserted || stamp.reason === null) continue;
1506
+ if (stamp.reason === "future") clampedEvents++;
1507
+ else restamped[stamp.reason]++;
1442
1508
  }
1443
1509
  for (const edge of bundle.edges ?? []) {
1444
1510
  await this.edgeRepo.addIgnoreDuplicate(
@@ -1463,6 +1529,17 @@ var ImportExportService = class {
1463
1529
  detail: { count: clampedEvents }
1464
1530
  });
1465
1531
  }
1532
+ for (const reason of ["behind_watermark", "invalid"]) {
1533
+ if (restamped[reason] > 0) {
1534
+ emitDiagnostic(this.options, {
1535
+ code: "event_created_at_restamped",
1536
+ operation: "importDump",
1537
+ trigger: "call",
1538
+ entityId,
1539
+ detail: { count: restamped[reason], reason }
1540
+ });
1541
+ }
1542
+ }
1466
1543
  if (merge) {
1467
1544
  await this.searchService.syncEntries(entityId, [...upsertedFactIds]);
1468
1545
  } else {
@@ -1479,7 +1556,19 @@ var ImportExportService = class {
1479
1556
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
1480
1557
  }, { operation: "importDump", trigger: "call" });
1481
1558
  if (!embedded) {
1482
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
1559
+ try {
1560
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
1561
+ } catch (hookErr) {
1562
+ console.warn(
1563
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
1564
+ hookErr
1565
+ );
1566
+ this.embeddingService.reportHookFailed(
1567
+ { operation: "importDump", trigger: "call" },
1568
+ entityId,
1569
+ fact.id
1570
+ );
1571
+ }
1483
1572
  }
1484
1573
  }
1485
1574
  }
@@ -2804,6 +2893,195 @@ function parseEmbedding(blob, text) {
2804
2893
  return null;
2805
2894
  }
2806
2895
 
2896
+ // src/utils/temporal.ts
2897
+ function liveAtSql(mode, alias = "") {
2898
+ const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
2899
+ return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
2900
+ }
2901
+ function assertEpochMs(name, v) {
2902
+ if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
2903
+ throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
2904
+ }
2905
+ return Math.trunc(v);
2906
+ }
2907
+
2908
+ // src/repositories/EdgeRepository.ts
2909
+ var CONFIDENCE_RANK = {
2910
+ tentative: 0,
2911
+ inferred: 1,
2912
+ certain: 2
2913
+ };
2914
+ var EdgeRepository = class extends BaseRepository {
2915
+ /**
2916
+ * Insert an edge, silently skipping on primary-key or uniqueness conflicts.
2917
+ * Returns true when a row was inserted, false when skipped as a duplicate.
2918
+ * Throws when the insert was skipped due to an id collision with a different edge tuple.
2919
+ */
2920
+ async addIgnoreDuplicate(edge, tx) {
2921
+ const executor = this.getExecutor(tx);
2922
+ const result = await executor.runAsync(
2923
+ `INSERT OR IGNORE INTO ${this.prefix}edges (id, entity_id, source_id, target_id, edge_type, created_at)
2924
+ VALUES (?, ?, ?, ?, ?, ?)`,
2925
+ [edge.id, edge.entity_id, edge.source_id, edge.target_id, edge.edge_type, edge.created_at]
2926
+ );
2927
+ if (result.changes > 0) return true;
2928
+ const existing = await executor.getFirstAsync(
2929
+ `SELECT entity_id, source_id, target_id, edge_type FROM ${this.prefix}edges WHERE id = ?`,
2930
+ [edge.id]
2931
+ );
2932
+ if (!existing) return false;
2933
+ 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) {
2934
+ throw new Error(
2935
+ `Edge id collision: ${JSON.stringify(edge.id)} already exists with a different (entity_id, source_id, target_id, edge_type) tuple`
2936
+ );
2937
+ }
2938
+ return false;
2939
+ }
2940
+ async getByEntityId(entityId, tx) {
2941
+ const executor = this.getExecutor(tx);
2942
+ const rows = await executor.getAllAsync(
2943
+ `SELECT * FROM ${this.prefix}edges WHERE entity_id = ? ORDER BY created_at ASC`,
2944
+ [entityId]
2945
+ );
2946
+ return rows.map(mapRowToEdge);
2947
+ }
2948
+ /** Hard delete — edges have no soft-delete concept, only presence/absence. `tx` is REQUIRED. */
2949
+ async bulkDeleteByEntityId(entityId, tx) {
2950
+ const executor = this.getExecutor(tx);
2951
+ await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);
2952
+ }
2953
+ /**
2954
+ * Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to
2955
+ * `entityId`. Returns the number of rows deleted. Edges have no soft-delete
2956
+ * concept; this method is named `softDeleteBySourceFactIds` for symmetry with
2957
+ * `EntryRepository.softDeleteBySource` (which IS a soft delete), but its
2958
+ * semantics are immediate presence/absence removal. Use ONLY inside an open
2959
+ * transaction — the method requires `tx` and performs no autocommit.
2960
+ *
2961
+ * Used by `IngestionService.upsertGraphCore` to retire the prior parse's
2962
+ * edges whose source facts are being superseded by `softDeleteBySource`.
2963
+ */
2964
+ async softDeleteBySourceFactIds(entityId, sourceFactIds, tx) {
2965
+ if (sourceFactIds.length === 0) return 0;
2966
+ const executor = this.getExecutor(tx);
2967
+ const chunkSize = 500;
2968
+ let totalChanges = 0;
2969
+ for (let i = 0; i < sourceFactIds.length; i += chunkSize) {
2970
+ const chunk = sourceFactIds.slice(i, i + chunkSize);
2971
+ const placeholders = chunk.map(() => "?").join(",");
2972
+ const result = await executor.runAsync(
2973
+ `DELETE FROM ${this.prefix}edges
2974
+ WHERE entity_id = ? AND source_id IN (${placeholders})`,
2975
+ [entityId, ...chunk]
2976
+ );
2977
+ totalChanges += result.changes;
2978
+ }
2979
+ return totalChanges;
2980
+ }
2981
+ /**
2982
+ * Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
2983
+ * dead-ending, cycle-guarding, capping, and ordering happens in this one query.
2984
+ * The anchor is validated (exists, right entity, not soft-deleted) but never gated
2985
+ * by confidence/source_type — only nodes discovered beyond it are.
2986
+ */
2987
+ async getNeighborhood(entityId, sourceId, opts, tx) {
2988
+ const executor = this.getExecutor(tx);
2989
+ if (opts.edgeTypes && opts.edgeTypes.length === 0) {
2990
+ const anchor = await executor.getFirstAsync(
2991
+ `SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
2992
+ [sourceId, entityId]
2993
+ );
2994
+ return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
2995
+ }
2996
+ const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
2997
+ const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
2998
+ const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
2999
+ const sql = `
3000
+ WITH RECURSIVE walk(node_id, depth, visited) AS (
3001
+ SELECT id, 0, ',' || id || ','
3002
+ FROM ${this.prefix}entries
3003
+ WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
3004
+
3005
+ UNION
3006
+
3007
+ SELECT
3008
+ CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
3009
+ w.depth + 1,
3010
+ w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
3011
+ FROM walk w
3012
+ JOIN ${this.prefix}edges e
3013
+ ON e.entity_id = ?
3014
+ AND (
3015
+ (? != 'inbound' AND e.source_id = w.node_id) OR
3016
+ (? != 'outbound' AND e.target_id = w.node_id)
3017
+ )
3018
+ AND (${edgeTypesClause})
3019
+ JOIN ${this.prefix}entries n
3020
+ ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
3021
+ AND n.entity_id = ?
3022
+ AND n.deleted_at IS NULL
3023
+ AND (
3024
+ CASE n.confidence
3025
+ WHEN 'tentative' THEN 0
3026
+ WHEN 'inferred' THEN 1
3027
+ WHEN 'certain' THEN 2
3028
+ ELSE -1
3029
+ END
3030
+ ) >= ?
3031
+ AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
3032
+ AND (? = 0 OR n.lifecycle_status != 'draft')
3033
+ AND ${liveAtSql(opts.live.mode, "n.")}
3034
+ WHERE w.depth < ?
3035
+ AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
3036
+ )
3037
+ SELECT node_id, MIN(depth) AS depth
3038
+ FROM walk
3039
+ GROUP BY node_id
3040
+ ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
3041
+ LIMIT ?
3042
+ `;
3043
+ const params = [
3044
+ sourceId,
3045
+ entityId,
3046
+ entityId,
3047
+ opts.direction,
3048
+ opts.direction,
3049
+ ...opts.edgeTypes ?? [],
3050
+ entityId,
3051
+ minConfidenceRank,
3052
+ ...opts.excludeSourceTypes,
3053
+ opts.excludeDrafts === true ? 1 : 0,
3054
+ opts.live.t,
3055
+ opts.live.t,
3056
+ opts.maxDepth,
3057
+ opts.maxNodes
3058
+ ];
3059
+ const rows = await executor.getAllAsync(sql, params);
3060
+ const nodeIds = rows.map((r) => r.node_id);
3061
+ if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
3062
+ const valueRows = nodeIds.map(() => "(?)").join(", ");
3063
+ const edgeRows = await executor.getAllAsync(
3064
+ `WITH neighborhood(node_id) AS (VALUES ${valueRows})
3065
+ SELECT e.* FROM ${this.prefix}edges e
3066
+ JOIN neighborhood ns ON e.source_id = ns.node_id
3067
+ JOIN neighborhood nt ON e.target_id = nt.node_id
3068
+ WHERE e.entity_id = ?`,
3069
+ [...nodeIds, entityId]
3070
+ );
3071
+ return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
3072
+ }
3073
+ };
3074
+ function mapRowToEdge(row) {
3075
+ return {
3076
+ id: String(row.id),
3077
+ entity_id: String(row.entity_id),
3078
+ source_id: String(row.source_id),
3079
+ target_id: String(row.target_id),
3080
+ edge_type: String(row.edge_type),
3081
+ created_at: Number(row.created_at)
3082
+ };
3083
+ }
3084
+
2807
3085
  // src/services/BoundedLlmCall.ts
2808
3086
  var DEFAULT_BATCH_SIZE = 10;
2809
3087
  var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
@@ -3521,7 +3799,9 @@ async function runExtract(deps, ctx, batch) {
3521
3799
  const base = { entityId, operation: "librarian", trigger };
3522
3800
  const diagnostics = [];
3523
3801
  const byLabel = new Map(batch.map((l) => [l.label, l]));
3524
- const newestAt = batch[batch.length - 1].at;
3802
+ let newestAt = batch[0].at;
3803
+ for (const l of batch) if (l.at > newestAt) newestAt = l.at;
3804
+ const defaultValidFrom = Math.min(newestAt, Date.now());
3525
3805
  const candidates = [];
3526
3806
  (Array.isArray(parsed.facts) ? parsed.facts : []).forEach((raw, index) => {
3527
3807
  const fact = validateFact(raw);
@@ -3531,7 +3811,7 @@ async function runExtract(deps, ctx, batch) {
3531
3811
  }
3532
3812
  const r = raw;
3533
3813
  const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
3534
- const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : newestAt);
3814
+ const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
3535
3815
  candidates.push({ index, fact, sourceLabel, validFrom });
3536
3816
  });
3537
3817
  const tasks = [];
@@ -3733,14 +4013,6 @@ async function runResolve(deps, ctx, ambiguous) {
3733
4013
  return out;
3734
4014
  }
3735
4015
 
3736
- // src/utils/temporal.ts
3737
- function assertEpochMs(name, v) {
3738
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3739
- throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3740
- }
3741
- return Math.trunc(v);
3742
- }
3743
-
3744
4016
  // src/services/TemporalService.ts
3745
4017
  var HISTORY_MAX_DEPTH = 100;
3746
4018
  var TemporalService = class {
@@ -4122,7 +4394,7 @@ var formatSkipError = (err) => {
4122
4394
  return base;
4123
4395
  };
4124
4396
  var MaintenanceService = class {
4125
- constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
4397
+ constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
4126
4398
  this.db = db;
4127
4399
  this.prefix = prefix;
4128
4400
  this.options = options;
@@ -4136,6 +4408,7 @@ var MaintenanceService = class {
4136
4408
  this.embeddingService = embeddingService;
4137
4409
  this.ontologyService = ontologyService;
4138
4410
  this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
4411
+ this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
4139
4412
  }
4140
4413
  async runPrune(entityId, options) {
4141
4414
  this.jobManager.acquireLock("prune", entityId);
@@ -4366,6 +4639,9 @@ var MaintenanceService = class {
4366
4639
  if (params.clearAll && (params.entryId !== void 0 || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
4367
4640
  throw new Error("forget() clearAll is mutually exclusive with entryId, taskId, sourceRef, and sourceHash");
4368
4641
  }
4642
+ if (params.includeEvents && !params.clearAll) {
4643
+ throw new Error("forget() includeEvents requires clearAll: true");
4644
+ }
4369
4645
  if (opts?.dryRun === true) {
4370
4646
  return this.forgetDryRun(entityId, params);
4371
4647
  }
@@ -4374,13 +4650,23 @@ var MaintenanceService = class {
4374
4650
  const now = Date.now();
4375
4651
  let deletedEntries = 0;
4376
4652
  let deletedTasks = 0;
4653
+ let deletedEvents = 0;
4377
4654
  const deletedEntryIds = [];
4378
4655
  await this.db.withTransactionAsync(async (tx) => {
4379
4656
  if (params.clearAll) {
4380
- deletedEntryIds.push(...await this.entryRepo.findIdsBySource(entityId, null, null, tx, true));
4657
+ for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
4381
4658
  deletedEntries = await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
4382
4659
  deletedTasks = await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
4383
- await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
4660
+ if (await this.sourceRefIndexPresent(tx)) {
4661
+ await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
4662
+ }
4663
+ await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
4664
+ if (params.includeEvents) {
4665
+ deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
4666
+ await this.metadataRepo.deleteCheckpoint(entityId, tx);
4667
+ } else {
4668
+ await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
4669
+ }
4384
4670
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
4385
4671
  } else {
4386
4672
  const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
@@ -4398,7 +4684,7 @@ var MaintenanceService = class {
4398
4684
  if (entryId) deletedEntryIds.push(entryId);
4399
4685
  }
4400
4686
  if (sourceRef || sourceHash) {
4401
- deletedEntryIds.push(...await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true));
4687
+ for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
4402
4688
  }
4403
4689
  const entryPromise = params.entryId ? this.entryRepo.softDelete(params.entryId, entityId, tx).then((r) => r.changes > 0) : null;
4404
4690
  const taskDeletedPromise = params.taskId ? this.taskRepo.softDeleteById(params.taskId, entityId, tx).then((r) => r.changes > 0) : null;
@@ -4432,7 +4718,8 @@ var MaintenanceService = class {
4432
4718
  throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
4433
4719
  }
4434
4720
  }
4435
- return params.clearAll ? { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks } };
4721
+ if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
4722
+ return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
4436
4723
  } finally {
4437
4724
  this.jobManager.releaseLock("forget", entityId);
4438
4725
  }
@@ -4483,6 +4770,10 @@ var MaintenanceService = class {
4483
4770
  if (params.clearAll) {
4484
4771
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
4485
4772
  const tasks = await this.taskRepo.countLiveByEntityId(entityId);
4773
+ if (params.includeEvents) {
4774
+ const events = await this.eventRepo.count(entityId);
4775
+ return { deleted: { entries: entries2, tasks, events }, metadataReset: true };
4776
+ }
4486
4777
  return { deleted: { entries: entries2, tasks }, metadataReset: true };
4487
4778
  }
4488
4779
  const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
@@ -5585,7 +5876,7 @@ var RetrievalService = class {
5585
5876
  if (topK.length < maxBackfill) {
5586
5877
  let insertIdx = topK.length;
5587
5878
  for (let i = 0; i < topK.length; i++) {
5588
- const cmp = this._compareScoredRows(
5879
+ const cmp2 = this._compareScoredRows(
5589
5880
  {
5590
5881
  id: candidate.row.id,
5591
5882
  score: candidate.kwScore,
@@ -5599,7 +5890,7 @@ var RetrievalService = class {
5599
5890
  access_count: topK[i].row.access_count
5600
5891
  }
5601
5892
  );
5602
- if (cmp < 0) {
5893
+ if (cmp2 < 0) {
5603
5894
  insertIdx = i;
5604
5895
  break;
5605
5896
  }
@@ -5623,7 +5914,7 @@ var RetrievalService = class {
5623
5914
  if (cmpWorst < 0) {
5624
5915
  let insertIdx = maxBackfill - 1;
5625
5916
  for (let i = 0; i < topK.length; i++) {
5626
- const cmp = this._compareScoredRows(
5917
+ const cmp2 = this._compareScoredRows(
5627
5918
  {
5628
5919
  id: candidate.row.id,
5629
5920
  score: candidate.kwScore,
@@ -5637,7 +5928,7 @@ var RetrievalService = class {
5637
5928
  access_count: topK[i].row.access_count
5638
5929
  }
5639
5930
  );
5640
- if (cmp < 0) {
5931
+ if (cmp2 < 0) {
5641
5932
  insertIdx = i;
5642
5933
  break;
5643
5934
  }