@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.
@@ -1014,6 +1014,10 @@ var UnavailableIndexStrategy = class {
1014
1014
  }
1015
1015
  async drain(_opts) {
1016
1016
  }
1017
+ /** Degraded like everything else: no passages, no throw (spec source-store section 7). */
1018
+ async searchPassages() {
1019
+ return [];
1020
+ }
1017
1021
  };
1018
1022
 
1019
1023
  // src/services/SearchService.ts
@@ -1235,6 +1239,36 @@ var _SearchService = class _SearchService {
1235
1239
  const results = finiteResults(await this.indexStrategy.search(query, { entityIds, limit }));
1236
1240
  return results.sort((a, b) => this._compareSearchResults(a, b)).slice(0, limit);
1237
1241
  }
1242
+ /**
1243
+ * Post-commit passage index sync (spec source-store section 6). FTS5: drains the
1244
+ * passage ledger (per document, entity-scoped when given). MiniSearch: reloads
1245
+ * the entity's stored passages (all stored entities when omitted: the open-time
1246
+ * pass). Serialized on the sync chain; never rejects, like sync().
1247
+ */
1248
+ async syncPassages(db, prefix, entityId, deadline) {
1249
+ const s = this.indexStrategy;
1250
+ if (!s.drainPassages && !s.reindexSourcePassages) return;
1251
+ const work = this.syncChain.then(async () => {
1252
+ try {
1253
+ if (s.drainPassages) await s.drainPassages({ entityId, deadline });
1254
+ else await s.reindexSourcePassages(db, prefix, entityId);
1255
+ } catch (err) {
1256
+ console.warn(`[WikiMemory] passage index sync failed for ${entityId ?? "*"}:`, err);
1257
+ }
1258
+ });
1259
+ this.syncChain = work;
1260
+ return work;
1261
+ }
1262
+ /**
1263
+ * Stored-source passage search for ONE entity (spec source-store section 7:
1264
+ * ranking and caps are per entity). Rides the active strategy; a strategy
1265
+ * without passage search yields none.
1266
+ */
1267
+ async searchPassages(query, entityId, limit) {
1268
+ if (!this.indexStrategy.searchPassages) return [];
1269
+ const hits = await this.indexStrategy.searchPassages(query, { entityIds: [entityId], limit });
1270
+ return hits.filter((h) => Number.isFinite(h.score) && h.entity_id === entityId).slice(0, limit);
1271
+ }
1238
1272
  /**
1239
1273
  * Pre-fetches keyword scores for candidate hydration, used during hybrid weighting.
1240
1274
  */
@@ -1391,7 +1425,8 @@ var JobManager = class {
1391
1425
  reembed: (id) => this._reembedKey(id),
1392
1426
  import: (id) => this._importKey(id),
1393
1427
  forget: (id) => this._forgetKey(id),
1394
- ontologyBackfill: (id) => this._ontologyBackfillKey(id)
1428
+ ontologyBackfill: (id) => this._ontologyBackfillKey(id),
1429
+ store: (id) => this._storeKey(id)
1395
1430
  };
1396
1431
  }
1397
1432
  _hashLockKey(entityId, sourceHash) {
@@ -1460,6 +1495,9 @@ var JobManager = class {
1460
1495
  _librarianKey(entityId) {
1461
1496
  return `${this.prefix}:${entityId}:librarian`;
1462
1497
  }
1498
+ _storeKey(entityId) {
1499
+ return `${this.prefix}:${entityId}:store`;
1500
+ }
1463
1501
  _healKey(entityId) {
1464
1502
  return `${this.prefix}:${entityId}:heal`;
1465
1503
  }
@@ -1488,6 +1526,9 @@ var JobManager = class {
1488
1526
  _isImportActiveFor(entityId) {
1489
1527
  return this.activeMaintenanceJobs.has(this._importKey(entityId)) || this.activeMaintenanceJobs.has(this._globalImportKey());
1490
1528
  }
1529
+ _isStoreActiveFor(entityId) {
1530
+ return this.activeMaintenanceJobs.has(this._storeKey(entityId));
1531
+ }
1491
1532
  _isForgetActiveFor(entityId) {
1492
1533
  return this.activeMaintenanceJobs.has(this._forgetKey(entityId));
1493
1534
  }
@@ -1537,6 +1578,7 @@ var JobManager = class {
1537
1578
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
1538
1579
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
1539
1580
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
1581
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
1540
1582
  break;
1541
1583
  case "librarian":
1542
1584
  case "heal":
@@ -1547,6 +1589,7 @@ var JobManager = class {
1547
1589
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
1548
1590
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
1549
1591
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
1592
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
1550
1593
  break;
1551
1594
  }
1552
1595
  case "reembed":
@@ -1559,6 +1602,7 @@ var JobManager = class {
1559
1602
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
1560
1603
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
1561
1604
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
1605
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
1562
1606
  break;
1563
1607
  case "global_reembed":
1564
1608
  if (this.activeMaintenanceJobs.has(this._globalReembedKey())) blockingOperation = "reembed";
@@ -1570,6 +1614,7 @@ var JobManager = class {
1570
1614
  else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
1571
1615
  else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
1572
1616
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
1617
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
1573
1618
  break;
1574
1619
  case "import":
1575
1620
  case "forget": {
@@ -1583,10 +1628,23 @@ var JobManager = class {
1583
1628
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
1584
1629
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
1585
1630
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
1631
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
1586
1632
  break;
1587
1633
  }
1634
+ case "store":
1635
+ if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
1636
+ else if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
1637
+ else if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) blockingOperation = "librarian";
1638
+ else if (this.activeMaintenanceJobs.has(this._healKey(entityId))) blockingOperation = "heal";
1639
+ else if (this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId))) blockingOperation = "ontologyBackfill";
1640
+ else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
1641
+ else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
1642
+ else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
1643
+ else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
1644
+ break;
1588
1645
  case "global_import":
1589
1646
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) blockingOperation = "import";
1647
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
1590
1648
  break;
1591
1649
  case "ingest": {
1592
1650
  const sourceKey = sourceRef ?? "";
@@ -1595,6 +1653,7 @@ var JobManager = class {
1595
1653
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
1596
1654
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
1597
1655
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
1656
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
1598
1657
  break;
1599
1658
  }
1600
1659
  }
@@ -1637,22 +1696,24 @@ var JobManager = class {
1637
1696
  case "librarian":
1638
1697
  case "heal":
1639
1698
  case "ontologyBackfill":
1640
- return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
1699
+ 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);
1641
1700
  case "prune":
1642
- 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);
1701
+ 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);
1643
1702
  case "reembed":
1644
- 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);
1703
+ 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);
1645
1704
  case "global_reembed":
1646
- 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");
1705
+ 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");
1647
1706
  case "import":
1648
1707
  case "forget": {
1649
1708
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
1650
- 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);
1709
+ 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);
1651
1710
  }
1711
+ case "store":
1712
+ 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);
1652
1713
  case "global_import":
1653
- return this.activeMaintenanceJobs.has(this._globalImportKey());
1714
+ return this.activeMaintenanceJobs.has(this._globalImportKey()) || this._isAnyMaintenanceActiveWithSuffix(":store");
1654
1715
  case "ingest":
1655
- return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
1716
+ return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
1656
1717
  default:
1657
1718
  return false;
1658
1719
  }
@@ -1717,6 +1778,7 @@ var JobManager = class {
1717
1778
  if (this._isReembedActive(entityId)) throw new WikiBusyError("reembed", entityId);
1718
1779
  if (this._isIngestActiveFor(entityId)) throw new WikiBusyError("ingest", entityId);
1719
1780
  if (this._isForgetActiveFor(entityId)) throw new WikiBusyError("forget", entityId);
1781
+ if (this._isStoreActiveFor(entityId)) throw new WikiBusyError("store", entityId);
1720
1782
  }
1721
1783
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) throw new WikiBusyError("import", "*");
1722
1784
  this.activeMaintenanceJobs.add(this._globalImportKey());
@@ -2177,6 +2239,10 @@ ${JSON.stringify(facts, null, 2)}`
2177
2239
  systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
2178
2240
  userPrompt: `Events:
2179
2241
  ${lines.join("\n")}`,
2242
+ // Corpus entries are one-per-batch-event in batch order (summaries are
2243
+ // TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
2244
+ // nothing): extract.ts stores a candidate's `sourcePartIndex` as the
2245
+ // batch index and buildSourcePointer reads the quote back by it.
2180
2246
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
2181
2247
  };
2182
2248
  }
@@ -2276,7 +2342,14 @@ var SEVERITY = {
2276
2342
  external_deletion_pending: "warn",
2277
2343
  external_deletion_discarded: "warn",
2278
2344
  guidance_too_long: "warn",
2279
- guidance_resolver_failed: "warn"
2345
+ guidance_resolver_failed: "warn",
2346
+ source_pointer_unresolved: "warn",
2347
+ source_pointer_invalid: "warn",
2348
+ source_store_source_too_large: "warn",
2349
+ source_store_budget_exceeded: "warn",
2350
+ source_store_hash_mismatch: "warn",
2351
+ source_store_duplicate_hash: "warn",
2352
+ source_store_text_not_storable: "warn"
2280
2353
  };
2281
2354
  var MESSAGE = {
2282
2355
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -2304,7 +2377,14 @@ var MESSAGE = {
2304
2377
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
2305
2378
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
2306
2379
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
2307
- guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
2380
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
2381
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
2382
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
2383
+ source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
2384
+ source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
2385
+ source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
2386
+ source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
2387
+ source_store_text_not_storable: "A source document text could not be stored as given."
2308
2388
  };
2309
2389
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
2310
2390
  function copyDetail(detail) {
@@ -4374,7 +4454,8 @@ async function setupDatabase(db, prefix) {
4374
4454
  valid_from INTEGER,
4375
4455
  valid_to INTEGER,
4376
4456
  superseded_by TEXT,
4377
- superseded_at INTEGER
4457
+ superseded_at INTEGER,
4458
+ source_pointer TEXT
4378
4459
  );
4379
4460
 
4380
4461
  CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
@@ -4400,6 +4481,29 @@ async function setupDatabase(db, prefix) {
4400
4481
  ON ${prefix}source_ref_index (entity_id, source_hash)
4401
4482
  WHERE deleted_at IS NULL;
4402
4483
 
4484
+ -- source_documents / source_passages: the source store (specs/source-store \xA73).
4485
+ -- New tables only; hard delete, so no deleted_at and both UNIQUE indexes are plain.
4486
+ -- Passage text is not stored: offsets (UTF-16 code units) slice source_documents.text.
4487
+ CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
4488
+ id TEXT PRIMARY KEY,
4489
+ entity_id TEXT NOT NULL,
4490
+ source_ref TEXT NOT NULL,
4491
+ source_hash TEXT NOT NULL,
4492
+ text TEXT NOT NULL,
4493
+ text_hash TEXT NOT NULL,
4494
+ char_count INTEGER NOT NULL,
4495
+ created_at INTEGER NOT NULL
4496
+ );
4497
+
4498
+ CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
4499
+ id TEXT PRIMARY KEY,
4500
+ entity_id TEXT NOT NULL,
4501
+ document_id TEXT NOT NULL,
4502
+ seq INTEGER NOT NULL,
4503
+ start_offset INTEGER NOT NULL,
4504
+ end_offset INTEGER NOT NULL
4505
+ );
4506
+
4403
4507
  CREATE TABLE IF NOT EXISTS ${prefix}tasks (
4404
4508
  id TEXT PRIMARY KEY,
4405
4509
  entity_id TEXT NOT NULL,
@@ -4526,6 +4630,8 @@ async function setupDatabase(db, prefix) {
4526
4630
  `);
4527
4631
  await createOkfV02IndexesIfColumnsExist(db, prefix);
4528
4632
  await createTemporalIndexesIfColumnsExist(db, prefix);
4633
+ await createSourcePassageIndexesIfColumnsExist(db, prefix);
4634
+ await createSourceDocumentIndexesIfColumnsExist(db, prefix);
4529
4635
  await createResurrectTrigger(db, prefix);
4530
4636
  }
4531
4637
  var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
@@ -4592,6 +4698,22 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
4592
4698
  );
4593
4699
  }
4594
4700
  }
4701
+ async function createSourcePassageIndexesIfColumnsExist(db, prefix) {
4702
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}source_passages)`);
4703
+ const names = new Set(cols.map((c) => c.name));
4704
+ if (!names.has("document_id") || !names.has("entity_id")) return;
4705
+ await db.execAsync(`
4706
+ CREATE INDEX IF NOT EXISTS ${prefix}idx_source_passages_doc ON ${prefix}source_passages (document_id, seq);
4707
+ CREATE INDEX IF NOT EXISTS ${prefix}idx_source_passages_entity ON ${prefix}source_passages (entity_id);`);
4708
+ }
4709
+ async function createSourceDocumentIndexesIfColumnsExist(db, prefix) {
4710
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}source_documents)`);
4711
+ const names = new Set(cols.map((c) => c.name));
4712
+ if (!names.has("entity_id") || !names.has("source_ref") || !names.has("source_hash")) return;
4713
+ await db.execAsync(`
4714
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref ON ${prefix}source_documents (entity_id, source_ref);
4715
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash ON ${prefix}source_documents (entity_id, source_hash);`);
4716
+ }
4595
4717
 
4596
4718
  // src/services/search/fts5Sql.ts
4597
4719
  var FTS5_STATE_KEY = "fts5_index_state";
@@ -4729,6 +4851,38 @@ function sweepChunkSql(p) {
4729
4851
  `DELETE FROM ${p}fts_map WHERE fts_rowid IN (${orphans})`
4730
4852
  ];
4731
4853
  }
4854
+ function passageFtsTriggerNames(p) {
4855
+ return [`${p}source_passages_fts_ai`, `${p}source_passages_fts_ad`];
4856
+ }
4857
+ function passageFtsTablesDdl(p) {
4858
+ return `
4859
+ CREATE VIRTUAL TABLE IF NOT EXISTS ${p}source_passages_fts USING fts5(
4860
+ passage_id UNINDEXED, entity_id UNINDEXED, doc_id UNINDEXED, text,
4861
+ tokenize = 'porter unicode61'
4862
+ );
4863
+ CREATE TABLE IF NOT EXISTS ${p}source_passages_fts_map (
4864
+ fts_rowid INTEGER PRIMARY KEY,
4865
+ passage_id TEXT NOT NULL UNIQUE,
4866
+ doc_id TEXT NOT NULL
4867
+ );
4868
+ CREATE INDEX IF NOT EXISTS ${p}source_passages_fts_map_doc ON ${p}source_passages_fts_map(doc_id);
4869
+ CREATE TABLE IF NOT EXISTS ${p}source_passages_fts_pending (
4870
+ seq INTEGER PRIMARY KEY,
4871
+ entity_id TEXT NOT NULL,
4872
+ doc_id TEXT NOT NULL
4873
+ );
4874
+ CREATE INDEX IF NOT EXISTS ${p}source_passages_fts_pending_doc ON ${p}source_passages_fts_pending(doc_id);`;
4875
+ }
4876
+ function passageFtsTriggersDdl(p) {
4877
+ const [ai, ad] = passageFtsTriggerNames(p);
4878
+ return `
4879
+ CREATE TRIGGER IF NOT EXISTS ${ai} AFTER INSERT ON ${p}source_passages BEGIN
4880
+ INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id) VALUES (NEW.entity_id, NEW.document_id);
4881
+ END;
4882
+ CREATE TRIGGER IF NOT EXISTS ${ad} AFTER DELETE ON ${p}source_passages BEGIN
4883
+ INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id) VALUES (OLD.entity_id, OLD.document_id);
4884
+ END;`;
4885
+ }
4732
4886
 
4733
4887
  // src/db/migrations.ts
4734
4888
  var MIGRATIONS = [
@@ -5023,6 +5177,68 @@ var MIGRATIONS = [
5023
5177
  );
5024
5178
  if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
5025
5179
  }
5180
+ },
5181
+ {
5182
+ version: 16,
5183
+ description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
5184
+ run: async (db, prefix) => {
5185
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
5186
+ const existing = new Set(cols.map((c) => c.name));
5187
+ if (!existing.has("source_pointer")) {
5188
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
5189
+ }
5190
+ }
5191
+ },
5192
+ {
5193
+ version: 17,
5194
+ description: "add_source_store",
5195
+ run: async (db, prefix) => {
5196
+ const expected = {
5197
+ source_documents: ["id", "entity_id", "source_ref", "source_hash", "text", "text_hash", "char_count", "created_at"],
5198
+ source_passages: ["id", "entity_id", "document_id", "seq", "start_offset", "end_offset"]
5199
+ };
5200
+ for (const [table, want] of Object.entries(expected)) {
5201
+ const full = `${prefix}${table}`;
5202
+ const cols = (await db.getAllAsync(`PRAGMA table_info(${full})`)).map((c) => c.name);
5203
+ if (cols.length === 0) continue;
5204
+ const same = cols.length === want.length && want.every((c) => cols.includes(c));
5205
+ if (!same) {
5206
+ throw new Error(
5207
+ `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().`
5208
+ );
5209
+ }
5210
+ const row = await db.getFirstAsync(`SELECT COUNT(*) AS n FROM ${full}`);
5211
+ if (row && row.n > 0) {
5212
+ throw new Error(
5213
+ `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().`
5214
+ );
5215
+ }
5216
+ }
5217
+ await db.execAsync(
5218
+ `CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
5219
+ id TEXT PRIMARY KEY,
5220
+ entity_id TEXT NOT NULL,
5221
+ source_ref TEXT NOT NULL,
5222
+ source_hash TEXT NOT NULL,
5223
+ text TEXT NOT NULL,
5224
+ text_hash TEXT NOT NULL,
5225
+ char_count INTEGER NOT NULL,
5226
+ created_at INTEGER NOT NULL
5227
+ );
5228
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref
5229
+ ON ${prefix}source_documents (entity_id, source_ref);
5230
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash
5231
+ ON ${prefix}source_documents (entity_id, source_hash);
5232
+ CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
5233
+ id TEXT PRIMARY KEY,
5234
+ entity_id TEXT NOT NULL,
5235
+ document_id TEXT NOT NULL,
5236
+ seq INTEGER NOT NULL,
5237
+ start_offset INTEGER NOT NULL,
5238
+ end_offset INTEGER NOT NULL
5239
+ );`
5240
+ );
5241
+ }
5026
5242
  }
5027
5243
  ];
5028
5244
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -5291,9 +5507,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
5291
5507
  access_count: 0,
5292
5508
  deleted_at: null,
5293
5509
  okf_type: normalized.okf_type,
5510
+ // Legacy writes no pointer (spec §Legacy path): the column stays null
5511
+ // on every legacy fact, and the legacy prompt keeps its exact text.
5512
+ source_pointer: null,
5294
5513
  ...grounding?.trust
5295
5514
  };
5296
5515
  await deps.entryRepo.upsert(factObj, tx);
5516
+ const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
5517
+ if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
5518
+ diagBuffer.push({
5519
+ ...diagBase,
5520
+ code: "source_pointer_unresolved",
5521
+ detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
5522
+ });
5523
+ }
5297
5524
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
5298
5525
  factsForDedupe.push(factObj);
5299
5526
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
@@ -5407,9 +5634,23 @@ async function runExtract(deps, ctx, batch) {
5407
5634
  return;
5408
5635
  }
5409
5636
  const r = raw;
5410
- const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
5637
+ let sourceEventId = null;
5638
+ let sourcePartIndex = null;
5639
+ let pointerUnresolved;
5640
+ const rawSourceEvent = r.source_event;
5641
+ if (rawSourceEvent === void 0 || rawSourceEvent === null) {
5642
+ pointerUnresolved = "missing";
5643
+ } else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
5644
+ const labeled = byLabel.get(rawSourceEvent);
5645
+ sourceEventId = labeled.event.id;
5646
+ sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
5647
+ pointerUnresolved = null;
5648
+ } else {
5649
+ pointerUnresolved = "unknown_label";
5650
+ }
5651
+ const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
5411
5652
  const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
5412
- candidates.push({ index, fact, sourceLabel, validFrom });
5653
+ candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
5413
5654
  });
5414
5655
  const tasks = [];
5415
5656
  (Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
@@ -5686,6 +5927,17 @@ var TemporalService = class {
5686
5927
  };
5687
5928
 
5688
5929
  // src/services/librarian/ops/apply.ts
5930
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
5931
+ if (candidate.sourceEventId === null) return null;
5932
+ let quote = null;
5933
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
5934
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
5935
+ if (part !== void 0) {
5936
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
5937
+ }
5938
+ }
5939
+ return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
5940
+ }
5689
5941
  async function applyOps(deps, ctx, input) {
5690
5942
  const { entityId, trigger } = ctx;
5691
5943
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -5714,7 +5966,8 @@ async function applyOps(deps, ctx, input) {
5714
5966
  const drops = [];
5715
5967
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
5716
5968
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
5717
- const g2 = grounding ? groundingOutcome(checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding), now) : null;
5969
+ const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
5970
+ const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
5718
5971
  if (g2?.diagnostic) {
5719
5972
  input.diagnostics.push({
5720
5973
  ...diagBase,
@@ -5722,6 +5975,7 @@ async function applyOps(deps, ctx, input) {
5722
5975
  detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
5723
5976
  });
5724
5977
  }
5978
+ const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
5725
5979
  const row = {
5726
5980
  id,
5727
5981
  entity_id: entityId,
@@ -5738,11 +5992,19 @@ async function applyOps(deps, ctx, input) {
5738
5992
  access_count: 0,
5739
5993
  deleted_at: null,
5740
5994
  okf_type: normalized.okf_type,
5995
+ source_pointer: pointer,
5741
5996
  ...g2?.trust,
5742
5997
  ...draft ? { lifecycle_status: "draft" } : {}
5743
5998
  };
5744
5999
  await deps.entryRepo.upsert(row, tx);
5745
6000
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
6001
+ if (g.candidate.pointerUnresolved !== null) {
6002
+ input.diagnostics.push({
6003
+ ...diagBase,
6004
+ code: "source_pointer_unresolved",
6005
+ detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
6006
+ });
6007
+ }
5746
6008
  titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
5747
6009
  if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
5748
6010
  const textChanged = title !== fact.title || body !== fact.body;
@@ -6295,6 +6557,10 @@ var MaintenanceService = class {
6295
6557
  if (await this.sourceRefIndexPresent(tx)) {
6296
6558
  await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
6297
6559
  }
6560
+ if (await this.sourceStorePresent(tx)) {
6561
+ await tx.runAsync(`DELETE FROM ${this.prefix}source_passages WHERE entity_id = ?`, [entityId]);
6562
+ await tx.runAsync(`DELETE FROM ${this.prefix}source_documents WHERE entity_id = ?`, [entityId]);
6563
+ }
6298
6564
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
6299
6565
  if (params.includeEvents) {
6300
6566
  deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
@@ -6318,6 +6584,16 @@ var MaintenanceService = class {
6318
6584
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
6319
6585
  if (entryId) deletedEntryIds.push(entryId);
6320
6586
  }
6587
+ if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
6588
+ const docs = `${this.prefix}source_documents`;
6589
+ const sel = "entity_id = ? AND (? IS NULL OR source_ref = ?) AND (? IS NULL OR source_hash = ?)";
6590
+ const selArgs = [entityId, sourceRef, sourceRef, sourceHash, sourceHash];
6591
+ await tx.runAsync(
6592
+ `DELETE FROM ${this.prefix}source_passages WHERE entity_id = ? AND document_id IN (SELECT id FROM ${docs} WHERE ${sel})`,
6593
+ [entityId, ...selArgs]
6594
+ );
6595
+ await tx.runAsync(`DELETE FROM ${docs} WHERE ${sel}`, selArgs);
6596
+ }
6321
6597
  if (sourceRef || sourceHash) {
6322
6598
  for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
6323
6599
  }
@@ -6434,6 +6710,10 @@ var MaintenanceService = class {
6434
6710
  if (version < 9) return false;
6435
6711
  throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
6436
6712
  }
6713
+ /** A never-set-up store has no source-store tables (#316 recovery); nothing to delete there. */
6714
+ async sourceStorePresent(tx) {
6715
+ return await this.metadataRepo.tableExists(`${this.prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${this.prefix}source_passages`, tx);
6716
+ }
6437
6717
  /**
6438
6718
  * Read-only dry-run preview of {@link forget}. Returns the same shape as a
6439
6719
  * real call would, without acquiring the lock, opening a transaction, staging
@@ -6766,6 +7046,7 @@ var MaintenanceService = class {
6766
7046
  source_type: "librarian_inferred",
6767
7047
  source_hash: null,
6768
7048
  source_ref: null,
7049
+ source_pointer: null,
6769
7050
  created_at: now,
6770
7051
  updated_at: now,
6771
7052
  last_accessed_at: null,
@@ -7167,6 +7448,413 @@ var MaintenanceService = class {
7167
7448
  }
7168
7449
  };
7169
7450
 
7451
+ // src/utils/passageCutter.ts
7452
+ var MAX_PASSAGE_UNITS = 12e3;
7453
+ var WHITESPACE = /\s/;
7454
+ function isHigh(code) {
7455
+ return code >= 55296 && code <= 56319;
7456
+ }
7457
+ function isLow(code) {
7458
+ return code >= 56320 && code <= 57343;
7459
+ }
7460
+ function cutPassages(text, maxUnits = MAX_PASSAGE_UNITS) {
7461
+ const limit = Math.max(2, Math.floor(maxUnits));
7462
+ const spans = [];
7463
+ let start = 0;
7464
+ while (start < text.length) {
7465
+ if (text.length - start <= limit) {
7466
+ spans.push({ start, end: text.length });
7467
+ break;
7468
+ }
7469
+ let end = start + limit;
7470
+ let cut = -1;
7471
+ for (let i = end - 1; i > start; i--) {
7472
+ if (WHITESPACE.test(text[i])) {
7473
+ cut = i + 1;
7474
+ break;
7475
+ }
7476
+ }
7477
+ if (cut > start) {
7478
+ end = cut;
7479
+ } else if (isHigh(text.charCodeAt(end - 1)) && isLow(text.charCodeAt(end))) {
7480
+ end -= 1;
7481
+ }
7482
+ spans.push({ start, end });
7483
+ start = end;
7484
+ }
7485
+ return spans;
7486
+ }
7487
+
7488
+ // src/utils/sha256.ts
7489
+ var K = new Uint32Array([
7490
+ 1116352408,
7491
+ 1899447441,
7492
+ 3049323471,
7493
+ 3921009573,
7494
+ 961987163,
7495
+ 1508970993,
7496
+ 2453635748,
7497
+ 2870763221,
7498
+ 3624381080,
7499
+ 310598401,
7500
+ 607225278,
7501
+ 1426881987,
7502
+ 1925078388,
7503
+ 2162078206,
7504
+ 2614888103,
7505
+ 3248222580,
7506
+ 3835390401,
7507
+ 4022224774,
7508
+ 264347078,
7509
+ 604807628,
7510
+ 770255983,
7511
+ 1249150122,
7512
+ 1555081692,
7513
+ 1996064986,
7514
+ 2554220882,
7515
+ 2821834349,
7516
+ 2952996808,
7517
+ 3210313671,
7518
+ 3336571891,
7519
+ 3584528711,
7520
+ 113926993,
7521
+ 338241895,
7522
+ 666307205,
7523
+ 773529912,
7524
+ 1294757372,
7525
+ 1396182291,
7526
+ 1695183700,
7527
+ 1986661051,
7528
+ 2177026350,
7529
+ 2456956037,
7530
+ 2730485921,
7531
+ 2820302411,
7532
+ 3259730800,
7533
+ 3345764771,
7534
+ 3516065817,
7535
+ 3600352804,
7536
+ 4094571909,
7537
+ 275423344,
7538
+ 430227734,
7539
+ 506948616,
7540
+ 659060556,
7541
+ 883997877,
7542
+ 958139571,
7543
+ 1322822218,
7544
+ 1537002063,
7545
+ 1747873779,
7546
+ 1955562222,
7547
+ 2024104815,
7548
+ 2227730452,
7549
+ 2361852424,
7550
+ 2428436474,
7551
+ 2756734187,
7552
+ 3204031479,
7553
+ 3329325298
7554
+ ]);
7555
+ var rotr = (x, n) => x >>> n | x << 32 - n;
7556
+ var IV = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
7557
+ function compress(H, W, view, off) {
7558
+ for (let t = 0; t < 16; t++) W[t] = view.getUint32(off + t * 4);
7559
+ for (let t = 16; t < 64; t++) {
7560
+ const s0 = rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ W[t - 15] >>> 3;
7561
+ const s1 = rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ W[t - 2] >>> 10;
7562
+ W[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;
7563
+ }
7564
+ 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];
7565
+ for (let t = 0; t < 64; t++) {
7566
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
7567
+ const ch = e & f ^ ~e & g;
7568
+ const t1 = h + S1 + ch + K[t] + W[t] >>> 0;
7569
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
7570
+ const maj = a & b ^ a & c ^ b & c;
7571
+ const t2 = S0 + maj >>> 0;
7572
+ h = g;
7573
+ g = f;
7574
+ f = e;
7575
+ e = d + t1 >>> 0;
7576
+ d = c;
7577
+ c = b;
7578
+ b = a;
7579
+ a = t1 + t2 >>> 0;
7580
+ }
7581
+ H[0] = H[0] + a >>> 0;
7582
+ H[1] = H[1] + b >>> 0;
7583
+ H[2] = H[2] + c >>> 0;
7584
+ H[3] = H[3] + d >>> 0;
7585
+ H[4] = H[4] + e >>> 0;
7586
+ H[5] = H[5] + f >>> 0;
7587
+ H[6] = H[6] + g >>> 0;
7588
+ H[7] = H[7] + h >>> 0;
7589
+ }
7590
+ function sha256(bytes) {
7591
+ const H = new Uint32Array(IV);
7592
+ const W = new Uint32Array(64);
7593
+ const whole = bytes.length - bytes.length % 64;
7594
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
7595
+ for (let off = 0; off < whole; off += 64) compress(H, W, view, off);
7596
+ const rest = bytes.subarray(whole);
7597
+ const bitLen = bytes.length * 8;
7598
+ const padded = new Uint8Array(rest.length + 9 + 63 >> 6 << 6);
7599
+ padded.set(rest);
7600
+ padded[rest.length] = 128;
7601
+ const pv = new DataView(padded.buffer);
7602
+ pv.setUint32(padded.length - 8, Math.floor(bitLen / 4294967296));
7603
+ pv.setUint32(padded.length - 4, bitLen >>> 0);
7604
+ for (let off = 0; off < padded.length; off += 64) compress(H, W, pv, off);
7605
+ const out = new Uint8Array(32);
7606
+ const outView = new DataView(out.buffer);
7607
+ for (let i = 0; i < 8; i++) outView.setUint32(i * 4, H[i]);
7608
+ return out;
7609
+ }
7610
+ function utf8Encode(s) {
7611
+ const out = [];
7612
+ for (let i = 0; i < s.length; i++) {
7613
+ let cp = s.charCodeAt(i);
7614
+ if (cp >= 55296 && cp <= 56319) {
7615
+ const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
7616
+ if (next >= 56320 && next <= 57343) {
7617
+ cp = 65536 + (cp - 55296 << 10) + (next - 56320);
7618
+ i++;
7619
+ } else {
7620
+ cp = 65533;
7621
+ }
7622
+ } else if (cp >= 56320 && cp <= 57343) {
7623
+ cp = 65533;
7624
+ }
7625
+ if (cp < 128) out.push(cp);
7626
+ else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63);
7627
+ else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
7628
+ else out.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
7629
+ }
7630
+ return Uint8Array.from(out);
7631
+ }
7632
+ function sha256Hex(text) {
7633
+ let hex = "";
7634
+ for (const b of sha256(utf8Encode(text))) hex += b.toString(16).padStart(2, "0");
7635
+ return hex;
7636
+ }
7637
+
7638
+ // src/services/sourceStoreUpsert.ts
7639
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
7640
+ async function upsertStoredSource(tx, prefix, entityId, src, limits, onRefusal, opts = {}) {
7641
+ const { sourceRef, sourceHash, text } = src;
7642
+ const refuse = (code) => {
7643
+ onRefusal(code);
7644
+ return { status: "refused" };
7645
+ };
7646
+ if (text.includes("\0") || LONE_SURROGATE.test(text)) return refuse("source_store_text_not_storable");
7647
+ if (text.length > limits.maxCharsPerSource) return refuse("source_store_source_too_large");
7648
+ const textHash = sha256Hex(text);
7649
+ const charCount = text.length;
7650
+ const docs = `${prefix}source_documents`;
7651
+ const passages = `${prefix}source_passages`;
7652
+ const registry = `${prefix}source_ref_index`;
7653
+ const existing = await tx.getFirstAsync(
7654
+ `SELECT id, source_hash, text_hash, char_count, created_at FROM ${docs}
7655
+ WHERE entity_id = ? AND source_ref = ?`,
7656
+ [entityId, sourceRef]
7657
+ );
7658
+ if (opts.idempotentSamePair && existing && existing.source_hash === sourceHash) {
7659
+ if (existing.text_hash !== textHash) return refuse("source_store_hash_mismatch");
7660
+ const row = await tx.getFirstAsync(
7661
+ `SELECT COUNT(*) AS n FROM ${passages} WHERE entity_id = ? AND document_id = ?`,
7662
+ [entityId, existing.id]
7663
+ );
7664
+ return { status: "stored", charCount: existing.char_count, passageCount: row?.n ?? 0, storedAt: existing.created_at };
7665
+ }
7666
+ const heldByStore = await tx.getFirstAsync(
7667
+ `SELECT source_ref FROM ${docs} WHERE entity_id = ? AND source_hash = ? AND source_ref <> ?`,
7668
+ [entityId, sourceHash, sourceRef]
7669
+ );
7670
+ const heldByFacts = await tx.getFirstAsync(
7671
+ `SELECT source_ref FROM ${registry}
7672
+ WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL AND source_ref <> ?`,
7673
+ [entityId, sourceHash, sourceRef]
7674
+ );
7675
+ if (heldByStore || heldByFacts) return refuse("source_store_duplicate_hash");
7676
+ const total = await tx.getFirstAsync(
7677
+ `SELECT COALESCE(SUM(char_count), 0) AS n FROM ${docs} WHERE entity_id = ? AND source_ref <> ?`,
7678
+ [entityId, sourceRef]
7679
+ );
7680
+ if ((total?.n ?? 0) + charCount > limits.maxTotalChars) return refuse("source_store_budget_exceeded");
7681
+ if (existing) {
7682
+ await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ? AND document_id = ?`, [entityId, existing.id]);
7683
+ await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ? AND id = ?`, [entityId, existing.id]);
7684
+ }
7685
+ const id = generateId("sdoc_");
7686
+ const storedAt = typeof src.storedAt === "number" && Number.isFinite(src.storedAt) ? src.storedAt : Date.now();
7687
+ await tx.runAsync(
7688
+ `INSERT INTO ${docs} (id, entity_id, source_ref, source_hash, text, text_hash, char_count, created_at)
7689
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
7690
+ [id, entityId, sourceRef, sourceHash, text, textHash, charCount, storedAt]
7691
+ );
7692
+ const spans = cutPassages(text);
7693
+ for (let seq = 0; seq < spans.length; seq++) {
7694
+ await tx.runAsync(
7695
+ `INSERT INTO ${passages} (id, entity_id, document_id, seq, start_offset, end_offset) VALUES (?, ?, ?, ?, ?, ?)`,
7696
+ [generateId("spas_"), entityId, id, seq, spans[seq].start, spans[seq].end]
7697
+ );
7698
+ }
7699
+ return { status: "stored", charCount, passageCount: spans.length, storedAt };
7700
+ }
7701
+
7702
+ // src/services/SourceStoreService.ts
7703
+ var DEFAULT_MAX_CHARS_PER_SOURCE = 2e5;
7704
+ var DEFAULT_MAX_TOTAL_CHARS = 5e6;
7705
+ function limitOr(value, fallback) {
7706
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
7707
+ }
7708
+ var SourceStoreService = class {
7709
+ constructor(db, prefix, options, jobManager) {
7710
+ this.db = db;
7711
+ this.prefix = prefix;
7712
+ this.options = options;
7713
+ this.jobManager = jobManager;
7714
+ }
7715
+ limits() {
7716
+ const cfg = this.options.config?.sourceStore;
7717
+ return {
7718
+ maxCharsPerSource: limitOr(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
7719
+ maxTotalChars: limitOr(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
7720
+ };
7721
+ }
7722
+ refuse(entityId, code, sourceRef) {
7723
+ const captured = [];
7724
+ const input = { code, operation: "sourceStore", trigger: "call", entityId, detail: { sourceRef } };
7725
+ emitDiagnostic({ onDiagnostic: (d) => {
7726
+ captured.push(d);
7727
+ } }, input);
7728
+ emitDiagnostic(this.options, input);
7729
+ return { stored: false, diagnostics: captured };
7730
+ }
7731
+ async storeSource(entityId, params) {
7732
+ const sourceRef = normalizeSourceRef(params.sourceRef);
7733
+ if (!sourceRef) throw new Error("Invalid sourceRef");
7734
+ const sourceHash = normalizeSourceHash(params.sourceHash);
7735
+ if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
7736
+ if (typeof params.text !== "string") throw new Error(`text must be a string, received ${typeof params.text}`);
7737
+ const text = params.text;
7738
+ this.jobManager.acquireLock("store", entityId);
7739
+ try {
7740
+ const limits = this.limits();
7741
+ let refused;
7742
+ const outcome = await this.db.withTransactionAsync((tx) => upsertStoredSource(
7743
+ tx,
7744
+ this.prefix,
7745
+ entityId,
7746
+ { sourceRef, sourceHash, text },
7747
+ limits,
7748
+ (code) => {
7749
+ refused = code;
7750
+ },
7751
+ { idempotentSamePair: true }
7752
+ ));
7753
+ if (outcome.status === "refused") return this.refuse(entityId, refused, sourceRef);
7754
+ return {
7755
+ stored: true,
7756
+ sourceRef,
7757
+ sourceHash,
7758
+ charCount: outcome.charCount,
7759
+ passageCount: outcome.passageCount,
7760
+ storedAt: outcome.storedAt
7761
+ };
7762
+ } finally {
7763
+ this.jobManager.releaseLock("store", entityId);
7764
+ }
7765
+ }
7766
+ /** Spec §7: the text exactly as handed, or null. Plain read, no write lock. */
7767
+ async getStoredSource(entityId, sourceRef) {
7768
+ const ref = normalizeSourceRef(sourceRef);
7769
+ if (!ref) return null;
7770
+ const row = await this.db.getFirstAsync(
7771
+ `SELECT source_ref, source_hash, text, char_count, created_at FROM ${this.prefix}source_documents
7772
+ WHERE entity_id = ? AND source_ref = ?`,
7773
+ [entityId, ref]
7774
+ );
7775
+ if (!row) return null;
7776
+ return {
7777
+ sourceRef: row.source_ref,
7778
+ sourceHash: row.source_hash,
7779
+ text: row.text,
7780
+ charCount: Number(row.char_count),
7781
+ storedAt: Number(row.created_at)
7782
+ };
7783
+ }
7784
+ /** Spec §4/§7: full store listing, including sources stored with no ingest. */
7785
+ async listStoredSources(entityId) {
7786
+ const rows = await this.db.getAllAsync(
7787
+ `SELECT d.source_ref, d.source_hash, d.char_count, d.created_at,
7788
+ (SELECT COUNT(*) FROM ${this.prefix}source_passages p
7789
+ WHERE p.entity_id = d.entity_id AND p.document_id = d.id) AS passage_count
7790
+ FROM ${this.prefix}source_documents d
7791
+ WHERE d.entity_id = ?
7792
+ ORDER BY d.source_ref COLLATE BINARY`,
7793
+ [entityId]
7794
+ );
7795
+ return rows.map((r) => ({
7796
+ sourceRef: r.source_ref,
7797
+ sourceHash: r.source_hash,
7798
+ charCount: Number(r.char_count),
7799
+ passageCount: Number(r.passage_count),
7800
+ storedAt: Number(r.created_at)
7801
+ }));
7802
+ }
7803
+ };
7804
+
7805
+ // src/utils/sourcePointer.ts
7806
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
7807
+ function isStringOrNull(v) {
7808
+ return v === null || typeof v === "string";
7809
+ }
7810
+ function isValidPosition(v) {
7811
+ if (v === null) return true;
7812
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
7813
+ const o = v;
7814
+ const keys = Object.keys(o);
7815
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
7816
+ const { start, length } = o;
7817
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
7818
+ }
7819
+ function validateSourcePointerValue(v) {
7820
+ if (v === null) return null;
7821
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
7822
+ const o = v;
7823
+ const keys = Object.keys(o);
7824
+ for (const k of keys) {
7825
+ if (!POINTER_SLOTS.includes(k)) return void 0;
7826
+ }
7827
+ 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"])) {
7828
+ return void 0;
7829
+ }
7830
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
7831
+ const normalized = {
7832
+ event_id: o["event_id"] ?? null,
7833
+ ref: o["ref"] ?? null,
7834
+ quote: o["quote"] ?? null,
7835
+ position: o["position"] ?? null
7836
+ };
7837
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
7838
+ return null;
7839
+ }
7840
+ return normalized;
7841
+ }
7842
+ function parseStoredSourcePointer(raw) {
7843
+ if (raw === null || raw === void 0) return null;
7844
+ if (typeof raw !== "string") return null;
7845
+ let parsed;
7846
+ try {
7847
+ parsed = JSON.parse(raw);
7848
+ } catch {
7849
+ return null;
7850
+ }
7851
+ const v = validateSourcePointerValue(parsed);
7852
+ return v === void 0 ? null : v;
7853
+ }
7854
+ function serializeSourcePointer(p) {
7855
+ return p ? JSON.stringify(p) : null;
7856
+ }
7857
+
7170
7858
  // src/services/importEventStamps.ts
7171
7859
  var DATE_MAX = 864e13;
7172
7860
  var DECIMAL_TEXT = /^\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*$/;
@@ -7229,7 +7917,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
7229
7917
  var IMPORT_TITLE_MAX = 500;
7230
7918
  var IMPORT_BODY_MAX = 8e3;
7231
7919
  var ImportExportService = class {
7232
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
7920
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
7233
7921
  this.db = db;
7234
7922
  this.entryRepo = entryRepo;
7235
7923
  this.taskRepo = taskRepo;
@@ -7241,6 +7929,7 @@ var ImportExportService = class {
7241
7929
  this.embeddingService = embeddingService;
7242
7930
  this.options = options;
7243
7931
  this.vectorRemoval = vectorRemoval;
7932
+ this.prefix = prefix;
7244
7933
  }
7245
7934
  async exportDump(entityIds) {
7246
7935
  let ids;
@@ -7248,6 +7937,13 @@ var ImportExportService = class {
7248
7937
  ids = Array.from(new Set(entityIds));
7249
7938
  } else {
7250
7939
  ids = await this.metadataRepo.getDistinctEntityIds();
7940
+ const prefix = this.storePrefix();
7941
+ if (prefix !== void 0 && await this.storePresent(prefix)) {
7942
+ const rows = await this.db.getAllAsync(
7943
+ `SELECT DISTINCT entity_id FROM ${prefix}source_documents`
7944
+ );
7945
+ ids = Array.from(/* @__PURE__ */ new Set([...ids, ...rows.map((r) => r.entity_id)])).sort();
7946
+ }
7251
7947
  }
7252
7948
  const entities = {};
7253
7949
  const BATCH = 3;
@@ -7255,10 +7951,11 @@ var ImportExportService = class {
7255
7951
  const batch = ids.slice(i, i + BATCH);
7256
7952
  const batchResults = await Promise.all(
7257
7953
  batch.map(
7258
- async (id) => [
7259
- id,
7260
- await this.getFullBundle(id, { includeBlobs: true })
7261
- ]
7954
+ async (id) => {
7955
+ const bundle = await this.getFullBundle(id, { includeBlobs: true });
7956
+ const storedSources = await this.exportStoredSources(id);
7957
+ return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
7958
+ }
7262
7959
  )
7263
7960
  );
7264
7961
  for (const [id, bundle] of batchResults) {
@@ -7269,16 +7966,96 @@ var ImportExportService = class {
7269
7966
  }
7270
7967
  async importDump(dump, opts) {
7271
7968
  const merge = opts?.merge ?? false;
7969
+ const skippedSources = [];
7272
7970
  const entityIds = Object.keys(dump.entities);
7273
7971
  this.jobManager.acquireImportLocks(entityIds);
7274
7972
  try {
7275
7973
  await this.assertNoLegacySourceTypes();
7276
7974
  for (const [entityId, bundle] of Object.entries(dump.entities)) {
7277
- await this.doImportEntity(entityId, bundle, merge);
7975
+ skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
7278
7976
  }
7279
7977
  } finally {
7280
7978
  this.jobManager.releaseImportLocks(entityIds);
7281
7979
  }
7980
+ return { skippedSources };
7981
+ }
7982
+ storePrefix() {
7983
+ return typeof this.prefix === "string" ? this.prefix : void 0;
7984
+ }
7985
+ // `source_ref_index` needs no check: the v9 migration (add_source_ref_index) creates it, and the
7986
+ // store tables come from v17, which only runs after v9 — so it exists whenever they do.
7987
+ async storePresent(prefix, tx) {
7988
+ return await this.metadataRepo.tableExists(`${prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${prefix}source_passages`, tx);
7989
+ }
7990
+ /** Spec source-store §8: stored sources for one exported entity; [] when none. */
7991
+ async exportStoredSources(entityId) {
7992
+ const prefix = this.storePrefix();
7993
+ if (prefix === void 0 || !await this.storePresent(prefix)) return [];
7994
+ const docs = await this.db.getAllAsync(
7995
+ `SELECT id, source_ref, source_hash, text, text_hash, char_count, created_at FROM ${prefix}source_documents
7996
+ WHERE entity_id = ? ORDER BY source_ref COLLATE BINARY`,
7997
+ [entityId]
7998
+ );
7999
+ const out = [];
8000
+ for (const d of docs) {
8001
+ const ps = await this.db.getAllAsync(
8002
+ `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages
8003
+ WHERE entity_id = ? AND document_id = ? ORDER BY seq`,
8004
+ [entityId, d.id]
8005
+ );
8006
+ out.push({
8007
+ sourceRef: d.source_ref,
8008
+ sourceHash: d.source_hash,
8009
+ text: d.text,
8010
+ textHash: d.text_hash,
8011
+ charCount: Number(d.char_count),
8012
+ storedAt: Number(d.created_at),
8013
+ passages: ps.map((p) => ({ seq: Number(p.seq), startOffset: Number(p.start_offset), endOffset: Number(p.end_offset) }))
8014
+ });
8015
+ }
8016
+ return out;
8017
+ }
8018
+ /**
8019
+ * Spec source-store §8/§9 import step, inside the import transaction. One
8020
+ * source at a time; a refusal skips that source only. Uses the
8021
+ * same upsert helper as SourceStoreService.storeSource, inside this transaction. A ref already stored is replaced: the dump is the
8022
+ * truth for that ref (so no hash_mismatch refusal on import).
8023
+ */
8024
+ async importStoredSources(tx, entityId, sources, merge, skipped, deferredDiagnostics) {
8025
+ const prefix = this.storePrefix();
8026
+ if (prefix === void 0) return;
8027
+ if (merge && !sources?.length) return;
8028
+ if (!await this.storePresent(prefix, tx)) return;
8029
+ const docs = `${prefix}source_documents`;
8030
+ const passages = `${prefix}source_passages`;
8031
+ if (!merge) {
8032
+ await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ?`, [entityId]);
8033
+ await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ?`, [entityId]);
8034
+ }
8035
+ const cfg = this.options.config?.sourceStore;
8036
+ const lim = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : d;
8037
+ const limits = {
8038
+ maxCharsPerSource: lim(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
8039
+ maxTotalChars: lim(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
8040
+ };
8041
+ for (const src of sources ?? []) {
8042
+ const sourceRef = normalizeSourceRef(src?.sourceRef);
8043
+ const sourceHash = normalizeSourceHash(src?.sourceHash);
8044
+ if (!sourceRef || !sourceHash || typeof src.text !== "string") {
8045
+ throw new Error(`importDump: invalid stored source for entity "${entityId}" (sourceRef, sourceHash and text are required)`);
8046
+ }
8047
+ await upsertStoredSource(
8048
+ tx,
8049
+ prefix,
8050
+ entityId,
8051
+ { sourceRef, sourceHash, text: src.text, storedAt: src.storedAt },
8052
+ limits,
8053
+ (code) => {
8054
+ skipped.push({ sourceRef, code });
8055
+ deferredDiagnostics.push({ code, operation: "importDump", trigger: "call", entityId, detail: { sourceRef } });
8056
+ }
8057
+ );
8058
+ }
7282
8059
  }
7283
8060
  async getFullBundle(entityId, opts) {
7284
8061
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
@@ -7317,6 +8094,8 @@ var ImportExportService = class {
7317
8094
  }
7318
8095
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
7319
8096
  async doImportEntity(entityId, bundle, merge) {
8097
+ const skippedSources = [];
8098
+ const refusalDiagnostics = [];
7320
8099
  const upsertedFactIds = /* @__PURE__ */ new Set();
7321
8100
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
7322
8101
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
@@ -7434,6 +8213,19 @@ var ImportExportService = class {
7434
8213
  );
7435
8214
  }
7436
8215
  }
8216
+ const hasSourcePointerKey = fact["source_pointer"] !== void 0;
8217
+ const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
8218
+ const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
8219
+ if (pointerValidated === void 0) {
8220
+ emitDiagnostic(this.options, {
8221
+ code: "source_pointer_invalid",
8222
+ operation: "importDump",
8223
+ trigger: "call",
8224
+ entityId,
8225
+ detail: { factId: fact.id }
8226
+ });
8227
+ }
8228
+ const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
7437
8229
  const factObj = {
7438
8230
  id: fact.id,
7439
8231
  entity_id: entityId,
@@ -7451,6 +8243,7 @@ var ImportExportService = class {
7451
8243
  deleted_at: fact.deleted_at,
7452
8244
  embedding_blob: blobData ?? void 0,
7453
8245
  okf_type: fact.okf_type ?? null,
8246
+ source_pointer: sourcePointer,
7454
8247
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
7455
8248
  // populating these per spec, importDump does not derive or validate them.
7456
8249
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -7468,7 +8261,7 @@ var ImportExportService = class {
7468
8261
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
7469
8262
  })()
7470
8263
  };
7471
- await this.entryRepo.upsertForImport(factObj, tx);
8264
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
7472
8265
  await this.entryRepo.setTemporal(fact.id, entityId, {
7473
8266
  valid_from: fact.valid_from ?? null,
7474
8267
  valid_to: fact.valid_to ?? null,
@@ -7580,7 +8373,9 @@ var ImportExportService = class {
7580
8373
  tx
7581
8374
  );
7582
8375
  }
8376
+ await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
7583
8377
  });
8378
+ for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
7584
8379
  if (clampedEvents > 0) {
7585
8380
  emitDiagnostic(this.options, {
7586
8381
  code: "event_created_at_clamped",
@@ -7748,6 +8543,7 @@ var ImportExportService = class {
7748
8543
  } finally {
7749
8544
  this.searchService.evictCache(entityId);
7750
8545
  }
8546
+ return skippedSources;
7751
8547
  }
7752
8548
  _warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
7753
8549
  console.warn(
@@ -8272,6 +9068,63 @@ function packFactsByBudget(items, budget, scores) {
8272
9068
 
8273
9069
  // src/services/RetrievalService.ts
8274
9070
  var EMPTY_ID_SET = /* @__PURE__ */ new Set();
9071
+ var DEFAULT_SOURCE_PASSAGES = 8;
9072
+ var DEFAULT_SOURCE_CHAR_BUDGET = 4e3;
9073
+ var asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
9074
+ var isHigh2 = (c) => c >= 55296 && c <= 56319;
9075
+ var isLow2 = (c) => c >= 56320 && c <= 57343;
9076
+ function queryTerms(query) {
9077
+ return [...new Set(asciiLower(query).split(/[^\p{L}\p{N}]+/u).filter((t) => t.length > 0))];
9078
+ }
9079
+ function assertSourcesQuery(opt) {
9080
+ const query = opt?.query;
9081
+ if (typeof query !== "string" || query.trim() === "") {
9082
+ throw new WikiInvalidReadOptions("sources.query", "must be a non-empty string");
9083
+ }
9084
+ if (queryTerms(query).length === 0) {
9085
+ throw new WikiInvalidReadOptions("sources.query", "must contain at least one searchable term");
9086
+ }
9087
+ }
9088
+ function windowPassage(text, terms, budget) {
9089
+ if (text.length <= budget) return { start: 0, end: text.length, truncated: false };
9090
+ const lower = asciiLower(text);
9091
+ let a = -1;
9092
+ let len = 0;
9093
+ for (const t of terms) {
9094
+ const i = lower.indexOf(t);
9095
+ if (i >= 0 && (a < 0 || i < a || i === a && t.length > len)) {
9096
+ a = i;
9097
+ len = t.length;
9098
+ }
9099
+ }
9100
+ const hardCut = (from) => {
9101
+ let end = Math.min(text.length, from + budget);
9102
+ if (end < text.length && isHigh2(text.charCodeAt(end - 1)) && isLow2(text.charCodeAt(end))) {
9103
+ if (end - 1 > from) end -= 1;
9104
+ else return { start: from, end: from, truncated: true };
9105
+ }
9106
+ return { start: from, end, truncated: from > 0 || end < text.length };
9107
+ };
9108
+ if (a < 0) return hardCut(0);
9109
+ if (len > budget) return hardCut(a);
9110
+ const toks = [];
9111
+ for (const m of text.matchAll(/\S+/g)) toks.push([m.index, m.index + m[0].length]);
9112
+ const mEnd = a + len;
9113
+ const ti = toks.findIndex(([, e]) => e > a);
9114
+ if (ti < 0) return hardCut(a);
9115
+ let tj = ti;
9116
+ while (tj + 1 < toks.length && toks[tj][1] < mEnd) tj++;
9117
+ if (toks[tj][1] - toks[ti][0] > budget) return hardCut(a);
9118
+ let r = toks.length - 1;
9119
+ let best = { start: toks[ti][0], end: toks[tj][1] };
9120
+ for (let l = ti; l >= 0; l--) {
9121
+ const s = toks[l][0];
9122
+ while (r > tj && toks[r][1] - s > budget) r--;
9123
+ if (toks[r][1] - s > budget) break;
9124
+ if (toks[r][1] - s > best.end - best.start) best = { start: s, end: toks[r][1] };
9125
+ }
9126
+ return { ...best, truncated: true };
9127
+ }
8275
9128
  var RetrievalService = class {
8276
9129
  constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
8277
9130
  this.options = options;
@@ -8286,8 +9139,10 @@ var RetrievalService = class {
8286
9139
  const entityIds = normalizeEntityIds(entityId);
8287
9140
  const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
8288
9141
  const exposeMetadata = shouldExposeReadMetadata(entityId);
9142
+ if (options?.sources) assertSourcesQuery(options.sources);
8289
9143
  if (entityIds.length === 0) {
8290
9144
  const empty = { facts: [], tasks: [], events: [], edges: [] };
9145
+ if (options?.sources) empty.sources = [];
8291
9146
  if (exposeMetadata) {
8292
9147
  empty.metadata = { query, entityIds: [] };
8293
9148
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
@@ -8802,6 +9657,7 @@ var RetrievalService = class {
8802
9657
  factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
8803
9658
  }
8804
9659
  const bundle = { facts, tasks, events: events.reverse(), edges: [] };
9660
+ if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
8805
9661
  if (exposeMetadata) {
8806
9662
  bundle.metadata = { query, entityIds };
8807
9663
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
@@ -8810,6 +9666,42 @@ var RetrievalService = class {
8810
9666
  }
8811
9667
  return bundle;
8812
9668
  }
9669
+ /**
9670
+ * The `sources` group (spec source-store section 7). One search per entity,
9671
+ * so ranking and caps never cross entities. No model call anywhere.
9672
+ * `charBudget` is per entity: windows are cut in rank order against the
9673
+ * entity's remaining budget, and once it is spent lower-ranked hits are not returned.
9674
+ */
9675
+ async _readSources(entityIds, opt) {
9676
+ const pos = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : d;
9677
+ const maxPassages = pos(opt.maxPassages, DEFAULT_SOURCE_PASSAGES);
9678
+ const charBudget = pos(opt.charBudget, DEFAULT_SOURCE_CHAR_BUDGET);
9679
+ assertSourcesQuery(opt);
9680
+ const query = opt.query;
9681
+ const terms = queryTerms(query);
9682
+ const out = [];
9683
+ for (const entityId of entityIds) {
9684
+ const hits = await this.searchService.searchPassages(query, entityId, maxPassages);
9685
+ let remaining = charBudget;
9686
+ for (const h of hits) {
9687
+ if (remaining <= 0) break;
9688
+ const w = windowPassage(h.text, terms, remaining);
9689
+ if (w.end === w.start) continue;
9690
+ remaining -= w.end - w.start;
9691
+ out.push({
9692
+ entityId,
9693
+ sourceRef: h.source_ref,
9694
+ sourceHash: h.source_hash,
9695
+ seq: h.seq,
9696
+ startOffset: h.start_offset + w.start,
9697
+ endOffset: h.start_offset + w.end,
9698
+ truncated: w.truncated,
9699
+ text: h.text.slice(w.start, w.end)
9700
+ });
9701
+ }
9702
+ }
9703
+ return out;
9704
+ }
8813
9705
  /**
8814
9706
  * Returns entity IDs that will participate in scored retrieval.
8815
9707
  * Excludes zero-weight entities unless includeZeroWeightEntities is true.
@@ -9098,6 +9990,6 @@ var WriteService = class {
9098
9990
  }
9099
9991
  };
9100
9992
 
9101
- export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
9102
- //# sourceMappingURL=chunk-G2H6TJUC.mjs.map
9103
- //# sourceMappingURL=chunk-G2H6TJUC.mjs.map
9993
+ export { BaseRepository, CURRENT_SCHEMA_VERSION, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, chunkText, configureRandomSource, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
9994
+ //# sourceMappingURL=chunk-E3JCZMJL.mjs.map
9995
+ //# sourceMappingURL=chunk-E3JCZMJL.mjs.map