@equationalapplications/core-llm-wiki 9.0.0 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -42,7 +42,14 @@ var SEVERITY = {
42
42
  external_deletion_pending: "warn",
43
43
  external_deletion_discarded: "warn",
44
44
  guidance_too_long: "warn",
45
- guidance_resolver_failed: "warn"
45
+ guidance_resolver_failed: "warn",
46
+ source_pointer_unresolved: "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"
46
53
  };
47
54
  var MESSAGE = {
48
55
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -70,7 +77,14 @@ var MESSAGE = {
70
77
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
71
78
  external_deletion_discarded: "Pending external vector removals were discarded because forceDeleteIgnoreRankerHook is set.",
72
79
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
73
- guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass."
80
+ guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
81
+ source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
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."
74
88
  };
75
89
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
76
90
  function copyDetail(detail) {
@@ -945,7 +959,8 @@ async function setupDatabase(db, prefix) {
945
959
  valid_from INTEGER,
946
960
  valid_to INTEGER,
947
961
  superseded_by TEXT,
948
- superseded_at INTEGER
962
+ superseded_at INTEGER,
963
+ source_pointer TEXT
949
964
  );
950
965
 
951
966
  CREATE INDEX IF NOT EXISTS ${prefix}entries_entity_idx ON ${prefix}entries(entity_id);
@@ -971,6 +986,29 @@ async function setupDatabase(db, prefix) {
971
986
  ON ${prefix}source_ref_index (entity_id, source_hash)
972
987
  WHERE deleted_at IS NULL;
973
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
+
974
1012
  CREATE TABLE IF NOT EXISTS ${prefix}tasks (
975
1013
  id TEXT PRIMARY KEY,
976
1014
  entity_id TEXT NOT NULL,
@@ -1097,6 +1135,8 @@ async function setupDatabase(db, prefix) {
1097
1135
  `);
1098
1136
  await createOkfV02IndexesIfColumnsExist(db, prefix);
1099
1137
  await createTemporalIndexesIfColumnsExist(db, prefix);
1138
+ await createSourcePassageIndexesIfColumnsExist(db, prefix);
1139
+ await createSourceDocumentIndexesIfColumnsExist(db, prefix);
1100
1140
  await createResurrectTrigger(db, prefix);
1101
1141
  }
1102
1142
  var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
@@ -1163,6 +1203,22 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
1163
1203
  );
1164
1204
  }
1165
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
+ }
1166
1222
 
1167
1223
  // src/services/search/fts5Sql.ts
1168
1224
  var FTS5_STATE_KEY = "fts5_index_state";
@@ -1300,6 +1356,38 @@ function sweepChunkSql(p) {
1300
1356
  `DELETE FROM ${p}fts_map WHERE fts_rowid IN (${orphans})`
1301
1357
  ];
1302
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
+ }
1303
1391
 
1304
1392
  // src/db/migrations.ts
1305
1393
  var MIGRATIONS = [
@@ -1594,6 +1682,68 @@ var MIGRATIONS = [
1594
1682
  );
1595
1683
  if (row?.n) await db.execAsync(fts5PendingIndexesDdl(prefix));
1596
1684
  }
1685
+ },
1686
+ {
1687
+ version: 16,
1688
+ description: "Source pointers on librarian facts: nullable source_pointer TEXT on entries",
1689
+ run: async (db, prefix) => {
1690
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}entries)`);
1691
+ const existing = new Set(cols.map((c) => c.name));
1692
+ if (!existing.has("source_pointer")) {
1693
+ await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
1694
+ }
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
+ }
1597
1747
  }
1598
1748
  ];
1599
1749
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -1834,6 +1984,61 @@ function assertEpochMs(name, v) {
1834
1984
  }
1835
1985
  return Math.trunc(v);
1836
1986
  }
1987
+
1988
+ // src/utils/sourcePointer.ts
1989
+ var POINTER_SLOTS = ["event_id", "ref", "quote", "position"];
1990
+ function isStringOrNull(v) {
1991
+ return v === null || typeof v === "string";
1992
+ }
1993
+ function isValidPosition(v) {
1994
+ if (v === null) return true;
1995
+ if (typeof v !== "object" || v === null || Array.isArray(v)) return false;
1996
+ const o = v;
1997
+ const keys = Object.keys(o);
1998
+ if (keys.length !== 2 || !("start" in o) || !("length" in o)) return false;
1999
+ const { start, length } = o;
2000
+ return typeof start === "number" && Number.isInteger(start) && start >= 0 && typeof length === "number" && Number.isInteger(length) && length >= 0;
2001
+ }
2002
+ function validateSourcePointerValue(v) {
2003
+ if (v === null) return null;
2004
+ if (typeof v !== "object" || Array.isArray(v)) return void 0;
2005
+ const o = v;
2006
+ const keys = Object.keys(o);
2007
+ for (const k of keys) {
2008
+ if (!POINTER_SLOTS.includes(k)) return void 0;
2009
+ }
2010
+ if (!isStringOrNull(o["event_id"] === void 0 ? null : o["event_id"]) || !isStringOrNull(o["ref"] === void 0 ? null : o["ref"]) || !isStringOrNull(o["quote"] === void 0 ? null : o["quote"])) {
2011
+ return void 0;
2012
+ }
2013
+ if (!isValidPosition(o["position"] === void 0 ? null : o["position"])) return void 0;
2014
+ const normalized = {
2015
+ event_id: o["event_id"] ?? null,
2016
+ ref: o["ref"] ?? null,
2017
+ quote: o["quote"] ?? null,
2018
+ position: o["position"] ?? null
2019
+ };
2020
+ if (normalized.event_id === null && normalized.ref === null && normalized.quote === null && normalized.position === null) {
2021
+ return null;
2022
+ }
2023
+ return normalized;
2024
+ }
2025
+ function parseStoredSourcePointer(raw) {
2026
+ if (raw === null || raw === void 0) return null;
2027
+ if (typeof raw !== "string") return null;
2028
+ let parsed;
2029
+ try {
2030
+ parsed = JSON.parse(raw);
2031
+ } catch {
2032
+ return null;
2033
+ }
2034
+ const v = validateSourcePointerValue(parsed);
2035
+ return v === void 0 ? null : v;
2036
+ }
2037
+ function serializeSourcePointer(p) {
2038
+ return p ? JSON.stringify(p) : null;
2039
+ }
2040
+
2041
+ // src/repositories/EntryRepository.ts
1837
2042
  function mapRowToFact(row) {
1838
2043
  const tags = (() => {
1839
2044
  if (Array.isArray(row.tags)) return row.tags;
@@ -1847,7 +2052,8 @@ function mapRowToFact(row) {
1847
2052
  const okf_verified = parseJsonArray(row.okf_verified, []);
1848
2053
  const now = Date.now();
1849
2054
  const staleAfterRaw = row.stale_after != null ? Number(row.stale_after) : null;
1850
- return {
2055
+ const sourcePointer = parseStoredSourcePointer(row.source_pointer);
2056
+ const mapped = {
1851
2057
  id: row.id,
1852
2058
  entity_id: row.entity_id,
1853
2059
  title: row.title,
@@ -1880,8 +2086,13 @@ function mapRowToFact(row) {
1880
2086
  ...row.valid_from != null ? { valid_from: Number(row.valid_from) } : {},
1881
2087
  ...row.valid_to != null ? { valid_to: Number(row.valid_to) } : {},
1882
2088
  ...row.superseded_by != null ? { superseded_by: String(row.superseded_by) } : {},
1883
- ...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {}
2089
+ ...row.superseded_at != null ? { superseded_at: Number(row.superseded_at) } : {},
2090
+ // Source pointer (specs/source-pointers): key appears only when non-null,
2091
+ // same temporal-fields pattern. Tolerant read: a malformed stored value
2092
+ // reads as null without throwing (test 1).
2093
+ ...sourcePointer ? { source_pointer: sourcePointer } : {}
1884
2094
  };
2095
+ return mapped;
1885
2096
  }
1886
2097
  function normalizeEmbeddingBlobValue(blob) {
1887
2098
  if (blob instanceof Uint8Array) return blob;
@@ -1996,7 +2207,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
1996
2207
  const existingRow = await executor.getFirstAsync(
1997
2208
  `SELECT id, entity_id, lifecycle_status, stale_after, generated_by,
1998
2209
  okf_sources, okf_verified, okf_usage_window,
1999
- last_verified_at, last_verified_by
2210
+ last_verified_at, last_verified_by, source_pointer
2000
2211
  FROM ${this.prefix}entries WHERE id = ?`,
2001
2212
  [fact.id]
2002
2213
  );
@@ -2010,8 +2221,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2010
2221
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
2011
2222
  deleted_at, embedding_blob, embedding, okf_type,
2012
2223
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
2013
- okf_sources, okf_verified, okf_usage_window
2014
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2224
+ okf_sources, okf_verified, okf_usage_window, source_pointer
2225
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2015
2226
  ON CONFLICT(id) DO UPDATE SET
2016
2227
  title = excluded.title,
2017
2228
  body = excluded.body,
@@ -2059,7 +2270,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2059
2270
  fact.last_verified_by ?? null,
2060
2271
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
2061
2272
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
2062
- fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
2273
+ fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
2274
+ serializeSourcePointer(fact.source_pointer)
2063
2275
  ]
2064
2276
  );
2065
2277
  if (result.changes === 0) {
@@ -2082,7 +2294,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2082
2294
  okf_verified: parseJsonArray(existingRow.okf_verified, []),
2083
2295
  okf_usage_window: parseJsonObject(existingRow.okf_usage_window),
2084
2296
  last_verified_at: existingRow.last_verified_at != null ? Number(existingRow.last_verified_at) : null,
2085
- last_verified_by: existingRow.last_verified_by ?? null
2297
+ last_verified_by: existingRow.last_verified_by ?? null,
2298
+ source_pointer: parseStoredSourcePointer(existingRow.source_pointer)
2086
2299
  } : null;
2087
2300
  await this.outbox.push({
2088
2301
  entityId: fact.entity_id,
@@ -2142,7 +2355,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2142
2355
  const rows = await executor.getAllAsync(sql, args);
2143
2356
  return rows.map((row) => row.id);
2144
2357
  }
2145
- async upsertForImport(fact, tx) {
2358
+ async upsertForImport(fact, tx, sourcePointerPresent = false) {
2146
2359
  const executor = this.getExecutor(tx);
2147
2360
  const tagsJson = JSON.stringify(fact.tags);
2148
2361
  const embeddingBlob = this.normalizeEmbeddingBlob(fact.embedding_blob);
@@ -2152,8 +2365,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2152
2365
  source_hash, source_ref, created_at, updated_at, last_accessed_at, access_count,
2153
2366
  deleted_at, embedding_blob, embedding, okf_type,
2154
2367
  lifecycle_status, stale_after, generated_by, last_verified_at, last_verified_by,
2155
- okf_sources, okf_verified, okf_usage_window
2156
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2368
+ okf_sources, okf_verified, okf_usage_window, source_pointer
2369
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2157
2370
  ON CONFLICT(id) DO UPDATE SET
2158
2371
  entity_id = excluded.entity_id,
2159
2372
  title = excluded.title,
@@ -2181,7 +2394,8 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2181
2394
  last_verified_by = excluded.last_verified_by,
2182
2395
  okf_sources = excluded.okf_sources,
2183
2396
  okf_verified = excluded.okf_verified,
2184
- okf_usage_window = excluded.okf_usage_window`,
2397
+ okf_usage_window = excluded.okf_usage_window,
2398
+ source_pointer = CASE WHEN ? THEN excluded.source_pointer ELSE source_pointer END`,
2185
2399
  [
2186
2400
  fact.id,
2187
2401
  fact.entity_id,
@@ -2208,7 +2422,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2208
2422
  fact.last_verified_by ?? null,
2209
2423
  fact.okf_sources ? JSON.stringify(fact.okf_sources) : null,
2210
2424
  fact.okf_verified ? JSON.stringify(fact.okf_verified) : null,
2211
- fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null
2425
+ fact.okf_usage_window ? JSON.stringify(fact.okf_usage_window) : null,
2426
+ serializeSourcePointer(fact.source_pointer),
2427
+ // The presence flag binds to the SET clause's CASE, AFTER the INSERT
2428
+ // values above.
2429
+ sourcePointerPresent ? 1 : 0
2212
2430
  ]
2213
2431
  );
2214
2432
  return result;
@@ -2944,20 +3162,26 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2944
3162
  FROM ${this.prefix}entries
2945
3163
  WHERE entity_id = ? AND deleted_at IS NULL AND source_ref IS NOT NULL
2946
3164
  )
2947
- SELECT source_ref,
2948
- source_hash AS source_hash,
2949
- fact_count AS fact_count,
2950
- 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
2951
3171
  FROM ranked
2952
- WHERE rn = 1
2953
- ORDER BY source_ref COLLATE BINARY`,
2954
- [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]
2955
3177
  );
2956
3178
  return rows.map((r) => ({
2957
3179
  sourceRef: r.source_ref,
2958
3180
  sourceHash: r.source_hash,
2959
3181
  factCount: Number(r.fact_count),
2960
- 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 }
2961
3185
  }));
2962
3186
  }
2963
3187
  /**
@@ -4609,6 +4833,10 @@ var UnavailableIndexStrategy = class {
4609
4833
  }
4610
4834
  async drain(_opts) {
4611
4835
  }
4836
+ /** Degraded like everything else: no passages, no throw (spec source-store section 7). */
4837
+ async searchPassages() {
4838
+ return [];
4839
+ }
4612
4840
  };
4613
4841
 
4614
4842
  // src/services/SearchService.ts
@@ -4830,6 +5058,36 @@ var _SearchService = class _SearchService {
4830
5058
  const results = finiteResults(await this.indexStrategy.search(query, { entityIds, limit }));
4831
5059
  return results.sort((a, b) => this._compareSearchResults(a, b)).slice(0, limit);
4832
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
+ }
4833
5091
  /**
4834
5092
  * Pre-fetches keyword scores for candidate hydration, used during hybrid weighting.
4835
5093
  */
@@ -4952,195 +5210,360 @@ var SearchService = _SearchService;
4952
5210
  function finiteResults(results) {
4953
5211
  return results.every((r) => Number.isFinite(r.score)) ? results : results.filter((r) => Number.isFinite(r.score));
4954
5212
  }
4955
- var MiniSearchIndexStrategy = class {
4956
- constructor() {
4957
- /**
4958
- * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
4959
- * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
4960
- * not see this map; it only sees `hasIndexedEntity`. The previous
4961
- * `miniSearchEntryIdsByEntity` lived on `SearchService`.
4962
- */
4963
- this.entryIdsByEntity = /* @__PURE__ */ new Map();
4964
- /**
4965
- * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
4966
- * decide which ids are owned by `entityId` (the only safe membership test
4967
- * — a rebuild that failed between its discard pass and the set replacement
4968
- * can leave the forward set claiming ids the MiniSearch instance does not
4969
- * hold). The pre-extraction `syncEntries` deleted from one set per id, not
4970
- * from every entity's set.
4971
- */
4972
- this.entityIdById = /* @__PURE__ */ new Map();
4973
- 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;
4974
5247
  }
4975
- /**
4976
- * Build a fresh MiniSearch instance with the project's index options.
4977
- * Called from the constructor and from `replaceAll`. We do not use
4978
- * `removeAll()` on an existing instance because that empties the index but
4979
- * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
4980
- * `syncEntries`' conditional vacuum early after a clear.
4981
- */
4982
- createIndex() {
4983
- return new MiniSearch__default.default({
4984
- fields: ["title", "body", "tags"],
4985
- storeFields: ["entity_id"],
4986
- // Vacuuming is driven explicitly at the end of each serialized rebuild
4987
- // (see SearchService.syncEntries). Auto-vacuum fires on its own
4988
- // schedule, asynchronously with respect to the caller, and traversing
4989
- // the tree mid-rebuild is what threw the uncaught TypeError in
4990
- // MiniSearch.performVacuuming (#64).
4991
- autoVacuum: false,
4992
- searchOptions: {
4993
- boost: { title: 2 },
4994
- fuzzy: 0.2,
4995
- 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;
4996
5384
  }
4997
- });
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);
4998
5392
  }
4999
- /**
5000
- * Incremental sync. Removes only ids currently tracked under `entityId`
5001
- * (other entities' docs are untouched), then upserts `documents` by id.
5002
- * The same id appearing in both `ids` and `documents` is discarded first
5003
- * so the upsert does not throw on a duplicate id.
5004
- *
5005
- * Every document must carry `entityId` as its `entity_id`; a mismatch is
5006
- * rejected before the write mutates anything. A tracking-only call
5007
- * (`replace(entityId, [], [])`) registers the entity as indexed, matching
5008
- * the interface contract.
5009
- *
5010
- * Atomicity: never awaits between the discard pass and `addDocuments`, so
5011
- * a concurrent `search()` sees the index wholly before or wholly after,
5012
- * never half-updated. This is the precondition the pre-extraction
5013
- * `syncEntries` kept with its "no await from here to `addAll`" comment.
5014
- */
5015
- async replace(entityId, ids, documents) {
5016
- assertOwnedBy(entityId, documents);
5017
- this.discardIds(ids, entityId);
5018
- if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
5019
- this.addDocuments(documents);
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 };
5020
5428
  }
5021
- /**
5022
- * Per-entity rebuild. Removes every id tracked under `entityId` (with the
5023
- * `index.has(id)` guard so a stale tracking set cannot make `discard()`
5024
- * throw), then writes `documents`. The entity stays registered as
5025
- * indexed — even when `documents` is empty — so the next `syncEntries`
5026
- * call can take the fast path. Every document must belong to `entityId`.
5027
- */
5028
- async replaceEntity(entityId, documents) {
5029
- assertOwnedBy(entityId, documents);
5030
- const previous = this.entryIdsByEntity.get(entityId);
5031
- if (previous) this.discardIds([...previous]);
5032
- this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
5033
- this.addDocuments(documents);
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
+ );
5034
5461
  }
5035
- /**
5036
- * Global rebuild / clear. Replaces the MiniSearch instance and clears both
5037
- * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
5038
- * `SearchService.clearAll()` calls `replaceAll([])`.
5039
- */
5040
- async replaceAll(documents) {
5041
- this.index = this.createIndex();
5042
- this.entryIdsByEntity.clear();
5043
- this.entityIdById.clear();
5044
- this.addDocuments(documents);
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;
5045
5477
  }
5046
- /**
5047
- * Best-match-first search over the documents whose `entity_id` is in
5048
- * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
5049
- * uses this to over-fetch candidates before the `limit` cap). Scores are
5050
- * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
5051
- * any scaling, not the strategy.
5052
- */
5053
- async search(query, options) {
5054
- if (options.entityIds.length === 0) return [];
5055
- const entityIdSet = new Set(options.entityIds);
5056
- const limit = options.preFilterLimit ?? options.limit;
5057
- const raw = this.index.search(query, {
5058
- filter: (r) => entityIdSet.has(r.entity_id),
5059
- combineWith: "OR"
5060
- });
5061
- raw.sort((a, b) => {
5062
- const scoreDiff = b.score - a.score;
5063
- if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
5064
- return a.id.localeCompare(b.id);
5065
- });
5066
- return raw.slice(0, limit).map((r) => ({
5067
- id: r.id,
5068
- entity_id: r.entity_id,
5069
- score: r.score
5070
- }));
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
+ };
5071
5484
  }
5072
- /**
5073
- * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
5074
- * un-vacuumed discard inverts the relative scores of term-sharing
5075
- * documents at any index size. `SearchService.syncEntries` calls this
5076
- * after a discard-bearing turn. No-op when `dirtCount === 0`.
5077
- */
5078
- async vacuum() {
5079
- if (this.index.dirtCount > 0) {
5080
- await this.index.vacuum();
5081
- }
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 };
5082
5493
  }
5083
- /**
5084
- * `true` when `entityId` has been indexed at least once under the current
5085
- * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
5086
- * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
5087
- */
5088
- hasIndexedEntity(entityId) {
5089
- return this.entryIdsByEntity.has(entityId);
5090
- }
5091
- /**
5092
- * Add `documents` to the MiniSearch instance and register them in
5093
- * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
5094
- * during `add`, so each doc is copied first. `add` throws on an id the
5095
- * index already holds — `replace` and `replaceEntity` discard first for
5096
- * that reason.
5097
- *
5098
- * Adds and registers one document at a time: if a duplicate id throws
5099
- * part-way through, every document already in the index is tracked, so
5100
- * the next rebuild can discard it instead of failing on it again. This is
5101
- * the precondition the per-turn recovery path relies on (#258 review).
5102
- */
5103
- addDocuments(documents) {
5104
- for (const d of documents) {
5105
- const doc = { ...d };
5106
- this.index.add(doc);
5107
- const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
5108
- set.add(doc.id);
5109
- this.entryIdsByEntity.set(doc.entity_id, set);
5110
- this.entityIdById.set(doc.id, doc.entity_id);
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);
5111
5527
  }
5112
5528
  }
5113
- /**
5114
- * Discard `ids` from the MiniSearch instance and from both id maps, but
5115
- * only for ids currently owned by `entityId` (the second argument). When
5116
- * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
5117
- * path), every id is discarded regardless of owning entity.
5118
- *
5119
- * `index.has(id)` is the membership test of record: a rebuild that failed
5120
- * between its own discard pass and the set replacement can leave the
5121
- * tracking set claiming ids the index no longer holds — `discard()` throws
5122
- * on those, so we guard.
5123
- */
5124
- discardIds(ids, entityId) {
5125
- for (const id of ids) {
5126
- const owning = this.entityIdById.get(id);
5127
- if (owning === void 0) continue;
5128
- if (entityId !== void 0 && owning !== entityId) continue;
5129
- if (this.index.has(id)) this.index.discard(id);
5130
- this.entryIdsByEntity.get(owning)?.delete(id);
5131
- this.entityIdById.delete(id);
5132
- }
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
+ };
5133
5546
  }
5134
- };
5135
- function assertOwnedBy(entityId, documents) {
5136
- for (const doc of documents) {
5137
- if (doc.entity_id !== entityId) {
5138
- throw new Error(
5139
- `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
5140
- );
5141
- }
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
+ }));
5142
5565
  }
5143
- }
5566
+ };
5144
5567
 
5145
5568
  // src/utils/monotonicNow.ts
5146
5569
  var monotonicNow = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
@@ -5158,12 +5581,46 @@ function buildFtsMatchQuery(query) {
5158
5581
  }
5159
5582
 
5160
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)
5612
+ });
5613
+ }
5614
+ return out;
5615
+ }
5161
5616
  var Fts5IndexStrategy = class {
5162
5617
  constructor(db, prefix, metadataRepo, budgetMs = DEFAULT_SETUP_BUDGET_MS) {
5163
5618
  this.db = db;
5164
5619
  this.prefix = prefix;
5165
5620
  this.metadataRepo = metadataRepo;
5166
5621
  this.budgetMs = budgetMs;
5622
+ /** Set when passage-index init failed; passage drain and search become no-ops. */
5623
+ this.passagesDisabled = false;
5167
5624
  }
5168
5625
  /**
5169
5626
  * Resolves the index state (spec #280 Change 3 transition table). Every
@@ -5171,6 +5628,120 @@ var Fts5IndexStrategy = class {
5171
5628
  * failure leaves zero mutation (Change 4 ordering).
5172
5629
  */
5173
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
+ }
5638
+ }
5639
+ /**
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).
5643
+ */
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
+ });
5659
+ }
5660
+ /**
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.
5666
+ */
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;
5717
+ }
5718
+ }
5719
+ /**
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).
5723
+ */
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);
5743
+ }
5744
+ async initEntries(opts) {
5174
5745
  try {
5175
5746
  await this.initOnce(opts);
5176
5747
  } catch (err) {
@@ -5579,75 +6150,350 @@ var Fts5IndexStrategy = class {
5579
6150
  args
5580
6151
  );
5581
6152
  }
5582
- /** One INSERT pair per document: a throw part-way rolls back the whole transaction. */
5583
- async insertDocs(tx, documents) {
5584
- const p = this.prefix;
5585
- for (const d of documents) {
5586
- const { lastInsertRowId } = await tx.runAsync(
5587
- `INSERT INTO ${p}fts_map (id, entity_id) VALUES (?, ?)`,
5588
- [d.id, d.entity_id]
5589
- );
5590
- await tx.runAsync(
5591
- `INSERT INTO ${p}entries_fts (rowid, id, entity_id, title, body, tags) VALUES (?, ?, ?, ?, ?, ?)`,
5592
- [lastInsertRowId, d.id, d.entity_id, d.title, d.body, d.tags]
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
+ });
6374
+ }
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]
5593
6417
  );
6418
+ for (const row of rows) live.add(row.id);
5594
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);
5595
6427
  }
5596
- /** The init probes' schema facts in one sqlite_master read (#284 review): FTS tables with their DDL, and the triggers. */
5597
- async readSchema() {
5598
- const p = this.prefix;
5599
- const triggers = fts5TriggerNames(p);
5600
- const names = [`${p}entries_fts`, `${p}fts_map`, `${p}fts_pending`, ...triggers];
5601
- const rows = await this.db.getAllAsync(
5602
- `SELECT type, name, sql FROM sqlite_master WHERE name IN (${names.map(() => "?").join(", ")})`,
5603
- names
5604
- );
5605
- const tables = new Map(rows.filter((r) => r.type === "table").map((r) => [r.name, r.sql]));
5606
- const present = new Set(rows.filter((r) => r.type === "trigger").map((r) => r.name));
5607
- 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
+ }
5608
6438
  }
5609
- };
5610
- var FtsOnlyStatementError = class extends Error {
5611
- constructor(cause) {
5612
- super("FTS-only statement failed");
5613
- 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);
5614
6446
  }
5615
- };
5616
- function unwrapFtsOnly(err) {
5617
- try {
5618
- if (err instanceof FtsOnlyStatementError) return { cause: err.ftsOnlyCause, ftsOnly: true };
5619
- } 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
+ }
5620
6468
  }
5621
- return { cause: err, ftsOnly: false };
5622
- }
5623
- function safeSqliteCode(err) {
5624
- try {
5625
- const code = extractSqliteCode(err);
5626
- if (code !== void 0) return code;
5627
- const lifted = err?.sqliteErrorCode;
5628
- return typeof lifted === "string" ? lifted : void 0;
5629
- } catch {
5630
- 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
+ }
5631
6489
  }
5632
- }
5633
- var TRANSIENT_OR_TX_FATAL = ["SQLITE_BUSY", "SQLITE_LOCKED", "SQLITE_FULL", "SQLITE_IOERR", "SQLITE_NOMEM", "SQLITE_INTERRUPT", "SQLITE_ABORT", "SQLITE_READONLY"];
5634
- function isTransientOrTxFatal(err) {
5635
- const code = safeSqliteCode(err);
5636
- return code !== void 0 && TRANSIENT_OR_TX_FATAL.some((c) => code === c || code.startsWith(`${c}_`));
5637
- }
5638
- function ftsCorruptionClass(err) {
5639
- const code = safeSqliteCode(err);
5640
- if (code === "SQLITE_CORRUPT_VTAB") return "vtab";
5641
- if (code?.startsWith("SQLITE_CORRUPT")) return "corrupt";
5642
- return null;
5643
- }
5644
- function isSqliteError(err) {
5645
- return safeSqliteCode(err) !== void 0;
5646
- }
5647
- function assertEntity(entityId, documents) {
5648
- for (const d of documents) {
5649
- if (d.entity_id !== entityId) {
5650
- 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
+ );
5651
6497
  }
5652
6498
  }
5653
6499
  }
@@ -5689,6 +6535,22 @@ async function probeFts5(db, prefix) {
5689
6535
  }
5690
6536
  }
5691
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
+ }
5692
6554
  const hasLedger = await metadataRepo.tableExists(`${prefix}fts_pending`);
5693
6555
  const state = await metadataRepo.getMeta(FTS5_STATE_KEY);
5694
6556
  if (!hasLedger && state !== "live") return;
@@ -5767,7 +6629,8 @@ var JobManager = class {
5767
6629
  reembed: (id) => this._reembedKey(id),
5768
6630
  import: (id) => this._importKey(id),
5769
6631
  forget: (id) => this._forgetKey(id),
5770
- ontologyBackfill: (id) => this._ontologyBackfillKey(id)
6632
+ ontologyBackfill: (id) => this._ontologyBackfillKey(id),
6633
+ store: (id) => this._storeKey(id)
5771
6634
  };
5772
6635
  }
5773
6636
  _hashLockKey(entityId, sourceHash) {
@@ -5836,6 +6699,9 @@ var JobManager = class {
5836
6699
  _librarianKey(entityId) {
5837
6700
  return `${this.prefix}:${entityId}:librarian`;
5838
6701
  }
6702
+ _storeKey(entityId) {
6703
+ return `${this.prefix}:${entityId}:store`;
6704
+ }
5839
6705
  _healKey(entityId) {
5840
6706
  return `${this.prefix}:${entityId}:heal`;
5841
6707
  }
@@ -5864,6 +6730,9 @@ var JobManager = class {
5864
6730
  _isImportActiveFor(entityId) {
5865
6731
  return this.activeMaintenanceJobs.has(this._importKey(entityId)) || this.activeMaintenanceJobs.has(this._globalImportKey());
5866
6732
  }
6733
+ _isStoreActiveFor(entityId) {
6734
+ return this.activeMaintenanceJobs.has(this._storeKey(entityId));
6735
+ }
5867
6736
  _isForgetActiveFor(entityId) {
5868
6737
  return this.activeMaintenanceJobs.has(this._forgetKey(entityId));
5869
6738
  }
@@ -5913,6 +6782,7 @@ var JobManager = class {
5913
6782
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
5914
6783
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
5915
6784
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6785
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
5916
6786
  break;
5917
6787
  case "librarian":
5918
6788
  case "heal":
@@ -5923,6 +6793,7 @@ var JobManager = class {
5923
6793
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
5924
6794
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
5925
6795
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6796
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
5926
6797
  break;
5927
6798
  }
5928
6799
  case "reembed":
@@ -5935,6 +6806,7 @@ var JobManager = class {
5935
6806
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
5936
6807
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
5937
6808
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6809
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
5938
6810
  break;
5939
6811
  case "global_reembed":
5940
6812
  if (this.activeMaintenanceJobs.has(this._globalReembedKey())) blockingOperation = "reembed";
@@ -5946,6 +6818,7 @@ var JobManager = class {
5946
6818
  else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
5947
6819
  else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
5948
6820
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
6821
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
5949
6822
  break;
5950
6823
  case "import":
5951
6824
  case "forget": {
@@ -5959,10 +6832,23 @@ var JobManager = class {
5959
6832
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
5960
6833
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
5961
6834
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6835
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
5962
6836
  break;
5963
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;
5964
6849
  case "global_import":
5965
6850
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) blockingOperation = "import";
6851
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
5966
6852
  break;
5967
6853
  case "ingest": {
5968
6854
  const sourceKey = sourceRef ?? "";
@@ -5971,6 +6857,7 @@ var JobManager = class {
5971
6857
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
5972
6858
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
5973
6859
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6860
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
5974
6861
  break;
5975
6862
  }
5976
6863
  }
@@ -6013,22 +6900,24 @@ var JobManager = class {
6013
6900
  case "librarian":
6014
6901
  case "heal":
6015
6902
  case "ontologyBackfill":
6016
- 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);
6017
6904
  case "prune":
6018
- 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);
6019
6906
  case "reembed":
6020
- 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);
6021
6908
  case "global_reembed":
6022
- 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");
6023
6910
  case "import":
6024
6911
  case "forget": {
6025
6912
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
6026
- 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);
6027
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);
6028
6917
  case "global_import":
6029
- return this.activeMaintenanceJobs.has(this._globalImportKey());
6918
+ return this.activeMaintenanceJobs.has(this._globalImportKey()) || this._isAnyMaintenanceActiveWithSuffix(":store");
6030
6919
  case "ingest":
6031
- 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);
6032
6921
  default:
6033
6922
  return false;
6034
6923
  }
@@ -6093,6 +6982,7 @@ var JobManager = class {
6093
6982
  if (this._isReembedActive(entityId)) throw new WikiBusyError("reembed", entityId);
6094
6983
  if (this._isIngestActiveFor(entityId)) throw new WikiBusyError("ingest", entityId);
6095
6984
  if (this._isForgetActiveFor(entityId)) throw new WikiBusyError("forget", entityId);
6985
+ if (this._isStoreActiveFor(entityId)) throw new WikiBusyError("store", entityId);
6096
6986
  }
6097
6987
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) throw new WikiBusyError("import", "*");
6098
6988
  this.activeMaintenanceJobs.add(this._globalImportKey());
@@ -6553,6 +7443,10 @@ ${JSON.stringify(facts, null, 2)}`
6553
7443
  systemPrompt: this.appendGrounding(this.appendGuidance(this.appendOntology(OPS_EXTRACT_SYSTEM_PROMPT, ontologyContext), guidance), "librarian"),
6554
7444
  userPrompt: `Events:
6555
7445
  ${lines.join("\n")}`,
7446
+ // Corpus entries are one-per-batch-event in batch order (summaries are
7447
+ // TEXT NOT NULL, so the filter inside buildGroundingCorpus drops
7448
+ // nothing): extract.ts stores a candidate's `sourcePartIndex` as the
7449
+ // batch index and buildSourcePointer reads the quote back by it.
6556
7450
  ...grounding ? { groundingCorpus: buildGroundingCorpus(events.map((l) => l.event.summary)) } : {}
6557
7451
  };
6558
7452
  }
@@ -8258,9 +9152,20 @@ var runLegacyLibrarianPass = async (deps, ctx) => {
8258
9152
  access_count: 0,
8259
9153
  deleted_at: null,
8260
9154
  okf_type: normalized.okf_type,
9155
+ // Legacy writes no pointer (spec §Legacy path): the column stays null
9156
+ // on every legacy fact, and the legacy prompt keeps its exact text.
9157
+ source_pointer: null,
8261
9158
  ...grounding?.trust
8262
9159
  };
8263
9160
  await deps.entryRepo.upsert(factObj, tx);
9161
+ const volunteeredSourceEvent = facts[validFactItemIndexes[k]]?.source_event;
9162
+ if (volunteeredSourceEvent !== void 0 && volunteeredSourceEvent !== null) {
9163
+ diagBuffer.push({
9164
+ ...diagBase,
9165
+ code: "source_pointer_unresolved",
9166
+ detail: { factId: id, itemIndex: validFactItemIndexes[k], reason: "unsupported_strategy" }
9167
+ });
9168
+ }
8264
9169
  insertedFacts.push({ id, entity_id: entityId, title: fact.title, body: fact.body, tags: JSON.stringify(fact.tags) });
8265
9170
  factsForDedupe.push(factObj);
8266
9171
  titleIndex.set(normalizeTitleKey(fact.title), { id, okf_type: normalized.okf_type });
@@ -8374,9 +9279,23 @@ async function runExtract(deps, ctx, batch) {
8374
9279
  return;
8375
9280
  }
8376
9281
  const r = raw;
8377
- const sourceLabel = typeof r.source_event === "string" && byLabel.has(r.source_event) ? r.source_event : null;
9282
+ let sourceEventId = null;
9283
+ let sourcePartIndex = null;
9284
+ let pointerUnresolved;
9285
+ const rawSourceEvent = r.source_event;
9286
+ if (rawSourceEvent === void 0 || rawSourceEvent === null) {
9287
+ pointerUnresolved = "missing";
9288
+ } else if (typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent)) {
9289
+ const labeled = byLabel.get(rawSourceEvent);
9290
+ sourceEventId = labeled.event.id;
9291
+ sourcePartIndex = batch.findIndex((b) => b.label === rawSourceEvent);
9292
+ pointerUnresolved = null;
9293
+ } else {
9294
+ pointerUnresolved = "unknown_label";
9295
+ }
9296
+ const sourceLabel = typeof rawSourceEvent === "string" && byLabel.has(rawSourceEvent) ? rawSourceEvent : null;
8378
9297
  const validFrom = parseValidFrom(r.valid_from) ?? (sourceLabel ? byLabel.get(sourceLabel).at : defaultValidFrom);
8379
- candidates.push({ index, fact, sourceLabel, validFrom });
9298
+ candidates.push({ index, fact, sourceLabel, sourceEventId, sourcePartIndex, pointerUnresolved, validFrom });
8380
9299
  });
8381
9300
  const tasks = [];
8382
9301
  (Array.isArray(parsed.tasks) ? parsed.tasks : []).forEach((raw, index) => {
@@ -8653,6 +9572,17 @@ var TemporalService = class {
8653
9572
  };
8654
9573
 
8655
9574
  // src/services/librarian/ops/apply.ts
9575
+ function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
9576
+ if (candidate.sourceEventId === null) return null;
9577
+ let quote = null;
9578
+ if (groundingOn && verdict?.status === "grounded" && candidate.sourcePartIndex !== null) {
9579
+ const part = groundingCorpus?.[candidate.sourcePartIndex];
9580
+ if (part !== void 0) {
9581
+ quote = verdict.retained.find((q) => part.includes(q)) ?? null;
9582
+ }
9583
+ }
9584
+ return { event_id: candidate.sourceEventId, ref: null, quote, position: null };
9585
+ }
8656
9586
  async function applyOps(deps, ctx, input) {
8657
9587
  const { entityId, trigger } = ctx;
8658
9588
  const diagBase = { entityId, operation: "librarian", trigger };
@@ -8681,7 +9611,8 @@ async function applyOps(deps, ctx, input) {
8681
9611
  const drops = [];
8682
9612
  const normalized = deps.ontologyService?.validateAndNormalizeFact(fact, manifest, { strict: false, drops }) ?? { okf_type: null, edges: [] };
8683
9613
  for (const d of drops) input.diagnostics.push(edgeDropDiagnostic(d, { ...diagBase, factId: id }));
8684
- const g2 = grounding ? groundingOutcome(checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding), now) : null;
9614
+ const gVerdict = grounding ? checkGrounding(fact.evidence, input.groundingCorpus ?? [], grounding) : null;
9615
+ const g2 = gVerdict ? groundingOutcome(gVerdict, now) : null;
8685
9616
  if (g2?.diagnostic) {
8686
9617
  input.diagnostics.push({
8687
9618
  ...diagBase,
@@ -8689,6 +9620,7 @@ async function applyOps(deps, ctx, input) {
8689
9620
  detail: { factId: id, itemIndex: g.candidate.index, reason: g2.diagnostic.reason }
8690
9621
  });
8691
9622
  }
9623
+ const pointer = buildSourcePointer(g.candidate, gVerdict, grounding !== void 0 && grounding !== null, input.groundingCorpus);
8692
9624
  const row = {
8693
9625
  id,
8694
9626
  entity_id: entityId,
@@ -8705,11 +9637,19 @@ async function applyOps(deps, ctx, input) {
8705
9637
  access_count: 0,
8706
9638
  deleted_at: null,
8707
9639
  okf_type: normalized.okf_type,
9640
+ source_pointer: pointer,
8708
9641
  ...g2?.trust,
8709
9642
  ...draft ? { lifecycle_status: "draft" } : {}
8710
9643
  };
8711
9644
  await deps.entryRepo.upsert(row, tx);
8712
9645
  await deps.entryRepo.setTemporal(id, entityId, { valid_from: validFrom }, tx);
9646
+ if (g.candidate.pointerUnresolved !== null) {
9647
+ input.diagnostics.push({
9648
+ ...diagBase,
9649
+ code: "source_pointer_unresolved",
9650
+ detail: { factId: id, itemIndex: g.candidate.index, reason: g.candidate.pointerUnresolved }
9651
+ });
9652
+ }
8713
9653
  titleIndex.set(normalizeTitleKey(title), { id, okf_type: normalized.okf_type });
8714
9654
  if (normalized.edges.length > 0) pendingEdges.push({ sourceId: id, sourceType: normalized.okf_type, edges: normalized.edges });
8715
9655
  const textChanged = title !== fact.title || body !== fact.body;
@@ -9262,6 +10202,10 @@ var MaintenanceService = class {
9262
10202
  if (await this.sourceRefIndexPresent(tx)) {
9263
10203
  await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
9264
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
+ }
9265
10209
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
9266
10210
  if (params.includeEvents) {
9267
10211
  deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
@@ -9285,6 +10229,16 @@ var MaintenanceService = class {
9285
10229
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
9286
10230
  if (entryId) deletedEntryIds.push(entryId);
9287
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
+ }
9288
10242
  if (sourceRef || sourceHash) {
9289
10243
  for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
9290
10244
  }
@@ -9401,6 +10355,10 @@ var MaintenanceService = class {
9401
10355
  if (version < 9) return false;
9402
10356
  throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
9403
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
+ }
9404
10362
  /**
9405
10363
  * Read-only dry-run preview of {@link forget}. Returns the same shape as a
9406
10364
  * real call would, without acquiring the lock, opening a transaction, staging
@@ -9733,6 +10691,7 @@ var MaintenanceService = class {
9733
10691
  source_type: "librarian_inferred",
9734
10692
  source_hash: null,
9735
10693
  source_ref: null,
10694
+ source_pointer: null,
9736
10695
  created_at: now,
9737
10696
  updated_at: now,
9738
10697
  last_accessed_at: null,
@@ -10447,7 +11406,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
10447
11406
  var IMPORT_TITLE_MAX = 500;
10448
11407
  var IMPORT_BODY_MAX = 8e3;
10449
11408
  var ImportExportService = class {
10450
- 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) {
10451
11410
  this.db = db;
10452
11411
  this.entryRepo = entryRepo;
10453
11412
  this.taskRepo = taskRepo;
@@ -10459,6 +11418,7 @@ var ImportExportService = class {
10459
11418
  this.embeddingService = embeddingService;
10460
11419
  this.options = options;
10461
11420
  this.vectorRemoval = vectorRemoval;
11421
+ this.prefix = prefix;
10462
11422
  }
10463
11423
  async exportDump(entityIds) {
10464
11424
  let ids;
@@ -10466,6 +11426,13 @@ var ImportExportService = class {
10466
11426
  ids = Array.from(new Set(entityIds));
10467
11427
  } else {
10468
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
+ }
10469
11436
  }
10470
11437
  const entities = {};
10471
11438
  const BATCH = 3;
@@ -10473,10 +11440,11 @@ var ImportExportService = class {
10473
11440
  const batch = ids.slice(i, i + BATCH);
10474
11441
  const batchResults = await Promise.all(
10475
11442
  batch.map(
10476
- async (id) => [
10477
- id,
10478
- await this.getFullBundle(id, { includeBlobs: true })
10479
- ]
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
+ }
10480
11448
  )
10481
11449
  );
10482
11450
  for (const [id, bundle] of batchResults) {
@@ -10487,16 +11455,96 @@ var ImportExportService = class {
10487
11455
  }
10488
11456
  async importDump(dump, opts) {
10489
11457
  const merge = opts?.merge ?? false;
11458
+ const skippedSources = [];
10490
11459
  const entityIds = Object.keys(dump.entities);
10491
11460
  this.jobManager.acquireImportLocks(entityIds);
10492
11461
  try {
10493
11462
  await this.assertNoLegacySourceTypes();
10494
11463
  for (const [entityId, bundle] of Object.entries(dump.entities)) {
10495
- await this.doImportEntity(entityId, bundle, merge);
11464
+ skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
10496
11465
  }
10497
11466
  } finally {
10498
11467
  this.jobManager.releaseImportLocks(entityIds);
10499
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
+ }
10500
11548
  }
10501
11549
  async getFullBundle(entityId, opts) {
10502
11550
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
@@ -10535,6 +11583,8 @@ var ImportExportService = class {
10535
11583
  }
10536
11584
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
10537
11585
  async doImportEntity(entityId, bundle, merge) {
11586
+ const skippedSources = [];
11587
+ const refusalDiagnostics = [];
10538
11588
  const upsertedFactIds = /* @__PURE__ */ new Set();
10539
11589
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
10540
11590
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
@@ -10652,6 +11702,19 @@ var ImportExportService = class {
10652
11702
  );
10653
11703
  }
10654
11704
  }
11705
+ const hasSourcePointerKey = fact["source_pointer"] !== void 0;
11706
+ const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
11707
+ const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
11708
+ if (pointerValidated === void 0) {
11709
+ emitDiagnostic(this.options, {
11710
+ code: "source_pointer_invalid",
11711
+ operation: "importDump",
11712
+ trigger: "call",
11713
+ entityId,
11714
+ detail: { factId: fact.id }
11715
+ });
11716
+ }
11717
+ const sourcePointer = pointerValidated === void 0 ? null : pointerValidated;
10655
11718
  const factObj = {
10656
11719
  id: fact.id,
10657
11720
  entity_id: entityId,
@@ -10669,6 +11732,7 @@ var ImportExportService = class {
10669
11732
  deleted_at: fact.deleted_at,
10670
11733
  embedding_blob: blobData ?? void 0,
10671
11734
  okf_type: fact.okf_type ?? null,
11735
+ source_pointer: sourcePointer,
10672
11736
  // OKF v0.2 — forwarded as-is; parseOkfBundle / the caller is responsible for
10673
11737
  // populating these per spec, importDump does not derive or validate them.
10674
11738
  lifecycle_status: fact.lifecycle_status ?? "stable",
@@ -10686,7 +11750,7 @@ var ImportExportService = class {
10686
11750
  return { last_verified_at: latest?.at ?? null, last_verified_by: latest?.by ?? null };
10687
11751
  })()
10688
11752
  };
10689
- await this.entryRepo.upsertForImport(factObj, tx);
11753
+ await this.entryRepo.upsertForImport(factObj, tx, hasSourcePointerKey);
10690
11754
  await this.entryRepo.setTemporal(fact.id, entityId, {
10691
11755
  valid_from: fact.valid_from ?? null,
10692
11756
  valid_to: fact.valid_to ?? null,
@@ -10798,7 +11862,9 @@ var ImportExportService = class {
10798
11862
  tx
10799
11863
  );
10800
11864
  }
11865
+ await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
10801
11866
  });
11867
+ for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
10802
11868
  if (clampedEvents > 0) {
10803
11869
  emitDiagnostic(this.options, {
10804
11870
  code: "event_created_at_clamped",
@@ -10966,6 +12032,7 @@ var ImportExportService = class {
10966
12032
  } finally {
10967
12033
  this.searchService.evictCache(entityId);
10968
12034
  }
12035
+ return skippedSources;
10969
12036
  }
10970
12037
  _warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
10971
12038
  console.warn(
@@ -11490,6 +12557,63 @@ function packFactsByBudget(items, budget, scores) {
11490
12557
 
11491
12558
  // src/services/RetrievalService.ts
11492
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
+ }
11493
12617
  var RetrievalService = class {
11494
12618
  constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
11495
12619
  this.options = options;
@@ -11504,8 +12628,10 @@ var RetrievalService = class {
11504
12628
  const entityIds = normalizeEntityIds(entityId);
11505
12629
  const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
11506
12630
  const exposeMetadata = shouldExposeReadMetadata(entityId);
12631
+ if (options?.sources) assertSourcesQuery(options.sources);
11507
12632
  if (entityIds.length === 0) {
11508
12633
  const empty = { facts: [], tasks: [], events: [], edges: [] };
12634
+ if (options?.sources) empty.sources = [];
11509
12635
  if (exposeMetadata) {
11510
12636
  empty.metadata = { query, entityIds: [] };
11511
12637
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
@@ -12020,6 +13146,7 @@ var RetrievalService = class {
12020
13146
  factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
12021
13147
  }
12022
13148
  const bundle = { facts, tasks, events: events.reverse(), edges: [] };
13149
+ if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
12023
13150
  if (exposeMetadata) {
12024
13151
  bundle.metadata = { query, entityIds };
12025
13152
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
@@ -12028,6 +13155,42 @@ var RetrievalService = class {
12028
13155
  }
12029
13156
  return bundle;
12030
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
+ }
12031
13194
  /**
12032
13195
  * Returns entity IDs that will participate in scored retrieval.
12033
13196
  * Excludes zero-weight entities unless includeZeroWeightEntities is true.
@@ -13034,7 +14197,8 @@ var WikiMemory = class {
13034
14197
  this.jobManager,
13035
14198
  this.embeddingService,
13036
14199
  this.options,
13037
- this.vectorRemovalService
14200
+ this.vectorRemovalService,
14201
+ this.prefix
13038
14202
  );
13039
14203
  this.retrievalService = new RetrievalService(
13040
14204
  this.options,
@@ -13044,6 +14208,7 @@ var WikiMemory = class {
13044
14208
  this.metadataRepo,
13045
14209
  this.searchService
13046
14210
  );
14211
+ this.sourceStoreService = new SourceStoreService(this.db, this.prefix, this.options, this.jobManager);
13047
14212
  this.writeService = new WriteService(
13048
14213
  this.db,
13049
14214
  this.options,
@@ -13171,9 +14336,13 @@ var WikiMemory = class {
13171
14336
  * host runs a plain `setup()` outside the lease.
13172
14337
  *
13173
14338
  * Keyword-index catch-up work is bounded by `config.setupBudgetMs`; anything
13174
- * left converges on later opens and no-arg `syncSearchIndex()` calls. Not
13175
- * bounded: an index reset (tokenizer change, re-attach after detach, a lost
13176
- * 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.
13177
14346
  */
13178
14347
  async setup(opts) {
13179
14348
  const setupBudgetMs = this.setupBudgetMs();
@@ -13217,6 +14386,7 @@ var WikiMemory = class {
13217
14386
  )
13218
14387
  );
13219
14388
  await this.searchService.sync(void 0, { deadline: openDeadline });
14389
+ await this.searchService.syncPassages(this.db, this.prefix, void 0, openDeadline);
13220
14390
  await this.startSetupRemovalDrain();
13221
14391
  }
13222
14392
  /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
@@ -13639,6 +14809,7 @@ var WikiMemory = class {
13639
14809
  );
13640
14810
  this.searchService.setIndexStrategy(strategy);
13641
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);
13642
14813
  } finally {
13643
14814
  if (this.searchService.isKeywordAvailable()) {
13644
14815
  this.reinitFailures = 0;
@@ -13681,7 +14852,13 @@ var WikiMemory = class {
13681
14852
  return this.metadataRepo.getMeta(entitySummaryMetaKey(entityId));
13682
14853
  }
13683
14854
  async importDump(dump, opts) {
13684
- 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
+ }
13685
14862
  }
13686
14863
  /**
13687
14864
  * Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
@@ -13702,7 +14879,28 @@ var WikiMemory = class {
13702
14879
  * or call `runExternalDeletions()`.
13703
14880
  */
13704
14881
  async forget(entityId, params, opts) {
13705
- 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);
13706
14904
  }
13707
14905
  /**
13708
14906
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
@@ -14059,6 +15257,10 @@ function renderEventPlain(event) {
14059
15257
  const ts = new Date(event.created_at).toISOString();
14060
15258
  return `[${event.event_type} @ ${ts}] ${event.summary}`;
14061
15259
  }
15260
+ function renderSourceLabel(p, includeEntityId) {
15261
+ const entity = includeEntityId ? `${p.entityId} ` : "";
15262
+ return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? " (excerpt)" : ""}`;
15263
+ }
14062
15264
  function formatContext(bundle, options) {
14063
15265
  const opts = {
14064
15266
  format: options?.format ?? "markdown",
@@ -14084,7 +15286,8 @@ function formatContext(bundle, options) {
14084
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);
14085
15287
  const sortedTasks = [...bundle.tasks].sort((a, b) => b.priority - a.priority || a.created_at - b.created_at).slice(0, opts.maxTasks);
14086
15288
  const sortedEvents = [...bundle.events].sort((a, b) => b.created_at - a.created_at).slice(0, opts.maxEvents);
14087
- 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) {
14088
15291
  return "";
14089
15292
  }
14090
15293
  const isMarkdown = opts.format === "markdown";
@@ -14112,6 +15315,13 @@ function formatContext(bundle, options) {
14112
15315
  lines.push(renderEventMarkdown(event));
14113
15316
  }
14114
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
+ }
14115
15325
  } else {
14116
15326
  if (sortedFacts.length > 0) {
14117
15327
  lines.push("KNOWN FACTS:");
@@ -14131,6 +15341,12 @@ function formatContext(bundle, options) {
14131
15341
  lines.push(renderEventPlain(event));
14132
15342
  }
14133
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
+ }
14134
15350
  }
14135
15351
  return lines.join("\n");
14136
15352
  }
@@ -14327,6 +15543,15 @@ function isoDateOrOmit(ms) {
14327
15543
  if (!Number.isFinite(d.getTime())) return void 0;
14328
15544
  return d.toISOString().slice(0, 10);
14329
15545
  }
15546
+ function sourcePointerFrontmatter(p) {
15547
+ if (!p) return void 0;
15548
+ return {
15549
+ ...p.event_id != null ? { event_id: p.event_id } : {},
15550
+ ...p.ref != null ? { ref: p.ref } : {},
15551
+ ...p.quote != null ? { quote: p.quote } : {},
15552
+ ...p.position != null ? { position: p.position } : {}
15553
+ };
15554
+ }
14330
15555
  function factFrontmatterV2(f) {
14331
15556
  return {
14332
15557
  type: f.okf_type ?? "fact",
@@ -14365,7 +15590,9 @@ function factFrontmatterV2(f) {
14365
15590
  ...f.valid_from != null ? { valid_from: f.valid_from } : {},
14366
15591
  ...f.valid_to != null ? { valid_to: f.valid_to } : {},
14367
15592
  ...f.superseded_by != null ? { superseded_by: f.superseded_by } : {},
14368
- ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {}
15593
+ ...f.superseded_at != null ? { superseded_at: f.superseded_at } : {},
15594
+ // Source pointer (specs/source-pointers): map only when non-null; null slots omitted.
15595
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
14369
15596
  };
14370
15597
  }
14371
15598
  function taskFrontmatterV2(t) {
@@ -14409,7 +15636,9 @@ function factFrontmatterV1(f) {
14409
15636
  created_at: f.created_at,
14410
15637
  access_count: f.access_count,
14411
15638
  last_accessed_at: f.last_accessed_at,
14412
- deleted_at: f.deleted_at
15639
+ deleted_at: f.deleted_at,
15640
+ // Source pointer (specs/source-pointers): same map rule as the v2 path.
15641
+ ...sourcePointerFrontmatter(f.source_pointer) ? { source_pointer: sourcePointerFrontmatter(f.source_pointer) } : {}
14413
15642
  };
14414
15643
  }
14415
15644
  function taskFrontmatterV1(t) {
@@ -14665,7 +15894,7 @@ function parseLogEntryText(text) {
14665
15894
  }
14666
15895
  return { event_type, summary: unescapeLogSummary((plainSummary ?? "").trim()) };
14667
15896
  }
14668
- function frontmatterToFact(entityId, id, frontmatter, body, now) {
15897
+ function frontmatterToFact(entityId, id, frontmatter, body, now, droppedPointerValues) {
14669
15898
  const created_at = parseFrontmatterTimestamp(frontmatter.created_at, now);
14670
15899
  const updated_at = parseFrontmatterTimestamp(
14671
15900
  frontmatter.generated?.at,
@@ -14719,7 +15948,23 @@ function frontmatterToFact(entityId, id, frontmatter, body, now) {
14719
15948
  ...optionalEpoch("valid_from", frontmatter.valid_from),
14720
15949
  ...optionalEpoch("valid_to", frontmatter.valid_to),
14721
15950
  ...typeof frontmatter.superseded_by === "string" ? { superseded_by: frontmatter.superseded_by } : {},
14722
- ...optionalEpoch("superseded_at", frontmatter.superseded_at)
15951
+ ...optionalEpoch("superseded_at", frontmatter.superseded_at),
15952
+ // Source pointer (specs/source-pointers §Export, import, and OKF): the
15953
+ // parse path has no diagnostic channel, so it reports through the result.
15954
+ // ABSENT key → the property is omitted (not null), so the import
15955
+ // presence guard survives the parse. Malformed → the property is omitted
15956
+ // AND the drop is reported as entry id + reason slug — never the raw
15957
+ // value, which can carry quote text.
15958
+ ...(() => {
15959
+ const raw = frontmatter.source_pointer;
15960
+ if (raw === void 0) return {};
15961
+ const v = validateSourcePointerValue(raw);
15962
+ if (v === void 0) {
15963
+ droppedPointerValues.push({ factId: id, reason: "malformed" });
15964
+ return {};
15965
+ }
15966
+ return { source_pointer: v };
15967
+ })()
14723
15968
  };
14724
15969
  }
14725
15970
  function optionalEpoch(key, v) {
@@ -14840,6 +16085,7 @@ function parseOkfBundle(entityId, files, options) {
14840
16085
  }
14841
16086
  const facts = [];
14842
16087
  const tasks = [];
16088
+ const droppedPointerValues = [];
14843
16089
  const edges = [];
14844
16090
  let logContent = null;
14845
16091
  const logMdPath = findLogMdPath(allowedFiles);
@@ -14857,7 +16103,7 @@ function parseOkfBundle(entityId, files, options) {
14857
16103
  const edgeLinks = isProfile1 || isLegacyV1 ? relatedLinks : [...relatedLinks, ...coreOkf.extractMarkdownLinks(storedBody)];
14858
16104
  const usesV1StatusRule = isProfile1 || isLegacyV1 || profile === void 0 && okfVersion === void 0;
14859
16105
  if (route === "fact") {
14860
- facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now));
16106
+ facts.push(frontmatterToFact(entityId, resolvedId, frontmatter, storedBody, now, droppedPointerValues));
14861
16107
  } else {
14862
16108
  tasks.push(frontmatterToTask(entityId, resolvedId, frontmatter, now, usesV1StatusRule));
14863
16109
  }
@@ -14924,7 +16170,8 @@ function parseOkfBundle(entityId, files, options) {
14924
16170
  generatedAt: now,
14925
16171
  entities: {
14926
16172
  [entityId]: { facts, tasks, events, edges, summary: entitySummary }
14927
- }
16173
+ },
16174
+ ...droppedPointerValues.length > 0 ? { dropped_pointer_values: droppedPointerValues } : {}
14928
16175
  };
14929
16176
  }
14930
16177