@equationalapplications/core-llm-wiki 9.1.0 → 9.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-SIJD5GEF.mjs → chunk-E3JCZMJL.mjs} +777 -19
- package/dist/chunk-E3JCZMJL.mjs.map +1 -0
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1396 -329
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +515 -206
- package/dist/index.mjs.map +1 -1
- package/dist/{testing-CmcCGx0_.d.mts → testing-BQScWWSA.d.mts} +189 -16
- package/dist/{testing-CmcCGx0_.d.ts → testing-BQScWWSA.d.ts} +189 -16
- package/dist/testing.d.mts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +615 -29
- package/dist/testing.js.map +1 -1
- package/dist/testing.mjs +1 -1
- package/package.json +2 -2
- package/dist/chunk-SIJD5GEF.mjs.map +0 -1
|
@@ -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());
|
|
@@ -2282,7 +2344,12 @@ var SEVERITY = {
|
|
|
2282
2344
|
guidance_too_long: "warn",
|
|
2283
2345
|
guidance_resolver_failed: "warn",
|
|
2284
2346
|
source_pointer_unresolved: "warn",
|
|
2285
|
-
source_pointer_invalid: "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"
|
|
2286
2353
|
};
|
|
2287
2354
|
var MESSAGE = {
|
|
2288
2355
|
ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
|
|
@@ -2312,7 +2379,12 @@ var MESSAGE = {
|
|
|
2312
2379
|
guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
|
|
2313
2380
|
guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
|
|
2314
2381
|
source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
|
|
2315
|
-
source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
|
|
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."
|
|
2316
2388
|
};
|
|
2317
2389
|
var warnedNonFunction = /* @__PURE__ */ new WeakSet();
|
|
2318
2390
|
function copyDetail(detail) {
|
|
@@ -4409,6 +4481,29 @@ async function setupDatabase(db, prefix) {
|
|
|
4409
4481
|
ON ${prefix}source_ref_index (entity_id, source_hash)
|
|
4410
4482
|
WHERE deleted_at IS NULL;
|
|
4411
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
|
+
|
|
4412
4507
|
CREATE TABLE IF NOT EXISTS ${prefix}tasks (
|
|
4413
4508
|
id TEXT PRIMARY KEY,
|
|
4414
4509
|
entity_id TEXT NOT NULL,
|
|
@@ -4535,6 +4630,8 @@ async function setupDatabase(db, prefix) {
|
|
|
4535
4630
|
`);
|
|
4536
4631
|
await createOkfV02IndexesIfColumnsExist(db, prefix);
|
|
4537
4632
|
await createTemporalIndexesIfColumnsExist(db, prefix);
|
|
4633
|
+
await createSourcePassageIndexesIfColumnsExist(db, prefix);
|
|
4634
|
+
await createSourceDocumentIndexesIfColumnsExist(db, prefix);
|
|
4538
4635
|
await createResurrectTrigger(db, prefix);
|
|
4539
4636
|
}
|
|
4540
4637
|
var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
|
|
@@ -4601,6 +4698,22 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
|
|
|
4601
4698
|
);
|
|
4602
4699
|
}
|
|
4603
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
|
+
}
|
|
4604
4717
|
|
|
4605
4718
|
// src/services/search/fts5Sql.ts
|
|
4606
4719
|
var FTS5_STATE_KEY = "fts5_index_state";
|
|
@@ -4738,6 +4851,38 @@ function sweepChunkSql(p) {
|
|
|
4738
4851
|
`DELETE FROM ${p}fts_map WHERE fts_rowid IN (${orphans})`
|
|
4739
4852
|
];
|
|
4740
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
|
+
}
|
|
4741
4886
|
|
|
4742
4887
|
// src/db/migrations.ts
|
|
4743
4888
|
var MIGRATIONS = [
|
|
@@ -5043,6 +5188,57 @@ var MIGRATIONS = [
|
|
|
5043
5188
|
await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
|
|
5044
5189
|
}
|
|
5045
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
|
+
}
|
|
5046
5242
|
}
|
|
5047
5243
|
];
|
|
5048
5244
|
async function createLegacySourceTypeIndex(db, prefix) {
|
|
@@ -6361,6 +6557,10 @@ var MaintenanceService = class {
|
|
|
6361
6557
|
if (await this.sourceRefIndexPresent(tx)) {
|
|
6362
6558
|
await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
|
|
6363
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
|
+
}
|
|
6364
6564
|
await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
|
|
6365
6565
|
if (params.includeEvents) {
|
|
6366
6566
|
deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
|
|
@@ -6384,6 +6584,16 @@ var MaintenanceService = class {
|
|
|
6384
6584
|
const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
|
|
6385
6585
|
if (entryId) deletedEntryIds.push(entryId);
|
|
6386
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
|
+
}
|
|
6387
6597
|
if (sourceRef || sourceHash) {
|
|
6388
6598
|
for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
|
|
6389
6599
|
}
|
|
@@ -6500,6 +6710,10 @@ var MaintenanceService = class {
|
|
|
6500
6710
|
if (version < 9) return false;
|
|
6501
6711
|
throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
|
|
6502
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
|
+
}
|
|
6503
6717
|
/**
|
|
6504
6718
|
* Read-only dry-run preview of {@link forget}. Returns the same shape as a
|
|
6505
6719
|
* real call would, without acquiring the lock, opening a transaction, staging
|
|
@@ -7234,6 +7448,360 @@ var MaintenanceService = class {
|
|
|
7234
7448
|
}
|
|
7235
7449
|
};
|
|
7236
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
|
+
|
|
7237
7805
|
// src/utils/sourcePointer.ts
|
|
7238
7806
|
var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
|
|
7239
7807
|
function isStringOrNull(v) {
|
|
@@ -7349,7 +7917,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
|
|
|
7349
7917
|
var IMPORT_TITLE_MAX = 500;
|
|
7350
7918
|
var IMPORT_BODY_MAX = 8e3;
|
|
7351
7919
|
var ImportExportService = class {
|
|
7352
|
-
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) {
|
|
7353
7921
|
this.db = db;
|
|
7354
7922
|
this.entryRepo = entryRepo;
|
|
7355
7923
|
this.taskRepo = taskRepo;
|
|
@@ -7361,6 +7929,7 @@ var ImportExportService = class {
|
|
|
7361
7929
|
this.embeddingService = embeddingService;
|
|
7362
7930
|
this.options = options;
|
|
7363
7931
|
this.vectorRemoval = vectorRemoval;
|
|
7932
|
+
this.prefix = prefix;
|
|
7364
7933
|
}
|
|
7365
7934
|
async exportDump(entityIds) {
|
|
7366
7935
|
let ids;
|
|
@@ -7368,6 +7937,13 @@ var ImportExportService = class {
|
|
|
7368
7937
|
ids = Array.from(new Set(entityIds));
|
|
7369
7938
|
} else {
|
|
7370
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
|
+
}
|
|
7371
7947
|
}
|
|
7372
7948
|
const entities = {};
|
|
7373
7949
|
const BATCH = 3;
|
|
@@ -7375,10 +7951,11 @@ var ImportExportService = class {
|
|
|
7375
7951
|
const batch = ids.slice(i, i + BATCH);
|
|
7376
7952
|
const batchResults = await Promise.all(
|
|
7377
7953
|
batch.map(
|
|
7378
|
-
async (id) =>
|
|
7379
|
-
id,
|
|
7380
|
-
await this.
|
|
7381
|
-
|
|
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
|
+
}
|
|
7382
7959
|
)
|
|
7383
7960
|
);
|
|
7384
7961
|
for (const [id, bundle] of batchResults) {
|
|
@@ -7389,16 +7966,96 @@ var ImportExportService = class {
|
|
|
7389
7966
|
}
|
|
7390
7967
|
async importDump(dump, opts) {
|
|
7391
7968
|
const merge = opts?.merge ?? false;
|
|
7969
|
+
const skippedSources = [];
|
|
7392
7970
|
const entityIds = Object.keys(dump.entities);
|
|
7393
7971
|
this.jobManager.acquireImportLocks(entityIds);
|
|
7394
7972
|
try {
|
|
7395
7973
|
await this.assertNoLegacySourceTypes();
|
|
7396
7974
|
for (const [entityId, bundle] of Object.entries(dump.entities)) {
|
|
7397
|
-
await this.doImportEntity(entityId, bundle, merge);
|
|
7975
|
+
skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
|
|
7398
7976
|
}
|
|
7399
7977
|
} finally {
|
|
7400
7978
|
this.jobManager.releaseImportLocks(entityIds);
|
|
7401
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
|
+
}
|
|
7402
8059
|
}
|
|
7403
8060
|
async getFullBundle(entityId, opts) {
|
|
7404
8061
|
const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
|
|
@@ -7437,6 +8094,8 @@ var ImportExportService = class {
|
|
|
7437
8094
|
}
|
|
7438
8095
|
/** Single-entity import transaction + post-processing; package-internal hook for tests. */
|
|
7439
8096
|
async doImportEntity(entityId, bundle, merge) {
|
|
8097
|
+
const skippedSources = [];
|
|
8098
|
+
const refusalDiagnostics = [];
|
|
7440
8099
|
const upsertedFactIds = /* @__PURE__ */ new Set();
|
|
7441
8100
|
const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
|
|
7442
8101
|
const factsWithPreservedBlob = /* @__PURE__ */ new Map();
|
|
@@ -7714,7 +8373,9 @@ var ImportExportService = class {
|
|
|
7714
8373
|
tx
|
|
7715
8374
|
);
|
|
7716
8375
|
}
|
|
8376
|
+
await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
|
|
7717
8377
|
});
|
|
8378
|
+
for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
|
|
7718
8379
|
if (clampedEvents > 0) {
|
|
7719
8380
|
emitDiagnostic(this.options, {
|
|
7720
8381
|
code: "event_created_at_clamped",
|
|
@@ -7882,6 +8543,7 @@ var ImportExportService = class {
|
|
|
7882
8543
|
} finally {
|
|
7883
8544
|
this.searchService.evictCache(entityId);
|
|
7884
8545
|
}
|
|
8546
|
+
return skippedSources;
|
|
7885
8547
|
}
|
|
7886
8548
|
_warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
|
|
7887
8549
|
console.warn(
|
|
@@ -8406,6 +9068,63 @@ function packFactsByBudget(items, budget, scores) {
|
|
|
8406
9068
|
|
|
8407
9069
|
// src/services/RetrievalService.ts
|
|
8408
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
|
+
}
|
|
8409
9128
|
var RetrievalService = class {
|
|
8410
9129
|
constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
|
|
8411
9130
|
this.options = options;
|
|
@@ -8420,8 +9139,10 @@ var RetrievalService = class {
|
|
|
8420
9139
|
const entityIds = normalizeEntityIds(entityId);
|
|
8421
9140
|
const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
|
|
8422
9141
|
const exposeMetadata = shouldExposeReadMetadata(entityId);
|
|
9142
|
+
if (options?.sources) assertSourcesQuery(options.sources);
|
|
8423
9143
|
if (entityIds.length === 0) {
|
|
8424
9144
|
const empty = { facts: [], tasks: [], events: [], edges: [] };
|
|
9145
|
+
if (options?.sources) empty.sources = [];
|
|
8425
9146
|
if (exposeMetadata) {
|
|
8426
9147
|
empty.metadata = { query, entityIds: [] };
|
|
8427
9148
|
if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
|
|
@@ -8936,6 +9657,7 @@ var RetrievalService = class {
|
|
|
8936
9657
|
factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
|
|
8937
9658
|
}
|
|
8938
9659
|
const bundle = { facts, tasks, events: events.reverse(), edges: [] };
|
|
9660
|
+
if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
|
|
8939
9661
|
if (exposeMetadata) {
|
|
8940
9662
|
bundle.metadata = { query, entityIds };
|
|
8941
9663
|
if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
|
|
@@ -8944,6 +9666,42 @@ var RetrievalService = class {
|
|
|
8944
9666
|
}
|
|
8945
9667
|
return bundle;
|
|
8946
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
|
+
}
|
|
8947
9705
|
/**
|
|
8948
9706
|
* Returns entity IDs that will participate in scored retrieval.
|
|
8949
9707
|
* Excludes zero-weight entities unless includeZeroWeightEntities is true.
|
|
@@ -9232,6 +9990,6 @@ var WriteService = class {
|
|
|
9232
9990
|
}
|
|
9233
9991
|
};
|
|
9234
9992
|
|
|
9235
|
-
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, parseStoredSourcePointer, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveEdgeDefinitions, resolveGrounding, resolveLibrarianStrategy, resolveNodeType, retiredTableName, runSourceRefNormalize, safeSlice, serializeSourcePointer, setupDatabase, sweepChunkSql, sweepHiSql, typeSatisfies, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
|
|
9236
|
-
//# sourceMappingURL=chunk-
|
|
9237
|
-
//# sourceMappingURL=chunk-
|
|
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
|