void-audit-tui 0.0.4

Audit viewer TUI for void — integrity and encryption inspection
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
//! Void repository backend for audit TUI.
//!
//! Provides object enumeration, indexing, and audit using `VoidContext`.

use std::collections::VecDeque;
use std::fs;

use thiserror::Error;
use void_core::{
    cid as void_cid,
    cid::VoidCid,
    collab::WrappedKey,
    crypto::{
        reader::collect_ancestor_content_keys_vault,
        EncryptedShard,
    },
    metadata::{Commit, MetadataBundle},
    support::ToVoidCid,
    store::{FsStore, ObjectStoreExt},
    VoidContext,
};

/// Error type for void backend operations.
#[derive(Debug, Error)]
pub enum VoidBackendError {
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    #[error("void error: {0}")]
    Void(#[from] void_core::VoidError),
}

/// Result type for void backend operations.
pub type Result<T> = std::result::Result<T, VoidBackendError>;

/// Type of a void object.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ObjectType {
    Commit,
    Metadata,
    Manifest,
    RepoManifest,
    Shard,
    Unknown,
}

impl ObjectType {
    pub fn as_str(&self) -> &'static str {
        match self {
            ObjectType::Commit => "commit",
            ObjectType::Metadata => "metadata",
            ObjectType::Manifest => "manifest",
            ObjectType::RepoManifest => "repo-manifest",
            ObjectType::Shard => "shard",
            ObjectType::Unknown => "unknown",
        }
    }
}

/// Encryption format, derived from the AAD used during encryption.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
    CommitV1,
    ShardV1,
    MetadataV1,
    ManifestV1,
    RepoManifestV1,
    Unknown,
}

impl Format {
    pub fn as_str(&self) -> &'static str {
        match self {
            Format::CommitV1 => "commit/v1",
            Format::ShardV1 => "shard/v1",
            Format::MetadataV1 => "metadata/v1",
            Format::ManifestV1 => "manifest/v1",
            Format::RepoManifestV1 => "repo-manifest/v1",
            Format::Unknown => "unknown",
        }
    }

    /// Whether this is a recognized (non-unknown) format.
    pub fn is_known(&self) -> bool {
        !matches!(self, Format::Unknown)
    }
}

/// Information about a repository object.
#[derive(Debug, Clone)]
pub struct ObjectInfo {
    pub cid: String,
    pub object_type: ObjectType,
    pub format: Format,
    pub encrypted_size: usize,
}

impl ObjectInfo {
    /// Return first 12 chars of CID for display.
    pub fn short_cid(&self) -> &str {
        &self.cid[..self.cid.len().min(12)]
    }
}

/// Detailed audit result for a commit.
#[derive(Debug, Clone)]
pub struct CommitAudit {
    pub message: String,
    pub timestamp: u64,
    pub parent_cid: Option<String>,
    pub metadata_cid: String,
    pub is_signed: bool,
    pub author: Option<String>,
}

/// Detailed audit result for metadata.
#[derive(Debug, Clone)]
pub struct MetadataAudit {
    pub version: u32,
    pub range_count: usize,
    pub shards: Vec<ShardRef>,
    pub parent_commit: Option<ParentCommitInfo>,
}

/// Reference to a shard.
#[derive(Debug, Clone)]
pub struct ShardRef {
    pub shard_id: u32,
    pub cid: String,
}

/// Detailed audit result for a shard.
#[derive(Debug, Clone)]
pub struct ShardAudit {
    pub version: u32,
    pub entry_count: u32,
    pub dir_count: u32,
    pub body_compressed: u32,
    pub body_decompressed: u32,
    pub entries: Vec<ShardEntry>,
    pub parent_commit: Option<ParentCommitInfo>,
}

/// A file entry in a shard.
#[derive(Debug, Clone)]
pub struct ShardEntry {
    pub path: String,
    pub size: u64,
    pub lines: u32,
}

/// Parent commit information.
#[derive(Debug, Clone)]
pub struct ParentCommitInfo {
    pub cid: String,
    pub message: String,
    pub timestamp: u64,
}

/// A file entry in the tree manifest.
#[derive(Debug, Clone)]
pub struct ManifestFileEntry {
    pub path: String,
    pub size: u64,
    pub lines: u32,
    pub shard_index: u32,
}

/// A shard summary in the tree manifest.
#[derive(Debug, Clone)]
pub struct ManifestShardInfo {
    pub cid: String,
    pub size_compressed: u64,
    pub size_decompressed: u64,
    pub file_count: usize,
}

/// Detailed audit result for a tree manifest.
#[derive(Debug, Clone)]
pub struct ManifestAudit {
    pub file_count: u64,
    pub total_bytes: u64,
    pub shard_count: usize,
    pub files: Vec<ManifestFileEntry>,
    pub shards: Vec<ManifestShardInfo>,
    pub parent_commit: Option<ParentCommitInfo>,
}

/// Detailed audit result for a repo manifest (contributors.json).
#[derive(Debug, Clone)]
pub struct RepoManifestAudit {
    pub encrypted_size: usize,
    pub parent_commit: Option<ParentCommitInfo>,
}

/// Full audit result for any object type.
#[derive(Debug, Clone)]
pub enum AuditResult {
    Commit(CommitAudit),
    Metadata(MetadataAudit),
    Manifest(ManifestAudit),
    RepoManifest(RepoManifestAudit),
    Shard(ShardAudit),
    Error(String),
}

/// Cached info about a commit's referenced objects.
#[derive(Debug, Clone)]
pub struct CommitIndex {
    pub commit_cid: String,
    pub message: String,
    pub timestamp: u64,
    pub metadata_cid: String,
    pub shard_cids: Vec<(String, Option<WrappedKey>)>,
}

/// What type of object an indexed CID refers to.
pub enum IndexedObject<'a> {
    Commit,
    Metadata(&'a CommitIndex),
    Manifest(&'a CommitIndex),
    RepoManifest(&'a CommitIndex),
    Shard(&'a CommitIndex, Option<&'a WrappedKey>),
    Unknown,
}

/// Pre-built index mapping object CIDs to their parent commits.
#[derive(Debug, Default)]
pub struct ObjectIndex {
    pub metadata_to_commit: rustc_hash::FxHashMap<String, CommitIndex>,
    pub manifest_to_commit: rustc_hash::FxHashMap<String, CommitIndex>,
    pub repo_manifest_to_commit: rustc_hash::FxHashMap<String, CommitIndex>,
    pub shard_to_commit: rustc_hash::FxHashMap<String, (CommitIndex, Option<WrappedKey>)>,
    pub commit_cids: rustc_hash::FxHashSet<String>,
}

impl ObjectIndex {
    /// Look up a CID and return its known type with associated context.
    pub fn lookup(&self, cid_str: &str) -> IndexedObject<'_> {
        if self.commit_cids.contains(cid_str) {
            return IndexedObject::Commit;
        }
        if let Some(idx) = self.metadata_to_commit.get(cid_str) {
            return IndexedObject::Metadata(idx);
        }
        if let Some(idx) = self.manifest_to_commit.get(cid_str) {
            return IndexedObject::Manifest(idx);
        }
        if let Some(idx) = self.repo_manifest_to_commit.get(cid_str) {
            return IndexedObject::RepoManifest(idx);
        }
        if let Some((idx, wrapped_key)) = self.shard_to_commit.get(cid_str) {
            return IndexedObject::Shard(idx, wrapped_key.as_ref());
        }
        IndexedObject::Unknown
    }
}

// ---------------------------------------------------------------------------
// Index building
// ---------------------------------------------------------------------------

/// Build an index by walking commit history once using BFS.
///
/// Starts from HEAD and all branch heads, correctly handling merge commits.
pub fn build_index(ctx: &VoidContext, store: &FsStore, max_commits: usize) -> Result<ObjectIndex> {
    let mut index = ObjectIndex::default();
    let mut visited: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
    let mut queue: VecDeque<VoidCid> = VecDeque::new();

    // Start from HEAD
    if let Ok(Some(head_cid)) = ctx.resolve_head() {
        if let Ok(cid) = void_cid::from_bytes(head_cid.as_bytes()) {
            queue.push_back(cid);
        }
    }

    // Also add all branch heads for complete coverage
    let refs_dir = ctx.paths.void_dir.join("refs/heads");
    if refs_dir.exists() {
        if let Ok(entries) = fs::read_dir(&refs_dir) {
            for entry in entries.flatten() {
                if let Ok(content) = fs::read_to_string(entry.path()) {
                    if let Ok(branch_cid) = void_cid::parse(content.trim()) {
                        queue.push_back(branch_cid);
                    }
                }
            }
        }
    }

    let mut commits_processed = 0;

    while let Some(commit_cid) = queue.pop_front() {
        let commit_cid_str = commit_cid.to_string();

        if visited.contains(&commit_cid_str) {
            continue;
        }
        visited.insert(commit_cid_str.clone());

        if commits_processed >= max_commits {
            continue;
        }
        commits_processed += 1;

        index.commit_cids.insert(commit_cid_str.clone());

        // Load commit + metadata in one call
        let (commit, bundle, _reader) = match ctx.load_commit_with_metadata(store, &commit_cid) {
            Ok(r) => r,
            Err(_) => {
                // Still need to try loading just the commit to queue parents
                if let Ok((commit, _)) = ctx.load_commit(store, &commit_cid) {
                    queue_parents(&commit, &mut queue);
                }
                continue;
            }
        };

        let metadata_cid_str = commit.metadata_bundle.to_void_cid()
            .map(|c| c.to_string())
            .unwrap_or_default();

        // Collect shard CIDs from metadata
        let mut shard_cids = Vec::new();
        for range in &bundle.shard_map.ranges {
            if let Some(ref shard_cid_typed) = range.cid {
                if let Ok(shard_cid) = void_cid::from_bytes(shard_cid_typed.as_bytes()) {
                    shard_cids.push((shard_cid.to_string(), range.wrapped_key.clone()));
                }
            }
        }

        let commit_index = CommitIndex {
            commit_cid: commit_cid_str,
            message: commit.message.clone(),
            timestamp: commit.timestamp,
            metadata_cid: metadata_cid_str.clone(),
            shard_cids: shard_cids.clone(),
        };

        index.metadata_to_commit.insert(metadata_cid_str, commit_index.clone());

        for (shard_cid_str, wrapped_key) in shard_cids {
            index.shard_to_commit.insert(shard_cid_str, (commit_index.clone(), wrapped_key));
        }

        if let Some(ref manifest_cid_bytes) = commit.manifest_cid {
            if let Ok(manifest_cid) = manifest_cid_bytes.to_void_cid() {
                index.manifest_to_commit.insert(manifest_cid.to_string(), commit_index.clone());
            }
        }

        if let Some(ref rm_cid_bytes) = commit.repo_manifest_cid {
            if let Ok(rm_cid) = rm_cid_bytes.to_void_cid() {
                index.repo_manifest_to_commit.insert(rm_cid.to_string(), commit_index.clone());
            }
        }

        queue_parents(&commit, &mut queue);
    }

    Ok(index)
}

// ---------------------------------------------------------------------------
// Object listing and categorization
// ---------------------------------------------------------------------------

/// List all object CIDs in the repository.
pub fn list_all_objects(ctx: &VoidContext) -> Vec<String> {
    let objects_dir = ctx.paths.void_dir.join("objects");
    let mut cids = Vec::new();

    let Ok(prefixes) = fs::read_dir(&objects_dir) else {
        return cids;
    };

    for prefix_entry in prefixes.flatten() {
        let prefix_path = prefix_entry.path();
        if !prefix_path.is_dir() {
            continue;
        }

        let Ok(objects) = fs::read_dir(&prefix_path) else {
            continue;
        };

        for obj_entry in objects.flatten() {
            if let Some(name) = obj_entry.file_name().to_str() {
                if !name.ends_with(".tmp") {
                    cids.push(name.to_string());
                }
            }
        }
    }

    cids.sort();
    cids
}

/// Categorize an object using the pre-built index.
pub fn categorize_object(store: &FsStore, index: &ObjectIndex, cid_str: &str) -> ObjectInfo {
    let cid = match void_cid::parse(cid_str) {
        Ok(c) => c,
        Err(_) => {
            return ObjectInfo {
                cid: cid_str.to_string(),
                object_type: ObjectType::Unknown,
                format: Format::Unknown,
                encrypted_size: 0,
            };
        }
    };

    let object_type = match index.lookup(cid_str) {
        IndexedObject::Commit => ObjectType::Commit,
        IndexedObject::Metadata(_) => ObjectType::Metadata,
        IndexedObject::Manifest(_) => ObjectType::Manifest,
        IndexedObject::RepoManifest(_) => ObjectType::RepoManifest,
        IndexedObject::Shard(_, _) => ObjectType::Shard,
        IndexedObject::Unknown => ObjectType::Unknown,
    };

    let encrypted_size = store.get_blob::<EncryptedShard>(&cid)
        .map(|b| b.as_bytes().len())
        .unwrap_or(0);

    ObjectInfo {
        cid: cid_str.to_string(),
        object_type,
        format: Format::Unknown,
        encrypted_size,
    }
}

// ---------------------------------------------------------------------------
// Audit functions
// ---------------------------------------------------------------------------

/// Audit an object using the pre-built index.
pub fn audit_object_indexed(
    ctx: &VoidContext,
    store: &FsStore,
    index: &ObjectIndex,
    cid_str: &str,
) -> AuditResult {
    let cid = match void_cid::parse(cid_str) {
        Ok(c) => c,
        Err(e) => return AuditResult::Error(format!("Invalid CID: {e}")),
    };

    match index.lookup(cid_str) {
        IndexedObject::Commit => {
            match ctx.load_commit(store, &cid) {
                Ok((commit, _)) => audit_commit(&commit),
                Err(e) => AuditResult::Error(format!("Failed to decrypt commit: {e}")),
            }
        }
        IndexedObject::Metadata(commit_idx) => {
            audit_metadata_indexed(ctx, store, commit_idx)
        }
        IndexedObject::Manifest(commit_idx) => {
            audit_manifest_indexed(ctx, store, commit_idx)
        }
        IndexedObject::RepoManifest(commit_idx) => {
            let size = store.get_blob::<EncryptedShard>(&cid)
                .map(|b| b.as_bytes().len())
                .unwrap_or(0);
            AuditResult::RepoManifest(RepoManifestAudit {
                encrypted_size: size,
                parent_commit: Some(parent_info(commit_idx)),
            })
        }
        IndexedObject::Shard(commit_idx, wrapped_key) => {
            let encrypted: EncryptedShard = match store.get_blob(&cid) {
                Ok(d) => d,
                Err(e) => return AuditResult::Error(format!("Object not found: {e}")),
            };
            audit_shard_idxed(ctx, store, &encrypted, wrapped_key, commit_idx, &cid)
        }
        IndexedObject::Unknown => {
            AuditResult::Error("Object not found in commit history - may be orphaned".to_string())
        }
    }
}

/// Audit a commit object.
fn audit_commit(commit: &Commit) -> AuditResult {
    let parent_cid = commit.parents.first().and_then(|p| {
        p.to_void_cid().map(|c| c.to_string()).ok()
    });

    let metadata_cid = commit.metadata_bundle.to_void_cid()
        .map(|c| c.to_string())
        .unwrap_or_else(|_| hex::encode(commit.metadata_bundle.as_bytes()));

    AuditResult::Commit(CommitAudit {
        message: commit.message.clone(),
        timestamp: commit.timestamp,
        parent_cid,
        metadata_cid,
        is_signed: commit.is_signed(),
        author: commit.author.map(|a| a.to_hex()),
    })
}

/// Audit metadata using indexed commit info.
fn audit_metadata_indexed(
    ctx: &VoidContext,
    store: &FsStore,
    commit_idx: &CommitIndex,
) -> AuditResult {
    let commit_cid = match void_cid::parse(&commit_idx.commit_cid) {
        Ok(c) => c,
        Err(e) => return AuditResult::Error(format!("Invalid commit CID: {e}")),
    };

    let (_, metadata, _) = match ctx.load_commit_with_metadata(store, &commit_cid) {
        Ok(r) => r,
        Err(e) => return AuditResult::Error(format!("Failed to load commit+metadata: {e}")),
    };

    let shards = extract_shard_refs(&metadata);

    AuditResult::Metadata(MetadataAudit {
        version: metadata.version,
        range_count: metadata.shard_map.ranges.len(),
        shards,
        parent_commit: Some(parent_info(commit_idx)),
    })
}

/// Audit tree manifest using indexed commit info.
fn audit_manifest_indexed(
    ctx: &VoidContext,
    store: &FsStore,
    commit_idx: &CommitIndex,
) -> AuditResult {
    let commit_cid = match void_cid::parse(&commit_idx.commit_cid) {
        Ok(c) => c,
        Err(e) => return AuditResult::Error(format!("Invalid commit CID: {e}")),
    };

    let (commit, reader) = match ctx.load_commit(store, &commit_cid) {
        Ok(r) => r,
        Err(e) => return AuditResult::Error(format!("Failed to load commit: {e}")),
    };

    let manifest = match ctx.load_manifest(store, &commit, &reader) {
        Ok(Some(m)) => m,
        Ok(None) => return AuditResult::Error("Commit has no manifest".to_string()),
        Err(e) => return AuditResult::Error(format!("Failed to load manifest: {e}")),
    };

    // Extract file entries
    let files: Vec<ManifestFileEntry> = manifest.iter()
        .filter_map(|r| r.ok())
        .map(|e| ManifestFileEntry {
            path: e.path.clone(),
            size: e.size,
            lines: e.lines,
            shard_index: e.shard_index,
        })
        .collect();

    // Extract shard info with file counts
    let groups = manifest.entries_by_shard().unwrap_or_default();
    let shards: Vec<ManifestShardInfo> = manifest.shards().iter().enumerate()
        .map(|(i, s)| {
            let cid_str = void_cid::from_bytes(s.cid.as_bytes())
                .map(|c| c.to_string())
                .unwrap_or_else(|_| hex::encode(s.cid.as_bytes()));
            ManifestShardInfo {
                cid: cid_str,
                size_compressed: s.size_compressed,
                size_decompressed: s.size_decompressed,
                file_count: groups.get(i).map(|g| g.len()).unwrap_or(0),
            }
        })
        .collect();

    AuditResult::Manifest(ManifestAudit {
        file_count: manifest.total_files(),
        total_bytes: manifest.total_bytes(),
        shard_count: manifest.shards().len(),
        files,
        shards,
        parent_commit: Some(parent_info(commit_idx)),
    })
}

/// Audit shard using indexed commit info and TreeManifest.
fn audit_shard_idxed(
    ctx: &VoidContext,
    store: &FsStore,
    encrypted: &EncryptedShard,
    wrapped_key: Option<&WrappedKey>,
    commit_idx: &CommitIndex,
    shard_cid: &VoidCid,
) -> AuditResult {
    let commit_cid = match void_cid::parse(&commit_idx.commit_cid) {
        Ok(c) => c,
        Err(e) => return AuditResult::Error(format!("Invalid commit CID: {e}")),
    };

    let (commit, reader) = match ctx.load_commit(store, &commit_cid) {
        Ok(r) => r,
        Err(e) => return AuditResult::Error(format!("Failed to load commit: {e}")),
    };

    // Load manifest to get file entries for this shard
    let manifest = match ctx.load_manifest(store, &commit, &reader) {
        Ok(Some(m)) => m,
        Ok(None) => return AuditResult::Error("Commit has no manifest".to_string()),
        Err(e) => return AuditResult::Error(format!("Failed to load manifest: {e}")),
    };

    // Find shard index by matching CID against manifest shards
    let shard_cid_bytes = shard_cid.to_bytes();
    let shard_idx = manifest.shards().iter().position(|s| s.cid.as_bytes() == &shard_cid_bytes);

    let groups = match manifest.entries_by_shard() {
        Ok(g) => g,
        Err(e) => return AuditResult::Error(format!("Failed to group entries: {e}")),
    };

    let manifest_entries = shard_idx
        .and_then(|idx| groups.get(idx))
        .cloned()
        .unwrap_or_default();

    // Decrypt and decompress to validate shard integrity
    let ancestor_keys = collect_ancestor_content_keys_vault(&ctx.crypto.vault, store, &commit);
    let decrypted = match reader.decrypt_shard(encrypted, wrapped_key, &ancestor_keys) {
        Ok(d) => d,
        Err(e) => return AuditResult::Error(format!("Failed to decrypt shard: {e}")),
    };

    let body = match decrypted.decompress() {
        Ok(b) => b,
        Err(e) => return AuditResult::Error(format!("Invalid shard: {e}")),
    };

    let shard_ref = shard_idx.and_then(|idx| manifest.shards().get(idx));

    let entries: Vec<ShardEntry> = manifest_entries
        .iter()
        .map(|e| ShardEntry {
            path: e.path.clone(),
            size: e.length,
            lines: e.lines,
        })
        .collect();

    AuditResult::Shard(ShardAudit {
        version: 0, // headerless format
        entry_count: entries.len() as u32,
        dir_count: 0,
        body_compressed: shard_ref.map(|s| s.size_compressed as u32).unwrap_or(0),
        body_decompressed: body.len() as u32,
        entries,
        parent_commit: Some(parent_info(commit_idx)),
    })
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Queue all parent CIDs from a commit into the BFS queue.
fn queue_parents(commit: &Commit, queue: &mut VecDeque<VoidCid>) {
    for parent_bytes in &commit.parents {
        if !parent_bytes.as_bytes().is_empty() {
            if let Ok(parent_cid) = parent_bytes.to_void_cid() {
                queue.push_back(parent_cid);
            }
        }
    }
}

/// Build a ParentCommitInfo from a CommitIndex.
fn parent_info(idx: &CommitIndex) -> ParentCommitInfo {
    ParentCommitInfo {
        cid: idx.commit_cid.clone(),
        message: idx.message.clone(),
        timestamp: idx.timestamp,
    }
}

/// Extract shard references from a metadata bundle.
fn extract_shard_refs(bundle: &MetadataBundle) -> Vec<ShardRef> {
    bundle
        .shard_map
        .ranges
        .iter()
        .filter_map(|r| {
            r.cid.as_ref().map(|shard_cid_typed| {
                let cid_str = void_cid::from_bytes(shard_cid_typed.as_bytes())
                    .map(|c| c.to_string())
                    .unwrap_or_else(|_| hex::encode(shard_cid_typed.as_bytes()));
                ShardRef {
                    shard_id: r.shard_id as u32,
                    cid: cid_str,
                }
            })
        })
        .collect()
}