@equationalapplications/core-llm-wiki 9.0.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/testing.js CHANGED
@@ -729,7 +729,14 @@ var SEVERITY = {
729
729
  external_deletion_pending: "warn",
730
730
  external_deletion_discarded: "warn",
731
731
  guidance_too_long: "warn",
732
- guidance_resolver_failed: "warn"
732
+ guidance_resolver_failed: "warn",
733
+ source_pointer_unresolved: "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"
733
740
  };
734
741
  var MESSAGE = {
735
742
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -757,7 +764,14 @@ var MESSAGE = {
757
764
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
758
765
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
759
766
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
760
- guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
767
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
768
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
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."
761
775
  };
762
776
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
763
777
  function copyDetail(detail) {
@@ -1237,6 +1251,312 @@ function entitySummaryMetaKey(entityId) {
1237
1251
  return `entity_summary:${entityId}`;
1238
1252
  }
1239
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;
1522
+
1523
+ // src/utils/sourcePointer.ts
1524
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
1525
+ function isStringOrNull(v) {
1526
+ return v === null || typeof v === "string";
1527
+ }
1528
+ function isValidPosition(v) {
1529
+ if (v === null) return true;
1530
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
1531
+ const o = v;
1532
+ const keys = Object.keys(o);
1533
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
1534
+ const { start, length } = o;
1535
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
1536
+ }
1537
+ function validateSourcePointerValue(v) {
1538
+ if (v === null) return null;
1539
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
1540
+ const o = v;
1541
+ const keys = Object.keys(o);
1542
+ for (const k of keys) {
1543
+ if (!POINTER_SLOTS.includes(k)) return void 0;
1544
+ }
1545
+ if (!isStringOrNull(o["event_id"] === void 0 ? null : o["event_id"]) || !isStringOrNull(o["ref"] === void 0 ? null : o["ref"]) || !isStringOrNull(o["quote"] === void 0 ? null : o["quote"])) {
1546
+ return void 0;
1547
+ }
1548
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
1549
+ const normalized = {
1550
+ event_id: o["event_id"] ?? null,
1551
+ ref: o["ref"] ?? null,
1552
+ quote: o["quote"] ?? null,
1553
+ position: o["position"] ?? null
1554
+ };
1555
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
1556
+ return null;
1557
+ }
1558
+ return normalized;
1559
+ }
1240
1560
 
1241
1561
  // src/services/legacyWatermark.ts
1242
1562
  async function anchorAtLegacyBoundary(metadataRepo, eventRepo, entityId, checkpoint, total, db) {
@@ -1322,7 +1642,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
1322
1642
  var IMPORT_TITLE_MAX = 500;
1323
1643
  var IMPORT_BODY_MAX = 8e3;
1324
1644
  var ImportExportService = class {
1325
- 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) {
1326
1646
  this.db = db;
1327
1647
  this.entryRepo = entryRepo;
1328
1648
  this.taskRepo = taskRepo;
@@ -1334,6 +1654,7 @@ var ImportExportService = class {
1334
1654
  this.embeddingService = embeddingService;
1335
1655
  this.options = options;
1336
1656
  this.vectorRemoval = vectorRemoval;
1657
+ this.prefix = prefix;
1337
1658
  }
1338
1659
  async exportDump(entityIds) {
1339
1660
  let ids;
@@ -1341,6 +1662,13 @@ var ImportExportService = class {
1341
1662
  ids = Array.from(new Set(entityIds));
1342
1663
  } else {
1343
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
+ }
1344
1672
  }
1345
1673
  const entities = {};
1346
1674
  const BATCH = 3;
@@ -1348,10 +1676,11 @@ var ImportExportService = class {
1348
1676
  const batch = ids.slice(i, i + BATCH);
1349
1677
  const batchResults = await Promise.all(
1350
1678
  batch.map(
1351
- async (id) => [
1352
- id,
1353
- await this.getFullBundle(id, { includeBlobs: true })
1354
- ]
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
+ }
1355
1684
  )
1356
1685
  );
1357
1686
  for (const [id, bundle] of batchResults) {
@@ -1362,16 +1691,96 @@ var ImportExportService = class {
1362
1691
  }
1363
1692
  async importDump(dump, opts) {
1364
1693
  const merge = opts?.merge ?? false;
1694
+ const skippedSources = [];
1365
1695
  const entityIds = Object.keys(dump.entities);
1366
1696
  this.jobManager.acquireImportLocks(entityIds);
1367
1697
  try {
1368
1698
  await this.assertNoLegacySourceTypes();
1369
1699
  for (const [entityId, bundle] of Object.entries(dump.entities)) {
1370
- await this.doImportEntity(entityId, bundle, merge);
1700
+ skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
1371
1701
  }
1372
1702
  } finally {
1373
1703
  this.jobManager.releaseImportLocks(entityIds);
1374
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
+ }
1375
1784
  }
1376
1785
  async getFullBundle(entityId, opts) {
1377
1786
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
@@ -1410,6 +1819,8 @@ var ImportExportService = class {
1410
1819
  }
1411
1820
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
1412
1821
  async doImportEntity(entityId, bundle, merge) {
1822
+ const skippedSources = [];
1823
+ const refusalDiagnostics = [];
1413
1824
  const upsertedFactIds = /* @__PURE__ */ new Set();
1414
1825
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
1415
1826
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
@@ -1527,6 +1938,19 @@ var ImportExportService = class {
1527
1938
  );
1528
1939
  }
1529
1940
  }
1941
+ const hasSourcePointerKey = fact["source_pointer"] !== void 0;
1942
+ const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
1943
+ const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
1944
+ if (pointerValidated === void 0) {
1945
+ emitDiagnostic(this.options, {
1946
+ code: "source_pointer_invalid",
1947
+ operation: "importDump",
1948
+ trigger: "call",
1949
+ entityId,
1950
+ detail: { factId: fact.id }
1951
+ });
1952
+ }
1953
+ const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
1530
1954
  const factObj = {
1531
1955
  id: fact.id,
1532
1956
  entity_id: entityId,
@@ -1544,6 +1968,7 @@ var ImportExportService = class {
1544
1968
  deleted_at: fact.deleted_at,
1545
1969
  embedding_blob: blobData ?? void 0,
1546
1970
  okf_type: fact.okf_type ?? null,
1971
+ source_pointer: sourcePointer,
1547
1972
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
1548
1973
  // populating these per spec, importDump does not derive or validate them.
1549
1974
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -1561,7 +1986,7 @@ var ImportExportService = class {
1561
1986
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
1562
1987
  })()
1563
1988
  };
1564
- await this.entryRepo.upsertForImport(factObj, tx);
1989
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
1565
1990
  await this.entryRepo.setTemporal(fact.id, entityId, {
1566
1991
  valid_from: fact.valid_from ?? null,
1567
1992
  valid_to: fact.valid_to ?? null,
@@ -1673,7 +2098,9 @@ var ImportExportService = class {
1673
2098
  tx
1674
2099
  );
1675
2100
  }
2101
+ await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
1676
2102
  });
2103
+ for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
1677
2104
  if (clampedEvents > 0) {
1678
2105
  emitDiagnostic(this.options, {
1679
2106
  code: "event_created_at_clamped",
@@ -1841,6 +2268,7 @@ var ImportExportService = class {
1841
2268
  } finally {
1842
2269
  this.searchService.evictCache(entityId);
1843
2270
  }
2271
+ return skippedSources;
1844
2272
  }
1845
2273
  _warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
1846
2274
  console.warn(
@@ -1875,19 +2303,6 @@ After running the migration SQL, restart your application.`
1875
2303
  );
1876
2304
  }
1877
2305
  };
1878
- function generateId(prefix = "") {
1879
- if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
1880
- return prefix + crypto.randomUUID().replace(/-/g, "").substring(0, 24);
1881
- }
1882
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
1883
- const bytes = new Uint8Array(16);
1884
- crypto.getRandomValues(bytes);
1885
- return prefix + Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("").substring(0, 24);
1886
- }
1887
- throw new Error(
1888
- "generateId: no cryptographically secure random source available (crypto.randomUUID and crypto.getRandomValues are both missing, and no configureRandomSource() injection was provided)."
1889
- );
1890
- }
1891
2306
 
1892
2307
  // src/prompts.ts
1893
2308
  var LEAVE_OUT_RULE_SENTENCE = "Memory leaves out what a better record already holds, and points to that record.";
@@ -2282,6 +2697,10 @@ ${JSON.stringify(facts, null, 2)}`
2282
2697
  systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2283
2698
  userPrompt: `Events:
2284
2699
  ${lines.join("\n")}`,
2700
+ // Corpus entries are one-per-batch-event in batch order (summaries are
2701
+ // TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
2702
+ // nothing): extract.ts stores a candidate's `sourcePartIndex` as the
2703
+ // batch index and buildSourcePointer reads the quote back by it.
2285
2704
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
2286
2705
  };
2287
2706
  }
@@ -3834,6 +4253,68 @@ var MIGRATIONS = [
3834
4253
  );
3835
4254
  if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
3836
4255
  }
4256
+ },
4257
+ {
4258
+ version: 16,
4259
+ description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
4260
+ run: async (db, prefix) => {
4261
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
4262
+ const existing = new Set(cols.map((c) => c.name));
4263
+ if (!existing.has("source_pointer")) {
4264
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
4265
+ }
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
+ }
3837
4318
  }
3838
4319
  ];
3839
4320
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -3996,9 +4477,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
3996
4477
  access_count: 0,
3997
4478
  deleted_at: null,
3998
4479
  okf_type: normalized.okf_type,
4480
+ // Legacy writes no pointer (spec §Legacy path): the column stays null
4481
+ // on every legacy fact, and the legacy prompt keeps its exact text.
4482
+ source_pointer: null,
3999
4483
  ...grounding?.trust
4000
4484
  };
4001
4485
  await deps.entryRepo.upsert(factObj, tx);
4486
+ const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
4487
+ if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
4488
+ diagBuffer.push({
4489
+ ...diagBase,
4490
+ code: "source_pointer_unresolved",
4491
+ detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
4492
+ });
4493
+ }
4002
4494
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
4003
4495
  factsForDedupe.push(factObj);
4004
4496
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
@@ -4112,9 +4604,23 @@ async function runExtract(deps, ctx, batch) {
4112
4604
  return;
4113
4605
  }
4114
4606
  const r = raw;
4115
- const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
4607
+ let sourceEventId = null;
4608
+ let sourcePartIndex = null;
4609
+ let pointerUnresolved;
4610
+ const rawSourceEvent = r.source_event;
4611
+ if (rawSourceEvent === void 0 || rawSourceEvent === null) {
4612
+ pointerUnresolved = "missing";
4613
+ } else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
4614
+ const labeled = byLabel.get(rawSourceEvent);
4615
+ sourceEventId = labeled.event.id;
4616
+ sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
4617
+ pointerUnresolved = null;
4618
+ } else {
4619
+ pointerUnresolved = "unknown_label";
4620
+ }
4621
+ const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
4116
4622
  const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
4117
- candidates.push({ index, fact, sourceLabel, validFrom });
4623
+ candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
4118
4624
  });
4119
4625
  const tasks = [];
4120
4626
  (Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
@@ -4404,6 +4910,17 @@ var TemporalService = class {
4404
4910
  };
4405
4911
 
4406
4912
  // src/services/librarian/ops/apply.ts
4913
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
4914
+ if (candidate.sourceEventId === null) return null;
4915
+ let quote = null;
4916
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
4917
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
4918
+ if (part !== void 0) {
4919
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
4920
+ }
4921
+ }
4922
+ return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
4923
+ }
4407
4924
  async function applyOps(deps, ctx, input) {
4408
4925
  const { entityId, trigger } = ctx;
4409
4926
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -4432,7 +4949,8 @@ async function applyOps(deps, ctx, input) {
4432
4949
  const drops = [];
4433
4950
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
4434
4951
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
4435
- const g2 = grounding ? groundingOutcome(checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding), now) : null;
4952
+ const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
4953
+ const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
4436
4954
  if (g2?.diagnostic) {
4437
4955
  input.diagnostics.push({
4438
4956
  ...diagBase,
@@ -4440,6 +4958,7 @@ async function applyOps(deps, ctx, input) {
4440
4958
  detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
4441
4959
  });
4442
4960
  }
4961
+ const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
4443
4962
  const row = {
4444
4963
  id,
4445
4964
  entity_id: entityId,
@@ -4456,11 +4975,19 @@ async function applyOps(deps, ctx, input) {
4456
4975
  access_count: 0,
4457
4976
  deleted_at: null,
4458
4977
  okf_type: normalized.okf_type,
4978
+ source_pointer: pointer,
4459
4979
  ...g2?.trust,
4460
4980
  ...draft ? { lifecycle_status: "draft" } : {}
4461
4981
  };
4462
4982
  await deps.entryRepo.upsert(row, tx);
4463
4983
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
4984
+ if (g.candidate.pointerUnresolved !== null) {
4985
+ input.diagnostics.push({
4986
+ ...diagBase,
4987
+ code: "source_pointer_unresolved",
4988
+ detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
4989
+ });
4990
+ }
4464
4991
  titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
4465
4992
  if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
4466
4993
  const textChanged = title !== fact.title || body !== fact.body;
@@ -5013,6 +5540,10 @@ var MaintenanceService = class {
5013
5540
  if (await this.sourceRefIndexPresent(tx)) {
5014
5541
  await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
5015
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
+ }
5016
5547
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
5017
5548
  if (params.includeEvents) {
5018
5549
  deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
@@ -5036,6 +5567,16 @@ var MaintenanceService = class {
5036
5567
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
5037
5568
  if (entryId) deletedEntryIds.push(entryId);
5038
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
+ }
5039
5580
  if (sourceRef || sourceHash) {
5040
5581
  for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
5041
5582
  }
@@ -5152,6 +5693,10 @@ var MaintenanceService = class {
5152
5693
  if (version < 9) return false;
5153
5694
  throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
5154
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
+ }
5155
5700
  /**
5156
5701
  * Read-only dry-run preview of {@link forget}. Returns the same shape as a
5157
5702
  * real call would, without acquiring the lock, opening a transaction, staging
@@ -5484,6 +6029,7 @@ var MaintenanceService = class {
5484
6029
  source_type: "librarian_inferred",
5485
6030
  source_hash: null,
5486
6031
  source_ref: null,
6032
+ source_pointer: null,
5487
6033
  created_at: now,
5488
6034
  updated_at: now,
5489
6035
  last_accessed_at: null,
@@ -6012,6 +6558,63 @@ function packFactsByBudget(items, budget, scores) {
6012
6558
 
6013
6559
  // src/services/RetrievalService.ts
6014
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
+ }
6015
6618
  var RetrievalService = class {
6016
6619
  constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
6017
6620
  this.options = options;
@@ -6026,8 +6629,10 @@ var RetrievalService = class {
6026
6629
  const entityIds = normalizeEntityIds(entityId);
6027
6630
  const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
6028
6631
  const exposeMetadata = shouldExposeReadMetadata(entityId);
6632
+ if (options?.sources) assertSourcesQuery(options.sources);
6029
6633
  if (entityIds.length === 0) {
6030
6634
  const empty = { facts: [], tasks: [], events: [], edges: [] };
6635
+ if (options?.sources) empty.sources = [];
6031
6636
  if (exposeMetadata) {
6032
6637
  empty.metadata = { query, entityIds: [] };
6033
6638
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
@@ -6542,6 +7147,7 @@ var RetrievalService = class {
6542
7147
  factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
6543
7148
  }
6544
7149
  const bundle = { facts, tasks, events: events.reverse(), edges: [] };
7150
+ if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
6545
7151
  if (exposeMetadata) {
6546
7152
  bundle.metadata = { query, entityIds };
6547
7153
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
@@ -6550,6 +7156,42 @@ var RetrievalService = class {
6550
7156
  }
6551
7157
  return bundle;
6552
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
+ }
6553
7195
  /**
6554
7196
  * Returns entity IDs that will participate in scored retrieval.
6555
7197
  * Excludes zero-weight entities unless includeZeroWeightEntities is true.
@@ -6677,6 +7319,10 @@ var UnavailableIndexStrategy = class {
6677
7319
  }
6678
7320
  async drain(_opts) {
6679
7321
  }
7322
+ /** Degraded like everything else: no passages, no throw (spec source-store section 7). */
7323
+ async searchPassages() {
7324
+ return [];
7325
+ }
6680
7326
  };
6681
7327
 
6682
7328
  // src/services/SearchService.ts
@@ -6898,6 +7544,36 @@ var _SearchService = class _SearchService {
6898
7544
  const results = finiteResults(await this.indexStrategy.search(query, { entityIds, limit }));
6899
7545
  return results.sort((a, b) => this._compareSearchResults(a, b)).slice(0, limit);
6900
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
+ }
6901
7577
  /**
6902
7578
  * Pre-fetches keyword scores for candidate hydration, used during hybrid weighting.
6903
7579
  */
@@ -7054,7 +7730,8 @@ var JobManager = class {
7054
7730
  reembed: (id) => this._reembedKey(id),
7055
7731
  import: (id) => this._importKey(id),
7056
7732
  forget: (id) => this._forgetKey(id),
7057
- ontologyBackfill: (id) => this._ontologyBackfillKey(id)
7733
+ ontologyBackfill: (id) => this._ontologyBackfillKey(id),
7734
+ store: (id) => this._storeKey(id)
7058
7735
  };
7059
7736
  }
7060
7737
  _hashLockKey(entityId, sourceHash) {
@@ -7123,6 +7800,9 @@ var JobManager = class {
7123
7800
  _librarianKey(entityId) {
7124
7801
  return `${this.prefix}:${entityId}:librarian`;
7125
7802
  }
7803
+ _storeKey(entityId) {
7804
+ return `${this.prefix}:${entityId}:store`;
7805
+ }
7126
7806
  _healKey(entityId) {
7127
7807
  return `${this.prefix}:${entityId}:heal`;
7128
7808
  }
@@ -7151,6 +7831,9 @@ var JobManager = class {
7151
7831
  _isImportActiveFor(entityId) {
7152
7832
  return this.activeMaintenanceJobs.has(this._importKey(entityId)) || this.activeMaintenanceJobs.has(this._globalImportKey());
7153
7833
  }
7834
+ _isStoreActiveFor(entityId) {
7835
+ return this.activeMaintenanceJobs.has(this._storeKey(entityId));
7836
+ }
7154
7837
  _isForgetActiveFor(entityId) {
7155
7838
  return this.activeMaintenanceJobs.has(this._forgetKey(entityId));
7156
7839
  }
@@ -7200,6 +7883,7 @@ var JobManager = class {
7200
7883
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
7201
7884
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7202
7885
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7886
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7203
7887
  break;
7204
7888
  case "librarian":
7205
7889
  case "heal":
@@ -7210,6 +7894,7 @@ var JobManager = class {
7210
7894
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
7211
7895
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7212
7896
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7897
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7213
7898
  break;
7214
7899
  }
7215
7900
  case "reembed":
@@ -7222,6 +7907,7 @@ var JobManager = class {
7222
7907
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
7223
7908
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7224
7909
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7910
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7225
7911
  break;
7226
7912
  case "global_reembed":
7227
7913
  if (this.activeMaintenanceJobs.has(this._globalReembedKey())) blockingOperation = "reembed";
@@ -7233,6 +7919,7 @@ var JobManager = class {
7233
7919
  else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
7234
7920
  else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
7235
7921
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
7922
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7236
7923
  break;
7237
7924
  case "import":
7238
7925
  case "forget": {
@@ -7246,10 +7933,23 @@ var JobManager = class {
7246
7933
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
7247
7934
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7248
7935
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7936
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7249
7937
  break;
7250
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;
7251
7950
  case "global_import":
7252
7951
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) blockingOperation = "import";
7952
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7253
7953
  break;
7254
7954
  case "ingest": {
7255
7955
  const sourceKey = sourceRef ?? "";
@@ -7258,6 +7958,7 @@ var JobManager = class {
7258
7958
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
7259
7959
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7260
7960
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7961
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7261
7962
  break;
7262
7963
  }
7263
7964
  }
@@ -7300,22 +8001,24 @@ var JobManager = class {
7300
8001
  case "librarian":
7301
8002
  case "heal":
7302
8003
  case "ontologyBackfill":
7303
- 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);
7304
8005
  case "prune":
7305
- 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);
7306
8007
  case "reembed":
7307
- 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);
7308
8009
  case "global_reembed":
7309
- 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");
7310
8011
  case "import":
7311
8012
  case "forget": {
7312
8013
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
7313
- 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);
7314
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);
7315
8018
  case "global_import":
7316
- return this.activeMaintenanceJobs.has(this._globalImportKey());
8019
+ return this.activeMaintenanceJobs.has(this._globalImportKey()) || this._isAnyMaintenanceActiveWithSuffix(":store");
7317
8020
  case "ingest":
7318
- 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);
7319
8022
  default:
7320
8023
  return false;
7321
8024
  }
@@ -7380,6 +8083,7 @@ var JobManager = class {
7380
8083
  if (this._isReembedActive(entityId)) throw new WikiBusyError("reembed", entityId);
7381
8084
  if (this._isIngestActiveFor(entityId)) throw new WikiBusyError("ingest", entityId);
7382
8085
  if (this._isForgetActiveFor(entityId)) throw new WikiBusyError("forget", entityId);
8086
+ if (this._isStoreActiveFor(entityId)) throw new WikiBusyError("store", entityId);
7383
8087
  }
7384
8088
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) throw new WikiBusyError("import", "*");
7385
8089
  this.activeMaintenanceJobs.add(this._globalImportKey());