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