Skip to main content

wm_memory/
reindex.rs

1//! Index rebuild — reconstruct the Tantivy full-text index from LMDB.
2//!
3//! The Tantivy index can drift from the LMDB store (stale entries survive
4//! deletes, binary migration artifacts pollute results). `rebuild_index`
5//! rebuilds it from scratch: every memory in every galaxy is re-indexed
6//! through the same sanitization gate used at write time, so garbage content
7//! is skipped and deleted memories disappear.
8//!
9//! The caller is responsible for backing up the existing index directory
10//! before rebuilding (the `wm reindex` CLI does this automatically).
11
12use serde::{Deserialize, Serialize};
13use wm_core::{CoreError, Galaxy, Result};
14
15use crate::memory::Memory;
16use crate::search::{SearchEngine, sanitize_content_for_index};
17use crate::store::MemoryStore;
18
19/// Batch size for scanning galaxies during rebuild (unused by `scan_all`
20/// today; kept for callers that stream batches).
21pub const REINDEX_BATCH: usize = 2_000;
22
23/// Per-galaxy statistics for an index rebuild.
24#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
25pub struct GalaxyRebuildStats {
26    /// Galaxy database name.
27    pub galaxy: String,
28    /// Memories scanned from LMDB.
29    pub scanned: usize,
30    /// Documents added to the index.
31    pub indexed: usize,
32    /// Memories skipped (failed content sanitization).
33    pub skipped: usize,
34    /// Index documents deleted — LMDB rows that no longer exist (orphans
35    /// from failed deletes or interrupted runs). Nonzero only on the
36    /// incremental heal path; a full rebuild deletes by galaxy instead.
37    pub deleted: usize,
38}
39
40/// Report of a full index rebuild.
41#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
42pub struct IndexRebuildReport {
43    /// Memories scanned from LMDB across all galaxies.
44    pub scanned: usize,
45    /// Documents added to the index.
46    pub indexed: usize,
47    /// Memories skipped because content failed sanitization.
48    pub skipped: usize,
49    /// Index documents deleted as orphans (incremental heal only).
50    pub deleted: usize,
51    /// Per-galaxy breakdown.
52    pub galaxies: Vec<GalaxyRebuildStats>,
53}
54
55/// Per-galaxy consistency check result.
56#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
57pub struct GalaxyConsistency {
58    /// Galaxy database name.
59    pub galaxy: String,
60    /// Memories in LMDB.
61    pub lmdb_count: usize,
62    /// Documents in Tantivy.
63    pub tantivy_count: usize,
64    /// True when counts differ (index is stale or has orphan documents).
65    pub drift: bool,
66}
67
68/// Consistency check report comparing LMDB to Tantivy.
69#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
70pub struct ConsistencyReport {
71    /// Per-galaxy comparison.
72    pub galaxies: Vec<GalaxyConsistency>,
73    /// Total LMDB memories across all galaxies.
74    pub total_lmdb: usize,
75    /// Total Tantivy documents across all galaxies.
76    pub total_tantivy: usize,
77    /// True if any galaxy has drift.
78    pub has_drift: bool,
79}
80
81/// Check consistency between LMDB store and Tantivy index.
82///
83/// Compares memory counts in LMDB to document counts in Tantivy for each
84/// galaxy. A mismatch indicates the index is stale (LMDB has memories that
85/// Tantivy doesn't) or has orphan documents (Tantivy has documents that
86/// LMDB doesn't — e.g. from a failed delete).
87///
88/// Note: content that fails sanitization is intentionally not indexed, so
89/// a small drift is expected when memories contain binary/garbage content.
90/// The caller should use `IndexHealth::failures` to distinguish best-effort
91/// skips from actual indexing failures.
92#[must_use]
93pub fn check_consistency(store: &MemoryStore, search: &SearchEngine) -> ConsistencyReport {
94    let mut report = ConsistencyReport::default();
95    for galaxy in Galaxy::memory_galaxies() {
96        let lmdb_count = store.count(galaxy).unwrap_or(0);
97        let tantivy_count = search.count_docs_in_galaxy(galaxy.db_name()).unwrap_or(0);
98        let drift = lmdb_count != tantivy_count;
99        report.total_lmdb += lmdb_count;
100        report.total_tantivy += tantivy_count;
101        if drift {
102            report.has_drift = true;
103        }
104        report.galaxies.push(GalaxyConsistency {
105            galaxy: galaxy.db_name().to_string(),
106            lmdb_count,
107            tantivy_count,
108            drift,
109        });
110    }
111    report
112}
113
114/// Per-galaxy drift classification — the truthfulness layer over
115/// [`check_consistency`].
116///
117/// A count mismatch is not automatically healable drift: docs the index
118/// gate refuses (null bytes / printable ratio < [`MIN_PRINTABLE_RATIO`])
119/// are **never indexable as-is** and survive every rebuild by design. This
120/// classification separates that documented reserve from real drift —
121/// `healable_gap != 0` means the index differs from what a rebuild would
122/// actually produce.
123#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
124pub struct GalaxyDriftClass {
125    /// Galaxy database name.
126    pub galaxy: String,
127    /// Memories in LMDB.
128    pub lmdb_count: usize,
129    /// Documents in Tantivy.
130    pub tantivy_count: usize,
131    /// LMDB docs that fail the index gate — the documented reserve, never
132    /// indexable as-is. Counted only in the LMDB > Tantivy direction (a
133    /// gate-failing doc cannot exist in the index).
134    pub skip_reserve: usize,
135    /// Signed gap between what a rebuild WOULD index (`lmdb - skip_reserve`)
136    /// and what the index holds. `0` = the index is exactly rebuild output;
137    /// positive = missing indexable docs; negative = orphan documents.
138    pub healable_gap: i64,
139}
140
141/// Classification report across all memory galaxies.
142#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
143pub struct DriftClassification {
144    /// Per-galaxy classification.
145    pub galaxies: Vec<GalaxyDriftClass>,
146    /// Σ skip-reserve docs across galaxies.
147    pub skip_reserve_total: usize,
148    /// Σ |healable_gap| across galaxies — the docs a rebuild would change.
149    pub healable_total: usize,
150}
151
152/// Classify per-galaxy count mismatches into healable drift vs the
153/// sanitization-skip reserve.
154///
155/// The skip-reserve count requires one LMDB scan + gate evaluation per
156/// galaxy in the `lmdb > tantivy` direction only (galaxies whose counts
157/// match, or that have orphans, cannot contain gate-failing docs — those
158/// are never indexed). Cheap when consistent, one scan pass when drifted.
159#[must_use]
160pub fn classify_drift(store: &MemoryStore, search: &SearchEngine) -> DriftClassification {
161    let mut out = DriftClassification::default();
162    for galaxy in Galaxy::memory_galaxies() {
163        let lmdb_count = store.count(galaxy).unwrap_or(0);
164        let tantivy_count = search.count_docs_in_galaxy(galaxy.db_name()).unwrap_or(0);
165        let mut skip_reserve = 0usize;
166        if lmdb_count > tantivy_count {
167            for mem in store.scan(galaxy, lmdb_count).unwrap_or_default() {
168                if sanitize_content_for_index(&mem.content).is_none() {
169                    skip_reserve += 1;
170                }
171            }
172        }
173        let indexable = usize::try_into(lmdb_count - skip_reserve).unwrap_or(i64::MAX);
174        let indexed = usize::try_into(tantivy_count).unwrap_or(i64::MAX);
175        let healable_gap = indexable - indexed;
176        out.skip_reserve_total += skip_reserve;
177        out.healable_total += healable_gap.unsigned_abs() as usize;
178        out.galaxies.push(GalaxyDriftClass {
179            galaxy: galaxy.db_name().to_string(),
180            lmdb_count,
181            tantivy_count,
182            skip_reserve,
183            healable_gap,
184        });
185    }
186    out
187}
188
189/// Rebuild the Tantivy index from LMDB contents.
190///
191/// With no filter, all existing index documents are deleted and every memory
192/// in every galaxy is re-indexed. With a filter, only the selected galaxies
193/// are deleted and re-indexed — documents belonging to other galaxies are
194/// left untouched. Content that fails [`sanitize_content_for_index`] is
195/// skipped (counted in the report).
196///
197/// NOTE: the existing index directory must be backed up by the caller before
198/// this runs — deletion is permanent once committed.
199pub fn rebuild_index(
200    store: &MemoryStore,
201    search: &SearchEngine,
202    galaxy_filter: &[String],
203) -> Result<IndexRebuildReport> {
204    // Decode every selected source before queuing any index deletion. Keep
205    // these snapshots for the write phase, so no second tolerant scan can
206    // silently drop records. Callers must still quiesce concurrent writers.
207    let mut snapshots = Vec::new();
208    for galaxy in Galaxy::memory_galaxies() {
209        if galaxy_filter.is_empty() || galaxy_filter.iter().any(|g| g == galaxy.db_name()) {
210            snapshots.push((galaxy, store.scan_all_strict(galaxy)?));
211        }
212    }
213    if galaxy_filter.iter().any(|name| {
214        !Galaxy::memory_galaxies()
215            .iter()
216            .any(|g| g.db_name() == name)
217    }) {
218        return Err(CoreError::Memory(
219            "reindex filter must name a memory galaxy".into(),
220        ));
221    }
222    let mut report = IndexRebuildReport::default();
223    {
224        let mut writer = search.writer()?;
225        if galaxy_filter.is_empty() {
226            writer
227                .as_mut()
228                .ok_or_else(|| {
229                    CoreError::Memory("Tantivy writer unavailable: index opened read-only".into())
230                })?
231                .delete_all_documents()
232                .map_err(|e| CoreError::Memory(format!("Tantivy delete_all_documents: {e}")))?;
233        } else {
234            // Filtered rebuild: remove only the selected galaxies' documents.
235            // The old behavior deleted everything first, so `--galaxy codex`
236            // silently wiped search documents for every other galaxy.
237            for galaxy in Galaxy::all() {
238                if galaxy_filter.iter().any(|g| g == galaxy.db_name()) {
239                    search.delete_by_galaxy(&mut writer, galaxy.db_name())?;
240                }
241            }
242        }
243
244        for (galaxy, memories) in snapshots {
245            let mut stats = GalaxyRebuildStats {
246                galaxy: galaxy.db_name().to_string(),
247                ..GalaxyRebuildStats::default()
248            };
249            for mem in &memories {
250                stats.scanned += 1;
251                if index_memory(search, &mut writer, galaxy, mem)?.is_some() {
252                    stats.indexed += 1;
253                } else {
254                    stats.skipped += 1;
255                }
256            }
257            report.scanned += stats.scanned;
258            report.indexed += stats.indexed;
259            report.skipped += stats.skipped;
260            report.galaxies.push(stats);
261        }
262
263        search.commit(&mut writer)?;
264        drop(writer);
265    }
266    Ok(report)
267}
268
269/// Index a single memory, returning `Ok(Some(()))` when indexed and
270/// `Ok(None)` when the content was skipped by sanitization.
271fn index_memory(
272    search: &SearchEngine,
273    writer: &mut Option<tantivy::IndexWriter>,
274    galaxy: Galaxy,
275    mem: &Memory,
276) -> Result<Option<()>> {
277    let Some(content) = sanitize_content_for_index(&mem.content) else {
278        return Ok(None);
279    };
280    let timestamp = mem.metadata.created_at.timestamp();
281    let id = mem.metadata.id.to_string();
282    search.add_document(
283        writer,
284        &id,
285        galaxy.db_name(),
286        &content,
287        &mem.metadata.tags,
288        timestamp,
289    )?;
290    Ok(Some(()))
291}
292
293/// Heal index drift by indexing only what the index is actually missing.
294///
295/// Whole-galaxy drift is systematic, not exceptional: session tools, dream
296/// consolidation, and research cycles write to LMDB without a search engine,
297/// and best-effort indexing failures are swallowed at the tool layer. Call
298/// this on writable server startup (and periodically in the daemon) so search
299/// stays complete without manual `wm reindex` runs.
300///
301/// Incremental by design (2026-09-10, daemon crash-loop fix): the previous
302/// implementation delegated to [`rebuild_index`], deleting and re-indexing
303/// every document of every drifted galaxy. On the live store that meant
304/// ~58k docs (~5 min) per 5-minute checkpoint cycle, synchronously inside
305/// the daemon's watchdogged main loop — the 120s watchdog killed the heal
306/// mid-run every cycle, the index never caught up, and the daemon
307/// crash-looped forever (35 failures in two days). The incremental path
308/// diffs indexed IDs against LMDB IDs and touches only the difference, so
309/// a steady-state cycle indexes a handful of docs in well under a second.
310/// Full rebuilds stay available via [`rebuild_index`] for manual
311/// `wm reindex` runs and the server-shutdown path.
312///
313/// Returns `Ok(None)` when nothing is healable — either the index matches
314/// LMDB, or the only gap is the documented sanitization-skip reserve
315/// (gate-failing content that every rebuild re-skips; healing those
316/// galaxies would be pure churn). Use [`repair_content`] to shrink the
317/// reserve itself.
318pub fn heal_index_drift(
319    store: &MemoryStore,
320    search: &SearchEngine,
321) -> Result<Option<IndexRebuildReport>> {
322    // Classify, don't just count: galaxies whose entire gap is the
323    // documented sanitization-skip reserve reproduce the same index on
324    // every rebuild — re-healing them each startup is pure churn. Only a
325    // nonzero healable gap (missing indexable docs, or orphans) triggers.
326    let class = classify_drift(store, search);
327    let drifted: Vec<String> = class
328        .galaxies
329        .iter()
330        .filter(|g| g.healable_gap != 0)
331        .map(|g| g.galaxy.clone())
332        .collect();
333    if drifted.is_empty() {
334        return Ok(None);
335    }
336
337    let mut report = IndexRebuildReport::default();
338    let mut writer = search.writer()?;
339    for name in &drifted {
340        let Some(galaxy) = Galaxy::from_db_name(name) else {
341            return Err(CoreError::Memory(format!(
342                "drift classification named a non-memory galaxy: {name}"
343            )));
344        };
345        let mut stats = GalaxyRebuildStats {
346            galaxy: name.clone(),
347            ..GalaxyRebuildStats::default()
348        };
349
350        let indexed_ids = search.indexed_ids_in_galaxy(name)?;
351        let mut lmdb_ids: std::collections::HashSet<String> =
352            std::collections::HashSet::with_capacity(indexed_ids.len());
353        for mem in store.scan_all(galaxy)? {
354            let id = mem.metadata.id.to_string();
355            lmdb_ids.insert(id.clone());
356            if !indexed_ids.contains(&id) {
357                stats.scanned += 1;
358                if index_memory(search, &mut writer, galaxy, &mem)?.is_some() {
359                    stats.indexed += 1;
360                } else {
361                    // Gate-failing content: counted as the documented
362                    // skip-reserve, never indexed. `classify_drift` moves it
363                    // out of the healable gap on the next pass, so this is
364                    // not churn.
365                    stats.skipped += 1;
366                }
367            }
368        }
369        // Orphans: indexed docs whose LMDB twin is gone (failed delete,
370        // interrupted run). Remove them so counts converge.
371        for id in &indexed_ids {
372            if !lmdb_ids.contains(id) {
373                search.delete_document(&mut writer, id)?;
374                stats.deleted += 1;
375            }
376        }
377
378        report.scanned += stats.scanned;
379        report.indexed += stats.indexed;
380        report.skipped += stats.skipped;
381        report.deleted += stats.deleted;
382        report.galaxies.push(stats);
383    }
384
385    search.commit(&mut writer)?;
386    drop(writer);
387    Ok(Some(report))
388}
389
390// ── Content repair ─────────────────────────────────────────────────────
391
392/// Per-galaxy content-repair stats.
393#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
394pub struct GalaxyContentRepairStats {
395    /// Galaxy database name.
396    pub galaxy: String,
397    /// Memories scanned.
398    pub scanned: usize,
399    /// Rows rewritten in place with gate-passing content and indexed.
400    pub repaired: usize,
401    /// Majority-binary content left untouched (scrubbing would only
402    /// manufacture searchable noise).
403    pub unrepairable: usize,
404    /// Memories that already passed the gate — untouched.
405    pub already_clean: usize,
406}
407
408/// Content-repair report.
409#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
410pub struct ContentRepairReport {
411    /// Memories scanned across all targeted galaxies.
412    pub scanned: usize,
413    /// Rows rewritten in place and indexed.
414    pub repaired: usize,
415    /// True-binary rows left as-is (the permanent reserve).
416    pub unrepairable: usize,
417    /// Rows that already passed the gate.
418    pub already_clean: usize,
419    /// Per-galaxy breakdown.
420    pub galaxies: Vec<GalaxyContentRepairStats>,
421}
422
423/// Clean content for a repair attempt: control characters → spaces
424/// (mirroring `scrub_text`'s keep-set) WITHOUT the index length cap — the
425/// stored content stays full-length; only the index caps.
426fn clean_for_repair(content: &str) -> String {
427    content
428        .chars()
429        .map(|c| {
430            if c.is_control() && c != '\n' && c != '\t' && c != '\r' {
431                ' '
432            } else {
433                c
434            }
435        })
436        .collect()
437}
438
439/// Repair gate-failing memory content **in place** (V8 drift fix, part 2).
440///
441/// For every memory whose content fails [`sanitize_content_for_index`], the
442/// cleaner replaces control characters with spaces and re-runs the gate;
443/// rows that pass are rewritten under the SAME id (content + recomputed
444/// content_hash — `store.put` refreshes the secondary indexes) and indexed.
445/// In-place is deliberate: the B5 recovery's alongside-copies are what
446/// created the standing reserve, and the raw originals remain recoverable
447/// from the upstream heritage sources.
448///
449/// Majority-binary content (printable ratio < 0.5 before cleaning) is left
450/// untouched: scrubbing it would only manufacture searchable noise. These
451/// are the documented true-binary docs — the permanent reserve.
452///
453/// Indexing uses one writer and a single commit at the end; the caller
454/// must hold the writer lock (no writable serve on the store). The report
455/// gives exact per-galaxy counts; a fresh `wm backup` before applying is
456/// the operator's responsibility.
457///
458/// # Errors
459/// Propagates store/index errors; a mid-run failure leaves earlier
460/// repairs committed only at the end (single transaction on the index;
461/// LMDB rows are committed per-put — take a backup first).
462pub fn repair_content(
463    store: &MemoryStore,
464    search: &SearchEngine,
465    galaxies: &[Galaxy],
466) -> Result<ContentRepairReport> {
467    let mut report = ContentRepairReport::default();
468    let mut writer = search.writer()?;
469    for galaxy in galaxies {
470        let mut stats = GalaxyContentRepairStats {
471            galaxy: galaxy.db_name().to_string(),
472            ..Default::default()
473        };
474        for mem in store.scan_all(*galaxy)? {
475            stats.scanned += 1;
476            if sanitize_content_for_index(&mem.content).is_some() {
477                stats.already_clean += 1;
478                continue;
479            }
480            // Majority-text rule: control-char scrubbing must not manufacture
481            // searchable noise out of binary garbage.
482            let total = mem.content.chars().count();
483            let printable = mem.content.chars().filter(|c| !c.is_control()).count();
484            let cleaned = clean_for_repair(&mem.content);
485            if total == 0
486                || (printable as f32 / total as f32) < 0.5
487                || sanitize_content_for_index(&cleaned).is_none()
488            {
489                stats.unrepairable += 1;
490                continue;
491            }
492            let mut repaired_mem = mem;
493            let old_hash = repaired_mem.metadata.content_hash.clone();
494            repaired_mem.content = cleaned;
495            repaired_mem.metadata.content_hash = crate::content_hash(&repaired_mem.content);
496            repaired_mem.metadata.revision_count =
497                repaired_mem.metadata.revision_count.saturating_add(1);
498            store.put(*galaxy, &repaired_mem)?;
499            // V8 S11c: an operator repair IS a content change — chain it
500            // like any update so `memory.revisions verify` stays truthful
501            // afterwards instead of crying tamper on repaired docs.
502            store.record_revision(
503                *galaxy,
504                repaired_mem.metadata.id,
505                &old_hash,
506                &repaired_mem.metadata.content_hash,
507                crate::revision::RevisionActor {
508                    session: None,
509                    user: Some("wm-repair-content".to_string()),
510                    compartment: None,
511                },
512            )?;
513            let id_str = repaired_mem.metadata.id.to_string();
514            // Defensive delete-then-add: gate-failing docs have no index
515            // doc, but a prior partial repair could have left one.
516            search.delete_document(&mut writer, &id_str)?;
517            search.add_document(
518                &mut writer,
519                &id_str,
520                galaxy.db_name(),
521                &repaired_mem.content,
522                &repaired_mem.metadata.tags,
523                repaired_mem.metadata.created_at.timestamp(),
524            )?;
525            stats.repaired += 1;
526        }
527        report.scanned += stats.scanned;
528        report.repaired += stats.repaired;
529        report.unrepairable += stats.unrepairable;
530        report.already_clean += stats.already_clean;
531        report.galaxies.push(stats);
532    }
533    search.commit(&mut writer)?;
534    Ok(report)
535}
536
537/// Helper for the `wm reindex` CLI: validate that the tantivy index directory
538/// exists next to the LMDB store.
539#[must_use]
540pub fn tantivy_path_for(store_path: &std::path::Path) -> std::path::PathBuf {
541    store_path.join("tantivy")
542}
543
544/// Error message used when the index directory is missing.
545#[must_use]
546pub fn missing_index_error(store_path: &std::path::Path) -> CoreError {
547    CoreError::Memory(format!(
548        "Tantivy index not found at {} — run 'wm serve' once to create it",
549        tantivy_path_for(store_path).display()
550    ))
551}
552
553#[cfg(test)]
554mod tests {
555    use super::*;
556    use crate::Memory;
557    use tempfile::tempdir;
558
559    fn setup() -> (tempfile::TempDir, MemoryStore, SearchEngine) {
560        let tmp = tempdir().unwrap();
561        let store = MemoryStore::open_default(tmp.path()).unwrap();
562        let tantivy_dir = tmp.path().join("tantivy");
563        std::fs::create_dir_all(&tantivy_dir).unwrap();
564        let search = SearchEngine::open(&tantivy_dir).unwrap();
565        (tmp, store, search)
566    }
567
568    fn put_and_index(store: &MemoryStore, search: &SearchEngine, galaxy: Galaxy, content: &str) {
569        let mem = Memory::new(galaxy, content.to_string());
570        let id = mem.metadata.id;
571        store.put(galaxy, &mem).unwrap();
572        let mut writer = search.writer().unwrap();
573        search
574            .add_document(
575                &mut writer,
576                &id.to_string(),
577                galaxy.db_name(),
578                content,
579                &mem.metadata.tags,
580                mem.metadata.created_at.timestamp(),
581            )
582            .unwrap();
583        search.commit(&mut writer).unwrap();
584    }
585
586    #[test]
587    fn rebuild_repopulates_index_from_lmdb() {
588        let (_tmp, store, search) = setup();
589        put_and_index(&store, &search, Galaxy::Codex, "rust memory one");
590        put_and_index(&store, &search, Galaxy::Codex, "python memory two");
591        put_and_index(&store, &search, Galaxy::Research, "research notes");
592
593        // Inject a stale document that exists in the index but not in LMDB —
594        // the rebuild must remove it.
595        {
596            let mut writer = search.writer().unwrap();
597            search
598                .add_document(
599                    &mut writer,
600                    "99999999-9999-9999-9999-999999999999",
601                    "codex",
602                    "stale ghost document",
603                    &[],
604                    1000,
605                )
606                .unwrap();
607            search.commit(&mut writer).unwrap();
608        }
609        let ghost = search.search("ghost", 10).unwrap();
610        assert_eq!(ghost.len(), 1);
611
612        let report = rebuild_index(&store, &search, &[]).unwrap();
613        assert_eq!(report.indexed, 3);
614        assert_eq!(report.scanned, 3);
615        assert_eq!(report.galaxies.len(), Galaxy::memory_galaxies().len());
616
617        let ghost = search.search("ghost", 10).unwrap();
618        assert!(ghost.is_empty(), "stale index entry must be purged");
619
620        let rust = search.search("rust memory one", 10).unwrap();
621        assert_eq!(rust.len(), 1);
622        assert_eq!(rust[0].content, "rust memory one");
623    }
624
625    #[test]
626    fn rebuild_refuses_undecodable_sources_before_touching_index() {
627        let (_tmp, store, search) = setup();
628        put_and_index(
629            &store,
630            &search,
631            Galaxy::Codex,
632            "preserved searchable evidence",
633        );
634        let id = uuid::Uuid::new_v4();
635        store
636            .put_raw(Galaxy::Sessions, id.as_bytes(), b"invalid messagepack")
637            .unwrap();
638        let before = search.count_docs_in_galaxy("codex").unwrap();
639        assert!(rebuild_index(&store, &search, &[]).is_err());
640        // Committing afterward also proves no deletion was left pending.
641        let mut writer = search.writer().unwrap();
642        search.commit(&mut writer).unwrap();
643        assert_eq!(search.count_docs_in_galaxy("codex").unwrap(), before);
644        assert_eq!(search.search("preserved", 10).unwrap().len(), 1);
645    }
646
647    #[test]
648    fn rebuild_skips_binary_garbage() {
649        let (_tmp, store, search) = setup();
650        put_and_index(&store, &search, Galaxy::Codex, "clean text entry");
651        let mem = Memory::new(Galaxy::Codex, "\u{00}\u{01}\u{02}raw bytes".to_string());
652        store.put(Galaxy::Codex, &mem).unwrap();
653
654        let report = rebuild_index(&store, &search, &[]).unwrap();
655        assert_eq!(report.indexed, 1, "garbage content must be skipped");
656        assert_eq!(report.skipped, 1);
657
658        let results = search.search("raw", 10).unwrap();
659        assert!(results.is_empty());
660    }
661
662    #[test]
663    fn rebuild_respects_galaxy_filter() {
664        let (_tmp, store, search) = setup();
665        put_and_index(&store, &search, Galaxy::Codex, "codex memory");
666        put_and_index(&store, &search, Galaxy::Research, "research memory");
667
668        let report = rebuild_index(&store, &search, &["codex".to_string()]).unwrap();
669        assert_eq!(report.indexed, 1);
670        assert_eq!(report.galaxies.len(), 1);
671        assert_eq!(report.galaxies[0].galaxy, "codex");
672
673        // Regression: the filtered rebuild used to delete ALL documents first,
674        // so documents from unselected galaxies vanished from the index.
675        // Use galaxy-scoped search since OR semantics returns partial matches
676        // for 2-term queries (both docs contain "memory").
677        let codex = search
678            .search_in_galaxy("codex memory", Some(Galaxy::Codex), 10)
679            .unwrap();
680        assert_eq!(codex.len(), 1);
681        let research = search
682            .search_in_galaxy("research memory", Some(Galaxy::Research), 10)
683            .unwrap();
684        assert_eq!(
685            research.len(),
686            1,
687            "filtered rebuild must preserve documents in unselected galaxies"
688        );
689    }
690
691    #[test]
692    fn consistency_check_no_drift_when_indexed() {
693        let (_tmp, store, search) = setup();
694        put_and_index(&store, &search, Galaxy::Codex, "hello world");
695        put_and_index(&store, &search, Galaxy::Codex, "another memory");
696
697        let report = check_consistency(&store, &search);
698        assert!(!report.has_drift, "no drift expected when all indexed");
699        let codex = report
700            .galaxies
701            .iter()
702            .find(|g| g.galaxy == "codex")
703            .unwrap();
704        assert_eq!(codex.lmdb_count, 2);
705        assert_eq!(codex.tantivy_count, 2);
706    }
707
708    #[test]
709    fn consistency_check_detects_drift() {
710        let (_tmp, store, search) = setup();
711        // Write to LMDB without indexing → drift.
712        let mem = Memory::new(Galaxy::Codex, "unindexed".to_string());
713        store.put(Galaxy::Codex, &mem).unwrap();
714
715        let report = check_consistency(&store, &search);
716        assert!(
717            report.has_drift,
718            "drift expected when LMDB has unindexed memory"
719        );
720        let codex = report
721            .galaxies
722            .iter()
723            .find(|g| g.galaxy == "codex")
724            .unwrap();
725        assert_eq!(codex.lmdb_count, 1);
726        assert_eq!(codex.tantivy_count, 0);
727    }
728
729    #[test]
730    fn heal_repairs_only_drifted_galaxies() {
731        let (_tmp, store, search) = setup();
732
733        // LMDB-only writes (the session-tool pattern) — never touch the index.
734        store
735            .put(
736                Galaxy::Sessions,
737                &Memory::new(Galaxy::Sessions, "session needle".into()),
738            )
739            .unwrap();
740        store
741            .put(
742                Galaxy::Research,
743                &Memory::new(Galaxy::Research, "research needle".into()),
744            )
745            .unwrap();
746        // A healthy galaxy that must not be rebuilt.
747        put_and_index(&store, &search, Galaxy::Codex, "healthy codex entry");
748
749        let report = heal_index_drift(&store, &search)
750            .unwrap()
751            .expect("drift expected before heal");
752        let healed: Vec<_> = report.galaxies.iter().map(|g| g.galaxy.as_str()).collect();
753        assert!(healed.contains(&"sessions"));
754        assert!(healed.contains(&"research"));
755        assert!(
756            !healed.contains(&"codex"),
757            "healthy galaxy must be untouched"
758        );
759        assert_eq!(report.indexed, 2);
760
761        assert!(
762            heal_index_drift(&store, &search).unwrap().is_none(),
763            "second heal must be a no-op once consistent"
764        );
765        assert_eq!(
766            search
767                .search_in_galaxy("session needle", Some(Galaxy::Sessions), 10)
768                .unwrap()
769                .len(),
770            1
771        );
772        assert_eq!(
773            search
774                .search_in_galaxy("healthy codex", Some(Galaxy::Codex), 10)
775                .unwrap()
776                .len(),
777            1
778        );
779    }
780
781    #[test]
782    fn heal_noop_when_consistent() {
783        let (_tmp, store, search) = setup();
784        put_and_index(&store, &search, Galaxy::Codex, "indexed entry");
785        put_and_index(&store, &search, Galaxy::Dreams, "dream entry");
786
787        assert!(heal_index_drift(&store, &search).unwrap().is_none());
788    }
789
790    #[test]
791    fn index_health_tracks_successes() {
792        let (_tmp, store, search) = setup();
793        put_and_index(&store, &search, Galaxy::Codex, "test content");
794
795        let health = search.health().snapshot();
796        let successes = health
797            .get("successes")
798            .and_then(serde_json::Value::as_u64)
799            .unwrap_or(0);
800        assert!(successes > 0, "expected at least one success");
801        let failures = health
802            .get("failures")
803            .and_then(serde_json::Value::as_u64)
804            .unwrap_or(0);
805        assert_eq!(failures, 0);
806        assert_eq!(
807            health.get("degraded").and_then(serde_json::Value::as_bool),
808            Some(false)
809        );
810    }
811
812    #[test]
813    fn consistency_check_ignores_non_memory_galaxies() {
814        let (_tmp, store, search) = setup();
815        put_and_index(&store, &search, Galaxy::Codex, "indexed memory");
816
817        // Write raw bytes into the Karma galaxy (non-memory data).
818        // Karma is not a memory galaxy and is intentionally not indexed in Tantivy.
819        store.put_raw(Galaxy::Karma, b"key1", b"value1").unwrap();
820
821        let report = check_consistency(&store, &search);
822        assert!(
823            !report.has_drift,
824            "karma entries should not cause drift — non-memory galaxies are excluded"
825        );
826        // Only memory galaxies should appear in the report.
827        let galaxy_names: Vec<_> = report.galaxies.iter().map(|g| g.galaxy.as_str()).collect();
828        assert!(
829            !galaxy_names.contains(&"karma"),
830            "karma should not appear in consistency report"
831        );
832        assert!(
833            !galaxy_names.contains(&"dharma"),
834            "dharma should not appear in consistency report"
835        );
836    }
837    // ── Drift classification + content repair (V8 truthfulness fix) ────────
838
839    #[test]
840    fn classify_separates_skip_reserve_from_healable_drift() {
841        let (tmp, store, search) = setup();
842        // 2 clean docs indexed + 1 gate-failing doc NOT indexed.
843        put_and_index(&store, &search, Galaxy::Codex, "clean doc one");
844        put_and_index(&store, &search, Galaxy::Codex, "clean doc two");
845        store
846            .put(
847                Galaxy::Codex,
848                &Memory::new(Galaxy::Codex, "bad \u{1}\u{2} doc".into()),
849            )
850            .unwrap();
851        search.commit(&mut search.writer().unwrap()).unwrap();
852
853        let class = classify_drift(&store, &search);
854        let codex = class.galaxies.iter().find(|g| g.galaxy == "codex").unwrap();
855        assert_eq!(codex.lmdb_count, 3);
856        assert_eq!(codex.tantivy_count, 2);
857        assert_eq!(codex.skip_reserve, 1);
858        assert_eq!(codex.healable_gap, 0, "skip reserve fully explains the gap");
859        assert_eq!(class.healable_total, 0);
860        drop(tmp);
861    }
862
863    #[test]
864    fn classify_flags_missing_indexable_docs_as_healable() {
865        let (tmp, store, search) = setup();
866        put_and_index(&store, &search, Galaxy::Codex, "indexed doc");
867        // A second clean doc that never reached the index — real drift.
868        store
869            .put(
870                Galaxy::Codex,
871                &Memory::new(Galaxy::Codex, "unindexed clean doc".into()),
872            )
873            .unwrap();
874        search.commit(&mut search.writer().unwrap()).unwrap();
875
876        let class = classify_drift(&store, &search);
877        let codex = class.galaxies.iter().find(|g| g.galaxy == "codex").unwrap();
878        assert_eq!(codex.skip_reserve, 0);
879        assert_eq!(codex.healable_gap, 1);
880        assert_eq!(class.healable_total, 1);
881        drop(tmp);
882    }
883
884    #[test]
885    fn heal_ignores_pure_skip_reserve_and_heals_real_gaps() {
886        let (tmp, store, search) = setup();
887        put_and_index(&store, &search, Galaxy::Codex, "clean doc");
888        // Only a skip-reserve gap: heal must be a no-op (no churn).
889        // The \0 makes this genuinely gate-failing (null byte → immediate refuse).
890        store
891            .put(
892                Galaxy::Codex,
893                &Memory::new(Galaxy::Codex, "gate\u{0} fails".into()),
894            )
895            .unwrap();
896        search.commit(&mut search.writer().unwrap()).unwrap();
897        let healed = heal_index_drift(&store, &search).unwrap();
898        assert!(
899            healed.is_none(),
900            "skip-reserve-only drift must not trigger a rebuild"
901        );
902
903        // Now a real gap: an unindexed clean doc — heal must rebuild.
904        store
905            .put(
906                Galaxy::Codex,
907                &Memory::new(Galaxy::Codex, "genuinely missing doc".into()),
908            )
909            .unwrap();
910        let healed = heal_index_drift(&store, &search).unwrap();
911        assert!(healed.is_some(), "healable drift must trigger a heal");
912        // Incremental heal touches only the delta: the already-indexed clean
913        // doc is left alone, the missing doc is added, the \0 doc is in the
914        // id diff, gets attempted, fails the gate and is counted skipped —
915        // that is the whole point of the classification.
916        let healed = healed.unwrap();
917        assert_eq!(healed.indexed, 1);
918        assert_eq!(healed.skipped, 1);
919        assert_eq!(healed.deleted, 0);
920        drop(tmp);
921    }
922
923    #[test]
924    fn heal_indexes_only_the_missing_delta() {
925        let (_tmp, store, search) = setup();
926        // Two memories written straight to LMDB (the session-tool pattern).
927        let a = Memory::new(Galaxy::Sessions, "alpha missing doc".into());
928        let b = Memory::new(Galaxy::Sessions, "beta missing doc".into());
929        store.put(Galaxy::Sessions, &a).unwrap();
930        store.put(Galaxy::Sessions, &b).unwrap();
931
932        // Heal once: both are missing, both get indexed.
933        let report = heal_index_drift(&store, &search).unwrap().unwrap();
934        assert_eq!(report.indexed, 2);
935        assert_eq!(report.deleted, 0);
936        assert_eq!(
937            search
938                .search_in_galaxy("alpha", Some(Galaxy::Sessions), 10)
939                .unwrap()
940                .len(),
941            1
942        );
943
944        // One more LMDB-only write; the heal must index exactly the new one.
945        store
946            .put(
947                Galaxy::Sessions,
948                &Memory::new(Galaxy::Sessions, "gamma missing doc".into()),
949            )
950            .unwrap();
951        let report = heal_index_drift(&store, &search).unwrap().unwrap();
952        assert_eq!(report.indexed, 1, "only the delta is indexed");
953        assert_eq!(
954            search
955                .search_in_galaxy("gamma", Some(Galaxy::Sessions), 10)
956                .unwrap()
957                .len(),
958            1
959        );
960        // Prior docs still present exactly once.
961        assert_eq!(
962            search
963                .search_in_galaxy("alpha", Some(Galaxy::Sessions), 10)
964                .unwrap()
965                .len(),
966            1
967        );
968    }
969
970    #[test]
971    fn heal_deletes_orphan_index_docs() {
972        let (_tmp, store, search) = setup();
973        put_and_index(&store, &search, Galaxy::Codex, "legit doc");
974        // Index an entry whose LMDB row is then removed outright (the
975        // failed-delete / interrupted-run shape). NOTE: `store.delete` keeps
976        // the key as a validity-state row, which count-based classification
977        // deliberately ignores (a rebuild would re-index that row anyway);
978        // only a raw key removal makes the index doc a true orphan.
979        let orphan = Memory::new(Galaxy::Codex, "orphan doc".into());
980        let orphan_id = orphan.metadata.id;
981        store.put(Galaxy::Codex, &orphan).unwrap();
982        {
983            let mut writer = search.writer().unwrap();
984            search
985                .add_document(
986                    &mut writer,
987                    &orphan_id.to_string(),
988                    "codex",
989                    "orphan doc",
990                    &orphan.metadata.tags,
991                    orphan.metadata.created_at.timestamp(),
992                )
993                .unwrap();
994            search.commit(&mut writer).unwrap();
995        }
996        store
997            .delete_raw(Galaxy::Codex, orphan_id.as_bytes())
998            .unwrap();
999        assert_eq!(search.count_docs_in_galaxy("codex").unwrap(), 2);
1000
1001        let report = heal_index_drift(&store, &search).unwrap().unwrap();
1002        assert_eq!(report.deleted, 1, "the orphan must be deleted");
1003        assert_eq!(report.indexed, 0);
1004        assert_eq!(search.count_docs_in_galaxy("codex").unwrap(), 1);
1005        // `search()` uses the delayed-reload reader (OnCommitWithDelay) —
1006        // count/enum reload eagerly, the text-search path does not by design.
1007        // Poll briefly instead of forcing a reload into the hot path.
1008        let mut gone = false;
1009        for _ in 0..40 {
1010            // "orphan" alone: an OR query with "doc" would match the legit
1011            // doc too (single-term coverage floor).
1012            if search.search("orphan", 10).unwrap().is_empty() {
1013                gone = true;
1014                break;
1015            }
1016            std::thread::sleep(std::time::Duration::from_millis(50));
1017        }
1018        assert!(gone, "orphan doc must be gone from search");
1019        assert!(heal_index_drift(&store, &search).unwrap().is_none());
1020    }
1021
1022    #[test]
1023    fn repair_rewrites_in_place_and_indexes_clean_content() {
1024        let (tmp, store, search) = setup();
1025        // Repairable: majority text with a null byte (immediate gate refuse)
1026        // plus a control char — printable ratio ≥ 0.5.
1027        let mut repairable = Memory::new(
1028            Galaxy::Codex,
1029            "kumquat\u{0} ratchet \u{1} repair end".into(),
1030        );
1031        // True-binary: majority control chars — must be left untouched.
1032        let mut binary = Memory::new(Galaxy::Codex, "\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}".into());
1033        // Already clean.
1034        let mut clean = Memory::new(Galaxy::Codex, "perfectly fine prose".into());
1035        let (id_r, id_b, id_c) = (
1036            repairable.metadata.id,
1037            binary.metadata.id,
1038            clean.metadata.id,
1039        );
1040        for m in [&mut repairable, &mut binary, &mut clean] {
1041            store.put(Galaxy::Codex, m).unwrap();
1042        }
1043
1044        let report = repair_content(&store, &search, &[Galaxy::Codex]).unwrap();
1045        assert_eq!(report.scanned, 3);
1046        assert_eq!(report.repaired, 1, "{report:?}");
1047        assert_eq!(report.unrepairable, 1, "{report:?}");
1048        assert_eq!(report.already_clean, 1);
1049
1050        // The repaired row kept its id, got clean content + fresh hash, and is
1051        // now gate-passing.
1052        let row = store.get(Galaxy::Codex, id_r).unwrap().unwrap();
1053        assert_eq!(row.content, "kumquat  ratchet   repair end");
1054        assert_eq!(row.metadata.content_hash, crate::content_hash(&row.content));
1055        assert!(sanitize_content_for_index(&row.content).is_some());
1056        assert_eq!(row.metadata.revision_count, 1);
1057
1058        // V8 S11c: the repair chained itself — old hash preserved, operator
1059        // actor labeled, head verifies against the repaired content.
1060        let chain = store.revisions(Galaxy::Codex, id_r).unwrap();
1061        assert_eq!(chain.len(), 1);
1062        assert_eq!(
1063            chain[0].old_hash,
1064            crate::content_hash("kumquat\u{0} ratchet \u{1} repair end")
1065        );
1066        assert_eq!(chain[0].new_hash, row.metadata.content_hash);
1067        assert_eq!(chain[0].actor_user.as_deref(), Some("wm-repair-content"));
1068        assert_eq!(chain[0].actor_session, None);
1069        let verdict = store
1070            .verify_revision_chain(Galaxy::Codex, id_r, &row.metadata.content_hash)
1071            .unwrap();
1072        assert!(verdict.valid, "{:?}", verdict.breaks);
1073
1074        // Untouched rows chained nothing.
1075        assert!(store.revisions(Galaxy::Codex, id_b).unwrap().is_empty());
1076        assert!(store.revisions(Galaxy::Codex, id_c).unwrap().is_empty());
1077
1078        // True-binary row untouched.
1079        let untouched = store.get(Galaxy::Codex, id_b).unwrap().unwrap();
1080        assert_eq!(untouched.content, "\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}");
1081
1082        // Clean row untouched.
1083        let kept = store.get(Galaxy::Codex, id_c).unwrap().unwrap();
1084        assert_eq!(kept.content, "perfectly fine prose");
1085
1086        // The repaired doc is now findable through the index.
1087        let hits = search.search("kumquat ratchet repair", 10).unwrap();
1088        assert!(
1089            hits.iter().any(|h| h.memory_id == id_r.to_string()),
1090            "repaired doc must be indexed: {hits:?}"
1091        );
1092
1093        // Re-run: the repaired doc is already clean; nothing new happens.
1094        let again = repair_content(&store, &search, &[Galaxy::Codex]).unwrap();
1095        assert_eq!(again.repaired, 0);
1096        assert_eq!(again.already_clean, 2);
1097        assert_eq!(
1098            store.revisions(Galaxy::Codex, id_r).unwrap().len(),
1099            1,
1100            "idempotent re-run must not append"
1101        );
1102        drop(tmp);
1103    }
1104}