@equationalapplications/core-llm-wiki 8.2.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
@@ -1048,6 +1048,21 @@ var EmbeddingService = class {
1048
1048
  }
1049
1049
  };
1050
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
+
1051
1066
  // src/utils/ontology.ts
1052
1067
  function normalizeTitleKey(title) {
1053
1068
  return title.trim().toLowerCase().replace(/\s+/g, " ");
@@ -1541,7 +1556,19 @@ var ImportExportService = class {
1541
1556
  tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
1542
1557
  }, { operation: "importDump", trigger: "call" });
1543
1558
  if (!embedded) {
1544
- 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
+ }
1545
1572
  }
1546
1573
  }
1547
1574
  }
@@ -2866,6 +2893,195 @@ function parseEmbedding(blob, text) {
2866
2893
  return null;
2867
2894
  }
2868
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
+
2869
3085
  // src/services/BoundedLlmCall.ts
2870
3086
  var DEFAULT_BATCH_SIZE = 10;
2871
3087
  var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
@@ -3583,7 +3799,9 @@ async function runExtract(deps, ctx, batch) {
3583
3799
  const base = { entityId, operation: "librarian", trigger };
3584
3800
  const diagnostics = [];
3585
3801
  const byLabel = new Map(batch.map((l) => [l.label, l]));
3586
- 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());
3587
3805
  const candidates = [];
3588
3806
  (Array.isArray(parsed.facts) ? parsed.facts : []).forEach((raw, index) => {
3589
3807
  const fact = validateFact(raw);
@@ -3593,7 +3811,7 @@ async function runExtract(deps, ctx, batch) {
3593
3811
  }
3594
3812
  const r = raw;
3595
3813
  const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
3596
- 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);
3597
3815
  candidates.push({ index, fact, sourceLabel, validFrom });
3598
3816
  });
3599
3817
  const tasks = [];
@@ -3795,14 +4013,6 @@ async function runResolve(deps, ctx, ambiguous) {
3795
4013
  return out;
3796
4014
  }
3797
4015
 
3798
- // src/utils/temporal.ts
3799
- function assertEpochMs(name, v) {
3800
- if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
3801
- throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
3802
- }
3803
- return Math.trunc(v);
3804
- }
3805
-
3806
4016
  // src/services/TemporalService.ts
3807
4017
  var HISTORY_MAX_DEPTH = 100;
3808
4018
  var TemporalService = class {
@@ -4184,7 +4394,7 @@ var formatSkipError = (err) => {
4184
4394
  return base;
4185
4395
  };
4186
4396
  var MaintenanceService = class {
4187
- 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) {
4188
4398
  this.db = db;
4189
4399
  this.prefix = prefix;
4190
4400
  this.options = options;
@@ -4198,6 +4408,7 @@ var MaintenanceService = class {
4198
4408
  this.embeddingService = embeddingService;
4199
4409
  this.ontologyService = ontologyService;
4200
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);
4201
4412
  }
4202
4413
  async runPrune(entityId, options) {
4203
4414
  this.jobManager.acquireLock("prune", entityId);
@@ -4428,6 +4639,9 @@ var MaintenanceService = class {
4428
4639
  if (params.clearAll && (params.entryId !== void 0 || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
4429
4640
  throw new Error("forget() clearAll is mutually exclusive with entryId, taskId, sourceRef, and sourceHash");
4430
4641
  }
4642
+ if (params.includeEvents && !params.clearAll) {
4643
+ throw new Error("forget() includeEvents requires clearAll: true");
4644
+ }
4431
4645
  if (opts?.dryRun === true) {
4432
4646
  return this.forgetDryRun(entityId, params);
4433
4647
  }
@@ -4436,13 +4650,23 @@ var MaintenanceService = class {
4436
4650
  const now = Date.now();
4437
4651
  let deletedEntries = 0;
4438
4652
  let deletedTasks = 0;
4653
+ let deletedEvents = 0;
4439
4654
  const deletedEntryIds = [];
4440
4655
  await this.db.withTransactionAsync(async (tx) => {
4441
4656
  if (params.clearAll) {
4442
- 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);
4443
4658
  deletedEntries = await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
4444
4659
  deletedTasks = await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
4445
- 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
+ }
4446
4670
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
4447
4671
  } else {
4448
4672
  const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
@@ -4460,7 +4684,7 @@ var MaintenanceService = class {
4460
4684
  if (entryId) deletedEntryIds.push(entryId);
4461
4685
  }
4462
4686
  if (sourceRef || sourceHash) {
4463
- 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);
4464
4688
  }
4465
4689
  const entryPromise = params.entryId ? this.entryRepo.softDelete(params.entryId, entityId, tx).then((r) => r.changes > 0) : null;
4466
4690
  const taskDeletedPromise = params.taskId ? this.taskRepo.softDeleteById(params.taskId, entityId, tx).then((r) => r.changes > 0) : null;
@@ -4494,7 +4718,8 @@ var MaintenanceService = class {
4494
4718
  throw new Error(`forget(${entityId}/${factId}) failed: ANN cleanup hook rejected`, { cause: this._sanitizeRankerError(hookErr) });
4495
4719
  }
4496
4720
  }
4497
- 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 };
4498
4723
  } finally {
4499
4724
  this.jobManager.releaseLock("forget", entityId);
4500
4725
  }
@@ -4545,6 +4770,10 @@ var MaintenanceService = class {
4545
4770
  if (params.clearAll) {
4546
4771
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
4547
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
+ }
4548
4777
  return { deleted: { entries: entries2, tasks }, metadataReset: true };
4549
4778
  }
4550
4779
  const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;