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