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
use clap::{Args, Subcommand};
use std::path::{Path, PathBuf};

use claw_core::id::ObjectId;
use claw_core::object::Object;
use claw_store::{ClawStore, HeadState};
use claw_sync::client::{RetryPolicy, SyncClient};
use claw_sync::compat::{compatibility_report, CompatibilityLevel};
use claw_sync::negotiation::ordered_reachable_objects;
use claw_sync::proto::sync::HelloResponse;
use claw_sync::protocol::{negotiated_protocol_version, SYNC_PROTOCOL_VERSION};
use claw_sync::transport::{GrpcTlsConfig, RemoteTransportConfig};

use crate::auth_store;
use crate::config::{self, find_repo_root};
use crate::worktree;

use super::{remote, RuntimeOptions};

const CLI_VERSION: &str = env!("CARGO_PKG_VERSION");

fn resolve_token_profiles(
    token_profile: Option<&str>,
    runtime_profile: &str,
    repo_default_profile: &str,
) -> Vec<String> {
    let explicit_profile = token_profile
        .map(str::trim)
        .filter(|value| !value.is_empty());
    if let Some(profile) = explicit_profile {
        return vec![profile.to_string()];
    }

    let mut profiles = Vec::new();
    let runtime_profile = runtime_profile.trim();
    if !runtime_profile.is_empty() {
        profiles.push(runtime_profile.to_string());
    }

    let repo_default_profile = repo_default_profile.trim();
    if !repo_default_profile.is_empty() && !profiles.iter().any(|p| p == repo_default_profile) {
        profiles.push(repo_default_profile.to_string());
    }

    if profiles.is_empty() {
        profiles.push("default".to_string());
    }

    profiles
}

fn require_access_token(
    token_profile: Option<&str>,
    runtime_profile: &str,
    repo_default_profile: &str,
) -> anyhow::Result<String> {
    let candidates = resolve_token_profiles(token_profile, runtime_profile, repo_default_profile);
    for profile_name in &candidates {
        if let Some(token) = auth_store::resolve_access_token(Some(profile_name)) {
            return Ok(token);
        }
    }

    let suggested_profile = candidates
        .first()
        .cloned()
        .unwrap_or_else(|| "default".to_string());
    anyhow::bail!(
        "no token found for profiles [{}]; run `claw auth login --profile {}`",
        candidates.join(", "),
        suggested_profile
    );
}

#[derive(Args)]
pub struct SyncArgs {
    /// Trust this PEM CA certificate when connecting to gRPC remotes over TLS
    #[arg(long)]
    tls_ca_cert: Option<PathBuf>,
    /// Override the TLS server name used for gRPC certificate verification
    #[arg(long)]
    tls_domain: Option<String>,
    /// PEM client certificate for mutual TLS with gRPC remotes
    #[arg(long)]
    client_cert: Option<PathBuf>,
    /// PEM client private key for mutual TLS with gRPC remotes
    #[arg(long)]
    client_key: Option<PathBuf>,
    #[command(subcommand)]
    command: Option<SyncCommand>,
    /// Remote name or address (compatibility form: `claw sync <remote>`)
    remote: Option<String>,
}

#[derive(Subcommand)]
enum SyncCommand {
    /// Push objects to remote
    Push {
        /// Remote name or address (e.g., origin or http://localhost:50051)
        #[arg(short, long, default_value = "origin")]
        remote: String,
        /// Ref to push
        #[arg(short = 'b', long, default_value = "heads/main")]
        ref_name: String,
        /// Force non-fast-forward push
        #[arg(long)]
        force: bool,
        /// Preview objects and ref update without uploading or mutating remote refs
        #[arg(long)]
        dry_run: bool,
    },
    /// Pull objects from remote
    Pull {
        /// Remote name or address
        #[arg(short, long, default_value = "origin")]
        remote: String,
        /// Ref to pull
        #[arg(short = 'b', long, default_value = "heads/main")]
        ref_name: String,
        /// Force non-fast-forward update
        #[arg(long)]
        force: bool,
    },
    /// Clone a remote repository
    Clone {
        /// Remote address
        remote: String,
        /// Transport kind (grpc|clawlab)
        #[arg(long, default_value = "grpc")]
        kind: String,
        /// Repository slug for clawlab remotes
        #[arg(long)]
        repo: Option<String>,
        /// Auth profile for clawlab remotes
        #[arg(long)]
        token_profile: Option<String>,
        /// Local path
        #[arg(default_value = ".")]
        path: String,
    },
}

fn resolve_command(args: SyncArgs) -> SyncCommand {
    match args.command {
        Some(command) => command,
        None => SyncCommand::Pull {
            remote: args.remote.unwrap_or_else(|| "origin".to_string()),
            ref_name: "heads/main".to_string(),
            force: false,
        },
    }
}

async fn connect_from_remote(
    root: &Path,
    remote_arg: &str,
    runtime: &RuntimeOptions,
    grpc_tls: Option<GrpcTlsConfig>,
) -> anyhow::Result<SyncClient> {
    let resolved = remote::resolve_remote(root, remote_arg)?;
    let cfg = config::load_or_default_config(root)?;
    let repo_default_profile = config::default_profile(&cfg);
    let transport = match resolved {
        remote::ResolvedRemote::Grpc {
            addr,
            token_profile,
        } => {
            let bearer_token = token_profile
                .as_deref()
                .map(|profile| {
                    require_access_token(Some(profile), &runtime.profile, repo_default_profile)
                })
                .transpose()?;
            RemoteTransportConfig::Grpc {
                addr,
                bearer_token,
                tls: grpc_tls,
            }
        }
        remote::ResolvedRemote::ClawLab {
            base_url,
            repo,
            token_profile,
        } => {
            let token = require_access_token(
                token_profile.as_deref(),
                &runtime.profile,
                repo_default_profile,
            )?;
            RemoteTransportConfig::Http {
                base_url,
                repo,
                bearer_token: Some(token),
            }
        }
    };

    let retry_policy = RetryPolicy {
        idempotent_only: cfg.retries.idempotent_only,
        max_attempts: cfg.retries.max_attempts,
        base_backoff_ms: cfg.retries.base_backoff_ms,
        max_backoff_ms: cfg.retries.max_backoff_ms,
        jitter: cfg.retries.jitter,
    };

    let client = SyncClient::connect_with_transport_and_retry(transport, retry_policy).await?;
    Ok(client)
}

fn load_optional_pem(path: Option<&Path>) -> anyhow::Result<Option<Vec<u8>>> {
    path.map(std::fs::read).transpose().map_err(Into::into)
}

fn build_grpc_tls_config(args: &SyncArgs) -> anyhow::Result<Option<GrpcTlsConfig>> {
    if args.client_cert.is_some() != args.client_key.is_some() {
        anyhow::bail!("--client-cert and --client-key must be provided together");
    }

    if args.tls_ca_cert.is_none()
        && args.tls_domain.is_none()
        && args.client_cert.is_none()
        && args.client_key.is_none()
    {
        return Ok(None);
    }

    Ok(Some(GrpcTlsConfig {
        ca_cert_pem: load_optional_pem(args.tls_ca_cert.as_deref())?,
        client_cert_pem: load_optional_pem(args.client_cert.as_deref())?,
        client_key_pem: load_optional_pem(args.client_key.as_deref())?,
        domain_name: args.tls_domain.clone(),
    }))
}

fn check_remote_compatibility(remote: &str, hello: &HelloResponse) -> anyhow::Result<()> {
    let report = compatibility_report(CLI_VERSION, &hello.server_version);
    let protocol = negotiated_protocol_version(&hello.capabilities);
    if protocol != Some(SYNC_PROTOCOL_VERSION) {
        anyhow::bail!(
            "protocol negotiation failed for {remote}: expected {expected}, got capabilities [{caps}]",
            expected = SYNC_PROTOCOL_VERSION,
            caps = hello.capabilities.join(", "),
        );
    }

    match report.level {
        CompatibilityLevel::Full => Ok(()),
        CompatibilityLevel::Limited => {
            eprintln!(
                "compatibility check: limited support for {remote} (local {local}, remote {remote_ver}); N/N-1 compatibility applies, but prefer matching versions for best results",
                local = report.local,
                remote_ver = report.remote,
            );
            Ok(())
        }
        CompatibilityLevel::Unsupported => anyhow::bail!(
            "compatibility check failed for {remote}: local claw version '{local}' is incompatible with remote version '{remote_ver}'; use matching major version and at most one minor difference (N/N-1), or retry with --no-compat-check only after verifying the risk",
            local = report.local,
            remote_ver = report.remote,
        ),
    }
}

async fn maybe_check_compatibility(
    runtime: &RuntimeOptions,
    remote: &str,
    client: &mut SyncClient,
) -> anyhow::Result<()> {
    if runtime.compat_check {
        let hello = client.hello().await?;
        check_remote_compatibility(remote, &hello)?;
    }

    Ok(())
}

pub async fn run(args: SyncArgs, runtime: &RuntimeOptions) -> anyhow::Result<()> {
    let grpc_tls = build_grpc_tls_config(&args)?;
    match resolve_command(args) {
        SyncCommand::Push {
            remote,
            ref_name,
            force,
            dry_run,
        } => {
            let root = find_repo_root()?;
            let store = ClawStore::open(&root)?;
            let mut client = connect_from_remote(&root, &remote, runtime, grpc_tls.clone()).await?;
            maybe_check_compatibility(runtime, &remote, &mut client).await?;

            let local_id = store
                .get_ref(&ref_name)?
                .ok_or_else(|| anyhow::anyhow!("ref not found: {ref_name}"))?;

            let push_ids: Vec<ObjectId> = ordered_reachable_objects(&store, &[local_id]);

            let remote_refs = client.advertise_refs("").await?;
            let remote_old = remote_refs
                .iter()
                .find(|(name, _)| name == &ref_name)
                .map(|(_, id)| *id);

            let updates = vec![(ref_name.clone(), remote_old, local_id)];
            if dry_run {
                println!(
                    "Dry run: would push {} object(s) to {}.",
                    push_ids.len(),
                    remote
                );
                match remote_old {
                    Some(old) => println!("  Ref update: {ref_name} {old} -> {local_id}"),
                    None => println!("  Ref create: {ref_name} -> {local_id}"),
                }
                if force {
                    println!("  Force: true");
                }
                println!("  Object upload skipped.");
                println!("  Remote ref update skipped.");
                return Ok(());
            }

            let resp = client.push_objects(&store, &push_ids).await?;
            println!("Push: {}", resp.message);

            let ref_resp = client.update_refs(&updates, force).await?;

            if ref_resp.success {
                println!("Pushed {} to {}", ref_name, remote);
            } else {
                anyhow::bail!("ref update failed: {}", ref_resp.message);
            }
        }
        SyncCommand::Pull {
            remote,
            ref_name,
            force,
        } => {
            let root = find_repo_root()?;
            let store = ClawStore::open(&root)?;
            let mut client = connect_from_remote(&root, &remote, runtime, grpc_tls.clone()).await?;
            maybe_check_compatibility(runtime, &remote, &mut client).await?;

            let remote_refs = client.advertise_refs("").await?;
            let remote_target = remote_refs
                .iter()
                .find(|(name, _)| name == &ref_name)
                .map(|(_, id)| *id);

            let remote_id = match remote_target {
                Some(id) => id,
                None => {
                    println!("Remote ref {ref_name} not found");
                    return Ok(());
                }
            };

            let local_id = store.get_ref(&ref_name)?;
            let have: Vec<ObjectId> = local_id.into_iter().collect();

            let fetched = client.fetch_objects(&store, &[remote_id], &have).await?;
            println!("Fetched {} objects", fetched.len());

            if let Some(local) = store.get_ref(&ref_name)? {
                let is_ff = claw_sync::ancestry::is_ancestor(&store, &local, &remote_id);
                if !is_ff && !force {
                    anyhow::bail!(
                        "non-fast-forward update on {}; use --force to override",
                        ref_name
                    );
                }
            }

            let old = store.get_ref(&ref_name)?;
            store.update_ref_cas(&ref_name, old.as_ref(), &remote_id, "sync", "pull")?;
            println!("Updated {} to {}", ref_name, remote_id);

            let head_state = store.read_head()?;
            if let HeadState::Symbolic {
                ref_name: ref head_ref,
            } = head_state
            {
                if *head_ref == ref_name {
                    let rev_obj = store.load_object(&remote_id)?;
                    if let Object::Revision(ref rev) = rev_obj {
                        if let Some(ref tree_id) = rev.tree {
                            worktree::materialize_tree(&store, tree_id, &root)?;
                            println!("Working tree updated.");
                        }
                    }
                }
            }
        }
        SyncCommand::Clone {
            remote,
            kind,
            repo,
            token_profile,
            path,
        } => {
            let root = std::path::Path::new(&path);
            let store = ClawStore::init(root)?;
            let cfg = config::load_or_default_config(root)?;
            let repo_default_profile = config::default_profile(&cfg);
            let retry_policy = RetryPolicy {
                idempotent_only: cfg.retries.idempotent_only,
                max_attempts: cfg.retries.max_attempts,
                base_backoff_ms: cfg.retries.base_backoff_ms,
                max_backoff_ms: cfg.retries.max_backoff_ms,
                jitter: cfg.retries.jitter,
            };
            let mut client = match kind.as_str() {
                "grpc" => {
                    let bearer_token = token_profile
                        .as_deref()
                        .map(|profile| {
                            require_access_token(
                                Some(profile),
                                &runtime.profile,
                                repo_default_profile,
                            )
                        })
                        .transpose()?;
                    SyncClient::connect_with_transport_and_retry(
                        RemoteTransportConfig::Grpc {
                            addr: remote.clone(),
                            bearer_token,
                            tls: grpc_tls.clone(),
                        },
                        retry_policy,
                    )
                    .await?
                }
                "clawlab" => {
                    let repo_slug = repo.clone().ok_or_else(|| {
                        anyhow::anyhow!(
                            "--repo is required for --kind clawlab (example: acme/widgets)"
                        )
                    })?;
                    let token = require_access_token(
                        token_profile.as_deref(),
                        &runtime.profile,
                        repo_default_profile,
                    )?;
                    SyncClient::connect_with_transport_and_retry(
                        RemoteTransportConfig::Http {
                            base_url: remote.clone(),
                            repo: repo_slug,
                            bearer_token: Some(token),
                        },
                        retry_policy,
                    )
                    .await?
                }
                other => anyhow::bail!("unsupported --kind: {other} (expected grpc|clawlab)"),
            };

            let hello = client.hello().await?;
            if runtime.compat_check {
                check_remote_compatibility(&remote, &hello)?;
            }
            let remote_refs = client.advertise_refs("").await?;

            let want: Vec<_> = remote_refs.iter().map(|(_, id)| *id).collect();
            let fetched = client.fetch_objects(&store, &want, &[]).await?;

            for (name, id) in &remote_refs {
                store.set_ref(name, id)?;
            }

            store.write_head(&HeadState::Symbolic {
                ref_name: "heads/main".to_string(),
            })?;

            let main_id = store.get_ref("heads/main")?;
            let checkout_id = main_id.or_else(|| remote_refs.first().map(|(_, id)| *id));
            if let Some(rev_id) = checkout_id {
                let rev_obj = store.load_object(&rev_id)?;
                if let Object::Revision(ref rev) = rev_obj {
                    if let Some(ref tree_id) = rev.tree {
                        worktree::materialize_tree(&store, tree_id, root)?;
                    }
                }
            }

            let config_path = root.join(".claw").join("remotes.toml");
            let mut remotes = remote::load_remotes(&config_path);
            let origin_entry = match kind.as_str() {
                "grpc" => remote::RemoteEntry {
                    kind: Some("grpc".to_string()),
                    url: Some(remote.clone()),
                    token_profile: token_profile.clone(),
                    ..remote::RemoteEntry::default()
                },
                "clawlab" => remote::RemoteEntry {
                    kind: Some("clawlab".to_string()),
                    base_url: Some(remote.clone()),
                    repo: repo.clone(),
                    token_profile: token_profile.clone(),
                    ..remote::RemoteEntry::default()
                },
                _ => remote::RemoteEntry::default(),
            };
            remotes.remotes.insert("origin".to_string(), origin_entry);
            let content = toml::to_string_pretty(&remotes)?;
            std::fs::write(&config_path, content)?;

            println!(
                "Cloned {} ({} objects, {} refs)",
                remote,
                fetched.len(),
                remote_refs.len()
            );
        }
    }
    Ok(())
}

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

    use super::{
        build_grpc_tls_config, check_remote_compatibility, resolve_command, resolve_token_profiles,
        SyncArgs, SyncCommand, CLI_VERSION,
    };
    use claw_sync::proto::sync::HelloResponse;
    use claw_sync::protocol::CAP_PROTOCOL_V1;

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

    #[test]
    fn parse_compat_remote_form() {
        let cli = TestCli::parse_from(["claw", "origin"]);

        match resolve_command(cli.args) {
            SyncCommand::Pull {
                remote,
                ref_name,
                force,
            } => {
                assert_eq!(remote, "origin");
                assert_eq!(ref_name, "heads/main");
                assert!(!force);
            }
            _ => panic!("expected pull command"),
        }
    }

    #[test]
    fn parse_pull_subcommand_form() {
        let cli = TestCli::parse_from(["claw", "pull", "--remote", "upstream"]);

        match resolve_command(cli.args) {
            SyncCommand::Pull {
                remote,
                ref_name,
                force,
            } => {
                assert_eq!(remote, "upstream");
                assert_eq!(ref_name, "heads/main");
                assert!(!force);
            }
            _ => panic!("expected pull command"),
        }
    }

    #[test]
    fn parse_push_dry_run() {
        let cli = TestCli::parse_from(["claw", "push", "--remote", "origin", "--dry-run"]);

        match resolve_command(cli.args) {
            SyncCommand::Push {
                remote,
                ref_name,
                force,
                dry_run,
            } => {
                assert_eq!(remote, "origin");
                assert_eq!(ref_name, "heads/main");
                assert!(!force);
                assert!(dry_run);
            }
            _ => panic!("expected push command"),
        }
    }

    #[test]
    fn parse_sync_without_remote_defaults_to_origin() {
        let cli = TestCli::parse_from(["claw"]);

        match resolve_command(cli.args) {
            SyncCommand::Pull {
                remote,
                ref_name,
                force,
            } => {
                assert_eq!(remote, "origin");
                assert_eq!(ref_name, "heads/main");
                assert!(!force);
            }
            _ => panic!("expected pull command"),
        }
    }

    #[test]
    fn compat_check_accepts_matching_version() {
        let hello = HelloResponse {
            server_version: CLI_VERSION.to_string(),
            capabilities: vec![CAP_PROTOCOL_V1.to_string(), "partial-clone".to_string()],
        };

        check_remote_compatibility("origin", &hello).expect("expected compatible versions");
    }

    #[test]
    fn compat_check_accepts_n_minus_one_minor_version() {
        let mut parts = CLI_VERSION.split('.');
        let major: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
        let minor: u64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
        let n_minus_one = minor.saturating_sub(1);
        let hello = HelloResponse {
            server_version: format!("{major}.{n_minus_one}.99"),
            capabilities: vec![CAP_PROTOCOL_V1.to_string(), "partial-clone".to_string()],
        };

        check_remote_compatibility("origin", &hello)
            .expect("N/N-1 compatibility should be accepted");
    }

    #[test]
    fn compat_check_rejects_unsupported_version_gap() {
        let hello = HelloResponse {
            server_version: "9.9.9".to_string(),
            capabilities: vec![CAP_PROTOCOL_V1.to_string(), "partial-clone".to_string()],
        };

        let err = check_remote_compatibility("origin", &hello).expect_err("expected mismatch");
        let message = err.to_string();
        assert!(message.contains("compatibility check failed"));
        assert!(message.contains("incompatible"));
        assert!(message.contains("N/N-1"));
        assert!(message.contains("--no-compat-check"));
    }

    #[test]
    fn compat_check_rejects_missing_protocol_marker() {
        let hello = HelloResponse {
            server_version: CLI_VERSION.to_string(),
            capabilities: vec!["partial-clone".to_string()],
        };

        let err =
            check_remote_compatibility("origin", &hello).expect_err("expected protocol mismatch");
        assert!(err.to_string().contains("protocol negotiation failed"));
    }

    #[test]
    fn parse_sync_mtls_flags() {
        let cli = TestCli::parse_from([
            "claw",
            "--tls-ca-cert",
            "ca.pem",
            "--tls-domain",
            "claw.example",
            "--client-cert",
            "client.pem",
            "--client-key",
            "client-key.pem",
            "push",
        ]);

        assert_eq!(
            cli.args.tls_ca_cert.as_deref(),
            Some(std::path::Path::new("ca.pem"))
        );
        assert_eq!(cli.args.tls_domain.as_deref(), Some("claw.example"));
        assert_eq!(
            cli.args.client_cert.as_deref(),
            Some(std::path::Path::new("client.pem"))
        );
        assert_eq!(
            cli.args.client_key.as_deref(),
            Some(std::path::Path::new("client-key.pem"))
        );
    }

    #[test]
    fn mtls_config_requires_cert_and_key_pair() {
        let cli = TestCli::parse_from(["claw", "--client-cert", "client.pem", "pull"]);

        let err = build_grpc_tls_config(&cli.args).expect_err("missing key should fail");
        assert!(err.to_string().contains("--client-cert and --client-key"));
    }

    #[test]
    fn resolve_token_profiles_prefers_explicit_profile() {
        let profiles = resolve_token_profiles(Some("team-ci"), "prod", "default");

        assert_eq!(profiles, vec!["team-ci"]);
    }

    #[test]
    fn resolve_token_profiles_uses_runtime_then_repo_default_when_omitted() {
        let profiles = resolve_token_profiles(None, "prod", "default");

        assert_eq!(profiles, vec!["prod", "default"]);
    }

    #[test]
    fn resolve_token_profiles_deduplicates_runtime_and_repo_default() {
        let profiles = resolve_token_profiles(None, "default", "default");

        assert_eq!(profiles, vec!["default"]);
    }
}