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
//! Push command - push commits to IPFS.
//!
//! Pushes a commit and all its objects (metadata bundle, shards) to an IPFS
//! backend. Uses delta-based optimization: only objects that differ from the
//! parent commit are pushed, making incremental pushes efficient.
//!
//! After pushing to local IPFS, replicates to configured SSH remotes by
//! exporting a CAR file, SCP-ing it to the remote, and running
//! `ipfs dag import` + `ipfs pin add` via SSH.

use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use camino::Utf8PathBuf;
use serde::Serialize;
use void_core::config;
use void_core::pipeline::{export_commit_to_car, push_repo, ExportCarOptions, PushOptions};
use void_core::transport::IpfsBackend;
use void_core::refs;

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

/// Default Kubo API URL.
pub const DEFAULT_KUBO_URL: &str = "http://127.0.0.1:5001";

/// Default timeout in milliseconds.
pub const DEFAULT_TIMEOUT_MS: u64 = 30000;

/// Command-line arguments for push.
#[derive(Debug)]
pub struct PushArgs {
    /// Optional commit CID to push (default: HEAD).
    pub commit: Option<String>,
    /// Backend type: kubo or gateway.
    pub backend: String,
    /// Kubo API URL.
    pub kubo_url: String,
    /// Gateway URL (required if backend is gateway).
    pub gateway: Option<String>,
    /// Request timeout in milliseconds.
    pub timeout_ms: u64,
    /// Pin objects after pushing.
    pub pin: bool,
    /// Skip remotes, only push to local IPFS (default: true).
    pub local: bool,
    /// Push to specific remote only.
    pub remote: Option<String>,
    /// Ignore push markers and push all objects.
    pub full: bool,
    /// Force push: skip missing objects instead of failing.
    pub force: bool,
}

impl Default for PushArgs {
    fn default() -> Self {
        Self {
            commit: None,
            backend: "daemon".to_string(),
            kubo_url: DEFAULT_KUBO_URL.to_string(),
            gateway: None,
            timeout_ms: DEFAULT_TIMEOUT_MS,
            pin: true,
            local: false,
            remote: None,
            full: false,
            force: false,
        }
    }
}

/// Result for a single remote push operation.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RemoteResult {
    /// Remote name.
    pub name: String,
    /// Whether the push succeeded.
    pub success: bool,
    /// Error message if push failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// JSON output for the push command.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PushOutput {
    /// The CID of the pushed commit.
    pub commit: String,
    /// Number of objects pushed to IPFS.
    pub objects_pushed: usize,
    /// Number of objects pinned (0 if --pin not specified).
    pub pinned: usize,
    /// Number of commits included in this push.
    pub commits_pushed: usize,
    /// Results for each remote (if remotes were configured).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remotes: Option<Vec<RemoteResult>>,
}

/// Run the push command.
pub fn run(cwd: &Path, args: PushArgs, opts: &CliOptions) -> Result<(), CliError> {
    run_command("push", opts, |ctx| {
        let repo = open_repo(cwd)?;
        let void_dir = repo.void_dir().to_owned();

        ctx.progress("Connecting to IPFS...");

        // Select backend: daemon (default), kubo (legacy), or gateway.
        let (backend, daemon_remote, _daemon_rt) = match args.backend.as_str() {
            "kubo" => (
                IpfsBackend::Kubo {
                    api: args.kubo_url.clone(),
                },
                None,
                None,
            ),
            "gateway" => {
                let gateway_url = args.gateway.as_ref().ok_or_else(|| {
                    crate::output::CliError::invalid_args(
                        "--gateway URL is required when using gateway backend",
                    )
                })?;
                (
                    IpfsBackend::Gateway {
                        base: gateway_url.clone(),
                    },
                    None,
                    None,
                )
            }
            _ => {
                // Default: embedded daemon (no external dependencies).
                ctx.progress("Starting embedded node...");
                let (remote, rt) = crate::daemon::start_daemon(repo.void_dir().as_std_path())
                    .map_err(|e| crate::output::CliError::internal(e))?;
                (
                    IpfsBackend::Kubo {
                        api: "unused".to_string(),
                    },
                    Some(remote),
                    Some(rt),
                )
            }
        };

        // Create observer based on output mode
        let progress_observer = if opts.is_human_mode() {
            ProgressObserver::new("Pushing...")
        } else {
            ProgressObserver::new_hidden()
        };
        let observer: Arc<dyn void_core::support::events::VoidObserver> =
            Arc::new(progress_observer);

        let push_opts = PushOptions {
            ctx: repo.context().clone(),
            commit_cid: args.commit.clone(),
            backend,
            timeout: Duration::from_millis(args.timeout_ms),
            pin: args.pin,
            backend_name: "local".to_string(),
            full: args.full,
            force: args.force,
            observer: Some(observer),
            remote: daemon_remote,
        };

        ctx.progress("Pushing...");

        let result = push_repo(push_opts).map_err(void_err_to_cli)?;

        // Human-readable output
        if !ctx.use_json() {
            let short_cid = if result.commit_cid.len() > 12 {
                &result.commit_cid[..12]
            } else {
                &result.commit_cid
            };

            ctx.info(format!(
                "Pushed {} objects for commit {}...",
                result.objects_pushed, short_cid
            ));

            if result.pinned > 0 {
                ctx.info(format!("Pinned {} objects", result.pinned));
            }
        }

        // Step 2: Replicate to remotes (unless --local)
        let remote_results = if args.local {
            None
        } else {
            replicate_to_remotes(
                ctx,
                repo.context(),
                &result.commit_cid,
                args.commit.as_deref(),
                args.remote.as_deref(),
            )?
        };

        // Update registry HEAD (best-effort)
        {
            let cfg = config::load(void_dir.as_std_path()).ok();
            if let Some(ref repo_id) = cfg.as_ref().and_then(|c| c.repo_id.as_ref()) {
                let branch = get_current_branch(void_dir.as_std_path()).unwrap_or_else(|| "trunk".to_string());
                if let Err(e) = crate::registry::update_head(repo_id, &branch, &result.commit_cid) {
                    ctx.warn(format!("Failed to update registry: {}", e));
                }
            }
        }

        ctx.progress("Push complete.");

        Ok(PushOutput {
            commit: result.commit_cid,
            objects_pushed: result.objects_pushed,
            pinned: result.pinned,
            commits_pushed: result.commits_pushed,
            remotes: remote_results,
        })
    })
}

/// Get the current branch name from HEAD.
fn get_current_branch(void_dir: &Path) -> Option<String> {
    let void_dir_utf8 = Utf8PathBuf::try_from(void_dir.to_path_buf()).ok()?;
    match refs::read_head(&void_dir_utf8).ok()? {
        Some(refs::HeadRef::Symbolic(branch)) => Some(branch),
        _ => None,
    }
}

// ============================================================================
// Remote replication helpers
// ============================================================================

/// Expand `~` to the user's home directory in a path string.
fn expand_tilde(path: &str) -> String {
    if path.starts_with('~') {
        if let Some(home) = dirs::home_dir() {
            return path.replacen('~', &home.to_string_lossy(), 1);
        }
    }
    path.to_string()
}

/// Pin a commit to a single SSH remote by exporting a CAR, SCP-ing it, then
/// running `ipfs dag import` + `ipfs pin add` over SSH.
///
/// Returns a `RemoteResult` — failures are captured, never propagated.
fn pin_to_remote(
    ctx: &mut crate::output::CommandContext,
    name: &str,
    remote: &config::RemoteConfig,
    commit_cid: &str,
    car_path: &Path,
) -> RemoteResult {
    let ssh_host = match remote.host.as_deref() {
        Some(h) => h,
        None => {
            return RemoteResult {
                name: name.to_string(),
                success: false,
                error: Some(format!("Remote '{}' has no host configured", name)),
            };
        }
    };

    let ssh_user = remote.user.as_deref().unwrap_or("root");
    let ssh_key = remote
        .key_path
        .as_deref()
        .map(expand_tilde)
        .unwrap_or_else(|| {
            dirs::home_dir()
                .map(|h| h.join(".ssh/id_rsa").to_string_lossy().to_string())
                .unwrap_or_else(|| "~/.ssh/id_rsa".to_string())
        });

    let host_display = format!("{}@{}", ssh_user, ssh_host);

    let ts = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    let remote_car_path = format!("/tmp/void-{}.car", ts);
    let scp_dest = format!("{}@{}:{}", ssh_user, ssh_host, remote_car_path);

    // SCP the CAR file to the remote
    ctx.progress(format!("Copying CAR to {}...", host_display));

    let scp_output = match Command::new("scp")
        .args([
            "-i",
            &ssh_key,
            "-o",
            "StrictHostKeyChecking=accept-new",
            &car_path.to_string_lossy(),
            &scp_dest,
        ])
        .output()
    {
        Ok(o) => o,
        Err(e) => {
            return RemoteResult {
                name: name.to_string(),
                success: false,
                error: Some(format!("failed to run scp: {}", e)),
            };
        }
    };

    if !scp_output.status.success() {
        let stderr = String::from_utf8_lossy(&scp_output.stderr);
        return RemoteResult {
            name: name.to_string(),
            success: false,
            error: Some(format!("SCP failed: {}", stderr.trim())),
        };
    }

    // SSH to import and pin
    ctx.progress(format!("Importing and pinning on {}...", host_display));

    let ssh_cmd = format!(
        "sudo IPFS_PATH=/home/ipfs/.ipfs ipfs dag import {} && \
         sudo IPFS_PATH=/home/ipfs/.ipfs ipfs pin add {} && \
         rm {}",
        remote_car_path, commit_cid, remote_car_path
    );

    let ssh_output = match Command::new("ssh")
        .args([
            "-i",
            &ssh_key,
            "-o",
            "StrictHostKeyChecking=accept-new",
            &format!("{}@{}", ssh_user, ssh_host),
            &ssh_cmd,
        ])
        .output()
    {
        Ok(o) => o,
        Err(e) => {
            return RemoteResult {
                name: name.to_string(),
                success: false,
                error: Some(format!("failed to run ssh: {}", e)),
            };
        }
    };

    if !ssh_output.status.success() {
        let stderr = String::from_utf8_lossy(&ssh_output.stderr);
        return RemoteResult {
            name: name.to_string(),
            success: false,
            error: Some(format!("SSH failed: {}", stderr.trim())),
        };
    }

    ctx.info(format!("Pinned on {}", host_display));

    RemoteResult {
        name: name.to_string(),
        success: true,
        error: None,
    }
}

/// Replicate blocks to a P2P remote via the daemon control protocol.
///
/// Connects to the remote daemon, authenticates with void identity,
/// then sends each block via Put.
fn pin_to_p2p_remote(
    ctx: &mut crate::output::CommandContext,
    name: &str,
    remote: &config::RemoteConfig,
    void_ctx: &void_core::VoidContext,
    commit_cid: &str,
) -> RemoteResult {
    // Extract peer_id and addr — try new fields first, fall back to peerMultiaddr.
    let (peer_id_str, addr_str) = if let (Some(pid), Some(a)) = (remote.peer_id.as_deref(), remote.addrs.first()) {
        (pid.to_string(), a.clone())
    } else if let Some(ref multiaddr) = remote.peer_multiaddr {
        // Parse "/ip4/.../tcp/.../p2p/12D3KooW..." format
        match multiaddr.rfind("/p2p/") {
            Some(idx) => (multiaddr[idx + 5..].to_string(), multiaddr[..idx].to_string()),
            None => {
                return RemoteResult {
                    name: name.to_string(),
                    success: false,
                    error: Some(format!("Remote '{}': peerMultiaddr missing /p2p/ component", name)),
                };
            }
        }
    } else {
        return RemoteResult {
            name: name.to_string(),
            success: false,
            error: Some(format!("Remote '{}' has no peerId or peerMultiaddr configured", name)),
        };
    };

    let peer_id: libp2p::PeerId = match peer_id_str.as_str().parse() {
        Ok(p) => p,
        Err(e) => {
            return RemoteResult {
                name: name.to_string(),
                success: false,
                error: Some(format!("invalid peerId: {e}")),
            };
        }
    };

    let addr: libp2p::Multiaddr = match addr_str.as_str().parse() {
        Ok(a) => a,
        Err(e) => {
            return RemoteResult {
                name: name.to_string(),
                success: false,
                error: Some(format!("invalid multiaddr: {e}")),
            };
        }
    };

    ctx.info(format!("Syncing to remote '{}' ({})...", name, &peer_id_str[..12.min(peer_id_str.len())]));

    // Build a tokio runtime for the async operations.
    let rt = match tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
    {
        Ok(rt) => rt,
        Err(e) => {
            return RemoteResult {
                name: name.to_string(),
                success: false,
                error: Some(format!("runtime: {e}")),
            };
        }
    };

    let result = rt.block_on(async {
        // Connect to remote daemon.
        let client = void_daemon::DaemonClient::connect(addr, peer_id).await
            .map_err(|e| format!("connect failed: {e}"))?;

        // Authenticate with void identity signing key.
        let signing_key = crate::context::load_signing_key()
            .map_err(|e| format!("load identity: {e}"))?;

        // Convert void signing key to ed25519-dalek SigningKey
        let key_bytes = signing_key.as_bytes();
        let dalek_key = ed25519_dalek::SigningKey::from_bytes(key_bytes);

        client.authenticate(&dalek_key).await
            .map_err(|e| format!("auth failed: {e}"))?;

        ctx.progress(format!("Authenticated with {}. Syncing blocks...", name));

        // Collect all objects for this commit (CID + encrypted bytes).
        let commit_cid_obj = void_core::cid::parse(commit_cid)
            .map_err(|e| format!("invalid CID: {e}"))?;
        use void_core::pipeline::collect_local_objects;
        let objects = collect_local_objects(void_ctx, &commit_cid_obj)
            .map_err(|e| format!("collect objects: {e}"))?;

        let mut synced = 0usize;
        for (cid, data) in &objects {
            client.put(cid.to_bytes(), data.clone()).await
                .map_err(|e| format!("put failed: {e}"))?;
            synced += 1;
        }

        // Update HEAD on the remote registry.
        let repo_name = void_ctx.repo.name.clone()
            .unwrap_or_else(|| "unnamed".to_string());
        let branch = {
            let void_dir_std = void_ctx.paths.void_dir.as_std_path();
            get_current_branch(void_dir_std).unwrap_or_else(|| "trunk".to_string())
        };
        client.set_head(&repo_name, &branch, commit_cid).await
            .map_err(|e| format!("set_head failed: {e}"))?;

        Ok::<usize, String>(synced)
    });

    match result {
        Ok(synced) => {
            ctx.info(format!("Synced {} blocks to {}", synced, name));
            RemoteResult {
                name: name.to_string(),
                success: true,
                error: None,
            }
        }
        Err(e) => RemoteResult {
            name: name.to_string(),
            success: false,
            error: Some(e),
        },
    }
}

/// Load remotes from config, export a CAR, and replicate to each remote.
///
/// If `specific_remote` is `Some`, only that remote is targeted.
/// Remote errors are collected into the result vec — they never fail the push.
fn replicate_to_remotes(
    ctx: &mut crate::output::CommandContext,
    void_ctx: &void_core::VoidContext,
    commit_cid: &str,
    commit_arg: Option<&str>,
    specific_remote: Option<&str>,
) -> Result<Option<Vec<RemoteResult>>, CliError> {
    let void_dir = &void_ctx.paths.void_dir;
    // Load config to discover remotes
    let cfg = config::load(void_dir.as_std_path())
        .map_err(|e| CliError::internal(format!("failed to load config: {e}")))?;

    if cfg.remote.is_empty() {
        return Ok(None);
    }

    // Filter to specific remote if requested
    let target_remotes: Vec<(&String, &config::RemoteConfig)> = if let Some(name) = specific_remote
    {
        match cfg.remote.get_key_value(name) {
            Some(entry) => vec![entry],
            None => {
                return Err(CliError::not_found(format!("Remote '{}' not found", name)));
            }
        }
    } else {
        cfg.remote.iter().collect()
    };

    if target_remotes.is_empty() {
        return Ok(None);
    }

    // Separate P2P remotes from SSH remotes.
    let (p2p_remotes, ssh_remotes): (Vec<_>, Vec<_>) = target_remotes
        .iter()
        .partition(|(_, r)| r.peer_id.is_some() || r.peer_multiaddr.is_some());

    let names: Vec<&str> = target_remotes.iter().map(|(n, _)| n.as_str()).collect();
    ctx.progress(format!("Replicating to: {}", names.join(", ")));

    let mut results = Vec::with_capacity(target_remotes.len());

    // P2P remotes: authenticate + send via control protocol (no CAR needed).
    for (name, remote_cfg) in &p2p_remotes {
        let r = pin_to_p2p_remote(ctx, name, remote_cfg, void_ctx, commit_cid);
        results.push(r);
    }

    // SSH remotes: export CAR + SCP + ipfs import (legacy).
    if !ssh_remotes.is_empty() {
        ctx.progress("Exporting CAR for SSH remote replication...");

        let ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis();
        let temp_car = std::env::temp_dir().join(format!("void-push-{}.car", ts));

        let export_opts = ExportCarOptions {
            ctx: void_ctx.clone(),
            commit_cid: commit_arg.map(String::from),
        };

        match export_commit_to_car(export_opts, &temp_car) {
            Ok(export_result) => {
                ctx.progress(format!(
                    "Exported {} blocks ({} bytes)",
                    export_result.blocks_exported, export_result.car_size
                ));

                for (name, remote_cfg) in &ssh_remotes {
                    let r = pin_to_remote(ctx, name, remote_cfg, commit_cid, &temp_car);
                    results.push(r);
                }

                let _ = std::fs::remove_file(&temp_car);
            }
            Err(e) => {
                ctx.warn(format!("CAR export failed: {e} — skipping SSH remotes"));
            }
        }
    }

    // Report failures as warnings (never fail the whole push)
    let failures: Vec<&RemoteResult> = results.iter().filter(|r| !r.success).collect();
    if !failures.is_empty() {
        ctx.warn(format!("{} remote(s) failed", failures.len()));
    }

    Ok(Some(results))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::output::CliOptions;
    use std::fs;
    use tempfile::tempdir;
    use void_core::crypto;

    fn default_opts() -> CliOptions {
        CliOptions {
            human: true,
            ..Default::default()
        }
    }

    fn setup_test_repo() -> (tempfile::TempDir, std::path::PathBuf, tempfile::TempDir, crate::context::VoidHomeGuard) {
        let dir = tempdir().unwrap();
        let void_dir = dir.path().join(".void");
        fs::create_dir_all(void_dir.join("objects")).unwrap();
        fs::create_dir_all(void_dir.join("refs/heads")).unwrap();

        // Set up manifest-based key
        let key = crypto::generate_key();
        let home = tempdir().unwrap();
        let guard = crate::context::setup_test_manifest(&void_dir, &key, home.path());

        // Create config file with repoSecret
        let repo_secret = hex::encode(crypto::generate_key());
        fs::write(
            void_dir.join("config.json"),
            format!(r#"{{"repoSecret": "{}"}}"#, repo_secret),
        )
        .unwrap();

        (dir, void_dir, home, guard)
    }

    #[test]
    fn test_push_args_default() {
        let args = PushArgs::default();
        assert_eq!(args.backend, "daemon");
        assert_eq!(args.kubo_url, DEFAULT_KUBO_URL);
        assert_eq!(args.timeout_ms, DEFAULT_TIMEOUT_MS);
        assert!(args.pin); // pin defaults to true now
        assert!(args.commit.is_none());
        assert!(args.gateway.is_none());
        assert!(!args.local); // default: sync to remotes (replicate_to_remotes handles empty config)
        assert!(args.remote.is_none());
    }

    #[test]
    fn test_push_output_serialization() {
        let output = PushOutput {
            commit: "bafytest123456789abcdef".to_string(),
            objects_pushed: 42,
            pinned: 42,
            commits_pushed: 1,
            remotes: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"commit\":\"bafytest123456789abcdef\""));
        assert!(json.contains("\"objectsPushed\":42"));
        assert!(json.contains("\"pinned\":42"));
        // remotes should not appear when None
        assert!(!json.contains("\"remotes\""));
    }

    #[test]
    fn test_push_output_serialization_no_pin() {
        let output = PushOutput {
            commit: "bafytest123".to_string(),
            objects_pushed: 10,
            pinned: 0,
            commits_pushed: 1,
            remotes: None,
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"objectsPushed\":10"));
        assert!(json.contains("\"pinned\":0"));
    }

    #[test]
    fn test_push_output_serialization_with_remotes() {
        let output = PushOutput {
            commit: "bafytest123".to_string(),
            objects_pushed: 10,
            pinned: 10,
            commits_pushed: 1,
            remotes: Some(vec![
                RemoteResult {
                    name: "origin".to_string(),
                    success: true,
                    error: None,
                },
                RemoteResult {
                    name: "backup".to_string(),
                    success: false,
                    error: Some("connection refused".to_string()),
                },
            ]),
        };

        let json = serde_json::to_string(&output).unwrap();
        assert!(json.contains("\"remotes\""));
        assert!(json.contains("\"name\":\"origin\""));
        assert!(json.contains("\"success\":true"));
        assert!(json.contains("\"name\":\"backup\""));
        assert!(json.contains("\"success\":false"));
        assert!(json.contains("\"error\":\"connection refused\""));
    }

    #[test]
    fn test_remote_result_skips_none_error() {
        let result = RemoteResult {
            name: "origin".to_string(),
            success: true,
            error: None,
        };

        let json = serde_json::to_string(&result).unwrap();
        assert!(!json.contains("\"error\""));
    }

    #[test]
    fn test_push_not_initialized() {
        let dir = tempdir().unwrap();
        // No .void directory

        let args = PushArgs::default();
        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
    }

    #[test]
    fn test_push_no_head() {
        let (dir, _void_dir, _home, _guard) = setup_test_repo();
        // No HEAD set

        let args = PushArgs::default();
        // This will fail because there's no HEAD and no commit specified
        // The error comes from push_repo when it can't resolve HEAD
        let result = run(dir.path(), args, &default_opts());
        assert!(result.is_err());
    }
}