ai-dispatch 10.37.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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
// Unit tests for `cmd::show` — context, summary/audit, JSON. Loaded via `#[path]` from `show.rs`.
// Deps: `super::*`, `chrono`, `tempfile`.

use super::show_json::task_json;
use super::*;
use crate::cmd::summary::CompletionSummary;
use crate::types::{AgentKind, EventKind, Task, TaskEvent, TaskId, TaskStatus, VerifyStatus};
use chrono::Local;
use std::path::Path;
use std::process::Command;
use std::sync::Arc;

fn task_fixture(
    id: &str,
    prompt: &str,
    resolved_prompt: Option<&str>,
    repo_path: Option<String>,
) -> Task {
    Task {
        id: TaskId(id.to_string()),
        agent: AgentKind::Codex,
        custom_agent_name: None,
        prompt: prompt.to_string(),
        resolved_prompt: resolved_prompt.map(String::from),
        category: None,
        status: TaskStatus::Done,
        parent_task_id: None,
        workgroup_id: None,
        caller_kind: None,
        caller_session_id: None,
        agent_session_id: None,
        repo_path, project_id: None,
        worktree_path: None, effective_dir: None,
        worktree_branch: None,
        final_head_sha: None,
        final_branch: None,
        start_sha: None,
        log_path: None,
        output_path: None,
        tokens: None,
        prompt_tokens: None,
        duration_ms: None,
        requested_model: None, observed_model: None, attribution_source: None,
        cost_usd: None,
        exit_code: None,
        created_at: Local::now(),
        completed_at: None,
        verify: None,
        verify_status: VerifyStatus::Skipped,
        pending_reason: None,
        read_only: false,
        budget: false,
        audit_verdict: None,
        audit_report_path: None,
        delivery_assessment: None,
    }
}

fn research_task(task_id: &str, repo: &Path) -> Task {
    task_fixture(
        task_id,
        "research task",
        None,
        Some(repo.display().to_string()),
    )
}

#[test]
fn context_text_prefers_stored_resolved_prompt() {
    let store = Arc::new(Store::open_memory().unwrap());
    let task = task_fixture("t-context", "raw prompt", Some("resolved prompt"), None);
    store.insert_task(&task).unwrap();

    let text = context_text(&store, "t-context").unwrap();

    assert!(text.contains("=== Original Prompt ===\nraw prompt"));
    assert!(text.contains("=== Resolved Prompt ===\nresolved prompt"));
    assert!(!text.contains("(reconstructed"));
}

/// Reconstruction reports the skills the task was actually dispatched with,
/// read from its stored args. It used to re-derive them from the agent kind,
/// which reported `implementer` for a codex task even when the caller had
/// passed `--skill reviewer`, or none at all.
#[test]
fn context_text_reports_the_skills_the_task_was_dispatched_with() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let dir = crate::paths::aid_dir().join("skills");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("implementer.md"), "# Implementer").unwrap();

    let store = Arc::new(Store::open_memory().unwrap());
    let task = task_fixture("t-reconstruct", "raw prompt", None, None);
    store.insert_task(&task).unwrap();
    store
        .update_task_dispatch_args("t-reconstruct", r#"{"skills":["implementer"]}"#)
        .unwrap();

    let text = context_text(&store, "t-reconstruct").unwrap();

    assert!(text.contains("(reconstructed"));
    assert!(text.contains("=== Injected Skills ===\n# Implementer"));
    assert!(text.contains("=== Resolved Prompt ===\nraw prompt"));
    assert!(text.contains("[MILESTONE] <brief description>"));
}

/// A task dispatched with no skills reports none, rather than having one
/// invented for it from the agent kind.
#[test]
fn context_text_reports_no_skills_when_none_were_dispatched() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let dir = crate::paths::aid_dir().join("skills");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("implementer.md"), "# Implementer").unwrap();

    let store = Arc::new(Store::open_memory().unwrap());
    let task = task_fixture("t-noskill", "raw prompt", None, None);
    store.insert_task(&task).unwrap();

    let text = context_text(&store, "t-noskill").unwrap();

    assert!(!text.contains("# Implementer"), "no skill was dispatched, none may be reported");
}

#[test]
fn summary_text_shows_diff_stat_without_full_diff() {
    let temp = tempfile::tempdir().unwrap();
    let repo = temp.path();
    Command::new("git")
        .args(["init"])
        .current_dir(repo)
        .output()
        .unwrap();
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo)
        .output()
        .unwrap();
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo)
        .output()
        .unwrap();
    std::fs::write(repo.join("note.txt"), "before\n").unwrap();
    Command::new("git")
        .args(["add", "note.txt"])
        .current_dir(repo)
        .output()
        .unwrap();
    Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(repo)
        .output()
        .unwrap();
    std::fs::write(repo.join("note.txt"), "before\nafter\n").unwrap();

    let store = Arc::new(Store::open_memory().unwrap());
    let task = task_fixture(
        "t-summary",
        "summarize diff",
        None,
        Some(repo.display().to_string()),
    );
    store.insert_task(&task).unwrap();

    let text = summary_text(&store, "t-summary").unwrap();

    assert!(text.contains("--- Diff Stat ---"));
    assert!(text.contains("note.txt | 1 +"));
    assert!(!text.contains("--- Full Diff ---"));
    assert!(!text.contains("@@"));
}

#[test]
fn audit_text_shows_findings_for_research_task() {
    let temp = tempfile::tempdir().unwrap();
    init_git_repo(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let task = research_task("t-audit-findings", temp.path());
    store.insert_task(&task).unwrap();
    save_completion_summary(&store, task.id.as_str(), "Investigated the failure mode.");

    let text = audit_text(&store, task.id.as_str()).unwrap();

    assert!(text.contains("Findings:\nInvestigated the failure mode."));
}

#[test]
fn summary_text_shows_conclusion_for_research_task() {
    let temp = tempfile::tempdir().unwrap();
    init_git_repo(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let task = research_task("t-summary-conclusion", temp.path());
    store.insert_task(&task).unwrap();
    save_completion_summary(&store, task.id.as_str(), "Summarized the research outcome.");

    let text = summary_text(&store, task.id.as_str()).unwrap();

    assert!(text.contains("--- Diff Stat ---"));
    assert!(text.contains("(no changes detected)"));
    assert!(text.contains("Conclusion: Summarized the research outcome."));
}

#[test]
fn audit_text_shows_pending_reason() {
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = research_task("t-show-pending-reason", Path::new("."));
    task.status = TaskStatus::Failed;
    task.pending_reason = Some("agent_starting".to_string());
    store.insert_task(&task).unwrap();

    let text = audit_text(&store, task.id.as_str()).unwrap();

    assert!(text.contains("Pending reason: agent_starting"));
}

#[test]
fn audit_text_shows_done_status_when_result_file_is_missing() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let task = task_fixture("t-done-no-result", "investigate issue", None, None);
    store.insert_task(&task).unwrap();

    let text = audit_text(&store, task.id.as_str()).unwrap();

    assert!(text.contains("Status: DONE (no result file - see --output / output.md)"));
}

#[test]
fn audit_text_shows_inconclusive_verification_tag() {
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = task_fixture("t-show-timeout", "investigate issue", None, None);
    task.verify = Some("cargo test".to_string());
    task.verify_status = VerifyStatus::TimedOut;
    store.insert_task(&task).unwrap();

    let text = audit_text(&store, task.id.as_str()).unwrap();

    // audit_text prints the status twice — the detail header and the missing-result
    // notice. Pin the notice line, or the header alone satisfies the assertion.
    assert!(
        text.contains("Status: DONE [VTIMEOUT] (no result file"),
        "output: {text}"
    );
}

#[test]
fn task_hook_payload_adds_outcome_and_verification_status() {
    let mut task = task_fixture("t-hook-timeout", "hook task", None, None);
    task.verify = Some("cargo test".to_string());
    task.verify_status = VerifyStatus::TimedOut;

    let payload = task_hook_json(&task, "codex", Some("/repo"));

    assert_eq!(payload["status"], "done");
    assert_eq!(payload["outcome"], "unverified");
    assert_eq!(payload["verify_status"], "timed_out");
}

#[test]
fn audit_text_shows_failed_status_when_result_file_is_missing() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = task_fixture("t-failed-no-result", "investigate issue", None, None);
    task.status = TaskStatus::Failed;
    store.insert_task(&task).unwrap();

    let text = audit_text(&store, task.id.as_str()).unwrap();

    // The summary header also prints "Status: FAILED", so anchor on the notice's
    // own line or a broken notice still satisfies this.
    assert!(text.contains("Status: FAILED\n"), "output: {text}");
}

#[test]
fn audit_text_shows_full_failure_details() {
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = research_task("t-show-failure-details", Path::new("."));
    task.status = TaskStatus::Failed;
    store.insert_task(&task).unwrap();
    store
        .insert_event(&TaskEvent {
            task_id: task.id.clone(),
            timestamp: Local::now(),
            event_kind: EventKind::Error,
            detail: "Failed during execution: agent exited with code 1\nFailure context: working directory: /tmp/demo; agent binary: /bin/sh; worktree path: /Users/test/.aid/worktrees/demo/feat/demo; worktree created: true".to_string(),
            metadata: None,
        })
        .unwrap();

    let text = audit_text(&store, task.id.as_str()).unwrap();

    assert!(text.contains("Failure details:"));
    assert!(text.contains("Failed during execution: agent exited with code 1"));
    assert!(text.contains("Failure context: working directory: /tmp/demo; agent binary: /bin/sh; worktree path: /Users/test/.aid/worktrees/demo/feat/demo; worktree created: true"));
}

#[test]
fn task_json_includes_pending_reason() {
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = research_task("t-show-json", Path::new("."));
    let output_file = tempfile::NamedTempFile::new().unwrap();
    std::fs::write(output_file.path(), "full output\n").unwrap();
    task.pending_reason = Some("unknown".to_string());
    task.output_path = Some(output_file.path().display().to_string());
    store.insert_task(&task).unwrap();

    let payload: serde_json::Value =
        serde_json::from_str(&task_json(&store, task.id.as_str()).unwrap()).unwrap();

    assert_eq!(payload["pending_reason"], "unknown");
    assert_eq!(payload["output"], "full output\n");
}

#[test]
fn task_json_includes_delivery_assessment() {
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = research_task("t-show-delivery", Path::new("."));
    task.delivery_assessment = Some(crate::types::DeliveryAssessment::EmptyDiff);
    store.insert_task(&task).unwrap();

    let payload: serde_json::Value =
        serde_json::from_str(&task_json(&store, task.id.as_str()).unwrap()).unwrap();

    assert_eq!(payload["delivery_assessment"], "empty_diff");
}

#[test]
fn task_json_does_not_report_unobserved_as_success() {
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = research_task("t-show-unobs", Path::new("."));
    task.verify_status = VerifyStatus::Unobserved;
    store.insert_task(&task).unwrap();

    let payload: serde_json::Value =
        serde_json::from_str(&task_json(&store, task.id.as_str()).unwrap()).unwrap();

    assert_eq!(payload["status"], "done");
    assert_eq!(payload["verify_status"], "unobserved");
    assert_eq!(payload["outcome"], "unverified");
    assert_ne!(payload["outcome"], "delivered");
}

#[test]
fn result_text_reads_task_result_file() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let path = crate::paths::task_dir("t-result").join("result.md");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(&path, "structured result\n").unwrap();

    let text = result_text(&store, "t-result").unwrap();

    assert_eq!(text, "structured result\n");
}

#[test]
fn audit_text_with_missing_result_md_shows_banner() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = task_fixture(
        "t-audit-missing",
        "Cross-audit the parser changes and produce findings.",
        None,
        None,
    );
    task.status = TaskStatus::Done;
    task.read_only = true;
    store.insert_task(&task).unwrap();

    let text = audit_text(&store, "t-audit-missing").unwrap();

    assert!(text.contains("Structured audit result missing"));
    assert!(text.contains("aid retry t-audit-missing --agent codex"));
}

#[test]
fn result_text_for_audit_without_result_md_uses_banner() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = task_fixture(
        "t-audit-result-missing",
        "Review the implementation and list findings with severity.",
        None,
        None,
    );
    task.status = TaskStatus::Done;
    task.read_only = true;
    store.insert_task(&task).unwrap();

    let text = result_text(&store, "t-audit-result-missing").unwrap();

    assert!(text.contains("Structured audit result missing"));
}

/// A result.md salvaged from the log must not silence the banner: that file holds the
/// tool narration aid rescued, not the audit the caller asked for.
#[test]
fn result_text_for_audit_warns_when_result_md_is_a_salvaged_log() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let mut task = task_fixture(
        "t-audit-salvaged",
        "Review the implementation and list findings with severity.",
        None,
        None,
    );
    task.status = TaskStatus::Done;
    task.read_only = true;
    store.insert_task(&task).unwrap();
    store
        .update_delivery_assessment(
            "t-audit-salvaged",
            Some(crate::types::DeliveryAssessment::MissingFinalDelivery),
        )
        .unwrap();
    let result_path = crate::paths::task_dir("t-audit-salvaged").join("result.md");
    std::fs::create_dir_all(result_path.parent().unwrap()).unwrap();
    std::fs::write(&result_path, "I will run `git diff main..HEAD` to see the changes.\n").unwrap();

    let text = result_text(&store, "t-audit-salvaged").unwrap();

    assert!(text.contains("Structured audit result missing"));
}

#[test]
fn render_mode_text_reads_transcript() {
    let temp = tempfile::tempdir().unwrap();
    let _aid_home = crate::paths::AidHomeGuard::set(temp.path());
    let store = Arc::new(Store::open_memory().unwrap());
    let task = task_fixture("t-show-transcript", "raw prompt", None, None);
    store.insert_task(&task).unwrap();
    let transcript = crate::paths::transcript_path(task.id.as_str());
    std::fs::create_dir_all(transcript.parent().unwrap()).unwrap();
    std::fs::write(&transcript, "raw transcript\n").unwrap();

    let text = render_mode_text(&store, task.id.as_str(), ShowMode::Transcript).unwrap();

    assert_eq!(text, "raw transcript\n");
}

fn init_git_repo(repo: &Path) {
    Command::new("git")
        .args(["init"])
        .current_dir(repo)
        .output()
        .unwrap();
    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo)
        .output()
        .unwrap();
    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo)
        .output()
        .unwrap();
    std::fs::write(repo.join("note.txt"), "baseline\n").unwrap();
    Command::new("git")
        .args(["add", "note.txt"])
        .current_dir(repo)
        .output()
        .unwrap();
    Command::new("git")
        .args(["commit", "-m", "init"])
        .current_dir(repo)
        .output()
        .unwrap();
}

fn save_completion_summary(store: &Store, task_id: &str, conclusion: &str) {
    let summary = CompletionSummary {
        task_id: task_id.to_string(),
        agent: "codex".to_string(),
        status: "done".to_string(),
        files_changed: vec![],
        summary_text: "research task completed".to_string(),
        conclusion: conclusion.to_string(),
        duration_secs: None,
        token_count: None,
    };
    store
        .save_completion_summary(task_id, &serde_json::to_string(&summary).unwrap())
        .unwrap();
}