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