claw-vcs 0.1.1

Claw VCS: intent-native, agent-native version 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
use std::collections::BTreeSet;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;

use clap::{Args, Subcommand};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

use claw_store::ClawStore;

use crate::auth_store;
use crate::commands::RuntimeOptions;
use crate::config::{self, ClawConfigV1};

#[derive(Args)]
pub struct AdminArgs {
    #[command(subcommand)]
    command: AdminCommand,
}

#[derive(Subcommand)]
enum AdminCommand {
    /// Validate host and repository production preconditions
    Preflight,
    /// Manage backups
    Backup {
        #[command(subcommand)]
        command: BackupCommand,
    },
    /// Plan/apply config migrations
    Migrate {
        #[command(subcommand)]
        command: MigrateCommand,
    },
    /// Plan/execute rollback from backups
    Rollback {
        #[command(subcommand)]
        command: RollbackCommand,
    },
    /// Produce a diagnostic support bundle
    SupportBundle {
        /// Output path for support bundle JSON
        #[arg(long)]
        out: Option<PathBuf>,
    },
}

#[derive(Subcommand)]
enum BackupCommand {
    /// Create a repository metadata backup
    Create,
    /// Verify backup integrity
    Verify {
        /// Backup id to verify (defaults to latest)
        #[arg(long)]
        backup_id: Option<String>,
    },
}

#[derive(Subcommand)]
enum MigrateCommand {
    /// Show migration plan and config diff preview
    Plan,
    /// Apply config migration (or preview with --dry-run)
    Apply {
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(Subcommand)]
enum RollbackCommand {
    /// Show rollback plan for a backup
    Plan {
        /// Backup id to rollback to (defaults to latest)
        #[arg(long)]
        backup_id: Option<String>,
    },
    /// Execute rollback from backup snapshot
    Execute {
        /// Backup id to rollback to (defaults to latest)
        #[arg(long)]
        backup_id: Option<String>,
    },
}

#[derive(Serialize, Deserialize)]
struct BackupManifest {
    backup_id: String,
    created_at_ms: u64,
    files: Vec<BackupEntry>,
}

#[derive(Serialize, serde::Deserialize)]
struct BackupEntry {
    path: String,
    bytes: u64,
    sha256: String,
}

#[derive(Serialize)]
struct LedgerEntry {
    timestamp_ms: u64,
    action: String,
    status: String,
    details: serde_json::Value,
}

#[derive(Serialize)]
struct SupportBundle {
    request_id: String,
    created_at_ms: u64,
    repo_root: String,
    config: ClawConfigV1,
    head: Option<String>,
    refs_count: usize,
    latest_backup_id: Option<String>,
}

pub fn run(args: AdminArgs, runtime: &RuntimeOptions) -> anyhow::Result<()> {
    match args.command {
        AdminCommand::Preflight => run_preflight(runtime),
        AdminCommand::Backup { command } => match command {
            BackupCommand::Create => run_backup_create(),
            BackupCommand::Verify { backup_id } => run_backup_verify(backup_id),
        },
        AdminCommand::Migrate { command } => match command {
            MigrateCommand::Plan => run_migrate_plan(),
            MigrateCommand::Apply { dry_run } => run_migrate_apply(dry_run),
        },
        AdminCommand::Rollback { command } => match command {
            RollbackCommand::Plan { backup_id } => run_rollback_plan(backup_id),
            RollbackCommand::Execute { backup_id } => run_rollback_execute(backup_id),
        },
        AdminCommand::SupportBundle { out } => run_support_bundle(out),
    }
}

fn run_preflight(_runtime: &RuntimeOptions) -> anyhow::Result<()> {
    const DISK_FREE_WARN_KIB: u64 = 1_048_576; // 1 GiB
    const DISK_FREE_FAIL_KIB: u64 = 262_144; // 256 MiB
    const NOFILE_WARN_SOFT_LIMIT: u64 = 8_192;
    const NOFILE_FAIL_SOFT_LIMIT: u64 = 1_024;

    let root = config::find_repo_root()?;
    let claw_dir = root.join(".claw");
    let cfg = config::load_or_default_config(&root)?;

    let mut checks = Vec::new();

    if !claw_dir.is_dir() {
        checks.push(CheckResult::fail(
            "metadata directory",
            format!(
                "missing repository metadata directory: {}",
                claw_dir.display()
            ),
            "create the .claw directory or re-initialize the repository metadata",
        ));
    } else {
        checks.push(CheckResult::pass(
            "metadata directory",
            format!("found {}", claw_dir.display()),
        ));
    }

    if claw_dir.is_dir() {
        match fsync_probe(&claw_dir) {
            Ok(()) => checks.push(CheckResult::pass(
                "metadata fsync",
                "probe file write+sync succeeded".to_string(),
            )),
            Err(err) => checks.push(CheckResult::fail(
                "metadata fsync",
                format!("probe file write+sync failed: {err}"),
                "verify disk health and mount options, then ensure the process can write and fsync inside .claw",
            )),
        }

        match disk_free_kib(&claw_dir) {
            Ok(free_kib) => {
                let disk_status =
                    evaluate_threshold(free_kib, DISK_FREE_WARN_KIB, DISK_FREE_FAIL_KIB);
                let free_mib = free_kib / 1024;
                match disk_status {
                    ThresholdStatus::Pass => checks.push(CheckResult::pass(
                        "metadata disk space",
                        format!("{free_mib} MiB available on .claw filesystem"),
                    )),
                    ThresholdStatus::Warn => checks.push(CheckResult::warn(
                        "metadata disk space",
                        format!(
                            "{free_mib} MiB available (< {} MiB warning threshold)",
                            DISK_FREE_WARN_KIB / 1024
                        ),
                        "free up space or move repository metadata to a filesystem with more capacity",
                    )),
                    ThresholdStatus::Fail => checks.push(CheckResult::fail(
                        "metadata disk space",
                        format!(
                            "{free_mib} MiB available (< {} MiB fail threshold)",
                            DISK_FREE_FAIL_KIB / 1024
                        ),
                        "free disk space immediately before running production workloads",
                    )),
                }
            }
            Err(err) => checks.push(CheckResult::warn(
                "metadata disk space",
                format!("unable to measure free space: {err}"),
                "run `df -h .claw` manually and ensure available space exceeds deployment needs",
            )),
        }

        match nofile_soft_limit() {
            Ok(limit) => {
                if limit == u64::MAX {
                    checks.push(CheckResult::pass(
                        "open file descriptor limit (nofile)",
                        "soft limit is unlimited".to_string(),
                    ));
                } else {
                    match evaluate_threshold(limit, NOFILE_WARN_SOFT_LIMIT, NOFILE_FAIL_SOFT_LIMIT) {
                        ThresholdStatus::Pass => checks.push(CheckResult::pass(
                            "open file descriptor limit (nofile)",
                            format!("soft limit is {limit}"),
                        )),
                        ThresholdStatus::Warn => checks.push(CheckResult::warn(
                            "open file descriptor limit (nofile)",
                            format!(
                                "soft limit is {limit} (< {NOFILE_WARN_SOFT_LIMIT} warning threshold)"
                            ),
                            "raise the soft limit (for example `ulimit -n 8192`) before high-concurrency runs",
                        )),
                        ThresholdStatus::Fail => checks.push(CheckResult::fail(
                            "open file descriptor limit (nofile)",
                            format!(
                                "soft limit is {limit} (< {NOFILE_FAIL_SOFT_LIMIT} fail threshold)"
                            ),
                            "increase file descriptor limits in shell/system configuration and re-run preflight",
                        )),
                    }
                }
            }
            Err(err) => checks.push(CheckResult::warn(
                "open file descriptor limit (nofile)",
                format!("unable to read soft limit: {err}"),
                "check `ulimit -n` manually and ensure it is sized for production concurrency",
            )),
        }
    }

    let selected_profile = config::default_profile(&cfg).to_string();
    if cfg.auth.require_auth_for_daemon
        && auth_store::resolve_access_token(Some(&selected_profile)).is_none()
    {
        checks.push(CheckResult::warn(
            "daemon auth token",
            format!(
                "no auth token found for profile '{selected_profile}' (required for production daemon auth)"
            ),
            "run `claw auth login --profile <profile>` before starting the production daemon",
        ));
    } else if cfg.auth.require_auth_for_daemon {
        checks.push(CheckResult::pass(
            "daemon auth token",
            format!("token present for profile '{selected_profile}'"),
        ));
    } else {
        checks.push(CheckResult::pass(
            "daemon auth token",
            "not required by current configuration".to_string(),
        ));
    }

    if cfg.tls.require_for_non_localhost {
        match (&cfg.tls.cert_path, &cfg.tls.key_path) {
            (Some(_), None) | (None, Some(_)) => checks.push(CheckResult::fail(
                "tls configuration",
                "tls.cert_path and tls.key_path must both be set when TLS is configured"
                    .to_string(),
                "set both TLS paths in config or disable tls.require_for_non_localhost for local-only usage",
            )),
            _ => checks.push(CheckResult::pass(
                "tls configuration",
                "TLS settings are consistent".to_string(),
            )),
        }
    } else {
        checks.push(CheckResult::pass(
            "tls configuration",
            "TLS is not required for non-localhost by current configuration".to_string(),
        ));
    }

    let has_failures = checks.iter().any(|check| check.status == CheckStatus::Fail);

    if has_failures {
        println!("Preflight: FAIL");
    } else {
        println!("Preflight: PASS");
    }

    for check in &checks {
        println!("  {}", check.render());
    }

    println!("  repository: {}", root.display());
    println!("  config: {}", config::config_file_path(&root).display());

    if has_failures {
        anyhow::bail!("preflight failed");
    }

    Ok(())
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CheckStatus {
    Pass,
    Warn,
    Fail,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ThresholdStatus {
    Pass,
    Warn,
    Fail,
}

#[derive(Debug)]
struct CheckResult {
    status: CheckStatus,
    name: &'static str,
    detail: String,
    next_step: Option<&'static str>,
}

impl CheckResult {
    fn pass(name: &'static str, detail: String) -> Self {
        Self {
            status: CheckStatus::Pass,
            name,
            detail,
            next_step: None,
        }
    }

    fn warn(name: &'static str, detail: String, next_step: &'static str) -> Self {
        Self {
            status: CheckStatus::Warn,
            name,
            detail,
            next_step: Some(next_step),
        }
    }

    fn fail(name: &'static str, detail: String, next_step: &'static str) -> Self {
        Self {
            status: CheckStatus::Fail,
            name,
            detail,
            next_step: Some(next_step),
        }
    }

    fn render(&self) -> String {
        let status_label = match self.status {
            CheckStatus::Pass => "PASS",
            CheckStatus::Warn => "WARN",
            CheckStatus::Fail => "FAIL",
        };
        match self.next_step {
            Some(step) => format!(
                "[{status_label}] {}: {} | next: {step}",
                self.name, self.detail
            ),
            None => format!("[{status_label}] {}: {}", self.name, self.detail),
        }
    }
}

fn evaluate_threshold(value: u64, warn_threshold: u64, fail_threshold: u64) -> ThresholdStatus {
    if value < fail_threshold {
        ThresholdStatus::Fail
    } else if value < warn_threshold {
        ThresholdStatus::Warn
    } else {
        ThresholdStatus::Pass
    }
}

fn fsync_probe(claw_dir: &Path) -> anyhow::Result<()> {
    let path = claw_dir.join("preflight-fsync-probe.tmp");
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .truncate(true)
        .write(true)
        .open(&path)?;
    file.write_all(b"probe")?;
    file.sync_all()?;
    std::fs::remove_file(path)?;
    Ok(())
}

fn disk_free_kib(path: &Path) -> anyhow::Result<u64> {
    let output = Command::new("df").arg("-Pk").arg(path).output()?;
    if !output.status.success() {
        anyhow::bail!("df exited with status {}", output.status);
    }

    let stdout = String::from_utf8(output.stdout)?;
    let data_line = stdout
        .lines()
        .skip(1)
        .find(|line| !line.trim().is_empty())
        .ok_or_else(|| anyhow::anyhow!("df output missing filesystem data row"))?;
    let columns: Vec<&str> = data_line.split_whitespace().collect();
    if columns.len() < 4 {
        anyhow::bail!("unexpected df output row: {data_line}");
    }

    columns[3]
        .parse::<u64>()
        .map_err(|err| anyhow::anyhow!("invalid df available column '{}': {err}", columns[3]))
}

fn nofile_soft_limit() -> anyhow::Result<u64> {
    let output = Command::new("sh").arg("-c").arg("ulimit -Sn").output()?;
    if !output.status.success() {
        anyhow::bail!("ulimit exited with status {}", output.status);
    }

    let value = String::from_utf8(output.stdout)?.trim().to_string();
    if value.eq_ignore_ascii_case("unlimited") {
        return Ok(u64::MAX);
    }

    value
        .parse::<u64>()
        .map_err(|err| anyhow::anyhow!("invalid nofile soft limit '{value}': {err}"))
}

fn run_backup_create() -> anyhow::Result<()> {
    let root = config::find_repo_root()?;
    let backup = create_backup(&root)?;
    append_ledger(
        &root,
        LedgerEntry {
            timestamp_ms: now_ms(),
            action: "backup.create".to_string(),
            status: "ok".to_string(),
            details: serde_json::json!({"backup_id": backup.backup_id}),
        },
    )?;
    println!("Created backup: {}", backup.backup_id);
    println!("  files: {}", backup.files.len());
    Ok(())
}

fn run_backup_verify(backup_id: Option<String>) -> anyhow::Result<()> {
    let root = config::find_repo_root()?;
    let backup_id = resolve_backup_id(&root, backup_id.as_deref())?;
    verify_backup(&root, &backup_id)?;
    println!("Backup verified: {backup_id}");
    Ok(())
}

fn run_migrate_plan() -> anyhow::Result<()> {
    let root = config::find_repo_root()?;
    let plan = config::plan_config_migration(&root)?;
    println!("Migration plan -> {}", plan.target.display());
    if let Some(source) = plan.source {
        println!("  source: {}", source.display());
    } else {
        println!("  source: defaults");
    }
    println!("{}", plan.diff);
    Ok(())
}

fn run_migrate_apply(dry_run: bool) -> anyhow::Result<()> {
    let root = config::find_repo_root()?;
    let plan = config::plan_config_migration(&root)?;
    println!("Migration target: {}", plan.target.display());
    println!("{}", plan.diff);
    if dry_run {
        println!("Dry run complete. No files changed.");
        return Ok(());
    }

    let backup = create_backup(&root)?;
    let applied = config::apply_config_migration(&root)?;
    append_ledger(
        &root,
        LedgerEntry {
            timestamp_ms: now_ms(),
            action: "migrate.apply".to_string(),
            status: "ok".to_string(),
            details: serde_json::json!({
                "backup_id": backup.backup_id,
                "target": applied.target.display().to_string(),
            }),
        },
    )?;
    println!("Migration applied.");
    Ok(())
}

fn run_rollback_plan(backup_id: Option<String>) -> anyhow::Result<()> {
    let root = config::find_repo_root()?;
    let backup_id = resolve_backup_id(&root, backup_id.as_deref())?;
    verify_backup(&root, &backup_id)?;
    let snapshot = snapshot_dir(&root, &backup_id);
    let files = collect_relative_files(&snapshot)?;
    println!("Rollback plan from backup: {backup_id}");
    println!("  restore files: {}", files.len());
    Ok(())
}

fn run_rollback_execute(backup_id: Option<String>) -> anyhow::Result<()> {
    let root = config::find_repo_root()?;
    let backup_id = resolve_backup_id(&root, backup_id.as_deref())?;
    verify_backup(&root, &backup_id)?;
    restore_backup(&root, &backup_id)?;
    append_ledger(
        &root,
        LedgerEntry {
            timestamp_ms: now_ms(),
            action: "rollback.execute".to_string(),
            status: "ok".to_string(),
            details: serde_json::json!({"backup_id": backup_id}),
        },
    )?;
    println!("Rollback executed: {backup_id}");
    Ok(())
}

fn run_support_bundle(out: Option<PathBuf>) -> anyhow::Result<()> {
    let root = config::find_repo_root()?;
    let cfg = config::load_or_default_config(&root)?;
    let store = ClawStore::open(&root)?;

    let refs_count = store.list_refs("")?.len();
    let head = store.read_head().ok().map(|v| format!("{v:?}"));
    let latest_backup_id = resolve_backup_id(&root, None).ok();
    let request_id = format!("req_{}", now_ms());

    let bundle = SupportBundle {
        request_id: request_id.clone(),
        created_at_ms: now_ms(),
        repo_root: root.display().to_string(),
        config: cfg,
        head,
        refs_count,
        latest_backup_id,
    };

    let output_path = out.unwrap_or_else(|| {
        root.join(".claw")
            .join("support")
            .join(format!("support-bundle-{request_id}.json"))
    });
    if let Some(parent) = output_path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let content = serde_json::to_string_pretty(&bundle)?;
    std::fs::write(&output_path, content)?;

    append_ledger(
        &root,
        LedgerEntry {
            timestamp_ms: now_ms(),
            action: "support-bundle".to_string(),
            status: "ok".to_string(),
            details: serde_json::json!({"path": output_path.display().to_string()}),
        },
    )?;

    println!("Support bundle written: {}", output_path.display());
    Ok(())
}

fn create_backup(root: &Path) -> anyhow::Result<BackupManifest> {
    let backup_id = now_ms().to_string();
    let backup_root = backups_dir(root).join(&backup_id);
    let snapshot_root = backup_root.join("snapshot");
    std::fs::create_dir_all(&snapshot_root)?;

    let source = root.join(".claw");
    let mut entries = Vec::new();
    copy_tree_with_hashes(&source, &source, &snapshot_root, &mut entries)?;

    let manifest = BackupManifest {
        backup_id: backup_id.clone(),
        created_at_ms: now_ms(),
        files: entries,
    };
    let manifest_path = backup_root.join("manifest.json");
    std::fs::write(manifest_path, serde_json::to_vec_pretty(&manifest)?)?;
    Ok(manifest)
}

fn verify_backup(root: &Path, backup_id: &str) -> anyhow::Result<()> {
    let manifest_path = backups_dir(root).join(backup_id).join("manifest.json");
    let manifest: BackupManifest = serde_json::from_slice(&std::fs::read(&manifest_path)?)
        .map_err(|err| {
            anyhow::anyhow!("invalid backup manifest {}: {err}", manifest_path.display())
        })?;

    let snapshot = snapshot_dir(root, backup_id);
    for entry in &manifest.files {
        let path = snapshot.join(&entry.path);
        let bytes = std::fs::read(&path)
            .map_err(|err| anyhow::anyhow!("backup file missing {}: {err}", path.display()))?;
        if bytes.len() as u64 != entry.bytes {
            anyhow::bail!("backup size mismatch for {}", entry.path);
        }
        let hash = sha256_hex(&bytes);
        if hash != entry.sha256 {
            anyhow::bail!("backup checksum mismatch for {}", entry.path);
        }
    }
    Ok(())
}

fn restore_backup(root: &Path, backup_id: &str) -> anyhow::Result<()> {
    let snapshot = snapshot_dir(root, backup_id);
    let target = root.join(".claw");

    let snapshot_files = collect_relative_files(&snapshot)?;
    let target_files = collect_relative_files(&target)?;

    for rel in target_files.difference(&snapshot_files) {
        if rel.starts_with("backups/") {
            continue;
        }
        let path = target.join(rel);
        if path.is_file() {
            std::fs::remove_file(path)?;
        }
    }

    for rel in snapshot_files {
        if rel.starts_with("backups/") {
            continue;
        }
        let source = snapshot.join(&rel);
        let dest = target.join(&rel);
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::copy(source, dest)?;
    }

    Ok(())
}

fn copy_tree_with_hashes(
    source_root: &Path,
    current: &Path,
    destination_root: &Path,
    entries: &mut Vec<BackupEntry>,
) -> anyhow::Result<()> {
    let mut dir_entries: Vec<std::fs::DirEntry> =
        std::fs::read_dir(current)?.collect::<Result<_, _>>()?;
    dir_entries.sort_by_key(|entry| entry.file_name());

    for entry in dir_entries {
        let path = entry.path();
        let rel = path
            .strip_prefix(source_root)
            .map_err(|err| anyhow::anyhow!("backup path error: {err}"))?;

        if rel.starts_with("backups") {
            continue;
        }

        let dest = destination_root.join(rel);
        if entry.file_type()?.is_dir() {
            std::fs::create_dir_all(&dest)?;
            copy_tree_with_hashes(source_root, &path, destination_root, entries)?;
            continue;
        }

        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::copy(&path, &dest)?;
        let bytes = std::fs::read(&path)?;
        let rel_path = dest
            .strip_prefix(destination_root)
            .map_err(|err| anyhow::anyhow!("backup relative path error: {err}"))?
            .to_string_lossy()
            .replace('\\', "/");
        entries.push(BackupEntry {
            path: rel_path,
            bytes: bytes.len() as u64,
            sha256: sha256_hex(&bytes),
        });
    }

    Ok(())
}

fn collect_relative_files(root: &Path) -> anyhow::Result<BTreeSet<String>> {
    let mut out = BTreeSet::new();
    if !root.exists() {
        return Ok(out);
    }
    collect_relative_files_inner(root, root, &mut out)?;
    Ok(out)
}

fn collect_relative_files_inner(
    root: &Path,
    current: &Path,
    out: &mut BTreeSet<String>,
) -> anyhow::Result<()> {
    for entry in std::fs::read_dir(current)? {
        let entry = entry?;
        let path = entry.path();
        if entry.file_type()?.is_dir() {
            collect_relative_files_inner(root, &path, out)?;
            continue;
        }
        let rel = path
            .strip_prefix(root)
            .map_err(|err| anyhow::anyhow!("relative file path error: {err}"))?
            .to_string_lossy()
            .replace('\\', "/");
        out.insert(rel);
    }
    Ok(())
}

fn append_ledger(root: &Path, entry: LedgerEntry) -> anyhow::Result<()> {
    let path = root.join(".claw").join("migrations").join("ledger.jsonl");
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let mut line = serde_json::to_vec(&entry)?;
    line.push(b'\n');

    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    file.write_all(&line)?;
    Ok(())
}

fn backups_dir(root: &Path) -> PathBuf {
    root.join(".claw").join("backups")
}

fn snapshot_dir(root: &Path, backup_id: &str) -> PathBuf {
    backups_dir(root).join(backup_id).join("snapshot")
}

fn resolve_backup_id(root: &Path, backup_id: Option<&str>) -> anyhow::Result<String> {
    if let Some(id) = backup_id {
        return Ok(id.to_string());
    }

    let mut candidates = Vec::new();
    let dir = backups_dir(root);
    if dir.is_dir() {
        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            if entry.file_type()?.is_dir() {
                candidates.push(entry.file_name().to_string_lossy().to_string());
            }
        }
    }
    candidates.sort();
    candidates
        .pop()
        .ok_or_else(|| anyhow::anyhow!("no backups found"))
}

fn sha256_hex(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    hex::encode(hasher.finalize())
}

fn now_ms() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|dur| dur.as_millis() as u64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use super::{
        create_backup, evaluate_threshold, verify_backup, AdminArgs, AdminCommand, BackupCommand,
        MigrateCommand, RollbackCommand, ThresholdStatus,
    };

    #[derive(Parser)]
    struct TestCli {
        #[command(flatten)]
        args: AdminArgs,
    }

    #[test]
    fn parse_backup_verify_with_backup_id() {
        let cli = TestCli::parse_from(["claw", "backup", "verify", "--backup-id", "1700000000000"]);

        match cli.args.command {
            AdminCommand::Backup { command } => match command {
                BackupCommand::Verify { backup_id } => {
                    assert_eq!(backup_id.as_deref(), Some("1700000000000"));
                }
                _ => panic!("expected backup verify command"),
            },
            _ => panic!("expected backup command"),
        }
    }

    #[test]
    fn parse_migrate_apply_dry_run() {
        let cli = TestCli::parse_from(["claw", "migrate", "apply", "--dry-run"]);

        match cli.args.command {
            AdminCommand::Migrate { command } => match command {
                MigrateCommand::Apply { dry_run } => {
                    assert!(dry_run);
                }
                _ => panic!("expected migrate apply command"),
            },
            _ => panic!("expected migrate command"),
        }
    }

    #[test]
    fn parse_rollback_execute_with_backup_id() {
        let cli = TestCli::parse_from([
            "claw",
            "rollback",
            "execute",
            "--backup-id",
            "1700000000000",
        ]);

        match cli.args.command {
            AdminCommand::Rollback { command } => match command {
                RollbackCommand::Execute { backup_id } => {
                    assert_eq!(backup_id.as_deref(), Some("1700000000000"));
                }
                _ => panic!("expected rollback execute command"),
            },
            _ => panic!("expected rollback command"),
        }
    }

    #[test]
    fn backup_create_and_verify_happy_path() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let root = tmp.path();
        let claw_dir = root.join(".claw");

        std::fs::create_dir_all(claw_dir.join("refs")).expect("create refs");
        std::fs::create_dir_all(claw_dir.join("objects")).expect("create objects");
        std::fs::create_dir_all(claw_dir.join("backups").join("legacy").join("snapshot"))
            .expect("create legacy backup tree");

        std::fs::write(claw_dir.join("refs").join("heads_main"), b"main").expect("write ref");
        std::fs::write(claw_dir.join("objects").join("obj1"), b"payload").expect("write object");
        std::fs::write(
            claw_dir
                .join("backups")
                .join("legacy")
                .join("snapshot")
                .join("ignored.txt"),
            b"do-not-include",
        )
        .expect("write ignored backup file");

        let manifest = create_backup(root).expect("create backup");
        assert!(!manifest.files.is_empty());
        assert!(manifest
            .files
            .iter()
            .all(|entry| !entry.path.starts_with("backups/")));

        verify_backup(root, &manifest.backup_id).expect("verify backup");
    }

    #[test]
    fn threshold_evaluation_pass_at_warning_boundary() {
        let status = evaluate_threshold(8_192, 8_192, 1_024);
        assert_eq!(status, ThresholdStatus::Pass);
    }

    #[test]
    fn threshold_evaluation_warn_between_fail_and_warn() {
        let status = evaluate_threshold(4_096, 8_192, 1_024);
        assert_eq!(status, ThresholdStatus::Warn);
    }

    #[test]
    fn threshold_evaluation_fail_below_fail_threshold() {
        let status = evaluate_threshold(1_023, 8_192, 1_024);
        assert_eq!(status, ThresholdStatus::Fail);
    }
}