Skip to main content

orch/cli/
task.rs

1use crate::backends::{ExternalBackend, ExternalId, Status};
2use crate::cli::init_task_manager;
3use crate::cmd::SyncCommandErrorContext;
4use crate::config;
5use crate::engine::router::Router;
6use crate::engine::runner::TaskRunner;
7use crate::engine::tasks::{status_to_task_status, CreateTaskRequest, Task, TaskFilter, TaskType};
8use crate::home;
9use crate::store;
10use crate::store::TaskStore;
11use crate::tmux::TmuxManager;
12use anyhow::Context;
13use chrono::{DateTime, Utc};
14use futures::future::join_all;
15use std::sync::Arc;
16
17/// Format a timestamp as a human-readable age (e.g. "5m", "2h", "3d").
18fn format_age(updated_at: &str) -> String {
19    let Ok(dt) = DateTime::parse_from_rfc3339(updated_at) else {
20        return "-".to_string();
21    };
22    let secs = (Utc::now() - dt.with_timezone(&Utc)).num_seconds();
23    if secs < 0 {
24        return "now".to_string();
25    }
26    if secs < 60 {
27        format!("{}s", secs)
28    } else if secs < 3600 {
29        format!("{}m", secs / 60)
30    } else if secs < 86400 {
31        format!("{}h", secs / 3600)
32    } else {
33        let days = secs / 86400;
34        if days >= 365 {
35            let years = days / 365;
36            format!("{}y", years)
37        } else {
38            format!("{}d", days)
39        }
40    }
41}
42
43/// Truncate an error message to a maximum length, appending an ellipsis when truncated.
44/// Format one `review_attempt_failed` activity row for `orch task inspect`.
45fn review_attempt_line(activity: &store::TaskActivity) -> String {
46    let field = |key: &str| {
47        activity
48            .details
49            .get(key)
50            .and_then(|v| v.as_str())
51            .unwrap_or("-")
52            .to_string()
53    };
54    let external = activity
55        .details
56        .get("external")
57        .and_then(|v| v.as_bool())
58        .unwrap_or(false);
59    format!(
60        "{}  {}{}: {}",
61        activity.timestamp,
62        field("cause"),
63        if external { " (external)" } else { "" },
64        truncate_err(field("reason").trim(), 160)
65    )
66}
67
68fn truncate_err(err: &str, max: usize) -> String {
69    if err.len() > max {
70        let mut end = max;
71        while end > 0 && !err.is_char_boundary(end) {
72            end -= 1;
73        }
74        format!("{}...", &err[..end])
75    } else {
76        err.to_string()
77    }
78}
79
80fn format_run_duration(duration_secs: f64) -> String {
81    if duration_secs < 60.0 {
82        format!("{duration_secs:.0}s")
83    } else {
84        format!("{:.1}m", duration_secs / 60.0)
85    }
86}
87
88fn format_run_cost(cost: f64) -> String {
89    if cost <= 0.0 {
90        "-".to_string()
91    } else {
92        format!("${cost:.2}")
93    }
94}
95
96fn format_run_text(text: &str, verbose: bool, max: usize) -> String {
97    if verbose {
98        text.to_string()
99    } else if text.is_empty() {
100        String::new()
101    } else {
102        truncate_err(text, max)
103    }
104}
105
106/// Store-first status update for CLI: updates SQLite first, then mirrors to backend.
107async fn update_status_store_first(
108    store: &Option<Arc<TaskStore>>,
109    backend: &Arc<dyn ExternalBackend>,
110    repo: &str,
111    id: &ExternalId,
112    status: Status,
113) -> anyhow::Result<()> {
114    let db_status = status_to_task_status(status);
115    if let Some(ref s) = store {
116        if let Ok(Some(store_id)) = s.resolve_task_id(repo, &id.0).await {
117            s.update_status(store_id, db_status).await?;
118        }
119    }
120    if let Err(e) = backend.update_status(id, status).await {
121        tracing::warn!(
122            task_id = id.0,
123            ?status,
124            err = %e,
125            "failed to mirror status to backend — store is authoritative"
126        );
127    }
128    Ok(())
129}
130
131fn matches_project_filter(repo: &str, project: &str) -> bool {
132    let repo_name = repo.rsplit('/').next().unwrap_or(repo);
133    repo == project || repo_name == project || repo.ends_with(&format!("/{project}"))
134}
135
136fn waiting_title(title: &str, status: &str, blockers: &[String]) -> String {
137    if status == "waiting" && !blockers.is_empty() {
138        format!("{title} [waiting on {}]", blockers.join(", "))
139    } else {
140        title.to_string()
141    }
142}
143
144fn dep_label(task_repo: &str, dep_repo: &str, number: i64) -> String {
145    if task_repo == dep_repo {
146        format!("#{number}")
147    } else {
148        format!("{dep_repo}#{number}")
149    }
150}
151
152async fn refuse_external_claim(
153    store: &TaskStore,
154    repo: &str,
155    external_id: &str,
156) -> anyhow::Result<()> {
157    if let Some(id) = store.resolve_task_id(repo, external_id).await? {
158        crate::engine::dependencies::refuse_if_waiting(store, id).await?;
159    }
160    Ok(())
161}
162
163/// Refuse to move a done task back into the pipeline.
164///
165/// Done is terminal: a done task keeps the body it was created with, so
166/// reviving one re-runs a prompt that may be months stale (#3780)
167fn refuse_if_done(resolved: &store::CliTaskRef, action: &str) -> anyhow::Result<()> {
168    if resolved.status != crate::store::TaskStatus::Done.as_str() {
169        return Ok(());
170    }
171    anyhow::bail!(
172        "{} is done — {action} does not revive done tasks; file a new issue or task for follow-up work",
173        resolved.display_spec()
174    )
175}
176
177/// True when the task still has an open dependency and must stay `waiting`.
178async fn release_or_keep_waiting(store: &TaskStore, task_id: i64) -> anyhow::Result<bool> {
179    Ok(store.status_after_unblock(task_id).await? == crate::store::TaskStatus::Waiting)
180}
181
182/// List tasks with optional filters.
183pub async fn list(
184    status: Option<String>,
185    source: Option<String>,
186    global: bool,
187    project: Option<String>,
188) -> anyhow::Result<()> {
189    // When no project context is available (e.g. running from a worktree without
190    // .orch.yml), fall back to a store-only listing across all configured projects
191    // instead of printing a fatal error.
192    if global || project.is_some() {
193        return list_from_global_store(status, source, project.as_deref()).await;
194    }
195
196    let task_manager = match init_task_manager().await {
197        Ok(tm) => tm,
198        Err(e) => {
199            tracing::debug!("no project context available, falling back to global store: {e:#}");
200            return list_from_global_store(status, source, project.as_deref()).await;
201        }
202    };
203    let filter = TaskFilter { status, source };
204    let tasks = task_manager.list_tasks(filter).await?;
205
206    if tasks.is_empty() {
207        println!("No tasks found.");
208        return Ok(());
209    }
210
211    let store: Option<Arc<TaskStore>> = crate::cli::init_store().await.ok().map(Arc::new);
212    let repo = config::get_current_repo().unwrap_or_default();
213
214    // Preload all store tasks for this repo into a map keyed by external_id.
215    // This avoids 4 SQL queries per external task (resolve_id + get, twice for agent and attempts).
216    let store_by_ext_id: std::collections::HashMap<String, crate::store::Task> =
217        if let Some(ref s) = store {
218            s.list_all(&repo)
219                .await
220                .unwrap_or_default()
221                .into_iter()
222                .filter_map(|t| t.external_id.clone().map(|eid| (eid, t)))
223                .collect()
224        } else {
225            std::collections::HashMap::new()
226        };
227    let waiting_on = if let Some(ref s) = store {
228        s.unmet_labels_by_task().await.unwrap_or_default()
229    } else {
230        std::collections::HashMap::new()
231    };
232
233    println!(
234        "{:<15} {:<12} {:<20} {:<24} {:<10} {:<6} {:<5} TITLE",
235        "ID", "TYPE", "STATUS", "PROJECT", "AGENT", "AGE", "TRIES"
236    );
237    println!("{}", "-".repeat(125));
238
239    for task in tasks {
240        match task {
241            Task::External(ext) => {
242                let status = ext
243                    .labels
244                    .iter()
245                    .find(|l| l.starts_with("status:"))
246                    .map(|s| s.replace("status:", ""))
247                    .unwrap_or_else(|| "unknown".to_string());
248                let store_task = store_by_ext_id.get(&ext.id.0);
249                let agent = store_task
250                    .and_then(|t| t.agent.as_deref())
251                    .unwrap_or("")
252                    .to_string();
253                let age = format_age(&ext.updated_at);
254                let project = store_task.map(|t| t.repo.as_str()).unwrap_or(&repo);
255                let tries = store_task
256                    .map(|t| {
257                        if t.attempts > 0 {
258                            t.attempts.to_string()
259                        } else {
260                            String::new()
261                        }
262                    })
263                    .unwrap_or_default();
264                let blockers = store_task
265                    .and_then(|row| waiting_on.get(&row.id))
266                    .map(Vec::as_slice)
267                    .unwrap_or(&[]);
268                let title = waiting_title(&ext.title, &status, blockers);
269                println!(
270                    "{:<15} {:<12} {:<20} {:<24} {:<10} {:<6} {:<5} {}",
271                    ext.id.0, "external", status, project, agent, age, tries, title
272                );
273            }
274            Task::Internal(int) => {
275                let agent = int.agent.as_deref().unwrap_or("-");
276                let age = format_age(&int.updated_at);
277                let project = &int.repo;
278                let tries = if int.attempts > 0 {
279                    int.attempts.to_string()
280                } else {
281                    "-".to_string()
282                };
283                let blockers = waiting_on.get(&int.id).map(Vec::as_slice).unwrap_or(&[]);
284                let title = if int.status == crate::store::TaskStatus::Blocked {
285                    if let Some(ref reason) = int.block_reason {
286                        format!("{} [blocked: {}]", int.title, reason)
287                    } else {
288                        int.title.clone()
289                    }
290                } else {
291                    waiting_title(&int.title, int.status.as_str(), blockers)
292                };
293                println!(
294                    "{:<15} {:<12} {:<20} {:<24} {:<10} {:<6} {:<5} {}",
295                    format!("internal:{}", int.id),
296                    "internal",
297                    int.status.as_str(),
298                    project,
299                    agent,
300                    age,
301                    tries,
302                    title
303                );
304            }
305        }
306    }
307
308    Ok(())
309}
310
311/// Fallback listing used when no project context is available (no `.orch.yml` in CWD or parents).
312///
313/// Queries the global SQLite store directly without scoping to a specific repo.
314/// This suppresses the fatal "no valid projects" error that previously appeared
315/// when agents ran `orch task list` from inside a worktree.
316async fn list_from_global_store(
317    status: Option<String>,
318    source: Option<String>,
319    project: Option<&str>,
320) -> anyhow::Result<()> {
321    let store = match crate::cli::init_store().await {
322        Ok(s) => s,
323        Err(_) => {
324            println!("No tasks found.");
325            return Ok(());
326        }
327    };
328
329    let tasks = if let Some(ref status_str) = status {
330        if status_str == "all" {
331            store.list_all_global().await?
332        } else {
333            let task_status = crate::store::TaskStatus::from_str(status_str)
334                .ok_or_else(|| anyhow::anyhow!(
335                    "invalid status: '{}'. allowed: new, routed, in_progress, needs_review, in_review, blocked, waiting, done, all",
336                    status_str
337                ))?;
338            store.list_all_by_status_global(task_status).await?
339        }
340    } else {
341        store.list_all_active_global().await?
342    };
343
344    // Apply optional source filter.
345    let tasks: Vec<_> = tasks
346        .into_iter()
347        .filter(|t| source.as_ref().map(|s| &t.source == s).unwrap_or(true))
348        .filter(|t| {
349            project
350                .map(|p| matches_project_filter(&t.repo, p))
351                .unwrap_or(true)
352        })
353        .collect();
354
355    if tasks.is_empty() {
356        println!("No tasks found.");
357        return Ok(());
358    }
359
360    let waiting_on = store.unmet_labels_by_task().await.unwrap_or_default();
361
362    println!(
363        "{:<15} {:<12} {:<20} {:<24} {:<10} {:<6} {:<5} TITLE",
364        "ID", "TYPE", "STATUS", "PROJECT", "AGENT", "AGE", "TRIES"
365    );
366    println!("{}", "-".repeat(125));
367
368    for task in tasks {
369        let type_str = if task.origin == "internal" {
370            "internal"
371        } else {
372            "external"
373        };
374        let project = task.repo.as_str();
375        let id_str = if task.origin == "internal" {
376            format!("internal:{}", task.id)
377        } else {
378            task.external_id
379                .clone()
380                .unwrap_or_else(|| task.id.to_string())
381        };
382        let agent = task.agent.as_deref().unwrap_or("-");
383        let age = format_age(&task.updated_at);
384        let tries = if task.attempts > 0 {
385            task.attempts.to_string()
386        } else {
387            "-".to_string()
388        };
389        let blockers = waiting_on.get(&task.id).map(Vec::as_slice).unwrap_or(&[]);
390        let title = if task.status == crate::store::TaskStatus::Blocked {
391            if let Some(ref reason) = task.block_reason {
392                format!("{} [blocked: {}]", task.title, reason)
393            } else {
394                task.title.clone()
395            }
396        } else {
397            waiting_title(&task.title, task.status.as_str(), blockers)
398        };
399        println!(
400            "{:<15} {:<12} {:<20} {:<24} {:<10} {:<6} {:<5} {}",
401            id_str,
402            type_str,
403            task.status.as_str(),
404            project,
405            agent,
406            age,
407            tries,
408            title
409        );
410    }
411
412    Ok(())
413}
414
415/// Create a new task.
416pub async fn add(
417    title: String,
418    body: Option<String>,
419    labels: Vec<String>,
420    source: String,
421    depends_on: Vec<String>,
422) -> anyhow::Result<()> {
423    let task_manager = init_task_manager().await?;
424
425    // Labels or dependencies create a GitHub issue. Dependencies need the native link
426    let task_type = if !labels.is_empty() || !depends_on.is_empty() {
427        TaskType::External
428    } else {
429        TaskType::Internal
430    };
431
432    let req = CreateTaskRequest {
433        title,
434        body: body.unwrap_or_default(),
435        task_type,
436        labels,
437        source,
438        source_id: String::new(),
439    };
440    let task = task_manager.create_task(req).await?;
441
442    match task {
443        Task::Internal(t) => {
444            println!("Created internal task #{}: {}", t.id, t.title);
445        }
446        Task::External(t) => {
447            if !depends_on.is_empty() {
448                link_created_dependencies(&t, &depends_on).await?;
449            }
450            println!("Created external task #{}: {}", t.id.0, t.title);
451        }
452    }
453
454    Ok(())
455}
456
457async fn link_created_dependencies(
458    task: &crate::backends::ExternalTask,
459    depends_on: &[String],
460) -> anyhow::Result<()> {
461    use crate::backends::github::GitHubBackend;
462    use crate::engine::dependencies::parse_depends_on_token;
463    use crate::store::{DepSource, NewDependency, UpsertExternal};
464
465    let repo =
466        config::get_current_repo().context("'repo' not set — ensure .orch.yml has gh.repo")?;
467    let issue_number: i64 = task
468        .id
469        .0
470        .parse()
471        .with_context(|| format!("created issue id '{}' is not a number", task.id.0))?;
472    let backend = GitHubBackend::new(repo.clone())?;
473    let store = crate::cli::init_store().await?;
474    let store_id = store
475        .upsert_external(&UpsertExternal {
476            repo: &repo,
477            ext_id: &task.id.0,
478            title: &task.title,
479            body: &task.body,
480            author: &task.author,
481            url: &task.url,
482            labels: &task.labels,
483            origin: "github",
484        })
485        .await?;
486    let mut rows = Vec::new();
487    for token in depends_on {
488        let Some(dep) = parse_depends_on_token(token, &repo) else {
489            anyhow::bail!("invalid --depends-on value '{token}'");
490        };
491        let source = match backend
492            .add_dependency(issue_number, &dep.repo, dep.number)
493            .await
494        {
495            Ok(()) => DepSource::Github,
496            Err(err) => {
497                eprintln!(
498                    "warning: could not link {}#{} on GitHub ({err}). Stored the dependency locally.",
499                    dep.repo, dep.number
500                );
501                DepSource::Cli
502            }
503        };
504        rows.push(NewDependency {
505            repo: dep.repo,
506            number: dep.number,
507            source,
508        });
509    }
510    store.replace_dependencies(store_id, &rows).await?;
511    Ok(())
512}
513
514/// Get task details by ID.
515pub async fn get(id: &str) -> anyhow::Result<()> {
516    use crate::backends::github::GitHubBackend;
517    use crate::engine::tasks::store_task_to_external;
518
519    let store = crate::cli::init_store().await?;
520    let resolved = crate::cli::task_ref::resolve(&store, id).await?;
521    let store_arc: Option<Arc<TaskStore>> = Some(Arc::new(store.clone()));
522    let repo = resolved.repo.clone();
523
524    if resolved.is_internal() {
525        let store_id = resolved
526            .store_id
527            .context("internal task missing store id")?;
528        let int = store.get(store_id).await?;
529        println!("ID: {} (internal)", int.id);
530        println!("Title: {}", int.title);
531        println!("Status: {}", int.status.as_str());
532        println!("Source: {}", int.source);
533        if let Some(model) = &int.model {
534            println!("Model: {}", model);
535        }
536        if !int.complexity.is_empty() {
537            println!("Complexity: {}", int.complexity);
538        }
539        if let Some(reason) = &int.block_reason {
540            println!("Block reason: {}", reason);
541        }
542        if int.status == crate::store::TaskStatus::Waiting {
543            let blockers = store.unmet_blocker_labels(int.id).await.unwrap_or_default();
544            if !blockers.is_empty() {
545                println!("Waiting on: {}", blockers.join(", "));
546            }
547        }
548        if int.route_attempts > 0 {
549            println!("Route attempts: {}", int.route_attempts);
550        }
551        if int.attempts > 0 {
552            println!("Attempts: {}", int.attempts);
553        }
554        if int.review_cycles > 0 {
555            println!("Review cycles: {}", int.review_cycles);
556        }
557        if let Some(pr) = int.pr_number {
558            println!("PR: #{}", pr);
559        }
560        if !int.branch.is_empty() {
561            println!("Branch: {}", int.branch);
562        }
563        if !int.last_error.is_empty() {
564            let err = truncate_err(&int.last_error, 200);
565            println!("Last error: {}", err);
566        }
567        if let Some(parent) = int.parent_id {
568            println!("Parent: internal:{}", parent);
569        }
570        if int.input_tokens > 0 || int.output_tokens > 0 {
571            println!(
572                "Tokens: {} in / {} out — ${:.6}",
573                int.input_tokens, int.output_tokens, int.total_cost_usd
574            );
575        }
576        println!("Created: {}", int.created_at);
577        println!("Updated: {}", int.updated_at);
578        println!("\n{}", int.body);
579        return Ok(());
580    }
581
582    let ext_id = ExternalId(resolved.external_id.clone());
583    let backend = GitHubBackend::new(repo.clone())?;
584    let ext = match backend.get_task(&ext_id).await {
585        Ok(ext) => ext,
586        Err(err) => match resolved.store_id {
587            Some(store_id) => store_task_to_external(&store.get(store_id).await?),
588            None => return Err(err),
589        },
590    };
591
592    println!("ID: {} (external)", ext.id.0);
593    println!("Title: {}", ext.title);
594    println!("State: {}", ext.state);
595    println!("Labels: {}", ext.labels.join(", "));
596    println!("Author: {}", ext.author);
597    println!("URL: {}", ext.url);
598    println!("Created: {}", ext.created_at);
599    println!("Updated: {}", ext.updated_at);
600
601    if let Some(ref s) = store_arc {
602        if let Ok(Some(t)) = s.get_by_external_id(&repo, &ext.id.0).await {
603            if let Some(ref agent) = t.agent {
604                println!("Agent: {}", agent);
605            }
606            if let Some(ref model) = t.model {
607                println!("Model: {}", model);
608            }
609            if !t.complexity.is_empty() {
610                println!("Complexity: {}", t.complexity);
611            }
612            if t.route_attempts > 0 {
613                println!("Route attempts: {}", t.route_attempts);
614            }
615            if t.attempts > 0 {
616                println!("Attempts: {}", t.attempts);
617            }
618            if t.review_cycles > 0 {
619                println!("Review cycles: {}", t.review_cycles);
620            }
621            if let Some(pr) = t.pr_number {
622                if pr > 0 {
623                    println!("PR: #{}", pr);
624                }
625            }
626            if !t.branch.is_empty() {
627                println!("Branch: {}", t.branch);
628            }
629            if !t.last_error.is_empty() {
630                println!("Last error: {}", truncate_err(&t.last_error, 200));
631            }
632            if t.status == crate::store::TaskStatus::Waiting {
633                let blockers = s.unmet_blocker_labels(t.id).await.unwrap_or_default();
634                if !blockers.is_empty() {
635                    println!("Waiting on: {}", blockers.join(", "));
636                }
637            }
638        }
639    }
640    let usage = store::get_token_usage(&store_arc, &repo, &ext.id.0).await;
641    let cost = store::get_cost_estimate(&store_arc, &repo, &ext.id.0).await;
642    if usage.total_tokens() > 0 || cost.total_cost_usd > 0.0 {
643        println!(
644            "Tokens: {} in / {} out — ${:.6}",
645            usage.input_tokens, usage.output_tokens, cost.total_cost_usd
646        );
647    }
648
649    println!("\n{}", ext.body);
650
651    Ok(())
652}
653
654/// Show task status summary.
655pub async fn status(json: bool) -> anyhow::Result<()> {
656    use crate::store::TaskStatus;
657
658    let task_manager = init_task_manager().await?;
659
660    let statuses = [
661        Status::New,
662        Status::Routed,
663        Status::InProgress,
664        Status::Done,
665        Status::Blocked,
666        Status::InReview,
667        Status::NeedsReview,
668        Status::Waiting,
669    ];
670
671    // Fetch all tasks from both backends
672    let all_external = task_manager.list_all_external_tasks().await?;
673    let all_internal = task_manager.list_all_internal().await.unwrap_or_default();
674
675    // Count external tasks per status via labels
676    let ext_counts: Vec<usize> = statuses
677        .iter()
678        .map(|s| {
679            let label = s.as_label().to_string();
680            all_external
681                .iter()
682                .filter(|t| t.labels.contains(&label))
683                .count()
684        })
685        .collect();
686
687    // Count internal tasks per status
688    let int_counts: Vec<usize> = statuses
689        .iter()
690        .map(|s| {
691            let ts = match s {
692                Status::New => TaskStatus::New,
693                Status::Routed => TaskStatus::Routed,
694                Status::InProgress => TaskStatus::InProgress,
695                Status::Done => TaskStatus::Done,
696                Status::Blocked => TaskStatus::Blocked,
697                Status::InReview => TaskStatus::InReview,
698                Status::NeedsReview => TaskStatus::NeedsReview,
699                Status::Waiting => TaskStatus::Waiting,
700            };
701            all_internal.iter().filter(|t| t.status == ts).count()
702        })
703        .collect();
704
705    // Calculate total cost using a single aggregate query instead of per-task lookups.
706    let store: Option<Arc<TaskStore>> = crate::cli::init_store().await.ok().map(Arc::new);
707    let repo = config::get_current_repo().unwrap_or_default();
708    let mut total_input_tokens: u64 = 0;
709    let mut total_output_tokens: u64 = 0;
710    let mut total_cost: f64 = 0.0;
711
712    if let Some(ref s) = store {
713        if let Ok((input, output, cost)) = s.cost_summary(&repo).await {
714            total_input_tokens = input as u64;
715            total_output_tokens = output as u64;
716            total_cost = cost;
717        }
718    } else {
719        // No store available: sum up internal task costs directly from already-loaded data.
720        for task in &all_internal {
721            total_input_tokens += task.input_tokens as u64;
722            total_output_tokens += task.output_tokens as u64;
723            total_cost += task.total_cost_usd;
724        }
725    }
726
727    // The engine process owns the live rate-limit state, so it leaves the reset epoch in
728    // KV for this one. Stale entries read as expired and are dropped.
729    let rate_limited_until = match store.as_ref() {
730        Some(s) => s
731            .kv_get(crate::engine::RATE_LIMITED_UNTIL_KEY)
732            .await
733            .ok()
734            .flatten()
735            .and_then(|v| v.parse::<i64>().ok())
736            .filter(|reset_at| *reset_at > chrono::Utc::now().timestamp()),
737        None => None,
738    };
739
740    if json {
741        let mut map = serde_json::Map::new();
742        for (i, s) in statuses.iter().enumerate() {
743            let key = s.as_label().replace("status:", "");
744            let mut entry = serde_json::Map::new();
745            entry.insert(
746                "external".to_string(),
747                serde_json::Value::Number(ext_counts[i].into()),
748            );
749            entry.insert(
750                "internal".to_string(),
751                serde_json::Value::Number(int_counts[i].into()),
752            );
753            map.insert(key, serde_json::Value::Object(entry));
754        }
755
756        map.insert(
757            "total_cost_usd".to_string(),
758            serde_json::Value::Number(
759                serde_json::Number::from_f64(total_cost).unwrap_or(serde_json::Number::from(0)),
760            ),
761        );
762        map.insert(
763            "total_input_tokens".to_string(),
764            serde_json::Value::Number(total_input_tokens.into()),
765        );
766        map.insert(
767            "total_output_tokens".to_string(),
768            serde_json::Value::Number(total_output_tokens.into()),
769        );
770        map.insert(
771            "total_tokens".to_string(),
772            serde_json::Value::Number((total_input_tokens + total_output_tokens).into()),
773        );
774
775        if let Some(reset_at) = rate_limited_until {
776            map.insert(
777                "github_rate_limited_until".to_string(),
778                serde_json::Value::Number(reset_at.into()),
779            );
780        }
781
782        println!("{}", serde_json::to_string_pretty(&map)?);
783    } else {
784        if let Some(reset_at) = rate_limited_until {
785            println!(
786                "GitHub: rate limited until {}",
787                crate::engine::format_rate_limited_until(reset_at)
788            );
789            println!();
790        }
791
792        println!("{:<20} {:>8}  {:>8}", "STATUS", "EXTERNAL", "INTERNAL");
793        println!("{}", "-".repeat(42));
794        let total_ext: usize = ext_counts.iter().sum();
795        let total_int: usize = int_counts.iter().sum();
796        for (i, s) in statuses.iter().enumerate() {
797            let ext = ext_counts[i];
798            let int = int_counts[i];
799            if ext > 0 || int > 0 {
800                println!(
801                    "{:<20} {:>8}  {:>8}",
802                    s.as_label().replace("status:", ""),
803                    ext,
804                    int
805                );
806            }
807        }
808        println!("{}", "-".repeat(42));
809        println!("{:<20} {:>8}  {:>8}", "total", total_ext, total_int);
810
811        // Show cost summary if any
812        if total_cost > 0.0 {
813            println!();
814            println!("Cost summary:");
815            println!(
816                "  Total tokens: {}",
817                total_input_tokens + total_output_tokens
818            );
819            println!("  Total cost:   ${:.6}", total_cost);
820        }
821    }
822
823    Ok(())
824}
825
826/// Route a task to an agent.
827pub async fn route(id: &str) -> anyhow::Result<()> {
828    use crate::backends::github::GitHubBackend;
829    use crate::backends::ExternalBackend;
830    use crate::engine::tasks::store_task_to_external;
831    use crate::store::TaskStatus;
832
833    let store: Arc<TaskStore> = Arc::new(crate::cli::init_store().await?);
834    let resolved = crate::cli::task_ref::resolve(&store, id).await?;
835    let repo = resolved.repo.clone();
836    let ext_id = ExternalId(resolved.external_id.clone());
837
838    let (task, backend) = if resolved.is_internal() {
839        let store_id = resolved
840            .store_id
841            .context("internal task missing store id")?;
842        crate::engine::dependencies::refuse_if_waiting(&store, store_id).await?;
843        (
844            store_task_to_external(&store.get(store_id).await?),
845            None::<Arc<dyn ExternalBackend>>,
846        )
847    } else {
848        let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
849        refuse_external_claim(&store, &repo, &ext_id.0).await?;
850        (backend.get_task(&ext_id).await?, Some(backend))
851    };
852
853    let mut router = Router::from_config();
854    let result = router.route(&task, &store, &repo).await?;
855
856    router
857        .store_route_result(&ext_id.0, &result, &store, &repo)
858        .await?;
859
860    if let Some(backend) = backend {
861        let labels = vec![
862            format!("agent:{}", result.agent),
863            format!("complexity:{}", result.complexity),
864        ];
865        backend.set_labels(&ext_id, &labels).await?;
866        update_status_store_first(&Some(store), &backend, &repo, &ext_id, Status::Routed).await?;
867    } else if let Some(store_id) = resolved.store_id {
868        store.update_status(store_id, TaskStatus::Routed).await?;
869    }
870
871    println!(
872        "Routed task {} → {} (complexity: {}, reason: {})",
873        resolved.display_spec(),
874        result.agent,
875        result.complexity,
876        result.reason
877    );
878
879    Ok(())
880}
881
882/// Run a task (manual execution).
883pub async fn run(id: Option<String>) -> anyhow::Result<()> {
884    use crate::backends::github::GitHubBackend;
885    use crate::backends::ExternalBackend;
886    use crate::engine::router::get_route_result;
887    use crate::store::TaskStatus;
888
889    let store: Arc<TaskStore> = Arc::new(crate::cli::init_store().await?);
890
891    let (repo, task_id, backend) = match id {
892        Some(id) => {
893            let resolved = crate::cli::task_ref::resolve(&store, &id).await?;
894            let backend: Option<Arc<dyn ExternalBackend>> = if resolved.is_internal() {
895                None
896            } else {
897                Some(Arc::new(GitHubBackend::new(resolved.repo.clone())?))
898            };
899            (resolved.repo, resolved.external_id, backend)
900        }
901        None => {
902            let repo = config::get_current_repo()
903                .context("'repo' not set — ensure .orch.yml has gh.repo")?;
904            let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
905            let routed = backend.list_by_status(Status::Routed).await?;
906            let task_id = if let Some(task) = routed.first() {
907                task.id.0.clone()
908            } else {
909                let new = backend.list_by_status(Status::New).await?;
910                if let Some(task) = new.first() {
911                    task.id.0.clone()
912                } else {
913                    anyhow::bail!("no runnable tasks found");
914                }
915            };
916            (repo, task_id, Some(backend))
917        }
918    };
919
920    let route_result = get_route_result(&store, &repo, &task_id).await.ok();
921    let agent = route_result.as_ref().map(|r| r.agent.clone());
922    let model = route_result.as_ref().and_then(|r| r.model.clone());
923
924    println!(
925        "Running task #{} (agent: {}, model: {})",
926        task_id,
927        agent.as_deref().unwrap_or("default"),
928        model.as_deref().unwrap_or("default")
929    );
930
931    refuse_external_claim(&store, &repo, &task_id).await?;
932
933    let ext_id = ExternalId(task_id.clone());
934    let started_at = Utc::now();
935    if let Some(ref backend) = backend {
936        update_status_store_first(
937            &Some(store.clone()),
938            backend,
939            &repo,
940            &ext_id,
941            Status::InProgress,
942        )
943        .await?;
944    } else if let Some(store_id) = store.resolve_task_id(&repo, &task_id).await? {
945        store
946            .update_status(store_id, TaskStatus::InProgress)
947            .await?;
948    }
949
950    let runner = TaskRunner::new(repo).with_store(store);
951    runner
952        .run(
953            &task_id,
954            agent.as_deref(),
955            model.as_deref(),
956            backend.as_deref(),
957            &started_at,
958        )
959        .await?;
960
961    println!("Task #{} completed", task_id);
962    Ok(())
963}
964
965/// Retry a task (reset to new).
966///
967/// When `agent` is provided, the task is force-routed to that agent/model and
968/// set directly to `Routed` status, bypassing the router entirely.
969pub async fn retry(id: &str, agent: Option<String>, model: Option<String>) -> anyhow::Result<()> {
970    use crate::backends::github::GitHubBackend;
971    use crate::backends::ExternalBackend;
972    use crate::store::TaskStatus;
973
974    let s = Arc::new(crate::cli::init_store().await?);
975    let resolved = crate::cli::task_ref::resolve(&s, id).await?;
976    refuse_if_done(&resolved, "retry")?;
977    let store = Some(s.clone());
978    let repo = resolved.repo.clone();
979    let shown = resolved.display_spec();
980
981    if resolved.is_internal() {
982        let store_id = resolved
983            .store_id
984            .context("internal task missing store id")?;
985        crate::engine::dependencies::refuse_if_waiting(&s, store_id).await?;
986        store::store_reset_counters(&store, &repo, &resolved.external_id).await;
987
988        if let Some(ref forced_agent) = agent {
989            let fields = retry_force_fields(forced_agent, model.as_deref());
990            s.set_fields(store_id, &fields).await?;
991            s.update_status(store_id, TaskStatus::Routed).await?;
992            let model_hint = model.as_deref().unwrap_or("(router default)");
993            println!(
994                "Task {shown} force-routed to {forced_agent}:{model_hint} (set to routed, dispatches on next tick)"
995            );
996        } else {
997            s.update_status(store_id, TaskStatus::New).await?;
998            println!("Task {shown} reset to new (attempts reset, will be re-routed)");
999        }
1000        return Ok(());
1001    }
1002
1003    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
1004    let ext_id = ExternalId(resolved.external_id.clone());
1005    refuse_external_claim(&s, &repo, &ext_id.0).await?;
1006
1007    let task = backend.get_task(&ext_id).await?;
1008    for label in &task.labels {
1009        if label.starts_with("agent:") {
1010            backend.remove_label(&ext_id, label).await?;
1011        }
1012    }
1013
1014    store::store_reset_counters(&store, &repo, &ext_id.0).await;
1015
1016    if let Some(ref forced_agent) = agent {
1017        backend
1018            .set_labels(&ext_id, &[format!("agent:{forced_agent}")])
1019            .await?;
1020
1021        if let Some(store_id) = resolved.store_id {
1022            let fields = retry_force_fields(forced_agent, model.as_deref());
1023            s.set_fields(store_id, &fields).await?;
1024        }
1025
1026        update_status_store_first(&store, &backend, &repo, &ext_id, Status::Routed).await?;
1027        let model_hint = model.as_deref().unwrap_or("(router default)");
1028        println!(
1029            "Task {shown} force-routed to {forced_agent}:{model_hint} (set to routed, dispatches on next tick)"
1030        );
1031    } else {
1032        update_status_store_first(&store, &backend, &repo, &ext_id, Status::New).await?;
1033        println!("Task {shown} reset to new (attempts reset, will be re-routed)");
1034    }
1035
1036    Ok(())
1037}
1038
1039fn retry_force_fields<'a>(
1040    forced_agent: &'a str,
1041    model: Option<&'a str>,
1042) -> Vec<(&'a str, serde_json::Value)> {
1043    let mut fields = vec![
1044        ("agent", serde_json::json!(forced_agent)),
1045        (
1046            "route_reason",
1047            serde_json::json!(format!("forced via retry --agent {forced_agent}")),
1048        ),
1049    ];
1050    if let Some(model) = model {
1051        fields.push(("model", serde_json::json!(model)));
1052    }
1053    fields
1054}
1055
1056/// Unblock a task or all blocked tasks.
1057pub async fn unblock(id: &str) -> anyhow::Result<()> {
1058    use crate::backends::github::GitHubBackend;
1059    use crate::backends::ExternalBackend;
1060    use crate::store::TaskStatus;
1061
1062    if id == "all" {
1063        let repo =
1064            config::get_current_repo().context("'repo' not set — ensure .orch.yml has gh.repo")?;
1065        let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
1066        let store = crate::cli::init_store().await.ok().map(std::sync::Arc::new);
1067        let blocked = backend.list_by_status(Status::Blocked).await?;
1068        let needs_review = backend.list_by_status(Status::NeedsReview).await?;
1069
1070        let tasks_to_unblock: Vec<_> = blocked.iter().chain(needs_review.iter()).collect();
1071        let external_count = tasks_to_unblock.len();
1072        let ext_futs = tasks_to_unblock.into_iter().map(|task| {
1073            let store = store.clone();
1074            let backend = backend.clone();
1075            let repo = repo.clone();
1076            let id = task.id.clone();
1077            async move {
1078                store::store_reset_counters(&store, &repo, &id.0).await;
1079                if let Some(ref s) = store {
1080                    if let Ok(Some(store_id)) = s.resolve_task_id(&repo, &id.0).await {
1081                        match s.status_after_unblock(store_id).await {
1082                            Ok(TaskStatus::Waiting) => {
1083                                let _ = backend.update_status(&id, Status::Waiting).await;
1084                                return Ok(());
1085                            }
1086                            Ok(_) => {}
1087                            Err(err) => return Err(err),
1088                        }
1089                    }
1090                }
1091                update_status_store_first(&store, &backend, &repo, &id, Status::New).await
1092            }
1093        });
1094        for result in join_all(ext_futs).await {
1095            result?;
1096        }
1097
1098        let mut internal_count = 0;
1099        if let Some(ref s) = store {
1100            let internal_blocked = s
1101                .list_internal_by_status(&repo, TaskStatus::Blocked)
1102                .await
1103                .unwrap_or_default();
1104            let internal_needs_review = s
1105                .list_internal_by_status(&repo, TaskStatus::NeedsReview)
1106                .await
1107                .unwrap_or_default();
1108            let tasks_internal: Vec<_> = internal_blocked
1109                .iter()
1110                .chain(internal_needs_review.iter())
1111                .collect();
1112            internal_count = tasks_internal.len();
1113            let int_futs = tasks_internal.into_iter().map(|task| {
1114                let store = store.clone();
1115                let s = s.clone();
1116                let repo = repo.clone();
1117                let ext_id = task
1118                    .external_id
1119                    .clone()
1120                    .unwrap_or_else(|| format!("internal:{}", task.id));
1121                let task_id = task.id;
1122                async move {
1123                    store::store_reset_counters(&store, &repo, &ext_id).await;
1124                    match s.status_after_unblock(task_id).await? {
1125                        TaskStatus::Waiting => Ok(()),
1126                        _ => s.update_status(task_id, TaskStatus::New).await,
1127                    }
1128                }
1129            });
1130            for result in join_all(int_futs).await {
1131                result?;
1132            }
1133        }
1134
1135        let total = external_count + internal_count;
1136        println!(
1137            "Unblocked {} tasks ({} external, {} internal) (attempts reset)",
1138            total, external_count, internal_count
1139        );
1140        return Ok(());
1141    }
1142
1143    let s = Arc::new(crate::cli::init_store().await?);
1144    let resolved = crate::cli::task_ref::resolve(&s, id).await?;
1145    refuse_if_done(&resolved, "unblock")?;
1146    let store = Some(s.clone());
1147    let repo = resolved.repo.clone();
1148    let shown = resolved.display_spec();
1149
1150    if resolved.is_internal() {
1151        let store_id = resolved
1152            .store_id
1153            .context("internal task missing store id")?;
1154        store::store_reset_counters(&store, &repo, &resolved.external_id).await;
1155        if release_or_keep_waiting(&s, store_id).await? {
1156            println!("Task {shown} stays waiting on an open dependency");
1157        } else {
1158            s.update_status(store_id, TaskStatus::New).await?;
1159            println!("Unblocked {shown} (attempts reset, will be re-routed)");
1160        }
1161        return Ok(());
1162    }
1163
1164    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
1165    let ext_id = ExternalId(resolved.external_id.clone());
1166    store::store_reset_counters(&store, &repo, &ext_id.0).await;
1167    if let Some(store_id) = resolved.store_id {
1168        if release_or_keep_waiting(&s, store_id).await? {
1169            let _ = backend.update_status(&ext_id, Status::Waiting).await;
1170            println!("Task {shown} stays waiting on an open dependency");
1171            return Ok(());
1172        }
1173    }
1174    update_status_store_first(&store, &backend, &repo, &ext_id, Status::New).await?;
1175    println!("Unblocked {shown} (attempts reset)");
1176
1177    Ok(())
1178}
1179
1180/// Kill tmux sessions and remove the worktree for a closed task.
1181///
1182/// Sessions are killed first (before worktree removal) so that the tmux-active
1183/// guard in `cleanup_task_worktree_with_opts` does not skip the removal.
1184/// Errors are logged but do not fail the close operation.
1185async fn cleanup_sessions_and_worktree(
1186    task_id: &str,
1187    repo: &str,
1188    store: &Option<Arc<crate::store::TaskStore>>,
1189) {
1190    let tmux = TmuxManager::new();
1191
1192    // Session names follow `orch-{project}-{task_id}` and optionally
1193    // `orch-{project}-{task_id}-{suffix}` (e.g. `-review`).
1194    // Build a pattern that matches the task_id as a complete dash-delimited segment.
1195    let safe_id = task_id.replace(':', "-");
1196    let pattern = format!("-{safe_id}");
1197
1198    match tmux.list_sessions().await {
1199        Ok(sessions) => {
1200            for sess in sessions {
1201                let name = &sess.name;
1202                if let Some(pos) = name.find(&pattern) {
1203                    let after = &name[pos + pattern.len()..];
1204                    if after.is_empty() || after.starts_with('-') {
1205                        tracing::info!(
1206                            session = name,
1207                            task_id,
1208                            "killing tmux session for closed task"
1209                        );
1210                        if let Err(e) = tmux.kill_session(name).await {
1211                            tracing::warn!(session = name, err = %e, "failed to kill session on close");
1212                        } else {
1213                            println!("  killed session {name}");
1214                        }
1215                    }
1216                }
1217            }
1218        }
1219        Err(e) => {
1220            tracing::warn!(task_id, err = %e, "could not list tmux sessions during close cleanup");
1221        }
1222    }
1223
1224    // Remove the worktree (sessions are already gone so the tmux guard won't block).
1225    if let Some(ref s) = store {
1226        match crate::engine::cleanup::cleanup_task_worktree(task_id, repo, s).await {
1227            Ok(()) => {}
1228            Err(e) => {
1229                tracing::warn!(task_id, err = %e, "worktree cleanup failed after task close");
1230            }
1231        }
1232    }
1233}
1234
1235/// Mark a task as done (without running an agent).
1236pub async fn close(id: &str, note: Option<&str>) -> anyhow::Result<()> {
1237    use crate::backends::github::GitHubBackend;
1238    use crate::backends::ExternalBackend;
1239    use crate::store::TaskStatus;
1240
1241    let s = crate::cli::init_store().await?;
1242    let resolved = crate::cli::task_ref::resolve(&s, id).await?;
1243    let store = Some(Arc::new(s.clone()));
1244    let repo = resolved.repo.clone();
1245    let shown = resolved.display_spec();
1246
1247    if resolved.is_internal() {
1248        let store_id = resolved
1249            .store_id
1250            .context("internal task missing store id")?;
1251        s.update_status(store_id, TaskStatus::Done).await?;
1252        println!("Closed {shown} (marked done)");
1253        cleanup_sessions_and_worktree(&resolved.external_id, &repo, &store).await;
1254        return Ok(());
1255    }
1256
1257    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
1258    let ext_id = ExternalId(resolved.external_id.clone());
1259
1260    if let Some(text) = note {
1261        backend.post_comment(&ext_id, text).await?;
1262    }
1263
1264    update_status_store_first(&store, &backend, &repo, &ext_id, Status::Done).await?;
1265    println!("Closed {shown} (marked done)");
1266    cleanup_sessions_and_worktree(&resolved.external_id, &repo, &store).await;
1267    Ok(())
1268}
1269
1270/// Attach to a running agent's tmux session.
1271pub async fn attach(id: &str) -> anyhow::Result<()> {
1272    let store = crate::cli::init_store().await?;
1273    let task = crate::cli::task_ref::resolve(&store, id).await?;
1274    let tmux = TmuxManager::new();
1275    let session = tmux.session_name(&task.repo, &task.external_id);
1276    let status = std::process::Command::new("tmux")
1277        .args(["attach-session", "-t", &session])
1278        .status_with_context()?;
1279
1280    if !status.success() {
1281        anyhow::bail!("no active session for task {}", task.display_spec());
1282    }
1283    Ok(())
1284}
1285
1286/// List active agent tmux sessions.
1287pub async fn live() -> anyhow::Result<()> {
1288    let tmux = TmuxManager::new();
1289    let sessions = tmux.list_sessions().await?;
1290
1291    if sessions.is_empty() {
1292        println!("No active agent sessions.");
1293        return Ok(());
1294    }
1295
1296    let store: Option<Arc<TaskStore>> = crate::cli::init_store().await.ok().map(Arc::new);
1297    let repo = config::get_current_repo().unwrap_or_default();
1298
1299    println!("{:<30} {:<15} {:<10} ACTIVE", "SESSION", "TASK", "AGENT");
1300    println!("{}", "-".repeat(70));
1301
1302    let active_map = tmux.batch_session_active().await;
1303    let agent_futs = sessions.iter().map(|session| {
1304        let store = store.clone();
1305        let repo = repo.clone();
1306        let task_id = session.task_id.clone();
1307        async move {
1308            store::opt_store_get_task(&store, &repo, &task_id)
1309                .await
1310                .and_then(|t| t.agent)
1311                .unwrap_or_default()
1312        }
1313    });
1314    let agents = join_all(agent_futs).await;
1315    for (session, agent) in sessions.iter().zip(agents.iter()) {
1316        let active = active_map.get(&session.name).copied().unwrap_or(false);
1317        println!(
1318            "{:<30} {:<15} {:<10} {}",
1319            session.name,
1320            session.task_id,
1321            agent,
1322            if active { "yes" } else { "no" },
1323        );
1324    }
1325
1326    Ok(())
1327}
1328
1329/// Kill a running agent tmux session.
1330pub async fn kill(id: &str) -> anyhow::Result<()> {
1331    let store = crate::cli::init_store().await?;
1332    let task = crate::cli::task_ref::resolve(&store, id).await?;
1333    let tmux = TmuxManager::new();
1334    let session = tmux.session_name(&task.repo, &task.external_id);
1335    if let Some(store_id) = task.store_id {
1336        store
1337            .finalize_incomplete_runs(store_id, "killed", "killed by orch task kill")
1338            .await?;
1339    }
1340    tmux.kill_session(&session).await?;
1341    println!("Killed session for task {}", task.display_spec());
1342    Ok(())
1343}
1344
1345/// Publish an internal task to GitHub.
1346pub async fn publish(id: i64, labels: Vec<String>) -> anyhow::Result<()> {
1347    let task_manager = init_task_manager().await?;
1348    let ext_id = task_manager.publish_task(id, &labels).await?;
1349    println!("Published task #{} as GitHub issue #{}", id, ext_id.0);
1350    Ok(())
1351}
1352
1353/// Show token cost breakdown for a task.
1354pub async fn cost(id: &str) -> anyhow::Result<()> {
1355    // Delegate to cli::cost::show_task for consistent formatting
1356    super::cost::show_task(id).await
1357}
1358
1359/// Show task tree view (parent-child relationships).
1360pub async fn tree(id: Option<i64>, deps: bool) -> anyhow::Result<()> {
1361    if deps {
1362        return dependency_tree(id).await;
1363    }
1364    use crate::cli::tree::{build_forest, render_forest, render_single_tree};
1365    use crate::engine::tasks::TaskFilter;
1366
1367    let task_manager = init_task_manager().await?;
1368
1369    // If a specific task ID is provided, show just that tree
1370    if let Some(task_id) = id {
1371        let task = task_manager.get_task(task_id).await?;
1372
1373        // For a single task, we need to find its children
1374        // First get all tasks to build the full hierarchy
1375        let all_tasks = task_manager.list_tasks(TaskFilter::default()).await?;
1376        let forest = build_forest(all_tasks);
1377
1378        // Find the requested task in the forest
1379        fn find_node_in_forest<'a>(
1380            forest: &'a [crate::cli::tree::TreeNode],
1381            id: &str,
1382        ) -> Option<&'a crate::cli::tree::TreeNode> {
1383            for root in forest {
1384                if root.id == id {
1385                    return Some(root);
1386                }
1387                if let Some(found) = find_node_in_forest(&root.children, id) {
1388                    return Some(found);
1389                }
1390            }
1391            None
1392        }
1393
1394        let target_id = task_id.to_string();
1395        if let Some(node) = find_node_in_forest(&forest, &target_id) {
1396            let output = render_single_tree(node, true);
1397            print!("{}", output);
1398        } else {
1399            // Task exists but not in any tree - show as standalone
1400            match &task {
1401                Task::External(ext) => {
1402                    let node = crate::cli::tree::TreeNode::from_external(ext);
1403                    let output = render_single_tree(&node, true);
1404                    print!("{}", output);
1405                }
1406                Task::Internal(int) => {
1407                    let node = crate::cli::tree::TreeNode::from_internal(int);
1408                    let output = render_single_tree(&node, true);
1409                    print!("{}", output);
1410                }
1411            }
1412        }
1413        return Ok(());
1414    }
1415
1416    // No ID provided - show all root tasks
1417    let filter = TaskFilter::default();
1418    let tasks = task_manager.list_tasks(filter).await?;
1419
1420    if tasks.is_empty() {
1421        println!("No tasks found.");
1422        return Ok(());
1423    }
1424
1425    let forest = build_forest(tasks);
1426    let output = render_forest(&forest);
1427    print!("{}", output);
1428
1429    Ok(())
1430}
1431
1432async fn dependency_tree(focus: Option<i64>) -> anyhow::Result<()> {
1433    use std::collections::HashMap;
1434
1435    let store = crate::cli::init_store().await?;
1436    let focus_id = match focus {
1437        Some(id) => Some(crate::cli::task_ref::resolve_store_id(&store, &id.to_string()).await?),
1438        None => None,
1439    };
1440    let edges = store.list_dependency_edges().await?;
1441    let mut by_task: HashMap<i64, Vec<_>> = HashMap::new();
1442    for edge in edges {
1443        if let Some(focus_id) = focus_id {
1444            if edge.task_id != focus_id {
1445                continue;
1446            }
1447        }
1448        by_task.entry(edge.task_id).or_default().push(edge);
1449    }
1450    if by_task.is_empty() {
1451        println!("No dependency edges.");
1452        return Ok(());
1453    }
1454    let mut ids: Vec<i64> = by_task.keys().copied().collect();
1455    ids.sort_unstable();
1456    for id in ids {
1457        let group = &by_task[&id];
1458        let head = &group[0];
1459        let number = head
1460            .task_external_id
1461            .clone()
1462            .unwrap_or_else(|| format!("task:{id}"));
1463        let status = store
1464            .get(id)
1465            .await
1466            .map(|task| task.status.as_str().to_string())
1467            .unwrap_or_else(|_| "unknown".to_string());
1468        println!("{number} {} [{status}]", head.task_title);
1469        for edge in group {
1470            let label = dep_label(
1471                &edge.task_repo,
1472                &edge.depends_on_repo,
1473                edge.depends_on_number,
1474            );
1475            let done = store
1476                .blocker_snapshot(&edge.depends_on_repo, edge.depends_on_number)
1477                .await
1478                .ok()
1479                .flatten()
1480                .is_some_and(|snap| snap.is_satisfied());
1481            let state = if done { "done" } else { "open" };
1482            println!("  blocked by {label} [{state}]");
1483        }
1484    }
1485    Ok(())
1486}
1487
1488/// List what a task waits on, and what waits on it.
1489pub async fn deps(id: &str) -> anyhow::Result<()> {
1490    let store = crate::cli::init_store().await?;
1491    let task_id = crate::cli::task_ref::resolve_store_id(&store, id).await?;
1492    let task = store.get(task_id).await?;
1493    let shown = task
1494        .external_id
1495        .clone()
1496        .unwrap_or_else(|| format!("internal:{}", task.id));
1497    println!("{shown} {} [{}]", task.title, task.status.as_str());
1498    println!("Waiting on:");
1499    let dependencies = store.list_dependencies(task_id).await?;
1500    if dependencies.is_empty() {
1501        println!("  (none)");
1502    }
1503    for dep in dependencies {
1504        let label = dep_label(&task.repo, &dep.depends_on_repo, dep.depends_on_number);
1505        let done = store
1506            .blocker_snapshot(&dep.depends_on_repo, dep.depends_on_number)
1507            .await?
1508            .is_some_and(|snap| snap.is_satisfied());
1509        let state = if done { "done" } else { "open" };
1510        let local = dep.blocker_status.as_deref().unwrap_or("untracked");
1511        println!("  {label}  {state}  local:{local}  source:{}", dep.source);
1512    }
1513    println!("Waiting on this:");
1514    let number = task
1515        .external_id
1516        .as_deref()
1517        .and_then(|value| value.parse::<i64>().ok())
1518        .unwrap_or(0);
1519    let dependents = if number > 0 {
1520        store.list_dependents(&task.repo, number).await?
1521    } else {
1522        Vec::new()
1523    };
1524    if dependents.is_empty() {
1525        println!("  (none)");
1526    }
1527    for dep in dependents {
1528        let waiter = store.get(dep.task_id).await?;
1529        let label = waiter
1530            .external_id
1531            .clone()
1532            .unwrap_or_else(|| format!("internal:{}", waiter.id));
1533        println!("  {label}  {}  {}", waiter.status.as_str(), waiter.title);
1534    }
1535    Ok(())
1536}
1537
1538/// Show logs / post-mortem for a task (internal or external).
1539pub async fn logs(id: &str) -> anyhow::Result<()> {
1540    let store_owned = crate::cli::init_store().await?;
1541    let resolved = crate::cli::task_ref::resolve(&store_owned, id).await?;
1542    let store: Option<Arc<TaskStore>> = Some(Arc::new(store_owned.clone()));
1543    let repo = resolved.repo.clone();
1544    let task_key = resolved.external_id.clone();
1545
1546    if let Some(store_id) = resolved.store_id {
1547        if let Ok(task) = store_owned.get(store_id).await {
1548            if resolved.is_internal() {
1549                println!("ID: {} (internal)", task.id);
1550                println!("Title: {}", task.title);
1551                println!("Status: {}", task.status.as_str());
1552                if let Some(agent) = &task.agent {
1553                    println!("Agent: {}", agent);
1554                }
1555                if let Some(reason) = &task.block_reason {
1556                    println!("Block reason: {}", reason);
1557                }
1558                println!("Created: {}", task.created_at);
1559                println!("Updated: {}", task.updated_at);
1560            } else {
1561                println!("ID: {} (external)", task_key);
1562                println!("Title: {}", task.title);
1563                println!("State: {}", task.status.as_str());
1564                println!("Labels: {}", task.labels.join(", "));
1565                println!("Author: {}", task.author);
1566                println!("URL: {}", task.url);
1567                println!("Created: {}", task.created_at);
1568                println!("Updated: {}", task.updated_at);
1569            }
1570        }
1571    } else {
1572        println!("ID: {}", resolved.display_spec());
1573    }
1574
1575    // Task store fields
1576    {
1577        {
1578            // Agent, model, and attempts from store — single DB round-trip.
1579            if let Some(ref s) = store {
1580                if let Ok(Some(t)) = s.get_by_external_id(&repo, &task_key).await {
1581                    if let Some(ref agent) = t.agent {
1582                        println!("Agent: {}", agent);
1583                    }
1584                    if let Some(ref model) = t.model {
1585                        println!("Model: {}", model);
1586                    }
1587                    if t.attempts > 0 {
1588                        println!("Attempts: {}", t.attempts);
1589                    }
1590                }
1591            }
1592
1593            // Token & cost summary
1594            let usage = store::get_token_usage(&store, &repo, &task_key).await;
1595            let cost = store::get_cost_estimate(&store, &repo, &task_key).await;
1596            let total_tokens = usage.total_tokens();
1597            if total_tokens > 0 || cost.total_cost_usd > 0.0 {
1598                println!("\nCost summary:");
1599                println!("  input tokens:  {}", usage.input_tokens);
1600                println!("  output tokens: {}", usage.output_tokens);
1601                println!("  total tokens:  {}", total_tokens);
1602                println!("  estimated $:   ${:.6}", cost.total_cost_usd);
1603            }
1604
1605            // Memory (recent attempts)
1606            {
1607                let mem = store::get_recent_memory(&store, &repo, &task_key, 10).await;
1608                if !mem.is_empty() {
1609                    println!("\nMemory (recent attempts):");
1610                    for m in mem {
1611                        println!(
1612                            "- Attempt {} @ {}: agent={} model={}",
1613                            m.attempt,
1614                            m.timestamp,
1615                            m.agent,
1616                            m.model.clone().unwrap_or_default()
1617                        );
1618                        if let Some(err) = m.error.as_ref() {
1619                            println!("    Error: {}", err);
1620                        }
1621                        if !m.learnings.is_empty() {
1622                            println!("    Learnings:");
1623                            for l in &m.learnings {
1624                                println!("      - {}", l);
1625                            }
1626                        }
1627                        if !m.files_modified.is_empty() {
1628                            println!("    Files modified:");
1629                            for f in &m.files_modified {
1630                                println!("      - {}", f);
1631                            }
1632                        }
1633                    }
1634                }
1635            }
1636        }
1637    }
1638
1639    // Show agent output from last attempt if available
1640    let attempt_n: u32 = store::opt_store_get_task(&store, &repo, &task_key)
1641        .await
1642        .map(|t| t.attempts)
1643        .unwrap_or(0) as u32;
1644    if attempt_n > 0 {
1645        match home::task_attempt_dir(&repo, &task_key, attempt_n) {
1646            Ok(attempt_dir) => {
1647                let output_file = attempt_dir.join("output.json");
1648                let exit_file = attempt_dir.join("exit.txt");
1649
1650                if output_file.exists() {
1651                    if let Ok(content) = std::fs::read_to_string(&output_file) {
1652                        let tail =
1653                            crate::engine::runner::agents::patterns::safe_tail(&content, 2000);
1654                        let truncated = if content.len() > 2000 {
1655                            format!(
1656                                "...({} chars truncated)...\n{}",
1657                                content.len() - tail.len(),
1658                                tail
1659                            )
1660                        } else {
1661                            content.clone()
1662                        };
1663                        println!("\n--- Last attempt output (attempt {}) ---", attempt_n);
1664                        println!("{}", truncated);
1665                    }
1666                }
1667
1668                if exit_file.exists() {
1669                    if let Ok(exit_code) = std::fs::read_to_string(&exit_file) {
1670                        println!("Exit code: {}", exit_code.trim());
1671                    }
1672                }
1673            }
1674            Err(e) => {
1675                println!("(could not resolve attempt dir: {})", e);
1676            }
1677        }
1678    }
1679
1680    // Show review agent output if available
1681    let review_task_id = format!("{}-review", task_key);
1682    if let Ok(review_attempt_dir) = home::task_attempt_dir(&repo, &review_task_id, 1) {
1683        let review_output_file = review_attempt_dir.join("output.json");
1684        if review_output_file.exists() {
1685            if let Ok(content) = std::fs::read_to_string(&review_output_file) {
1686                println!("\n--- Review agent output ---");
1687                println!("{}", content);
1688            }
1689        }
1690    }
1691
1692    // Show audit trail from task_runs table (if available in store)
1693    if let Ok(store) = crate::cli::init_store().await {
1694        if let Ok(Some(store_id)) = store.resolve_task_id(&repo, &task_key).await {
1695            if let Ok(runs) = store.get_runs(store_id).await {
1696                if !runs.is_empty() {
1697                    println!("\n--- Run audit trail ({} runs) ---", runs.len());
1698                    for run in &runs {
1699                        println!(
1700                            "\n  Run #{} [{}] agent={} model={} outcome={}",
1701                            run.attempt, run.run_type, run.agent, run.model, run.outcome,
1702                        );
1703                        if let Some(code) = run.exit_code {
1704                            println!("    exit_code: {}", code);
1705                        }
1706                        if !run.error.is_empty() {
1707                            println!("    error: {}", run.error);
1708                        }
1709                        if run.total_cost_usd > 0.0 {
1710                            println!(
1711                                "    tokens: {}in/{}out  cost: ${:.6}  duration: {:.1}s",
1712                                run.input_tokens,
1713                                run.output_tokens,
1714                                run.total_cost_usd,
1715                                run.duration_secs,
1716                            );
1717                        }
1718                        println!("    started: {}", run.started_at);
1719                        if let Some(ref completed) = run.completed_at {
1720                            println!("    completed: {}", completed);
1721                        }
1722                    }
1723                }
1724            }
1725        }
1726    }
1727
1728    // If tmux session is live, append recent pane capture
1729    let tmux = TmuxManager::new();
1730    let session = tmux.session_name(&repo, &task_key);
1731    if tmux.session_exists(&session).await {
1732        println!(
1733            "\nLive tmux session detected: {} — appending recent output:\n---",
1734            session
1735        );
1736        match tmux.capture_pane(&session, 200).await {
1737            Ok(output) => {
1738                println!("{}", output);
1739            }
1740            Err(e) => {
1741                println!("(tmux capture failed: {})", e);
1742            }
1743        }
1744    }
1745
1746    Ok(())
1747}
1748
1749/// Show run history for a task.
1750pub async fn runs(id: &str, verbose: bool) -> anyhow::Result<()> {
1751    let store = crate::cli::init_store().await?;
1752    let task_id = crate::cli::task_ref::resolve_store_id(&store, id).await?;
1753
1754    let runs = store.get_runs(task_id).await?;
1755    if runs.is_empty() {
1756        println!("No runs found for task {id}.");
1757        return Ok(());
1758    }
1759
1760    println!(
1761        "{:<4} {:<8} {:<18} {:<12} {:<8} {:<8} ERROR",
1762        "RUN", "AGENT", "MODEL", "OUTCOME", "DURATION", "COST"
1763    );
1764    println!("{}", "-".repeat(90));
1765
1766    for run in runs {
1767        let model = if run.model.is_empty() {
1768            "-"
1769        } else {
1770            &run.model
1771        };
1772        let error = format_run_text(&run.error, verbose, 48);
1773        println!(
1774            "{:<4} {:<8} {:<18} {:<12} {:<8} {:<8} {}",
1775            run.attempt,
1776            run.agent,
1777            model,
1778            run.outcome,
1779            format_run_duration(run.duration_secs),
1780            format_run_cost(run.total_cost_usd),
1781            error,
1782        );
1783
1784        if verbose {
1785            if !run.stdout.is_empty() {
1786                println!("  stdout:\n{}", run.stdout);
1787            }
1788            if !run.stderr.is_empty() {
1789                println!("  stderr:\n{}", run.stderr);
1790            }
1791            if !run.parsed_response.is_empty() {
1792                println!("  parsed_response:\n{}", run.parsed_response);
1793            }
1794            println!();
1795        }
1796    }
1797
1798    Ok(())
1799}
1800
1801/// Show lifecycle activity timeline for a task.
1802pub async fn activity_log(id: &str, limit: Option<usize>, json: bool) -> anyhow::Result<()> {
1803    let store = crate::cli::init_store().await?;
1804    let task_id = crate::cli::task_ref::resolve_store_id(&store, id).await?;
1805
1806    let events = store.get_activity(task_id, limit).await?;
1807    if events.is_empty() {
1808        println!("No activity found for task {id}.");
1809        return Ok(());
1810    }
1811
1812    println!(
1813        "{:<20} {:<16} {:<12} {:<12} {:<10} {:<14} DETAILS",
1814        "TIME", "EVENT", "FROM", "TO", "AGENT", "MODEL"
1815    );
1816    println!("{}", "-".repeat(120));
1817
1818    for event in events {
1819        let details = if json {
1820            serde_json::to_string(&event.details).unwrap_or_else(|_| "{}".to_string())
1821        } else if event.details.is_null() || event.details == serde_json::json!({}) {
1822            String::new()
1823        } else {
1824            let compact =
1825                serde_json::to_string(&event.details).unwrap_or_else(|_| "{}".to_string());
1826            truncate_err(&compact, 80)
1827        };
1828        println!(
1829            "{:<20} {:<16} {:<12} {:<12} {:<10} {:<14} {}",
1830            event.timestamp,
1831            event.event_type,
1832            event.from_status.as_deref().unwrap_or("-"),
1833            event.to_status.as_deref().unwrap_or("-"),
1834            event.agent.as_deref().unwrap_or("-"),
1835            event.model.as_deref().unwrap_or("-"),
1836            details
1837        );
1838    }
1839
1840    Ok(())
1841}
1842
1843/// Show task routing history with attempt timeline.
1844pub async fn history(id: &str) -> anyhow::Result<()> {
1845    let store = crate::cli::init_store().await?;
1846    let task_id = crate::cli::task_ref::resolve_store_id(&store, id).await?;
1847
1848    let task = store.get(task_id).await?;
1849    let events = store.get_activity(task_id, None).await?;
1850
1851    // Header
1852    println!("Routing History for Task {}", id);
1853    println!("{}", "=".repeat(60));
1854    println!("Title: {}", task.title);
1855    println!("Status: {:?}", task.status);
1856    println!();
1857
1858    // Find routing events (routed, rerouted)
1859    let routing_events: Vec<_> = events
1860        .iter()
1861        .filter(|e| e.event_type == "routed" || e.event_type == "rerouted")
1862        .collect();
1863
1864    if routing_events.is_empty() {
1865        println!("No routing history found. Task has not been routed yet.");
1866        return Ok(());
1867    }
1868
1869    // Display routing timeline
1870    println!("Attempt Timeline:");
1871    println!("{}", "-".repeat(60));
1872
1873    for (i, event) in routing_events.iter().enumerate() {
1874        let attempt_num = i + 1;
1875        let agent = event.agent.as_deref().unwrap_or("-");
1876        let model = event.model.as_deref().unwrap_or("-");
1877        let timestamp = &event.timestamp;
1878
1879        if event.event_type == "routed" {
1880            println!("\nAttempt #{}", attempt_num);
1881            println!("  Time:     {}", timestamp);
1882            println!("  Agent:    {}", agent);
1883            println!("  Model:    {}", model);
1884
1885            // Extract routing details
1886            if let Some(reason) = event.details.get("reason").and_then(|r| r.as_str()) {
1887                println!("  Reason:   {}", reason);
1888            }
1889            if let Some(complexity) = event.details.get("complexity").and_then(|c| c.as_str()) {
1890                println!("  Complexity: {}", complexity);
1891            }
1892        } else if event.event_type == "rerouted" {
1893            println!("  → Rerouted at {}", timestamp);
1894
1895            // Check for failure reason
1896            if let Some(failure) = event.details.get("failure_reason").and_then(|f| f.as_str()) {
1897                println!("    Failure: {}", failure);
1898            } else if let Some(failure) = event.details.get("silence_duration_secs") {
1899                println!("    Failure: Agent silent for {}s", failure);
1900            }
1901
1902            // Show from/to agent if available
1903            if let Some(from) = event.details.get("from_agent").and_then(|a| a.as_str()) {
1904                if let Some(to) = event.details.get("to_agent").and_then(|a| a.as_str()) {
1905                    println!("    Change:   {} → {}", from, to);
1906                }
1907            }
1908
1909            // Show if agents were exhausted
1910            if event.details.get("agents_exhausted").is_some() {
1911                println!("    Note:     All agents exhausted");
1912            }
1913            if event.details.get("no_fallback_available").is_some() {
1914                println!("    Note:     No fallback available");
1915            }
1916        }
1917    }
1918
1919    // Summary
1920    println!("\n{}", "-".repeat(60));
1921    println!("Summary:");
1922    println!("  Total routing attempts: {}", routing_events.len());
1923
1924    // Get cost summary from task
1925    let total_tokens = task.input_tokens + task.output_tokens;
1926    if total_tokens > 0 {
1927        println!("  Input tokens:  {}", task.input_tokens);
1928        println!("  Output tokens: {}", task.output_tokens);
1929        println!(
1930            "  Total cost:    ${:.6}",
1931            task.input_cost_usd + task.output_cost_usd
1932        );
1933    }
1934
1935    // Show current assigned agent/model if available
1936    if let Some(ref agent) = task.agent {
1937        println!("  Current agent: {}", agent);
1938    }
1939    if let Some(ref model) = task.model {
1940        println!("  Current model: {}", model);
1941    }
1942
1943    Ok(())
1944}
1945
1946/// Unified diagnostic view for a task: status, agent, attempts, last error, PR, block reason.
1947pub async fn inspect(id: &str) -> anyhow::Result<()> {
1948    let store = crate::cli::init_store().await?;
1949    let task_id = crate::cli::task_ref::resolve_store_id(&store, id).await?;
1950
1951    let task = store.get(task_id).await?;
1952
1953    // ── Identity ─────────────────────────────────────────────────────────────
1954    println!("Task: {}", task.title);
1955    println!(
1956        "  ID      : {} (internal:{})",
1957        task.external_id.as_deref().unwrap_or("-"),
1958        task.id
1959    );
1960    println!("  Status  : {}", task.status.as_str());
1961    if task.status == crate::store::TaskStatus::Waiting {
1962        let blockers = store
1963            .unmet_blocker_labels(task.id)
1964            .await
1965            .unwrap_or_default();
1966        if !blockers.is_empty() {
1967            println!("  Waiting : {}", blockers.join(", "));
1968        }
1969    }
1970    println!(
1971        "  Created : {} ({})",
1972        task.created_at,
1973        format_age(&task.created_at)
1974    );
1975    println!(
1976        "  Updated : {} ({})",
1977        task.updated_at,
1978        format_age(&task.updated_at)
1979    );
1980    if !task.url.is_empty() {
1981        println!("  URL     : {}", task.url);
1982    }
1983
1984    // ── Routing ───────────────────────────────────────────────────────────────
1985    println!();
1986    println!("Routing:");
1987    println!("  Agent      : {}", task.agent.as_deref().unwrap_or("-"));
1988    println!("  Model      : {}", task.model.as_deref().unwrap_or("-"));
1989    if !task.complexity.is_empty() {
1990        println!("  Complexity : {}", task.complexity);
1991    }
1992    if task.route_attempts > 0 {
1993        println!("  Route attempts : {}", task.route_attempts);
1994    }
1995    if !task.route_reason.is_empty() {
1996        println!("  Reason     : {}", truncate_err(&task.route_reason, 120));
1997    }
1998
1999    // ── Execution ─────────────────────────────────────────────────────────────
2000    println!();
2001    println!("Execution:");
2002    println!("  Attempts : {}", task.attempts);
2003    if !task.branch.is_empty() {
2004        println!("  Branch   : {}", task.branch);
2005    }
2006    if !task.worktree.is_empty() {
2007        println!("  Worktree : {}", task.worktree);
2008    }
2009    if !task.last_error.is_empty() {
2010        println!("  Last error : {}", truncate_err(&task.last_error, 200));
2011    }
2012    if !task.summary.is_empty() {
2013        println!("  Summary  : {}", truncate_err(&task.summary, 200));
2014    }
2015
2016    // ── PR / Review ───────────────────────────────────────────────────────────
2017    if task.pr_number.is_some() || task.review_cycles > 0 || !task.pr_review_context.is_empty() {
2018        println!();
2019        println!("PR / Review:");
2020        if let Some(pr) = task.pr_number {
2021            println!("  PR number     : {}", pr);
2022        }
2023        if task.review_cycles > 0 {
2024            println!("  Review cycles : {}", task.review_cycles);
2025        }
2026        if !task.pr_review_context.is_empty() {
2027            println!(
2028                "  Review context: {}",
2029                truncate_err(&task.pr_review_context, 200)
2030            );
2031        }
2032    }
2033
2034    // Each failed review attempt, so a rebroadcast escalation shows what kept failing
2035    // instead of only the final "escalated after N retries"
2036    let attempts: Vec<_> = store
2037        .get_activity(task.id, None)
2038        .await
2039        .unwrap_or_default()
2040        .into_iter()
2041        .filter(|a| a.event_type == "review_attempt_failed")
2042        .collect();
2043    if !attempts.is_empty() {
2044        println!();
2045        println!("Review attempts ({} failed):", attempts.len());
2046        for activity in attempts.iter().rev().take(10).rev() {
2047            println!("  {}", review_attempt_line(activity));
2048        }
2049    }
2050
2051    // ── Block reason ─────────────────────────────────────────────────────────
2052    if let Some(ref reason) = task.block_reason {
2053        println!();
2054        println!("Blocked:");
2055        println!("  Reason : {}", reason);
2056        if task.auto_unblock_count > 0 {
2057            println!("  Auto-unblock attempts : {}", task.auto_unblock_count);
2058        }
2059    }
2060
2061    // ── Cost ─────────────────────────────────────────────────────────────────
2062    let total_tokens = task.input_tokens + task.output_tokens;
2063    if total_tokens > 0 || task.total_cost_usd > 0.0 {
2064        println!();
2065        println!("Cost:");
2066        println!(
2067            "  Tokens : {}in / {}out",
2068            task.input_tokens, task.output_tokens
2069        );
2070        println!("  Total  : ${:.6}", task.total_cost_usd);
2071    }
2072
2073    // ── Live session ─────────────────────────────────────────────────────────
2074    let task_key = task
2075        .external_id
2076        .clone()
2077        .unwrap_or_else(|| format!("internal:{}", task.id));
2078    let tmux = TmuxManager::new();
2079    let session = tmux.session_name(&task.repo, &task_key);
2080    if tmux.session_exists(&session).await {
2081        println!();
2082        println!(
2083            "Live session: {} (use `orch task attach {}` to connect)",
2084            session, id
2085        );
2086    }
2087
2088    Ok(())
2089}
2090
2091#[cfg(test)]
2092mod tests {
2093    use super::*;
2094
2095    #[test]
2096    fn format_age_seconds() {
2097        let ts = (Utc::now() - chrono::Duration::seconds(30)).to_rfc3339();
2098        let age = format_age(&ts);
2099        assert!(age.ends_with('s'), "expected seconds format, got {age}");
2100    }
2101
2102    #[test]
2103    fn format_age_minutes() {
2104        let ts = (Utc::now() - chrono::Duration::minutes(5)).to_rfc3339();
2105        let age = format_age(&ts);
2106        assert!(age.ends_with('m'), "expected minutes format, got {age}");
2107    }
2108
2109    #[test]
2110    fn format_age_hours() {
2111        let ts = (Utc::now() - chrono::Duration::hours(3)).to_rfc3339();
2112        let age = format_age(&ts);
2113        assert!(age.ends_with('h'), "expected hours format, got {age}");
2114    }
2115
2116    #[test]
2117    fn format_age_days() {
2118        let ts = (Utc::now() - chrono::Duration::days(2)).to_rfc3339();
2119        let age = format_age(&ts);
2120        assert!(age.ends_with('d'), "expected days format, got {age}");
2121    }
2122
2123    #[test]
2124    fn format_age_invalid_returns_dash() {
2125        let age = format_age("not-a-timestamp");
2126        assert_eq!(age, "-");
2127    }
2128
2129    fn task_ref(status: &str) -> store::CliTaskRef {
2130        store::CliTaskRef {
2131            store_id: Some(7),
2132            repo: "owner/repo".to_string(),
2133            origin: "github".to_string(),
2134            title: "t".to_string(),
2135            external_id: "58".to_string(),
2136            status: status.to_string(),
2137        }
2138    }
2139
2140    #[test]
2141    fn refuse_if_done_rejects_done_tasks() {
2142        for action in ["retry", "unblock"] {
2143            let err = refuse_if_done(&task_ref("done"), action)
2144                .expect_err("done task must not be revived");
2145            let msg = err.to_string();
2146            assert!(msg.contains("is done"), "got: {msg}");
2147            assert!(msg.contains(action), "got: {msg}");
2148        }
2149    }
2150
2151    #[test]
2152    fn refuse_if_done_allows_other_statuses() {
2153        for status in ["blocked", "needs_review", "new", "in_review", ""] {
2154            assert!(refuse_if_done(&task_ref(status), "unblock").is_ok());
2155        }
2156    }
2157
2158    #[test]
2159    fn matches_project_filter_accepts_exact_repo_slug() {
2160        assert!(matches_project_filter(
2161            "gabrielkoerich/orch",
2162            "gabrielkoerich/orch"
2163        ));
2164    }
2165
2166    #[test]
2167    fn matches_project_filter_accepts_repo_name_suffix() {
2168        assert!(matches_project_filter("gabrielkoerich/orch", "orch"));
2169    }
2170
2171    #[test]
2172    fn matches_project_filter_rejects_non_matching_repo() {
2173        assert!(!matches_project_filter("gabrielkoerich/orch", "bean"));
2174    }
2175
2176    /// Verify the forced-routing field construction for agent-only case.
2177    #[test]
2178    fn retry_force_route_fields_agent_only() {
2179        let forced_agent = "claude";
2180        let model: Option<String> = None;
2181        let fields: Vec<(&str, serde_json::Value)> = {
2182            let mut f = vec![
2183                ("agent", serde_json::json!(forced_agent)),
2184                (
2185                    "route_reason",
2186                    serde_json::json!(format!("forced via retry --agent {forced_agent}")),
2187                ),
2188            ];
2189            if let Some(ref m) = model {
2190                f.push(("model", serde_json::json!(m)));
2191            }
2192            f
2193        };
2194        assert_eq!(fields.len(), 2);
2195        assert_eq!(fields[0].1, serde_json::json!("claude"));
2196        assert_eq!(
2197            fields[1].1,
2198            serde_json::json!("forced via retry --agent claude")
2199        );
2200    }
2201
2202    /// Verify the forced-routing field construction for agent+model case.
2203    #[test]
2204    fn retry_force_route_fields_agent_and_model() {
2205        let fields = retry_force_fields("claude", Some("opus"));
2206        assert_eq!(fields.len(), 3);
2207        assert_eq!(fields[0].1, serde_json::json!("claude"));
2208        assert_eq!(fields[2].0, "model");
2209        assert_eq!(fields[2].1, serde_json::json!("opus"));
2210    }
2211
2212    /// Verify that the model hint display is correct in both cases.
2213    #[test]
2214    fn retry_model_hint_display() {
2215        let model_some: Option<String> = Some("opus".to_string());
2216        let model_none: Option<String> = None;
2217        assert_eq!(model_some.as_deref().unwrap_or("(router default)"), "opus");
2218        assert_eq!(
2219            model_none.as_deref().unwrap_or("(router default)"),
2220            "(router default)"
2221        );
2222    }
2223
2224    #[test]
2225    fn review_attempt_line_shows_cause_and_reason() {
2226        let activity = store::TaskActivity {
2227            id: 1,
2228            task_id: 7,
2229            timestamp: "2026-10-25T22:40:00Z".to_string(),
2230            event_type: "review_attempt_failed".to_string(),
2231            from_status: None,
2232            to_status: None,
2233            agent: None,
2234            model: None,
2235            details: serde_json::json!({
2236                "cause": "rate_limit",
2237                "external": true,
2238                "reason": "claude failed: rate limit reached",
2239            }),
2240        };
2241        let line = review_attempt_line(&activity);
2242        assert_eq!(
2243            line,
2244            "2026-10-25T22:40:00Z  rate_limit (external): claude failed: rate limit reached"
2245        );
2246    }
2247
2248    #[test]
2249    fn truncate_err_under_limit() {
2250        let s = "short error";
2251        assert_eq!(truncate_err(s, 50), "short error");
2252    }
2253
2254    #[test]
2255    fn truncate_err_exact_limit() {
2256        let s = "short error";
2257        assert_eq!(truncate_err(s, 11), "short error");
2258    }
2259
2260    #[test]
2261    fn truncate_err_truncates() {
2262        let s = "this is a long error message that should be cut";
2263        let result = truncate_err(s, 10);
2264        assert!(result.ends_with("..."));
2265        assert!(result.len() <= 13); // 10 chars + "..."
2266    }
2267
2268    #[test]
2269    fn truncate_err_multi_byte_char_boundary() {
2270        // "héllo world" bytes: h(0)=1, é(1-2)=2, l(3)=1, l(4)=1, o(5)=1, sp(6)=1, w(7)=1...
2271        // byte 3 = 'l' (valid boundary); byte 4 = 'l' (valid); byte 5 = 'o' (valid)
2272        // No panic = success; exact result varies by where the boundary lands
2273        let s = "héllo world";
2274        let result = truncate_err(s, 3);
2275        assert!(result.ends_with("..."));
2276        assert!(!result.contains("panic"));
2277    }
2278
2279    #[test]
2280    fn truncate_err_emoji() {
2281        // "🔥 error message": 🔥=4 bytes, space=1, e=1, r=1, r=1, o=1, sp=1, m=1...
2282        // byte 5 = 'e' (valid boundary); walk-back not needed
2283        let s = "🔥 error message";
2284        let result = truncate_err(s, 5);
2285        assert_eq!(result, "🔥 ...");
2286    }
2287
2288    #[test]
2289    fn truncate_err_cjk() {
2290        // "你好世界": 你=3 bytes(0-2), 好=3 bytes(3-5), 世=3 bytes(6-8), 界=3 bytes(9-11)
2291        // byte 4 falls inside 好; walk back to byte 3 (= end of 你)
2292        let s = "你好世界";
2293        let result = truncate_err(s, 4);
2294        assert_eq!(result, "你...");
2295    }
2296}