@equationalapplications/core-llm-wiki 9.1.0 → 9.3.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
@@ -37,6 +37,15 @@ var SEVERITY = {
37
37
  resolve_failed: "warn",
38
38
  read_budget: "info",
39
39
  event_retention_held: "info",
40
+ prune_checkpoint_incomplete: "warn",
41
+ erase_secure_delete_off: "error",
42
+ erase_entity_skipped: "warn",
43
+ erase_retired_vtab_undroppable: "warn",
44
+ erase_retired_remaining: "error",
45
+ erase_tombstones_remaining: "error",
46
+ erase_retired_read_failed: "error",
47
+ erase_registry_sweep_skipped: "info",
48
+ import_tombstone_skipped: "info",
40
49
  event_created_at_clamped: "warn",
41
50
  event_created_at_restamped: "info",
42
51
  external_deletion_pending: "warn",
@@ -44,7 +53,12 @@ var SEVERITY = {
44
53
  guidance_too_long: "warn",
45
54
  guidance_resolver_failed: "warn",
46
55
  source_pointer_unresolved: "warn",
47
- source_pointer_invalid: "warn"
56
+ source_pointer_invalid: "warn",
57
+ source_store_source_too_large: "warn",
58
+ source_store_budget_exceeded: "warn",
59
+ source_store_hash_mismatch: "warn",
60
+ source_store_duplicate_hash: "warn",
61
+ source_store_text_not_storable: "warn"
48
62
  };
49
63
  var MESSAGE = {
50
64
  ingest_chunk_failed: "One or more document chunks failed to parse or generate.",
@@ -67,6 +81,15 @@ var MESSAGE = {
67
81
  resolve_failed: "Reconciliation failed for a candidate; it was stored as a draft.",
68
82
  read_budget: "A read was packed to a token budget.",
69
83
  event_retention_held: "Event pruning was held back because the librarian has not processed those events yet.",
84
+ prune_checkpoint_incomplete: "The post-VACUUM WAL checkpoint was incomplete while a prune partial failure was also reported; deleted bytes may remain in the WAL.",
85
+ erase_secure_delete_off: "secure_delete could not be confirmed ON on the connection; erasure is unverified and the erase was stopped.",
86
+ erase_retired_vtab_undroppable: "A retired FTS table could not be dropped on a runtime without FTS5; its shadow tables were emptied and the name stays listed until an FTS5-capable open drops it.",
87
+ erase_retired_remaining: "Erase stopped: retired FTS tables still exist after reclamation; the erase is incomplete.",
88
+ erase_tombstones_remaining: "Erase stopped: soft-deleted rows remain in the database file after the erase pipeline; the erase is incomplete and unverified.",
89
+ erase_retired_read_failed: "Erase stopped: the retired-FTS-table inventory read failed; the erase is incomplete and unverified.",
90
+ erase_entity_skipped: "Erase skipped an entity because another operation held its prune lock.",
91
+ erase_registry_sweep_skipped: "Erase skipped the source_ref_index tombstone sweep because the table does not exist (pre-v9 store).",
92
+ import_tombstone_skipped: "Import skipped live dump rows (facts and tasks) whose ids were forgotten locally. The protection holds while the tombstone is retained; once a prune hard-deletes the row, an old dump can import the fact again \u2014 see the OKF guide\u2019s restore caveat.",
70
93
  event_created_at_clamped: "Imported events dated in the future were re-dated just after the current time, or after the librarian position if that is later, keeping their order.",
71
94
  event_created_at_restamped: "Imported events that would have sorted behind the librarian position, or had an unusable date, were adjusted: an affected created_at was re-dated just after the current time, or after the librarian position if that is later, keeping their order; an unusable occurred_at was cleared.",
72
95
  external_deletion_pending: "Removals owed to the external vector index are still pending.",
@@ -74,7 +97,12 @@ var MESSAGE = {
74
97
  guidance_too_long: "The configured guidance exceeded the length cap and was not sent for this pass.",
75
98
  guidance_resolver_failed: "The per-entity guidance resolver failed; its value was not used for this pass.",
76
99
  source_pointer_unresolved: "A stored librarian fact carries no source pointer because the model answer could not yield one.",
77
- source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer."
100
+ source_pointer_invalid: "Import met a malformed source pointer value and stored a null pointer.",
101
+ source_store_source_too_large: "A source document exceeded the per-document size cap and was not stored.",
102
+ source_store_budget_exceeded: "Storing a source document would exceed the store UTF-16 code-unit budget and it was not stored.",
103
+ source_store_hash_mismatch: "A source document text did not match its recorded hash and was not stored.",
104
+ source_store_duplicate_hash: "A source document duplicated the hash of one already stored and was not stored.",
105
+ source_store_text_not_storable: "A source document text could not be stored as given."
78
106
  };
79
107
  var warnedNonFunction = /* @__PURE__ */ new WeakSet();
80
108
  function copyDetail(detail) {
@@ -976,6 +1004,29 @@ async function setupDatabase(db, prefix) {
976
1004
  ON ${prefix}source_ref_index (entity_id, source_hash)
977
1005
  WHERE deleted_at IS NULL;
978
1006
 
1007
+ -- source_documents / source_passages: the source store (specs/source-store \xA73).
1008
+ -- New tables only; hard delete, so no deleted_at and both UNIQUE indexes are plain.
1009
+ -- Passage text is not stored: offsets (UTF-16 code units) slice source_documents.text.
1010
+ CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
1011
+ id TEXT PRIMARY KEY,
1012
+ entity_id TEXT NOT NULL,
1013
+ source_ref TEXT NOT NULL,
1014
+ source_hash TEXT NOT NULL,
1015
+ text TEXT NOT NULL,
1016
+ text_hash TEXT NOT NULL,
1017
+ char_count INTEGER NOT NULL,
1018
+ created_at INTEGER NOT NULL
1019
+ );
1020
+
1021
+ CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
1022
+ id TEXT PRIMARY KEY,
1023
+ entity_id TEXT NOT NULL,
1024
+ document_id TEXT NOT NULL,
1025
+ seq INTEGER NOT NULL,
1026
+ start_offset INTEGER NOT NULL,
1027
+ end_offset INTEGER NOT NULL
1028
+ );
1029
+
979
1030
  CREATE TABLE IF NOT EXISTS ${prefix}tasks (
980
1031
  id TEXT PRIMARY KEY,
981
1032
  entity_id TEXT NOT NULL,
@@ -1102,6 +1153,8 @@ async function setupDatabase(db, prefix) {
1102
1153
  `);
1103
1154
  await createOkfV02IndexesIfColumnsExist(db, prefix);
1104
1155
  await createTemporalIndexesIfColumnsExist(db, prefix);
1156
+ await createSourcePassageIndexesIfColumnsExist(db, prefix);
1157
+ await createSourceDocumentIndexesIfColumnsExist(db, prefix);
1105
1158
  await createResurrectTrigger(db, prefix);
1106
1159
  }
1107
1160
  var EMBED_MARKER_COLUMNS = ["embedding_failed_at", "embedding_failure_kind", "embedding_attempts"];
@@ -1168,6 +1221,22 @@ async function createTemporalIndexesIfColumnsExist(db, prefix) {
1168
1221
  );
1169
1222
  }
1170
1223
  }
1224
+ async function createSourcePassageIndexesIfColumnsExist(db, prefix) {
1225
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}source_passages)`);
1226
+ const names = new Set(cols.map((c) => c.name));
1227
+ if (!names.has("document_id") || !names.has("entity_id")) return;
1228
+ await db.execAsync(`
1229
+ CREATE INDEX IF NOT EXISTS ${prefix}idx_source_passages_doc ON ${prefix}source_passages (document_id, seq);
1230
+ CREATE INDEX IF NOT EXISTS ${prefix}idx_source_passages_entity ON ${prefix}source_passages (entity_id);`);
1231
+ }
1232
+ async function createSourceDocumentIndexesIfColumnsExist(db, prefix) {
1233
+ const cols = await db.getAllAsync(`PRAGMA table_info(${prefix}source_documents)`);
1234
+ const names = new Set(cols.map((c) => c.name));
1235
+ if (!names.has("entity_id") || !names.has("source_ref") || !names.has("source_hash")) return;
1236
+ await db.execAsync(`
1237
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref ON ${prefix}source_documents (entity_id, source_ref);
1238
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash ON ${prefix}source_documents (entity_id, source_hash);`);
1239
+ }
1171
1240
 
1172
1241
  // src/services/search/fts5Sql.ts
1173
1242
  var FTS5_STATE_KEY = "fts5_index_state";
@@ -1305,6 +1374,38 @@ function sweepChunkSql(p) {
1305
1374
  `DELETE FROM ${p}fts_map WHERE fts_rowid IN (${orphans})`
1306
1375
  ];
1307
1376
  }
1377
+ function passageFtsTriggerNames(p) {
1378
+ return [`${p}source_passages_fts_ai`, `${p}source_passages_fts_ad`];
1379
+ }
1380
+ function passageFtsTablesDdl(p) {
1381
+ return `
1382
+ CREATE VIRTUAL TABLE IF NOT EXISTS ${p}source_passages_fts USING fts5(
1383
+ passage_id UNINDEXED, entity_id UNINDEXED, doc_id UNINDEXED, text,
1384
+ tokenize = 'porter unicode61'
1385
+ );
1386
+ CREATE TABLE IF NOT EXISTS ${p}source_passages_fts_map (
1387
+ fts_rowid INTEGER PRIMARY KEY,
1388
+ passage_id TEXT NOT NULL UNIQUE,
1389
+ doc_id TEXT NOT NULL
1390
+ );
1391
+ CREATE INDEX IF NOT EXISTS ${p}source_passages_fts_map_doc ON ${p}source_passages_fts_map(doc_id);
1392
+ CREATE TABLE IF NOT EXISTS ${p}source_passages_fts_pending (
1393
+ seq INTEGER PRIMARY KEY,
1394
+ entity_id TEXT NOT NULL,
1395
+ doc_id TEXT NOT NULL
1396
+ );
1397
+ CREATE INDEX IF NOT EXISTS ${p}source_passages_fts_pending_doc ON ${p}source_passages_fts_pending(doc_id);`;
1398
+ }
1399
+ function passageFtsTriggersDdl(p) {
1400
+ const [ai, ad] = passageFtsTriggerNames(p);
1401
+ return `
1402
+ CREATE TRIGGER IF NOT EXISTS ${ai} AFTER INSERT ON ${p}source_passages BEGIN
1403
+ INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id) VALUES (NEW.entity_id, NEW.document_id);
1404
+ END;
1405
+ CREATE TRIGGER IF NOT EXISTS ${ad} AFTER DELETE ON ${p}source_passages BEGIN
1406
+ INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id) VALUES (OLD.entity_id, OLD.document_id);
1407
+ END;`;
1408
+ }
1308
1409
 
1309
1410
  // src/db/migrations.ts
1310
1411
  var MIGRATIONS = [
@@ -1610,6 +1711,57 @@ var MIGRATIONS = [
1610
1711
  await db.execAsync(`ALTER TABLE ${prefix}entries ADD COLUMN source_pointer TEXT`);
1611
1712
  }
1612
1713
  }
1714
+ },
1715
+ {
1716
+ version: 17,
1717
+ description: "add_source_store",
1718
+ run: async (db, prefix) => {
1719
+ const expected = {
1720
+ source_documents: ["id", "entity_id", "source_ref", "source_hash", "text", "text_hash", "char_count", "created_at"],
1721
+ source_passages: ["id", "entity_id", "document_id", "seq", "start_offset", "end_offset"]
1722
+ };
1723
+ for (const [table, want] of Object.entries(expected)) {
1724
+ const full = `${prefix}${table}`;
1725
+ const cols = (await db.getAllAsync(`PRAGMA table_info(${full})`)).map((c) => c.name);
1726
+ if (cols.length === 0) continue;
1727
+ const same = cols.length === want.length && want.every((c) => cols.includes(c));
1728
+ if (!same) {
1729
+ throw new Error(
1730
+ `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().`
1731
+ );
1732
+ }
1733
+ const row = await db.getFirstAsync(`SELECT COUNT(*) AS n FROM ${full}`);
1734
+ if (row && row.n > 0) {
1735
+ throw new Error(
1736
+ `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().`
1737
+ );
1738
+ }
1739
+ }
1740
+ await db.execAsync(
1741
+ `CREATE TABLE IF NOT EXISTS ${prefix}source_documents (
1742
+ id TEXT PRIMARY KEY,
1743
+ entity_id TEXT NOT NULL,
1744
+ source_ref TEXT NOT NULL,
1745
+ source_hash TEXT NOT NULL,
1746
+ text TEXT NOT NULL,
1747
+ text_hash TEXT NOT NULL,
1748
+ char_count INTEGER NOT NULL,
1749
+ created_at INTEGER NOT NULL
1750
+ );
1751
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_ref
1752
+ ON ${prefix}source_documents (entity_id, source_ref);
1753
+ CREATE UNIQUE INDEX IF NOT EXISTS ${prefix}idx_source_documents_hash
1754
+ ON ${prefix}source_documents (entity_id, source_hash);
1755
+ CREATE TABLE IF NOT EXISTS ${prefix}source_passages (
1756
+ id TEXT PRIMARY KEY,
1757
+ entity_id TEXT NOT NULL,
1758
+ document_id TEXT NOT NULL,
1759
+ seq INTEGER NOT NULL,
1760
+ start_offset INTEGER NOT NULL,
1761
+ end_offset INTEGER NOT NULL
1762
+ );`
1763
+ );
1764
+ }
1613
1765
  }
1614
1766
  ];
1615
1767
  async function createLegacySourceTypeIndex(db, prefix) {
@@ -2188,10 +2340,15 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2188
2340
  const chunk = ids.slice(i, i + this.chunkSize);
2189
2341
  const placeholders = chunk.map(() => "?").join(",");
2190
2342
  const chunkRows = await executor.getAllAsync(
2191
- `SELECT id, entity_id, updated_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
2343
+ `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}entries WHERE id IN (${placeholders})`,
2192
2344
  chunk
2193
2345
  );
2194
- rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));
2346
+ rows.push(...chunkRows.map((row) => ({
2347
+ id: row.id,
2348
+ entity_id: row.entity_id,
2349
+ updated_at: Number(row.updated_at),
2350
+ deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
2351
+ })));
2195
2352
  }
2196
2353
  return rows;
2197
2354
  }
@@ -2363,22 +2520,25 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2363
2520
  * Fetch IDs + entity_ids of soft-deleted rows older than cutoff for a given entity.
2364
2521
  * Used by runPrune().
2365
2522
  */
2366
- async getPrunableMetadata(entityId, cutoff, tx) {
2523
+ async getPrunableMetadata(entityId, cutoff, tx, opts) {
2367
2524
  const executor = this.getExecutor(tx);
2525
+ const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
2526
+ const args = opts?.noCutoff ? [entityId] : [entityId, cutoff];
2368
2527
  return executor.getAllAsync(
2369
2528
  `SELECT id, entity_id FROM ${this.prefix}entries
2370
- WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
2371
- [entityId, cutoff]
2529
+ WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
2530
+ args
2372
2531
  );
2373
2532
  }
2374
2533
  /**
2375
2534
  * Fetch all non-deleted entries for an entity, ordered by updated_at DESC.
2376
2535
  * Used by _getFullBundle().
2377
2536
  */
2378
- async findAllByEntityId(entityId, tx) {
2537
+ async findAllByEntityId(entityId, tx, opts) {
2379
2538
  const executor = this.getExecutor(tx);
2539
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
2380
2540
  const rows = await executor.getAllAsync(
2381
- `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,
2541
+ `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
2382
2542
  [entityId]
2383
2543
  );
2384
2544
  return rows.map(mapRowToFact);
@@ -2458,10 +2618,11 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2458
2618
  * Fetch all non-deleted entries for an entity with embedding blobs preserved.
2459
2619
  * Used by ImportExportService for export/import round-tripping.
2460
2620
  */
2461
- async findAllByEntityIdWithBlobs(entityId, tx) {
2621
+ async findAllByEntityIdWithBlobs(entityId, tx, opts) {
2462
2622
  const executor = this.getExecutor(tx);
2623
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
2463
2624
  const rows = await executor.getAllAsync(
2464
- `SELECT * FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC`,
2625
+ `SELECT * FROM ${this.prefix}entries WHERE entity_id = ?${live} ORDER BY updated_at DESC`,
2465
2626
  [entityId]
2466
2627
  );
2467
2628
  return rows.map(mapRowToFactWithBlobs);
@@ -2532,20 +2693,22 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2532
2693
  for (let i = 0; i < ids.length; i += chunkSize) {
2533
2694
  const chunk = ids.slice(i, i + chunkSize);
2534
2695
  const placeholders = chunk.map(() => "?").join(",");
2696
+ const cutoffPredicate = opts.noCutoff ? "" : " AND deleted_at <= ?";
2697
+ const delArgs = opts.noCutoff ? [entityId, ...chunk] : [entityId, cutoff, ...chunk];
2535
2698
  const deleted = (await executor.getAllAsync(
2536
- `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ? AND id IN (${placeholders})${guard} RETURNING id`,
2537
- [entityId, cutoff, ...chunk]
2538
- )).map((r) => r.id);
2699
+ `DELETE FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate} AND id IN (${placeholders})${guard} RETURNING id, deleted_at`,
2700
+ delArgs
2701
+ )).map((r) => ({ id: r.id, deleted_at: typeof r.deleted_at === "number" ? r.deleted_at : Number(r.deleted_at) }));
2539
2702
  totalChanges += deleted.length;
2540
- opts.deletedIds?.push(...deleted);
2703
+ opts.deletedIds?.push(...deleted.map((r) => r.id));
2541
2704
  if (deleted.length > 0) {
2542
- for (const id of deleted) {
2705
+ for (const row of deleted) {
2543
2706
  await this.outbox.push({
2544
2707
  entityId,
2545
2708
  tableName: "entries",
2546
- recordId: id,
2709
+ recordId: row.id,
2547
2710
  operation: "DELETE",
2548
- payload: { id, entity_id: entityId, deleted_at: cutoff }
2711
+ payload: { id: row.id, entity_id: entityId, deleted_at: row.deleted_at }
2549
2712
  }, tx);
2550
2713
  }
2551
2714
  }
@@ -2714,6 +2877,19 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2714
2877
  );
2715
2878
  return new Set(rows.map((r) => r.id));
2716
2879
  }
2880
+ /**
2881
+ * Depth-aware supersession walk for chain forget (spec forget-erasure §3).
2882
+ * Probes `maxDepth + 1` levels so a chain longer than the cap is detectable;
2883
+ * the returned ids are capped to `maxDepth` per direction (successors nearest first; predecessors are returned farthest-first).
2884
+ * No `deleted_at` filter: soft-deleted links still carry the chain.
2885
+ */
2886
+ async findSupersessionChainWalk(entityId, factId, maxDepth, tx) {
2887
+ const { predecessors, successors } = await this.findSupersessionChainIds(entityId, factId, maxDepth + 1, tx);
2888
+ const truncated = predecessors.some((r) => r.depth > maxDepth) || successors.some((r) => r.depth > maxDepth);
2889
+ const pred = predecessors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
2890
+ const succ = successors.filter((r) => r.depth <= maxDepth).map((r) => r.id);
2891
+ return { ids: Array.from(/* @__PURE__ */ new Set([...succ, ...pred])), truncated };
2892
+ }
2717
2893
  async findSupersessionChainIds(entityId, factId, maxDepth, tx) {
2718
2894
  const executor = this.getExecutor(tx);
2719
2895
  const successors = await executor.getAllAsync(
@@ -2724,7 +2900,7 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2724
2900
  JOIN ${this.prefix}entries e ON e.id = fwd.id AND e.entity_id = ?
2725
2901
  WHERE e.superseded_by IS NOT NULL AND fwd.depth < ?
2726
2902
  )
2727
- SELECT id FROM fwd ORDER BY depth ASC`,
2903
+ SELECT id, depth FROM fwd ORDER BY depth ASC`,
2728
2904
  [factId, entityId, entityId, maxDepth]
2729
2905
  );
2730
2906
  const predecessors = await executor.getAllAsync(
@@ -2735,10 +2911,10 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
2735
2911
  JOIN ${this.prefix}entries e ON e.entity_id = ? AND e.superseded_by = bwd.id
2736
2912
  WHERE bwd.depth < ?
2737
2913
  )
2738
- SELECT id FROM bwd ORDER BY depth DESC`,
2914
+ SELECT id, depth FROM bwd ORDER BY depth DESC`,
2739
2915
  [entityId, factId, entityId, maxDepth]
2740
2916
  );
2741
- const drop = (ids) => ids.map((r) => r.id).filter((id) => id !== factId);
2917
+ const drop = (rows) => rows.filter((r) => r.id !== factId);
2742
2918
  return { predecessors: drop(predecessors), successors: drop(successors) };
2743
2919
  }
2744
2920
  async findExpiredIds(entityId, cutoff, tx) {
@@ -3028,20 +3204,26 @@ var _EntryRepository = class _EntryRepository extends BaseRepository {
3028
3204
  FROM ${this.prefix}entries
3029
3205
  WHERE entity_id = ? AND deleted_at IS NULL AND source_ref IS NOT NULL
3030
3206
  )
3031
- SELECT source_ref,
3032
- source_hash AS source_hash,
3033
- fact_count AS fact_count,
3034
- updated_at AS last_ingested_at
3207
+ SELECT ranked.source_ref,
3208
+ ranked.source_hash AS source_hash,
3209
+ ranked.fact_count AS fact_count,
3210
+ ranked.updated_at AS last_ingested_at,
3211
+ d.source_hash AS stored_hash,
3212
+ d.char_count AS stored_chars
3035
3213
  FROM ranked
3036
- WHERE rn = 1
3037
- ORDER BY source_ref COLLATE BINARY`,
3038
- [entityId]
3214
+ LEFT JOIN ${this.prefix}source_documents d
3215
+ ON d.entity_id = ? AND d.source_ref = ranked.source_ref
3216
+ WHERE ranked.rn = 1
3217
+ ORDER BY ranked.source_ref COLLATE BINARY`,
3218
+ [entityId, entityId]
3039
3219
  );
3040
3220
  return rows.map((r) => ({
3041
3221
  sourceRef: r.source_ref,
3042
3222
  sourceHash: r.source_hash,
3043
3223
  factCount: Number(r.fact_count),
3044
- lastIngestedAt: Number(r.last_ingested_at)
3224
+ lastIngestedAt: Number(r.last_ingested_at),
3225
+ // Spec source-store §4: keyed on the ref's own (sourceRef, sourceHash) pair.
3226
+ stored: r.stored_hash === null || r.stored_hash === void 0 ? null : r.stored_hash === r.source_hash ? { charCount: Number(r.stored_chars) } : { charCount: Number(r.stored_chars), staleHash: true }
3045
3227
  }));
3046
3228
  }
3047
3229
  /**
@@ -3563,10 +3745,15 @@ var TaskRepository = class extends BaseRepository {
3563
3745
  const chunk = ids.slice(i, i + chunkSize);
3564
3746
  const placeholders = chunk.map(() => "?").join(",");
3565
3747
  const chunkRows = await executor.getAllAsync(
3566
- `SELECT id, entity_id, updated_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
3748
+ `SELECT id, entity_id, updated_at, deleted_at FROM ${this.prefix}tasks WHERE id IN (${placeholders})`,
3567
3749
  chunk
3568
3750
  );
3569
- rows.push(...chunkRows.map((row) => ({ id: row.id, entity_id: row.entity_id, updated_at: Number(row.updated_at) })));
3751
+ rows.push(...chunkRows.map((row) => ({
3752
+ id: row.id,
3753
+ entity_id: row.entity_id,
3754
+ updated_at: Number(row.updated_at),
3755
+ deleted_at: row.deleted_at == null ? null : Number(row.deleted_at)
3756
+ })));
3570
3757
  }
3571
3758
  return rows;
3572
3759
  }
@@ -3729,10 +3916,11 @@ var TaskRepository = class extends BaseRepository {
3729
3916
  * Fetch all non-deleted tasks for an entity, ordered by priority DESC, created_at ASC.
3730
3917
  * Used by _getFullBundle().
3731
3918
  */
3732
- async findAllByEntityId(entityId, tx) {
3919
+ async findAllByEntityId(entityId, tx, opts) {
3733
3920
  const executor = this.getExecutor(tx);
3921
+ const live = opts?.includeDeleted ? "" : " AND deleted_at IS NULL";
3734
3922
  const rows = await executor.getAllAsync(
3735
- `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NULL ORDER BY priority DESC, created_at ASC`,
3923
+ `SELECT * FROM ${this.prefix}tasks WHERE entity_id = ?${live} ORDER BY priority DESC, created_at ASC`,
3736
3924
  [entityId]
3737
3925
  );
3738
3926
  return rows.map(mapRowToTask);
@@ -3741,16 +3929,19 @@ var TaskRepository = class extends BaseRepository {
3741
3929
  * Bulk delete pruned tasks (already soft-deleted) by cutoff date.
3742
3930
  * Used by runPrune(). Returns number of deleted rows.
3743
3931
  */
3744
- async bulkDeletePruned(entityId, cutoff, tx) {
3932
+ async bulkDeletePruned(entityId, cutoff, tx, opts) {
3745
3933
  const executor = this.getExecutor(tx);
3934
+ const cutoffPredicate = opts?.noCutoff ? "" : " AND deleted_at <= ?";
3935
+ const selectArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
3746
3936
  const rowsToDelete = await executor.getAllAsync(
3747
- `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
3748
- [entityId, cutoff]
3937
+ `SELECT id, deleted_at FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
3938
+ selectArgs
3749
3939
  );
3750
3940
  if (rowsToDelete.length === 0) return 0;
3941
+ const deleteArgs = opts?.noCutoff ? [entityId] : [entityId, cutoff];
3751
3942
  const result = await executor.runAsync(
3752
- `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL AND deleted_at <= ?`,
3753
- [entityId, cutoff]
3943
+ `DELETE FROM ${this.prefix}tasks WHERE entity_id = ? AND deleted_at IS NOT NULL${cutoffPredicate}`,
3944
+ deleteArgs
3754
3945
  );
3755
3946
  for (const row of rowsToDelete) {
3756
3947
  await this.outbox.push(
@@ -4416,6 +4607,12 @@ function entitySummaryMetaKey(entityId) {
4416
4607
  return `entity_summary:${entityId}`;
4417
4608
  }
4418
4609
  var START_OF_LOG_WATERMARK = Object.freeze({ at: Number.MIN_SAFE_INTEGER, id: "" });
4610
+ var CheckpointIncompleteError = class extends Error {
4611
+ constructor() {
4612
+ super(...arguments);
4613
+ this.code = "erase_checkpoint_incomplete";
4614
+ }
4615
+ };
4419
4616
  var MetadataRepository = class extends BaseRepository {
4420
4617
  // CHECKPOINTS TABLE METHODS
4421
4618
  async getCheckpoint(entityId, tx) {
@@ -4534,9 +4731,25 @@ var MetadataRepository = class extends BaseRepository {
4534
4731
  );
4535
4732
  return row?.sql ?? null;
4536
4733
  }
4734
+ /**
4735
+ * `PRAGMA wal_checkpoint(TRUNCATE)`, verified: `busy !== 0` or
4736
+ * `log !== checkpointed` means frames survive in the WAL, so a deleted
4737
+ * row's bytes may still be on disk. Non-WAL reports (0,-1,-1) = complete.
4738
+ */
4739
+ async checkpointTruncateVerified() {
4740
+ const row = await this.db.getFirstAsync(
4741
+ `PRAGMA wal_checkpoint(TRUNCATE)`
4742
+ );
4743
+ if (row && (row.busy !== 0 || row.log !== row.checkpointed)) {
4744
+ throw new CheckpointIncompleteError(
4745
+ `wal_checkpoint(TRUNCATE) incomplete (busy=${row?.busy}, log=${row?.log}, checkpointed=${row?.checkpointed})`
4746
+ );
4747
+ }
4748
+ }
4537
4749
  async vacuum() {
4538
- await this.db.execAsync(`PRAGMA wal_checkpoint(TRUNCATE)`);
4750
+ await this.checkpointTruncateVerified();
4539
4751
  await this.db.execAsync(`VACUUM`);
4752
+ await this.checkpointTruncateVerified();
4540
4753
  }
4541
4754
  /**
4542
4755
  * Returns the set of distinct `entity_id` values across entries/tasks/events.
@@ -4546,9 +4759,36 @@ var MetadataRepository = class extends BaseRepository {
4546
4759
  * soft-deleted, so the host's maintenance sweep can visit such
4547
4760
  * "decommissioned-scope" namespaces and reap the soft-deleted rows. Sorting
4548
4761
  * is `entity_id COLLATE BINARY` for stable, locale-independent ordering.
4762
+ *
4763
+ * With `opts.softDeletedAtOrBefore` the walk is narrowed to entities holding
4764
+ * at least one soft-deleted entry or task with `deleted_at` at or before
4765
+ * that cutoff (erase's hard-delete walk, forget-erasure spec §2). Without
4766
+ * the option the host-facing semantics above are unchanged.
4549
4767
  */
4550
- async getDistinctEntityIds(tx) {
4768
+ async getDistinctEntityIds(tx, opts) {
4551
4769
  const executor = this.getExecutor(tx);
4770
+ if (opts?.softDeletedAll) {
4771
+ const rows2 = await executor.getAllAsync(
4772
+ `SELECT DISTINCT entity_id FROM (
4773
+ SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL
4774
+ UNION
4775
+ SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL
4776
+ ) ORDER BY entity_id COLLATE BINARY`
4777
+ );
4778
+ return rows2.map((r) => r.entity_id);
4779
+ }
4780
+ if (opts?.softDeletedAtOrBefore !== void 0) {
4781
+ const cutoff = opts.softDeletedAtOrBefore;
4782
+ const rows2 = await executor.getAllAsync(
4783
+ `SELECT DISTINCT entity_id FROM (
4784
+ SELECT entity_id FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL AND deleted_at <= ?
4785
+ UNION
4786
+ SELECT entity_id FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL AND deleted_at <= ?
4787
+ ) ORDER BY entity_id COLLATE BINARY`,
4788
+ [cutoff, cutoff]
4789
+ );
4790
+ return rows2.map((r) => r.entity_id);
4791
+ }
4552
4792
  const rows = await executor.getAllAsync(
4553
4793
  `SELECT DISTINCT entity_id FROM (
4554
4794
  SELECT entity_id FROM ${this.prefix}entries
@@ -4693,6 +4933,10 @@ var UnavailableIndexStrategy = class {
4693
4933
  }
4694
4934
  async drain(_opts) {
4695
4935
  }
4936
+ /** Degraded like everything else: no passages, no throw (spec source-store section 7). */
4937
+ async searchPassages() {
4938
+ return [];
4939
+ }
4696
4940
  };
4697
4941
 
4698
4942
  // src/services/SearchService.ts
@@ -4914,6 +5158,91 @@ var _SearchService = class _SearchService {
4914
5158
  const results = finiteResults(await this.indexStrategy.search(query, { entityIds, limit }));
4915
5159
  return results.sort((a, b) => this._compareSearchResults(a, b)).slice(0, limit);
4916
5160
  }
5161
+ /**
5162
+ * Post-commit passage index sync (spec source-store section 6). FTS5: drains the
5163
+ * passage ledger (per document, entity-scoped when given). MiniSearch: reloads
5164
+ * the entity's stored passages (all stored entities when omitted: the open-time
5165
+ * pass). Serialized on the sync chain; never rejects, like sync().
5166
+ */
5167
+ async syncPassages(db, prefix, entityId, deadline) {
5168
+ const s = this.indexStrategy;
5169
+ if (!s.drainPassages && !s.reindexSourcePassages) return;
5170
+ const work = this.syncChain.then(async () => {
5171
+ try {
5172
+ if (s.drainPassages) await s.drainPassages({ entityId, deadline });
5173
+ else await s.reindexSourcePassages(db, prefix, entityId);
5174
+ } catch (err) {
5175
+ console.warn(`[WikiMemory] passage index sync failed for ${entityId ?? "*"}:`, err);
5176
+ }
5177
+ });
5178
+ this.syncChain = work;
5179
+ return work;
5180
+ }
5181
+ /** Run `fn` on the sync chain; the caller sees its rejection, the chain never rejects. */
5182
+ chainSurfaced(fn) {
5183
+ const work = this.syncChain.then(fn);
5184
+ this.syncChain = work.then(() => void 0, () => void 0);
5185
+ return work;
5186
+ }
5187
+ /** True when the active strategy has both strict erase drains (FTS5); false for MiniSearch / Unavailable. */
5188
+ hasStrictDrain() {
5189
+ const s = this.indexStrategy;
5190
+ return typeof s.drainPassagesStrict === "function" && typeof s.drainEntriesLedgerStrict === "function";
5191
+ }
5192
+ /** Erase step 3: chained passage drain, no deadline, errors surfaced. */
5193
+ drainPassagesSurfaced() {
5194
+ const s = this.indexStrategy;
5195
+ if (!s.drainPassagesStrict) return this.chainSurfaced(async () => {
5196
+ });
5197
+ return this.chainSurfaced(() => s.drainPassagesStrict());
5198
+ }
5199
+ /** Erase step 4: listed retired FTS tables (empty for strategies without any). */
5200
+ async retiredTables() {
5201
+ const s = this.indexStrategy;
5202
+ return s.retiredTables ? s.retiredTables() : [];
5203
+ }
5204
+ /** True when the active strategy can DROP retired tables (FTS5); false for MiniSearch / Unavailable. */
5205
+ canReclaimRetired() {
5206
+ return typeof this.indexStrategy.reclaimRetiredToCompletion === "function";
5207
+ }
5208
+ /** Erase step 3: store-wide entries-side fts_pending drain on the sync chain, no deadline, errors surfaced. */
5209
+ drainEntriesLedgerSurfaced() {
5210
+ const s = this.indexStrategy;
5211
+ if (!s.drainEntriesLedgerStrict) return this.chainSurfaced(async () => {
5212
+ });
5213
+ return this.chainSurfaced(() => s.drainEntriesLedgerStrict());
5214
+ }
5215
+ /** Erase step 4: reclaim retired tables to completion; errors surfaced. */
5216
+ reclaimRetiredSurfaced() {
5217
+ const s = this.indexStrategy;
5218
+ if (!s.reclaimRetiredToCompletion) return this.chainSurfaced(async () => {
5219
+ });
5220
+ return this.chainSurfaced(() => s.reclaimRetiredToCompletion());
5221
+ }
5222
+ /** Erase step 7: FTS optimize on every FTS table that exists. */
5223
+ optimizeSurfaced() {
5224
+ const s = this.indexStrategy;
5225
+ if (!s.optimizeFts) return this.chainSurfaced(async () => {
5226
+ });
5227
+ return this.chainSurfaced(() => s.optimizeFts());
5228
+ }
5229
+ /** `erase({ rebuild: true })` wiring point; the orchestration (T6) calls it. */
5230
+ rebuildSurfaced() {
5231
+ const s = this.indexStrategy;
5232
+ if (!s.rebuildForErase) return this.chainSurfaced(async () => {
5233
+ });
5234
+ return this.chainSurfaced(() => s.rebuildForErase());
5235
+ }
5236
+ /**
5237
+ * Stored-source passage search for ONE entity (spec source-store section 7:
5238
+ * ranking and caps are per entity). Rides the active strategy; a strategy
5239
+ * without passage search yields none.
5240
+ */
5241
+ async searchPassages(query, entityId, limit) {
5242
+ if (!this.indexStrategy.searchPassages) return [];
5243
+ const hits = await this.indexStrategy.searchPassages(query, { entityIds: [entityId], limit });
5244
+ return hits.filter((h) => Number.isFinite(h.score) && h.entity_id === entityId).slice(0, limit);
5245
+ }
4917
5246
  /**
4918
5247
  * Pre-fetches keyword scores for candidate hydration, used during hybrid weighting.
4919
5248
  */
@@ -5036,195 +5365,360 @@ var SearchService = _SearchService;
5036
5365
  function finiteResults(results) {
5037
5366
  return results.every((r) => Number.isFinite(r.score)) ? results : results.filter((r) => Number.isFinite(r.score));
5038
5367
  }
5039
- var MiniSearchIndexStrategy = class {
5040
- constructor() {
5041
- /**
5042
- * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
5043
- * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
5044
- * not see this map; it only sees `hasIndexedEntity`. The previous
5045
- * `miniSearchEntryIdsByEntity` lived on `SearchService`.
5046
- */
5047
- this.entryIdsByEntity = /* @__PURE__ */ new Map();
5048
- /**
5049
- * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
5050
- * decide which ids are owned by `entityId` (the only safe membership test
5051
- * — a rebuild that failed between its discard pass and the set replacement
5052
- * can leave the forward set claiming ids the MiniSearch instance does not
5053
- * hold). The pre-extraction `syncEntries` deleted from one set per id, not
5054
- * from every entity's set.
5055
- */
5056
- this.entityIdById = /* @__PURE__ */ new Map();
5057
- this.index = this.createIndex();
5368
+
5369
+ // src/utils/passageCutter.ts
5370
+ var MAX_PASSAGE_UNITS = 12e3;
5371
+ var WHITESPACE = /\s/;
5372
+ function isHigh(code) {
5373
+ return code >= 55296 && code <= 56319;
5374
+ }
5375
+ function isLow(code) {
5376
+ return code >= 56320 && code <= 57343;
5377
+ }
5378
+ function cutPassages(text, maxUnits = MAX_PASSAGE_UNITS) {
5379
+ const limit = Math.max(2, Math.floor(maxUnits));
5380
+ const spans = [];
5381
+ let start = 0;
5382
+ while (start < text.length) {
5383
+ if (text.length - start <= limit) {
5384
+ spans.push({ start, end: text.length });
5385
+ break;
5386
+ }
5387
+ let end = start + limit;
5388
+ let cut = -1;
5389
+ for (let i = end - 1; i > start; i--) {
5390
+ if (WHITESPACE.test(text[i])) {
5391
+ cut = i + 1;
5392
+ break;
5393
+ }
5394
+ }
5395
+ if (cut > start) {
5396
+ end = cut;
5397
+ } else if (isHigh(text.charCodeAt(end - 1)) && isLow(text.charCodeAt(end))) {
5398
+ end -= 1;
5399
+ }
5400
+ spans.push({ start, end });
5401
+ start = end;
5058
5402
  }
5059
- /**
5060
- * Build a fresh MiniSearch instance with the project's index options.
5061
- * Called from the constructor and from `replaceAll`. We do not use
5062
- * `removeAll()` on an existing instance because that empties the index but
5063
- * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
5064
- * `syncEntries`' conditional vacuum early after a clear.
5065
- */
5066
- createIndex() {
5067
- return new MiniSearch__default.default({
5068
- fields: ["title", "body", "tags"],
5069
- storeFields: ["entity_id"],
5070
- // Vacuuming is driven explicitly at the end of each serialized rebuild
5071
- // (see SearchService.syncEntries). Auto-vacuum fires on its own
5072
- // schedule, asynchronously with respect to the caller, and traversing
5073
- // the tree mid-rebuild is what threw the uncaught TypeError in
5074
- // MiniSearch.performVacuuming (#64).
5075
- autoVacuum: false,
5076
- searchOptions: {
5077
- boost: { title: 2 },
5078
- fuzzy: 0.2,
5079
- prefix: true
5403
+ return spans;
5404
+ }
5405
+
5406
+ // src/utils/sha256.ts
5407
+ var K = new Uint32Array([
5408
+ 1116352408,
5409
+ 1899447441,
5410
+ 3049323471,
5411
+ 3921009573,
5412
+ 961987163,
5413
+ 1508970993,
5414
+ 2453635748,
5415
+ 2870763221,
5416
+ 3624381080,
5417
+ 310598401,
5418
+ 607225278,
5419
+ 1426881987,
5420
+ 1925078388,
5421
+ 2162078206,
5422
+ 2614888103,
5423
+ 3248222580,
5424
+ 3835390401,
5425
+ 4022224774,
5426
+ 264347078,
5427
+ 604807628,
5428
+ 770255983,
5429
+ 1249150122,
5430
+ 1555081692,
5431
+ 1996064986,
5432
+ 2554220882,
5433
+ 2821834349,
5434
+ 2952996808,
5435
+ 3210313671,
5436
+ 3336571891,
5437
+ 3584528711,
5438
+ 113926993,
5439
+ 338241895,
5440
+ 666307205,
5441
+ 773529912,
5442
+ 1294757372,
5443
+ 1396182291,
5444
+ 1695183700,
5445
+ 1986661051,
5446
+ 2177026350,
5447
+ 2456956037,
5448
+ 2730485921,
5449
+ 2820302411,
5450
+ 3259730800,
5451
+ 3345764771,
5452
+ 3516065817,
5453
+ 3600352804,
5454
+ 4094571909,
5455
+ 275423344,
5456
+ 430227734,
5457
+ 506948616,
5458
+ 659060556,
5459
+ 883997877,
5460
+ 958139571,
5461
+ 1322822218,
5462
+ 1537002063,
5463
+ 1747873779,
5464
+ 1955562222,
5465
+ 2024104815,
5466
+ 2227730452,
5467
+ 2361852424,
5468
+ 2428436474,
5469
+ 2756734187,
5470
+ 3204031479,
5471
+ 3329325298
5472
+ ]);
5473
+ var rotr = (x, n) => x >>> n | x << 32 - n;
5474
+ var IV = [1779033703, 3144134277, 1013904242, 2773480762, 1359893119, 2600822924, 528734635, 1541459225];
5475
+ function compress(H, W, view, off) {
5476
+ for (let t = 0; t < 16; t++) W[t] = view.getUint32(off + t * 4);
5477
+ for (let t = 16; t < 64; t++) {
5478
+ const s0 = rotr(W[t - 15], 7) ^ rotr(W[t - 15], 18) ^ W[t - 15] >>> 3;
5479
+ const s1 = rotr(W[t - 2], 17) ^ rotr(W[t - 2], 19) ^ W[t - 2] >>> 10;
5480
+ W[t] = W[t - 16] + s0 + W[t - 7] + s1 >>> 0;
5481
+ }
5482
+ 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];
5483
+ for (let t = 0; t < 64; t++) {
5484
+ const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
5485
+ const ch = e & f ^ ~e & g;
5486
+ const t1 = h + S1 + ch + K[t] + W[t] >>> 0;
5487
+ const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);
5488
+ const maj = a & b ^ a & c ^ b & c;
5489
+ const t2 = S0 + maj >>> 0;
5490
+ h = g;
5491
+ g = f;
5492
+ f = e;
5493
+ e = d + t1 >>> 0;
5494
+ d = c;
5495
+ c = b;
5496
+ b = a;
5497
+ a = t1 + t2 >>> 0;
5498
+ }
5499
+ H[0] = H[0] + a >>> 0;
5500
+ H[1] = H[1] + b >>> 0;
5501
+ H[2] = H[2] + c >>> 0;
5502
+ H[3] = H[3] + d >>> 0;
5503
+ H[4] = H[4] + e >>> 0;
5504
+ H[5] = H[5] + f >>> 0;
5505
+ H[6] = H[6] + g >>> 0;
5506
+ H[7] = H[7] + h >>> 0;
5507
+ }
5508
+ function sha256(bytes) {
5509
+ const H = new Uint32Array(IV);
5510
+ const W = new Uint32Array(64);
5511
+ const whole = bytes.length - bytes.length % 64;
5512
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
5513
+ for (let off = 0; off < whole; off += 64) compress(H, W, view, off);
5514
+ const rest = bytes.subarray(whole);
5515
+ const bitLen = bytes.length * 8;
5516
+ const padded = new Uint8Array(rest.length + 9 + 63 >> 6 << 6);
5517
+ padded.set(rest);
5518
+ padded[rest.length] = 128;
5519
+ const pv = new DataView(padded.buffer);
5520
+ pv.setUint32(padded.length - 8, Math.floor(bitLen / 4294967296));
5521
+ pv.setUint32(padded.length - 4, bitLen >>> 0);
5522
+ for (let off = 0; off < padded.length; off += 64) compress(H, W, pv, off);
5523
+ const out = new Uint8Array(32);
5524
+ const outView = new DataView(out.buffer);
5525
+ for (let i = 0; i < 8; i++) outView.setUint32(i * 4, H[i]);
5526
+ return out;
5527
+ }
5528
+ function utf8Encode(s) {
5529
+ const out = [];
5530
+ for (let i = 0; i < s.length; i++) {
5531
+ let cp = s.charCodeAt(i);
5532
+ if (cp >= 55296 && cp <= 56319) {
5533
+ const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
5534
+ if (next >= 56320 && next <= 57343) {
5535
+ cp = 65536 + (cp - 55296 << 10) + (next - 56320);
5536
+ i++;
5537
+ } else {
5538
+ cp = 65533;
5080
5539
  }
5081
- });
5540
+ } else if (cp >= 56320 && cp <= 57343) {
5541
+ cp = 65533;
5542
+ }
5543
+ if (cp < 128) out.push(cp);
5544
+ else if (cp < 2048) out.push(192 | cp >> 6, 128 | cp & 63);
5545
+ else if (cp < 65536) out.push(224 | cp >> 12, 128 | cp >> 6 & 63, 128 | cp & 63);
5546
+ else out.push(240 | cp >> 18, 128 | cp >> 12 & 63, 128 | cp >> 6 & 63, 128 | cp & 63);
5082
5547
  }
5083
- /**
5084
- * Incremental sync. Removes only ids currently tracked under `entityId`
5085
- * (other entities' docs are untouched), then upserts `documents` by id.
5086
- * The same id appearing in both `ids` and `documents` is discarded first
5087
- * so the upsert does not throw on a duplicate id.
5088
- *
5089
- * Every document must carry `entityId` as its `entity_id`; a mismatch is
5090
- * rejected before the write mutates anything. A tracking-only call
5091
- * (`replace(entityId, [], [])`) registers the entity as indexed, matching
5092
- * the interface contract.
5093
- *
5094
- * Atomicity: never awaits between the discard pass and `addDocuments`, so
5095
- * a concurrent `search()` sees the index wholly before or wholly after,
5096
- * never half-updated. This is the precondition the pre-extraction
5097
- * `syncEntries` kept with its "no await from here to `addAll`" comment.
5098
- */
5099
- async replace(entityId, ids, documents) {
5100
- assertOwnedBy(entityId, documents);
5101
- this.discardIds(ids, entityId);
5102
- if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
5103
- this.addDocuments(documents);
5548
+ return Uint8Array.from(out);
5549
+ }
5550
+ function sha256Hex(text) {
5551
+ let hex = "";
5552
+ for (const b of sha256(utf8Encode(text))) hex += b.toString(16).padStart(2, "0");
5553
+ return hex;
5554
+ }
5555
+
5556
+ // src/services/sourceStoreUpsert.ts
5557
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
5558
+ async function upsertStoredSource(tx, prefix, entityId, src, limits, onRefusal, opts = {}) {
5559
+ const { sourceRef, sourceHash, text } = src;
5560
+ const refuse = (code) => {
5561
+ onRefusal(code);
5562
+ return { status: "refused" };
5563
+ };
5564
+ if (text.includes("\0") || LONE_SURROGATE.test(text)) return refuse("source_store_text_not_storable");
5565
+ if (text.length > limits.maxCharsPerSource) return refuse("source_store_source_too_large");
5566
+ const textHash = sha256Hex(text);
5567
+ const charCount = text.length;
5568
+ const docs = `${prefix}source_documents`;
5569
+ const passages = `${prefix}source_passages`;
5570
+ const registry = `${prefix}source_ref_index`;
5571
+ const existing = await tx.getFirstAsync(
5572
+ `SELECT id, source_hash, text_hash, char_count, created_at FROM ${docs}
5573
+ WHERE entity_id = ? AND source_ref = ?`,
5574
+ [entityId, sourceRef]
5575
+ );
5576
+ if (opts.idempotentSamePair && existing && existing.source_hash === sourceHash) {
5577
+ if (existing.text_hash !== textHash) return refuse("source_store_hash_mismatch");
5578
+ const row = await tx.getFirstAsync(
5579
+ `SELECT COUNT(*) AS n FROM ${passages} WHERE entity_id = ? AND document_id = ?`,
5580
+ [entityId, existing.id]
5581
+ );
5582
+ return { status: "stored", charCount: existing.char_count, passageCount: row?.n ?? 0, storedAt: existing.created_at };
5104
5583
  }
5105
- /**
5106
- * Per-entity rebuild. Removes every id tracked under `entityId` (with the
5107
- * `index.has(id)` guard so a stale tracking set cannot make `discard()`
5108
- * throw), then writes `documents`. The entity stays registered as
5109
- * indexed — even when `documents` is empty — so the next `syncEntries`
5110
- * call can take the fast path. Every document must belong to `entityId`.
5111
- */
5112
- async replaceEntity(entityId, documents) {
5113
- assertOwnedBy(entityId, documents);
5114
- const previous = this.entryIdsByEntity.get(entityId);
5115
- if (previous) this.discardIds([...previous]);
5116
- this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
5117
- this.addDocuments(documents);
5584
+ const heldByStore = await tx.getFirstAsync(
5585
+ `SELECT source_ref FROM ${docs} WHERE entity_id = ? AND source_hash = ? AND source_ref <> ?`,
5586
+ [entityId, sourceHash, sourceRef]
5587
+ );
5588
+ const heldByFacts = await tx.getFirstAsync(
5589
+ `SELECT source_ref FROM ${registry}
5590
+ WHERE entity_id = ? AND source_hash = ? AND deleted_at IS NULL AND source_ref <> ?`,
5591
+ [entityId, sourceHash, sourceRef]
5592
+ );
5593
+ if (heldByStore || heldByFacts) return refuse("source_store_duplicate_hash");
5594
+ const total = await tx.getFirstAsync(
5595
+ `SELECT COALESCE(SUM(char_count), 0) AS n FROM ${docs} WHERE entity_id = ? AND source_ref <> ?`,
5596
+ [entityId, sourceRef]
5597
+ );
5598
+ if ((total?.n ?? 0) + charCount > limits.maxTotalChars) return refuse("source_store_budget_exceeded");
5599
+ if (existing) {
5600
+ await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ? AND document_id = ?`, [entityId, existing.id]);
5601
+ await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ? AND id = ?`, [entityId, existing.id]);
5602
+ }
5603
+ const id = generateId("sdoc_");
5604
+ const storedAt = typeof src.storedAt === "number" && Number.isFinite(src.storedAt) ? src.storedAt : Date.now();
5605
+ await tx.runAsync(
5606
+ `INSERT INTO ${docs} (id, entity_id, source_ref, source_hash, text, text_hash, char_count, created_at)
5607
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
5608
+ [id, entityId, sourceRef, sourceHash, text, textHash, charCount, storedAt]
5609
+ );
5610
+ const spans = cutPassages(text);
5611
+ for (let seq = 0; seq < spans.length; seq++) {
5612
+ await tx.runAsync(
5613
+ `INSERT INTO ${passages} (id, entity_id, document_id, seq, start_offset, end_offset) VALUES (?, ?, ?, ?, ?, ?)`,
5614
+ [generateId("spas_"), entityId, id, seq, spans[seq].start, spans[seq].end]
5615
+ );
5118
5616
  }
5119
- /**
5120
- * Global rebuild / clear. Replaces the MiniSearch instance and clears both
5121
- * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
5122
- * `SearchService.clearAll()` calls `replaceAll([])`.
5123
- */
5124
- async replaceAll(documents) {
5125
- this.index = this.createIndex();
5126
- this.entryIdsByEntity.clear();
5127
- this.entityIdById.clear();
5128
- this.addDocuments(documents);
5617
+ return { status: "stored", charCount, passageCount: spans.length, storedAt };
5618
+ }
5619
+
5620
+ // src/services/SourceStoreService.ts
5621
+ var DEFAULT_MAX_CHARS_PER_SOURCE = 2e5;
5622
+ var DEFAULT_MAX_TOTAL_CHARS = 5e6;
5623
+ function limitOr(value, fallback) {
5624
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
5625
+ }
5626
+ var SourceStoreService = class {
5627
+ constructor(db, prefix, options, jobManager) {
5628
+ this.db = db;
5629
+ this.prefix = prefix;
5630
+ this.options = options;
5631
+ this.jobManager = jobManager;
5129
5632
  }
5130
- /**
5131
- * Best-match-first search over the documents whose `entity_id` is in
5132
- * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
5133
- * uses this to over-fetch candidates before the `limit` cap). Scores are
5134
- * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
5135
- * any scaling, not the strategy.
5136
- */
5137
- async search(query, options) {
5138
- if (options.entityIds.length === 0) return [];
5139
- const entityIdSet = new Set(options.entityIds);
5140
- const limit = options.preFilterLimit ?? options.limit;
5141
- const raw = this.index.search(query, {
5142
- filter: (r) => entityIdSet.has(r.entity_id),
5143
- combineWith: "OR"
5144
- });
5145
- raw.sort((a, b) => {
5146
- const scoreDiff = b.score - a.score;
5147
- if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
5148
- return a.id.localeCompare(b.id);
5149
- });
5150
- return raw.slice(0, limit).map((r) => ({
5151
- id: r.id,
5152
- entity_id: r.entity_id,
5153
- score: r.score
5154
- }));
5155
- }
5156
- /**
5157
- * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
5158
- * un-vacuumed discard inverts the relative scores of term-sharing
5159
- * documents at any index size. `SearchService.syncEntries` calls this
5160
- * after a discard-bearing turn. No-op when `dirtCount === 0`.
5161
- */
5162
- async vacuum() {
5163
- if (this.index.dirtCount > 0) {
5164
- await this.index.vacuum();
5165
- }
5633
+ limits() {
5634
+ const cfg = this.options.config?.sourceStore;
5635
+ return {
5636
+ maxCharsPerSource: limitOr(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
5637
+ maxTotalChars: limitOr(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
5638
+ };
5166
5639
  }
5167
- /**
5168
- * `true` when `entityId` has been indexed at least once under the current
5169
- * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
5170
- * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
5171
- */
5172
- hasIndexedEntity(entityId) {
5173
- return this.entryIdsByEntity.has(entityId);
5640
+ refuse(entityId, code, sourceRef) {
5641
+ const captured = [];
5642
+ const input = { code, operation: "sourceStore", trigger: "call", entityId, detail: { sourceRef } };
5643
+ emitDiagnostic({ onDiagnostic: (d) => {
5644
+ captured.push(d);
5645
+ } }, input);
5646
+ emitDiagnostic(this.options, input);
5647
+ return { stored: false, diagnostics: captured };
5174
5648
  }
5175
- /**
5176
- * Add `documents` to the MiniSearch instance and register them in
5177
- * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
5178
- * during `add`, so each doc is copied first. `add` throws on an id the
5179
- * index already holds — `replace` and `replaceEntity` discard first for
5180
- * that reason.
5181
- *
5182
- * Adds and registers one document at a time: if a duplicate id throws
5183
- * part-way through, every document already in the index is tracked, so
5184
- * the next rebuild can discard it instead of failing on it again. This is
5185
- * the precondition the per-turn recovery path relies on (#258 review).
5186
- */
5187
- addDocuments(documents) {
5188
- for (const d of documents) {
5189
- const doc = { ...d };
5190
- this.index.add(doc);
5191
- const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
5192
- set.add(doc.id);
5193
- this.entryIdsByEntity.set(doc.entity_id, set);
5194
- this.entityIdById.set(doc.id, doc.entity_id);
5649
+ async storeSource(entityId, params) {
5650
+ const sourceRef = normalizeSourceRef(params.sourceRef);
5651
+ if (!sourceRef) throw new Error("Invalid sourceRef");
5652
+ const sourceHash = normalizeSourceHash(params.sourceHash);
5653
+ if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
5654
+ if (typeof params.text !== "string") throw new Error(`text must be a string, received ${typeof params.text}`);
5655
+ const text = params.text;
5656
+ this.jobManager.acquireLock("store", entityId);
5657
+ try {
5658
+ const limits = this.limits();
5659
+ let refused;
5660
+ const outcome = await this.db.withTransactionAsync((tx) => upsertStoredSource(
5661
+ tx,
5662
+ this.prefix,
5663
+ entityId,
5664
+ { sourceRef, sourceHash, text },
5665
+ limits,
5666
+ (code) => {
5667
+ refused = code;
5668
+ },
5669
+ { idempotentSamePair: true }
5670
+ ));
5671
+ if (outcome.status === "refused") return this.refuse(entityId, refused, sourceRef);
5672
+ return {
5673
+ stored: true,
5674
+ sourceRef,
5675
+ sourceHash,
5676
+ charCount: outcome.charCount,
5677
+ passageCount: outcome.passageCount,
5678
+ storedAt: outcome.storedAt
5679
+ };
5680
+ } finally {
5681
+ this.jobManager.releaseLock("store", entityId);
5195
5682
  }
5196
5683
  }
5197
- /**
5198
- * Discard `ids` from the MiniSearch instance and from both id maps, but
5199
- * only for ids currently owned by `entityId` (the second argument). When
5200
- * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
5201
- * path), every id is discarded regardless of owning entity.
5202
- *
5203
- * `index.has(id)` is the membership test of record: a rebuild that failed
5204
- * between its own discard pass and the set replacement can leave the
5205
- * tracking set claiming ids the index no longer holds — `discard()` throws
5206
- * on those, so we guard.
5207
- */
5208
- discardIds(ids, entityId) {
5209
- for (const id of ids) {
5210
- const owning = this.entityIdById.get(id);
5211
- if (owning === void 0) continue;
5212
- if (entityId !== void 0 && owning !== entityId) continue;
5213
- if (this.index.has(id)) this.index.discard(id);
5214
- this.entryIdsByEntity.get(owning)?.delete(id);
5215
- this.entityIdById.delete(id);
5216
- }
5684
+ /** Spec §7: the text exactly as handed, or null. Plain read, no write lock. */
5685
+ async getStoredSource(entityId, sourceRef) {
5686
+ const ref = normalizeSourceRef(sourceRef);
5687
+ if (!ref) return null;
5688
+ const row = await this.db.getFirstAsync(
5689
+ `SELECT source_ref, source_hash, text, char_count, created_at FROM ${this.prefix}source_documents
5690
+ WHERE entity_id = ? AND source_ref = ?`,
5691
+ [entityId, ref]
5692
+ );
5693
+ if (!row) return null;
5694
+ return {
5695
+ sourceRef: row.source_ref,
5696
+ sourceHash: row.source_hash,
5697
+ text: row.text,
5698
+ charCount: Number(row.char_count),
5699
+ storedAt: Number(row.created_at)
5700
+ };
5217
5701
  }
5218
- };
5219
- function assertOwnedBy(entityId, documents) {
5220
- for (const doc of documents) {
5221
- if (doc.entity_id !== entityId) {
5222
- throw new Error(
5223
- `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
5224
- );
5225
- }
5702
+ /** Spec §4/§7: full store listing, including sources stored with no ingest. */
5703
+ async listStoredSources(entityId) {
5704
+ const rows = await this.db.getAllAsync(
5705
+ `SELECT d.source_ref, d.source_hash, d.char_count, d.created_at,
5706
+ (SELECT COUNT(*) FROM ${this.prefix}source_passages p
5707
+ WHERE p.entity_id = d.entity_id AND p.document_id = d.id) AS passage_count
5708
+ FROM ${this.prefix}source_documents d
5709
+ WHERE d.entity_id = ?
5710
+ ORDER BY d.source_ref COLLATE BINARY`,
5711
+ [entityId]
5712
+ );
5713
+ return rows.map((r) => ({
5714
+ sourceRef: r.source_ref,
5715
+ sourceHash: r.source_hash,
5716
+ charCount: Number(r.char_count),
5717
+ passageCount: Number(r.passage_count),
5718
+ storedAt: Number(r.created_at)
5719
+ }));
5226
5720
  }
5227
- }
5721
+ };
5228
5722
 
5229
5723
  // src/utils/monotonicNow.ts
5230
5724
  var monotonicNow = () => typeof performance !== "undefined" && typeof performance.now === "function" ? performance.now() : Date.now();
@@ -5242,12 +5736,46 @@ function buildFtsMatchQuery(query) {
5242
5736
  }
5243
5737
 
5244
5738
  // src/services/search/Fts5IndexStrategy.ts
5739
+ async function hydratePassageHits(db, prefix, raw) {
5740
+ const docs = /* @__PURE__ */ new Map();
5741
+ const out = [];
5742
+ for (const r of raw) {
5743
+ const pas = await db.getFirstAsync(
5744
+ `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages WHERE id = ? AND entity_id = ?`,
5745
+ [r.id, r.entity_id]
5746
+ );
5747
+ if (!pas) continue;
5748
+ const dk = `${r.entity_id}\0${r.document_id}`;
5749
+ if (!docs.has(dk)) {
5750
+ docs.set(dk, await db.getFirstAsync(
5751
+ `SELECT source_ref, source_hash, text FROM ${prefix}source_documents WHERE id = ? AND entity_id = ?`,
5752
+ [r.document_id, r.entity_id]
5753
+ ) ?? null);
5754
+ }
5755
+ const doc = docs.get(dk);
5756
+ if (!doc) continue;
5757
+ const start = Number(pas.start_offset);
5758
+ const end = Number(pas.end_offset);
5759
+ out.push({
5760
+ ...r,
5761
+ seq: Number(pas.seq),
5762
+ start_offset: start,
5763
+ end_offset: end,
5764
+ source_ref: doc.source_ref,
5765
+ source_hash: doc.source_hash,
5766
+ text: doc.text.slice(start, end)
5767
+ });
5768
+ }
5769
+ return out;
5770
+ }
5245
5771
  var Fts5IndexStrategy = class {
5246
5772
  constructor(db, prefix, metadataRepo, budgetMs = DEFAULT_SETUP_BUDGET_MS) {
5247
5773
  this.db = db;
5248
5774
  this.prefix = prefix;
5249
5775
  this.metadataRepo = metadataRepo;
5250
5776
  this.budgetMs = budgetMs;
5777
+ /** Set when passage-index init failed; passage drain and search become no-ops. */
5778
+ this.passagesDisabled = false;
5251
5779
  }
5252
5780
  /**
5253
5781
  * Resolves the index state (spec #280 Change 3 transition table). Every
@@ -5255,6 +5783,120 @@ var Fts5IndexStrategy = class {
5255
5783
  * failure leaves zero mutation (Change 4 ordering).
5256
5784
  */
5257
5785
  async init(opts = {}) {
5786
+ await this.initEntries(opts);
5787
+ try {
5788
+ await this.ensurePassageObjects();
5789
+ } catch (err) {
5790
+ this.passagesDisabled = true;
5791
+ console.warn("[WikiMemory] passage index init failed; passage search returns [] until a later open:", err);
5792
+ }
5793
+ }
5794
+ /**
5795
+ * Source-store passage index objects (spec source-store §6): created here,
5796
+ * the way the entries_fts objects are, never by setupDatabase. Skipped when
5797
+ * the store tables are absent (a pre-v17 database).
5798
+ */
5799
+ async ensurePassageObjects() {
5800
+ const p = this.prefix;
5801
+ if (!await this.metadataRepo.tableExists(`${p}source_passages`)) return;
5802
+ await this.db.withTransactionAsync(async (tx) => {
5803
+ await tx.execAsync(passageFtsTablesDdl(p) + passageFtsTriggersDdl(p));
5804
+ const mapped = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_map LIMIT 1`);
5805
+ const queued = await tx.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`);
5806
+ if (mapped === null && queued === null) {
5807
+ await tx.runAsync(`DELETE FROM ${p}source_passages_fts`);
5808
+ await tx.runAsync(
5809
+ `INSERT INTO ${p}source_passages_fts_pending (entity_id, doc_id)
5810
+ SELECT entity_id, id FROM ${p}source_documents`
5811
+ );
5812
+ }
5813
+ });
5814
+ }
5815
+ /**
5816
+ * Drain the passage ledger one document at a time (spec §6, the stated
5817
+ * departure from all-SQL): the document's text is read into JS and sliced at
5818
+ * the offsets the cutter stored, so transient memory is bounded by
5819
+ * `maxCharsPerSource` for the ONE document, never the store. Each document
5820
+ * is one transaction. `entityId` limits the drain to that entity's ledger rows.
5821
+ */
5822
+ async drainPassages(opts = {}) {
5823
+ if (this.passagesDisabled) return;
5824
+ const p = this.prefix;
5825
+ if (!await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`)) return;
5826
+ for (; ; ) {
5827
+ if (opts.deadline !== void 0 && monotonicNow() >= opts.deadline) return;
5828
+ let ran = false;
5829
+ await this.db.withTransactionAsync(async (tx) => {
5830
+ const first = opts.entityId === void 0 ? await tx.getFirstAsync(
5831
+ `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending ORDER BY seq LIMIT 1`
5832
+ ) : await tx.getFirstAsync(
5833
+ `SELECT doc_id, entity_id FROM ${p}source_passages_fts_pending WHERE entity_id = ? ORDER BY seq LIMIT 1`,
5834
+ [opts.entityId]
5835
+ );
5836
+ if (!first) return;
5837
+ const docId = first.doc_id;
5838
+ const ent = first.entity_id;
5839
+ const hi = await tx.getFirstAsync(
5840
+ `SELECT max(seq) AS hi FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND entity_id = ?`,
5841
+ [docId, ent]
5842
+ );
5843
+ await tx.runAsync(
5844
+ `DELETE FROM ${p}source_passages_fts WHERE rowid IN (SELECT fts_rowid FROM ${p}source_passages_fts_map WHERE doc_id = ?)`,
5845
+ [docId]
5846
+ );
5847
+ await tx.runAsync(`DELETE FROM ${p}source_passages_fts_map WHERE doc_id = ?`, [docId]);
5848
+ const doc = await tx.getFirstAsync(`SELECT text FROM ${p}source_documents WHERE id = ? AND entity_id = ?`, [docId, ent]);
5849
+ if (doc) {
5850
+ const rows = await tx.getAllAsync(
5851
+ `SELECT id, entity_id, start_offset, end_offset FROM ${p}source_passages WHERE document_id = ? AND entity_id = ? ORDER BY seq`,
5852
+ [docId, ent]
5853
+ );
5854
+ for (const r of rows) {
5855
+ const { lastInsertRowId } = await tx.runAsync(
5856
+ `INSERT INTO ${p}source_passages_fts_map (passage_id, doc_id) VALUES (?, ?)`,
5857
+ [r.id, docId]
5858
+ );
5859
+ await tx.runAsync(
5860
+ `INSERT INTO ${p}source_passages_fts (rowid, passage_id, entity_id, doc_id, text) VALUES (?, ?, ?, ?, ?)`,
5861
+ [lastInsertRowId, r.id, r.entity_id, docId, doc.text.slice(Number(r.start_offset), Number(r.end_offset))]
5862
+ );
5863
+ }
5864
+ }
5865
+ await tx.runAsync(
5866
+ `DELETE FROM ${p}source_passages_fts_pending WHERE doc_id = ? AND seq <= ?`,
5867
+ [docId, hi?.hi ?? 0]
5868
+ );
5869
+ ran = true;
5870
+ });
5871
+ if (!ran) return;
5872
+ }
5873
+ }
5874
+ /**
5875
+ * Best-match-first passage search. A hit counts only while its
5876
+ * `source_passages` row exists, so a stalled drain never surfaces a deleted
5877
+ * passage (spec §5).
5878
+ */
5879
+ async searchPassages(query, options) {
5880
+ if (this.passagesDisabled || options.entityIds.length === 0) return [];
5881
+ const match = buildFtsMatchQuery(query);
5882
+ if (match === null) return [];
5883
+ const p = this.prefix;
5884
+ const t = `${p}source_passages_fts`;
5885
+ const limit = options.limit >= Number.MAX_SAFE_INTEGER ? -1 : options.limit;
5886
+ const raw = await this.db.getAllAsync(
5887
+ `SELECT passage_id AS id, entity_id, doc_id AS document_id, max(0.0, -raw) AS score FROM (
5888
+ SELECT passage_id, entity_id, doc_id, bm25(${t}, 0.0, 0.0, 0.0, 1.0) AS raw
5889
+ FROM ${t}
5890
+ WHERE ${t} MATCH ? AND entity_id IN (SELECT value FROM json_each(?))
5891
+ AND passage_id IN (SELECT id FROM ${p}source_passages WHERE entity_id IN (SELECT value FROM json_each(?)))
5892
+ ORDER BY raw, passage_id
5893
+ LIMIT ?)
5894
+ ORDER BY raw, id`,
5895
+ [match, JSON.stringify(options.entityIds), JSON.stringify(options.entityIds), limit]
5896
+ );
5897
+ return hydratePassageHits(this.db, p, raw);
5898
+ }
5899
+ async initEntries(opts) {
5258
5900
  try {
5259
5901
  await this.initOnce(opts);
5260
5902
  } catch (err) {
@@ -5428,6 +6070,53 @@ var Fts5IndexStrategy = class {
5428
6070
  if (!isSqliteError(err)) throw err;
5429
6071
  }
5430
6072
  }
6073
+ /** Listed retired table names (erase step 4 / module-less fallback). */
6074
+ async retiredTables() {
6075
+ return this.retiredList();
6076
+ }
6077
+ /**
6078
+ * Erase step 4: reclaim every retired table to completion (DROP + delist), no
6079
+ * deadline. Failures surface (unlike the best-effort quantum path); the
6080
+ * SQLITE_CORRUPT_VTAB hollowed-shell exit inside reclaimRetired is designed.
6081
+ */
6082
+ async reclaimRetiredToCompletion() {
6083
+ await this.reclaimRetired(Number.POSITIVE_INFINITY);
6084
+ }
6085
+ /**
6086
+ * Erase step 3: surfaced passage drain, no deadline. Fails only when passage
6087
+ * init was disabled AND the ledger still has rows; otherwise warns and continues.
6088
+ */
6089
+ async drainPassagesStrict() {
6090
+ if (this.passagesDisabled) {
6091
+ const p = this.prefix;
6092
+ const pending = await this.metadataRepo.tableExists(`${p}source_passages_fts_pending`) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${p}source_passages_fts_pending LIMIT 1`) !== null;
6093
+ if (pending) throw new Error("passage index disabled with pending ledger rows");
6094
+ console.warn("[WikiMemory] erase: passage index disabled; nothing pending, continuing");
6095
+ return;
6096
+ }
6097
+ await this.drainPassages({});
6098
+ }
6099
+ /**
6100
+ * Erase step 3 (entries side): drain the trigger-fed `fts_pending` ledger store-wide to
6101
+ * empty, no deadline, errors surfaced; throws if rows remain afterwards.
6102
+ */
6103
+ async drainEntriesLedgerStrict() {
6104
+ while (await this.drainLedgerChunk()) ;
6105
+ const left = await this.db.getFirstAsync(`SELECT 1 AS x FROM ${this.prefix}fts_pending LIMIT 1`);
6106
+ if (left !== null && left !== void 0) throw new Error("entries FTS ledger still has pending rows after drain");
6107
+ }
6108
+ /** Erase step 7: FTS 'optimize' on each FTS table that exists. */
6109
+ async optimizeFts() {
6110
+ const p = this.prefix;
6111
+ for (const t of [`${p}entries_fts`, `${p}source_passages_fts`]) {
6112
+ if (!await this.metadataRepo.tableExists(t)) continue;
6113
+ await this.db.runAsync(`INSERT INTO ${t}(${t}) VALUES('optimize')`);
6114
+ }
6115
+ }
6116
+ /** `erase({ rebuild: true })` surface: retire + recreate the entries index and re-arm the rebuild. */
6117
+ async rebuildForErase() {
6118
+ await this.resetAndRearm();
6119
+ }
5431
6120
  /** Bounded reclamation steps, each its own tx, until the deadline or nothing is retired. */
5432
6121
  async reclaimRetired(deadline) {
5433
6122
  while (monotonicNow() < deadline) {
@@ -5702,36 +6391,311 @@ function unwrapFtsOnly(err) {
5702
6391
  if (err instanceof FtsOnlyStatementError) return { cause: err.ftsOnlyCause, ftsOnly: true };
5703
6392
  } catch {
5704
6393
  }
5705
- return { cause: err, ftsOnly: false };
5706
- }
5707
- function safeSqliteCode(err) {
5708
- try {
5709
- const code = extractSqliteCode(err);
5710
- if (code !== void 0) return code;
5711
- const lifted = err?.sqliteErrorCode;
5712
- return typeof lifted === "string" ? lifted : void 0;
5713
- } catch {
5714
- return void 0;
6394
+ return { cause: err, ftsOnly: false };
6395
+ }
6396
+ function safeSqliteCode(err) {
6397
+ try {
6398
+ const code = extractSqliteCode(err);
6399
+ if (code !== void 0) return code;
6400
+ const lifted = err?.sqliteErrorCode;
6401
+ return typeof lifted === "string" ? lifted : void 0;
6402
+ } catch {
6403
+ return void 0;
6404
+ }
6405
+ }
6406
+ var TRANSIENT_OR_TX_FATAL = ["SQLITE_BUSY", "SQLITE_LOCKED", "SQLITE_FULL", "SQLITE_IOERR", "SQLITE_NOMEM", "SQLITE_INTERRUPT", "SQLITE_ABORT", "SQLITE_READONLY"];
6407
+ function isTransientOrTxFatal(err) {
6408
+ const code = safeSqliteCode(err);
6409
+ return code !== void 0 && TRANSIENT_OR_TX_FATAL.some((c) => code === c || code.startsWith(`${c}_`));
6410
+ }
6411
+ function ftsCorruptionClass(err) {
6412
+ const code = safeSqliteCode(err);
6413
+ if (code === "SQLITE_CORRUPT_VTAB") return "vtab";
6414
+ if (code?.startsWith("SQLITE_CORRUPT")) return "corrupt";
6415
+ return null;
6416
+ }
6417
+ function isSqliteError(err) {
6418
+ return safeSqliteCode(err) !== void 0;
6419
+ }
6420
+ function assertEntity(entityId, documents) {
6421
+ for (const d of documents) {
6422
+ if (d.entity_id !== entityId) {
6423
+ throw new TypeError(`IndexDocument ${d.id} has entity_id ${d.entity_id}, expected ${entityId}`);
6424
+ }
6425
+ }
6426
+ }
6427
+
6428
+ // src/services/search/MiniSearchIndexStrategy.ts
6429
+ async function loadStoredPassages(db, prefix, entityId) {
6430
+ const out = [];
6431
+ const docs = await db.getAllAsync(`SELECT id FROM ${prefix}source_documents WHERE entity_id = ?`, [entityId]);
6432
+ for (const d of docs) {
6433
+ const doc = await db.getFirstAsync(`SELECT text FROM ${prefix}source_documents WHERE id = ?`, [d.id]);
6434
+ if (!doc) continue;
6435
+ const rows = await db.getAllAsync(
6436
+ `SELECT id, start_offset, end_offset FROM ${prefix}source_passages WHERE document_id = ? ORDER BY seq`,
6437
+ [d.id]
6438
+ );
6439
+ for (const r of rows) {
6440
+ out.push({ id: r.id, entity_id: entityId, document_id: d.id, text: doc.text.slice(Number(r.start_offset), Number(r.end_offset)) });
6441
+ }
6442
+ }
6443
+ return out;
6444
+ }
6445
+ var MiniSearchIndexStrategy = class {
6446
+ constructor() {
6447
+ /**
6448
+ * Per-entity id set. `replaceEntity()` and `hasIndexedEntity()` read it;
6449
+ * `addDocuments()` and `discardIds()` keep it in sync. `SearchService` does
6450
+ * not see this map; it only sees `hasIndexedEntity`. The previous
6451
+ * `miniSearchEntryIdsByEntity` lived on `SearchService`.
6452
+ */
6453
+ this.entryIdsByEntity = /* @__PURE__ */ new Map();
6454
+ /**
6455
+ * Reverse of `entryIdsByEntity`. `replace(entityId, ids, …)` uses it to
6456
+ * decide which ids are owned by `entityId` (the only safe membership test
6457
+ * — a rebuild that failed between its discard pass and the set replacement
6458
+ * can leave the forward set claiming ids the MiniSearch instance does not
6459
+ * hold). The pre-extraction `syncEntries` deleted from one set per id, not
6460
+ * from every entity's set.
6461
+ */
6462
+ this.entityIdById = /* @__PURE__ */ new Map();
6463
+ // ---- Source-store passage index (spec source-store §6) --------------------
6464
+ // A second in-heap instance over the same passage slices as the FTS5 path.
6465
+ this.passageIndex = this.createPassageIndex();
6466
+ this.passageIdsByEntity = /* @__PURE__ */ new Map();
6467
+ /** Handle `reindexSourcePassages` last indexed from; `searchPassages` hydrates hits through it. */
6468
+ this.passageSource = null;
6469
+ this.index = this.createIndex();
6470
+ }
6471
+ /**
6472
+ * Build a fresh MiniSearch instance with the project's index options.
6473
+ * Called from the constructor and from `replaceAll`. We do not use
6474
+ * `removeAll()` on an existing instance because that empties the index but
6475
+ * leaves `dirtCount` and the vacuum bookkeeping intact, which would trip
6476
+ * `syncEntries`' conditional vacuum early after a clear.
6477
+ */
6478
+ createIndex() {
6479
+ return new MiniSearch__default.default({
6480
+ fields: ["title", "body", "tags"],
6481
+ storeFields: ["entity_id"],
6482
+ // Vacuuming is driven explicitly at the end of each serialized rebuild
6483
+ // (see SearchService.syncEntries). Auto-vacuum fires on its own
6484
+ // schedule, asynchronously with respect to the caller, and traversing
6485
+ // the tree mid-rebuild is what threw the uncaught TypeError in
6486
+ // MiniSearch.performVacuuming (#64).
6487
+ autoVacuum: false,
6488
+ searchOptions: {
6489
+ boost: { title: 2 },
6490
+ fuzzy: 0.2,
6491
+ prefix: true
6492
+ }
6493
+ });
6494
+ }
6495
+ /**
6496
+ * Incremental sync. Removes only ids currently tracked under `entityId`
6497
+ * (other entities' docs are untouched), then upserts `documents` by id.
6498
+ * The same id appearing in both `ids` and `documents` is discarded first
6499
+ * so the upsert does not throw on a duplicate id.
6500
+ *
6501
+ * Every document must carry `entityId` as its `entity_id`; a mismatch is
6502
+ * rejected before the write mutates anything. A tracking-only call
6503
+ * (`replace(entityId, [], [])`) registers the entity as indexed, matching
6504
+ * the interface contract.
6505
+ *
6506
+ * Atomicity: never awaits between the discard pass and `addDocuments`, so
6507
+ * a concurrent `search()` sees the index wholly before or wholly after,
6508
+ * never half-updated. This is the precondition the pre-extraction
6509
+ * `syncEntries` kept with its "no await from here to `addAll`" comment.
6510
+ */
6511
+ async replace(entityId, ids, documents) {
6512
+ assertOwnedBy(entityId, documents);
6513
+ this.discardIds(ids, entityId);
6514
+ if (!this.entryIdsByEntity.has(entityId)) this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
6515
+ this.addDocuments(documents);
6516
+ }
6517
+ /**
6518
+ * Per-entity rebuild. Removes every id tracked under `entityId` (with the
6519
+ * `index.has(id)` guard so a stale tracking set cannot make `discard()`
6520
+ * throw), then writes `documents`. The entity stays registered as
6521
+ * indexed — even when `documents` is empty — so the next `syncEntries`
6522
+ * call can take the fast path. Every document must belong to `entityId`.
6523
+ */
6524
+ async replaceEntity(entityId, documents) {
6525
+ assertOwnedBy(entityId, documents);
6526
+ const previous = this.entryIdsByEntity.get(entityId);
6527
+ if (previous) this.discardIds([...previous]);
6528
+ this.entryIdsByEntity.set(entityId, /* @__PURE__ */ new Set());
6529
+ this.addDocuments(documents);
6530
+ }
6531
+ /**
6532
+ * Global rebuild / clear. Replaces the MiniSearch instance and clears both
6533
+ * id maps, so `hasIndexedEntity` returns `false` for every entity afterwards.
6534
+ * `SearchService.clearAll()` calls `replaceAll([])`.
6535
+ */
6536
+ async replaceAll(documents) {
6537
+ this.index = this.createIndex();
6538
+ this.entryIdsByEntity.clear();
6539
+ this.entityIdById.clear();
6540
+ this.addDocuments(documents);
6541
+ }
6542
+ /**
6543
+ * Best-match-first search over the documents whose `entity_id` is in
6544
+ * `options.entityIds`. `preFilterLimit` overrides `limit` (hybrid retrieval
6545
+ * uses this to over-fetch candidates before the `limit` cap). Scores are
6546
+ * raw BM25+ — `SearchService.getKeywordScores` and `searchKeyword` apply
6547
+ * any scaling, not the strategy.
6548
+ */
6549
+ async search(query, options) {
6550
+ if (options.entityIds.length === 0) return [];
6551
+ const entityIdSet = new Set(options.entityIds);
6552
+ const limit = options.preFilterLimit ?? options.limit;
6553
+ const raw = this.index.search(query, {
6554
+ filter: (r) => entityIdSet.has(r.entity_id),
6555
+ combineWith: "OR"
6556
+ });
6557
+ raw.sort((a, b) => {
6558
+ const scoreDiff = b.score - a.score;
6559
+ if (!Number.isNaN(scoreDiff) && scoreDiff !== 0) return scoreDiff;
6560
+ return a.id.localeCompare(b.id);
6561
+ });
6562
+ return raw.slice(0, limit).map((r) => ({
6563
+ id: r.id,
6564
+ entity_id: r.entity_id,
6565
+ score: r.score
6566
+ }));
6567
+ }
6568
+ createPassageIndex() {
6569
+ return new MiniSearch__default.default({
6570
+ fields: ["text"],
6571
+ storeFields: ["entity_id", "document_id"],
6572
+ autoVacuum: false,
6573
+ // explicit vacuum below, same reason as the facts instance (#64)
6574
+ searchOptions: { fuzzy: 0.2, prefix: true }
6575
+ });
6576
+ }
6577
+ /**
6578
+ * Re-index stored passages from SQLite: one entity, or every stored entity
6579
+ * when `entityId` is omitted (the open-time pass; up to `maxTotalChars` per
6580
+ * entity, and the heap grows with the number of stored entities, spec §6).
6581
+ * It is also the post-commit sync after forget/clearAll: deleted passages
6582
+ * drop out because the reload no longer finds their rows (spec §5).
6583
+ * Reads happen first; the discard and add are synchronous, so the swap is
6584
+ * atomic (a concurrent search sees the index wholly before or wholly after),
6585
+ * and the vacuum runs after the swap.
6586
+ */
6587
+ async reindexSourcePassages(db, prefix, entityId) {
6588
+ this.passageSource = { db, prefix };
6589
+ const entityIds = entityId !== void 0 ? [entityId] : [.../* @__PURE__ */ new Set([
6590
+ ...(await db.getAllAsync(`SELECT DISTINCT entity_id FROM ${prefix}source_documents`)).map((r) => r.entity_id),
6591
+ ...this.passageIdsByEntity.keys()
6592
+ ])];
6593
+ for (const id of entityIds) {
6594
+ const passages = await loadStoredPassages(db, prefix, id);
6595
+ for (const old of this.passageIdsByEntity.get(id) ?? []) {
6596
+ if (this.passageIndex.has(old)) this.passageIndex.discard(old);
6597
+ }
6598
+ const ids = /* @__PURE__ */ new Set();
6599
+ for (const d of passages) {
6600
+ this.passageIndex.add({ ...d });
6601
+ ids.add(d.id);
6602
+ }
6603
+ if (ids.size > 0) this.passageIdsByEntity.set(id, ids);
6604
+ else this.passageIdsByEntity.delete(id);
6605
+ if (this.passageIndex.dirtCount > 0) await this.passageIndex.vacuum();
6606
+ }
6607
+ }
6608
+ /** Best-match-first passage search over the entities in `options.entityIds`. */
6609
+ async searchPassages(query, options) {
6610
+ if (options.entityIds.length === 0 || !this.passageSource) return [];
6611
+ const allowed = new Set(options.entityIds);
6612
+ const raw = this.passageIndex.search(query, { filter: (r) => allowed.has(r.entity_id), combineWith: "OR" });
6613
+ raw.sort((a, b) => b.score - a.score || a.id.localeCompare(b.id));
6614
+ const live = /* @__PURE__ */ new Set();
6615
+ for (const eid of options.entityIds) {
6616
+ const rows = await this.passageSource.db.getAllAsync(
6617
+ `SELECT id FROM ${this.passageSource.prefix}source_passages WHERE entity_id = ?`,
6618
+ [eid]
6619
+ );
6620
+ for (const row of rows) live.add(row.id);
6621
+ }
6622
+ const hits = raw.filter((r) => live.has(r.id)).slice(0, options.limit).map((r) => ({
6623
+ id: r.id,
6624
+ entity_id: r.entity_id,
6625
+ document_id: r.document_id,
6626
+ score: r.score
6627
+ }));
6628
+ return hydratePassageHits(this.passageSource.db, this.passageSource.prefix, hits);
6629
+ }
6630
+ /**
6631
+ * Explicit vacuum. MiniSearch 7.2.0's `dirtCount` rule: search after an
6632
+ * un-vacuumed discard inverts the relative scores of term-sharing
6633
+ * documents at any index size. `SearchService.syncEntries` calls this
6634
+ * after a discard-bearing turn. No-op when `dirtCount === 0`.
6635
+ */
6636
+ async vacuum() {
6637
+ if (this.index.dirtCount > 0) {
6638
+ await this.index.vacuum();
6639
+ }
6640
+ }
6641
+ /**
6642
+ * `true` when `entityId` has been indexed at least once under the current
6643
+ * strategy state. Backed by `entryIdsByEntity.has(entityId)`, which is
6644
+ * kept in sync by `addDocuments`, `replaceEntity`, and `replaceAll`.
6645
+ */
6646
+ hasIndexedEntity(entityId) {
6647
+ return this.entryIdsByEntity.has(entityId);
6648
+ }
6649
+ /**
6650
+ * Add `documents` to the MiniSearch instance and register them in
6651
+ * `entryIdsByEntity` and `entityIdById`. MiniSearch mutates documents
6652
+ * during `add`, so each doc is copied first. `add` throws on an id the
6653
+ * index already holds — `replace` and `replaceEntity` discard first for
6654
+ * that reason.
6655
+ *
6656
+ * Adds and registers one document at a time: if a duplicate id throws
6657
+ * part-way through, every document already in the index is tracked, so
6658
+ * the next rebuild can discard it instead of failing on it again. This is
6659
+ * the precondition the per-turn recovery path relies on (#258 review).
6660
+ */
6661
+ addDocuments(documents) {
6662
+ for (const d of documents) {
6663
+ const doc = { ...d };
6664
+ this.index.add(doc);
6665
+ const set = this.entryIdsByEntity.get(doc.entity_id) ?? /* @__PURE__ */ new Set();
6666
+ set.add(doc.id);
6667
+ this.entryIdsByEntity.set(doc.entity_id, set);
6668
+ this.entityIdById.set(doc.id, doc.entity_id);
6669
+ }
6670
+ }
6671
+ /**
6672
+ * Discard `ids` from the MiniSearch instance and from both id maps, but
6673
+ * only for ids currently owned by `entityId` (the second argument). When
6674
+ * `entityId` is omitted (used by `replaceEntity` for the bulk rebuild
6675
+ * path), every id is discarded regardless of owning entity.
6676
+ *
6677
+ * `index.has(id)` is the membership test of record: a rebuild that failed
6678
+ * between its own discard pass and the set replacement can leave the
6679
+ * tracking set claiming ids the index no longer holds — `discard()` throws
6680
+ * on those, so we guard.
6681
+ */
6682
+ discardIds(ids, entityId) {
6683
+ for (const id of ids) {
6684
+ const owning = this.entityIdById.get(id);
6685
+ if (owning === void 0) continue;
6686
+ if (entityId !== void 0 && owning !== entityId) continue;
6687
+ if (this.index.has(id)) this.index.discard(id);
6688
+ this.entryIdsByEntity.get(owning)?.delete(id);
6689
+ this.entityIdById.delete(id);
6690
+ }
5715
6691
  }
5716
- }
5717
- var TRANSIENT_OR_TX_FATAL = ["SQLITE_BUSY", "SQLITE_LOCKED", "SQLITE_FULL", "SQLITE_IOERR", "SQLITE_NOMEM", "SQLITE_INTERRUPT", "SQLITE_ABORT", "SQLITE_READONLY"];
5718
- function isTransientOrTxFatal(err) {
5719
- const code = safeSqliteCode(err);
5720
- return code !== void 0 && TRANSIENT_OR_TX_FATAL.some((c) => code === c || code.startsWith(`${c}_`));
5721
- }
5722
- function ftsCorruptionClass(err) {
5723
- const code = safeSqliteCode(err);
5724
- if (code === "SQLITE_CORRUPT_VTAB") return "vtab";
5725
- if (code?.startsWith("SQLITE_CORRUPT")) return "corrupt";
5726
- return null;
5727
- }
5728
- function isSqliteError(err) {
5729
- return safeSqliteCode(err) !== void 0;
5730
- }
5731
- function assertEntity(entityId, documents) {
5732
- for (const d of documents) {
5733
- if (d.entity_id !== entityId) {
5734
- throw new TypeError(`IndexDocument ${d.id} has entity_id ${d.entity_id}, expected ${entityId}`);
6692
+ };
6693
+ function assertOwnedBy(entityId, documents) {
6694
+ for (const doc of documents) {
6695
+ if (doc.entity_id !== entityId) {
6696
+ throw new Error(
6697
+ `IndexStrategy write for entity ${entityId} got document ${doc.id} under entity ${doc.entity_id}`
6698
+ );
5735
6699
  }
5736
6700
  }
5737
6701
  }
@@ -5773,6 +6737,22 @@ async function probeFts5(db, prefix) {
5773
6737
  }
5774
6738
  }
5775
6739
  async function detachFts5(db, prefix, metadataRepo) {
6740
+ const passageLedger = await metadataRepo.tableExists(`${prefix}source_passages_fts_pending`);
6741
+ if (passageLedger) {
6742
+ const [ai, ad] = passageFtsTriggerNames(prefix);
6743
+ await db.withTransactionAsync(async (tx) => {
6744
+ await tx.execAsync(
6745
+ `DROP TRIGGER IF EXISTS ${ai};
6746
+ DROP TRIGGER IF EXISTS ${ad};
6747
+ DROP TABLE IF EXISTS ${prefix}source_passages_fts_map;
6748
+ DROP TABLE IF EXISTS ${prefix}source_passages_fts_pending;`
6749
+ );
6750
+ });
6751
+ try {
6752
+ await db.execAsync(`DROP TABLE IF EXISTS ${prefix}source_passages_fts`);
6753
+ } catch {
6754
+ }
6755
+ }
5776
6756
  const hasLedger = await metadataRepo.tableExists(`${prefix}fts_pending`);
5777
6757
  const state = await metadataRepo.getMeta(FTS5_STATE_KEY);
5778
6758
  if (!hasLedger && state !== "live") return;
@@ -5840,7 +6820,7 @@ var JobManager = class {
5840
6820
  this.statusSubscribers = /* @__PURE__ */ new Map();
5841
6821
  /**
5842
6822
  * Lookup table for acquireLock/releaseLock's dynamic-dispatch branch.
5843
- * Excludes 'ingest' | 'global_reembed' | 'global_import', which those
6823
+ * Excludes 'ingest' | 'global_reembed' | 'global_import' | 'erase', which those
5844
6824
  * methods already handle via explicit if/else branches before reaching
5845
6825
  * this table.
5846
6826
  */
@@ -5851,7 +6831,8 @@ var JobManager = class {
5851
6831
  reembed: (id) => this._reembedKey(id),
5852
6832
  import: (id) => this._importKey(id),
5853
6833
  forget: (id) => this._forgetKey(id),
5854
- ontologyBackfill: (id) => this._ontologyBackfillKey(id)
6834
+ ontologyBackfill: (id) => this._ontologyBackfillKey(id),
6835
+ store: (id) => this._storeKey(id)
5855
6836
  };
5856
6837
  }
5857
6838
  _hashLockKey(entityId, sourceHash) {
@@ -5908,6 +6889,9 @@ var JobManager = class {
5908
6889
  _globalReembedKey() {
5909
6890
  return `${this.prefix}:reembed`;
5910
6891
  }
6892
+ _eraseKey() {
6893
+ return `${this.prefix}:erase`;
6894
+ }
5911
6895
  _importKey(entityId) {
5912
6896
  return `${this.prefix}:${entityId}:import`;
5913
6897
  }
@@ -5920,6 +6904,9 @@ var JobManager = class {
5920
6904
  _librarianKey(entityId) {
5921
6905
  return `${this.prefix}:${entityId}:librarian`;
5922
6906
  }
6907
+ _storeKey(entityId) {
6908
+ return `${this.prefix}:${entityId}:store`;
6909
+ }
5923
6910
  _healKey(entityId) {
5924
6911
  return `${this.prefix}:${entityId}:heal`;
5925
6912
  }
@@ -5948,6 +6935,9 @@ var JobManager = class {
5948
6935
  _isImportActiveFor(entityId) {
5949
6936
  return this.activeMaintenanceJobs.has(this._importKey(entityId)) || this.activeMaintenanceJobs.has(this._globalImportKey());
5950
6937
  }
6938
+ _isStoreActiveFor(entityId) {
6939
+ return this.activeMaintenanceJobs.has(this._storeKey(entityId));
6940
+ }
5951
6941
  _isForgetActiveFor(entityId) {
5952
6942
  return this.activeMaintenanceJobs.has(this._forgetKey(entityId));
5953
6943
  }
@@ -5982,11 +6972,19 @@ var JobManager = class {
5982
6972
  _isIngestActiveFor(entityId) {
5983
6973
  return this.activeIngestJobs.has(entityId);
5984
6974
  }
5985
- acquireLock(operation, entityId, sourceRef) {
6975
+ /**
6976
+ * `owner` is the fourth parameter (the third, `sourceRef`, is ingest-only).
6977
+ * `'erase'` marks the erase() pipeline's own per-entity prune, the only
6978
+ * operation exempt from the universal erase pre-check below.
6979
+ */
6980
+ acquireLock(operation, entityId, sourceRef, owner = "host") {
5986
6981
  let blockingOperation = null;
5987
6982
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) {
5988
6983
  throw new WikiBusyError("import", "*");
5989
6984
  }
6985
+ if (operation !== "erase" && !(operation === "prune" && owner === "erase") && this.activeMaintenanceJobs.has(this._eraseKey())) {
6986
+ throw new WikiBusyError("erase", "*");
6987
+ }
5990
6988
  switch (operation) {
5991
6989
  case "prune":
5992
6990
  if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
@@ -5997,6 +6995,7 @@ var JobManager = class {
5997
6995
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
5998
6996
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
5999
6997
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
6998
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6000
6999
  break;
6001
7000
  case "librarian":
6002
7001
  case "heal":
@@ -6007,6 +7006,7 @@ var JobManager = class {
6007
7006
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
6008
7007
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6009
7008
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7009
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6010
7010
  break;
6011
7011
  }
6012
7012
  case "reembed":
@@ -6019,6 +7019,7 @@ var JobManager = class {
6019
7019
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
6020
7020
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6021
7021
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7022
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6022
7023
  break;
6023
7024
  case "global_reembed":
6024
7025
  if (this.activeMaintenanceJobs.has(this._globalReembedKey())) blockingOperation = "reembed";
@@ -6030,6 +7031,19 @@ var JobManager = class {
6030
7031
  else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
6031
7032
  else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
6032
7033
  else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
7034
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
7035
+ break;
7036
+ case "erase":
7037
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) blockingOperation = "erase";
7038
+ else if (this._isAnyMaintenanceActiveWithSuffix(":reembed")) blockingOperation = "reembed";
7039
+ else if (this._isAnyMaintenanceActiveWithSuffix(":prune")) blockingOperation = "prune";
7040
+ else if (this._isAnyMaintenanceActiveWithSuffix(":librarian")) blockingOperation = "librarian";
7041
+ else if (this._isAnyMaintenanceActiveWithSuffix(":heal")) blockingOperation = "heal";
7042
+ else if (this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill")) blockingOperation = "ontologyBackfill";
7043
+ else if (this.activeIngestJobs.size > 0) blockingOperation = "ingest";
7044
+ else if (this._isAnyMaintenanceActiveWithSuffix(":import")) blockingOperation = "import";
7045
+ else if (this._isAnyMaintenanceActiveWithSuffix(":forget")) blockingOperation = "forget";
7046
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
6033
7047
  break;
6034
7048
  case "import":
6035
7049
  case "forget": {
@@ -6043,10 +7057,23 @@ var JobManager = class {
6043
7057
  else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
6044
7058
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6045
7059
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7060
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6046
7061
  break;
6047
7062
  }
7063
+ case "store":
7064
+ if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
7065
+ else if (this.activeMaintenanceJobs.has(this._pruneKey(entityId))) blockingOperation = "prune";
7066
+ else if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) blockingOperation = "librarian";
7067
+ else if (this.activeMaintenanceJobs.has(this._healKey(entityId))) blockingOperation = "heal";
7068
+ else if (this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId))) blockingOperation = "ontologyBackfill";
7069
+ else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
7070
+ else if (this._isIngestActiveFor(entityId)) blockingOperation = "ingest";
7071
+ else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
7072
+ else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7073
+ break;
6048
7074
  case "global_import":
6049
7075
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) blockingOperation = "import";
7076
+ else if (this._isAnyMaintenanceActiveWithSuffix(":store")) blockingOperation = "store";
6050
7077
  break;
6051
7078
  case "ingest": {
6052
7079
  const sourceKey = sourceRef ?? "";
@@ -6055,13 +7082,14 @@ var JobManager = class {
6055
7082
  else if (this._isReembedActive(entityId)) blockingOperation = "reembed";
6056
7083
  else if (this._isImportActiveFor(entityId)) blockingOperation = "import";
6057
7084
  else if (this._isForgetActiveFor(entityId)) blockingOperation = "forget";
7085
+ else if (this._isStoreActiveFor(entityId)) blockingOperation = "store";
6058
7086
  break;
6059
7087
  }
6060
7088
  }
6061
7089
  if (blockingOperation) {
6062
7090
  throw new WikiBusyError(
6063
7091
  blockingOperation,
6064
- operation === "global_reembed" || operation === "global_import" ? "*" : entityId
7092
+ operation === "global_reembed" || operation === "global_import" || operation === "erase" ? "*" : entityId
6065
7093
  );
6066
7094
  }
6067
7095
  if (operation === "ingest") {
@@ -6070,6 +7098,8 @@ var JobManager = class {
6070
7098
  this.activeMaintenanceJobs.add(this._globalReembedKey());
6071
7099
  } else if (operation === "global_import") {
6072
7100
  this.activeMaintenanceJobs.add(this._globalImportKey());
7101
+ } else if (operation === "erase") {
7102
+ this.activeMaintenanceJobs.add(this._eraseKey());
6073
7103
  } else {
6074
7104
  this.activeMaintenanceJobs.add(this.lockKeyFns[operation](entityId));
6075
7105
  }
@@ -6082,6 +7112,8 @@ var JobManager = class {
6082
7112
  this.activeMaintenanceJobs.delete(this._globalReembedKey());
6083
7113
  } else if (operation === "global_import") {
6084
7114
  this.activeMaintenanceJobs.delete(this._globalImportKey());
7115
+ } else if (operation === "erase") {
7116
+ this.activeMaintenanceJobs.delete(this._eraseKey());
6085
7117
  } else {
6086
7118
  this.activeMaintenanceJobs.delete(this.lockKeyFns[operation](entityId));
6087
7119
  }
@@ -6093,26 +7125,31 @@ var JobManager = class {
6093
7125
  */
6094
7126
  isBlocked(operation, entityId) {
6095
7127
  if (operation !== "global_import" && this.activeMaintenanceJobs.has(this._globalImportKey())) return true;
7128
+ if (operation !== "erase" && this.activeMaintenanceJobs.has(this._eraseKey())) return true;
6096
7129
  switch (operation) {
7130
+ case "erase":
7131
+ return this.activeMaintenanceJobs.has(this._eraseKey()) || 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");
6097
7132
  case "librarian":
6098
7133
  case "heal":
6099
7134
  case "ontologyBackfill":
6100
- return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
7135
+ return this.activeMaintenanceJobs.has(this.lockKeyFns[operation](entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
6101
7136
  case "prune":
6102
- return this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
7137
+ return this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
6103
7138
  case "reembed":
6104
- return this.activeMaintenanceJobs.has(this._reembedKey(entityId)) || this.activeMaintenanceJobs.has(this._globalReembedKey()) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
7139
+ return this.activeMaintenanceJobs.has(this._reembedKey(entityId)) || this.activeMaintenanceJobs.has(this._globalReembedKey()) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
6105
7140
  case "global_reembed":
6106
- return this.activeMaintenanceJobs.has(this._globalReembedKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget");
7141
+ return this.activeMaintenanceJobs.has(this._globalReembedKey()) || this._isAnyMaintenanceActiveWithSuffix(":reembed") || this._isAnyMaintenanceActiveWithSuffix(":prune") || this._isAnyMaintenanceActiveWithSuffix(":librarian") || this._isAnyMaintenanceActiveWithSuffix(":heal") || this._isAnyMaintenanceActiveWithSuffix(":ontologyBackfill") || this.activeIngestJobs.size > 0 || this._isAnyMaintenanceActiveWithSuffix(":import") || this._isAnyMaintenanceActiveWithSuffix(":forget") || this._isAnyMaintenanceActiveWithSuffix(":store");
6107
7142
  case "import":
6108
7143
  case "forget": {
6109
7144
  const selfKey = operation === "import" ? this._importKey(entityId) : this._forgetKey(entityId);
6110
- return this.activeMaintenanceJobs.has(selfKey) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
7145
+ return this.activeMaintenanceJobs.has(selfKey) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
6111
7146
  }
7147
+ case "store":
7148
+ return this._isStoreActiveFor(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this.activeMaintenanceJobs.has(this._librarianKey(entityId)) || this.activeMaintenanceJobs.has(this._healKey(entityId)) || this.activeMaintenanceJobs.has(this._ontologyBackfillKey(entityId)) || this._isReembedActive(entityId) || this._isIngestActiveFor(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
6112
7149
  case "global_import":
6113
- return this.activeMaintenanceJobs.has(this._globalImportKey());
7150
+ return this.activeMaintenanceJobs.has(this._globalImportKey()) || this._isAnyMaintenanceActiveWithSuffix(":store");
6114
7151
  case "ingest":
6115
- return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId);
7152
+ return this._hasIngestJob(entityId) || this.activeMaintenanceJobs.has(this._pruneKey(entityId)) || this._isReembedActive(entityId) || this._isImportActiveFor(entityId) || this._isForgetActiveFor(entityId) || this._isStoreActiveFor(entityId);
6116
7153
  default:
6117
7154
  return false;
6118
7155
  }
@@ -6125,6 +7162,7 @@ var JobManager = class {
6125
7162
  */
6126
7163
  tryAcquireAutoHealLock(entityId) {
6127
7164
  if (this.isAnyReembedActive()) return false;
7165
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) return false;
6128
7166
  const healKey = this._healKey(entityId);
6129
7167
  if (this.activeMaintenanceJobs.has(healKey)) return false;
6130
7168
  this.activeMaintenanceJobs.add(healKey);
@@ -6168,6 +7206,7 @@ var JobManager = class {
6168
7206
  * Validates all entities before acquiring any lock (same as current importDump semantics).
6169
7207
  */
6170
7208
  acquireImportLocks(entityIds) {
7209
+ if (this.activeMaintenanceJobs.has(this._eraseKey())) throw new WikiBusyError("erase", "*");
6171
7210
  for (const entityId of entityIds) {
6172
7211
  if (this.activeMaintenanceJobs.has(this._importKey(entityId))) throw new WikiBusyError("import", entityId);
6173
7212
  if (this.activeMaintenanceJobs.has(this._librarianKey(entityId))) throw new WikiBusyError("librarian", entityId);
@@ -6177,6 +7216,7 @@ var JobManager = class {
6177
7216
  if (this._isReembedActive(entityId)) throw new WikiBusyError("reembed", entityId);
6178
7217
  if (this._isIngestActiveFor(entityId)) throw new WikiBusyError("ingest", entityId);
6179
7218
  if (this._isForgetActiveFor(entityId)) throw new WikiBusyError("forget", entityId);
7219
+ if (this._isStoreActiveFor(entityId)) throw new WikiBusyError("store", entityId);
6180
7220
  }
6181
7221
  if (this.activeMaintenanceJobs.has(this._globalImportKey())) throw new WikiBusyError("import", "*");
6182
7222
  this.activeMaintenanceJobs.add(this._globalImportKey());
@@ -7493,6 +8533,94 @@ function classifierStateForFact(fact) {
7493
8533
  return parts.join("\n\n");
7494
8534
  }
7495
8535
 
8536
+ // src/services/TemporalService.ts
8537
+ var HISTORY_MAX_DEPTH = 100;
8538
+ var TemporalService = class {
8539
+ constructor(db, options, entryRepo, searchService, embeddingService) {
8540
+ this.db = db;
8541
+ this.options = options;
8542
+ this.entryRepo = entryRepo;
8543
+ this.searchService = searchService;
8544
+ this.embeddingService = embeddingService;
8545
+ }
8546
+ /**
8547
+ * Link `oldId` → `newId` inside the caller's transaction. `newId` must
8548
+ * already exist. Throws WikiSupersedeError on any rule violation; the
8549
+ * caller's transaction then rolls back.
8550
+ */
8551
+ async supersedeInTx(tx, entityId, oldId, newId, t, now) {
8552
+ const old = await this.entryRepo.findTemporalRow(oldId, tx);
8553
+ if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
8554
+ if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
8555
+ if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
8556
+ if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
8557
+ if (newId === oldId) throw new WikiSupersedeError("cycle");
8558
+ const repl = await this.entryRepo.findTemporalRow(newId, tx);
8559
+ if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
8560
+ if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
8561
+ if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
8562
+ const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
8563
+ if (predecessors.some((r) => r.id === newId)) throw new WikiSupersedeError("cycle");
8564
+ await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
8565
+ if (repl.valid_from == null) {
8566
+ await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
8567
+ }
8568
+ }
8569
+ async supersede(entityId, oldId, replacement, options) {
8570
+ const now = Date.now();
8571
+ const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
8572
+ let created = null;
8573
+ if (typeof replacement !== "string") {
8574
+ if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
8575
+ throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
8576
+ }
8577
+ created = {
8578
+ id: generateId("fact_"),
8579
+ entity_id: entityId,
8580
+ title: replacement.title,
8581
+ body: replacement.body,
8582
+ tags: Array.isArray(replacement.tags) ? replacement.tags : [],
8583
+ confidence: replacement.confidence ?? "certain",
8584
+ source_type: replacement.source_type ?? "user_stated",
8585
+ source_hash: null,
8586
+ source_ref: null,
8587
+ created_at: now,
8588
+ updated_at: now,
8589
+ last_accessed_at: null,
8590
+ access_count: 0,
8591
+ deleted_at: null
8592
+ };
8593
+ }
8594
+ const newId = typeof replacement === "string" ? replacement : created.id;
8595
+ const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
8596
+ await this.db.withTransactionAsync(async (tx) => {
8597
+ if (created) {
8598
+ await this.entryRepo.upsert(created, tx);
8599
+ if (newValidFrom !== void 0) {
8600
+ await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
8601
+ }
8602
+ }
8603
+ await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
8604
+ });
8605
+ await this.searchService.syncEntries(entityId, [oldId, newId]);
8606
+ if (created) {
8607
+ await this.embeddingService.embedFact(
8608
+ { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
8609
+ { operation: "supersede", trigger: "call" }
8610
+ );
8611
+ }
8612
+ this.searchService.evictCache(entityId);
8613
+ return { newId };
8614
+ }
8615
+ async history(entityId, factId) {
8616
+ const start = await this.entryRepo.findTemporalRow(factId);
8617
+ if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
8618
+ const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
8619
+ const facts = await this.entryRepo.findByIds([...predecessors.map((r) => r.id), factId, ...successors.map((r) => r.id)], [entityId]);
8620
+ return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
8621
+ }
8622
+ };
8623
+
7496
8624
  // src/utils/engineDefaults.ts
7497
8625
  var DEFAULT_LIBRARIAN_STRATEGY = "ops";
7498
8626
  var DEFAULT_MAINTENANCE_MODE = "deferred";
@@ -8660,110 +9788,22 @@ async function runResolve(deps, ctx, ambiguous) {
8660
9788
  const byItem = /* @__PURE__ */ new Map();
8661
9789
  for (const raw of ops) {
8662
9790
  const item = raw?.item;
8663
- if (typeof item === "number" && Number.isInteger(item) && item >= 0 && item < batch.length && !byItem.has(item)) {
8664
- byItem.set(item, raw);
8665
- }
8666
- }
8667
- batch.forEach((g, i) => {
8668
- const op = validateOp(byItem.get(i), aliasMapOf(g));
8669
- if (op) out.ops.set(g, op);
8670
- else out.rejected.push(g);
8671
- });
8672
- }
8673
- if (outcome.skipped.some((s) => s.reason === "call_error")) {
8674
- throw new Error("resolve: transient provider error; retry the pass");
8675
- }
8676
- for (const s of outcome.skipped) out.failed.push(s.item);
8677
- return out;
8678
- }
8679
-
8680
- // src/services/TemporalService.ts
8681
- var HISTORY_MAX_DEPTH = 100;
8682
- var TemporalService = class {
8683
- constructor(db, options, entryRepo, searchService, embeddingService) {
8684
- this.db = db;
8685
- this.options = options;
8686
- this.entryRepo = entryRepo;
8687
- this.searchService = searchService;
8688
- this.embeddingService = embeddingService;
8689
- }
8690
- /**
8691
- * Link `oldId` → `newId` inside the caller's transaction. `newId` must
8692
- * already exist. Throws WikiSupersedeError on any rule violation; the
8693
- * caller's transaction then rolls back.
8694
- */
8695
- async supersedeInTx(tx, entityId, oldId, newId, t, now) {
8696
- const old = await this.entryRepo.findTemporalRow(oldId, tx);
8697
- if (!old || old.deleted_at != null) throw new WikiSupersedeError("not_found");
8698
- if (old.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
8699
- if (old.superseded_by != null) throw new WikiSupersedeError("already_superseded");
8700
- if (old.source_type === "immutable_document") throw new WikiSupersedeError("immutable_target");
8701
- if (newId === oldId) throw new WikiSupersedeError("cycle");
8702
- const repl = await this.entryRepo.findTemporalRow(newId, tx);
8703
- if (!repl || repl.deleted_at != null) throw new WikiSupersedeError("not_found");
8704
- if (repl.entity_id !== entityId) throw new WikiSupersedeError("cross_entity");
8705
- if (repl.superseded_by != null) throw new WikiSupersedeError("already_superseded");
8706
- const { predecessors } = await this.entryRepo.findSupersessionChainIds(entityId, oldId, HISTORY_MAX_DEPTH, tx);
8707
- if (predecessors.includes(newId)) throw new WikiSupersedeError("cycle");
8708
- await this.entryRepo.setTemporal(oldId, entityId, { valid_to: t, superseded_by: newId, superseded_at: now }, tx);
8709
- if (repl.valid_from == null) {
8710
- await this.entryRepo.setTemporal(newId, entityId, { valid_from: t }, tx);
8711
- }
8712
- }
8713
- async supersede(entityId, oldId, replacement, options) {
8714
- const now = Date.now();
8715
- const t = options?.validFrom === void 0 ? now : assertEpochMs("options.validFrom", options.validFrom);
8716
- let created = null;
8717
- if (typeof replacement !== "string") {
8718
- if (typeof replacement?.title !== "string" || replacement.title.trim() === "" || typeof replacement.body !== "string") {
8719
- throw new TypeError("supersede(): replacement must be a fact id or { title, body }");
8720
- }
8721
- created = {
8722
- id: generateId("fact_"),
8723
- entity_id: entityId,
8724
- title: replacement.title,
8725
- body: replacement.body,
8726
- tags: Array.isArray(replacement.tags) ? replacement.tags : [],
8727
- confidence: replacement.confidence ?? "certain",
8728
- source_type: replacement.source_type ?? "user_stated",
8729
- source_hash: null,
8730
- source_ref: null,
8731
- created_at: now,
8732
- updated_at: now,
8733
- last_accessed_at: null,
8734
- access_count: 0,
8735
- deleted_at: null
8736
- };
8737
- }
8738
- const newId = typeof replacement === "string" ? replacement : created.id;
8739
- const newValidFrom = typeof replacement !== "string" && replacement.valid_from !== void 0 ? assertEpochMs("replacement.valid_from", replacement.valid_from) : void 0;
8740
- await this.db.withTransactionAsync(async (tx) => {
8741
- if (created) {
8742
- await this.entryRepo.upsert(created, tx);
8743
- if (newValidFrom !== void 0) {
8744
- await this.entryRepo.setTemporal(created.id, entityId, { valid_from: newValidFrom }, tx);
8745
- }
9791
+ if (typeof item === "number" && Number.isInteger(item) && item >= 0 && item < batch.length && !byItem.has(item)) {
9792
+ byItem.set(item, raw);
8746
9793
  }
8747
- await this.supersedeInTx(tx, entityId, oldId, newId, t, now);
8748
- });
8749
- await this.searchService.syncEntries(entityId, [oldId, newId]);
8750
- if (created) {
8751
- await this.embeddingService.embedFact(
8752
- { id: created.id, entity_id: entityId, title: created.title, body: created.body, tags: created.tags },
8753
- { operation: "supersede", trigger: "call" }
8754
- );
8755
9794
  }
8756
- this.searchService.evictCache(entityId);
8757
- return { newId };
9795
+ batch.forEach((g, i) => {
9796
+ const op = validateOp(byItem.get(i), aliasMapOf(g));
9797
+ if (op) out.ops.set(g, op);
9798
+ else out.rejected.push(g);
9799
+ });
8758
9800
  }
8759
- async history(entityId, factId) {
8760
- const start = await this.entryRepo.findTemporalRow(factId);
8761
- if (!start || start.entity_id !== entityId || start.deleted_at != null) return [];
8762
- const { predecessors, successors } = await this.entryRepo.findSupersessionChainIds(entityId, factId, HISTORY_MAX_DEPTH);
8763
- const facts = await this.entryRepo.findByIds([...predecessors, factId, ...successors], [entityId]);
8764
- return facts.sort((a, b) => (a.valid_from ?? a.created_at) - (b.valid_from ?? b.created_at) || a.created_at - b.created_at || a.id.localeCompare(b.id));
9801
+ if (outcome.skipped.some((s) => s.reason === "call_error")) {
9802
+ throw new Error("resolve: transient provider error; retry the pass");
8765
9803
  }
8766
- };
9804
+ for (const s of outcome.skipped) out.failed.push(s.item);
9805
+ return out;
9806
+ }
8767
9807
 
8768
9808
  // src/services/librarian/ops/apply.ts
8769
9809
  function buildSourcePointer(candidate, verdict, groundingOn, groundingCorpus) {
@@ -9030,6 +10070,7 @@ async function runLibrarianStrategy(deps, ctx) {
9030
10070
  }
9031
10071
 
9032
10072
  // src/services/MaintenanceService.ts
10073
+ var CHAIN_TRUNCATED_NOTICE = `includeChain walk stopped at the depth cap (${HISTORY_MAX_DEPTH} links per direction); the chain is longer than the ids listed. Run forget again on a remaining chain id to continue.`;
9033
10074
  var ONTOLOGY_BACKFILL_BATCH_SIZE = 25;
9034
10075
  var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
9035
10076
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -9078,6 +10119,20 @@ var formatSkipError = (err) => {
9078
10119
  }
9079
10120
  return base;
9080
10121
  };
10122
+ function eraseRuntime() {
10123
+ const g = globalThis;
10124
+ if (g.process?.versions?.node) return `node ${g.process.versions.node}`;
10125
+ return g.HermesInternal ? "hermes" : "unknown";
10126
+ }
10127
+ var EraseStepError = class extends Error {
10128
+ constructor(code, message, report, cause) {
10129
+ super(message);
10130
+ this.code = code;
10131
+ this.report = report;
10132
+ this.name = "EraseStepError";
10133
+ if (cause !== void 0) this.cause = cause;
10134
+ }
10135
+ };
9081
10136
  var MaintenanceService = class {
9082
10137
  constructor(db, prefix, options, entryRepo, sourceRefIndexRepo, taskRepo, eventRepo, metadataRepo, searchService, jobManager, embeddingService, promptService, ontologyService, edgeRepo, vectorRemoval, vectorRemovalRepo) {
9083
10138
  this.db = db;
@@ -9098,7 +10153,15 @@ var MaintenanceService = class {
9098
10153
  this.edgeRepo = edgeRepo ?? new EdgeRepository(this.db, this.prefix);
9099
10154
  }
9100
10155
  async runPrune(entityId, options) {
9101
- this.jobManager.acquireLock("prune", entityId);
10156
+ return this._runPrune(entityId, options, "host");
10157
+ }
10158
+ /**
10159
+ * Shared prune body. `owner: 'erase'` lets erase()'s own per-entity prune
10160
+ * through the universal erase fence in JobManager; the public `runPrune`
10161
+ * always passes `'host'`.
10162
+ */
10163
+ async _runPrune(entityId, options, owner) {
10164
+ this.jobManager.acquireLock("prune", entityId, void 0, owner);
9102
10165
  try {
9103
10166
  const retainSoftDeletedFor = options?.retainSoftDeletedFor !== void 0 ? options.retainSoftDeletedFor : this.options.config?.pruneRetainSoftDeletedFor ?? 7;
9104
10167
  const retainEventsFor = options?.retainEventsFor !== void 0 ? options.retainEventsFor : this.options.config?.pruneEventsAfter ?? 30;
@@ -9129,8 +10192,9 @@ var MaintenanceService = class {
9129
10192
  }
9130
10193
  }
9131
10194
  if (retainSoftDeletedFor !== null) {
9132
- const cutoff = now - retainSoftDeletedFor * 864e5;
9133
- const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff);
10195
+ const softDeletedAll = options?.softDeletedCutoff === "all";
10196
+ const cutoff = softDeletedAll ? 0 : options?.softDeletedCutoff ?? now - retainSoftDeletedFor * 864e5;
10197
+ const entriesToDelete = await this.entryRepo.getPrunableMetadata(entityId, cutoff, void 0, { noCutoff: softDeletedAll });
9134
10198
  const prunableIds = entriesToDelete.map((r) => r.id);
9135
10199
  const vr = this.vectorRemoval;
9136
10200
  const vrRepo = this.vectorRemovalRepo;
@@ -9176,7 +10240,7 @@ var MaintenanceService = class {
9176
10240
  }
9177
10241
  if (deletable.length > 0) {
9178
10242
  const deletedIds = [];
9179
- deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds });
10243
+ deletedEntries = await this.entryRepo.bulkDeletePruned(entityId, cutoff, deletable, tx, { keepUnconfirmedRemovals: hookLedger, deletedIds, noCutoff: softDeletedAll });
9180
10244
  if (hookLedger) {
9181
10245
  const gone = new Set(deletedIds);
9182
10246
  const skipped = deletable.filter((id) => !gone.has(id));
@@ -9191,7 +10255,7 @@ var MaintenanceService = class {
9191
10255
  else await vrRepo.deleteForFacts(entityId, deletable, tx, "confirmedGone");
9192
10256
  }
9193
10257
  }
9194
- deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx);
10258
+ deletedTasks = await this.taskRepo.bulkDeletePruned(entityId, cutoff, tx, { noCutoff: softDeletedAll });
9195
10259
  });
9196
10260
  if (hookLedger) {
9197
10261
  const keptSet = new Set(kept);
@@ -9236,12 +10300,20 @@ var MaintenanceService = class {
9236
10300
  }
9237
10301
  }
9238
10302
  }
10303
+ let vacuumCheckpointErr;
9239
10304
  if (vacuum) {
9240
- await resetNormalizeWatermarks(this.metadataRepo);
9241
- await this.metadataRepo.vacuum();
9242
- await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
10305
+ try {
10306
+ await this._wrappedVacuum();
10307
+ } catch (err) {
10308
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
10309
+ vacuumCheckpointErr = err;
10310
+ }
9243
10311
  }
10312
+ if (options?.syncedIds) for (const id of syncedIds) options.syncedIds.push(id);
9244
10313
  await this.searchService.syncEntries(entityId, syncedIds);
10314
+ if (prunePartial && vacuumCheckpointErr) {
10315
+ emitDiagnostic(this.options, { code: "prune_checkpoint_incomplete", operation: "prune", trigger: "call", entityId, detail: { reason: vacuumCheckpointErr.message } });
10316
+ }
9245
10317
  if (prunePartial) {
9246
10318
  throw new PrunePartialFailureError(
9247
10319
  deletedEntries,
@@ -9252,11 +10324,327 @@ var MaintenanceService = class {
9252
10324
  deletedEvents
9253
10325
  );
9254
10326
  }
10327
+ if (vacuumCheckpointErr) throw vacuumCheckpointErr;
9255
10328
  return { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents };
9256
10329
  } finally {
9257
10330
  this.jobManager.releaseLock("prune", entityId);
9258
10331
  }
9259
10332
  }
10333
+ /** Shared by runPrune and erase step 5. */
10334
+ async _wrappedVacuum() {
10335
+ await resetNormalizeWatermarks(this.metadataRepo);
10336
+ let checkpointErr;
10337
+ try {
10338
+ await this.metadataRepo.vacuum();
10339
+ } catch (err) {
10340
+ if (!(err instanceof CheckpointIncompleteError)) throw err;
10341
+ checkpointErr = err;
10342
+ }
10343
+ await restartRebuildAfterVacuum(this.db, this.prefix, this.metadataRepo);
10344
+ if (checkpointErr) throw checkpointErr;
10345
+ }
10346
+ /**
10347
+ * Erase core (forget-erasure spec §2, steps 0 / 1 / 1b). Thin entry: T6
10348
+ * completes the pipeline (FTS, VACUUM, checkpoint, sync). Never reports a
10349
+ * success it cannot verify: a failed step throws {@link EraseStepError}
10350
+ * carrying the partial report with `verified: false`.
10351
+ */
10352
+ async erase(opts) {
10353
+ const rebuild = opts?.rebuild === true;
10354
+ this.jobManager.acquireLock("erase", "*");
10355
+ const report = {
10356
+ verified: false,
10357
+ secureDelete: null,
10358
+ sqliteVersion: "",
10359
+ entities: [],
10360
+ holds: [],
10361
+ skipped: [],
10362
+ syncedIds: [],
10363
+ registrySweep: { skipped: false, deleted: 0 },
10364
+ retiredUndroppable: [],
10365
+ failedStep: null,
10366
+ runtime: eraseRuntime(),
10367
+ steps: []
10368
+ };
10369
+ const ok = (step, outcome = "ok") => {
10370
+ report.steps.push({ step, outcome });
10371
+ };
10372
+ try {
10373
+ const readPragma = async () => (await this.db.getFirstAsync("PRAGMA secure_delete"))?.secure_delete ?? null;
10374
+ let pragma;
10375
+ try {
10376
+ pragma = await readPragma();
10377
+ if (pragma !== 1) {
10378
+ await this.db.execAsync("PRAGMA secure_delete=ON");
10379
+ pragma = await readPragma();
10380
+ }
10381
+ report.secureDelete = pragma;
10382
+ report.sqliteVersion = (await this.db.getFirstAsync("SELECT sqlite_version() AS v"))?.v ?? "";
10383
+ } catch (err) {
10384
+ report.failedStep = "secure_delete";
10385
+ throw new EraseStepError("erase_secure_delete_read_failed", "erase stopped at step 0: secure_delete pragma read failed; erasure is unverified", report, err);
10386
+ }
10387
+ if (pragma !== 1) {
10388
+ emitDiagnostic(this.options, { code: "erase_secure_delete_off", operation: "erase", trigger: "call", entityId: "" });
10389
+ report.failedStep = "secure_delete";
10390
+ throw new EraseStepError("erase_secure_delete_off", "erase stopped at step 0: secure_delete is not ON; erasure is unverified", report);
10391
+ }
10392
+ ok("secure_delete");
10393
+ try {
10394
+ report.entities = await this.metadataRepo.getDistinctEntityIds(void 0, { softDeletedAll: true });
10395
+ } catch (err) {
10396
+ report.failedStep = "prune";
10397
+ throw new EraseStepError("erase_prune_failed", "erase stopped at step 1: the entity walk failed; erasure is unverified", report, err);
10398
+ }
10399
+ const syncedByEntity = /* @__PURE__ */ new Map();
10400
+ for (const entityId of report.entities) {
10401
+ const syncedIds = [];
10402
+ syncedByEntity.set(entityId, syncedIds);
10403
+ try {
10404
+ await this._runPrune(entityId, { retainSoftDeletedFor: 0, retainEventsFor: null, vacuum: false, syncedIds, softDeletedCutoff: "all" }, "erase");
10405
+ } catch (err) {
10406
+ if (err instanceof PrunePartialFailureError) {
10407
+ report.holds.push({ entityId, deleted: err.deleted, deletedTasks: err.deletedTasks, failedAt: err.failedAt, remaining: err.remaining });
10408
+ } else if (err instanceof WikiBusyError) {
10409
+ report.skipped.push(entityId);
10410
+ emitDiagnostic(this.options, { code: "erase_entity_skipped", operation: "erase", trigger: "call", entityId });
10411
+ } else {
10412
+ report.failedStep = "prune";
10413
+ throw new EraseStepError("erase_prune_failed", `erase stopped at step 1 (entity ${entityId})`, report, err);
10414
+ }
10415
+ }
10416
+ for (const id of syncedIds) report.syncedIds.push(id);
10417
+ }
10418
+ ok("prune", report.holds.length > 0 || report.skipped.length > 0 ? "partial" : "ok");
10419
+ try {
10420
+ await this.db.withTransactionAsync(async (tx) => {
10421
+ if (await this.sourceRefIndexPresent(tx)) {
10422
+ const r = await tx.runAsync(`DELETE FROM ${this.prefix}source_ref_index WHERE deleted_at IS NOT NULL`);
10423
+ report.registrySweep = { skipped: false, deleted: r.changes };
10424
+ } else {
10425
+ report.registrySweep = { skipped: true, deleted: 0 };
10426
+ }
10427
+ });
10428
+ } catch (err) {
10429
+ report.failedStep = "registry_sweep";
10430
+ throw new EraseStepError("erase_registry_sweep_failed", "erase stopped at step 1b", report, err);
10431
+ }
10432
+ if (report.registrySweep.skipped) {
10433
+ emitDiagnostic(this.options, { code: "erase_registry_sweep_skipped", operation: "erase", trigger: "call", entityId: "" });
10434
+ }
10435
+ ok("registry_sweep", report.registrySweep.skipped ? "partial" : "ok");
10436
+ await this._eraseDrainPassages(report);
10437
+ ok("passage_drain");
10438
+ await this._eraseReclaimRetired(report);
10439
+ ok("retired_reclaim");
10440
+ try {
10441
+ await this._wrappedVacuum();
10442
+ } catch (err) {
10443
+ if (err instanceof CheckpointIncompleteError) {
10444
+ report.failedStep = "checkpoint";
10445
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 5: WAL checkpoint incomplete; erasure is unverified", report, err);
10446
+ }
10447
+ report.failedStep = "vacuum";
10448
+ throw new EraseStepError("erase_vacuum_failed", "erase stopped at step 5: VACUUM failed (commonly an unfenced writer holding the database \u2014 quiesce and retry; also any other VACUUM failure, e.g. disk-full or I/O errors)", report, err);
10449
+ }
10450
+ ok("vacuum");
10451
+ const byEntity = /* @__PURE__ */ new Map();
10452
+ for (const e of report.entities) byEntity.set(e, []);
10453
+ for (const [entityId, ids] of syncedByEntity) byEntity.set(entityId, ids);
10454
+ for (const [entityId, ids] of byEntity) {
10455
+ if (ids.length > 0) await this._eraseSyncEntries(entityId, ids, report);
10456
+ }
10457
+ ok("index_sync");
10458
+ if (rebuild) {
10459
+ try {
10460
+ await this.searchService.rebuildSurfaced();
10461
+ } catch (err) {
10462
+ report.failedStep = "rebuild";
10463
+ throw new EraseStepError("erase_rebuild_failed", "erase stopped at step 7: FTS rebuild failed", report, err);
10464
+ }
10465
+ ok("rebuild");
10466
+ }
10467
+ await this._eraseReclaimRetired(report);
10468
+ let present;
10469
+ try {
10470
+ present = await this.db.getAllAsync(
10471
+ `SELECT name FROM sqlite_master WHERE type = 'table' AND name LIKE '%entries_fts_retired_%'`
10472
+ );
10473
+ } catch (err) {
10474
+ report.failedStep = "retired_reclaim";
10475
+ emitDiagnostic(this.options, { code: "erase_retired_read_failed", operation: "erase", trigger: "call", entityId: "" });
10476
+ throw new EraseStepError("erase_retired_read_failed", "erase stopped after step 6: the retired-table read failed; erasure is unverified", report, err);
10477
+ }
10478
+ const left = present.map((r) => r.name).filter((n) => isRetiredTableName(this.prefix, n) && !report.retiredUndroppable.includes(n));
10479
+ if (left.length > 0) {
10480
+ report.failedStep = "retired_reclaim";
10481
+ emitDiagnostic(this.options, { code: "erase_retired_remaining", operation: "erase", trigger: "call", entityId: "", detail: { tables: left } });
10482
+ throw new EraseStepError("erase_retired_remaining", `erase stopped after step 6: retired FTS tables remain (${left.join(", ")})`, report);
10483
+ }
10484
+ ok("retired_reclaim_rerun");
10485
+ await this._eraseOptimize(report);
10486
+ ok("optimize");
10487
+ try {
10488
+ await this.metadataRepo.checkpointTruncateVerified();
10489
+ } catch (err) {
10490
+ report.failedStep = "checkpoint";
10491
+ throw new EraseStepError("erase_checkpoint_incomplete", "erase stopped at step 8: WAL checkpoint incomplete; erasure is unverified", report, err);
10492
+ }
10493
+ ok("checkpoint");
10494
+ if (report.skipped.length === 0 && report.holds.length === 0) {
10495
+ let remainingTombstones;
10496
+ try {
10497
+ const row = await this.db.getFirstAsync(
10498
+ `SELECT (SELECT COUNT(*) FROM ${this.prefix}entries WHERE deleted_at IS NOT NULL)
10499
+ + (SELECT COUNT(*) FROM ${this.prefix}tasks WHERE deleted_at IS NOT NULL) AS n`
10500
+ );
10501
+ remainingTombstones = row?.n ?? 0;
10502
+ } catch (err) {
10503
+ report.failedStep = "tombstone_gate";
10504
+ throw new EraseStepError("erase_tombstone_gate_failed", "erase stopped at step 9: could not count remaining tombstones; erasure is unverified", report, err);
10505
+ }
10506
+ if (remainingTombstones > 0) {
10507
+ emitDiagnostic(this.options, { code: "erase_tombstones_remaining", operation: "erase", trigger: "call", entityId: "", detail: { count: remainingTombstones } });
10508
+ report.failedStep = "tombstone_gate";
10509
+ throw new EraseStepError("erase_tombstones_remaining", `erase stopped at step 9: ${remainingTombstones} soft-deleted row(s) remain; erasure is unverified`, report);
10510
+ }
10511
+ ok("tombstone_gate");
10512
+ } else {
10513
+ report.steps.push({ step: "tombstone_gate", outcome: "partial" });
10514
+ }
10515
+ report.verified = report.skipped.length === 0 && report.holds.length === 0;
10516
+ return report;
10517
+ } catch (err) {
10518
+ if (err instanceof EraseStepError && err.report === report && report.failedStep) {
10519
+ report.steps.push({ step: report.failedStep, outcome: "failed" });
10520
+ report.verified = false;
10521
+ }
10522
+ throw err;
10523
+ } finally {
10524
+ this.jobManager.releaseLock("erase", "*");
10525
+ }
10526
+ }
10527
+ // ── Erase FTS surfaces (spec §2 steps 3/4/6-sync/7). T6 composes these into erase(). ──
10528
+ /**
10529
+ * Step 3: chained, surfaced drains (no deadline). Entries-ledger failures are
10530
+ * the entries/index-sync step (`index_sync`); passage failures `passage_drain`.
10531
+ * N2 guard (probe lives here, strategy-agnostic): a strategy without the strict
10532
+ * drains (Unavailable / MiniSearch) cannot drain, so rows in either FTS ledger
10533
+ * mean text was never drained -> the step fails and erasure is unverified.
10534
+ * Absent or empty ledgers proceed.
10535
+ */
10536
+ async _eraseDrainPassages(report) {
10537
+ if (!this.searchService.hasStrictDrain()) {
10538
+ for (const [table, failedStep, code] of [
10539
+ [`${this.prefix}fts_pending`, "index_sync", "erase_index_sync_failed"],
10540
+ [`${this.prefix}source_passages_fts_pending`, "passage_drain", "erase_passage_drain_failed"]
10541
+ ]) {
10542
+ let rows = false;
10543
+ try {
10544
+ rows = await this.sourceTableExists(table) && await this.db.getFirstAsync(`SELECT 1 AS x FROM ${table} LIMIT 1`) != null;
10545
+ } catch (err) {
10546
+ report.failedStep = failedStep;
10547
+ throw new EraseStepError(code, `erase stopped at step 3: could not probe ${table}`, report, err);
10548
+ }
10549
+ if (rows) {
10550
+ report.failedStep = failedStep;
10551
+ throw new EraseStepError(code, `erase stopped at step 3: ${table} holds undrained rows and the FTS index strategy cannot drain them; erasure is unverified`, report);
10552
+ }
10553
+ }
10554
+ for (const suffix of ["entries_fts_content", "source_passages_fts_content"]) {
10555
+ let orphaned = false;
10556
+ try {
10557
+ orphaned = await this.sourceTableExists(`${this.prefix}${suffix}`);
10558
+ } catch (err) {
10559
+ report.failedStep = "index_sync";
10560
+ throw new EraseStepError("erase_orphaned_fts_content", `erase stopped: could not probe ${this.prefix}${suffix}`, report, err);
10561
+ }
10562
+ if (orphaned) {
10563
+ report.failedStep = "index_sync";
10564
+ throw new EraseStepError("erase_orphaned_fts_content", "erase stopped: orphaned full-text content tables may still hold forgotten text", report);
10565
+ }
10566
+ }
10567
+ }
10568
+ try {
10569
+ await this.searchService.drainEntriesLedgerSurfaced();
10570
+ } catch (err) {
10571
+ report.failedStep = "index_sync";
10572
+ throw new EraseStepError("erase_index_sync_failed", "erase stopped at step 3: entries ledger drain failed", report, err);
10573
+ }
10574
+ try {
10575
+ await this.searchService.drainPassagesSurfaced();
10576
+ } catch (err) {
10577
+ report.failedStep = "passage_drain";
10578
+ throw new EraseStepError("erase_passage_drain_failed", "erase stopped at step 3: passage drain failed", report, err);
10579
+ }
10580
+ }
10581
+ /**
10582
+ * Step 4 (and its re-run after step 6): reclaim retired FTS tables to
10583
+ * completion. A module-less runtime cannot DROP a virtual table, so each
10584
+ * retired table's shadow tables are emptied under the pragma and the name
10585
+ * stays listed; a later FTS5-capable open's step 4 completes the DROP.
10586
+ */
10587
+ async _eraseReclaimRetired(report) {
10588
+ if (this.searchService.canReclaimRetired()) {
10589
+ try {
10590
+ await this.searchService.reclaimRetiredSurfaced();
10591
+ return;
10592
+ } catch (err) {
10593
+ if (!/no such module/i.test(err instanceof Error ? err.message : String(err))) {
10594
+ report.failedStep = "retired_reclaim";
10595
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: retired FTS table reclaim failed", report, err);
10596
+ }
10597
+ }
10598
+ }
10599
+ try {
10600
+ for (const name of await this._retiredList()) {
10601
+ for (const sfx of ["_content", "_data", "_idx", "_docsize", "_config"]) {
10602
+ if (await this.sourceTableExists(`${name}${sfx}`)) await this.db.runAsync(`DELETE FROM ${name}${sfx}`);
10603
+ }
10604
+ if (!report.retiredUndroppable.includes(name)) report.retiredUndroppable.push(name);
10605
+ emitDiagnostic(this.options, { code: "erase_retired_vtab_undroppable", operation: "erase", trigger: "call", entityId: "" });
10606
+ }
10607
+ } catch (err) {
10608
+ report.failedStep = "retired_reclaim";
10609
+ throw new EraseStepError("erase_retired_reclaim_failed", "erase stopped at step 4: module-less shadow-table clear failed", report, err);
10610
+ }
10611
+ }
10612
+ /** Retired list straight from metadata (same key Fts5IndexStrategy maintains), independent of the active strategy. */
10613
+ async _retiredList() {
10614
+ let raw;
10615
+ try {
10616
+ raw = JSON.parse(await this.metadataRepo.getMeta(FTS5_RETIRED_TABLES_KEY) ?? "[]");
10617
+ } catch {
10618
+ return [];
10619
+ }
10620
+ return Array.isArray(raw) ? raw.filter((n) => isRetiredTableName(this.prefix, n)) : [];
10621
+ }
10622
+ sourceTableExists(name) {
10623
+ return this.metadataRepo.tableExists(name);
10624
+ }
10625
+ /** Step 6 sync: `syncEntries` resolving false means the ledger drain failed — a failed step. */
10626
+ async _eraseSyncEntries(entityId, ids, report) {
10627
+ let ok = false;
10628
+ try {
10629
+ ok = await this.searchService.syncEntries(entityId, ids);
10630
+ } catch (err) {
10631
+ report.failedStep = "index_sync";
10632
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId})`, report, err);
10633
+ }
10634
+ if (!ok) {
10635
+ report.failedStep = "index_sync";
10636
+ throw new EraseStepError("erase_index_sync_failed", `erase stopped at index sync (entity ${entityId}): ledger drain failed`, report);
10637
+ }
10638
+ }
10639
+ /** Step 7: FTS optimize on both FTS tables, after syncEntries. */
10640
+ async _eraseOptimize(report) {
10641
+ try {
10642
+ await this.searchService.optimizeSurfaced();
10643
+ } catch (err) {
10644
+ report.failedStep = "optimize";
10645
+ throw new EraseStepError("erase_optimize_failed", "erase stopped at step 7: FTS optimize failed", report, err);
10646
+ }
10647
+ }
9260
10648
  async runLibrarian(entityId, options) {
9261
10649
  this.jobManager.acquireLock("librarian", entityId);
9262
10650
  try {
@@ -9377,6 +10765,9 @@ var MaintenanceService = class {
9377
10765
  if (params.includeEvents && !params.clearAll) {
9378
10766
  throw new Error("forget() includeEvents requires clearAll: true");
9379
10767
  }
10768
+ if (params.includeChain && (params.entryId === void 0 || params.clearAll || params.taskId !== void 0 || params.sourceRef !== void 0 || params.sourceHash !== void 0)) {
10769
+ throw new Error("forget() includeChain composes only with entryId");
10770
+ }
9380
10771
  if (opts?.dryRun === true) {
9381
10772
  return this.forgetDryRun(entityId, params);
9382
10773
  }
@@ -9386,6 +10777,8 @@ var MaintenanceService = class {
9386
10777
  let deletedEntries = 0;
9387
10778
  let deletedTasks = 0;
9388
10779
  let deletedEvents = 0;
10780
+ let chainIds = [];
10781
+ let chainTruncated = false;
9389
10782
  const deletedEntryIds = [];
9390
10783
  const ledgerOn = !!this.vectorRemoval && !!this.vectorRemovalRepo && await this.vectorRemoval.ledgerPresent();
9391
10784
  await this.db.withTransactionAsync(async (tx) => {
@@ -9396,6 +10789,10 @@ var MaintenanceService = class {
9396
10789
  if (await this.sourceRefIndexPresent(tx)) {
9397
10790
  await this.sourceRefIndexRepo.deleteByEntityId(entityId, tx);
9398
10791
  }
10792
+ if (await this.sourceStorePresent(tx)) {
10793
+ await tx.runAsync(`DELETE FROM ${this.prefix}source_passages WHERE entity_id = ?`, [entityId]);
10794
+ await tx.runAsync(`DELETE FROM ${this.prefix}source_documents WHERE entity_id = ?`, [entityId]);
10795
+ }
9399
10796
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
9400
10797
  if (params.includeEvents) {
9401
10798
  deletedEvents = (await this.eventRepo.deleteByEntityId(entityId, tx)).changes;
@@ -9418,6 +10815,22 @@ var MaintenanceService = class {
9418
10815
  if (params.entryId) {
9419
10816
  const entryId = await this.entryRepo.findIdById(params.entryId, entityId, tx);
9420
10817
  if (entryId) deletedEntryIds.push(entryId);
10818
+ if (entryId && params.includeChain) {
10819
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, entryId, HISTORY_MAX_DEPTH, tx);
10820
+ chainIds = walk.ids.filter((id) => id !== entryId);
10821
+ chainTruncated = walk.truncated;
10822
+ for (const id of chainIds) deletedEntryIds.push(id);
10823
+ }
10824
+ }
10825
+ if ((sourceRef || sourceHash) && await this.sourceStorePresent(tx)) {
10826
+ const docs = `${this.prefix}source_documents`;
10827
+ const sel = "entity_id = ? AND (? IS NULL OR source_ref = ?) AND (? IS NULL OR source_hash = ?)";
10828
+ const selArgs = [entityId, sourceRef, sourceRef, sourceHash, sourceHash];
10829
+ await tx.runAsync(
10830
+ `DELETE FROM ${this.prefix}source_passages WHERE entity_id = ? AND document_id IN (SELECT id FROM ${docs} WHERE ${sel})`,
10831
+ [entityId, ...selArgs]
10832
+ );
10833
+ await tx.runAsync(`DELETE FROM ${docs} WHERE ${sel}`, selArgs);
9421
10834
  }
9422
10835
  if (sourceRef || sourceHash) {
9423
10836
  for (const id of await this.entryRepo.findIdsBySource(entityId, sourceRef, sourceHash, tx, true)) deletedEntryIds.push(id);
@@ -9433,6 +10846,9 @@ var MaintenanceService = class {
9433
10846
  sourceRefIndexPromise ?? Promise.resolve(void 0)
9434
10847
  ]);
9435
10848
  if (entryResult) deletedEntries++;
10849
+ for (const id of chainIds) {
10850
+ if ((await this.entryRepo.softDelete(id, entityId, tx)).changes > 0) deletedEntries++;
10851
+ }
9436
10852
  if (taskResult) deletedTasks++;
9437
10853
  deletedEntries += refResult;
9438
10854
  }
@@ -9486,7 +10902,17 @@ var MaintenanceService = class {
9486
10902
  });
9487
10903
  }
9488
10904
  }
9489
- if (!params.clearAll) return { deleted: { entries: deletedEntries, tasks: deletedTasks } };
10905
+ if (!params.clearAll) {
10906
+ const base = { deleted: { entries: deletedEntries, tasks: deletedTasks } };
10907
+ if (params.includeChain) {
10908
+ base.chainEntryIds = chainIds;
10909
+ if (chainTruncated) {
10910
+ base.truncated = true;
10911
+ base.notice = CHAIN_TRUNCATED_NOTICE;
10912
+ }
10913
+ }
10914
+ return base;
10915
+ }
9490
10916
  return params.includeEvents ? { deleted: { entries: deletedEntries, tasks: deletedTasks, events: deletedEvents }, metadataReset: true } : { deleted: { entries: deletedEntries, tasks: deletedTasks }, metadataReset: true };
9491
10917
  } finally {
9492
10918
  this.jobManager.releaseLock("forget", entityId);
@@ -9535,6 +10961,10 @@ var MaintenanceService = class {
9535
10961
  if (version < 9) return false;
9536
10962
  throw new Error(`forget(): source_ref_index is missing on a schema_version=${version} database; run setup()`);
9537
10963
  }
10964
+ /** A never-set-up store has no source-store tables (#316 recovery); nothing to delete there. */
10965
+ async sourceStorePresent(tx) {
10966
+ return await this.metadataRepo.tableExists(`${this.prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${this.prefix}source_passages`, tx);
10967
+ }
9538
10968
  /**
9539
10969
  * Read-only dry-run preview of {@link forget}. Returns the same shape as a
9540
10970
  * real call would, without acquiring the lock, opening a transaction, staging
@@ -9548,8 +10978,25 @@ var MaintenanceService = class {
9548
10978
  * (the spec keeps dry-run narrow).
9549
10979
  */
9550
10980
  async forgetDryRun(entityId, params) {
10981
+ if (params.entryId !== void 0 && params.includeChain && params.taskId === void 0) {
10982
+ const id = await this.entryRepo.findIdById(params.entryId, entityId);
10983
+ if (!id) return { deleted: { entries: 0, tasks: 0 }, chainEntryIds: [] };
10984
+ const walk = await this.entryRepo.findSupersessionChainWalk(entityId, id, HISTORY_MAX_DEPTH);
10985
+ const chainEntryIds = walk.ids.filter((c) => c !== id);
10986
+ const all = [id, ...chainEntryIds];
10987
+ const live = await this.db.getFirstAsync(
10988
+ `SELECT COUNT(*) AS n FROM ${this.prefix}entries WHERE entity_id = ? AND deleted_at IS NULL AND id IN (${all.map(() => "?").join(",")})`,
10989
+ [entityId, ...all]
10990
+ );
10991
+ const out = { deleted: { entries: live?.n ?? 0, tasks: 0 }, chainEntryIds };
10992
+ if (walk.truncated) {
10993
+ out.truncated = true;
10994
+ out.notice = CHAIN_TRUNCATED_NOTICE;
10995
+ }
10996
+ return out;
10997
+ }
9551
10998
  if (params.entryId !== void 0 || params.taskId !== void 0) {
9552
- throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors; use sourceRef/sourceHash or clearAll");
10999
+ throw new Error("forget({ dryRun: true }) does not support entryId/taskId selectors (entryId is accepted only with includeChain); use sourceRef/sourceHash or clearAll");
9553
11000
  }
9554
11001
  if (params.clearAll) {
9555
11002
  const entries2 = await this.entryRepo.countLiveByEntityId(entityId);
@@ -10582,7 +12029,7 @@ var MAX_EMBEDDING_BLOB_BYTES = 32 * 1024;
10582
12029
  var IMPORT_TITLE_MAX = 500;
10583
12030
  var IMPORT_BODY_MAX = 8e3;
10584
12031
  var ImportExportService = class {
10585
- constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval) {
12032
+ constructor(db, entryRepo, taskRepo, eventRepo, edgeRepo, metadataRepo, searchService, jobManager, embeddingService, options = {}, vectorRemoval, prefix) {
10586
12033
  this.db = db;
10587
12034
  this.entryRepo = entryRepo;
10588
12035
  this.taskRepo = taskRepo;
@@ -10594,13 +12041,22 @@ var ImportExportService = class {
10594
12041
  this.embeddingService = embeddingService;
10595
12042
  this.options = options;
10596
12043
  this.vectorRemoval = vectorRemoval;
12044
+ this.prefix = prefix;
10597
12045
  }
10598
- async exportDump(entityIds) {
12046
+ async exportDump(entityIds, opts) {
12047
+ const includeForgotten = opts?.includeForgotten === true;
10599
12048
  let ids;
10600
12049
  if (entityIds && entityIds.length > 0) {
10601
12050
  ids = Array.from(new Set(entityIds));
10602
12051
  } else {
10603
12052
  ids = await this.metadataRepo.getDistinctEntityIds();
12053
+ const prefix = this.storePrefix();
12054
+ if (prefix !== void 0 && await this.storePresent(prefix)) {
12055
+ const rows = await this.db.getAllAsync(
12056
+ `SELECT DISTINCT entity_id FROM ${prefix}source_documents`
12057
+ );
12058
+ ids = Array.from(/* @__PURE__ */ new Set([...ids, ...rows.map((r) => r.entity_id)])).sort();
12059
+ }
10604
12060
  }
10605
12061
  const entities = {};
10606
12062
  const BATCH = 3;
@@ -10608,10 +12064,11 @@ var ImportExportService = class {
10608
12064
  const batch = ids.slice(i, i + BATCH);
10609
12065
  const batchResults = await Promise.all(
10610
12066
  batch.map(
10611
- async (id) => [
10612
- id,
10613
- await this.getFullBundle(id, { includeBlobs: true })
10614
- ]
12067
+ async (id) => {
12068
+ const bundle = await this.getFullBundle(id, { includeBlobs: true, includeForgotten });
12069
+ const storedSources = await this.exportStoredSources(id);
12070
+ return [id, storedSources.length > 0 ? { ...bundle, storedSources } : bundle];
12071
+ }
10615
12072
  )
10616
12073
  );
10617
12074
  for (const [id, bundle] of batchResults) {
@@ -10622,22 +12079,103 @@ var ImportExportService = class {
10622
12079
  }
10623
12080
  async importDump(dump, opts) {
10624
12081
  const merge = opts?.merge ?? false;
12082
+ const skippedSources = [];
10625
12083
  const entityIds = Object.keys(dump.entities);
10626
12084
  this.jobManager.acquireImportLocks(entityIds);
10627
12085
  try {
10628
12086
  await this.assertNoLegacySourceTypes();
10629
12087
  for (const [entityId, bundle] of Object.entries(dump.entities)) {
10630
- await this.doImportEntity(entityId, bundle, merge);
12088
+ skippedSources.push(...await this.doImportEntity(entityId, bundle, merge));
10631
12089
  }
10632
12090
  } finally {
10633
12091
  this.jobManager.releaseImportLocks(entityIds);
10634
12092
  }
12093
+ return { skippedSources };
12094
+ }
12095
+ storePrefix() {
12096
+ return typeof this.prefix === "string" ? this.prefix : void 0;
12097
+ }
12098
+ // `source_ref_index` needs no check: the v9 migration (add_source_ref_index) creates it, and the
12099
+ // store tables come from v17, which only runs after v9 — so it exists whenever they do.
12100
+ async storePresent(prefix, tx) {
12101
+ return await this.metadataRepo.tableExists(`${prefix}source_documents`, tx) && await this.metadataRepo.tableExists(`${prefix}source_passages`, tx);
12102
+ }
12103
+ /** Spec source-store §8: stored sources for one exported entity; [] when none. */
12104
+ async exportStoredSources(entityId) {
12105
+ const prefix = this.storePrefix();
12106
+ if (prefix === void 0 || !await this.storePresent(prefix)) return [];
12107
+ const docs = await this.db.getAllAsync(
12108
+ `SELECT id, source_ref, source_hash, text, text_hash, char_count, created_at FROM ${prefix}source_documents
12109
+ WHERE entity_id = ? ORDER BY source_ref COLLATE BINARY`,
12110
+ [entityId]
12111
+ );
12112
+ const out = [];
12113
+ for (const d of docs) {
12114
+ const ps = await this.db.getAllAsync(
12115
+ `SELECT seq, start_offset, end_offset FROM ${prefix}source_passages
12116
+ WHERE entity_id = ? AND document_id = ? ORDER BY seq`,
12117
+ [entityId, d.id]
12118
+ );
12119
+ out.push({
12120
+ sourceRef: d.source_ref,
12121
+ sourceHash: d.source_hash,
12122
+ text: d.text,
12123
+ textHash: d.text_hash,
12124
+ charCount: Number(d.char_count),
12125
+ storedAt: Number(d.created_at),
12126
+ passages: ps.map((p) => ({ seq: Number(p.seq), startOffset: Number(p.start_offset), endOffset: Number(p.end_offset) }))
12127
+ });
12128
+ }
12129
+ return out;
12130
+ }
12131
+ /**
12132
+ * Spec source-store §8/§9 import step, inside the import transaction. One
12133
+ * source at a time; a refusal skips that source only. Uses the
12134
+ * same upsert helper as SourceStoreService.storeSource, inside this transaction. A ref already stored is replaced: the dump is the
12135
+ * truth for that ref (so no hash_mismatch refusal on import).
12136
+ */
12137
+ async importStoredSources(tx, entityId, sources, merge, skipped, deferredDiagnostics) {
12138
+ const prefix = this.storePrefix();
12139
+ if (prefix === void 0) return;
12140
+ if (merge && !sources?.length) return;
12141
+ if (!await this.storePresent(prefix, tx)) return;
12142
+ const docs = `${prefix}source_documents`;
12143
+ const passages = `${prefix}source_passages`;
12144
+ if (!merge) {
12145
+ await tx.runAsync(`DELETE FROM ${passages} WHERE entity_id = ?`, [entityId]);
12146
+ await tx.runAsync(`DELETE FROM ${docs} WHERE entity_id = ?`, [entityId]);
12147
+ }
12148
+ const cfg = this.options.config?.sourceStore;
12149
+ const lim = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.floor(v) : d;
12150
+ const limits = {
12151
+ maxCharsPerSource: lim(cfg?.maxCharsPerSource, DEFAULT_MAX_CHARS_PER_SOURCE),
12152
+ maxTotalChars: lim(cfg?.maxTotalChars, DEFAULT_MAX_TOTAL_CHARS)
12153
+ };
12154
+ for (const src of sources ?? []) {
12155
+ const sourceRef = normalizeSourceRef(src?.sourceRef);
12156
+ const sourceHash = normalizeSourceHash(src?.sourceHash);
12157
+ if (!sourceRef || !sourceHash || typeof src.text !== "string") {
12158
+ throw new Error(`importDump: invalid stored source for entity "${entityId}" (sourceRef, sourceHash and text are required)`);
12159
+ }
12160
+ await upsertStoredSource(
12161
+ tx,
12162
+ prefix,
12163
+ entityId,
12164
+ { sourceRef, sourceHash, text: src.text, storedAt: src.storedAt },
12165
+ limits,
12166
+ (code) => {
12167
+ skipped.push({ sourceRef, code });
12168
+ deferredDiagnostics.push({ code, operation: "importDump", trigger: "call", entityId, detail: { sourceRef } });
12169
+ }
12170
+ );
12171
+ }
10635
12172
  }
10636
12173
  async getFullBundle(entityId, opts) {
12174
+ const incl = opts?.includeForgotten ? { includeDeleted: true } : void 0;
10637
12175
  const wm = await this.metadataRepo.getLibrarianWatermark(entityId, this.db);
10638
12176
  const [factsRaw, tasks, events, edges, summaryValue] = await Promise.all([
10639
- opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId) : this.entryRepo.findAllByEntityId(entityId),
10640
- this.taskRepo.findAllByEntityId(entityId),
12177
+ opts?.includeBlobs ? this.entryRepo.findAllByEntityIdWithBlobs(entityId, void 0, incl) : this.entryRepo.findAllByEntityId(entityId, void 0, incl),
12178
+ this.taskRepo.findAllByEntityId(entityId, void 0, incl),
10641
12179
  this.eventRepo.getByEntityId(entityId, opts?.maxEvents),
10642
12180
  this.edgeRepo.getByEntityId(entityId),
10643
12181
  this.metadataRepo.getMeta(entitySummaryMetaKey(entityId))
@@ -10670,13 +12208,18 @@ var ImportExportService = class {
10670
12208
  }
10671
12209
  /** Single-entity import transaction + post-processing; package-internal hook for tests. */
10672
12210
  async doImportEntity(entityId, bundle, merge) {
12211
+ const skippedSources = [];
12212
+ const refusalDiagnostics = [];
10673
12213
  const upsertedFactIds = /* @__PURE__ */ new Set();
12214
+ const liveEmbedFactIds = /* @__PURE__ */ new Set();
10674
12215
  const upsertedDeletedFactIds = /* @__PURE__ */ new Set();
10675
12216
  const factsWithPreservedBlob = /* @__PURE__ */ new Map();
10676
12217
  const preservedBlobDims = /* @__PURE__ */ new Set();
10677
12218
  const softDeletedFactIds = [];
12219
+ const softDeletedTaskIds = [];
10678
12220
  const clippedTextByFactId = /* @__PURE__ */ new Map();
10679
12221
  let clampedEvents = 0;
12222
+ let tombstoneSkipped = 0;
10680
12223
  const restamped = { behind_watermark: 0, invalid: 0 };
10681
12224
  await this.db.withTransactionAsync(async (tx) => {
10682
12225
  if (!merge) {
@@ -10687,8 +12230,9 @@ var ImportExportService = class {
10687
12230
  tx,
10688
12231
  false
10689
12232
  );
10690
- softDeletedFactIds.push(...deletedLiveFactIds);
12233
+ for (const fid of deletedLiveFactIds) softDeletedFactIds.push(fid);
10691
12234
  await this.entryRepo.bulkSoftDeleteByEntityId(entityId, tx);
12235
+ for (const t of await this.taskRepo.findAllByEntityId(entityId, tx)) softDeletedTaskIds.push(t.id);
10692
12236
  await this.taskRepo.bulkSoftDeleteByEntityId(entityId, tx);
10693
12237
  await this.edgeRepo.bulkDeleteByEntityId(entityId, tx);
10694
12238
  await this.metadataRepo.deleteCheckpoint(entityId, tx);
@@ -10698,6 +12242,8 @@ var ImportExportService = class {
10698
12242
  } else if (!merge) {
10699
12243
  await this.metadataRepo.deleteMeta(entitySummaryMetaKey(entityId), tx);
10700
12244
  }
12245
+ const wipedByThisImport = new Set(softDeletedFactIds);
12246
+ const wipedTasksByThisImport = new Set(softDeletedTaskIds);
10701
12247
  const factIds = bundle.facts.map((fact) => fact.id);
10702
12248
  const existingFactsById = /* @__PURE__ */ new Map();
10703
12249
  const existingFacts = await this.entryRepo.findExistingMetadataByIds(
@@ -10773,11 +12319,16 @@ var ImportExportService = class {
10773
12319
  );
10774
12320
  continue;
10775
12321
  }
10776
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
12322
+ if (existing.deleted_at != null && fact.deleted_at == null && !wipedByThisImport.has(fact.id)) {
12323
+ tombstoneSkipped++;
12324
+ continue;
12325
+ }
12326
+ if (merge && safeUpdatedAt <= existing.updated_at && fact.deleted_at == null) continue;
10777
12327
  }
10778
12328
  const safeTitle = clip(String(fact.title ?? ""), IMPORT_TITLE_MAX);
10779
12329
  const safeBody = clip(String(fact.body ?? ""), IMPORT_BODY_MAX);
10780
- clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody });
12330
+ const safeTags = Array.isArray(fact.tags) ? fact.tags : [];
12331
+ clippedTextByFactId.set(fact.id, { title: safeTitle, body: safeBody, tags: safeTags });
10781
12332
  let normalizedSourceRef = null;
10782
12333
  if (fact.source_ref !== null && fact.source_ref !== void 0) {
10783
12334
  normalizedSourceRef = normalizeSourceRef(fact.source_ref);
@@ -10844,15 +12395,22 @@ var ImportExportService = class {
10844
12395
  }, tx, { outbox: false });
10845
12396
  if (blobData != null) {
10846
12397
  factsWithPreservedBlob.set(fact.id, blobData);
10847
- if (!fact.deleted_at) preservedBlobDims.add(blobData.byteLength / 4);
12398
+ if (fact.deleted_at == null) preservedBlobDims.add(blobData.byteLength / 4);
10848
12399
  }
10849
12400
  existingFactsById.set(fact.id, {
10850
12401
  id: fact.id,
10851
12402
  entity_id: entityId,
10852
- updated_at: safeUpdatedAt
12403
+ updated_at: safeUpdatedAt,
12404
+ deleted_at: fact.deleted_at ?? null
10853
12405
  });
12406
+ wipedByThisImport.delete(fact.id);
10854
12407
  upsertedFactIds.add(fact.id);
10855
- if (fact.deleted_at) upsertedDeletedFactIds.add(fact.id);
12408
+ if (fact.deleted_at != null) {
12409
+ upsertedDeletedFactIds.add(fact.id);
12410
+ liveEmbedFactIds.delete(fact.id);
12411
+ } else {
12412
+ liveEmbedFactIds.add(fact.id);
12413
+ }
10856
12414
  }
10857
12415
  const taskIds = bundle.tasks.map((task) => task.id);
10858
12416
  const existingTasksById = /* @__PURE__ */ new Map();
@@ -10876,7 +12434,11 @@ var ImportExportService = class {
10876
12434
  );
10877
12435
  continue;
10878
12436
  }
10879
- if (merge && safeUpdatedAt <= existing.updated_at) continue;
12437
+ if (existing.deleted_at != null && task.deleted_at == null && !wipedTasksByThisImport.has(task.id)) {
12438
+ tombstoneSkipped++;
12439
+ continue;
12440
+ }
12441
+ if (merge && safeUpdatedAt <= existing.updated_at && task.deleted_at == null) continue;
10880
12442
  }
10881
12443
  await this.taskRepo.upsertForImport(
10882
12444
  {
@@ -10909,8 +12471,10 @@ var ImportExportService = class {
10909
12471
  existingTasksById.set(task.id, {
10910
12472
  id: task.id,
10911
12473
  entity_id: entityId,
10912
- updated_at: safeUpdatedAt
12474
+ updated_at: safeUpdatedAt,
12475
+ deleted_at: task.deleted_at ?? null
10913
12476
  });
12477
+ wipedTasksByThisImport.delete(task.id);
10914
12478
  }
10915
12479
  const now = Date.now();
10916
12480
  const wm = bundle.events.length > 0 ? await seedLegacyWatermark(this.metadataRepo, this.eventRepo, entityId, tx) : await this.metadataRepo.getLibrarianWatermark(entityId, tx);
@@ -10947,7 +12511,18 @@ var ImportExportService = class {
10947
12511
  tx
10948
12512
  );
10949
12513
  }
12514
+ await this.importStoredSources(tx, entityId, bundle.storedSources, merge, skippedSources, refusalDiagnostics);
10950
12515
  });
12516
+ for (const d of refusalDiagnostics) emitDiagnostic(this.options, d);
12517
+ if (tombstoneSkipped > 0) {
12518
+ emitDiagnostic(this.options, {
12519
+ code: "import_tombstone_skipped",
12520
+ operation: "importDump",
12521
+ trigger: "call",
12522
+ entityId,
12523
+ detail: { count: tombstoneSkipped }
12524
+ });
12525
+ }
10951
12526
  if (clampedEvents > 0) {
10952
12527
  emitDiagnostic(this.options, {
10953
12528
  code: "event_created_at_clamped",
@@ -10973,28 +12548,28 @@ var ImportExportService = class {
10973
12548
  } else {
10974
12549
  await this.searchService.sync(entityId, { ids: [.../* @__PURE__ */ new Set([...upsertedFactIds, ...softDeletedFactIds])] });
10975
12550
  }
10976
- for (const fact of bundle.facts) {
10977
- if (!fact.deleted_at && upsertedFactIds.has(fact.id) && !factsWithPreservedBlob.has(fact.id)) {
10978
- const clipped = clippedTextByFactId.get(fact.id);
12551
+ for (const id of liveEmbedFactIds) {
12552
+ if (!factsWithPreservedBlob.has(id)) {
12553
+ const clipped = clippedTextByFactId.get(id);
10979
12554
  const embedded = await this.embeddingService.embedFact({
10980
- id: fact.id,
12555
+ id,
10981
12556
  entity_id: entityId,
10982
- title: clipped?.title ?? fact.title,
10983
- body: clipped?.body ?? fact.body,
10984
- tags: Array.isArray(fact.tags) || typeof fact.tags === "string" ? fact.tags : []
12557
+ title: clipped?.title ?? "",
12558
+ body: clipped?.body ?? "",
12559
+ tags: clipped?.tags ?? []
10985
12560
  }, { operation: "importDump", trigger: "call" });
10986
12561
  if (!embedded && this.options.forceDeleteIgnoreRankerHook !== true) {
10987
12562
  try {
10988
- await this.embeddingService.notifyEmbeddingPersisted(entityId, fact.id, null);
12563
+ await this.embeddingService.notifyEmbeddingPersisted(entityId, id, null);
10989
12564
  } catch (hookErr) {
10990
12565
  console.warn(
10991
- `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${fact.id}:`,
12566
+ `[WikiMemory] onEmbeddingPersisted hook failed for unembedded fact ${id}:`,
10992
12567
  hookErr
10993
12568
  );
10994
12569
  this.embeddingService.reportHookFailed(
10995
12570
  { operation: "importDump", trigger: "call" },
10996
12571
  entityId,
10997
- fact.id
12572
+ id
10998
12573
  );
10999
12574
  }
11000
12575
  }
@@ -11002,7 +12577,7 @@ var ImportExportService = class {
11002
12577
  }
11003
12578
  for (const fact of bundle.facts) {
11004
12579
  const blobData = factsWithPreservedBlob.get(fact.id);
11005
- if (blobData && !fact.deleted_at && upsertedFactIds.has(fact.id)) {
12580
+ if (blobData && fact.deleted_at == null && liveEmbedFactIds.has(fact.id)) {
11006
12581
  try {
11007
12582
  const float32Vector = new Float32Array(
11008
12583
  blobData.buffer,
@@ -11115,6 +12690,7 @@ var ImportExportService = class {
11115
12690
  } finally {
11116
12691
  this.searchService.evictCache(entityId);
11117
12692
  }
12693
+ return skippedSources;
11118
12694
  }
11119
12695
  _warnCrossEntityCollision(type, id, existingEntityId, targetEntityId) {
11120
12696
  console.warn(
@@ -11639,6 +13215,63 @@ function packFactsByBudget(items, budget, scores) {
11639
13215
 
11640
13216
  // src/services/RetrievalService.ts
11641
13217
  var EMPTY_ID_SET = /* @__PURE__ */ new Set();
13218
+ var DEFAULT_SOURCE_PASSAGES = 8;
13219
+ var DEFAULT_SOURCE_CHAR_BUDGET = 4e3;
13220
+ var asciiLower = (s) => s.replace(/[A-Z]/g, (c) => c.toLowerCase());
13221
+ var isHigh2 = (c) => c >= 55296 && c <= 56319;
13222
+ var isLow2 = (c) => c >= 56320 && c <= 57343;
13223
+ function queryTerms(query) {
13224
+ return [...new Set(asciiLower(query).split(/[^\p{L}\p{N}]+/u).filter((t) => t.length > 0))];
13225
+ }
13226
+ function assertSourcesQuery(opt) {
13227
+ const query = opt?.query;
13228
+ if (typeof query !== "string" || query.trim() === "") {
13229
+ throw new WikiInvalidReadOptions("sources.query", "must be a non-empty string");
13230
+ }
13231
+ if (queryTerms(query).length === 0) {
13232
+ throw new WikiInvalidReadOptions("sources.query", "must contain at least one searchable term");
13233
+ }
13234
+ }
13235
+ function windowPassage(text, terms, budget) {
13236
+ if (text.length <= budget) return { start: 0, end: text.length, truncated: false };
13237
+ const lower = asciiLower(text);
13238
+ let a = -1;
13239
+ let len = 0;
13240
+ for (const t of terms) {
13241
+ const i = lower.indexOf(t);
13242
+ if (i >= 0 && (a < 0 || i < a || i === a && t.length > len)) {
13243
+ a = i;
13244
+ len = t.length;
13245
+ }
13246
+ }
13247
+ const hardCut = (from) => {
13248
+ let end = Math.min(text.length, from + budget);
13249
+ if (end < text.length && isHigh2(text.charCodeAt(end - 1)) && isLow2(text.charCodeAt(end))) {
13250
+ if (end - 1 > from) end -= 1;
13251
+ else return { start: from, end: from, truncated: true };
13252
+ }
13253
+ return { start: from, end, truncated: from > 0 || end < text.length };
13254
+ };
13255
+ if (a < 0) return hardCut(0);
13256
+ if (len > budget) return hardCut(a);
13257
+ const toks = [];
13258
+ for (const m of text.matchAll(/\S+/g)) toks.push([m.index, m.index + m[0].length]);
13259
+ const mEnd = a + len;
13260
+ const ti = toks.findIndex(([, e]) => e > a);
13261
+ if (ti < 0) return hardCut(a);
13262
+ let tj = ti;
13263
+ while (tj + 1 < toks.length && toks[tj][1] < mEnd) tj++;
13264
+ if (toks[tj][1] - toks[ti][0] > budget) return hardCut(a);
13265
+ let r = toks.length - 1;
13266
+ let best = { start: toks[ti][0], end: toks[tj][1] };
13267
+ for (let l = ti; l >= 0; l--) {
13268
+ const s = toks[l][0];
13269
+ while (r > tj && toks[r][1] - s > budget) r--;
13270
+ if (toks[r][1] - s > budget) break;
13271
+ if (toks[r][1] - s > best.end - best.start) best = { start: s, end: toks[r][1] };
13272
+ }
13273
+ return { ...best, truncated: true };
13274
+ }
11642
13275
  var RetrievalService = class {
11643
13276
  constructor(options, entryRepo, taskRepo, eventRepo, metadataRepo, searchService) {
11644
13277
  this.options = options;
@@ -11653,8 +13286,10 @@ var RetrievalService = class {
11653
13286
  const entityIds = normalizeEntityIds(entityId);
11654
13287
  const sanitizedTierWeights = shouldExposeReadMetadata(entityId) ? sanitizeTierWeights(entityIds, options?.tierWeights) : void 0;
11655
13288
  const exposeMetadata = shouldExposeReadMetadata(entityId);
13289
+ if (options?.sources) assertSourcesQuery(options.sources);
11656
13290
  if (entityIds.length === 0) {
11657
13291
  const empty = { facts: [], tasks: [], events: [], edges: [] };
13292
+ if (options?.sources) empty.sources = [];
11658
13293
  if (exposeMetadata) {
11659
13294
  empty.metadata = { query, entityIds: [] };
11660
13295
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) empty.metadata.tierWeights = sanitizedTierWeights;
@@ -12169,6 +13804,7 @@ var RetrievalService = class {
12169
13804
  factScores = Object.fromEntries(facts.map((fact) => [fact.id, scoreByFactId.get(fact.id) ?? 0]));
12170
13805
  }
12171
13806
  const bundle = { facts, tasks, events: events.reverse(), edges: [] };
13807
+ if (options?.sources) bundle.sources = await this._readSources(entityIds, options.sources);
12172
13808
  if (exposeMetadata) {
12173
13809
  bundle.metadata = { query, entityIds };
12174
13810
  if (sanitizedTierWeights && Object.keys(sanitizedTierWeights).length > 0) bundle.metadata.tierWeights = sanitizedTierWeights;
@@ -12177,6 +13813,42 @@ var RetrievalService = class {
12177
13813
  }
12178
13814
  return bundle;
12179
13815
  }
13816
+ /**
13817
+ * The `sources` group (spec source-store section 7). One search per entity,
13818
+ * so ranking and caps never cross entities. No model call anywhere.
13819
+ * `charBudget` is per entity: windows are cut in rank order against the
13820
+ * entity's remaining budget, and once it is spent lower-ranked hits are not returned.
13821
+ */
13822
+ async _readSources(entityIds, opt) {
13823
+ const pos = (v, d) => typeof v === "number" && Number.isFinite(v) && v >= 1 ? Math.floor(v) : d;
13824
+ const maxPassages = pos(opt.maxPassages, DEFAULT_SOURCE_PASSAGES);
13825
+ const charBudget = pos(opt.charBudget, DEFAULT_SOURCE_CHAR_BUDGET);
13826
+ assertSourcesQuery(opt);
13827
+ const query = opt.query;
13828
+ const terms = queryTerms(query);
13829
+ const out = [];
13830
+ for (const entityId of entityIds) {
13831
+ const hits = await this.searchService.searchPassages(query, entityId, maxPassages);
13832
+ let remaining = charBudget;
13833
+ for (const h of hits) {
13834
+ if (remaining <= 0) break;
13835
+ const w = windowPassage(h.text, terms, remaining);
13836
+ if (w.end === w.start) continue;
13837
+ remaining -= w.end - w.start;
13838
+ out.push({
13839
+ entityId,
13840
+ sourceRef: h.source_ref,
13841
+ sourceHash: h.source_hash,
13842
+ seq: h.seq,
13843
+ startOffset: h.start_offset + w.start,
13844
+ endOffset: h.start_offset + w.end,
13845
+ truncated: w.truncated,
13846
+ text: h.text.slice(w.start, w.end)
13847
+ });
13848
+ }
13849
+ }
13850
+ return out;
13851
+ }
12180
13852
  /**
12181
13853
  * Returns entity IDs that will participate in scored retrieval.
12182
13854
  * Excludes zero-weight entities unless includeZeroWeightEntities is true.
@@ -13183,7 +14855,8 @@ var WikiMemory = class {
13183
14855
  this.jobManager,
13184
14856
  this.embeddingService,
13185
14857
  this.options,
13186
- this.vectorRemovalService
14858
+ this.vectorRemovalService,
14859
+ this.prefix
13187
14860
  );
13188
14861
  this.retrievalService = new RetrievalService(
13189
14862
  this.options,
@@ -13193,6 +14866,7 @@ var WikiMemory = class {
13193
14866
  this.metadataRepo,
13194
14867
  this.searchService
13195
14868
  );
14869
+ this.sourceStoreService = new SourceStoreService(this.db, this.prefix, this.options, this.jobManager);
13196
14870
  this.writeService = new WriteService(
13197
14871
  this.db,
13198
14872
  this.options,
@@ -13320,11 +14994,22 @@ var WikiMemory = class {
13320
14994
  * host runs a plain `setup()` outside the lease.
13321
14995
  *
13322
14996
  * Keyword-index catch-up work is bounded by `config.setupBudgetMs`; anything
13323
- * left converges on later opens and no-arg `syncSearchIndex()` calls. Not
13324
- * bounded: an index reset (tokenizer change, re-attach after detach, a lost
13325
- * or inconsistent index), which runs as one unchunked transaction.
14997
+ * left converges on later opens, and on no-arg `syncSearchIndex()` calls for
14998
+ * the entries ledger. Passage-ledger leftover converges on later opens and on
14999
+ * passage-store writes for the entity (`storeSource`, `forget`,
15000
+ * `importDump`), which drain that entity's rows; no-arg calls do not touch
15001
+ * the passage ledger. Not bounded: an index reset (tokenizer change, re-attach
15002
+ * after detach, a lost or inconsistent index), which runs as one unchunked
15003
+ * transaction.
13326
15004
  */
13327
15005
  async setup(opts) {
15006
+ await this.db.execAsync("PRAGMA secure_delete=ON");
15007
+ const secureDelete = await this.db.getFirstAsync("PRAGMA secure_delete");
15008
+ if (!secureDelete || Number(secureDelete.secure_delete) !== 1) {
15009
+ console.warn(
15010
+ "[WikiMemory] PRAGMA secure_delete=ON (full zeroing) was not honored by this SQLite runtime; deleted content may remain recoverable in the database file until erase() verifies it."
15011
+ );
15012
+ }
13328
15013
  const setupBudgetMs = this.setupBudgetMs();
13329
15014
  const openDeadline = monotonicNow() + setupBudgetMs;
13330
15015
  const entriesExistedBeforeSetup = await this.metadataRepo.tableExists(`${this.prefix}entries`);
@@ -13366,6 +15051,7 @@ var WikiMemory = class {
13366
15051
  )
13367
15052
  );
13368
15053
  await this.searchService.sync(void 0, { deadline: openDeadline });
15054
+ await this.searchService.syncPassages(this.db, this.prefix, void 0, openDeadline);
13369
15055
  await this.startSetupRemovalDrain();
13370
15056
  }
13371
15057
  /** Marks the external index in use, then drains owed removals in the background (spec §5.7). */
@@ -13606,6 +15292,15 @@ var WikiMemory = class {
13606
15292
  if (options?.prefix === void 0) return ids;
13607
15293
  return ids.filter((id) => id.startsWith(options.prefix));
13608
15294
  }
15295
+ /**
15296
+ * Erase everything soft-deleted, store-wide, and verify it (forget-erasure
15297
+ * spec §2). Throws `EraseStepError` (partial report, `verified: false`) when
15298
+ * a step fails; skipped entities report `verified: false`.
15299
+ * `{ rebuild: true }` additionally restarts the FTS rebuild.
15300
+ */
15301
+ async erase(options) {
15302
+ return this.maintenanceService.erase(options);
15303
+ }
13609
15304
  async runPrune(entityId, options) {
13610
15305
  return this.maintenanceService.runPrune(entityId, options);
13611
15306
  }
@@ -13788,6 +15483,7 @@ var WikiMemory = class {
13788
15483
  );
13789
15484
  this.searchService.setIndexStrategy(strategy);
13790
15485
  if (this.searchService.isKeywordAvailable() && !this.searchService.hasLedger()) await this.searchService.sync();
15486
+ if (this.searchService.isKeywordAvailable()) await this.searchService.syncPassages(this.db, this.prefix);
13791
15487
  } finally {
13792
15488
  if (this.searchService.isKeywordAvailable()) {
13793
15489
  this.reinitFailures = 0;
@@ -13822,15 +15518,35 @@ var WikiMemory = class {
13822
15518
  async syncDrained(sync) {
13823
15519
  return await sync && this.searchService.isKeywordAvailable();
13824
15520
  }
13825
- async exportDump(entityIds) {
13826
- return this.importExportService.exportDump(entityIds);
15521
+ async exportDump(entityIds, opts) {
15522
+ return this.importExportService.exportDump(entityIds, opts);
15523
+ }
15524
+ /**
15525
+ * The retention windows `runPrune()` uses when the host runs it (shipped
15526
+ * defaults plus host overrides), for GDPR disclosure. Nothing prunes
15527
+ * automatically; `erase()` ignores `retainSoftDeletedFor`. Days; `null`
15528
+ * means "keep forever". Read-only.
15529
+ */
15530
+ getRetentionPolicy() {
15531
+ const c = this.options.config;
15532
+ return {
15533
+ retainSoftDeletedFor: c?.pruneRetainSoftDeletedFor ?? 7,
15534
+ retainEventsFor: c?.pruneEventsAfter ?? 30,
15535
+ pruneSupersededAfter: c?.pruneSupersededAfter ?? null
15536
+ };
13827
15537
  }
13828
15538
  /** Entity summary prose persisted from an OKF profile ≥ 1 import; null when none stored. */
13829
15539
  async getEntitySummary(entityId) {
13830
15540
  return this.metadataRepo.getMeta(entitySummaryMetaKey(entityId));
13831
15541
  }
13832
15542
  async importDump(dump, opts) {
13833
- return this.importExportService.importDump(dump, opts);
15543
+ try {
15544
+ return await this.importExportService.importDump(dump, opts);
15545
+ } finally {
15546
+ for (const entityId of Object.keys(dump?.entities ?? {})) {
15547
+ await this.searchService.syncPassages(this.db, this.prefix, entityId);
15548
+ }
15549
+ }
13834
15550
  }
13835
15551
  /**
13836
15552
  * Soft-delete facts and tasks by id, by source, or all of them (`clearAll`).
@@ -13851,7 +15567,28 @@ var WikiMemory = class {
13851
15567
  * or call `runExternalDeletions()`.
13852
15568
  */
13853
15569
  async forget(entityId, params, opts) {
13854
- return this.maintenanceService.forget(entityId, params, opts);
15570
+ try {
15571
+ return await this.maintenanceService.forget(entityId, params, opts);
15572
+ } finally {
15573
+ if (!opts?.dryRun) {
15574
+ await this.searchService.syncPassages(this.db, this.prefix, entityId);
15575
+ }
15576
+ }
15577
+ }
15578
+ /** Store a source's text (spec source-store §7). Refusals return `stored: false`; a busy lock throws. */
15579
+ async storeSource(entityId, params) {
15580
+ assertEntityId2(entityId);
15581
+ const result = await this.sourceStoreService.storeSource(entityId, params);
15582
+ if (result.stored) await this.searchService.syncPassages(this.db, this.prefix, entityId);
15583
+ return result;
15584
+ }
15585
+ async getStoredSource(entityId, sourceRef) {
15586
+ assertEntityId2(entityId);
15587
+ return this.sourceStoreService.getStoredSource(entityId, sourceRef);
15588
+ }
15589
+ async listStoredSources(entityId) {
15590
+ assertEntityId2(entityId);
15591
+ return this.sourceStoreService.listStoredSources(entityId);
13855
15592
  }
13856
15593
  /**
13857
15594
  * End `oldId`'s validity and link it to its replacement (spec §4.3). One
@@ -14208,6 +15945,10 @@ function renderEventPlain(event) {
14208
15945
  const ts = new Date(event.created_at).toISOString();
14209
15946
  return `[${event.event_type} @ ${ts}] ${event.summary}`;
14210
15947
  }
15948
+ function renderSourceLabel(p, includeEntityId) {
15949
+ const entity = includeEntityId ? `${p.entityId} ` : "";
15950
+ return `${entity}${p.sourceRef} #${p.seq}${p.truncated ? " (excerpt)" : ""}`;
15951
+ }
14211
15952
  function formatContext(bundle, options) {
14212
15953
  const opts = {
14213
15954
  format: options?.format ?? "markdown",
@@ -14233,7 +15974,8 @@ function formatContext(bundle, options) {
14233
15974
  const sortedFacts = bundle.factScores ? [...bundle.facts].slice(0, opts.maxFacts) : [...bundle.facts].sort((a, b) => scoreFactFor(b, weights, now) - scoreFactFor(a, weights, now)).slice(0, opts.maxFacts);
14234
15975
  const sortedTasks = [...bundle.tasks].sort((a, b) => b.priority - a.priority || a.created_at - b.created_at).slice(0, opts.maxTasks);
14235
15976
  const sortedEvents = [...bundle.events].sort((a, b) => b.created_at - a.created_at).slice(0, opts.maxEvents);
14236
- if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0) {
15977
+ const sources = bundle.sources ?? [];
15978
+ if (sortedFacts.length === 0 && sortedTasks.length === 0 && sortedEvents.length === 0 && sources.length === 0) {
14237
15979
  return "";
14238
15980
  }
14239
15981
  const isMarkdown = opts.format === "markdown";
@@ -14261,6 +16003,13 @@ function formatContext(bundle, options) {
14261
16003
  lines.push(renderEventMarkdown(event));
14262
16004
  }
14263
16005
  }
16006
+ if (sources.length > 0) {
16007
+ lines.push("");
16008
+ lines.push("### Sources");
16009
+ for (const p of sources) {
16010
+ lines.push(`- [${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text.replace(/\n/g, "\n ")}`);
16011
+ }
16012
+ }
14264
16013
  } else {
14265
16014
  if (sortedFacts.length > 0) {
14266
16015
  lines.push("KNOWN FACTS:");
@@ -14280,6 +16029,12 @@ function formatContext(bundle, options) {
14280
16029
  lines.push(renderEventPlain(event));
14281
16030
  }
14282
16031
  }
16032
+ if (sources.length > 0) {
16033
+ lines.push("SOURCES:");
16034
+ for (const p of sources) {
16035
+ lines.push(`[${renderSourceLabel(p, opts.includeEntityIds)}] ${p.text}`);
16036
+ }
16037
+ }
14283
16038
  }
14284
16039
  return lines.join("\n");
14285
16040
  }
@@ -15152,12 +16907,14 @@ function createWiki(db, options) {
15152
16907
  return new WikiMemory(db, options);
15153
16908
  }
15154
16909
 
16910
+ exports.CheckpointIncompleteError = CheckpointIncompleteError;
15155
16911
  exports.DEFAULT_CHUNK_OVERLAP = DEFAULT_CHUNK_OVERLAP;
15156
16912
  exports.DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT;
15157
16913
  exports.DEFAULT_MAX_CHUNK_LENGTH = DEFAULT_MAX_CHUNK_LENGTH;
15158
16914
  exports.DEFAULT_MAX_EMBED_CHARS = DEFAULT_MAX_EMBED_CHARS;
15159
16915
  exports.DEFAULT_SETUP_BUDGET_MS = DEFAULT_SETUP_BUDGET_MS;
15160
16916
  exports.EMBED_CHARS_CEILING = EMBED_CHARS_CEILING;
16917
+ exports.EraseStepError = EraseStepError;
15161
16918
  exports.HEAL_ANCHORS_PER_CANDIDATE = HEAL_ANCHORS_PER_CANDIDATE;
15162
16919
  exports.HEAL_BATCH_SIZE = HEAL_BATCH_SIZE;
15163
16920
  exports.HEAL_MAX_FACT_BODY_CHARS_L3 = HEAL_MAX_FACT_BODY_CHARS_L3;