argentor-orchestrator 1.4.7

Multi-agent orchestration, task queues, and deployment for Argentor
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
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
//! Advanced multi-agent collaboration patterns.
//!
//! Goes beyond the basic Orchestrator-Workers pattern to support sophisticated
//! multi-agent workflows: pipelines, map-reduce, adversarial debate, ensemble
//! voting, supervised review, and swarm convergence.

use crate::types::AgentRole;
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Core pattern enum
// ---------------------------------------------------------------------------

/// A collaboration pattern describing how multiple agents interact to solve a task.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CollaborationPattern {
    /// Sequential processing chain -- each stage's output feeds the next stage's input,
    /// like Unix pipes: Agent A output -> Agent B input -> Agent C input.
    Pipeline {
        /// Ordered list of processing stages.
        stages: Vec<PipelineStage>,
    },

    /// Split work across N mapper agents, then reduce (aggregate) the partial results
    /// with a dedicated reducer agent.
    MapReduce {
        /// Agent role for the mapping (parallelizable) phase.
        mapper_role: AgentRole,
        /// Agent role for the reducing (aggregation) phase.
        reducer_role: AgentRole,
        /// Number of chunks the input is split into.
        chunk_count: usize,
    },

    /// Two agents argue opposing positions while a judge evaluates and decides,
    /// improving decision quality through adversarial deliberation.
    Debate {
        /// Agent role arguing in favor.
        proponent: AgentRole,
        /// Agent role arguing against.
        opponent: AgentRole,
        /// Agent role making the final decision.
        judge: AgentRole,
        /// Maximum debate rounds before forcing a decision.
        max_rounds: u32,
    },

    /// Multiple agents tackle the same task independently and results are aggregated
    /// via a configurable strategy (voting, best-of-N, concatenation, LLM synthesis).
    Ensemble {
        /// Agent roles participating in the ensemble.
        agents: Vec<AgentRole>,
        /// How the individual results are combined.
        aggregation: AggregationStrategy,
    },

    /// A supervisor agent reviews worker outputs and can accept or reject them
    /// according to a configurable review policy.
    Supervisor {
        /// Agent role responsible for review.
        supervisor: AgentRole,
        /// Agent roles producing work to be reviewed.
        workers: Vec<AgentRole>,
        /// When and how outputs are reviewed.
        review_policy: ReviewPolicy,
    },

    /// Agents iterate collaboratively until consensus or a convergence threshold is met.
    Swarm {
        /// Agent roles participating in the swarm.
        roles: Vec<AgentRole>,
        /// Maximum number of iterations before stopping.
        max_iterations: u32,
        /// Convergence threshold (0.0 -- 1.0); iteration stops when reached.
        convergence_threshold: f64,
    },
}

// ---------------------------------------------------------------------------
// Supporting types
// ---------------------------------------------------------------------------

/// A single stage in a [`CollaborationPattern::Pipeline`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PipelineStage {
    /// The agent role responsible for this stage.
    pub role: AgentRole,
    /// Human-readable description of what this stage does.
    pub description: String,
    /// Optional transformation hint applied to the output before passing it downstream.
    pub transform: Option<String>,
}

/// Strategy used by [`CollaborationPattern::Ensemble`] to aggregate results.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "strategy", rename_all = "snake_case")]
pub enum AggregationStrategy {
    /// Pick the result that appears most often among agents.
    MajorityVote,
    /// Pick the single best result according to a named metric.
    BestOfN {
        /// Metric name used to rank results.
        metric: String,
    },
    /// Concatenate all results in order.
    Concatenate,
    /// Use an LLM to synthesize a unified answer from all results.
    LlmSynthesize,
}

/// Policy for when a supervisor reviews worker output.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "policy", rename_all = "snake_case")]
pub enum ReviewPolicy {
    /// Supervisor reviews every piece of output.
    AlwaysReview,
    /// Supervisor randomly reviews a percentage of outputs.
    SamplePercent(f64),
    /// Supervisor only reviews outputs flagged as errors.
    OnError,
    /// No review — workers are fully trusted.
    Never,
}

/// Top-level configuration wrapping a [`CollaborationPattern`] with execution settings.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatternConfig {
    /// The collaboration pattern to execute.
    pub pattern: CollaborationPattern,
    /// Maximum wall-clock seconds the entire pattern execution may take.
    pub timeout_secs: u64,
    /// Maximum number of retries on transient failures.
    pub max_retries: u32,
}

/// Outcome of executing a collaboration pattern.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PatternResult {
    /// Name of the pattern that was executed (e.g. "pipeline", "debate").
    pub pattern_name: String,
    /// How many stages / rounds were completed.
    pub stages_completed: u32,
    /// Total stages / rounds that were planned.
    pub total_stages: u32,
    /// Identifiers (or summaries) of artifacts produced.
    pub artifacts: Vec<String>,
    /// Whether agents reached consensus (meaningful for Debate / Swarm).
    pub consensus_reached: bool,
    /// The final aggregated output text.
    pub final_output: String,
}

// ---------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------

/// Ergonomic builder for [`PatternConfig`].
#[derive(Debug, Clone)]
pub struct PatternConfigBuilder {
    pattern: CollaborationPattern,
    timeout_secs: u64,
    max_retries: u32,
}

impl PatternConfig {
    /// Start building a pipeline pattern (stages will be added via the builder).
    pub fn pipeline() -> PatternConfigBuilder {
        PatternConfigBuilder {
            pattern: CollaborationPattern::Pipeline { stages: Vec::new() },
            timeout_secs: 300,
            max_retries: 1,
        }
    }

    /// Start building a debate pattern with default roles and 3 rounds.
    pub fn debate() -> PatternConfigBuilder {
        PatternConfigBuilder {
            pattern: CollaborationPattern::Debate {
                proponent: AgentRole::Coder,
                opponent: AgentRole::Reviewer,
                judge: AgentRole::Architect,
                max_rounds: 3,
            },
            timeout_secs: 300,
            max_retries: 1,
        }
    }

    /// Start building an ensemble pattern.
    pub fn ensemble() -> PatternConfigBuilder {
        PatternConfigBuilder {
            pattern: CollaborationPattern::Ensemble {
                agents: Vec::new(),
                aggregation: AggregationStrategy::MajorityVote,
            },
            timeout_secs: 300,
            max_retries: 1,
        }
    }

    /// Start building a map-reduce pattern.
    pub fn map_reduce() -> PatternConfigBuilder {
        PatternConfigBuilder {
            pattern: CollaborationPattern::MapReduce {
                mapper_role: AgentRole::Coder,
                reducer_role: AgentRole::Orchestrator,
                chunk_count: 4,
            },
            timeout_secs: 600,
            max_retries: 1,
        }
    }

    /// Start building a supervisor pattern.
    pub fn supervisor() -> PatternConfigBuilder {
        PatternConfigBuilder {
            pattern: CollaborationPattern::Supervisor {
                supervisor: AgentRole::Reviewer,
                workers: Vec::new(),
                review_policy: ReviewPolicy::AlwaysReview,
            },
            timeout_secs: 300,
            max_retries: 1,
        }
    }

    /// Start building a swarm pattern.
    pub fn swarm() -> PatternConfigBuilder {
        PatternConfigBuilder {
            pattern: CollaborationPattern::Swarm {
                roles: Vec::new(),
                max_iterations: 10,
                convergence_threshold: 0.9,
            },
            timeout_secs: 600,
            max_retries: 1,
        }
    }
}

impl PatternConfigBuilder {
    /// Set the execution timeout in seconds.
    pub fn with_timeout(mut self, secs: u64) -> Self {
        self.timeout_secs = secs;
        self
    }

    /// Set the maximum number of retries.
    pub fn with_retries(mut self, n: u32) -> Self {
        self.max_retries = n;
        self
    }

    /// Add a stage to a pipeline pattern. No-op if the pattern is not a pipeline.
    pub fn add_stage(mut self, stage: PipelineStage) -> Self {
        if let CollaborationPattern::Pipeline { ref mut stages } = self.pattern {
            stages.push(stage);
        }
        self
    }

    /// Add an agent to an ensemble pattern. No-op if not an ensemble.
    pub fn add_agent(mut self, role: AgentRole) -> Self {
        if let CollaborationPattern::Ensemble { ref mut agents, .. } = self.pattern {
            agents.push(role);
        }
        self
    }

    /// Set the aggregation strategy for an ensemble. No-op if not an ensemble.
    pub fn with_aggregation(mut self, strategy: AggregationStrategy) -> Self {
        if let CollaborationPattern::Ensemble {
            ref mut aggregation,
            ..
        } = self.pattern
        {
            *aggregation = strategy;
        }
        self
    }

    /// Set the roles participating in a debate.
    pub fn with_debate_roles(
        mut self,
        proponent: AgentRole,
        opponent: AgentRole,
        judge: AgentRole,
    ) -> Self {
        if let CollaborationPattern::Debate {
            proponent: ref mut p,
            opponent: ref mut o,
            judge: ref mut j,
            ..
        } = self.pattern
        {
            *p = proponent;
            *o = opponent;
            *j = judge;
        }
        self
    }

    /// Set the maximum number of rounds for a debate.
    pub fn with_max_rounds(mut self, rounds: u32) -> Self {
        if let CollaborationPattern::Debate {
            ref mut max_rounds, ..
        } = self.pattern
        {
            *max_rounds = rounds;
        }
        self
    }

    /// Add a worker to a supervisor pattern.
    pub fn add_worker(mut self, role: AgentRole) -> Self {
        if let CollaborationPattern::Supervisor {
            ref mut workers, ..
        } = self.pattern
        {
            workers.push(role);
        }
        self
    }

    /// Set the review policy for a supervisor pattern.
    pub fn with_review_policy(mut self, policy: ReviewPolicy) -> Self {
        if let CollaborationPattern::Supervisor {
            ref mut review_policy,
            ..
        } = self.pattern
        {
            *review_policy = policy;
        }
        self
    }

    /// Set the mapper and reducer roles for map-reduce.
    pub fn with_mapper_reducer(
        mut self,
        mapper: AgentRole,
        reducer: AgentRole,
        chunks: usize,
    ) -> Self {
        if let CollaborationPattern::MapReduce {
            ref mut mapper_role,
            ref mut reducer_role,
            ref mut chunk_count,
        } = self.pattern
        {
            *mapper_role = mapper;
            *reducer_role = reducer;
            *chunk_count = chunks;
        }
        self
    }

    /// Add a role to a swarm pattern.
    pub fn add_swarm_role(mut self, role: AgentRole) -> Self {
        if let CollaborationPattern::Swarm { ref mut roles, .. } = self.pattern {
            roles.push(role);
        }
        self
    }

    /// Set convergence parameters for a swarm.
    pub fn with_convergence(mut self, max_iterations: u32, threshold: f64) -> Self {
        if let CollaborationPattern::Swarm {
            max_iterations: ref mut mi,
            convergence_threshold: ref mut ct,
            ..
        } = self.pattern
        {
            *mi = max_iterations;
            *ct = threshold;
        }
        self
    }

    /// Consume the builder and produce a [`PatternConfig`].
    pub fn build(self) -> PatternConfig {
        PatternConfig {
            pattern: self.pattern,
            timeout_secs: self.timeout_secs,
            max_retries: self.max_retries,
        }
    }
}

// ---------------------------------------------------------------------------
// Helper functions
// ---------------------------------------------------------------------------

/// Returns a human-readable description of a collaboration pattern.
pub fn describe_pattern(pattern: &CollaborationPattern) -> String {
    match pattern {
        CollaborationPattern::Pipeline { stages } => {
            let names: Vec<String> = stages.iter().map(|s| s.role.to_string()).collect();
            format!(
                "Pipeline with {} stages: {}",
                stages.len(),
                names.join(" -> ")
            )
        }
        CollaborationPattern::MapReduce {
            mapper_role,
            reducer_role,
            chunk_count,
        } => {
            format!("MapReduce: {chunk_count} x {mapper_role} mappers -> {reducer_role} reducer")
        }
        CollaborationPattern::Debate {
            proponent,
            opponent,
            judge,
            max_rounds,
        } => {
            format!(
                "Debate: {proponent} vs {opponent}, judged by {judge} (max {max_rounds} rounds)"
            )
        }
        CollaborationPattern::Ensemble {
            agents,
            aggregation,
        } => {
            let names: Vec<String> = agents
                .iter()
                .map(std::string::ToString::to_string)
                .collect();
            let strat = match aggregation {
                AggregationStrategy::MajorityVote => "majority vote",
                AggregationStrategy::BestOfN { metric } => {
                    return format!(
                        "Ensemble of {} agents [{}], aggregated by best-of-N (metric: {metric})",
                        agents.len(),
                        names.join(", ")
                    );
                }
                AggregationStrategy::Concatenate => "concatenation",
                AggregationStrategy::LlmSynthesize => "LLM synthesis",
            };
            format!(
                "Ensemble of {} agents [{}], aggregated by {strat}",
                agents.len(),
                names.join(", ")
            )
        }
        CollaborationPattern::Supervisor {
            supervisor,
            workers,
            review_policy,
        } => {
            let worker_names: Vec<String> = workers
                .iter()
                .map(std::string::ToString::to_string)
                .collect();
            let policy = match review_policy {
                ReviewPolicy::AlwaysReview => "always review",
                ReviewPolicy::SamplePercent(p) => {
                    return format!(
                        "Supervisor {supervisor} overseeing [{}], reviewing {:.0}% of outputs",
                        worker_names.join(", "),
                        p * 100.0
                    );
                }
                ReviewPolicy::OnError => "review on error",
                ReviewPolicy::Never => "no review",
            };
            format!(
                "Supervisor {supervisor} overseeing [{}], policy: {policy}",
                worker_names.join(", ")
            )
        }
        CollaborationPattern::Swarm {
            roles,
            max_iterations,
            convergence_threshold,
        } => {
            let names: Vec<String> = roles.iter().map(std::string::ToString::to_string).collect();
            format!(
                "Swarm of {} agents [{}], max {max_iterations} iterations, convergence >= {convergence_threshold}",
                roles.len(),
                names.join(", ")
            )
        }
    }
}

/// Validates that a collaboration pattern has a sensible configuration.
///
/// Returns `Ok(())` if valid, or `Err(reason)` describing the problem.
pub fn validate_pattern(pattern: &CollaborationPattern) -> Result<(), String> {
    match pattern {
        CollaborationPattern::Pipeline { stages } => {
            if stages.is_empty() {
                return Err("Pipeline must have at least one stage".into());
            }
            Ok(())
        }
        CollaborationPattern::MapReduce { chunk_count, .. } => {
            if *chunk_count == 0 {
                return Err("MapReduce chunk_count must be > 0".into());
            }
            Ok(())
        }
        CollaborationPattern::Debate {
            max_rounds,
            proponent,
            opponent,
            ..
        } => {
            if *max_rounds == 0 {
                return Err("Debate must have at least 1 round".into());
            }
            if proponent == opponent {
                return Err("Debate proponent and opponent must be different roles".into());
            }
            Ok(())
        }
        CollaborationPattern::Ensemble { agents, .. } => {
            if agents.len() < 2 {
                return Err("Ensemble requires at least 2 agents".into());
            }
            Ok(())
        }
        CollaborationPattern::Supervisor { workers, .. } => {
            if workers.is_empty() {
                return Err("Supervisor pattern requires at least one worker".into());
            }
            Ok(())
        }
        CollaborationPattern::Swarm {
            roles,
            max_iterations,
            convergence_threshold,
        } => {
            if roles.len() < 2 {
                return Err("Swarm requires at least 2 agents".into());
            }
            if *max_iterations == 0 {
                return Err("Swarm must have at least 1 iteration".into());
            }
            if *convergence_threshold <= 0.0 || *convergence_threshold > 1.0 {
                return Err("Swarm convergence_threshold must be in (0.0, 1.0]".into());
            }
            Ok(())
        }
    }
}

/// Estimates the total token usage for a pattern given a per-agent token budget.
///
/// This is a rough heuristic:
/// - Pipeline: `stages * tokens_per_agent`
/// - MapReduce: `(chunk_count + 1) * tokens_per_agent`
/// - Debate: `(2 * max_rounds + 1) * tokens_per_agent`  (proponent + opponent per round, plus judge)
/// - Ensemble: `agents.len() * tokens_per_agent`  (plus aggregation cost if LLM)
/// - Supervisor: `(workers.len() + review_overhead) * tokens_per_agent`
/// - Swarm: `roles.len() * max_iterations * tokens_per_agent`
pub fn estimate_cost(pattern: &CollaborationPattern, tokens_per_agent: u64) -> u64 {
    match pattern {
        CollaborationPattern::Pipeline { stages } => stages.len() as u64 * tokens_per_agent,
        CollaborationPattern::MapReduce { chunk_count, .. } => {
            (*chunk_count as u64 + 1) * tokens_per_agent
        }
        CollaborationPattern::Debate { max_rounds, .. } => {
            // Each round: proponent + opponent; final: judge
            (2 * *max_rounds as u64 + 1) * tokens_per_agent
        }
        CollaborationPattern::Ensemble {
            agents,
            aggregation,
        } => {
            let base = agents.len() as u64 * tokens_per_agent;
            match aggregation {
                AggregationStrategy::LlmSynthesize => base + tokens_per_agent,
                _ => base,
            }
        }
        CollaborationPattern::Supervisor {
            workers,
            review_policy,
            ..
        } => {
            let worker_cost = workers.len() as u64 * tokens_per_agent;
            let review_cost = match review_policy {
                ReviewPolicy::AlwaysReview => workers.len() as u64 * tokens_per_agent,
                ReviewPolicy::SamplePercent(p) => {
                    (workers.len() as f64 * p * tokens_per_agent as f64) as u64
                }
                ReviewPolicy::OnError => tokens_per_agent, // assume ~1 review
                ReviewPolicy::Never => 0,
            };
            worker_cost + review_cost
        }
        CollaborationPattern::Swarm {
            roles,
            max_iterations,
            ..
        } => roles.len() as u64 * *max_iterations as u64 * tokens_per_agent,
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    // -- Pipeline --

    #[test]
    fn test_pipeline_describe() {
        let pattern = CollaborationPattern::Pipeline {
            stages: vec![
                PipelineStage {
                    role: AgentRole::Spec,
                    description: "Generate spec".into(),
                    transform: None,
                },
                PipelineStage {
                    role: AgentRole::Coder,
                    description: "Implement".into(),
                    transform: Some("extract_code".into()),
                },
            ],
        };
        let desc = describe_pattern(&pattern);
        assert!(desc.contains("Pipeline"));
        assert!(desc.contains("2 stages"));
        assert!(desc.contains("spec -> coder"));
    }

    #[test]
    fn test_pipeline_validate_empty() {
        let pattern = CollaborationPattern::Pipeline { stages: Vec::new() };
        assert!(validate_pattern(&pattern).is_err());
    }

    #[test]
    fn test_pipeline_validate_ok() {
        let pattern = CollaborationPattern::Pipeline {
            stages: vec![PipelineStage {
                role: AgentRole::Coder,
                description: "Code it".into(),
                transform: None,
            }],
        };
        assert!(validate_pattern(&pattern).is_ok());
    }

    #[test]
    fn test_pipeline_estimate_cost() {
        let pattern = CollaborationPattern::Pipeline {
            stages: vec![
                PipelineStage {
                    role: AgentRole::Spec,
                    description: "Spec".into(),
                    transform: None,
                },
                PipelineStage {
                    role: AgentRole::Coder,
                    description: "Code".into(),
                    transform: None,
                },
                PipelineStage {
                    role: AgentRole::Tester,
                    description: "Test".into(),
                    transform: None,
                },
            ],
        };
        assert_eq!(estimate_cost(&pattern, 1000), 3000);
    }

    // -- MapReduce --

    #[test]
    fn test_map_reduce_validate_zero_chunks() {
        let pattern = CollaborationPattern::MapReduce {
            mapper_role: AgentRole::Coder,
            reducer_role: AgentRole::Orchestrator,
            chunk_count: 0,
        };
        assert!(validate_pattern(&pattern).is_err());
    }

    #[test]
    fn test_map_reduce_estimate() {
        let pattern = CollaborationPattern::MapReduce {
            mapper_role: AgentRole::Coder,
            reducer_role: AgentRole::Orchestrator,
            chunk_count: 4,
        };
        // 4 mappers + 1 reducer = 5
        assert_eq!(estimate_cost(&pattern, 500), 2500);
    }

    // -- Debate --

    #[test]
    fn test_debate_validate_same_roles() {
        let pattern = CollaborationPattern::Debate {
            proponent: AgentRole::Coder,
            opponent: AgentRole::Coder,
            judge: AgentRole::Architect,
            max_rounds: 3,
        };
        assert!(validate_pattern(&pattern).is_err());
    }

    #[test]
    fn test_debate_validate_zero_rounds() {
        let pattern = CollaborationPattern::Debate {
            proponent: AgentRole::Coder,
            opponent: AgentRole::Reviewer,
            judge: AgentRole::Architect,
            max_rounds: 0,
        };
        assert!(validate_pattern(&pattern).is_err());
    }

    #[test]
    fn test_debate_estimate() {
        let pattern = CollaborationPattern::Debate {
            proponent: AgentRole::Coder,
            opponent: AgentRole::Reviewer,
            judge: AgentRole::Architect,
            max_rounds: 3,
        };
        // 2 * 3 + 1 = 7
        assert_eq!(estimate_cost(&pattern, 1000), 7000);
    }

    // -- Ensemble --

    #[test]
    fn test_ensemble_validate_too_few() {
        let pattern = CollaborationPattern::Ensemble {
            agents: vec![AgentRole::Coder],
            aggregation: AggregationStrategy::MajorityVote,
        };
        assert!(validate_pattern(&pattern).is_err());
    }

    #[test]
    fn test_ensemble_llm_synthesize_extra_cost() {
        let pattern = CollaborationPattern::Ensemble {
            agents: vec![AgentRole::Coder, AgentRole::Reviewer, AgentRole::Architect],
            aggregation: AggregationStrategy::LlmSynthesize,
        };
        // 3 agents + 1 synthesis = 4
        assert_eq!(estimate_cost(&pattern, 1000), 4000);
    }

    // -- Supervisor --

    #[test]
    fn test_supervisor_validate_no_workers() {
        let pattern = CollaborationPattern::Supervisor {
            supervisor: AgentRole::Reviewer,
            workers: Vec::new(),
            review_policy: ReviewPolicy::AlwaysReview,
        };
        assert!(validate_pattern(&pattern).is_err());
    }

    #[test]
    fn test_supervisor_estimate_always_review() {
        let pattern = CollaborationPattern::Supervisor {
            supervisor: AgentRole::Reviewer,
            workers: vec![AgentRole::Coder, AgentRole::Tester],
            review_policy: ReviewPolicy::AlwaysReview,
        };
        // workers: 2 * 1000 = 2000, reviews: 2 * 1000 = 2000 => 4000
        assert_eq!(estimate_cost(&pattern, 1000), 4000);
    }

    // -- Swarm --

    #[test]
    fn test_swarm_validate_threshold_out_of_range() {
        let pattern = CollaborationPattern::Swarm {
            roles: vec![AgentRole::Coder, AgentRole::Reviewer],
            max_iterations: 5,
            convergence_threshold: 1.5,
        };
        assert!(validate_pattern(&pattern).is_err());
    }

    #[test]
    fn test_swarm_validate_zero_threshold() {
        let pattern = CollaborationPattern::Swarm {
            roles: vec![AgentRole::Coder, AgentRole::Reviewer],
            max_iterations: 5,
            convergence_threshold: 0.0,
        };
        assert!(validate_pattern(&pattern).is_err());
    }

    #[test]
    fn test_swarm_estimate() {
        let pattern = CollaborationPattern::Swarm {
            roles: vec![AgentRole::Coder, AgentRole::Reviewer, AgentRole::Tester],
            max_iterations: 10,
            convergence_threshold: 0.9,
        };
        // 3 roles * 10 iterations * 500 = 15000
        assert_eq!(estimate_cost(&pattern, 500), 15000);
    }

    // -- Builder --

    #[test]
    fn test_builder_pipeline() {
        let config = PatternConfig::pipeline()
            .add_stage(PipelineStage {
                role: AgentRole::Spec,
                description: "Requirements".into(),
                transform: None,
            })
            .add_stage(PipelineStage {
                role: AgentRole::Coder,
                description: "Implementation".into(),
                transform: Some("extract_rust".into()),
            })
            .with_timeout(120)
            .with_retries(3)
            .build();

        assert_eq!(config.timeout_secs, 120);
        assert_eq!(config.max_retries, 3);
        if let CollaborationPattern::Pipeline { stages } = &config.pattern {
            assert_eq!(stages.len(), 2);
            assert_eq!(stages[0].role, AgentRole::Spec);
            assert_eq!(stages[1].transform.as_deref(), Some("extract_rust"));
        } else {
            panic!("Expected Pipeline pattern");
        }
    }

    #[test]
    fn test_builder_debate() {
        let config = PatternConfig::debate()
            .with_debate_roles(
                AgentRole::Architect,
                AgentRole::SecurityAuditor,
                AgentRole::Reviewer,
            )
            .with_max_rounds(5)
            .with_timeout(600)
            .build();

        if let CollaborationPattern::Debate {
            proponent,
            opponent,
            judge,
            max_rounds,
        } = &config.pattern
        {
            assert_eq!(*proponent, AgentRole::Architect);
            assert_eq!(*opponent, AgentRole::SecurityAuditor);
            assert_eq!(*judge, AgentRole::Reviewer);
            assert_eq!(*max_rounds, 5);
        } else {
            panic!("Expected Debate pattern");
        }
    }

    #[test]
    fn test_builder_ensemble() {
        let config = PatternConfig::ensemble()
            .add_agent(AgentRole::Coder)
            .add_agent(AgentRole::Reviewer)
            .add_agent(AgentRole::Architect)
            .with_aggregation(AggregationStrategy::BestOfN {
                metric: "accuracy".into(),
            })
            .build();

        if let CollaborationPattern::Ensemble {
            agents,
            aggregation,
        } = &config.pattern
        {
            assert_eq!(agents.len(), 3);
            if let AggregationStrategy::BestOfN { metric } = aggregation {
                assert_eq!(metric, "accuracy");
            } else {
                panic!("Expected BestOfN strategy");
            }
        } else {
            panic!("Expected Ensemble pattern");
        }
    }

    // -- Serialization --

    #[test]
    fn test_pattern_config_roundtrip() {
        let config = PatternConfig::debate()
            .with_debate_roles(AgentRole::Coder, AgentRole::Reviewer, AgentRole::Architect)
            .with_max_rounds(3)
            .with_timeout(180)
            .with_retries(2)
            .build();

        let json = serde_json::to_string(&config).unwrap();
        let parsed: PatternConfig = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.timeout_secs, 180);
        assert_eq!(parsed.max_retries, 2);
        if let CollaborationPattern::Debate { max_rounds, .. } = &parsed.pattern {
            assert_eq!(*max_rounds, 3);
        } else {
            panic!("Expected Debate after deserialization");
        }
    }

    #[test]
    fn test_pattern_result_construction() {
        let result = PatternResult {
            pattern_name: "debate".into(),
            stages_completed: 6,
            total_stages: 7,
            artifacts: vec!["spec.md".into(), "review.md".into()],
            consensus_reached: true,
            final_output: "Use approach A".into(),
        };
        assert!(result.consensus_reached);
        assert_eq!(result.artifacts.len(), 2);
        assert_eq!(result.stages_completed, 6);
    }

    #[test]
    fn test_describe_all_patterns() {
        // Verify describe_pattern does not panic for any variant.
        let patterns = vec![
            CollaborationPattern::Pipeline {
                stages: vec![PipelineStage {
                    role: AgentRole::Coder,
                    description: "code".into(),
                    transform: None,
                }],
            },
            CollaborationPattern::MapReduce {
                mapper_role: AgentRole::Coder,
                reducer_role: AgentRole::Orchestrator,
                chunk_count: 3,
            },
            CollaborationPattern::Debate {
                proponent: AgentRole::Coder,
                opponent: AgentRole::Reviewer,
                judge: AgentRole::Architect,
                max_rounds: 2,
            },
            CollaborationPattern::Ensemble {
                agents: vec![AgentRole::Coder, AgentRole::Reviewer],
                aggregation: AggregationStrategy::Concatenate,
            },
            CollaborationPattern::Supervisor {
                supervisor: AgentRole::Reviewer,
                workers: vec![AgentRole::Coder],
                review_policy: ReviewPolicy::SamplePercent(0.5),
            },
            CollaborationPattern::Swarm {
                roles: vec![AgentRole::Coder, AgentRole::Tester],
                max_iterations: 5,
                convergence_threshold: 0.8,
            },
        ];

        for p in &patterns {
            let desc = describe_pattern(p);
            assert!(!desc.is_empty(), "Description should not be empty");
        }
    }
}