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