@equationalapplications/core-llm-wiki 8.2.0 → 8.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{chunk-FOX6TNFO.mjs → chunk-EKYWAR2E.mjs} +1210 -136
- package/dist/chunk-EKYWAR2E.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1514 -319
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +331 -211
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-D6So3dKX.d.mts → testing-Og5x9rFu.d.mts} +385 -56
- package/dist/{testing-D6So3dKX.d.ts → testing-Og5x9rFu.d.ts} +385 -56
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +641 -120
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-FOX6TNFO.mjs.map +0 -1
package/dist/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
|
|
@@ -3137,6 +3366,19 @@ var SourceRefIndexRepository = class extends BaseRepository {
|
|
|
3137
3366
|
[generateId("sri_"), entityId, sourceHash, sourceRef, Date.now()]
|
|
3138
3367
|
);
|
|
3139
3368
|
}
|
|
3369
|
+
/**
|
|
3370
|
+
* Hard-delete every row of the entity, live or soft-deleted (forget clearAll,
|
|
3371
|
+
* spec import-followups §6 rev 4). Nothing reads a soft-deleted row and
|
|
3372
|
+
* runPrune never sweeps this table, so a wipe leaves no tombstones.
|
|
3373
|
+
*/
|
|
3374
|
+
async deleteByEntityId(entityId, tx) {
|
|
3375
|
+
const executor = this.getExecutor(tx);
|
|
3376
|
+
const result = await executor.runAsync(
|
|
3377
|
+
`DELETE FROM ${this.prefix}source_ref_index WHERE entity_id = ?`,
|
|
3378
|
+
[entityId]
|
|
3379
|
+
);
|
|
3380
|
+
return result.changes;
|
|
3381
|
+
}
|
|
3140
3382
|
/**
|
|
3141
3383
|
* Idempotent soft-delete of the live row for (entity_id, source_ref).
|
|
3142
3384
|
* Called at the start of every ingestDocument to remove the prior run's
|
|
@@ -3579,6 +3821,10 @@ var EventRepository = class extends BaseRepository {
|
|
|
3579
3821
|
);
|
|
3580
3822
|
return rows.map(mapEvent);
|
|
3581
3823
|
}
|
|
3824
|
+
/** Hard-delete every event of the entity, read or not (requested wipe, spec import-followups §6). */
|
|
3825
|
+
async deleteByEntityId(entityId, tx) {
|
|
3826
|
+
return tx.runAsync(`DELETE FROM ${this.prefix}events WHERE entity_id = ?`, [entityId]);
|
|
3827
|
+
}
|
|
3582
3828
|
/**
|
|
3583
3829
|
* Delete events for an entity that were created at or before the given cutoff timestamp.
|
|
3584
3830
|
* Returns the number of deleted rows.
|
|
@@ -5964,139 +6210,6 @@ function groundingOutcome(verdict, now) {
|
|
|
5964
6210
|
};
|
|
5965
6211
|
}
|
|
5966
6212
|
|
|
5967
|
-
// src/utils/diagnostics.ts
|
|
5968
|
-
var SEVERITY = {
|
|
5969
|
-
ingest_chunk_failed: "warn",
|
|
5970
|
-
fact_rejected: "warn",
|
|
5971
|
-
task_rejected: "warn",
|
|
5972
|
-
fact_deduplicated: "info",
|
|
5973
|
-
edge_dropped: "warn",
|
|
5974
|
-
embedding_failed: "warn",
|
|
5975
|
-
hook_failed: "warn",
|
|
5976
|
-
background_job_failed: "error",
|
|
5977
|
-
heal_skipped: "warn",
|
|
5978
|
-
grounding_missing: "warn",
|
|
5979
|
-
grounding_failed: "warn",
|
|
5980
|
-
classification_low_confidence: "info",
|
|
5981
|
-
classification_invalid: "warn",
|
|
5982
|
-
llm_usage: "info",
|
|
5983
|
-
librarian_gate: "info",
|
|
5984
|
-
librarian_op_rejected: "warn",
|
|
5985
|
-
contradicts_document: "warn",
|
|
5986
|
-
resolve_failed: "warn",
|
|
5987
|
-
read_budget: "info",
|
|
5988
|
-
event_retention_held: "info",
|
|
5989
|
-
event_created_at_clamped: "warn",
|
|
5990
|
-
event_created_at_restamped: "info"
|
|
5991
|
-
};
|
|
5992
|
-
var MESSAGE = {
|
|
5993
|
-
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
5994
|
-
fact_rejected: "An extracted fact failed validation and was not written.",
|
|
5995
|
-
task_rejected: "An extracted task failed validation and was not written.",
|
|
5996
|
-
fact_deduplicated: "An extracted fact duplicated an existing fact and was not written.",
|
|
5997
|
-
edge_dropped: "An extracted edge could not be resolved against the ontology and was not written.",
|
|
5998
|
-
embedding_failed: "A fact could not be embedded.",
|
|
5999
|
-
hook_failed: "A host hook threw or rejected.",
|
|
6000
|
-
background_job_failed: "A background maintenance job failed.",
|
|
6001
|
-
heal_skipped: "Heal skipped a candidate fact, or the whole LLM pass when keyword search is unavailable.",
|
|
6002
|
-
grounding_missing: "A fact carried no qualifying evidence and was stored as a draft.",
|
|
6003
|
-
grounding_failed: "A fact carried evidence not found in its source and was stored as a draft.",
|
|
6004
|
-
classification_low_confidence: "A classifier answer was below the confidence threshold and was not applied.",
|
|
6005
|
-
classification_invalid: "A classifier answer was invalid and was not applied.",
|
|
6006
|
-
llm_usage: "An LLM call completed; token usage attached.",
|
|
6007
|
-
librarian_gate: "Librarian gate outcome counts for one pass.",
|
|
6008
|
-
librarian_op_rejected: "A librarian reconciliation op was invalid and the candidate was added instead.",
|
|
6009
|
-
contradicts_document: "A candidate contradicted a document fact and was stored as a draft.",
|
|
6010
|
-
resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
|
|
6011
|
-
read_budget: "A read was packed to a token budget.",
|
|
6012
|
-
event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
|
|
6013
|
-
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.",
|
|
6014
|
-
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."
|
|
6015
|
-
};
|
|
6016
|
-
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
6017
|
-
function copyDetail(detail) {
|
|
6018
|
-
const copy = { ...detail };
|
|
6019
|
-
if (detail.chunkIndexes) copy.chunkIndexes = detail.chunkIndexes.slice();
|
|
6020
|
-
return copy;
|
|
6021
|
-
}
|
|
6022
|
-
function emitDiagnostic(options, input) {
|
|
6023
|
-
const hook = options.onDiagnostic;
|
|
6024
|
-
if (hook === void 0 || hook === null) return;
|
|
6025
|
-
if (typeof hook !== "function") {
|
|
6026
|
-
if (!warnedNonFunction.has(options)) {
|
|
6027
|
-
warnedNonFunction.add(options);
|
|
6028
|
-
console.warn("[WikiMemory] onDiagnostic is not a function; diagnostics are disabled.");
|
|
6029
|
-
}
|
|
6030
|
-
return;
|
|
6031
|
-
}
|
|
6032
|
-
const diagnostic = {
|
|
6033
|
-
code: input.code,
|
|
6034
|
-
severity: SEVERITY[input.code],
|
|
6035
|
-
operation: input.operation,
|
|
6036
|
-
trigger: input.trigger,
|
|
6037
|
-
entityId: input.entityId,
|
|
6038
|
-
at: Date.now(),
|
|
6039
|
-
message: MESSAGE[input.code],
|
|
6040
|
-
...input.detail ? { detail: copyDetail(input.detail) } : {}
|
|
6041
|
-
};
|
|
6042
|
-
try {
|
|
6043
|
-
const returned = hook(diagnostic);
|
|
6044
|
-
if (returned !== void 0) {
|
|
6045
|
-
Promise.resolve(returned).catch((err) => {
|
|
6046
|
-
console.warn("[WikiMemory] onDiagnostic hook rejected:", err);
|
|
6047
|
-
});
|
|
6048
|
-
}
|
|
6049
|
-
} catch (err) {
|
|
6050
|
-
console.warn("[WikiMemory] onDiagnostic hook threw:", err);
|
|
6051
|
-
}
|
|
6052
|
-
}
|
|
6053
|
-
var DiagnosticBuffer = class {
|
|
6054
|
-
constructor() {
|
|
6055
|
-
this.items = [];
|
|
6056
|
-
}
|
|
6057
|
-
push(input) {
|
|
6058
|
-
this.items.push(input);
|
|
6059
|
-
}
|
|
6060
|
-
get size() {
|
|
6061
|
-
return this.items.length;
|
|
6062
|
-
}
|
|
6063
|
-
flush(options) {
|
|
6064
|
-
const pending = this.items;
|
|
6065
|
-
this.items = [];
|
|
6066
|
-
for (const input of pending) emitDiagnostic(options, input);
|
|
6067
|
-
}
|
|
6068
|
-
/**
|
|
6069
|
-
* Emit only the buffered diagnostics whose code is in `codes` and discard
|
|
6070
|
-
* the rest. The buffer is empty afterwards either way.
|
|
6071
|
-
*
|
|
6072
|
-
* For an operation that did real work before its write was rolled back:
|
|
6073
|
-
* some buffered diagnostics describe that work and are still true, while
|
|
6074
|
-
* others describe rows that no longer exist (anything carrying a `factId`
|
|
6075
|
-
* minted inside the aborted transaction). `flush` would emit both and
|
|
6076
|
-
* `discard` would drop both; this emits the first set only.
|
|
6077
|
-
*/
|
|
6078
|
-
flushOnly(options, codes) {
|
|
6079
|
-
const pending = this.items;
|
|
6080
|
-
this.items = [];
|
|
6081
|
-
for (const input of pending) {
|
|
6082
|
-
if (codes.includes(input.code)) emitDiagnostic(options, input);
|
|
6083
|
-
}
|
|
6084
|
-
}
|
|
6085
|
-
discard() {
|
|
6086
|
-
this.items = [];
|
|
6087
|
-
}
|
|
6088
|
-
};
|
|
6089
|
-
function edgeDropDiagnostic(drop, ctx) {
|
|
6090
|
-
const detail = { reason: drop.reason };
|
|
6091
|
-
const factId = ctx.factId ?? drop.sourceId;
|
|
6092
|
-
if (factId) detail.factId = factId;
|
|
6093
|
-
if (drop.edgeType) detail.edgeType = drop.edgeType;
|
|
6094
|
-
if (drop.sourceNodeType) detail.sourceNodeType = drop.sourceNodeType;
|
|
6095
|
-
if (drop.targetNodeType) detail.targetNodeType = drop.targetNodeType;
|
|
6096
|
-
if (ctx.sourceRef) detail.sourceRef = ctx.sourceRef;
|
|
6097
|
-
return { code: "edge_dropped", operation: ctx.operation, trigger: ctx.trigger, entityId: ctx.entityId, detail };
|
|
6098
|
-
}
|
|
6099
|
-
|
|
6100
6213
|
// src/prompts.ts
|
|
6101
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.
|
|
6102
6215
|
Return ONLY a valid JSON object matching this schema:
|
|
@@ -6524,7 +6637,7 @@ function zeroChunkResult(duplicateOf) {
|
|
|
6524
6637
|
return result;
|
|
6525
6638
|
}
|
|
6526
6639
|
var IngestionService = class {
|
|
6527
|
-
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) {
|
|
6528
6641
|
this.db = db;
|
|
6529
6642
|
this.prefix = prefix;
|
|
6530
6643
|
this.options = options;
|
|
@@ -6536,6 +6649,7 @@ var IngestionService = class {
|
|
|
6536
6649
|
this.jobManager = jobManager;
|
|
6537
6650
|
this.embeddingService = embeddingService;
|
|
6538
6651
|
this.ontologyService = ontologyService;
|
|
6652
|
+
this.vectorRemoval = vectorRemoval;
|
|
6539
6653
|
this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
|
|
6540
6654
|
}
|
|
6541
6655
|
async ingestDocument(entityId, params, opts) {
|
|
@@ -6566,12 +6680,12 @@ var IngestionService = class {
|
|
|
6566
6680
|
return zeroChunkResult(canonical);
|
|
6567
6681
|
}
|
|
6568
6682
|
}
|
|
6569
|
-
const { chunks, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
6570
|
-
if (
|
|
6683
|
+
const { chunks: chunks2, truncated } = chunkText(params.documentChunk, maxChunkLength, chunkOverlap);
|
|
6684
|
+
if (chunks2.length === 0) return zeroChunkResult();
|
|
6571
6685
|
const ontologyContext = await this.ontologyService?.buildPromptContext(entityId) ?? null;
|
|
6572
6686
|
const ingestGrounding = this.promptService.groundingFor("ingest");
|
|
6573
6687
|
const chunkResults = await withConcurrency(
|
|
6574
|
-
|
|
6688
|
+
chunks2.map((chunk, chunkIndex) => async () => {
|
|
6575
6689
|
const { systemPrompt, userPrompt } = this.promptService.buildIngestPrompt(
|
|
6576
6690
|
chunk,
|
|
6577
6691
|
params.promptOverride,
|
|
@@ -6629,7 +6743,7 @@ var IngestionService = class {
|
|
|
6629
6743
|
position: null,
|
|
6630
6744
|
message: safeErrorToString(e)
|
|
6631
6745
|
};
|
|
6632
|
-
const total =
|
|
6746
|
+
const total = chunks2.length;
|
|
6633
6747
|
const tags = [];
|
|
6634
6748
|
if (failure.tier) tags.push(`tier=${failure.tier}`);
|
|
6635
6749
|
if (failure.position !== null) tags.push(`position=${failure.position}`);
|
|
@@ -6706,11 +6820,11 @@ var IngestionService = class {
|
|
|
6706
6820
|
}
|
|
6707
6821
|
});
|
|
6708
6822
|
}
|
|
6709
|
-
if (failedChunks ===
|
|
6823
|
+
if (failedChunks === chunks2.length) {
|
|
6710
6824
|
throw new WikiIngestEmptyError({
|
|
6711
6825
|
parseFailures: failures,
|
|
6712
6826
|
sourceRef,
|
|
6713
|
-
chunks:
|
|
6827
|
+
chunks: chunks2.length
|
|
6714
6828
|
});
|
|
6715
6829
|
}
|
|
6716
6830
|
const insertedFacts = [];
|
|
@@ -6748,18 +6862,22 @@ var IngestionService = class {
|
|
|
6748
6862
|
);
|
|
6749
6863
|
if (failedChunks === 0) {
|
|
6750
6864
|
const uniqueDeletedSourceFactIds = Array.from(new Set(deletedSourceFactIds));
|
|
6751
|
-
|
|
6752
|
-
|
|
6753
|
-
|
|
6754
|
-
|
|
6755
|
-
|
|
6756
|
-
|
|
6757
|
-
|
|
6758
|
-
|
|
6759
|
-
|
|
6760
|
-
|
|
6761
|
-
|
|
6762
|
-
|
|
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
|
+
}
|
|
6763
6881
|
}
|
|
6764
6882
|
}
|
|
6765
6883
|
}
|
|
@@ -6769,7 +6887,7 @@ var IngestionService = class {
|
|
|
6769
6887
|
this.searchService.evictCache(entityId);
|
|
6770
6888
|
const result = {
|
|
6771
6889
|
truncated,
|
|
6772
|
-
chunks:
|
|
6890
|
+
chunks: chunks2.length,
|
|
6773
6891
|
ingestedChunks,
|
|
6774
6892
|
failedChunks
|
|
6775
6893
|
};
|
|
@@ -7180,55 +7298,592 @@ function validateClassifierAnswer(response, key, question) {
|
|
|
7180
7298
|
if (typeof a.score !== "number" || !Number.isFinite(a.score) || a.score < 0 || a.score > maxScore) {
|
|
7181
7299
|
return { ok: false, reason: "score_out_of_range" };
|
|
7182
7300
|
}
|
|
7183
|
-
if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
|
|
7184
|
-
if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
|
|
7185
|
-
return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
|
|
7186
|
-
} catch {
|
|
7187
|
-
return { ok: false, reason: "malformed" };
|
|
7188
|
-
}
|
|
7189
|
-
}
|
|
7190
|
-
function classifierStateForFact(fact) {
|
|
7191
|
-
const parts = [fact.title, fact.body];
|
|
7192
|
-
if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
|
|
7193
|
-
return parts.join("\n\n");
|
|
7194
|
-
}
|
|
7195
|
-
|
|
7196
|
-
// src/utils/engineDefaults.ts
|
|
7197
|
-
var DEFAULT_LIBRARIAN_STRATEGY = "ops";
|
|
7198
|
-
var DEFAULT_MAINTENANCE_MODE = "deferred";
|
|
7199
|
-
function resolveLibrarianStrategy(config) {
|
|
7200
|
-
return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
|
|
7201
|
-
}
|
|
7202
|
-
function resolveMaintenanceMode(config) {
|
|
7203
|
-
return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
|
|
7204
|
-
}
|
|
7205
|
-
function changedDefaultWarnings(config) {
|
|
7206
|
-
const warnings = [];
|
|
7207
|
-
const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
|
|
7208
|
-
if (hasThreshold && config?.maintenance === void 0) {
|
|
7209
|
-
warnings.push(
|
|
7210
|
-
"[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
|
|
7211
|
-
);
|
|
7301
|
+
if (!isUnit(a.confidence)) return { ok: false, reason: "invalid_probability" };
|
|
7302
|
+
if (!Array.isArray(a.probabilities) || !a.probabilities.every(isUnit)) return { ok: false, reason: "invalid_probability" };
|
|
7303
|
+
return { ok: true, answer: { kind: "score", score: a.score, confidence: a.confidence, probabilities: a.probabilities.slice() } };
|
|
7304
|
+
} catch {
|
|
7305
|
+
return { ok: false, reason: "malformed" };
|
|
7306
|
+
}
|
|
7307
|
+
}
|
|
7308
|
+
function classifierStateForFact(fact) {
|
|
7309
|
+
const parts = [fact.title, fact.body];
|
|
7310
|
+
if (Array.isArray(fact.tags) && fact.tags.length > 0) parts.push(`Tags: ${fact.tags.join(", ")}`);
|
|
7311
|
+
return parts.join("\n\n");
|
|
7312
|
+
}
|
|
7313
|
+
|
|
7314
|
+
// src/utils/engineDefaults.ts
|
|
7315
|
+
var DEFAULT_LIBRARIAN_STRATEGY = "ops";
|
|
7316
|
+
var DEFAULT_MAINTENANCE_MODE = "deferred";
|
|
7317
|
+
function resolveLibrarianStrategy(config) {
|
|
7318
|
+
return config?.librarian?.strategy ?? DEFAULT_LIBRARIAN_STRATEGY;
|
|
7319
|
+
}
|
|
7320
|
+
function resolveMaintenanceMode(config) {
|
|
7321
|
+
return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
|
|
7322
|
+
}
|
|
7323
|
+
function changedDefaultWarnings(config) {
|
|
7324
|
+
const warnings = [];
|
|
7325
|
+
const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
|
|
7326
|
+
if (hasThreshold && config?.maintenance === void 0) {
|
|
7327
|
+
warnings.push(
|
|
7328
|
+
"[core-llm-wiki] auto-run thresholds are set, but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal. Set `maintenance: 'auto'` or call runPendingMaintenance()."
|
|
7329
|
+
);
|
|
7330
|
+
}
|
|
7331
|
+
if (config?.prompts?.librarianSystemPrompt !== void 0 && config?.librarian?.strategy === void 0) {
|
|
7332
|
+
warnings.push(
|
|
7333
|
+
"[core-llm-wiki] `prompts.librarianSystemPrompt` is set, but `librarian.strategy` now defaults to 'ops', which does not use it. Set `librarian: { strategy: 'legacy' }` to keep the override."
|
|
7334
|
+
);
|
|
7335
|
+
}
|
|
7336
|
+
if (config?.librarian?.strategy === "legacy" && config?.maintenance === void 0 && !hasThreshold) {
|
|
7337
|
+
warnings.push(
|
|
7338
|
+
"[core-llm-wiki] `librarian.strategy` is pinned to 'legacy', but `maintenance` now defaults to 'deferred', so write() will not start the librarian or heal, and a deferred backlog run keeps only the newest 50 events. Set `maintenance: 'auto'` to keep 7.x auto-run behavior."
|
|
7339
|
+
);
|
|
7340
|
+
}
|
|
7341
|
+
return warnings;
|
|
7342
|
+
}
|
|
7343
|
+
var warnedDefaults = /* @__PURE__ */ new Set();
|
|
7344
|
+
function warnChangedDefaultsOnce(config) {
|
|
7345
|
+
for (const message of changedDefaultWarnings(config)) {
|
|
7346
|
+
if (warnedDefaults.has(message)) continue;
|
|
7347
|
+
warnedDefaults.add(message);
|
|
7348
|
+
console.warn(message);
|
|
7349
|
+
}
|
|
7350
|
+
}
|
|
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;
|
|
7212
7810
|
}
|
|
7213
|
-
|
|
7214
|
-
|
|
7215
|
-
|
|
7216
|
-
|
|
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
|
+
}
|
|
7217
7849
|
}
|
|
7218
|
-
|
|
7219
|
-
|
|
7220
|
-
|
|
7221
|
-
|
|
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;
|
|
7222
7855
|
}
|
|
7223
|
-
|
|
7224
|
-
|
|
7225
|
-
|
|
7226
|
-
|
|
7227
|
-
|
|
7228
|
-
|
|
7229
|
-
|
|
7230
|
-
|
|
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
|
+
}
|
|
7231
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
|
+
});
|
|
7232
7887
|
}
|
|
7233
7888
|
|
|
7234
7889
|
// src/services/legacyWatermark.ts
|
|
@@ -7613,7 +8268,9 @@ async function runExtract(deps, ctx, batch) {
|
|
|
7613
8268
|
const base = { entityId, operation: "librarian", trigger };
|
|
7614
8269
|
const diagnostics = [];
|
|
7615
8270
|
const byLabel = new Map(batch.map((l) => [l.label, l]));
|
|
7616
|
-
|
|
8271
|
+
let newestAt = batch[0].at;
|
|
8272
|
+
for (const l of batch) if (l.at > newestAt) newestAt = l.at;
|
|
8273
|
+
const defaultValidFrom = Math.min(newestAt, Date.now());
|
|
7617
8274
|
const candidates = [];
|
|
7618
8275
|
(Array.isArray(parsed.facts) ? parsed.facts : []).forEach((raw, index) => {
|
|
7619
8276
|
const fact = validateFact(raw);
|
|
@@ -7623,7 +8280,7 @@ async function runExtract(deps, ctx, batch) {
|
|
|
7623
8280
|
}
|
|
7624
8281
|
const r = raw;
|
|
7625
8282
|
const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
|
|
7626
|
-
const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at :
|
|
8283
|
+
const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
|
|
7627
8284
|
candidates.push({ index, fact, sourceLabel, validFrom });
|
|
7628
8285
|
});
|
|
7629
8286
|
const tasks = [];
|
|
@@ -8193,7 +8850,7 @@ var formatSkipError = (err) => {
|
|
|
8193
8850
|
return base;
|
|
8194
8851
|
};
|
|
8195
8852
|
var MaintenanceService = class {
|
|
8196
|
-
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService) {
|
|
8853
|
+
constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
|
|
8197
8854
|
this.db = db;
|
|
8198
8855
|
this.prefix = prefix;
|
|
8199
8856
|
this.options = options;
|
|
@@ -8206,7 +8863,10 @@ var MaintenanceService = class {
|
|
|
8206
8863
|
this.jobManager = jobManager;
|
|
8207
8864
|
this.embeddingService = embeddingService;
|
|
8208
8865
|
this.ontologyService = ontologyService;
|
|
8866
|
+
this.vectorRemoval = vectorRemoval;
|
|
8867
|
+
this.vectorRemovalRepo = vectorRemovalRepo;
|
|
8209
8868
|
this.promptService = promptService ?? new PromptService(this.options.config?.prompts, resolveGrounding(this.options.config?.grounding));
|
|
8869
|
+
this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
|
|
8210
8870
|
}
|
|
8211
8871
|
async runPrune(entityId, options) {
|
|
8212
8872
|
this.jobManager.acquireLock("prune", entityId);
|
|
@@ -8218,11 +8878,14 @@ var MaintenanceService = class {
|
|
|
8218
8878
|
this._validatePruneDuration(retainEventsFor, "retainEventsFor");
|
|
8219
8879
|
const pruneSupersededAfter = this.options.config?.pruneSupersededAfter ?? null;
|
|
8220
8880
|
this._validatePruneDuration(pruneSupersededAfter, "pruneSupersededAfter");
|
|
8881
|
+
const gate = removalGate(this.options);
|
|
8882
|
+
if (gate === "hook") this.embeddingService.validateDeletionTimeout();
|
|
8221
8883
|
const now = Date.now();
|
|
8222
8884
|
let syncedIds = [];
|
|
8223
8885
|
let deletedEntries = 0;
|
|
8224
8886
|
let deletedTasks = 0;
|
|
8225
8887
|
let deletedEvents = 0;
|
|
8888
|
+
let prunePartial = null;
|
|
8226
8889
|
if (pruneSupersededAfter !== null) {
|
|
8227
8890
|
const expiredCutoff = now - pruneSupersededAfter * 864e5;
|
|
8228
8891
|
const expiredIds = await this.entryRepo.findExpiredIds(entityId, expiredCutoff);
|
|
@@ -8231,55 +8894,89 @@ var MaintenanceService = class {
|
|
|
8231
8894
|
await this.entryRepo.softDeleteByIds(expiredIds, entityId, tx);
|
|
8232
8895
|
});
|
|
8233
8896
|
syncedIds = [...expiredIds];
|
|
8897
|
+
if (this.vectorRemoval && await this.vectorRemoval.ledgerPresent()) {
|
|
8898
|
+
await this.vectorRemoval.deliverRemovals(entityId, expiredIds, "prune", "call", []);
|
|
8899
|
+
}
|
|
8234
8900
|
}
|
|
8235
8901
|
}
|
|
8236
8902
|
if (retainSoftDeletedFor !== null) {
|
|
8237
8903
|
const cutoff = now - retainSoftDeletedFor * 864e5;
|
|
8238
8904
|
const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
|
|
8239
|
-
const
|
|
8240
|
-
|
|
8241
|
-
|
|
8242
|
-
|
|
8243
|
-
|
|
8244
|
-
|
|
8245
|
-
|
|
8246
|
-
|
|
8247
|
-
|
|
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
|
+
});
|
|
8248
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];
|
|
8249
8940
|
}
|
|
8250
|
-
const
|
|
8251
|
-
syncedIds = [...syncedIds, ...succeededIds];
|
|
8941
|
+
const hookLedger = ledgerOn && !!vrRepo && gate === "hook";
|
|
8252
8942
|
await this.db.withTransactionAsync(async (tx) => {
|
|
8253
|
-
if (
|
|
8254
|
-
|
|
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
|
+
}
|
|
8255
8964
|
}
|
|
8256
8965
|
deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
|
|
8257
8966
|
});
|
|
8258
|
-
if (
|
|
8259
|
-
|
|
8260
|
-
|
|
8261
|
-
|
|
8262
|
-
|
|
8263
|
-
|
|
8264
|
-
|
|
8265
|
-
|
|
8266
|
-
|
|
8267
|
-
|
|
8268
|
-
|
|
8269
|
-
|
|
8270
|
-
);
|
|
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) };
|
|
8271
8979
|
}
|
|
8272
|
-
const errMsg = failure.cause?.message ?? "";
|
|
8273
|
-
const isValidationError = errMsg.startsWith("Invalid deletionHookTimeoutMs");
|
|
8274
|
-
const sanitizedCause = isValidationError ? failure.cause : this._sanitizeRankerError(failure.cause);
|
|
8275
|
-
throw new PrunePartialFailureError(
|
|
8276
|
-
succeeded.length,
|
|
8277
|
-
failure.factId,
|
|
8278
|
-
remaining,
|
|
8279
|
-
sanitizedCause,
|
|
8280
|
-
deletedTasks,
|
|
8281
|
-
0
|
|
8282
|
-
);
|
|
8283
8980
|
}
|
|
8284
8981
|
}
|
|
8285
8982
|
if (retainEventsFor !== null) {
|
|
@@ -8316,6 +9013,16 @@ var MaintenanceService = class {
|
|
|
8316
9013
|
await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
|
|
8317
9014
|
}
|
|
8318
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
|
+
}
|
|
8319
9026
|
return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
|
|
8320
9027
|
} finally {
|
|
8321
9028
|
this.jobManager.releaseLock("prune", entityId);
|
|
@@ -8420,6 +9127,7 @@ var MaintenanceService = class {
|
|
|
8420
9127
|
}
|
|
8421
9128
|
const result = await this.embeddingService.tryEmbedFact(row, { operation: "reembed", trigger: "call" });
|
|
8422
9129
|
if (result.ok) embedded++;
|
|
9130
|
+
else if (result.kind === "fact_deleted") skipped++;
|
|
8423
9131
|
else failed++;
|
|
8424
9132
|
}
|
|
8425
9133
|
if (embedded > 0) {
|
|
@@ -8437,6 +9145,9 @@ var MaintenanceService = class {
|
|
|
8437
9145
|
if (params.clearAll && (params.entryId !== void 0 || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
|
|
8438
9146
|
throw new Error("forget() clearAll is mutually exclusive with entryId, taskId, sourceRef, and sourceHash");
|
|
8439
9147
|
}
|
|
9148
|
+
if (params.includeEvents && !params.clearAll) {
|
|
9149
|
+
throw new Error("forget() includeEvents requires clearAll: true");
|
|
9150
|
+
}
|
|
8440
9151
|
if (opts?.dryRun === true) {
|
|
8441
9152
|
return this.forgetDryRun(entityId, params);
|
|
8442
9153
|
}
|
|
@@ -8445,13 +9156,24 @@ var MaintenanceService = class {
|
|
|
8445
9156
|
const now = Date.now();
|
|
8446
9157
|
let deletedEntries = 0;
|
|
8447
9158
|
let deletedTasks = 0;
|
|
9159
|
+
let deletedEvents = 0;
|
|
8448
9160
|
const deletedEntryIds = [];
|
|
9161
|
+
const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
|
|
8449
9162
|
await this.db.withTransactionAsync(async (tx) => {
|
|
8450
9163
|
if (params.clearAll) {
|
|
8451
|
-
|
|
9164
|
+
for (const id of await this.entryRepo.findIdsBySource(entityId, null, null, tx, true)) deletedEntryIds.push(id);
|
|
8452
9165
|
deletedEntries = await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
|
|
8453
9166
|
deletedTasks = await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
|
|
8454
|
-
await this.
|
|
9167
|
+
if (await this.sourceRefIndexPresent(tx)) {
|
|
9168
|
+
await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
|
|
9169
|
+
}
|
|
9170
|
+
await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
|
|
9171
|
+
if (params.includeEvents) {
|
|
9172
|
+
deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
|
|
9173
|
+
await this.metadataRepo.deleteCheckpoint(entityId, tx);
|
|
9174
|
+
} else {
|
|
9175
|
+
await this.metadataRepo.updateCheckpoint(entityId, { memory: 0, heal: 0 }, tx);
|
|
9176
|
+
}
|
|
8455
9177
|
await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
|
|
8456
9178
|
} else {
|
|
8457
9179
|
const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
|
|
@@ -8469,7 +9191,7 @@ var MaintenanceService = class {
|
|
|
8469
9191
|
if (entryId) deletedEntryIds.push(entryId);
|
|
8470
9192
|
}
|
|
8471
9193
|
if (sourceRef || sourceHash) {
|
|
8472
|
-
|
|
9194
|
+
for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
|
|
8473
9195
|
}
|
|
8474
9196
|
const entryPromise = params.entryId ? this.entryRepo.softDelete(params.entryId, entityId, tx).then((r) => r.changes > 0) : null;
|
|
8475
9197
|
const taskDeletedPromise = params.taskId ? this.taskRepo.softDeleteById(params.taskId, entityId, tx).then((r) => r.changes > 0) : null;
|
|
@@ -8485,29 +9207,78 @@ var MaintenanceService = class {
|
|
|
8485
9207
|
if (taskResult) deletedTasks++;
|
|
8486
9208
|
deletedEntries += refResult;
|
|
8487
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
|
+
}
|
|
8488
9213
|
});
|
|
8489
9214
|
const uniqueDeletedIds = Array.from(new Set(deletedEntryIds));
|
|
8490
9215
|
await this.searchService.syncEntries(entityId, uniqueDeletedIds);
|
|
8491
|
-
|
|
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;
|
|
8492
9224
|
try {
|
|
8493
|
-
|
|
8494
|
-
|
|
8495
|
-
|
|
8496
|
-
|
|
8497
|
-
|
|
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;
|
|
8498
9240
|
}
|
|
9241
|
+
} catch (hookErr) {
|
|
8499
9242
|
const errMsg = hookErr?.message ?? "";
|
|
8500
9243
|
if (errMsg.startsWith("Invalid deletionHookTimeoutMs")) {
|
|
8501
|
-
throw new Error(`forget(${entityId}/${
|
|
9244
|
+
throw new Error(`forget(${entityId}/${firstId}) failed: ${errMsg}`, { cause: hookErr });
|
|
8502
9245
|
}
|
|
8503
|
-
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
|
+
});
|
|
8504
9258
|
}
|
|
8505
9259
|
}
|
|
8506
|
-
|
|
9260
|
+
if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
|
|
9261
|
+
return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
|
|
8507
9262
|
} finally {
|
|
8508
9263
|
this.jobManager.releaseLock("forget", entityId);
|
|
8509
9264
|
}
|
|
8510
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
|
+
}
|
|
8511
9282
|
/**
|
|
8512
9283
|
* Whether forget() should soft-delete in source_ref_index (#316,
|
|
8513
9284
|
* specs/forget-pre-v9 §3.1). Normally true: setup()'s DDL creates the table.
|
|
@@ -8554,6 +9325,10 @@ var MaintenanceService = class {
|
|
|
8554
9325
|
if (params.clearAll) {
|
|
8555
9326
|
const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
|
|
8556
9327
|
const tasks = await this.taskRepo.countLiveByEntityId(entityId);
|
|
9328
|
+
if (params.includeEvents) {
|
|
9329
|
+
const events = await this.eventRepo.count(entityId);
|
|
9330
|
+
return { deleted: { entries: entries2, tasks, events }, metadataReset: true };
|
|
9331
|
+
}
|
|
8557
9332
|
return { deleted: { entries: entries2, tasks }, metadataReset: true };
|
|
8558
9333
|
}
|
|
8559
9334
|
const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
|
|
@@ -8701,14 +9476,7 @@ var MaintenanceService = class {
|
|
|
8701
9476
|
staleDowngradedIds.push(...await this.entryRepo.downgradeStaleInferred(entityId, staleThreshold, tx));
|
|
8702
9477
|
}
|
|
8703
9478
|
});
|
|
8704
|
-
|
|
8705
|
-
try {
|
|
8706
|
-
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
8707
|
-
} catch (hookErr) {
|
|
8708
|
-
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal orphan pass for ${factId}:`, hookErr);
|
|
8709
|
-
emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
|
|
8710
|
-
}
|
|
8711
|
-
}
|
|
9479
|
+
await this.deliverHealRemovals(entityId, orphanedIds, trigger);
|
|
8712
9480
|
const healCandidates = await this.entryRepo.findHealCandidatesByEntityId(entityId, batchSize, recheckCutoff);
|
|
8713
9481
|
const keywordUnavailable = healCandidates.length > 0 && !this.searchService.isKeywordAvailable();
|
|
8714
9482
|
if (healCandidates.length === 0 || keywordUnavailable) {
|
|
@@ -8897,14 +9665,7 @@ var MaintenanceService = class {
|
|
|
8897
9665
|
...insertedFacts.map((f) => f.id)
|
|
8898
9666
|
]));
|
|
8899
9667
|
await this.searchService.syncEntries(entityId, healSyncIds);
|
|
8900
|
-
|
|
8901
|
-
try {
|
|
8902
|
-
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
8903
|
-
} catch (hookErr) {
|
|
8904
|
-
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed during heal for ${factId}:`, hookErr);
|
|
8905
|
-
emitDiagnostic(this.options, { ...diagBase, code: "hook_failed", detail: { factId, reason: "on_embedding_persisted" } });
|
|
8906
|
-
}
|
|
8907
|
-
}
|
|
9668
|
+
await this.deliverHealRemovals(entityId, uniqueDeletedFactIds, trigger);
|
|
8908
9669
|
for (const fact of insertedFacts) {
|
|
8909
9670
|
await this.embeddingService.embedFact(fact, { operation: "heal", trigger });
|
|
8910
9671
|
}
|
|
@@ -9270,7 +10031,7 @@ var MaintenanceService = class {
|
|
|
9270
10031
|
|
|
9271
10032
|
// src/services/MaintenanceScheduler.ts
|
|
9272
10033
|
var MaintenanceScheduler = class {
|
|
9273
|
-
constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager) {
|
|
10034
|
+
constructor(db, options, maintenanceService, metadataRepo, eventRepo, entryRepo, jobManager, vectorRemovalService, vectorRemovalRepo) {
|
|
9274
10035
|
this.db = db;
|
|
9275
10036
|
this.options = options;
|
|
9276
10037
|
this.maintenanceService = maintenanceService;
|
|
@@ -9278,6 +10039,8 @@ var MaintenanceScheduler = class {
|
|
|
9278
10039
|
this.eventRepo = eventRepo;
|
|
9279
10040
|
this.entryRepo = entryRepo;
|
|
9280
10041
|
this.jobManager = jobManager;
|
|
10042
|
+
this.vectorRemovalService = vectorRemovalService;
|
|
10043
|
+
this.vectorRemovalRepo = vectorRemovalRepo;
|
|
9281
10044
|
}
|
|
9282
10045
|
/**
|
|
9283
10046
|
* Entities with **any** pending work only, sorted by `pendingEvents` desc
|
|
@@ -9289,7 +10052,17 @@ var MaintenanceScheduler = class {
|
|
|
9289
10052
|
const autoHealThreshold = this.options.config?.autoHealThreshold || 100;
|
|
9290
10053
|
const canEmbed = typeof this.options.llmProvider.embed === "function";
|
|
9291
10054
|
const out = [];
|
|
9292
|
-
|
|
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) {
|
|
9293
10066
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
9294
10067
|
const pendingEvents = await this.eventRepo.countAfter(entityId, wm);
|
|
9295
10068
|
const chars = pendingEvents > 0 ? await this.eventRepo.sumSummaryCharsAfter(entityId, wm) : 0;
|
|
@@ -9299,8 +10072,16 @@ var MaintenanceScheduler = class {
|
|
|
9299
10072
|
if (healCheckpoint > eventCount) healCheckpoint = 0;
|
|
9300
10073
|
const healDue = eventCount - healCheckpoint >= autoHealThreshold;
|
|
9301
10074
|
const reembedPending = canEmbed && await this.entryRepo.countReembedPending(entityId, MAX_EMBED_ATTEMPTS) > 0;
|
|
9302
|
-
|
|
9303
|
-
|
|
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
|
+
});
|
|
9304
10085
|
}
|
|
9305
10086
|
}
|
|
9306
10087
|
return out.sort((x, y) => y.pendingEvents - x.pendingEvents || (x.entityId < y.entityId ? -1 : x.entityId > y.entityId ? 1 : 0));
|
|
@@ -9326,8 +10107,9 @@ var MaintenanceScheduler = class {
|
|
|
9326
10107
|
const meter = new UsageMeter(opts.tokenBudget);
|
|
9327
10108
|
const budget = opts.tokenBudget;
|
|
9328
10109
|
const deadline = opts.deadlineMs !== void 0 ? Date.now() + Math.max(0, opts.deadlineMs) : Infinity;
|
|
9329
|
-
const jobs = new Set(opts.jobs ?? ["librarian", "heal", "reembed"]);
|
|
9330
|
-
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);
|
|
9331
10113
|
const states = pending.map((p) => ({
|
|
9332
10114
|
p,
|
|
9333
10115
|
report: { entityId: p.entityId, librarianPasses: 0, factsWritten: 0, healPasses: 0, reembedded: false },
|
|
@@ -9459,9 +10241,43 @@ var MaintenanceScheduler = class {
|
|
|
9459
10241
|
tokensUsed: meter.used,
|
|
9460
10242
|
estimated: meter.estimated,
|
|
9461
10243
|
remaining: budget === void 0 ? null : meter.remaining,
|
|
9462
|
-
stoppedReason: stopped
|
|
10244
|
+
stoppedReason: stopped,
|
|
10245
|
+
externalDeletions
|
|
9463
10246
|
};
|
|
9464
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
|
+
}
|
|
9465
10281
|
};
|
|
9466
10282
|
|
|
9467
10283
|
// src/services/importEventStamps.ts
|
|
@@ -9526,7 +10342,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
|
|
|
9526
10342
|
var IMPORT_TITLE_MAX = 500;
|
|
9527
10343
|
var IMPORT_BODY_MAX = 8e3;
|
|
9528
10344
|
var ImportExportService = class {
|
|
9529
|
-
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}) {
|
|
10345
|
+
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
|
|
9530
10346
|
this.db = db;
|
|
9531
10347
|
this.entryRepo = entryRepo;
|
|
9532
10348
|
this.taskRepo = taskRepo;
|
|
@@ -9537,6 +10353,7 @@ var ImportExportService = class {
|
|
|
9537
10353
|
this.jobManager = jobManager;
|
|
9538
10354
|
this.embeddingService = embeddingService;
|
|
9539
10355
|
this.options = options;
|
|
10356
|
+
this.vectorRemoval = vectorRemoval;
|
|
9540
10357
|
}
|
|
9541
10358
|
async exportDump(entityIds) {
|
|
9542
10359
|
let ids;
|
|
@@ -9912,8 +10729,20 @@ var ImportExportService = class {
|
|
|
9912
10729
|
body: clipped?.body ?? fact.body,
|
|
9913
10730
|
tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
|
|
9914
10731
|
}, { operation: "importDump", trigger: "call" });
|
|
9915
|
-
if (!embedded) {
|
|
9916
|
-
|
|
10732
|
+
if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
|
|
10733
|
+
try {
|
|
10734
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
|
|
10735
|
+
} catch (hookErr) {
|
|
10736
|
+
console.warn(
|
|
10737
|
+
`[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
|
|
10738
|
+
hookErr
|
|
10739
|
+
);
|
|
10740
|
+
this.embeddingService.reportHookFailed(
|
|
10741
|
+
{ operation: "importDump", trigger: "call" },
|
|
10742
|
+
entityId,
|
|
10743
|
+
fact.id
|
|
10744
|
+
);
|
|
10745
|
+
}
|
|
9917
10746
|
}
|
|
9918
10747
|
}
|
|
9919
10748
|
}
|
|
@@ -9942,16 +10771,26 @@ var ImportExportService = class {
|
|
|
9942
10771
|
fact.id
|
|
9943
10772
|
);
|
|
9944
10773
|
}
|
|
10774
|
+
if (this.embeddingService.hasVectorHook()) {
|
|
10775
|
+
await this.embeddingService.settleAfterVectorCall(entityId, fact.id, "importDump", "call");
|
|
10776
|
+
}
|
|
9945
10777
|
}
|
|
9946
10778
|
}
|
|
9947
|
-
|
|
9948
|
-
|
|
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) {
|
|
9949
10792
|
try {
|
|
9950
|
-
await this.embeddingService.notifyEmbeddingPersisted(
|
|
9951
|
-
entityId,
|
|
9952
|
-
factId,
|
|
9953
|
-
null
|
|
9954
|
-
);
|
|
10793
|
+
await this.embeddingService.notifyEmbeddingPersisted(entityId, factId, null);
|
|
9955
10794
|
} catch (hookErr) {
|
|
9956
10795
|
console.warn(
|
|
9957
10796
|
`[WikiMemory] onEmbeddingPersisted(vector=null) hook failed for soft-deleted fact ${factId}:`,
|
|
@@ -10188,27 +11027,62 @@ var EmbeddingService = class {
|
|
|
10188
11027
|
}
|
|
10189
11028
|
/**
|
|
10190
11029
|
* Storage half: persist the computed vector to the entry row, then fire the
|
|
10191
|
-
* `onEmbeddingPersisted` hook. Failure kinds: `storage_error`
|
|
10192
|
-
*
|
|
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).
|
|
10193
11034
|
*/
|
|
10194
11035
|
async storeFactVector(fact, float32Vector, ctx) {
|
|
11036
|
+
let stored = true;
|
|
10195
11037
|
try {
|
|
10196
11038
|
await this.storeEmbeddingDimension(float32Vector.length);
|
|
10197
11039
|
const blob = new Uint8Array(float32Vector.buffer);
|
|
10198
|
-
await this.entryRepo.updateEmbeddingBlob(fact.id, blob);
|
|
11040
|
+
stored = (await this.entryRepo.updateEmbeddingBlob(fact.id, blob)).changes > 0;
|
|
10199
11041
|
} catch (err) {
|
|
10200
11042
|
console.warn(`[WikiMemory] embedFact: persisting embedding failed for ${fact.id}:`, err);
|
|
10201
11043
|
this.reportEmbed(ctx, fact, "embedding_failed", "persist_failed");
|
|
10202
11044
|
return { ok: false, kind: "storage_error" };
|
|
10203
11045
|
}
|
|
11046
|
+
if (!stored) return { ok: false, kind: "fact_deleted" };
|
|
10204
11047
|
try {
|
|
10205
11048
|
await this.notifyEmbeddingPersisted(fact.entity_id, fact.id, float32Vector);
|
|
10206
11049
|
} catch (hookErr) {
|
|
10207
11050
|
console.warn(`[WikiMemory] onEmbeddingPersisted hook failed for ${fact.id}:`, hookErr);
|
|
10208
11051
|
this.reportEmbed(ctx, fact, "hook_failed", "on_embedding_persisted");
|
|
10209
11052
|
}
|
|
11053
|
+
if (this.hasVectorHook()) {
|
|
11054
|
+
await this.settleAfterVectorCall(fact.entity_id, fact.id, ctx?.operation ?? "externalDeletion", ctx?.trigger ?? "call");
|
|
11055
|
+
}
|
|
10210
11056
|
return { ok: true, dimension: float32Vector.length };
|
|
10211
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
|
+
}
|
|
10212
11086
|
reportEmbed(ctx, fact, code, reason) {
|
|
10213
11087
|
if (!ctx) return;
|
|
10214
11088
|
emitDiagnostic(this.options, {
|
|
@@ -10240,6 +11114,48 @@ var EmbeddingService = class {
|
|
|
10240
11114
|
const result = await this.tryEmbedFact(fact, ctx);
|
|
10241
11115
|
return result.ok;
|
|
10242
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
|
+
}
|
|
10243
11159
|
async notifyEmbeddingPersisted(entityId, factId, vector) {
|
|
10244
11160
|
if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
|
|
10245
11161
|
const vectorCopy = vector ? vector.slice() : null;
|
|
@@ -10249,15 +11165,72 @@ var EmbeddingService = class {
|
|
|
10249
11165
|
vector: vectorCopy
|
|
10250
11166
|
});
|
|
10251
11167
|
}
|
|
10252
|
-
|
|
10253
|
-
if (!this.options.vectorRanker?.onEmbeddingPersisted) return;
|
|
10254
|
-
if (this.options.forceDeleteIgnoreRankerHook === true) return;
|
|
10255
|
-
const vectorCopy = vector ? vector.slice() : null;
|
|
11168
|
+
validateDeletionTimeout() {
|
|
10256
11169
|
const rawTimeout = this.options.deletionHookTimeoutMs ?? 3e4;
|
|
10257
11170
|
if (typeof rawTimeout !== "number" || !Number.isFinite(rawTimeout) || rawTimeout <= 0) {
|
|
10258
11171
|
throw new Error("Invalid deletionHookTimeoutMs: must be a positive finite number");
|
|
10259
11172
|
}
|
|
10260
|
-
|
|
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();
|
|
10261
11234
|
let timeoutHandle;
|
|
10262
11235
|
const timeoutPromise = new Promise((_, reject) => {
|
|
10263
11236
|
timeoutHandle = setTimeout(() => {
|
|
@@ -11857,11 +12830,15 @@ var WikiMemory = class {
|
|
|
11857
12830
|
this.upsertIdStashSize = 0;
|
|
11858
12831
|
/** Bumped per stashed id; a re-stash during an in-flight drain outlives that drain's drop. */
|
|
11859
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;
|
|
11860
12836
|
this.reinitSearch = null;
|
|
11861
12837
|
/** Monotonic time before which a no-arg syncSearchIndex() skips the re-init (0 = no cooldown). */
|
|
11862
12838
|
this.reinitRetryAt = 0;
|
|
11863
12839
|
/** Consecutive failed re-inits; drives the exponential backoff. */
|
|
11864
12840
|
this.reinitFailures = 0;
|
|
12841
|
+
this.setupRemovalDrain = null;
|
|
11865
12842
|
this.db = withSerializedTransactions(db);
|
|
11866
12843
|
this.options = options;
|
|
11867
12844
|
warnChangedDefaultsOnce(options.config);
|
|
@@ -11886,6 +12863,9 @@ var WikiMemory = class {
|
|
|
11886
12863
|
);
|
|
11887
12864
|
this.lintService = new LintService(this.lintRepo, this.ontologyService);
|
|
11888
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);
|
|
11889
12869
|
this.searchService = new SearchService(
|
|
11890
12870
|
this.entryRepo,
|
|
11891
12871
|
new MiniSearchIndexStrategy()
|
|
@@ -11906,7 +12886,8 @@ var WikiMemory = class {
|
|
|
11906
12886
|
this.jobManager,
|
|
11907
12887
|
this.embeddingService,
|
|
11908
12888
|
this.promptService,
|
|
11909
|
-
this.ontologyService
|
|
12889
|
+
this.ontologyService,
|
|
12890
|
+
this.vectorRemovalService
|
|
11910
12891
|
);
|
|
11911
12892
|
this.maintenanceService = new MaintenanceService(
|
|
11912
12893
|
this.db,
|
|
@@ -11921,7 +12902,10 @@ var WikiMemory = class {
|
|
|
11921
12902
|
this.jobManager,
|
|
11922
12903
|
this.embeddingService,
|
|
11923
12904
|
this.promptService,
|
|
11924
|
-
this.ontologyService
|
|
12905
|
+
this.ontologyService,
|
|
12906
|
+
this.edgeRepo,
|
|
12907
|
+
this.vectorRemovalService,
|
|
12908
|
+
this.vectorRemovalRepo
|
|
11925
12909
|
);
|
|
11926
12910
|
this.maintenanceScheduler = new MaintenanceScheduler(
|
|
11927
12911
|
this.db,
|
|
@@ -11930,7 +12914,9 @@ var WikiMemory = class {
|
|
|
11930
12914
|
this.metadataRepo,
|
|
11931
12915
|
this.eventRepo,
|
|
11932
12916
|
this.entryRepo,
|
|
11933
|
-
this.jobManager
|
|
12917
|
+
this.jobManager,
|
|
12918
|
+
this.vectorRemovalService,
|
|
12919
|
+
this.vectorRemovalRepo
|
|
11934
12920
|
);
|
|
11935
12921
|
this.importExportService = new ImportExportService(
|
|
11936
12922
|
this.db,
|
|
@@ -11942,7 +12928,8 @@ var WikiMemory = class {
|
|
|
11942
12928
|
this.searchService,
|
|
11943
12929
|
this.jobManager,
|
|
11944
12930
|
this.embeddingService,
|
|
11945
|
-
this.options
|
|
12931
|
+
this.options,
|
|
12932
|
+
this.vectorRemovalService
|
|
11946
12933
|
);
|
|
11947
12934
|
this.retrievalService = new RetrievalService(
|
|
11948
12935
|
this.options,
|
|
@@ -12010,6 +12997,33 @@ var WikiMemory = class {
|
|
|
12010
12997
|
}
|
|
12011
12998
|
if (stash.size > 0) this.upsertIdStash.set(entityId, stash);
|
|
12012
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
|
+
}
|
|
12013
13027
|
/** Snapshot of the stash (one entity, or all) with generations, without removing anything. */
|
|
12014
13028
|
peekStashedIds(entityId) {
|
|
12015
13029
|
const snapshot = /* @__PURE__ */ new Map();
|
|
@@ -12098,6 +13112,84 @@ var WikiMemory = class {
|
|
|
12098
13112
|
)
|
|
12099
13113
|
);
|
|
12100
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);
|
|
12101
13193
|
}
|
|
12102
13194
|
async hasChanged(entityId, sourceRefOrEntries, sourceHashArg) {
|
|
12103
13195
|
if (typeof sourceRefOrEntries === "string") {
|
|
@@ -12265,8 +13357,9 @@ var WikiMemory = class {
|
|
|
12265
13357
|
async write(entityId, event) {
|
|
12266
13358
|
return this.writeService.write(entityId, event);
|
|
12267
13359
|
}
|
|
12268
|
-
/** 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`. */
|
|
12269
13361
|
async drain() {
|
|
13362
|
+
await this.setupRemovalDrain;
|
|
12270
13363
|
return this.writeService.drain();
|
|
12271
13364
|
}
|
|
12272
13365
|
/**
|
|
@@ -12278,9 +13371,32 @@ var WikiMemory = class {
|
|
|
12278
13371
|
async getPendingMaintenance(entityIds) {
|
|
12279
13372
|
return this.maintenanceScheduler.getPending(entityIds);
|
|
12280
13373
|
}
|
|
12281
|
-
/** 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. */
|
|
12282
13375
|
async runPendingMaintenance(options) {
|
|
12283
|
-
|
|
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);
|
|
12284
13400
|
}
|
|
12285
13401
|
/**
|
|
12286
13402
|
* @param options.promptOverride - Applies only to this manual call. Does NOT affect
|
|
@@ -12361,6 +13477,11 @@ var WikiMemory = class {
|
|
|
12361
13477
|
* waits at least 5 s, doubling per consecutive failure up to 5 min (longer
|
|
12362
13478
|
* when an attempt is itself slow), before retrying again.
|
|
12363
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
|
+
*
|
|
12364
13485
|
* Call only after the host's transaction commits: called inside it, the
|
|
12365
13486
|
* rebuild may index rows that later roll back, or miss them and clear the
|
|
12366
13487
|
* stale flag anyway. Serialized with core's internal index syncs and takes
|
|
@@ -12376,6 +13497,19 @@ var WikiMemory = class {
|
|
|
12376
13497
|
* @throws {TypeError} when `entityId` is given but is not a non-empty string.
|
|
12377
13498
|
*/
|
|
12378
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) {
|
|
12379
13513
|
if (entityId === void 0) {
|
|
12380
13514
|
if (!this.searchService.isKeywordAvailable() && monotonicNow() >= this.reinitRetryAt) {
|
|
12381
13515
|
this.reinitSearch ?? (this.reinitSearch = (async () => {
|
|
@@ -12434,6 +13568,24 @@ var WikiMemory = class {
|
|
|
12434
13568
|
async importDump(dump, opts) {
|
|
12435
13569
|
return this.importExportService.importDump(dump, opts);
|
|
12436
13570
|
}
|
|
13571
|
+
/**
|
|
13572
|
+
* Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
|
|
13573
|
+
* `clearAll` also deletes the entity's edges and its source-ref index rows.
|
|
13574
|
+
* Add `includeEvents: true` to `clearAll` to hard-delete every event too,
|
|
13575
|
+
* read or not, and reset the librarian's position: without it a later
|
|
13576
|
+
* maintenance run can read the events into facts again. `runPrune()` then
|
|
13577
|
+
* hard-deletes the soft-deleted rows once they are older than
|
|
13578
|
+
* `retainSoftDeletedFor` (7 days by default; pass 0 to remove them now).
|
|
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()`.
|
|
13588
|
+
*/
|
|
12437
13589
|
async forget(entityId, params, opts) {
|
|
12438
13590
|
return this.maintenanceService.forget(entityId, params, opts);
|
|
12439
13591
|
}
|
|
@@ -12485,12 +13637,15 @@ var WikiMemory = class {
|
|
|
12485
13637
|
* semantics identical to `ingestDocument`, minus the LLM extraction step.
|
|
12486
13638
|
*
|
|
12487
13639
|
* MUST be called from inside an open `db.withTransactionAsync` callback —
|
|
12488
|
-
* 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
|
|
12489
13643
|
* nested transaction, does not acquire any lock, and does not perform
|
|
12490
13644
|
* post-commit work (search sync, embedding, cache eviction). After the
|
|
12491
13645
|
* transaction commits, call `syncSearchIndex(entityId)` — or
|
|
12492
13646
|
* `syncSearchIndex()` after writing several entities in one transaction —
|
|
12493
|
-
* 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
|
|
12494
13649
|
* first, to completion, so the nodes are searchable under any backlog (up to
|
|
12495
13650
|
* `WikiMemory.UPSERT_ID_STASH_CAP` pending ids; beyond that they converge with
|
|
12496
13651
|
* the backlog). Embeddings still come from the maintenance
|
|
@@ -12550,6 +13705,7 @@ var WikiMemory = class {
|
|
|
12550
13705
|
{ diag: { buffer: diagBuffer, operation: "upsertGraph" } }
|
|
12551
13706
|
);
|
|
12552
13707
|
this.stashUpsertIds(entityId, [...supersededFactIds, ...params.nodes.map((n) => n.id)]);
|
|
13708
|
+
this.stashRemovalIds(entityId, supersededFactIds);
|
|
12553
13709
|
this.searchService.markStale(entityId);
|
|
12554
13710
|
diagBuffer.flush(this.options);
|
|
12555
13711
|
return result;
|
|
@@ -12732,8 +13888,10 @@ var WikiMemory = class {
|
|
|
12732
13888
|
}
|
|
12733
13889
|
};
|
|
12734
13890
|
_testAccessNonTestEnvWarned = new WeakMap();
|
|
12735
|
-
/** 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). */
|
|
12736
13892
|
WikiMemory.UPSERT_ID_STASH_CAP = 1e4;
|
|
13893
|
+
/** Max superseded-fact ids held for post-commit removal delivery. */
|
|
13894
|
+
WikiMemory.REMOVAL_STASH_CAP = 1e4;
|
|
12737
13895
|
function assertEntityId2(entityId) {
|
|
12738
13896
|
if (typeof entityId !== "string" || entityId.length === 0) {
|
|
12739
13897
|
throw new TypeError("Invalid entityId: must be a non-empty string.");
|
|
@@ -13360,6 +14518,24 @@ function parseStaleAfterRaw(raw) {
|
|
|
13360
14518
|
}
|
|
13361
14519
|
return ms;
|
|
13362
14520
|
}
|
|
14521
|
+
function replaceLoneSurrogates(s) {
|
|
14522
|
+
let out = "";
|
|
14523
|
+
for (let i = 0; i < s.length; i++) {
|
|
14524
|
+
const c = s.charCodeAt(i);
|
|
14525
|
+
if (c >= 55296 && c <= 56319) {
|
|
14526
|
+
const n = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
|
|
14527
|
+
if (n >= 56320 && n <= 57343) {
|
|
14528
|
+
out += s[i] + s[i + 1];
|
|
14529
|
+
i++;
|
|
14530
|
+
} else out += "\uFFFD";
|
|
14531
|
+
} else if (c >= 56320 && c <= 57343) {
|
|
14532
|
+
out += "\uFFFD";
|
|
14533
|
+
} else {
|
|
14534
|
+
out += s[i];
|
|
14535
|
+
}
|
|
14536
|
+
}
|
|
14537
|
+
return out;
|
|
14538
|
+
}
|
|
13363
14539
|
function unescapeLogSummary(summary) {
|
|
13364
14540
|
return summary.replace(/\\\]/g, "]").replace(/\\\[/g, "[").replace(/\\\\/g, "\\");
|
|
13365
14541
|
}
|
|
@@ -13372,7 +14548,7 @@ function parseLogEntryText(text) {
|
|
|
13372
14548
|
if (linkPath) {
|
|
13373
14549
|
return { event_type, summary: unescapeLogSummary(linkedSummary), linkPath };
|
|
13374
14550
|
}
|
|
13375
|
-
return { event_type, summary: (plainSummary ?? "").trim() };
|
|
14551
|
+
return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
|
|
13376
14552
|
}
|
|
13377
14553
|
function frontmatterToFact(entityId, id, frontmatter, body, now) {
|
|
13378
14554
|
const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
|
|
@@ -13584,6 +14760,7 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
13584
14760
|
}
|
|
13585
14761
|
const events = [];
|
|
13586
14762
|
if (logContent != null) {
|
|
14763
|
+
const pending = [];
|
|
13587
14764
|
const logPath = logMdPath ?? `entities/${entityId}/log.md`;
|
|
13588
14765
|
for (const entry of coreOkf.parseLogMd(logContent)) {
|
|
13589
14766
|
const { text, eventId } = coreOkf.parseEventIdComment(entry.text);
|
|
@@ -13601,8 +14778,9 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
13601
14778
|
}
|
|
13602
14779
|
const created_at = (/* @__PURE__ */ new Date(`${entry.date}T00:00:00.000Z`)).getTime();
|
|
13603
14780
|
if (!Number.isFinite(created_at)) continue;
|
|
14781
|
+
if (eventId === void 0) pending.push({ index: events.length, date: entry.date });
|
|
13604
14782
|
events.push({
|
|
13605
|
-
id: eventId ??
|
|
14783
|
+
id: eventId ?? "",
|
|
13606
14784
|
entity_id: entityId,
|
|
13607
14785
|
event_type: parsed.event_type,
|
|
13608
14786
|
summary: parsed.summary,
|
|
@@ -13610,6 +14788,22 @@ function parseOkfBundle(entityId, files, options) {
|
|
|
13610
14788
|
created_at
|
|
13611
14789
|
});
|
|
13612
14790
|
}
|
|
14791
|
+
const taken = new Set(events.map((e) => e.id).filter((id) => id !== ""));
|
|
14792
|
+
const nextOccurrence = /* @__PURE__ */ new Map();
|
|
14793
|
+
for (const { index, date } of pending) {
|
|
14794
|
+
const e = events[index];
|
|
14795
|
+
const key = JSON.stringify([date, e.event_type, replaceLoneSurrogates(e.summary)]);
|
|
14796
|
+
let occurrence = nextOccurrence.get(key) ?? 0;
|
|
14797
|
+
const derive = coreOkf.createEventIdDeriver({ entityId, date, eventType: e.event_type, summary: e.summary });
|
|
14798
|
+
let id = derive(occurrence);
|
|
14799
|
+
while (taken.has(id)) {
|
|
14800
|
+
occurrence += 1;
|
|
14801
|
+
id = derive(occurrence);
|
|
14802
|
+
}
|
|
14803
|
+
taken.add(id);
|
|
14804
|
+
nextOccurrence.set(key, occurrence + 1);
|
|
14805
|
+
e.id = id;
|
|
14806
|
+
}
|
|
13613
14807
|
}
|
|
13614
14808
|
return {
|
|
13615
14809
|
generatedAt: now,
|
|
@@ -13684,6 +14878,7 @@ exports.PrunePartialFailureError = PrunePartialFailureError;
|
|
|
13684
14878
|
exports.WikiBusyError = WikiBusyError;
|
|
13685
14879
|
exports.WikiDraftNotFound = WikiDraftNotFound;
|
|
13686
14880
|
exports.WikiDuplicateHashError = WikiDuplicateHashError;
|
|
14881
|
+
exports.WikiExternalDeletionError = WikiExternalDeletionError;
|
|
13687
14882
|
exports.WikiGraphNodeOwnershipConflict = WikiGraphNodeOwnershipConflict;
|
|
13688
14883
|
exports.WikiIngestEmptyError = WikiIngestEmptyError;
|
|
13689
14884
|
exports.WikiInvalidReadOptions = WikiInvalidReadOptions;
|