@equationalapplications/core-llm-wiki 9.1.0 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, FTS5_STATE_KEY, fts5LedgerDropSql, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-SIJD5GEF.mjs';
2
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-SIJD5GEF.mjs';
1
+ import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, WikiDraftNotFound, generateId, emptyManifest, resolveNodeType, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-E3JCZMJL.mjs';
2
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, EMBED_CHARS_CEILING, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isWikiSearchUnavailableError, parseEmbedding, safeSlice, validateManifest } from './chunk-E3JCZMJL.mjs';
3
3
  import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, createEventIdDeriver, latestVerified, formatSourcesJson, appendEventIdComment, parseVerifiedFlexible, parseCitationsList } from '@equationalapplications/core-okf';
4
4
  import MiniSearch from 'minisearch';
5
5
 
@@ -1188,20 +1188,26 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
1188
1188
  FROM ${this.prefix}entries
1189
1189
  WHERE entity_id = ? AND deleted_at IS NULL AND source_ref IS NOT NULL
1190
1190
  )
1191
- SELECT source_ref,
1192
- source_hash AS source_hash,
1193
- fact_count AS fact_count,
1194
- updated_at AS last_ingested_at
1191
+ SELECT ranked.source_ref,
1192
+ ranked.source_hash AS source_hash,
1193
+ ranked.fact_count AS fact_count,
1194
+ ranked.updated_at AS last_ingested_at,
1195
+ d.source_hash AS stored_hash,
1196
+ d.char_count AS stored_chars
1195
1197
  FROM ranked
1196
- WHERE rn = 1
1197
- ORDER BY source_ref COLLATE BINARY`,
1198
- [entityId]
1198
+ LEFT JOIN ${this.prefix}source_documents d
1199
+ ON d.entity_id = ? AND d.source_ref = ranked.source_ref
1200
+ WHERE ranked.rn = 1
1201
+ ORDER BY ranked.source_ref COLLATE BINARY`,
1202
+ [entityId, entityId]
1199
1203
  );
1200
1204
  return rows.map((r) => ({
1201
1205
  sourceRef: r.source_ref,
1202
1206
  sourceHash: r.source_hash,
1203
1207
  factCount: Number(r.fact_count),
1204
- lastIngestedAt: Number(r.last_ingested_at)
1208
+ lastIngestedAt: Number(r.last_ingested_at),
1209
+ // Spec source-store §4: keyed on the ref's own (sourceRef, sourceHash) pair.
1210
+ 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 }
1205
1211
  }));
1206
1212
  }
1207
1213
  /**
@@ -2194,195 +2200,6 @@ var EventRepository = class extends BaseRepository {
2194
2200
  return row?.total ?? 0;
2195
2201
  }
2196
2202
  };
2197
- var MiniSearchIndexStrategy = class {
2198
- constructor() {
2199
- /**
2200
- * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
2201
- * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
2202
- * not see this map; it only sees `hasIndexedEntity`. The previous
2203
- * `miniSearchEntryIdsByEntity` lived on `SearchService`.
2204
- */
2205
- this.entryIdsByEntity = /* @__PURE__ */ new Map();
2206
- /**
2207
- * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
2208
- * decide which ids are owned by `entityId` (the only safe membership test
2209
- * — a rebuild that failed between its discard pass and the set replacement
2210
- * can leave the forward set claiming ids the MiniSearch instance does not
2211
- * hold). The pre-extraction `syncEntries` deleted from one set per id, not
2212
- * from every entity's set.
2213
- */
2214
- this.entityIdById = /* @__PURE__ */ new Map();
2215
- this.index = this.createIndex();
2216
- }
2217
- /**
2218
- * Build a fresh MiniSearch instance with the project's index options.
2219
- * Called from the constructor and from `replaceAll`. We do not use
2220
- * `removeAll()` on an existing instance because that empties the index but
2221
- * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
2222
- * `syncEntries`' conditional vacuum early after a clear.
2223
- */
2224
- createIndex() {
2225
- return new MiniSearch({
2226
- fields: ["title", "body", "tags"],
2227
- storeFields: ["entity_id"],
2228
- // Vacuuming is driven explicitly at the end of each serialized rebuild
2229
- // (see SearchService.syncEntries). Auto-vacuum fires on its own
2230
- // schedule, asynchronously with respect to the caller, and traversing
2231
- // the tree mid-rebuild is what threw the uncaught TypeError in
2232
- // MiniSearch.performVacuuming (#64).
2233
- autoVacuum: false,
2234
- searchOptions: {
2235
- boost: { title: 2 },
2236
- fuzzy: 0.2,
2237
- prefix: true
2238
- }
2239
- });
2240
- }
2241
- /**
2242
- * Incremental sync. Removes only ids currently tracked under `entityId`
2243
- * (other entities' docs are untouched), then upserts `documents` by id.
2244
- * The same id appearing in both `ids` and `documents` is discarded first
2245
- * so the upsert does not throw on a duplicate id.
2246
- *
2247
- * Every document must carry `entityId` as its `entity_id`; a mismatch is
2248
- * rejected before the write mutates anything. A tracking-only call
2249
- * (`replace(entityId, [], [])`) registers the entity as indexed, matching
2250
- * the interface contract.
2251
- *
2252
- * Atomicity: never awaits between the discard pass and `addDocuments`, so
2253
- * a concurrent `search()` sees the index wholly before or wholly after,
2254
- * never half-updated. This is the precondition the pre-extraction
2255
- * `syncEntries` kept with its "no await from here to `addAll`" comment.
2256
- */
2257
- async replace(entityId, ids, documents) {
2258
- assertOwnedBy(entityId, documents);
2259
- this.discardIds(ids, entityId);
2260
- if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
2261
- this.addDocuments(documents);
2262
- }
2263
- /**
2264
- * Per-entity rebuild. Removes every id tracked under `entityId` (with the
2265
- * `index.has(id)` guard so a stale tracking set cannot make `discard()`
2266
- * throw), then writes `documents`. The entity stays registered as
2267
- * indexed — even when `documents` is empty — so the next `syncEntries`
2268
- * call can take the fast path. Every document must belong to `entityId`.
2269
- */
2270
- async replaceEntity(entityId, documents) {
2271
- assertOwnedBy(entityId, documents);
2272
- const previous = this.entryIdsByEntity.get(entityId);
2273
- if (previous) this.discardIds([...previous]);
2274
- this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
2275
- this.addDocuments(documents);
2276
- }
2277
- /**
2278
- * Global rebuild / clear. Replaces the MiniSearch instance and clears both
2279
- * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
2280
- * `SearchService.clearAll()` calls `replaceAll([])`.
2281
- */
2282
- async replaceAll(documents) {
2283
- this.index = this.createIndex();
2284
- this.entryIdsByEntity.clear();
2285
- this.entityIdById.clear();
2286
- this.addDocuments(documents);
2287
- }
2288
- /**
2289
- * Best-match-first search over the documents whose `entity_id` is in
2290
- * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
2291
- * uses this to over-fetch candidates before the `limit` cap). Scores are
2292
- * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
2293
- * any scaling, not the strategy.
2294
- */
2295
- async search(query, options) {
2296
- if (options.entityIds.length === 0) return [];
2297
- const entityIdSet = new Set(options.entityIds);
2298
- const limit = options.preFilterLimit ?? options.limit;
2299
- const raw = this.index.search(query, {
2300
- filter: (r) => entityIdSet.has(r.entity_id),
2301
- combineWith: "OR"
2302
- });
2303
- raw.sort((a, b) => {
2304
- const scoreDiff = b.score - a.score;
2305
- if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
2306
- return a.id.localeCompare(b.id);
2307
- });
2308
- return raw.slice(0, limit).map((r) => ({
2309
- id: r.id,
2310
- entity_id: r.entity_id,
2311
- score: r.score
2312
- }));
2313
- }
2314
- /**
2315
- * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
2316
- * un-vacuumed discard inverts the relative scores of term-sharing
2317
- * documents at any index size. `SearchService.syncEntries` calls this
2318
- * after a discard-bearing turn. No-op when `dirtCount === 0`.
2319
- */
2320
- async vacuum() {
2321
- if (this.index.dirtCount > 0) {
2322
- await this.index.vacuum();
2323
- }
2324
- }
2325
- /**
2326
- * `true` when `entityId` has been indexed at least once under the current
2327
- * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
2328
- * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
2329
- */
2330
- hasIndexedEntity(entityId) {
2331
- return this.entryIdsByEntity.has(entityId);
2332
- }
2333
- /**
2334
- * Add `documents` to the MiniSearch instance and register them in
2335
- * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
2336
- * during `add`, so each doc is copied first. `add` throws on an id the
2337
- * index already holds — `replace` and `replaceEntity` discard first for
2338
- * that reason.
2339
- *
2340
- * Adds and registers one document at a time: if a duplicate id throws
2341
- * part-way through, every document already in the index is tracked, so
2342
- * the next rebuild can discard it instead of failing on it again. This is
2343
- * the precondition the per-turn recovery path relies on (#258 review).
2344
- */
2345
- addDocuments(documents) {
2346
- for (const d of documents) {
2347
- const doc = { ...d };
2348
- this.index.add(doc);
2349
- const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
2350
- set.add(doc.id);
2351
- this.entryIdsByEntity.set(doc.entity_id, set);
2352
- this.entityIdById.set(doc.id, doc.entity_id);
2353
- }
2354
- }
2355
- /**
2356
- * Discard `ids` from the MiniSearch instance and from both id maps, but
2357
- * only for ids currently owned by `entityId` (the second argument). When
2358
- * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
2359
- * path), every id is discarded regardless of owning entity.
2360
- *
2361
- * `index.has(id)` is the membership test of record: a rebuild that failed
2362
- * between its own discard pass and the set replacement can leave the
2363
- * tracking set claiming ids the index no longer holds — `discard()` throws
2364
- * on those, so we guard.
2365
- */
2366
- discardIds(ids, entityId) {
2367
- for (const id of ids) {
2368
- const owning = this.entityIdById.get(id);
2369
- if (owning === void 0) continue;
2370
- if (entityId !== void 0 && owning !== entityId) continue;
2371
- if (this.index.has(id)) this.index.discard(id);
2372
- this.entryIdsByEntity.get(owning)?.delete(id);
2373
- this.entityIdById.delete(id);
2374
- }
2375
- }
2376
- };
2377
- function assertOwnedBy(entityId, documents) {
2378
- for (const doc of documents) {
2379
- if (doc.entity_id !== entityId) {
2380
- throw new Error(
2381
- `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
2382
- );
2383
- }
2384
- }
2385
- }
2386
2203
 
2387
2204
  // src/utils/monotonicNow.ts
2388
2205
  var monotonicNow = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
@@ -2400,12 +2217,46 @@ function buildFtsMatchQuery(query) {
2400
2217
  }
2401
2218
 
2402
2219
  // src/services/search/Fts5IndexStrategy.ts
2220
+ async function hydratePassageHits(db, prefix, raw) {
2221
+ const docs = /* @__PURE__ */ new Map();
2222
+ const out = [];
2223
+ for (const r of raw) {
2224
+ const pas = await db.getFirstAsync(
2225
+ `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages WHERE id = ? AND entity_id = ?`,
2226
+ [r.id, r.entity_id]
2227
+ );
2228
+ if (!pas) continue;
2229
+ const dk = `${r.entity_id}\0${r.document_id}`;
2230
+ if (!docs.has(dk)) {
2231
+ docs.set(dk, await db.getFirstAsync(
2232
+ `SELECT source_ref, source_hash, text FROM ${prefix}source_documents WHERE id = ? AND entity_id = ?`,
2233
+ [r.document_id, r.entity_id]
2234
+ ) ?? null);
2235
+ }
2236
+ const doc = docs.get(dk);
2237
+ if (!doc) continue;
2238
+ const start = Number(pas.start_offset);
2239
+ const end = Number(pas.end_offset);
2240
+ out.push({
2241
+ ...r,
2242
+ seq: Number(pas.seq),
2243
+ start_offset: start,
2244
+ end_offset: end,
2245
+ source_ref: doc.source_ref,
2246
+ source_hash: doc.source_hash,
2247
+ text: doc.text.slice(start, end)
2248
+ });
2249
+ }
2250
+ return out;
2251
+ }
2403
2252
  var Fts5IndexStrategy = class {
2404
2253
  constructor(db, prefix, metadataRepo, budgetMs = DEFAULT_SETUP_BUDGET_MS) {
2405
2254
  this.db = db;
2406
2255
  this.prefix = prefix;
2407
2256
  this.metadataRepo = metadataRepo;
2408
2257
  this.budgetMs = budgetMs;
2258
+ /** Set when passage-index init failed; passage drain and search become no-ops. */
2259
+ this.passagesDisabled = false;
2409
2260
  }
2410
2261
  /**
2411
2262
  * Resolves the index state (spec #280 Change 3 transition table). Every
@@ -2413,6 +2264,120 @@ var Fts5IndexStrategy = class {
2413
2264
  * failure leaves zero mutation (Change 4 ordering).
2414
2265
  */
2415
2266
  async init(opts = {}) {
2267
+ await this.initEntries(opts);
2268
+ try {
2269
+ await this.ensurePassageObjects();
2270
+ } catch (err) {
2271
+ this.passagesDisabled = true;
2272
+ console.warn("[WikiMemory] passage index init failed; passage search returns [] until a later open:", err);
2273
+ }
2274
+ }
2275
+ /**
2276
+ * Source-store passage index objects (spec source-store §6): created here,
2277
+ * the way the entries_fts objects are, never by setupDatabase. Skipped when
2278
+ * the store tables are absent (a pre-v17 database).
2279
+ */
2280
+ async ensurePassageObjects() {
2281
+ const p = this.prefix;
2282
+ if (!await this.metadataRepo.tableExists(`${p}source_passages`)) return;
2283
+ await this.db.withTransactionAsync(async (tx) => {
2284
+ await tx.execAsync(passageFtsTablesDdl(p) + passageFtsTriggersDdl(p));
2285
+ const mapped = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_map LIMIT 1`);
2286
+ const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);
2287
+ if (mapped === null && queued === null) {
2288
+ await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);
2289
+ await tx.runAsync(
2290
+ `INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)
2291
+ SELECT entity_id, id FROM ${p}source_documents`
2292
+ );
2293
+ }
2294
+ });
2295
+ }
2296
+ /**
2297
+ * Drain the passage ledger one document at a time (spec §6, the stated
2298
+ * departure from all-SQL): the document's text is read into JS and sliced at
2299
+ * the offsets the cutter stored, so transient memory is bounded by
2300
+ * `maxCharsPerSource` for the ONE document, never the store. Each document
2301
+ * is one transaction. `entityId` limits the drain to that entity's ledger rows.
2302
+ */
2303
+ async drainPassages(opts = {}) {
2304
+ if (this.passagesDisabled) return;
2305
+ const p = this.prefix;
2306
+ if (!await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`)) return;
2307
+ for (; ; ) {
2308
+ if (opts.deadline !== void 0 && monotonicNow() >= opts.deadline) return;
2309
+ let ran = false;
2310
+ await this.db.withTransactionAsync(async (tx) => {
2311
+ const first = opts.entityId === void 0 ? await tx.getFirstAsync(
2312
+ `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending ORDER BY seq LIMIT 1`
2313
+ ) : await tx.getFirstAsync(
2314
+ `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending WHERE entity_id = ? ORDER BY seq LIMIT 1`,
2315
+ [opts.entityId]
2316
+ );
2317
+ if (!first) return;
2318
+ const docId = first.doc_id;
2319
+ const ent = first.entity_id;
2320
+ const hi = await tx.getFirstAsync(
2321
+ `SELECT max(seq) AS hi FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND entity_id = ?`,
2322
+ [docId, ent]
2323
+ );
2324
+ await tx.runAsync(
2325
+ `DELETE FROM ${p}source_passages_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}source_passages_fts_map WHERE doc_id = ?)`,
2326
+ [docId]
2327
+ );
2328
+ await tx.runAsync(`DELETE FROM ${p}source_passages_fts_map WHERE doc_id = ?`, [docId]);
2329
+ const doc = await tx.getFirstAsync(`SELECT text FROM ${p}source_documents WHERE id = ? AND entity_id = ?`, [docId, ent]);
2330
+ if (doc) {
2331
+ const rows = await tx.getAllAsync(
2332
+ `SELECT id, entity_id, start_offset, end_offset FROM ${p}source_passages WHERE document_id = ? AND entity_id = ? ORDER BY seq`,
2333
+ [docId, ent]
2334
+ );
2335
+ for (const r of rows) {
2336
+ const { lastInsertRowId } = await tx.runAsync(
2337
+ `INSERT INTO ${p}source_passages_fts_map (passage_id, doc_id) VALUES (?, ?)`,
2338
+ [r.id, docId]
2339
+ );
2340
+ await tx.runAsync(
2341
+ `INSERT INTO ${p}source_passages_fts (rowid, passage_id, entity_id, doc_id, text) VALUES (?, ?, ?, ?, ?)`,
2342
+ [lastInsertRowId, r.id, r.entity_id, docId, doc.text.slice(Number(r.start_offset), Number(r.end_offset))]
2343
+ );
2344
+ }
2345
+ }
2346
+ await tx.runAsync(
2347
+ `DELETE FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND seq <= ?`,
2348
+ [docId, hi?.hi ?? 0]
2349
+ );
2350
+ ran = true;
2351
+ });
2352
+ if (!ran) return;
2353
+ }
2354
+ }
2355
+ /**
2356
+ * Best-match-first passage search. A hit counts only while its
2357
+ * `source_passages` row exists, so a stalled drain never surfaces a deleted
2358
+ * passage (spec §5).
2359
+ */
2360
+ async searchPassages(query, options) {
2361
+ if (this.passagesDisabled || options.entityIds.length === 0) return [];
2362
+ const match = buildFtsMatchQuery(query);
2363
+ if (match === null) return [];
2364
+ const p = this.prefix;
2365
+ const t = `${p}source_passages_fts`;
2366
+ const limit = options.limit >= Number.MAX_SAFE_INTEGER ? -1 : options.limit;
2367
+ const raw = await this.db.getAllAsync(
2368
+ `SELECT passage_id AS id, entity_id, doc_id AS document_id, max(0.0, -raw) AS score FROM (
2369
+ SELECT passage_id, entity_id, doc_id, bm25(${t}, 0.0, 0.0, 0.0, 1.0) AS raw
2370
+ FROM ${t}
2371
+ WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))
2372
+ AND passage_id IN (SELECT id FROM ${p}source_passages WHERE entity_id IN (SELECT value FROM json_each(?)))
2373
+ ORDER BY raw, passage_id
2374
+ LIMIT ?)
2375
+ ORDER BY raw, id`,
2376
+ [match, JSON.stringify(options.entityIds), JSON.stringify(options.entityIds), limit]
2377
+ );
2378
+ return hydratePassageHits(this.db, p, raw);
2379
+ }
2380
+ async initEntries(opts) {
2416
2381
  try {
2417
2382
  await this.initOnce(opts);
2418
2383
  } catch (err) {
@@ -2894,6 +2859,281 @@ function assertEntity(entityId, documents) {
2894
2859
  }
2895
2860
  }
2896
2861
 
2862
+ // src/services/search/MiniSearchIndexStrategy.ts
2863
+ async function loadStoredPassages(db, prefix, entityId) {
2864
+ const out = [];
2865
+ const docs = await db.getAllAsync(`SELECT id FROM ${prefix}source_documents WHERE entity_id = ?`, [entityId]);
2866
+ for (const d of docs) {
2867
+ const doc = await db.getFirstAsync(`SELECT text FROM ${prefix}source_documents WHERE id = ?`, [d.id]);
2868
+ if (!doc) continue;
2869
+ const rows = await db.getAllAsync(
2870
+ `SELECT id, start_offset, end_offset FROM ${prefix}source_passages WHERE document_id = ? ORDER BY seq`,
2871
+ [d.id]
2872
+ );
2873
+ for (const r of rows) {
2874
+ out.push({ id: r.id, entity_id: entityId, document_id: d.id, text: doc.text.slice(Number(r.start_offset), Number(r.end_offset)) });
2875
+ }
2876
+ }
2877
+ return out;
2878
+ }
2879
+ var MiniSearchIndexStrategy = class {
2880
+ constructor() {
2881
+ /**
2882
+ * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
2883
+ * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
2884
+ * not see this map; it only sees `hasIndexedEntity`. The previous
2885
+ * `miniSearchEntryIdsByEntity` lived on `SearchService`.
2886
+ */
2887
+ this.entryIdsByEntity = /* @__PURE__ */ new Map();
2888
+ /**
2889
+ * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
2890
+ * decide which ids are owned by `entityId` (the only safe membership test
2891
+ * — a rebuild that failed between its discard pass and the set replacement
2892
+ * can leave the forward set claiming ids the MiniSearch instance does not
2893
+ * hold). The pre-extraction `syncEntries` deleted from one set per id, not
2894
+ * from every entity's set.
2895
+ */
2896
+ this.entityIdById = /* @__PURE__ */ new Map();
2897
+ // ---- Source-store passage index (spec source-store §6) --------------------
2898
+ // A second in-heap instance over the same passage slices as the FTS5 path.
2899
+ this.passageIndex = this.createPassageIndex();
2900
+ this.passageIdsByEntity = /* @__PURE__ */ new Map();
2901
+ /** Handle `reindexSourcePassages` last indexed from; `searchPassages` hydrates hits through it. */
2902
+ this.passageSource = null;
2903
+ this.index = this.createIndex();
2904
+ }
2905
+ /**
2906
+ * Build a fresh MiniSearch instance with the project's index options.
2907
+ * Called from the constructor and from `replaceAll`. We do not use
2908
+ * `removeAll()` on an existing instance because that empties the index but
2909
+ * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
2910
+ * `syncEntries`' conditional vacuum early after a clear.
2911
+ */
2912
+ createIndex() {
2913
+ return new MiniSearch({
2914
+ fields: ["title", "body", "tags"],
2915
+ storeFields: ["entity_id"],
2916
+ // Vacuuming is driven explicitly at the end of each serialized rebuild
2917
+ // (see SearchService.syncEntries). Auto-vacuum fires on its own
2918
+ // schedule, asynchronously with respect to the caller, and traversing
2919
+ // the tree mid-rebuild is what threw the uncaught TypeError in
2920
+ // MiniSearch.performVacuuming (#64).
2921
+ autoVacuum: false,
2922
+ searchOptions: {
2923
+ boost: { title: 2 },
2924
+ fuzzy: 0.2,
2925
+ prefix: true
2926
+ }
2927
+ });
2928
+ }
2929
+ /**
2930
+ * Incremental sync. Removes only ids currently tracked under `entityId`
2931
+ * (other entities' docs are untouched), then upserts `documents` by id.
2932
+ * The same id appearing in both `ids` and `documents` is discarded first
2933
+ * so the upsert does not throw on a duplicate id.
2934
+ *
2935
+ * Every document must carry `entityId` as its `entity_id`; a mismatch is
2936
+ * rejected before the write mutates anything. A tracking-only call
2937
+ * (`replace(entityId, [], [])`) registers the entity as indexed, matching
2938
+ * the interface contract.
2939
+ *
2940
+ * Atomicity: never awaits between the discard pass and `addDocuments`, so
2941
+ * a concurrent `search()` sees the index wholly before or wholly after,
2942
+ * never half-updated. This is the precondition the pre-extraction
2943
+ * `syncEntries` kept with its "no await from here to `addAll`" comment.
2944
+ */
2945
+ async replace(entityId, ids, documents) {
2946
+ assertOwnedBy(entityId, documents);
2947
+ this.discardIds(ids, entityId);
2948
+ if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
2949
+ this.addDocuments(documents);
2950
+ }
2951
+ /**
2952
+ * Per-entity rebuild. Removes every id tracked under `entityId` (with the
2953
+ * `index.has(id)` guard so a stale tracking set cannot make `discard()`
2954
+ * throw), then writes `documents`. The entity stays registered as
2955
+ * indexed — even when `documents` is empty — so the next `syncEntries`
2956
+ * call can take the fast path. Every document must belong to `entityId`.
2957
+ */
2958
+ async replaceEntity(entityId, documents) {
2959
+ assertOwnedBy(entityId, documents);
2960
+ const previous = this.entryIdsByEntity.get(entityId);
2961
+ if (previous) this.discardIds([...previous]);
2962
+ this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
2963
+ this.addDocuments(documents);
2964
+ }
2965
+ /**
2966
+ * Global rebuild / clear. Replaces the MiniSearch instance and clears both
2967
+ * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
2968
+ * `SearchService.clearAll()` calls `replaceAll([])`.
2969
+ */
2970
+ async replaceAll(documents) {
2971
+ this.index = this.createIndex();
2972
+ this.entryIdsByEntity.clear();
2973
+ this.entityIdById.clear();
2974
+ this.addDocuments(documents);
2975
+ }
2976
+ /**
2977
+ * Best-match-first search over the documents whose `entity_id` is in
2978
+ * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
2979
+ * uses this to over-fetch candidates before the `limit` cap). Scores are
2980
+ * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
2981
+ * any scaling, not the strategy.
2982
+ */
2983
+ async search(query, options) {
2984
+ if (options.entityIds.length === 0) return [];
2985
+ const entityIdSet = new Set(options.entityIds);
2986
+ const limit = options.preFilterLimit ?? options.limit;
2987
+ const raw = this.index.search(query, {
2988
+ filter: (r) => entityIdSet.has(r.entity_id),
2989
+ combineWith: "OR"
2990
+ });
2991
+ raw.sort((a, b) => {
2992
+ const scoreDiff = b.score - a.score;
2993
+ if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
2994
+ return a.id.localeCompare(b.id);
2995
+ });
2996
+ return raw.slice(0, limit).map((r) => ({
2997
+ id: r.id,
2998
+ entity_id: r.entity_id,
2999
+ score: r.score
3000
+ }));
3001
+ }
3002
+ createPassageIndex() {
3003
+ return new MiniSearch({
3004
+ fields: ["text"],
3005
+ storeFields: ["entity_id", "document_id"],
3006
+ autoVacuum: false,
3007
+ // explicit vacuum below, same reason as the facts instance (#64)
3008
+ searchOptions: { fuzzy: 0.2, prefix: true }
3009
+ });
3010
+ }
3011
+ /**
3012
+ * Re-index stored passages from SQLite: one entity, or every stored entity
3013
+ * when `entityId` is omitted (the open-time pass; up to `maxTotalChars` per
3014
+ * entity, and the heap grows with the number of stored entities, spec §6).
3015
+ * It is also the post-commit sync after forget/clearAll: deleted passages
3016
+ * drop out because the reload no longer finds their rows (spec §5).
3017
+ * Reads happen first; the discard and add are synchronous, so the swap is
3018
+ * atomic (a concurrent search sees the index wholly before or wholly after),
3019
+ * and the vacuum runs after the swap.
3020
+ */
3021
+ async reindexSourcePassages(db, prefix, entityId) {
3022
+ this.passageSource = { db, prefix };
3023
+ const entityIds = entityId !== void 0 ? [entityId] : [.../* @__PURE__ */ new Set([
3024
+ ...(await db.getAllAsync(`SELECT DISTINCT entity_id FROM ${prefix}source_documents`)).map((r) => r.entity_id),
3025
+ ...this.passageIdsByEntity.keys()
3026
+ ])];
3027
+ for (const id of entityIds) {
3028
+ const passages = await loadStoredPassages(db, prefix, id);
3029
+ for (const old of this.passageIdsByEntity.get(id) ?? []) {
3030
+ if (this.passageIndex.has(old)) this.passageIndex.discard(old);
3031
+ }
3032
+ const ids = /* @__PURE__ */ new Set();
3033
+ for (const d of passages) {
3034
+ this.passageIndex.add({ ...d });
3035
+ ids.add(d.id);
3036
+ }
3037
+ if (ids.size > 0) this.passageIdsByEntity.set(id, ids);
3038
+ else this.passageIdsByEntity.delete(id);
3039
+ if (this.passageIndex.dirtCount > 0) await this.passageIndex.vacuum();
3040
+ }
3041
+ }
3042
+ /** Best-match-first passage search over the entities in `options.entityIds`. */
3043
+ async searchPassages(query, options) {
3044
+ if (options.entityIds.length === 0 || !this.passageSource) return [];
3045
+ const allowed = new Set(options.entityIds);
3046
+ const raw = this.passageIndex.search(query, { filter: (r) => allowed.has(r.entity_id), combineWith: "OR" });
3047
+ raw.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
3048
+ const live = /* @__PURE__ */ new Set();
3049
+ for (const eid of options.entityIds) {
3050
+ const rows = await this.passageSource.db.getAllAsync(
3051
+ `SELECT id FROM ${this.passageSource.prefix}source_passages WHERE entity_id = ?`,
3052
+ [eid]
3053
+ );
3054
+ for (const row of rows) live.add(row.id);
3055
+ }
3056
+ const hits = raw.filter((r) => live.has(r.id)).slice(0, options.limit).map((r) => ({
3057
+ id: r.id,
3058
+ entity_id: r.entity_id,
3059
+ document_id: r.document_id,
3060
+ score: r.score
3061
+ }));
3062
+ return hydratePassageHits(this.passageSource.db, this.passageSource.prefix, hits);
3063
+ }
3064
+ /**
3065
+ * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
3066
+ * un-vacuumed discard inverts the relative scores of term-sharing
3067
+ * documents at any index size. `SearchService.syncEntries` calls this
3068
+ * after a discard-bearing turn. No-op when `dirtCount === 0`.
3069
+ */
3070
+ async vacuum() {
3071
+ if (this.index.dirtCount > 0) {
3072
+ await this.index.vacuum();
3073
+ }
3074
+ }
3075
+ /**
3076
+ * `true` when `entityId` has been indexed at least once under the current
3077
+ * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
3078
+ * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
3079
+ */
3080
+ hasIndexedEntity(entityId) {
3081
+ return this.entryIdsByEntity.has(entityId);
3082
+ }
3083
+ /**
3084
+ * Add `documents` to the MiniSearch instance and register them in
3085
+ * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
3086
+ * during `add`, so each doc is copied first. `add` throws on an id the
3087
+ * index already holds — `replace` and `replaceEntity` discard first for
3088
+ * that reason.
3089
+ *
3090
+ * Adds and registers one document at a time: if a duplicate id throws
3091
+ * part-way through, every document already in the index is tracked, so
3092
+ * the next rebuild can discard it instead of failing on it again. This is
3093
+ * the precondition the per-turn recovery path relies on (#258 review).
3094
+ */
3095
+ addDocuments(documents) {
3096
+ for (const d of documents) {
3097
+ const doc = { ...d };
3098
+ this.index.add(doc);
3099
+ const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
3100
+ set.add(doc.id);
3101
+ this.entryIdsByEntity.set(doc.entity_id, set);
3102
+ this.entityIdById.set(doc.id, doc.entity_id);
3103
+ }
3104
+ }
3105
+ /**
3106
+ * Discard `ids` from the MiniSearch instance and from both id maps, but
3107
+ * only for ids currently owned by `entityId` (the second argument). When
3108
+ * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
3109
+ * path), every id is discarded regardless of owning entity.
3110
+ *
3111
+ * `index.has(id)` is the membership test of record: a rebuild that failed
3112
+ * between its own discard pass and the set replacement can leave the
3113
+ * tracking set claiming ids the index no longer holds — `discard()` throws
3114
+ * on those, so we guard.
3115
+ */
3116
+ discardIds(ids, entityId) {
3117
+ for (const id of ids) {
3118
+ const owning = this.entityIdById.get(id);
3119
+ if (owning === void 0) continue;
3120
+ if (entityId !== void 0 && owning !== entityId) continue;
3121
+ if (this.index.has(id)) this.index.discard(id);
3122
+ this.entryIdsByEntity.get(owning)?.delete(id);
3123
+ this.entityIdById.delete(id);
3124
+ }
3125
+ }
3126
+ };
3127
+ function assertOwnedBy(entityId, documents) {
3128
+ for (const doc of documents) {
3129
+ if (doc.entity_id !== entityId) {
3130
+ throw new Error(
3131
+ `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
3132
+ );
3133
+ }
3134
+ }
3135
+ }
3136
+
2897
3137
  // src/services/search/createIndexStrategy.ts
2898
3138
  var FTS5_INIT_RETRY_MS = 250;
2899
3139
  function isModuleAbsentError(err) {
@@ -2931,6 +3171,22 @@ async function probeFts5(db, prefix) {
2931
3171
  }
2932
3172
  }
2933
3173
  async function detachFts5(db, prefix, metadataRepo) {
3174
+ const passageLedger = await metadataRepo.tableExists(`${prefix}source_passages_fts_pending`);
3175
+ if (passageLedger) {
3176
+ const [ai, ad] = passageFtsTriggerNames(prefix);
3177
+ await db.withTransactionAsync(async (tx) => {
3178
+ await tx.execAsync(
3179
+ `DROP TRIGGER IF EXISTS ${ai};
3180
+ DROP TRIGGER IF EXISTS ${ad};
3181
+ DROP TABLE IF EXISTS ${prefix}source_passages_fts_map;
3182
+ DROP TABLE IF EXISTS ${prefix}source_passages_fts_pending;`
3183
+ );
3184
+ });
3185
+ try {
3186
+ await db.execAsync(`DROP TABLE IF EXISTS ${prefix}source_passages_fts`);
3187
+ } catch {
3188
+ }
3189
+ }
2934
3190
  const hasLedger = await metadataRepo.tableExists(`${prefix}fts_pending`);
2935
3191
  const state = await metadataRepo.getMeta(FTS5_STATE_KEY);
2936
3192
  if (!hasLedger && state !== "live") return;
@@ -3945,7 +4201,8 @@ var WikiMemory = class {
3945
4201
  this.jobManager,
3946
4202
  this.embeddingService,
3947
4203
  this.options,
3948
- this.vectorRemovalService
4204
+ this.vectorRemovalService,
4205
+ this.prefix
3949
4206
  );
3950
4207
  this.retrievalService = new RetrievalService(
3951
4208
  this.options,
@@ -3955,6 +4212,7 @@ var WikiMemory = class {
3955
4212
  this.metadataRepo,
3956
4213
  this.searchService
3957
4214
  );
4215
+ this.sourceStoreService = new SourceStoreService(this.db, this.prefix, this.options, this.jobManager);
3958
4216
  this.writeService = new WriteService(
3959
4217
  this.db,
3960
4218
  this.options,
@@ -4082,9 +4340,13 @@ var WikiMemory = class {
4082
4340
  * host runs a plain `setup()` outside the lease.
4083
4341
  *
4084
4342
  * Keyword-index catch-up work is bounded by `config.setupBudgetMs`; anything
4085
- * left converges on later opens and no-arg `syncSearchIndex()` calls. Not
4086
- * bounded: an index reset (tokenizer change, re-attach after detach, a lost
4087
- * or inconsistent index), which runs as one unchunked transaction.
4343
+ * left converges on later opens, and on no-arg `syncSearchIndex()` calls for
4344
+ * the entries ledger. Passage-ledger leftover converges on later opens and on
4345
+ * passage-store writes for the entity (`storeSource`, `forget`,
4346
+ * `importDump`), which drain that entity's rows; no-arg calls do not touch
4347
+ * the passage ledger. Not bounded: an index reset (tokenizer change, re-attach
4348
+ * after detach, a lost or inconsistent index), which runs as one unchunked
4349
+ * transaction.
4088
4350
  */
4089
4351
  async setup(opts) {
4090
4352
  const setupBudgetMs = this.setupBudgetMs();
@@ -4128,6 +4390,7 @@ var WikiMemory = class {
4128
4390
  )
4129
4391
  );
4130
4392
  await this.searchService.sync(void 0, { deadline: openDeadline });
4393
+ await this.searchService.syncPassages(this.db, this.prefix, void 0, openDeadline);
4131
4394
  await this.startSetupRemovalDrain();
4132
4395
  }
4133
4396
  /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
@@ -4550,6 +4813,7 @@ var WikiMemory = class {
4550
4813
  );
4551
4814
  this.searchService.setIndexStrategy(strategy);
4552
4815
  if (this.searchService.isKeywordAvailable() && !this.searchService.hasLedger()) await this.searchService.sync();
4816
+ if (this.searchService.isKeywordAvailable()) await this.searchService.syncPassages(this.db, this.prefix);
4553
4817
  } finally {
4554
4818
  if (this.searchService.isKeywordAvailable()) {
4555
4819
  this.reinitFailures = 0;
@@ -4592,7 +4856,13 @@ var WikiMemory = class {
4592
4856
  return this.metadataRepo.getMeta(entitySummaryMetaKey(entityId));
4593
4857
  }
4594
4858
  async importDump(dump, opts) {
4595
- return this.importExportService.importDump(dump, opts);
4859
+ try {
4860
+ return await this.importExportService.importDump(dump, opts);
4861
+ } finally {
4862
+ for (const entityId of Object.keys(dump?.entities ?? {})) {
4863
+ await this.searchService.syncPassages(this.db, this.prefix, entityId);
4864
+ }
4865
+ }
4596
4866
  }
4597
4867
  /**
4598
4868
  * Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
@@ -4613,7 +4883,28 @@ var WikiMemory = class {
4613
4883
  * or call `runExternalDeletions()`.
4614
4884
  */
4615
4885
  async forget(entityId, params, opts) {
4616
- return this.maintenanceService.forget(entityId, params, opts);
4886
+ try {
4887
+ return await this.maintenanceService.forget(entityId, params, opts);
4888
+ } finally {
4889
+ if (!opts?.dryRun) {
4890
+ await this.searchService.syncPassages(this.db, this.prefix, entityId);
4891
+ }
4892
+ }
4893
+ }
4894
+ /** Store a source's text (spec source-store §7). Refusals return `stored: false`; a busy lock throws. */
4895
+ async storeSource(entityId, params) {
4896
+ assertEntityId2(entityId);
4897
+ const result = await this.sourceStoreService.storeSource(entityId, params);
4898
+ if (result.stored) await this.searchService.syncPassages(this.db, this.prefix, entityId);
4899
+ return result;
4900
+ }
4901
+ async getStoredSource(entityId, sourceRef) {
4902
+ assertEntityId2(entityId);
4903
+ return this.sourceStoreService.getStoredSource(entityId, sourceRef);
4904
+ }
4905
+ async listStoredSources(entityId) {
4906
+ assertEntityId2(entityId);
4907
+ return this.sourceStoreService.listStoredSources(entityId);
4617
4908
  }
4618
4909
  /**
4619
4910
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
@@ -4970,6 +5261,10 @@ function renderEventPlain(event) {
4970
5261
  const ts = new Date(event.created_at).toISOString();
4971
5262
  return `[${event.event_type} @ ${ts}] ${event.summary}`;
4972
5263
  }
5264
+ function renderSourceLabel(p, includeEntityId) {
5265
+ const entity = includeEntityId ? `${p.entityId} ` : "";
5266
+ return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? " (excerpt)" : ""}`;
5267
+ }
4973
5268
  function formatContext(bundle, options) {
4974
5269
  const opts = {
4975
5270
  format: options?.format ?? "markdown",
@@ -4995,7 +5290,8 @@ function formatContext(bundle, options) {
4995
5290
  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);
4996
5291
  const sortedTasks = [...bundle.tasks].sort((a, b) => b.priority - a.priority || a.created_at - b.created_at).slice(0, opts.maxTasks);
4997
5292
  const sortedEvents = [...bundle.events].sort((a, b) => b.created_at - a.created_at).slice(0, opts.maxEvents);
4998
- if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0) {
5293
+ const sources = bundle.sources ?? [];
5294
+ if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.length === 0) {
4999
5295
  return "";
5000
5296
  }
5001
5297
  const isMarkdown = opts.format === "markdown";
@@ -5023,6 +5319,13 @@ function formatContext(bundle, options) {
5023
5319
  lines.push(renderEventMarkdown(event));
5024
5320
  }
5025
5321
  }
5322
+ if (sources.length > 0) {
5323
+ lines.push("");
5324
+ lines.push("### Sources");
5325
+ for (const p of sources) {
5326
+ lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\n/g, "\n ")}`);
5327
+ }
5328
+ }
5026
5329
  } else {
5027
5330
  if (sortedFacts.length > 0) {
5028
5331
  lines.push("KNOWN FACTS:");
@@ -5042,6 +5345,12 @@ function formatContext(bundle, options) {
5042
5345
  lines.push(renderEventPlain(event));
5043
5346
  }
5044
5347
  }
5348
+ if (sources.length > 0) {
5349
+ lines.push("SOURCES:");
5350
+ for (const p of sources) {
5351
+ lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);
5352
+ }
5353
+ }
5045
5354
  }
5046
5355
  return lines.join("\n");
5047
5356
  }