Skip to main content

orch/cli/task/
history.rs

1//! `orch task` logs, runs, activity, history and inspect
2
3use super::{
4    format_age, format_run_cost, format_run_duration, format_run_text, review_attempt_line,
5    truncate_err,
6};
7use crate::cli;
8use crate::cli::cost::format_cost;
9use crate::cli::task_ref;
10use crate::engine::agents::patterns;
11use crate::engine::priority::Priority;
12use crate::home;
13use crate::store;
14use crate::store::TaskStatus;
15use crate::store::TaskStore;
16use crate::tmux::TmuxManager;
17use std::fs;
18use std::sync::Arc;
19
20/// Show logs / post-mortem for a task (internal or external).
21pub async fn logs(id: &str) -> anyhow::Result<()> {
22    let store_owned = cli::init_store().await?;
23    let resolved = task_ref::resolve(&store_owned, id).await?;
24    let store: Option<Arc<TaskStore>> = Some(Arc::new(store_owned.clone()));
25    let repo = resolved.repo.clone();
26    let task_key = resolved.external_id.clone();
27
28    if let Some(store_id) = resolved.store_id {
29        if let Ok(task) = store_owned.get(store_id).await {
30            if resolved.is_internal() {
31                println!("ID: {} (internal)", task.id);
32                println!("Title: {}", task.title);
33                println!("Status: {}", task.status.as_str());
34                if let Some(agent) = &task.agent {
35                    println!("Agent: {agent}");
36                }
37                if let Some(reason) = &task.block_reason {
38                    println!("Block reason: {reason}");
39                }
40                println!("Created: {}", task.created_at);
41                println!("Updated: {}", task.updated_at);
42            } else {
43                println!("ID: {task_key} (external)");
44                println!("Title: {}", task.title);
45                println!("State: {}", task.status.as_str());
46                println!("Labels: {}", task.labels.join(", "));
47                println!("Author: {}", task.author);
48                println!("URL: {}", task.url);
49                println!("Created: {}", task.created_at);
50                println!("Updated: {}", task.updated_at);
51            }
52        }
53    } else {
54        println!("ID: {}", resolved.display_spec());
55    }
56
57    // Task store fields
58    {
59        {
60            // Agent, model, and attempts from store — single DB round-trip.
61            if let Some(ref s) = store
62                && let Ok(Some(t)) = s.get_by_external_id(&repo, &task_key).await
63            {
64                if let Some(ref agent) = t.agent {
65                    println!("Agent: {agent}");
66                }
67                if let Some(ref model) = t.model {
68                    println!("Model: {model}");
69                }
70                if t.attempts > 0 {
71                    println!("Attempts: {}", t.attempts);
72                }
73            }
74
75            // Token & cost summary
76            let usage = store::get_token_usage(&store, &repo, &task_key).await;
77            let cost = store::get_reported_cost(&store, &repo, &task_key).await;
78            let total_tokens = usage.total_tokens();
79            if total_tokens > 0 || cost.is_some() {
80                println!("\nCost summary:");
81                println!("  input tokens:  {}", usage.input_tokens);
82                println!("  output tokens: {}", usage.output_tokens);
83                println!("  total tokens:  {total_tokens}");
84                println!("  cost:          {}", format_cost(cost.unwrap_or(0.0)));
85            }
86
87            // Memory (recent attempts)
88            {
89                let mem = store::get_recent_memory(&store, &repo, &task_key, 10).await;
90                if !mem.is_empty() {
91                    println!("\nMemory (recent attempts):");
92                    for m in mem {
93                        println!(
94                            "- Attempt {} @ {}: agent={} model={}",
95                            m.attempt,
96                            m.timestamp,
97                            m.agent,
98                            m.model.clone().unwrap_or_default()
99                        );
100                        if let Some(err) = m.error.as_ref() {
101                            println!("    Error: {err}");
102                        }
103                        if !m.learnings.is_empty() {
104                            println!("    Learnings:");
105                            for l in &m.learnings {
106                                println!("      - {l}");
107                            }
108                        }
109                        if !m.files_modified.is_empty() {
110                            println!("    Files modified:");
111                            for f in &m.files_modified {
112                                println!("      - {f}");
113                            }
114                        }
115                    }
116                }
117            }
118        }
119    }
120
121    // Show agent output from last attempt if available
122    let attempt_n = store::opt_store_get_task(&store, &repo, &task_key)
123        .await
124        .map_or(0, |t| u32::try_from(t.attempts).unwrap_or(0));
125    if attempt_n > 0 {
126        match home::task_attempt_dir(&repo, &task_key, attempt_n) {
127            Ok(attempt_dir) => {
128                let output_file = attempt_dir.join("output.json");
129                let exit_file = attempt_dir.join("exit.txt");
130
131                if output_file.exists()
132                    && let Ok(content) = fs::read_to_string(&output_file)
133                {
134                    let tail = patterns::safe_tail(&content, 2000);
135                    let truncated = if content.len() > 2000 {
136                        format!(
137                            "...({} chars truncated)...\n{}",
138                            content.len() - tail.len(),
139                            tail
140                        )
141                    } else {
142                        content.clone()
143                    };
144                    println!("\n--- Last attempt output (attempt {attempt_n}) ---");
145                    println!("{truncated}");
146                }
147
148                if exit_file.exists()
149                    && let Ok(exit_code) = fs::read_to_string(&exit_file)
150                {
151                    println!("Exit code: {}", exit_code.trim());
152                }
153            }
154            Err(e) => {
155                println!("(could not resolve attempt dir: {e})");
156            }
157        }
158    }
159
160    // Show review agent output if available
161    let review_task_id = format!("{task_key}-review");
162    if let Ok(review_attempt_dir) = home::task_attempt_dir(&repo, &review_task_id, 1) {
163        let review_output_file = review_attempt_dir.join("output.json");
164        if review_output_file.exists()
165            && let Ok(content) = fs::read_to_string(&review_output_file)
166        {
167            println!("\n--- Review agent output ---");
168            println!("{content}");
169        }
170    }
171
172    // Show audit trail from task_runs table (if available in store)
173    if let Ok(store) = cli::init_store().await
174        && let Ok(Some(store_id)) = store.resolve_task_id(&repo, &task_key).await
175        && let Ok(runs) = store.get_runs(store_id).await
176        && !runs.is_empty()
177    {
178        println!("\n--- Run audit trail ({} runs) ---", runs.len());
179        for run in &runs {
180            println!(
181                "\n  Run #{} [{}] agent={} model={} outcome={}",
182                run.attempt, run.run_type, run.agent, run.model, run.outcome,
183            );
184            if let Some(code) = run.exit_code {
185                println!("    exit_code: {code}");
186            }
187            if !run.error.is_empty() {
188                println!("    error: {}", run.error);
189            }
190            if run.input_tokens > 0 || run.output_tokens > 0 || run.total_cost_usd > 0.0 {
191                println!(
192                    "    tokens: {}in/{}out  cost: {}  duration: {:.1}s",
193                    run.input_tokens,
194                    run.output_tokens,
195                    format_cost(run.total_cost_usd),
196                    run.duration_secs,
197                );
198            }
199            println!("    started: {}", run.started_at);
200            if let Some(ref completed) = run.completed_at {
201                println!("    completed: {completed}");
202            }
203        }
204    }
205
206    // If tmux session is live, append recent pane capture
207    let tmux = TmuxManager::new();
208    let session = tmux.session_name(&repo, &task_key);
209    if tmux.session_exists(&session).await {
210        println!("\nLive tmux session detected: {session} — appending recent output:\n---");
211        match tmux.capture_pane(&session, 200).await {
212            Ok(output) => {
213                println!("{output}");
214            }
215            Err(e) => {
216                println!("(tmux capture failed: {e})");
217            }
218        }
219    }
220
221    Ok(())
222}
223
224/// Show run history for a task.
225pub async fn runs(id: &str, verbose: bool) -> anyhow::Result<()> {
226    let store = cli::init_store().await?;
227    let task_id = task_ref::resolve_store_id(&store, id).await?;
228
229    let runs = store.get_runs(task_id).await?;
230    if runs.is_empty() {
231        println!("No runs found for task {id}.");
232        return Ok(());
233    }
234
235    println!(
236        "{:<4} {:<8} {:<18} {:<12} {:<8} {:<8} ERROR",
237        "RUN", "AGENT", "MODEL", "OUTCOME", "DURATION", "COST"
238    );
239    println!("{}", "-".repeat(90));
240
241    for run in runs {
242        let model = if run.model.is_empty() {
243            "-"
244        } else {
245            &run.model
246        };
247        let error = format_run_text(&run.error, verbose, 48);
248        println!(
249            "{:<4} {:<8} {:<18} {:<12} {:<8} {:<8} {}",
250            run.attempt,
251            run.agent,
252            model,
253            run.outcome,
254            format_run_duration(run.duration_secs),
255            format_run_cost(run.total_cost_usd),
256            error,
257        );
258
259        if verbose {
260            if !run.stdout.is_empty() {
261                println!("  stdout:\n{}", run.stdout);
262            }
263            if !run.stderr.is_empty() {
264                println!("  stderr:\n{}", run.stderr);
265            }
266            if !run.parsed_response.is_empty() {
267                println!("  parsed_response:\n{}", run.parsed_response);
268            }
269            println!();
270        }
271    }
272
273    Ok(())
274}
275
276/// Show lifecycle activity timeline for a task.
277pub async fn activity_log(id: &str, limit: Option<usize>, json: bool) -> anyhow::Result<()> {
278    let store = cli::init_store().await?;
279    let task_id = task_ref::resolve_store_id(&store, id).await?;
280
281    let events = store.get_activity(task_id, limit).await?;
282    if events.is_empty() {
283        println!("No activity found for task {id}.");
284        return Ok(());
285    }
286
287    println!(
288        "{:<20} {:<16} {:<12} {:<12} {:<10} {:<14} DETAILS",
289        "TIME", "EVENT", "FROM", "TO", "AGENT", "MODEL"
290    );
291    println!("{}", "-".repeat(120));
292
293    for event in events {
294        let details = if json {
295            serde_json::to_string(&event.details).unwrap_or_else(|_| "{}".to_string())
296        } else if event.details.is_null() || event.details == serde_json::json!({}) {
297            String::new()
298        } else {
299            let compact =
300                serde_json::to_string(&event.details).unwrap_or_else(|_| "{}".to_string());
301            truncate_err(&compact, 80)
302        };
303        println!(
304            "{:<20} {:<16} {:<12} {:<12} {:<10} {:<14} {}",
305            event.timestamp,
306            event.event_type,
307            event.from_status.as_deref().unwrap_or("-"),
308            event.to_status.as_deref().unwrap_or("-"),
309            event.agent.as_deref().unwrap_or("-"),
310            event.model.as_deref().unwrap_or("-"),
311            details
312        );
313    }
314
315    Ok(())
316}
317
318/// Show task routing history with attempt timeline.
319pub async fn history(id: &str) -> anyhow::Result<()> {
320    let store = cli::init_store().await?;
321    let task_id = task_ref::resolve_store_id(&store, id).await?;
322
323    let task = store.get(task_id).await?;
324    let events = store.get_activity(task_id, None).await?;
325
326    // Header
327    println!("Routing History for Task {id}");
328    println!("{}", "=".repeat(60));
329    println!("Title: {}", task.title);
330    println!("Status: {:?}", task.status);
331    println!();
332
333    // Find routing events (routed, rerouted)
334    let routing_events: Vec<_> = events
335        .iter()
336        .filter(|e| e.event_type == "routed" || e.event_type == "rerouted")
337        .collect();
338
339    if routing_events.is_empty() {
340        println!("No routing history found. Task has not been routed yet.");
341        return Ok(());
342    }
343
344    // Display routing timeline
345    println!("Attempt Timeline:");
346    println!("{}", "-".repeat(60));
347
348    for (i, event) in routing_events.iter().enumerate() {
349        let attempt_num = i + 1;
350        let agent = event.agent.as_deref().unwrap_or("-");
351        let model = event.model.as_deref().unwrap_or("-");
352        let timestamp = &event.timestamp;
353
354        if event.event_type == "routed" {
355            println!("\nAttempt #{attempt_num}");
356            println!("  Time:     {timestamp}");
357            println!("  Agent:    {agent}");
358            println!("  Model:    {model}");
359
360            // Extract routing details
361            if let Some(reason) = event.details.get("reason").and_then(|r| r.as_str()) {
362                println!("  Reason:   {reason}");
363            }
364            if let Some(complexity) = event.details.get("complexity").and_then(|c| c.as_str()) {
365                println!("  Complexity: {complexity}");
366            }
367        } else if event.event_type == "rerouted" {
368            println!("  → Rerouted at {timestamp}");
369
370            // Check for failure reason
371            if let Some(failure) = event.details.get("failure_reason").and_then(|f| f.as_str()) {
372                println!("    Failure: {failure}");
373            } else if let Some(failure) = event.details.get("silence_duration_secs") {
374                println!("    Failure: Agent silent for {failure}s");
375            }
376
377            // Show from/to agent if available
378            if let Some(from) = event.details.get("from_agent").and_then(|a| a.as_str())
379                && let Some(to) = event.details.get("to_agent").and_then(|a| a.as_str())
380            {
381                println!("    Change:   {from} → {to}");
382            }
383
384            // Show if agents were exhausted
385            if event.details.get("agents_exhausted").is_some() {
386                println!("    Note:     All agents exhausted");
387            }
388            if event.details.get("no_fallback_available").is_some() {
389                println!("    Note:     No fallback available");
390            }
391        }
392    }
393
394    // Summary
395    println!("\n{}", "-".repeat(60));
396    println!("Summary:");
397    println!("  Total routing attempts: {}", routing_events.len());
398
399    // Get cost summary from task
400    let total_tokens = task.input_tokens + task.output_tokens;
401    if total_tokens > 0 {
402        println!("  Input tokens:  {}", task.input_tokens);
403        println!("  Output tokens: {}", task.output_tokens);
404        println!("  Total cost:    {}", format_cost(task.total_cost_usd));
405    }
406
407    // Show current assigned agent/model if available
408    if let Some(ref agent) = task.agent {
409        println!("  Current agent: {agent}");
410    }
411    if let Some(ref model) = task.model {
412        println!("  Current model: {model}");
413    }
414
415    Ok(())
416}
417
418/// Unified diagnostic view for a task: status, agent, attempts, last error, PR, block reason.
419pub async fn inspect(id: &str) -> anyhow::Result<()> {
420    let store = cli::init_store().await?;
421    let task_id = task_ref::resolve_store_id(&store, id).await?;
422
423    let task = store.get(task_id).await?;
424
425    // ── Identity ─────────────────────────────────────────────────────────────
426    println!("Task: {}", task.title);
427    println!(
428        "  ID      : {} (internal:{})",
429        task.external_id.as_deref().unwrap_or("-"),
430        task.id
431    );
432    println!("  Status  : {}", task.status.as_str());
433    println!(
434        "  Priority: {}",
435        Priority::from_labels(&task.labels).as_str()
436    );
437    if task.status == TaskStatus::Waiting {
438        let blockers = store
439            .unmet_blocker_labels(task.id)
440            .await
441            .unwrap_or_default();
442        if !blockers.is_empty() {
443            println!("  Waiting : {}", blockers.join(", "));
444        }
445    }
446    println!(
447        "  Created : {} ({})",
448        task.created_at,
449        format_age(&task.created_at)
450    );
451    println!(
452        "  Updated : {} ({})",
453        task.updated_at,
454        format_age(&task.updated_at)
455    );
456    if !task.url.is_empty() {
457        println!("  URL     : {}", task.url);
458    }
459
460    // ── Routing ───────────────────────────────────────────────────────────────
461    println!();
462    println!("Routing:");
463    println!("  Agent      : {}", task.agent.as_deref().unwrap_or("-"));
464    println!("  Model      : {}", task.model.as_deref().unwrap_or("-"));
465    if !task.complexity.is_empty() {
466        println!("  Complexity : {}", task.complexity);
467    }
468    if task.route_attempts > 0 {
469        println!("  Route attempts : {}", task.route_attempts);
470    }
471    if !task.route_reason.is_empty() {
472        println!("  Reason     : {}", truncate_err(&task.route_reason, 120));
473    }
474
475    // ── Execution ─────────────────────────────────────────────────────────────
476    println!();
477    println!("Execution:");
478    println!("  Attempts : {}", task.attempts);
479    if !task.branch.is_empty() {
480        println!("  Branch   : {}", task.branch);
481    }
482    if !task.worktree.is_empty() {
483        println!("  Worktree : {}", task.worktree);
484    }
485    if !task.last_error.is_empty() {
486        println!("  Last error : {}", truncate_err(&task.last_error, 200));
487    }
488    if !task.summary.is_empty() {
489        println!("  Summary  : {}", truncate_err(&task.summary, 200));
490    }
491
492    // ── PR / Review ───────────────────────────────────────────────────────────
493    if task.pr_number.is_some() || task.review_cycles > 0 || !task.pr_review_context.is_empty() {
494        println!();
495        println!("PR / Review:");
496        if let Some(pr) = task.pr_number {
497            println!("  PR number     : {pr}");
498        }
499        if task.review_cycles > 0 {
500            println!("  Review cycles : {}", task.review_cycles);
501        }
502        if !task.pr_review_context.is_empty() {
503            println!(
504                "  Review context: {}",
505                truncate_err(&task.pr_review_context, 200)
506            );
507        }
508    }
509
510    // Each failed review attempt, so a rebroadcast escalation shows what kept failing
511    // instead of only the final "escalated after N retries"
512    let attempts: Vec<_> = store
513        .get_activity(task.id, None)
514        .await
515        .unwrap_or_default()
516        .into_iter()
517        .filter(|a| a.event_type == "review_attempt_failed")
518        .collect();
519    if !attempts.is_empty() {
520        println!();
521        println!("Review attempts ({} failed):", attempts.len());
522        for activity in attempts.iter().rev().take(10).rev() {
523            println!("  {}", review_attempt_line(activity));
524        }
525    }
526
527    // ── Block reason ─────────────────────────────────────────────────────────
528    if let Some(ref reason) = task.block_reason {
529        println!();
530        println!("Blocked:");
531        println!("  Reason : {reason}");
532        if task.auto_unblock_count > 0 {
533            println!("  Auto-unblock attempts : {}", task.auto_unblock_count);
534        }
535    }
536
537    // ── Cost ─────────────────────────────────────────────────────────────────
538    let total_tokens = task.input_tokens + task.output_tokens;
539    if total_tokens > 0 || task.total_cost_usd > 0.0 {
540        println!();
541        println!("Cost:");
542        println!(
543            "  Tokens : {}in / {}out",
544            task.input_tokens, task.output_tokens
545        );
546        println!("  Total  : {}", format_cost(task.total_cost_usd));
547    }
548
549    // ── Live session ─────────────────────────────────────────────────────────
550    let task_key = task
551        .external_id
552        .clone()
553        .unwrap_or_else(|| format!("internal:{}", task.id));
554    let tmux = TmuxManager::new();
555    let session = tmux.session_name(&task.repo, &task_key);
556    if tmux.session_exists(&session).await {
557        println!();
558        println!("Live session: {session} (use `orch task attach {id}` to connect)");
559    }
560
561    Ok(())
562}