ai-dispatch 9.1.0

Multi-AI CLI team orchestrator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// Handler for `aid show <task-id>` — unified task inspection.
// Combines events, diff, output, log, and AI explanation into one command.

use anyhow::{Context, Result};
use std::path::Path;
use std::sync::Arc;

use crate::board::render_task_detail;
use crate::cmd;
use crate::store::Store;
use crate::types::TaskStatus;

#[path = "show_output.rs"]
mod show_output;

pub use show_output::{
    diff_text, log_text, log_text_brief, output_text, output_text_brief, output_text_for_task,
};
#[allow(unused_imports)]
pub use show_output::read_task_output;
pub(crate) use show_output::{
    diff_stat, diff_text_file, extract_messages_from_log, parse_diff_stat, read_tail,
    worktree_diff, worktree_state_section,
};

#[path = "show_helpers.rs"]
mod show_helpers;
#[path = "show_json.rs"]
mod show_json;

pub(crate) use show_helpers::load_task;
pub(crate) use show_json::task_hook_json;

use show_json::task_json;
use show_helpers::{
    completion_conclusion, failure_details, inplace_diff_stat, reconstruct_context,
    research_findings, stderr_tail, task_has_changes,
};

pub struct ShowArgs {
    pub task_id: String,
    pub events: bool,
    pub context: bool,
    pub diff: bool,
    pub summary: bool,
    pub file: Option<String>,
    pub output: bool,
    pub result: bool,
    pub transcript: bool,
    pub full: bool,
    pub brief: bool,
    pub explain: bool,
    pub log: bool,
    pub json: bool,
    pub agent: Option<String>,
    pub model: Option<String>,
}

#[derive(Clone, Copy)]
pub enum ShowMode {
    Default,
    Summary,
    Events,
    Context,
    Diff,
    Output,
    Transcript,
    Log,
}

pub async fn run(store: Arc<Store>, args: ShowArgs) -> Result<()> {
    if args.result {
        print!("{}", result_text(&store, &args.task_id)?);
        return Ok(());
    }
    if args.json {
        let text = task_json(&store, &args.task_id)?;
        println!("{text}");
        return Ok(());
    }
    if args.context {
        let text = render_mode_text(&store, &args.task_id, ShowMode::Context)?;
        print!("{text}");
        return Ok(());
    }
    if args.explain {
        return cmd::explain::run_explain(store, &args.task_id, args.agent, args.model).await;
    }
    let mode = if args.summary {
        ShowMode::Summary
    } else if args.events {
        ShowMode::Events
    } else if args.diff {
        ShowMode::Diff
    } else if args.output {
        ShowMode::Output
    } else if args.transcript {
        ShowMode::Transcript
    } else if args.log {
        ShowMode::Log
    } else {
        ShowMode::Default
    };
    let task = load_task(&store, &args.task_id)?;
    let text = if matches!(mode, ShowMode::Events) {
        events_text(&store, &args.task_id, args.full)?
    } else if matches!(mode, ShowMode::Output) {
        render_output_text(&store, &args.task_id, args.full, args.brief)?
    } else if matches!(mode, ShowMode::Log) {
        render_log_text(&args.task_id, args.full)?
    } else if matches!(mode, ShowMode::Diff) {
        if let Some(file) = args.file.as_deref() {
            diff_text_file(&store, &args.task_id, file)?
        } else {
            diff_text(&store, &args.task_id)?
        }
    } else {
        render_mode_text(&store, &args.task_id, mode)?
    };
    print!("{text}");
    if matches!(mode, ShowMode::Diff) {
        aid_hint!(
            "[aid] Actions: aid merge {} | aid retry {} -f \"feedback\"",
            args.task_id, args.task_id
        );
    }
    if !task.status.is_terminal() {
        aid_hint!(
            "[aid] Task is still running. To wait for completion: aid watch --wait {}",
            args.task_id
        );
    }
    Ok(())
}

fn render_output_text(store: &Arc<Store>, task_id: &str, full: bool, brief: bool) -> Result<String> {
    if full && !brief {
        return output_text(store, task_id);
    }
    render_output_brief_text(store, task_id)
}

fn render_output_brief_text(store: &Arc<Store>, task_id: &str) -> Result<String> {
    let mut text = output_text_brief(store, task_id)?;
    let truncated = output_text(store, task_id)
        .map(|full_text| full_text != text)
        .unwrap_or(false);
    if truncated {
        if !text.ends_with('\n') {
            text.push('\n');
        }
        text.push_str(&format!(
            "[truncated — use `aid show {task_id} --output --full` for full content]"
        ));
    }
    Ok(text)
}

fn render_log_text(task_id: &str, full: bool) -> Result<String> {
    if full {
        return log_text(task_id);
    }
    log_text_brief(task_id)
}

pub fn render_mode_text(store: &Arc<Store>, task_id: &str, mode: ShowMode) -> Result<String> {
    match mode {
        ShowMode::Default => audit_text(store, task_id),
        ShowMode::Summary => summary_text(store, task_id),
        ShowMode::Events => events_text(store, task_id, false),
        ShowMode::Context => context_text(store, task_id),
        ShowMode::Diff => diff_text(store, task_id),
        ShowMode::Output => output_text(store, task_id),
        ShowMode::Transcript => transcript_text(task_id),
        ShowMode::Log => log_text(task_id),
    }
}

fn result_text(store: &Arc<Store>, task_id: &str) -> Result<String> {
    let path = crate::paths::task_dir(task_id).join("result.md");
    if !path.exists() {
        if let Ok(task) = load_task(store, task_id)
            && let Some(banner) = audit_result_missing_banner(&task)
        {
            return Ok(banner);
        }
        return Ok("No result file for this task\n".to_string());
    }
    Ok(std::fs::read_to_string(path)?)
}

fn events_text(store: &Arc<Store>, task_id: &str, full: bool) -> Result<String> {
    let events = store.get_events(task_id)?;
    if events.is_empty() {
        return Ok("No events.\n".to_string());
    }
    let mut out = String::from("Events:\n");
    for event in events {
        let detail = if full { event.full_detail() } else { &event.detail };
        out.push_str(&format!(
            "  {}  [{:>10}] {}\n",
            event.timestamp.format("%H:%M:%S"),
            event.event_kind.as_str(),
            detail,
        ));
    }
    Ok(out)
}

/// When an audit-style task ends without producing the structured `result.md`,
/// surface a clear retry hint instead of letting the caller fall back to the
/// raw (often truncated) agent output.
fn audit_result_missing_banner(task: &crate::types::Task) -> Option<String> {
    if !matches!(task.status, TaskStatus::Done | TaskStatus::Merged) {
        return None;
    }
    if !crate::cmd::report_mode::prompt_is_audit_report(&task.prompt) {
        return None;
    }
    let result_path = crate::paths::task_dir(&task.id.0).join("result.md");
    if result_path.exists() {
        return None;
    }
    Some(format!(
        "⚠ Structured audit result missing.\n\
         The agent did not write result.md as instructed.\n\
         Likely cause: weak model truncated mid-output or ignored the result-file instruction.\n\
         Retry with a stronger agent:\n  \
         aid retry {} --agent codex\n",
        task.id.0
    ))
}

fn transcript_text(task_id: &str) -> Result<String> {
    let path = crate::paths::transcript_path(task_id);
    std::fs::read_to_string(&path)
        .with_context(|| format!("Failed to read transcript {}", path.display()))
}

// --- Default mode: events + stderr + diff stat ---

pub fn audit_text(store: &Arc<Store>, task_id: &str) -> Result<String> {
    let task = load_task(store, task_id)?;
    let events = store.get_events(task_id)?;
    let retry_chain = if task.parent_task_id.is_some() {
        Some(store.get_retry_chain(task_id)?)
    } else {
        None
    };
    let mut out = render_task_detail(&task, &events, retry_chain);
    if let Some(notice) = terminal_missing_result_notice(&task) {
        out.push('\n');
        out.push_str(&notice);
    }

    if let Some(checklist) = cmd::show_checklist::render_checklist_status(store.as_ref(), &task) {
        out.push('\n');
        out.push_str(&checklist);
    }

    if task.status == TaskStatus::Failed
        && let Some(details) = failure_details(&events)
    {
        out.push_str("\nFailure details:\n");
        out.push_str(&details);
    }

    if task.status == TaskStatus::Failed
        && let Some(stderr) = stderr_tail(task_id)
    {
        out.push_str("\nStderr:\n");
        out.push_str(&stderr);
    }

    let mut live_dirty = false;
    if let Some(ref wt_path) = task.worktree_path
        && Path::new(wt_path).exists()
    {
        let state = crate::worktree::capture_live_worktree_state(Path::new(wt_path)).ok();
        live_dirty = state.as_ref().is_some_and(|state| state.is_dirty());
        out.push_str(&worktree_state_section(wt_path, state.as_ref()));
    }

    if task
        .delivery_assessment()
        .is_some_and(|delivery| delivery.implies_no_changes())
        && !live_dirty
    {
        out.push_str("\nChanges:\n[no changes]\n");
    } else if let Some(ref wt_path) = task.worktree_path
        && Path::new(wt_path).exists()
    {
        out.push_str("\nChanges:\n");
        let stat = diff_stat(wt_path, task.start_sha.as_deref());
        if live_dirty && stat.contains("(no changes detected)") {
            out.push_str("  (no committed diff detected)\n");
        } else {
            out.push_str(&stat);
        }
    } else if task.worktree_branch.is_none()
        && matches!(task.status, TaskStatus::Done | TaskStatus::Merged)
    {
        // In-place task: show working tree diff stat from repo
        let repo = task.repo_path.as_deref().unwrap_or(".");
        if let Some(stat) = inplace_diff_stat(repo) {
            out.push_str("\nWorking tree changes (in-place edit):\n");
            out.push_str(&stat);
        }
    }

    if let Some(banner) = audit_result_missing_banner(&task) {
        out.push('\n');
        out.push_str(&banner);
    } else if !task_has_changes(&task) && task.status.is_terminal()
        && let Some(findings) = research_findings(store.as_ref(), &task)
    {
        out.push_str("\nFindings:\n");
        out.push_str(&findings);
        out.push('\n');
        aid_hint!(
            "[aid] Research task. Full output: aid show {} --output --full",
            task.id
        );
    }

    Ok(out)
}

fn terminal_missing_result_notice(task: &crate::types::Task) -> Option<String> {
    if !matches!(task.status, TaskStatus::Done | TaskStatus::Failed) {
        return None;
    }
    let result_path = crate::paths::task_dir(task.id.as_str()).join("result.md");
    if result_path.exists() {
        return None;
    }
    if task.status == TaskStatus::Done {
        return Some("Status: DONE (no result file - see --output / output.md)\n".to_string());
    }
    Some("Status: FAILED\n".to_string())
}

pub fn summary_text(store: &Arc<Store>, task_id: &str) -> Result<String> {
    let task = load_task(store, task_id)?;
    let mut out = String::new();
    out.push_str(&format!("=== Review: {} ===\n", task.id));
    out.push_str(&format!(
        "Agent: {}  Status: {}  Prompt: {}\n",
        task.agent_display_name(),
        task.status.label(),
        task.prompt,
    ));
    if let Some(verdict) = task.audit_verdict.as_deref() {
        out.push_str("Audit: ");
        out.push_str(verdict);
        if let Some(report_path) = task.audit_report_path.as_deref() {
            out.push_str(&format!(" (report: {report_path})"));
        }
        out.push('\n');
    }

    let mut live_dirty = false;
    if let Some(ref wt_path) = task.worktree_path
        && Path::new(wt_path).exists()
    {
        let state = crate::worktree::capture_live_worktree_state(Path::new(wt_path)).ok();
        live_dirty = state.as_ref().is_some_and(|state| state.is_dirty());
        out.push_str(&worktree_state_section(wt_path, state.as_ref()));
    }

    if task
        .delivery_assessment()
        .is_some_and(|delivery| delivery.implies_no_changes())
        && !live_dirty
    {
        out.push_str("\n--- Diff Stat ---\n  (no changes detected)\n");
    } else if let Some(ref wt_path) = task.worktree_path
        && Path::new(wt_path).exists()
    {
        out.push_str("\n--- Diff Stat ---\n");
        let stat = diff_stat(wt_path, task.start_sha.as_deref());
        if live_dirty && stat.contains("(no changes detected)") {
            out.push_str("  (no committed diff detected)\n");
        } else {
            out.push_str(&stat);
        }
    } else if task.worktree_branch.is_none()
        && matches!(task.status, TaskStatus::Done | TaskStatus::Merged)
    {
        let repo = task.repo_path.as_deref().unwrap_or(".");
        out.push_str("\n--- Diff Stat ---\n");
        if let Some(stat) = inplace_diff_stat(repo) {
            out.push_str(&stat);
        } else {
            out.push_str("  (no changes detected)\n");
        }
    }

    if !out.contains("--- Diff Stat ---") || out.contains("(no changes detected)") {
        if let Some(conclusion) = completion_conclusion(store.as_ref(), task.id.as_str()) {
            out.push_str("\nConclusion: ");
            out.push_str(&conclusion);
            out.push('\n');
        }
    }

    Ok(out)
}

pub fn context_text(store: &Arc<Store>, task_id: &str) -> Result<String> {
    let task = load_task(store, task_id)?;
    let mut out = String::new();
    out.push_str("=== Original Prompt ===\n");
    out.push_str(&task.prompt);
    out.push('\n');

    if let Some(resolved_prompt) = task.resolved_prompt.as_deref() {
        out.push_str("\n=== Resolved Prompt ===\n");
        out.push_str(resolved_prompt);
        out.push('\n');
        return Ok(out);
    }

    let (skill_content, resolved_prompt) = reconstruct_context(store, &task)?;
    out.push_str("\n(reconstructed — context files may have changed since dispatch)\n");
    out.push_str("\n=== Injected Skills ===\n");
    if skill_content.trim().is_empty() {
        out.push_str("(none)\n");
    } else {
        out.push_str(&skill_content);
        out.push('\n');
    }
    out.push_str("\n=== Resolved Prompt ===\n");
    out.push_str(&resolved_prompt);
    out.push('\n');
    Ok(out)
}

#[cfg(test)]
#[path = "show_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "show_mode_tests.rs"]
mod show_mode_tests;

#[cfg(test)]
#[path = "show_checklist_tests.rs"]
mod show_checklist_tests;