@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/index.js CHANGED
@@ -44,7 +44,12 @@ var SEVERITY = {
44
44
  guidance_too_long: "warn",
45
45
  guidance_resolver_failed: "warn",
46
46
  source_pointer_unresolved: "warn",
47
- source_pointer_invalid: "warn"
47
+ source_pointer_invalid: "warn",
48
+ source_store_source_too_large: "warn",
49
+ source_store_budget_exceeded: "warn",
50
+ source_store_hash_mismatch: "warn",
51
+ source_store_duplicate_hash: "warn",
52
+ source_store_text_not_storable: "warn"
48
53
  };
49
54
  var MESSAGE = {
50
55
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -74,7 +79,12 @@ var MESSAGE = {
74
79
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
75
80
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
76
81
  source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
77
- source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
82
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
83
+ source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
84
+ source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
85
+ source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
86
+ source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
87
+ source_store_text_not_storable: "A source document text could not be stored as given."
78
88
  };
79
89
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
80
90
  function copyDetail(detail) {
@@ -976,6 +986,29 @@ async function setupDatabase(db, prefix) {
976
986
  ON ${prefix}source_ref_index (entity_id, source_hash)
977
987
  WHERE deleted_at IS NULL;
978
988
 
989
+ -- source_documents / source_passages: the source store (specs/source-store \xA73).
990
+ -- New tables only; hard delete, so no deleted_at and both UNIQUE indexes are plain.
991
+ -- Passage text is not stored: offsets (UTF-16 code units) slice source_documents.text.
992
+ CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
993
+ id TEXT PRIMARY KEY,
994
+ entity_id TEXT NOT NULL,
995
+ source_ref TEXT NOT NULL,
996
+ source_hash TEXT NOT NULL,
997
+ text TEXT NOT NULL,
998
+ text_hash TEXT NOT NULL,
999
+ char_count INTEGER NOT NULL,
1000
+ created_at INTEGER NOT NULL
1001
+ );
1002
+
1003
+ CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
1004
+ id TEXT PRIMARY KEY,
1005
+ entity_id TEXT NOT NULL,
1006
+ document_id TEXT NOT NULL,
1007
+ seq INTEGER NOT NULL,
1008
+ start_offset INTEGER NOT NULL,
1009
+ end_offset INTEGER NOT NULL
1010
+ );
1011
+
979
1012
  CREATE TABLE IF NOT EXISTS ${prefix}tasks (
980
1013
  id TEXT PRIMARY KEY,
981
1014
  entity_id TEXT NOT NULL,
@@ -1102,6 +1135,8 @@ async function setupDatabase(db, prefix) {
1102
1135
  `);
1103
1136
  await createOkfV02IndexesIfColumnsExist(db, prefix);
1104
1137
  await createTemporalIndexesIfColumnsExist(db, prefix);
1138
+ await createSourcePassageIndexesIfColumnsExist(db, prefix);
1139
+ await createSourceDocumentIndexesIfColumnsExist(db, prefix);
1105
1140
  await createResurrectTrigger(db, prefix);
1106
1141
  }
1107
1142
  var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
@@ -1168,6 +1203,22 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
1168
1203
  );
1169
1204
  }
1170
1205
  }
1206
+ async function createSourcePassageIndexesIfColumnsExist(db, prefix) {
1207
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}source_passages)`);
1208
+ const names = new Set(cols.map((c) => c.name));
1209
+ if (!names.has("document_id") || !names.has("entity_id")) return;
1210
+ await db.execAsync(`
1211
+ CREATE INDEX IF NOT EXISTS ${prefix}idx_source_passages_doc ON ${prefix}source_passages (document_id, seq);
1212
+ CREATE INDEX IF NOT EXISTS ${prefix}idx_source_passages_entity ON ${prefix}source_passages (entity_id);`);
1213
+ }
1214
+ async function createSourceDocumentIndexesIfColumnsExist(db, prefix) {
1215
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}source_documents)`);
1216
+ const names = new Set(cols.map((c) => c.name));
1217
+ if (!names.has("entity_id") || !names.has("source_ref") || !names.has("source_hash")) return;
1218
+ await db.execAsync(`
1219
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref ON ${prefix}source_documents (entity_id, source_ref);
1220
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash ON ${prefix}source_documents (entity_id, source_hash);`);
1221
+ }
1171
1222
 
1172
1223
  // src/services/search/fts5Sql.ts
1173
1224
  var FTS5_STATE_KEY = "fts5_index_state";
@@ -1305,6 +1356,38 @@ function sweepChunkSql(p) {
1305
1356
  `DELETE FROM ${p}fts_map WHERE fts_rowid IN (${orphans})`
1306
1357
  ];
1307
1358
  }
1359
+ function passageFtsTriggerNames(p) {
1360
+ return [`${p}source_passages_fts_ai`, `${p}source_passages_fts_ad`];
1361
+ }
1362
+ function passageFtsTablesDdl(p) {
1363
+ return `
1364
+ CREATE VIRTUAL TABLE IF NOT EXISTS ${p}source_passages_fts USING fts5(
1365
+ passage_id UNINDEXED, entity_id UNINDEXED, doc_id UNINDEXED, text,
1366
+ tokenize = 'porter unicode61'
1367
+ );
1368
+ CREATE TABLE IF NOT EXISTS ${p}source_passages_fts_map (
1369
+ fts_rowid INTEGER PRIMARY KEY,
1370
+ passage_id TEXT NOT NULL UNIQUE,
1371
+ doc_id TEXT NOT NULL
1372
+ );
1373
+ CREATE INDEX IF NOT EXISTS ${p}source_passages_fts_map_doc ON ${p}source_passages_fts_map(doc_id);
1374
+ CREATE TABLE IF NOT EXISTS ${p}source_passages_fts_pending (
1375
+ seq INTEGER PRIMARY KEY,
1376
+ entity_id TEXT NOT NULL,
1377
+ doc_id TEXT NOT NULL
1378
+ );
1379
+ CREATE INDEX IF NOT EXISTS ${p}source_passages_fts_pending_doc ON ${p}source_passages_fts_pending(doc_id);`;
1380
+ }
1381
+ function passageFtsTriggersDdl(p) {
1382
+ const [ai, ad] = passageFtsTriggerNames(p);
1383
+ return `
1384
+ CREATE TRIGGER IF NOT EXISTS ${ai} AFTER INSERT ON ${p}source_passages BEGIN
1385
+ INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id) VALUES (NEW.entity_id, NEW.document_id);
1386
+ END;
1387
+ CREATE TRIGGER IF NOT EXISTS ${ad} AFTER DELETE ON ${p}source_passages BEGIN
1388
+ INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id) VALUES (OLD.entity_id, OLD.document_id);
1389
+ END;`;
1390
+ }
1308
1391
 
1309
1392
  // src/db/migrations.ts
1310
1393
  var MIGRATIONS = [
@@ -1610,6 +1693,57 @@ var MIGRATIONS = [
1610
1693
  await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
1611
1694
  }
1612
1695
  }
1696
+ },
1697
+ {
1698
+ version: 17,
1699
+ description: "add_source_store",
1700
+ run: async (db, prefix) => {
1701
+ const expected = {
1702
+ source_documents: ["id", "entity_id", "source_ref", "source_hash", "text", "text_hash", "char_count", "created_at"],
1703
+ source_passages: ["id", "entity_id", "document_id", "seq", "start_offset", "end_offset"]
1704
+ };
1705
+ for (const [table, want] of Object.entries(expected)) {
1706
+ const full = `${prefix}${table}`;
1707
+ const cols = (await db.getAllAsync(`PRAGMA table_info(${full})`)).map((c) => c.name);
1708
+ if (cols.length === 0) continue;
1709
+ const same = cols.length === want.length && want.every((c) => cols.includes(c));
1710
+ if (!same) {
1711
+ throw new Error(
1712
+ `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().`
1713
+ );
1714
+ }
1715
+ const row = await db.getFirstAsync(`SELECT COUNT(*) AS n FROM ${full}`);
1716
+ if (row && row.n > 0) {
1717
+ throw new Error(
1718
+ `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().`
1719
+ );
1720
+ }
1721
+ }
1722
+ await db.execAsync(
1723
+ `CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
1724
+ id TEXT PRIMARY KEY,
1725
+ entity_id TEXT NOT NULL,
1726
+ source_ref TEXT NOT NULL,
1727
+ source_hash TEXT NOT NULL,
1728
+ text TEXT NOT NULL,
1729
+ text_hash TEXT NOT NULL,
1730
+ char_count INTEGER NOT NULL,
1731
+ created_at INTEGER NOT NULL
1732
+ );
1733
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref
1734
+ ON ${prefix}source_documents (entity_id, source_ref);
1735
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash
1736
+ ON ${prefix}source_documents (entity_id, source_hash);
1737
+ CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
1738
+ id TEXT PRIMARY KEY,
1739
+ entity_id TEXT NOT NULL,
1740
+ document_id TEXT NOT NULL,
1741
+ seq INTEGER NOT NULL,
1742
+ start_offset INTEGER NOT NULL,
1743
+ end_offset INTEGER NOT NULL
1744
+ );`
1745
+ );
1746
+ }
1613
1747
  }
1614
1748
  ];
1615
1749
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -3028,20 +3162,26 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3028
3162
  FROM ${this.prefix}entries
3029
3163
  WHERE entity_id = ? AND deleted_at IS NULL AND source_ref IS NOT NULL
3030
3164
  )
3031
- SELECT source_ref,
3032
- source_hash AS source_hash,
3033
- fact_count AS fact_count,
3034
- updated_at AS last_ingested_at
3165
+ SELECT ranked.source_ref,
3166
+ ranked.source_hash AS source_hash,
3167
+ ranked.fact_count AS fact_count,
3168
+ ranked.updated_at AS last_ingested_at,
3169
+ d.source_hash AS stored_hash,
3170
+ d.char_count AS stored_chars
3035
3171
  FROM ranked
3036
- WHERE rn = 1
3037
- ORDER BY source_ref COLLATE BINARY`,
3038
- [entityId]
3172
+ LEFT JOIN ${this.prefix}source_documents d
3173
+ ON d.entity_id = ? AND d.source_ref = ranked.source_ref
3174
+ WHERE ranked.rn = 1
3175
+ ORDER BY ranked.source_ref COLLATE BINARY`,
3176
+ [entityId, entityId]
3039
3177
  );
3040
3178
  return rows.map((r) => ({
3041
3179
  sourceRef: r.source_ref,
3042
3180
  sourceHash: r.source_hash,
3043
3181
  factCount: Number(r.fact_count),
3044
- lastIngestedAt: Number(r.last_ingested_at)
3182
+ lastIngestedAt: Number(r.last_ingested_at),
3183
+ // Spec source-store §4: keyed on the ref's own (sourceRef, sourceHash) pair.
3184
+ stored: r.stored_hash === null || r.stored_hash === void 0 ? null : r.stored_hash === r.source_hash ? { charCount: Number(r.stored_chars) } : { charCount: Number(r.stored_chars), staleHash: true }
3045
3185
  }));
3046
3186
  }
3047
3187
  /**
@@ -4693,6 +4833,10 @@ var UnavailableIndexStrategy = class {
4693
4833
  }
4694
4834
  async drain(_opts) {
4695
4835
  }
4836
+ /** Degraded like everything else: no passages, no throw (spec source-store section 7). */
4837
+ async searchPassages() {
4838
+ return [];
4839
+ }
4696
4840
  };
4697
4841
 
4698
4842
  // src/services/SearchService.ts
@@ -4914,6 +5058,36 @@ var _SearchService = class _SearchService {
4914
5058
  const results = finiteResults(await this.indexStrategy.search(query, { entityIds, limit }));
4915
5059
  return results.sort((a, b) => this._compareSearchResults(a, b)).slice(0, limit);
4916
5060
  }
5061
+ /**
5062
+ * Post-commit passage index sync (spec source-store section 6). FTS5: drains the
5063
+ * passage ledger (per document, entity-scoped when given). MiniSearch: reloads
5064
+ * the entity's stored passages (all stored entities when omitted: the open-time
5065
+ * pass). Serialized on the sync chain; never rejects, like sync().
5066
+ */
5067
+ async syncPassages(db, prefix, entityId, deadline) {
5068
+ const s = this.indexStrategy;
5069
+ if (!s.drainPassages && !s.reindexSourcePassages) return;
5070
+ const work = this.syncChain.then(async () => {
5071
+ try {
5072
+ if (s.drainPassages) await s.drainPassages({ entityId, deadline });
5073
+ else await s.reindexSourcePassages(db, prefix, entityId);
5074
+ } catch (err) {
5075
+ console.warn(`[WikiMemory] passage index sync failed for ${entityId ?? "*"}:`, err);
5076
+ }
5077
+ });
5078
+ this.syncChain = work;
5079
+ return work;
5080
+ }
5081
+ /**
5082
+ * Stored-source passage search for ONE entity (spec source-store section 7:
5083
+ * ranking and caps are per entity). Rides the active strategy; a strategy
5084
+ * without passage search yields none.
5085
+ */
5086
+ async searchPassages(query, entityId, limit) {
5087
+ if (!this.indexStrategy.searchPassages) return [];
5088
+ const hits = await this.indexStrategy.searchPassages(query, { entityIds: [entityId], limit });
5089
+ return hits.filter((h) => Number.isFinite(h.score) && h.entity_id === entityId).slice(0, limit);
5090
+ }
4917
5091
  /**
4918
5092
  * Pre-fetches keyword scores for candidate hydration, used during hybrid weighting.
4919
5093
  */
@@ -5036,225 +5210,538 @@ var SearchService = _SearchService;
5036
5210
  function finiteResults(results) {
5037
5211
  return results.every((r) => Number.isFinite(r.score)) ? results : results.filter((r) => Number.isFinite(r.score));
5038
5212
  }
5039
- var MiniSearchIndexStrategy = class {
5040
- constructor() {
5041
- /**
5042
- * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
5043
- * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
5044
- * not see this map; it only sees `hasIndexedEntity`. The previous
5045
- * `miniSearchEntryIdsByEntity` lived on `SearchService`.
5046
- */
5047
- this.entryIdsByEntity = /* @__PURE__ */ new Map();
5048
- /**
5049
- * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
5050
- * decide which ids are owned by `entityId` (the only safe membership test
5051
- * — a rebuild that failed between its discard pass and the set replacement
5052
- * can leave the forward set claiming ids the MiniSearch instance does not
5053
- * hold). The pre-extraction `syncEntries` deleted from one set per id, not
5054
- * from every entity's set.
5055
- */
5056
- this.entityIdById = /* @__PURE__ */ new Map();
5057
- this.index = this.createIndex();
5213
+
5214
+ // src/utils/passageCutter.ts
5215
+ var MAX_PASSAGE_UNITS = 12e3;
5216
+ var WHITESPACE = /\s/;
5217
+ function isHigh(code) {
5218
+ return code >= 55296 && code <= 56319;
5219
+ }
5220
+ function isLow(code) {
5221
+ return code >= 56320 && code <= 57343;
5222
+ }
5223
+ function cutPassages(text, maxUnits = MAX_PASSAGE_UNITS) {
5224
+ const limit = Math.max(2, Math.floor(maxUnits));
5225
+ const spans = [];
5226
+ let start = 0;
5227
+ while (start < text.length) {
5228
+ if (text.length - start <= limit) {
5229
+ spans.push({ start, end: text.length });
5230
+ break;
5231
+ }
5232
+ let end = start + limit;
5233
+ let cut = -1;
5234
+ for (let i = end - 1; i > start; i--) {
5235
+ if (WHITESPACE.test(text[i])) {
5236
+ cut = i + 1;
5237
+ break;
5238
+ }
5239
+ }
5240
+ if (cut > start) {
5241
+ end = cut;
5242
+ } else if (isHigh(text.charCodeAt(end - 1)) && isLow(text.charCodeAt(end))) {
5243
+ end -= 1;
5244
+ }
5245
+ spans.push({ start, end });
5246
+ start = end;
5058
5247
  }
5059
- /**
5060
- * Build a fresh MiniSearch instance with the project's index options.
5061
- * Called from the constructor and from `replaceAll`. We do not use
5062
- * `removeAll()` on an existing instance because that empties the index but
5063
- * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
5064
- * `syncEntries`' conditional vacuum early after a clear.
5065
- */
5066
- createIndex() {
5067
- return new MiniSearch__default.default({
5068
- fields: ["title", "body", "tags"],
5069
- storeFields: ["entity_id"],
5070
- // Vacuuming is driven explicitly at the end of each serialized rebuild
5071
- // (see SearchService.syncEntries). Auto-vacuum fires on its own
5072
- // schedule, asynchronously with respect to the caller, and traversing
5073
- // the tree mid-rebuild is what threw the uncaught TypeError in
5074
- // MiniSearch.performVacuuming (#64).
5075
- autoVacuum: false,
5076
- searchOptions: {
5077
- boost: { title: 2 },
5078
- fuzzy: 0.2,
5079
- prefix: true
5248
+ return spans;
5249
+ }
5250
+
5251
+ // src/utils/sha256.ts
5252
+ var K = new Uint32Array([
5253
+ 1116352408,
5254
+ 1899447441,
5255
+ 3049323471,
5256
+ 3921009573,
5257
+ 961987163,
5258
+ 1508970993,
5259
+ 2453635748,
5260
+ 2870763221,
5261
+ 3624381080,
5262
+ 310598401,
5263
+ 607225278,
5264
+ 1426881987,
5265
+ 1925078388,
5266
+ 2162078206,
5267
+ 2614888103,
5268
+ 3248222580,
5269
+ 3835390401,
5270
+ 4022224774,
5271
+ 264347078,
5272
+ 604807628,
5273
+ 770255983,
5274
+ 1249150122,
5275
+ 1555081692,
5276
+ 1996064986,
5277
+ 2554220882,
5278
+ 2821834349,
5279
+ 2952996808,
5280
+ 3210313671,
5281
+ 3336571891,
5282
+ 3584528711,
5283
+ 113926993,
5284
+ 338241895,
5285
+ 666307205,
5286
+ 773529912,
5287
+ 1294757372,
5288
+ 1396182291,
5289
+ 1695183700,
5290
+ 1986661051,
5291
+ 2177026350,
5292
+ 2456956037,
5293
+ 2730485921,
5294
+ 2820302411,
5295
+ 3259730800,
5296
+ 3345764771,
5297
+ 3516065817,
5298
+ 3600352804,
5299
+ 4094571909,
5300
+ 275423344,
5301
+ 430227734,
5302
+ 506948616,
5303
+ 659060556,
5304
+ 883997877,
5305
+ 958139571,
5306
+ 1322822218,
5307
+ 1537002063,
5308
+ 1747873779,
5309
+ 1955562222,
5310
+ 2024104815,
5311
+ 2227730452,
5312
+ 2361852424,
5313
+ 2428436474,
5314
+ 2756734187,
5315
+ 3204031479,
5316
+ 3329325298
5317
+ ]);
5318
+ var rotr = (x, n) => x >>> n | x << 32 - n;
5319
+ var IV = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
5320
+ function compress(H, W, view, off) {
5321
+ for (let t = 0; t < 16; t++) W[t] = view.getUint32(off + t * 4);
5322
+ for (let t = 16; t < 64; t++) {
5323
+ const s0 = rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ W[t - 15] >>> 3;
5324
+ const s1 = rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ W[t - 2] >>> 10;
5325
+ W[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;
5326
+ }
5327
+ 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];
5328
+ for (let t = 0; t < 64; t++) {
5329
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
5330
+ const ch = e & f ^ ~e & g;
5331
+ const t1 = h + S1 + ch + K[t] + W[t] >>> 0;
5332
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
5333
+ const maj = a & b ^ a & c ^ b & c;
5334
+ const t2 = S0 + maj >>> 0;
5335
+ h = g;
5336
+ g = f;
5337
+ f = e;
5338
+ e = d + t1 >>> 0;
5339
+ d = c;
5340
+ c = b;
5341
+ b = a;
5342
+ a = t1 + t2 >>> 0;
5343
+ }
5344
+ H[0] = H[0] + a >>> 0;
5345
+ H[1] = H[1] + b >>> 0;
5346
+ H[2] = H[2] + c >>> 0;
5347
+ H[3] = H[3] + d >>> 0;
5348
+ H[4] = H[4] + e >>> 0;
5349
+ H[5] = H[5] + f >>> 0;
5350
+ H[6] = H[6] + g >>> 0;
5351
+ H[7] = H[7] + h >>> 0;
5352
+ }
5353
+ function sha256(bytes) {
5354
+ const H = new Uint32Array(IV);
5355
+ const W = new Uint32Array(64);
5356
+ const whole = bytes.length - bytes.length % 64;
5357
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
5358
+ for (let off = 0; off < whole; off += 64) compress(H, W, view, off);
5359
+ const rest = bytes.subarray(whole);
5360
+ const bitLen = bytes.length * 8;
5361
+ const padded = new Uint8Array(rest.length + 9 + 63 >> 6 << 6);
5362
+ padded.set(rest);
5363
+ padded[rest.length] = 128;
5364
+ const pv = new DataView(padded.buffer);
5365
+ pv.setUint32(padded.length - 8, Math.floor(bitLen / 4294967296));
5366
+ pv.setUint32(padded.length - 4, bitLen >>> 0);
5367
+ for (let off = 0; off < padded.length; off += 64) compress(H, W, pv, off);
5368
+ const out = new Uint8Array(32);
5369
+ const outView = new DataView(out.buffer);
5370
+ for (let i = 0; i < 8; i++) outView.setUint32(i * 4, H[i]);
5371
+ return out;
5372
+ }
5373
+ function utf8Encode(s) {
5374
+ const out = [];
5375
+ for (let i = 0; i < s.length; i++) {
5376
+ let cp = s.charCodeAt(i);
5377
+ if (cp >= 55296 && cp <= 56319) {
5378
+ const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
5379
+ if (next >= 56320 && next <= 57343) {
5380
+ cp = 65536 + (cp - 55296 << 10) + (next - 56320);
5381
+ i++;
5382
+ } else {
5383
+ cp = 65533;
5080
5384
  }
5385
+ } else if (cp >= 56320 && cp <= 57343) {
5386
+ cp = 65533;
5387
+ }
5388
+ if (cp < 128) out.push(cp);
5389
+ else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63);
5390
+ else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
5391
+ else out.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
5392
+ }
5393
+ return Uint8Array.from(out);
5394
+ }
5395
+ function sha256Hex(text) {
5396
+ let hex = "";
5397
+ for (const b of sha256(utf8Encode(text))) hex += b.toString(16).padStart(2, "0");
5398
+ return hex;
5399
+ }
5400
+
5401
+ // src/services/sourceStoreUpsert.ts
5402
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
5403
+ async function upsertStoredSource(tx, prefix, entityId, src, limits, onRefusal, opts = {}) {
5404
+ const { sourceRef, sourceHash, text } = src;
5405
+ const refuse = (code) => {
5406
+ onRefusal(code);
5407
+ return { status: "refused" };
5408
+ };
5409
+ if (text.includes("\0") || LONE_SURROGATE.test(text)) return refuse("source_store_text_not_storable");
5410
+ if (text.length > limits.maxCharsPerSource) return refuse("source_store_source_too_large");
5411
+ const textHash = sha256Hex(text);
5412
+ const charCount = text.length;
5413
+ const docs = `${prefix}source_documents`;
5414
+ const passages = `${prefix}source_passages`;
5415
+ const registry = `${prefix}source_ref_index`;
5416
+ const existing = await tx.getFirstAsync(
5417
+ `SELECT id, source_hash, text_hash, char_count, created_at FROM ${docs}
5418
+ WHERE entity_id = ? AND source_ref = ?`,
5419
+ [entityId, sourceRef]
5420
+ );
5421
+ if (opts.idempotentSamePair && existing && existing.source_hash === sourceHash) {
5422
+ if (existing.text_hash !== textHash) return refuse("source_store_hash_mismatch");
5423
+ const row = await tx.getFirstAsync(
5424
+ `SELECT COUNT(*) AS n FROM ${passages} WHERE entity_id = ? AND document_id = ?`,
5425
+ [entityId, existing.id]
5426
+ );
5427
+ return { status: "stored", charCount: existing.char_count, passageCount: row?.n ?? 0, storedAt: existing.created_at };
5428
+ }
5429
+ const heldByStore = await tx.getFirstAsync(
5430
+ `SELECT source_ref FROM ${docs} WHERE entity_id = ? AND source_hash = ? AND source_ref <> ?`,
5431
+ [entityId, sourceHash, sourceRef]
5432
+ );
5433
+ const heldByFacts = await tx.getFirstAsync(
5434
+ `SELECT source_ref FROM ${registry}
5435
+ WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL AND source_ref <> ?`,
5436
+ [entityId, sourceHash, sourceRef]
5437
+ );
5438
+ if (heldByStore || heldByFacts) return refuse("source_store_duplicate_hash");
5439
+ const total = await tx.getFirstAsync(
5440
+ `SELECT COALESCE(SUM(char_count), 0) AS n FROM ${docs} WHERE entity_id = ? AND source_ref <> ?`,
5441
+ [entityId, sourceRef]
5442
+ );
5443
+ if ((total?.n ?? 0) + charCount > limits.maxTotalChars) return refuse("source_store_budget_exceeded");
5444
+ if (existing) {
5445
+ await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ? AND document_id = ?`, [entityId, existing.id]);
5446
+ await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ? AND id = ?`, [entityId, existing.id]);
5447
+ }
5448
+ const id = generateId("sdoc_");
5449
+ const storedAt = typeof src.storedAt === "number" && Number.isFinite(src.storedAt) ? src.storedAt : Date.now();
5450
+ await tx.runAsync(
5451
+ `INSERT INTO ${docs} (id, entity_id, source_ref, source_hash, text, text_hash, char_count, created_at)
5452
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
5453
+ [id, entityId, sourceRef, sourceHash, text, textHash, charCount, storedAt]
5454
+ );
5455
+ const spans = cutPassages(text);
5456
+ for (let seq = 0; seq < spans.length; seq++) {
5457
+ await tx.runAsync(
5458
+ `INSERT INTO ${passages} (id, entity_id, document_id, seq, start_offset, end_offset) VALUES (?, ?, ?, ?, ?, ?)`,
5459
+ [generateId("spas_"), entityId, id, seq, spans[seq].start, spans[seq].end]
5460
+ );
5461
+ }
5462
+ return { status: "stored", charCount, passageCount: spans.length, storedAt };
5463
+ }
5464
+
5465
+ // src/services/SourceStoreService.ts
5466
+ var DEFAULT_MAX_CHARS_PER_SOURCE = 2e5;
5467
+ var DEFAULT_MAX_TOTAL_CHARS = 5e6;
5468
+ function limitOr(value, fallback) {
5469
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
5470
+ }
5471
+ var SourceStoreService = class {
5472
+ constructor(db, prefix, options, jobManager) {
5473
+ this.db = db;
5474
+ this.prefix = prefix;
5475
+ this.options = options;
5476
+ this.jobManager = jobManager;
5477
+ }
5478
+ limits() {
5479
+ const cfg = this.options.config?.sourceStore;
5480
+ return {
5481
+ maxCharsPerSource: limitOr(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
5482
+ maxTotalChars: limitOr(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
5483
+ };
5484
+ }
5485
+ refuse(entityId, code, sourceRef) {
5486
+ const captured = [];
5487
+ const input = { code, operation: "sourceStore", trigger: "call", entityId, detail: { sourceRef } };
5488
+ emitDiagnostic({ onDiagnostic: (d) => {
5489
+ captured.push(d);
5490
+ } }, input);
5491
+ emitDiagnostic(this.options, input);
5492
+ return { stored: false, diagnostics: captured };
5493
+ }
5494
+ async storeSource(entityId, params) {
5495
+ const sourceRef = normalizeSourceRef(params.sourceRef);
5496
+ if (!sourceRef) throw new Error("Invalid sourceRef");
5497
+ const sourceHash = normalizeSourceHash(params.sourceHash);
5498
+ if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
5499
+ if (typeof params.text !== "string") throw new Error(`text must be a string, received ${typeof params.text}`);
5500
+ const text = params.text;
5501
+ this.jobManager.acquireLock("store", entityId);
5502
+ try {
5503
+ const limits = this.limits();
5504
+ let refused;
5505
+ const outcome = await this.db.withTransactionAsync((tx) => upsertStoredSource(
5506
+ tx,
5507
+ this.prefix,
5508
+ entityId,
5509
+ { sourceRef, sourceHash, text },
5510
+ limits,
5511
+ (code) => {
5512
+ refused = code;
5513
+ },
5514
+ { idempotentSamePair: true }
5515
+ ));
5516
+ if (outcome.status === "refused") return this.refuse(entityId, refused, sourceRef);
5517
+ return {
5518
+ stored: true,
5519
+ sourceRef,
5520
+ sourceHash,
5521
+ charCount: outcome.charCount,
5522
+ passageCount: outcome.passageCount,
5523
+ storedAt: outcome.storedAt
5524
+ };
5525
+ } finally {
5526
+ this.jobManager.releaseLock("store", entityId);
5527
+ }
5528
+ }
5529
+ /** Spec §7: the text exactly as handed, or null. Plain read, no write lock. */
5530
+ async getStoredSource(entityId, sourceRef) {
5531
+ const ref = normalizeSourceRef(sourceRef);
5532
+ if (!ref) return null;
5533
+ const row = await this.db.getFirstAsync(
5534
+ `SELECT source_ref, source_hash, text, char_count, created_at FROM ${this.prefix}source_documents
5535
+ WHERE entity_id = ? AND source_ref = ?`,
5536
+ [entityId, ref]
5537
+ );
5538
+ if (!row) return null;
5539
+ return {
5540
+ sourceRef: row.source_ref,
5541
+ sourceHash: row.source_hash,
5542
+ text: row.text,
5543
+ charCount: Number(row.char_count),
5544
+ storedAt: Number(row.created_at)
5545
+ };
5546
+ }
5547
+ /** Spec §4/§7: full store listing, including sources stored with no ingest. */
5548
+ async listStoredSources(entityId) {
5549
+ const rows = await this.db.getAllAsync(
5550
+ `SELECT d.source_ref, d.source_hash, d.char_count, d.created_at,
5551
+ (SELECT COUNT(*) FROM ${this.prefix}source_passages p
5552
+ WHERE p.entity_id = d.entity_id AND p.document_id = d.id) AS passage_count
5553
+ FROM ${this.prefix}source_documents d
5554
+ WHERE d.entity_id = ?
5555
+ ORDER BY d.source_ref COLLATE BINARY`,
5556
+ [entityId]
5557
+ );
5558
+ return rows.map((r) => ({
5559
+ sourceRef: r.source_ref,
5560
+ sourceHash: r.source_hash,
5561
+ charCount: Number(r.char_count),
5562
+ passageCount: Number(r.passage_count),
5563
+ storedAt: Number(r.created_at)
5564
+ }));
5565
+ }
5566
+ };
5567
+
5568
+ // src/utils/monotonicNow.ts
5569
+ var monotonicNow = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
5570
+
5571
+ // src/utils/setupDefaults.ts
5572
+ var DEFAULT_SETUP_BUDGET_MS = 1500;
5573
+
5574
+ // src/services/search/ftsQuery.ts
5575
+ var TOKEN = /[\p{L}\p{N}]+/gu;
5576
+ function buildFtsMatchQuery(query) {
5577
+ const seen = /* @__PURE__ */ new Set();
5578
+ for (const m of query.toLowerCase().matchAll(TOKEN)) seen.add(m[0]);
5579
+ if (seen.size === 0) return null;
5580
+ return [...seen].map((t) => `"${t}"*`).join(" OR ");
5581
+ }
5582
+
5583
+ // src/services/search/Fts5IndexStrategy.ts
5584
+ async function hydratePassageHits(db, prefix, raw) {
5585
+ const docs = /* @__PURE__ */ new Map();
5586
+ const out = [];
5587
+ for (const r of raw) {
5588
+ const pas = await db.getFirstAsync(
5589
+ `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages WHERE id = ? AND entity_id = ?`,
5590
+ [r.id, r.entity_id]
5591
+ );
5592
+ if (!pas) continue;
5593
+ const dk = `${r.entity_id}\0${r.document_id}`;
5594
+ if (!docs.has(dk)) {
5595
+ docs.set(dk, await db.getFirstAsync(
5596
+ `SELECT source_ref, source_hash, text FROM ${prefix}source_documents WHERE id = ? AND entity_id = ?`,
5597
+ [r.document_id, r.entity_id]
5598
+ ) ?? null);
5599
+ }
5600
+ const doc = docs.get(dk);
5601
+ if (!doc) continue;
5602
+ const start = Number(pas.start_offset);
5603
+ const end = Number(pas.end_offset);
5604
+ out.push({
5605
+ ...r,
5606
+ seq: Number(pas.seq),
5607
+ start_offset: start,
5608
+ end_offset: end,
5609
+ source_ref: doc.source_ref,
5610
+ source_hash: doc.source_hash,
5611
+ text: doc.text.slice(start, end)
5081
5612
  });
5082
5613
  }
5614
+ return out;
5615
+ }
5616
+ var Fts5IndexStrategy = class {
5617
+ constructor(db, prefix, metadataRepo, budgetMs = DEFAULT_SETUP_BUDGET_MS) {
5618
+ this.db = db;
5619
+ this.prefix = prefix;
5620
+ this.metadataRepo = metadataRepo;
5621
+ this.budgetMs = budgetMs;
5622
+ /** Set when passage-index init failed; passage drain and search become no-ops. */
5623
+ this.passagesDisabled = false;
5624
+ }
5083
5625
  /**
5084
- * Incremental sync. Removes only ids currently tracked under `entityId`
5085
- * (other entities' docs are untouched), then upserts `documents` by id.
5086
- * The same id appearing in both `ids` and `documents` is discarded first
5087
- * so the upsert does not throw on a duplicate id.
5088
- *
5089
- * Every document must carry `entityId` as its `entity_id`; a mismatch is
5090
- * rejected before the write mutates anything. A tracking-only call
5091
- * (`replace(entityId, [], [])`) registers the entity as indexed, matching
5092
- * the interface contract.
5093
- *
5094
- * Atomicity: never awaits between the discard pass and `addDocuments`, so
5095
- * a concurrent `search()` sees the index wholly before or wholly after,
5096
- * never half-updated. This is the precondition the pre-extraction
5097
- * `syncEntries` kept with its "no await from here to `addAll`" comment.
5626
+ * Resolves the index state (spec #280 Change 3 transition table). Every
5627
+ * read-only probe runs before the one transition transaction, so a probe
5628
+ * failure leaves zero mutation (Change 4 ordering).
5098
5629
  */
5099
- async replace(entityId, ids, documents) {
5100
- assertOwnedBy(entityId, documents);
5101
- this.discardIds(ids, entityId);
5102
- if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
5103
- this.addDocuments(documents);
5630
+ async init(opts = {}) {
5631
+ await this.initEntries(opts);
5632
+ try {
5633
+ await this.ensurePassageObjects();
5634
+ } catch (err) {
5635
+ this.passagesDisabled = true;
5636
+ console.warn("[WikiMemory] passage index init failed; passage search returns [] until a later open:", err);
5637
+ }
5104
5638
  }
5105
5639
  /**
5106
- * Per-entity rebuild. Removes every id tracked under `entityId` (with the
5107
- * `index.has(id)` guard so a stale tracking set cannot make `discard()`
5108
- * throw), then writes `documents`. The entity stays registered as
5109
- * indexed — even when `documents` is empty — so the next `syncEntries`
5110
- * call can take the fast path. Every document must belong to `entityId`.
5640
+ * Source-store passage index objects (spec source-store §6): created here,
5641
+ * the way the entries_fts objects are, never by setupDatabase. Skipped when
5642
+ * the store tables are absent (a pre-v17 database).
5111
5643
  */
5112
- async replaceEntity(entityId, documents) {
5113
- assertOwnedBy(entityId, documents);
5114
- const previous = this.entryIdsByEntity.get(entityId);
5115
- if (previous) this.discardIds([...previous]);
5116
- this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
5117
- this.addDocuments(documents);
5644
+ async ensurePassageObjects() {
5645
+ const p = this.prefix;
5646
+ if (!await this.metadataRepo.tableExists(`${p}source_passages`)) return;
5647
+ await this.db.withTransactionAsync(async (tx) => {
5648
+ await tx.execAsync(passageFtsTablesDdl(p) + passageFtsTriggersDdl(p));
5649
+ const mapped = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_map LIMIT 1`);
5650
+ const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);
5651
+ if (mapped === null && queued === null) {
5652
+ await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);
5653
+ await tx.runAsync(
5654
+ `INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)
5655
+ SELECT entity_id, id FROM ${p}source_documents`
5656
+ );
5657
+ }
5658
+ });
5118
5659
  }
5119
5660
  /**
5120
- * Global rebuild / clear. Replaces the MiniSearch instance and clears both
5121
- * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
5122
- * `SearchService.clearAll()` calls `replaceAll([])`.
5661
+ * Drain the passage ledger one document at a time (spec §6, the stated
5662
+ * departure from all-SQL): the document's text is read into JS and sliced at
5663
+ * the offsets the cutter stored, so transient memory is bounded by
5664
+ * `maxCharsPerSource` for the ONE document, never the store. Each document
5665
+ * is one transaction. `entityId` limits the drain to that entity's ledger rows.
5123
5666
  */
5124
- async replaceAll(documents) {
5125
- this.index = this.createIndex();
5126
- this.entryIdsByEntity.clear();
5127
- this.entityIdById.clear();
5128
- this.addDocuments(documents);
5129
- }
5130
- /**
5131
- * Best-match-first search over the documents whose `entity_id` is in
5132
- * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
5133
- * uses this to over-fetch candidates before the `limit` cap). Scores are
5134
- * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
5135
- * any scaling, not the strategy.
5136
- */
5137
- async search(query, options) {
5138
- if (options.entityIds.length === 0) return [];
5139
- const entityIdSet = new Set(options.entityIds);
5140
- const limit = options.preFilterLimit ?? options.limit;
5141
- const raw = this.index.search(query, {
5142
- filter: (r) => entityIdSet.has(r.entity_id),
5143
- combineWith: "OR"
5144
- });
5145
- raw.sort((a, b) => {
5146
- const scoreDiff = b.score - a.score;
5147
- if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
5148
- return a.id.localeCompare(b.id);
5149
- });
5150
- return raw.slice(0, limit).map((r) => ({
5151
- id: r.id,
5152
- entity_id: r.entity_id,
5153
- score: r.score
5154
- }));
5155
- }
5156
- /**
5157
- * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
5158
- * un-vacuumed discard inverts the relative scores of term-sharing
5159
- * documents at any index size. `SearchService.syncEntries` calls this
5160
- * after a discard-bearing turn. No-op when `dirtCount === 0`.
5161
- */
5162
- async vacuum() {
5163
- if (this.index.dirtCount > 0) {
5164
- await this.index.vacuum();
5165
- }
5166
- }
5167
- /**
5168
- * `true` when `entityId` has been indexed at least once under the current
5169
- * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
5170
- * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
5171
- */
5172
- hasIndexedEntity(entityId) {
5173
- return this.entryIdsByEntity.has(entityId);
5174
- }
5175
- /**
5176
- * Add `documents` to the MiniSearch instance and register them in
5177
- * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
5178
- * during `add`, so each doc is copied first. `add` throws on an id the
5179
- * index already holds — `replace` and `replaceEntity` discard first for
5180
- * that reason.
5181
- *
5182
- * Adds and registers one document at a time: if a duplicate id throws
5183
- * part-way through, every document already in the index is tracked, so
5184
- * the next rebuild can discard it instead of failing on it again. This is
5185
- * the precondition the per-turn recovery path relies on (#258 review).
5186
- */
5187
- addDocuments(documents) {
5188
- for (const d of documents) {
5189
- const doc = { ...d };
5190
- this.index.add(doc);
5191
- const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
5192
- set.add(doc.id);
5193
- this.entryIdsByEntity.set(doc.entity_id, set);
5194
- this.entityIdById.set(doc.id, doc.entity_id);
5667
+ async drainPassages(opts = {}) {
5668
+ if (this.passagesDisabled) return;
5669
+ const p = this.prefix;
5670
+ if (!await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`)) return;
5671
+ for (; ; ) {
5672
+ if (opts.deadline !== void 0 && monotonicNow() >= opts.deadline) return;
5673
+ let ran = false;
5674
+ await this.db.withTransactionAsync(async (tx) => {
5675
+ const first = opts.entityId === void 0 ? await tx.getFirstAsync(
5676
+ `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending ORDER BY seq LIMIT 1`
5677
+ ) : await tx.getFirstAsync(
5678
+ `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending WHERE entity_id = ? ORDER BY seq LIMIT 1`,
5679
+ [opts.entityId]
5680
+ );
5681
+ if (!first) return;
5682
+ const docId = first.doc_id;
5683
+ const ent = first.entity_id;
5684
+ const hi = await tx.getFirstAsync(
5685
+ `SELECT max(seq) AS hi FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND entity_id = ?`,
5686
+ [docId, ent]
5687
+ );
5688
+ await tx.runAsync(
5689
+ `DELETE FROM ${p}source_passages_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}source_passages_fts_map WHERE doc_id = ?)`,
5690
+ [docId]
5691
+ );
5692
+ await tx.runAsync(`DELETE FROM ${p}source_passages_fts_map WHERE doc_id = ?`, [docId]);
5693
+ const doc = await tx.getFirstAsync(`SELECT text FROM ${p}source_documents WHERE id = ? AND entity_id = ?`, [docId, ent]);
5694
+ if (doc) {
5695
+ const rows = await tx.getAllAsync(
5696
+ `SELECT id, entity_id, start_offset, end_offset FROM ${p}source_passages WHERE document_id = ? AND entity_id = ? ORDER BY seq`,
5697
+ [docId, ent]
5698
+ );
5699
+ for (const r of rows) {
5700
+ const { lastInsertRowId } = await tx.runAsync(
5701
+ `INSERT INTO ${p}source_passages_fts_map (passage_id, doc_id) VALUES (?, ?)`,
5702
+ [r.id, docId]
5703
+ );
5704
+ await tx.runAsync(
5705
+ `INSERT INTO ${p}source_passages_fts (rowid, passage_id, entity_id, doc_id, text) VALUES (?, ?, ?, ?, ?)`,
5706
+ [lastInsertRowId, r.id, r.entity_id, docId, doc.text.slice(Number(r.start_offset), Number(r.end_offset))]
5707
+ );
5708
+ }
5709
+ }
5710
+ await tx.runAsync(
5711
+ `DELETE FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND seq <= ?`,
5712
+ [docId, hi?.hi ?? 0]
5713
+ );
5714
+ ran = true;
5715
+ });
5716
+ if (!ran) return;
5195
5717
  }
5196
5718
  }
5197
5719
  /**
5198
- * Discard `ids` from the MiniSearch instance and from both id maps, but
5199
- * only for ids currently owned by `entityId` (the second argument). When
5200
- * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
5201
- * path), every id is discarded regardless of owning entity.
5202
- *
5203
- * `index.has(id)` is the membership test of record: a rebuild that failed
5204
- * between its own discard pass and the set replacement can leave the
5205
- * tracking set claiming ids the index no longer holds — `discard()` throws
5206
- * on those, so we guard.
5720
+ * Best-match-first passage search. A hit counts only while its
5721
+ * `source_passages` row exists, so a stalled drain never surfaces a deleted
5722
+ * passage (spec §5).
5207
5723
  */
5208
- discardIds(ids, entityId) {
5209
- for (const id of ids) {
5210
- const owning = this.entityIdById.get(id);
5211
- if (owning === void 0) continue;
5212
- if (entityId !== void 0 && owning !== entityId) continue;
5213
- if (this.index.has(id)) this.index.discard(id);
5214
- this.entryIdsByEntity.get(owning)?.delete(id);
5215
- this.entityIdById.delete(id);
5216
- }
5217
- }
5218
- };
5219
- function assertOwnedBy(entityId, documents) {
5220
- for (const doc of documents) {
5221
- if (doc.entity_id !== entityId) {
5222
- throw new Error(
5223
- `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
5224
- );
5225
- }
5226
- }
5227
- }
5228
-
5229
- // src/utils/monotonicNow.ts
5230
- var monotonicNow = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
5231
-
5232
- // src/utils/setupDefaults.ts
5233
- var DEFAULT_SETUP_BUDGET_MS = 1500;
5234
-
5235
- // src/services/search/ftsQuery.ts
5236
- var TOKEN = /[\p{L}\p{N}]+/gu;
5237
- function buildFtsMatchQuery(query) {
5238
- const seen = /* @__PURE__ */ new Set();
5239
- for (const m of query.toLowerCase().matchAll(TOKEN)) seen.add(m[0]);
5240
- if (seen.size === 0) return null;
5241
- return [...seen].map((t) => `"${t}"*`).join(" OR ");
5242
- }
5243
-
5244
- // src/services/search/Fts5IndexStrategy.ts
5245
- var Fts5IndexStrategy = class {
5246
- constructor(db, prefix, metadataRepo, budgetMs = DEFAULT_SETUP_BUDGET_MS) {
5247
- this.db = db;
5248
- this.prefix = prefix;
5249
- this.metadataRepo = metadataRepo;
5250
- this.budgetMs = budgetMs;
5724
+ async searchPassages(query, options) {
5725
+ if (this.passagesDisabled || options.entityIds.length === 0) return [];
5726
+ const match = buildFtsMatchQuery(query);
5727
+ if (match === null) return [];
5728
+ const p = this.prefix;
5729
+ const t = `${p}source_passages_fts`;
5730
+ const limit = options.limit >= Number.MAX_SAFE_INTEGER ? -1 : options.limit;
5731
+ const raw = await this.db.getAllAsync(
5732
+ `SELECT passage_id AS id, entity_id, doc_id AS document_id, max(0.0, -raw) AS score FROM (
5733
+ SELECT passage_id, entity_id, doc_id, bm25(${t}, 0.0, 0.0, 0.0, 1.0) AS raw
5734
+ FROM ${t}
5735
+ WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))
5736
+ AND passage_id IN (SELECT id FROM ${p}source_passages WHERE entity_id IN (SELECT value FROM json_each(?)))
5737
+ ORDER BY raw, passage_id
5738
+ LIMIT ?)
5739
+ ORDER BY raw, id`,
5740
+ [match, JSON.stringify(options.entityIds), JSON.stringify(options.entityIds), limit]
5741
+ );
5742
+ return hydratePassageHits(this.db, p, raw);
5251
5743
  }
5252
- /**
5253
- * Resolves the index state (spec #280 Change 3 transition table). Every
5254
- * read-only probe runs before the one transition transaction, so a probe
5255
- * failure leaves zero mutation (Change 4 ordering).
5256
- */
5257
- async init(opts = {}) {
5744
+ async initEntries(opts) {
5258
5745
  try {
5259
5746
  await this.initOnce(opts);
5260
5747
  } catch (err) {
@@ -5628,110 +6115,385 @@ var Fts5IndexStrategy = class {
5628
6115
  await this.insertDocs(tx, documents);
5629
6116
  });
5630
6117
  }
5631
- async search(query, options) {
5632
- if (options.entityIds.length === 0) return [];
5633
- const match = buildFtsMatchQuery(query);
5634
- if (match === null) return [];
5635
- const cap = options.preFilterLimit ?? options.limit;
5636
- const limit = cap >= Number.MAX_SAFE_INTEGER ? -1 : cap;
5637
- const t = `${this.prefix}entries_fts`;
5638
- return this.db.getAllAsync(
5639
- `SELECT id, entity_id, max(0.0, -raw) AS score FROM (
5640
- SELECT id, entity_id, bm25(${t}, 0.0, 0.0, 2.0, 1.0, 1.0) AS raw
5641
- FROM ${t}
5642
- WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))
5643
- ORDER BY raw, id
5644
- LIMIT ?)
5645
- ORDER BY raw, id`,
5646
- [match, JSON.stringify(options.entityIds), limit]
5647
- );
5648
- }
5649
- async deleteByIds(tx, entityId, ids) {
5650
- if (ids.length === 0) return;
5651
- const p = this.prefix;
5652
- const json = JSON.stringify(ids);
5653
- const whereEntity = entityId === null ? "" : " AND entity_id = ?";
5654
- const args = [json];
5655
- if (entityId !== null) args.push(entityId);
5656
- await tx.runAsync(
5657
- `DELETE FROM ${p}entries_fts WHERE rowid IN (
5658
- SELECT fts_rowid FROM ${p}fts_map WHERE id IN (SELECT value FROM json_each(?))${whereEntity})`,
5659
- args
5660
- );
5661
- await tx.runAsync(
5662
- `DELETE FROM ${p}fts_map WHERE id IN (SELECT value FROM json_each(?))${whereEntity}`,
5663
- args
5664
- );
6118
+ async search(query, options) {
6119
+ if (options.entityIds.length === 0) return [];
6120
+ const match = buildFtsMatchQuery(query);
6121
+ if (match === null) return [];
6122
+ const cap = options.preFilterLimit ?? options.limit;
6123
+ const limit = cap >= Number.MAX_SAFE_INTEGER ? -1 : cap;
6124
+ const t = `${this.prefix}entries_fts`;
6125
+ return this.db.getAllAsync(
6126
+ `SELECT id, entity_id, max(0.0, -raw) AS score FROM (
6127
+ SELECT id, entity_id, bm25(${t}, 0.0, 0.0, 2.0, 1.0, 1.0) AS raw
6128
+ FROM ${t}
6129
+ WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))
6130
+ ORDER BY raw, id
6131
+ LIMIT ?)
6132
+ ORDER BY raw, id`,
6133
+ [match, JSON.stringify(options.entityIds), limit]
6134
+ );
6135
+ }
6136
+ async deleteByIds(tx, entityId, ids) {
6137
+ if (ids.length === 0) return;
6138
+ const p = this.prefix;
6139
+ const json = JSON.stringify(ids);
6140
+ const whereEntity = entityId === null ? "" : " AND entity_id = ?";
6141
+ const args = [json];
6142
+ if (entityId !== null) args.push(entityId);
6143
+ await tx.runAsync(
6144
+ `DELETE FROM ${p}entries_fts WHERE rowid IN (
6145
+ SELECT fts_rowid FROM ${p}fts_map WHERE id IN (SELECT value FROM json_each(?))${whereEntity})`,
6146
+ args
6147
+ );
6148
+ await tx.runAsync(
6149
+ `DELETE FROM ${p}fts_map WHERE id IN (SELECT value FROM json_each(?))${whereEntity}`,
6150
+ args
6151
+ );
6152
+ }
6153
+ /** One INSERT pair per document: a throw part-way rolls back the whole transaction. */
6154
+ async insertDocs(tx, documents) {
6155
+ const p = this.prefix;
6156
+ for (const d of documents) {
6157
+ const { lastInsertRowId } = await tx.runAsync(
6158
+ `INSERT INTO ${p}fts_map (id, entity_id) VALUES (?, ?)`,
6159
+ [d.id, d.entity_id]
6160
+ );
6161
+ await tx.runAsync(
6162
+ `INSERT INTO ${p}entries_fts (rowid, id, entity_id, title, body, tags) VALUES (?, ?, ?, ?, ?, ?)`,
6163
+ [lastInsertRowId, d.id, d.entity_id, d.title, d.body, d.tags]
6164
+ );
6165
+ }
6166
+ }
6167
+ /** The init probes' schema facts in one sqlite_master read (#284 review): FTS tables with their DDL, and the triggers. */
6168
+ async readSchema() {
6169
+ const p = this.prefix;
6170
+ const triggers = fts5TriggerNames(p);
6171
+ const names = [`${p}entries_fts`, `${p}fts_map`, `${p}fts_pending`, ...triggers];
6172
+ const rows = await this.db.getAllAsync(
6173
+ `SELECT type, name, sql FROM sqlite_master WHERE name IN (${names.map(() => "?").join(", ")})`,
6174
+ names
6175
+ );
6176
+ const tables = new Map(rows.filter((r) => r.type === "table").map((r) => [r.name, r.sql]));
6177
+ const present = new Set(rows.filter((r) => r.type === "trigger").map((r) => r.name));
6178
+ return { tables, triggersPresent: triggers.every((n) => present.has(n)) };
6179
+ }
6180
+ };
6181
+ var FtsOnlyStatementError = class extends Error {
6182
+ constructor(cause) {
6183
+ super("FTS-only statement failed");
6184
+ this.ftsOnlyCause = cause;
6185
+ }
6186
+ };
6187
+ function unwrapFtsOnly(err) {
6188
+ try {
6189
+ if (err instanceof FtsOnlyStatementError) return { cause: err.ftsOnlyCause, ftsOnly: true };
6190
+ } catch {
6191
+ }
6192
+ return { cause: err, ftsOnly: false };
6193
+ }
6194
+ function safeSqliteCode(err) {
6195
+ try {
6196
+ const code = extractSqliteCode(err);
6197
+ if (code !== void 0) return code;
6198
+ const lifted = err?.sqliteErrorCode;
6199
+ return typeof lifted === "string" ? lifted : void 0;
6200
+ } catch {
6201
+ return void 0;
6202
+ }
6203
+ }
6204
+ var TRANSIENT_OR_TX_FATAL = ["SQLITE_BUSY", "SQLITE_LOCKED", "SQLITE_FULL", "SQLITE_IOERR", "SQLITE_NOMEM", "SQLITE_INTERRUPT", "SQLITE_ABORT", "SQLITE_READONLY"];
6205
+ function isTransientOrTxFatal(err) {
6206
+ const code = safeSqliteCode(err);
6207
+ return code !== void 0 && TRANSIENT_OR_TX_FATAL.some((c) => code === c || code.startsWith(`${c}_`));
6208
+ }
6209
+ function ftsCorruptionClass(err) {
6210
+ const code = safeSqliteCode(err);
6211
+ if (code === "SQLITE_CORRUPT_VTAB") return "vtab";
6212
+ if (code?.startsWith("SQLITE_CORRUPT")) return "corrupt";
6213
+ return null;
6214
+ }
6215
+ function isSqliteError(err) {
6216
+ return safeSqliteCode(err) !== void 0;
6217
+ }
6218
+ function assertEntity(entityId, documents) {
6219
+ for (const d of documents) {
6220
+ if (d.entity_id !== entityId) {
6221
+ throw new TypeError(`IndexDocument ${d.id} has entity_id ${d.entity_id}, expected ${entityId}`);
6222
+ }
6223
+ }
6224
+ }
6225
+
6226
+ // src/services/search/MiniSearchIndexStrategy.ts
6227
+ async function loadStoredPassages(db, prefix, entityId) {
6228
+ const out = [];
6229
+ const docs = await db.getAllAsync(`SELECT id FROM ${prefix}source_documents WHERE entity_id = ?`, [entityId]);
6230
+ for (const d of docs) {
6231
+ const doc = await db.getFirstAsync(`SELECT text FROM ${prefix}source_documents WHERE id = ?`, [d.id]);
6232
+ if (!doc) continue;
6233
+ const rows = await db.getAllAsync(
6234
+ `SELECT id, start_offset, end_offset FROM ${prefix}source_passages WHERE document_id = ? ORDER BY seq`,
6235
+ [d.id]
6236
+ );
6237
+ for (const r of rows) {
6238
+ out.push({ id: r.id, entity_id: entityId, document_id: d.id, text: doc.text.slice(Number(r.start_offset), Number(r.end_offset)) });
6239
+ }
6240
+ }
6241
+ return out;
6242
+ }
6243
+ var MiniSearchIndexStrategy = class {
6244
+ constructor() {
6245
+ /**
6246
+ * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
6247
+ * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
6248
+ * not see this map; it only sees `hasIndexedEntity`. The previous
6249
+ * `miniSearchEntryIdsByEntity` lived on `SearchService`.
6250
+ */
6251
+ this.entryIdsByEntity = /* @__PURE__ */ new Map();
6252
+ /**
6253
+ * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
6254
+ * decide which ids are owned by `entityId` (the only safe membership test
6255
+ * — a rebuild that failed between its discard pass and the set replacement
6256
+ * can leave the forward set claiming ids the MiniSearch instance does not
6257
+ * hold). The pre-extraction `syncEntries` deleted from one set per id, not
6258
+ * from every entity's set.
6259
+ */
6260
+ this.entityIdById = /* @__PURE__ */ new Map();
6261
+ // ---- Source-store passage index (spec source-store §6) --------------------
6262
+ // A second in-heap instance over the same passage slices as the FTS5 path.
6263
+ this.passageIndex = this.createPassageIndex();
6264
+ this.passageIdsByEntity = /* @__PURE__ */ new Map();
6265
+ /** Handle `reindexSourcePassages` last indexed from; `searchPassages` hydrates hits through it. */
6266
+ this.passageSource = null;
6267
+ this.index = this.createIndex();
6268
+ }
6269
+ /**
6270
+ * Build a fresh MiniSearch instance with the project's index options.
6271
+ * Called from the constructor and from `replaceAll`. We do not use
6272
+ * `removeAll()` on an existing instance because that empties the index but
6273
+ * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
6274
+ * `syncEntries`' conditional vacuum early after a clear.
6275
+ */
6276
+ createIndex() {
6277
+ return new MiniSearch__default.default({
6278
+ fields: ["title", "body", "tags"],
6279
+ storeFields: ["entity_id"],
6280
+ // Vacuuming is driven explicitly at the end of each serialized rebuild
6281
+ // (see SearchService.syncEntries). Auto-vacuum fires on its own
6282
+ // schedule, asynchronously with respect to the caller, and traversing
6283
+ // the tree mid-rebuild is what threw the uncaught TypeError in
6284
+ // MiniSearch.performVacuuming (#64).
6285
+ autoVacuum: false,
6286
+ searchOptions: {
6287
+ boost: { title: 2 },
6288
+ fuzzy: 0.2,
6289
+ prefix: true
6290
+ }
6291
+ });
6292
+ }
6293
+ /**
6294
+ * Incremental sync. Removes only ids currently tracked under `entityId`
6295
+ * (other entities' docs are untouched), then upserts `documents` by id.
6296
+ * The same id appearing in both `ids` and `documents` is discarded first
6297
+ * so the upsert does not throw on a duplicate id.
6298
+ *
6299
+ * Every document must carry `entityId` as its `entity_id`; a mismatch is
6300
+ * rejected before the write mutates anything. A tracking-only call
6301
+ * (`replace(entityId, [], [])`) registers the entity as indexed, matching
6302
+ * the interface contract.
6303
+ *
6304
+ * Atomicity: never awaits between the discard pass and `addDocuments`, so
6305
+ * a concurrent `search()` sees the index wholly before or wholly after,
6306
+ * never half-updated. This is the precondition the pre-extraction
6307
+ * `syncEntries` kept with its "no await from here to `addAll`" comment.
6308
+ */
6309
+ async replace(entityId, ids, documents) {
6310
+ assertOwnedBy(entityId, documents);
6311
+ this.discardIds(ids, entityId);
6312
+ if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
6313
+ this.addDocuments(documents);
6314
+ }
6315
+ /**
6316
+ * Per-entity rebuild. Removes every id tracked under `entityId` (with the
6317
+ * `index.has(id)` guard so a stale tracking set cannot make `discard()`
6318
+ * throw), then writes `documents`. The entity stays registered as
6319
+ * indexed — even when `documents` is empty — so the next `syncEntries`
6320
+ * call can take the fast path. Every document must belong to `entityId`.
6321
+ */
6322
+ async replaceEntity(entityId, documents) {
6323
+ assertOwnedBy(entityId, documents);
6324
+ const previous = this.entryIdsByEntity.get(entityId);
6325
+ if (previous) this.discardIds([...previous]);
6326
+ this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
6327
+ this.addDocuments(documents);
6328
+ }
6329
+ /**
6330
+ * Global rebuild / clear. Replaces the MiniSearch instance and clears both
6331
+ * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
6332
+ * `SearchService.clearAll()` calls `replaceAll([])`.
6333
+ */
6334
+ async replaceAll(documents) {
6335
+ this.index = this.createIndex();
6336
+ this.entryIdsByEntity.clear();
6337
+ this.entityIdById.clear();
6338
+ this.addDocuments(documents);
6339
+ }
6340
+ /**
6341
+ * Best-match-first search over the documents whose `entity_id` is in
6342
+ * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
6343
+ * uses this to over-fetch candidates before the `limit` cap). Scores are
6344
+ * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
6345
+ * any scaling, not the strategy.
6346
+ */
6347
+ async search(query, options) {
6348
+ if (options.entityIds.length === 0) return [];
6349
+ const entityIdSet = new Set(options.entityIds);
6350
+ const limit = options.preFilterLimit ?? options.limit;
6351
+ const raw = this.index.search(query, {
6352
+ filter: (r) => entityIdSet.has(r.entity_id),
6353
+ combineWith: "OR"
6354
+ });
6355
+ raw.sort((a, b) => {
6356
+ const scoreDiff = b.score - a.score;
6357
+ if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
6358
+ return a.id.localeCompare(b.id);
6359
+ });
6360
+ return raw.slice(0, limit).map((r) => ({
6361
+ id: r.id,
6362
+ entity_id: r.entity_id,
6363
+ score: r.score
6364
+ }));
6365
+ }
6366
+ createPassageIndex() {
6367
+ return new MiniSearch__default.default({
6368
+ fields: ["text"],
6369
+ storeFields: ["entity_id", "document_id"],
6370
+ autoVacuum: false,
6371
+ // explicit vacuum below, same reason as the facts instance (#64)
6372
+ searchOptions: { fuzzy: 0.2, prefix: true }
6373
+ });
5665
6374
  }
5666
- /** One INSERT pair per document: a throw part-way rolls back the whole transaction. */
5667
- async insertDocs(tx, documents) {
5668
- const p = this.prefix;
5669
- for (const d of documents) {
5670
- const { lastInsertRowId } = await tx.runAsync(
5671
- `INSERT INTO ${p}fts_map (id, entity_id) VALUES (?, ?)`,
5672
- [d.id, d.entity_id]
5673
- );
5674
- await tx.runAsync(
5675
- `INSERT INTO ${p}entries_fts (rowid, id, entity_id, title, body, tags) VALUES (?, ?, ?, ?, ?, ?)`,
5676
- [lastInsertRowId, d.id, d.entity_id, d.title, d.body, d.tags]
6375
+ /**
6376
+ * Re-index stored passages from SQLite: one entity, or every stored entity
6377
+ * when `entityId` is omitted (the open-time pass; up to `maxTotalChars` per
6378
+ * entity, and the heap grows with the number of stored entities, spec §6).
6379
+ * It is also the post-commit sync after forget/clearAll: deleted passages
6380
+ * drop out because the reload no longer finds their rows (spec §5).
6381
+ * Reads happen first; the discard and add are synchronous, so the swap is
6382
+ * atomic (a concurrent search sees the index wholly before or wholly after),
6383
+ * and the vacuum runs after the swap.
6384
+ */
6385
+ async reindexSourcePassages(db, prefix, entityId) {
6386
+ this.passageSource = { db, prefix };
6387
+ const entityIds = entityId !== void 0 ? [entityId] : [.../* @__PURE__ */ new Set([
6388
+ ...(await db.getAllAsync(`SELECT DISTINCT entity_id FROM ${prefix}source_documents`)).map((r) => r.entity_id),
6389
+ ...this.passageIdsByEntity.keys()
6390
+ ])];
6391
+ for (const id of entityIds) {
6392
+ const passages = await loadStoredPassages(db, prefix, id);
6393
+ for (const old of this.passageIdsByEntity.get(id) ?? []) {
6394
+ if (this.passageIndex.has(old)) this.passageIndex.discard(old);
6395
+ }
6396
+ const ids = /* @__PURE__ */ new Set();
6397
+ for (const d of passages) {
6398
+ this.passageIndex.add({ ...d });
6399
+ ids.add(d.id);
6400
+ }
6401
+ if (ids.size > 0) this.passageIdsByEntity.set(id, ids);
6402
+ else this.passageIdsByEntity.delete(id);
6403
+ if (this.passageIndex.dirtCount > 0) await this.passageIndex.vacuum();
6404
+ }
6405
+ }
6406
+ /** Best-match-first passage search over the entities in `options.entityIds`. */
6407
+ async searchPassages(query, options) {
6408
+ if (options.entityIds.length === 0 || !this.passageSource) return [];
6409
+ const allowed = new Set(options.entityIds);
6410
+ const raw = this.passageIndex.search(query, { filter: (r) => allowed.has(r.entity_id), combineWith: "OR" });
6411
+ raw.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
6412
+ const live = /* @__PURE__ */ new Set();
6413
+ for (const eid of options.entityIds) {
6414
+ const rows = await this.passageSource.db.getAllAsync(
6415
+ `SELECT id FROM ${this.passageSource.prefix}source_passages WHERE entity_id = ?`,
6416
+ [eid]
5677
6417
  );
6418
+ for (const row of rows) live.add(row.id);
5678
6419
  }
6420
+ const hits = raw.filter((r) => live.has(r.id)).slice(0, options.limit).map((r) => ({
6421
+ id: r.id,
6422
+ entity_id: r.entity_id,
6423
+ document_id: r.document_id,
6424
+ score: r.score
6425
+ }));
6426
+ return hydratePassageHits(this.passageSource.db, this.passageSource.prefix, hits);
5679
6427
  }
5680
- /** The init probes' schema facts in one sqlite_master read (#284 review): FTS tables with their DDL, and the triggers. */
5681
- async readSchema() {
5682
- const p = this.prefix;
5683
- const triggers = fts5TriggerNames(p);
5684
- const names = [`${p}entries_fts`, `${p}fts_map`, `${p}fts_pending`, ...triggers];
5685
- const rows = await this.db.getAllAsync(
5686
- `SELECT type, name, sql FROM sqlite_master WHERE name IN (${names.map(() => "?").join(", ")})`,
5687
- names
5688
- );
5689
- const tables = new Map(rows.filter((r) => r.type === "table").map((r) => [r.name, r.sql]));
5690
- const present = new Set(rows.filter((r) => r.type === "trigger").map((r) => r.name));
5691
- return { tables, triggersPresent: triggers.every((n) => present.has(n)) };
6428
+ /**
6429
+ * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
6430
+ * un-vacuumed discard inverts the relative scores of term-sharing
6431
+ * documents at any index size. `SearchService.syncEntries` calls this
6432
+ * after a discard-bearing turn. No-op when `dirtCount === 0`.
6433
+ */
6434
+ async vacuum() {
6435
+ if (this.index.dirtCount > 0) {
6436
+ await this.index.vacuum();
6437
+ }
5692
6438
  }
5693
- };
5694
- var FtsOnlyStatementError = class extends Error {
5695
- constructor(cause) {
5696
- super("FTS-only statement failed");
5697
- this.ftsOnlyCause = cause;
6439
+ /**
6440
+ * `true` when `entityId` has been indexed at least once under the current
6441
+ * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
6442
+ * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
6443
+ */
6444
+ hasIndexedEntity(entityId) {
6445
+ return this.entryIdsByEntity.has(entityId);
5698
6446
  }
5699
- };
5700
- function unwrapFtsOnly(err) {
5701
- try {
5702
- if (err instanceof FtsOnlyStatementError) return { cause: err.ftsOnlyCause, ftsOnly: true };
5703
- } catch {
6447
+ /**
6448
+ * Add `documents` to the MiniSearch instance and register them in
6449
+ * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
6450
+ * during `add`, so each doc is copied first. `add` throws on an id the
6451
+ * index already holds — `replace` and `replaceEntity` discard first for
6452
+ * that reason.
6453
+ *
6454
+ * Adds and registers one document at a time: if a duplicate id throws
6455
+ * part-way through, every document already in the index is tracked, so
6456
+ * the next rebuild can discard it instead of failing on it again. This is
6457
+ * the precondition the per-turn recovery path relies on (#258 review).
6458
+ */
6459
+ addDocuments(documents) {
6460
+ for (const d of documents) {
6461
+ const doc = { ...d };
6462
+ this.index.add(doc);
6463
+ const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
6464
+ set.add(doc.id);
6465
+ this.entryIdsByEntity.set(doc.entity_id, set);
6466
+ this.entityIdById.set(doc.id, doc.entity_id);
6467
+ }
5704
6468
  }
5705
- return { cause: err, ftsOnly: false };
5706
- }
5707
- function safeSqliteCode(err) {
5708
- try {
5709
- const code = extractSqliteCode(err);
5710
- if (code !== void 0) return code;
5711
- const lifted = err?.sqliteErrorCode;
5712
- return typeof lifted === "string" ? lifted : void 0;
5713
- } catch {
5714
- return void 0;
6469
+ /**
6470
+ * Discard `ids` from the MiniSearch instance and from both id maps, but
6471
+ * only for ids currently owned by `entityId` (the second argument). When
6472
+ * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
6473
+ * path), every id is discarded regardless of owning entity.
6474
+ *
6475
+ * `index.has(id)` is the membership test of record: a rebuild that failed
6476
+ * between its own discard pass and the set replacement can leave the
6477
+ * tracking set claiming ids the index no longer holds — `discard()` throws
6478
+ * on those, so we guard.
6479
+ */
6480
+ discardIds(ids, entityId) {
6481
+ for (const id of ids) {
6482
+ const owning = this.entityIdById.get(id);
6483
+ if (owning === void 0) continue;
6484
+ if (entityId !== void 0 && owning !== entityId) continue;
6485
+ if (this.index.has(id)) this.index.discard(id);
6486
+ this.entryIdsByEntity.get(owning)?.delete(id);
6487
+ this.entityIdById.delete(id);
6488
+ }
5715
6489
  }
5716
- }
5717
- var TRANSIENT_OR_TX_FATAL = ["SQLITE_BUSY", "SQLITE_LOCKED", "SQLITE_FULL", "SQLITE_IOERR", "SQLITE_NOMEM", "SQLITE_INTERRUPT", "SQLITE_ABORT", "SQLITE_READONLY"];
5718
- function isTransientOrTxFatal(err) {
5719
- const code = safeSqliteCode(err);
5720
- return code !== void 0 && TRANSIENT_OR_TX_FATAL.some((c) => code === c || code.startsWith(`${c}_`));
5721
- }
5722
- function ftsCorruptionClass(err) {
5723
- const code = safeSqliteCode(err);
5724
- if (code === "SQLITE_CORRUPT_VTAB") return "vtab";
5725
- if (code?.startsWith("SQLITE_CORRUPT")) return "corrupt";
5726
- return null;
5727
- }
5728
- function isSqliteError(err) {
5729
- return safeSqliteCode(err) !== void 0;
5730
- }
5731
- function assertEntity(entityId, documents) {
5732
- for (const d of documents) {
5733
- if (d.entity_id !== entityId) {
5734
- throw new TypeError(`IndexDocument ${d.id} has entity_id ${d.entity_id}, expected ${entityId}`);
6490
+ };
6491
+ function assertOwnedBy(entityId, documents) {
6492
+ for (const doc of documents) {
6493
+ if (doc.entity_id !== entityId) {
6494
+ throw new Error(
6495
+ `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
6496
+ );
5735
6497
  }
5736
6498
  }
5737
6499
  }
@@ -5773,6 +6535,22 @@ async function probeFts5(db, prefix) {
5773
6535
  }
5774
6536
  }
5775
6537
  async function detachFts5(db, prefix, metadataRepo) {
6538
+ const passageLedger = await metadataRepo.tableExists(`${prefix}source_passages_fts_pending`);
6539
+ if (passageLedger) {
6540
+ const [ai, ad] = passageFtsTriggerNames(prefix);
6541
+ await db.withTransactionAsync(async (tx) => {
6542
+ await tx.execAsync(
6543
+ `DROP TRIGGER IF EXISTS ${ai};
6544
+ DROP TRIGGER IF EXISTS ${ad};
6545
+ DROP TABLE IF EXISTS ${prefix}source_passages_fts_map;
6546
+ DROP TABLE IF EXISTS ${prefix}source_passages_fts_pending;`
6547
+ );
6548
+ });
6549
+ try {
6550
+ await db.execAsync(`DROP TABLE IF EXISTS ${prefix}source_passages_fts`);
6551
+ } catch {
6552
+ }
6553
+ }
5776
6554
  const hasLedger = await metadataRepo.tableExists(`${prefix}fts_pending`);
5777
6555
  const state = await metadataRepo.getMeta(FTS5_STATE_KEY);
5778
6556
  if (!hasLedger && state !== "live") return;
@@ -5851,7 +6629,8 @@ var JobManager = class {
5851
6629
  reembed: (id) => this._reembedKey(id),
5852
6630
  import: (id) => this._importKey(id),
5853
6631
  forget: (id) => this._forgetKey(id),
5854
- ontologyBackfill: (id) => this._ontologyBackfillKey(id)
6632
+ ontologyBackfill: (id) => this._ontologyBackfillKey(id),
6633
+ store: (id) => this._storeKey(id)
5855
6634
  };
5856
6635
  }
5857
6636
  _hashLockKey(entityId, sourceHash) {
@@ -5920,6 +6699,9 @@ var JobManager = class {
5920
6699
  _librarianKey(entityId) {
5921
6700
  return `${this.prefix}:${entityId}:librarian`;
5922
6701
  }
6702
+ _storeKey(entityId) {
6703
+ return `${this.prefix}:${entityId}:store`;
6704
+ }
5923
6705
  _healKey(entityId) {
5924
6706
  return `${this.prefix}:${entityId}:heal`;
5925
6707
  }
@@ -5948,6 +6730,9 @@ var JobManager = class {
5948
6730
  _isImportActiveFor(entityId) {
5949
6731
  return this.activeMaintenanceJobs.has(this._importKey(entityId)) || this.activeMaintenanceJobs.has(this._globalImportKey());
5950
6732
  }
6733
+ _isStoreActiveFor(entityId) {
6734
+ return this.activeMaintenanceJobs.has(this._storeKey(entityId));
6735
+ }
5951
6736
  _isForgetActiveFor(entityId) {
5952
6737
  return this.activeMaintenanceJobs.has(this._forgetKey(entityId));
5953
6738
  }
@@ -5997,6 +6782,7 @@ var JobManager = class {
5997
6782
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
5998
6783
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
5999
6784
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6785
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6000
6786
  break;
6001
6787
  case "librarian":
6002
6788
  case "heal":
@@ -6007,6 +6793,7 @@ var JobManager = class {
6007
6793
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
6008
6794
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6009
6795
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6796
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6010
6797
  break;
6011
6798
  }
6012
6799
  case "reembed":
@@ -6019,6 +6806,7 @@ var JobManager = class {
6019
6806
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
6020
6807
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6021
6808
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6809
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6022
6810
  break;
6023
6811
  case "global_reembed":
6024
6812
  if (this.activeMaintenanceJobs.has(this._globalReembedKey())) blockingOperation = "reembed";
@@ -6030,6 +6818,7 @@ var JobManager = class {
6030
6818
  else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
6031
6819
  else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
6032
6820
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
6821
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
6033
6822
  break;
6034
6823
  case "import":
6035
6824
  case "forget": {
@@ -6043,10 +6832,23 @@ var JobManager = class {
6043
6832
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
6044
6833
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6045
6834
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6835
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6046
6836
  break;
6047
6837
  }
6838
+ case "store":
6839
+ if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6840
+ else if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
6841
+ else if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) blockingOperation = "librarian";
6842
+ else if (this.activeMaintenanceJobs.has(this._healKey(entityId))) blockingOperation = "heal";
6843
+ else if (this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId))) blockingOperation = "ontologyBackfill";
6844
+ else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
6845
+ else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
6846
+ else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6847
+ else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6848
+ break;
6048
6849
  case "global_import":
6049
6850
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) blockingOperation = "import";
6851
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
6050
6852
  break;
6051
6853
  case "ingest": {
6052
6854
  const sourceKey = sourceRef ?? "";
@@ -6055,6 +6857,7 @@ var JobManager = class {
6055
6857
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
6056
6858
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6057
6859
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6860
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6058
6861
  break;
6059
6862
  }
6060
6863
  }
@@ -6097,22 +6900,24 @@ var JobManager = class {
6097
6900
  case "librarian":
6098
6901
  case "heal":
6099
6902
  case "ontologyBackfill":
6100
- return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
6903
+ 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);
6101
6904
  case "prune":
6102
- 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);
6905
+ 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);
6103
6906
  case "reembed":
6104
- 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);
6907
+ 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);
6105
6908
  case "global_reembed":
6106
- 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");
6909
+ 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");
6107
6910
  case "import":
6108
6911
  case "forget": {
6109
6912
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
6110
- 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);
6913
+ 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);
6111
6914
  }
6915
+ case "store":
6916
+ 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);
6112
6917
  case "global_import":
6113
- return this.activeMaintenanceJobs.has(this._globalImportKey());
6918
+ return this.activeMaintenanceJobs.has(this._globalImportKey()) || this._isAnyMaintenanceActiveWithSuffix(":store");
6114
6919
  case "ingest":
6115
- return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
6920
+ return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
6116
6921
  default:
6117
6922
  return false;
6118
6923
  }
@@ -6177,6 +6982,7 @@ var JobManager = class {
6177
6982
  if (this._isReembedActive(entityId)) throw new WikiBusyError("reembed", entityId);
6178
6983
  if (this._isIngestActiveFor(entityId)) throw new WikiBusyError("ingest", entityId);
6179
6984
  if (this._isForgetActiveFor(entityId)) throw new WikiBusyError("forget", entityId);
6985
+ if (this._isStoreActiveFor(entityId)) throw new WikiBusyError("store", entityId);
6180
6986
  }
6181
6987
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) throw new WikiBusyError("import", "*");
6182
6988
  this.activeMaintenanceJobs.add(this._globalImportKey());
@@ -9396,6 +10202,10 @@ var MaintenanceService = class {
9396
10202
  if (await this.sourceRefIndexPresent(tx)) {
9397
10203
  await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
9398
10204
  }
10205
+ if (await this.sourceStorePresent(tx)) {
10206
+ await tx.runAsync(`DELETE FROM ${this.prefix}source_passages WHERE entity_id = ?`, [entityId]);
10207
+ await tx.runAsync(`DELETE FROM ${this.prefix}source_documents WHERE entity_id = ?`, [entityId]);
10208
+ }
9399
10209
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
9400
10210
  if (params.includeEvents) {
9401
10211
  deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
@@ -9419,6 +10229,16 @@ var MaintenanceService = class {
9419
10229
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
9420
10230
  if (entryId) deletedEntryIds.push(entryId);
9421
10231
  }
10232
+ if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
10233
+ const docs = `${this.prefix}source_documents`;
10234
+ const sel = "entity_id = ? AND (? IS NULL OR source_ref = ?) AND (? IS NULL OR source_hash = ?)";
10235
+ const selArgs = [entityId, sourceRef, sourceRef, sourceHash, sourceHash];
10236
+ await tx.runAsync(
10237
+ `DELETE FROM ${this.prefix}source_passages WHERE entity_id = ? AND document_id IN (SELECT id FROM ${docs} WHERE ${sel})`,
10238
+ [entityId, ...selArgs]
10239
+ );
10240
+ await tx.runAsync(`DELETE FROM ${docs} WHERE ${sel}`, selArgs);
10241
+ }
9422
10242
  if (sourceRef || sourceHash) {
9423
10243
  for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
9424
10244
  }
@@ -9535,6 +10355,10 @@ var MaintenanceService = class {
9535
10355
  if (version < 9) return false;
9536
10356
  throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
9537
10357
  }
10358
+ /** A never-set-up store has no source-store tables (#316 recovery); nothing to delete there. */
10359
+ async sourceStorePresent(tx) {
10360
+ return await this.metadataRepo.tableExists(`${this.prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${this.prefix}source_passages`, tx);
10361
+ }
9538
10362
  /**
9539
10363
  * Read-only dry-run preview of {@link forget}. Returns the same shape as a
9540
10364
  * real call would, without acquiring the lock, opening a transaction, staging
@@ -10582,7 +11406,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
10582
11406
  var IMPORT_TITLE_MAX = 500;
10583
11407
  var IMPORT_BODY_MAX = 8e3;
10584
11408
  var ImportExportService = class {
10585
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
11409
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
10586
11410
  this.db = db;
10587
11411
  this.entryRepo = entryRepo;
10588
11412
  this.taskRepo = taskRepo;
@@ -10594,6 +11418,7 @@ var ImportExportService = class {
10594
11418
  this.embeddingService = embeddingService;
10595
11419
  this.options = options;
10596
11420
  this.vectorRemoval = vectorRemoval;
11421
+ this.prefix = prefix;
10597
11422
  }
10598
11423
  async exportDump(entityIds) {
10599
11424
  let ids;
@@ -10601,6 +11426,13 @@ var ImportExportService = class {
10601
11426
  ids = Array.from(new Set(entityIds));
10602
11427
  } else {
10603
11428
  ids = await this.metadataRepo.getDistinctEntityIds();
11429
+ const prefix = this.storePrefix();
11430
+ if (prefix !== void 0 && await this.storePresent(prefix)) {
11431
+ const rows = await this.db.getAllAsync(
11432
+ `SELECT DISTINCT entity_id FROM ${prefix}source_documents`
11433
+ );
11434
+ ids = Array.from(/* @__PURE__ */ new Set([...ids, ...rows.map((r) => r.entity_id)])).sort();
11435
+ }
10604
11436
  }
10605
11437
  const entities = {};
10606
11438
  const BATCH = 3;
@@ -10608,10 +11440,11 @@ var ImportExportService = class {
10608
11440
  const batch = ids.slice(i, i + BATCH);
10609
11441
  const batchResults = await Promise.all(
10610
11442
  batch.map(
10611
- async (id) => [
10612
- id,
10613
- await this.getFullBundle(id, { includeBlobs: true })
10614
- ]
11443
+ async (id) => {
11444
+ const bundle = await this.getFullBundle(id, { includeBlobs: true });
11445
+ const storedSources = await this.exportStoredSources(id);
11446
+ return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
11447
+ }
10615
11448
  )
10616
11449
  );
10617
11450
  for (const [id, bundle] of batchResults) {
@@ -10622,16 +11455,96 @@ var ImportExportService = class {
10622
11455
  }
10623
11456
  async importDump(dump, opts) {
10624
11457
  const merge = opts?.merge ?? false;
11458
+ const skippedSources = [];
10625
11459
  const entityIds = Object.keys(dump.entities);
10626
11460
  this.jobManager.acquireImportLocks(entityIds);
10627
11461
  try {
10628
11462
  await this.assertNoLegacySourceTypes();
10629
11463
  for (const [entityId, bundle] of Object.entries(dump.entities)) {
10630
- await this.doImportEntity(entityId, bundle, merge);
11464
+ skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
10631
11465
  }
10632
11466
  } finally {
10633
11467
  this.jobManager.releaseImportLocks(entityIds);
10634
11468
  }
11469
+ return { skippedSources };
11470
+ }
11471
+ storePrefix() {
11472
+ return typeof this.prefix === "string" ? this.prefix : void 0;
11473
+ }
11474
+ // `source_ref_index` needs no check: the v9 migration (add_source_ref_index) creates it, and the
11475
+ // store tables come from v17, which only runs after v9 — so it exists whenever they do.
11476
+ async storePresent(prefix, tx) {
11477
+ return await this.metadataRepo.tableExists(`${prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${prefix}source_passages`, tx);
11478
+ }
11479
+ /** Spec source-store §8: stored sources for one exported entity; [] when none. */
11480
+ async exportStoredSources(entityId) {
11481
+ const prefix = this.storePrefix();
11482
+ if (prefix === void 0 || !await this.storePresent(prefix)) return [];
11483
+ const docs = await this.db.getAllAsync(
11484
+ `SELECT id, source_ref, source_hash, text, text_hash, char_count, created_at FROM ${prefix}source_documents
11485
+ WHERE entity_id = ? ORDER BY source_ref COLLATE BINARY`,
11486
+ [entityId]
11487
+ );
11488
+ const out = [];
11489
+ for (const d of docs) {
11490
+ const ps = await this.db.getAllAsync(
11491
+ `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages
11492
+ WHERE entity_id = ? AND document_id = ? ORDER BY seq`,
11493
+ [entityId, d.id]
11494
+ );
11495
+ out.push({
11496
+ sourceRef: d.source_ref,
11497
+ sourceHash: d.source_hash,
11498
+ text: d.text,
11499
+ textHash: d.text_hash,
11500
+ charCount: Number(d.char_count),
11501
+ storedAt: Number(d.created_at),
11502
+ passages: ps.map((p) => ({ seq: Number(p.seq), startOffset: Number(p.start_offset), endOffset: Number(p.end_offset) }))
11503
+ });
11504
+ }
11505
+ return out;
11506
+ }
11507
+ /**
11508
+ * Spec source-store §8/§9 import step, inside the import transaction. One
11509
+ * source at a time; a refusal skips that source only. Uses the
11510
+ * same upsert helper as SourceStoreService.storeSource, inside this transaction. A ref already stored is replaced: the dump is the
11511
+ * truth for that ref (so no hash_mismatch refusal on import).
11512
+ */
11513
+ async importStoredSources(tx, entityId, sources, merge, skipped, deferredDiagnostics) {
11514
+ const prefix = this.storePrefix();
11515
+ if (prefix === void 0) return;
11516
+ if (merge && !sources?.length) return;
11517
+ if (!await this.storePresent(prefix, tx)) return;
11518
+ const docs = `${prefix}source_documents`;
11519
+ const passages = `${prefix}source_passages`;
11520
+ if (!merge) {
11521
+ await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ?`, [entityId]);
11522
+ await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ?`, [entityId]);
11523
+ }
11524
+ const cfg = this.options.config?.sourceStore;
11525
+ const lim = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : d;
11526
+ const limits = {
11527
+ maxCharsPerSource: lim(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
11528
+ maxTotalChars: lim(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
11529
+ };
11530
+ for (const src of sources ?? []) {
11531
+ const sourceRef = normalizeSourceRef(src?.sourceRef);
11532
+ const sourceHash = normalizeSourceHash(src?.sourceHash);
11533
+ if (!sourceRef || !sourceHash || typeof src.text !== "string") {
11534
+ throw new Error(`importDump: invalid stored source for entity "${entityId}" (sourceRef, sourceHash and text are required)`);
11535
+ }
11536
+ await upsertStoredSource(
11537
+ tx,
11538
+ prefix,
11539
+ entityId,
11540
+ { sourceRef, sourceHash, text: src.text, storedAt: src.storedAt },
11541
+ limits,
11542
+ (code) => {
11543
+ skipped.push({ sourceRef, code });
11544
+ deferredDiagnostics.push({ code, operation: "importDump", trigger: "call", entityId, detail: { sourceRef } });
11545
+ }
11546
+ );
11547
+ }
10635
11548
  }
10636
11549
  async getFullBundle(entityId, opts) {
10637
11550
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
@@ -10670,6 +11583,8 @@ var ImportExportService = class {
10670
11583
  }
10671
11584
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
10672
11585
  async doImportEntity(entityId, bundle, merge) {
11586
+ const skippedSources = [];
11587
+ const refusalDiagnostics = [];
10673
11588
  const upsertedFactIds = /* @__PURE__ */ new Set();
10674
11589
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
10675
11590
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
@@ -10947,7 +11862,9 @@ var ImportExportService = class {
10947
11862
  tx
10948
11863
  );
10949
11864
  }
11865
+ await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
10950
11866
  });
11867
+ for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
10951
11868
  if (clampedEvents > 0) {
10952
11869
  emitDiagnostic(this.options, {
10953
11870
  code: "event_created_at_clamped",
@@ -11115,6 +12032,7 @@ var ImportExportService = class {
11115
12032
  } finally {
11116
12033
  this.searchService.evictCache(entityId);
11117
12034
  }
12035
+ return skippedSources;
11118
12036
  }
11119
12037
  _warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
11120
12038
  console.warn(
@@ -11639,6 +12557,63 @@ function packFactsByBudget(items, budget, scores) {
11639
12557
 
11640
12558
  // src/services/RetrievalService.ts
11641
12559
  var EMPTY_ID_SET = /* @__PURE__ */ new Set();
12560
+ var DEFAULT_SOURCE_PASSAGES = 8;
12561
+ var DEFAULT_SOURCE_CHAR_BUDGET = 4e3;
12562
+ var asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
12563
+ var isHigh2 = (c) => c >= 55296 && c <= 56319;
12564
+ var isLow2 = (c) => c >= 56320 && c <= 57343;
12565
+ function queryTerms(query) {
12566
+ return [...new Set(asciiLower(query).split(/[^\p{L}\p{N}]+/u).filter((t) => t.length > 0))];
12567
+ }
12568
+ function assertSourcesQuery(opt) {
12569
+ const query = opt?.query;
12570
+ if (typeof query !== "string" || query.trim() === "") {
12571
+ throw new WikiInvalidReadOptions("sources.query", "must be a non-empty string");
12572
+ }
12573
+ if (queryTerms(query).length === 0) {
12574
+ throw new WikiInvalidReadOptions("sources.query", "must contain at least one searchable term");
12575
+ }
12576
+ }
12577
+ function windowPassage(text, terms, budget) {
12578
+ if (text.length <= budget) return { start: 0, end: text.length, truncated: false };
12579
+ const lower = asciiLower(text);
12580
+ let a = -1;
12581
+ let len = 0;
12582
+ for (const t of terms) {
12583
+ const i = lower.indexOf(t);
12584
+ if (i >= 0 && (a < 0 || i < a || i === a && t.length > len)) {
12585
+ a = i;
12586
+ len = t.length;
12587
+ }
12588
+ }
12589
+ const hardCut = (from) => {
12590
+ let end = Math.min(text.length, from + budget);
12591
+ if (end < text.length && isHigh2(text.charCodeAt(end - 1)) && isLow2(text.charCodeAt(end))) {
12592
+ if (end - 1 > from) end -= 1;
12593
+ else return { start: from, end: from, truncated: true };
12594
+ }
12595
+ return { start: from, end, truncated: from > 0 || end < text.length };
12596
+ };
12597
+ if (a < 0) return hardCut(0);
12598
+ if (len > budget) return hardCut(a);
12599
+ const toks = [];
12600
+ for (const m of text.matchAll(/\S+/g)) toks.push([m.index, m.index + m[0].length]);
12601
+ const mEnd = a + len;
12602
+ const ti = toks.findIndex(([, e]) => e > a);
12603
+ if (ti < 0) return hardCut(a);
12604
+ let tj = ti;
12605
+ while (tj + 1 < toks.length && toks[tj][1] < mEnd) tj++;
12606
+ if (toks[tj][1] - toks[ti][0] > budget) return hardCut(a);
12607
+ let r = toks.length - 1;
12608
+ let best = { start: toks[ti][0], end: toks[tj][1] };
12609
+ for (let l = ti; l >= 0; l--) {
12610
+ const s = toks[l][0];
12611
+ while (r > tj && toks[r][1] - s > budget) r--;
12612
+ if (toks[r][1] - s > budget) break;
12613
+ if (toks[r][1] - s > best.end - best.start) best = { start: s, end: toks[r][1] };
12614
+ }
12615
+ return { ...best, truncated: true };
12616
+ }
11642
12617
  var RetrievalService = class {
11643
12618
  constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
11644
12619
  this.options = options;
@@ -11653,8 +12628,10 @@ var RetrievalService = class {
11653
12628
  const entityIds = normalizeEntityIds(entityId);
11654
12629
  const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
11655
12630
  const exposeMetadata = shouldExposeReadMetadata(entityId);
12631
+ if (options?.sources) assertSourcesQuery(options.sources);
11656
12632
  if (entityIds.length === 0) {
11657
12633
  const empty = { facts: [], tasks: [], events: [], edges: [] };
12634
+ if (options?.sources) empty.sources = [];
11658
12635
  if (exposeMetadata) {
11659
12636
  empty.metadata = { query, entityIds: [] };
11660
12637
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
@@ -12169,6 +13146,7 @@ var RetrievalService = class {
12169
13146
  factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
12170
13147
  }
12171
13148
  const bundle = { facts, tasks, events: events.reverse(), edges: [] };
13149
+ if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
12172
13150
  if (exposeMetadata) {
12173
13151
  bundle.metadata = { query, entityIds };
12174
13152
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
@@ -12177,6 +13155,42 @@ var RetrievalService = class {
12177
13155
  }
12178
13156
  return bundle;
12179
13157
  }
13158
+ /**
13159
+ * The `sources` group (spec source-store section 7). One search per entity,
13160
+ * so ranking and caps never cross entities. No model call anywhere.
13161
+ * `charBudget` is per entity: windows are cut in rank order against the
13162
+ * entity's remaining budget, and once it is spent lower-ranked hits are not returned.
13163
+ */
13164
+ async _readSources(entityIds, opt) {
13165
+ const pos = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : d;
13166
+ const maxPassages = pos(opt.maxPassages, DEFAULT_SOURCE_PASSAGES);
13167
+ const charBudget = pos(opt.charBudget, DEFAULT_SOURCE_CHAR_BUDGET);
13168
+ assertSourcesQuery(opt);
13169
+ const query = opt.query;
13170
+ const terms = queryTerms(query);
13171
+ const out = [];
13172
+ for (const entityId of entityIds) {
13173
+ const hits = await this.searchService.searchPassages(query, entityId, maxPassages);
13174
+ let remaining = charBudget;
13175
+ for (const h of hits) {
13176
+ if (remaining <= 0) break;
13177
+ const w = windowPassage(h.text, terms, remaining);
13178
+ if (w.end === w.start) continue;
13179
+ remaining -= w.end - w.start;
13180
+ out.push({
13181
+ entityId,
13182
+ sourceRef: h.source_ref,
13183
+ sourceHash: h.source_hash,
13184
+ seq: h.seq,
13185
+ startOffset: h.start_offset + w.start,
13186
+ endOffset: h.start_offset + w.end,
13187
+ truncated: w.truncated,
13188
+ text: h.text.slice(w.start, w.end)
13189
+ });
13190
+ }
13191
+ }
13192
+ return out;
13193
+ }
12180
13194
  /**
12181
13195
  * Returns entity IDs that will participate in scored retrieval.
12182
13196
  * Excludes zero-weight entities unless includeZeroWeightEntities is true.
@@ -13183,7 +14197,8 @@ var WikiMemory = class {
13183
14197
  this.jobManager,
13184
14198
  this.embeddingService,
13185
14199
  this.options,
13186
- this.vectorRemovalService
14200
+ this.vectorRemovalService,
14201
+ this.prefix
13187
14202
  );
13188
14203
  this.retrievalService = new RetrievalService(
13189
14204
  this.options,
@@ -13193,6 +14208,7 @@ var WikiMemory = class {
13193
14208
  this.metadataRepo,
13194
14209
  this.searchService
13195
14210
  );
14211
+ this.sourceStoreService = new SourceStoreService(this.db, this.prefix, this.options, this.jobManager);
13196
14212
  this.writeService = new WriteService(
13197
14213
  this.db,
13198
14214
  this.options,
@@ -13320,9 +14336,13 @@ var WikiMemory = class {
13320
14336
  * host runs a plain `setup()` outside the lease.
13321
14337
  *
13322
14338
  * Keyword-index catch-up work is bounded by `config.setupBudgetMs`; anything
13323
- * left converges on later opens and no-arg `syncSearchIndex()` calls. Not
13324
- * bounded: an index reset (tokenizer change, re-attach after detach, a lost
13325
- * or inconsistent index), which runs as one unchunked transaction.
14339
+ * left converges on later opens, and on no-arg `syncSearchIndex()` calls for
14340
+ * the entries ledger. Passage-ledger leftover converges on later opens and on
14341
+ * passage-store writes for the entity (`storeSource`, `forget`,
14342
+ * `importDump`), which drain that entity's rows; no-arg calls do not touch
14343
+ * the passage ledger. Not bounded: an index reset (tokenizer change, re-attach
14344
+ * after detach, a lost or inconsistent index), which runs as one unchunked
14345
+ * transaction.
13326
14346
  */
13327
14347
  async setup(opts) {
13328
14348
  const setupBudgetMs = this.setupBudgetMs();
@@ -13366,6 +14386,7 @@ var WikiMemory = class {
13366
14386
  )
13367
14387
  );
13368
14388
  await this.searchService.sync(void 0, { deadline: openDeadline });
14389
+ await this.searchService.syncPassages(this.db, this.prefix, void 0, openDeadline);
13369
14390
  await this.startSetupRemovalDrain();
13370
14391
  }
13371
14392
  /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
@@ -13788,6 +14809,7 @@ var WikiMemory = class {
13788
14809
  );
13789
14810
  this.searchService.setIndexStrategy(strategy);
13790
14811
  if (this.searchService.isKeywordAvailable() && !this.searchService.hasLedger()) await this.searchService.sync();
14812
+ if (this.searchService.isKeywordAvailable()) await this.searchService.syncPassages(this.db, this.prefix);
13791
14813
  } finally {
13792
14814
  if (this.searchService.isKeywordAvailable()) {
13793
14815
  this.reinitFailures = 0;
@@ -13830,7 +14852,13 @@ var WikiMemory = class {
13830
14852
  return this.metadataRepo.getMeta(entitySummaryMetaKey(entityId));
13831
14853
  }
13832
14854
  async importDump(dump, opts) {
13833
- return this.importExportService.importDump(dump, opts);
14855
+ try {
14856
+ return await this.importExportService.importDump(dump, opts);
14857
+ } finally {
14858
+ for (const entityId of Object.keys(dump?.entities ?? {})) {
14859
+ await this.searchService.syncPassages(this.db, this.prefix, entityId);
14860
+ }
14861
+ }
13834
14862
  }
13835
14863
  /**
13836
14864
  * Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
@@ -13851,7 +14879,28 @@ var WikiMemory = class {
13851
14879
  * or call `runExternalDeletions()`.
13852
14880
  */
13853
14881
  async forget(entityId, params, opts) {
13854
- return this.maintenanceService.forget(entityId, params, opts);
14882
+ try {
14883
+ return await this.maintenanceService.forget(entityId, params, opts);
14884
+ } finally {
14885
+ if (!opts?.dryRun) {
14886
+ await this.searchService.syncPassages(this.db, this.prefix, entityId);
14887
+ }
14888
+ }
14889
+ }
14890
+ /** Store a source's text (spec source-store §7). Refusals return `stored: false`; a busy lock throws. */
14891
+ async storeSource(entityId, params) {
14892
+ assertEntityId2(entityId);
14893
+ const result = await this.sourceStoreService.storeSource(entityId, params);
14894
+ if (result.stored) await this.searchService.syncPassages(this.db, this.prefix, entityId);
14895
+ return result;
14896
+ }
14897
+ async getStoredSource(entityId, sourceRef) {
14898
+ assertEntityId2(entityId);
14899
+ return this.sourceStoreService.getStoredSource(entityId, sourceRef);
14900
+ }
14901
+ async listStoredSources(entityId) {
14902
+ assertEntityId2(entityId);
14903
+ return this.sourceStoreService.listStoredSources(entityId);
13855
14904
  }
13856
14905
  /**
13857
14906
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
@@ -14208,6 +15257,10 @@ function renderEventPlain(event) {
14208
15257
  const ts = new Date(event.created_at).toISOString();
14209
15258
  return `[${event.event_type} @ ${ts}] ${event.summary}`;
14210
15259
  }
15260
+ function renderSourceLabel(p, includeEntityId) {
15261
+ const entity = includeEntityId ? `${p.entityId} ` : "";
15262
+ return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? " (excerpt)" : ""}`;
15263
+ }
14211
15264
  function formatContext(bundle, options) {
14212
15265
  const opts = {
14213
15266
  format: options?.format ?? "markdown",
@@ -14233,7 +15286,8 @@ function formatContext(bundle, options) {
14233
15286
  const sortedFacts = bundle.factScores ? [...bundle.facts].slice(0, opts.maxFacts) : [...bundle.facts].sort((a, b) => scoreFactFor(b, weights, now) - scoreFactFor(a, weights, now)).slice(0, opts.maxFacts);
14234
15287
  const sortedTasks = [...bundle.tasks].sort((a, b) => b.priority - a.priority || a.created_at - b.created_at).slice(0, opts.maxTasks);
14235
15288
  const sortedEvents = [...bundle.events].sort((a, b) => b.created_at - a.created_at).slice(0, opts.maxEvents);
14236
- if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0) {
15289
+ const sources = bundle.sources ?? [];
15290
+ if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.length === 0) {
14237
15291
  return "";
14238
15292
  }
14239
15293
  const isMarkdown = opts.format === "markdown";
@@ -14261,6 +15315,13 @@ function formatContext(bundle, options) {
14261
15315
  lines.push(renderEventMarkdown(event));
14262
15316
  }
14263
15317
  }
15318
+ if (sources.length > 0) {
15319
+ lines.push("");
15320
+ lines.push("### Sources");
15321
+ for (const p of sources) {
15322
+ lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\n/g, "\n ")}`);
15323
+ }
15324
+ }
14264
15325
  } else {
14265
15326
  if (sortedFacts.length > 0) {
14266
15327
  lines.push("KNOWN FACTS:");
@@ -14280,6 +15341,12 @@ function formatContext(bundle, options) {
14280
15341
  lines.push(renderEventPlain(event));
14281
15342
  }
14282
15343
  }
15344
+ if (sources.length > 0) {
15345
+ lines.push("SOURCES:");
15346
+ for (const p of sources) {
15347
+ lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);
15348
+ }
15349
+ }
14283
15350
  }
14284
15351
  return lines.join("\n");
14285
15352
  }