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