rkat 0.8.13

CLI for the Meerkat agent platform — run LLM agents from the terminal
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
//! `rkat storage migrate` / `rkat storage prune` orchestration (Phase 6 of
//! the storage unification arc).
//!
//! The reusable primitives (realm maintenance fence, backup naming, report
//! shapes, divergence computation) live in `meerkat_store::migrate`; this
//! module owns the disk-realm orchestration because only the CLI sits above
//! every store crate and can run each store's normal constructor.
//!
//! The migration cases:
//!
//! 1. **Ledger baseline (auto-safe):** under the realm's exclusive
//!    maintenance fence, each store is opened through its NORMAL constructor
//!    — the guarded schema-ledger migrations ARE the structural
//!    verification, admitting only fresh domains or exact released
//!    predecessors. Dry-run reads recorded versions only and reports row
//!    presence; it does not certify a missing row as fresh or promise a
//!    future stamp.
//! 2. **State-root adoption (report-only):** the dual-root resolver already
//!    uses realms where they lie; the report states each realm's root.
//! 3. **Split-brain reconciliation (manual, fail-closed):** a realm id under
//!    2+ swept roots produces a per-domain divergence report and a typed
//!    refusal. With `--apply --adopt-root <path>` every copy is fenced, the
//!    divergence is recomputed under the held fences, the archive decision
//!    is gated on a conclusive comparison, and then one root is adopted
//!    where it lies while every other copy is archived read-only under the
//!    registered backup naming (its released fence lock files ride into the
//!    archive). No synthesis, no merging.
//! 4. **Deprecated leftovers (report-only):** doctor's artifact findings
//!    plus a legacy `<home>/.rkat/sessions` directory if present.
//!    Credential stores are never read, moved, or reported.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;

use meerkat_core::storage_diagnostics::{DiagnoseScope, FindingSeverity, StorageFinding};
use meerkat_store::migrate::{
    self as store_migrate, DivergenceStatus, LedgerBaselineAction, LedgerBaselineEntry,
    MigrateMode, MigrateReport, PruneAction, PruneReport, RealmDirEntry, RealmMigrateReport,
    SplitBrainReport, SplitBrainResolution,
};

/// Case-5 finding codes copied into the migrate report (deprecated
/// leftovers; report-only).
const LEFTOVER_FINDING_CODES: &[&str] = &[
    meerkat_store::doctor::FINDING_BACKUP_ARTIFACT,
    meerkat_store::doctor::FINDING_QUARANTINED_INDEX,
    meerkat_store::doctor::FINDING_ORPHANED_LEASE,
    meerkat_store::doctor::FINDING_UNPARSEABLE_LEASE,
    meerkat_store::doctor::FINDING_STALE_MANIFEST_LOCK,
];

/// Options for one `storage migrate` run. Roots are resolved by the caller
/// (explicit roots, or the CLI's dual-root candidates) — this module reads
/// nothing ambient.
pub(crate) struct MigrateOptions {
    pub roots: Vec<PathBuf>,
    pub realm_filter: Option<String>,
    pub apply: bool,
    pub adopt_root: Option<PathBuf>,
    pub fence_wait: Duration,
    /// Legacy pre-realm `<home>/.rkat/sessions` directory to probe
    /// (report-only), resolved by the caller's bootstrap.
    pub legacy_home_sessions: Option<PathBuf>,
}

fn canonical(path: &Path) -> PathBuf {
    std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

/// Enumerate realm directories across the swept roots, deduplicating roots
/// by canonical identity and applying the realm filter the same way doctor
/// does (sanitized directory name or manifest identity).
fn enumerate_realms(roots: &[PathBuf], realm_filter: Option<&str>) -> Vec<RealmDirEntry> {
    let mut seen_roots: Vec<PathBuf> = Vec::new();
    let mut realms = Vec::new();
    for root in roots {
        let root_canonical = canonical(root);
        if seen_roots.contains(&root_canonical) {
            continue;
        }
        seen_roots.push(root_canonical);
        for realm in store_migrate::list_realm_dirs(root) {
            if let Some(filter) = realm_filter {
                let dir_name = realm
                    .dir
                    .file_name()
                    .map(|name| name.to_string_lossy().into_owned())
                    .unwrap_or_default();
                if dir_name != meerkat_core::sanitize_realm_id(filter) && realm.realm_id != filter {
                    continue;
                }
            }
            realms.push(realm);
        }
    }
    realms
}

/// Group realms by id, deduplicating same-directory spellings so one realm
/// reached through two root spellings never fabricates a twin.
fn group_by_realm(realms: Vec<RealmDirEntry>) -> BTreeMap<String, Vec<RealmDirEntry>> {
    let mut groups: BTreeMap<String, Vec<RealmDirEntry>> = BTreeMap::new();
    for realm in realms {
        let entry = groups.entry(realm.realm_id.clone()).or_default();
        let dir_canonical = canonical(&realm.dir);
        if !entry
            .iter()
            .any(|existing| canonical(&existing.dir) == dir_canonical)
        {
            entry.push(realm);
        }
    }
    for copies in groups.values_mut() {
        copies.sort_by(|a, b| a.dir.cmp(&b.dir));
    }
    groups
}

/// Run `storage migrate` over the given options and produce the report.
/// The caller renders it and maps [`MigrateReport::has_errors`] to exit 1.
pub(crate) async fn run_storage_migrate(options: MigrateOptions) -> MigrateReport {
    let mode = if options.apply {
        MigrateMode::Apply
    } else {
        MigrateMode::DryRun
    };
    let mut report = MigrateReport::new(mode, options.roots.clone());

    let mut groups = group_by_realm(enumerate_realms(
        &options.roots,
        options.realm_filter.as_deref(),
    ));

    // ── Case 3: split-brain reconciliation (fail-closed). ────────────────
    let twin_ids: Vec<String> = groups
        .iter()
        .filter(|(_, copies)| copies.len() > 1)
        .map(|(realm_id, _)| realm_id.clone())
        .collect();
    let resolving = options.apply && options.adopt_root.is_some();
    for realm_id in &twin_ids {
        let Some(copies) = groups.get(realm_id).cloned() else {
            continue;
        };
        if let (true, Some(adopt_root)) = (options.apply, options.adopt_root.as_deref()) {
            // Resolution path: divergence is computed and acted on under
            // held maintenance fences (see `resolve_split_brain`).
            let (split, adopted) =
                resolve_split_brain(realm_id, &copies, adopt_root, options.fence_wait).await;
            match adopted {
                Some(adopted) => {
                    groups.insert(realm_id.clone(), vec![adopted]);
                }
                None => {
                    let reason = match &split.resolution {
                        SplitBrainResolution::Refused { reason }
                        | SplitBrainResolution::ArchiveFailed { reason, .. } => reason.clone(),
                        _ => "split-brain resolution did not complete".to_string(),
                    };
                    report
                        .errors
                        .push(format!("split-brain realm '{realm_id}': {reason}"));
                    groups.remove(realm_id);
                }
            }
            report.split_brain.push(split);
        } else {
            // Fail-closed refusal: the unfenced comparison is advisory (no
            // archive decision rests on it) and is the whole output.
            let locations: Vec<PathBuf> = copies.iter().map(|copy| copy.dir.clone()).collect();
            let divergence_realm = realm_id.clone();
            let divergence_locations = locations.clone();
            let split = tokio::task::spawn_blocking(move || {
                store_migrate::compute_split_brain_report(&divergence_realm, &divergence_locations)
            })
            .await
            .unwrap_or_else(|join_error| {
                let mut failed = SplitBrainReport::new(realm_id.clone(), locations);
                failed
                    .errors
                    .push(format!("divergence computation failed: {join_error}"));
                failed
            });
            report.errors.push(format!(
                "split-brain realm '{realm_id}' is materialized under multiple swept roots; \
                 fail-closed refusal — rerun with `--apply --adopt-root <path>` to adopt one \
                 root and archive the other copies read-only"
            ));
            report.split_brain.push(split);
        }
    }

    if !twin_ids.is_empty() && !resolving {
        // Fail-closed: the divergence report is the whole output.
        return report;
    }

    // ── Cases 1, 2, 4 per unique realm materialization. ──────────────────
    for copies in groups.values() {
        let Some(realm) = copies.first() else {
            continue;
        };
        if copies.len() > 1 {
            continue; // unresolved twin; already reported
        }
        report
            .realms
            .push(migrate_realm(realm, options.apply, options.fence_wait).await);
    }

    // ── Case 5: deprecated leftovers (report-only). ──────────────────────
    let mut scope = DiagnoseScope::new(options.roots.clone());
    if let Some(filter) = &options.realm_filter {
        scope = scope.with_realm(filter.clone());
    }
    let diagnosis = meerkat_store::diagnose_disk_roots(&scope).await;
    report.findings.extend(
        diagnosis
            .findings
            .into_iter()
            .filter(|finding| LEFTOVER_FINDING_CODES.contains(&finding.code.as_str())),
    );
    if let Some(legacy_dir) = &options.legacy_home_sessions
        && legacy_dir.is_dir()
    {
        report.findings.push(
            StorageFinding::new(
                FindingSeverity::Info,
                store_migrate::FINDING_LEGACY_HOME_SESSIONS_DIR,
                "legacy pre-realm sessions directory (report-only; migrate does not move it — \
                 realm-scoped storage supersedes it)",
            )
            .with_path(legacy_dir.clone()),
        );
    }

    report
}

/// Resolve one split-brain twin under held maintenance fences: verify the
/// adopted root is one of the twin's swept roots, fence EVERY copy, compute
/// the divergence report while the fences are held (the archive decision
/// rests on a quiesced snapshot), gate archiving on a conclusive
/// comparison, then archive the non-adopted copies read-only. Returns the
/// finished report plus the adopted copy when — and only when — every
/// archive completed.
async fn resolve_split_brain(
    realm_id: &str,
    copies: &[RealmDirEntry],
    adopt_root: &Path,
    fence_wait: Duration,
) -> (SplitBrainReport, Option<RealmDirEntry>) {
    let locations: Vec<PathBuf> = copies.iter().map(|copy| copy.dir.clone()).collect();
    let refused = |reason: String| {
        let mut split = SplitBrainReport::new(realm_id.to_string(), locations.clone());
        split.resolution = SplitBrainResolution::Refused { reason };
        (split, None)
    };

    let adopt_canonical = canonical(adopt_root);
    let Some(adopted) = copies
        .iter()
        .find(|copy| canonical(&copy.state_root) == adopt_canonical)
        .cloned()
    else {
        return refused(format!(
            "--adopt-root {} is not one of the swept roots materializing this realm \
             (candidates: {})",
            adopt_root.display(),
            copies
                .iter()
                .map(|copy| copy.state_root.display().to_string())
                .collect::<Vec<_>>()
                .join(", ")
        ));
    };

    let realm = realm_id.to_string();
    let adopted_dir = adopted.dir.clone();
    let copy_dirs: Vec<PathBuf> = copies.iter().map(|copy| copy.dir.clone()).collect();
    let task_locations = locations.clone();
    let outcome = tokio::task::spawn_blocking(move || {
        // Fence EVERY copy BEFORE the comparison and hold through the
        // archive renames; copies arrive sorted, so two racing migrators
        // acquire in the same global order.
        let mut fences = Vec::with_capacity(copy_dirs.len());
        for dir in &copy_dirs {
            match store_migrate::RealmMaintenanceFence::acquire(dir, fence_wait) {
                Ok(fence) => fences.push(Some(fence)),
                Err(error) => {
                    let mut split = SplitBrainReport::new(realm, task_locations);
                    split.resolution = SplitBrainResolution::Refused {
                        reason: format!(
                            "maintenance fence not acquirable for {}: {error}",
                            dir.display()
                        ),
                    };
                    return (split, None);
                }
            }
        }

        let mut split = store_migrate::compute_split_brain_report(&realm, &task_locations);
        if !split.comparison_is_conclusive() {
            // An unreadable side may hold the only copy of content the
            // report cannot account for; no archive decision may rest on it.
            split.resolution = SplitBrainResolution::Refused {
                reason: "divergence comparison is inconclusive (unreadable entries poisoned \
                         it); repair the read failures in the report and rerun"
                    .to_string(),
            };
            return (split, None);
        }

        // Successful archives accumulate here so a later failure keeps them
        // visible (`ArchiveFailed`) instead of discarding them.
        let mut archived: Vec<PathBuf> = Vec::new();
        let mut warnings: Vec<String> = Vec::new();
        for (index, dir) in copy_dirs.iter().enumerate() {
            if *dir == adopted_dir {
                continue;
            }
            // Release this copy's fence right before the rename: the fence
            // holds open lock-file handles inside the directory, and a
            // directory with open handles cannot be renamed on Windows.
            // Quiescence is already established; the fences on the other
            // copies stay held until every archive completes. The released
            // lock files ride into the archive.
            fences[index] = None;
            match store_migrate::archive_path_read_only_reported(dir, "split-brain") {
                Ok(archive) => {
                    warnings.extend(archive.warnings);
                    archived.push(archive.archive);
                }
                Err(error) => {
                    split.errors.extend(warnings);
                    split.resolution = SplitBrainResolution::ArchiveFailed {
                        adopted: adopted_dir,
                        archived,
                        reason: format!("archive of {} failed: {error}", dir.display()),
                    };
                    return (split, None);
                }
            }
        }
        drop(fences);
        // Post-rename hardening/durability warnings are report-only; the
        // report has no separate warning slot, so they ride the split-brain
        // `errors` (which `MigrateReport::has_errors` does not count).
        split.errors.extend(warnings);
        split.resolution = SplitBrainResolution::Archived {
            adopted: adopted_dir,
            archived,
        };
        (split, Some(adopted))
    })
    .await;

    match outcome {
        Ok(result) => result,
        Err(join_error) => refused(format!("archive task failed: {join_error}")),
    }
}

/// Fold a read-only ledger baseline into the per-realm report: rows become
/// ledger entries under `action_of`, read failures become per-realm errors
/// (a corrupt database is never laundered into a missing ledger the report
/// could call missing-row), and future-versioned domains become refusals
/// exactly as `--apply`'s guarded constructors would refuse them
/// (`SchemaFromTheFuture`) — their rows report-only, never missing-row.
fn fold_ledger_baseline(
    baseline: &store_migrate::RealmLedgerBaseline,
    entry: &mut RealmMigrateReport,
    action_of: impl Fn(&store_migrate::LedgerDomainReading) -> LedgerBaselineAction,
) {
    entry.errors.extend(baseline.errors.iter().cloned());
    for future in &baseline.future {
        entry.errors.push(format!(
            "refusing domain '{}' in {}: schema is from the future (file has version {}, this \
             binary supports up to {})",
            future.domain,
            future.database.display(),
            future.found,
            future.supported
        ));
    }
    for row in &baseline.rows {
        let action = if baseline
            .future
            .iter()
            .any(|future| future.database == row.database && future.domain == row.domain)
        {
            LedgerBaselineAction::ReportOnly
        } else {
            action_of(row)
        };
        let mut ledger_entry =
            LedgerBaselineEntry::new(row.database.clone(), row.domain.clone(), action);
        ledger_entry.before = row.version;
        entry.ledger.push(ledger_entry);
    }
}

/// Report-only entries for per-mob databases (`mobs/*.db`): their ledger
/// versions are read, but v1 never opens mob stores offline — the owning
/// store converges each file on its next open.
fn mob_report_only_entries(realm_dir: &Path, entry: &mut RealmMigrateReport) {
    let Ok(dir_entries) = std::fs::read_dir(realm_dir.join("mobs")) else {
        return;
    };
    let mut databases: Vec<PathBuf> = dir_entries
        .filter_map(Result::ok)
        .map(|dir_entry| dir_entry.path())
        .filter(|path| {
            path.extension().and_then(|ext| ext.to_str()) == Some("db") && path.is_file()
        })
        .collect();
    databases.sort();
    if databases.is_empty() {
        return;
    }
    for database in databases {
        let version = store_migrate::read_domain_versions(&database)
            .ok()
            .flatten()
            .and_then(|rows| {
                rows.into_iter()
                    .find(|(domain, _)| domain == "mob")
                    .map(|(_, version)| version)
            });
        let mut ledger_entry =
            LedgerBaselineEntry::new(database, "mob", LedgerBaselineAction::ReportOnly);
        ledger_entry.before = version;
        entry.ledger.push(ledger_entry);
    }
    entry.notes.push(
        "mob databases are report-only in v1; the owning mob store converges each file on its \
         next open"
            .to_string(),
    );
}

/// Cases 1 and 2 for one realm materialization.
async fn migrate_realm(
    realm: &RealmDirEntry,
    apply: bool,
    fence_wait: Duration,
) -> RealmMigrateReport {
    let mut entry = RealmMigrateReport::new(realm.realm_id.clone(), realm.dir.clone());
    entry.backend = realm.backend.clone();
    // Case 2: state-root adoption is report-only — the realm is used where
    // it lies (the phase-2 dual-root resolver's steady state).
    entry.notes.push(format!(
        "state-root adoption: realm is used where it lies (state root {})",
        realm.state_root.display()
    ));

    if !realm.manifest_readable {
        entry.errors.push(
            "realm manifest unreadable; refusing to migrate (repair or remove the manifest \
             first)"
                .to_string(),
        );
        return entry;
    }
    let backend = realm.backend.clone().unwrap_or_default();
    match backend.as_str() {
        "memory" => {
            entry
                .notes
                .push("memory backend: no durable storage; nothing to migrate".to_string());
            return entry;
        }
        "sqlite" | "jsonl" => {}
        other => {
            entry.notes.push(format!(
                "backend '{other}' is not disk-migratable by this build; report-only"
            ));
            let baseline = store_migrate::read_realm_ledger_baseline(&realm.dir);
            fold_ledger_baseline(&baseline, &mut entry, |_| LedgerBaselineAction::ReportOnly);
            return entry;
        }
    }

    // Path-alias guard: the realm's directory must be the one its id
    // sanitizes to, or the normal constructors would open a different path.
    let expected_dir = meerkat_store::realm_paths_in(&realm.state_root, &realm.realm_id).root;
    if canonical(&expected_dir) != canonical(&realm.dir) {
        entry.errors.push(format!(
            "realm id '{}' sanitizes to directory {}, but this realm lies at {}; refusing to \
             open (path-aliased manifest)",
            realm.realm_id,
            expected_dir.display(),
            realm.dir.display()
        ));
        return entry;
    }

    if !apply {
        dry_run_realm(realm, &backend, &mut entry).await;
        mob_report_only_entries(&realm.dir, &mut entry);
        return entry;
    }

    apply_realm(realm, &backend, fence_wait, &mut entry).await;
    mob_report_only_entries(&realm.dir, &mut entry);
    entry
}

/// Case 1 dry-run: read-only ledger baseline. The database bytes are
/// untouched.
async fn dry_run_realm(realm: &RealmDirEntry, _backend: &str, entry: &mut RealmMigrateReport) {
    let dir = realm.dir.clone();
    match tokio::task::spawn_blocking(move || store_migrate::read_realm_ledger_baseline(&dir)).await
    {
        Ok(baseline) => fold_ledger_baseline(&baseline, entry, |row| {
            if row.version.is_some() {
                LedgerBaselineAction::Recorded
            } else {
                LedgerBaselineAction::MissingRow
            }
        }),
        Err(join_error) => entry
            .errors
            .push(format!("ledger baseline read failed: {join_error}")),
    }
}

/// Apply: fence the realm and run every store's normal constructor. The
/// guarded ledger migrations are the structural verification.
#[cfg(feature = "session-store")]
async fn apply_realm(
    realm: &RealmDirEntry,
    _backend: &str,
    fence_wait: Duration,
    entry: &mut RealmMigrateReport,
) {
    // Exclusive maintenance fence over every database in the realm (waits
    // for in-flight per-operation guards to drain; foreign holders surface
    // typed).
    let fence_dir = realm.dir.clone();
    let fence = match tokio::task::spawn_blocking(move || {
        store_migrate::RealmMaintenanceFence::acquire(&fence_dir, fence_wait)
    })
    .await
    {
        Ok(Ok(fence)) => fence,
        Ok(Err(error)) => {
            entry
                .errors
                .push(format!("maintenance fence not acquirable: {error}"));
            return;
        }
        Err(join_error) => {
            entry
                .errors
                .push(format!("maintenance fence not acquirable: {join_error}"));
            return;
        }
    };

    let before_dir = realm.dir.clone();
    let before = match tokio::task::spawn_blocking(move || {
        store_migrate::read_realm_ledger_baseline(&before_dir)
    })
    .await
    {
        Ok(baseline) => {
            // Read failures surface; the guarded constructors below own the
            // future-version refusals on apply.
            entry.errors.extend(baseline.errors.iter().cloned());
            baseline.rows
        }
        Err(join_error) => {
            entry
                .errors
                .push(format!("ledger baseline read failed: {join_error}"));
            Vec::new()
        }
    };

    // Case 1: normal constructors via the facade bundle (sessions, schedule,
    // runtime, workgraph, blobs) — plus the stores the bundle does not own.
    let opened =
        meerkat::open_realm_persistence_in(&realm.state_root, &realm.realm_id, None, None).await;
    let bundle = match opened {
        Ok((_manifest, bundle)) => bundle,
        Err(error) => {
            entry
                .errors
                .push(format!("realm store open failed: {error}"));
            drop(fence);
            return;
        }
    };

    let memory_db = realm.dir.join("memory").join("memory.sqlite3");
    if memory_db.is_file() {
        #[cfg(feature = "memory-store")]
        {
            let memory_dir = realm.dir.join("memory");
            match tokio::task::spawn_blocking(move || meerkat::HnswMemoryStore::open(&memory_dir))
                .await
            {
                Ok(Ok(_store)) => {}
                Ok(Err(error)) => entry
                    .errors
                    .push(format!("memory store open failed: {error}")),
                Err(join_error) => entry
                    .errors
                    .push(format!("memory store open failed: {join_error}")),
            }
        }
        #[cfg(not(feature = "memory-store"))]
        entry.notes.push(
            "memory database present but this build lacks the memory-store feature; report-only"
                .to_string(),
        );
    }
    let tasks_db = realm.dir.join("tasks.db");
    if tasks_db.is_file() {
        use meerkat::TaskStore as _;
        let task_store = meerkat::SqliteTaskStore::unscoped(&tasks_db);
        if let Err(error) = task_store.list().await {
            entry
                .errors
                .push(format!("task store open failed: {error}"));
        }
    }
    let index_db = realm
        .dir
        .join("sessions_jsonl")
        .join("session_index.sqlite3");
    if index_db.is_file()
        && let Err(error) = tokio::task::spawn_blocking(move || {
            meerkat_store::index::SqliteSessionIndex::open(index_db)
        })
        .await
        .map_err(|join_error| meerkat_store::StoreError::Internal(join_error.to_string()))
        .and_then(|result| result.map(|_| ()))
    {
        entry
            .errors
            .push(format!("session index open failed: {error}"));
    }

    drop(bundle);

    // Ledger entries: before → after per database × domain.
    let after_dir = realm.dir.clone();
    let after = match tokio::task::spawn_blocking(move || {
        store_migrate::read_realm_ledger_baseline(&after_dir)
    })
    .await
    {
        Ok(baseline) => {
            // The before read already reported still-standing failures.
            for error in &baseline.errors {
                if !entry.errors.contains(error) {
                    entry.errors.push(error.clone());
                }
            }
            baseline.rows
        }
        Err(join_error) => {
            entry
                .errors
                .push(format!("ledger baseline read failed: {join_error}"));
            Vec::new()
        }
    };
    let before_of = |database: &Path, domain: &str| -> Option<i64> {
        before
            .iter()
            .find(|row| row.database == database && row.domain == domain)
            .and_then(|row| row.version)
    };
    for row in after {
        let before_version = before_of(&row.database, &row.domain);
        let action = if row.version == before_version {
            LedgerBaselineAction::AlreadyCurrent
        } else {
            LedgerBaselineAction::Stamped
        };
        let mut ledger_entry = LedgerBaselineEntry::new(row.database, row.domain, action);
        ledger_entry.before = before_version;
        ledger_entry.after = row.version;
        entry.ledger.push(ledger_entry);
    }

    drop(fence);
}

#[cfg(not(feature = "session-store"))]
async fn apply_realm(
    _realm: &RealmDirEntry,
    _backend: &str,
    _fence_wait: Duration,
    entry: &mut RealmMigrateReport,
) {
    entry.errors.push(
        "this rkat build lacks the session-store feature; `storage migrate --apply` is \
         unavailable"
            .to_string(),
    );
}

// ─────────────────────────────────────────────────────────────────────────
// `storage prune`
// ─────────────────────────────────────────────────────────────────────────

/// Options for one `storage prune` run.
pub(crate) struct PruneOptions {
    pub roots: Vec<PathBuf>,
    pub apply: bool,
    pub older_than_days: u64,
    /// `--realm` scope: only this realm's artifacts are eligible.
    pub realm_filter: Option<String>,
}

/// Run `storage prune`: enumerate registered maintenance artifacts
/// (`*.pre-*` backups and `*.corrupt-*` quarantines) under the swept roots;
/// with `--apply`, delete those at least `older_than_days` old. Nothing
/// outside the registered naming patterns is ever touched.
pub(crate) async fn run_storage_prune(options: PruneOptions) -> PruneReport {
    let roots = options.roots.clone();
    let realm_filter = options.realm_filter.clone();
    let mut artifacts = tokio::task::spawn_blocking(move || {
        store_migrate::enumerate_maintenance_artifacts_filtered(&roots, realm_filter.as_deref())
    })
    .await
    .unwrap_or_default();

    let mode = if options.apply {
        MigrateMode::Apply
    } else {
        MigrateMode::DryRun
    };
    let mut report = PruneReport::new(mode, options.roots, options.older_than_days);

    for artifact in &mut artifacts {
        if artifact.age_days < options.older_than_days {
            artifact.action = PruneAction::Kept;
            continue;
        }
        if !options.apply {
            artifact.action = PruneAction::WouldDelete;
            continue;
        }
        let path = artifact.path.clone();
        match tokio::task::spawn_blocking(move || store_migrate::remove_maintenance_artifact(&path))
            .await
        {
            Ok(Ok(())) => artifact.action = PruneAction::Deleted,
            Ok(Err(error)) => {
                artifact.action = PruneAction::DeleteFailed;
                report.errors.push(format!(
                    "failed to delete {}: {error}",
                    artifact.path.display()
                ));
            }
            Err(join_error) => {
                artifact.action = PruneAction::DeleteFailed;
                report.errors.push(format!(
                    "failed to delete {}: {join_error}",
                    artifact.path.display()
                ));
            }
        }
    }
    report.artifacts = artifacts;
    report
}

// ─────────────────────────────────────────────────────────────────────────
// Text rendering (per-realm grouping; --json serializes the report types).
// ─────────────────────────────────────────────────────────────────────────

fn describe_status(status: &DivergenceStatus) -> String {
    match status {
        DivergenceStatus::Equal => "equal".to_string(),
        DivergenceStatus::Divergent => "divergent".to_string(),
        DivergenceStatus::OnlyIn { location } => format!("only in {}", location.display()),
        _ => "unknown".to_string(),
    }
}

fn describe_ledger_action(action: LedgerBaselineAction) -> &'static str {
    match action {
        LedgerBaselineAction::MissingRow => "missing-row",
        LedgerBaselineAction::Recorded => "recorded",
        LedgerBaselineAction::Stamped => "stamped",
        LedgerBaselineAction::AlreadyCurrent => "already-current",
        LedgerBaselineAction::ReportOnly => "report-only",
        _ => "unknown",
    }
}

fn describe_version(version: Option<i64>) -> String {
    version.map_or_else(|| "none".to_string(), |value| value.to_string())
}

/// Human-readable migrate report, grouped per realm.
pub(crate) fn print_migrate_report_text(report: &MigrateReport) {
    let mode = match report.mode {
        MigrateMode::Apply => "apply",
        _ => "dry-run",
    };
    println!(
        "Storage migrate ({mode}) over {} root(s):",
        report.swept_roots.len()
    );
    for root in &report.swept_roots {
        println!("  {}", root.display());
    }
    println!();

    for split in &report.split_brain {
        println!("Split-brain realm '{}':", split.realm);
        for location in &split.locations {
            println!("  copy: {}", location.display());
        }
        println!(
            "  sessions: {} equal across all copies",
            split.sessions_equal
        );
        for session in &split.sessions {
            println!(
                "    {}: {}",
                session.session_id,
                describe_status(&session.status)
            );
        }
        for file in &split.files {
            println!("  file {}: {}", file.file, describe_status(&file.status));
        }
        match &split.resolution {
            SplitBrainResolution::Refused { reason } => {
                println!("  resolution: REFUSED — {reason}");
            }
            SplitBrainResolution::Archived { adopted, archived } => {
                println!("  resolution: adopted {}", adopted.display());
                for archive in archived {
                    println!("    archived read-only: {}", archive.display());
                }
            }
            SplitBrainResolution::ArchiveFailed {
                adopted,
                archived,
                reason,
            } => {
                println!("  resolution: ARCHIVE FAILED — {reason}");
                println!("    adopted (untouched): {}", adopted.display());
                for archive in archived {
                    println!(
                        "    archived read-only before the failure: {}",
                        archive.display()
                    );
                }
            }
            _ => println!("  resolution: unknown"),
        }
        for error in &split.errors {
            println!("  error: {error}");
        }
        println!();
    }

    for realm in &report.realms {
        println!(
            "Realm '{}'  backend={}  at {}",
            realm.realm,
            realm.backend.as_deref().unwrap_or("unknown"),
            realm.root.display()
        );
        for entry in &realm.ledger {
            let database = entry
                .database
                .strip_prefix(&realm.root)
                .map(|relative| relative.display().to_string())
                .unwrap_or_else(|_| entry.database.display().to_string());
            println!(
                "  ledger {database} [{}]: {} -> {} ({})",
                entry.domain,
                describe_version(entry.before),
                describe_version(entry.after),
                describe_ledger_action(entry.action)
            );
        }
        for note in &realm.notes {
            println!("  note: {note}");
        }
        for error in &realm.errors {
            println!("  error: {error}");
        }
        println!();
    }

    if !report.findings.is_empty() {
        println!("Leftovers (report-only):");
        for finding in &report.findings {
            let path = finding
                .path
                .as_ref()
                .map(|path| format!(" at {}", path.display()))
                .unwrap_or_default();
            println!("  [{}] {}{path}", finding.code, finding.message);
        }
        println!();
    }

    let error_count = report.errors.len()
        + report
            .realms
            .iter()
            .map(|realm| realm.errors.len())
            .sum::<usize>();
    for error in &report.errors {
        println!("error: {error}");
    }
    println!("storage migrate: {error_count} error(s)");
}

/// Human-readable prune report.
pub(crate) fn print_prune_report_text(report: &PruneReport) {
    let mode = match report.mode {
        MigrateMode::Apply => "apply",
        _ => "dry-run",
    };
    println!(
        "Storage prune ({mode}, older than {} day(s)) over {} root(s):",
        report.older_than_days,
        report.swept_roots.len()
    );
    for root in &report.swept_roots {
        println!("  {}", root.display());
    }
    println!();
    if report.artifacts.is_empty() {
        println!("No registered maintenance artifacts found.");
    }
    for artifact in &report.artifacts {
        let action = match artifact.action {
            PruneAction::WouldDelete => "would delete",
            PruneAction::Deleted => "deleted",
            PruneAction::Kept => "kept (younger than threshold)",
            PruneAction::DeleteFailed => "DELETE FAILED",
            _ => "unknown",
        };
        println!(
            "  {}  {} bytes, {} day(s) old — {action}",
            artifact.path.display(),
            artifact.bytes,
            artifact.age_days
        );
    }
    for error in &report.errors {
        println!("error: {error}");
    }
    println!("storage prune: {} error(s)", report.errors.len());
}