@equationalapplications/core-llm-wiki 8.3.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/dist/{chunk-V432RHCG.mjs → chunk-EKYWAR2E.mjs} +975 -111
- 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 +1376 -278
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +264 -31
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-BT5qSnGB.d.mts → testing-Og5x9rFu.d.mts} +336 -30
- package/dist/{testing-BT5qSnGB.d.ts → testing-Og5x9rFu.d.ts} +336 -30
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +397 -105
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-V432RHCG.mjs.map +0 -1
package/dist/index.js
CHANGED
|
@@ -15,6 +15,143 @@ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read fr
|
|
|
15
15
|
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
16
16
|
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
|
|
17
17
|
|
|
18
|
+
// src/utils/diagnostics.ts
|
|
19
|
+
var SEVERITY = {
|
|
20
|
+
ingest_chunk_failed: "warn",
|
|
21
|
+
fact_rejected: "warn",
|
|
22
|
+
task_rejected: "warn",
|
|
23
|
+
fact_deduplicated: "info",
|
|
24
|
+
edge_dropped: "warn",
|
|
25
|
+
embedding_failed: "warn",
|
|
26
|
+
hook_failed: "warn",
|
|
27
|
+
background_job_failed: "error",
|
|
28
|
+
heal_skipped: "warn",
|
|
29
|
+
grounding_missing: "warn",
|
|
30
|
+
grounding_failed: "warn",
|
|
31
|
+
classification_low_confidence: "info",
|
|
32
|
+
classification_invalid: "warn",
|
|
33
|
+
llm_usage: "info",
|
|
34
|
+
librarian_gate: "info",
|
|
35
|
+
librarian_op_rejected: "warn",
|
|
36
|
+
contradicts_document: "warn",
|
|
37
|
+
resolve_failed: "warn",
|
|
38
|
+
read_budget: "info",
|
|
39
|
+
event_retention_held: "info",
|
|
40
|
+
event_created_at_clamped: "warn",
|
|
41
|
+
event_created_at_restamped: "info",
|
|
42
|
+
external_deletion_pending: "warn",
|
|
43
|
+
external_deletion_discarded: "warn"
|
|
44
|
+
};
|
|
45
|
+
var MESSAGE = {
|
|
46
|
+
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
47
|
+
fact_rejected: "An extracted fact failed validation and was not written.",
|
|
48
|
+
task_rejected: "An extracted task failed validation and was not written.",
|
|
49
|
+
fact_deduplicated: "An extracted fact duplicated an existing fact and was not written.",
|
|
50
|
+
edge_dropped: "An extracted edge could not be resolved against the ontology and was not written.",
|
|
51
|
+
embedding_failed: "A fact could not be embedded.",
|
|
52
|
+
hook_failed: "A host hook threw or rejected.",
|
|
53
|
+
background_job_failed: "A background maintenance job failed.",
|
|
54
|
+
heal_skipped: "Heal skipped a candidate fact, or the whole LLM pass when keyword search is unavailable.",
|
|
55
|
+
grounding_missing: "A fact carried no qualifying evidence and was stored as a draft.",
|
|
56
|
+
grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
|
|
57
|
+
classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
|
|
58
|
+
classification_invalid: "A classifier answer was invalid and was not applied.",
|
|
59
|
+
llm_usage: "An LLM call completed; token usage attached.",
|
|
60
|
+
librarian_gate: "Librarian gate outcome counts for one pass.",
|
|
61
|
+
librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
|
|
62
|
+
contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
|
|
63
|
+
resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
|
|
64
|
+
read_budget: "A read was packed to a token budget.",
|
|
65
|
+
event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
|
|
66
|
+
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.",
|
|
67
|
+
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.",
|
|
68
|
+
external_deletion_pending: "Removals owed to the external vector index are still pending.",
|
|
69
|
+
external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set."
|
|
70
|
+
};
|
|
71
|
+
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
72
|
+
function copyDetail(detail) {
|
|
73
|
+
const copy = { ...detail };
|
|
74
|
+
if (detail.chunkIndexes) copy.chunkIndexes = detail.chunkIndexes.slice();
|
|
75
|
+
return copy;
|
|
76
|
+
}
|
|
77
|
+
function emitDiagnostic(options, input) {
|
|
78
|
+
const hook = options.onDiagnostic;
|
|
79
|
+
if (hook === void 0 || hook === null) return;
|
|
80
|
+
if (typeof hook !== "function") {
|
|
81
|
+
if (!warnedNonFunction.has(options)) {
|
|
82
|
+
warnedNonFunction.add(options);
|
|
83
|
+
console.warn("[WikiMemory] onDiagnostic is not a function; diagnostics are disabled.");
|
|
84
|
+
}
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const diagnostic = {
|
|
88
|
+
code: input.code,
|
|
89
|
+
severity: SEVERITY[input.code],
|
|
90
|
+
operation: input.operation,
|
|
91
|
+
trigger: input.trigger,
|
|
92
|
+
entityId: input.entityId,
|
|
93
|
+
at: Date.now(),
|
|
94
|
+
message: MESSAGE[input.code],
|
|
95
|
+
...input.detail ? { detail: copyDetail(input.detail) } : {}
|
|
96
|
+
};
|
|
97
|
+
try {
|
|
98
|
+
const returned = hook(diagnostic);
|
|
99
|
+
if (returned !== void 0) {
|
|
100
|
+
Promise.resolve(returned).catch((err) => {
|
|
101
|
+
console.warn("[WikiMemory] onDiagnostic hook rejected:", err);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
} catch (err) {
|
|
105
|
+
console.warn("[WikiMemory] onDiagnostic hook threw:", err);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
var DiagnosticBuffer = class {
|
|
109
|
+
constructor() {
|
|
110
|
+
this.items = [];
|
|
111
|
+
}
|
|
112
|
+
push(input) {
|
|
113
|
+
this.items.push(input);
|
|
114
|
+
}
|
|
115
|
+
get size() {
|
|
116
|
+
return this.items.length;
|
|
117
|
+
}
|
|
118
|
+
flush(options) {
|
|
119
|
+
const pending = this.items;
|
|
120
|
+
this.items = [];
|
|
121
|
+
for (const input of pending) emitDiagnostic(options, input);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Emit only the buffered diagnostics whose code is in `codes` and discard
|
|
125
|
+
* the rest. The buffer is empty afterwards either way.
|
|
126
|
+
*
|
|
127
|
+
* For an operation that did real work before its write was rolled back:
|
|
128
|
+
* some buffered diagnostics describe that work and are still true, while
|
|
129
|
+
* others describe rows that no longer exist (anything carrying a `factId`
|
|
130
|
+
* minted inside the aborted transaction). `flush` would emit both and
|
|
131
|
+
* `discard` would drop both; this emits the first set only.
|
|
132
|
+
*/
|
|
133
|
+
flushOnly(options, codes) {
|
|
134
|
+
const pending = this.items;
|
|
135
|
+
this.items = [];
|
|
136
|
+
for (const input of pending) {
|
|
137
|
+
if (codes.includes(input.code)) emitDiagnostic(options, input);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
discard() {
|
|
141
|
+
this.items = [];
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
function edgeDropDiagnostic(drop, ctx) {
|
|
145
|
+
const detail = { reason: drop.reason };
|
|
146
|
+
const factId = ctx.factId ?? drop.sourceId;
|
|
147
|
+
if (factId) detail.factId = factId;
|
|
148
|
+
if (drop.edgeType) detail.edgeType = drop.edgeType;
|
|
149
|
+
if (drop.sourceNodeType) detail.sourceNodeType = drop.sourceNodeType;
|
|
150
|
+
if (drop.targetNodeType) detail.targetNodeType = drop.targetNodeType;
|
|
151
|
+
if (ctx.sourceRef) detail.sourceRef = ctx.sourceRef;
|
|
152
|
+
return { code: "edge_dropped", operation: ctx.operation, trigger: ctx.trigger, entityId: ctx.entityId, detail };
|
|
153
|
+
}
|
|
154
|
+
|
|
18
155
|
// src/repositories/rowMappers.ts
|
|
19
156
|
function parseJsonArray(s, fallback) {
|
|
20
157
|
if (Array.isArray(s)) return s;
|
|
@@ -103,6 +240,17 @@ var WikiBusyError = class extends Error {
|
|
|
103
240
|
this.entityId = entityId;
|
|
104
241
|
}
|
|
105
242
|
};
|
|
243
|
+
var WikiExternalDeletionError = class extends Error {
|
|
244
|
+
constructor(message, params) {
|
|
245
|
+
super(message, params.cause ? { cause: params.cause } : void 0);
|
|
246
|
+
this.code = "WIKI_EXTERNAL_DELETION";
|
|
247
|
+
this.name = "WikiExternalDeletionError";
|
|
248
|
+
this.entityId = params.entityId;
|
|
249
|
+
this.unconfirmedIds = params.unconfirmedIds;
|
|
250
|
+
this.unconfirmedCount = params.unconfirmedCount;
|
|
251
|
+
this.timedOut = params.timedOut;
|
|
252
|
+
}
|
|
253
|
+
};
|
|
106
254
|
var WikiDuplicateHashError = class extends Error {
|
|
107
255
|
constructor(params) {
|
|
108
256
|
super(`Duplicate source hash for entity ${params.entityId}; another ref already holds this content`);
|
|
@@ -603,14 +751,14 @@ function chunkText(input, maxChunkLength, overlap) {
|
|
|
603
751
|
if (!Number.isInteger(overlap) || overlap < 0 || overlap >= maxChunkLength) {
|
|
604
752
|
throw new Error("overlap must be a non-negative integer < maxChunkLength");
|
|
605
753
|
}
|
|
606
|
-
const
|
|
754
|
+
const chunks2 = [];
|
|
607
755
|
let truncated = false;
|
|
608
756
|
let cursor = 0;
|
|
609
757
|
const halfMax = Math.floor(maxChunkLength / 2);
|
|
610
758
|
while (cursor < text.length) {
|
|
611
759
|
const remaining = text.length - cursor;
|
|
612
760
|
if (remaining <= maxChunkLength) {
|
|
613
|
-
|
|
761
|
+
chunks2.push(safeSlice(text, cursor, text.length));
|
|
614
762
|
break;
|
|
615
763
|
}
|
|
616
764
|
const windowEnd = cursor + maxChunkLength;
|
|
@@ -642,11 +790,11 @@ function chunkText(input, maxChunkLength, overlap) {
|
|
|
642
790
|
truncated = true;
|
|
643
791
|
splitPoint = windowEnd;
|
|
644
792
|
}
|
|
645
|
-
|
|
793
|
+
chunks2.push(safeSlice(text, cursor, splitPoint));
|
|
646
794
|
const next = Math.max(splitPoint - overlap, cursor + 1);
|
|
647
795
|
cursor = next;
|
|
648
796
|
}
|
|
649
|
-
return { chunks, truncated };
|
|
797
|
+
return { chunks: chunks2, truncated };
|
|
650
798
|
}
|
|
651
799
|
async function withConcurrency(tasks, limit) {
|
|
652
800
|
const results = new Array(tasks.length);
|
|
@@ -902,8 +1050,83 @@ async function setupDatabase(db, prefix) {
|
|
|
902
1050
|
CREATE INDEX IF NOT EXISTS ${prefix}outbox_created_at
|
|
903
1051
|
ON ${prefix}outbox (created_at);
|
|
904
1052
|
`);
|
|
1053
|
+
await db.execAsync(`
|
|
1054
|
+
CREATE TABLE IF NOT EXISTS ${prefix}vector_removals (
|
|
1055
|
+
seq INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1056
|
+
entity_id TEXT NOT NULL,
|
|
1057
|
+
fact_id TEXT NOT NULL UNIQUE,
|
|
1058
|
+
enqueued_at INTEGER NOT NULL,
|
|
1059
|
+
attempts INTEGER NOT NULL DEFAULT 0,
|
|
1060
|
+
last_attempt_at INTEGER,
|
|
1061
|
+
confirmed_at INTEGER
|
|
1062
|
+
);
|
|
1063
|
+
CREATE INDEX IF NOT EXISTS ${prefix}vector_removals_pending
|
|
1064
|
+
ON ${prefix}vector_removals (entity_id, attempts, seq) WHERE confirmed_at IS NULL;
|
|
1065
|
+
|
|
1066
|
+
CREATE TRIGGER IF NOT EXISTS ${prefix}vector_removals_enqueue
|
|
1067
|
+
AFTER UPDATE OF deleted_at ON ${prefix}entries
|
|
1068
|
+
WHEN OLD.deleted_at IS NULL AND NEW.deleted_at IS NOT NULL
|
|
1069
|
+
BEGIN
|
|
1070
|
+
-- DELETE then INSERT, not INSERT OR REPLACE: an outer UPSERT's conflict
|
|
1071
|
+
-- handling would override OR REPLACE and abort on fact_id (spec rev 5).
|
|
1072
|
+
DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
|
|
1073
|
+
INSERT INTO ${prefix}vector_removals (entity_id, fact_id, enqueued_at)
|
|
1074
|
+
VALUES (NEW.entity_id, NEW.id, CAST(strftime('%s','now') AS INTEGER) * 1000);
|
|
1075
|
+
END;
|
|
1076
|
+
|
|
1077
|
+
-- A hard delete outside prune (host SQL, an older engine after a
|
|
1078
|
+
-- downgrade). A live fact is owed only where an external index was in use;
|
|
1079
|
+
-- a soft-deleted one drops the rows nothing can owe (spec rev 5).
|
|
1080
|
+
CREATE TRIGGER IF NOT EXISTS ${prefix}vector_removals_hard_delete
|
|
1081
|
+
AFTER DELETE ON ${prefix}entries
|
|
1082
|
+
BEGIN
|
|
1083
|
+
DELETE FROM ${prefix}vector_removals
|
|
1084
|
+
WHERE fact_id = OLD.id
|
|
1085
|
+
AND (OLD.deleted_at IS NULL
|
|
1086
|
+
OR confirmed_at IS NOT NULL
|
|
1087
|
+
OR NOT EXISTS (SELECT 1 FROM ${prefix}meta WHERE key = 'external_index_in_use' AND value = '1'));
|
|
1088
|
+
INSERT INTO ${prefix}vector_removals (entity_id, fact_id, enqueued_at)
|
|
1089
|
+
SELECT OLD.entity_id, OLD.id, CAST(strftime('%s','now') AS INTEGER) * 1000
|
|
1090
|
+
WHERE OLD.deleted_at IS NULL
|
|
1091
|
+
AND EXISTS (SELECT 1 FROM ${prefix}meta WHERE key = 'external_index_in_use' AND value = '1');
|
|
1092
|
+
END;
|
|
1093
|
+
`);
|
|
905
1094
|
await createOkfV02IndexesIfColumnsExist(db, prefix);
|
|
906
1095
|
await createTemporalIndexesIfColumnsExist(db, prefix);
|
|
1096
|
+
await createResurrectTrigger(db, prefix);
|
|
1097
|
+
}
|
|
1098
|
+
var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
|
|
1099
|
+
function resurrectLevel(sql) {
|
|
1100
|
+
if (sql.includes("embedding_failed_at")) return 2;
|
|
1101
|
+
return sql.includes("embedding_blob") ? 1 : 0;
|
|
1102
|
+
}
|
|
1103
|
+
async function createResurrectTrigger(db, prefix) {
|
|
1104
|
+
const name = `${prefix}vector_removals_resurrect`;
|
|
1105
|
+
const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
|
|
1106
|
+
const names = new Set(cols.map((c) => c.name));
|
|
1107
|
+
const want = !(names.has("embedding_blob") && names.has("embedding")) ? 0 : EMBED_MARKER_COLUMNS.every((c) => names.has(c)) ? 2 : 1;
|
|
1108
|
+
const existing = await db.getFirstAsync(
|
|
1109
|
+
`SELECT sql FROM sqlite_master WHERE type = 'trigger' AND name = ?`,
|
|
1110
|
+
[name]
|
|
1111
|
+
);
|
|
1112
|
+
if (existing) {
|
|
1113
|
+
if (resurrectLevel(existing.sql ?? "") >= want) return;
|
|
1114
|
+
await db.execAsync(`DROP TRIGGER IF EXISTS ${name};`);
|
|
1115
|
+
}
|
|
1116
|
+
const clearVector = want === 0 ? "" : `
|
|
1117
|
+
UPDATE ${prefix}entries
|
|
1118
|
+
SET embedding_blob = NULL, embedding = NULL${want === 2 ? `,
|
|
1119
|
+
embedding_failed_at = NULL, embedding_failure_kind = NULL, embedding_attempts = 0` : ""}
|
|
1120
|
+
WHERE id = NEW.id
|
|
1121
|
+
AND EXISTS (SELECT 1 FROM ${prefix}vector_removals WHERE fact_id = NEW.id AND confirmed_at IS NOT NULL);`;
|
|
1122
|
+
await db.execAsync(`
|
|
1123
|
+
CREATE TRIGGER IF NOT EXISTS ${name}
|
|
1124
|
+
AFTER UPDATE OF deleted_at ON ${prefix}entries
|
|
1125
|
+
WHEN OLD.deleted_at IS NOT NULL AND NEW.deleted_at IS NULL
|
|
1126
|
+
BEGIN${clearVector}
|
|
1127
|
+
DELETE FROM ${prefix}vector_removals WHERE fact_id = NEW.id;
|
|
1128
|
+
END;
|
|
1129
|
+
`);
|
|
907
1130
|
}
|
|
908
1131
|
async function createOkfV02IndexesIfColumnsExist(db, prefix) {
|
|
909
1132
|
for (const table of ["entries", "tasks"]) {
|
|
@@ -1114,6 +1337,7 @@ var MIGRATIONS = [
|
|
|
1114
1337
|
`ALTER TABLE ${prefix}entries ADD COLUMN embedding_blob BLOB`
|
|
1115
1338
|
);
|
|
1116
1339
|
}
|
|
1340
|
+
await createResurrectTrigger(db, prefix);
|
|
1117
1341
|
}
|
|
1118
1342
|
},
|
|
1119
1343
|
{
|
|
@@ -1307,6 +1531,7 @@ var MIGRATIONS = [
|
|
|
1307
1531
|
for (const [name, sql] of adds) {
|
|
1308
1532
|
if (!existing.has(name)) await db.execAsync(sql);
|
|
1309
1533
|
}
|
|
1534
|
+
await createResurrectTrigger(db, prefix);
|
|
1310
1535
|
}
|
|
1311
1536
|
},
|
|
1312
1537
|
{
|
|
@@ -2211,20 +2436,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2211
2436
|
* Used by runPrune(). Returns total number of deleted rows.
|
|
2212
2437
|
* `tx` is REQUIRED so outbox deletion events are staged atomically.
|
|
2213
2438
|
*/
|
|
2214
|
-
async bulkDeletePruned(entityId, cutoff, ids, tx) {
|
|
2439
|
+
async bulkDeletePruned(entityId, cutoff, ids, tx, opts = {}) {
|
|
2215
2440
|
const executor = this.getExecutor(tx);
|
|
2441
|
+
const guard = opts.keepUnconfirmedRemovals ? ` AND NOT EXISTS (SELECT 1 FROM ${this.prefix}vector_removals v WHERE v.fact_id = ${this.prefix}entries.id AND v.confirmed_at IS NULL)` : "";
|
|
2216
2442
|
let totalChanges = 0;
|
|
2217
2443
|
const chunkSize = 500;
|
|
2218
2444
|
for (let i = 0; i < ids.length; i += chunkSize) {
|
|
2219
2445
|
const chunk = ids.slice(i, i + chunkSize);
|
|
2220
2446
|
const placeholders = chunk.map(() => "?").join(",");
|
|
2221
|
-
const
|
|
2222
|
-
`DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})`,
|
|
2447
|
+
const deleted = (await executor.getAllAsync(
|
|
2448
|
+
`DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})${guard} RETURNING id`,
|
|
2223
2449
|
[entityId, cutoff, ...chunk]
|
|
2224
|
-
);
|
|
2225
|
-
totalChanges +=
|
|
2226
|
-
|
|
2227
|
-
|
|
2450
|
+
)).map((r) => r.id);
|
|
2451
|
+
totalChanges += deleted.length;
|
|
2452
|
+
opts.deletedIds?.push(...deleted);
|
|
2453
|
+
if (deleted.length > 0) {
|
|
2454
|
+
for (const id of deleted) {
|
|
2228
2455
|
await this.outbox.push({
|
|
2229
2456
|
entityId,
|
|
2230
2457
|
tableName: "entries",
|
|
@@ -2331,11 +2558,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2331
2558
|
const executor = this.getExecutor(tx);
|
|
2332
2559
|
const now = Date.now();
|
|
2333
2560
|
const placeholders = ids.map(() => "?").join(",");
|
|
2334
|
-
await executor.
|
|
2335
|
-
`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id =
|
|
2561
|
+
const updated = await executor.getAllAsync(
|
|
2562
|
+
`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id IN (${placeholders}) AND entity_id = ? AND deleted_at IS NULL RETURNING id`,
|
|
2336
2563
|
[now, now, ...ids, entityId]
|
|
2337
2564
|
);
|
|
2338
|
-
for (const id of
|
|
2565
|
+
for (const { id } of updated) {
|
|
2339
2566
|
await this.outbox.push({
|
|
2340
2567
|
entityId,
|
|
2341
2568
|
tableName: "entries",
|
|
@@ -2495,18 +2722,20 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
|
|
|
2495
2722
|
}
|
|
2496
2723
|
return rows;
|
|
2497
2724
|
}
|
|
2725
|
+
/** Returns `changes: 0` when the row is soft-deleted or gone (spec durable-vector-removal §5.7, G10). */
|
|
2498
2726
|
async updateEmbeddingBlob(id, blob, tx) {
|
|
2499
2727
|
const executor = this.getExecutor(tx);
|
|
2500
|
-
await executor.runAsync(
|
|
2728
|
+
const r = await executor.runAsync(
|
|
2501
2729
|
`UPDATE ${this.prefix}entries
|
|
2502
2730
|
SET embedding_blob = ?,
|
|
2503
2731
|
embedding = NULL,
|
|
2504
2732
|
embedding_failed_at = NULL,
|
|
2505
2733
|
embedding_failure_kind = NULL,
|
|
2506
2734
|
embedding_attempts = 0
|
|
2507
|
-
WHERE id =
|
|
2735
|
+
WHERE id = ? AND deleted_at IS NULL`,
|
|
2508
2736
|
[blob, id]
|
|
2509
2737
|
);
|
|
2738
|
+
return { changes: r?.changes ?? 0 };
|
|
2510
2739
|
}
|
|
2511
2740
|
/**
|
|
2512
2741
|
* Record a failed embedding attempt. Deliberately does NOT touch updated_at
|
|
@@ -5981,153 +6210,20 @@ function groundingOutcome(verdict, now) {
|
|
|
5981
6210
|
};
|
|
5982
6211
|
}
|
|
5983
6212
|
|
|
5984
|
-
// src/
|
|
5985
|
-
var
|
|
5986
|
-
|
|
5987
|
-
|
|
5988
|
-
|
|
5989
|
-
|
|
5990
|
-
edge_dropped: "warn",
|
|
5991
|
-
embedding_failed: "warn",
|
|
5992
|
-
hook_failed: "warn",
|
|
5993
|
-
background_job_failed: "error",
|
|
5994
|
-
heal_skipped: "warn",
|
|
5995
|
-
grounding_missing: "warn",
|
|
5996
|
-
grounding_failed: "warn",
|
|
5997
|
-
classification_low_confidence: "info",
|
|
5998
|
-
classification_invalid: "warn",
|
|
5999
|
-
llm_usage: "info",
|
|
6000
|
-
librarian_gate: "info",
|
|
6001
|
-
librarian_op_rejected: "warn",
|
|
6002
|
-
contradicts_document: "warn",
|
|
6003
|
-
resolve_failed: "warn",
|
|
6004
|
-
read_budget: "info",
|
|
6005
|
-
event_retention_held: "info",
|
|
6006
|
-
event_created_at_clamped: "warn",
|
|
6007
|
-
event_created_at_restamped: "info"
|
|
6008
|
-
};
|
|
6009
|
-
var MESSAGE = {
|
|
6010
|
-
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
6011
|
-
fact_rejected: "An extracted fact failed validation and was not written.",
|
|
6012
|
-
task_rejected: "An extracted task failed validation and was not written.",
|
|
6013
|
-
fact_deduplicated: "An extracted fact duplicated an existing fact and was not written.",
|
|
6014
|
-
edge_dropped: "An extracted edge could not be resolved against the ontology and was not written.",
|
|
6015
|
-
embedding_failed: "A fact could not be embedded.",
|
|
6016
|
-
hook_failed: "A host hook threw or rejected.",
|
|
6017
|
-
background_job_failed: "A background maintenance job failed.",
|
|
6018
|
-
heal_skipped: "Heal skipped a candidate fact, or the whole LLM pass when keyword search is unavailable.",
|
|
6019
|
-
grounding_missing: "A fact carried no qualifying evidence and was stored as a draft.",
|
|
6020
|
-
grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
|
|
6021
|
-
classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
|
|
6022
|
-
classification_invalid: "A classifier answer was invalid and was not applied.",
|
|
6023
|
-
llm_usage: "An LLM call completed; token usage attached.",
|
|
6024
|
-
librarian_gate: "Librarian gate outcome counts for one pass.",
|
|
6025
|
-
librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
|
|
6026
|
-
contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
|
|
6027
|
-
resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
|
|
6028
|
-
read_budget: "A read was packed to a token budget.",
|
|
6029
|
-
event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
|
|
6030
|
-
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.",
|
|
6031
|
-
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."
|
|
6032
|
-
};
|
|
6033
|
-
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
6034
|
-
function copyDetail(detail) {
|
|
6035
|
-
const copy = { ...detail };
|
|
6036
|
-
if (detail.chunkIndexes) copy.chunkIndexes = detail.chunkIndexes.slice();
|
|
6037
|
-
return copy;
|
|
6213
|
+
// src/prompts.ts
|
|
6214
|
+
var LIBRARIAN_SYSTEM_PROMPT = `You are a knowledge extraction agent. Your job is to analyze recent episodic events and extract stable facts and actionable tasks about the user or entity.
|
|
6215
|
+
Return ONLY a valid JSON object matching this schema:
|
|
6216
|
+
{
|
|
6217
|
+
"facts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }],
|
|
6218
|
+
"tasks": [{ "description": "string", "priority": "number (0-10)" }]
|
|
6038
6219
|
}
|
|
6039
|
-
|
|
6040
|
-
|
|
6041
|
-
|
|
6042
|
-
|
|
6043
|
-
|
|
6044
|
-
|
|
6045
|
-
|
|
6046
|
-
}
|
|
6047
|
-
return;
|
|
6048
|
-
}
|
|
6049
|
-
const diagnostic = {
|
|
6050
|
-
code: input.code,
|
|
6051
|
-
severity: SEVERITY[input.code],
|
|
6052
|
-
operation: input.operation,
|
|
6053
|
-
trigger: input.trigger,
|
|
6054
|
-
entityId: input.entityId,
|
|
6055
|
-
at: Date.now(),
|
|
6056
|
-
message: MESSAGE[input.code],
|
|
6057
|
-
...input.detail ? { detail: copyDetail(input.detail) } : {}
|
|
6058
|
-
};
|
|
6059
|
-
try {
|
|
6060
|
-
const returned = hook(diagnostic);
|
|
6061
|
-
if (returned !== void 0) {
|
|
6062
|
-
Promise.resolve(returned).catch((err) => {
|
|
6063
|
-
console.warn("[WikiMemory] onDiagnostic hook rejected:", err);
|
|
6064
|
-
});
|
|
6065
|
-
}
|
|
6066
|
-
} catch (err) {
|
|
6067
|
-
console.warn("[WikiMemory] onDiagnostic hook threw:", err);
|
|
6068
|
-
}
|
|
6069
|
-
}
|
|
6070
|
-
var DiagnosticBuffer = class {
|
|
6071
|
-
constructor() {
|
|
6072
|
-
this.items = [];
|
|
6073
|
-
}
|
|
6074
|
-
push(input) {
|
|
6075
|
-
this.items.push(input);
|
|
6076
|
-
}
|
|
6077
|
-
get size() {
|
|
6078
|
-
return this.items.length;
|
|
6079
|
-
}
|
|
6080
|
-
flush(options) {
|
|
6081
|
-
const pending = this.items;
|
|
6082
|
-
this.items = [];
|
|
6083
|
-
for (const input of pending) emitDiagnostic(options, input);
|
|
6084
|
-
}
|
|
6085
|
-
/**
|
|
6086
|
-
* Emit only the buffered diagnostics whose code is in `codes` and discard
|
|
6087
|
-
* the rest. The buffer is empty afterwards either way.
|
|
6088
|
-
*
|
|
6089
|
-
* For an operation that did real work before its write was rolled back:
|
|
6090
|
-
* some buffered diagnostics describe that work and are still true, while
|
|
6091
|
-
* others describe rows that no longer exist (anything carrying a `factId`
|
|
6092
|
-
* minted inside the aborted transaction). `flush` would emit both and
|
|
6093
|
-
* `discard` would drop both; this emits the first set only.
|
|
6094
|
-
*/
|
|
6095
|
-
flushOnly(options, codes) {
|
|
6096
|
-
const pending = this.items;
|
|
6097
|
-
this.items = [];
|
|
6098
|
-
for (const input of pending) {
|
|
6099
|
-
if (codes.includes(input.code)) emitDiagnostic(options, input);
|
|
6100
|
-
}
|
|
6101
|
-
}
|
|
6102
|
-
discard() {
|
|
6103
|
-
this.items = [];
|
|
6104
|
-
}
|
|
6105
|
-
};
|
|
6106
|
-
function edgeDropDiagnostic(drop, ctx) {
|
|
6107
|
-
const detail = { reason: drop.reason };
|
|
6108
|
-
const factId = ctx.factId ?? drop.sourceId;
|
|
6109
|
-
if (factId) detail.factId = factId;
|
|
6110
|
-
if (drop.edgeType) detail.edgeType = drop.edgeType;
|
|
6111
|
-
if (drop.sourceNodeType) detail.sourceNodeType = drop.sourceNodeType;
|
|
6112
|
-
if (drop.targetNodeType) detail.targetNodeType = drop.targetNodeType;
|
|
6113
|
-
if (ctx.sourceRef) detail.sourceRef = ctx.sourceRef;
|
|
6114
|
-
return { code: "edge_dropped", operation: ctx.operation, trigger: ctx.trigger, entityId: ctx.entityId, detail };
|
|
6115
|
-
}
|
|
6116
|
-
|
|
6117
|
-
// src/prompts.ts
|
|
6118
|
-
var LIBRARIAN_SYSTEM_PROMPT = `You are a knowledge extraction agent. Your job is to analyze recent episodic events and extract stable facts and actionable tasks about the user or entity.
|
|
6119
|
-
Return ONLY a valid JSON object matching this schema:
|
|
6120
|
-
{
|
|
6121
|
-
"facts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }],
|
|
6122
|
-
"tasks": [{ "description": "string", "priority": "number (0-10)" }]
|
|
6123
|
-
}
|
|
6124
|
-
Keep facts concise. Do not return markdown, just raw JSON.`;
|
|
6125
|
-
var HEAL_SYSTEM_PROMPT = `You are a memory grooming agent. Your job is to review a full dump of facts and recent events to resolve contradictions, downgrade stale claims, and flag obsolete facts for deletion.
|
|
6126
|
-
Return ONLY a valid JSON object matching this schema:
|
|
6127
|
-
{
|
|
6128
|
-
"downgraded": ["string (fact IDs)"],
|
|
6129
|
-
"deleted": ["string (fact IDs)"],
|
|
6130
|
-
"newFacts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
|
|
6220
|
+
Keep facts concise. Do not return markdown, just raw JSON.`;
|
|
6221
|
+
var HEAL_SYSTEM_PROMPT = `You are a memory grooming agent. Your job is to review a full dump of facts and recent events to resolve contradictions, downgrade stale claims, and flag obsolete facts for deletion.
|
|
6222
|
+
Return ONLY a valid JSON object matching this schema:
|
|
6223
|
+
{
|
|
6224
|
+
"downgraded": ["string (fact IDs)"],
|
|
6225
|
+
"deleted": ["string (fact IDs)"],
|
|
6226
|
+
"newFacts": [{ "title": "string (max 80 chars)", "body": "string (max 800 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
|
|
6131
6227
|
}
|
|
6132
6228
|
Do not return markdown, just raw JSON.`;
|
|
6133
6229
|
var INGEST_SYSTEM_PROMPT = `You are a document ingestion agent. Your job is to extract factual knowledge from the provided document chunk.
|
|
@@ -6541,7 +6637,7 @@ function zeroChunkResult(duplicateOf) {
|
|
|
6541
6637
|
return result;
|
|
6542
6638
|
}
|
|
6543
6639
|
var IngestionService = class {
|
|
6544
|
-
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
|
|
6640
|
+
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, metadataRepo, edgeRepo, searchService, jobManager, embeddingService, promptService, ontologyService, vectorRemoval) {
|
|
6545
6641
|
this.db = db;
|
|
6546
6642
|
this.prefix = prefix;
|
|
6547
6643
|
this.options = options;
|
|
@@ -6553,6 +6649,7 @@ var IngestionService = class {
|
|
|
6553
6649
|
this.jobManager = jobManager;
|
|
6554
6650
|
this.embeddingService = embeddingService;
|
|
6555
6651
|
this.ontologyService = ontologyService;
|
|
6652
|
+
this.vectorRemoval = vectorRemoval;
|
|
6556
6653
|
this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
|
|
6557
6654
|
}
|
|
6558
6655
|
async ingestDocument(entityId, params, opts) {
|
|
@@ -6583,12 +6680,12 @@ var IngestionService = class {
|
|
|
6583
6680
|
return zeroChunkResult(canonical);
|
|
6584
6681
|
}
|
|
6585
6682
|
}
|
|
6586
|
-
const { chunks, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
6587
|
-
if (
|
|
6683
|
+
const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
6684
|
+
if (chunks2.length === 0) return zeroChunkResult();
|
|
6588
6685
|
const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
|
|
6589
6686
|
const ingestGrounding = this.promptService.groundingFor("ingest");
|
|
6590
6687
|
const chunkResults = await withConcurrency(
|
|
6591
|
-
|
|
6688
|
+
chunks2.map((chunk, chunkIndex) => async () => {
|
|
6592
6689
|
const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
|
|
6593
6690
|
chunk,
|
|
6594
6691
|
params.promptOverride,
|
|
@@ -6646,7 +6743,7 @@ var IngestionService = class {
|
|
|
6646
6743
|
position: null,
|
|
6647
6744
|
message: safeErrorToString(e)
|
|
6648
6745
|
};
|
|
6649
|
-
const total =
|
|
6746
|
+
const total = chunks2.length;
|
|
6650
6747
|
const tags = [];
|
|
6651
6748
|
if (failure.tier) tags.push(`tier=${failure.tier}`);
|
|
6652
6749
|
if (failure.position !== null) tags.push(`position=${failure.position}`);
|
|
@@ -6723,11 +6820,11 @@ var IngestionService = class {
|
|
|
6723
6820
|
}
|
|
6724
6821
|
});
|
|
6725
6822
|
}
|
|
6726
|
-
if (failedChunks ===
|
|
6823
|
+
if (failedChunks === chunks2.length) {
|
|
6727
6824
|
throw new WikiIngestEmptyError({
|
|
6728
6825
|
parseFailures: failures,
|
|
6729
6826
|
sourceRef,
|
|
6730
|
-
chunks:
|
|
6827
|
+
chunks: chunks2.length
|
|
6731
6828
|
});
|
|
6732
6829
|
}
|
|
6733
6830
|
const insertedFacts = [];
|
|
@@ -6765,18 +6862,22 @@ var IngestionService = class {
|
|
|
6765
6862
|
);
|
|
6766
6863
|
if (failedChunks === 0) {
|
|
6767
6864
|
const uniqueDeletedSourceFactIds = Array.from(new Set(deletedSourceFactIds));
|
|
6768
|
-
|
|
6769
|
-
|
|
6770
|
-
|
|
6771
|
-
|
|
6772
|
-
|
|
6773
|
-
|
|
6774
|
-
|
|
6775
|
-
|
|
6776
|
-
|
|
6777
|
-
|
|
6778
|
-
|
|
6779
|
-
|
|
6865
|
+
if (this.vectorRemoval) {
|
|
6866
|
+
await this.vectorRemoval.deliverRemovals(entityId, uniqueDeletedSourceFactIds, "ingest", "call");
|
|
6867
|
+
} else if (this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
6868
|
+
for (const factId of uniqueDeletedSourceFactIds) {
|
|
6869
|
+
try {
|
|
6870
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
6871
|
+
} catch (hookErr) {
|
|
6872
|
+
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during ingest for ${factId}:`, hookErr);
|
|
6873
|
+
emitDiagnostic(this.options, {
|
|
6874
|
+
entityId,
|
|
6875
|
+
operation: "ingest",
|
|
6876
|
+
trigger: "call",
|
|
6877
|
+
code: "hook_failed",
|
|
6878
|
+
detail: { factId, reason: "on_embedding_persisted" }
|
|
6879
|
+
});
|
|
6880
|
+
}
|
|
6780
6881
|
}
|
|
6781
6882
|
}
|
|
6782
6883
|
}
|
|
@@ -6786,7 +6887,7 @@ var IngestionService = class {
|
|
|
6786
6887
|
this.searchService.evictCache(entityId);
|
|
6787
6888
|
const result = {
|
|
6788
6889
|
truncated,
|
|
6789
|
-
chunks:
|
|
6890
|
+
chunks: chunks2.length,
|
|
6790
6891
|
ingestedChunks,
|
|
6791
6892
|
failedChunks
|
|
6792
6893
|
};
|
|
@@ -7248,6 +7349,543 @@ function warnChangedDefaultsOnce(config) {
|
|
|
7248
7349
|
}
|
|
7249
7350
|
}
|
|
7250
7351
|
|
|
7352
|
+
// src/repositories/VectorRemovalRepository.ts
|
|
7353
|
+
var CHUNK2 = 500;
|
|
7354
|
+
function removalBackoffMs(attempts) {
|
|
7355
|
+
return Math.min(2 ** attempts, 3600) * 1e3;
|
|
7356
|
+
}
|
|
7357
|
+
function chunks(xs, n) {
|
|
7358
|
+
const out = [];
|
|
7359
|
+
for (let i = 0; i < xs.length; i += n) out.push(xs.slice(i, i + n));
|
|
7360
|
+
return out;
|
|
7361
|
+
}
|
|
7362
|
+
var marks = (n) => new Array(n).fill("?").join(",");
|
|
7363
|
+
var VectorRemovalRepository = class extends BaseRepository {
|
|
7364
|
+
/** Name of the ledger table. */
|
|
7365
|
+
get ledgerTable() {
|
|
7366
|
+
return `${this.prefix}vector_removals`;
|
|
7367
|
+
}
|
|
7368
|
+
/** Whether `factId` exists and is not soft-deleted. */
|
|
7369
|
+
async isLive(factId) {
|
|
7370
|
+
const row = await this.db.getFirstAsync(
|
|
7371
|
+
`SELECT 1 AS x FROM ${this.prefix}entries WHERE id = ? AND deleted_at IS NULL`,
|
|
7372
|
+
[factId]
|
|
7373
|
+
);
|
|
7374
|
+
return !!row;
|
|
7375
|
+
}
|
|
7376
|
+
/**
|
|
7377
|
+
* Owe the host a removal for `factId` unless a live row exists (a missing row
|
|
7378
|
+
* counts as not live). The liveness test is part of the write, so it is
|
|
7379
|
+
* atomic. Returns whether a row was enqueued.
|
|
7380
|
+
*/
|
|
7381
|
+
async enqueueIfNotLive(entityId, factId, now) {
|
|
7382
|
+
return this.db.withTransactionAsync(async (tx) => {
|
|
7383
|
+
const r = await tx.runAsync(
|
|
7384
|
+
`INSERT OR REPLACE INTO ${this.prefix}vector_removals (entity_id, fact_id, enqueued_at)
|
|
7385
|
+
SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM ${this.prefix}entries WHERE id = ? AND deleted_at IS NULL)`,
|
|
7386
|
+
[entityId, factId, now, factId]
|
|
7387
|
+
);
|
|
7388
|
+
return (r?.changes ?? 0) > 0;
|
|
7389
|
+
});
|
|
7390
|
+
}
|
|
7391
|
+
/** Unconfirmed rows after `cursor`, ordered by (attempts, seq). */
|
|
7392
|
+
async readPage(scope, cursor, limit, tx) {
|
|
7393
|
+
const executor = this.getExecutor(tx);
|
|
7394
|
+
const t = `${this.prefix}vector_removals`;
|
|
7395
|
+
const where = [
|
|
7396
|
+
"v.confirmed_at IS NULL",
|
|
7397
|
+
"v.seq <= ?",
|
|
7398
|
+
"(v.attempts > ? OR (v.attempts = ? AND v.seq > ?))"
|
|
7399
|
+
];
|
|
7400
|
+
const args = [cursor.maxSeq, cursor.attempts, cursor.attempts, cursor.seq];
|
|
7401
|
+
if (scope.entityId !== void 0) {
|
|
7402
|
+
where.push(scope.ids !== void 0 ? "+v.entity_id = ?" : "v.entity_id = ?");
|
|
7403
|
+
args.push(scope.entityId);
|
|
7404
|
+
}
|
|
7405
|
+
if (scope.ids !== void 0) {
|
|
7406
|
+
if (scope.ids.length === 0) return [];
|
|
7407
|
+
where.push(`v.fact_id IN (${marks(scope.ids.length)})`);
|
|
7408
|
+
args.push(...scope.ids);
|
|
7409
|
+
}
|
|
7410
|
+
args.push(limit);
|
|
7411
|
+
return executor.getAllAsync(
|
|
7412
|
+
`SELECT v.seq AS seq, v.entity_id AS entity_id, v.fact_id AS fact_id,
|
|
7413
|
+
v.attempts AS attempts, v.last_attempt_at AS last_attempt_at,
|
|
7414
|
+
CASE WHEN e.id IS NULL THEN 'gone'
|
|
7415
|
+
WHEN e.deleted_at IS NULL THEN 'live'
|
|
7416
|
+
ELSE 'deleted' END AS fact_state
|
|
7417
|
+
FROM ${t} v
|
|
7418
|
+
LEFT JOIN ${this.prefix}entries e ON e.id = v.fact_id
|
|
7419
|
+
WHERE ${where.join(" AND ")}
|
|
7420
|
+
ORDER BY v.attempts, v.seq
|
|
7421
|
+
LIMIT ?`,
|
|
7422
|
+
args
|
|
7423
|
+
);
|
|
7424
|
+
}
|
|
7425
|
+
async maxSeq(tx) {
|
|
7426
|
+
const row = await this.getExecutor(tx).getFirstAsync(
|
|
7427
|
+
`SELECT MAX(seq) AS m FROM ${this.prefix}vector_removals`
|
|
7428
|
+
);
|
|
7429
|
+
return row?.m ?? 0;
|
|
7430
|
+
}
|
|
7431
|
+
/** Returns the number of rows changed. */
|
|
7432
|
+
async confirm(seqs, now, tx) {
|
|
7433
|
+
const executor = this.getExecutor(tx);
|
|
7434
|
+
let changed = 0;
|
|
7435
|
+
for (const c of chunks(seqs, CHUNK2)) {
|
|
7436
|
+
const r = await executor.runAsync(
|
|
7437
|
+
`UPDATE ${this.prefix}vector_removals SET confirmed_at = ?
|
|
7438
|
+
WHERE confirmed_at IS NULL AND seq IN (${marks(c.length)})`,
|
|
7439
|
+
[now, ...c]
|
|
7440
|
+
);
|
|
7441
|
+
changed += r.changes;
|
|
7442
|
+
}
|
|
7443
|
+
return changed;
|
|
7444
|
+
}
|
|
7445
|
+
async bumpAttempts(seqs, now, tx) {
|
|
7446
|
+
const executor = this.getExecutor(tx);
|
|
7447
|
+
for (const c of chunks(seqs, CHUNK2)) {
|
|
7448
|
+
await executor.runAsync(
|
|
7449
|
+
`UPDATE ${this.prefix}vector_removals
|
|
7450
|
+
SET attempts = attempts + 1, last_attempt_at = ?
|
|
7451
|
+
WHERE seq IN (${marks(c.length)})`,
|
|
7452
|
+
[now, ...c]
|
|
7453
|
+
);
|
|
7454
|
+
}
|
|
7455
|
+
}
|
|
7456
|
+
/** Delete the given rows when they are confirmed and their fact row is gone. */
|
|
7457
|
+
async deleteConfirmedGone(seqs, tx) {
|
|
7458
|
+
const executor = this.getExecutor(tx);
|
|
7459
|
+
for (const c of chunks(seqs, CHUNK2)) {
|
|
7460
|
+
await executor.runAsync(
|
|
7461
|
+
`DELETE FROM ${this.prefix}vector_removals
|
|
7462
|
+
WHERE seq IN (${marks(c.length)}) AND confirmed_at IS NOT NULL
|
|
7463
|
+
AND NOT EXISTS (SELECT 1 FROM ${this.prefix}entries e WHERE e.id = ${this.prefix}vector_removals.fact_id)`,
|
|
7464
|
+
c
|
|
7465
|
+
);
|
|
7466
|
+
}
|
|
7467
|
+
}
|
|
7468
|
+
/** For stale, gone or resurrected rows. Applies to the given seqs only. */
|
|
7469
|
+
async deleteBySeq(seqs, tx) {
|
|
7470
|
+
const executor = this.getExecutor(tx);
|
|
7471
|
+
let changed = 0;
|
|
7472
|
+
for (const c of chunks(seqs, CHUNK2)) {
|
|
7473
|
+
const r = await executor.runAsync(
|
|
7474
|
+
`DELETE FROM ${this.prefix}vector_removals WHERE seq IN (${marks(c.length)})`,
|
|
7475
|
+
c
|
|
7476
|
+
);
|
|
7477
|
+
changed += r.changes;
|
|
7478
|
+
}
|
|
7479
|
+
return changed;
|
|
7480
|
+
}
|
|
7481
|
+
/** Unconfirmed rows of `entityId` among `ids`. */
|
|
7482
|
+
async pendingCountForIds(entityId, ids) {
|
|
7483
|
+
let n = 0;
|
|
7484
|
+
for (const c of chunks(ids, CHUNK2)) {
|
|
7485
|
+
const row = await this.db.getFirstAsync(
|
|
7486
|
+
`SELECT COUNT(*) AS c FROM ${this.prefix}vector_removals
|
|
7487
|
+
WHERE confirmed_at IS NULL AND +entity_id = ? AND fact_id IN (${marks(c.length)})`,
|
|
7488
|
+
[entityId, ...c]
|
|
7489
|
+
);
|
|
7490
|
+
n += row?.c ?? 0;
|
|
7491
|
+
}
|
|
7492
|
+
return n;
|
|
7493
|
+
}
|
|
7494
|
+
/** Enqueue ids that have no row yet. Returns the number inserted. */
|
|
7495
|
+
async backstopEnqueue(entityId, ids, now, tx) {
|
|
7496
|
+
const executor = this.getExecutor(tx);
|
|
7497
|
+
let inserted = 0;
|
|
7498
|
+
for (const c of chunks(ids, 300)) {
|
|
7499
|
+
const values = c.map(() => "(?, ?, ?)").join(",");
|
|
7500
|
+
const args = c.flatMap((id) => [entityId, id, now]);
|
|
7501
|
+
const r = await executor.runAsync(
|
|
7502
|
+
`INSERT OR IGNORE INTO ${this.prefix}vector_removals (entity_id, fact_id, enqueued_at)
|
|
7503
|
+
VALUES ${values}`,
|
|
7504
|
+
args
|
|
7505
|
+
);
|
|
7506
|
+
inserted += r.changes;
|
|
7507
|
+
}
|
|
7508
|
+
return inserted;
|
|
7509
|
+
}
|
|
7510
|
+
/**
|
|
7511
|
+
* Remove rows together with a hard delete of the facts. `'all'` drops every
|
|
7512
|
+
* row of those ids; `'confirmedGone'` drops only confirmed rows whose fact
|
|
7513
|
+
* row no longer exists, so a removal re-owed meanwhile is never erased.
|
|
7514
|
+
*/
|
|
7515
|
+
async deleteForFacts(entityId, ids, tx, mode = "all") {
|
|
7516
|
+
const executor = this.getExecutor(tx);
|
|
7517
|
+
const extra = mode === "all" ? "" : ` AND confirmed_at IS NOT NULL
|
|
7518
|
+
AND NOT EXISTS (SELECT 1 FROM ${this.prefix}entries e WHERE e.id = ${this.prefix}vector_removals.fact_id)`;
|
|
7519
|
+
for (const c of chunks(ids, CHUNK2)) {
|
|
7520
|
+
await executor.runAsync(
|
|
7521
|
+
`DELETE FROM ${this.prefix}vector_removals
|
|
7522
|
+
WHERE entity_id = ? AND fact_id IN (${marks(c.length)})${extra}`,
|
|
7523
|
+
[entityId, ...c]
|
|
7524
|
+
);
|
|
7525
|
+
}
|
|
7526
|
+
}
|
|
7527
|
+
/** Drop unconfirmed rows. Returns the count removed. */
|
|
7528
|
+
async discardPending(entityId, tx) {
|
|
7529
|
+
const executor = this.getExecutor(tx);
|
|
7530
|
+
const r = entityId === void 0 ? await executor.runAsync(
|
|
7531
|
+
`DELETE FROM ${this.prefix}vector_removals WHERE confirmed_at IS NULL`
|
|
7532
|
+
) : await executor.runAsync(
|
|
7533
|
+
`DELETE FROM ${this.prefix}vector_removals WHERE confirmed_at IS NULL AND entity_id = ?`,
|
|
7534
|
+
[entityId]
|
|
7535
|
+
);
|
|
7536
|
+
return r.changes;
|
|
7537
|
+
}
|
|
7538
|
+
async pendingStats(entityId) {
|
|
7539
|
+
const row = await this.db.getFirstAsync(
|
|
7540
|
+
`SELECT COUNT(*) AS c, MIN(enqueued_at) AS o, MAX(attempts) AS m
|
|
7541
|
+
FROM ${this.prefix}vector_removals
|
|
7542
|
+
WHERE confirmed_at IS NULL${entityId === void 0 ? "" : " AND entity_id = ?"}`,
|
|
7543
|
+
entityId === void 0 ? [] : [entityId]
|
|
7544
|
+
);
|
|
7545
|
+
return { count: row?.c ?? 0, oldestEnqueuedAt: row?.o ?? null, maxAttempts: row?.m ?? 0 };
|
|
7546
|
+
}
|
|
7547
|
+
async entitiesWithPending() {
|
|
7548
|
+
const rows = await this.db.getAllAsync(
|
|
7549
|
+
`SELECT DISTINCT entity_id FROM ${this.prefix}vector_removals
|
|
7550
|
+
WHERE confirmed_at IS NULL ORDER BY entity_id`
|
|
7551
|
+
);
|
|
7552
|
+
return rows.map((r) => r.entity_id);
|
|
7553
|
+
}
|
|
7554
|
+
/**
|
|
7555
|
+
* Entities with at least one pending row outside backoff (never attempted,
|
|
7556
|
+
* or last attempted longer ago than removalBackoffMs). Same rule as the drain.
|
|
7557
|
+
*/
|
|
7558
|
+
async entitiesWithDuePending(now) {
|
|
7559
|
+
const rows = await this.db.getAllAsync(
|
|
7560
|
+
`SELECT DISTINCT entity_id FROM ${this.prefix}vector_removals
|
|
7561
|
+
WHERE confirmed_at IS NULL
|
|
7562
|
+
AND (last_attempt_at IS NULL
|
|
7563
|
+
OR ? - last_attempt_at >= MIN(1 << MIN(attempts, 12), 3600) * 1000)
|
|
7564
|
+
ORDER BY entity_id`,
|
|
7565
|
+
[now]
|
|
7566
|
+
);
|
|
7567
|
+
return rows.map((r) => r.entity_id);
|
|
7568
|
+
}
|
|
7569
|
+
async statusFor(ids, tx) {
|
|
7570
|
+
const executor = this.getExecutor(tx);
|
|
7571
|
+
const out = /* @__PURE__ */ new Map();
|
|
7572
|
+
for (const c of chunks(ids, CHUNK2)) {
|
|
7573
|
+
const rows = await executor.getAllAsync(
|
|
7574
|
+
`SELECT fact_id, confirmed_at FROM ${this.prefix}vector_removals
|
|
7575
|
+
WHERE fact_id IN (${marks(c.length)})`,
|
|
7576
|
+
c
|
|
7577
|
+
);
|
|
7578
|
+
for (const r of rows) out.set(r.fact_id, r.confirmed_at === null ? "pending" : "confirmed");
|
|
7579
|
+
}
|
|
7580
|
+
return out;
|
|
7581
|
+
}
|
|
7582
|
+
};
|
|
7583
|
+
|
|
7584
|
+
// src/services/VectorRemovalService.ts
|
|
7585
|
+
var MARKER_KEY = "external_index_in_use";
|
|
7586
|
+
var PAGE = 100;
|
|
7587
|
+
var ID_CHUNK = 500;
|
|
7588
|
+
var MAX_FAILED_IDS = 100;
|
|
7589
|
+
var MAX_CONSECUTIVE_REJECTIONS = 5;
|
|
7590
|
+
function removalGate(options) {
|
|
7591
|
+
if (options.forceDeleteIgnoreRankerHook === true) return "force";
|
|
7592
|
+
if (options.vectorRanker?.onEmbeddingPersisted) return "hook";
|
|
7593
|
+
return "none";
|
|
7594
|
+
}
|
|
7595
|
+
var VectorRemovalService = class {
|
|
7596
|
+
constructor(db, options, repo, embeddingService, metadataRepo) {
|
|
7597
|
+
this.db = db;
|
|
7598
|
+
this.options = options;
|
|
7599
|
+
this.repo = repo;
|
|
7600
|
+
this.embeddingService = embeddingService;
|
|
7601
|
+
this.metadataRepo = metadataRepo;
|
|
7602
|
+
this.inFlight = /* @__PURE__ */ new Map();
|
|
7603
|
+
this.ledgerSeen = false;
|
|
7604
|
+
}
|
|
7605
|
+
gate() {
|
|
7606
|
+
return removalGate(this.options);
|
|
7607
|
+
}
|
|
7608
|
+
async ledgerPresent() {
|
|
7609
|
+
if (this.ledgerSeen) return true;
|
|
7610
|
+
this.ledgerSeen = await this.metadataRepo.tableExists(this.repo.ledgerTable);
|
|
7611
|
+
return this.ledgerSeen;
|
|
7612
|
+
}
|
|
7613
|
+
/** One `hook_failed` diagnostic per id (the removal stays owed). */
|
|
7614
|
+
emitHookFailed(entityId, ids, operation, trigger) {
|
|
7615
|
+
for (const factId of ids) {
|
|
7616
|
+
emitDiagnostic(this.options, {
|
|
7617
|
+
entityId,
|
|
7618
|
+
operation,
|
|
7619
|
+
trigger,
|
|
7620
|
+
code: "hook_failed",
|
|
7621
|
+
detail: { factId, reason: "on_embedding_persisted" }
|
|
7622
|
+
});
|
|
7623
|
+
}
|
|
7624
|
+
}
|
|
7625
|
+
/**
|
|
7626
|
+
* Post-commit delivery for heal, ingest and import (spec §5.7). Never throws:
|
|
7627
|
+
* a failed id emits `hook_failed` and stays owed on the ledger. Without a
|
|
7628
|
+
* ledger table (setup never ran) it falls back to a best-effort call per id.
|
|
7629
|
+
* Under `forceDeleteIgnoreRankerHook` no removal call is made.
|
|
7630
|
+
*/
|
|
7631
|
+
async deliverRemovals(entityId, ids, operation, trigger, fallbackIds = ids) {
|
|
7632
|
+
try {
|
|
7633
|
+
if (await this.ledgerPresent()) {
|
|
7634
|
+
if (ids.length === 0) return;
|
|
7635
|
+
const r2 = await this.drain({ entityId, ids }, { trigger });
|
|
7636
|
+
this.emitHookFailed(entityId, r2.failedIds, operation, trigger);
|
|
7637
|
+
if (r2.pending > 0 && this.gate() === "hook") await this.emitPending(entityId, trigger);
|
|
7638
|
+
return;
|
|
7639
|
+
}
|
|
7640
|
+
if (this.gate() !== "hook") return;
|
|
7641
|
+
const r = await this.embeddingService.callRemovalHookEach(entityId, [...new Set(fallbackIds)], { warn: true });
|
|
7642
|
+
this.emitHookFailed(entityId, r.failed, operation, trigger);
|
|
7643
|
+
} catch (err) {
|
|
7644
|
+
console.warn("[WikiMemory] removal delivery failed:", err);
|
|
7645
|
+
let stillPending = ids;
|
|
7646
|
+
try {
|
|
7647
|
+
const st = await this.repo.statusFor(ids);
|
|
7648
|
+
stillPending = ids.filter((id) => st.get(id) === "pending");
|
|
7649
|
+
} catch {
|
|
7650
|
+
}
|
|
7651
|
+
this.emitHookFailed(entityId, stillPending, operation, trigger);
|
|
7652
|
+
}
|
|
7653
|
+
}
|
|
7654
|
+
async markExternalIndexInUse(tx) {
|
|
7655
|
+
await this.metadataRepo.setMeta(MARKER_KEY, "1", tx);
|
|
7656
|
+
}
|
|
7657
|
+
async clearExternalIndexMarker() {
|
|
7658
|
+
await this.metadataRepo.deleteMeta(MARKER_KEY);
|
|
7659
|
+
}
|
|
7660
|
+
async externalIndexInUse() {
|
|
7661
|
+
return await this.metadataRepo.getMeta(MARKER_KEY) === "1";
|
|
7662
|
+
}
|
|
7663
|
+
async drain(scope, opts = {}) {
|
|
7664
|
+
const trigger = opts.trigger ?? "call";
|
|
7665
|
+
const entityId = "all" in scope ? void 0 : scope.entityId;
|
|
7666
|
+
const ids = "all" in scope ? void 0 : scope.ids;
|
|
7667
|
+
const gate = this.gate();
|
|
7668
|
+
if (gate === "none") {
|
|
7669
|
+
const pending = await this.pendingFor(entityId, ids);
|
|
7670
|
+
if (pending > 0 && await this.externalIndexInUse()) await this.emitPending(entityId, trigger);
|
|
7671
|
+
return { confirmed: 0, pending, failedIds: [], timedOut: false };
|
|
7672
|
+
}
|
|
7673
|
+
if (gate === "force") {
|
|
7674
|
+
const entities = entityId === void 0 ? await this.repo.entitiesWithPending() : [entityId];
|
|
7675
|
+
const counts = [];
|
|
7676
|
+
for (const e of entities) counts.push([e, (await this.repo.pendingStats(e)).count]);
|
|
7677
|
+
await this.repo.discardPending(entityId);
|
|
7678
|
+
await this.metadataRepo.deleteMeta(MARKER_KEY);
|
|
7679
|
+
for (const [e, count] of counts) {
|
|
7680
|
+
if (count === 0) continue;
|
|
7681
|
+
emitDiagnostic(this.options, {
|
|
7682
|
+
code: "external_deletion_discarded",
|
|
7683
|
+
operation: "externalDeletion",
|
|
7684
|
+
trigger,
|
|
7685
|
+
entityId: e,
|
|
7686
|
+
detail: { count }
|
|
7687
|
+
});
|
|
7688
|
+
}
|
|
7689
|
+
return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
|
|
7690
|
+
}
|
|
7691
|
+
const timeoutMs = this.embeddingService.validateDeletionTimeout();
|
|
7692
|
+
const result = { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
|
|
7693
|
+
let timeoutErr;
|
|
7694
|
+
let firstRejection;
|
|
7695
|
+
let consecutive = 0;
|
|
7696
|
+
let stop = false;
|
|
7697
|
+
let transient = false;
|
|
7698
|
+
const tried = /* @__PURE__ */ new Set();
|
|
7699
|
+
let scopes;
|
|
7700
|
+
let maxSeq;
|
|
7701
|
+
try {
|
|
7702
|
+
scopes = entityId === void 0 ? (await this.repo.entitiesWithPending()).map((e) => ({ entityId: e })) : ids === void 0 ? [{ entityId }] : chunks(ids, ID_CHUNK).map((c) => ({ entityId, ids: c }));
|
|
7703
|
+
maxSeq = await this.repo.maxSeq();
|
|
7704
|
+
} catch {
|
|
7705
|
+
result.transient = true;
|
|
7706
|
+
try {
|
|
7707
|
+
result.pending = await this.pendingFor(entityId, ids);
|
|
7708
|
+
} catch {
|
|
7709
|
+
}
|
|
7710
|
+
return result;
|
|
7711
|
+
}
|
|
7712
|
+
const perEntity = entityId === void 0;
|
|
7713
|
+
for (const sc of scopes) {
|
|
7714
|
+
if (stop || transient) break;
|
|
7715
|
+
let cursor = { maxSeq, attempts: -1, seq: 0 };
|
|
7716
|
+
let scopeDone = false;
|
|
7717
|
+
if (perEntity) consecutive = 0;
|
|
7718
|
+
while (!stop && !scopeDone) {
|
|
7719
|
+
let page;
|
|
7720
|
+
try {
|
|
7721
|
+
page = await this.db.withTransactionAsync(
|
|
7722
|
+
(tx) => this.repo.readPage(sc, cursor, PAGE, tx)
|
|
7723
|
+
);
|
|
7724
|
+
} catch {
|
|
7725
|
+
transient = true;
|
|
7726
|
+
result.transient = true;
|
|
7727
|
+
break;
|
|
7728
|
+
}
|
|
7729
|
+
if (page.length === 0) break;
|
|
7730
|
+
const last = page[page.length - 1];
|
|
7731
|
+
cursor = { maxSeq, attempts: last.attempts, seq: last.seq };
|
|
7732
|
+
const confirmSeqs = [];
|
|
7733
|
+
const bumpSeqs = [];
|
|
7734
|
+
const deleteSeqs = [];
|
|
7735
|
+
const goneSeqs = [];
|
|
7736
|
+
for (const row of page) {
|
|
7737
|
+
if (tried.has(row.seq)) continue;
|
|
7738
|
+
if (row.fact_state === "live") {
|
|
7739
|
+
tried.add(row.seq);
|
|
7740
|
+
deleteSeqs.push(row.seq);
|
|
7741
|
+
continue;
|
|
7742
|
+
}
|
|
7743
|
+
if (opts.backoff === true && row.last_attempt_at !== null) {
|
|
7744
|
+
if (Date.now() - row.last_attempt_at < removalBackoffMs(row.attempts)) continue;
|
|
7745
|
+
}
|
|
7746
|
+
let budget = timeoutMs;
|
|
7747
|
+
if (opts.deadlineAt !== void 0) {
|
|
7748
|
+
const left = opts.deadlineAt - Date.now();
|
|
7749
|
+
if (left <= 0) {
|
|
7750
|
+
stop = true;
|
|
7751
|
+
break;
|
|
7752
|
+
}
|
|
7753
|
+
budget = Math.min(timeoutMs, left);
|
|
7754
|
+
}
|
|
7755
|
+
tried.add(row.seq);
|
|
7756
|
+
const outcome = await this.callFor(row, budget);
|
|
7757
|
+
if (outcome.ok) {
|
|
7758
|
+
consecutive = 0;
|
|
7759
|
+
if (row.fact_state === "gone") goneSeqs.push(row.seq);
|
|
7760
|
+
else confirmSeqs.push(row.seq);
|
|
7761
|
+
} else {
|
|
7762
|
+
if (!outcome.joined) bumpSeqs.push(row.seq);
|
|
7763
|
+
if (result.failedIds.length < MAX_FAILED_IDS) result.failedIds.push(row.fact_id);
|
|
7764
|
+
if (outcome.timedOut) {
|
|
7765
|
+
result.timedOut = true;
|
|
7766
|
+
result.timedOutId ?? (result.timedOutId = row.fact_id);
|
|
7767
|
+
timeoutErr ?? (timeoutErr = outcome.cause);
|
|
7768
|
+
stop = true;
|
|
7769
|
+
break;
|
|
7770
|
+
}
|
|
7771
|
+
firstRejection ?? (firstRejection = outcome.cause);
|
|
7772
|
+
if (++consecutive >= MAX_CONSECUTIVE_REJECTIONS) {
|
|
7773
|
+
if (perEntity) scopeDone = true;
|
|
7774
|
+
else stop = true;
|
|
7775
|
+
break;
|
|
7776
|
+
}
|
|
7777
|
+
}
|
|
7778
|
+
}
|
|
7779
|
+
if (confirmSeqs.length || bumpSeqs.length || deleteSeqs.length || goneSeqs.length) {
|
|
7780
|
+
const now = Date.now();
|
|
7781
|
+
try {
|
|
7782
|
+
const changed = await this.db.withTransactionAsync(async (tx) => {
|
|
7783
|
+
let n = 0;
|
|
7784
|
+
if (confirmSeqs.length) {
|
|
7785
|
+
n += await this.repo.confirm(confirmSeqs, now, tx);
|
|
7786
|
+
await this.repo.deleteConfirmedGone(confirmSeqs, tx);
|
|
7787
|
+
}
|
|
7788
|
+
if (bumpSeqs.length) await this.repo.bumpAttempts(bumpSeqs, now, tx);
|
|
7789
|
+
if (goneSeqs.length) n += await this.repo.deleteBySeq(goneSeqs, tx);
|
|
7790
|
+
if (deleteSeqs.length) await this.repo.deleteBySeq(deleteSeqs, tx);
|
|
7791
|
+
return n;
|
|
7792
|
+
});
|
|
7793
|
+
result.confirmed += changed;
|
|
7794
|
+
} catch {
|
|
7795
|
+
transient = true;
|
|
7796
|
+
result.transient = true;
|
|
7797
|
+
break;
|
|
7798
|
+
}
|
|
7799
|
+
}
|
|
7800
|
+
if (page.length < PAGE) break;
|
|
7801
|
+
}
|
|
7802
|
+
}
|
|
7803
|
+
result.firstCause = timeoutErr ?? firstRejection;
|
|
7804
|
+
try {
|
|
7805
|
+
result.pending = await this.pendingFor(entityId, ids);
|
|
7806
|
+
} catch {
|
|
7807
|
+
result.transient = true;
|
|
7808
|
+
}
|
|
7809
|
+
return result;
|
|
7810
|
+
}
|
|
7811
|
+
/**
|
|
7812
|
+
* Makes the removal call for `row`, or joins another drain's call for the
|
|
7813
|
+
* same seq. Never throws: the outcome says whether it succeeded, whether
|
|
7814
|
+
* this drain joined (only the owner bumps attempts on failure), and whether
|
|
7815
|
+
* the failure was a timeout.
|
|
7816
|
+
*/
|
|
7817
|
+
async callFor(row, budgetMs) {
|
|
7818
|
+
const end = Date.now() + budgetMs;
|
|
7819
|
+
const left = () => Math.max(1, end - Date.now());
|
|
7820
|
+
let joined = false;
|
|
7821
|
+
try {
|
|
7822
|
+
let existing = this.inFlight.get(row.fact_id);
|
|
7823
|
+
while (existing && existing.seq !== row.seq) {
|
|
7824
|
+
joined = true;
|
|
7825
|
+
await withBudget(existing.promise.catch(() => {
|
|
7826
|
+
}), left());
|
|
7827
|
+
const next = this.inFlight.get(row.fact_id);
|
|
7828
|
+
existing = next === existing ? void 0 : next;
|
|
7829
|
+
}
|
|
7830
|
+
if (existing) {
|
|
7831
|
+
joined = true;
|
|
7832
|
+
await withBudget(existing.promise, left());
|
|
7833
|
+
return { ok: true, joined: true };
|
|
7834
|
+
}
|
|
7835
|
+
joined = false;
|
|
7836
|
+
const p = this.embeddingService.callRemovalHook(row.entity_id, row.fact_id, left());
|
|
7837
|
+
const entry = { seq: row.seq, promise: p };
|
|
7838
|
+
this.inFlight.set(row.fact_id, entry);
|
|
7839
|
+
const clear = () => {
|
|
7840
|
+
if (this.inFlight.get(row.fact_id) === entry) this.inFlight.delete(row.fact_id);
|
|
7841
|
+
};
|
|
7842
|
+
p.then(clear, clear);
|
|
7843
|
+
await p;
|
|
7844
|
+
return { ok: true, joined: false };
|
|
7845
|
+
} catch (err) {
|
|
7846
|
+
const e = err instanceof Error ? err : new Error(String(err));
|
|
7847
|
+
return { ok: false, joined, timedOut: e[HOOK_TIMEOUT_MARKER] === true, cause: e };
|
|
7848
|
+
}
|
|
7849
|
+
}
|
|
7850
|
+
async pendingFor(entityId, ids) {
|
|
7851
|
+
if (entityId !== void 0 && ids !== void 0) {
|
|
7852
|
+
return this.repo.pendingCountForIds(entityId, ids);
|
|
7853
|
+
}
|
|
7854
|
+
return (await this.repo.pendingStats(entityId)).count;
|
|
7855
|
+
}
|
|
7856
|
+
async emitPending(entityId, trigger) {
|
|
7857
|
+
const entities = entityId === void 0 ? await this.repo.entitiesWithPending() : [entityId];
|
|
7858
|
+
for (const e of entities) {
|
|
7859
|
+
const st = await this.repo.pendingStats(e);
|
|
7860
|
+
if (st.count === 0) continue;
|
|
7861
|
+
emitDiagnostic(this.options, {
|
|
7862
|
+
code: "external_deletion_pending",
|
|
7863
|
+
operation: "externalDeletion",
|
|
7864
|
+
trigger,
|
|
7865
|
+
entityId: e,
|
|
7866
|
+
detail: {
|
|
7867
|
+
count: st.count,
|
|
7868
|
+
...st.oldestEnqueuedAt !== null ? { oldestEnqueuedAt: st.oldestEnqueuedAt } : {},
|
|
7869
|
+
maxAttempts: st.maxAttempts
|
|
7870
|
+
}
|
|
7871
|
+
});
|
|
7872
|
+
}
|
|
7873
|
+
}
|
|
7874
|
+
};
|
|
7875
|
+
function withBudget(p, ms) {
|
|
7876
|
+
let handle;
|
|
7877
|
+
const timer = new Promise((_, reject) => {
|
|
7878
|
+
handle = setTimeout(() => {
|
|
7879
|
+
const e = new Error(`onEmbeddingPersisted timed out after ${ms}ms`);
|
|
7880
|
+
e[HOOK_TIMEOUT_MARKER] = true;
|
|
7881
|
+
reject(e);
|
|
7882
|
+
}, ms);
|
|
7883
|
+
});
|
|
7884
|
+
return Promise.race([p, timer]).finally(() => {
|
|
7885
|
+
if (handle) clearTimeout(handle);
|
|
7886
|
+
});
|
|
7887
|
+
}
|
|
7888
|
+
|
|
7251
7889
|
// src/services/legacyWatermark.ts
|
|
7252
7890
|
async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
|
|
7253
7891
|
if (checkpoint <= 0 || total <= 0) return null;
|
|
@@ -8212,7 +8850,7 @@ var formatSkipError = (err) => {
|
|
|
8212
8850
|
return base;
|
|
8213
8851
|
};
|
|
8214
8852
|
var MaintenanceService = class {
|
|
8215
|
-
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo) {
|
|
8853
|
+
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
|
|
8216
8854
|
this.db = db;
|
|
8217
8855
|
this.prefix = prefix;
|
|
8218
8856
|
this.options = options;
|
|
@@ -8225,6 +8863,8 @@ var MaintenanceService = class {
|
|
|
8225
8863
|
this.jobManager = jobManager;
|
|
8226
8864
|
this.embeddingService = embeddingService;
|
|
8227
8865
|
this.ontologyService = ontologyService;
|
|
8866
|
+
this.vectorRemoval = vectorRemoval;
|
|
8867
|
+
this.vectorRemovalRepo = vectorRemovalRepo;
|
|
8228
8868
|
this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
|
|
8229
8869
|
this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
|
|
8230
8870
|
}
|
|
@@ -8238,11 +8878,14 @@ var MaintenanceService = class {
|
|
|
8238
8878
|
this._validatePruneDuration(retainEventsFor, "retainEventsFor");
|
|
8239
8879
|
const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
|
|
8240
8880
|
this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
|
|
8881
|
+
const gate = removalGate(this.options);
|
|
8882
|
+
if (gate === "hook") this.embeddingService.validateDeletionTimeout();
|
|
8241
8883
|
const now = Date.now();
|
|
8242
8884
|
let syncedIds = [];
|
|
8243
8885
|
let deletedEntries = 0;
|
|
8244
8886
|
let deletedTasks = 0;
|
|
8245
8887
|
let deletedEvents = 0;
|
|
8888
|
+
let prunePartial = null;
|
|
8246
8889
|
if (pruneSupersededAfter !== null) {
|
|
8247
8890
|
const expiredCutoff = now - pruneSupersededAfter * 864e5;
|
|
8248
8891
|
const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
|
|
@@ -8251,55 +8894,89 @@ var MaintenanceService = class {
|
|
|
8251
8894
|
await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
|
|
8252
8895
|
});
|
|
8253
8896
|
syncedIds = [...expiredIds];
|
|
8897
|
+
if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
|
|
8898
|
+
await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
|
|
8899
|
+
}
|
|
8254
8900
|
}
|
|
8255
8901
|
}
|
|
8256
8902
|
if (retainSoftDeletedFor !== null) {
|
|
8257
8903
|
const cutoff = now - retainSoftDeletedFor * 864e5;
|
|
8258
8904
|
const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
|
|
8259
|
-
const
|
|
8260
|
-
|
|
8261
|
-
|
|
8262
|
-
|
|
8263
|
-
|
|
8264
|
-
|
|
8265
|
-
|
|
8266
|
-
|
|
8267
|
-
|
|
8905
|
+
const prunableIds = entriesToDelete.map((r) => r.id);
|
|
8906
|
+
const vr = this.vectorRemoval;
|
|
8907
|
+
const vrRepo = this.vectorRemovalRepo;
|
|
8908
|
+
const ledgerOn = !!vr && !!vrRepo && await vr.ledgerPresent();
|
|
8909
|
+
let deletable = prunableIds;
|
|
8910
|
+
let removeLedger = false;
|
|
8911
|
+
let kept = [];
|
|
8912
|
+
let timedOut = false;
|
|
8913
|
+
let cause;
|
|
8914
|
+
let firstFailed;
|
|
8915
|
+
let failedOrder = [];
|
|
8916
|
+
if (ledgerOn && vr && vrRepo) {
|
|
8917
|
+
if (gate === "hook" && prunableIds.length > 0) {
|
|
8918
|
+
await this.db.withTransactionAsync(async (tx) => {
|
|
8919
|
+
await vrRepo.backstopEnqueue(entityId, prunableIds, now, tx);
|
|
8920
|
+
});
|
|
8268
8921
|
}
|
|
8922
|
+
const result = prunableIds.length > 0 ? await vr.drain({ entityId, ids: prunableIds }) : { failedIds: [], timedOut: false, firstCause: void 0 };
|
|
8923
|
+
if (gate === "hook") {
|
|
8924
|
+
timedOut = result.timedOut;
|
|
8925
|
+
cause = result.firstCause;
|
|
8926
|
+
failedOrder = result.failedIds;
|
|
8927
|
+
} else if (gate === "force") {
|
|
8928
|
+
removeLedger = true;
|
|
8929
|
+
} else {
|
|
8930
|
+
removeLedger = !await vr.externalIndexInUse();
|
|
8931
|
+
}
|
|
8932
|
+
} else if (gate === "hook") {
|
|
8933
|
+
const r = await this.embeddingService.callRemovalHookEach(entityId, prunableIds);
|
|
8934
|
+
const failedSet = new Set(r.failed);
|
|
8935
|
+
kept = r.failed;
|
|
8936
|
+
deletable = prunableIds.filter((id) => !failedSet.has(id));
|
|
8937
|
+
timedOut = r.timedOut;
|
|
8938
|
+
cause = r.cause;
|
|
8939
|
+
firstFailed = kept[0];
|
|
8269
8940
|
}
|
|
8270
|
-
const
|
|
8271
|
-
syncedIds = [...syncedIds, ...succeededIds];
|
|
8941
|
+
const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
|
|
8272
8942
|
await this.db.withTransactionAsync(async (tx) => {
|
|
8273
|
-
if (
|
|
8274
|
-
|
|
8943
|
+
if (hookLedger && vrRepo && prunableIds.length > 0) {
|
|
8944
|
+
const status = await vrRepo.statusFor(prunableIds, tx);
|
|
8945
|
+
deletable = prunableIds.filter((id) => status.get(id) !== "pending");
|
|
8946
|
+
kept = prunableIds.filter((id) => status.get(id) === "pending");
|
|
8947
|
+
}
|
|
8948
|
+
if (deletable.length > 0) {
|
|
8949
|
+
const deletedIds = [];
|
|
8950
|
+
deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
|
|
8951
|
+
if (hookLedger) {
|
|
8952
|
+
const gone = new Set(deletedIds);
|
|
8953
|
+
const skipped = deletable.filter((id) => !gone.has(id));
|
|
8954
|
+
if (skipped.length > 0) {
|
|
8955
|
+
const after = await vrRepo.statusFor(skipped, tx);
|
|
8956
|
+
kept = [...kept, ...skipped.filter((id) => after.get(id) === "pending")];
|
|
8957
|
+
}
|
|
8958
|
+
deletable = deletedIds;
|
|
8959
|
+
}
|
|
8960
|
+
if (vrRepo && ledgerOn) {
|
|
8961
|
+
if (removeLedger) await vrRepo.deleteForFacts(entityId, deletable, tx, "all");
|
|
8962
|
+
else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
|
|
8963
|
+
}
|
|
8275
8964
|
}
|
|
8276
8965
|
deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
|
|
8277
8966
|
});
|
|
8278
|
-
if (
|
|
8279
|
-
|
|
8280
|
-
|
|
8281
|
-
|
|
8282
|
-
|
|
8283
|
-
|
|
8284
|
-
|
|
8285
|
-
|
|
8286
|
-
|
|
8287
|
-
|
|
8288
|
-
|
|
8289
|
-
|
|
8290
|
-
);
|
|
8967
|
+
if (hookLedger) {
|
|
8968
|
+
const keptSet = new Set(kept);
|
|
8969
|
+
firstFailed = failedOrder.find((id) => keptSet.has(id)) ?? kept[0];
|
|
8970
|
+
}
|
|
8971
|
+
syncedIds = [...syncedIds, ...deletable];
|
|
8972
|
+
if (kept.length > 0) {
|
|
8973
|
+
if (timedOut) {
|
|
8974
|
+
prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("Deletion hook timed out") };
|
|
8975
|
+
} else if (cause === void 0) {
|
|
8976
|
+
prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: new Error("external removal not confirmed") };
|
|
8977
|
+
} else {
|
|
8978
|
+
prunePartial = { failedAt: firstFailed ?? kept[0], remaining: kept.length, cause: this._sanitizeRankerError(cause) };
|
|
8291
8979
|
}
|
|
8292
|
-
const errMsg = failure.cause?.message ?? "";
|
|
8293
|
-
const isValidationError = errMsg.startsWith("Invalid deletionHookTimeoutMs");
|
|
8294
|
-
const sanitizedCause = isValidationError ? failure.cause : this._sanitizeRankerError(failure.cause);
|
|
8295
|
-
throw new PrunePartialFailureError(
|
|
8296
|
-
succeeded.length,
|
|
8297
|
-
failure.factId,
|
|
8298
|
-
remaining,
|
|
8299
|
-
sanitizedCause,
|
|
8300
|
-
deletedTasks,
|
|
8301
|
-
0
|
|
8302
|
-
);
|
|
8303
8980
|
}
|
|
8304
8981
|
}
|
|
8305
8982
|
if (retainEventsFor !== null) {
|
|
@@ -8336,6 +9013,16 @@ var MaintenanceService = class {
|
|
|
8336
9013
|
await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
|
|
8337
9014
|
}
|
|
8338
9015
|
await this.searchService.syncEntries(entityId, syncedIds);
|
|
9016
|
+
if (prunePartial) {
|
|
9017
|
+
throw new PrunePartialFailureError(
|
|
9018
|
+
deletedEntries,
|
|
9019
|
+
prunePartial.failedAt,
|
|
9020
|
+
prunePartial.remaining,
|
|
9021
|
+
prunePartial.cause,
|
|
9022
|
+
deletedTasks,
|
|
9023
|
+
deletedEvents
|
|
9024
|
+
);
|
|
9025
|
+
}
|
|
8339
9026
|
return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
|
|
8340
9027
|
} finally {
|
|
8341
9028
|
this.jobManager.releaseLock("prune", entityId);
|
|
@@ -8440,6 +9127,7 @@ var MaintenanceService = class {
|
|
|
8440
9127
|
}
|
|
8441
9128
|
const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
|
|
8442
9129
|
if (result.ok) embedded++;
|
|
9130
|
+
else if (result.kind === "fact_deleted") skipped++;
|
|
8443
9131
|
else failed++;
|
|
8444
9132
|
}
|
|
8445
9133
|
if (embedded > 0) {
|
|
@@ -8470,6 +9158,7 @@ var MaintenanceService = class {
|
|
|
8470
9158
|
let deletedTasks = 0;
|
|
8471
9159
|
let deletedEvents = 0;
|
|
8472
9160
|
const deletedEntryIds = [];
|
|
9161
|
+
const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
|
|
8473
9162
|
await this.db.withTransactionAsync(async (tx) => {
|
|
8474
9163
|
if (params.clearAll) {
|
|
8475
9164
|
for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
|
|
@@ -8518,22 +9207,54 @@ var MaintenanceService = class {
|
|
|
8518
9207
|
if (taskResult) deletedTasks++;
|
|
8519
9208
|
deletedEntries += refResult;
|
|
8520
9209
|
}
|
|
9210
|
+
if (ledgerOn && this.vectorRemoval?.gate() === "hook" && deletedEntryIds.length > 0) {
|
|
9211
|
+
await this.vectorRemovalRepo?.backstopEnqueue(entityId, Array.from(new Set(deletedEntryIds)), now, tx);
|
|
9212
|
+
}
|
|
8521
9213
|
});
|
|
8522
9214
|
const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
|
|
8523
9215
|
await this.searchService.syncEntries(entityId, uniqueDeletedIds);
|
|
8524
|
-
|
|
9216
|
+
if (uniqueDeletedIds.length > 0) {
|
|
9217
|
+
const firstId = uniqueDeletedIds[0];
|
|
9218
|
+
const vr = this.vectorRemoval;
|
|
9219
|
+
const vrRepo = this.vectorRemovalRepo;
|
|
9220
|
+
let unconfirmed = [];
|
|
9221
|
+
let timedOut = false;
|
|
9222
|
+
let cause;
|
|
9223
|
+
let timedOutId;
|
|
8525
9224
|
try {
|
|
8526
|
-
|
|
8527
|
-
|
|
8528
|
-
|
|
8529
|
-
|
|
8530
|
-
|
|
9225
|
+
if (vr && vrRepo && ledgerOn) {
|
|
9226
|
+
const result = await vr.drain({ entityId, ids: uniqueDeletedIds });
|
|
9227
|
+
if (vr.gate() === "hook") {
|
|
9228
|
+
const status = await vrRepo.statusFor(uniqueDeletedIds);
|
|
9229
|
+
unconfirmed = uniqueDeletedIds.filter((id) => status.get(id) === "pending");
|
|
9230
|
+
timedOut = result.timedOut;
|
|
9231
|
+
timedOutId = result.timedOutId;
|
|
9232
|
+
cause = result.firstCause;
|
|
9233
|
+
}
|
|
9234
|
+
} else if (this.options.vectorRanker?.onEmbeddingPersisted && this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
9235
|
+
const r = await this.embeddingService.callRemovalHookEach(entityId, uniqueDeletedIds);
|
|
9236
|
+
unconfirmed = r.failed;
|
|
9237
|
+
timedOut = r.timedOut;
|
|
9238
|
+
timedOutId = r.timedOutId;
|
|
9239
|
+
cause = r.cause;
|
|
8531
9240
|
}
|
|
9241
|
+
} catch (hookErr) {
|
|
8532
9242
|
const errMsg = hookErr?.message ?? "";
|
|
8533
9243
|
if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
|
|
8534
|
-
throw new Error(`forget(${entityId}/${
|
|
9244
|
+
throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
|
|
8535
9245
|
}
|
|
8536
|
-
throw
|
|
9246
|
+
throw hookErr;
|
|
9247
|
+
}
|
|
9248
|
+
if (unconfirmed.length > 0) {
|
|
9249
|
+
const head = `forget(${entityId}/${(timedOut ? timedOutId : void 0) ?? unconfirmed[0]}) failed: `;
|
|
9250
|
+
const message = timedOut ? head + (cause?.message ?? "onEmbeddingPersisted timed out") : cause === void 0 ? head + "ANN cleanup not confirmed" : head + "ANN cleanup hook rejected";
|
|
9251
|
+
throw new WikiExternalDeletionError(message, {
|
|
9252
|
+
entityId,
|
|
9253
|
+
unconfirmedIds: unconfirmed.slice(0, 100),
|
|
9254
|
+
unconfirmedCount: unconfirmed.length,
|
|
9255
|
+
timedOut,
|
|
9256
|
+
cause: timedOut || cause === void 0 ? void 0 : this._sanitizeRankerError(cause)
|
|
9257
|
+
});
|
|
8537
9258
|
}
|
|
8538
9259
|
}
|
|
8539
9260
|
if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
|
|
@@ -8542,6 +9263,22 @@ var MaintenanceService = class {
|
|
|
8542
9263
|
this.jobManager.releaseLock("forget", entityId);
|
|
8543
9264
|
}
|
|
8544
9265
|
}
|
|
9266
|
+
/** Heal's post-commit removal delivery (spec §5.7). Never throws. */
|
|
9267
|
+
async deliverHealRemovals(entityId, ids, trigger) {
|
|
9268
|
+
if (this.vectorRemoval) {
|
|
9269
|
+
await this.vectorRemoval.deliverRemovals(entityId, ids, "heal", trigger);
|
|
9270
|
+
return;
|
|
9271
|
+
}
|
|
9272
|
+
if (this.options.forceDeleteIgnoreRankerHook === true) return;
|
|
9273
|
+
for (const factId of ids) {
|
|
9274
|
+
try {
|
|
9275
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
9276
|
+
} catch (hookErr) {
|
|
9277
|
+
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
|
|
9278
|
+
emitDiagnostic(this.options, { entityId, operation: "heal", trigger, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
|
|
9279
|
+
}
|
|
9280
|
+
}
|
|
9281
|
+
}
|
|
8545
9282
|
/**
|
|
8546
9283
|
* Whether forget() should soft-delete in source_ref_index (#316,
|
|
8547
9284
|
* specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
|
|
@@ -8739,14 +9476,7 @@ var MaintenanceService = class {
|
|
|
8739
9476
|
staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
|
|
8740
9477
|
}
|
|
8741
9478
|
});
|
|
8742
|
-
|
|
8743
|
-
try {
|
|
8744
|
-
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
8745
|
-
} catch (hookErr) {
|
|
8746
|
-
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal orphan pass for ${factId}:`, hookErr);
|
|
8747
|
-
emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
|
|
8748
|
-
}
|
|
8749
|
-
}
|
|
9479
|
+
await this.deliverHealRemovals(entityId, orphanedIds, trigger);
|
|
8750
9480
|
const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
|
|
8751
9481
|
const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
|
|
8752
9482
|
if (healCandidates.length === 0 || keywordUnavailable) {
|
|
@@ -8935,14 +9665,7 @@ var MaintenanceService = class {
|
|
|
8935
9665
|
...insertedFacts.map((f) => f.id)
|
|
8936
9666
|
]));
|
|
8937
9667
|
await this.searchService.syncEntries(entityId, healSyncIds);
|
|
8938
|
-
|
|
8939
|
-
try {
|
|
8940
|
-
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
8941
|
-
} catch (hookErr) {
|
|
8942
|
-
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
|
|
8943
|
-
emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
|
|
8944
|
-
}
|
|
8945
|
-
}
|
|
9668
|
+
await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
|
|
8946
9669
|
for (const fact of insertedFacts) {
|
|
8947
9670
|
await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
|
|
8948
9671
|
}
|
|
@@ -9308,7 +10031,7 @@ var MaintenanceService = class {
|
|
|
9308
10031
|
|
|
9309
10032
|
// src/services/MaintenanceScheduler.ts
|
|
9310
10033
|
var MaintenanceScheduler = class {
|
|
9311
|
-
constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager) {
|
|
10034
|
+
constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager, vectorRemovalService, vectorRemovalRepo) {
|
|
9312
10035
|
this.db = db;
|
|
9313
10036
|
this.options = options;
|
|
9314
10037
|
this.maintenanceService = maintenanceService;
|
|
@@ -9316,6 +10039,8 @@ var MaintenanceScheduler = class {
|
|
|
9316
10039
|
this.eventRepo = eventRepo;
|
|
9317
10040
|
this.entryRepo = entryRepo;
|
|
9318
10041
|
this.jobManager = jobManager;
|
|
10042
|
+
this.vectorRemovalService = vectorRemovalService;
|
|
10043
|
+
this.vectorRemovalRepo = vectorRemovalRepo;
|
|
9319
10044
|
}
|
|
9320
10045
|
/**
|
|
9321
10046
|
* Entities with **any** pending work only, sorted by `pendingEvents` desc
|
|
@@ -9327,7 +10052,17 @@ var MaintenanceScheduler = class {
|
|
|
9327
10052
|
const autoHealThreshold = this.options.config?.autoHealThreshold || 100;
|
|
9328
10053
|
const canEmbed = typeof this.options.llmProvider.embed === "function";
|
|
9329
10054
|
const out = [];
|
|
9330
|
-
|
|
10055
|
+
const owed = /* @__PURE__ */ new Map();
|
|
10056
|
+
if (this.vectorRemovalService.gate() !== "none" && await this.vectorRemovalService.ledgerPresent()) {
|
|
10057
|
+
const scope = entityIds === void 0 ? void 0 : new Set(entityIds);
|
|
10058
|
+
for (const e of await this.vectorRemovalRepo.entitiesWithDuePending(Date.now())) {
|
|
10059
|
+
if (scope !== void 0 && !scope.has(e)) continue;
|
|
10060
|
+
owed.set(e, (await this.vectorRemovalRepo.pendingStats(e)).count);
|
|
10061
|
+
}
|
|
10062
|
+
}
|
|
10063
|
+
const listed = new Set(ids);
|
|
10064
|
+
const scan = [...ids, ...[...owed.keys()].filter((e) => !listed.has(e))];
|
|
10065
|
+
for (const entityId of scan) {
|
|
9331
10066
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
9332
10067
|
const pendingEvents = await this.eventRepo.countAfter(entityId, wm);
|
|
9333
10068
|
const chars = pendingEvents > 0 ? await this.eventRepo.sumSummaryCharsAfter(entityId, wm) : 0;
|
|
@@ -9337,8 +10072,16 @@ var MaintenanceScheduler = class {
|
|
|
9337
10072
|
if (healCheckpoint > eventCount) healCheckpoint = 0;
|
|
9338
10073
|
const healDue = eventCount - healCheckpoint >= autoHealThreshold;
|
|
9339
10074
|
const reembedPending = canEmbed && await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS) > 0;
|
|
9340
|
-
|
|
9341
|
-
|
|
10075
|
+
const owedCount = owed.get(entityId) ?? 0;
|
|
10076
|
+
if (pendingEvents > 0 || healDue || reembedPending || owedCount > 0) {
|
|
10077
|
+
out.push({
|
|
10078
|
+
entityId,
|
|
10079
|
+
pendingEvents,
|
|
10080
|
+
pendingTokensEstimate: Math.ceil(chars / 4),
|
|
10081
|
+
healDue,
|
|
10082
|
+
reembedPending,
|
|
10083
|
+
...owedCount > 0 ? { pendingExternalDeletions: owedCount } : {}
|
|
10084
|
+
});
|
|
9342
10085
|
}
|
|
9343
10086
|
}
|
|
9344
10087
|
return out.sort((x, y) => y.pendingEvents - x.pendingEvents || (x.entityId < y.entityId ? -1 : x.entityId > y.entityId ? 1 : 0));
|
|
@@ -9364,8 +10107,9 @@ var MaintenanceScheduler = class {
|
|
|
9364
10107
|
const meter = new UsageMeter(opts.tokenBudget);
|
|
9365
10108
|
const budget = opts.tokenBudget;
|
|
9366
10109
|
const deadline = opts.deadlineMs !== void 0 ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;
|
|
9367
|
-
const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed"]);
|
|
9368
|
-
const
|
|
10110
|
+
const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed", "externalDeletions"]);
|
|
10111
|
+
const externalDeletions = await this.runExternalDeletions(opts.entityIds, jobs.has("externalDeletions"), deadline);
|
|
10112
|
+
const pending = (await this.getPending(opts.entityIds)).filter((p) => p.pendingEvents > 0 || p.healDue || p.reembedPending);
|
|
9369
10113
|
const states = pending.map((p) => ({
|
|
9370
10114
|
p,
|
|
9371
10115
|
report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false },
|
|
@@ -9497,9 +10241,43 @@ var MaintenanceScheduler = class {
|
|
|
9497
10241
|
tokensUsed: meter.used,
|
|
9498
10242
|
estimated: meter.estimated,
|
|
9499
10243
|
remaining: budget === void 0 ? null : meter.remaining,
|
|
9500
|
-
stoppedReason: stopped
|
|
10244
|
+
stoppedReason: stopped,
|
|
10245
|
+
externalDeletions
|
|
9501
10246
|
};
|
|
9502
10247
|
}
|
|
10248
|
+
/**
|
|
10249
|
+
* Runs first and outside the token budget: delivers owed vector-index
|
|
10250
|
+
* removals per entity (wiped entities included), without backoff. Pending is
|
|
10251
|
+
* reported even when the job is not listed or no hook is configured.
|
|
10252
|
+
*/
|
|
10253
|
+
async runExternalDeletions(entityIds, enabled, deadline) {
|
|
10254
|
+
if (!await this.vectorRemovalService.ledgerPresent()) return { confirmed: 0, pending: 0 };
|
|
10255
|
+
const all = await this.vectorRemovalRepo.entitiesWithPending();
|
|
10256
|
+
const scope = entityIds === void 0 ? void 0 : new Set(entityIds);
|
|
10257
|
+
const entities = scope === void 0 ? all : all.filter((e) => scope.has(e));
|
|
10258
|
+
let confirmed = 0;
|
|
10259
|
+
let pending = 0;
|
|
10260
|
+
const counted = /* @__PURE__ */ new Set();
|
|
10261
|
+
if (enabled) {
|
|
10262
|
+
for (const e of entities) {
|
|
10263
|
+
if (Date.now() >= deadline) break;
|
|
10264
|
+
const r = await this.vectorRemovalService.drain(
|
|
10265
|
+
{ entityId: e },
|
|
10266
|
+
{ trigger: "call", ...deadline === Infinity ? {} : { deadlineAt: deadline } }
|
|
10267
|
+
);
|
|
10268
|
+
confirmed += r.confirmed;
|
|
10269
|
+
if (!r.transient) {
|
|
10270
|
+
pending += r.pending;
|
|
10271
|
+
counted.add(e);
|
|
10272
|
+
}
|
|
10273
|
+
if (r.timedOut) break;
|
|
10274
|
+
}
|
|
10275
|
+
}
|
|
10276
|
+
for (const e of entities) {
|
|
10277
|
+
if (!counted.has(e)) pending += (await this.vectorRemovalRepo.pendingStats(e)).count;
|
|
10278
|
+
}
|
|
10279
|
+
return { confirmed, pending };
|
|
10280
|
+
}
|
|
9503
10281
|
};
|
|
9504
10282
|
|
|
9505
10283
|
// src/services/importEventStamps.ts
|
|
@@ -9564,7 +10342,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
|
|
|
9564
10342
|
var IMPORT_TITLE_MAX = 500;
|
|
9565
10343
|
var IMPORT_BODY_MAX = 8e3;
|
|
9566
10344
|
var ImportExportService = class {
|
|
9567
|
-
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
|
|
10345
|
+
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
|
|
9568
10346
|
this.db = db;
|
|
9569
10347
|
this.entryRepo = entryRepo;
|
|
9570
10348
|
this.taskRepo = taskRepo;
|
|
@@ -9575,6 +10353,7 @@ var ImportExportService = class {
|
|
|
9575
10353
|
this.jobManager = jobManager;
|
|
9576
10354
|
this.embeddingService = embeddingService;
|
|
9577
10355
|
this.options = options;
|
|
10356
|
+
this.vectorRemoval = vectorRemoval;
|
|
9578
10357
|
}
|
|
9579
10358
|
async exportDump(entityIds) {
|
|
9580
10359
|
let ids;
|
|
@@ -9950,7 +10729,7 @@ var ImportExportService = class {
|
|
|
9950
10729
|
body: clipped?.body ?? fact.body,
|
|
9951
10730
|
tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
|
|
9952
10731
|
}, { operation: "importDump", trigger: "call" });
|
|
9953
|
-
if (!embedded) {
|
|
10732
|
+
if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
9954
10733
|
try {
|
|
9955
10734
|
await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
|
|
9956
10735
|
} catch (hookErr) {
|
|
@@ -9992,16 +10771,26 @@ var ImportExportService = class {
|
|
|
9992
10771
|
fact.id
|
|
9993
10772
|
);
|
|
9994
10773
|
}
|
|
10774
|
+
if (this.embeddingService.hasVectorHook()) {
|
|
10775
|
+
await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
|
|
10776
|
+
}
|
|
9995
10777
|
}
|
|
9996
10778
|
}
|
|
9997
|
-
|
|
9998
|
-
|
|
10779
|
+
const removedIds = softDeletedFactIds.filter(
|
|
10780
|
+
(id) => !upsertedFactIds.has(id) || upsertedDeletedFactIds.has(id)
|
|
10781
|
+
);
|
|
10782
|
+
if (this.vectorRemoval) {
|
|
10783
|
+
await this.vectorRemoval.deliverRemovals(
|
|
10784
|
+
entityId,
|
|
10785
|
+
Array.from(/* @__PURE__ */ new Set([...removedIds, ...upsertedDeletedFactIds])),
|
|
10786
|
+
"importDump",
|
|
10787
|
+
"call",
|
|
10788
|
+
removedIds
|
|
10789
|
+
);
|
|
10790
|
+
} else if (this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
10791
|
+
for (const factId of removedIds) {
|
|
9999
10792
|
try {
|
|
10000
|
-
await this.embeddingService.notifyEmbeddingPersisted(
|
|
10001
|
-
entityId,
|
|
10002
|
-
factId,
|
|
10003
|
-
null
|
|
10004
|
-
);
|
|
10793
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
10005
10794
|
} catch (hookErr) {
|
|
10006
10795
|
console.warn(
|
|
10007
10796
|
`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
|
|
@@ -10238,27 +11027,62 @@ var EmbeddingService = class {
|
|
|
10238
11027
|
}
|
|
10239
11028
|
/**
|
|
10240
11029
|
* Storage half: persist the computed vector to the entry row, then fire the
|
|
10241
|
-
* `onEmbeddingPersisted` hook. Failure kinds: `storage_error`
|
|
10242
|
-
*
|
|
11030
|
+
* `onEmbeddingPersisted` hook. Failure kinds: `storage_error` (a DB error) and
|
|
11031
|
+
* `fact_deleted` (the row was soft-deleted or gone: no blob, no vector call, no
|
|
11032
|
+
* marker). Embed failures do not originate here, so they cannot be marked as
|
|
11033
|
+
* such (spec §3.2, D3).
|
|
10243
11034
|
*/
|
|
10244
11035
|
async storeFactVector(fact, float32Vector, ctx) {
|
|
11036
|
+
let stored = true;
|
|
10245
11037
|
try {
|
|
10246
11038
|
await this.storeEmbeddingDimension(float32Vector.length);
|
|
10247
11039
|
const blob = new Uint8Array(float32Vector.buffer);
|
|
10248
|
-
await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
|
|
11040
|
+
stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
|
|
10249
11041
|
} catch (err) {
|
|
10250
11042
|
console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
|
|
10251
11043
|
this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
|
|
10252
11044
|
return { ok: false, kind: "storage_error" };
|
|
10253
11045
|
}
|
|
11046
|
+
if (!stored) return { ok: false, kind: "fact_deleted" };
|
|
10254
11047
|
try {
|
|
10255
11048
|
await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
|
|
10256
11049
|
} catch (hookErr) {
|
|
10257
11050
|
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
|
|
10258
11051
|
this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
|
|
10259
11052
|
}
|
|
11053
|
+
if (this.hasVectorHook()) {
|
|
11054
|
+
await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
|
|
11055
|
+
}
|
|
10260
11056
|
return { ok: true, dimension: float32Vector.length };
|
|
10261
11057
|
}
|
|
11058
|
+
hasVectorHook() {
|
|
11059
|
+
return !!this.options.vectorRanker?.onEmbeddingPersisted;
|
|
11060
|
+
}
|
|
11061
|
+
/**
|
|
11062
|
+
* Run after a vector call (resolved or not) by every path that sends one.
|
|
11063
|
+
* Never throws: a failure here leaves the removal owed or unrecorded, as before.
|
|
11064
|
+
*/
|
|
11065
|
+
async settleAfterVectorCall(entityId, factId, operation, trigger) {
|
|
11066
|
+
const vr = this.vectorRemoval;
|
|
11067
|
+
if (!vr) return;
|
|
11068
|
+
const outcome = await this.recordAfterVectorCall(entityId, factId);
|
|
11069
|
+
if (outcome === "enqueued") {
|
|
11070
|
+
try {
|
|
11071
|
+
await vr.service.deliverRemovals(entityId, [factId], operation, trigger, []);
|
|
11072
|
+
} catch (err) {
|
|
11073
|
+
console.warn(`[WikiMemory] post-embed removal delivery failed for ${factId}:`, err);
|
|
11074
|
+
}
|
|
11075
|
+
return;
|
|
11076
|
+
}
|
|
11077
|
+
if (outcome !== "write_failed") return;
|
|
11078
|
+
try {
|
|
11079
|
+
await this.callRemovalHook(entityId, factId, this.validateDeletionTimeout());
|
|
11080
|
+
} catch (hookErr) {
|
|
11081
|
+
console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
|
|
11082
|
+
this.reportHookFailed({ operation, trigger }, entityId, factId);
|
|
11083
|
+
await this.recordAfterVectorCall(entityId, factId);
|
|
11084
|
+
}
|
|
11085
|
+
}
|
|
10262
11086
|
reportEmbed(ctx, fact, code, reason) {
|
|
10263
11087
|
if (!ctx) return;
|
|
10264
11088
|
emitDiagnostic(this.options, {
|
|
@@ -10290,6 +11114,48 @@ var EmbeddingService = class {
|
|
|
10290
11114
|
const result = await this.tryEmbedFact(fact, ctx);
|
|
10291
11115
|
return result.ok;
|
|
10292
11116
|
}
|
|
11117
|
+
/** Wired by WikiMemory (VectorRemovalService itself depends on this class). */
|
|
11118
|
+
attachVectorRemoval(service, repo) {
|
|
11119
|
+
this.vectorRemoval = { service, repo };
|
|
11120
|
+
}
|
|
11121
|
+
/**
|
|
11122
|
+
* After an embed (and its vector call) settles: owe a removal if the fact is
|
|
11123
|
+
* no longer live, so a vector the host just received is taken back (§5.7, G10).
|
|
11124
|
+
* Never throws. `'enqueued'`: a ledger row was written. `'none'`: no
|
|
11125
|
+
* removal hook (or the hook gate is off). `'live'`: the fact is live. A row already pending is
|
|
11126
|
+
* replaced (attempts reset, spec §5.2), so it counts as `'enqueued'` and
|
|
11127
|
+
* is sent now: the last call the host sees after this vector is `null`.
|
|
11128
|
+
* `'owed'`: the write failed but a pending row already holds the removal.
|
|
11129
|
+
* `'write_failed'`: the fact is known not live, the write failed, and its
|
|
11130
|
+
* row is confirmed or missing; or the store has no ledger table and the
|
|
11131
|
+
* fact is known not live.
|
|
11132
|
+
* `'unknown'`: the liveness read and the guarded write both failed.
|
|
11133
|
+
*/
|
|
11134
|
+
async recordAfterVectorCall(entityId, factId) {
|
|
11135
|
+
const vr = this.vectorRemoval;
|
|
11136
|
+
if (!vr || vr.service.gate() !== "hook") return "none";
|
|
11137
|
+
let live;
|
|
11138
|
+
try {
|
|
11139
|
+
if (!await vr.service.ledgerPresent()) {
|
|
11140
|
+
return await vr.repo.isLive(factId) ? "live" : "write_failed";
|
|
11141
|
+
}
|
|
11142
|
+
live = await vr.repo.isLive(factId);
|
|
11143
|
+
} catch (err) {
|
|
11144
|
+
console.warn(`[WikiMemory] post-embed liveness read failed for ${factId}:`, err);
|
|
11145
|
+
}
|
|
11146
|
+
if (live) return "live";
|
|
11147
|
+
try {
|
|
11148
|
+
return await vr.repo.enqueueIfNotLive(entityId, factId, Date.now()) ? "enqueued" : "live";
|
|
11149
|
+
} catch (err) {
|
|
11150
|
+
console.warn(`[WikiMemory] post-embed removal could not be recorded for ${factId}:`, err);
|
|
11151
|
+
if (live !== false) return "unknown";
|
|
11152
|
+
try {
|
|
11153
|
+
if ((await vr.repo.statusFor([factId])).get(factId) === "pending") return "owed";
|
|
11154
|
+
} catch {
|
|
11155
|
+
}
|
|
11156
|
+
return "write_failed";
|
|
11157
|
+
}
|
|
11158
|
+
}
|
|
10293
11159
|
async notifyEmbeddingPersisted(entityId, factId, vector) {
|
|
10294
11160
|
if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
|
|
10295
11161
|
const vectorCopy = vector ? vector.slice() : null;
|
|
@@ -10299,15 +11165,72 @@ var EmbeddingService = class {
|
|
|
10299
11165
|
vector: vectorCopy
|
|
10300
11166
|
});
|
|
10301
11167
|
}
|
|
10302
|
-
|
|
10303
|
-
if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
|
|
10304
|
-
if (this.options.forceDeleteIgnoreRankerHook === true) return;
|
|
10305
|
-
const vectorCopy = vector ? vector.slice() : null;
|
|
11168
|
+
validateDeletionTimeout() {
|
|
10306
11169
|
const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
|
|
10307
11170
|
if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
|
|
10308
11171
|
throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
|
|
10309
11172
|
}
|
|
10310
|
-
|
|
11173
|
+
return rawTimeout;
|
|
11174
|
+
}
|
|
11175
|
+
/** Send a removal (`vector: null`) to the hook. No gate check; the caller owns the gate. */
|
|
11176
|
+
async callRemovalHook(entityId, factId, timeoutMs) {
|
|
11177
|
+
if (!this.options.vectorRanker?.onEmbeddingPersisted) {
|
|
11178
|
+
throw new Error("callRemovalHook requires vectorRanker.onEmbeddingPersisted");
|
|
11179
|
+
}
|
|
11180
|
+
let timeoutHandle;
|
|
11181
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
11182
|
+
timeoutHandle = setTimeout(() => {
|
|
11183
|
+
const timeoutError = new Error(`onEmbeddingPersisted timed out after ${timeoutMs}ms`);
|
|
11184
|
+
timeoutError[HOOK_TIMEOUT_MARKER] = true;
|
|
11185
|
+
reject(timeoutError);
|
|
11186
|
+
}, timeoutMs);
|
|
11187
|
+
});
|
|
11188
|
+
const hookPromise = Promise.resolve().then(
|
|
11189
|
+
() => this.options.vectorRanker.onEmbeddingPersisted({ entityId, factId, vector: null })
|
|
11190
|
+
);
|
|
11191
|
+
try {
|
|
11192
|
+
await Promise.race([hookPromise, timeoutPromise]);
|
|
11193
|
+
} catch (err) {
|
|
11194
|
+
hookPromise.catch(() => {
|
|
11195
|
+
});
|
|
11196
|
+
throw err;
|
|
11197
|
+
} finally {
|
|
11198
|
+
if (timeoutHandle) clearTimeout(timeoutHandle);
|
|
11199
|
+
}
|
|
11200
|
+
}
|
|
11201
|
+
/**
|
|
11202
|
+
* One removal call per id for a store with no ledger table (setup() never
|
|
11203
|
+
* ran), so nothing records what is owed (spec §5.5.5). Stops at the first
|
|
11204
|
+
* timeout: a dead index costs one timeout, as in a drain (spec rev 5).
|
|
11205
|
+
* `failed` lists the ids not confirmed, in order; after a timeout it ends
|
|
11206
|
+
* with the timed-out id and every id after it. Throws only for an invalid
|
|
11207
|
+
* `deletionHookTimeoutMs`.
|
|
11208
|
+
*/
|
|
11209
|
+
async callRemovalHookEach(entityId, ids, opts = {}) {
|
|
11210
|
+
const timeoutMs = this.validateDeletionTimeout();
|
|
11211
|
+
const failed = [];
|
|
11212
|
+
let firstRejection;
|
|
11213
|
+
for (let i = 0; i < ids.length; i++) {
|
|
11214
|
+
const factId = ids[i];
|
|
11215
|
+
try {
|
|
11216
|
+
await this.callRemovalHook(entityId, factId, timeoutMs);
|
|
11217
|
+
} catch (hookErr) {
|
|
11218
|
+
if (opts.warn) console.warn(`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for ${factId}:`, hookErr);
|
|
11219
|
+
if (hookErr?.[HOOK_TIMEOUT_MARKER] === true) {
|
|
11220
|
+
failed.push(...ids.slice(i));
|
|
11221
|
+
return { failed, timedOut: true, timedOutId: factId, cause: hookErr };
|
|
11222
|
+
}
|
|
11223
|
+
failed.push(factId);
|
|
11224
|
+
firstRejection ?? (firstRejection = hookErr);
|
|
11225
|
+
}
|
|
11226
|
+
}
|
|
11227
|
+
return { failed, timedOut: false, cause: firstRejection };
|
|
11228
|
+
}
|
|
11229
|
+
async notifyEmbeddingPersistedOrThrow(entityId, factId, vector) {
|
|
11230
|
+
if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
|
|
11231
|
+
if (this.options.forceDeleteIgnoreRankerHook === true) return;
|
|
11232
|
+
const vectorCopy = vector ? vector.slice() : null;
|
|
11233
|
+
const timeoutMs = this.validateDeletionTimeout();
|
|
10311
11234
|
let timeoutHandle;
|
|
10312
11235
|
const timeoutPromise = new Promise((_, reject) => {
|
|
10313
11236
|
timeoutHandle = setTimeout(() => {
|
|
@@ -11907,11 +12830,15 @@ var WikiMemory = class {
|
|
|
11907
12830
|
this.upsertIdStashSize = 0;
|
|
11908
12831
|
/** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */
|
|
11909
12832
|
this.upsertIdStashGen = 0;
|
|
12833
|
+
/** Superseded fact ids per entity awaiting a post-commit delivery from syncSearchIndex(). */
|
|
12834
|
+
this.removalStash = /* @__PURE__ */ new Map();
|
|
12835
|
+
this.removalStashSize = 0;
|
|
11910
12836
|
this.reinitSearch = null;
|
|
11911
12837
|
/** Monotonic time before which a no-arg syncSearchIndex() skips the re-init (0 = no cooldown). */
|
|
11912
12838
|
this.reinitRetryAt = 0;
|
|
11913
12839
|
/** Consecutive failed re-inits; drives the exponential backoff. */
|
|
11914
12840
|
this.reinitFailures = 0;
|
|
12841
|
+
this.setupRemovalDrain = null;
|
|
11915
12842
|
this.db = withSerializedTransactions(db);
|
|
11916
12843
|
this.options = options;
|
|
11917
12844
|
warnChangedDefaultsOnce(options.config);
|
|
@@ -11936,6 +12863,9 @@ var WikiMemory = class {
|
|
|
11936
12863
|
);
|
|
11937
12864
|
this.lintService = new LintService(this.lintRepo, this.ontologyService);
|
|
11938
12865
|
this.embeddingService = new EmbeddingService(this.db, this.options, this.entryRepo, this.metadataRepo);
|
|
12866
|
+
this.vectorRemovalRepo = new VectorRemovalRepository(this.db, this.prefix);
|
|
12867
|
+
this.vectorRemovalService = new VectorRemovalService(this.db, this.options, this.vectorRemovalRepo, this.embeddingService, this.metadataRepo);
|
|
12868
|
+
this.embeddingService.attachVectorRemoval(this.vectorRemovalService, this.vectorRemovalRepo);
|
|
11939
12869
|
this.searchService = new SearchService(
|
|
11940
12870
|
this.entryRepo,
|
|
11941
12871
|
new MiniSearchIndexStrategy()
|
|
@@ -11956,7 +12886,8 @@ var WikiMemory = class {
|
|
|
11956
12886
|
this.jobManager,
|
|
11957
12887
|
this.embeddingService,
|
|
11958
12888
|
this.promptService,
|
|
11959
|
-
this.ontologyService
|
|
12889
|
+
this.ontologyService,
|
|
12890
|
+
this.vectorRemovalService
|
|
11960
12891
|
);
|
|
11961
12892
|
this.maintenanceService = new MaintenanceService(
|
|
11962
12893
|
this.db,
|
|
@@ -11972,7 +12903,9 @@ var WikiMemory = class {
|
|
|
11972
12903
|
this.embeddingService,
|
|
11973
12904
|
this.promptService,
|
|
11974
12905
|
this.ontologyService,
|
|
11975
|
-
this.edgeRepo
|
|
12906
|
+
this.edgeRepo,
|
|
12907
|
+
this.vectorRemovalService,
|
|
12908
|
+
this.vectorRemovalRepo
|
|
11976
12909
|
);
|
|
11977
12910
|
this.maintenanceScheduler = new MaintenanceScheduler(
|
|
11978
12911
|
this.db,
|
|
@@ -11981,7 +12914,9 @@ var WikiMemory = class {
|
|
|
11981
12914
|
this.metadataRepo,
|
|
11982
12915
|
this.eventRepo,
|
|
11983
12916
|
this.entryRepo,
|
|
11984
|
-
this.jobManager
|
|
12917
|
+
this.jobManager,
|
|
12918
|
+
this.vectorRemovalService,
|
|
12919
|
+
this.vectorRemovalRepo
|
|
11985
12920
|
);
|
|
11986
12921
|
this.importExportService = new ImportExportService(
|
|
11987
12922
|
this.db,
|
|
@@ -11993,7 +12928,8 @@ var WikiMemory = class {
|
|
|
11993
12928
|
this.searchService,
|
|
11994
12929
|
this.jobManager,
|
|
11995
12930
|
this.embeddingService,
|
|
11996
|
-
this.options
|
|
12931
|
+
this.options,
|
|
12932
|
+
this.vectorRemovalService
|
|
11997
12933
|
);
|
|
11998
12934
|
this.retrievalService = new RetrievalService(
|
|
11999
12935
|
this.options,
|
|
@@ -12061,6 +12997,33 @@ var WikiMemory = class {
|
|
|
12061
12997
|
}
|
|
12062
12998
|
if (stash.size > 0) this.upsertIdStash.set(entityId, stash);
|
|
12063
12999
|
}
|
|
13000
|
+
/**
|
|
13001
|
+
* Overflow past the cap drops the id from the stash only: the trigger already
|
|
13002
|
+
* put it on the ledger, so it stays owed and runExternalDeletions or
|
|
13003
|
+
* runPendingMaintenance delivers it later.
|
|
13004
|
+
*/
|
|
13005
|
+
stashRemovalIds(entityId, ids) {
|
|
13006
|
+
const cap = this.constructor.REMOVAL_STASH_CAP;
|
|
13007
|
+
const stash = this.removalStash.get(entityId) ?? /* @__PURE__ */ new Set();
|
|
13008
|
+
for (const id of ids) {
|
|
13009
|
+
if (stash.has(id)) continue;
|
|
13010
|
+
if (this.removalStashSize >= cap) continue;
|
|
13011
|
+
stash.add(id);
|
|
13012
|
+
this.removalStashSize++;
|
|
13013
|
+
}
|
|
13014
|
+
if (stash.size > 0) this.removalStash.set(entityId, stash);
|
|
13015
|
+
}
|
|
13016
|
+
/** Removes and returns the stashed removal ids (one entity, or all). */
|
|
13017
|
+
takeRemovalIds(entityId) {
|
|
13018
|
+
const out = /* @__PURE__ */ new Map();
|
|
13019
|
+
for (const [e, set] of [...this.removalStash]) {
|
|
13020
|
+
if (entityId !== void 0 && e !== entityId) continue;
|
|
13021
|
+
out.set(e, [...set]);
|
|
13022
|
+
this.removalStashSize -= set.size;
|
|
13023
|
+
this.removalStash.delete(e);
|
|
13024
|
+
}
|
|
13025
|
+
return out;
|
|
13026
|
+
}
|
|
12064
13027
|
/** Snapshot of the stash (one entity, or all) with generations, without removing anything. */
|
|
12065
13028
|
peekStashedIds(entityId) {
|
|
12066
13029
|
const snapshot = /* @__PURE__ */ new Map();
|
|
@@ -12149,6 +13112,84 @@ var WikiMemory = class {
|
|
|
12149
13112
|
)
|
|
12150
13113
|
);
|
|
12151
13114
|
await this.searchService.sync(void 0, { deadline: openDeadline });
|
|
13115
|
+
await this.startSetupRemovalDrain();
|
|
13116
|
+
}
|
|
13117
|
+
/** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
|
|
13118
|
+
async startSetupRemovalDrain() {
|
|
13119
|
+
if (this.setupRemovalDrain) return;
|
|
13120
|
+
const gate = this.vectorRemovalService.gate();
|
|
13121
|
+
if (gate === "none") return;
|
|
13122
|
+
const prelude = (async () => {
|
|
13123
|
+
if (gate === "hook" && !await this.vectorRemovalService.externalIndexInUse()) {
|
|
13124
|
+
await this.db.withTransactionAsync((tx) => this.vectorRemovalService.markExternalIndexInUse(tx));
|
|
13125
|
+
}
|
|
13126
|
+
if ((await this.vectorRemovalRepo.pendingStats()).count === 0) {
|
|
13127
|
+
if (gate === "force") await this.vectorRemovalService.clearExternalIndexMarker();
|
|
13128
|
+
return { drain: null };
|
|
13129
|
+
}
|
|
13130
|
+
if (this.options.drainExternalDeletionsOnSetup !== true) {
|
|
13131
|
+
if (gate === "hook") await this.vectorRemovalService.emitPending(void 0, "auto");
|
|
13132
|
+
return { drain: null };
|
|
13133
|
+
}
|
|
13134
|
+
const drain = (async () => {
|
|
13135
|
+
try {
|
|
13136
|
+
const r = await this.vectorRemovalService.drain(
|
|
13137
|
+
{ all: true },
|
|
13138
|
+
{ backoff: true, deadlineAt: Date.now() + 1e4, trigger: "auto" }
|
|
13139
|
+
);
|
|
13140
|
+
if (r.pending > 0) await this.vectorRemovalService.emitPending(void 0, "auto");
|
|
13141
|
+
} catch {
|
|
13142
|
+
emitDiagnostic(this.options, {
|
|
13143
|
+
code: "background_job_failed",
|
|
13144
|
+
operation: "externalDeletion",
|
|
13145
|
+
trigger: "auto",
|
|
13146
|
+
entityId: "",
|
|
13147
|
+
// store-wide drain
|
|
13148
|
+
detail: { reason: "unhandled_rejection" }
|
|
13149
|
+
});
|
|
13150
|
+
}
|
|
13151
|
+
})();
|
|
13152
|
+
return { drain };
|
|
13153
|
+
})();
|
|
13154
|
+
const joined = prelude.then((r) => r.drain ?? void 0, () => void 0);
|
|
13155
|
+
this.setupRemovalDrain = joined;
|
|
13156
|
+
void joined.then(() => {
|
|
13157
|
+
if (this.setupRemovalDrain === joined) this.setupRemovalDrain = null;
|
|
13158
|
+
});
|
|
13159
|
+
await prelude;
|
|
13160
|
+
}
|
|
13161
|
+
/**
|
|
13162
|
+
* Delivers owed vector-index removals now (spec §5.9). No backoff. With an
|
|
13163
|
+
* entity id only that entity's rows; otherwise all. `deadlineMs` is a duration.
|
|
13164
|
+
* `transient: true` means a ledger read or write could not run (for example,
|
|
13165
|
+
* you held a transaction open on the connection); the rows stay pending.
|
|
13166
|
+
*/
|
|
13167
|
+
async runExternalDeletions(entityId, opts) {
|
|
13168
|
+
if (entityId !== void 0) assertEntityId2(entityId);
|
|
13169
|
+
const ms = opts?.deadlineMs;
|
|
13170
|
+
if (ms !== void 0 && (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)) {
|
|
13171
|
+
throw new TypeError("deadlineMs must be a finite number >= 0");
|
|
13172
|
+
}
|
|
13173
|
+
if (!await this.vectorRemovalService.ledgerPresent()) {
|
|
13174
|
+
return { confirmed: 0, pending: 0, failedIds: [], timedOut: false };
|
|
13175
|
+
}
|
|
13176
|
+
const r = await this.vectorRemovalService.drain(
|
|
13177
|
+
entityId === void 0 ? { all: true } : { entityId },
|
|
13178
|
+
{ trigger: "call", ...ms !== void 0 ? { deadlineAt: Date.now() + ms } : {} }
|
|
13179
|
+
);
|
|
13180
|
+
return {
|
|
13181
|
+
confirmed: r.confirmed,
|
|
13182
|
+
pending: r.pending,
|
|
13183
|
+
failedIds: r.failedIds,
|
|
13184
|
+
timedOut: r.timedOut,
|
|
13185
|
+
...r.transient ? { transient: true } : {}
|
|
13186
|
+
};
|
|
13187
|
+
}
|
|
13188
|
+
/** Removals still owed to the host's vector index (all entities, or one). */
|
|
13189
|
+
async getPendingExternalDeletions(entityId) {
|
|
13190
|
+
if (entityId !== void 0) assertEntityId2(entityId);
|
|
13191
|
+
if (!await this.vectorRemovalService.ledgerPresent()) return { count: 0, oldestEnqueuedAt: null, maxAttempts: 0 };
|
|
13192
|
+
return this.vectorRemovalRepo.pendingStats(entityId);
|
|
12152
13193
|
}
|
|
12153
13194
|
async hasChanged(entityId, sourceRefOrEntries, sourceHashArg) {
|
|
12154
13195
|
if (typeof sourceRefOrEntries === "string") {
|
|
@@ -12316,8 +13357,9 @@ var WikiMemory = class {
|
|
|
12316
13357
|
async write(entityId, event) {
|
|
12317
13358
|
return this.writeService.write(entityId, event);
|
|
12318
13359
|
}
|
|
12319
|
-
/** Await auto-mode background librarian/heal jobs started by write()
|
|
13360
|
+
/** Await auto-mode background librarian/heal jobs started by write(), and the removal drain `setup()` started under `drainExternalDeletionsOnSetup`. */
|
|
12320
13361
|
async drain() {
|
|
13362
|
+
await this.setupRemovalDrain;
|
|
12321
13363
|
return this.writeService.drain();
|
|
12322
13364
|
}
|
|
12323
13365
|
/**
|
|
@@ -12329,9 +13371,32 @@ var WikiMemory = class {
|
|
|
12329
13371
|
async getPendingMaintenance(entityIds) {
|
|
12330
13372
|
return this.maintenanceScheduler.getPending(entityIds);
|
|
12331
13373
|
}
|
|
12332
|
-
/** Run pending librarian
|
|
13374
|
+
/** Run pending removals, librarian, heal and reembed work under an optional token budget and deadline (spec §6.2). Awaits the setup removal drain first, when `drainExternalDeletionsOnSetup` started one. */
|
|
12333
13375
|
async runPendingMaintenance(options) {
|
|
12334
|
-
|
|
13376
|
+
let opts = options;
|
|
13377
|
+
const ms = options?.deadlineMs;
|
|
13378
|
+
if (ms !== void 0 && (typeof ms !== "number" || !Number.isFinite(ms) || ms < 0)) {
|
|
13379
|
+
throw new TypeError("deadlineMs must be a finite number >= 0");
|
|
13380
|
+
}
|
|
13381
|
+
const setupDrain = this.setupRemovalDrain;
|
|
13382
|
+
if (setupDrain) {
|
|
13383
|
+
if (ms !== void 0) {
|
|
13384
|
+
const started = Date.now();
|
|
13385
|
+
let handle;
|
|
13386
|
+
await Promise.race([
|
|
13387
|
+
setupDrain,
|
|
13388
|
+
new Promise((resolve) => {
|
|
13389
|
+
handle = setTimeout(resolve, ms);
|
|
13390
|
+
})
|
|
13391
|
+
]).finally(() => {
|
|
13392
|
+
if (handle) clearTimeout(handle);
|
|
13393
|
+
});
|
|
13394
|
+
opts = { ...options, deadlineMs: Math.max(0, ms - (Date.now() - started)) };
|
|
13395
|
+
} else {
|
|
13396
|
+
await setupDrain;
|
|
13397
|
+
}
|
|
13398
|
+
}
|
|
13399
|
+
return this.maintenanceScheduler.run(opts);
|
|
12335
13400
|
}
|
|
12336
13401
|
/**
|
|
12337
13402
|
* @param options.promptOverride - Applies only to this manual call. Does NOT affect
|
|
@@ -12412,6 +13477,11 @@ var WikiMemory = class {
|
|
|
12412
13477
|
* waits at least 5 s, doubling per consecutive failure up to 5 min (longer
|
|
12413
13478
|
* when an attempt is itself slow), before retrying again.
|
|
12414
13479
|
*
|
|
13480
|
+
* It also calls the host's removal hook (`onEmbeddingPersisted(…, null)`) for
|
|
13481
|
+
* the stashed ids that `upsertGraph` superseded, and can take up to
|
|
13482
|
+
* `deletionHookTimeoutMs` per id when the host's index is slow. It never
|
|
13483
|
+
* drains an entity's wider removal backlog.
|
|
13484
|
+
*
|
|
12415
13485
|
* Call only after the host's transaction commits: called inside it, the
|
|
12416
13486
|
* rebuild may index rows that later roll back, or miss them and clear the
|
|
12417
13487
|
* stale flag anyway. Serialized with core's internal index syncs and takes
|
|
@@ -12427,6 +13497,19 @@ var WikiMemory = class {
|
|
|
12427
13497
|
* @throws {TypeError} when `entityId` is given but is not a non-empty string.
|
|
12428
13498
|
*/
|
|
12429
13499
|
async syncSearchIndex(entityId) {
|
|
13500
|
+
if (entityId !== void 0) assertEntityId2(entityId);
|
|
13501
|
+
const removals = this.takeRemovalIds(entityId);
|
|
13502
|
+
try {
|
|
13503
|
+
await this.syncSearchIndexCore(entityId);
|
|
13504
|
+
} catch (err) {
|
|
13505
|
+
for (const [e, ids] of removals) this.stashRemovalIds(e, ids);
|
|
13506
|
+
throw err;
|
|
13507
|
+
}
|
|
13508
|
+
for (const [e, ids] of removals) {
|
|
13509
|
+
await this.vectorRemovalService.deliverRemovals(e, ids, "upsertGraph", "call");
|
|
13510
|
+
}
|
|
13511
|
+
}
|
|
13512
|
+
async syncSearchIndexCore(entityId) {
|
|
12430
13513
|
if (entityId === void 0) {
|
|
12431
13514
|
if (!this.searchService.isKeywordAvailable() && monotonicNow() >= this.reinitRetryAt) {
|
|
12432
13515
|
this.reinitSearch ?? (this.reinitSearch = (async () => {
|
|
@@ -12494,6 +13577,14 @@ var WikiMemory = class {
|
|
|
12494
13577
|
* hard-deletes the soft-deleted rows once they are older than
|
|
12495
13578
|
* `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).
|
|
12496
13579
|
* `dryRun` previews the counts.
|
|
13580
|
+
*
|
|
13581
|
+
* With a removal hook (`vectorRanker.onEmbeddingPersisted`), the deleted
|
|
13582
|
+
* facts are recorded as owed in the same transaction and then delivered to
|
|
13583
|
+
* the hook before this resolves.
|
|
13584
|
+
*
|
|
13585
|
+
* @throws {WikiExternalDeletionError} when the hook didn't confirm every
|
|
13586
|
+
* removal. The local delete stays committed and the rest stay owed; retry,
|
|
13587
|
+
* or call `runExternalDeletions()`.
|
|
12497
13588
|
*/
|
|
12498
13589
|
async forget(entityId, params, opts) {
|
|
12499
13590
|
return this.maintenanceService.forget(entityId, params, opts);
|
|
@@ -12546,12 +13637,15 @@ var WikiMemory = class {
|
|
|
12546
13637
|
* semantics identical to `ingestDocument`, minus the LLM extraction step.
|
|
12547
13638
|
*
|
|
12548
13639
|
* MUST be called from inside an open `db.withTransactionAsync` callback —
|
|
12549
|
-
* the third argument is the caller's `tx
|
|
13640
|
+
* the third argument is the caller's `tx`, and that transaction must be
|
|
13641
|
+
* opened through the adapter given to `createWiki` (the removal ledger is
|
|
13642
|
+
* filled by triggers inside it, and a rollback discards the rows). The method does not open a
|
|
12550
13643
|
* nested transaction, does not acquire any lock, and does not perform
|
|
12551
13644
|
* post-commit work (search sync, embedding, cache eviction). After the
|
|
12552
13645
|
* transaction commits, call `syncSearchIndex(entityId)` — or
|
|
12553
13646
|
* `syncSearchIndex()` after writing several entities in one transaction —
|
|
12554
|
-
* to make the new nodes keyword-searchable
|
|
13647
|
+
* to make the new nodes keyword-searchable and to deliver, through the
|
|
13648
|
+
* host's removal hook, the vectors of any facts the call superseded: both forms drain this call's node ids
|
|
12555
13649
|
* first, to completion, so the nodes are searchable under any backlog (up to
|
|
12556
13650
|
* `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with
|
|
12557
13651
|
* the backlog). Embeddings still come from the maintenance
|
|
@@ -12611,6 +13705,7 @@ var WikiMemory = class {
|
|
|
12611
13705
|
{ diag: { buffer: diagBuffer, operation: "upsertGraph" } }
|
|
12612
13706
|
);
|
|
12613
13707
|
this.stashUpsertIds(entityId, [...supersededFactIds, ...params.nodes.map((n) => n.id)]);
|
|
13708
|
+
this.stashRemovalIds(entityId, supersededFactIds);
|
|
12614
13709
|
this.searchService.markStale(entityId);
|
|
12615
13710
|
diagBuffer.flush(this.options);
|
|
12616
13711
|
return result;
|
|
@@ -12793,8 +13888,10 @@ var WikiMemory = class {
|
|
|
12793
13888
|
}
|
|
12794
13889
|
};
|
|
12795
13890
|
_testAccessNonTestEnvWarned = new WeakMap();
|
|
12796
|
-
/** Max upsertGraph node ids held for their post-commit sync (spec #280 id threading). */
|
|
13891
|
+
/** Max upsertGraph node and superseded-fact ids held for their post-commit sync (spec #280 id threading). */
|
|
12797
13892
|
WikiMemory.UPSERT_ID_STASH_CAP = 1e4;
|
|
13893
|
+
/** Max superseded-fact ids held for post-commit removal delivery. */
|
|
13894
|
+
WikiMemory.REMOVAL_STASH_CAP = 1e4;
|
|
12798
13895
|
function assertEntityId2(entityId) {
|
|
12799
13896
|
if (typeof entityId !== "string" || entityId.length === 0) {
|
|
12800
13897
|
throw new TypeError("Invalid entityId: must be a non-empty string.");
|
|
@@ -13781,6 +14878,7 @@ exports.PrunePartialFailureError = PrunePartialFailureError;
|
|
|
13781
14878
|
exports.WikiBusyError = WikiBusyError;
|
|
13782
14879
|
exports.WikiDraftNotFound = WikiDraftNotFound;
|
|
13783
14880
|
exports.WikiDuplicateHashError = WikiDuplicateHashError;
|
|
14881
|
+
exports.WikiExternalDeletionError = WikiExternalDeletionError;
|
|
13784
14882
|
exports.WikiGraphNodeOwnershipConflict = WikiGraphNodeOwnershipConflict;
|
|
13785
14883
|
exports.WikiIngestEmptyError = WikiIngestEmptyError;
|
|
13786
14884
|
exports.WikiInvalidReadOptions = WikiInvalidReadOptions;
|