Skip to main content

orch/cli/
task.rs

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