godmode-core 0.8.1

Core library for godmode: task graphs, session state, dispatch, and Claude Code plugin integrations.
Documentation
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
//! Compute independent task chains for parallel agent dispatch.
//!
//! Two chains are independent when no task in one chain appears in the `depends_on`
//! of any task in the other chain (transitively). Each chain is dispatched to one
//! `godmode-crate-agent`. Maximum 5 concurrent chains.

use std::collections::{HashMap, HashSet};
use std::future::Future;
use std::sync::Arc;

use tokio::sync::Semaphore;

use crate::model::{Status, Task, TaskGraph};
use crate::wave::{BlockOutcome, ConcurrencyTracker, SlotHealth, WaveConfig, on_blocked};

/// A task reference with id and title for orca-strait agent consumption.
#[derive(Debug, Clone, serde::Serialize)]
pub struct TaskRef {
    pub id: String,
    pub title: String,
}

/// A group of tasks that must execute sequentially, targeting one crate.
#[derive(Debug, serde::Serialize)]
pub struct Chain {
    /// Crate this chain targets (if all tasks share a crate name).
    pub crate_name: Option<String>,
    /// Tasks in execution order with id + title.
    pub tasks: Vec<TaskRef>,
}

/// Decompose the graph into independent chains of runnable + pending tasks.
///
/// Returns at most `max_concurrent` chains (default 5).
pub fn independent_chains(graph: &TaskGraph, max_concurrent: usize) -> Vec<Chain> {
    // Only consider pending/running tasks — done/blocked are settled.
    let active: Vec<&Task> = graph
        .tasks
        .iter()
        .filter(|t| matches!(t.status, Status::Pending | Status::Running))
        .collect();

    if active.is_empty() {
        return vec![];
    }

    // Build adjacency: id -> deps (within active set only).
    let active_ids: HashSet<&str> = active.iter().map(|t| t.id.as_str()).collect();
    let deps_map: HashMap<&str, Vec<&str>> = active
        .iter()
        .map(|t| {
            let deps: Vec<&str> = t
                .depends_on
                .iter()
                .filter(|d| active_ids.contains(d.as_str()))
                .map(|d| d.as_str())
                .collect();
            (t.id.as_str(), deps)
        })
        .collect();

    // Identify root tasks (no active dependencies).
    let roots: Vec<&str> = active
        .iter()
        .filter(|t| deps_map[t.id.as_str()].is_empty())
        .map(|t| t.id.as_str())
        .collect();

    // Build chains by following each root forward through its dependents.
    let mut chains: Vec<Chain> = Vec::new();
    let mut claimed: HashSet<&str> = HashSet::new();

    // Build reverse map: id -> tasks that depend on it.
    let mut rev: HashMap<&str, Vec<&str>> = HashMap::new();
    for (id, deps) in &deps_map {
        for dep in deps {
            rev.entry(dep).or_default().push(id);
        }
    }

    // O(n) index built once; used for O(1) lookups in chain construction below.
    let task_index: HashMap<&str, &Task> = graph.tasks.iter().map(|t| (t.id.as_str(), t)).collect();

    for root in roots {
        if claimed.contains(root) {
            continue;
        }
        let mut chain_ids = vec![root];
        claimed.insert(root);

        // Follow single-successor chains.
        loop {
            let last = *chain_ids.last().unwrap();
            let successors: Vec<&str> = rev
                .get(last)
                .map(|v| v.iter().copied().filter(|s| !claimed.contains(s)).collect())
                .unwrap_or_default();
            if successors.len() == 1 {
                let next = successors[0];
                chain_ids.push(next);
                claimed.insert(next);
            } else {
                break;
            }
        }

        let crate_name = infer_crate(&chain_ids, &task_index);
        let tasks = chain_ids
            .iter()
            .filter_map(|id| task_index.get(id))
            .map(|t| TaskRef {
                id: t.id.clone(),
                title: t.title.clone(),
            })
            .collect();
        chains.push(Chain { crate_name, tasks });

        if chains.len() >= max_concurrent {
            break;
        }
    }

    chains
}

/// Return the longest dependency chain among pending/running tasks (critical path).
/// Uses topological sort + DP on depth. Ties broken by insertion order.
/// Returns tasks in root → tail execution order.
pub fn critical_path(graph: &TaskGraph) -> Vec<TaskRef> {
    let active: Vec<&Task> = graph
        .tasks
        .iter()
        .filter(|t| matches!(t.status, Status::Pending | Status::Running))
        .collect();

    if active.is_empty() {
        return vec![];
    }

    let active_ids: HashSet<&str> = active.iter().map(|t| t.id.as_str()).collect();

    let mut in_degree: HashMap<&str, usize> = active.iter().map(|t| (t.id.as_str(), 0)).collect();
    let mut rev: HashMap<&str, Vec<&str>> = HashMap::new();

    for t in &active {
        for dep in t
            .depends_on
            .iter()
            .filter(|d| active_ids.contains(d.as_str()))
        {
            *in_degree.entry(t.id.as_str()).or_default() += 1;
            rev.entry(dep.as_str()).or_default().push(t.id.as_str());
        }
    }

    let mut depth: HashMap<&str, usize> = active.iter().map(|t| (t.id.as_str(), 1)).collect();
    let mut parent: HashMap<&str, Option<&str>> =
        active.iter().map(|t| (t.id.as_str(), None)).collect();

    let mut queue: std::collections::VecDeque<&str> = active
        .iter()
        .filter(|t| in_degree[t.id.as_str()] == 0)
        .map(|t| t.id.as_str())
        .collect();

    while let Some(id) = queue.pop_front() {
        let d = depth[id];
        if let Some(successors) = rev.get(id) {
            for &succ in successors {
                let new_d = d + 1;
                if new_d > depth[succ] {
                    depth.insert(succ, new_d);
                    parent.insert(succ, Some(id));
                }
                let deg = in_degree.get_mut(succ).unwrap();
                *deg -= 1;
                if *deg == 0 {
                    queue.push_back(succ);
                }
            }
        }
    }

    // Pick the first task (insertion order) with maximum depth for stable tie-breaking.
    let max_depth = active.iter().map(|t| depth[t.id.as_str()]).max().unwrap();
    let tail = active
        .iter()
        .find(|t| depth[t.id.as_str()] == max_depth)
        .map(|t| t.id.as_str())
        .unwrap();

    let mut path_ids: Vec<&str> = Vec::new();
    let mut cur = Some(tail);
    while let Some(id) = cur {
        path_ids.push(id);
        cur = parent[id];
    }
    path_ids.reverse();

    path_ids
        .iter()
        .filter_map(|id| graph.tasks.iter().find(|t| t.id == *id))
        .map(|t| TaskRef {
            id: t.id.clone(),
            title: t.title.clone(),
        })
        .collect()
}

// Gated dispatch — concurrency-limited chain execution simulation

/// Outcome for a single chain execution in `dispatch_with_config`.
#[derive(Debug, PartialEq, Eq)]
pub enum ChainOutcome {
    Completed,
    /// Slot unavailable — concurrency limit hit; chain was not executed.
    Skipped,
    /// Retries exhausted after transient blocks; chain did not complete.
    Exhausted,
}

/// Simulate dispatching `chains` through a `WaveConfig`-gated concurrency tracker.
///
/// `execute` is called with each chain; it returns `Ok(())` on success or
/// `Err(true)` for a transient block (retry-eligible) or `Err(false)` for permanent failure.
///
/// Returns the per-chain outcomes in chain order.
// qual:test_helper
pub fn dispatch_with_config<F>(
    chains: &[Chain],
    config: &WaveConfig,
    mut execute: F,
) -> Vec<ChainOutcome>
where
    F: FnMut(&Chain) -> Result<(), bool>,
{
    let mut tracker = ConcurrencyTracker::new(config.max_concurrency);
    let mut outcomes = Vec::with_capacity(chains.len());

    for chain in chains {
        // Gate: block until a slot is available (synchronous simulation).
        // For true parallel execution, use `async_dispatch_with_config` which uses
        // tokio::spawn + Semaphore. This sync version is kept for backward compatibility.
        if !tracker.try_acquire() {
            // In a real async runtime we'd await; here we record Skipped for the chain.
            outcomes.push(ChainOutcome::Skipped);
            continue;
        }

        let mut health = SlotHealth::default();
        let mut result = execute(chain);

        // Retry loop for transient blocks.
        while let Err(true) = result {
            match on_blocked(&mut health, config) {
                BlockOutcome::Retry { attempt } => {
                    if config.retry_backoff_ms > 0 {
                        let delay = config.retry_backoff_ms * 2u64.pow(attempt as u32 - 1);
                        std::thread::sleep(std::time::Duration::from_millis(delay));
                    }
                    result = execute(chain);
                }
                BlockOutcome::Exhausted => {
                    result = Err(false);
                    break;
                }
            }
        }

        tracker.release();
        outcomes.push(if result.is_ok() {
            ChainOutcome::Completed
        } else {
            ChainOutcome::Exhausted
        });
    }

    outcomes
}

/// Async dispatch: run chains concurrently up to `config.max_concurrency` using
/// a tokio semaphore. Each chain is spawned as a task; the `execute` future factory
/// is called per-chain. Retries use `tokio::time::sleep` instead of `thread::sleep`.
///
/// Returns per-chain outcomes in the same order as input chains.
// qual:test_helper
pub async fn async_dispatch_with_config<F, Fut>(
    chains: &[Chain],
    config: &WaveConfig,
    execute: F,
) -> Vec<ChainOutcome>
where
    F: Fn(Vec<TaskRef>) -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<(), bool>> + Send + 'static,
{
    if chains.is_empty() {
        return vec![];
    }

    let semaphore = Arc::new(Semaphore::new(config.max_concurrency));
    let max_retries = config.max_retries;
    let backoff_ms = config.retry_backoff_ms;
    let execute = Arc::new(execute);

    let mut handles = Vec::with_capacity(chains.len());

    for chain in chains {
        let sem = semaphore.clone();
        let tasks = chain.tasks.clone();
        let exec = execute.clone();

        let handle = tokio::spawn(async move {
            // Acquire semaphore permit.
            let permit = match sem.acquire().await {
                Ok(p) => p,
                Err(_) => return ChainOutcome::Skipped,
            };

            let mut health = SlotHealth::default();
            let mut result = exec(tasks.clone()).await;

            // Retry loop for transient blocks.
            let wave_cfg = WaveConfig {
                max_concurrency: 0,
                max_retries,
                retry_backoff_ms: backoff_ms,
                ..Default::default()
            };

            while let Err(true) = result {
                match on_blocked(&mut health, &wave_cfg) {
                    BlockOutcome::Retry { attempt } => {
                        if backoff_ms > 0 {
                            let delay = backoff_ms * 2u64.pow(attempt as u32 - 1);
                            tokio::time::sleep(std::time::Duration::from_millis(delay)).await;
                        }
                        result = exec(tasks.clone()).await;
                    }
                    BlockOutcome::Exhausted => {
                        result = Err(false);
                        break;
                    }
                }
            }

            drop(permit);
            if result.is_ok() {
                ChainOutcome::Completed
            } else {
                ChainOutcome::Exhausted
            }
        });

        handles.push(handle);
    }

    let mut outcomes = Vec::with_capacity(handles.len());
    for handle in handles {
        outcomes.push(handle.await.unwrap_or(ChainOutcome::Exhausted));
    }
    outcomes
}

/// Check if any two chains target the same crate, which would cause merge
/// conflicts when dispatched in parallel. Returns pairs of conflicting chain
/// indices with the shared crate name.
// qual:test_helper
pub fn file_overlap_warnings(chains: &[Chain]) -> Vec<(usize, usize, String)> {
    let mut warnings = Vec::new();
    for (i, a) in chains.iter().enumerate() {
        for (j, b) in chains.iter().enumerate().skip(i + 1) {
            if let (Some(ca), Some(cb)) = (&a.crate_name, &b.crate_name)
                && ca == cb
            {
                warnings.push((i, j, ca.clone()));
            }
        }
    }
    warnings
}

fn infer_crate(ids: &[&str], task_index: &HashMap<&str, &Task>) -> Option<String> {
    let crates: HashSet<Option<&str>> = ids
        .iter()
        .filter_map(|id| task_index.get(id))
        .map(|t| t.crate_name.as_deref())
        .collect();
    // If all tasks share exactly one crate name, return it.
    if crates.len() == 1 {
        crates.into_iter().next().flatten().map(str::to_string)
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::Task;
    use crate::wave::WaveConfig;
    use std::sync::{Arc, Mutex};

    fn make_graph(specs: &[(&str, &str, &[&str], Option<&str>)]) -> TaskGraph {
        let mut g = TaskGraph::default();
        for (id, title, deps, krate) in specs {
            let mut t = Task::new(*id, *title);
            t.depends_on = deps.iter().map(|s| s.to_string()).collect();
            t.crate_name = krate.map(str::to_string);
            g.tasks.push(t);
        }
        g
    }

    #[test]
    fn single_chain() {
        let g = make_graph(&[
            ("t1", "A", &[], Some("foo")),
            ("t2", "B", &["t1"], Some("foo")),
        ]);
        let chains = independent_chains(&g, 5);
        assert_eq!(chains.len(), 1);
        let ids: Vec<&str> = chains[0].tasks.iter().map(|t| t.id.as_str()).collect();
        assert_eq!(ids, vec!["t1", "t2"]);
        assert_eq!(chains[0].crate_name.as_deref(), Some("foo"));
    }

    #[test]
    fn two_independent_chains() {
        let g = make_graph(&[
            ("a1", "A1", &[], Some("auth")),
            ("a2", "A2", &["a1"], Some("auth")),
            ("b1", "B1", &[], Some("cache")),
            ("b2", "B2", &["b1"], Some("cache")),
        ]);
        let chains = independent_chains(&g, 5);
        assert_eq!(chains.len(), 2);
    }

    #[test]
    fn respects_max_concurrent() {
        let g = make_graph(&[
            ("t1", "A", &[], None),
            ("t2", "B", &[], None),
            ("t3", "C", &[], None),
            ("t4", "D", &[], None),
            ("t5", "E", &[], None),
            ("t6", "F", &[], None),
        ]);
        let chains = independent_chains(&g, 5);
        assert!(chains.len() <= 5);
    }

    #[test]
    fn empty_graph_returns_no_chains() {
        let g = TaskGraph::default();
        let chains = independent_chains(&g, 5);
        assert!(chains.is_empty());
    }

    #[test]
    fn critical_path_linear_chain() {
        let g = make_graph(&[
            ("t1", "A", &[], None),
            ("t2", "B", &["t1"], None),
            ("t3", "C", &["t2"], None),
        ]);
        let path = critical_path(&g);
        let ids: Vec<&str> = path.iter().map(|t| t.id.as_str()).collect();
        assert_eq!(ids, vec!["t1", "t2", "t3"]);
    }

    #[test]
    fn critical_path_diamond_picks_longer_side() {
        let g = make_graph(&[
            ("t1", "A", &[], None),
            ("t2", "B", &["t1"], None),
            ("t3", "C", &["t1"], None),
            ("t4", "D", &["t2", "t3"], None),
        ]);
        let path = critical_path(&g);
        assert_eq!(path.len(), 3);
        assert_eq!(path[0].id, "t1");
        assert_eq!(path.last().unwrap().id, "t4");
    }

    #[test]
    fn critical_path_parallel_equal_length() {
        let g = make_graph(&[
            ("a1", "A1", &[], None),
            ("a2", "A2", &["a1"], None),
            ("b1", "B1", &[], None),
            ("b2", "B2", &["b1"], None),
        ]);
        let path = critical_path(&g);
        assert_eq!(path.len(), 2);
        assert_eq!(path[0].id, "a1");
    }

    #[test]
    fn critical_path_empty_graph() {
        let g = TaskGraph::default();
        assert!(critical_path(&g).is_empty());
    }

    // --- dispatch_with_config tests ---

    fn make_chains(n: usize) -> Vec<Chain> {
        (0..n)
            .map(|i| Chain {
                crate_name: None,
                tasks: vec![TaskRef {
                    id: format!("t{i}"),
                    title: format!("Task {i}"),
                }],
            })
            .collect()
    }

    #[test]
    fn dispatch_max_concurrency_2_runs_sequentially() {
        // With max_concurrency=2 and 4 chains, each chain runs but slots are gated.
        // The concurrency tracker is synchronous here so all 4 run (released after each).
        let cfg = WaveConfig {
            max_concurrency: 2,
            max_retries: 0,
            ..Default::default()
        };
        let chains = make_chains(4);
        // Track peak concurrency via a shared counter.
        let peak = Arc::new(Mutex::new(0usize));
        let current = Arc::new(Mutex::new(0usize));
        let peak_c = peak.clone();
        let current_c = current.clone();

        let outcomes = dispatch_with_config(&chains, &cfg, move |_chain| {
            let mut c = current_c.lock().unwrap();
            *c += 1;
            let mut p = peak_c.lock().unwrap();
            if *c > *p {
                *p = *c;
            }
            // simulate completion — release happens in dispatch_with_config
            *c -= 1;
            Ok(())
        });

        // All 4 chains should complete (synchronous, slots released between each).
        assert_eq!(
            outcomes
                .iter()
                .filter(|o| **o == ChainOutcome::Completed)
                .count(),
            4
        );
        // Peak concurrency never exceeded 2 — but since synchronous, each is 1.
        assert!(*peak.lock().unwrap() <= 2);
    }

    #[test]
    fn dispatch_transient_block_recovered_with_retry() {
        // Fake agent: fails with transient block on first call, succeeds on retry.
        let cfg = WaveConfig {
            max_concurrency: 5,
            max_retries: 3,
            retry_backoff_ms: 0,
            ..Default::default()
        };
        let chains = make_chains(1);
        let call_count = Arc::new(Mutex::new(0usize));
        let call_count_c = call_count.clone();

        let outcomes = dispatch_with_config(&chains, &cfg, move |_chain| {
            let mut c = call_count_c.lock().unwrap();
            *c += 1;
            if *c == 1 {
                Err(true) // transient block
            } else {
                Ok(()) // success on retry
            }
        });

        assert_eq!(outcomes[0], ChainOutcome::Completed);
        assert_eq!(*call_count.lock().unwrap(), 2, "should have retried once");
    }

    #[test]
    fn dispatch_backoff_delays_retry() {
        let cfg = WaveConfig {
            max_concurrency: 5,
            max_retries: 1,
            retry_backoff_ms: 50,
            ..Default::default()
        };
        let chains = make_chains(1);
        let call_count = Arc::new(Mutex::new(0usize));
        let cc = call_count.clone();
        let start = std::time::Instant::now();
        let outcomes = dispatch_with_config(&chains, &cfg, move |_| {
            let mut c = cc.lock().unwrap();
            *c += 1;
            if *c == 1 { Err(true) } else { Ok(()) }
        });
        let elapsed = start.elapsed();
        assert_eq!(outcomes[0], ChainOutcome::Completed);
        assert!(
            elapsed.as_millis() >= 50,
            "expected backoff delay, got {elapsed:?}"
        );
    }

    #[test]
    fn dispatch_slot_unavailable_yields_skipped() {
        // max_concurrency=0 so every chain is skipped immediately
        let cfg = WaveConfig {
            max_concurrency: 0,
            max_retries: 0,
            retry_backoff_ms: 0,
            ..Default::default()
        };
        let chains = make_chains(3);
        let outcomes = dispatch_with_config(&chains, &cfg, |_| Ok(()));
        assert!(outcomes.iter().all(|o| *o == ChainOutcome::Skipped));
    }

    #[test]
    fn file_overlap_warnings_detects_shared_crate() {
        let chains = vec![
            Chain {
                crate_name: Some("auth".into()),
                tasks: vec![TaskRef {
                    id: "t1".into(),
                    title: "A".into(),
                }],
            },
            Chain {
                crate_name: Some("auth".into()),
                tasks: vec![TaskRef {
                    id: "t2".into(),
                    title: "B".into(),
                }],
            },
            Chain {
                crate_name: Some("cache".into()),
                tasks: vec![TaskRef {
                    id: "t3".into(),
                    title: "C".into(),
                }],
            },
        ];
        let warnings = super::file_overlap_warnings(&chains);
        assert_eq!(warnings.len(), 1);
        assert_eq!(warnings[0], (0, 1, "auth".to_string()));
    }

    #[test]
    fn file_overlap_warnings_none_when_distinct() {
        let chains = vec![
            Chain {
                crate_name: Some("auth".into()),
                tasks: vec![TaskRef {
                    id: "t1".into(),
                    title: "A".into(),
                }],
            },
            Chain {
                crate_name: Some("cache".into()),
                tasks: vec![TaskRef {
                    id: "t2".into(),
                    title: "B".into(),
                }],
            },
        ];
        assert!(super::file_overlap_warnings(&chains).is_empty());
    }

    // --- async_dispatch_with_config tests ---

    #[tokio::test]
    async fn async_dispatch_runs_chains_concurrently() {
        let cfg = WaveConfig {
            max_concurrency: 3,
            max_retries: 0,
            retry_backoff_ms: 0,
            ..Default::default()
        };
        let chains = make_chains(3);

        let peak = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let current = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let peak_c = peak.clone();
        let current_c = current.clone();

        let outcomes = super::async_dispatch_with_config(&chains, &cfg, move |_tasks| {
            let p = peak_c.clone();
            let c = current_c.clone();
            async move {
                let prev = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                // Update peak.
                let _ = p.fetch_max(prev + 1, std::sync::atomic::Ordering::SeqCst);
                // Simulate work so other tasks can start concurrently.
                tokio::time::sleep(std::time::Duration::from_millis(50)).await;
                c.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
                Ok(())
            }
        })
        .await;

        assert_eq!(outcomes.len(), 3);
        assert!(outcomes.iter().all(|o| *o == ChainOutcome::Completed));
        // With concurrency=3 and 3 chains, peak should be >1 (true parallelism).
        assert!(
            peak.load(std::sync::atomic::Ordering::SeqCst) > 1,
            "expected concurrent execution, peak was {}",
            peak.load(std::sync::atomic::Ordering::SeqCst)
        );
    }

    #[tokio::test]
    async fn async_dispatch_respects_concurrency_limit() {
        let cfg = WaveConfig {
            max_concurrency: 1,
            max_retries: 0,
            retry_backoff_ms: 0,
            ..Default::default()
        };
        let chains = make_chains(3);

        let peak = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let current = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let peak_c = peak.clone();
        let current_c = current.clone();

        let outcomes = super::async_dispatch_with_config(&chains, &cfg, move |_tasks| {
            let p = peak_c.clone();
            let c = current_c.clone();
            async move {
                let prev = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                let _ = p.fetch_max(prev + 1, std::sync::atomic::Ordering::SeqCst);
                tokio::time::sleep(std::time::Duration::from_millis(10)).await;
                c.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
                Ok(())
            }
        })
        .await;

        assert!(outcomes.iter().all(|o| *o == ChainOutcome::Completed));
        assert_eq!(
            peak.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "concurrency limit of 1 should mean peak=1"
        );
    }

    #[tokio::test]
    async fn async_dispatch_retries_transient_failure() {
        let cfg = WaveConfig {
            max_concurrency: 5,
            max_retries: 3,
            retry_backoff_ms: 0,
            ..Default::default()
        };
        let chains = make_chains(1);
        let call_count = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let cc = call_count.clone();

        let outcomes = super::async_dispatch_with_config(&chains, &cfg, move |_tasks| {
            let c = cc.clone();
            async move {
                let n = c.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                if n == 0 { Err(true) } else { Ok(()) }
            }
        })
        .await;

        assert_eq!(outcomes[0], ChainOutcome::Completed);
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn async_dispatch_empty_chains() {
        let cfg = WaveConfig::default();
        let chains: Vec<super::Chain> = vec![];
        let outcomes =
            super::async_dispatch_with_config(&chains, &cfg, |_tasks| async { Ok(()) }).await;
        assert!(outcomes.is_empty());
    }

    #[test]
    fn dispatch_permanent_block_exhausted() {
        let cfg = WaveConfig {
            max_concurrency: 5,
            max_retries: 2,
            retry_backoff_ms: 0,
            ..Default::default()
        };
        let chains = make_chains(1);

        // Always fails with transient block — should exhaust retries.
        let outcomes = dispatch_with_config(&chains, &cfg, |_chain| Err(true));

        assert_eq!(outcomes[0], ChainOutcome::Exhausted);
    }
}