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