@equationalapplications/core-llm-wiki 9.1.0 → 9.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-SIJD5GEF.mjs → chunk-E3JCZMJL.mjs} +777 -19
- package/dist/chunk-E3JCZMJL.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1396 -329
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +515 -206
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-CmcCGx0_.d.mts → testing-BQScWWSA.d.mts} +189 -16
- package/dist/{testing-CmcCGx0_.d.ts → testing-BQScWWSA.d.ts} +189 -16
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +615 -29
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-SIJD5GEF.mjs.map +0 -1
package/dist/testing.js
CHANGED
|
@@ -731,7 +731,12 @@ var SEVERITY = {
|
|
|
731
731
|
guidance_too_long: "warn",
|
|
732
732
|
guidance_resolver_failed: "warn",
|
|
733
733
|
source_pointer_unresolved: "warn",
|
|
734
|
-
source_pointer_invalid: "warn"
|
|
734
|
+
source_pointer_invalid: "warn",
|
|
735
|
+
source_store_source_too_large: "warn",
|
|
736
|
+
source_store_budget_exceeded: "warn",
|
|
737
|
+
source_store_hash_mismatch: "warn",
|
|
738
|
+
source_store_duplicate_hash: "warn",
|
|
739
|
+
source_store_text_not_storable: "warn"
|
|
735
740
|
};
|
|
736
741
|
var MESSAGE = {
|
|
737
742
|
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
@@ -761,7 +766,12 @@ var MESSAGE = {
|
|
|
761
766
|
guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
|
|
762
767
|
guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
|
|
763
768
|
source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
|
|
764
|
-
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
|
|
769
|
+
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
|
|
770
|
+
source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
|
|
771
|
+
source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
|
|
772
|
+
source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
|
|
773
|
+
source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
|
|
774
|
+
source_store_text_not_storable: "A source document text could not be stored as given."
|
|
765
775
|
};
|
|
766
776
|
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
767
777
|
function copyDetail(detail) {
|
|
@@ -1241,6 +1251,274 @@ function entitySummaryMetaKey(entityId) {
|
|
|
1241
1251
|
return `entity_summary:${entityId}`;
|
|
1242
1252
|
}
|
|
1243
1253
|
var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
|
|
1254
|
+
function generateId(prefix = "") {
|
|
1255
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
1256
|
+
return prefix + crypto.randomUUID().replace(/-/g, "").substring(0, 24);
|
|
1257
|
+
}
|
|
1258
|
+
if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
|
|
1259
|
+
const bytes = new Uint8Array(16);
|
|
1260
|
+
crypto.getRandomValues(bytes);
|
|
1261
|
+
return prefix + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("").substring(0, 24);
|
|
1262
|
+
}
|
|
1263
|
+
throw new Error(
|
|
1264
|
+
"generateId: no cryptographically secure random source available (crypto.randomUUID and crypto.getRandomValues are both missing, and no configureRandomSource() injection was provided)."
|
|
1265
|
+
);
|
|
1266
|
+
}
|
|
1267
|
+
|
|
1268
|
+
// src/utils/passageCutter.ts
|
|
1269
|
+
var MAX_PASSAGE_UNITS = 12e3;
|
|
1270
|
+
var WHITESPACE = /\s/;
|
|
1271
|
+
function isHigh(code) {
|
|
1272
|
+
return code >= 55296 && code <= 56319;
|
|
1273
|
+
}
|
|
1274
|
+
function isLow(code) {
|
|
1275
|
+
return code >= 56320 && code <= 57343;
|
|
1276
|
+
}
|
|
1277
|
+
function cutPassages(text, maxUnits = MAX_PASSAGE_UNITS) {
|
|
1278
|
+
const limit = Math.max(2, Math.floor(maxUnits));
|
|
1279
|
+
const spans = [];
|
|
1280
|
+
let start = 0;
|
|
1281
|
+
while (start < text.length) {
|
|
1282
|
+
if (text.length - start <= limit) {
|
|
1283
|
+
spans.push({ start, end: text.length });
|
|
1284
|
+
break;
|
|
1285
|
+
}
|
|
1286
|
+
let end = start + limit;
|
|
1287
|
+
let cut = -1;
|
|
1288
|
+
for (let i = end - 1; i > start; i--) {
|
|
1289
|
+
if (WHITESPACE.test(text[i])) {
|
|
1290
|
+
cut = i + 1;
|
|
1291
|
+
break;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
if (cut > start) {
|
|
1295
|
+
end = cut;
|
|
1296
|
+
} else if (isHigh(text.charCodeAt(end - 1)) && isLow(text.charCodeAt(end))) {
|
|
1297
|
+
end -= 1;
|
|
1298
|
+
}
|
|
1299
|
+
spans.push({ start, end });
|
|
1300
|
+
start = end;
|
|
1301
|
+
}
|
|
1302
|
+
return spans;
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// src/utils/sha256.ts
|
|
1306
|
+
var K = new Uint32Array([
|
|
1307
|
+
1116352408,
|
|
1308
|
+
1899447441,
|
|
1309
|
+
3049323471,
|
|
1310
|
+
3921009573,
|
|
1311
|
+
961987163,
|
|
1312
|
+
1508970993,
|
|
1313
|
+
2453635748,
|
|
1314
|
+
2870763221,
|
|
1315
|
+
3624381080,
|
|
1316
|
+
310598401,
|
|
1317
|
+
607225278,
|
|
1318
|
+
1426881987,
|
|
1319
|
+
1925078388,
|
|
1320
|
+
2162078206,
|
|
1321
|
+
2614888103,
|
|
1322
|
+
3248222580,
|
|
1323
|
+
3835390401,
|
|
1324
|
+
4022224774,
|
|
1325
|
+
264347078,
|
|
1326
|
+
604807628,
|
|
1327
|
+
770255983,
|
|
1328
|
+
1249150122,
|
|
1329
|
+
1555081692,
|
|
1330
|
+
1996064986,
|
|
1331
|
+
2554220882,
|
|
1332
|
+
2821834349,
|
|
1333
|
+
2952996808,
|
|
1334
|
+
3210313671,
|
|
1335
|
+
3336571891,
|
|
1336
|
+
3584528711,
|
|
1337
|
+
113926993,
|
|
1338
|
+
338241895,
|
|
1339
|
+
666307205,
|
|
1340
|
+
773529912,
|
|
1341
|
+
1294757372,
|
|
1342
|
+
1396182291,
|
|
1343
|
+
1695183700,
|
|
1344
|
+
1986661051,
|
|
1345
|
+
2177026350,
|
|
1346
|
+
2456956037,
|
|
1347
|
+
2730485921,
|
|
1348
|
+
2820302411,
|
|
1349
|
+
3259730800,
|
|
1350
|
+
3345764771,
|
|
1351
|
+
3516065817,
|
|
1352
|
+
3600352804,
|
|
1353
|
+
4094571909,
|
|
1354
|
+
275423344,
|
|
1355
|
+
430227734,
|
|
1356
|
+
506948616,
|
|
1357
|
+
659060556,
|
|
1358
|
+
883997877,
|
|
1359
|
+
958139571,
|
|
1360
|
+
1322822218,
|
|
1361
|
+
1537002063,
|
|
1362
|
+
1747873779,
|
|
1363
|
+
1955562222,
|
|
1364
|
+
2024104815,
|
|
1365
|
+
2227730452,
|
|
1366
|
+
2361852424,
|
|
1367
|
+
2428436474,
|
|
1368
|
+
2756734187,
|
|
1369
|
+
3204031479,
|
|
1370
|
+
3329325298
|
|
1371
|
+
]);
|
|
1372
|
+
var rotr = (x, n) => x >>> n | x << 32 - n;
|
|
1373
|
+
var IV = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
|
|
1374
|
+
function compress(H, W, view, off) {
|
|
1375
|
+
for (let t = 0; t < 16; t++) W[t] = view.getUint32(off + t * 4);
|
|
1376
|
+
for (let t = 16; t < 64; t++) {
|
|
1377
|
+
const s0 = rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ W[t - 15] >>> 3;
|
|
1378
|
+
const s1 = rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ W[t - 2] >>> 10;
|
|
1379
|
+
W[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;
|
|
1380
|
+
}
|
|
1381
|
+
let a = H[0], b = H[1], c = H[2], d = H[3], e = H[4], f = H[5], g = H[6], h = H[7];
|
|
1382
|
+
for (let t = 0; t < 64; t++) {
|
|
1383
|
+
const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
1384
|
+
const ch = e & f ^ ~e & g;
|
|
1385
|
+
const t1 = h + S1 + ch + K[t] + W[t] >>> 0;
|
|
1386
|
+
const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
|
|
1387
|
+
const maj = a & b ^ a & c ^ b & c;
|
|
1388
|
+
const t2 = S0 + maj >>> 0;
|
|
1389
|
+
h = g;
|
|
1390
|
+
g = f;
|
|
1391
|
+
f = e;
|
|
1392
|
+
e = d + t1 >>> 0;
|
|
1393
|
+
d = c;
|
|
1394
|
+
c = b;
|
|
1395
|
+
b = a;
|
|
1396
|
+
a = t1 + t2 >>> 0;
|
|
1397
|
+
}
|
|
1398
|
+
H[0] = H[0] + a >>> 0;
|
|
1399
|
+
H[1] = H[1] + b >>> 0;
|
|
1400
|
+
H[2] = H[2] + c >>> 0;
|
|
1401
|
+
H[3] = H[3] + d >>> 0;
|
|
1402
|
+
H[4] = H[4] + e >>> 0;
|
|
1403
|
+
H[5] = H[5] + f >>> 0;
|
|
1404
|
+
H[6] = H[6] + g >>> 0;
|
|
1405
|
+
H[7] = H[7] + h >>> 0;
|
|
1406
|
+
}
|
|
1407
|
+
function sha256(bytes) {
|
|
1408
|
+
const H = new Uint32Array(IV);
|
|
1409
|
+
const W = new Uint32Array(64);
|
|
1410
|
+
const whole = bytes.length - bytes.length % 64;
|
|
1411
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
1412
|
+
for (let off = 0; off < whole; off += 64) compress(H, W, view, off);
|
|
1413
|
+
const rest = bytes.subarray(whole);
|
|
1414
|
+
const bitLen = bytes.length * 8;
|
|
1415
|
+
const padded = new Uint8Array(rest.length + 9 + 63 >> 6 << 6);
|
|
1416
|
+
padded.set(rest);
|
|
1417
|
+
padded[rest.length] = 128;
|
|
1418
|
+
const pv = new DataView(padded.buffer);
|
|
1419
|
+
pv.setUint32(padded.length - 8, Math.floor(bitLen / 4294967296));
|
|
1420
|
+
pv.setUint32(padded.length - 4, bitLen >>> 0);
|
|
1421
|
+
for (let off = 0; off < padded.length; off += 64) compress(H, W, pv, off);
|
|
1422
|
+
const out = new Uint8Array(32);
|
|
1423
|
+
const outView = new DataView(out.buffer);
|
|
1424
|
+
for (let i = 0; i < 8; i++) outView.setUint32(i * 4, H[i]);
|
|
1425
|
+
return out;
|
|
1426
|
+
}
|
|
1427
|
+
function utf8Encode(s) {
|
|
1428
|
+
const out = [];
|
|
1429
|
+
for (let i = 0; i < s.length; i++) {
|
|
1430
|
+
let cp = s.charCodeAt(i);
|
|
1431
|
+
if (cp >= 55296 && cp <= 56319) {
|
|
1432
|
+
const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
|
|
1433
|
+
if (next >= 56320 && next <= 57343) {
|
|
1434
|
+
cp = 65536 + (cp - 55296 << 10) + (next - 56320);
|
|
1435
|
+
i++;
|
|
1436
|
+
} else {
|
|
1437
|
+
cp = 65533;
|
|
1438
|
+
}
|
|
1439
|
+
} else if (cp >= 56320 && cp <= 57343) {
|
|
1440
|
+
cp = 65533;
|
|
1441
|
+
}
|
|
1442
|
+
if (cp < 128) out.push(cp);
|
|
1443
|
+
else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63);
|
|
1444
|
+
else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
|
|
1445
|
+
else out.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
|
|
1446
|
+
}
|
|
1447
|
+
return Uint8Array.from(out);
|
|
1448
|
+
}
|
|
1449
|
+
function sha256Hex(text) {
|
|
1450
|
+
let hex = "";
|
|
1451
|
+
for (const b of sha256(utf8Encode(text))) hex += b.toString(16).padStart(2, "0");
|
|
1452
|
+
return hex;
|
|
1453
|
+
}
|
|
1454
|
+
|
|
1455
|
+
// src/services/sourceStoreUpsert.ts
|
|
1456
|
+
var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
|
|
1457
|
+
async function upsertStoredSource(tx, prefix, entityId, src, limits, onRefusal, opts = {}) {
|
|
1458
|
+
const { sourceRef, sourceHash, text } = src;
|
|
1459
|
+
const refuse = (code) => {
|
|
1460
|
+
onRefusal(code);
|
|
1461
|
+
return { status: "refused" };
|
|
1462
|
+
};
|
|
1463
|
+
if (text.includes("\0") || LONE_SURROGATE.test(text)) return refuse("source_store_text_not_storable");
|
|
1464
|
+
if (text.length > limits.maxCharsPerSource) return refuse("source_store_source_too_large");
|
|
1465
|
+
const textHash = sha256Hex(text);
|
|
1466
|
+
const charCount = text.length;
|
|
1467
|
+
const docs = `${prefix}source_documents`;
|
|
1468
|
+
const passages = `${prefix}source_passages`;
|
|
1469
|
+
const registry = `${prefix}source_ref_index`;
|
|
1470
|
+
const existing = await tx.getFirstAsync(
|
|
1471
|
+
`SELECT id, source_hash, text_hash, char_count, created_at FROM ${docs}
|
|
1472
|
+
WHERE entity_id = ? AND source_ref = ?`,
|
|
1473
|
+
[entityId, sourceRef]
|
|
1474
|
+
);
|
|
1475
|
+
if (opts.idempotentSamePair && existing && existing.source_hash === sourceHash) {
|
|
1476
|
+
if (existing.text_hash !== textHash) return refuse("source_store_hash_mismatch");
|
|
1477
|
+
const row = await tx.getFirstAsync(
|
|
1478
|
+
`SELECT COUNT(*) AS n FROM ${passages} WHERE entity_id = ? AND document_id = ?`,
|
|
1479
|
+
[entityId, existing.id]
|
|
1480
|
+
);
|
|
1481
|
+
return { status: "stored", charCount: existing.char_count, passageCount: row?.n ?? 0, storedAt: existing.created_at };
|
|
1482
|
+
}
|
|
1483
|
+
const heldByStore = await tx.getFirstAsync(
|
|
1484
|
+
`SELECT source_ref FROM ${docs} WHERE entity_id = ? AND source_hash = ? AND source_ref <> ?`,
|
|
1485
|
+
[entityId, sourceHash, sourceRef]
|
|
1486
|
+
);
|
|
1487
|
+
const heldByFacts = await tx.getFirstAsync(
|
|
1488
|
+
`SELECT source_ref FROM ${registry}
|
|
1489
|
+
WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL AND source_ref <> ?`,
|
|
1490
|
+
[entityId, sourceHash, sourceRef]
|
|
1491
|
+
);
|
|
1492
|
+
if (heldByStore || heldByFacts) return refuse("source_store_duplicate_hash");
|
|
1493
|
+
const total = await tx.getFirstAsync(
|
|
1494
|
+
`SELECT COALESCE(SUM(char_count), 0) AS n FROM ${docs} WHERE entity_id = ? AND source_ref <> ?`,
|
|
1495
|
+
[entityId, sourceRef]
|
|
1496
|
+
);
|
|
1497
|
+
if ((total?.n ?? 0) + charCount > limits.maxTotalChars) return refuse("source_store_budget_exceeded");
|
|
1498
|
+
if (existing) {
|
|
1499
|
+
await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ? AND document_id = ?`, [entityId, existing.id]);
|
|
1500
|
+
await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ? AND id = ?`, [entityId, existing.id]);
|
|
1501
|
+
}
|
|
1502
|
+
const id = generateId("sdoc_");
|
|
1503
|
+
const storedAt = typeof src.storedAt === "number" && Number.isFinite(src.storedAt) ? src.storedAt : Date.now();
|
|
1504
|
+
await tx.runAsync(
|
|
1505
|
+
`INSERT INTO ${docs} (id, entity_id, source_ref, source_hash, text, text_hash, char_count, created_at)
|
|
1506
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
1507
|
+
[id, entityId, sourceRef, sourceHash, text, textHash, charCount, storedAt]
|
|
1508
|
+
);
|
|
1509
|
+
const spans = cutPassages(text);
|
|
1510
|
+
for (let seq = 0; seq < spans.length; seq++) {
|
|
1511
|
+
await tx.runAsync(
|
|
1512
|
+
`INSERT INTO ${passages} (id, entity_id, document_id, seq, start_offset, end_offset) VALUES (?, ?, ?, ?, ?, ?)`,
|
|
1513
|
+
[generateId("spas_"), entityId, id, seq, spans[seq].start, spans[seq].end]
|
|
1514
|
+
);
|
|
1515
|
+
}
|
|
1516
|
+
return { status: "stored", charCount, passageCount: spans.length, storedAt };
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
// src/services/SourceStoreService.ts
|
|
1520
|
+
var DEFAULT_MAX_CHARS_PER_SOURCE = 2e5;
|
|
1521
|
+
var DEFAULT_MAX_TOTAL_CHARS = 5e6;
|
|
1244
1522
|
|
|
1245
1523
|
// src/utils/sourcePointer.ts
|
|
1246
1524
|
var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
|
|
@@ -1364,7 +1642,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
|
|
|
1364
1642
|
var IMPORT_TITLE_MAX = 500;
|
|
1365
1643
|
var IMPORT_BODY_MAX = 8e3;
|
|
1366
1644
|
var ImportExportService = class {
|
|
1367
|
-
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
|
|
1645
|
+
constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
|
|
1368
1646
|
this.db = db;
|
|
1369
1647
|
this.entryRepo = entryRepo;
|
|
1370
1648
|
this.taskRepo = taskRepo;
|
|
@@ -1376,6 +1654,7 @@ var ImportExportService = class {
|
|
|
1376
1654
|
this.embeddingService = embeddingService;
|
|
1377
1655
|
this.options = options;
|
|
1378
1656
|
this.vectorRemoval = vectorRemoval;
|
|
1657
|
+
this.prefix = prefix;
|
|
1379
1658
|
}
|
|
1380
1659
|
async exportDump(entityIds) {
|
|
1381
1660
|
let ids;
|
|
@@ -1383,6 +1662,13 @@ var ImportExportService = class {
|
|
|
1383
1662
|
ids = Array.from(new Set(entityIds));
|
|
1384
1663
|
} else {
|
|
1385
1664
|
ids = await this.metadataRepo.getDistinctEntityIds();
|
|
1665
|
+
const prefix = this.storePrefix();
|
|
1666
|
+
if (prefix !== void 0 && await this.storePresent(prefix)) {
|
|
1667
|
+
const rows = await this.db.getAllAsync(
|
|
1668
|
+
`SELECT DISTINCT entity_id FROM ${prefix}source_documents`
|
|
1669
|
+
);
|
|
1670
|
+
ids = Array.from(/* @__PURE__ */ new Set([...ids, ...rows.map((r) => r.entity_id)])).sort();
|
|
1671
|
+
}
|
|
1386
1672
|
}
|
|
1387
1673
|
const entities = {};
|
|
1388
1674
|
const BATCH = 3;
|
|
@@ -1390,10 +1676,11 @@ var ImportExportService = class {
|
|
|
1390
1676
|
const batch = ids.slice(i, i + BATCH);
|
|
1391
1677
|
const batchResults = await Promise.all(
|
|
1392
1678
|
batch.map(
|
|
1393
|
-
async (id) =>
|
|
1394
|
-
id,
|
|
1395
|
-
await this.
|
|
1396
|
-
|
|
1679
|
+
async (id) => {
|
|
1680
|
+
const bundle = await this.getFullBundle(id, { includeBlobs: true });
|
|
1681
|
+
const storedSources = await this.exportStoredSources(id);
|
|
1682
|
+
return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
|
|
1683
|
+
}
|
|
1397
1684
|
)
|
|
1398
1685
|
);
|
|
1399
1686
|
for (const [id, bundle] of batchResults) {
|
|
@@ -1404,16 +1691,96 @@ var ImportExportService = class {
|
|
|
1404
1691
|
}
|
|
1405
1692
|
async importDump(dump, opts) {
|
|
1406
1693
|
const merge = opts?.merge ?? false;
|
|
1694
|
+
const skippedSources = [];
|
|
1407
1695
|
const entityIds = Object.keys(dump.entities);
|
|
1408
1696
|
this.jobManager.acquireImportLocks(entityIds);
|
|
1409
1697
|
try {
|
|
1410
1698
|
await this.assertNoLegacySourceTypes();
|
|
1411
1699
|
for (const [entityId, bundle] of Object.entries(dump.entities)) {
|
|
1412
|
-
await this.doImportEntity(entityId, bundle, merge);
|
|
1700
|
+
skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
|
|
1413
1701
|
}
|
|
1414
1702
|
} finally {
|
|
1415
1703
|
this.jobManager.releaseImportLocks(entityIds);
|
|
1416
1704
|
}
|
|
1705
|
+
return { skippedSources };
|
|
1706
|
+
}
|
|
1707
|
+
storePrefix() {
|
|
1708
|
+
return typeof this.prefix === "string" ? this.prefix : void 0;
|
|
1709
|
+
}
|
|
1710
|
+
// `source_ref_index` needs no check: the v9 migration (add_source_ref_index) creates it, and the
|
|
1711
|
+
// store tables come from v17, which only runs after v9 — so it exists whenever they do.
|
|
1712
|
+
async storePresent(prefix, tx) {
|
|
1713
|
+
return await this.metadataRepo.tableExists(`${prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${prefix}source_passages`, tx);
|
|
1714
|
+
}
|
|
1715
|
+
/** Spec source-store §8: stored sources for one exported entity; [] when none. */
|
|
1716
|
+
async exportStoredSources(entityId) {
|
|
1717
|
+
const prefix = this.storePrefix();
|
|
1718
|
+
if (prefix === void 0 || !await this.storePresent(prefix)) return [];
|
|
1719
|
+
const docs = await this.db.getAllAsync(
|
|
1720
|
+
`SELECT id, source_ref, source_hash, text, text_hash, char_count, created_at FROM ${prefix}source_documents
|
|
1721
|
+
WHERE entity_id = ? ORDER BY source_ref COLLATE BINARY`,
|
|
1722
|
+
[entityId]
|
|
1723
|
+
);
|
|
1724
|
+
const out = [];
|
|
1725
|
+
for (const d of docs) {
|
|
1726
|
+
const ps = await this.db.getAllAsync(
|
|
1727
|
+
`SELECT seq, start_offset, end_offset FROM ${prefix}source_passages
|
|
1728
|
+
WHERE entity_id = ? AND document_id = ? ORDER BY seq`,
|
|
1729
|
+
[entityId, d.id]
|
|
1730
|
+
);
|
|
1731
|
+
out.push({
|
|
1732
|
+
sourceRef: d.source_ref,
|
|
1733
|
+
sourceHash: d.source_hash,
|
|
1734
|
+
text: d.text,
|
|
1735
|
+
textHash: d.text_hash,
|
|
1736
|
+
charCount: Number(d.char_count),
|
|
1737
|
+
storedAt: Number(d.created_at),
|
|
1738
|
+
passages: ps.map((p) => ({ seq: Number(p.seq), startOffset: Number(p.start_offset), endOffset: Number(p.end_offset) }))
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
return out;
|
|
1742
|
+
}
|
|
1743
|
+
/**
|
|
1744
|
+
* Spec source-store §8/§9 import step, inside the import transaction. One
|
|
1745
|
+
* source at a time; a refusal skips that source only. Uses the
|
|
1746
|
+
* same upsert helper as SourceStoreService.storeSource, inside this transaction. A ref already stored is replaced: the dump is the
|
|
1747
|
+
* truth for that ref (so no hash_mismatch refusal on import).
|
|
1748
|
+
*/
|
|
1749
|
+
async importStoredSources(tx, entityId, sources, merge, skipped, deferredDiagnostics) {
|
|
1750
|
+
const prefix = this.storePrefix();
|
|
1751
|
+
if (prefix === void 0) return;
|
|
1752
|
+
if (merge && !sources?.length) return;
|
|
1753
|
+
if (!await this.storePresent(prefix, tx)) return;
|
|
1754
|
+
const docs = `${prefix}source_documents`;
|
|
1755
|
+
const passages = `${prefix}source_passages`;
|
|
1756
|
+
if (!merge) {
|
|
1757
|
+
await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ?`, [entityId]);
|
|
1758
|
+
await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ?`, [entityId]);
|
|
1759
|
+
}
|
|
1760
|
+
const cfg = this.options.config?.sourceStore;
|
|
1761
|
+
const lim = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : d;
|
|
1762
|
+
const limits = {
|
|
1763
|
+
maxCharsPerSource: lim(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
|
|
1764
|
+
maxTotalChars: lim(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
|
|
1765
|
+
};
|
|
1766
|
+
for (const src of sources ?? []) {
|
|
1767
|
+
const sourceRef = normalizeSourceRef(src?.sourceRef);
|
|
1768
|
+
const sourceHash = normalizeSourceHash(src?.sourceHash);
|
|
1769
|
+
if (!sourceRef || !sourceHash || typeof src.text !== "string") {
|
|
1770
|
+
throw new Error(`importDump: invalid stored source for entity "${entityId}" (sourceRef, sourceHash and text are required)`);
|
|
1771
|
+
}
|
|
1772
|
+
await upsertStoredSource(
|
|
1773
|
+
tx,
|
|
1774
|
+
prefix,
|
|
1775
|
+
entityId,
|
|
1776
|
+
{ sourceRef, sourceHash, text: src.text, storedAt: src.storedAt },
|
|
1777
|
+
limits,
|
|
1778
|
+
(code) => {
|
|
1779
|
+
skipped.push({ sourceRef, code });
|
|
1780
|
+
deferredDiagnostics.push({ code, operation: "importDump", trigger: "call", entityId, detail: { sourceRef } });
|
|
1781
|
+
}
|
|
1782
|
+
);
|
|
1783
|
+
}
|
|
1417
1784
|
}
|
|
1418
1785
|
async getFullBundle(entityId, opts) {
|
|
1419
1786
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
@@ -1452,6 +1819,8 @@ var ImportExportService = class {
|
|
|
1452
1819
|
}
|
|
1453
1820
|
/** Single-entity import transaction + post-processing; package-internal hook for tests. */
|
|
1454
1821
|
async doImportEntity(entityId, bundle, merge) {
|
|
1822
|
+
const skippedSources = [];
|
|
1823
|
+
const refusalDiagnostics = [];
|
|
1455
1824
|
const upsertedFactIds = /* @__PURE__ */ new Set();
|
|
1456
1825
|
const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
|
|
1457
1826
|
const factsWithPreservedBlob = /* @__PURE__ */ new Map();
|
|
@@ -1729,7 +2098,9 @@ var ImportExportService = class {
|
|
|
1729
2098
|
tx
|
|
1730
2099
|
);
|
|
1731
2100
|
}
|
|
2101
|
+
await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
|
|
1732
2102
|
});
|
|
2103
|
+
for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
|
|
1733
2104
|
if (clampedEvents > 0) {
|
|
1734
2105
|
emitDiagnostic(this.options, {
|
|
1735
2106
|
code: "event_created_at_clamped",
|
|
@@ -1897,6 +2268,7 @@ var ImportExportService = class {
|
|
|
1897
2268
|
} finally {
|
|
1898
2269
|
this.searchService.evictCache(entityId);
|
|
1899
2270
|
}
|
|
2271
|
+
return skippedSources;
|
|
1900
2272
|
}
|
|
1901
2273
|
_warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
|
|
1902
2274
|
console.warn(
|
|
@@ -1931,19 +2303,6 @@ After running the migration SQL, restart your application.`
|
|
|
1931
2303
|
);
|
|
1932
2304
|
}
|
|
1933
2305
|
};
|
|
1934
|
-
function generateId(prefix = "") {
|
|
1935
|
-
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
1936
|
-
return prefix + crypto.randomUUID().replace(/-/g, "").substring(0, 24);
|
|
1937
|
-
}
|
|
1938
|
-
if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
|
|
1939
|
-
const bytes = new Uint8Array(16);
|
|
1940
|
-
crypto.getRandomValues(bytes);
|
|
1941
|
-
return prefix + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("").substring(0, 24);
|
|
1942
|
-
}
|
|
1943
|
-
throw new Error(
|
|
1944
|
-
"generateId: no cryptographically secure random source available (crypto.randomUUID and crypto.getRandomValues are both missing, and no configureRandomSource() injection was provided)."
|
|
1945
|
-
);
|
|
1946
|
-
}
|
|
1947
2306
|
|
|
1948
2307
|
// src/prompts.ts
|
|
1949
2308
|
var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
|
|
@@ -3905,6 +4264,57 @@ var MIGRATIONS = [
|
|
|
3905
4264
|
await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
|
|
3906
4265
|
}
|
|
3907
4266
|
}
|
|
4267
|
+
},
|
|
4268
|
+
{
|
|
4269
|
+
version: 17,
|
|
4270
|
+
description: "add_source_store",
|
|
4271
|
+
run: async (db, prefix) => {
|
|
4272
|
+
const expected = {
|
|
4273
|
+
source_documents: ["id", "entity_id", "source_ref", "source_hash", "text", "text_hash", "char_count", "created_at"],
|
|
4274
|
+
source_passages: ["id", "entity_id", "document_id", "seq", "start_offset", "end_offset"]
|
|
4275
|
+
};
|
|
4276
|
+
for (const [table, want] of Object.entries(expected)) {
|
|
4277
|
+
const full = `${prefix}${table}`;
|
|
4278
|
+
const cols = (await db.getAllAsync(`PRAGMA table_info(${full})`)).map((c) => c.name);
|
|
4279
|
+
if (cols.length === 0) continue;
|
|
4280
|
+
const same = cols.length === want.length && want.every((c) => cols.includes(c));
|
|
4281
|
+
if (!same) {
|
|
4282
|
+
throw new Error(
|
|
4283
|
+
`Migration v17 (add_source_store) failed: table ${full} exists with columns [${cols.join(", ")}], expected [${want.join(", ")}]. Drop the stray table (it predates the source store) and re-run setup().`
|
|
4284
|
+
);
|
|
4285
|
+
}
|
|
4286
|
+
const row = await db.getFirstAsync(`SELECT COUNT(*) AS n FROM ${full}`);
|
|
4287
|
+
if (row && row.n > 0) {
|
|
4288
|
+
throw new Error(
|
|
4289
|
+
`Migration v17 (add_source_store) failed: table ${full} already holds ${row.n} row(s), but no source text exists before v17. Back up and drop the table, then re-run setup().`
|
|
4290
|
+
);
|
|
4291
|
+
}
|
|
4292
|
+
}
|
|
4293
|
+
await db.execAsync(
|
|
4294
|
+
`CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
|
|
4295
|
+
id TEXT PRIMARY KEY,
|
|
4296
|
+
entity_id TEXT NOT NULL,
|
|
4297
|
+
source_ref TEXT NOT NULL,
|
|
4298
|
+
source_hash TEXT NOT NULL,
|
|
4299
|
+
text TEXT NOT NULL,
|
|
4300
|
+
text_hash TEXT NOT NULL,
|
|
4301
|
+
char_count INTEGER NOT NULL,
|
|
4302
|
+
created_at INTEGER NOT NULL
|
|
4303
|
+
);
|
|
4304
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref
|
|
4305
|
+
ON ${prefix}source_documents (entity_id, source_ref);
|
|
4306
|
+
CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash
|
|
4307
|
+
ON ${prefix}source_documents (entity_id, source_hash);
|
|
4308
|
+
CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
|
|
4309
|
+
id TEXT PRIMARY KEY,
|
|
4310
|
+
entity_id TEXT NOT NULL,
|
|
4311
|
+
document_id TEXT NOT NULL,
|
|
4312
|
+
seq INTEGER NOT NULL,
|
|
4313
|
+
start_offset INTEGER NOT NULL,
|
|
4314
|
+
end_offset INTEGER NOT NULL
|
|
4315
|
+
);`
|
|
4316
|
+
);
|
|
4317
|
+
}
|
|
3908
4318
|
}
|
|
3909
4319
|
];
|
|
3910
4320
|
async function createLegacySourceTypeIndex(db, prefix) {
|
|
@@ -5130,6 +5540,10 @@ var MaintenanceService = class {
|
|
|
5130
5540
|
if (await this.sourceRefIndexPresent(tx)) {
|
|
5131
5541
|
await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
|
|
5132
5542
|
}
|
|
5543
|
+
if (await this.sourceStorePresent(tx)) {
|
|
5544
|
+
await tx.runAsync(`DELETE FROM ${this.prefix}source_passages WHERE entity_id = ?`, [entityId]);
|
|
5545
|
+
await tx.runAsync(`DELETE FROM ${this.prefix}source_documents WHERE entity_id = ?`, [entityId]);
|
|
5546
|
+
}
|
|
5133
5547
|
await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
|
|
5134
5548
|
if (params.includeEvents) {
|
|
5135
5549
|
deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
|
|
@@ -5153,6 +5567,16 @@ var MaintenanceService = class {
|
|
|
5153
5567
|
const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
|
|
5154
5568
|
if (entryId) deletedEntryIds.push(entryId);
|
|
5155
5569
|
}
|
|
5570
|
+
if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
|
|
5571
|
+
const docs = `${this.prefix}source_documents`;
|
|
5572
|
+
const sel = "entity_id = ? AND (? IS NULL OR source_ref = ?) AND (? IS NULL OR source_hash = ?)";
|
|
5573
|
+
const selArgs = [entityId, sourceRef, sourceRef, sourceHash, sourceHash];
|
|
5574
|
+
await tx.runAsync(
|
|
5575
|
+
`DELETE FROM ${this.prefix}source_passages WHERE entity_id = ? AND document_id IN (SELECT id FROM ${docs} WHERE ${sel})`,
|
|
5576
|
+
[entityId, ...selArgs]
|
|
5577
|
+
);
|
|
5578
|
+
await tx.runAsync(`DELETE FROM ${docs} WHERE ${sel}`, selArgs);
|
|
5579
|
+
}
|
|
5156
5580
|
if (sourceRef || sourceHash) {
|
|
5157
5581
|
for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
|
|
5158
5582
|
}
|
|
@@ -5269,6 +5693,10 @@ var MaintenanceService = class {
|
|
|
5269
5693
|
if (version < 9) return false;
|
|
5270
5694
|
throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
|
|
5271
5695
|
}
|
|
5696
|
+
/** A never-set-up store has no source-store tables (#316 recovery); nothing to delete there. */
|
|
5697
|
+
async sourceStorePresent(tx) {
|
|
5698
|
+
return await this.metadataRepo.tableExists(`${this.prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${this.prefix}source_passages`, tx);
|
|
5699
|
+
}
|
|
5272
5700
|
/**
|
|
5273
5701
|
* Read-only dry-run preview of {@link forget}. Returns the same shape as a
|
|
5274
5702
|
* real call would, without acquiring the lock, opening a transaction, staging
|
|
@@ -6130,6 +6558,63 @@ function packFactsByBudget(items, budget, scores) {
|
|
|
6130
6558
|
|
|
6131
6559
|
// src/services/RetrievalService.ts
|
|
6132
6560
|
var EMPTY_ID_SET = /* @__PURE__ */ new Set();
|
|
6561
|
+
var DEFAULT_SOURCE_PASSAGES = 8;
|
|
6562
|
+
var DEFAULT_SOURCE_CHAR_BUDGET = 4e3;
|
|
6563
|
+
var asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
|
6564
|
+
var isHigh2 = (c) => c >= 55296 && c <= 56319;
|
|
6565
|
+
var isLow2 = (c) => c >= 56320 && c <= 57343;
|
|
6566
|
+
function queryTerms(query) {
|
|
6567
|
+
return [...new Set(asciiLower(query).split(/[^\p{L}\p{N}]+/u).filter((t) => t.length > 0))];
|
|
6568
|
+
}
|
|
6569
|
+
function assertSourcesQuery(opt) {
|
|
6570
|
+
const query = opt?.query;
|
|
6571
|
+
if (typeof query !== "string" || query.trim() === "") {
|
|
6572
|
+
throw new WikiInvalidReadOptions("sources.query", "must be a non-empty string");
|
|
6573
|
+
}
|
|
6574
|
+
if (queryTerms(query).length === 0) {
|
|
6575
|
+
throw new WikiInvalidReadOptions("sources.query", "must contain at least one searchable term");
|
|
6576
|
+
}
|
|
6577
|
+
}
|
|
6578
|
+
function windowPassage(text, terms, budget) {
|
|
6579
|
+
if (text.length <= budget) return { start: 0, end: text.length, truncated: false };
|
|
6580
|
+
const lower = asciiLower(text);
|
|
6581
|
+
let a = -1;
|
|
6582
|
+
let len = 0;
|
|
6583
|
+
for (const t of terms) {
|
|
6584
|
+
const i = lower.indexOf(t);
|
|
6585
|
+
if (i >= 0 && (a < 0 || i < a || i === a && t.length > len)) {
|
|
6586
|
+
a = i;
|
|
6587
|
+
len = t.length;
|
|
6588
|
+
}
|
|
6589
|
+
}
|
|
6590
|
+
const hardCut = (from) => {
|
|
6591
|
+
let end = Math.min(text.length, from + budget);
|
|
6592
|
+
if (end < text.length && isHigh2(text.charCodeAt(end - 1)) && isLow2(text.charCodeAt(end))) {
|
|
6593
|
+
if (end - 1 > from) end -= 1;
|
|
6594
|
+
else return { start: from, end: from, truncated: true };
|
|
6595
|
+
}
|
|
6596
|
+
return { start: from, end, truncated: from > 0 || end < text.length };
|
|
6597
|
+
};
|
|
6598
|
+
if (a < 0) return hardCut(0);
|
|
6599
|
+
if (len > budget) return hardCut(a);
|
|
6600
|
+
const toks = [];
|
|
6601
|
+
for (const m of text.matchAll(/\S+/g)) toks.push([m.index, m.index + m[0].length]);
|
|
6602
|
+
const mEnd = a + len;
|
|
6603
|
+
const ti = toks.findIndex(([, e]) => e > a);
|
|
6604
|
+
if (ti < 0) return hardCut(a);
|
|
6605
|
+
let tj = ti;
|
|
6606
|
+
while (tj + 1 < toks.length && toks[tj][1] < mEnd) tj++;
|
|
6607
|
+
if (toks[tj][1] - toks[ti][0] > budget) return hardCut(a);
|
|
6608
|
+
let r = toks.length - 1;
|
|
6609
|
+
let best = { start: toks[ti][0], end: toks[tj][1] };
|
|
6610
|
+
for (let l = ti; l >= 0; l--) {
|
|
6611
|
+
const s = toks[l][0];
|
|
6612
|
+
while (r > tj && toks[r][1] - s > budget) r--;
|
|
6613
|
+
if (toks[r][1] - s > budget) break;
|
|
6614
|
+
if (toks[r][1] - s > best.end - best.start) best = { start: s, end: toks[r][1] };
|
|
6615
|
+
}
|
|
6616
|
+
return { ...best, truncated: true };
|
|
6617
|
+
}
|
|
6133
6618
|
var RetrievalService = class {
|
|
6134
6619
|
constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
|
|
6135
6620
|
this.options = options;
|
|
@@ -6144,8 +6629,10 @@ var RetrievalService = class {
|
|
|
6144
6629
|
const entityIds = normalizeEntityIds(entityId);
|
|
6145
6630
|
const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
|
|
6146
6631
|
const exposeMetadata = shouldExposeReadMetadata(entityId);
|
|
6632
|
+
if (options?.sources) assertSourcesQuery(options.sources);
|
|
6147
6633
|
if (entityIds.length === 0) {
|
|
6148
6634
|
const empty = { facts: [], tasks: [], events: [], edges: [] };
|
|
6635
|
+
if (options?.sources) empty.sources = [];
|
|
6149
6636
|
if (exposeMetadata) {
|
|
6150
6637
|
empty.metadata = { query, entityIds: [] };
|
|
6151
6638
|
if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
|
|
@@ -6660,6 +7147,7 @@ var RetrievalService = class {
|
|
|
6660
7147
|
factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
|
|
6661
7148
|
}
|
|
6662
7149
|
const bundle = { facts, tasks, events: events.reverse(), edges: [] };
|
|
7150
|
+
if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
|
|
6663
7151
|
if (exposeMetadata) {
|
|
6664
7152
|
bundle.metadata = { query, entityIds };
|
|
6665
7153
|
if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
|
|
@@ -6668,6 +7156,42 @@ var RetrievalService = class {
|
|
|
6668
7156
|
}
|
|
6669
7157
|
return bundle;
|
|
6670
7158
|
}
|
|
7159
|
+
/**
|
|
7160
|
+
* The `sources` group (spec source-store section 7). One search per entity,
|
|
7161
|
+
* so ranking and caps never cross entities. No model call anywhere.
|
|
7162
|
+
* `charBudget` is per entity: windows are cut in rank order against the
|
|
7163
|
+
* entity's remaining budget, and once it is spent lower-ranked hits are not returned.
|
|
7164
|
+
*/
|
|
7165
|
+
async _readSources(entityIds, opt) {
|
|
7166
|
+
const pos = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : d;
|
|
7167
|
+
const maxPassages = pos(opt.maxPassages, DEFAULT_SOURCE_PASSAGES);
|
|
7168
|
+
const charBudget = pos(opt.charBudget, DEFAULT_SOURCE_CHAR_BUDGET);
|
|
7169
|
+
assertSourcesQuery(opt);
|
|
7170
|
+
const query = opt.query;
|
|
7171
|
+
const terms = queryTerms(query);
|
|
7172
|
+
const out = [];
|
|
7173
|
+
for (const entityId of entityIds) {
|
|
7174
|
+
const hits = await this.searchService.searchPassages(query, entityId, maxPassages);
|
|
7175
|
+
let remaining = charBudget;
|
|
7176
|
+
for (const h of hits) {
|
|
7177
|
+
if (remaining <= 0) break;
|
|
7178
|
+
const w = windowPassage(h.text, terms, remaining);
|
|
7179
|
+
if (w.end === w.start) continue;
|
|
7180
|
+
remaining -= w.end - w.start;
|
|
7181
|
+
out.push({
|
|
7182
|
+
entityId,
|
|
7183
|
+
sourceRef: h.source_ref,
|
|
7184
|
+
sourceHash: h.source_hash,
|
|
7185
|
+
seq: h.seq,
|
|
7186
|
+
startOffset: h.start_offset + w.start,
|
|
7187
|
+
endOffset: h.start_offset + w.end,
|
|
7188
|
+
truncated: w.truncated,
|
|
7189
|
+
text: h.text.slice(w.start, w.end)
|
|
7190
|
+
});
|
|
7191
|
+
}
|
|
7192
|
+
}
|
|
7193
|
+
return out;
|
|
7194
|
+
}
|
|
6671
7195
|
/**
|
|
6672
7196
|
* Returns entity IDs that will participate in scored retrieval.
|
|
6673
7197
|
* Excludes zero-weight entities unless includeZeroWeightEntities is true.
|
|
@@ -6795,6 +7319,10 @@ var UnavailableIndexStrategy = class {
|
|
|
6795
7319
|
}
|
|
6796
7320
|
async drain(_opts) {
|
|
6797
7321
|
}
|
|
7322
|
+
/** Degraded like everything else: no passages, no throw (spec source-store section 7). */
|
|
7323
|
+
async searchPassages() {
|
|
7324
|
+
return [];
|
|
7325
|
+
}
|
|
6798
7326
|
};
|
|
6799
7327
|
|
|
6800
7328
|
// src/services/SearchService.ts
|
|
@@ -7016,6 +7544,36 @@ var _SearchService = class _SearchService {
|
|
|
7016
7544
|
const results = finiteResults(await this.indexStrategy.search(query, { entityIds, limit }));
|
|
7017
7545
|
return results.sort((a, b) => this._compareSearchResults(a, b)).slice(0, limit);
|
|
7018
7546
|
}
|
|
7547
|
+
/**
|
|
7548
|
+
* Post-commit passage index sync (spec source-store section 6). FTS5: drains the
|
|
7549
|
+
* passage ledger (per document, entity-scoped when given). MiniSearch: reloads
|
|
7550
|
+
* the entity's stored passages (all stored entities when omitted: the open-time
|
|
7551
|
+
* pass). Serialized on the sync chain; never rejects, like sync().
|
|
7552
|
+
*/
|
|
7553
|
+
async syncPassages(db, prefix, entityId, deadline) {
|
|
7554
|
+
const s = this.indexStrategy;
|
|
7555
|
+
if (!s.drainPassages && !s.reindexSourcePassages) return;
|
|
7556
|
+
const work = this.syncChain.then(async () => {
|
|
7557
|
+
try {
|
|
7558
|
+
if (s.drainPassages) await s.drainPassages({ entityId, deadline });
|
|
7559
|
+
else await s.reindexSourcePassages(db, prefix, entityId);
|
|
7560
|
+
} catch (err) {
|
|
7561
|
+
console.warn(`[WikiMemory] passage index sync failed for ${entityId ?? "*"}:`, err);
|
|
7562
|
+
}
|
|
7563
|
+
});
|
|
7564
|
+
this.syncChain = work;
|
|
7565
|
+
return work;
|
|
7566
|
+
}
|
|
7567
|
+
/**
|
|
7568
|
+
* Stored-source passage search for ONE entity (spec source-store section 7:
|
|
7569
|
+
* ranking and caps are per entity). Rides the active strategy; a strategy
|
|
7570
|
+
* without passage search yields none.
|
|
7571
|
+
*/
|
|
7572
|
+
async searchPassages(query, entityId, limit) {
|
|
7573
|
+
if (!this.indexStrategy.searchPassages) return [];
|
|
7574
|
+
const hits = await this.indexStrategy.searchPassages(query, { entityIds: [entityId], limit });
|
|
7575
|
+
return hits.filter((h) => Number.isFinite(h.score) && h.entity_id === entityId).slice(0, limit);
|
|
7576
|
+
}
|
|
7019
7577
|
/**
|
|
7020
7578
|
* Pre-fetches keyword scores for candidate hydration, used during hybrid weighting.
|
|
7021
7579
|
*/
|
|
@@ -7172,7 +7730,8 @@ var JobManager = class {
|
|
|
7172
7730
|
reembed: (id) => this._reembedKey(id),
|
|
7173
7731
|
import: (id) => this._importKey(id),
|
|
7174
7732
|
forget: (id) => this._forgetKey(id),
|
|
7175
|
-
ontologyBackfill: (id) => this._ontologyBackfillKey(id)
|
|
7733
|
+
ontologyBackfill: (id) => this._ontologyBackfillKey(id),
|
|
7734
|
+
store: (id) => this._storeKey(id)
|
|
7176
7735
|
};
|
|
7177
7736
|
}
|
|
7178
7737
|
_hashLockKey(entityId, sourceHash) {
|
|
@@ -7241,6 +7800,9 @@ var JobManager = class {
|
|
|
7241
7800
|
_librarianKey(entityId) {
|
|
7242
7801
|
return `${this.prefix}:${entityId}:librarian`;
|
|
7243
7802
|
}
|
|
7803
|
+
_storeKey(entityId) {
|
|
7804
|
+
return `${this.prefix}:${entityId}:store`;
|
|
7805
|
+
}
|
|
7244
7806
|
_healKey(entityId) {
|
|
7245
7807
|
return `${this.prefix}:${entityId}:heal`;
|
|
7246
7808
|
}
|
|
@@ -7269,6 +7831,9 @@ var JobManager = class {
|
|
|
7269
7831
|
_isImportActiveFor(entityId) {
|
|
7270
7832
|
return this.activeMaintenanceJobs.has(this._importKey(entityId)) || this.activeMaintenanceJobs.has(this._globalImportKey());
|
|
7271
7833
|
}
|
|
7834
|
+
_isStoreActiveFor(entityId) {
|
|
7835
|
+
return this.activeMaintenanceJobs.has(this._storeKey(entityId));
|
|
7836
|
+
}
|
|
7272
7837
|
_isForgetActiveFor(entityId) {
|
|
7273
7838
|
return this.activeMaintenanceJobs.has(this._forgetKey(entityId));
|
|
7274
7839
|
}
|
|
@@ -7318,6 +7883,7 @@ var JobManager = class {
|
|
|
7318
7883
|
else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
|
|
7319
7884
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
7320
7885
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
7886
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
7321
7887
|
break;
|
|
7322
7888
|
case "librarian":
|
|
7323
7889
|
case "heal":
|
|
@@ -7328,6 +7894,7 @@ var JobManager = class {
|
|
|
7328
7894
|
else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
|
|
7329
7895
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
7330
7896
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
7897
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
7331
7898
|
break;
|
|
7332
7899
|
}
|
|
7333
7900
|
case "reembed":
|
|
@@ -7340,6 +7907,7 @@ var JobManager = class {
|
|
|
7340
7907
|
else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
|
|
7341
7908
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
7342
7909
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
7910
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
7343
7911
|
break;
|
|
7344
7912
|
case "global_reembed":
|
|
7345
7913
|
if (this.activeMaintenanceJobs.has(this._globalReembedKey())) blockingOperation = "reembed";
|
|
@@ -7351,6 +7919,7 @@ var JobManager = class {
|
|
|
7351
7919
|
else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
|
|
7352
7920
|
else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
|
|
7353
7921
|
else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
|
|
7922
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
|
|
7354
7923
|
break;
|
|
7355
7924
|
case "import":
|
|
7356
7925
|
case "forget": {
|
|
@@ -7364,10 +7933,23 @@ var JobManager = class {
|
|
|
7364
7933
|
else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
|
|
7365
7934
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
7366
7935
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
7936
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
7367
7937
|
break;
|
|
7368
7938
|
}
|
|
7939
|
+
case "store":
|
|
7940
|
+
if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
7941
|
+
else if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
|
|
7942
|
+
else if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) blockingOperation = "librarian";
|
|
7943
|
+
else if (this.activeMaintenanceJobs.has(this._healKey(entityId))) blockingOperation = "heal";
|
|
7944
|
+
else if (this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId))) blockingOperation = "ontologyBackfill";
|
|
7945
|
+
else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
|
|
7946
|
+
else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
|
|
7947
|
+
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
7948
|
+
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
7949
|
+
break;
|
|
7369
7950
|
case "global_import":
|
|
7370
7951
|
if (this.activeMaintenanceJobs.has(this._globalImportKey())) blockingOperation = "import";
|
|
7952
|
+
else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
|
|
7371
7953
|
break;
|
|
7372
7954
|
case "ingest": {
|
|
7373
7955
|
const sourceKey = sourceRef ?? "";
|
|
@@ -7376,6 +7958,7 @@ var JobManager = class {
|
|
|
7376
7958
|
else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
|
|
7377
7959
|
else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
|
|
7378
7960
|
else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
|
|
7961
|
+
else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
|
|
7379
7962
|
break;
|
|
7380
7963
|
}
|
|
7381
7964
|
}
|
|
@@ -7418,22 +8001,24 @@ var JobManager = class {
|
|
|
7418
8001
|
case "librarian":
|
|
7419
8002
|
case "heal":
|
|
7420
8003
|
case "ontologyBackfill":
|
|
7421
|
-
return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
8004
|
+
return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
7422
8005
|
case "prune":
|
|
7423
|
-
return this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
8006
|
+
return this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
7424
8007
|
case "reembed":
|
|
7425
|
-
return this.activeMaintenanceJobs.has(this._reembedKey(entityId)) || this.activeMaintenanceJobs.has(this._globalReembedKey()) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
8008
|
+
return this.activeMaintenanceJobs.has(this._reembedKey(entityId)) || this.activeMaintenanceJobs.has(this._globalReembedKey()) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
7426
8009
|
case "global_reembed":
|
|
7427
|
-
return this.activeMaintenanceJobs.has(this._globalReembedKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget");
|
|
8010
|
+
return this.activeMaintenanceJobs.has(this._globalReembedKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget") || this._isAnyMaintenanceActiveWithSuffix(":store");
|
|
7428
8011
|
case "import":
|
|
7429
8012
|
case "forget": {
|
|
7430
8013
|
const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
|
|
7431
|
-
return this.activeMaintenanceJobs.has(selfKey) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
8014
|
+
return this.activeMaintenanceJobs.has(selfKey) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
7432
8015
|
}
|
|
8016
|
+
case "store":
|
|
8017
|
+
return this._isStoreActiveFor(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
7433
8018
|
case "global_import":
|
|
7434
|
-
return this.activeMaintenanceJobs.has(this._globalImportKey());
|
|
8019
|
+
return this.activeMaintenanceJobs.has(this._globalImportKey()) || this._isAnyMaintenanceActiveWithSuffix(":store");
|
|
7435
8020
|
case "ingest":
|
|
7436
|
-
return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
|
|
8021
|
+
return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
|
|
7437
8022
|
default:
|
|
7438
8023
|
return false;
|
|
7439
8024
|
}
|
|
@@ -7498,6 +8083,7 @@ var JobManager = class {
|
|
|
7498
8083
|
if (this._isReembedActive(entityId)) throw new WikiBusyError("reembed", entityId);
|
|
7499
8084
|
if (this._isIngestActiveFor(entityId)) throw new WikiBusyError("ingest", entityId);
|
|
7500
8085
|
if (this._isForgetActiveFor(entityId)) throw new WikiBusyError("forget", entityId);
|
|
8086
|
+
if (this._isStoreActiveFor(entityId)) throw new WikiBusyError("store", entityId);
|
|
7501
8087
|
}
|
|
7502
8088
|
if (this.activeMaintenanceJobs.has(this._globalImportKey())) throw new WikiBusyError("import", "*");
|
|
7503
8089
|
this.activeMaintenanceJobs.add(this._globalImportKey());
|