Skip to main content

orch/cli/
mod.rs

1#![expect(
2    clippy::print_stdout,
3    clippy::print_stderr,
4    reason = "the CLI writes its output to the terminal"
5)]
6
7pub mod chat;
8pub mod commit;
9pub mod cooldown;
10pub mod cost;
11pub mod dashboard;
12pub mod doctor;
13pub mod events;
14pub(crate) mod init;
15pub mod job;
16pub mod ndjson;
17pub mod nodes;
18pub mod notify;
19pub mod plan;
20pub mod progress;
21pub mod proof;
22pub mod prune;
23pub mod service;
24pub mod session;
25pub mod stats;
26pub mod stream;
27pub mod task;
28pub mod task_ref;
29pub mod tree;
30pub mod ui;
31pub mod webhook;
32
33use crate::backends::ExternalBackend;
34use crate::backends::github::GitHubBackend;
35use crate::cluster::local;
36use crate::cmd::SyncCommandErrorContext;
37use crate::config;
38use crate::engine;
39use crate::engine::tasks::TaskManager;
40use crate::github::http::GhHttp;
41use crate::github::projects::ProjectSync;
42use crate::github::projects::label_status::LabelSyncConfig;
43use crate::github::projects::label_status::ProjectApi;
44use crate::home;
45use crate::store;
46use crate::store::TaskStore;
47use anyhow::Context;
48use std::env;
49use std::fs;
50use std::iter;
51use std::path;
52use std::path::Path;
53use std::path::PathBuf;
54use std::process;
55use std::process::Command;
56use std::sync::Arc;
57
58/// Detect agents, write a minimal config, and start the service
59pub fn init(repo: Option<String>) -> anyhow::Result<()> {
60    init::run(repo)
61}
62
63/// Show orch logs.
64pub fn log(lines: &str) -> anyhow::Result<()> {
65    let state_dir = home::state_dir().unwrap_or_default();
66    let brew_prefix = env::var("HOMEBREW_PREFIX").unwrap_or_else(|_| "/opt/homebrew".into());
67
68    let mut log_files = Vec::new();
69
70    let candidates = [
71        state_dir.join("orch.log"),
72        state_dir.join("orch.error.log"),
73        PathBuf::from(&brew_prefix).join("var/log/orch.log"),
74        PathBuf::from(&brew_prefix).join("var/log/orch.error.log"),
75    ];
76
77    for path in &candidates {
78        if path.exists() && fs::metadata(path).is_ok_and(|m| m.len() > 0) {
79            log_files.push(path.clone());
80        } else {
81            // Fall back to rotated log files (orch.log.1, orch.log.2, ...) if primary is empty
82            for n in 1..=5 {
83                let rotated = PathBuf::from(format!("{}.{}", path.display(), n));
84                if rotated.exists() && fs::metadata(&rotated).is_ok_and(|m| m.len() > 0) {
85                    log_files.push(rotated);
86                    break;
87                }
88            }
89        }
90    }
91
92    if log_files.is_empty() {
93        println!("No log files found");
94        return Ok(());
95    }
96
97    if lines == "watch" {
98        let args: Vec<String> = iter::once("-f".to_string())
99            .chain(log_files.iter().map(|p| p.to_string_lossy().to_string()))
100            .collect();
101        let status = Command::new("tail").args(&args).status_with_context()?;
102        process::exit(status.code().unwrap_or(1));
103    }
104    let n = lines.parse::<usize>().unwrap_or(50);
105    for path in &log_files {
106        let filename = path.file_name().unwrap_or_default().to_string_lossy();
107        println!("=== {filename} ===");
108
109        let content = fs::read_to_string(path)?;
110        let all_lines: Vec<&str> = content.lines().collect();
111        let start = if all_lines.len() > n {
112            all_lines.len() - n
113        } else {
114            0
115        };
116        for line in &all_lines[start..] {
117            println!("{line}");
118        }
119        println!();
120    }
121
122    Ok(())
123}
124
125/// List installed agent CLIs.
126pub fn agents() {
127    let agents = engine::configured_agents();
128
129    println!("{:<12} {:<10} PATH", "AGENT", "STATUS");
130    println!("{}", "-".repeat(60));
131
132    for agent in &agents {
133        match which::which(agent) {
134            Ok(path) => {
135                // Try to get version
136                let version = Command::new(agent)
137                    .arg("--version")
138                    .output_with_context()
139                    .ok()
140                    .and_then(|o| {
141                        if o.status.success() {
142                            Some(
143                                String::from_utf8_lossy(&o.stdout)
144                                    .lines()
145                                    .next()
146                                    .unwrap_or("")
147                                    .trim()
148                                    .to_string(),
149                            )
150                        } else {
151                            None
152                        }
153                    })
154                    .unwrap_or_default();
155
156                let info = if version.is_empty() {
157                    path.display().to_string()
158                } else {
159                    format!("{} ({})", path.display(), version)
160                };
161                println!("{:<12} {:<10} {}", agent, "installed", info);
162            }
163            Err(_) => {
164                println!("{:<12} {:<10} ", agent, "missing");
165            }
166        }
167    }
168}
169
170/// Show task metrics summary.
171///
172/// `since_hours` controls the time window (default 24; pass 168 for 7 days, etc.).
173pub async fn metrics(details: bool, since_hours: u32) -> anyhow::Result<()> {
174    let store = init_store().await?;
175
176    let summary = store.get_metrics_summary(since_hours).await?;
177    let window_label = hours_to_label(since_hours);
178
179    println!();
180    let header = format!("Orch Metrics (Last {window_label})");
181    let width = 58usize;
182    let pad = width.saturating_sub(header.len() + 2);
183    let left_pad = pad / 2;
184    let right_pad = pad - left_pad;
185    println!("╔{}╗", "═".repeat(width));
186    println!(
187        "║{}{header}{}║",
188        " ".repeat(left_pad),
189        " ".repeat(right_pad)
190    );
191    println!("╚{}╝", "═".repeat(width));
192    println!();
193
194    // Task counts
195    println!(" Tasks:");
196    println!("   {:>6} completed", summary.tasks_completed_24h);
197    println!("   {:>6} failed", summary.tasks_failed_24h);
198    println!();
199
200    // Average duration by complexity
201    println!(" Average Duration by Complexity:");
202    if let Some(d) = summary.avg_duration_simple {
203        println!("   {d:>6.1}s (simple)");
204    } else {
205        println!("   {:>6} (simple)", "-");
206    }
207    if let Some(d) = summary.avg_duration_medium {
208        println!("   {d:>6.1}s (medium)");
209    } else {
210        println!("   {:>6} (medium)", "-");
211    }
212    if let Some(d) = summary.avg_duration_complex {
213        println!("   {d:>6.1}s (complex)");
214    } else {
215        println!("   {:>6} (complex)", "-");
216    }
217    println!();
218
219    // Agent success rates
220    if !summary.agent_stats.is_empty() {
221        println!(" Agent Success Rates:");
222        for stat in &summary.agent_stats {
223            println!(
224                "   {:<12} {:>4} runs, {:>5.1}% success",
225                stat.agent, stat.total_runs, stat.success_rate
226            );
227        }
228        println!();
229    }
230
231    // Rate limits
232    println!(" Rate Limit Events: {:>6}", summary.rate_limits_24h);
233    println!();
234
235    if details {
236        // Slow tasks
237        let slow = store.get_slow_tasks(since_hours).await?;
238        if !slow.is_empty() {
239            println!(" Slowest Tasks (Last {window_label}):");
240            println!(
241                "   {:<20} {:<12} {:<10} DURATION",
242                "TASK ID", "AGENT", "COMPLEXITY"
243            );
244            println!("   {}", "-".repeat(56));
245            for t in &slow {
246                println!(
247                    "   {:<20} {:<12} {:<10} {:.1}s",
248                    t.task_id,
249                    t.agent,
250                    t.complexity.as_deref().unwrap_or("-"),
251                    t.duration_seconds
252                );
253            }
254            println!();
255        }
256
257        // Error distribution
258        let errors = store.get_error_distribution(since_hours).await?;
259        if errors.is_empty() {
260            println!(" Error Distribution (Last {window_label}): none");
261            println!();
262        } else {
263            println!(" Error Distribution (Last {window_label}):");
264            println!("   {:<30} {:>6}", "ERROR TYPE", "COUNT");
265            println!("   {}", "-".repeat(38));
266            for e in &errors {
267                println!(
268                    "   {:<30} {:>6}",
269                    e.error_type.as_deref().unwrap_or("unknown"),
270                    e.count
271                );
272            }
273            println!();
274        }
275
276        // Repeated review loops
277        let review_loops = store.get_high_review_cycle_tasks(since_hours).await?;
278        if !review_loops.is_empty() {
279            println!(" Tasks with Repeated Review Loops (Last {window_label}):");
280            println!("   {:<10} {:<12} TITLE", "CYCLES", "AGENT");
281            println!("   {}", "-".repeat(60));
282            for t in &review_loops {
283                println!(
284                    "   {:<10} {:<12} {}",
285                    t.review_cycles,
286                    t.agent.as_deref().unwrap_or("-"),
287                    t.title,
288                );
289            }
290            println!();
291        }
292    }
293
294    Ok(())
295}
296
297/// Convert hours to a human-readable label (e.g. 24 → "24h", 168 → "7d").
298pub fn hours_to_label(hours: u32) -> String {
299    if hours.is_multiple_of(24) {
300        format!("{}d", hours / 24)
301    } else {
302        format!("{hours}h")
303    }
304}
305
306/// Parse a `--since` string like "24h", "7d", "30d" into hours.
307/// Returns `None` if the format is unrecognised.
308pub fn parse_since(s: &str) -> Option<u32> {
309    if let Some(d) = s.strip_suffix('d') {
310        d.parse::<u32>().ok().map(|n| n * 24)
311    } else if let Some(h) = s.strip_suffix('h') {
312        h.parse::<u32>().ok()
313    } else {
314        // bare number treated as hours
315        s.parse::<u32>().ok()
316    }
317}
318
319/// List accessible GitHub Projects V2 boards.
320pub async fn board_list() -> anyhow::Result<()> {
321    let projects = ProjectSync::list_projects().await?;
322
323    if projects.is_empty() {
324        println!("No GitHub Projects V2 boards found");
325        return Ok(());
326    }
327
328    println!("{:<50} {:<8} ID", "TITLE", "NUMBER");
329    println!("{}", "-".repeat(80));
330    for p in &projects {
331        println!("{:<50} #{:<7} {}", p.title, p.number, p.id);
332    }
333
334    Ok(())
335}
336
337/// Link current repo to a GitHub Projects V2 board by ID and discover fields.
338pub async fn board_link(project_id: &str) -> anyhow::Result<()> {
339    println!("Discovering board fields...");
340    let sync = ProjectSync::discover_fields(project_id).await?;
341
342    sync.write_config().await?;
343
344    println!("Linked board: {project_id}");
345    println!("Status field: {}", sync.status_field_id());
346    println!("Column mappings:");
347    for line in sync.column_lines() {
348        println!("{line}");
349    }
350
351    Ok(())
352}
353
354/// Re-discover field IDs from configured board and update config.
355pub async fn board_sync() -> anyhow::Result<()> {
356    let project_id = config::get("gh.project_id").map_err(|_| {
357        anyhow::anyhow!("no board configured — run `orch project board link <id>` first")
358    })?;
359
360    if project_id.is_empty() {
361        anyhow::bail!("no board configured — run `orch project board link <id>` first");
362    }
363
364    println!("Syncing board fields for {project_id}...");
365    let sync = ProjectSync::discover_fields(&project_id).await?;
366
367    sync.write_config().await?;
368
369    println!("Updated config:");
370    println!("  Status field: {}", sync.status_field_id());
371    for line in sync.column_lines() {
372        println!("{line}");
373    }
374
375    Ok(())
376}
377
378/// Show current board configuration.
379pub fn board_info() -> anyhow::Result<()> {
380    let project_id = config::get("gh.project_id").unwrap_or_default();
381
382    if project_id.is_empty() {
383        println!("No board configured");
384        println!("  Run `orch project board list` to see available boards");
385        println!("  Run `orch project board link <id>` to link one");
386        return Ok(());
387    }
388
389    println!("Board ID: {project_id}");
390
391    if let Ok(field_id) = config::get("gh.project_status_field_id") {
392        println!("Status field: {field_id}");
393    }
394
395    for col in &["backlog", "in_progress", "review", "done"] {
396        if let Ok(opt_id) = config::get(&format!("gh.project_status_map.{col}")) {
397            println!("  {col}: {opt_id}");
398        }
399    }
400
401    Ok(())
402}
403
404/// One display-only reconciliation pass. No engine, TaskStore, router,
405/// task ingestion, configuration write or agent process is initialized here.
406pub async fn board_reconcile(repo: Option<&str>) -> anyhow::Result<()> {
407    let repo = match repo {
408        Some(repo) => repo.to_owned(),
409        None => config::get_current_repo()?,
410    };
411    let config = LabelSyncConfig::from_config()?;
412    let gh = GhHttp::owner()?;
413    let updated = board_reconcile_with(&config, &gh, &repo).await?;
414    println!(
415        "Updated {updated} project Status field(s) in this pass; skipped items are reported at debug level."
416    );
417    Ok(())
418}
419
420pub(crate) async fn board_reconcile_with(
421    config: &LabelSyncConfig,
422    api: &impl ProjectApi,
423    repo: &str,
424) -> anyhow::Result<usize> {
425    if !config.configured_for_repo(repo) {
426        anyhow::bail!("no enabled gh.project_label_sync board configured for this repository");
427    }
428    config.reconcile(api, repo).await
429}
430
431/// Try to parse a GitHub slug (owner/repo) from the input.
432///
433/// Accepts:
434/// - `owner/repo` — direct slug
435/// - `https://github.com/owner/repo` — GitHub URL (with optional .git suffix)
436///
437/// Returns `None` if the input looks like a local path.
438pub(crate) fn parse_github_slug(input: &str) -> Option<(String, String)> {
439    // SSH URL format: git@github.com:owner/repo.git
440    if input.starts_with("git@github.com:") {
441        let path = input
442            .trim_start_matches("git@github.com:")
443            .trim_end_matches('/')
444            .trim_end_matches(".git");
445        let parts: Vec<&str> = path.splitn(3, '/').collect();
446        if parts.len() >= 2 && !parts[0].is_empty() && !parts[1].is_empty() {
447            return Some((parts[0].to_string(), parts[1].to_string()));
448        }
449        return None;
450    }
451
452    // GitHub URL format
453    if input.starts_with("https://github.com/") || input.starts_with("http://github.com/") {
454        let path = input
455            .trim_start_matches("https://github.com/")
456            .trim_start_matches("http://github.com/")
457            .trim_end_matches('/')
458            .trim_end_matches(".git");
459        let parts: Vec<&str> = path.splitn(3, '/').collect();
460        if parts.len() >= 2 && !parts[0].is_empty() && !parts[1].is_empty() {
461            return Some((parts[0].to_string(), parts[1].to_string()));
462        }
463        return None;
464    }
465
466    // Skip anything that looks like a local path
467    if input.starts_with('/')
468        || input.starts_with('.')
469        || input.starts_with('~')
470        || (input.contains(path::MAIN_SEPARATOR) && path::MAIN_SEPARATOR != '/')
471    {
472        return None;
473    }
474
475    // owner/repo slug (exactly one slash, no path-like characters)
476    let parts: Vec<&str> = input.splitn(3, '/').collect();
477    if parts.len() == 2 && !parts[0].is_empty() && !parts[1].is_empty() {
478        // Sanity check: slugs don't contain spaces or typical path characters
479        let owner = parts[0];
480        let repo = parts[1].trim_end_matches(".git");
481        if !owner.contains(' ') && !repo.contains(' ') && !repo.contains('/') {
482            return Some((owner.to_string(), repo.to_string()));
483        }
484    }
485
486    None
487}
488
489/// Add a project to the global registry.
490///
491/// Accepts:
492/// - A local path (existing behavior)
493/// - A GitHub slug (`owner/repo`) — auto-clones as a bare repo
494/// - A GitHub URL (`https://github.com/owner/repo`) — auto-clones as a bare repo
495pub fn project_add(input: &str) -> anyhow::Result<()> {
496    // Check if this is a GitHub slug or URL
497    if let Some((owner, repo)) = parse_github_slug(input) {
498        return project_add_github(&owner, &repo);
499    }
500
501    // Local path (existing behavior)
502    project_add_local(input)
503}
504
505/// Add a local project path to the global registry.
506fn project_add_local(path: &str) -> anyhow::Result<()> {
507    let abs_path = if path == "." {
508        env::current_dir()?
509    } else {
510        PathBuf::from(path).canonicalize()?
511    };
512
513    // Verify .orch.yml exists in the project
514    let orch_yml = abs_path.join(".orch.yml");
515    if !orch_yml.exists() {
516        // Check for legacy .orchestrator.yml
517        let legacy = abs_path.join(".orchestrator.yml");
518        if legacy.exists() {
519            println!("Found legacy .orchestrator.yml — consider renaming to .orch.yml");
520        } else {
521            anyhow::bail!(
522                "no .orch.yml found in {} — run `orch init` in the project first",
523                abs_path.display()
524            );
525        }
526    }
527
528    let path_str = abs_path.to_string_lossy().to_string();
529    register_project_path(&path_str)?;
530
531    // Show the repo from .orch.yml if available
532    if orch_yml.exists() {
533        let project_content = fs::read_to_string(&orch_yml)?;
534        let project_doc: serde_norway::Value = serde_norway::from_str(&project_content)?;
535        if let Some(repo) = project_doc
536            .get("gh")
537            .and_then(|gh| gh.get("repo"))
538            .and_then(|r| r.as_str())
539        {
540            println!("  repo: {repo}");
541        }
542    }
543
544    Ok(())
545}
546
547/**
548 * `git clone` of a GitHub repo over HTTPS with gh's token as the credential, whatever protocol gh
549 * prefers. The service runs unattended, and an SSH clone through an agent that asks a person to
550 * approve each signature fails there
551 **/
552pub(crate) fn clone_over_https(slug: &str, dest: &Path, bare: bool) -> Command {
553    let mut cmd = Command::new("git");
554    cmd.args([
555        "-c",
556        "credential.helper=",
557        "-c",
558        "credential.https://github.com.helper=!gh auth git-credential",
559        "clone",
560    ]);
561    if bare {
562        cmd.arg("--bare");
563    }
564    cmd.arg(format!("https://github.com/{slug}.git")).arg(dest);
565    cmd
566}
567
568/// Clone a GitHub repo as a bare clone and register it.
569fn project_add_github(owner: &str, repo: &str) -> anyhow::Result<()> {
570    let projects_dir = home::projects_dir()?;
571    let bare_path = projects_dir.join(owner).join(format!("{repo}.git"));
572    let slug = format!("{owner}/{repo}");
573
574    if bare_path.exists() {
575        println!("Bare clone already exists: {}", bare_path.display());
576    } else {
577        // Create parent directory
578        let parent = bare_path
579            .parent()
580            .ok_or_else(|| anyhow::anyhow!("bare path has no parent: {}", bare_path.display()))?;
581        fs::create_dir_all(parent)?;
582
583        println!("Cloning {slug} as bare repo...");
584        let status = clone_over_https(&slug, &bare_path, true).status_with_context()?;
585        if !status.success() {
586            anyhow::bail!("git clone failed for {slug}");
587        }
588
589        println!("Cloned to {}", bare_path.display());
590    }
591
592    // Create .orch.yml inside the bare clone if it doesn't exist
593    let orch_yml = bare_path.join(".orch.yml");
594    if !orch_yml.exists() {
595        let content = format!("# Project-specific orch config\ngh:\n  repo: \"{slug}\"\n");
596        fs::write(&orch_yml, content)?;
597        println!("Created .orch.yml with gh.repo: {slug}");
598    }
599
600    // Register in global config
601    let path_str = bare_path.to_string_lossy().to_string();
602    register_project_path(&path_str)?;
603    println!("  repo: {slug}");
604
605    Ok(())
606}
607
608/// Register a project path in the global config (shared by local and GitHub flows).
609fn register_project_path(path_str: &str) -> anyhow::Result<()> {
610    let config_path = home::config_path()?;
611    let content = if config_path.exists() {
612        fs::read_to_string(&config_path)?
613    } else {
614        String::new()
615    };
616
617    match config::projects_yaml::add_project(&content, path_str)? {
618        config::projects_yaml::ProjectsEdit::Unchanged => {
619            println!("Project already registered: {path_str}");
620        }
621        config::projects_yaml::ProjectsEdit::Updated(updated) => {
622            fs::write(&config_path, updated)?;
623            println!("Added project: {path_str}");
624        }
625    }
626
627    Ok(())
628}
629
630/// Remove a project from the global registry.
631pub fn project_remove(path: &str) -> anyhow::Result<()> {
632    let abs_path = PathBuf::from(path)
633        .canonicalize()
634        .unwrap_or_else(|_| PathBuf::from(path));
635    let path_str = abs_path.to_string_lossy().to_string();
636
637    let config_path = home::config_path()?;
638    if !config_path.exists() {
639        anyhow::bail!("no global config found");
640    }
641
642    let content = fs::read_to_string(&config_path)?;
643    match config::projects_yaml::remove_project(&content, &[&path_str, path])? {
644        config::projects_yaml::ProjectsEdit::Unchanged => {
645            println!("Project not found: {path}");
646        }
647        config::projects_yaml::ProjectsEdit::Updated(updated) => {
648            fs::write(&config_path, updated)?;
649            println!("Removed project: {path_str}");
650        }
651    }
652
653    Ok(())
654}
655
656/// List all registered projects.
657pub fn project_list() -> anyhow::Result<()> {
658    let projects = config::get_project_paths()?;
659
660    if projects.is_empty() {
661        println!("No projects registered");
662        println!("  Run `orch project add <path>` to register a project");
663        return Ok(());
664    }
665
666    println!("{:<50} REPO", "PATH");
667    println!("{}", "-".repeat(80));
668
669    for path_str in &projects {
670        let path = Path::new(path_str);
671
672        // Try to read repo from .orch.yml
673        let repo = read_project_repo(path).unwrap_or_else(|| "(.orch.yml not found)".to_string());
674
675        let status = if path.exists() { "" } else { " (missing)" };
676
677        println!("{path_str:<50} {repo}{status}");
678    }
679
680    Ok(())
681}
682
683/// Re-key every stored task, dependency and job row from `old` to `new`.
684pub async fn project_move(old: &str, new: &str) -> anyhow::Result<()> {
685    for slug in [old, new] {
686        if parse_github_slug(slug).is_none() {
687            anyhow::bail!("invalid slug {slug:?}, expected owner/repo");
688        }
689    }
690    let store = init_store().await?;
691    let moved = store.move_repo(old, new).await?;
692    println!("Moved {moved} task(s) from {old} to {new}");
693    println!("Now set gh.repo: {new} in the project's .orch.yml");
694    Ok(())
695}
696
697/// Read gh.repo from a project's .orch.yml.
698fn read_project_repo(project_path: &Path) -> Option<String> {
699    let orch_yml = project_path.join(".orch.yml");
700    let content = fs::read_to_string(&orch_yml).ok()?;
701    let doc: serde_norway::Value = serde_norway::from_str(&content).ok()?;
702    doc.get("gh")
703        .and_then(|gh| gh.get("repo"))
704        .and_then(|r| r.as_str())
705        .map(String::from)
706}
707
708/// Initialize task manager with database and backend.
709pub async fn init_task_manager() -> anyhow::Result<TaskManager> {
710    let repo = config::get_current_repo()
711        .context("'repo' not set — run `orch init` or set gh.repo in .orch.yml")?;
712    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
713    let store = Arc::new(init_store().await?);
714    Ok(TaskManager::with_store(backend, store, repo))
715}
716
717/// Initialize the unified task store for CLI commands.
718pub async fn init_store() -> anyhow::Result<TaskStore> {
719    let store = TaskStore::open(&store::default_db_path().await?).await?;
720    if let Some(endpoint) = local::daemon_endpoint().await {
721        store.attach_daemon(endpoint);
722    }
723
724    Ok(store)
725}
726
727#[cfg(test)]
728mod tests {
729    use super::*;
730
731    #[test]
732    fn hours_to_label_prefers_days_for_full_day_windows() {
733        assert_eq!(hours_to_label(24), "1d");
734        assert_eq!(hours_to_label(168), "7d");
735        assert_eq!(hours_to_label(30), "30h");
736    }
737
738    #[test]
739    fn parse_since_supports_days_hours_and_bare_numbers() {
740        assert_eq!(parse_since("7d"), Some(168));
741        assert_eq!(parse_since("24h"), Some(24));
742        assert_eq!(parse_since("36"), Some(36));
743        assert_eq!(parse_since("bad"), None);
744    }
745
746    #[test]
747    fn parse_slug_owner_repo() {
748        let result = parse_github_slug("gabrielkoerich/orch");
749        assert_eq!(
750            result,
751            Some(("gabrielkoerich".to_string(), "orch".to_string()))
752        );
753    }
754
755    #[test]
756    fn parse_slug_https_url() {
757        let result = parse_github_slug("https://github.com/gabrielkoerich/orch");
758        assert_eq!(
759            result,
760            Some(("gabrielkoerich".to_string(), "orch".to_string()))
761        );
762    }
763
764    #[test]
765    fn parse_slug_https_url_with_git_suffix() {
766        let result = parse_github_slug("https://github.com/gabrielkoerich/orch.git");
767        assert_eq!(
768            result,
769            Some(("gabrielkoerich".to_string(), "orch".to_string()))
770        );
771    }
772
773    #[test]
774    fn parse_slug_https_url_trailing_slash() {
775        let result = parse_github_slug("https://github.com/gabrielkoerich/orch/");
776        assert_eq!(
777            result,
778            Some(("gabrielkoerich".to_string(), "orch".to_string()))
779        );
780    }
781
782    #[test]
783    fn parse_slug_absolute_path_returns_none() {
784        assert_eq!(parse_github_slug("/Users/gb/Projects/my-app"), None);
785    }
786
787    #[test]
788    fn parse_slug_relative_path_returns_none() {
789        assert_eq!(parse_github_slug("./my-app"), None);
790    }
791
792    #[test]
793    fn parse_slug_dot_returns_none() {
794        assert_eq!(parse_github_slug("."), None);
795    }
796
797    #[test]
798    fn parse_slug_tilde_path_returns_none() {
799        assert_eq!(parse_github_slug("~/Projects/my-app"), None);
800    }
801
802    #[test]
803    fn parse_slug_single_word_returns_none() {
804        assert_eq!(parse_github_slug("my-app"), None);
805    }
806
807    #[test]
808    fn parse_slug_three_segments_returns_none() {
809        // Three segments like a deep path shouldn't match as a slug
810        assert_eq!(parse_github_slug("a/b/c"), None);
811    }
812
813    #[test]
814    fn parse_slug_ssh_url() {
815        let result = parse_github_slug("git@github.com:gabrielkoerich/bean.git");
816        assert_eq!(
817            result,
818            Some(("gabrielkoerich".to_string(), "bean".to_string()))
819        );
820    }
821
822    #[test]
823    fn parse_slug_ssh_url_no_git_suffix() {
824        let result = parse_github_slug("git@github.com:gabrielkoerich/bean");
825        assert_eq!(
826            result,
827            Some(("gabrielkoerich".to_string(), "bean".to_string()))
828        );
829    }
830}