@equationalapplications/expo-llm-wiki 0.0.0-development
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/LICENSE +21 -0
- package/README.md +259 -0
- package/dist/WikiMemory-B-yFw9Dc.d.mts +118 -0
- package/dist/WikiMemory-B-yFw9Dc.d.ts +118 -0
- package/dist/WikiMemory-BI2Aizwv.d.mts +121 -0
- package/dist/WikiMemory-BI2Aizwv.d.ts +121 -0
- package/dist/WikiMemory-BWTt1Ynm.d.mts +103 -0
- package/dist/WikiMemory-BWTt1Ynm.d.ts +103 -0
- package/dist/index.d.mts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +679 -0
- package/dist/index.mjs +651 -0
- package/dist/react/index.d.mts +72 -0
- package/dist/react/index.d.ts +72 -0
- package/dist/react/index.js +230 -0
- package/dist/react/index.mjs +197 -0
- package/package.json +67 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,651 @@
|
|
|
1
|
+
// src/db/schema.ts
|
|
2
|
+
async function setupDatabase(db, prefix) {
|
|
3
|
+
await db.execAsync(`
|
|
4
|
+
CREATE TABLE IF NOT EXISTS ${prefix}entries (
|
|
5
|
+
id TEXT PRIMARY KEY,
|
|
6
|
+
entity_id TEXT NOT NULL,
|
|
7
|
+
title TEXT NOT NULL,
|
|
8
|
+
body TEXT NOT NULL,
|
|
9
|
+
tags TEXT NOT NULL DEFAULT '[]',
|
|
10
|
+
confidence TEXT NOT NULL DEFAULT 'inferred',
|
|
11
|
+
source_type TEXT NOT NULL DEFAULT 'agent_inferred',
|
|
12
|
+
source_hash TEXT,
|
|
13
|
+
source_ref TEXT,
|
|
14
|
+
created_at INTEGER NOT NULL,
|
|
15
|
+
updated_at INTEGER NOT NULL,
|
|
16
|
+
last_accessed_at INTEGER,
|
|
17
|
+
access_count INTEGER NOT NULL DEFAULT 0,
|
|
18
|
+
deleted_at INTEGER
|
|
19
|
+
);
|
|
20
|
+
|
|
21
|
+
CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
|
|
22
|
+
CREATE INDEX IF NOT EXISTS ${prefix}entries_source_ref_idx ON ${prefix}entries(entity_id, source_ref);
|
|
23
|
+
CREATE INDEX IF NOT EXISTS ${prefix}entries_source_hash_idx ON ${prefix}entries(entity_id, source_hash) WHERE source_hash IS NOT NULL;
|
|
24
|
+
CREATE INDEX IF NOT EXISTS ${prefix}entries_updated_idx ON ${prefix}entries(updated_at DESC);
|
|
25
|
+
|
|
26
|
+
-- FTS5 Virtual Table for full-text search
|
|
27
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS ${prefix}entries_fts USING fts5(
|
|
28
|
+
title,
|
|
29
|
+
body,
|
|
30
|
+
tags,
|
|
31
|
+
content='${prefix}entries',
|
|
32
|
+
content_rowid='rowid'
|
|
33
|
+
);
|
|
34
|
+
|
|
35
|
+
-- Triggers to keep FTS5 in sync with entries
|
|
36
|
+
CREATE TRIGGER IF NOT EXISTS ${prefix}entries_ai AFTER INSERT ON ${prefix}entries BEGIN
|
|
37
|
+
INSERT INTO ${prefix}entries_fts(rowid, title, body, tags)
|
|
38
|
+
VALUES (new.rowid, new.title, new.body, new.tags);
|
|
39
|
+
END;
|
|
40
|
+
|
|
41
|
+
CREATE TRIGGER IF NOT EXISTS ${prefix}entries_ad AFTER DELETE ON ${prefix}entries BEGIN
|
|
42
|
+
INSERT INTO ${prefix}entries_fts(${prefix}entries_fts, rowid, title, body, tags)
|
|
43
|
+
VALUES ('delete', old.rowid, old.title, old.body, old.tags);
|
|
44
|
+
END;
|
|
45
|
+
|
|
46
|
+
CREATE TRIGGER IF NOT EXISTS ${prefix}entries_au AFTER UPDATE ON ${prefix}entries BEGIN
|
|
47
|
+
INSERT INTO ${prefix}entries_fts(${prefix}entries_fts, rowid, title, body, tags)
|
|
48
|
+
VALUES ('delete', old.rowid, old.title, old.body, old.tags);
|
|
49
|
+
INSERT INTO ${prefix}entries_fts(rowid, title, body, tags)
|
|
50
|
+
VALUES (new.rowid, new.title, new.body, new.tags);
|
|
51
|
+
END;
|
|
52
|
+
|
|
53
|
+
CREATE TABLE IF NOT EXISTS ${prefix}tasks (
|
|
54
|
+
id TEXT PRIMARY KEY,
|
|
55
|
+
entity_id TEXT NOT NULL,
|
|
56
|
+
description TEXT NOT NULL,
|
|
57
|
+
status TEXT NOT NULL DEFAULT 'pending',
|
|
58
|
+
priority INTEGER NOT NULL DEFAULT 0,
|
|
59
|
+
created_at INTEGER NOT NULL,
|
|
60
|
+
updated_at INTEGER NOT NULL,
|
|
61
|
+
resolved_at INTEGER,
|
|
62
|
+
deleted_at INTEGER
|
|
63
|
+
);
|
|
64
|
+
|
|
65
|
+
CREATE INDEX IF NOT EXISTS ${prefix}tasks_entity_idx ON ${prefix}tasks(entity_id, status);
|
|
66
|
+
|
|
67
|
+
CREATE TABLE IF NOT EXISTS ${prefix}events (
|
|
68
|
+
id TEXT PRIMARY KEY,
|
|
69
|
+
entity_id TEXT NOT NULL,
|
|
70
|
+
event_type TEXT NOT NULL,
|
|
71
|
+
summary TEXT NOT NULL,
|
|
72
|
+
related_entry_id TEXT,
|
|
73
|
+
created_at INTEGER NOT NULL
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
CREATE INDEX IF NOT EXISTS ${prefix}events_entity_idx ON ${prefix}events(entity_id, created_at DESC);
|
|
77
|
+
|
|
78
|
+
CREATE TABLE IF NOT EXISTS ${prefix}checkpoints (
|
|
79
|
+
entity_id TEXT PRIMARY KEY,
|
|
80
|
+
heal_checkpoint INTEGER NOT NULL DEFAULT 0,
|
|
81
|
+
memory_checkpoint INTEGER NOT NULL DEFAULT 0
|
|
82
|
+
);
|
|
83
|
+
`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// src/prompts.ts
|
|
87
|
+
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.
|
|
88
|
+
Return ONLY a valid JSON object matching this schema:
|
|
89
|
+
{
|
|
90
|
+
"facts": [{ "title": "string (max 80 chars)", "body": "string (max 200 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }],
|
|
91
|
+
"tasks": [{ "description": "string", "priority": "number (0-10)" }]
|
|
92
|
+
}
|
|
93
|
+
Keep facts concise. Do not return markdown, just raw JSON.`;
|
|
94
|
+
var HEAL_SYSTEM_PROMPT = `You are a memory grooming agent. Your job is to review a full dump of facts and recent events to resolve contradictions, downgrade stale claims, and flag obsolete facts for deletion.
|
|
95
|
+
Return ONLY a valid JSON object matching this schema:
|
|
96
|
+
{
|
|
97
|
+
"downgraded": ["string (fact IDs)"],
|
|
98
|
+
"deleted": ["string (fact IDs)"],
|
|
99
|
+
"newFacts": [{ "title": "string", "body": "string", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
|
|
100
|
+
}
|
|
101
|
+
Do not return markdown, just raw JSON.`;
|
|
102
|
+
var INGEST_SYSTEM_PROMPT = `You are a document ingestion agent. Your job is to extract factual knowledge from the provided document chunk.
|
|
103
|
+
Return ONLY a valid JSON object matching this schema:
|
|
104
|
+
{
|
|
105
|
+
"facts": [{ "title": "string (max 80 chars)", "body": "string (max 200 chars)", "tags": ["string"], "confidence": "certain|inferred|tentative" }]
|
|
106
|
+
}
|
|
107
|
+
Extract verbatim factual content. Do not return markdown, just raw JSON.`;
|
|
108
|
+
|
|
109
|
+
// src/WikiMemory.ts
|
|
110
|
+
function parseJsonResponse(text) {
|
|
111
|
+
const firstBrace = text.indexOf("{");
|
|
112
|
+
const firstBracket = text.indexOf("[");
|
|
113
|
+
let start;
|
|
114
|
+
let openChar;
|
|
115
|
+
let closeChar;
|
|
116
|
+
if (firstBrace !== -1 && (firstBracket === -1 || firstBrace < firstBracket)) {
|
|
117
|
+
start = firstBrace;
|
|
118
|
+
openChar = "{";
|
|
119
|
+
closeChar = "}";
|
|
120
|
+
} else if (firstBracket !== -1) {
|
|
121
|
+
start = firstBracket;
|
|
122
|
+
openChar = "[";
|
|
123
|
+
closeChar = "]";
|
|
124
|
+
} else {
|
|
125
|
+
throw new SyntaxError("No JSON object/array found in LLM response");
|
|
126
|
+
}
|
|
127
|
+
let depth = 0;
|
|
128
|
+
let inString = false;
|
|
129
|
+
let escape = false;
|
|
130
|
+
let end = -1;
|
|
131
|
+
for (let i = start; i < text.length; i++) {
|
|
132
|
+
const ch = text[i];
|
|
133
|
+
if (escape) {
|
|
134
|
+
escape = false;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (ch === "\\" && inString) {
|
|
138
|
+
escape = true;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (ch === '"') {
|
|
142
|
+
inString = !inString;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
if (inString) continue;
|
|
146
|
+
if (ch === openChar) {
|
|
147
|
+
depth++;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (ch === closeChar) {
|
|
151
|
+
depth--;
|
|
152
|
+
if (depth === 0) {
|
|
153
|
+
end = i;
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (end === -1) throw new SyntaxError("No JSON object/array found in LLM response");
|
|
159
|
+
return JSON.parse(text.slice(start, end + 1));
|
|
160
|
+
}
|
|
161
|
+
function generateId(prefix = "") {
|
|
162
|
+
return prefix + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
|
|
163
|
+
}
|
|
164
|
+
function safeSlice(value, start, end) {
|
|
165
|
+
const length = value.length;
|
|
166
|
+
let safeStart = start < 0 ? Math.max(length + start, 0) : Math.min(start, length);
|
|
167
|
+
let safeEnd = end === void 0 ? length : end < 0 ? Math.max(length + end, 0) : Math.min(end, length);
|
|
168
|
+
if (safeStart > safeEnd) {
|
|
169
|
+
[safeStart, safeEnd] = [safeEnd, safeStart];
|
|
170
|
+
}
|
|
171
|
+
if (safeStart > 0 && safeStart < length && value.charCodeAt(safeStart) >= 56320 && value.charCodeAt(safeStart) <= 57343 && value.charCodeAt(safeStart - 1) >= 55296 && value.charCodeAt(safeStart - 1) <= 56319) {
|
|
172
|
+
safeStart--;
|
|
173
|
+
}
|
|
174
|
+
if (safeEnd > 0 && safeEnd < length && value.charCodeAt(safeEnd - 1) >= 55296 && value.charCodeAt(safeEnd - 1) <= 56319 && value.charCodeAt(safeEnd) >= 56320 && value.charCodeAt(safeEnd) <= 57343) {
|
|
175
|
+
safeEnd--;
|
|
176
|
+
}
|
|
177
|
+
return value.slice(safeStart, safeEnd);
|
|
178
|
+
}
|
|
179
|
+
function clip(value, max) {
|
|
180
|
+
if (typeof value !== "string") return "";
|
|
181
|
+
const s = value.trim();
|
|
182
|
+
return s.length <= max ? s : safeSlice(s, 0, max).trimEnd();
|
|
183
|
+
}
|
|
184
|
+
function validateTags(tags) {
|
|
185
|
+
if (!Array.isArray(tags)) return [];
|
|
186
|
+
return tags.filter((t) => typeof t === "string").map((t) => t.trim().toLowerCase()).filter((t) => t.length > 0 && t.length <= 40).slice(0, 6);
|
|
187
|
+
}
|
|
188
|
+
function validateFact(fact) {
|
|
189
|
+
if (typeof fact?.title !== "string" || typeof fact?.body !== "string") return null;
|
|
190
|
+
const title = clip(fact.title, 80);
|
|
191
|
+
const body = clip(fact.body, 200);
|
|
192
|
+
if (!title || !body) return null;
|
|
193
|
+
let confidence = fact.confidence;
|
|
194
|
+
if (confidence !== "certain" && confidence !== "tentative") confidence = "inferred";
|
|
195
|
+
return {
|
|
196
|
+
...fact,
|
|
197
|
+
title,
|
|
198
|
+
body,
|
|
199
|
+
confidence,
|
|
200
|
+
tags: validateTags(fact.tags)
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
function validateTask(task) {
|
|
204
|
+
if (typeof task?.description !== "string") return null;
|
|
205
|
+
const description = clip(task.description, 200);
|
|
206
|
+
if (!description) return null;
|
|
207
|
+
let priority = task.priority;
|
|
208
|
+
if (typeof priority !== "number" || !isFinite(priority)) priority = 0;
|
|
209
|
+
return {
|
|
210
|
+
...task,
|
|
211
|
+
description,
|
|
212
|
+
priority
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
function normalizeSourceRef(value) {
|
|
216
|
+
if (typeof value !== "string") return null;
|
|
217
|
+
const cleaned = value.replace(/[^A-Za-z0-9._\- ]/g, "").trim().slice(0, 255);
|
|
218
|
+
return cleaned.length > 0 ? cleaned : null;
|
|
219
|
+
}
|
|
220
|
+
function normalizeSourceHash(value) {
|
|
221
|
+
if (typeof value !== "string") return null;
|
|
222
|
+
return /^[0-9a-f]{64}$/i.test(value) ? value.toLowerCase() : null;
|
|
223
|
+
}
|
|
224
|
+
function titleTokens(title) {
|
|
225
|
+
return new Set(title.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter((t) => t.length >= 3));
|
|
226
|
+
}
|
|
227
|
+
function jaccardScore(a, b) {
|
|
228
|
+
if (a.size === 0 && b.size === 0) return 0;
|
|
229
|
+
const intersection = new Set([...a].filter((x) => b.has(x)));
|
|
230
|
+
const union = /* @__PURE__ */ new Set([...a, ...b]);
|
|
231
|
+
return intersection.size / union.size;
|
|
232
|
+
}
|
|
233
|
+
var FUZZY_THRESHOLD = 0.5;
|
|
234
|
+
var MIN_TOKENS_TO_QUALIFY = 3;
|
|
235
|
+
var WikiMemory = class {
|
|
236
|
+
db;
|
|
237
|
+
prefix;
|
|
238
|
+
options;
|
|
239
|
+
activeMaintenanceJobs = /* @__PURE__ */ new Set();
|
|
240
|
+
constructor(db, options) {
|
|
241
|
+
this.db = db;
|
|
242
|
+
this.options = options;
|
|
243
|
+
this.prefix = options.config?.tablePrefix || "llm_wiki_";
|
|
244
|
+
}
|
|
245
|
+
async setup() {
|
|
246
|
+
await setupDatabase(this.db, this.prefix);
|
|
247
|
+
const rows = await this.db.getAllAsync(`
|
|
248
|
+
SELECT rowid, source_ref FROM ${this.prefix}entries
|
|
249
|
+
WHERE source_ref IS NOT NULL
|
|
250
|
+
AND (
|
|
251
|
+
TRIM(source_ref) != source_ref
|
|
252
|
+
OR INSTR(source_ref, '/') > 0
|
|
253
|
+
OR INSTR(source_ref, '\\') > 0
|
|
254
|
+
OR INSTR(source_ref, CHAR(0)) > 0
|
|
255
|
+
OR source_ref GLOB '*[^-A-Za-z0-9._ ]*'
|
|
256
|
+
)
|
|
257
|
+
`);
|
|
258
|
+
await this.db.withTransactionAsync(async () => {
|
|
259
|
+
for (const row of rows) {
|
|
260
|
+
const normalized = normalizeSourceRef(row.source_ref);
|
|
261
|
+
if (normalized !== row.source_ref) {
|
|
262
|
+
await this.db.runAsync(
|
|
263
|
+
`UPDATE ${this.prefix}entries SET source_ref = ? WHERE rowid = ?`,
|
|
264
|
+
[normalized, row.rowid]
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
}
|
|
270
|
+
formatSearchQuery(query) {
|
|
271
|
+
const tokens = query.toLowerCase().replace(/[^a-z0-9\s]/g, "").split(/\s+/).filter((t) => t.length >= 3).slice(0, 6);
|
|
272
|
+
if (tokens.length === 0) return "";
|
|
273
|
+
return tokens.map((t) => `"${t}"*`).join(" OR ");
|
|
274
|
+
}
|
|
275
|
+
async read(entityId, query) {
|
|
276
|
+
const ftsQuery = this.formatSearchQuery(query);
|
|
277
|
+
const maxResults = this.options.config?.maxFtsResults || 10;
|
|
278
|
+
let factsPromise;
|
|
279
|
+
if (ftsQuery) {
|
|
280
|
+
factsPromise = this.db.getAllAsync(`
|
|
281
|
+
SELECT e.* FROM ${this.prefix}entries e
|
|
282
|
+
JOIN ${this.prefix}entries_fts fts ON e.rowid = fts.rowid
|
|
283
|
+
WHERE fts.${this.prefix}entries_fts MATCH ?
|
|
284
|
+
AND e.entity_id = ?
|
|
285
|
+
AND e.deleted_at IS NULL
|
|
286
|
+
ORDER BY e.confidence DESC, e.access_count DESC, e.updated_at DESC
|
|
287
|
+
LIMIT ?
|
|
288
|
+
`, [ftsQuery, entityId, maxResults]);
|
|
289
|
+
} else {
|
|
290
|
+
factsPromise = this.db.getAllAsync(`
|
|
291
|
+
SELECT * FROM ${this.prefix}entries
|
|
292
|
+
WHERE entity_id = ? AND deleted_at IS NULL
|
|
293
|
+
ORDER BY updated_at DESC
|
|
294
|
+
LIMIT ?
|
|
295
|
+
`, [entityId, maxResults]);
|
|
296
|
+
}
|
|
297
|
+
const tasksPromise = this.db.getAllAsync(`
|
|
298
|
+
SELECT * FROM ${this.prefix}tasks
|
|
299
|
+
WHERE entity_id = ? AND status IN ('pending', 'in_progress') AND deleted_at IS NULL
|
|
300
|
+
ORDER BY priority DESC, created_at ASC
|
|
301
|
+
`, [entityId]);
|
|
302
|
+
const eventsPromise = this.db.getAllAsync(`
|
|
303
|
+
SELECT * FROM ${this.prefix}events
|
|
304
|
+
WHERE entity_id = ?
|
|
305
|
+
ORDER BY created_at DESC
|
|
306
|
+
LIMIT 10
|
|
307
|
+
`, [entityId]);
|
|
308
|
+
const [factsRaw, tasks, events] = await Promise.all([factsPromise, tasksPromise, eventsPromise]);
|
|
309
|
+
if (ftsQuery && factsRaw.length > 0) {
|
|
310
|
+
const ids = factsRaw.map((f) => f.id);
|
|
311
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
312
|
+
const now = Date.now();
|
|
313
|
+
await this.db.runAsync(`
|
|
314
|
+
UPDATE ${this.prefix}entries
|
|
315
|
+
SET access_count = access_count + 1, last_accessed_at = ?
|
|
316
|
+
WHERE id IN (${placeholders})
|
|
317
|
+
`, [now, ...ids]);
|
|
318
|
+
}
|
|
319
|
+
const facts = factsRaw.map((f) => ({
|
|
320
|
+
...f,
|
|
321
|
+
tags: typeof f.tags === "string" ? JSON.parse(f.tags) : f.tags
|
|
322
|
+
}));
|
|
323
|
+
return { facts, tasks, events: events.reverse() };
|
|
324
|
+
}
|
|
325
|
+
async write(entityId, event) {
|
|
326
|
+
const id = generateId("evt_");
|
|
327
|
+
const now = Date.now();
|
|
328
|
+
let eventType = event.event_type;
|
|
329
|
+
if (!["observation", "decision", "action", "outcome"].includes(eventType)) {
|
|
330
|
+
eventType = "observation";
|
|
331
|
+
}
|
|
332
|
+
await this.db.runAsync(`
|
|
333
|
+
INSERT INTO ${this.prefix}events (id, entity_id, event_type, summary, related_entry_id, created_at)
|
|
334
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
335
|
+
`, [id, entityId, eventType, event.summary, event.related_entry_id || null, now]);
|
|
336
|
+
const threshold = this.options.config?.autoLibrarianThreshold || 20;
|
|
337
|
+
const [row, cp] = await Promise.all([
|
|
338
|
+
this.db.getFirstAsync(`SELECT COUNT(*) as count FROM ${this.prefix}events WHERE entity_id = ?`, [entityId]),
|
|
339
|
+
this.db.getFirstAsync(`SELECT * FROM ${this.prefix}checkpoints WHERE entity_id = ?`, [entityId])
|
|
340
|
+
]);
|
|
341
|
+
const count = row?.count || 0;
|
|
342
|
+
let memoryCheckpoint = cp?.memory_checkpoint || 0;
|
|
343
|
+
if (memoryCheckpoint > count) memoryCheckpoint = 0;
|
|
344
|
+
if (count - memoryCheckpoint >= threshold) {
|
|
345
|
+
const jobKey = `${this.prefix}:${entityId}`;
|
|
346
|
+
if (!this.activeMaintenanceJobs.has(jobKey)) {
|
|
347
|
+
this.activeMaintenanceJobs.add(jobKey);
|
|
348
|
+
this.runLibrarianThenMaybeHeal(entityId, count).catch(console.error).finally(() => this.activeMaintenanceJobs.delete(jobKey));
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
async runLibrarianThenMaybeHeal(entityId, currentEventCount) {
|
|
353
|
+
await this._doRunLibrarian(entityId);
|
|
354
|
+
await this.db.runAsync(`
|
|
355
|
+
INSERT INTO ${this.prefix}checkpoints (entity_id, memory_checkpoint)
|
|
356
|
+
VALUES (?, ?)
|
|
357
|
+
ON CONFLICT(entity_id) DO UPDATE SET memory_checkpoint = ?
|
|
358
|
+
`, [entityId, currentEventCount, currentEventCount]);
|
|
359
|
+
const autoHealThreshold = this.options.config?.autoHealThreshold || 100;
|
|
360
|
+
const cp = await this.db.getFirstAsync(`SELECT * FROM ${this.prefix}checkpoints WHERE entity_id = ?`, [entityId]);
|
|
361
|
+
let healCheckpoint = cp?.heal_checkpoint || 0;
|
|
362
|
+
if (healCheckpoint > currentEventCount) healCheckpoint = 0;
|
|
363
|
+
if (currentEventCount - healCheckpoint >= autoHealThreshold) {
|
|
364
|
+
await this._doRunHeal(entityId);
|
|
365
|
+
await this.db.runAsync(`
|
|
366
|
+
INSERT INTO ${this.prefix}checkpoints (entity_id, heal_checkpoint)
|
|
367
|
+
VALUES (?, ?)
|
|
368
|
+
ON CONFLICT(entity_id) DO UPDATE SET heal_checkpoint = ?
|
|
369
|
+
`, [entityId, currentEventCount, currentEventCount]);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
async _doRunLibrarian(entityId) {
|
|
373
|
+
const events = await this.db.getAllAsync(`
|
|
374
|
+
SELECT * FROM ${this.prefix}events
|
|
375
|
+
WHERE entity_id = ?
|
|
376
|
+
ORDER BY created_at DESC
|
|
377
|
+
LIMIT 50
|
|
378
|
+
`, [entityId]);
|
|
379
|
+
const currentFactsRows = await this.db.getAllAsync(`
|
|
380
|
+
SELECT * FROM ${this.prefix}entries
|
|
381
|
+
WHERE entity_id = ? AND deleted_at IS NULL
|
|
382
|
+
ORDER BY updated_at DESC
|
|
383
|
+
LIMIT 100
|
|
384
|
+
`, [entityId]);
|
|
385
|
+
const currentFacts = currentFactsRows.map((f) => ({
|
|
386
|
+
...f,
|
|
387
|
+
tags: typeof f.tags === "string" ? JSON.parse(f.tags) : f.tags
|
|
388
|
+
}));
|
|
389
|
+
const userPrompt = `Events:
|
|
390
|
+
${JSON.stringify(events.reverse(), null, 2)}
|
|
391
|
+
|
|
392
|
+
Current Facts:
|
|
393
|
+
${JSON.stringify(currentFacts, null, 2)}`;
|
|
394
|
+
const responseText = await this.options.llmProvider.generateText({
|
|
395
|
+
systemPrompt: LIBRARIAN_SYSTEM_PROMPT,
|
|
396
|
+
userPrompt
|
|
397
|
+
});
|
|
398
|
+
const result = parseJsonResponse(responseText);
|
|
399
|
+
const facts = Array.isArray(result.facts) ? result.facts : [];
|
|
400
|
+
const tasks = Array.isArray(result.tasks) ? result.tasks : [];
|
|
401
|
+
const validFacts = facts.map(validateFact).filter((f) => f !== null);
|
|
402
|
+
const validTasks = tasks.map(validateTask).filter((t) => t !== null);
|
|
403
|
+
const now = Date.now();
|
|
404
|
+
await this.db.withTransactionAsync(async () => {
|
|
405
|
+
for (const fact of validFacts) {
|
|
406
|
+
const newTokens = titleTokens(fact.title);
|
|
407
|
+
let skip = false;
|
|
408
|
+
if (newTokens.size >= MIN_TOKENS_TO_QUALIFY) {
|
|
409
|
+
for (const existing of currentFactsRows) {
|
|
410
|
+
if (existing.source_type !== "agent_inferred") continue;
|
|
411
|
+
const existingTokens = titleTokens(existing.title);
|
|
412
|
+
if (existingTokens.size >= MIN_TOKENS_TO_QUALIFY) {
|
|
413
|
+
if (jaccardScore(newTokens, existingTokens) >= FUZZY_THRESHOLD) {
|
|
414
|
+
skip = true;
|
|
415
|
+
break;
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
if (skip) continue;
|
|
421
|
+
const id = generateId("fact_");
|
|
422
|
+
await this.db.runAsync(`
|
|
423
|
+
INSERT INTO ${this.prefix}entries (id, entity_id, title, body, tags, confidence, source_type, created_at, updated_at)
|
|
424
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
425
|
+
`, [id, entityId, fact.title, fact.body, JSON.stringify(fact.tags), fact.confidence, "agent_inferred", now, now]);
|
|
426
|
+
}
|
|
427
|
+
for (const task of validTasks) {
|
|
428
|
+
const id = generateId("task_");
|
|
429
|
+
await this.db.runAsync(`
|
|
430
|
+
INSERT INTO ${this.prefix}tasks (id, entity_id, description, status, priority, created_at, updated_at)
|
|
431
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
432
|
+
`, [id, entityId, task.description, "pending", task.priority, now, now]);
|
|
433
|
+
}
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
async _doRunHeal(entityId) {
|
|
437
|
+
const now = Date.now();
|
|
438
|
+
const orphanAfterDays = this.options.config?.orphanAfterDays !== void 0 ? this.options.config.orphanAfterDays : 30;
|
|
439
|
+
const staleInferredAfterDays = this.options.config?.staleInferredAfterDays !== void 0 ? this.options.config.staleInferredAfterDays : 60;
|
|
440
|
+
const MS_PER_DAY = 24 * 60 * 60 * 1e3;
|
|
441
|
+
if (orphanAfterDays !== null && (typeof orphanAfterDays !== "number" || !Number.isFinite(orphanAfterDays) || orphanAfterDays < 0)) {
|
|
442
|
+
throw new Error("Invalid orphanAfterDays: must be a finite number >= 0 or null");
|
|
443
|
+
}
|
|
444
|
+
if (staleInferredAfterDays !== null && (typeof staleInferredAfterDays !== "number" || !Number.isFinite(staleInferredAfterDays) || staleInferredAfterDays < 0)) {
|
|
445
|
+
throw new Error("Invalid staleInferredAfterDays: must be a finite number >= 0 or null");
|
|
446
|
+
}
|
|
447
|
+
await this.db.withTransactionAsync(async () => {
|
|
448
|
+
if (orphanAfterDays !== null) {
|
|
449
|
+
const orphanThreshold = now - orphanAfterDays * MS_PER_DAY;
|
|
450
|
+
await this.db.runAsync(`
|
|
451
|
+
UPDATE ${this.prefix}entries
|
|
452
|
+
SET deleted_at = ?, updated_at = ?
|
|
453
|
+
WHERE entity_id = ? AND access_count = 0 AND created_at < ? AND source_type != 'user_document' AND deleted_at IS NULL
|
|
454
|
+
`, [now, now, entityId, orphanThreshold]);
|
|
455
|
+
}
|
|
456
|
+
if (staleInferredAfterDays !== null) {
|
|
457
|
+
const staleThreshold = now - staleInferredAfterDays * MS_PER_DAY;
|
|
458
|
+
await this.db.runAsync(`
|
|
459
|
+
UPDATE ${this.prefix}entries
|
|
460
|
+
SET confidence = 'tentative', updated_at = ?
|
|
461
|
+
WHERE entity_id = ? AND confidence = 'inferred' AND (last_accessed_at < ? OR (last_accessed_at IS NULL AND created_at < ?)) AND source_type != 'user_document' AND deleted_at IS NULL
|
|
462
|
+
`, [now, entityId, staleThreshold, staleThreshold]);
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
const allFactsRows = await this.db.getAllAsync(`SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL`, [entityId]);
|
|
466
|
+
const allTasks = await this.db.getAllAsync(`SELECT * FROM ${this.prefix}tasks WHERE entity_id = ? AND status IN ('pending', 'in_progress') AND deleted_at IS NULL`, [entityId]);
|
|
467
|
+
const recentEvents = await this.db.getAllAsync(`SELECT * FROM ${this.prefix}events WHERE entity_id = ? ORDER BY created_at DESC LIMIT 20`, [entityId]);
|
|
468
|
+
const healCandidates = allFactsRows.filter((f) => f.source_type !== "user_document");
|
|
469
|
+
const documentAnchors = allFactsRows.filter((f) => f.source_type === "user_document").map(({ id, title, source_ref }) => ({ id, title, source_ref }));
|
|
470
|
+
const userPrompt = `Heal Candidates:
|
|
471
|
+
${JSON.stringify(healCandidates.map((f) => ({ ...f, tags: typeof f.tags === "string" ? JSON.parse(f.tags) : f.tags })), null, 2)}
|
|
472
|
+
|
|
473
|
+
Document Anchors (DO NOT MODIFY OR DELETE):
|
|
474
|
+
${JSON.stringify(documentAnchors, null, 2)}
|
|
475
|
+
|
|
476
|
+
All Tasks:
|
|
477
|
+
${JSON.stringify(allTasks, null, 2)}
|
|
478
|
+
|
|
479
|
+
Recent Events:
|
|
480
|
+
${JSON.stringify(recentEvents, null, 2)}
|
|
481
|
+
|
|
482
|
+
The following document anchors are provided for contradiction detection only. Do not include them in \`downgraded\`, \`deleted\`, or \`newFacts\`.`;
|
|
483
|
+
const responseText = await this.options.llmProvider.generateText({
|
|
484
|
+
systemPrompt: HEAL_SYSTEM_PROMPT,
|
|
485
|
+
userPrompt
|
|
486
|
+
});
|
|
487
|
+
const result = parseJsonResponse(responseText);
|
|
488
|
+
const mutableIds = new Set(healCandidates.map((f) => f.id));
|
|
489
|
+
const downgraded = Array.isArray(result.downgraded) ? result.downgraded : [];
|
|
490
|
+
const deleted = Array.isArray(result.deleted) ? result.deleted : [];
|
|
491
|
+
const newFacts = Array.isArray(result.newFacts) ? result.newFacts : [];
|
|
492
|
+
const safeDowngraded = downgraded.filter((id) => mutableIds.has(id));
|
|
493
|
+
const safeDeleted = deleted.filter((id) => mutableIds.has(id));
|
|
494
|
+
const validNewFacts = newFacts.map(validateFact).filter((f) => f !== null);
|
|
495
|
+
await this.db.withTransactionAsync(async () => {
|
|
496
|
+
for (const id of safeDowngraded) {
|
|
497
|
+
await this.db.runAsync(`UPDATE ${this.prefix}entries SET confidence = 'tentative', updated_at = ? WHERE id = ? AND entity_id = ?`, [now, id, entityId]);
|
|
498
|
+
}
|
|
499
|
+
for (const id of safeDeleted) {
|
|
500
|
+
await this.db.runAsync(`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ?`, [now, now, id, entityId]);
|
|
501
|
+
}
|
|
502
|
+
for (const fact of validNewFacts) {
|
|
503
|
+
const id = generateId("fact_");
|
|
504
|
+
await this.db.runAsync(`
|
|
505
|
+
INSERT INTO ${this.prefix}entries (id, entity_id, title, body, tags, confidence, source_type, created_at, updated_at)
|
|
506
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
507
|
+
`, [id, entityId, fact.title, fact.body, JSON.stringify(fact.tags), fact.confidence, "agent_inferred", now, now]);
|
|
508
|
+
}
|
|
509
|
+
});
|
|
510
|
+
}
|
|
511
|
+
async runLibrarian(entityId) {
|
|
512
|
+
const jobKey = `${this.prefix}:${entityId}`;
|
|
513
|
+
if (this.activeMaintenanceJobs.has(jobKey)) return;
|
|
514
|
+
this.activeMaintenanceJobs.add(jobKey);
|
|
515
|
+
try {
|
|
516
|
+
await this._doRunLibrarian(entityId);
|
|
517
|
+
} finally {
|
|
518
|
+
this.activeMaintenanceJobs.delete(jobKey);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
async runHeal(entityId) {
|
|
522
|
+
const jobKey = `${this.prefix}:${entityId}`;
|
|
523
|
+
if (this.activeMaintenanceJobs.has(jobKey)) return;
|
|
524
|
+
this.activeMaintenanceJobs.add(jobKey);
|
|
525
|
+
try {
|
|
526
|
+
await this._doRunHeal(entityId);
|
|
527
|
+
} finally {
|
|
528
|
+
this.activeMaintenanceJobs.delete(jobKey);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
async forget(entityId, params) {
|
|
532
|
+
const now = Date.now();
|
|
533
|
+
let deletedEntries = 0;
|
|
534
|
+
let deletedTasks = 0;
|
|
535
|
+
if (params.clearAll) {
|
|
536
|
+
const [entriesRes, tasksRes] = await Promise.all([
|
|
537
|
+
this.db.runAsync(`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`, [now, now, entityId]),
|
|
538
|
+
this.db.runAsync(`UPDATE ${this.prefix}tasks SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`, [now, now, entityId])
|
|
539
|
+
]);
|
|
540
|
+
await this.db.runAsync(`UPDATE ${this.prefix}checkpoints SET memory_checkpoint = 0, heal_checkpoint = 0 WHERE entity_id = ?`, [entityId]);
|
|
541
|
+
deletedEntries = entriesRes.changes;
|
|
542
|
+
deletedTasks = tasksRes.changes;
|
|
543
|
+
} else {
|
|
544
|
+
const hasIdSelectors = params.entryId !== void 0 || params.taskId !== void 0;
|
|
545
|
+
const hasSourceSelectors = params.sourceRef !== void 0 || params.sourceHash !== void 0;
|
|
546
|
+
if (hasIdSelectors && hasSourceSelectors) {
|
|
547
|
+
throw new Error("forget() params are mutually exclusive: use entryId/taskId together, or sourceRef/sourceHash together, but not both in the same call");
|
|
548
|
+
}
|
|
549
|
+
const sourceRef = params.sourceRef !== void 0 ? normalizeSourceRef(params.sourceRef) : null;
|
|
550
|
+
if (params.sourceRef !== void 0 && !sourceRef) throw new Error("Invalid sourceRef");
|
|
551
|
+
const sourceHash = params.sourceHash !== void 0 ? normalizeSourceHash(params.sourceHash) : null;
|
|
552
|
+
if (params.sourceHash !== void 0 && !sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
|
|
553
|
+
const entryPromise = params.entryId ? this.db.runAsync(`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`, [now, now, params.entryId, entityId]) : null;
|
|
554
|
+
const taskPromise = params.taskId ? this.db.runAsync(`UPDATE ${this.prefix}tasks SET deleted_at = ?, updated_at = ? WHERE id = ? AND entity_id = ? AND deleted_at IS NULL`, [now, now, params.taskId, entityId]) : null;
|
|
555
|
+
let refPromise = null;
|
|
556
|
+
if (sourceRef || sourceHash) {
|
|
557
|
+
let q = `UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE entity_id = ? AND deleted_at IS NULL`;
|
|
558
|
+
const args = [now, now, entityId];
|
|
559
|
+
if (sourceRef) {
|
|
560
|
+
q += ` AND source_ref = ?`;
|
|
561
|
+
args.push(sourceRef);
|
|
562
|
+
}
|
|
563
|
+
if (sourceHash) {
|
|
564
|
+
q += ` AND source_hash = ?`;
|
|
565
|
+
args.push(sourceHash);
|
|
566
|
+
}
|
|
567
|
+
refPromise = this.db.runAsync(q, args);
|
|
568
|
+
}
|
|
569
|
+
const [entryResult, taskResult, refResult] = await Promise.all([
|
|
570
|
+
entryPromise ?? Promise.resolve(null),
|
|
571
|
+
taskPromise ?? Promise.resolve(null),
|
|
572
|
+
refPromise ?? Promise.resolve(null)
|
|
573
|
+
]);
|
|
574
|
+
if (entryResult) deletedEntries += entryResult.changes;
|
|
575
|
+
if (taskResult) deletedTasks += taskResult.changes;
|
|
576
|
+
if (refResult) deletedEntries += refResult.changes;
|
|
577
|
+
}
|
|
578
|
+
return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
|
|
579
|
+
}
|
|
580
|
+
async ingestDocument(entityId, params) {
|
|
581
|
+
const sourceRef = normalizeSourceRef(params.sourceRef);
|
|
582
|
+
if (!sourceRef) throw new Error("Invalid sourceRef");
|
|
583
|
+
const sourceHash = normalizeSourceHash(params.sourceHash);
|
|
584
|
+
if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
|
|
585
|
+
const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? 6e3;
|
|
586
|
+
if (!Number.isInteger(maxChunkLength) || maxChunkLength < 2) {
|
|
587
|
+
throw new Error("maxChunkLength must be an integer greater than or equal to 2");
|
|
588
|
+
}
|
|
589
|
+
if (typeof params.documentChunk !== "string") {
|
|
590
|
+
throw new Error(`documentChunk must be a string, received ${typeof params.documentChunk}`);
|
|
591
|
+
}
|
|
592
|
+
const chunks = [];
|
|
593
|
+
let truncated = false;
|
|
594
|
+
let text = params.documentChunk.trim();
|
|
595
|
+
if (text.length === 0) {
|
|
596
|
+
return { truncated: false, chunks: 0 };
|
|
597
|
+
}
|
|
598
|
+
while (text.length > 0) {
|
|
599
|
+
if (text.length <= maxChunkLength) {
|
|
600
|
+
chunks.push(text);
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
const searchArea = text.slice(0, maxChunkLength + 1);
|
|
604
|
+
const match = searchArea.match(/[.!?]\s+(?![\s\S]*[.!?]\s+)/);
|
|
605
|
+
if (match && match.index !== void 0) {
|
|
606
|
+
const splitPoint = Math.min(match.index + match[0].length, maxChunkLength);
|
|
607
|
+
const chunk = safeSlice(text, 0, splitPoint);
|
|
608
|
+
chunks.push(chunk);
|
|
609
|
+
text = text.slice(chunk.length);
|
|
610
|
+
} else {
|
|
611
|
+
truncated = true;
|
|
612
|
+
const chunk = safeSlice(text, 0, maxChunkLength);
|
|
613
|
+
chunks.push(chunk);
|
|
614
|
+
text = text.slice(chunk.length);
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
const allValidFacts = [];
|
|
618
|
+
for (const chunk of chunks) {
|
|
619
|
+
const userPrompt = `Document Chunk:
|
|
620
|
+
${chunk}`;
|
|
621
|
+
const responseText = await this.options.llmProvider.generateText({
|
|
622
|
+
systemPrompt: INGEST_SYSTEM_PROMPT,
|
|
623
|
+
userPrompt
|
|
624
|
+
});
|
|
625
|
+
const result = parseJsonResponse(responseText);
|
|
626
|
+
const validFacts = (Array.isArray(result.facts) ? result.facts : []).map(validateFact).filter((f) => f !== null);
|
|
627
|
+
allValidFacts.push(...validFacts);
|
|
628
|
+
}
|
|
629
|
+
const now = Date.now();
|
|
630
|
+
await this.db.withTransactionAsync(async () => {
|
|
631
|
+
await this.db.runAsync(`UPDATE ${this.prefix}entries SET deleted_at = ?, updated_at = ? WHERE source_ref = ? AND entity_id = ? AND deleted_at IS NULL`, [now, now, sourceRef, entityId]);
|
|
632
|
+
for (const fact of allValidFacts) {
|
|
633
|
+
const id = generateId("fact_");
|
|
634
|
+
await this.db.runAsync(`
|
|
635
|
+
INSERT INTO ${this.prefix}entries (id, entity_id, title, body, tags, confidence, source_type, source_hash, source_ref, created_at, updated_at)
|
|
636
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
637
|
+
`, [id, entityId, fact.title, fact.body, JSON.stringify(fact.tags), fact.confidence, "user_document", sourceHash, sourceRef, now, now]);
|
|
638
|
+
}
|
|
639
|
+
});
|
|
640
|
+
return { truncated, chunks: chunks.length };
|
|
641
|
+
}
|
|
642
|
+
};
|
|
643
|
+
|
|
644
|
+
// src/index.ts
|
|
645
|
+
function createWiki(db, options) {
|
|
646
|
+
return new WikiMemory(db, options);
|
|
647
|
+
}
|
|
648
|
+
export {
|
|
649
|
+
WikiMemory,
|
|
650
|
+
createWiki
|
|
651
|
+
};
|