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 = match s {
701                Status::New => TaskStatus::New,
702                Status::Routed => TaskStatus::Routed,
703                Status::InProgress => TaskStatus::InProgress,
704                Status::Done => TaskStatus::Done,
705                Status::Blocked => TaskStatus::Blocked,
706                Status::InReview => TaskStatus::InReview,
707                Status::Approved => TaskStatus::Approved,
708                Status::NeedsReview => TaskStatus::NeedsReview,
709                Status::Waiting => TaskStatus::Waiting,
710            };
711            all_internal.iter().filter(|t| t.status == ts).count()
712        })
713        .collect();
714
715    // Calculate total cost using a single aggregate query instead of per-task lookups.
716    let store: Option<Arc<TaskStore>> = cli::init_store().await.ok().map(Arc::new);
717    let repo = config::get_current_repo().unwrap_or_default();
718    let mut total_input_tokens: u64 = 0;
719    let mut total_output_tokens: u64 = 0;
720    let mut total_cost: f64 = 0.0;
721
722    if let Some(ref s) = store {
723        if let Ok((input, output, cost)) = s.cost_summary(&repo).await {
724            total_input_tokens = u64::try_from(input).unwrap_or(0);
725            total_output_tokens = u64::try_from(output).unwrap_or(0);
726            total_cost = cost;
727        }
728    } else {
729        // No store available: sum up internal task costs directly from already-loaded data.
730        for task in &all_internal {
731            total_input_tokens += u64::try_from(task.input_tokens).unwrap_or(0);
732            total_output_tokens += u64::try_from(task.output_tokens).unwrap_or(0);
733            total_cost += task.total_cost_usd;
734        }
735    }
736
737    // The engine process owns the live rate-limit state, so it leaves the reset epoch in
738    // KV for this one. Stale entries read as expired and are dropped.
739    let rate_limited_until = match store.as_ref() {
740        Some(s) => s
741            .kv_get(engine::RATE_LIMITED_UNTIL_KEY)
742            .await
743            .ok()
744            .flatten()
745            .and_then(|v| v.parse::<i64>().ok())
746            .filter(|reset_at| *reset_at > chrono::Utc::now().timestamp()),
747        None => None,
748    };
749
750    if json {
751        let mut map = serde_json::Map::new();
752        for (i, s) in statuses.iter().enumerate() {
753            let key = s.as_label().replace("status:", "");
754            let mut entry = serde_json::Map::new();
755            entry.insert(
756                "external".to_string(),
757                serde_json::Value::Number(ext_counts[i].into()),
758            );
759            entry.insert(
760                "internal".to_string(),
761                serde_json::Value::Number(int_counts[i].into()),
762            );
763            map.insert(key, serde_json::Value::Object(entry));
764        }
765
766        map.insert(
767            "total_cost_usd".to_string(),
768            serde_json::Value::Number(
769                serde_json::Number::from_f64(total_cost).unwrap_or(serde_json::Number::from(0)),
770            ),
771        );
772        map.insert(
773            "total_input_tokens".to_string(),
774            serde_json::Value::Number(total_input_tokens.into()),
775        );
776        map.insert(
777            "total_output_tokens".to_string(),
778            serde_json::Value::Number(total_output_tokens.into()),
779        );
780        map.insert(
781            "total_tokens".to_string(),
782            serde_json::Value::Number((total_input_tokens + total_output_tokens).into()),
783        );
784
785        if let Some(reset_at) = rate_limited_until {
786            map.insert(
787                "github_rate_limited_until".to_string(),
788                serde_json::Value::Number(reset_at.into()),
789            );
790        }
791
792        println!("{}", serde_json::to_string_pretty(&map)?);
793    } else {
794        if let Some(reset_at) = rate_limited_until {
795            println!(
796                "GitHub: rate limited until {}",
797                engine::format_rate_limited_until(reset_at)
798            );
799            println!();
800        }
801
802        println!("{:<20} {:>8}  {:>8}", "STATUS", "EXTERNAL", "INTERNAL");
803        println!("{}", "-".repeat(42));
804        let total_ext: usize = ext_counts.iter().sum();
805        let total_int: usize = int_counts.iter().sum();
806        for (i, s) in statuses.iter().enumerate() {
807            let ext = ext_counts[i];
808            let int = int_counts[i];
809            if ext > 0 || int > 0 {
810                println!(
811                    "{:<20} {:>8}  {:>8}",
812                    s.as_label().replace("status:", ""),
813                    ext,
814                    int
815                );
816            }
817        }
818        println!("{}", "-".repeat(42));
819        println!("{:<20} {:>8}  {:>8}", "total", total_ext, total_int);
820
821        // Show cost summary if any
822        if total_cost > 0.0 {
823            println!();
824            println!("Cost summary:");
825            println!(
826                "  Total tokens: {}",
827                total_input_tokens + total_output_tokens
828            );
829            println!("  Total cost:   ${total_cost:.6}");
830        }
831    }
832
833    Ok(())
834}
835
836/// Route a task to an agent.
837pub async fn route(id: &str) -> anyhow::Result<()> {
838    let store: Arc<TaskStore> = Arc::new(cli::init_store().await?);
839    let resolved = task_ref::resolve(&store, id).await?;
840    let repo = resolved.repo.clone();
841    let ext_id = ExternalId(resolved.external_id.clone());
842
843    let (task, backend) = if resolved.is_internal() {
844        let store_id = resolved
845            .store_id
846            .context("internal task missing store id")?;
847        dependencies::refuse_if_waiting(&store, store_id).await?;
848        (
849            store_task_to_external(&store.get(store_id).await?),
850            None::<Arc<dyn ExternalBackend>>,
851        )
852    } else {
853        let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
854        refuse_external_claim(&store, &repo, &ext_id.0).await?;
855        (backend.get_task(&ext_id).await?, Some(backend))
856    };
857
858    let mut router = Router::from_config();
859    let result = router.route(&task, &store, &repo).await?;
860
861    router
862        .store_route_result(&ext_id.0, &result, &store, &repo)
863        .await?;
864
865    if let Some(backend) = backend {
866        let labels = vec![
867            format!("agent:{}", result.agent),
868            format!("complexity:{}", result.complexity),
869        ];
870        backend.set_labels(&ext_id, &labels).await?;
871        update_status_store_first(Some(&store), &backend, &repo, &ext_id, Status::Routed).await?;
872    } else if let Some(store_id) = resolved.store_id {
873        store.update_status(store_id, TaskStatus::Routed).await?;
874    }
875
876    println!(
877        "Routed task {} → {} (complexity: {}, reason: {})",
878        resolved.display_spec(),
879        result.agent,
880        result.complexity,
881        result.reason
882    );
883
884    Ok(())
885}
886
887/// Run a task (manual execution).
888pub async fn run(id: Option<String>) -> anyhow::Result<()> {
889    let store: Arc<TaskStore> = Arc::new(cli::init_store().await?);
890
891    let (repo, task_id, backend) = if let Some(id) = id {
892        let resolved = task_ref::resolve(&store, &id).await?;
893        let backend: Option<Arc<dyn ExternalBackend>> = if resolved.is_internal() {
894            None
895        } else {
896            Some(Arc::new(GitHubBackend::new(resolved.repo.clone())?))
897        };
898        (resolved.repo, resolved.external_id, backend)
899    } else {
900        let repo =
901            config::get_current_repo().context("'repo' not set — ensure .orch.yml has gh.repo")?;
902        let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
903        let routed = backend.list_by_status(Status::Routed).await?;
904        let task_id = if let Some(task) = routed.first() {
905            task.id.0.clone()
906        } else {
907            let new = backend.list_by_status(Status::New).await?;
908            if let Some(task) = new.first() {
909                task.id.0.clone()
910            } else {
911                anyhow::bail!("no runnable tasks found");
912            }
913        };
914        (repo, task_id, Some(backend))
915    };
916
917    let route_result = get_route_result(&store, &repo, &task_id).await.ok();
918    let agent = route_result.as_ref().map(|r| r.agent.clone());
919    let model = route_result.as_ref().and_then(|r| r.model.clone());
920
921    println!(
922        "Running task #{} (agent: {}, model: {})",
923        task_id,
924        agent.as_deref().unwrap_or("default"),
925        model.as_deref().unwrap_or("default")
926    );
927
928    refuse_external_claim(&store, &repo, &task_id).await?;
929
930    let ext_id = ExternalId(task_id.clone());
931    let started_at = Utc::now();
932    if let Some(ref backend) = backend {
933        update_status_store_first(Some(&store), backend, &repo, &ext_id, Status::InProgress)
934            .await?;
935    } else if let Some(store_id) = store.resolve_task_id(&repo, &task_id).await? {
936        store
937            .update_status(store_id, TaskStatus::InProgress)
938            .await?;
939    }
940
941    let runner = TaskRunner::new(repo).with_store(store);
942    runner
943        .run(
944            &task_id,
945            agent.as_deref(),
946            model.as_deref(),
947            backend.as_deref(),
948            &started_at,
949        )
950        .await?;
951
952    println!("Task #{task_id} completed");
953    Ok(())
954}
955
956/// Retry a task (reset to new).
957///
958/// When `agent` is provided, the task is force-routed to that agent/model and
959/// set directly to `Routed` status, bypassing the router entirely.
960pub async fn retry(id: &str, agent: Option<String>, model: Option<String>) -> anyhow::Result<()> {
961    let s = Arc::new(cli::init_store().await?);
962    let resolved = task_ref::resolve(&s, id).await?;
963    refuse_if_done(&resolved, "retry")?;
964    let store = Some(Arc::clone(&s));
965    let repo = resolved.repo.clone();
966    let shown = resolved.display_spec();
967
968    if resolved.is_internal() {
969        let store_id = resolved
970            .store_id
971            .context("internal task missing store id")?;
972        dependencies::refuse_if_waiting(&s, store_id).await?;
973        store::store_reset_counters(&store, &repo, &resolved.external_id).await;
974
975        if let Some(ref forced_agent) = agent {
976            let fields = retry_force_fields(forced_agent, model.as_deref());
977            s.set_fields(store_id, &fields).await?;
978            s.update_status(store_id, TaskStatus::Routed).await?;
979            let model_hint = model.as_deref().unwrap_or("(router default)");
980            println!(
981                "Task {shown} force-routed to {forced_agent}:{model_hint} (set to routed, dispatches on next tick)"
982            );
983        } else {
984            s.update_status(store_id, TaskStatus::New).await?;
985            println!("Task {shown} reset to new (attempts reset, will be re-routed)");
986        }
987        return Ok(());
988    }
989
990    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
991    let ext_id = ExternalId(resolved.external_id.clone());
992    refuse_external_claim(&s, &repo, &ext_id.0).await?;
993
994    let task = backend.get_task(&ext_id).await?;
995    for label in &task.labels {
996        if label.starts_with("agent:") {
997            backend.remove_label(&ext_id, label).await?;
998        }
999    }
1000
1001    store::store_reset_counters(&store, &repo, &ext_id.0).await;
1002
1003    if let Some(ref forced_agent) = agent {
1004        backend
1005            .set_labels(&ext_id, &[format!("agent:{forced_agent}")])
1006            .await?;
1007
1008        if let Some(store_id) = resolved.store_id {
1009            let fields = retry_force_fields(forced_agent, model.as_deref());
1010            s.set_fields(store_id, &fields).await?;
1011        }
1012
1013        update_status_store_first(store.as_ref(), &backend, &repo, &ext_id, Status::Routed).await?;
1014        let model_hint = model.as_deref().unwrap_or("(router default)");
1015        println!(
1016            "Task {shown} force-routed to {forced_agent}:{model_hint} (set to routed, dispatches on next tick)"
1017        );
1018    } else {
1019        update_status_store_first(store.as_ref(), &backend, &repo, &ext_id, Status::New).await?;
1020        println!("Task {shown} reset to new (attempts reset, will be re-routed)");
1021    }
1022
1023    Ok(())
1024}
1025
1026fn retry_force_fields<'a>(
1027    forced_agent: &'a str,
1028    model: Option<&'a str>,
1029) -> Vec<(&'a str, serde_json::Value)> {
1030    let mut fields = vec![
1031        ("agent", serde_json::json!(forced_agent)),
1032        (
1033            "route_reason",
1034            serde_json::json!(format!("forced via retry --agent {forced_agent}")),
1035        ),
1036    ];
1037    if let Some(model) = model {
1038        fields.push(("model", serde_json::json!(model)));
1039    }
1040    fields
1041}
1042
1043/// Unblock a task or all blocked tasks.
1044pub async fn unblock(id: &str) -> anyhow::Result<()> {
1045    if id == "all" {
1046        let repo =
1047            config::get_current_repo().context("'repo' not set — ensure .orch.yml has gh.repo")?;
1048        let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
1049        let store = cli::init_store().await.ok().map(Arc::new);
1050        let blocked = backend.list_by_status(Status::Blocked).await?;
1051        let needs_review = backend.list_by_status(Status::NeedsReview).await?;
1052
1053        let tasks_to_unblock: Vec<_> = blocked.iter().chain(needs_review.iter()).collect();
1054        let external_count = tasks_to_unblock.len();
1055        let ext_futs = tasks_to_unblock.into_iter().map(|task| {
1056            let store = store.clone();
1057            let backend = Arc::clone(&backend);
1058            let repo = repo.clone();
1059            let id = task.id.clone();
1060            async move {
1061                store::store_reset_counters(&store, &repo, &id.0).await;
1062                if let Some(ref s) = store
1063                    && let Ok(Some(store_id)) = s.resolve_task_id(&repo, &id.0).await
1064                {
1065                    match s.status_after_unblock(store_id).await {
1066                        Ok(TaskStatus::Waiting) => {
1067                            let _ = backend.update_status(&id, Status::Waiting).await;
1068                            return Ok(());
1069                        }
1070                        Ok(_) => {}
1071                        Err(err) => return Err(err),
1072                    }
1073                }
1074                update_status_store_first(store.as_ref(), &backend, &repo, &id, Status::New).await
1075            }
1076        });
1077        for result in join_all(ext_futs).await {
1078            result?;
1079        }
1080
1081        let mut internal_count = 0;
1082        if let Some(ref s) = store {
1083            let internal_blocked = s
1084                .list_internal_by_status(&repo, TaskStatus::Blocked)
1085                .await
1086                .unwrap_or_default();
1087            let internal_needs_review = s
1088                .list_internal_by_status(&repo, TaskStatus::NeedsReview)
1089                .await
1090                .unwrap_or_default();
1091            let tasks_internal: Vec<_> = internal_blocked
1092                .iter()
1093                .chain(internal_needs_review.iter())
1094                .collect();
1095            internal_count = tasks_internal.len();
1096            let int_futs = tasks_internal.into_iter().map(|task| {
1097                let store = store.clone();
1098                let s = Arc::clone(s);
1099                let repo = repo.clone();
1100                let ext_id = task
1101                    .external_id
1102                    .clone()
1103                    .unwrap_or_else(|| format!("internal:{}", task.id));
1104                let task_id = task.id;
1105                async move {
1106                    store::store_reset_counters(&store, &repo, &ext_id).await;
1107                    match s.status_after_unblock(task_id).await? {
1108                        TaskStatus::Waiting => Ok(()),
1109                        _ => s.update_status(task_id, TaskStatus::New).await,
1110                    }
1111                }
1112            });
1113            for result in join_all(int_futs).await {
1114                result?;
1115            }
1116        }
1117
1118        let total = external_count + internal_count;
1119        println!(
1120            "Unblocked {total} tasks ({external_count} external, {internal_count} internal) (attempts reset)"
1121        );
1122        return Ok(());
1123    }
1124
1125    let s = Arc::new(cli::init_store().await?);
1126    let resolved = task_ref::resolve(&s, id).await?;
1127    refuse_if_done(&resolved, "unblock")?;
1128    let store = Some(Arc::clone(&s));
1129    let repo = resolved.repo.clone();
1130    let shown = resolved.display_spec();
1131
1132    if resolved.is_internal() {
1133        let store_id = resolved
1134            .store_id
1135            .context("internal task missing store id")?;
1136        store::store_reset_counters(&store, &repo, &resolved.external_id).await;
1137        if release_or_keep_waiting(&s, store_id).await? {
1138            println!("Task {shown} stays waiting on an open dependency");
1139        } else {
1140            s.update_status(store_id, TaskStatus::New).await?;
1141            println!("Unblocked {shown} (attempts reset, will be re-routed)");
1142        }
1143        return Ok(());
1144    }
1145
1146    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
1147    let ext_id = ExternalId(resolved.external_id.clone());
1148    store::store_reset_counters(&store, &repo, &ext_id.0).await;
1149    if let Some(store_id) = resolved.store_id
1150        && release_or_keep_waiting(&s, store_id).await?
1151    {
1152        let _ = backend.update_status(&ext_id, Status::Waiting).await;
1153        println!("Task {shown} stays waiting on an open dependency");
1154        return Ok(());
1155    }
1156    update_status_store_first(store.as_ref(), &backend, &repo, &ext_id, Status::New).await?;
1157    println!("Unblocked {shown} (attempts reset)");
1158
1159    Ok(())
1160}
1161
1162/// Kill tmux sessions and remove the worktree for a closed task.
1163///
1164/// Sessions are killed first (before worktree removal) so that the tmux-active
1165/// guard in `cleanup_task_worktree_with_opts` does not skip the removal.
1166/// Errors are logged but do not fail the close operation.
1167async fn cleanup_sessions_and_worktree(task_id: &str, repo: &str, store: Option<&Arc<TaskStore>>) {
1168    let tmux = TmuxManager::new();
1169
1170    // Session names follow `orch-{project}-{task_id}` and optionally
1171    // `orch-{project}-{task_id}-{suffix}` (e.g. `-review`).
1172    // Build a pattern that matches the task_id as a complete dash-delimited segment.
1173    let safe_id = task_id.replace(':', "-");
1174    let pattern = format!("-{safe_id}");
1175
1176    match tmux.list_sessions().await {
1177        Ok(sessions) => {
1178            for sess in sessions {
1179                let name = &sess.name;
1180                if let Some(pos) = name.find(&pattern) {
1181                    let after = &name[pos + pattern.len()..];
1182                    if after.is_empty() || after.starts_with('-') {
1183                        tracing::info!(
1184                            session = name,
1185                            task_id,
1186                            "killing tmux session for closed task"
1187                        );
1188                        match tmux.kill_session(name).await {
1189                            Err(e) => {
1190                                tracing::warn!(session = name, err = %e, "failed to kill session on close");
1191                            }
1192                            _ => {
1193                                println!("  killed session {name}");
1194                            }
1195                        }
1196                    }
1197                }
1198            }
1199        }
1200        Err(e) => {
1201            tracing::warn!(task_id, err = %e, "could not list tmux sessions during close cleanup");
1202        }
1203    }
1204
1205    // Remove the worktree (sessions are already gone so the tmux guard won't block).
1206    if let Some(s) = store {
1207        match cleanup::cleanup_task_worktree(task_id, repo, s).await {
1208            Ok(()) => {}
1209            Err(e) => {
1210                tracing::warn!(task_id, err = %e, "worktree cleanup failed after task close");
1211            }
1212        }
1213    }
1214}
1215
1216/// Mark a task as done (without running an agent).
1217pub async fn close(id: &str, note: Option<&str>) -> anyhow::Result<()> {
1218    let s = cli::init_store().await?;
1219    let resolved = task_ref::resolve(&s, id).await?;
1220    let store = Some(Arc::new(s.clone()));
1221    let repo = resolved.repo.clone();
1222    let shown = resolved.display_spec();
1223
1224    if resolved.is_internal() {
1225        let store_id = resolved
1226            .store_id
1227            .context("internal task missing store id")?;
1228        s.update_status(store_id, TaskStatus::Done).await?;
1229        println!("Closed {shown} (marked done)");
1230        cleanup_sessions_and_worktree(&resolved.external_id, &repo, store.as_ref()).await;
1231        return Ok(());
1232    }
1233
1234    let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
1235    let ext_id = ExternalId(resolved.external_id.clone());
1236
1237    if let Some(text) = note {
1238        backend.post_comment(&ext_id, text).await?;
1239    }
1240
1241    update_status_store_first(store.as_ref(), &backend, &repo, &ext_id, Status::Done).await?;
1242    println!("Closed {shown} (marked done)");
1243    cleanup_sessions_and_worktree(&resolved.external_id, &repo, store.as_ref()).await;
1244    Ok(())
1245}
1246
1247/// Set a task's priority label, on GitHub for external tasks and in the store for all.
1248pub async fn priority(id: &str, level: &str) -> anyhow::Result<()> {
1249    let wanted: Priority = level.parse()?;
1250    let s = cli::init_store().await?;
1251    let resolved = task_ref::resolve(&s, id).await?;
1252    let store_id = resolved.store_id.context("task missing store id")?;
1253    let task = s.get(store_id).await?;
1254
1255    if !resolved.is_internal() {
1256        let backend: Arc<dyn ExternalBackend> =
1257            Arc::new(GitHubBackend::new(resolved.repo.clone())?);
1258        let ext_id = ExternalId(resolved.external_id.clone());
1259        for label in task.labels.iter().filter(|l| is_priority_label(l)) {
1260            backend.remove_label(&ext_id, label).await?;
1261        }
1262        let added = wanted.apply_to(&[]);
1263        if !added.is_empty() {
1264            backend.set_labels(&ext_id, &added).await?;
1265        }
1266    }
1267
1268    let labels = wanted.apply_to(&task.labels);
1269    s.set_fields(store_id, &[("labels", serde_json::json!(labels))])
1270        .await?;
1271    println!(
1272        "{} priority set to {}",
1273        resolved.display_spec(),
1274        wanted.as_str()
1275    );
1276    Ok(())
1277}
1278
1279/// Attach to a running agent's tmux session.
1280pub async fn attach(id: &str) -> anyhow::Result<()> {
1281    let store = cli::init_store().await?;
1282    let task = task_ref::resolve(&store, id).await?;
1283    let tmux = TmuxManager::new();
1284    let session = tmux.session_name(&task.repo, &task.external_id);
1285    let status = Command::new("tmux")
1286        .args(["attach-session", "-t", &session])
1287        .status_with_context()?;
1288
1289    if !status.success() {
1290        anyhow::bail!("no active session for task {}", task.display_spec());
1291    }
1292    Ok(())
1293}
1294
1295/// List active agent tmux sessions.
1296pub async fn live() -> anyhow::Result<()> {
1297    let tmux = TmuxManager::new();
1298    let sessions = tmux.list_sessions().await?;
1299
1300    if sessions.is_empty() {
1301        println!("No active agent sessions.");
1302        return Ok(());
1303    }
1304
1305    let store: Option<Arc<TaskStore>> = cli::init_store().await.ok().map(Arc::new);
1306    let repo = config::get_current_repo().unwrap_or_default();
1307
1308    println!("{:<30} {:<15} {:<10} ACTIVE", "SESSION", "TASK", "AGENT");
1309    println!("{}", "-".repeat(70));
1310
1311    let active_map = tmux.batch_session_active().await;
1312    let agent_futs = sessions.iter().map(|session| {
1313        let store = store.clone();
1314        let repo = repo.clone();
1315        let task_id = session.task_id.clone();
1316        async move {
1317            store::opt_store_get_task(&store, &repo, &task_id)
1318                .await
1319                .and_then(|t| t.agent)
1320                .unwrap_or_default()
1321        }
1322    });
1323    let agents = join_all(agent_futs).await;
1324    for (session, agent) in sessions.iter().zip(agents.iter()) {
1325        let active = active_map.get(&session.name).copied().unwrap_or(false);
1326        println!(
1327            "{:<30} {:<15} {:<10} {}",
1328            session.name,
1329            session.task_id,
1330            agent,
1331            if active { "yes" } else { "no" },
1332        );
1333    }
1334
1335    Ok(())
1336}
1337
1338/// Kill a running agent tmux session.
1339pub async fn kill(id: &str) -> anyhow::Result<()> {
1340    let store = cli::init_store().await?;
1341    let task = task_ref::resolve(&store, id).await?;
1342    let tmux = TmuxManager::new();
1343    let session = tmux.session_name(&task.repo, &task.external_id);
1344    if let Some(store_id) = task.store_id {
1345        store
1346            .finalize_incomplete_runs(store_id, "killed", "killed by orch task kill")
1347            .await?;
1348    }
1349    tmux.kill_session(&session).await?;
1350    println!("Killed session for task {}", task.display_spec());
1351    Ok(())
1352}
1353
1354/// Publish an internal task to GitHub.
1355pub async fn publish(id: i64, labels: Vec<String>) -> anyhow::Result<()> {
1356    let task_manager = init_task_manager().await?;
1357    let ext_id = task_manager.publish_task(id, &labels).await?;
1358    println!("Published task #{} as GitHub issue #{}", id, ext_id.0);
1359    Ok(())
1360}
1361
1362/// Show token cost breakdown for a task.
1363pub async fn cost(id: &str) -> anyhow::Result<()> {
1364    // Delegate to cli::cost::show_task for consistent formatting
1365    super::cost::show_task(id).await
1366}
1367
1368/// Show task tree view (parent-child relationships).
1369pub async fn tree(id: Option<i64>, deps: bool) -> anyhow::Result<()> {
1370    if deps {
1371        return dependency_tree(id).await;
1372    }
1373
1374    let task_manager = init_task_manager().await?;
1375
1376    // If a specific task ID is provided, show just that tree
1377    if let Some(task_id) = id {
1378        // Find the requested task in the forest
1379        fn find_node_in_forest<'a>(forest: &'a [TreeNode], id: &str) -> Option<&'a TreeNode> {
1380            for root in forest {
1381                if root.id == id {
1382                    return Some(root);
1383                }
1384                if let Some(found) = find_node_in_forest(&root.children, id) {
1385                    return Some(found);
1386                }
1387            }
1388            None
1389        }
1390
1391        let task = task_manager.get_task(task_id).await?;
1392
1393        // For a single task, we need to find its children
1394        // First get all tasks to build the full hierarchy
1395        let all_tasks = task_manager.list_tasks(TaskFilter::default()).await?;
1396        let forest = build_forest(&all_tasks);
1397
1398        let target_id = task_id.to_string();
1399        if let Some(node) = find_node_in_forest(&forest, &target_id) {
1400            let output = render_single_tree(node, true);
1401            print!("{output}");
1402        } else {
1403            // Task exists but not in any tree - show as standalone
1404            match &task {
1405                Task::External(ext) => {
1406                    let node = TreeNode::from_external(ext);
1407                    let output = render_single_tree(&node, true);
1408                    print!("{output}");
1409                }
1410                Task::Internal(int) => {
1411                    let node = TreeNode::from_internal(int);
1412                    let output = render_single_tree(&node, true);
1413                    print!("{output}");
1414                }
1415            }
1416        }
1417        return Ok(());
1418    }
1419
1420    // No ID provided - show all root tasks
1421    let filter = TaskFilter::default();
1422    let tasks = task_manager.list_tasks(filter).await?;
1423
1424    if tasks.is_empty() {
1425        println!("No tasks found.");
1426        return Ok(());
1427    }
1428
1429    let forest = build_forest(&tasks);
1430    let output = render_forest(&forest);
1431    print!("{output}");
1432
1433    Ok(())
1434}
1435
1436async fn dependency_tree(focus: Option<i64>) -> anyhow::Result<()> {
1437    let store = cli::init_store().await?;
1438    let focus_id = match focus {
1439        Some(id) => Some(task_ref::resolve_store_id(&store, &id.to_string()).await?),
1440        None => None,
1441    };
1442    let edges = store.list_dependency_edges().await?;
1443    let mut by_task: HashMap<i64, Vec<_>> = HashMap::new();
1444    for edge in edges {
1445        if let Some(focus_id) = focus_id
1446            && edge.task_id != focus_id
1447        {
1448            continue;
1449        }
1450        by_task.entry(edge.task_id).or_default().push(edge);
1451    }
1452    if by_task.is_empty() {
1453        println!("No dependency edges.");
1454        return Ok(());
1455    }
1456    let mut ids: Vec<i64> = by_task.keys().copied().collect();
1457    ids.sort_unstable();
1458    for id in ids {
1459        let group = &by_task[&id];
1460        let head = &group[0];
1461        let number = head
1462            .task_external_id
1463            .clone()
1464            .unwrap_or_else(|| format!("task:{id}"));
1465        let status = store.get(id).await.map_or_else(
1466            |_| "unknown".to_string(),
1467            |task| task.status.as_str().to_string(),
1468        );
1469        println!("{number} {} [{status}]", head.task_title);
1470        for edge in group {
1471            let label = dep_label(
1472                &edge.task_repo,
1473                &edge.depends_on_repo,
1474                edge.depends_on_number,
1475            );
1476            let snap = store
1477                .blocker_snapshot(&edge.depends_on_repo, edge.depends_on_number)
1478                .await
1479                .ok()
1480                .flatten();
1481            let state = blocker_state_label(snap.as_ref());
1482            println!("  blocked by {label} [{state}]");
1483        }
1484    }
1485    Ok(())
1486}
1487
1488fn blocker_state_label(snap: Option<&BlockerSnapshot>) -> String {
1489    match snap {
1490        Some(snap) => snap
1491            .unsatisfied_reason()
1492            .unwrap_or_else(|| "done".to_string()),
1493        None => "open".to_string(),
1494    }
1495}
1496
1497/// List what a task waits on, and what waits on it.
1498pub async fn deps(id: &str) -> anyhow::Result<()> {
1499    let store = cli::init_store().await?;
1500    let task_id = task_ref::resolve_store_id(&store, id).await?;
1501    let task = store.get(task_id).await?;
1502    let shown = task
1503        .external_id
1504        .clone()
1505        .unwrap_or_else(|| format!("internal:{}", task.id));
1506    println!("{shown} {} [{}]", task.title, task.status.as_str());
1507    println!("Waiting on:");
1508    let dependencies = store.list_dependencies(task_id).await?;
1509    if dependencies.is_empty() {
1510        println!("  (none)");
1511    }
1512    for dep in dependencies {
1513        let label = dep_label(&task.repo, &dep.depends_on_repo, dep.depends_on_number);
1514        let snap = store
1515            .blocker_snapshot(&dep.depends_on_repo, dep.depends_on_number)
1516            .await?;
1517        let state = blocker_state_label(snap.as_ref());
1518        let local = dep.blocker_status.as_deref().unwrap_or("untracked");
1519        println!("  {label}  {state}  local:{local}  source:{}", dep.source);
1520    }
1521    println!("Waiting on this:");
1522    let number = task
1523        .external_id
1524        .as_deref()
1525        .and_then(|value| value.parse::<i64>().ok())
1526        .unwrap_or(0);
1527    let dependents = if number > 0 {
1528        store.list_dependents(&task.repo, number).await?
1529    } else {
1530        Vec::new()
1531    };
1532    if dependents.is_empty() {
1533        println!("  (none)");
1534    }
1535    for dep in dependents {
1536        let waiter = store.get(dep.task_id).await?;
1537        let label = waiter
1538            .external_id
1539            .clone()
1540            .unwrap_or_else(|| format!("internal:{}", waiter.id));
1541        println!("  {label}  {}  {}", waiter.status.as_str(), waiter.title);
1542    }
1543    Ok(())
1544}
1545
1546/// Show logs / post-mortem for a task (internal or external).
1547pub async fn logs(id: &str) -> anyhow::Result<()> {
1548    let store_owned = cli::init_store().await?;
1549    let resolved = task_ref::resolve(&store_owned, id).await?;
1550    let store: Option<Arc<TaskStore>> = Some(Arc::new(store_owned.clone()));
1551    let repo = resolved.repo.clone();
1552    let task_key = resolved.external_id.clone();
1553
1554    if let Some(store_id) = resolved.store_id {
1555        if let Ok(task) = store_owned.get(store_id).await {
1556            if resolved.is_internal() {
1557                println!("ID: {} (internal)", task.id);
1558                println!("Title: {}", task.title);
1559                println!("Status: {}", task.status.as_str());
1560                if let Some(agent) = &task.agent {
1561                    println!("Agent: {agent}");
1562                }
1563                if let Some(reason) = &task.block_reason {
1564                    println!("Block reason: {reason}");
1565                }
1566                println!("Created: {}", task.created_at);
1567                println!("Updated: {}", task.updated_at);
1568            } else {
1569                println!("ID: {task_key} (external)");
1570                println!("Title: {}", task.title);
1571                println!("State: {}", task.status.as_str());
1572                println!("Labels: {}", task.labels.join(", "));
1573                println!("Author: {}", task.author);
1574                println!("URL: {}", task.url);
1575                println!("Created: {}", task.created_at);
1576                println!("Updated: {}", task.updated_at);
1577            }
1578        }
1579    } else {
1580        println!("ID: {}", resolved.display_spec());
1581    }
1582
1583    // Task store fields
1584    {
1585        {
1586            // Agent, model, and attempts from store — single DB round-trip.
1587            if let Some(ref s) = store
1588                && let Ok(Some(t)) = s.get_by_external_id(&repo, &task_key).await
1589            {
1590                if let Some(ref agent) = t.agent {
1591                    println!("Agent: {agent}");
1592                }
1593                if let Some(ref model) = t.model {
1594                    println!("Model: {model}");
1595                }
1596                if t.attempts > 0 {
1597                    println!("Attempts: {}", t.attempts);
1598                }
1599            }
1600
1601            // Token & cost summary
1602            let usage = store::get_token_usage(&store, &repo, &task_key).await;
1603            let cost = store::get_reported_cost(&store, &repo, &task_key).await;
1604            let total_tokens = usage.total_tokens();
1605            if total_tokens > 0 || cost.is_some() {
1606                println!("\nCost summary:");
1607                println!("  input tokens:  {}", usage.input_tokens);
1608                println!("  output tokens: {}", usage.output_tokens);
1609                println!("  total tokens:  {total_tokens}");
1610                println!("  cost:          {}", format_cost(cost.unwrap_or(0.0)));
1611            }
1612
1613            // Memory (recent attempts)
1614            {
1615                let mem = store::get_recent_memory(&store, &repo, &task_key, 10).await;
1616                if !mem.is_empty() {
1617                    println!("\nMemory (recent attempts):");
1618                    for m in mem {
1619                        println!(
1620                            "- Attempt {} @ {}: agent={} model={}",
1621                            m.attempt,
1622                            m.timestamp,
1623                            m.agent,
1624                            m.model.clone().unwrap_or_default()
1625                        );
1626                        if let Some(err) = m.error.as_ref() {
1627                            println!("    Error: {err}");
1628                        }
1629                        if !m.learnings.is_empty() {
1630                            println!("    Learnings:");
1631                            for l in &m.learnings {
1632                                println!("      - {l}");
1633                            }
1634                        }
1635                        if !m.files_modified.is_empty() {
1636                            println!("    Files modified:");
1637                            for f in &m.files_modified {
1638                                println!("      - {f}");
1639                            }
1640                        }
1641                    }
1642                }
1643            }
1644        }
1645    }
1646
1647    // Show agent output from last attempt if available
1648    let attempt_n = store::opt_store_get_task(&store, &repo, &task_key)
1649        .await
1650        .map_or(0, |t| u32::try_from(t.attempts).unwrap_or(0));
1651    if attempt_n > 0 {
1652        match home::task_attempt_dir(&repo, &task_key, attempt_n) {
1653            Ok(attempt_dir) => {
1654                let output_file = attempt_dir.join("output.json");
1655                let exit_file = attempt_dir.join("exit.txt");
1656
1657                if output_file.exists()
1658                    && let Ok(content) = fs::read_to_string(&output_file)
1659                {
1660                    let tail = patterns::safe_tail(&content, 2000);
1661                    let truncated = if content.len() > 2000 {
1662                        format!(
1663                            "...({} chars truncated)...\n{}",
1664                            content.len() - tail.len(),
1665                            tail
1666                        )
1667                    } else {
1668                        content.clone()
1669                    };
1670                    println!("\n--- Last attempt output (attempt {attempt_n}) ---");
1671                    println!("{truncated}");
1672                }
1673
1674                if exit_file.exists()
1675                    && let Ok(exit_code) = fs::read_to_string(&exit_file)
1676                {
1677                    println!("Exit code: {}", exit_code.trim());
1678                }
1679            }
1680            Err(e) => {
1681                println!("(could not resolve attempt dir: {e})");
1682            }
1683        }
1684    }
1685
1686    // Show review agent output if available
1687    let review_task_id = format!("{task_key}-review");
1688    if let Ok(review_attempt_dir) = home::task_attempt_dir(&repo, &review_task_id, 1) {
1689        let review_output_file = review_attempt_dir.join("output.json");
1690        if review_output_file.exists()
1691            && let Ok(content) = fs::read_to_string(&review_output_file)
1692        {
1693            println!("\n--- Review agent output ---");
1694            println!("{content}");
1695        }
1696    }
1697
1698    // Show audit trail from task_runs table (if available in store)
1699    if let Ok(store) = cli::init_store().await
1700        && let Ok(Some(store_id)) = store.resolve_task_id(&repo, &task_key).await
1701        && let Ok(runs) = store.get_runs(store_id).await
1702        && !runs.is_empty()
1703    {
1704        println!("\n--- Run audit trail ({} runs) ---", runs.len());
1705        for run in &runs {
1706            println!(
1707                "\n  Run #{} [{}] agent={} model={} outcome={}",
1708                run.attempt, run.run_type, run.agent, run.model, run.outcome,
1709            );
1710            if let Some(code) = run.exit_code {
1711                println!("    exit_code: {code}");
1712            }
1713            if !run.error.is_empty() {
1714                println!("    error: {}", run.error);
1715            }
1716            if run.input_tokens > 0 || run.output_tokens > 0 || run.total_cost_usd > 0.0 {
1717                println!(
1718                    "    tokens: {}in/{}out  cost: {}  duration: {:.1}s",
1719                    run.input_tokens,
1720                    run.output_tokens,
1721                    format_cost(run.total_cost_usd),
1722                    run.duration_secs,
1723                );
1724            }
1725            println!("    started: {}", run.started_at);
1726            if let Some(ref completed) = run.completed_at {
1727                println!("    completed: {completed}");
1728            }
1729        }
1730    }
1731
1732    // If tmux session is live, append recent pane capture
1733    let tmux = TmuxManager::new();
1734    let session = tmux.session_name(&repo, &task_key);
1735    if tmux.session_exists(&session).await {
1736        println!("\nLive tmux session detected: {session} — appending recent output:\n---");
1737        match tmux.capture_pane(&session, 200).await {
1738            Ok(output) => {
1739                println!("{output}");
1740            }
1741            Err(e) => {
1742                println!("(tmux capture failed: {e})");
1743            }
1744        }
1745    }
1746
1747    Ok(())
1748}
1749
1750/// Show run history for a task.
1751pub async fn runs(id: &str, verbose: bool) -> anyhow::Result<()> {
1752    let store = cli::init_store().await?;
1753    let task_id = task_ref::resolve_store_id(&store, id).await?;
1754
1755    let runs = store.get_runs(task_id).await?;
1756    if runs.is_empty() {
1757        println!("No runs found for task {id}.");
1758        return Ok(());
1759    }
1760
1761    println!(
1762        "{:<4} {:<8} {:<18} {:<12} {:<8} {:<8} ERROR",
1763        "RUN", "AGENT", "MODEL", "OUTCOME", "DURATION", "COST"
1764    );
1765    println!("{}", "-".repeat(90));
1766
1767    for run in runs {
1768        let model = if run.model.is_empty() {
1769            "-"
1770        } else {
1771            &run.model
1772        };
1773        let error = format_run_text(&run.error, verbose, 48);
1774        println!(
1775            "{:<4} {:<8} {:<18} {:<12} {:<8} {:<8} {}",
1776            run.attempt,
1777            run.agent,
1778            model,
1779            run.outcome,
1780            format_run_duration(run.duration_secs),
1781            format_run_cost(run.total_cost_usd),
1782            error,
1783        );
1784
1785        if verbose {
1786            if !run.stdout.is_empty() {
1787                println!("  stdout:\n{}", run.stdout);
1788            }
1789            if !run.stderr.is_empty() {
1790                println!("  stderr:\n{}", run.stderr);
1791            }
1792            if !run.parsed_response.is_empty() {
1793                println!("  parsed_response:\n{}", run.parsed_response);
1794            }
1795            println!();
1796        }
1797    }
1798
1799    Ok(())
1800}
1801
1802/// Show lifecycle activity timeline for a task.
1803pub async fn activity_log(id: &str, limit: Option<usize>, json: bool) -> anyhow::Result<()> {
1804    let store = cli::init_store().await?;
1805    let task_id = task_ref::resolve_store_id(&store, id).await?;
1806
1807    let events = store.get_activity(task_id, limit).await?;
1808    if events.is_empty() {
1809        println!("No activity found for task {id}.");
1810        return Ok(());
1811    }
1812
1813    println!(
1814        "{:<20} {:<16} {:<12} {:<12} {:<10} {:<14} DETAILS",
1815        "TIME", "EVENT", "FROM", "TO", "AGENT", "MODEL"
1816    );
1817    println!("{}", "-".repeat(120));
1818
1819    for event in events {
1820        let details = if json {
1821            serde_json::to_string(&event.details).unwrap_or_else(|_| "{}".to_string())
1822        } else if event.details.is_null() || event.details == serde_json::json!({}) {
1823            String::new()
1824        } else {
1825            let compact =
1826                serde_json::to_string(&event.details).unwrap_or_else(|_| "{}".to_string());
1827            truncate_err(&compact, 80)
1828        };
1829        println!(
1830            "{:<20} {:<16} {:<12} {:<12} {:<10} {:<14} {}",
1831            event.timestamp,
1832            event.event_type,
1833            event.from_status.as_deref().unwrap_or("-"),
1834            event.to_status.as_deref().unwrap_or("-"),
1835            event.agent.as_deref().unwrap_or("-"),
1836            event.model.as_deref().unwrap_or("-"),
1837            details
1838        );
1839    }
1840
1841    Ok(())
1842}
1843
1844/// Show task routing history with attempt timeline.
1845pub async fn history(id: &str) -> anyhow::Result<()> {
1846    let store = cli::init_store().await?;
1847    let task_id = task_ref::resolve_store_id(&store, id).await?;
1848
1849    let task = store.get(task_id).await?;
1850    let events = store.get_activity(task_id, None).await?;
1851
1852    // Header
1853    println!("Routing History for Task {id}");
1854    println!("{}", "=".repeat(60));
1855    println!("Title: {}", task.title);
1856    println!("Status: {:?}", task.status);
1857    println!();
1858
1859    // Find routing events (routed, rerouted)
1860    let routing_events: Vec<_> = events
1861        .iter()
1862        .filter(|e| e.event_type == "routed" || e.event_type == "rerouted")
1863        .collect();
1864
1865    if routing_events.is_empty() {
1866        println!("No routing history found. Task has not been routed yet.");
1867        return Ok(());
1868    }
1869
1870    // Display routing timeline
1871    println!("Attempt Timeline:");
1872    println!("{}", "-".repeat(60));
1873
1874    for (i, event) in routing_events.iter().enumerate() {
1875        let attempt_num = i + 1;
1876        let agent = event.agent.as_deref().unwrap_or("-");
1877        let model = event.model.as_deref().unwrap_or("-");
1878        let timestamp = &event.timestamp;
1879
1880        if event.event_type == "routed" {
1881            println!("\nAttempt #{attempt_num}");
1882            println!("  Time:     {timestamp}");
1883            println!("  Agent:    {agent}");
1884            println!("  Model:    {model}");
1885
1886            // Extract routing details
1887            if let Some(reason) = event.details.get("reason").and_then(|r| r.as_str()) {
1888                println!("  Reason:   {reason}");
1889            }
1890            if let Some(complexity) = event.details.get("complexity").and_then(|c| c.as_str()) {
1891                println!("  Complexity: {complexity}");
1892            }
1893        } else if event.event_type == "rerouted" {
1894            println!("  → Rerouted at {timestamp}");
1895
1896            // Check for failure reason
1897            if let Some(failure) = event.details.get("failure_reason").and_then(|f| f.as_str()) {
1898                println!("    Failure: {failure}");
1899            } else if let Some(failure) = event.details.get("silence_duration_secs") {
1900                println!("    Failure: Agent silent for {failure}s");
1901            }
1902
1903            // Show from/to agent if available
1904            if let Some(from) = event.details.get("from_agent").and_then(|a| a.as_str())
1905                && let Some(to) = event.details.get("to_agent").and_then(|a| a.as_str())
1906            {
1907                println!("    Change:   {from} → {to}");
1908            }
1909
1910            // Show if agents were exhausted
1911            if event.details.get("agents_exhausted").is_some() {
1912                println!("    Note:     All agents exhausted");
1913            }
1914            if event.details.get("no_fallback_available").is_some() {
1915                println!("    Note:     No fallback available");
1916            }
1917        }
1918    }
1919
1920    // Summary
1921    println!("\n{}", "-".repeat(60));
1922    println!("Summary:");
1923    println!("  Total routing attempts: {}", routing_events.len());
1924
1925    // Get cost summary from task
1926    let total_tokens = task.input_tokens + task.output_tokens;
1927    if total_tokens > 0 {
1928        println!("  Input tokens:  {}", task.input_tokens);
1929        println!("  Output tokens: {}", task.output_tokens);
1930        println!("  Total cost:    {}", format_cost(task.total_cost_usd));
1931    }
1932
1933    // Show current assigned agent/model if available
1934    if let Some(ref agent) = task.agent {
1935        println!("  Current agent: {agent}");
1936    }
1937    if let Some(ref model) = task.model {
1938        println!("  Current model: {model}");
1939    }
1940
1941    Ok(())
1942}
1943
1944/// Unified diagnostic view for a task: status, agent, attempts, last error, PR, block reason.
1945pub async fn inspect(id: &str) -> anyhow::Result<()> {
1946    let store = cli::init_store().await?;
1947    let task_id = task_ref::resolve_store_id(&store, id).await?;
1948
1949    let task = store.get(task_id).await?;
1950
1951    // ── Identity ─────────────────────────────────────────────────────────────
1952    println!("Task: {}", task.title);
1953    println!(
1954        "  ID      : {} (internal:{})",
1955        task.external_id.as_deref().unwrap_or("-"),
1956        task.id
1957    );
1958    println!("  Status  : {}", task.status.as_str());
1959    println!(
1960        "  Priority: {}",
1961        Priority::from_labels(&task.labels).as_str()
1962    );
1963    if task.status == TaskStatus::Waiting {
1964        let blockers = store
1965            .unmet_blocker_labels(task.id)
1966            .await
1967            .unwrap_or_default();
1968        if !blockers.is_empty() {
1969            println!("  Waiting : {}", blockers.join(", "));
1970        }
1971    }
1972    println!(
1973        "  Created : {} ({})",
1974        task.created_at,
1975        format_age(&task.created_at)
1976    );
1977    println!(
1978        "  Updated : {} ({})",
1979        task.updated_at,
1980        format_age(&task.updated_at)
1981    );
1982    if !task.url.is_empty() {
1983        println!("  URL     : {}", task.url);
1984    }
1985
1986    // ── Routing ───────────────────────────────────────────────────────────────
1987    println!();
1988    println!("Routing:");
1989    println!("  Agent      : {}", task.agent.as_deref().unwrap_or("-"));
1990    println!("  Model      : {}", task.model.as_deref().unwrap_or("-"));
1991    if !task.complexity.is_empty() {
1992        println!("  Complexity : {}", task.complexity);
1993    }
1994    if task.route_attempts > 0 {
1995        println!("  Route attempts : {}", task.route_attempts);
1996    }
1997    if !task.route_reason.is_empty() {
1998        println!("  Reason     : {}", truncate_err(&task.route_reason, 120));
1999    }
2000
2001    // ── Execution ─────────────────────────────────────────────────────────────
2002    println!();
2003    println!("Execution:");
2004    println!("  Attempts : {}", task.attempts);
2005    if !task.branch.is_empty() {
2006        println!("  Branch   : {}", task.branch);
2007    }
2008    if !task.worktree.is_empty() {
2009        println!("  Worktree : {}", task.worktree);
2010    }
2011    if !task.last_error.is_empty() {
2012        println!("  Last error : {}", truncate_err(&task.last_error, 200));
2013    }
2014    if !task.summary.is_empty() {
2015        println!("  Summary  : {}", truncate_err(&task.summary, 200));
2016    }
2017
2018    // ── PR / Review ───────────────────────────────────────────────────────────
2019    if task.pr_number.is_some() || task.review_cycles > 0 || !task.pr_review_context.is_empty() {
2020        println!();
2021        println!("PR / Review:");
2022        if let Some(pr) = task.pr_number {
2023            println!("  PR number     : {pr}");
2024        }
2025        if task.review_cycles > 0 {
2026            println!("  Review cycles : {}", task.review_cycles);
2027        }
2028        if !task.pr_review_context.is_empty() {
2029            println!(
2030                "  Review context: {}",
2031                truncate_err(&task.pr_review_context, 200)
2032            );
2033        }
2034    }
2035
2036    // Each failed review attempt, so a rebroadcast escalation shows what kept failing
2037    // instead of only the final "escalated after N retries"
2038    let attempts: Vec<_> = store
2039        .get_activity(task.id, None)
2040        .await
2041        .unwrap_or_default()
2042        .into_iter()
2043        .filter(|a| a.event_type == "review_attempt_failed")
2044        .collect();
2045    if !attempts.is_empty() {
2046        println!();
2047        println!("Review attempts ({} failed):", attempts.len());
2048        for activity in attempts.iter().rev().take(10).rev() {
2049            println!("  {}", review_attempt_line(activity));
2050        }
2051    }
2052
2053    // ── Block reason ─────────────────────────────────────────────────────────
2054    if let Some(ref reason) = task.block_reason {
2055        println!();
2056        println!("Blocked:");
2057        println!("  Reason : {reason}");
2058        if task.auto_unblock_count > 0 {
2059            println!("  Auto-unblock attempts : {}", task.auto_unblock_count);
2060        }
2061    }
2062
2063    // ── Cost ─────────────────────────────────────────────────────────────────
2064    let total_tokens = task.input_tokens + task.output_tokens;
2065    if total_tokens > 0 || task.total_cost_usd > 0.0 {
2066        println!();
2067        println!("Cost:");
2068        println!(
2069            "  Tokens : {}in / {}out",
2070            task.input_tokens, task.output_tokens
2071        );
2072        println!("  Total  : {}", format_cost(task.total_cost_usd));
2073    }
2074
2075    // ── Live session ─────────────────────────────────────────────────────────
2076    let task_key = task
2077        .external_id
2078        .clone()
2079        .unwrap_or_else(|| format!("internal:{}", task.id));
2080    let tmux = TmuxManager::new();
2081    let session = tmux.session_name(&task.repo, &task_key);
2082    if tmux.session_exists(&session).await {
2083        println!();
2084        println!("Live session: {session} (use `orch task attach {id}` to connect)");
2085    }
2086
2087    Ok(())
2088}
2089
2090#[cfg(test)]
2091mod tests {
2092    use super::*;
2093
2094    #[test]
2095    fn format_age_seconds() {
2096        let ts = (Utc::now() - chrono::Duration::seconds(30)).to_rfc3339();
2097        let age = format_age(&ts);
2098        assert!(age.ends_with('s'), "expected seconds format, got {age}");
2099    }
2100
2101    #[test]
2102    fn format_age_minutes() {
2103        let ts = (Utc::now() - chrono::Duration::minutes(5)).to_rfc3339();
2104        let age = format_age(&ts);
2105        assert!(age.ends_with('m'), "expected minutes format, got {age}");
2106    }
2107
2108    #[test]
2109    fn format_age_hours() {
2110        let ts = (Utc::now() - chrono::Duration::hours(3)).to_rfc3339();
2111        let age = format_age(&ts);
2112        assert!(age.ends_with('h'), "expected hours format, got {age}");
2113    }
2114
2115    #[test]
2116    fn format_age_days() {
2117        let ts = (Utc::now() - chrono::Duration::days(2)).to_rfc3339();
2118        let age = format_age(&ts);
2119        assert!(age.ends_with('d'), "expected days format, got {age}");
2120    }
2121
2122    #[test]
2123    fn format_age_invalid_returns_dash() {
2124        let age = format_age("not-a-timestamp");
2125        assert_eq!(age, "-");
2126    }
2127
2128    fn task_ref(status: &str) -> store::CliTaskRef {
2129        store::CliTaskRef {
2130            store_id: Some(7),
2131            repo: "owner/repo".to_string(),
2132            origin: "github".to_string(),
2133            title: "t".to_string(),
2134            external_id: "58".to_string(),
2135            status: status.to_string(),
2136        }
2137    }
2138
2139    #[test]
2140    fn refuse_if_done_rejects_done_tasks() {
2141        for action in ["retry", "unblock"] {
2142            let err = refuse_if_done(&task_ref("done"), action)
2143                .expect_err("done task must not be revived");
2144            let msg = err.to_string();
2145            assert!(msg.contains("is done"), "got: {msg}");
2146            assert!(msg.contains(action), "got: {msg}");
2147        }
2148    }
2149
2150    #[test]
2151    fn refuse_if_done_allows_other_statuses() {
2152        for status in ["blocked", "needs_review", "new", "in_review", ""] {
2153            assert!(refuse_if_done(&task_ref(status), "unblock").is_ok());
2154        }
2155    }
2156
2157    #[test]
2158    fn matches_project_filter_accepts_exact_repo_slug() {
2159        assert!(matches_project_filter(
2160            "gabrielkoerich/orch",
2161            "gabrielkoerich/orch"
2162        ));
2163    }
2164
2165    #[test]
2166    fn matches_project_filter_accepts_repo_name_suffix() {
2167        assert!(matches_project_filter("gabrielkoerich/orch", "orch"));
2168    }
2169
2170    #[test]
2171    fn matches_project_filter_rejects_non_matching_repo() {
2172        assert!(!matches_project_filter("gabrielkoerich/orch", "bean"));
2173    }
2174
2175    /// Verify the forced-routing field construction for agent-only case.
2176    #[test]
2177    fn retry_force_route_fields_agent_only() {
2178        let forced_agent = "claude";
2179        let model: Option<String> = None;
2180        let fields: Vec<(&str, serde_json::Value)> = {
2181            let mut f = vec![
2182                ("agent", serde_json::json!(forced_agent)),
2183                (
2184                    "route_reason",
2185                    serde_json::json!(format!("forced via retry --agent {forced_agent}")),
2186                ),
2187            ];
2188            if let Some(ref m) = model {
2189                f.push(("model", serde_json::json!(m)));
2190            }
2191            f
2192        };
2193        assert_eq!(fields.len(), 2);
2194        assert_eq!(fields[0].1, serde_json::json!("claude"));
2195        assert_eq!(
2196            fields[1].1,
2197            serde_json::json!("forced via retry --agent claude")
2198        );
2199    }
2200
2201    /// Verify the forced-routing field construction for agent+model case.
2202    #[test]
2203    fn retry_force_route_fields_agent_and_model() {
2204        let fields = retry_force_fields("claude", Some("opus"));
2205        assert_eq!(fields.len(), 3);
2206        assert_eq!(fields[0].1, serde_json::json!("claude"));
2207        assert_eq!(fields[2].0, "model");
2208        assert_eq!(fields[2].1, serde_json::json!("opus"));
2209    }
2210
2211    /// Verify that the model hint display is correct in both cases.
2212    #[test]
2213    fn retry_model_hint_display() {
2214        let model_some: Option<String> = Some("opus".to_string());
2215        let model_none: Option<String> = None;
2216        assert_eq!(model_some.as_deref().unwrap_or("(router default)"), "opus");
2217        assert_eq!(
2218            model_none.as_deref().unwrap_or("(router default)"),
2219            "(router default)"
2220        );
2221    }
2222
2223    #[test]
2224    fn review_attempt_line_shows_cause_and_reason() {
2225        let activity = store::TaskActivity {
2226            id: 1,
2227            task_id: 7,
2228            timestamp: "2026-10-25T22:40:00Z".to_string(),
2229            event_type: "review_attempt_failed".to_string(),
2230            from_status: None,
2231            to_status: None,
2232            agent: None,
2233            model: None,
2234            details: serde_json::json!({
2235                "cause": "rate_limit",
2236                "external": true,
2237                "reason": "claude failed: rate limit reached",
2238            }),
2239        };
2240        let line = review_attempt_line(&activity);
2241        assert_eq!(
2242            line,
2243            "2026-10-25T22:40:00Z  rate_limit (external): claude failed: rate limit reached"
2244        );
2245    }
2246
2247    #[test]
2248    fn truncate_err_under_limit() {
2249        let s = "short error";
2250        assert_eq!(truncate_err(s, 50), "short error");
2251    }
2252
2253    #[test]
2254    fn truncate_err_cuts_inside_char_down_to_boundary() {
2255        assert_eq!(truncate_err("héllo", 2), "h...");
2256        assert_eq!(truncate_err("é", 1), "...");
2257        assert_eq!(truncate_err("abc", 0), "...");
2258    }
2259
2260    #[test]
2261    fn truncate_err_exact_limit() {
2262        let s = "short error";
2263        assert_eq!(truncate_err(s, 11), "short error");
2264    }
2265
2266    #[test]
2267    fn truncate_err_truncates() {
2268        let s = "this is a long error message that should be cut";
2269        let result = truncate_err(s, 10);
2270        assert!(result.ends_with("..."));
2271        assert!(result.len() <= 13); // 10 chars + "..."
2272    }
2273
2274    #[test]
2275    fn truncate_err_multi_byte_char_boundary() {
2276        // "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...
2277        // byte 3 = 'l' (valid boundary); byte 4 = 'l' (valid); byte 5 = 'o' (valid)
2278        // No panic = success; exact result varies by where the boundary lands
2279        let s = "héllo world";
2280        let result = truncate_err(s, 3);
2281        assert!(result.ends_with("..."));
2282        assert!(!result.contains("panic"));
2283    }
2284
2285    #[test]
2286    fn truncate_err_emoji() {
2287        // "🔥 error message": 🔥=4 bytes, space=1, e=1, r=1, r=1, o=1, sp=1, m=1...
2288        // byte 5 = 'e' (valid boundary); walk-back not needed
2289        let s = "🔥 error message";
2290        let result = truncate_err(s, 5);
2291        assert_eq!(result, "🔥 ...");
2292    }
2293
2294    #[test]
2295    fn truncate_err_cjk() {
2296        // "你好世界": 你=3 bytes(0-2), 好=3 bytes(3-5), 世=3 bytes(6-8), 界=3 bytes(9-11)
2297        // byte 4 falls inside 好; walk back to byte 3 (= end of 你)
2298        let s = "你好世界";
2299        let result = truncate_err(s, 4);
2300        assert_eq!(result, "你...");
2301    }
2302}