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
use std::path::Path;
use std::process::Command;

use clap::Args;
use serde::Serialize;

use claw_core::cof::{cof_decode, cof_encode};
use claw_core::object::Object;
use claw_core::types::Blob;
use claw_store::{ClawStore, HeadState};
use claw_sync::client::{RetryPolicy, SyncClient};
use claw_sync::protocol::{negotiated_protocol_version, SYNC_PROTOCOL_VERSION};
use claw_sync::transport::RemoteTransportConfig;

use crate::commands::remote::RemotesConfig;
use crate::config::find_repo_root;
use crate::{auth_store, commands::remote, config};

#[derive(Args)]
pub struct DoctorArgs {
    /// Output diagnostic report as JSON
    #[arg(long)]
    json: bool,
    /// Return a non-zero exit when any check reports an error
    #[arg(long)]
    strict: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
enum CheckStatus {
    Ok,
    Warning,
    Error,
    Skipped,
}

impl CheckStatus {
    fn label(self) -> &'static str {
        match self {
            CheckStatus::Ok => "ok",
            CheckStatus::Warning => "warning",
            CheckStatus::Error => "error",
            CheckStatus::Skipped => "skipped",
        }
    }
}

#[derive(Debug, Clone, Serialize)]
struct DoctorCheck {
    name: &'static str,
    status: CheckStatus,
    message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    remediation: Option<&'static str>,
}

#[derive(Debug, Clone, Default, Serialize)]
struct DoctorSummary {
    ok: usize,
    warnings: usize,
    errors: usize,
    skipped: usize,
}

#[derive(Debug, Clone, Serialize)]
struct DoctorReport {
    version: &'static str,
    cwd: Option<String>,
    repo_root: Option<String>,
    checks: Vec<DoctorCheck>,
    summary: DoctorSummary,
}

pub async fn run(args: DoctorArgs) -> anyhow::Result<()> {
    let report = build_report().await;

    if args.json {
        println!("{}", serde_json::to_string_pretty(&report)?);
    } else {
        print_human(&report);
    }

    if args.strict && report.summary.errors > 0 {
        anyhow::bail!("doctor found {} error(s)", report.summary.errors);
    }

    Ok(())
}

async fn build_report() -> DoctorReport {
    let mut checks = Vec::new();
    checks.push(check(
        "cli",
        CheckStatus::Ok,
        format!("claw {}", env!("CARGO_PKG_VERSION")),
        None,
    ));

    let cwd = match std::env::current_dir() {
        Ok(path) => {
            checks.push(check(
                "cwd",
                CheckStatus::Ok,
                path.display().to_string(),
                None,
            ));
            Some(path)
        }
        Err(err) => {
            checks.push(check(
                "cwd",
                CheckStatus::Error,
                format!("cannot read current directory: {err}"),
                Some("Check that the current directory still exists and is readable."),
            ));
            None
        }
    };

    add_git_check(&mut checks);
    add_object_format_check(&mut checks);

    let repo_root = match find_repo_root() {
        Ok(root) => {
            checks.push(check(
                "repository",
                CheckStatus::Ok,
                root.display().to_string(),
                None,
            ));
            Some(root)
        }
        Err(err) => {
            checks.push(check(
                "repository",
                CheckStatus::Warning,
                err.to_string(),
                Some("Run `claw init` here, or `cd` into an existing Claw repository."),
            ));
            None
        }
    };

    if let Some(root) = repo_root.as_deref() {
        add_layout_checks(root, &mut checks);
        add_config_check(root, &mut checks);
        add_store_checks(root, &mut checks);
        add_refs_validity_check(root, &mut checks);
        add_remote_check(root, &mut checks);
        add_daemon_reachability_check(root, &mut checks).await;
        add_daemon_auth_check(root, &mut checks);
        add_writable_check(root, &mut checks);
    } else {
        for name in [
            "layout",
            "config",
            "head",
            "refs",
            "remotes",
            "daemon_reachable",
            "daemon_auth",
            "writable",
        ] {
            checks.push(check(
                name,
                CheckStatus::Skipped,
                "requires a Claw repository".to_string(),
                None,
            ));
        }
    }

    let summary = summarize(&checks);
    DoctorReport {
        version: env!("CARGO_PKG_VERSION"),
        cwd: cwd.map(|path| path.display().to_string()),
        repo_root: repo_root.map(|path| path.display().to_string()),
        checks,
        summary,
    }
}

fn add_git_check(checks: &mut Vec<DoctorCheck>) {
    match Command::new("git").arg("--version").output() {
        Ok(output) if output.status.success() => {
            let version = String::from_utf8_lossy(&output.stdout).trim().to_string();
            checks.push(check(
                "git",
                CheckStatus::Ok,
                if version.is_empty() {
                    "git is available".to_string()
                } else {
                    version
                },
                None,
            ));
        }
        Ok(output) => checks.push(check(
            "git",
            CheckStatus::Warning,
            format!("git exited with status {}", output.status),
            Some("Install Git or fix PATH before using git import/export workflows."),
        )),
        Err(err) => checks.push(check(
            "git",
            CheckStatus::Warning,
            format!("git not available: {err}"),
            Some("Install Git or fix PATH before using git import/export workflows."),
        )),
    }
}

fn add_object_format_check(checks: &mut Vec<DoctorCheck>) {
    let object = Object::Blob(Blob {
        data: b"doctor".to_vec(),
        media_type: Some("text/plain".to_string()),
    });

    let result: anyhow::Result<()> = (|| {
        let payload = object.serialize_payload()?;
        let encoded = cof_encode(object.type_tag(), &payload)?;
        let (decoded_type, decoded_payload) = cof_decode(&encoded)?;
        if decoded_type == object.type_tag() && decoded_payload == payload {
            Ok(())
        } else {
            anyhow::bail!("COF roundtrip mismatch")
        }
    })();

    match result {
        Ok(()) => checks.push(check(
            "object_format",
            CheckStatus::Ok,
            "COF v1 encode/decode supported".to_string(),
            None,
        )),
        Err(err) => checks.push(check(
            "object_format",
            CheckStatus::Error,
            format!("COF v1 roundtrip failed: {err}"),
            Some("Reinstall the CLI or rebuild from a clean checkout."),
        )),
    }
}

fn add_layout_checks(root: &Path, checks: &mut Vec<DoctorCheck>) {
    let required = [
        root.join(".claw"),
        root.join(".claw").join("objects"),
        root.join(".claw").join("refs"),
        root.join(".claw").join("refs").join("heads"),
        root.join(".claw").join("HEAD"),
    ];

    let missing = required
        .iter()
        .filter(|path| !path.exists())
        .map(|path| {
            path.strip_prefix(root)
                .unwrap_or(path)
                .display()
                .to_string()
        })
        .collect::<Vec<_>>();

    if missing.is_empty() {
        checks.push(check(
            "layout",
            CheckStatus::Ok,
            ".claw layout has required paths".to_string(),
            None,
        ));
    } else {
        checks.push(check(
            "layout",
            CheckStatus::Error,
            format!("missing {}", missing.join(", ")),
            Some("Back up the repository, then repair by restoring these paths or reinitializing with `claw init` in a clean directory."),
        ));
    }
}

fn add_config_check(root: &Path, checks: &mut Vec<DoctorCheck>) {
    match config::load_or_default_config(root) {
        Ok(_) => {
            let config_path = config::config_file_path(root);
            let message = if config_path.exists() {
                format!("loaded {}", config_path.display())
            } else {
                "no .claw/config.toml; using built-in defaults".to_string()
            };
            checks.push(check("config", CheckStatus::Ok, message, None));
        }
        Err(err) => checks.push(check(
            "config",
            CheckStatus::Error,
            err.to_string(),
            Some("Fix .claw/config.toml, or run `claw admin migrate apply --dry-run` to preview the current migration output."),
        )),
    }
}

fn add_store_checks(root: &Path, checks: &mut Vec<DoctorCheck>) {
    let store = match ClawStore::open(root) {
        Ok(store) => store,
        Err(err) => {
            checks.push(check(
                "store",
                CheckStatus::Error,
                err.to_string(),
                Some("Confirm the .claw directory exists and is readable."),
            ));
            return;
        }
    };

    match store.read_head() {
        Ok(HeadState::Symbolic { ref_name }) => match store.resolve_head() {
            Ok(Some(id)) => checks.push(check(
                "head",
                CheckStatus::Ok,
                format!("{ref_name} -> {id}"),
                None,
            )),
            Ok(None) => checks.push(check(
                "head",
                CheckStatus::Warning,
                format!("{ref_name} has no commits yet"),
                Some("Create the first revision with `claw snapshot -m \"initial snapshot\"`."),
            )),
            Err(err) => checks.push(check(
                "head",
                CheckStatus::Error,
                err.to_string(),
                Some("Inspect .claw/HEAD and the matching file under .claw/refs."),
            )),
        },
        Ok(HeadState::Detached { target }) => checks.push(check(
            "head",
            CheckStatus::Ok,
            format!("detached at {target}"),
            None,
        )),
        Err(err) => checks.push(check(
            "head",
            CheckStatus::Error,
            err.to_string(),
            Some("Inspect .claw/HEAD and restore it to `ref: heads/main` if needed."),
        )),
    }
}

fn add_refs_validity_check(root: &Path, checks: &mut Vec<DoctorCheck>) {
    let store = match ClawStore::open(root) {
        Ok(store) => store,
        Err(err) => {
            checks.push(check(
                "refs",
                CheckStatus::Skipped,
                format!("store unavailable: {err}"),
                None,
            ));
            return;
        }
    };

    let refs = match store.list_refs("") {
        Ok(refs) => refs,
        Err(err) => {
            checks.push(check(
                "refs",
                CheckStatus::Error,
                err.to_string(),
                Some("Inspect .claw/refs for invalid names or object IDs."),
            ));
            return;
        }
    };

    let missing = refs
        .iter()
        .filter(|(_, id)| !store.has_object(id))
        .map(|(name, id)| format!("{name}->{id}"))
        .collect::<Vec<_>>();

    if missing.is_empty() {
        checks.push(check(
            "refs",
            CheckStatus::Ok,
            format!("{} ref(s) point to local objects", refs.len()),
            None,
        ));
    } else {
        checks.push(check(
            "refs",
            CheckStatus::Error,
            format!("missing object(s): {}", missing.join(", ")),
            Some("Restore missing objects from backup or repoint/delete the invalid refs."),
        ));
    }
}

fn add_remote_check(root: &Path, checks: &mut Vec<DoctorCheck>) {
    let config_path = root.join(".claw").join("remotes.toml");
    if !config_path.exists() {
        checks.push(check(
            "remotes",
            CheckStatus::Ok,
            "no remotes configured".to_string(),
            None,
        ));
        return;
    }

    match std::fs::read_to_string(&config_path)
        .ok()
        .and_then(|content| toml::from_str::<RemotesConfig>(&content).ok())
    {
        Some(config) => checks.push(check(
            "remotes",
            CheckStatus::Ok,
            format!("{} remote(s) configured", config.remotes.len()),
            None,
        )),
        None => checks.push(check(
            "remotes",
            CheckStatus::Error,
            format!("invalid {}", config_path.display()),
            Some("Fix .claw/remotes.toml, or remove and recreate remotes with `claw remote add`."),
        )),
    }
}

async fn add_daemon_reachability_check(root: &Path, checks: &mut Vec<DoctorCheck>) {
    let config_path = root.join(".claw").join("remotes.toml");
    if !config_path.exists() {
        checks.push(check(
            "daemon_reachable",
            CheckStatus::Skipped,
            "no remotes configured".to_string(),
            Some("Add a daemon remote with `claw remote add origin <url>` if this repository should sync."),
        ));
        return;
    }

    let config = match std::fs::read_to_string(&config_path)
        .ok()
        .and_then(|content| toml::from_str::<RemotesConfig>(&content).ok())
    {
        Some(config) => config,
        None => {
            checks.push(check(
                "daemon_reachable",
                CheckStatus::Skipped,
                format!("invalid {}; remote reachability not checked", config_path.display()),
                Some("Fix .claw/remotes.toml, or remove and recreate remotes with `claw remote add`."),
            ));
            return;
        }
    };

    if config.remotes.is_empty() {
        checks.push(check(
            "daemon_reachable",
            CheckStatus::Skipped,
            "no remotes configured".to_string(),
            Some("Add a daemon remote with `claw remote add origin <url>` if this repository should sync."),
        ));
        return;
    }

    let mut messages = Vec::new();
    let mut has_warning = false;

    for name in config.remotes.keys() {
        match probe_remote(root, name).await {
            Ok(message) => messages.push(format!("{name}: {message}")),
            Err(err) => {
                has_warning = true;
                messages.push(format!("{name}: unreachable ({err})"));
            }
        }
    }

    checks.push(check(
        "daemon_reachable",
        if has_warning {
            CheckStatus::Warning
        } else {
            CheckStatus::Ok
        },
        messages.join("; "),
        if has_warning {
            Some("Start the configured daemon, fix the remote URL/TLS/auth settings, or remove stale remotes with `claw remote remove`.")
        } else {
            None
        },
    ));
}

async fn probe_remote(root: &Path, name: &str) -> anyhow::Result<String> {
    let resolved = remote::resolve_remote(root, name)?;
    let transport = match resolved {
        remote::ResolvedRemote::Grpc {
            addr,
            token_profile,
        } => RemoteTransportConfig::Grpc {
            addr,
            bearer_token: token_profile
                .as_deref()
                .and_then(|profile| auth_store::resolve_access_token(Some(profile))),
            tls: None,
        },
        remote::ResolvedRemote::ClawLab {
            base_url,
            repo,
            token_profile,
        } => RemoteTransportConfig::Http {
            base_url,
            repo,
            bearer_token: auth_store::resolve_access_token(token_profile.as_deref()),
        },
    };

    let probe = async move {
        let mut client = SyncClient::connect_with_transport_and_retry(
            transport,
            RetryPolicy {
                max_attempts: 1,
                ..RetryPolicy::default()
            },
        )
        .await?;
        let hello = client.hello().await?;
        let protocol = negotiated_protocol_version(&hello.capabilities)
            .map(str::to_string)
            .unwrap_or_else(|| "missing protocol marker".to_string());
        if protocol == SYNC_PROTOCOL_VERSION {
            Ok(format!(
                "reachable, server {}, protocol {}",
                hello.server_version, protocol
            ))
        } else {
            Ok(format!(
                "reachable, server {}, protocol {} (expected {})",
                hello.server_version, protocol, SYNC_PROTOCOL_VERSION
            ))
        }
    };

    tokio::time::timeout(std::time::Duration::from_secs(2), probe)
        .await
        .map_err(|_| anyhow::anyhow!("probe timed out after 2s"))?
}

fn add_daemon_auth_check(root: &Path, checks: &mut Vec<DoctorCheck>) {
    let cfg = match config::load_or_default_config(root) {
        Ok(cfg) => cfg,
        Err(err) => {
            checks.push(check(
                "daemon_auth",
                CheckStatus::Skipped,
                format!("requires valid config: {err}"),
                None,
            ));
            return;
        }
    };

    let mut warnings = Vec::new();
    if cfg.auth.require_auth_for_daemon {
        let profile = config::default_profile(&cfg);
        if auth_store::resolve_access_token(Some(profile)).is_some() {
            warnings.push(format!(
                "auth required; token profile '{profile}' is present"
            ));
        } else {
            warnings.push(format!(
                "auth required; token profile '{profile}' is missing"
            ));
        }
    } else {
        warnings.push("daemon auth is not required by config".to_string());
    }

    if cfg.tls.require_for_non_localhost {
        match (cfg.tls.cert_path.as_deref(), cfg.tls.key_path.as_deref()) {
            (Some(cert), Some(key))
                if config_path_exists(root, cert) && config_path_exists(root, key) =>
            {
                warnings.push("TLS required; cert/key paths exist".to_string());
            }
            (Some(_), Some(_)) => {
                warnings.push("TLS required; cert/key path missing".to_string());
            }
            _ => {
                warnings.push("TLS required for non-localhost; cert/key not configured".to_string())
            }
        }
    } else {
        warnings.push("TLS is not required for non-localhost by config".to_string());
    }

    let status = if warnings.iter().any(|message| {
        message.contains("missing")
            || message.contains("not configured")
            || message.contains("not required")
    }) {
        CheckStatus::Warning
    } else {
        CheckStatus::Ok
    };

    checks.push(check(
        "daemon_auth",
        status,
        warnings.join("; "),
        if status == CheckStatus::Warning {
            Some("For production daemons, configure auth tokens and TLS certificate/key paths before binding beyond localhost.")
        } else {
            None
        },
    ));
}

fn config_path_exists(root: &Path, value: &str) -> bool {
    let path = Path::new(value);
    if path.is_absolute() {
        path.exists()
    } else {
        root.join(path).exists()
    }
}

fn add_writable_check(root: &Path, checks: &mut Vec<DoctorCheck>) {
    let claw_dir = root.join(".claw");
    match std::fs::metadata(&claw_dir) {
        Ok(metadata) if metadata.permissions().readonly() => checks.push(check(
            "writable",
            CheckStatus::Error,
            format!("{} is read-only", claw_dir.display()),
            Some(
                "Make the repository writable before running commands that update refs or objects.",
            ),
        )),
        Ok(_) => checks.push(check(
            "writable",
            CheckStatus::Ok,
            ".claw is writable by permission bits".to_string(),
            None,
        )),
        Err(err) => checks.push(check(
            "writable",
            CheckStatus::Error,
            err.to_string(),
            Some("Confirm the .claw directory exists and is readable."),
        )),
    }
}

fn check(
    name: &'static str,
    status: CheckStatus,
    message: String,
    remediation: Option<&'static str>,
) -> DoctorCheck {
    DoctorCheck {
        name,
        status,
        message,
        remediation,
    }
}

fn summarize(checks: &[DoctorCheck]) -> DoctorSummary {
    let mut summary = DoctorSummary::default();
    for check in checks {
        match check.status {
            CheckStatus::Ok => summary.ok += 1,
            CheckStatus::Warning => summary.warnings += 1,
            CheckStatus::Error => summary.errors += 1,
            CheckStatus::Skipped => summary.skipped += 1,
        }
    }
    summary
}

fn print_human(report: &DoctorReport) {
    println!("Claw doctor");
    for check in &report.checks {
        println!(
            "  {status:<8} {name:<12} {message}",
            status = check.status.label(),
            name = check.name,
            message = check.message
        );
        if let Some(remediation) = check.remediation {
            println!("           hint: {remediation}");
        }
    }
    println!(
        "Summary: {} ok, {} warning(s), {} error(s), {} skipped",
        report.summary.ok, report.summary.warnings, report.summary.errors, report.summary.skipped
    );
}

#[cfg(test)]
mod tests {
    use super::{check, summarize, CheckStatus};

    #[test]
    fn summary_counts_statuses() {
        let checks = vec![
            check("a", CheckStatus::Ok, "ok".to_string(), None),
            check("b", CheckStatus::Warning, "warn".to_string(), None),
            check("c", CheckStatus::Error, "err".to_string(), None),
            check("d", CheckStatus::Skipped, "skip".to_string(), None),
        ];

        let summary = summarize(&checks);
        assert_eq!(summary.ok, 1);
        assert_eq!(summary.warnings, 1);
        assert_eq!(summary.errors, 1);
        assert_eq!(summary.skipped, 1);
    }
}