@equationalapplications/core-llm-wiki 8.2.0 → 8.4.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 +1 -1
- package/dist/{chunk-FOX6TNFO.mjs → chunk-EKYWAR2E.mjs} +1210 -136
- package/dist/chunk-EKYWAR2E.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1514 -319
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +331 -211
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-D6So3dKX.d.mts → testing-Og5x9rFu.d.mts} +385 -56
- package/dist/{testing-D6So3dKX.d.ts → testing-Og5x9rFu.d.ts} +385 -56
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +641 -120
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-FOX6TNFO.mjs.map +0 -1
package/dist/testing.js
CHANGED
|
@@ -66,6 +66,17 @@ var WikiBusyError = class extends Error {
|
|
|
66
66
|
this.entityId = entityId;
|
|
67
67
|
}
|
|
68
68
|
};
|
|
69
|
+
var WikiExternalDeletionError = class extends Error {
|
|
70
|
+
constructor(message, params) {
|
|
71
|
+
super(message, params.cause ? { cause: params.cause } : void 0);
|
|
72
|
+
this.code = "WIKI_EXTERNAL_DELETION";
|
|
73
|
+
this.name = "WikiExternalDeletionError";
|
|
74
|
+
this.entityId = params.entityId;
|
|
75
|
+
this.unconfirmedIds = params.unconfirmedIds;
|
|
76
|
+
this.unconfirmedCount = params.unconfirmedCount;
|
|
77
|
+
this.timedOut = params.timedOut;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
69
80
|
var WikiDuplicateHashError = class extends Error {
|
|
70
81
|
constructor(params) {
|
|
71
82
|
super(`Duplicate source hash for entity ${params.entityId}; another ref already holds this content`);
|
|
@@ -534,14 +545,14 @@ function chunkText(input, maxChunkLength, overlap) {
|
|
|
534
545
|
if (!Number.isInteger(overlap) || overlap < 0 || overlap >= maxChunkLength) {
|
|
535
546
|
throw new Error("overlap must be a non-negative integer < maxChunkLength");
|
|
536
547
|
}
|
|
537
|
-
const
|
|
548
|
+
const chunks2 = [];
|
|
538
549
|
let truncated = false;
|
|
539
550
|
let cursor = 0;
|
|
540
551
|
const halfMax = Math.floor(maxChunkLength / 2);
|
|
541
552
|
while (cursor < text.length) {
|
|
542
553
|
const remaining = text.length - cursor;
|
|
543
554
|
if (remaining <= maxChunkLength) {
|
|
544
|
-
|
|
555
|
+
chunks2.push(safeSlice(text, cursor, text.length));
|
|
545
556
|
break;
|
|
546
557
|
}
|
|
547
558
|
const windowEnd = cursor + maxChunkLength;
|
|
@@ -573,11 +584,11 @@ function chunkText(input, maxChunkLength, overlap) {
|
|
|
573
584
|
truncated = true;
|
|
574
585
|
splitPoint = windowEnd;
|
|
575
586
|
}
|
|
576
|
-
|
|
587
|
+
chunks2.push(safeSlice(text, cursor, splitPoint));
|
|
577
588
|
const next = Math.max(splitPoint - overlap, cursor + 1);
|
|
578
589
|
cursor = next;
|
|
579
590
|
}
|
|
580
|
-
return { chunks, truncated };
|
|
591
|
+
return { chunks: chunks2, truncated };
|
|
581
592
|
}
|
|
582
593
|
async function withConcurrency(tasks, limit) {
|
|
583
594
|
const results = new Array(tasks.length);
|
|
@@ -714,7 +725,9 @@ var SEVERITY = {
|
|
|
714
725
|
read_budget: "info",
|
|
715
726
|
event_retention_held: "info",
|
|
716
727
|
event_created_at_clamped: "warn",
|
|
717
|
-
event_created_at_restamped: "info"
|
|
728
|
+
event_created_at_restamped: "info",
|
|
729
|
+
external_deletion_pending: "warn",
|
|
730
|
+
external_deletion_discarded: "warn"
|
|
718
731
|
};
|
|
719
732
|
var MESSAGE = {
|
|
720
733
|
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
@@ -738,7 +751,9 @@ var MESSAGE = {
|
|
|
738
751
|
read_budget: "A read was packed to a token budget.",
|
|
739
752
|
event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
|
|
740
753
|
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."
|
|
754
|
+
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.",
|
|
755
|
+
external_deletion_pending: "Removals owed to the external vector index are still pending.",
|
|
756
|
+
external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
|
|
742
757
|
};
|
|
743
758
|
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
744
759
|
function copyDetail(detail) {
|
|
@@ -951,27 +966,62 @@ var EmbeddingService = class {
|
|
|
951
966
|
}
|
|
952
967
|
/**
|
|
953
968
|
* Storage half: persist the computed vector to the entry row, then fire the
|
|
954
|
-
* `onEmbeddingPersisted` hook. Failure kinds: `storage_error`
|
|
955
|
-
*
|
|
969
|
+
* `onEmbeddingPersisted` hook. Failure kinds: `storage_error` (a DB error) and
|
|
970
|
+
* `fact_deleted` (the row was soft-deleted or gone: no blob, no vector call, no
|
|
971
|
+
* marker). Embed failures do not originate here, so they cannot be marked as
|
|
972
|
+
* such (spec §3.2, D3).
|
|
956
973
|
*/
|
|
957
974
|
async storeFactVector(fact, float32Vector, ctx) {
|
|
975
|
+
let stored = true;
|
|
958
976
|
try {
|
|
959
977
|
await this.storeEmbeddingDimension(float32Vector.length);
|
|
960
978
|
const blob = new Uint8Array(float32Vector.buffer);
|
|
961
|
-
await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
|
|
979
|
+
stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
|
|
962
980
|
} catch (err) {
|
|
963
981
|
console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
|
|
964
982
|
this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
|
|
965
983
|
return { ok: false, kind: "storage_error" };
|
|
966
984
|
}
|
|
985
|
+
if (!stored) return { ok: false, kind: "fact_deleted" };
|
|
967
986
|
try {
|
|
968
987
|
await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
|
|
969
988
|
} catch (hookErr) {
|
|
970
989
|
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
|
|
971
990
|
this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
|
|
972
991
|
}
|
|
992
|
+
if (this.hasVectorHook()) {
|
|
993
|
+
await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
|
|
994
|
+
}
|
|
973
995
|
return { ok: true, dimension: float32Vector.length };
|
|
974
996
|
}
|
|
997
|
+
hasVectorHook() {
|
|
998
|
+
return !!this.options.vectorRanker?.onEmbeddingPersisted;
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Run after a vector call (resolved or not) by every path that sends one.
|
|
1002
|
+
* Never throws: a failure here leaves the removal owed or unrecorded, as before.
|
|
1003
|
+
*/
|
|
1004
|
+
async settleAfterVectorCall(entityId, factId, operation, trigger) {
|
|
1005
|
+
const vr = this.vectorRemoval;
|
|
1006
|
+
if (!vr) return;
|
|
1007
|
+
const outcome = await this.recordAfterVectorCall(entityId, factId);
|
|
1008
|
+
if (outcome === "enqueued") {
|
|
1009
|
+
try {
|
|
1010
|
+
await vr.service.deliverRemovals(entityId, [factId], operation, trigger, []);
|
|
1011
|
+
} catch (err) {
|
|
1012
|
+
console.warn(`[WikiMemory] post-embed removal delivery failed for ${factId}:`, err);
|
|
1013
|
+
}
|
|
1014
|
+
return;
|
|
1015
|
+
}
|
|
1016
|
+
if (outcome !== "write_failed") return;
|
|
1017
|
+
try {
|
|
1018
|
+
await this.callRemovalHook(entityId, factId, this.validateDeletionTimeout());
|
|
1019
|
+
} catch (hookErr) {
|
|
1020
|
+
console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
|
|
1021
|
+
this.reportHookFailed({ operation, trigger }, entityId, factId);
|
|
1022
|
+
await this.recordAfterVectorCall(entityId, factId);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
975
1025
|
reportEmbed(ctx, fact, code, reason) {
|
|
976
1026
|
if (!ctx) return;
|
|
977
1027
|
emitDiagnostic(this.options, {
|
|
@@ -1003,6 +1053,48 @@ var EmbeddingService = class {
|
|
|
1003
1053
|
const result = await this.tryEmbedFact(fact, ctx);
|
|
1004
1054
|
return result.ok;
|
|
1005
1055
|
}
|
|
1056
|
+
/** Wired by WikiMemory (VectorRemovalService itself depends on this class). */
|
|
1057
|
+
attachVectorRemoval(service, repo) {
|
|
1058
|
+
this.vectorRemoval = { service, repo };
|
|
1059
|
+
}
|
|
1060
|
+
/**
|
|
1061
|
+
* After an embed (and its vector call) settles: owe a removal if the fact is
|
|
1062
|
+
* no longer live, so a vector the host just received is taken back (§5.7, G10).
|
|
1063
|
+
* Never throws. `'enqueued'`: a ledger row was written. `'none'`: no
|
|
1064
|
+
* removal hook (or the hook gate is off). `'live'`: the fact is live. A row already pending is
|
|
1065
|
+
* replaced (attempts reset, spec §5.2), so it counts as `'enqueued'` and
|
|
1066
|
+
* is sent now: the last call the host sees after this vector is `null`.
|
|
1067
|
+
* `'owed'`: the write failed but a pending row already holds the removal.
|
|
1068
|
+
* `'write_failed'`: the fact is known not live, the write failed, and its
|
|
1069
|
+
* row is confirmed or missing; or the store has no ledger table and the
|
|
1070
|
+
* fact is known not live.
|
|
1071
|
+
* `'unknown'`: the liveness read and the guarded write both failed.
|
|
1072
|
+
*/
|
|
1073
|
+
async recordAfterVectorCall(entityId, factId) {
|
|
1074
|
+
const vr = this.vectorRemoval;
|
|
1075
|
+
if (!vr || vr.service.gate() !== "hook") return "none";
|
|
1076
|
+
let live;
|
|
1077
|
+
try {
|
|
1078
|
+
if (!await vr.service.ledgerPresent()) {
|
|
1079
|
+
return await vr.repo.isLive(factId) ? "live" : "write_failed";
|
|
1080
|
+
}
|
|
1081
|
+
live = await vr.repo.isLive(factId);
|
|
1082
|
+
} catch (err) {
|
|
1083
|
+
console.warn(`[WikiMemory] post-embed liveness read failed for ${factId}:`, err);
|
|
1084
|
+
}
|
|
1085
|
+
if (live) return "live";
|
|
1086
|
+
try {
|
|
1087
|
+
return await vr.repo.enqueueIfNotLive(entityId, factId, Date.now()) ? "enqueued" : "live";
|
|
1088
|
+
} catch (err) {
|
|
1089
|
+
console.warn(`[WikiMemory] post-embed removal could not be recorded for ${factId}:`, err);
|
|
1090
|
+
if (live !== false) return "unknown";
|
|
1091
|
+
try {
|
|
1092
|
+
if ((await vr.repo.statusFor([factId])).get(factId) === "pending") return "owed";
|
|
1093
|
+
} catch {
|
|
1094
|
+
}
|
|
1095
|
+
return "write_failed";
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1006
1098
|
async notifyEmbeddingPersisted(entityId, factId, vector) {
|
|
1007
1099
|
if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
|
|
1008
1100
|
const vectorCopy = vector ? vector.slice() : null;
|
|
@@ -1012,15 +1104,72 @@ var EmbeddingService = class {
|
|
|
1012
1104
|
vector: vectorCopy
|
|
1013
1105
|
});
|
|
1014
1106
|
}
|
|
1015
|
-
|
|
1016
|
-
if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
|
|
1017
|
-
if (this.options.forceDeleteIgnoreRankerHook === true) return;
|
|
1018
|
-
const vectorCopy = vector ? vector.slice() : null;
|
|
1107
|
+
validateDeletionTimeout() {
|
|
1019
1108
|
const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
|
|
1020
1109
|
if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
|
|
1021
1110
|
throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
|
|
1022
1111
|
}
|
|
1023
|
-
|
|
1112
|
+
return rawTimeout;
|
|
1113
|
+
}
|
|
1114
|
+
/** Send a removal (`vector: null`) to the hook. No gate check; the caller owns the gate. */
|
|
1115
|
+
async callRemovalHook(entityId, factId, timeoutMs) {
|
|
1116
|
+
if (!this.options.vectorRanker?.onEmbeddingPersisted) {
|
|
1117
|
+
throw new Error("callRemovalHook requires vectorRanker.onEmbeddingPersisted");
|
|
1118
|
+
}
|
|
1119
|
+
let timeoutHandle;
|
|
1120
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
1121
|
+
timeoutHandle = setTimeout(() => {
|
|
1122
|
+
const timeoutError = new Error(`onEmbeddingPersisted timed out after ${timeoutMs}ms`);
|
|
1123
|
+
timeoutError[HOOK_TIMEOUT_MARKER] = true;
|
|
1124
|
+
reject(timeoutError);
|
|
1125
|
+
}, timeoutMs);
|
|
1126
|
+
});
|
|
1127
|
+
const hookPromise = Promise.resolve().then(
|
|
1128
|
+
() => this.options.vectorRanker.onEmbeddingPersisted({ entityId, factId, vector: null })
|
|
1129
|
+
);
|
|
1130
|
+
try {
|
|
1131
|
+
await Promise.race([hookPromise, timeoutPromise]);
|
|
1132
|
+
} catch (err) {
|
|
1133
|
+
hookPromise.catch(() => {
|
|
1134
|
+
});
|
|
1135
|
+
throw err;
|
|
1136
|
+
} finally {
|
|
1137
|
+
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* One removal call per id for a store with no ledger table (setup() never
|
|
1142
|
+
* ran), so nothing records what is owed (spec §5.5.5). Stops at the first
|
|
1143
|
+
* timeout: a dead index costs one timeout, as in a drain (spec rev 5).
|
|
1144
|
+
* `failed` lists the ids not confirmed, in order; after a timeout it ends
|
|
1145
|
+
* with the timed-out id and every id after it. Throws only for an invalid
|
|
1146
|
+
* `deletionHookTimeoutMs`.
|
|
1147
|
+
*/
|
|
1148
|
+
async callRemovalHookEach(entityId, ids, opts = {}) {
|
|
1149
|
+
const timeoutMs = this.validateDeletionTimeout();
|
|
1150
|
+
const failed = [];
|
|
1151
|
+
let firstRejection;
|
|
1152
|
+
for (let i = 0; i < ids.length; i++) {
|
|
1153
|
+
const factId = ids[i];
|
|
1154
|
+
try {
|
|
1155
|
+
await this.callRemovalHook(entityId, factId, timeoutMs);
|
|
1156
|
+
} catch (hookErr) {
|
|
1157
|
+
if (opts.warn) console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
|
|
1158
|
+
if (hookErr?.[HOOK_TIMEOUT_MARKER] === true) {
|
|
1159
|
+
failed.push(...ids.slice(i));
|
|
1160
|
+
return { failed, timedOut: true, timedOutId: factId, cause: hookErr };
|
|
1161
|
+
}
|
|
1162
|
+
failed.push(factId);
|
|
1163
|
+
firstRejection ?? (firstRejection = hookErr);
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
return { failed, timedOut: false, cause: firstRejection };
|
|
1167
|
+
}
|
|
1168
|
+
async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
|
|
1169
|
+
if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
|
|
1170
|
+
if (this.options.forceDeleteIgnoreRankerHook === true) return;
|
|
1171
|
+
const vectorCopy = vector ? vector.slice() : null;
|
|
1172
|
+
const timeoutMs = this.validateDeletionTimeout();
|
|
1024
1173
|
let timeoutHandle;
|
|
1025
1174
|
const timeoutPromise = new Promise((_, reject) => {
|
|
1026
1175
|
timeoutHandle = setTimeout(() => {
|
|
@@ -1048,6 +1197,21 @@ var EmbeddingService = class {
|
|
|
1048
1197
|
}
|
|
1049
1198
|
};
|
|
1050
1199
|
|
|
1200
|
+
// src/repositories/BaseRepository.ts
|
|
1201
|
+
var BaseRepository = class {
|
|
1202
|
+
constructor(db, prefix) {
|
|
1203
|
+
this.db = db;
|
|
1204
|
+
this.prefix = prefix;
|
|
1205
|
+
}
|
|
1206
|
+
/**
|
|
1207
|
+
* Return the DB executor for a given transaction handle.
|
|
1208
|
+
* If tx is provided, use it; otherwise fall back to this.db.
|
|
1209
|
+
*/
|
|
1210
|
+
getExecutor(tx) {
|
|
1211
|
+
return tx ?? this.db;
|
|
1212
|
+
}
|
|
1213
|
+
};
|
|
1214
|
+
|
|
1051
1215
|
// src/utils/ontology.ts
|
|
1052
1216
|
function normalizeTitleKey(title) {
|
|
1053
1217
|
return title.trim().toLowerCase().replace(/\s+/g, " ");
|
|
@@ -1154,7 +1318,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
|
|
|
1154
1318
|
var IMPORT_TITLE_MAX = 500;
|
|
1155
1319
|
var IMPORT_BODY_MAX = 8e3;
|
|
1156
1320
|
var ImportExportService = class {
|
|
1157
|
-
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
|
|
1321
|
+
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
|
|
1158
1322
|
this.db = db;
|
|
1159
1323
|
this.entryRepo = entryRepo;
|
|
1160
1324
|
this.taskRepo = taskRepo;
|
|
@@ -1165,6 +1329,7 @@ var ImportExportService = class {
|
|
|
1165
1329
|
this.jobManager = jobManager;
|
|
1166
1330
|
this.embeddingService = embeddingService;
|
|
1167
1331
|
this.options = options;
|
|
1332
|
+
this.vectorRemoval = vectorRemoval;
|
|
1168
1333
|
}
|
|
1169
1334
|
async exportDump(entityIds) {
|
|
1170
1335
|
let ids;
|
|
@@ -1540,8 +1705,20 @@ var ImportExportService = class {
|
|
|
1540
1705
|
body: clipped?.body ?? fact.body,
|
|
1541
1706
|
tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
|
|
1542
1707
|
}, { operation: "importDump", trigger: "call" });
|
|
1543
|
-
if (!embedded) {
|
|
1544
|
-
|
|
1708
|
+
if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
1709
|
+
try {
|
|
1710
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
|
|
1711
|
+
} catch (hookErr) {
|
|
1712
|
+
console.warn(
|
|
1713
|
+
`[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
|
|
1714
|
+
hookErr
|
|
1715
|
+
);
|
|
1716
|
+
this.embeddingService.reportHookFailed(
|
|
1717
|
+
{ operation: "importDump", trigger: "call" },
|
|
1718
|
+
entityId,
|
|
1719
|
+
fact.id
|
|
1720
|
+
);
|
|
1721
|
+
}
|
|
1545
1722
|
}
|
|
1546
1723
|
}
|
|
1547
1724
|
}
|
|
@@ -1570,16 +1747,26 @@ var ImportExportService = class {
|
|
|
1570
1747
|
fact.id
|
|
1571
1748
|
);
|
|
1572
1749
|
}
|
|
1750
|
+
if (this.embeddingService.hasVectorHook()) {
|
|
1751
|
+
await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
|
|
1752
|
+
}
|
|
1573
1753
|
}
|
|
1574
1754
|
}
|
|
1575
|
-
|
|
1576
|
-
|
|
1755
|
+
const removedIds = softDeletedFactIds.filter(
|
|
1756
|
+
(id) => !upsertedFactIds.has(id) || upsertedDeletedFactIds.has(id)
|
|
1757
|
+
);
|
|
1758
|
+
if (this.vectorRemoval) {
|
|
1759
|
+
await this.vectorRemoval.deliverRemovals(
|
|
1760
|
+
entityId,
|
|
1761
|
+
Array.from(/* @__PURE__ */ new Set([...removedIds, ...upsertedDeletedFactIds])),
|
|
1762
|
+
"importDump",
|
|
1763
|
+
"call",
|
|
1764
|
+
removedIds
|
|
1765
|
+
);
|
|
1766
|
+
} else if (this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
1767
|
+
for (const factId of removedIds) {
|
|
1577
1768
|
try {
|
|
1578
|
-
await this.embeddingService.notifyEmbeddingPersisted(
|
|
1579
|
-
entityId,
|
|
1580
|
-
factId,
|
|
1581
|
-
null
|
|
1582
|
-
);
|
|
1769
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
1583
1770
|
} catch (hookErr) {
|
|
1584
1771
|
console.warn(
|
|
1585
1772
|
`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
|
|
@@ -2159,7 +2346,7 @@ function zeroChunkResult(duplicateOf) {
|
|
|
2159
2346
|
return result;
|
|
2160
2347
|
}
|
|
2161
2348
|
var IngestionService = class {
|
|
2162
|
-
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
|
|
2349
|
+
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
|
|
2163
2350
|
this.db = db;
|
|
2164
2351
|
this.prefix = prefix;
|
|
2165
2352
|
this.options = options;
|
|
@@ -2171,6 +2358,7 @@ var IngestionService = class {
|
|
|
2171
2358
|
this.jobManager = jobManager;
|
|
2172
2359
|
this.embeddingService = embeddingService;
|
|
2173
2360
|
this.ontologyService = ontologyService;
|
|
2361
|
+
this.vectorRemoval = vectorRemoval;
|
|
2174
2362
|
this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
|
|
2175
2363
|
}
|
|
2176
2364
|
async ingestDocument(entityId, params, opts) {
|
|
@@ -2201,12 +2389,12 @@ var IngestionService = class {
|
|
|
2201
2389
|
return zeroChunkResult(canonical);
|
|
2202
2390
|
}
|
|
2203
2391
|
}
|
|
2204
|
-
const { chunks, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
2205
|
-
if (
|
|
2392
|
+
const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
2393
|
+
if (chunks2.length === 0) return zeroChunkResult();
|
|
2206
2394
|
const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
|
|
2207
2395
|
const ingestGrounding = this.promptService.groundingFor("ingest");
|
|
2208
2396
|
const chunkResults = await withConcurrency(
|
|
2209
|
-
|
|
2397
|
+
chunks2.map((chunk, chunkIndex) => async () => {
|
|
2210
2398
|
const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
|
|
2211
2399
|
chunk,
|
|
2212
2400
|
params.promptOverride,
|
|
@@ -2264,7 +2452,7 @@ var IngestionService = class {
|
|
|
2264
2452
|
position: null,
|
|
2265
2453
|
message: safeErrorToString(e)
|
|
2266
2454
|
};
|
|
2267
|
-
const total =
|
|
2455
|
+
const total = chunks2.length;
|
|
2268
2456
|
const tags = [];
|
|
2269
2457
|
if (failure.tier) tags.push(`tier=${failure.tier}`);
|
|
2270
2458
|
if (failure.position !== null) tags.push(`position=${failure.position}`);
|
|
@@ -2341,11 +2529,11 @@ var IngestionService = class {
|
|
|
2341
2529
|
}
|
|
2342
2530
|
});
|
|
2343
2531
|
}
|
|
2344
|
-
if (failedChunks ===
|
|
2532
|
+
if (failedChunks === chunks2.length) {
|
|
2345
2533
|
throw new WikiIngestEmptyError({
|
|
2346
2534
|
parseFailures: failures,
|
|
2347
2535
|
sourceRef,
|
|
2348
|
-
chunks:
|
|
2536
|
+
chunks: chunks2.length
|
|
2349
2537
|
});
|
|
2350
2538
|
}
|
|
2351
2539
|
const insertedFacts = [];
|
|
@@ -2383,18 +2571,22 @@ var IngestionService = class {
|
|
|
2383
2571
|
);
|
|
2384
2572
|
if (failedChunks === 0) {
|
|
2385
2573
|
const uniqueDeletedSourceFactIds = Array.from(new Set(deletedSourceFactIds));
|
|
2386
|
-
|
|
2387
|
-
|
|
2388
|
-
|
|
2389
|
-
|
|
2390
|
-
|
|
2391
|
-
|
|
2392
|
-
|
|
2393
|
-
|
|
2394
|
-
|
|
2395
|
-
|
|
2396
|
-
|
|
2397
|
-
|
|
2574
|
+
if (this.vectorRemoval) {
|
|
2575
|
+
await this.vectorRemoval.deliverRemovals(entityId, uniqueDeletedSourceFactIds, "ingest", "call");
|
|
2576
|
+
} else if (this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
2577
|
+
for (const factId of uniqueDeletedSourceFactIds) {
|
|
2578
|
+
try {
|
|
2579
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
2580
|
+
} catch (hookErr) {
|
|
2581
|
+
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
|
|
2582
|
+
emitDiagnostic(this.options, {
|
|
2583
|
+
entityId,
|
|
2584
|
+
operation: "ingest",
|
|
2585
|
+
trigger: "call",
|
|
2586
|
+
code: "hook_failed",
|
|
2587
|
+
detail: { factId, reason: "on_embedding_persisted" }
|
|
2588
|
+
});
|
|
2589
|
+
}
|
|
2398
2590
|
}
|
|
2399
2591
|
}
|
|
2400
2592
|
}
|
|
@@ -2404,7 +2596,7 @@ var IngestionService = class {
|
|
|
2404
2596
|
this.searchService.evictCache(entityId);
|
|
2405
2597
|
const result = {
|
|
2406
2598
|
truncated,
|
|
2407
|
-
chunks:
|
|
2599
|
+
chunks: chunks2.length,
|
|
2408
2600
|
ingestedChunks,
|
|
2409
2601
|
failedChunks
|
|
2410
2602
|
};
|
|
@@ -2866,6 +3058,202 @@ function parseEmbedding(blob, text) {
|
|
|
2866
3058
|
return null;
|
|
2867
3059
|
}
|
|
2868
3060
|
|
|
3061
|
+
// src/services/VectorRemovalService.ts
|
|
3062
|
+
function removalGate(options) {
|
|
3063
|
+
if (options.forceDeleteIgnoreRankerHook === true) return "force";
|
|
3064
|
+
if (options.vectorRanker?.onEmbeddingPersisted) return "hook";
|
|
3065
|
+
return "none";
|
|
3066
|
+
}
|
|
3067
|
+
|
|
3068
|
+
// src/utils/temporal.ts
|
|
3069
|
+
function liveAtSql(mode, alias = "") {
|
|
3070
|
+
const from = mode === "asOf" ? `COALESCE(${alias}valid_from, ${alias}created_at) <= ?` : `(${alias}valid_from IS NULL OR ${alias}valid_from <= ?)`;
|
|
3071
|
+
return `(${from} AND (${alias}valid_to IS NULL OR ${alias}valid_to > ?))`;
|
|
3072
|
+
}
|
|
3073
|
+
function assertEpochMs(name, v) {
|
|
3074
|
+
if (typeof v !== "number" || !Number.isFinite(v) || v < 0) {
|
|
3075
|
+
throw new TypeError(`${name} must be a finite epoch-ms number >= 0`);
|
|
3076
|
+
}
|
|
3077
|
+
return Math.trunc(v);
|
|
3078
|
+
}
|
|
3079
|
+
|
|
3080
|
+
// src/repositories/EdgeRepository.ts
|
|
3081
|
+
var CONFIDENCE_RANK = {
|
|
3082
|
+
tentative: 0,
|
|
3083
|
+
inferred: 1,
|
|
3084
|
+
certain: 2
|
|
3085
|
+
};
|
|
3086
|
+
var EdgeRepository = class extends BaseRepository {
|
|
3087
|
+
/**
|
|
3088
|
+
* Insert an edge, silently skipping on primary-key or uniqueness conflicts.
|
|
3089
|
+
* Returns true when a row was inserted, false when skipped as a duplicate.
|
|
3090
|
+
* Throws when the insert was skipped due to an id collision with a different edge tuple.
|
|
3091
|
+
*/
|
|
3092
|
+
async addIgnoreDuplicate(edge, tx) {
|
|
3093
|
+
const executor = this.getExecutor(tx);
|
|
3094
|
+
const result = await executor.runAsync(
|
|
3095
|
+
`INSERT OR IGNORE INTO ${this.prefix}edges (id, entity_id, source_id, target_id, edge_type, created_at)
|
|
3096
|
+
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
3097
|
+
[edge.id, edge.entity_id, edge.source_id, edge.target_id, edge.edge_type, edge.created_at]
|
|
3098
|
+
);
|
|
3099
|
+
if (result.changes > 0) return true;
|
|
3100
|
+
const existing = await executor.getFirstAsync(
|
|
3101
|
+
`SELECT entity_id, source_id, target_id, edge_type FROM ${this.prefix}edges WHERE id = ?`,
|
|
3102
|
+
[edge.id]
|
|
3103
|
+
);
|
|
3104
|
+
if (!existing) return false;
|
|
3105
|
+
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) {
|
|
3106
|
+
throw new Error(
|
|
3107
|
+
`Edge id collision: ${JSON.stringify(edge.id)} already exists with a different (entity_id, source_id, target_id, edge_type) tuple`
|
|
3108
|
+
);
|
|
3109
|
+
}
|
|
3110
|
+
return false;
|
|
3111
|
+
}
|
|
3112
|
+
async getByEntityId(entityId, tx) {
|
|
3113
|
+
const executor = this.getExecutor(tx);
|
|
3114
|
+
const rows = await executor.getAllAsync(
|
|
3115
|
+
`SELECT * FROM ${this.prefix}edges WHERE entity_id = ? ORDER BY created_at ASC`,
|
|
3116
|
+
[entityId]
|
|
3117
|
+
);
|
|
3118
|
+
return rows.map(mapRowToEdge);
|
|
3119
|
+
}
|
|
3120
|
+
/** Hard delete — edges have no soft-delete concept, only presence/absence. `tx` is REQUIRED. */
|
|
3121
|
+
async bulkDeleteByEntityId(entityId, tx) {
|
|
3122
|
+
const executor = this.getExecutor(tx);
|
|
3123
|
+
await executor.runAsync(`DELETE FROM ${this.prefix}edges WHERE entity_id = ?`, [entityId]);
|
|
3124
|
+
}
|
|
3125
|
+
/**
|
|
3126
|
+
* Hard-delete every edge whose `source_id` is in `sourceFactIds`, scoped to
|
|
3127
|
+
* `entityId`. Returns the number of rows deleted. Edges have no soft-delete
|
|
3128
|
+
* concept; this method is named `softDeleteBySourceFactIds` for symmetry with
|
|
3129
|
+
* `EntryRepository.softDeleteBySource` (which IS a soft delete), but its
|
|
3130
|
+
* semantics are immediate presence/absence removal. Use ONLY inside an open
|
|
3131
|
+
* transaction — the method requires `tx` and performs no autocommit.
|
|
3132
|
+
*
|
|
3133
|
+
* Used by `IngestionService.upsertGraphCore` to retire the prior parse's
|
|
3134
|
+
* edges whose source facts are being superseded by `softDeleteBySource`.
|
|
3135
|
+
*/
|
|
3136
|
+
async softDeleteBySourceFactIds(entityId, sourceFactIds, tx) {
|
|
3137
|
+
if (sourceFactIds.length === 0) return 0;
|
|
3138
|
+
const executor = this.getExecutor(tx);
|
|
3139
|
+
const chunkSize = 500;
|
|
3140
|
+
let totalChanges = 0;
|
|
3141
|
+
for (let i = 0; i < sourceFactIds.length; i += chunkSize) {
|
|
3142
|
+
const chunk = sourceFactIds.slice(i, i + chunkSize);
|
|
3143
|
+
const placeholders = chunk.map(() => "?").join(",");
|
|
3144
|
+
const result = await executor.runAsync(
|
|
3145
|
+
`DELETE FROM ${this.prefix}edges
|
|
3146
|
+
WHERE entity_id = ? AND source_id IN (${placeholders})`,
|
|
3147
|
+
[entityId, ...chunk]
|
|
3148
|
+
);
|
|
3149
|
+
totalChanges += result.changes;
|
|
3150
|
+
}
|
|
3151
|
+
return totalChanges;
|
|
3152
|
+
}
|
|
3153
|
+
/**
|
|
3154
|
+
* Multi-hop traversal from `sourceId` via SQLite `WITH RECURSIVE`. All filtering,
|
|
3155
|
+
* dead-ending, cycle-guarding, capping, and ordering happens in this one query.
|
|
3156
|
+
* The anchor is validated (exists, right entity, not soft-deleted) but never gated
|
|
3157
|
+
* by confidence/source_type — only nodes discovered beyond it are.
|
|
3158
|
+
*/
|
|
3159
|
+
async getNeighborhood(entityId, sourceId, opts, tx) {
|
|
3160
|
+
const executor = this.getExecutor(tx);
|
|
3161
|
+
if (opts.edgeTypes && opts.edgeTypes.length === 0) {
|
|
3162
|
+
const anchor = await executor.getFirstAsync(
|
|
3163
|
+
`SELECT id FROM ${this.prefix}entries WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`,
|
|
3164
|
+
[sourceId, entityId]
|
|
3165
|
+
);
|
|
3166
|
+
return { nodeIds: anchor ? [anchor.id] : [], edges: [] };
|
|
3167
|
+
}
|
|
3168
|
+
const edgeTypesClause = opts.edgeTypes ? `e.edge_type IN (${opts.edgeTypes.map(() => "?").join(",")})` : "1=1";
|
|
3169
|
+
const excludeSourceTypesPlaceholders = opts.excludeSourceTypes.map(() => "?").join(",");
|
|
3170
|
+
const minConfidenceRank = CONFIDENCE_RANK[opts.minConfidence];
|
|
3171
|
+
const sql = `
|
|
3172
|
+
WITH RECURSIVE walk(node_id, depth, visited) AS (
|
|
3173
|
+
SELECT id, 0, ',' || id || ','
|
|
3174
|
+
FROM ${this.prefix}entries
|
|
3175
|
+
WHERE id = ? AND entity_id = ? AND deleted_at IS NULL
|
|
3176
|
+
|
|
3177
|
+
UNION
|
|
3178
|
+
|
|
3179
|
+
SELECT
|
|
3180
|
+
CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END,
|
|
3181
|
+
w.depth + 1,
|
|
3182
|
+
w.visited || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ','
|
|
3183
|
+
FROM walk w
|
|
3184
|
+
JOIN ${this.prefix}edges e
|
|
3185
|
+
ON e.entity_id = ?
|
|
3186
|
+
AND (
|
|
3187
|
+
(? != 'inbound' AND e.source_id = w.node_id) OR
|
|
3188
|
+
(? != 'outbound' AND e.target_id = w.node_id)
|
|
3189
|
+
)
|
|
3190
|
+
AND (${edgeTypesClause})
|
|
3191
|
+
JOIN ${this.prefix}entries n
|
|
3192
|
+
ON n.id = (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END)
|
|
3193
|
+
AND n.entity_id = ?
|
|
3194
|
+
AND n.deleted_at IS NULL
|
|
3195
|
+
AND (
|
|
3196
|
+
CASE n.confidence
|
|
3197
|
+
WHEN 'tentative' THEN 0
|
|
3198
|
+
WHEN 'inferred' THEN 1
|
|
3199
|
+
WHEN 'certain' THEN 2
|
|
3200
|
+
ELSE -1
|
|
3201
|
+
END
|
|
3202
|
+
) >= ?
|
|
3203
|
+
AND n.source_type NOT IN (${excludeSourceTypesPlaceholders})
|
|
3204
|
+
AND (? = 0 OR n.lifecycle_status != 'draft')
|
|
3205
|
+
AND ${liveAtSql(opts.live.mode, "n.")}
|
|
3206
|
+
WHERE w.depth < ?
|
|
3207
|
+
AND instr(w.visited, ',' || (CASE WHEN e.source_id = w.node_id THEN e.target_id ELSE e.source_id END) || ',') = 0
|
|
3208
|
+
)
|
|
3209
|
+
SELECT node_id, MIN(depth) AS depth
|
|
3210
|
+
FROM walk
|
|
3211
|
+
GROUP BY node_id
|
|
3212
|
+
ORDER BY depth ASC, (SELECT updated_at FROM ${this.prefix}entries WHERE id = node_id) DESC
|
|
3213
|
+
LIMIT ?
|
|
3214
|
+
`;
|
|
3215
|
+
const params = [
|
|
3216
|
+
sourceId,
|
|
3217
|
+
entityId,
|
|
3218
|
+
entityId,
|
|
3219
|
+
opts.direction,
|
|
3220
|
+
opts.direction,
|
|
3221
|
+
...opts.edgeTypes ?? [],
|
|
3222
|
+
entityId,
|
|
3223
|
+
minConfidenceRank,
|
|
3224
|
+
...opts.excludeSourceTypes,
|
|
3225
|
+
opts.excludeDrafts === true ? 1 : 0,
|
|
3226
|
+
opts.live.t,
|
|
3227
|
+
opts.live.t,
|
|
3228
|
+
opts.maxDepth,
|
|
3229
|
+
opts.maxNodes
|
|
3230
|
+
];
|
|
3231
|
+
const rows = await executor.getAllAsync(sql, params);
|
|
3232
|
+
const nodeIds = rows.map((r) => r.node_id);
|
|
3233
|
+
if (nodeIds.length === 0) return { nodeIds: [], edges: [] };
|
|
3234
|
+
const valueRows = nodeIds.map(() => "(?)").join(", ");
|
|
3235
|
+
const edgeRows = await executor.getAllAsync(
|
|
3236
|
+
`WITH neighborhood(node_id) AS (VALUES ${valueRows})
|
|
3237
|
+
SELECT e.* FROM ${this.prefix}edges e
|
|
3238
|
+
JOIN neighborhood ns ON e.source_id = ns.node_id
|
|
3239
|
+
JOIN neighborhood nt ON e.target_id = nt.node_id
|
|
3240
|
+
WHERE e.entity_id = ?`,
|
|
3241
|
+
[...nodeIds, entityId]
|
|
3242
|
+
);
|
|
3243
|
+
return { nodeIds, edges: edgeRows.map(mapRowToEdge) };
|
|
3244
|
+
}
|
|
3245
|
+
};
|
|
3246
|
+
function mapRowToEdge(row) {
|
|
3247
|
+
return {
|
|
3248
|
+
id: String(row.id),
|
|
3249
|
+
entity_id: String(row.entity_id),
|
|
3250
|
+
source_id: String(row.source_id),
|
|
3251
|
+
target_id: String(row.target_id),
|
|
3252
|
+
edge_type: String(row.edge_type),
|
|
3253
|
+
created_at: Number(row.created_at)
|
|
3254
|
+
};
|
|
3255
|
+
}
|
|
3256
|
+
|
|
2869
3257
|
// src/services/BoundedLlmCall.ts
|
|
2870
3258
|
var DEFAULT_BATCH_SIZE = 10;
|
|
2871
3259
|
var ESTIMATED_OUTPUT_TOKENS_PER_ITEM = 150;
|
|
@@ -3000,6 +3388,39 @@ async function runBatched(args) {
|
|
|
3000
3388
|
}
|
|
3001
3389
|
|
|
3002
3390
|
// src/db/schema.ts
|
|
3391
|
+
var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
|
|
3392
|
+
function resurrectLevel(sql) {
|
|
3393
|
+
if (sql.includes("embedding_failed_at")) return 2;
|
|
3394
|
+
return sql.includes("embedding_blob") ? 1 : 0;
|
|
3395
|
+
}
|
|
3396
|
+
async function createResurrectTrigger(db, prefix) {
|
|
3397
|
+
const name = `${prefix}vector_removals_resurrect`;
|
|
3398
|
+
const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
|
|
3399
|
+
const names = new Set(cols.map((c) => c.name));
|
|
3400
|
+
const want = !(names.has("embedding_blob") && names.has("embedding")) ? 0 : EMBED_MARKER_COLUMNS.every((c) => names.has(c)) ? 2 : 1;
|
|
3401
|
+
const existing = await db.getFirstAsync(
|
|
3402
|
+
`SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?`,
|
|
3403
|
+
[name]
|
|
3404
|
+
);
|
|
3405
|
+
if (existing) {
|
|
3406
|
+
if (resurrectLevel(existing.sql ?? "") >= want) return;
|
|
3407
|
+
await db.execAsync(`DROP TRIGGER IF EXISTS ${name};`);
|
|
3408
|
+
}
|
|
3409
|
+
const clearVector = want === 0 ? "" : `
|
|
3410
|
+
UPDATE ${prefix}entries
|
|
3411
|
+
SET embedding_blob = NULL, embedding = NULL${want === 2 ? `,
|
|
3412
|
+
embedding_failed_at = NULL, embedding_failure_kind = NULL, embedding_attempts = 0` : ""}
|
|
3413
|
+
WHERE id = NEW.id
|
|
3414
|
+
AND EXISTS (SELECT 1 FROM ${prefix}vector_removals WHERE fact_id = NEW.id AND confirmed_at IS NOT NULL);`;
|
|
3415
|
+
await db.execAsync(`
|
|
3416
|
+
CREATE TRIGGER IF NOT EXISTS ${name}
|
|
3417
|
+
AFTER UPDATE OF deleted_at ON ${prefix}entries
|
|
3418
|
+
WHEN OLD.deleted_at IS NOT NULL AND NEW.deleted_at IS NULL
|
|
3419
|
+
BEGIN${clearVector}
|
|
3420
|
+
DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
|
|
3421
|
+
END;
|
|
3422
|
+
`);
|
|
3423
|
+
}
|
|
3003
3424
|
async function createTemporalIndexesIfColumnsExist(db, prefix) {
|
|
3004
3425
|
const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
|
|
3005
3426
|
const names = new Set(cols.map((c) => c.name));
|
|
@@ -3066,6 +3487,7 @@ var MIGRATIONS = [
|
|
|
3066
3487
|
`ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`
|
|
3067
3488
|
);
|
|
3068
3489
|
}
|
|
3490
|
+
await createResurrectTrigger(db, prefix);
|
|
3069
3491
|
}
|
|
3070
3492
|
},
|
|
3071
3493
|
{
|
|
@@ -3259,6 +3681,7 @@ var MIGRATIONS = [
|
|
|
3259
3681
|
for (const [name, sql] of adds) {
|
|
3260
3682
|
if (!existing.has(name)) await db.execAsync(sql);
|
|
3261
3683
|
}
|
|
3684
|
+
await createResurrectTrigger(db, prefix);
|
|
3262
3685
|
}
|
|
3263
3686
|
},
|
|
3264
3687
|
{
|
|
@@ -3583,7 +4006,9 @@ async function runExtract(deps, ctx, batch) {
|
|
|
3583
4006
|
const base = { entityId, operation: "librarian", trigger };
|
|
3584
4007
|
const diagnostics = [];
|
|
3585
4008
|
const byLabel = new Map(batch.map((l) => [l.label, l]));
|
|
3586
|
-
|
|
4009
|
+
let newestAt = batch[0].at;
|
|
4010
|
+
for (const l of batch) if (l.at > newestAt) newestAt = l.at;
|
|
4011
|
+
const defaultValidFrom = Math.min(newestAt, Date.now());
|
|
3587
4012
|
const candidates = [];
|
|
3588
4013
|
(Array.isArray(parsed.facts) ? parsed.facts : []).forEach((raw, index) => {
|
|
3589
4014
|
const fact = validateFact(raw);
|
|
@@ -3593,7 +4018,7 @@ async function runExtract(deps, ctx, batch) {
|
|
|
3593
4018
|
}
|
|
3594
4019
|
const r = raw;
|
|
3595
4020
|
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 :
|
|
4021
|
+
const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
|
|
3597
4022
|
candidates.push({ index, fact, sourceLabel, validFrom });
|
|
3598
4023
|
});
|
|
3599
4024
|
const tasks = [];
|
|
@@ -3795,14 +4220,6 @@ async function runResolve(deps, ctx, ambiguous) {
|
|
|
3795
4220
|
return out;
|
|
3796
4221
|
}
|
|
3797
4222
|
|
|
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
4223
|
// src/services/TemporalService.ts
|
|
3807
4224
|
var HISTORY_MAX_DEPTH = 100;
|
|
3808
4225
|
var TemporalService = class {
|
|
@@ -4184,7 +4601,7 @@ var formatSkipError = (err) => {
|
|
|
4184
4601
|
return base;
|
|
4185
4602
|
};
|
|
4186
4603
|
var MaintenanceService = class {
|
|
4187
|
-
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
|
|
4604
|
+
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
|
|
4188
4605
|
this.db = db;
|
|
4189
4606
|
this.prefix = prefix;
|
|
4190
4607
|
this.options = options;
|
|
@@ -4197,7 +4614,10 @@ var MaintenanceService = class {
|
|
|
4197
4614
|
this.jobManager = jobManager;
|
|
4198
4615
|
this.embeddingService = embeddingService;
|
|
4199
4616
|
this.ontologyService = ontologyService;
|
|
4617
|
+
this.vectorRemoval = vectorRemoval;
|
|
4618
|
+
this.vectorRemovalRepo = vectorRemovalRepo;
|
|
4200
4619
|
this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
|
|
4620
|
+
this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
|
|
4201
4621
|
}
|
|
4202
4622
|
async runPrune(entityId, options) {
|
|
4203
4623
|
this.jobManager.acquireLock("prune", entityId);
|
|
@@ -4209,11 +4629,14 @@ var MaintenanceService = class {
|
|
|
4209
4629
|
this._validatePruneDuration(retainEventsFor, "retainEventsFor");
|
|
4210
4630
|
const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
|
|
4211
4631
|
this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
|
|
4632
|
+
const gate = removalGate(this.options);
|
|
4633
|
+
if (gate === "hook") this.embeddingService.validateDeletionTimeout();
|
|
4212
4634
|
const now = Date.now();
|
|
4213
4635
|
let syncedIds = [];
|
|
4214
4636
|
let deletedEntries = 0;
|
|
4215
4637
|
let deletedTasks = 0;
|
|
4216
4638
|
let deletedEvents = 0;
|
|
4639
|
+
let prunePartial = null;
|
|
4217
4640
|
if (pruneSupersededAfter !== null) {
|
|
4218
4641
|
const expiredCutoff = now - pruneSupersededAfter * 864e5;
|
|
4219
4642
|
const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
|
|
@@ -4222,55 +4645,89 @@ var MaintenanceService = class {
|
|
|
4222
4645
|
await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
|
|
4223
4646
|
});
|
|
4224
4647
|
syncedIds = [...expiredIds];
|
|
4648
|
+
if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
|
|
4649
|
+
await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
|
|
4650
|
+
}
|
|
4225
4651
|
}
|
|
4226
4652
|
}
|
|
4227
4653
|
if (retainSoftDeletedFor !== null) {
|
|
4228
4654
|
const cutoff = now - retainSoftDeletedFor * 864e5;
|
|
4229
4655
|
const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
|
|
4230
|
-
const
|
|
4231
|
-
|
|
4232
|
-
|
|
4233
|
-
|
|
4234
|
-
|
|
4235
|
-
|
|
4236
|
-
|
|
4237
|
-
|
|
4238
|
-
|
|
4656
|
+
const prunableIds = entriesToDelete.map((r) => r.id);
|
|
4657
|
+
const vr = this.vectorRemoval;
|
|
4658
|
+
const vrRepo = this.vectorRemovalRepo;
|
|
4659
|
+
const ledgerOn = !!vr && !!vrRepo && await vr.ledgerPresent();
|
|
4660
|
+
let deletable = prunableIds;
|
|
4661
|
+
let removeLedger = false;
|
|
4662
|
+
let kept = [];
|
|
4663
|
+
let timedOut = false;
|
|
4664
|
+
let cause;
|
|
4665
|
+
let firstFailed;
|
|
4666
|
+
let failedOrder = [];
|
|
4667
|
+
if (ledgerOn && vr && vrRepo) {
|
|
4668
|
+
if (gate === "hook" && prunableIds.length > 0) {
|
|
4669
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
4670
|
+
await vrRepo.backstopEnqueue(entityId, prunableIds, now, tx);
|
|
4671
|
+
});
|
|
4672
|
+
}
|
|
4673
|
+
const result = prunableIds.length > 0 ? await vr.drain({ entityId, ids: prunableIds }) : { failedIds: [], timedOut: false, firstCause: void 0 };
|
|
4674
|
+
if (gate === "hook") {
|
|
4675
|
+
timedOut = result.timedOut;
|
|
4676
|
+
cause = result.firstCause;
|
|
4677
|
+
failedOrder = result.failedIds;
|
|
4678
|
+
} else if (gate === "force") {
|
|
4679
|
+
removeLedger = true;
|
|
4680
|
+
} else {
|
|
4681
|
+
removeLedger = !await vr.externalIndexInUse();
|
|
4239
4682
|
}
|
|
4683
|
+
} else if (gate === "hook") {
|
|
4684
|
+
const r = await this.embeddingService.callRemovalHookEach(entityId, prunableIds);
|
|
4685
|
+
const failedSet = new Set(r.failed);
|
|
4686
|
+
kept = r.failed;
|
|
4687
|
+
deletable = prunableIds.filter((id) => !failedSet.has(id));
|
|
4688
|
+
timedOut = r.timedOut;
|
|
4689
|
+
cause = r.cause;
|
|
4690
|
+
firstFailed = kept[0];
|
|
4240
4691
|
}
|
|
4241
|
-
const
|
|
4242
|
-
syncedIds = [...syncedIds, ...succeededIds];
|
|
4692
|
+
const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
|
|
4243
4693
|
await this.db.withTransactionAsync(async (tx) => {
|
|
4244
|
-
if (
|
|
4245
|
-
|
|
4694
|
+
if (hookLedger && vrRepo && prunableIds.length > 0) {
|
|
4695
|
+
const status = await vrRepo.statusFor(prunableIds, tx);
|
|
4696
|
+
deletable = prunableIds.filter((id) => status.get(id) !== "pending");
|
|
4697
|
+
kept = prunableIds.filter((id) => status.get(id) === "pending");
|
|
4698
|
+
}
|
|
4699
|
+
if (deletable.length > 0) {
|
|
4700
|
+
const deletedIds = [];
|
|
4701
|
+
deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
|
|
4702
|
+
if (hookLedger) {
|
|
4703
|
+
const gone = new Set(deletedIds);
|
|
4704
|
+
const skipped = deletable.filter((id) => !gone.has(id));
|
|
4705
|
+
if (skipped.length > 0) {
|
|
4706
|
+
const after = await vrRepo.statusFor(skipped, tx);
|
|
4707
|
+
kept = [...kept, ...skipped.filter((id) => after.get(id) === "pending")];
|
|
4708
|
+
}
|
|
4709
|
+
deletable = deletedIds;
|
|
4710
|
+
}
|
|
4711
|
+
if (vrRepo && ledgerOn) {
|
|
4712
|
+
if (removeLedger) await vrRepo.deleteForFacts(entityId, deletable, tx, "all");
|
|
4713
|
+
else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
|
|
4714
|
+
}
|
|
4246
4715
|
}
|
|
4247
4716
|
deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
|
|
4248
4717
|
});
|
|
4249
|
-
if (
|
|
4250
|
-
|
|
4251
|
-
|
|
4252
|
-
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4256
|
-
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
|
|
4261
|
-
);
|
|
4718
|
+
if (hookLedger) {
|
|
4719
|
+
const keptSet = new Set(kept);
|
|
4720
|
+
firstFailed = failedOrder.find((id) => keptSet.has(id)) ?? kept[0];
|
|
4721
|
+
}
|
|
4722
|
+
syncedIds = [...syncedIds, ...deletable];
|
|
4723
|
+
if (kept.length > 0) {
|
|
4724
|
+
if (timedOut) {
|
|
4725
|
+
prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("Deletion hook timed out") };
|
|
4726
|
+
} else if (cause === void 0) {
|
|
4727
|
+
prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("external removal not confirmed") };
|
|
4728
|
+
} else {
|
|
4729
|
+
prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: this._sanitizeRankerError(cause) };
|
|
4262
4730
|
}
|
|
4263
|
-
const errMsg = failure.cause?.message ?? "";
|
|
4264
|
-
const isValidationError = errMsg.startsWith("Invalid deletionHookTimeoutMs");
|
|
4265
|
-
const sanitizedCause = isValidationError ? failure.cause : this._sanitizeRankerError(failure.cause);
|
|
4266
|
-
throw new PrunePartialFailureError(
|
|
4267
|
-
succeeded.length,
|
|
4268
|
-
failure.factId,
|
|
4269
|
-
remaining,
|
|
4270
|
-
sanitizedCause,
|
|
4271
|
-
deletedTasks,
|
|
4272
|
-
0
|
|
4273
|
-
);
|
|
4274
4731
|
}
|
|
4275
4732
|
}
|
|
4276
4733
|
if (retainEventsFor !== null) {
|
|
@@ -4307,6 +4764,16 @@ var MaintenanceService = class {
|
|
|
4307
4764
|
await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
|
|
4308
4765
|
}
|
|
4309
4766
|
await this.searchService.syncEntries(entityId, syncedIds);
|
|
4767
|
+
if (prunePartial) {
|
|
4768
|
+
throw new PrunePartialFailureError(
|
|
4769
|
+
deletedEntries,
|
|
4770
|
+
prunePartial.failedAt,
|
|
4771
|
+
prunePartial.remaining,
|
|
4772
|
+
prunePartial.cause,
|
|
4773
|
+
deletedTasks,
|
|
4774
|
+
deletedEvents
|
|
4775
|
+
);
|
|
4776
|
+
}
|
|
4310
4777
|
return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
|
|
4311
4778
|
} finally {
|
|
4312
4779
|
this.jobManager.releaseLock("prune", entityId);
|
|
@@ -4411,6 +4878,7 @@ var MaintenanceService = class {
|
|
|
4411
4878
|
}
|
|
4412
4879
|
const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
|
|
4413
4880
|
if (result.ok) embedded++;
|
|
4881
|
+
else if (result.kind === "fact_deleted") skipped++;
|
|
4414
4882
|
else failed++;
|
|
4415
4883
|
}
|
|
4416
4884
|
if (embedded > 0) {
|
|
@@ -4428,6 +4896,9 @@ var MaintenanceService = class {
|
|
|
4428
4896
|
if (params.clearAll && (params.entryId !== void 0 || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
|
|
4429
4897
|
throw new Error("forget() clearAll is mutually exclusive with entryId, taskId, sourceRef, and sourceHash");
|
|
4430
4898
|
}
|
|
4899
|
+
if (params.includeEvents && !params.clearAll) {
|
|
4900
|
+
throw new Error("forget() includeEvents requires clearAll: true");
|
|
4901
|
+
}
|
|
4431
4902
|
if (opts?.dryRun === true) {
|
|
4432
4903
|
return this.forgetDryRun(entityId, params);
|
|
4433
4904
|
}
|
|
@@ -4436,13 +4907,24 @@ var MaintenanceService = class {
|
|
|
4436
4907
|
const now = Date.now();
|
|
4437
4908
|
let deletedEntries = 0;
|
|
4438
4909
|
let deletedTasks = 0;
|
|
4910
|
+
let deletedEvents = 0;
|
|
4439
4911
|
const deletedEntryIds = [];
|
|
4912
|
+
const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
|
|
4440
4913
|
await this.db.withTransactionAsync(async (tx) => {
|
|
4441
4914
|
if (params.clearAll) {
|
|
4442
|
-
|
|
4915
|
+
for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
|
|
4443
4916
|
deletedEntries = await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
|
|
4444
4917
|
deletedTasks = await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
|
|
4445
|
-
await this.
|
|
4918
|
+
if (await this.sourceRefIndexPresent(tx)) {
|
|
4919
|
+
await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
|
|
4920
|
+
}
|
|
4921
|
+
await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
|
|
4922
|
+
if (params.includeEvents) {
|
|
4923
|
+
deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
|
|
4924
|
+
await this.metadataRepo.deleteCheckpoint(entityId, tx);
|
|
4925
|
+
} else {
|
|
4926
|
+
await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
|
|
4927
|
+
}
|
|
4446
4928
|
await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
|
|
4447
4929
|
} else {
|
|
4448
4930
|
const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
|
|
@@ -4460,7 +4942,7 @@ var MaintenanceService = class {
|
|
|
4460
4942
|
if (entryId) deletedEntryIds.push(entryId);
|
|
4461
4943
|
}
|
|
4462
4944
|
if (sourceRef || sourceHash) {
|
|
4463
|
-
|
|
4945
|
+
for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
|
|
4464
4946
|
}
|
|
4465
4947
|
const entryPromise = params.entryId ? this.entryRepo.softDelete(params.entryId, entityId, tx).then((r) => r.changes > 0) : null;
|
|
4466
4948
|
const taskDeletedPromise = params.taskId ? this.taskRepo.softDeleteById(params.taskId, entityId, tx).then((r) => r.changes > 0) : null;
|
|
@@ -4476,29 +4958,78 @@ var MaintenanceService = class {
|
|
|
4476
4958
|
if (taskResult) deletedTasks++;
|
|
4477
4959
|
deletedEntries += refResult;
|
|
4478
4960
|
}
|
|
4961
|
+
if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
|
|
4962
|
+
await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
|
|
4963
|
+
}
|
|
4479
4964
|
});
|
|
4480
4965
|
const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
|
|
4481
4966
|
await this.searchService.syncEntries(entityId, uniqueDeletedIds);
|
|
4482
|
-
|
|
4967
|
+
if (uniqueDeletedIds.length > 0) {
|
|
4968
|
+
const firstId = uniqueDeletedIds[0];
|
|
4969
|
+
const vr = this.vectorRemoval;
|
|
4970
|
+
const vrRepo = this.vectorRemovalRepo;
|
|
4971
|
+
let unconfirmed = [];
|
|
4972
|
+
let timedOut = false;
|
|
4973
|
+
let cause;
|
|
4974
|
+
let timedOutId;
|
|
4483
4975
|
try {
|
|
4484
|
-
|
|
4485
|
-
|
|
4486
|
-
|
|
4487
|
-
|
|
4488
|
-
|
|
4976
|
+
if (vr && vrRepo && ledgerOn) {
|
|
4977
|
+
const result = await vr.drain({ entityId, ids: uniqueDeletedIds });
|
|
4978
|
+
if (vr.gate() === "hook") {
|
|
4979
|
+
const status = await vrRepo.statusFor(uniqueDeletedIds);
|
|
4980
|
+
unconfirmed = uniqueDeletedIds.filter((id) => status.get(id) === "pending");
|
|
4981
|
+
timedOut = result.timedOut;
|
|
4982
|
+
timedOutId = result.timedOutId;
|
|
4983
|
+
cause = result.firstCause;
|
|
4984
|
+
}
|
|
4985
|
+
} else if (this.options.vectorRanker?.onEmbeddingPersisted && this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
4986
|
+
const r = await this.embeddingService.callRemovalHookEach(entityId, uniqueDeletedIds);
|
|
4987
|
+
unconfirmed = r.failed;
|
|
4988
|
+
timedOut = r.timedOut;
|
|
4989
|
+
timedOutId = r.timedOutId;
|
|
4990
|
+
cause = r.cause;
|
|
4489
4991
|
}
|
|
4992
|
+
} catch (hookErr) {
|
|
4490
4993
|
const errMsg = hookErr?.message ?? "";
|
|
4491
4994
|
if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
|
|
4492
|
-
throw new Error(`forget(${entityId}/${
|
|
4995
|
+
throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
|
|
4493
4996
|
}
|
|
4494
|
-
throw
|
|
4997
|
+
throw hookErr;
|
|
4998
|
+
}
|
|
4999
|
+
if (unconfirmed.length > 0) {
|
|
5000
|
+
const head = `forget(${entityId}/${(timedOut ? timedOutId : void 0) ?? unconfirmed[0]}) failed: `;
|
|
5001
|
+
const message = timedOut ? head + (cause?.message ?? "onEmbeddingPersisted timed out") : cause === void 0 ? head + "ANN cleanup not confirmed" : head + "ANN cleanup hook rejected";
|
|
5002
|
+
throw new WikiExternalDeletionError(message, {
|
|
5003
|
+
entityId,
|
|
5004
|
+
unconfirmedIds: unconfirmed.slice(0, 100),
|
|
5005
|
+
unconfirmedCount: unconfirmed.length,
|
|
5006
|
+
timedOut,
|
|
5007
|
+
cause: timedOut || cause === void 0 ? void 0 : this._sanitizeRankerError(cause)
|
|
5008
|
+
});
|
|
4495
5009
|
}
|
|
4496
5010
|
}
|
|
4497
|
-
|
|
5011
|
+
if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
|
|
5012
|
+
return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
|
|
4498
5013
|
} finally {
|
|
4499
5014
|
this.jobManager.releaseLock("forget", entityId);
|
|
4500
5015
|
}
|
|
4501
5016
|
}
|
|
5017
|
+
/** Heal's post-commit removal delivery (spec §5.7). Never throws. */
|
|
5018
|
+
async deliverHealRemovals(entityId, ids, trigger) {
|
|
5019
|
+
if (this.vectorRemoval) {
|
|
5020
|
+
await this.vectorRemoval.deliverRemovals(entityId, ids, "heal", trigger);
|
|
5021
|
+
return;
|
|
5022
|
+
}
|
|
5023
|
+
if (this.options.forceDeleteIgnoreRankerHook === true) return;
|
|
5024
|
+
for (const factId of ids) {
|
|
5025
|
+
try {
|
|
5026
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
5027
|
+
} catch (hookErr) {
|
|
5028
|
+
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
|
|
5029
|
+
emitDiagnostic(this.options, { entityId, operation: "heal", trigger, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
|
|
5030
|
+
}
|
|
5031
|
+
}
|
|
5032
|
+
}
|
|
4502
5033
|
/**
|
|
4503
5034
|
* Whether forget() should soft-delete in source_ref_index (#316,
|
|
4504
5035
|
* specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
|
|
@@ -4545,6 +5076,10 @@ var MaintenanceService = class {
|
|
|
4545
5076
|
if (params.clearAll) {
|
|
4546
5077
|
const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
|
|
4547
5078
|
const tasks = await this.taskRepo.countLiveByEntityId(entityId);
|
|
5079
|
+
if (params.includeEvents) {
|
|
5080
|
+
const events = await this.eventRepo.count(entityId);
|
|
5081
|
+
return { deleted: { entries: entries2, tasks, events }, metadataReset: true };
|
|
5082
|
+
}
|
|
4548
5083
|
return { deleted: { entries: entries2, tasks }, metadataReset: true };
|
|
4549
5084
|
}
|
|
4550
5085
|
const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
|
|
@@ -4692,14 +5227,7 @@ var MaintenanceService = class {
|
|
|
4692
5227
|
staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
|
|
4693
5228
|
}
|
|
4694
5229
|
});
|
|
4695
|
-
|
|
4696
|
-
try {
|
|
4697
|
-
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
4698
|
-
} catch (hookErr) {
|
|
4699
|
-
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal orphan pass for ${factId}:`, hookErr);
|
|
4700
|
-
emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
|
|
4701
|
-
}
|
|
4702
|
-
}
|
|
5230
|
+
await this.deliverHealRemovals(entityId, orphanedIds, trigger);
|
|
4703
5231
|
const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
|
|
4704
5232
|
const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
|
|
4705
5233
|
if (healCandidates.length === 0 || keywordUnavailable) {
|
|
@@ -4888,14 +5416,7 @@ var MaintenanceService = class {
|
|
|
4888
5416
|
...insertedFacts.map((f) => f.id)
|
|
4889
5417
|
]));
|
|
4890
5418
|
await this.searchService.syncEntries(entityId, healSyncIds);
|
|
4891
|
-
|
|
4892
|
-
try {
|
|
4893
|
-
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
4894
|
-
} catch (hookErr) {
|
|
4895
|
-
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
|
|
4896
|
-
emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
|
|
4897
|
-
}
|
|
4898
|
-
}
|
|
5419
|
+
await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
|
|
4899
5420
|
for (const fact of insertedFacts) {
|
|
4900
5421
|
await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
|
|
4901
5422
|
}
|