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(crate) fn format_thousands(n: &str) -> String {
294 let mut result = String::new();
295 for (i, c) in n.chars().rev().enumerate() {
296 if i > 0 && i % 3 == 0 {
297 result.push(',');
298 }
299 result.push(c);
300 }
301 result.chars().rev().collect()
302}
303
304pub fn parse_since(s: &str) -> Option<u32> {
307 if let Some(d) = s.strip_suffix('d') {
308 d.parse::<u32>().ok().map(|n| n * 24)
309 } else if let Some(h) = s.strip_suffix('h') {
310 h.parse::<u32>().ok()
311 } else {
312 s.parse::<u32>().ok()
314 }
315}
316
317pub async fn board_list() -> anyhow::Result<()> {
319 let projects = ProjectSync::list_projects().await?;
320
321 if projects.is_empty() {
322 println!("No GitHub Projects V2 boards found");
323 return Ok(());
324 }
325
326 println!("{:<50} {:<8} ID", "TITLE", "NUMBER");
327 println!("{}", "-".repeat(80));
328 for p in &projects {
329 println!("{:<50} #{:<7} {}", p.title, p.number, p.id);
330 }
331
332 Ok(())
333}
334
335pub async fn board_link(project_id: &str) -> anyhow::Result<()> {
337 println!("Discovering board fields...");
338 let sync = ProjectSync::link(project_id).await?;
339
340 println!("Linked board: {project_id}");
341 let (status_field, columns) = sync.summary();
342 println!("Status field: {status_field}");
343 println!("Column mappings:");
344 for line in columns {
345 println!("{line}");
346 }
347
348 Ok(())
349}
350
351pub async fn board_sync() -> anyhow::Result<()> {
353 let project_id = config::get("gh.project_id").map_err(|_| {
354 anyhow::anyhow!("no board configured — run `orch project board link <id>` first")
355 })?;
356
357 if project_id.is_empty() {
358 anyhow::bail!("no board configured — run `orch project board link <id>` first");
359 }
360
361 println!("Syncing board fields for {project_id}...");
362 let sync = ProjectSync::link(&project_id).await?;
363
364 println!("Updated config:");
365 let (status_field, columns) = sync.summary();
366 println!(" Status field: {status_field}");
367 for line in columns {
368 println!("{line}");
369 }
370
371 Ok(())
372}
373
374pub fn board_info() -> anyhow::Result<()> {
376 let project_id = config::get("gh.project_id").unwrap_or_default();
377
378 if project_id.is_empty() {
379 println!("No board configured");
380 println!(" Run `orch project board list` to see available boards");
381 println!(" Run `orch project board link <id>` to link one");
382 return Ok(());
383 }
384
385 println!("Board ID: {project_id}");
386
387 if let Ok(field_id) = config::get("gh.project_status_field_id") {
388 println!("Status field: {field_id}");
389 }
390
391 for col in &["backlog", "in_progress", "review", "done"] {
392 if let Ok(opt_id) = config::get(&format!("gh.project_status_map.{col}")) {
393 println!(" {col}: {opt_id}");
394 }
395 }
396
397 Ok(())
398}
399
400pub async fn board_reconcile(repo: Option<&str>) -> anyhow::Result<()> {
403 let repo = match repo {
404 Some(repo) => repo.to_owned(),
405 None => config::get_current_repo()?,
406 };
407 let config = LabelSyncConfig::from_config()?;
408 let gh = GhHttp::owner()?;
409 let updated = board_reconcile_with(&config, &gh, &repo).await?;
410 println!(
411 "Updated {updated} project Status field(s) in this pass; skipped items are reported at debug level."
412 );
413 Ok(())
414}
415
416pub(crate) async fn board_reconcile_with(
417 config: &LabelSyncConfig,
418 api: &impl ProjectApi,
419 repo: &str,
420) -> anyhow::Result<usize> {
421 if !config.configured_for_repo(repo) {
422 anyhow::bail!("no enabled gh.project_label_sync board configured for this repository");
423 }
424 config.reconcile(api, repo).await
425}
426
427pub(crate) fn parse_github_slug(input: &str) -> Option<(String, String)> {
435 if input.starts_with("git@github.com:") {
437 let path = input
438 .trim_start_matches("git@github.com:")
439 .trim_end_matches('/')
440 .trim_end_matches(".git");
441 let parts: Vec<&str> = path.splitn(3, '/').collect();
442 if parts.len() >= 2 && !parts[0].is_empty() && !parts[1].is_empty() {
443 return Some((parts[0].to_string(), parts[1].to_string()));
444 }
445 return None;
446 }
447
448 if input.starts_with("https://github.com/") || input.starts_with("http://github.com/") {
450 let path = input
451 .trim_start_matches("https://github.com/")
452 .trim_start_matches("http://github.com/")
453 .trim_end_matches('/')
454 .trim_end_matches(".git");
455 let parts: Vec<&str> = path.splitn(3, '/').collect();
456 if parts.len() >= 2 && !parts[0].is_empty() && !parts[1].is_empty() {
457 return Some((parts[0].to_string(), parts[1].to_string()));
458 }
459 return None;
460 }
461
462 if input.starts_with('/')
464 || input.starts_with('.')
465 || input.starts_with('~')
466 || (input.contains(path::MAIN_SEPARATOR) && path::MAIN_SEPARATOR != '/')
467 {
468 return None;
469 }
470
471 let parts: Vec<&str> = input.splitn(3, '/').collect();
473 if parts.len() == 2 && !parts[0].is_empty() && !parts[1].is_empty() {
474 let owner = parts[0];
476 let repo = parts[1].trim_end_matches(".git");
477 if !owner.contains(' ') && !repo.contains(' ') && !repo.contains('/') {
478 return Some((owner.to_string(), repo.to_string()));
479 }
480 }
481
482 None
483}
484
485pub fn project_add(input: &str) -> anyhow::Result<()> {
492 if let Some((owner, repo)) = parse_github_slug(input) {
494 return project_add_github(&owner, &repo);
495 }
496
497 project_add_local(input)
499}
500
501fn project_add_local(path: &str) -> anyhow::Result<()> {
503 let abs_path = if path == "." {
504 env::current_dir()?
505 } else {
506 PathBuf::from(path).canonicalize()?
507 };
508
509 let orch_yml = abs_path.join(".orch.yml");
511 if !orch_yml.exists() {
512 let legacy = abs_path.join(".orchestrator.yml");
514 if legacy.exists() {
515 println!("Found legacy .orchestrator.yml — consider renaming to .orch.yml");
516 } else {
517 anyhow::bail!(
518 "no .orch.yml found in {} — run `orch init` in the project first",
519 abs_path.display()
520 );
521 }
522 }
523
524 let path_str = abs_path.to_string_lossy().to_string();
525 register_project_path(&path_str)?;
526
527 if orch_yml.exists() {
529 let project_content = fs::read_to_string(&orch_yml)?;
530 let project_doc: serde_norway::Value = serde_norway::from_str(&project_content)?;
531 if let Some(repo) = project_doc
532 .get("gh")
533 .and_then(|gh| gh.get("repo"))
534 .and_then(|r| r.as_str())
535 {
536 println!(" repo: {repo}");
537 }
538 }
539
540 Ok(())
541}
542
543pub(crate) fn clone_over_https(slug: &str, dest: &Path, bare: bool) -> Command {
549 let mut cmd = Command::new("git");
550 cmd.args([
551 "-c",
552 "credential.helper=",
553 "-c",
554 "credential.https://github.com.helper=!gh auth git-credential",
555 "clone",
556 ]);
557 if bare {
558 cmd.arg("--bare");
559 }
560 cmd.arg(format!("https://github.com/{slug}.git")).arg(dest);
561 cmd
562}
563
564fn project_add_github(owner: &str, repo: &str) -> anyhow::Result<()> {
566 let projects_dir = home::projects_dir()?;
567 let bare_path = projects_dir.join(owner).join(format!("{repo}.git"));
568 let slug = format!("{owner}/{repo}");
569
570 if bare_path.exists() {
571 println!("Bare clone already exists: {}", bare_path.display());
572 } else {
573 let parent = bare_path
575 .parent()
576 .ok_or_else(|| anyhow::anyhow!("bare path has no parent: {}", bare_path.display()))?;
577 fs::create_dir_all(parent)?;
578
579 println!("Cloning {slug} as bare repo...");
580 let status = clone_over_https(&slug, &bare_path, true).status_with_context()?;
581 if !status.success() {
582 anyhow::bail!("git clone failed for {slug}");
583 }
584
585 println!("Cloned to {}", bare_path.display());
586 }
587
588 let orch_yml = bare_path.join(".orch.yml");
590 if !orch_yml.exists() {
591 let content = format!("# Project-specific orch config\ngh:\n repo: \"{slug}\"\n");
592 fs::write(&orch_yml, content)?;
593 println!("Created .orch.yml with gh.repo: {slug}");
594 }
595
596 let path_str = bare_path.to_string_lossy().to_string();
598 register_project_path(&path_str)?;
599 println!(" repo: {slug}");
600
601 Ok(())
602}
603
604fn register_project_path(path_str: &str) -> anyhow::Result<()> {
606 let config_path = home::config_path()?;
607 let content = if config_path.exists() {
608 fs::read_to_string(&config_path)?
609 } else {
610 String::new()
611 };
612
613 match config::projects_yaml::add_project(&content, path_str)? {
614 config::projects_yaml::ProjectsEdit::Unchanged => {
615 println!("Project already registered: {path_str}");
616 }
617 config::projects_yaml::ProjectsEdit::Updated(updated) => {
618 fs::write(&config_path, updated)?;
619 println!("Added project: {path_str}");
620 }
621 }
622
623 Ok(())
624}
625
626pub fn project_remove(path: &str) -> anyhow::Result<()> {
628 let abs_path = PathBuf::from(path)
629 .canonicalize()
630 .unwrap_or_else(|_| PathBuf::from(path));
631 let path_str = abs_path.to_string_lossy().to_string();
632
633 let config_path = home::config_path()?;
634 if !config_path.exists() {
635 anyhow::bail!("no global config found");
636 }
637
638 let content = fs::read_to_string(&config_path)?;
639 match config::projects_yaml::remove_project(&content, &[&path_str, path])? {
640 config::projects_yaml::ProjectsEdit::Unchanged => {
641 println!("Project not found: {path}");
642 }
643 config::projects_yaml::ProjectsEdit::Updated(updated) => {
644 fs::write(&config_path, updated)?;
645 println!("Removed project: {path_str}");
646 }
647 }
648
649 Ok(())
650}
651
652pub fn project_list() -> anyhow::Result<()> {
654 let projects = config::get_project_paths()?;
655
656 if projects.is_empty() {
657 println!("No projects registered");
658 println!(" Run `orch project add <path>` to register a project");
659 return Ok(());
660 }
661
662 println!("{:<50} REPO", "PATH");
663 println!("{}", "-".repeat(80));
664
665 for path_str in &projects {
666 let path = Path::new(path_str);
667
668 let repo = read_project_repo(path).unwrap_or_else(|| "(.orch.yml not found)".to_string());
670
671 let status = if path.exists() { "" } else { " (missing)" };
672
673 println!("{path_str:<50} {repo}{status}");
674 }
675
676 Ok(())
677}
678
679pub async fn project_move(old: &str, new: &str) -> anyhow::Result<()> {
681 for slug in [old, new] {
682 if parse_github_slug(slug).is_none() {
683 anyhow::bail!("invalid slug {slug:?}, expected owner/repo");
684 }
685 }
686 let store = init_store().await?;
687 let moved = store.move_repo(old, new).await?;
688 println!("Moved {moved} task(s) from {old} to {new}");
689 println!("Now set gh.repo: {new} in the project's .orch.yml");
690 Ok(())
691}
692
693fn read_project_repo(project_path: &Path) -> Option<String> {
695 let orch_yml = project_path.join(".orch.yml");
696 let content = fs::read_to_string(&orch_yml).ok()?;
697 let doc: serde_norway::Value = serde_norway::from_str(&content).ok()?;
698 doc.get("gh")
699 .and_then(|gh| gh.get("repo"))
700 .and_then(|r| r.as_str())
701 .map(String::from)
702}
703
704pub async fn init_task_manager() -> anyhow::Result<TaskManager> {
706 let repo = config::get_current_repo()
707 .context("'repo' not set — run `orch init` or set gh.repo in .orch.yml")?;
708 let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
709 let store = Arc::new(init_store().await?);
710 Ok(TaskManager::with_store(backend, store, repo))
711}
712
713pub async fn init_store() -> anyhow::Result<TaskStore> {
715 let store = TaskStore::open(&store::default_db_path().await?).await?;
716 if let Some(endpoint) = local::daemon_endpoint().await {
717 store.attach_daemon(endpoint);
718 }
719
720 Ok(store)
721}
722
723#[cfg(test)]
724mod tests {
725 use super::*;
726
727 #[test]
728 fn hours_to_label_prefers_days_for_full_day_windows() {
729 assert_eq!(hours_to_label(24), "1d");
730 assert_eq!(hours_to_label(168), "7d");
731 assert_eq!(hours_to_label(30), "30h");
732 }
733
734 #[test]
735 fn parse_since_supports_days_hours_and_bare_numbers() {
736 assert_eq!(parse_since("7d"), Some(168));
737 assert_eq!(parse_since("24h"), Some(24));
738 assert_eq!(parse_since("36"), Some(36));
739 assert_eq!(parse_since("bad"), None);
740 }
741
742 #[test]
743 fn parse_slug_owner_repo() {
744 let result = parse_github_slug("gabrielkoerich/orch");
745 assert_eq!(
746 result,
747 Some(("gabrielkoerich".to_string(), "orch".to_string()))
748 );
749 }
750
751 #[test]
752 fn parse_slug_https_url() {
753 let result = parse_github_slug("https://github.com/gabrielkoerich/orch");
754 assert_eq!(
755 result,
756 Some(("gabrielkoerich".to_string(), "orch".to_string()))
757 );
758 }
759
760 #[test]
761 fn parse_slug_https_url_with_git_suffix() {
762 let result = parse_github_slug("https://github.com/gabrielkoerich/orch.git");
763 assert_eq!(
764 result,
765 Some(("gabrielkoerich".to_string(), "orch".to_string()))
766 );
767 }
768
769 #[test]
770 fn parse_slug_https_url_trailing_slash() {
771 let result = parse_github_slug("https://github.com/gabrielkoerich/orch/");
772 assert_eq!(
773 result,
774 Some(("gabrielkoerich".to_string(), "orch".to_string()))
775 );
776 }
777
778 #[test]
779 fn parse_slug_absolute_path_returns_none() {
780 assert_eq!(parse_github_slug("/Users/gb/Projects/my-app"), None);
781 }
782
783 #[test]
784 fn parse_slug_relative_path_returns_none() {
785 assert_eq!(parse_github_slug("./my-app"), None);
786 }
787
788 #[test]
789 fn parse_slug_dot_returns_none() {
790 assert_eq!(parse_github_slug("."), None);
791 }
792
793 #[test]
794 fn parse_slug_tilde_path_returns_none() {
795 assert_eq!(parse_github_slug("~/Projects/my-app"), None);
796 }
797
798 #[test]
799 fn parse_slug_single_word_returns_none() {
800 assert_eq!(parse_github_slug("my-app"), None);
801 }
802
803 #[test]
804 fn parse_slug_three_segments_returns_none() {
805 assert_eq!(parse_github_slug("a/b/c"), None);
807 }
808
809 #[test]
810 fn parse_slug_ssh_url() {
811 let result = parse_github_slug("git@github.com:gabrielkoerich/bean.git");
812 assert_eq!(
813 result,
814 Some(("gabrielkoerich".to_string(), "bean".to_string()))
815 );
816 }
817
818 #[test]
819 fn parse_slug_ssh_url_no_git_suffix() {
820 let result = parse_github_slug("git@github.com:gabrielkoerich/bean");
821 assert_eq!(
822 result,
823 Some(("gabrielkoerich".to_string(), "bean".to_string()))
824 );
825 }
826}