gitflow-cli 2.0.0

跨平台 Git 工程化工作流编排框架:统一封装 GitHub / GitLab / GitCode 三大平台,配合 AI Agent Skills,覆盖从需求到发布的完整工程循环。
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
//! gf CLI entrypoint.
//!
//! Provides a subcommand-based CLI with:
//! - TTY-aware tracing (human-readable for terminals, JSON for pipes)
//! - `NO_COLOR` / `CLICOLOR_FORCE` support
//! - SIGPIPE reset on Unix for clean pipe-exit behaviour
//! - Graceful shutdown via `tokio::signal`
//! - Top-level error display with `miette` formatting

// Tests legitimately need to unwrap fixture data and invoke sync FS helpers.
#![cfg_attr(
    test,
    allow(
        clippy::expect_used,
        clippy::unwrap_used,
        clippy::indexing_slicing,
        clippy::disallowed_methods,
        reason = "Tests legitimately need to unwrap fixture data and invoke sync FS helpers"
    )
)]

/// Build-time metadata generated by the `built` crate.
///
/// Exposes `PKG_VERSION`, `TARGET`, and similar constants. Does **not**
/// expose git information — the `built` crate's `git2` feature is
/// intentionally not enabled (see `build_git` module for the lightweight
/// alternative this binary uses instead). Unused fields are expected
/// because the `built` crate generates a fixed set of metadata regardless
/// of what the binary actually reads.
///
/// The lint suppressions are required because the `built` crate's
/// generated source uses unhashed raw string literals, reason-less
/// `#[allow(dead_code)]` attributes, and identifier-like tokens in
/// doc comments that would otherwise fail under the workspace's
/// pedantic lint configuration.
#[allow(
    dead_code,
    reason = "Generated by `built` crate; fields referenced via built_info::"
)]
#[allow(clippy::needless_raw_string_hashes)]
#[allow(clippy::allow_attributes_without_reason)]
#[allow(clippy::doc_markdown)]
pub mod built_info {
    include!(concat!(env!("OUT_DIR"), "/built.rs"));
}

/// Git commit short SHA captured at build time by `build.rs`.
///
/// `"unknown"` when the build tree is not a git checkout (e.g. a published
/// crates.io source tarball).
mod build_git {
    include!(concat!(env!("OUT_DIR"), "/git_sha.rs"));
}

mod commands;
mod errors;

use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};
use commands::{
    auth::AuthCommand,
    commit::CommitCommand,
    completions::CompletionsArgs,
    decide::DecideCommand,
    issue::IssueCommand,
    label::{LabelCommand, MilestoneCommand},
    pipeline::PipelineCommand,
    pr::PrCommand,
    regression_semantic::RegressionCommand,
    release::ReleaseCommand,
    review::ReviewCommand,
    workflow::WorkflowCommand,
};
use is_terminal::IsTerminal;

fn main() -> std::process::ExitCode {
    // Reset SIGPIPE on Unix so broken pipes exit cleanly
    #[cfg(unix)]
    reset_sigpipe();

    // Initialize tracing subscriber (TTY-aware, respects NO_COLOR)
    init_tracing();

    // Build version string: pkg version + git sha. `clap::Command::version` requires a
    // `'static` string and the `clap` dependency does not enable the `string` feature
    // (which would allow an owned `String` directly), so the formatted string is leaked
    // once at startup -- negligible cost for a CLI that runs this exactly once per process.
    let version_string: &'static str =
        Box::leak(format!("{} ({})", built_info::PKG_VERSION, build_git::GIT_SHA).into_boxed_str());

    let matches = match Cli::command().version(version_string).try_get_matches() {
        Ok(m) => m,
        Err(e) => e.exit(),
    };

    let cli = match Cli::from_arg_matches(&matches) {
        Ok(c) => c,
        Err(e) => e.exit(),
    };

    // Completions are purely synchronous -- generate and exit
    if let Commands::Completions(ref args) = cli.command {
        return commands::completions::generate::<Cli>(args);
    }

    // Build the async runtime
    let rt = match tokio::runtime::Runtime::new() {
        Ok(rt) => rt,
        Err(e) => {
            let report = miette::miette!("Failed to create async runtime: {e}");
            eprintln!("{report:?}");
            return std::process::ExitCode::from(1);
        }
    };

    // Resolve platform and repository early so they are available in the
    // error handler below. Skills, Completions, Workflow, and Update commands
    // don't need platform info, so skip resolve_platform for them (allows
    // running outside a git repository).
    let platform_needed = !matches!(
        cli.command,
        Commands::Skills(_)
            | Commands::Decide(_)
            | Commands::Regression(_)
            | Commands::Issue(IssueCommand::Precheck { .. })
            | Commands::Pr(PrCommand::Precheck { .. })
            | Commands::Pipeline(PipelineCommand::AnalyzeFailures { .. })
            | Commands::Completions(_)
            | Commands::Workflow(_)
            | Commands::Update(_)
            | Commands::Doctor(_)
    );
    let (platform, repo, remote_url) = if platform_needed {
        match resolve_platform(cli.platform.clone()) {
            Ok(pr) => pr,
            Err(e) => {
                eprintln!("{e:?}");
                return std::process::ExitCode::from(1);
            }
        }
    } else {
        ("unknown".to_string(), String::new(), String::new())
    };

    // Block on the async main, handling graceful shutdown signals
    match rt.block_on(async_main(cli, &platform, &repo, &remote_url)) {
        Ok(()) => std::process::ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("{e:?}");
            std::process::ExitCode::from(1)
        }
    }
}

/// Async entry point that wires graceful shutdown into the main flow.
///
/// Flow: check prerequisites → dispatch command.
///
/// The `platform` and `repo` are resolved in `main()` before this
/// function is called so they remain available in the error handler.
async fn async_main(cli: Cli, platform: &str, repo: &str, remote_url: &str) -> miette::Result<()> {
    // Skills/Completions/Workflow/Update don't need native CLI — skip prerequisite check
    if !matches!(
        cli.command,
        Commands::Skills(_)
            | Commands::Decide(_)
            | Commands::Regression(_)
            | Commands::Issue(IssueCommand::Precheck { .. } | IssueCommand::Search(_))
            | Commands::Pr(PrCommand::Precheck { .. } | PrCommand::Search(_))
            | Commands::Pipeline(PipelineCommand::AnalyzeFailures { .. })
            | Commands::Completions(_)
            | Commands::Workflow(_)
            | Commands::Update(_)
            | Commands::Doctor(_)
    ) {
        commands::prerequisites::check(platform).map_err(|e| miette::miette!("{e}"))?;
    }

    tokio::select! {
        result = router(cli.command, platform, repo, remote_url, cli.output) => result,
        () = async {
            match tokio::signal::ctrl_c().await {
                Ok(()) => tracing::info!("Received shutdown signal, exiting gracefully"),
                Err(e) => tracing::warn!("Failed to install Ctrl+C handler: {e}"),
            }
        } => {
            Ok(())
        }
    }
}

/// Dispatch a subcommand to the appropriate handler.
async fn router(
    command: Commands,
    platform: &str,
    repo: &str,
    remote_url: &str,
    output: OutputFormat,
) -> miette::Result<()> {
    match command {
        Commands::Issue(cmd) => {
            commands::issue::handle(cmd, platform, repo, remote_url, output).await
        }
        Commands::Pr(cmd) => commands::pr::handle(cmd, platform, repo, remote_url, output).await,
        Commands::Release(cmd) => {
            commands::release::handle(cmd, platform, repo, remote_url, output).await
        }
        Commands::Review(cmd) => commands::review::handle(cmd, platform, repo, output).await,
        Commands::Auth(cmd) => commands::auth::handle(cmd, platform, repo, output).await,
        Commands::Label(cmd) => {
            commands::label::handle_label(cmd, platform, repo, remote_url, output).await
        }
        Commands::Milestone(cmd) => {
            commands::label::handle_milestone(cmd, platform, repo, output).await
        }
        Commands::Commit(cmd) => commands::commit::handle(cmd, platform, repo, output).await,
        Commands::Pipeline(cmd) => {
            commands::pipeline::handle(cmd, platform, repo, remote_url, output).await
        }
        Commands::Workflow(cmd) => commands::workflow::handle(cmd).await,
        Commands::Doctor(ref args) => commands::doctor::handle(args),
        Commands::Skills(ref cmd) => commands::skills::handle(cmd, output).await,
        Commands::Decide(cmd) => commands::decide::handle(cmd, output).await,
        Commands::Regression(cmd) => commands::regression_semantic::handle(cmd).await,
        Commands::Update(cmd) => {
            // `handle_update` uses `self_update` (reqwest::blocking), which creates its own
            // tokio runtime. Running it on the async runtime thread panics on nested runtime
            // drop, so dispatch it to a blocking worker thread.
            tokio::task::spawn_blocking(move || commands::update::handle_update(&cmd))
                .await
                .map_err(|e| miette::miette!("update task panicked: {e}"))?
        }
        Commands::Completions(_) => Ok(()),
    }
}

/// Resolve the target platform and repository from CLI args and git remote.
///
/// # Why sync `std::process::Command`?
///
/// This function is called before the tokio runtime is constructed (see
/// `main()` entry point). Using async process spawning would require an
/// existing runtime, creating a chicken-and-egg problem. The sync call
/// blocks only briefly (~10ms) to read the git remote URL — acceptable
/// for CLI startup latency.
///
/// If future work adds network calls (e.g., resolving self-hosted domains
/// via DNS or HTTP), migrate those to async after the tokio runtime starts,
/// and keep this function limited to local filesystem / process operations.
///
/// Priority:
/// 1. `--platform` flag (explicit override)
/// 2. `git remote get-url origin` auto-detection
/// 3. Both fail → error with hint to use `--platform`
///
/// # Errors
///
/// - Git remote URL cannot be obtained → hint to run inside a git repo
/// - Platform cannot be detected → hint to use `--platform`
/// - `owner/repo` cannot be parsed from remote URL → parse error
#[allow(
    clippy::disallowed_types,
    reason = "Invoked before the tokio runtime is constructed"
)]
fn resolve_platform(cli_platform: Option<PlatformArg>) -> miette::Result<(String, String, String)> {
    // Get git remote URL (sync — see doc comment above).
    let output = std::process::Command::new("git")
        .args(["remote", "get-url", "origin"])
        .output()
        .map_err(|e| {
            miette::miette!("Failed to get git remote URL: {e}\nAre you in a git repository?")
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(miette::miette!(
            "git remote get-url origin failed: {}\nAre you in a git repository?",
            stderr.trim()
        ));
    }

    let remote_url = String::from_utf8_lossy(&output.stdout).trim().to_string();

    // Determine platform.
    // Note: detect_from_remote_url() never returns None — it always produces
    // a PlatformDetection (explicit match or GitLab fallback). See
    // crates/core/src/platform.rs:74-97.
    let platform = if let Some(p) = cli_platform {
        match p {
            PlatformArg::Github => "github",
            PlatformArg::Gitlab => "gitlab",
            PlatformArg::Gitcode => "gitcode",
        }
        .to_string()
    } else {
        let detection = gitflow_core::platform::Platform::detect_from_remote_url(&remote_url);
        if !detection.is_explicit() {
            eprintln!(
                "warning: unrecognized domain in remote URL: {remote_url}\nDefaulting to GitLab \
                 adapter. Use --platform to specify explicitly."
            );
        }
        format!("{:?}", detection.platform).to_lowercase()
    };

    // Extract owner/repo
    let repo = extract_repo_from_url(&remote_url)
        .ok_or_else(|| miette::miette!("Unable to parse owner/repo from URL: {remote_url}"))?;

    Ok((platform, repo, remote_url))
}

/// Extract repository path from a git remote URL.
///
/// Supports both HTTPS and SSH remote formats:
/// - `https://github.com/owner/repo.git` → `owner/repo`
/// - `git@github.com:owner/repo.git` → `owner/repo`
/// - `https://gitlab.example.com/group/project` → `group/project`
/// - `git@xyun.git.nyuncloud.com:fusion-cdn/bff/admin.git` → `fusion-cdn/bff/admin`
/// - `https://oauth2:token@gitlab.example.com/group/project.git` → `group/project`
///
/// Returns the full path after the domain, preserving multi-level paths
/// for self-hosted GitLab instances. Returns `None` if the URL cannot
/// be parsed into at least two path segments after stripping the scheme,
/// authentication info, and host.
#[must_use]
fn extract_repo_from_url(url: &str) -> Option<String> {
    let without_prefix = url
        .trim_start_matches("https://")
        .trim_start_matches("http://")
        .trim_start_matches("git@");

    // Remove authentication info (user:pass@ or token@) if present
    let without_auth = if let Some((_auth, host_and_path)) = without_prefix.split_once('@') {
        host_and_path
    } else {
        without_prefix
    };

    // For SSH URLs like `host:owner/repo`, take the part after `:`.
    // For HTTPS URLs like `host/owner/repo`, split by `/` and skip the host.
    let path = if let Some((_before, after)) = without_auth.split_once(':') {
        // SSH format: `host:owner/repo`
        after.to_string()
    } else {
        // HTTPS format: `host/owner/repo` - skip the first segment (host)
        // segments[1..] is safe here because we check `segments.len() >= 2` on the previous line
        let segments: Vec<&str> = without_auth.split('/').filter(|s| !s.is_empty()).collect();
        if segments.len() >= 2 {
            #[allow(
                clippy::indexing_slicing,
                reason = "Safe: segments.len() >= 2 checked above"
            )]
            segments[1..].join("/")
        } else {
            return None;
        }
    };

    let no_suffix = path.trim_end_matches(".git");
    let segments: Vec<&str> = no_suffix.split('/').filter(|s| !s.is_empty()).collect();

    if segments.len() >= 2 {
        // Preserve the full path for multi-level GitLab namespaces
        Some(segments.join("/"))
    } else {
        None
    }
}

/// Initialize the `tracing-subscriber` with TTY-aware output.
///
/// - **TTY (terminal)**: human-readable output. ANSI colours are enabled unless `NO_COLOR` is set.
/// - **Pipe / redirect**: JSON-formatted output for machine consumption, unless `CLICOLOR_FORCE` is
///   set (non-zero), which forces human-readable output with colour.
/// - `NO_COLOR` always disables ANSI escape sequences regardless of output target or
///   `CLICOLOR_FORCE`.
fn init_tracing() {
    let env_filter = tracing_subscriber::EnvFilter::try_from_default_env()
        .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"));

    let is_tty = std::io::stderr().is_terminal();
    let no_color = std::env::var("NO_COLOR").is_ok();
    let force_color = std::env::var("CLICOLOR_FORCE").is_ok_and(|v| v != "0");

    let use_json = !is_tty && !force_color;
    let use_ansi = !no_color && (is_tty || force_color);

    if use_json {
        tracing_subscriber::fmt()
            .with_env_filter(env_filter)
            .json()
            .init();
    } else {
        tracing_subscriber::fmt()
            .with_env_filter(env_filter)
            .with_ansi(use_ansi)
            .with_target(false)
            .init();
    }
}

/// Reset `SIGPIPE` to the default handler so the process exits
/// cleanly when the output pipe is broken, instead of panicking
/// with an `EPIPE` error.
///
/// # Investigation Result (2026-08-28)
///
/// After evaluating options, this function remains intentionally empty:
///
/// 1. **`signal-hook` crate**: Provides a safe-looking API but internally still uses `unsafe {
///    libc::sigaction() }`. Adding it would introduce a new dependency without eliminating unsafe
///    code — just moving it into a third-party crate. The workspace's `#![forbid(unsafe_code)]`
///    policy would need to be relaxed anyway.
///
/// 2. **tokio's built-in handling**: When the tokio runtime starts, it sets SIGPIPE to `SIG_IGN`
///    (ignore) via its internal signal handler. This means writes to a broken pipe return `EPIPE`
///    errors instead of terminating the process. Since `gf` does not `.unwrap()` or `.expect()` on
///    stdout write results, no panic occurs.
///
/// 3. **Verified behavior**: `gf --help | head -1` exits cleanly with code 0. No panic, no crash.
///
/// If future code adds explicit `.expect()` on stdout writes, revisit
/// this decision. For now, the empty implementation is correct.
#[cfg(unix)]
fn reset_sigpipe() {
    // Intentionally empty — see doc comment above.
    // tokio sets SIG_IGN at runtime startup; println! returns Err on EPIPE
    // but does not panic unless explicitly unwrapped.
}

/// Platform argument for the `--platform` CLI flag.
///
/// Maps to the three supported hosting platforms. Used as a
/// `clap::ValueEnum` so clap generates value completions and
/// validation automatically.
#[derive(Debug, Clone, clap::ValueEnum)]
enum PlatformArg {
    /// GitHub (github.com or Enterprise).
    #[value(name = "github")]
    Github,
    /// GitLab (gitlab.com or self-hosted).
    #[value(name = "gitlab")]
    Gitlab,
    /// `GitCode` (gitcode.com or self-hosted).
    #[value(name = "gitcode")]
    Gitcode,
}

/// Output format for CLI command results.
///
/// Controls how command output is rendered to the terminal.
#[derive(Debug, Default, Clone, clap::ValueEnum)]
pub enum OutputFormat {
    /// Structured JSON output (for machine consumption by skills).
    Json,
    /// Human-readable plain text output.
    Text,
    /// TOON (Token-Oriented Object Notation) — compact format for LLM consumption.
    Toon,
    /// Automatically select the best format based on data structure analysis (default).
    #[default]
    Auto,
}

/// gf command-line interface.
#[derive(Debug, Parser)]
#[command(name = "gf", about = "gf CLI tool", author)]
struct Cli {
    /// Override platform auto-detection.
    #[arg(long, global = true)]
    platform: Option<PlatformArg>,

    /// Output format (json, text, toon, or auto).
    #[arg(long, global = true, default_value = "auto")]
    output: OutputFormat,

    /// Enable verbose output.
    #[arg(short, long, global = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Commands,
}

/// Available subcommands.
#[derive(Debug, Subcommand)]
enum Commands {
    /// Evaluate bounded typed questions with an optional provider.
    #[command(subcommand)]
    Decide(DecideCommand),
    /// Evaluate captured regression cases with an optional semantic oracle.
    #[command(subcommand)]
    Regression(RegressionCommand),
    /// Issue operations (create, list, view).
    #[command(subcommand)]
    Issue(IssueCommand),

    /// Pull request operations (create, list, view).
    #[command(subcommand)]
    Pr(PrCommand),

    /// Release operations (create, list, view, edit, upload, download, delete).
    #[command(subcommand)]
    Release(ReleaseCommand),

    /// Code review operations (comment, approve, request-changes, submit).
    #[command(subcommand)]
    Review(ReviewCommand),

    /// Authentication operations (login, logout, status, token).
    #[command(subcommand)]
    Auth(AuthCommand),

    /// Label operations (create, list, edit, delete).
    #[command(subcommand)]
    Label(LabelCommand),

    /// Milestone operations (create, list, edit, close, reopen).
    #[command(subcommand)]
    Milestone(MilestoneCommand),

    /// Commit operations (view, diff, patch, comment).
    #[command(subcommand)]
    Commit(CommitCommand),

    /// Pipeline operations (status, logs, jobs, report).
    #[command(subcommand)]
    Pipeline(PipelineCommand),

    /// Workflow contract and gate management.
    #[command(subcommand)]
    Workflow(WorkflowCommand),

    /// Diagnose environments health (CLI, Agent, skills, config).
    Doctor(commands::doctor::DoctorArgs),

    /// Skills management operations (install, list, uninstall, update).
    #[command(subcommand)]
    Skills(commands::skills::SkillsCommand),

    /// Update the gf binary to the latest GitHub release.
    Update(commands::update::UpdateArgs),

    /// Generate shell completion scripts.
    #[command(hide = true)]
    Completions(CompletionsArgs),
}

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

    #[test]
    fn test_should_parse_skill_suggestion_without_provider() {
        let parsed =
            Cli::try_parse_from(["gf", "skills", "suggest", "--query", "审查这个 PR"]).unwrap();
        assert!(matches!(
            parsed.command,
            Commands::Skills(commands::skills::SkillsCommand::Suggest(_))
        ));
        assert!(
            Cli::try_parse_from(["gf", "skills", "suggest", "--stdin", "--query", "review PR"])
                .is_err()
        );
    }

    #[test]
    fn test_should_parse_workflow_recommendation_without_live_provider() {
        let parsed =
            Cli::try_parse_from(["gf", "workflow", "recommend", "--input", "task.json"]).unwrap();
        assert!(matches!(
            parsed.command,
            Commands::Workflow(WorkflowCommand::Recommend {
                live: false,
                response: None,
                ..
            })
        ));
        assert!(
            Cli::try_parse_from([
                "gf",
                "workflow",
                "recommend",
                "--input",
                "task.json",
                "--response",
                "saved.json",
                "--live"
            ])
            .is_err()
        );
    }

    #[test]
    fn test_should_parse_offline_decision_evaluation_commands() {
        let eval = Cli::try_parse_from([
            "gf",
            "decide",
            "eval",
            "--fixtures",
            "cases.json",
            "--responses",
            "saved.json",
        ])
        .unwrap();
        assert!(matches!(
            eval.command,
            Commands::Decide(DecideCommand::Eval(_))
        ));
        let calibrate = Cli::try_parse_from([
            "gf",
            "decide",
            "calibrate",
            "--report",
            "report.json",
            "--question",
            "type",
            "--target-accuracy",
            "0.9",
        ])
        .unwrap();
        assert!(matches!(
            calibrate.command,
            Commands::Decide(DecideCommand::Calibrate(_))
        ));
        let compare = Cli::try_parse_from([
            "gf",
            "decide",
            "compare",
            "--baseline",
            "base.json",
            "--candidate",
            "new.json",
        ])
        .unwrap();
        assert!(matches!(
            compare.command,
            Commands::Decide(DecideCommand::Compare(_))
        ));
    }

    #[test]
    fn test_should_extract_repo_from_https_url() {
        let url = "https://github.com/owner/repo.git";
        assert_eq!(extract_repo_from_url(url), Some("owner/repo".to_string()));
    }

    #[test]
    fn test_should_extract_repo_from_ssh_url() {
        let url = "git@github.com:owner/repo.git";
        assert_eq!(extract_repo_from_url(url), Some("owner/repo".to_string()));
    }

    #[test]
    fn test_should_extract_repo_without_dot_git_suffix() {
        let url = "https://github.com/owner/repo";
        assert_eq!(extract_repo_from_url(url), Some("owner/repo".to_string()));
    }

    #[test]
    fn test_should_return_none_for_invalid_url() {
        assert_eq!(extract_repo_from_url("just-a-string"), None);
        assert_eq!(extract_repo_from_url(""), None);
        assert_eq!(extract_repo_from_url("https://github.com"), None);
    }

    #[test]
    fn test_should_preserve_multilevel_gitlab_path() {
        // GitLab self-hosted with multi-level namespace
        let url = "git@xyun.git.nyuncloud.com:fusion-cdn/bff/admin.git";
        assert_eq!(
            extract_repo_from_url(url),
            Some("fusion-cdn/bff/admin".to_string())
        );
    }

    #[test]
    fn test_should_preserve_gitlab_subgroup_path() {
        // GitLab with subgroup
        let url = "https://gitlab.example.com/group/subgroup/project.git";
        assert_eq!(
            extract_repo_from_url(url),
            Some("group/subgroup/project".to_string())
        );
    }

    #[test]
    fn test_should_handle_https_with_authentication() {
        // HTTPS URL with authentication info
        let url = "https://oauth2:token@xyun.git.nyuncloud.com/fusion-cdn/bff/admin.git";
        assert_eq!(
            extract_repo_from_url(url),
            Some("fusion-cdn/bff/admin".to_string())
        );

        // HTTPS URL with simple token
        let url = "https://token@gitlab.example.com/group/project.git";
        assert_eq!(
            extract_repo_from_url(url),
            Some("group/project".to_string())
        );
    }

    #[test]
    fn test_should_parse_update_command() {
        let cli = Cli::try_parse_from(["gf", "update", "--check"]).expect("parse update");
        assert!(matches!(cli.command, Commands::Update(ref a) if a.check));
    }

    #[test]
    fn test_update_does_not_need_platform() {
        let cli = Cli::try_parse_from(["gf", "update"]).expect("parse update");
        let platform_needed = !matches!(
            cli.command,
            Commands::Skills(_)
                | Commands::Completions(_)
                | Commands::Workflow(_)
                | Commands::Update(_)
        );
        assert!(!platform_needed);
    }
}