ai-dispatch 10.26.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
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
// Tests for the `run` command module after splitting from run.rs.
// Covers dispatch validation, quota detection, cascade behavior, and dry-run flow.
// Depends on the parent run module, store, paths, tokio, and tempfile.
use super::*;
use crate::store::Store;
use crate::types::{AgentKind, Task, TaskStatus, VerifyStatus};
use std::process::Command;
use std::sync::Arc;
use tempfile::TempDir;

fn git(dir: &std::path::Path, args: &[&str]) {
    let output = Command::new("git")
        .current_dir(dir)
        .args(args)
        .output()
        .expect("git command failed");
    assert!(output.status.success(), "git {:?} failed: {}", args, String::from_utf8_lossy(&output.stderr));
}

#[test]
fn empty_diff_detection_respects_worktree_state() {
    let dir = TempDir::new().unwrap();
    git(dir.path(), &["init"]);
    git(dir.path(), &["config", "user.email", "aid@example.com"]);
    git(dir.path(), &["config", "user.name", "Aid Tester"]);
    let file = dir.path().join("file.txt");
    std::fs::write(&file, "initial").unwrap();
    git(dir.path(), &["add", "file.txt"]);
    git(dir.path(), &["commit", "-m", "initial"]);
    assert_eq!(worktree_is_empty_diff(dir.path()), Some(true));
    std::fs::write(&file, "updated").unwrap();
    assert_eq!(worktree_is_empty_diff(dir.path()), Some(false));
}

#[test]
fn take_next_cascade_agent_consumes_first_entry() {
    let args = RunArgs {
        agent_name: "primary".to_string(),
        cascade: vec!["codex".to_string(), "cursor".to_string()],
        ..Default::default()
    };
    let result = take_next_cascade_agent(&args);
    assert_eq!(result, Some(("codex".to_string(), vec!["cursor".to_string()])));
}

#[test]
fn take_next_cascade_agent_returns_none_when_empty() {
    let args = RunArgs { cascade: vec![], ..Default::default() };
    assert!(take_next_cascade_agent(&args).is_none());
}

#[test]
fn read_quota_error_message_uses_stderr() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();
    std::fs::write(
        paths::stderr_path("t-quota-stderr"),
        "You have hit your usage limit.",
    )
    .unwrap();
    let message = read_quota_error_message(&TaskId("t-quota-stderr".to_string()), &AgentKind::Codex);
    assert_eq!(message.as_deref(), Some("You have hit your usage limit."));
}

#[test]
fn read_quota_error_message_falls_back_to_log() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();
    std::fs::write(
        paths::log_path("t-quota-log"),
        "{\"error\":\"You have hit your usage limit.\"}\n",
    )
    .unwrap();
    let message = read_quota_error_message(&TaskId("t-quota-log".to_string()), &AgentKind::Codex);
    // The provider's sentence, lifted out of the envelope it arrived in — not
    // the raw JSON, which is what the marker used to end up holding.
    assert_eq!(message.as_deref(), Some("You have hit your usage limit."));
}

#[test]
fn read_quota_error_message_extracts_rate_limit_line_only() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();
    std::fs::write(
        paths::stderr_path("t-quota-mixed"),
        "tokens: 8714294 in + 27373 out = 8741667 (8442752 cached)\nYou have hit your usage limit.\nsome other line\n",
    )
    .unwrap();
    let message = read_quota_error_message(&TaskId("t-quota-mixed".to_string()), &AgentKind::Codex);
    assert_eq!(message.as_deref(), Some("You have hit your usage limit."));
}

#[test]
fn read_quota_error_message_detects_402_payment_errors() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();
    std::fs::write(
        paths::log_path("t-quota-402"),
        "{\"type\":\"error\",\"source\":\"agent_loop\",\"message\":\"402 payment required: reload your tokens\"}\n",
    )
    .unwrap();
    let message = read_quota_error_message(&TaskId("t-quota-402".to_string()), &AgentKind::Codex);
    assert_eq!(message.as_deref(), Some("402 payment required: reload your tokens"));
}

#[test]
fn read_quota_error_message_ignores_agent_grep_in_log() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();
    crate::rate_limit::clear_rate_limit(&AgentKind::Cursor, None);
    let grep_line = "completed: grep clear_rate_limit_if_stale|marker_path";
    std::fs::write(
        paths::log_path("t-quota-grep-log"),
        format!("{grep_line}\n"),
    )
    .unwrap();
    let task_id = TaskId("t-quota-grep-log".to_string());
    let message = read_quota_error_message(&task_id, &AgentKind::Cursor);
    assert_eq!(message, None);
    if let Some(line) = message.as_deref() {
        crate::rate_limit::mark_rate_limited(&AgentKind::Cursor, None, line);
    }
    assert!(!crate::rate_limit::is_rate_limited(&AgentKind::Cursor, None));
}

#[test]
fn rescue_quota_failed_task_refuses_empty_worktree_rescue() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();

    let wt_dir = dir.path().join("wt");
    std::fs::create_dir_all(&wt_dir).unwrap();
    git(&wt_dir, &["init"]);
    git(&wt_dir, &["config", "user.email", "aid@example.com"]);
    git(&wt_dir, &["config", "user.name", "Aid Tester"]);
    std::fs::write(wt_dir.join("file.txt"), "initial").unwrap();
    git(&wt_dir, &["add", "file.txt"]);
    git(&wt_dir, &["commit", "-m", "initial"]);

    std::fs::write(
        paths::stderr_path("t-empty-wt"),
        "Error: You have hit your usage limit.",
    )
    .unwrap();

    let store = Store::open_memory().unwrap();
    let mut task = make_failed_task("t-empty-wt");
    task.worktree_path = Some(wt_dir.to_str().unwrap().to_string());
    task.verify_status = VerifyStatus::Passed;
    store.insert_task(&task).unwrap();

    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );

    let task = store.get_task("t-empty-wt").unwrap().unwrap();
    assert_eq!(task.status, TaskStatus::Failed);
}

#[test]
fn rescue_quota_failed_task_rescues_worktree_with_modified_code() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();

    let wt_dir = dir.path().join("wt");
    std::fs::create_dir_all(&wt_dir).unwrap();
    git(&wt_dir, &["init"]);
    git(&wt_dir, &["config", "user.email", "aid@example.com"]);
    git(&wt_dir, &["config", "user.name", "Aid Tester"]);
    std::fs::write(wt_dir.join("file.txt"), "initial").unwrap();
    git(&wt_dir, &["add", "file.txt"]);
    git(&wt_dir, &["commit", "-m", "initial"]);

    std::fs::write(
        paths::stderr_path("t-work-wt"),
        "Error: You have hit your usage limit.",
    )
    .unwrap();

    let store = Store::open_memory().unwrap();
    let mut task = make_failed_task("t-work-wt");
    task.worktree_path = Some(wt_dir.to_str().unwrap().to_string());
    task.verify_status = VerifyStatus::Passed;
    store.insert_task(&task).unwrap();

    // Clean worktree: guard must refuse rescue so task stays Failed.
    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );
    let checked_task = store.get_task("t-work-wt").unwrap().unwrap();
    assert_eq!(checked_task.status, TaskStatus::Failed);

    // Modify file: guard allows rescue to Done.
    std::fs::write(wt_dir.join("file.txt"), "modified").unwrap();
    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );

    let task = store.get_task("t-work-wt").unwrap().unwrap();
    assert_eq!(task.status, TaskStatus::Done);
}

#[test]
fn rescue_quota_failed_task_rescues_untracked_source_files() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();

    let wt_dir = dir.path().join("wt");
    std::fs::create_dir_all(&wt_dir).unwrap();
    git(&wt_dir, &["init"]);
    git(&wt_dir, &["config", "user.email", "aid@example.com"]);
    git(&wt_dir, &["config", "user.name", "Aid Tester"]);
    std::fs::write(wt_dir.join("file.txt"), "initial").unwrap();
    git(&wt_dir, &["add", "file.txt"]);
    git(&wt_dir, &["commit", "-m", "initial"]);

    std::fs::write(
        paths::stderr_path("t-untracked-wt"),
        "Error: You have hit your usage limit.",
    )
    .unwrap();

    let store = Store::open_memory().unwrap();
    let mut task = make_failed_task("t-untracked-wt");
    task.worktree_path = Some(wt_dir.to_str().unwrap().to_string());
    task.verify_status = VerifyStatus::Passed;
    store.insert_task(&task).unwrap();

    // Nothing written yet, so the guard must refuse. Without this half the test
    // passes even when `produced_work` is forced to return true — a cross-audit
    // caught it doing exactly that, and a mutation run confirmed it.
    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );
    let checked = store.get_task("t-untracked-wt").unwrap().unwrap();
    assert_eq!(checked.status, TaskStatus::Failed);

    // The agent's only output is an untracked file. `git diff` cannot see it,
    // which is how the first version of this guard threw such work away.
    std::fs::write(wt_dir.join("new_file.txt"), "untracked work").unwrap();

    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );

    let task = store.get_task("t-untracked-wt").unwrap().unwrap();
    assert_eq!(task.status, TaskStatus::Done);
}

#[test]
fn rescue_quota_failed_task_rescues_committed_work_non_standard_branch() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();

    let wt_dir = dir.path().join("wt");
    std::fs::create_dir_all(&wt_dir).unwrap();
    git(&wt_dir, &["init", "-b", "feature-custom"]);
    git(&wt_dir, &["config", "user.email", "aid@example.com"]);
    git(&wt_dir, &["config", "user.name", "Aid Tester"]);
    std::fs::write(wt_dir.join("file.txt"), "initial").unwrap();
    git(&wt_dir, &["add", "file.txt"]);
    git(&wt_dir, &["commit", "-m", "initial"]);

    let start_sha = crate::commit::head_sha(wt_dir.to_str().unwrap()).unwrap();

    std::fs::write(
        paths::stderr_path("t-custom-branch"),
        "Error: You have hit your usage limit.",
    )
    .unwrap();

    let store = Store::open_memory().unwrap();
    let mut task = make_failed_task("t-custom-branch");
    task.worktree_path = Some(wt_dir.to_str().unwrap().to_string());
    task.start_sha = Some(start_sha);
    task.verify_status = VerifyStatus::Passed;
    store.insert_task(&task).unwrap();

    // Untouched: guard refuses rescue even on non-standard branch with base_branch=None.
    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );
    let checked = store.get_task("t-custom-branch").unwrap().unwrap();
    assert_eq!(checked.status, TaskStatus::Failed);

    // Agent commits work on feature-custom branch.
    std::fs::write(wt_dir.join("file.txt"), "agent commit").unwrap();
    git(&wt_dir, &["add", "file.txt"]);
    git(&wt_dir, &["commit", "-m", "agent commit"]);

    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );
    let rescued = store.get_task("t-custom-branch").unwrap().unwrap();
    assert_eq!(rescued.status, TaskStatus::Done);
}

#[test]
fn rescue_quota_failed_task_marks_passed_verify_as_done() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();
    std::fs::write(
        paths::stderr_path("t-rescue-pass"),
        "Error: You have hit your usage limit.",
    )
    .unwrap();
    let store = Store::open_memory().unwrap();
    let mut task = make_failed_task("t-rescue-pass");
    task.verify_status = VerifyStatus::Passed;
    store.insert_task(&task).unwrap();

    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );
    let task = store.get_task("t-rescue-pass").unwrap().unwrap();
    assert_eq!(task.status, TaskStatus::Done);
}

#[test]
fn rescue_quota_failed_task_keeps_failed_verify_failed() {
    let dir = TempDir::new().unwrap();
    let _guard = paths::AidHomeGuard::set(dir.path());
    std::fs::create_dir_all(paths::logs_dir()).unwrap();
    std::fs::write(
        paths::stderr_path("t-rescue-fail"),
        "Error: You have hit your usage limit.",
    )
    .unwrap();
    let store = Store::open_memory().unwrap();
    let task = make_failed_task("t-rescue-fail");
    store.insert_task(&task).unwrap();
    rescue_quota_failed_task(
        &store,
        &task.id,
        read_quota_error_message(&task.id, &task.agent).as_deref(),
    );
    let task = store.get_task("t-rescue-fail").unwrap().unwrap();
    assert_eq!(task.status, TaskStatus::Failed);
}

#[test]
fn validate_dispatch_warns_short_prompt() {
    assert_eq!(validate_dispatch(&RunArgs { prompt: "tiny".to_string(), ..Default::default() }, &AgentKind::Gemini), vec!["Prompt is very short, agent may not have enough context".to_string()]);
}

#[test]
fn validate_dispatch_warns_code_agent_without_dir() {
    assert_eq!(validate_dispatch(&RunArgs { prompt: "Implement the dispatcher".to_string(), ..Default::default() }, &AgentKind::Codex), vec!["Code agent without --dir may not be able to write files".to_string()]);
}

#[test]
fn validate_dispatch_warns_copilot_without_dir() {
    assert_eq!(validate_dispatch(&RunArgs { prompt: "Implement the dispatcher".to_string(), ..Default::default() }, &AgentKind::Copilot), vec!["Code agent without --dir may not be able to write files".to_string()]);
}

#[test]
fn validate_dispatch_stays_silent_when_worktree_supplies_the_dir() {
    let args = RunArgs {
        prompt: "Implement the dispatcher".to_string(),
        worktree: Some("fix/some-branch".to_string()),
        ..Default::default()
    };
    assert!(validate_dispatch(&args, &AgentKind::Codex).is_empty());
    assert!(validate_dispatch(&args, &AgentKind::Cursor).is_empty());
}

#[test]
fn resolve_prompt_input_reads_prompt_file() {
    let dir = TempDir::new().unwrap();
    let prompt_file = dir.path().join("prompt.md");
    std::fs::write(&prompt_file, "Prompt from file").unwrap();

    let prompt = resolve_prompt_input("", Some(prompt_file.to_str().unwrap())).unwrap();

    assert_eq!(prompt, "Prompt from file");
}

#[test]
fn resolve_prompt_input_rejects_prompt_and_prompt_file() {
    let err = resolve_prompt_input("inline prompt", Some("/tmp/prompt.md"))
        .unwrap_err()
        .to_string();

    assert_eq!(err, "Cannot use both --prompt and --prompt-file");
}

#[test]
fn resolve_prompt_input_requires_prompt_source() {
    let err = resolve_prompt_input("", None).unwrap_err().to_string();

    assert_eq!(err, "Either prompt or --prompt-file is required");
}

#[test]
fn sandboxed_agents_identified() {
    assert!(AgentKind::OpenCode.sandboxed_fs());
    assert!(!AgentKind::Codex.sandboxed_fs());
    assert!(!AgentKind::Gemini.sandboxed_fs());
}

#[test]
fn build_prompt_bundle_uses_relative_workspace_for_sandboxed_agents() {
    let temp = TempDir::new().unwrap();
    let _aid_home = paths::AidHomeGuard::set(temp.path());
    crate::paths::ensure_dirs().unwrap();
    let store = Store::open_memory().unwrap();
    let group = store.create_workgroup("batch", "desc", Some("seed"), None).unwrap();
    let workspace = crate::paths::workspace_dir(group.id.as_str()).unwrap();
    let bundle = run_prompt::build_prompt_bundle(
        &store,
        &RunArgs {
            agent_name: "opencode".to_string(),
            prompt: "Write the requested content".to_string(),
            group: Some(group.id.to_string()),
            ..Default::default()
        },
        &AgentKind::OpenCode,
        None,
        &[],
        "task-opencode",
    )
    .unwrap();

    assert!(bundle.effective_prompt.contains("[Shared Workspace] Path: .aid-workspace"));
    assert!(!bundle.effective_prompt.contains(&workspace.display().to_string()));
    let _ = std::fs::remove_dir_all(workspace);
}

#[test]
fn build_prompt_bundle_keeps_absolute_workspace_for_non_sandboxed_agents() {
    let temp = TempDir::new().unwrap();
    let _aid_home = paths::AidHomeGuard::set(temp.path());
    crate::paths::ensure_dirs().unwrap();
    let store = Store::open_memory().unwrap();
    let group = store.create_workgroup("batch", "desc", Some("seed"), None).unwrap();
    let workspace = crate::paths::workspace_dir(group.id.as_str()).unwrap();
    let bundle = run_prompt::build_prompt_bundle(
        &store,
        &RunArgs {
            agent_name: "codex".to_string(),
            prompt: "Write the requested content".to_string(),
            group: Some(group.id.to_string()),
            ..Default::default()
        },
        &AgentKind::Codex,
        None,
        &[],
        "task-codex",
    )
    .unwrap();

    assert!(bundle.effective_prompt.contains(&workspace.display().to_string()));
    assert!(!bundle.effective_prompt.contains("[Shared Workspace] Path: .aid-workspace"));
    let _ = std::fs::remove_dir_all(workspace);
}

#[test]
fn workspace_symlink_guard_creates_and_cleans_up_link() {
    let group_id = format!("wg-symlink-{:04x}", rand::random::<u16>());
    let workspace = crate::paths::workspace_dir(&group_id).unwrap();
    std::fs::create_dir_all(&workspace).unwrap();
    let work_dir = TempDir::new().unwrap();
    let link_path = work_dir.path().join(".aid-workspace");

    {
        let _guard = WorkspaceSymlinkGuard::create(
            AgentKind::OpenCode,
            Some(&group_id),
            work_dir.path().to_str(),
        )
        .unwrap();
        assert!(link_path.exists());
        assert_eq!(std::fs::read_link(&link_path).unwrap(), workspace);
    }

    assert!(!link_path.exists());
    let _ = std::fs::remove_dir_all(workspace);
}

#[test]
fn validate_dispatch_warns_long_prompt() {
    let prompt = "a".repeat(5001);
    assert_eq!(validate_dispatch(&RunArgs { prompt, ..Default::default() }, &AgentKind::Gemini), vec!["Very long prompt (5001 chars), consider using --context files instead".to_string()]);
}

#[test]
fn validate_dispatch_warns_research_worktree() {
    assert_eq!(validate_dispatch(&RunArgs { prompt: "valid prompt text".to_string(), worktree: Some("wt".to_string()), ..Default::default() }, &AgentKind::Gemini), vec!["Research agent with --worktree is unusual, did you mean a code agent?".to_string()]);
}
#[test]
fn resolve_id_conflict_none_for_missing_id() {
    let store = Store::open_memory().unwrap();
    assert!(matches!(resolve_id_conflict(&store, "new-task").unwrap(), IdConflict::None));
}

#[test]
fn resolve_id_conflict_replace_waiting() {
    let store = Store::open_memory().unwrap();
    let mut task = make_failed_task("my-task");
    task.status = TaskStatus::Waiting;
    store.insert_task(&task).unwrap();
    assert!(matches!(resolve_id_conflict(&store, "my-task").unwrap(), IdConflict::ReplaceWaiting));
}

#[test]
fn resolve_id_conflict_blocks_running() {
    let store = Store::open_memory().unwrap();
    let mut task = make_failed_task("my-task");
    task.status = TaskStatus::Running;
    store.insert_task(&task).unwrap();
    assert!(matches!(resolve_id_conflict(&store, "my-task").unwrap(), IdConflict::Running));
}

#[test]
fn resolve_id_conflict_auto_suffixes_terminal() {
    let store = Store::open_memory().unwrap();
    store.insert_task(&make_failed_task("my-task")).unwrap();
    match resolve_id_conflict(&store, "my-task").unwrap() {
        IdConflict::AutoSuffix(new_id) => assert_eq!(new_id, "my-task-2"),
        other => panic!("expected AutoSuffix, got {:?}", std::mem::discriminant(&other)),
    }
    // Insert my-task-2, should get my-task-3 next
    store.insert_task(&make_failed_task("my-task-2")).unwrap();
    match resolve_id_conflict(&store, "my-task").unwrap() {
        IdConflict::AutoSuffix(new_id) => assert_eq!(new_id, "my-task-3"),
        other => panic!("expected AutoSuffix, got {:?}", std::mem::discriminant(&other)),
    }
}

#[test]
fn validate_dispatch_skips_dir_warning_for_non_writing_tasks() {
    assert!(validate_dispatch(&RunArgs { prompt: "Research: compare the agent options".to_string(), ..Default::default() }, &AgentKind::Codex).is_empty());
    assert!(validate_dispatch(&RunArgs { prompt: "Implement the dispatcher".to_string(), read_only: true, ..Default::default() }, &AgentKind::Codex).is_empty());
}

#[test]
fn resolve_max_duration_mins_uses_timeout_when_minutes_missing() { assert_eq!(resolve_max_duration_mins(Some(300), None), Some(5)); assert_eq!(resolve_max_duration_mins(Some(301), None), Some(6)); }

#[test]
fn resolve_max_duration_mins_preserves_explicit_minutes() { assert_eq!(resolve_max_duration_mins(Some(300), Some(2)), Some(2)); }

#[test]
fn auto_save_creates_output_for_research_task() {
    let temp = TempDir::new().unwrap();
    let _aid_home = paths::AidHomeGuard::set(temp.path());
    let log_path = temp.path().join("research.jsonl");
    std::fs::write(&log_path, "{\"type\":\"message\",\"role\":\"assistant\",\"content\":\"saved output\"}\n").unwrap();
    let store = Store::open_memory().unwrap();
    let mut task = make_failed_task("t-research-save");
    task.status = TaskStatus::Done;
    task.exit_code = None;
    task.log_path = Some(log_path.display().to_string());
    store.insert_task(&task).unwrap();
    auto_save_task_output(&store, &task).unwrap();
    let output_path = crate::paths::task_dir(task.id.as_str()).join("output.md");
    assert_eq!(std::fs::read_to_string(&output_path).unwrap(), "saved output");
    assert_eq!(store.get_task(task.id.as_str()).unwrap().unwrap().output_path, Some(output_path.display().to_string()));
}

#[tokio::test]
async fn dry_run_returns_without_starting_task() {
    let temp = TempDir::new().unwrap();
    let _aid_home = paths::AidHomeGuard::set(temp.path());
    crate::paths::ensure_dirs().unwrap();
    let store = Arc::new(Store::open_memory().unwrap());
    let task_id = run(
        store.clone(),
        RunArgs {
            agent_name: "codex".to_string(),
            prompt: "Inspect the repository state".to_string(),
            dry_run: true,
            skills: vec![NO_SKILL_SENTINEL.to_string()],
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let task = store.get_task(task_id.as_str()).unwrap().unwrap();
    // Skipped, not Pending: a dry run never dispatches, and a row left pending
    // was reaped ten minutes later as a failure the agent never had.
    assert_eq!(task.status, TaskStatus::Skipped);
    assert!(task.resolved_prompt.is_some());
    assert!(task.prompt_tokens.is_some());
}

#[tokio::test]
async fn run_records_worktree_setup_failure_event() {
    let temp = TempDir::new().unwrap();
    let _aid_home = paths::AidHomeGuard::set(temp.path());
    crate::paths::ensure_dirs().unwrap();
    let store = Arc::new(Store::open_memory().unwrap());
    let task_id = TaskId("t-worktree-fail".to_string());

    let err = run(
        store.clone(),
        RunArgs {
            agent_name: "codex".to_string(),
            prompt: "Inspect the repository state".to_string(),
            dir: Some(temp.path().display().to_string()),
            worktree: Some("aid-worktree-fail".to_string()),
            dry_run: true,
            skills: vec![NO_SKILL_SENTINEL.to_string()],
            existing_task_id: Some(task_id.clone()),
            ..Default::default()
        },
    )
    .await
    .unwrap_err();

    assert!(err.to_string().contains("Not a git repository"));
    assert_eq!(
        store.get_task(task_id.as_str()).unwrap().unwrap().status,
        TaskStatus::Failed
    );
    let events = store.get_events(task_id.as_str()).unwrap();
    assert!(events.iter().any(|event| {
        event.detail.contains("Failed during worktree setup: Not a git repository")
    }));
}

#[tokio::test]
async fn rate_limited_agent_without_cascade_fails_early() {
    let temp = TempDir::new().unwrap();
    let _aid_home = paths::AidHomeGuard::set(temp.path());
    crate::paths::ensure_dirs().unwrap();
    // No installed peers → category-aware fallback correctly returns None.
    let _agents = crate::agent::DetectAgentsGuard::set(vec![AgentKind::MiMoCode]);
    let stated = crate::rate_limit::test_future_recovery_time();
    crate::rate_limit::mark_rate_limited(
        &AgentKind::MiMoCode,
        None,
        &format!("try again at {stated}."),
    );
    let err = run(Arc::new(Store::open_memory().unwrap()), RunArgs {
        agent_name: "mimocode".to_string(),
        prompt: "Inspect the repository state".to_string(),
        dry_run: true,
        skills: vec![NO_SKILL_SENTINEL.to_string()],
        ..Default::default()
    }).await.unwrap_err();
    assert!(err.to_string().contains(&format!("mimocode is held (until {stated})")));
}

#[tokio::test]
async fn rate_limited_agent_with_cascade_proceeds() {
    let temp = TempDir::new().unwrap();
    let _aid_home = paths::AidHomeGuard::set(temp.path());
    crate::paths::ensure_dirs().unwrap();
    let store = Arc::new(Store::open_memory().unwrap());
    crate::rate_limit::mark_rate_limited(
        &AgentKind::Kilo,
        None,
        &format!("try again at {}.", crate::rate_limit::test_future_recovery_time()),
    );
    let task_id = run(store.clone(), RunArgs {
        agent_name: "kilo".to_string(),
        prompt: "Inspect the repository state".to_string(),
        cascade: vec!["codex".to_string()],
        dry_run: true,
        skills: vec![NO_SKILL_SENTINEL.to_string()],
        ..Default::default()
    }).await.unwrap();
    let task = store.get_task(task_id.as_str()).unwrap().unwrap();
    // Skipped, not Pending: a dry run never dispatches, and a row left pending
    // was reaped ten minutes later as a failure the agent never had.
    assert_eq!(task.status, TaskStatus::Skipped);
}

fn make_failed_task(task_id: &str) -> Task {
    Task {
        id: TaskId(task_id.to_string()),
        agent: AgentKind::Codex,
        custom_agent_name: None,
        prompt: "prompt".to_string(),
        resolved_prompt: None,
        category: None,
        status: TaskStatus::Failed,
        parent_task_id: None,
        workgroup_id: None,
        caller_kind: None,
        caller_session_id: None,
        agent_session_id: None,
        repo_path: None, project_id: None,
        worktree_path: 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: Some(1),
        created_at: chrono::Local::now(),
        completed_at: None,
        verify: None,
        verify_status: VerifyStatus::Failed,
        pending_reason: None,
        read_only: false,
        budget: false,
        audit_verdict: None,
        audit_report_path: None,
        delivery_assessment: None,
    }
}

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

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