shodh-memory 0.2.0

Persistent cognitive memory for AI agents and robots — Hebbian learning, knowledge graph, spatial recall. Zenoh/ROS2 native. Single binary, runs offline.
Documentation
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
//! Offline migration from legacy serialization formats to postcard.
//!
//! Run via: `shodh-memory-server migrate --storage <path> [--dry-run]`
//!
//! This reads every record in every RocksDB store, decodes it using the
//! legacy format (bincode 2.x for most stores, msgpack for learning events),
//! re-encodes it as postcard with the appropriate format tag or SHO envelope,
//! and writes it back. Records that are already in postcard format are skipped.
//!
//! ## Safety
//!
//! - The server must NOT be running during migration (checked via RocksDB lock).
//! - On success, a marker file `migration_v2_postcard` is written to the storage
//!   directory. The server will refuse to start without this marker once the
//!   migration code is shipped (future enforcement, not yet gated).
//! - `--dry-run` reports what would be migrated without modifying any data.

use anyhow::{Context, Result};
use rocksdb::{ColumnFamilyDescriptor, IteratorMode, Options as RocksOptions, WriteBatch, DB};
use std::path::Path;

use crate::serialization;

// Re-use the actual stored types for deserialization.
// These are the concrete types that bincode encoded into RocksDB values.
use crate::graph_memory::{EntityNode, EpisodicNode, RelationshipEdge};
use crate::handlers::types::AuditEvent;
use crate::memory::compression::SemanticFact;
use crate::memory::lineage::{LineageBranch, LineageEdge};
use crate::memory::storage::VectorMappingEntry;
use crate::memory::temporal_facts::TemporalFact;

/// Marker file written after successful migration.
const MIGRATION_MARKER: &str = "migration_v2_postcard";

/// Maximum records per WriteBatch to bound memory usage.
const BATCH_SIZE: usize = 500;

/// Check whether the storage directory has already been migrated.
pub fn is_migrated(storage_path: &Path) -> bool {
    storage_path.join(MIGRATION_MARKER).exists()
}

/// Summary of a completed migration run.
#[derive(Debug, Default)]
pub struct MigrationReport {
    pub users: usize,
    pub memories_migrated: usize,
    pub memories_skipped: usize,
    pub graph_records_migrated: usize,
    pub graph_records_skipped: usize,
    pub facts_migrated: usize,
    pub facts_skipped: usize,
    pub lineage_migrated: usize,
    pub lineage_skipped: usize,
    pub temporal_migrated: usize,
    pub temporal_skipped: usize,
    pub vector_mappings_migrated: usize,
    pub vector_mappings_skipped: usize,
    pub audit_migrated: usize,
    pub audit_skipped: usize,
    pub errors: Vec<String>,
    pub dry_run: bool,
}

impl std::fmt::Display for MigrationReport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mode = if self.dry_run { "DRY RUN" } else { "MIGRATED" };
        writeln!(f, "=== Postcard Migration Report ({mode}) ===")?;
        writeln!(f, "Users processed:       {}", self.users)?;
        writeln!(
            f,
            "Memories:              {} migrated, {} skipped",
            self.memories_migrated, self.memories_skipped
        )?;
        writeln!(
            f,
            "Graph records:         {} migrated, {} skipped",
            self.graph_records_migrated, self.graph_records_skipped
        )?;
        writeln!(
            f,
            "Facts + embeddings:    {} migrated, {} skipped",
            self.facts_migrated, self.facts_skipped
        )?;
        writeln!(
            f,
            "Lineage edges/branches:{} migrated, {} skipped",
            self.lineage_migrated, self.lineage_skipped
        )?;
        writeln!(
            f,
            "Temporal facts:        {} migrated, {} skipped",
            self.temporal_migrated, self.temporal_skipped
        )?;
        writeln!(
            f,
            "Vector mappings:       {} migrated, {} skipped",
            self.vector_mappings_migrated, self.vector_mappings_skipped
        )?;
        writeln!(
            f,
            "Audit events:          {} migrated, {} skipped",
            self.audit_migrated, self.audit_skipped
        )?;
        if !self.errors.is_empty() {
            writeln!(f, "Errors:                {}", self.errors.len())?;
            for (i, e) in self.errors.iter().enumerate().take(20) {
                writeln!(f, "  [{i}] {e}")?;
            }
            if self.errors.len() > 20 {
                writeln!(f, "  ... and {} more", self.errors.len() - 20)?;
            }
        }
        Ok(())
    }
}

/// Run the full migration on the given storage directory.
pub fn migrate_all(storage_path: &Path, dry_run: bool) -> Result<MigrationReport> {
    let mut report = MigrationReport {
        dry_run,
        ..Default::default()
    };

    if is_migrated(storage_path) {
        eprintln!("Storage already migrated (marker file exists). Nothing to do.");
        return Ok(report);
    }

    if !storage_path.exists() {
        anyhow::bail!("Storage path does not exist: {}", storage_path.display());
    }

    // --- Shared DB (audit events) ---
    let shared_path = storage_path.join("shared");
    if shared_path.exists() {
        eprintln!("Migrating shared DB (audit events)...");
        match migrate_shared_db(&shared_path, dry_run) {
            Ok((migrated, skipped)) => {
                report.audit_migrated = migrated;
                report.audit_skipped = skipped;
            }
            Err(e) => {
                report.errors.push(format!("shared DB: {e:#}"));
            }
        }
    }

    // --- Per-user databases ---
    let entries: Vec<_> = std::fs::read_dir(storage_path)
        .context("reading storage directory")?
        .filter_map(|e| e.ok())
        .filter(|e| {
            let name = e.file_name();
            let name_str = name.to_string_lossy();
            e.path().is_dir() && name_str != "shared" && !name_str.ends_with(".pre_cf_migration")
        })
        .collect();

    for entry in &entries {
        let user_id = entry.file_name();
        let user_id_str = user_id.to_string_lossy();
        let user_path = entry.path();

        eprintln!("Migrating user: {user_id_str}");
        report.users += 1;

        // Memory DB (storage/ subdir)
        let storage_dir = user_path.join("storage");
        if storage_dir.exists() {
            match migrate_memory_db(&storage_dir, dry_run) {
                Ok(counts) => {
                    report.memories_migrated += counts.memories_migrated;
                    report.memories_skipped += counts.memories_skipped;
                    report.facts_migrated += counts.facts_migrated;
                    report.facts_skipped += counts.facts_skipped;
                    report.lineage_migrated += counts.lineage_migrated;
                    report.lineage_skipped += counts.lineage_skipped;
                    report.temporal_migrated += counts.temporal_migrated;
                    report.temporal_skipped += counts.temporal_skipped;
                    report.vector_mappings_migrated += counts.vector_mappings_migrated;
                    report.vector_mappings_skipped += counts.vector_mappings_skipped;
                }
                Err(e) => {
                    report
                        .errors
                        .push(format!("user {user_id_str} memory DB: {e:#}"));
                }
            }
        }

        // Graph DB (graph/ subdir)
        let graph_dir = user_path.join("graph");
        if graph_dir.exists() {
            match migrate_graph_db(&graph_dir, dry_run) {
                Ok((migrated, skipped)) => {
                    report.graph_records_migrated += migrated;
                    report.graph_records_skipped += skipped;
                }
                Err(e) => {
                    report
                        .errors
                        .push(format!("user {user_id_str} graph DB: {e:#}"));
                }
            }
        }
    }

    // Write migration marker.
    // We write the marker even if some individual records failed to decode —
    // those records are corrupted in the DB and won't improve on re-run.
    // The marker is only withheld if we had zero successful migrations
    // (indicating a systemic failure like wrong DB path or permissions).
    if !dry_run {
        let total_migrated = report.memories_migrated
            + report.graph_records_migrated
            + report.facts_migrated
            + report.lineage_migrated
            + report.temporal_migrated
            + report.audit_migrated;
        let total_skipped = report.memories_skipped
            + report.graph_records_skipped
            + report.facts_skipped
            + report.lineage_skipped
            + report.temporal_skipped
            + report.audit_skipped;

        if total_migrated > 0 || total_skipped > 0 {
            let marker_path = storage_path.join(MIGRATION_MARKER);
            let timestamp = chrono::Utc::now().to_rfc3339();
            std::fs::write(
                &marker_path,
                format!(
                    "migrated_at={timestamp}\nmemories={}\ngraph={}\nfacts={}\nlineage={}\ntemporal={}\naudit={}\nerrors={}\n",
                    report.memories_migrated,
                    report.graph_records_migrated,
                    report.facts_migrated,
                    report.lineage_migrated,
                    report.temporal_migrated,
                    report.audit_migrated,
                    report.errors.len(),
                ),
            )
            .context("writing migration marker file")?;
            eprintln!("Migration marker written to {}", marker_path.display());
            if !report.errors.is_empty() {
                eprintln!(
                    "NOTE: {} records could not be decoded (pre-existing corruption). These were skipped.",
                    report.errors.len()
                );
            }
        } else if !report.errors.is_empty() {
            eprintln!(
                "ERROR: {} errors and no records migrated — marker NOT written. Check storage path and permissions.",
                report.errors.len()
            );
        }
    }

    Ok(report)
}

// ---------------------------------------------------------------------------
// Memory DB migration
// ---------------------------------------------------------------------------

/// Counts for the per-user memory DB migration.
#[derive(Default)]
struct MemoryDbCounts {
    memories_migrated: usize,
    memories_skipped: usize,
    facts_migrated: usize,
    facts_skipped: usize,
    lineage_migrated: usize,
    lineage_skipped: usize,
    temporal_migrated: usize,
    temporal_skipped: usize,
    vector_mappings_migrated: usize,
    vector_mappings_skipped: usize,
}

/// Known prefixes for sub-stores in the memory DB default CF.
const FACTS_PREFIX: &[u8] = b"facts:";
const FACTS_BY_ENTITY_PREFIX: &[u8] = b"facts_by_entity:";
const FACTS_BY_TYPE_PREFIX: &[u8] = b"facts_by_type:";
const FACTS_EMBEDDING_PREFIX: &[u8] = b"facts_embedding:";
const TEMPORAL_FACTS_PREFIX: &[u8] = b"temporal_facts:";
const TEMPORAL_BY_ENTITY_PREFIX: &[u8] = b"temporal_by_entity:";
const TEMPORAL_BY_EVENT_PREFIX: &[u8] = b"temporal_by_event:";
const TEMPORAL_BY_TIME_PREFIX: &[u8] = b"temporal_by_time:";
const VMAPPING_PREFIX: &[u8] = b"vmapping:";
const LEARNING_PREFIX: &[u8] = b"learning:";

/// Prefixes whose values are plain string references (not serialized structs).
/// Index entries: their values are just key references — no binary format to migrate.
const INDEX_ONLY_PREFIXES: &[&[u8]] = &[
    b"stats:",
    b"interference:",
    b"interference_meta:",
    b"_watermark:",
    FACTS_BY_ENTITY_PREFIX,
    FACTS_BY_TYPE_PREFIX,
    b"learning_by_memory:",
    b"learning_by_type:",
    b"learning_by_fact:",
    b"learning_stats:",
    b"geo:",
    // lineage by_from / by_to are index refs, but edges/branches are bincode
    b"lineage:by_from:",
    b"lineage:by_to:",
    // temporal index entries
    TEMPORAL_BY_ENTITY_PREFIX,
    TEMPORAL_BY_EVENT_PREFIX,
    TEMPORAL_BY_TIME_PREFIX,
];

fn migrate_memory_db(storage_dir: &Path, dry_run: bool) -> Result<MemoryDbCounts> {
    let cf_index = "memory_index";
    let mut opts = RocksOptions::default();
    opts.create_if_missing(false);
    opts.create_missing_column_families(true);

    let cfs = vec![
        ColumnFamilyDescriptor::new("default", RocksOptions::default()),
        ColumnFamilyDescriptor::new(cf_index, RocksOptions::default()),
    ];

    let db = DB::open_cf_descriptors(&opts, storage_dir, cfs)
        .with_context(|| format!("opening memory DB at {}", storage_dir.display()))?;

    let mut counts = MemoryDbCounts::default();
    let mut total_processed: usize = 0;

    // --- Default CF: memories + sub-stores ---
    let mut batch = WriteBatch::default();
    let mut batch_count: usize = 0;

    for item in db.iterator(IteratorMode::Start) {
        let (key, value) = item?;

        total_processed += 1;
        if total_processed % 1000 == 0 {
            eprintln!("  ... processed {total_processed} records");
        }

        // Skip index-only entries (values are plain string references, not serialized)
        if INDEX_ONLY_PREFIXES.iter().any(|p| key.starts_with(p)) {
            continue;
        }

        // Learning events: stay on msgpack (ConsolidationEvent uses #[serde(tag = "type")])
        if key.starts_with(LEARNING_PREFIX) {
            continue;
        }

        // Determine record type by key prefix
        if key.starts_with(FACTS_PREFIX) && !key.starts_with(FACTS_EMBEDDING_PREFIX) {
            // SemanticFact
            migrate_generic_record::<SemanticFact>(
                &db,
                None,
                &key,
                &value,
                dry_run,
                &mut batch,
                &mut batch_count,
                &mut counts.facts_migrated,
                &mut counts.facts_skipped,
            )?;
        } else if key.starts_with(FACTS_EMBEDDING_PREFIX) {
            // Vec<f32> embedding
            migrate_generic_record::<Vec<f32>>(
                &db,
                None,
                &key,
                &value,
                dry_run,
                &mut batch,
                &mut batch_count,
                &mut counts.facts_migrated,
                &mut counts.facts_skipped,
            )?;
        } else if key.starts_with(b"lineage:edges:") {
            // LineageEdge
            migrate_generic_record::<LineageEdge>(
                &db,
                None,
                &key,
                &value,
                dry_run,
                &mut batch,
                &mut batch_count,
                &mut counts.lineage_migrated,
                &mut counts.lineage_skipped,
            )?;
        } else if key.starts_with(b"lineage:branches:") {
            // LineageBranch
            migrate_generic_record::<LineageBranch>(
                &db,
                None,
                &key,
                &value,
                dry_run,
                &mut batch,
                &mut batch_count,
                &mut counts.lineage_migrated,
                &mut counts.lineage_skipped,
            )?;
        } else if key.starts_with(TEMPORAL_FACTS_PREFIX) {
            // TemporalFact
            migrate_generic_record::<TemporalFact>(
                &db,
                None,
                &key,
                &value,
                dry_run,
                &mut batch,
                &mut batch_count,
                &mut counts.temporal_migrated,
                &mut counts.temporal_skipped,
            )?;
        } else if key.starts_with(VMAPPING_PREFIX) {
            // VectorMappingEntry
            migrate_generic_record::<VectorMappingEntry>(
                &db,
                None,
                &key,
                &value,
                dry_run,
                &mut batch,
                &mut batch_count,
                &mut counts.vector_mappings_migrated,
                &mut counts.vector_mappings_skipped,
            )?;
        } else if key.len() == 16 {
            // Memory record (16-byte UUID key) — uses SHO envelope
            if let Some((version, _payload)) = serialization::unwrap_sho(&value) {
                if version == serialization::SHO_VERSION_POSTCARD {
                    // Already postcard
                    counts.memories_skipped += 1;
                    continue;
                }
            }

            // Try to deserialize with the full legacy fallback chain
            match crate::memory::storage::deserialize_memory_for_migration(&value) {
                Ok(memory) => {
                    if !dry_run {
                        let new_value = serialization::encode_sho(&memory)?;
                        batch.put(&*key, &new_value);
                        batch_count += 1;
                    }
                    counts.memories_migrated += 1;
                }
                Err(e) => {
                    eprintln!(
                        "  WARNING: cannot decode memory key ({} bytes): {e:#}",
                        key.len()
                    );
                    // Don't fail the whole migration for one bad record
                }
            }
        }
        // else: unknown prefix / unknown key length — skip silently

        // Flush batch periodically
        if batch_count >= BATCH_SIZE && !dry_run {
            db.write(std::mem::take(&mut batch))?;
            batch_count = 0;
        }
    }

    // --- memory_index CF: VectorMappingEntry records ---
    if let Some(cf) = db.cf_handle(cf_index) {
        for item in db.iterator_cf(cf, IteratorMode::Start) {
            let (key, value) = item?;
            // The memory_index CF stores various index entries. Only vmapping entries
            // need migration — others are string references or small metadata.
            if key.starts_with(VMAPPING_PREFIX) {
                migrate_generic_record::<VectorMappingEntry>(
                    &db,
                    Some(cf),
                    &key,
                    &value,
                    dry_run,
                    &mut batch,
                    &mut batch_count,
                    &mut counts.vector_mappings_migrated,
                    &mut counts.vector_mappings_skipped,
                )?;
            }
        }
    }

    // Flush remaining
    if batch_count > 0 && !dry_run {
        db.write(batch)?;
    }

    eprintln!(
        "  Memory DB: {} memories migrated, {} skipped",
        counts.memories_migrated, counts.memories_skipped
    );

    Ok(counts)
}

// ---------------------------------------------------------------------------
// Graph DB migration
// ---------------------------------------------------------------------------

/// Graph DB column families that contain serialized data (entities, edges, episodes).
const GRAPH_DATA_CFS: &[&str] = &["entities", "relationships", "episodes", "entity_edges"];

/// Graph DB column families that contain index data (string references, counts) — skip.
const GRAPH_INDEX_CFS: &[&str] = &[
    "entity_pair_index",
    "entity_episodes",
    "name_index",
    "lowercase_index",
    "stemmed_index",
];

fn migrate_graph_db(graph_dir: &Path, dry_run: bool) -> Result<(usize, usize)> {
    let mut opts = RocksOptions::default();
    opts.create_if_missing(false);
    opts.create_missing_column_families(true);

    let all_cfs: Vec<&str> = GRAPH_DATA_CFS
        .iter()
        .chain(GRAPH_INDEX_CFS.iter())
        .copied()
        .collect();

    let cfs: Vec<ColumnFamilyDescriptor> = std::iter::once(ColumnFamilyDescriptor::new(
        "default",
        RocksOptions::default(),
    ))
    .chain(
        all_cfs
            .iter()
            .map(|name| ColumnFamilyDescriptor::new(*name, RocksOptions::default())),
    )
    .collect();

    let db = DB::open_cf_descriptors(&opts, graph_dir, cfs)
        .with_context(|| format!("opening graph DB at {}", graph_dir.display()))?;

    let mut migrated: usize = 0;
    let mut skipped: usize = 0;

    // Migrate data CFs. All three graph types (EntityNode, RelationshipEdge,
    // EpisodicNode) are stored as opaque bincode blobs. We use the generic
    // bincode→postcard migration which doesn't care about the concrete type
    // at compile time — we just need to round-trip the bytes through
    // try_decode → encode. But try_decode needs a concrete type parameter.
    //
    // Since the graph CFs are typed:
    //   entities → EntityNode
    //   relationships, entity_edges → RelationshipEdge
    //   episodes → EpisodicNode
    // we dispatch per CF name.

    for cf_name in GRAPH_DATA_CFS {
        let cf = match db.cf_handle(cf_name) {
            Some(cf) => cf,
            None => continue,
        };

        let mut batch = WriteBatch::default();
        let mut batch_count: usize = 0;

        for item in db.iterator_cf(cf, IteratorMode::Start) {
            let (key, value) = item?;

            match *cf_name {
                "entities" => {
                    migrate_generic_record::<EntityNode>(
                        &db,
                        Some(cf),
                        &key,
                        &value,
                        dry_run,
                        &mut batch,
                        &mut batch_count,
                        &mut migrated,
                        &mut skipped,
                    )?;
                }
                "relationships" | "entity_edges" => {
                    migrate_generic_record::<RelationshipEdge>(
                        &db,
                        Some(cf),
                        &key,
                        &value,
                        dry_run,
                        &mut batch,
                        &mut batch_count,
                        &mut migrated,
                        &mut skipped,
                    )?;
                }
                "episodes" => {
                    migrate_generic_record::<EpisodicNode>(
                        &db,
                        Some(cf),
                        &key,
                        &value,
                        dry_run,
                        &mut batch,
                        &mut batch_count,
                        &mut migrated,
                        &mut skipped,
                    )?;
                }
                _ => {}
            }

            if batch_count >= BATCH_SIZE && !dry_run {
                db.write(std::mem::take(&mut batch))?;
                batch_count = 0;
            }
        }

        if batch_count > 0 && !dry_run {
            db.write(batch)?;
        }
    }

    eprintln!("  Graph DB: {migrated} migrated, {skipped} skipped");
    Ok((migrated, skipped))
}

// ---------------------------------------------------------------------------
// Shared DB migration (audit events)
// ---------------------------------------------------------------------------

fn migrate_shared_db(shared_dir: &Path, dry_run: bool) -> Result<(usize, usize)> {
    let mut opts = RocksOptions::default();
    opts.create_if_missing(false);
    opts.create_missing_column_families(true);

    // The shared DB has many CFs but only "audit" contains bincode data.
    // Others (todos, projects, prospective, feedback, files) use JSON.
    let shared_cfs = [
        "default",
        "audit",
        "todos",
        "projects",
        "todo_index",
        "prospective",
        "prospective_index",
        "files",
        "file_index",
        "feedback",
    ];
    let cfs: Vec<ColumnFamilyDescriptor> = shared_cfs
        .iter()
        .map(|name| ColumnFamilyDescriptor::new(*name, RocksOptions::default()))
        .collect();

    let db = DB::open_cf_descriptors(&opts, shared_dir, cfs)
        .with_context(|| format!("opening shared DB at {}", shared_dir.display()))?;

    let cf = match db.cf_handle("audit") {
        Some(cf) => cf,
        None => return Ok((0, 0)),
    };

    let mut migrated: usize = 0;
    let mut skipped: usize = 0;
    let mut batch = WriteBatch::default();
    let mut batch_count: usize = 0;

    for item in db.iterator_cf(cf, IteratorMode::Start) {
        let (key, value) = item?;

        migrate_generic_record::<AuditEvent>(
            &db,
            Some(cf),
            &key,
            &value,
            dry_run,
            &mut batch,
            &mut batch_count,
            &mut migrated,
            &mut skipped,
        )?;

        if batch_count >= BATCH_SIZE && !dry_run {
            db.write(std::mem::take(&mut batch))?;
            batch_count = 0;
        }
    }

    if batch_count > 0 && !dry_run {
        db.write(batch)?;
    }

    eprintln!("  Shared DB: {migrated} audit events migrated, {skipped} skipped");
    Ok((migrated, skipped))
}

// ---------------------------------------------------------------------------
// Generic record migration helper
// ---------------------------------------------------------------------------

/// Migrate a single record from legacy bincode to tagged postcard.
///
/// If the record already has the postcard format tag, it is skipped.
/// Otherwise it is decoded via `try_decode` (postcard-first, bincode fallback)
/// and re-encoded as tagged postcard.
#[allow(clippy::too_many_arguments)]
fn migrate_generic_record<T>(
    _db: &DB,
    cf: Option<&rocksdb::ColumnFamily>,
    key: &[u8],
    value: &[u8],
    dry_run: bool,
    batch: &mut WriteBatch,
    batch_count: &mut usize,
    migrated: &mut usize,
    skipped: &mut usize,
) -> Result<()>
where
    T: serde::de::DeserializeOwned + serde::Serialize,
{
    // Already in postcard format — skip
    if serialization::has_format_tag_pub(value) {
        *skipped += 1;
        return Ok(());
    }

    // Decode with legacy bincode fallback
    let (val, _needs_migration): (T, bool) =
        serialization::try_decode(value).with_context(|| {
            format!(
                "decoding record (key len={}, value len={})",
                key.len(),
                value.len()
            )
        })?;

    if !dry_run {
        let new_value = serialization::encode(&val)?;
        if let Some(cf) = cf {
            batch.put_cf(cf, key, &new_value);
        } else {
            batch.put(key, &new_value);
        }
        *batch_count += 1;
    }

    *migrated += 1;
    Ok(())
}