void-cli 0.0.4

CLI for void — anonymous encrypted source control
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
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
//! Clone a void repository from IPFS.
//!
//! Fetches a commit and its objects from IPFS, creates a new repository,
//! and checks out the working tree.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use serde::Serialize;
use void_core::cid;
use void_core::support::ToVoidCid;
use void_core::config::{Config, CoreConfig};
use void_core::pipeline::{clone_repo, CloneMode, CloneOptions, CloneResult};
use void_core::store::FsStore;
use void_core::workspace::checkout::{checkout_tree, CheckoutOptions};

use camino::Utf8PathBuf;

use void_core::crypto::{CommitReader, ContentKey, EncryptedCommit, EncryptedMetadata, EncryptedRepoManifest, EncryptedShard, KeyVault};
use void_core::metadata::CommitStats;
use void_core::store::{RemoteStore, ObjectStoreExt};

use crate::context::void_err_to_cli;
use crate::observer::ProgressObserver;
use crate::output::{run_command, CliError, CliOptions};

/// Command-line arguments for clone.
#[derive(Debug)]
pub struct CloneArgs {
    /// Source: commit CID or registry name.
    pub source: String,
    /// Repository encryption key (64 hex chars = 32 bytes).
    /// Required if source is a CID, optional if resolved from registry.
    pub key: Option<String>,
    /// Scoped content key for single-commit clone (64 hex chars = 32 bytes).
    /// Used with published repos — decrypts only the target commit's objects.
    pub content_key: Option<String>,
    /// Target directory to clone into (positional, default: current directory).
    pub path: Option<PathBuf>,
    /// Backend type: "kubo" or "gateway".
    pub backend: Option<String>,
    /// Kubo API URL.
    pub kubo_url: String,
    /// Gateway URL (required if backend is gateway).
    pub gateway_url: Option<String>,
    /// Request timeout in milliseconds.
    pub timeout_ms: u64,
    /// Clone mode: "depth1", "full", or "lazy".
    pub mode: String,
    /// Skip interactive prompts (use defaults).
    pub yes: bool,
    /// Named remote to resolve repo name from (uses daemon registry).
    pub remote: Option<String>,
}

/// JSON output for the clone command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloneOutput {
    /// Directory where repository was cloned.
    pub path: String,
    /// The cloned commit CID.
    pub commit: String,
    /// The metadata bundle CID.
    pub metadata: String,
    /// Clone mode used.
    pub mode: String,
    /// Number of shards fetched.
    pub shards_fetched: usize,
    /// Total number of shards in the commit.
    pub shards_total: usize,
    /// Number of files extracted (only present if mode=full).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub files_extracted: Option<usize>,
    /// Source label (if cloned from registry name).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

/// Run the clone command.
///
/// # Arguments
///
/// * `cwd` - Current working directory
/// * `args` - Clone arguments
/// * `opts` - CLI options
///
/// # Operations
///
/// 1. Parse the encryption key from hex
/// 2. Create .void directory structure
/// 3. Create manifest with ECIES-wrapped key for the cloner
/// 4. Clone the repository from IPFS
/// 5. Save config.json with repo_secret
/// 6. Checkout the working tree
pub fn run(cwd: &Path, args: CloneArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("clone", opts, |ctx| {
        // Resolve source: CID, remote repo name, or local registry name
        let is_cid_source = cid::parse(&args.source).is_ok();

        // registry_info holds (repo_id, repo_name) when resolved from registry
        let (commit_cid, source_label, resolved_key, registry_info): (
            String,
            Option<String>,
            Option<[u8; 32]>,
            Option<(String, String)>,
        ) = if is_cid_source {
            (args.source.clone(), None, None, None)
        } else if let Some(ref remote_name) = args.remote {
            // Resolve repo name from remote daemon registry.
            ctx.progress(format!("Resolving '{}' from remote '{}'...", args.source, remote_name));
            let resolved_remote = crate::remotes::resolve_remote(remote_name, None)
                .map_err(|e| CliError::internal(format!("remote '{}': {}", remote_name, e)))?;

            let branch = "trunk".to_string(); // TODO: support --branch flag

            let rt = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .map_err(|e| CliError::internal(format!("runtime: {e}")))?;

            let cid_str = rt.block_on(async {
                let peer_id: libp2p::PeerId = resolved_remote.peer_id.parse()
                    .map_err(|e| format!("invalid peer_id: {e}"))?;
                let addr: libp2p::Multiaddr = resolved_remote.addr.parse()
                    .map_err(|e| format!("invalid addr: {e}"))?;

                let client = void_daemon::DaemonClient::connect(addr, peer_id).await
                    .map_err(|e| format!("connect to remote: {e}"))?;

                // Authenticate to access the repo registry.
                let signing_key = crate::context::load_signing_key()
                    .map_err(|e| format!("load identity: {e}"))?;
                let dalek_key = ed25519_dalek::SigningKey::from_bytes(signing_key.as_bytes());
                client.authenticate(&dalek_key).await
                    .map_err(|e| format!("auth: {e}"))?;

                // Query HEAD for the repo.
                client.get_head(&args.source, &branch).await
                    .map_err(|e| format!("get_head: {e}"))
            }).map_err(|e| CliError::internal(format!("remote resolve failed: {e}")))?;

            ctx.info(format!("Resolved '{}' → {}", args.source, &cid_str[..12.min(cid_str.len())]));
            (cid_str, Some(format!("{}@{}", args.source, remote_name)), None, None)
        } else {
            // Try local registry lookup
            let (cid_str, resolved_key, repo_id, repo_name) =
                resolve_clone_registry_name_with_record(&args.source)?;
            (
                cid_str,
                Some(args.source.clone()),
                Some(resolved_key),
                Some((repo_id, repo_name)),
            )
        };

        // Parse scoped content key if provided (single-commit read-only clone)
        let scoped_content_key: Option<ContentKey> = if let Some(ref ck_hex) = args.content_key {
            Some(ContentKey::from_hex(ck_hex)
                .map_err(|e| CliError::invalid_args(format!("invalid content-key: {}", e)))?)
        } else {
            None
        };

        // Parse the encryption key: registry-resolved or hex key.
        // (must happen before target dir resolution so probe can decrypt)
        // When --content-key is provided, the full repo key is optional.
        let key: Option<[u8; 32]> = if let Some(ik) = resolved_key {
            Some(ik)
        } else {
            match &args.key {
                Some(k) => Some(parse_hex_key(k)?),
                None => {
                    if scoped_content_key.is_some() {
                        None // content-key clone doesn't need a full repo key
                    } else {
                        return Err(CliError::invalid_args(
                            "--key is required when cloning from a CID (or use --content-key for scoped access)",
                        ));
                    }
                }
            }
        };

        // Parse clone mode
        let mode = parse_mode(&args.mode)?;

        // Resolve backend (daemon, kubo, or gateway)
        let timeout = Duration::from_millis(args.timeout_ms);
        let void_home = dirs::home_dir().map(|h| h.join(".void"));
        let resolved = crate::backend::resolve_backend(
            args.backend.as_deref(),
            &args.kubo_url,
            &args.gateway_url,
            void_home.as_deref(),
            timeout,
        )?;
        let backend = resolved.ipfs_backend.clone();
        let daemon_remote = Some(resolved.remote);

        // Determine target directory (derive from project/repo name when no --path)
        let target_dir = match &args.path {
            Some(dir) => {
                if dir.is_absolute() {
                    dir.clone()
                } else {
                    cwd.join(dir)
                }
            }
            None => {
                if let Some((_, ref repo_name)) = registry_info {
                    // Registry clone: use repo name as directory
                    cwd.join(repo_name)
                } else if let Some(ref label) = source_label {
                    let parts: Vec<&str> = label.split('/').collect();
                    if parts.len() >= 2 {
                        cwd.join(parts[1])
                    } else {
                        cwd.to_path_buf()
                    }
                } else {
                    // Bare CID: probe commit for repo name
                    ctx.progress("Probing commit...");
                    let probe_vault = if let Some(ref ck) = scoped_content_key {
                        KeyVault::from_content_key(*ck)
                    } else if let Some(k) = key {
                        KeyVault::new(k)
                            .map_err(|e| CliError::internal(format!("failed to initialize encryption: {e}")))?
                    } else {
                        return Err(CliError::invalid_args("--key or --content-key is required when cloning from a CID"));
                    };
                    let (repo_name, message, stats) =
                        probe_commit(&commit_cid, &probe_vault, daemon_remote.as_ref().unwrap().as_ref())?;

                    // Display probe results in human mode
                    if !ctx.use_json() {
                        let short_cid = if commit_cid.len() > 12 {
                            &commit_cid[..12]
                        } else {
                            &commit_cid
                        };
                        ctx.info(format!("  Commit   {}...", short_cid));
                        ctx.info(format!("  Message  {}", message));
                        if let Some(ref s) = stats {
                            ctx.info(format!(
                                "  Files    {} files ({})",
                                s.total_files,
                                format_bytes(s.total_bytes)
                            ));
                        }
                        if let Some(ref name) = repo_name {
                            ctx.info(format!("  Repo     {}", name));
                        }
                        eprintln!(); // blank line before prompt
                    }

                    let non_interactive = args.yes || ctx.use_json();

                    if non_interactive {
                        // --yes or --json: use repo name or error
                        match repo_name {
                            Some(name) => cwd.join(&name),
                            None => {
                                return Err(CliError::invalid_args(
                                    "could not determine repo name; use --path to specify target directory",
                                ))
                            }
                        }
                    } else {
                        // Interactive: prompt with repo_name as default
                        let dir_name: String = match repo_name {
                            Some(ref default) => dialoguer::Input::new()
                                .with_prompt("Clone directory?")
                                .default(default.clone())
                                .interact_text()
                                .map_err(|e| {
                                    CliError::internal(format!("prompt failed: {e}"))
                                })?,
                            None => dialoguer::Input::new()
                                .with_prompt("Clone directory")
                                .interact_text()
                                .map_err(|e| {
                                    CliError::internal(format!("prompt failed: {e}"))
                                })?,
                        };
                        cwd.join(&dir_name)
                    }
                }
            }
        };

        let void_dir = target_dir.join(".void");

        // Check if already initialized
        if void_dir.exists() {
            return Err(CliError::conflict(format!(
                "repository already exists at {}",
                void_dir.display()
            )));
        }

        // Human output: show what we're doing
        if !ctx.use_json() {
            ctx.info(format!("Cloning into '{}'...", target_dir.display()));
        }

        ctx.progress("Creating .void directory structure...");

        // Create .void directory structure
        crate::repo_init::create_void_dir_structure(&void_dir)?;

        // Create progress observer
        let observer: Arc<ProgressObserver> = if ctx.use_json() {
            Arc::new(ProgressObserver::new_hidden())
        } else {
            Arc::new(ProgressObserver::new("Fetching objects from IPFS..."))
        };

        // Clone the repository
        ctx.progress("Cloning repository from IPFS...");

        // Content-key clone uses scoped decryption (single commit, read-only).
        // Full-key clone uses the vault-based pipeline.
        let (clone_result, used_content_key_clone) = if let Some(ref ck) = scoped_content_key {
            if key.is_none() {
                // Pure content-key clone: force depth1 (no root key to walk history)
                let effective_mode = CloneMode::Depth1;
                let result = clone_repo_with_content_key(
                    &void_dir,
                    &commit_cid,
                    &ck,
                    daemon_remote.clone().unwrap(),
                    effective_mode,
                    Some(observer.clone()),
                )?;
                (result, true)
            } else {
                // Both keys provided: use full vault clone (content-key is ignored)
                let clone_opts = CloneOptions {
                    ctx: void_core::VoidContext::headless(
                        void_dir.clone(),
                        Arc::new(KeyVault::new(key.unwrap()).map_err(|e| {
                            CliError::internal(format!("failed to initialize encryption: {e}"))
                        })?),
                        0,
                    )
                    .map_err(void_err_to_cli)?,
                    commit_cid: commit_cid.clone(),
                    backend,
                    timeout,
                    mode,
                    observer: Some(observer.clone()),
                    remote: daemon_remote.clone(),
                };
                (clone_repo(clone_opts).map_err(void_err_to_cli)?, false)
            }
        } else {
            let clone_opts = CloneOptions {
                ctx: void_core::VoidContext::headless(
                    void_dir.clone(),
                    Arc::new(KeyVault::new(key.unwrap()).map_err(|e| {
                        CliError::internal(format!("failed to initialize encryption: {e}"))
                    })?),
                    0,
                )
                .map_err(void_err_to_cli)?,
                commit_cid: commit_cid.clone(),
                backend,
                timeout,
                mode,
                observer: Some(observer.clone()),
                remote: None,
            };
            (clone_repo(clone_opts).map_err(void_err_to_cli)?, false)
        };

        observer.finish();

        // Human output: show fetch progress
        if !ctx.use_json() {
            let short_cid = if commit_cid.len() > 12 {
                &commit_cid[..12]
            } else {
                &commit_cid
            };
            if let Some(ref source) = source_label {
                ctx.info(format!("Fetched commit {}... from {}", short_cid, source));
            } else {
                ctx.info(format!("Fetched commit {}...", short_cid));
            }
            ctx.info(format!(
                "Fetched {}/{} shards (mode: {})",
                clone_result.shards_fetched,
                clone_result.shards_total,
                mode_to_string(clone_result.mode)
            ));
        }

        // Save config with repo_secret (and identity if from registry or manifest)
        ctx.progress("Saving configuration...");
        let (cfg_repo_id, cfg_repo_name) = match &registry_info {
            Some((id, name)) => (Some(id.to_string()), Some(name.to_string())),
            None => {
                // Fall back to committed manifest identity (collab repos)
                if clone_result.repo_manifest_cid.is_some() {
                    let manifest = void_core::collab::manifest::load_manifest(&void_dir)
                        .ok()
                        .flatten();
                    (
                        manifest.as_ref().and_then(|m| m.repo_id.clone()),
                        manifest.as_ref().and_then(|m| m.repo_name.clone()),
                    )
                } else {
                    (None, None)
                }
            }
        };
        save_config(
            &void_dir,
            &clone_result,
            cfg_repo_id.as_deref(),
            cfg_repo_name.as_deref(),
        )?;

        // Ensure the cloner has an ECIES-wrapped key in the manifest.
        // If the cloned repo already has a manifest (from the source), add the
        // cloner's wrapped key. Otherwise, create a new manifest with the cloner
        // as owner. Skip for content-key-only clones (no full repo key).
        if let Some(ref k) = key {
            ensure_cloner_manifest(&void_dir, k, ctx)?;
        }

        // Checkout the working tree (Depth1 and Full both fetch all shards)
        let mode_str = mode_to_string(clone_result.mode);
        let files_extracted = if clone_result.mode != CloneMode::Lazy && clone_result.mode != CloneMode::Virtual {
            ctx.progress("Checking out working tree...");
            let checkout_observer: Arc<ProgressObserver> = if ctx.use_json() {
                Arc::new(ProgressObserver::new_hidden())
            } else {
                Arc::new(ProgressObserver::new("Restoring files..."))
            };

            let checkout_vault = if used_content_key_clone {
                KeyVault::from_content_key(*scoped_content_key.as_ref().unwrap())
            } else {
                KeyVault::new(key.unwrap())
                    .map_err(|e| CliError::internal(format!("failed to initialize encryption: {e}")))?
            };
            let count = checkout_working_tree(
                &void_dir,
                &checkout_vault,
                &commit_cid,
                &target_dir,
                checkout_observer.clone(),
            )?;

            checkout_observer.finish();

            if !ctx.use_json() {
                ctx.info("Checked out working tree");
            }
            Some(count)
        } else {
            if !ctx.use_json() {
                ctx.info(format!(
                    "Cloned in {} mode (no working tree checkout). Use 'void unseal' to extract files.",
                    mode_str
                ));
            }
            None
        };

        // Register in local registry and set HEAD (best-effort).
        // Works for both registry clones and invite clones.
        let reg_identity: Option<(String, String)> = if let Some((ref id, ref name)) = registry_info
        {
            Some((id.clone(), name.clone()))
        } else {
            None
        };
        if let Some((ref repo_id, ref repo_name)) = reg_identity {
            if let Err(e) =
                crate::registry::register_repo(repo_id, repo_name, &target_dir, "clone", None)
            {
                ctx.warn(format!("Failed to register cloned repo in registry: {}", e));
            }
            if let Err(e) = crate::registry::update_head(repo_id, "trunk", &commit_cid) {
                ctx.warn(format!("Failed to update registry HEAD: {}", e));
            }
        }

        Ok(CloneOutput {
            path: target_dir.display().to_string(),
            commit: clone_result.commit_cid,
            metadata: clone_result.metadata_cid,
            mode: mode_str,
            shards_fetched: clone_result.shards_fetched,
            shards_total: clone_result.shards_total,
            files_extracted,
            source: source_label,
        })
    })
}

/// Parse a hex-encoded 32-byte key (test helper).
#[cfg(test)]
fn parse_key(hex_str: &str) -> Result<[u8; 32], CliError> {
    let hex_str = hex_str.trim();

    let bytes = hex::decode(hex_str)
        .map_err(|e| CliError::invalid_args(format!("invalid key hex: {}", e)))?;

    if bytes.len() != 32 {
        return Err(CliError::invalid_args(format!(
            "key must be 32 bytes (64 hex chars), got {} bytes",
            bytes.len()
        )));
    }

    let mut key = [0u8; 32];
    key.copy_from_slice(&bytes);
    Ok(key)
}

/// Clone a single commit using a scoped content key (no root key).
///
/// The content key can decrypt the target commit's metadata and shards but
/// cannot walk history (that requires the root key for envelope derivation).
/// The resulting repo is read-only until a full key is provided via `void key set`.
fn clone_repo_with_content_key(
    void_dir: &Path,
    commit_cid_str: &str,
    content_key: &ContentKey,
    remote: Arc<dyn RemoteStore>,
    mode: CloneMode,
    observer: Option<Arc<ProgressObserver>>,
) -> Result<CloneResult, CliError> {
    use void_core::metadata::MetadataBundle;
    let objects_dir = Utf8PathBuf::try_from(void_dir.join("objects"))
        .map_err(|e| CliError::internal(format!("invalid objects path: {}", e)))?;
    let store = FsStore::new(objects_dir).map_err(void_err_to_cli)?;

    // Fetch commit via typed RemoteStore (CID validation + integrity handled internally)
    let commit_cid_obj = cid::parse(commit_cid_str).map_err(void_err_to_cli)?;
    let commit_encrypted = EncryptedCommit::from_bytes(remote.fetch_raw(&commit_cid_obj).map_err(void_err_to_cli)?);
    if !store.exists(&commit_cid_obj).map_err(void_err_to_cli)? {
        store.put_blob(&commit_encrypted).map_err(void_err_to_cli)?;
    }

    // Decrypt commit via content-key vault (replaces hand-rolled VD01 envelope parsing)
    let vault = KeyVault::from_content_key(*content_key);
    let (commit_plaintext, reader) = CommitReader::open_with_vault(&vault, &commit_encrypted)
        .map_err(|e| CliError::encryption_error(format!("failed to decrypt commit: {e}")))?;
    let commit = commit_plaintext.parse().map_err(void_err_to_cli)?;

    // Fetch and store metadata via typed RemoteStore
    let metadata_cid = commit.metadata_bundle.to_void_cid().map_err(void_err_to_cli)?;
    let metadata_cid_str = metadata_cid.to_string();
    let metadata_encrypted = EncryptedMetadata::from_bytes(remote.fetch_raw(&metadata_cid).map_err(void_err_to_cli)?);
    if !store.exists(&metadata_cid).map_err(void_err_to_cli)? {
        store.put_blob(&metadata_encrypted).map_err(void_err_to_cli)?;
    }
    let metadata: MetadataBundle = reader.decrypt_metadata(&metadata_encrypted)
        .map_err(void_err_to_cli)?;

    // Fetch shards
    let mut fetched = 0usize;
    let mut total = 0usize;
    if mode != CloneMode::Lazy && mode != CloneMode::Virtual {
        for range in &metadata.shard_map.ranges {
            let cid_bytes = match range.cid.as_ref() {
                Some(c) => c,
                None => continue,
            };
            total += 1;
            let shard_cid = cid::from_bytes(cid_bytes.as_bytes()).map_err(void_err_to_cli)?;
            let shard_encrypted = EncryptedShard::from_bytes(remote.fetch_raw(&shard_cid).map_err(void_err_to_cli)?);
            if !store.exists(&shard_cid).map_err(void_err_to_cli)? {
                store.put_blob(&shard_encrypted).map_err(void_err_to_cli)?;
            }
            fetched += 1;
            if let Some(ref obs) = observer {
                obs.set_message(&format!("Fetched {}/{} shards", fetched, total));
            }
        }
    } else {
        total = metadata.shard_map.ranges.iter().filter(|r| r.cid.is_some()).count();
    }

    // Update HEAD
    let void_dir_utf8 = Utf8PathBuf::try_from(void_dir.to_path_buf())
        .map_err(|e| CliError::internal(format!("invalid void dir path: {}", e)))?;
    let commit_cid_bytes = cid::to_bytes(&commit_cid_obj);
    void_core::refs::write_branch(&void_dir_utf8, "trunk", &void_core::crypto::CommitCid::from_bytes(commit_cid_bytes))
        .map_err(void_err_to_cli)?;

    // Extract repo manifest if present
    let repo_manifest_cid_str = if let Some(ref rm_cid_bytes) = commit.repo_manifest_cid {
        let rm_cid = rm_cid_bytes.to_void_cid().map_err(void_err_to_cli)?;
        let rm_cid_str = rm_cid.to_string();
        match remote.fetch_raw(&rm_cid) {
            Ok(rm_bytes) => {
                let rm_blob = EncryptedRepoManifest::from_bytes(rm_bytes);
                if !store.exists(&rm_cid).map_err(void_err_to_cli)? {
                    store.put_blob(&rm_blob).map_err(void_err_to_cli)?;
                }
                match reader.decrypt_repo_manifest(&rm_blob) {
                    Ok(manifest) => {
                        if let Ok(json) = manifest.to_json() {
                            let _ = std::fs::write(void_dir.join("contributors.json"), &json);
                        }
                        Some(rm_cid_str)
                    }
                    Err(_) => None,
                }
            }
            Err(_) => None,
        }
    } else {
        None
    };

    Ok(CloneResult {
        commit_cid: commit_cid_str.to_string(),
        metadata_cid: metadata_cid_str,
        repo_secret: metadata.repo_secret,
        shards_fetched: fetched,
        shards_total: total,
        mode,
        repo_manifest_cid: repo_manifest_cid_str,
    })
}

/// Parse the clone mode string.
fn parse_mode(mode_str: &str) -> Result<CloneMode, CliError> {
    match mode_str.to_lowercase().as_str() {
        "depth1" => Ok(CloneMode::Depth1),
        "full" => Ok(CloneMode::Full),
        "lazy" => Ok(CloneMode::Lazy),
        "virtual" => Ok(CloneMode::Virtual),
        other => Err(CliError::invalid_args(format!(
            "invalid clone mode '{}': expected depth1, full, lazy, or virtual",
            other
        ))),
    }
}

/// Convert CloneMode to string for output.
fn mode_to_string(mode: CloneMode) -> String {
    match mode {
        CloneMode::Depth1 => "depth1".to_string(),
        CloneMode::Full => "full".to_string(),
        CloneMode::Lazy => "lazy".to_string(),
        CloneMode::Virtual => "virtual".to_string(),
    }
}

/// Probes a commit to extract repo metadata without a full clone.
///
/// Fetches at most 2 objects (commit + repo manifest). The IPFS node caches
/// these, so the subsequent `clone_repo()` re-fetch is effectively free.
///
/// Returns `(repo_name, commit_message, commit_stats)`.
fn probe_commit(
    commit_cid_str: &str,
    vault: &KeyVault,
    remote: &dyn RemoteStore,
) -> Result<(Option<String>, String, Option<CommitStats>), CliError> {
    let commit_cid = cid::parse(commit_cid_str).map_err(void_err_to_cli)?;

    let commit_encrypted = EncryptedCommit::from_bytes(remote.fetch_raw(&commit_cid).map_err(void_err_to_cli)?);
    let (commit_bytes, reader) =
        CommitReader::open_with_vault(vault, &commit_encrypted).map_err(void_err_to_cli)?;
    let commit = commit_bytes.parse().map_err(void_err_to_cli)?;

    let repo_name = if let Some(ref rm_cid_bytes) = commit.repo_manifest_cid {
        let rm_cid = rm_cid_bytes.to_void_cid().map_err(void_err_to_cli)?;
        match remote.fetch_raw(&rm_cid) {
            Ok(rm_bytes) => {
                let rm_blob = EncryptedRepoManifest::from_bytes(rm_bytes);
                match reader.decrypt_repo_manifest(&rm_blob) {
                    Ok(manifest) => manifest.repo_name.clone(),
                    Err(_) => None,
                }
            }
            Err(_) => None,
        }
    } else {
        None
    };

    Ok((repo_name, commit.message.clone(), commit.stats.clone()))
}

/// Format a byte count as a human-readable string.
fn format_bytes(bytes: u64) -> String {
    if bytes < 1024 {
        return format!("{} B", bytes);
    }
    if bytes < 1024 * 1024 {
        return format!("{:.1} KB", bytes as f64 / 1024.0);
    }
    if bytes < 1024 * 1024 * 1024 {
        return format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0));
    }
    format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
}


/// Resolve a registry name into (CID, key, repo_id, repo_name).
///
/// Looks up the repo by name in `~/.void/repos/`, finds the HEAD CID for "trunk",
/// then loads the encryption key from the source repo's manifest via identity.
/// Returns the repo identity so it can be written into the cloned config.
fn resolve_clone_registry_name_with_record(
    name: &str,
) -> Result<(String, [u8; 32], String, String), CliError> {
    let record = crate::registry::resolve_target(name).map_err(|e| CliError::not_found(e))?;

    // Get HEAD CID — prefer "trunk", fall back to any branch
    let cid_str = record
        .head
        .get("trunk")
        .or_else(|| record.head.values().next())
        .ok_or_else(|| {
            CliError::not_found(format!(
                "repo '{}' has no HEAD CID in registry (no pushes recorded yet)",
                name
            ))
        })?
        .clone();

    // Load key from source repo's manifest via identity + ECIES unwrap.
    // Try each known local checkout path until one works.
    let identity = crate::context::load_identity_cached()?;
    let mut key = None;
    for local_path in &record.local_paths {
        let source_void_dir = local_path.join(".void");
        if source_void_dir.exists() {
            if let Ok(repo_key) = void_core::collab::manifest::load_repo_key(&source_void_dir, Some(&identity)) {
                key = Some(*repo_key.as_bytes());
                break;
            }
        }
    }
    let key = key.ok_or_else(|| {
        CliError::not_found(format!(
            "could not load encryption key for repo '{}'. \
             Ensure a local checkout exists and your identity has access.",
            name,
        ))
    })?;

    Ok((cid_str, key, record.id.clone(), record.name.clone()))
}



/// Parse a 64-char hex string into a 32-byte key.
fn parse_hex_key(hex_str: &str) -> Result<[u8; 32], CliError> {
    let trimmed = hex_str.trim();
    let bytes = hex::decode(trimmed)
        .map_err(|e| CliError::invalid_args(format!("invalid key hex: {}", e)))?;
    bytes
        .try_into()
        .map_err(|_| CliError::invalid_args("key must be 32 bytes (64 hex chars)"))
}

/// Ensure the cloner has an ECIES-wrapped key in the manifest.
///
/// If the cloned repo already has a manifest (from the source), the cloner's
/// wrapped key is added. Otherwise a fresh manifest is created with the cloner
/// as owner. This replaces the old `save_key()` which wrote plaintext.
fn ensure_cloner_manifest(
    void_dir: &Path,
    key: &[u8; 32],
    _ctx: &crate::output::CommandContext,
) -> Result<(), CliError> {
    use std::time::{SystemTime, UNIX_EPOCH};
    use void_core::collab::manifest::{
        ecies_wrap_key, save_manifest, Contributor, ContributorId, Manifest, RepoKey,
    };

    let (username, signing_pubkey, recipient_pubkey, _nostr) =
        match crate::context::load_public_identity() {
            Ok(id) => id,
            Err(_) => {
                // No identity available — can't wrap key in manifest.
                // The repo will still work via --key on next clone, but the
                // user will need to set up an identity to use it normally.
                eprintln!(
                    "warning: No identity found — repo key not wrapped in manifest. \
                     Run 'void identity init' then re-clone to enable identity-based access."
                );
                return Ok(());
            }
        };
    let username = username.unwrap_or_else(|| "anonymous".to_string());

    let repo_key = RepoKey::from_bytes(*key);
    let wrapped = ecies_wrap_key(&repo_key, &recipient_pubkey)
        .map_err(|e| CliError::internal(format!("failed to wrap key: {}", e)))?;

    // Check if the cloned repo already has a manifest (from the source)
    let mut manifest = void_core::collab::manifest::load_manifest(void_dir)
        .ok()
        .flatten()
        .unwrap_or_else(|| {
            let mut m = Manifest::new(signing_pubkey.clone(), None);
            m.repo_id = None;
            m.repo_name = None;
            m
        });

    // Add cloner's wrapped key
    manifest
        .read_keys
        .wrapped
        .insert(signing_pubkey.clone(), wrapped);

    // Add cloner as contributor if not already present
    let already_contributor = manifest
        .contributors
        .iter()
        .any(|c| c.identity.signing == signing_pubkey);
    if !already_contributor {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        manifest.contributors.push(Contributor {
            identity: ContributorId::new(signing_pubkey.clone(), recipient_pubkey),
            name: Some(username),
            nostr_pubkey: None,
            added_at: timestamp,
            added_by: signing_pubkey,
            signature: vec![],
        });
    }

    save_manifest(void_dir, &manifest)
        .map_err(|e| CliError::internal(format!("failed to write manifest: {}", e)))?;

    Ok(())
}

/// Save the config.json file with the repo_secret from the cloned metadata.
/// If `repo_id` and `repo_name` are provided (e.g., from a registry clone), they
/// are written into the config for future identity lookups.
fn save_config(
    void_dir: &Path,
    clone_result: &CloneResult,
    repo_id: Option<&str>,
    repo_name: Option<&str>,
) -> Result<(), CliError> {
    let repo_secret_hex = hex::encode(clone_result.repo_secret.as_bytes());

    let config = Config {
        version: Some(1),
        created: Some(chrono::Utc::now().to_rfc3339()),
        repo_secret: Some(repo_secret_hex),
        repo_id: repo_id.map(|s| s.to_string()),
        repo_name: repo_name.map(|s| s.to_string()),
        ipfs: None,
        tor: None,
        user: Default::default(),
        core: CoreConfig::default(),
        remote: Default::default(),
    };

    void_core::config::save(void_dir, &config)
        .map_err(|e| CliError::internal(format!("failed to write config file: {}", e)))?;

    Ok(())
}

/// Checkout the working tree from the cloned commit.
/// Returns the number of files extracted.
fn checkout_working_tree(
    void_dir: &Path,
    vault: &KeyVault,
    commit_cid_str: &str,
    workspace: &Path,
    observer: Arc<ProgressObserver>,
) -> Result<usize, CliError> {
    let commit_cid = cid::parse(commit_cid_str)
        .map_err(|e| CliError::internal(format!("invalid commit CID: {}", e)))?;

    let objects_dir = Utf8PathBuf::try_from(void_dir.join("objects"))
        .map_err(|e| CliError::internal(format!("invalid objects path: {}", e)))?;

    let store = FsStore::new(objects_dir)
        .map_err(|e| CliError::internal(format!("failed to open store: {}", e)))?;

    let checkout_opts = CheckoutOptions {
        paths: None, // Full tree checkout
        force: true, // We're cloning into a fresh directory
        observer: Some(observer),
        workspace_dir: None,
        include_large: false,
    };

    let result = checkout_tree(&store, vault, &commit_cid, workspace, &checkout_opts)
        .map_err(void_err_to_cli)?;

    Ok(result.files_restored)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_key_valid() {
        let hex = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        let key = parse_key(hex).unwrap();
        assert_eq!(key.len(), 32);
        assert_eq!(key[0], 0x01);
        assert_eq!(key[1], 0x23);
    }

    #[test]
    fn test_parse_key_with_whitespace() {
        let hex = "  0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef  \n";
        let key = parse_key(hex).unwrap();
        assert_eq!(key.len(), 32);
    }

    #[test]
    fn test_parse_key_invalid_hex() {
        let hex = "not-valid-hex";
        let result = parse_key(hex);
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("invalid key hex"));
    }

    #[test]
    fn test_parse_key_wrong_length() {
        let hex = "0123456789abcdef"; // Only 8 bytes
        let result = parse_key(hex);
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("32 bytes"));
    }

    #[test]
    fn test_parse_mode_full() {
        assert_eq!(parse_mode("full").unwrap(), CloneMode::Full);
        assert_eq!(parse_mode("FULL").unwrap(), CloneMode::Full);
        assert_eq!(parse_mode("Full").unwrap(), CloneMode::Full);
    }

    #[test]
    fn test_parse_mode_depth1() {
        assert_eq!(parse_mode("depth1").unwrap(), CloneMode::Depth1);
        assert_eq!(parse_mode("DEPTH1").unwrap(), CloneMode::Depth1);
    }

    #[test]
    fn test_parse_mode_lazy() {
        assert_eq!(parse_mode("lazy").unwrap(), CloneMode::Lazy);
        assert_eq!(parse_mode("LAZY").unwrap(), CloneMode::Lazy);
    }

    #[test]
    fn test_parse_mode_invalid() {
        let result = parse_mode("invalid");
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("invalid clone mode"));
    }

    #[test]
    fn test_mode_to_string() {
        assert_eq!(mode_to_string(CloneMode::Full), "full");
        assert_eq!(mode_to_string(CloneMode::Depth1), "depth1");
        assert_eq!(mode_to_string(CloneMode::Lazy), "lazy");
    }

    #[test]
    fn test_clone_output_serialization() {
        let output = CloneOutput {
            path: "/path/to/repo".to_string(),
            commit: "bafyabc123".to_string(),
            metadata: "bafydef456".to_string(),
            mode: "full".to_string(),
            shards_fetched: 10,
            shards_total: 15,
            files_extracted: Some(100),
            source: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"path\":\"/path/to/repo\""));
        assert!(json.contains("\"commit\":\"bafyabc123\""));
        assert!(json.contains("\"metadata\":\"bafydef456\""));
        assert!(json.contains("\"shardsFetched\":10"));
        assert!(json.contains("\"shardsTotal\":15"));
        assert!(json.contains("\"mode\":\"full\""));
        assert!(json.contains("\"filesExtracted\":100"));
        // source should not be present when None
        assert!(!json.contains("\"source\""));
    }

    #[test]
    fn test_clone_output_serialization_depth1() {
        let output = CloneOutput {
            path: "/path/to/repo".to_string(),
            commit: "bafyabc123".to_string(),
            metadata: "bafydef456".to_string(),
            mode: "depth1".to_string(),
            shards_fetched: 5,
            shards_total: 15,
            files_extracted: None,
            source: Some("alice/proj/main".to_string()),
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"path\":\"/path/to/repo\""));
        assert!(json.contains("\"mode\":\"depth1\""));
        assert!(json.contains("\"source\":\"alice/proj/main\""));
        // files_extracted should not be present when None
        assert!(!json.contains("\"filesExtracted\""));
    }
}