RavenClaws 1.2.0

Lightweight, secure Rust agent framework with multi-provider LLM support
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
982
983
984
985
986
987
988
989
990
991
//! Multi-agent pattern primitives
//!
//! Built-in multi-agent collaboration patterns that extend beyond simple
//! swarm/supervisor modes. Each pattern implements a distinct collaboration
//! strategy:
//!
//! - **Debate** — Multiple agents argue different positions, then converge
//! - **Review-Loop** — One agent produces, another reviews, iterating to quality
//! - **Research-Synthesize** — Parallel research agents feed a synthesizer
//! - **Voting** — Multiple agents vote on options, majority decides
//!
//! These patterns are first-class modes accessible via `--mode debate`,
//! `--mode review-loop`, `--mode research-synthesize`, or `--mode voting`.

use std::sync::Arc;
use tracing::{info, warn};

use crate::agent::ConversationMemory;
use crate::config::Config;
use crate::error::RavenClawsError;
use crate::llm::{LLMProviderTrait, MultiModelManager};
use crate::ravenfabric::RavenFabricClient;

// ── Pattern Configuration ──────────────────────────────────────────────────

/// Configuration for multi-agent patterns
#[derive(Debug, Clone)]
pub struct PatternConfig {
    /// Maximum debate rounds (default: 3)
    pub max_rounds: usize,
    /// Maximum review iterations (default: 3)
    pub max_review_iterations: usize,
    /// Number of research agents (default: 3)
    pub research_agent_count: usize,
    /// Number of voters (default: 3)
    pub voter_count: usize,
    /// Whether to show intermediate results
    pub verbose: bool,
}

impl Default for PatternConfig {
    fn default() -> Self {
        Self {
            max_rounds: 3,
            max_review_iterations: 3,
            research_agent_count: 3,
            voter_count: 3,
            verbose: false,
        }
    }
}

// ── Pattern 1: Debate ──────────────────────────────────────────────────────

/// Run a debate between multiple agents with different positions.
///
/// Each agent argues a distinct position, then a judge synthesizes the
/// final conclusion after configurable rounds of debate.
pub async fn run_debate(
    llm: Arc<dyn LLMProviderTrait>,
    config: Config,
    ravenfabric: Option<RavenFabricClient>,
    pattern_config: PatternConfig,
) -> crate::error::Result<()> {
    info!(
        "Starting debate mode with {} max rounds",
        pattern_config.max_rounds
    );

    let system_prompt = &config.llm.system_prompt;
    let task = "Analyze the given task and provide your solution.";

    // Define debate positions
    let positions = [
        ("Proponent", "You argue FOR the proposition. Focus on benefits, opportunities, and strengths. Be persuasive and evidence-based."),
        ("Opponent", "You argue AGAINST the proposition. Focus on risks, drawbacks, and weaknesses. Be critical and thorough."),
        ("Synthesizer", "You are the neutral judge. Listen to both sides, identify common ground, and synthesize a balanced conclusion."),
    ];

    let mut debate_history = ConversationMemory::new(system_prompt, 50);
    debate_history.add_user_message(&format!(
        "Debate topic: {}\n\nProponent, present your opening argument.",
        task
    ));

    // Debate rounds
    for round in 0..pattern_config.max_rounds {
        info!(round = round + 1, "Debate round starting");

        for (role, persona) in &positions {
            if *role == "Synthesizer" && round < pattern_config.max_rounds - 1 {
                continue; // Synthesizer only speaks in final round
            }

            let mut agent_memory = ConversationMemory::new(persona, 20);
            // Feed debate history
            for msg in debate_history.history() {
                if msg.role == "system" {
                    continue;
                }
                if msg.role == "user" {
                    agent_memory.add_user_message(&msg.content);
                } else {
                    agent_memory.add_assistant_message(&msg.content);
                }
            }

            let messages = agent_memory.history().to_vec();
            match llm.chat(messages).await {
                Ok(response) => {
                    if let Some(choice) = response.choices.first() {
                        let content = &choice.message.content;
                        info!(role = %role, round = round + 1, "Debate contribution received");

                        if pattern_config.verbose {
                            println!("\n── {} (Round {}) ──\n{}", role, round + 1, content);
                        }

                        debate_history.add_assistant_message(&format!("{}: {}", role, content));
                    }
                }
                Err(e) => {
                    warn!(error = %e, role = %role, round = round + 1, "Debate LLM request failed");
                }
            }
        }
    }

    // Final synthesis
    let synthesizer_persona = "You are a neutral synthesizer. Produce a final balanced conclusion that incorporates the best arguments from both sides.";
    let mut final_memory = ConversationMemory::new(synthesizer_persona, 30);
    for msg in debate_history.history() {
        if msg.role == "system" {
            continue;
        }
        if msg.role == "user" {
            final_memory.add_user_message(&msg.content);
        } else {
            final_memory.add_assistant_message(&msg.content);
        }
    }
    final_memory
        .add_user_message("Now produce your FINAL synthesis that balances all perspectives:");

    let messages = final_memory.history().to_vec();
    match llm.chat(messages).await {
        Ok(response) => {
            if let Some(choice) = response.choices.first() {
                let result = &choice.message.content;
                println!("\n🐦‍⬛ Debate Synthesis:\n{}", result);

                if let Some(ref rf) = ravenfabric {
                    if rf.is_enabled() {
                        let preview = result.chars().take(500).collect::<String>();
                        let _ = rf.broadcast(&preview, 30).await;
                    }
                }
            }
        }
        Err(e) => {
            warn!(error = %e, "Debate synthesis failed");
            return Err(RavenClawsError::CommandExecution(format!(
                "Debate synthesis failed: {}",
                e
            )));
        }
    }

    Ok(())
}

// ── Pattern 2: Review-Loop ─────────────────────────────────────────────────

/// Run a producer-reviewer loop that iterates until quality is met.
///
/// A producer agent creates content, a reviewer agent critiques it,
/// and the producer revises based on feedback. Repeats until the
/// reviewer approves or max iterations reached.
pub async fn run_review_loop(
    llm: Arc<dyn LLMProviderTrait>,
    config: Config,
    ravenfabric: Option<RavenFabricClient>,
    pattern_config: PatternConfig,
) -> crate::error::Result<()> {
    info!(
        "Starting review-loop mode with max {} iterations",
        pattern_config.max_review_iterations
    );

    let _system_prompt = &config.llm.system_prompt;
    let task = "Analyze the given task and provide your solution.";

    let producer_persona = "You are a producer. Create high-quality content based on the requirements. Be thorough and detailed.";
    let reviewer_persona = "You are a reviewer. Critically evaluate the content. Identify specific issues, gaps, and improvements needed. Be constructive and precise. If the content meets quality standards, respond with APPROVED: followed by your final sign-off.";

    let mut current_content = String::new();
    let mut approved = false;

    for iteration in 0..pattern_config.max_review_iterations {
        info!(iteration = iteration + 1, "Review-loop iteration");

        if iteration == 0 {
            // Producer creates initial content
            let mut producer_memory = ConversationMemory::new(producer_persona, 10);
            producer_memory.add_user_message(&format!(
                "Create content for the following task:\n\n{}",
                task
            ));

            let messages = producer_memory.history().to_vec();
            match llm.chat(messages).await {
                Ok(response) => {
                    if let Some(choice) = response.choices.first() {
                        current_content = choice.message.content.clone();
                        info!("Initial content produced: {} chars", current_content.len());

                        if pattern_config.verbose {
                            println!("\n── Initial Content ──\n{}", current_content);
                        }
                    }
                }
                Err(e) => {
                    warn!(error = %e, "Producer LLM request failed");
                    return Err(RavenClawsError::CommandExecution(format!(
                        "Producer failed: {}",
                        e
                    )));
                }
            }
        } else {
            // Reviewer critiques
            let mut reviewer_memory = ConversationMemory::new(reviewer_persona, 10);
            reviewer_memory.add_user_message(&format!(
                "Review the following content and provide constructive feedback:\n\n{}",
                current_content
            ));

            let messages = reviewer_memory.history().to_vec();
            let review = match llm.chat(messages).await {
                Ok(response) => response
                    .choices
                    .first()
                    .map(|c| c.message.content.clone())
                    .unwrap_or_default(),
                Err(e) => {
                    warn!(error = %e, "Reviewer LLM request failed");
                    continue;
                }
            };

            if pattern_config.verbose {
                println!("\n── Review (Iteration {}) ──\n{}", iteration + 1, review);
            }

            // Check if approved
            if review.contains("APPROVED:") {
                info!("Content approved after {} iterations", iteration + 1);
                let final_content = review.split("APPROVED:").nth(1).unwrap_or(&current_content);
                current_content = final_content.trim().to_string();
                approved = true;
                break;
            }

            // Producer revises based on feedback
            let mut producer_memory = ConversationMemory::new(producer_persona, 10);
            producer_memory.add_user_message(&format!(
                "Your previous content:\n\n{}\n\nReviewer feedback:\n\n{}\n\nPlease revise the content addressing all feedback.",
                current_content, review
            ));

            let messages = producer_memory.history().to_vec();
            match llm.chat(messages).await {
                Ok(response) => {
                    if let Some(choice) = response.choices.first() {
                        current_content = choice.message.content.clone();
                        info!("Content revised: {} chars", current_content.len());

                        if pattern_config.verbose {
                            println!(
                                "\n── Revised Content (Iteration {}) ──\n{}",
                                iteration + 1,
                                current_content
                            );
                        }
                    }
                }
                Err(e) => {
                    warn!(error = %e, "Producer revision failed");
                    continue;
                }
            }
        }
    }

    if !approved {
        warn!("Review-loop reached max iterations without approval");
    }

    println!("\n🐦‍⬛ Review-Loop Final Content:\n{}", current_content);

    if let Some(ref rf) = ravenfabric {
        if rf.is_enabled() {
            let preview = current_content.chars().take(500).collect::<String>();
            let _ = rf.broadcast(&preview, 30).await;
        }
    }

    Ok(())
}

// ── Pattern 3: Research-Synthesize ─────────────────────────────────────────

/// Run parallel research agents followed by a synthesizer.
///
/// Multiple research agents explore different aspects of a topic in parallel.
/// A synthesizer agent then combines their findings into a coherent report.
pub async fn run_research_synthesize(
    llm: Arc<dyn LLMProviderTrait>,
    config: Config,
    ravenfabric: Option<RavenFabricClient>,
    pattern_config: PatternConfig,
) -> crate::error::Result<()> {
    info!(
        "Starting research-synthesize mode with {} research agents",
        pattern_config.research_agent_count
    );

    let _system_prompt = &config.llm.system_prompt;
    let task = "Analyze the given task and provide your solution.";

    // Define research perspectives
    let perspectives = [
        ("Fact-Finder", "You are a fact-finding researcher. Focus on verifiable facts, data, statistics, and concrete evidence. Cite specific sources and numbers."),
        ("Analyst", "You are an analytical researcher. Focus on patterns, trends, cause-and-effect relationships, and strategic implications."),
        ("Innovator", "You are an innovative researcher. Focus on novel approaches, emerging trends, creative solutions, and future possibilities."),
    ];

    let agent_count = pattern_config.research_agent_count.min(perspectives.len());
    let mut research_results: Vec<(String, String)> = Vec::new();

    // Phase 1: Parallel research
    for (role, persona) in perspectives.iter().take(agent_count) {
        info!(role = %role, "Research agent starting");

        let mut memory = ConversationMemory::new(persona, 10);
        memory.add_user_message(&format!(
            "Research the following topic from your perspective:\n\n{}",
            task
        ));

        let messages = memory.history().to_vec();
        match llm.chat(messages).await {
            Ok(response) => {
                if let Some(choice) = response.choices.first() {
                    let content = choice.message.content.clone();
                    info!(role = %role, "Research completed: {} chars", content.len());
                    research_results.push((role.to_string(), content));
                }
            }
            Err(e) => {
                warn!(error = %e, role = %role, "Research agent failed");
                research_results.push((role.to_string(), format!("[Research failed: {}]", e)));
            }
        }
    }

    // Print intermediate research if verbose
    if pattern_config.verbose {
        println!("\n── Research Findings ──");
        for (role, content) in &research_results {
            println!("\n--- {} ---\n{}", role, content);
        }
    }

    // Phase 2: Synthesis
    let synthesizer_persona = "You are a synthesis specialist. Combine multiple research perspectives into a coherent, well-structured report. Identify common themes, resolve contradictions, and present a unified analysis.";
    let mut synth_memory = ConversationMemory::new(synthesizer_persona, 20);

    let mut synthesis_input =
        String::from("Synthesize the following research findings into a comprehensive report:\n\n");
    for (role, content) in &research_results {
        synthesis_input.push_str(&format!("\n=== {} ===\n{}\n", role, content));
    }
    synth_memory.add_user_message(&synthesis_input);

    let messages = synth_memory.history().to_vec();
    match llm.chat(messages).await {
        Ok(response) => {
            if let Some(choice) = response.choices.first() {
                let result = &choice.message.content;
                println!("\n🐦‍⬛ Research Synthesis:\n{}", result);

                if let Some(ref rf) = ravenfabric {
                    if rf.is_enabled() {
                        let preview = result.chars().take(500).collect::<String>();
                        let _ = rf.broadcast(&preview, 30).await;
                    }
                }
            }
        }
        Err(e) => {
            warn!(error = %e, "Synthesis failed");
            return Err(RavenClawsError::CommandExecution(format!(
                "Synthesis failed: {}",
                e
            )));
        }
    }

    Ok(())
}

// ── Pattern 4: Voting ──────────────────────────────────────────────────────

/// Run a voting process where multiple agents evaluate options.
///
/// Each voter agent independently evaluates the options and provides
/// their choice with reasoning. Results are tallied and the majority
/// decision is reported.
pub async fn run_voting(
    llm: Arc<dyn LLMProviderTrait>,
    config: Config,
    ravenfabric: Option<RavenFabricClient>,
    pattern_config: PatternConfig,
) -> crate::error::Result<()> {
    info!(
        "Starting voting mode with {} voters",
        pattern_config.voter_count
    );

    let system_prompt = &config.llm.system_prompt;
    let task = "Analyze the given task and provide your solution.";

    // Define voter personas for diversity
    let voter_personas = [
        "You are a conservative voter. You prefer safe, proven approaches. Prioritize stability and risk mitigation. Respond with: VOTE: <your choice> REASONING: <your reasoning>",
        "You are an aggressive voter. You prefer bold, ambitious approaches. Prioritize maximum impact and innovation. Respond with: VOTE: <your choice> REASONING: <your reasoning>",
        "You are a balanced voter. You weigh pros and cons carefully. Prioritize pragmatic, well-rounded solutions. Respond with: VOTE: <your choice> REASONING: <your reasoning>",
        "You are a detail-oriented voter. You focus on implementation feasibility and technical soundness. Respond with: VOTE: <your choice> REASONING: <your reasoning>",
        "You are a user-centric voter. You prioritize user experience, accessibility, and usability. Respond with: VOTE: <your choice> REASONING: <your reasoning>",
    ];

    let voter_count = pattern_config.voter_count.min(voter_personas.len());
    let mut votes: Vec<(String, String, String)> = Vec::new(); // (persona_name, vote, reasoning)

    // Phase 1: Independent voting
    for (i, persona) in voter_personas.iter().enumerate().take(voter_count) {
        let persona_name = persona
            .split('.')
            .next()
            .unwrap_or(&format!("Voter {}", i + 1))
            .to_string();

        let mut memory = ConversationMemory::new(&format!("{}\n\n{}", system_prompt, persona), 10);
        memory.add_user_message(&format!(
            "Evaluate the following and cast your vote:\n\n{}",
            task
        ));

        let messages = memory.history().to_vec();
        match llm.chat(messages).await {
            Ok(response) => {
                if let Some(choice) = response.choices.first() {
                    let content = choice.message.content.clone();
                    info!(voter = %persona_name, "Vote cast");

                    // Extract vote and reasoning
                    let vote = content
                        .split("VOTE:")
                        .nth(1)
                        .and_then(|s| s.split("REASONING:").next())
                        .map(|s| s.trim().to_string())
                        .unwrap_or_else(|| "Unknown".to_string());

                    let reasoning = content
                        .split("REASONING:")
                        .nth(1)
                        .map(|s| s.trim().to_string())
                        .unwrap_or_default();

                    if pattern_config.verbose {
                        println!(
                            "\n── {} ──\nVOTE: {}\nREASONING: {}",
                            persona_name, vote, reasoning
                        );
                    }

                    votes.push((persona_name, vote, reasoning));
                }
            }
            Err(e) => {
                warn!(error = %e, voter = %persona_name, "Voter LLM request failed");
                votes.push((
                    persona_name,
                    "Error".to_string(),
                    format!("Vote failed: {}", e),
                ));
            }
        }
    }

    // Phase 2: Tally results
    let mut tally: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for (_, vote, _) in &votes {
        *tally.entry(vote.clone()).or_insert(0) += 1;
    }

    // Find winner(s)
    let max_votes = tally.values().cloned().max().unwrap_or(0);
    let winners: Vec<String> = tally
        .iter()
        .filter(|(_, count)| **count == max_votes)
        .map(|(vote, _)| vote.clone())
        .collect();

    println!("\n🐦‍⬛ Voting Results:");
    println!("───");
    for (persona, vote, reasoning) in &votes {
        println!("{}: VOTE = {} | {}", persona, vote, reasoning);
    }
    println!("───");
    println!("Tally: {:?}", tally);
    println!("\n🏆 Decision: {}", winners.join(", "));

    if let Some(ref rf) = ravenfabric {
        if rf.is_enabled() {
            let summary = format!(
                "Voting completed: {} voters, decision: {}",
                votes.len(),
                winners.join(", ")
            );
            let _ = rf.broadcast(&summary, 30).await;
        }
    }

    Ok(())
}

// ── Multi-model variants ───────────────────────────────────────────────────

/// Run debate mode with multiple LLM providers (round-robin)
pub async fn run_debate_multi(
    multi_llm: MultiModelManager,
    config: Config,
    _ravenfabric: Option<RavenFabricClient>,
    pattern_config: PatternConfig,
) -> crate::error::Result<()> {
    info!(
        "Starting debate mode (multi-model) with {} providers",
        multi_llm.client_count()
    );

    let system_prompt = &config.llm.system_prompt;
    let task = "Analyze the given task and provide your solution.";

    let positions = [
        (
            "Proponent",
            "You argue FOR the proposition. Focus on benefits, opportunities, and strengths.",
        ),
        (
            "Opponent",
            "You argue AGAINST the proposition. Focus on risks, drawbacks, and weaknesses.",
        ),
        (
            "Synthesizer",
            "You are the neutral judge. Synthesize a balanced conclusion.",
        ),
    ];

    let mut debate_history = ConversationMemory::new(system_prompt, 50);
    debate_history.add_user_message(&format!("Debate topic: {}", task));

    for round in 0..pattern_config.max_rounds {
        info!(round = round + 1, "Multi-model debate round");

        for (role, persona) in &positions {
            if *role == "Synthesizer" && round < pattern_config.max_rounds - 1 {
                continue;
            }

            let provider_idx = round % multi_llm.client_count();
            let client = multi_llm.get_client(provider_idx);

            if let Some(client) = client {
                let mut agent_memory = ConversationMemory::new(persona, 20);
                for msg in debate_history.history() {
                    if msg.role == "system" {
                        continue;
                    }
                    if msg.role == "user" {
                        agent_memory.add_user_message(&msg.content);
                    } else {
                        agent_memory.add_assistant_message(&msg.content);
                    }
                }

                let messages = agent_memory.history().to_vec();
                match client.chat(messages).await {
                    Ok(response) => {
                        if let Some(choice) = response.choices.first() {
                            let content = &choice.message.content;
                            info!(role = %role, provider = client.provider_name(), round = round + 1, "Debate contribution");
                            if pattern_config.verbose {
                                println!(
                                    "\n── {} ({} via {}, Round {}) ──\n{}",
                                    role,
                                    client.provider_name(),
                                    client.model(),
                                    round + 1,
                                    content
                                );
                            }
                            debate_history.add_assistant_message(&format!(
                                "{} ({}): {}",
                                role,
                                client.provider_name(),
                                content
                            ));
                        }
                    }
                    Err(e) => warn!(error = %e, role = %role, "Multi-model debate failed"),
                }
            }
        }
    }

    // Final synthesis using first provider
    if let Some(client) = multi_llm.get_client(0) {
        let synthesizer_persona =
            "You are a neutral synthesizer. Produce a final balanced conclusion.";
        let mut final_memory = ConversationMemory::new(synthesizer_persona, 30);
        for msg in debate_history.history() {
            if msg.role == "system" {
                continue;
            }
            if msg.role == "user" {
                final_memory.add_user_message(&msg.content);
            } else {
                final_memory.add_assistant_message(&msg.content);
            }
        }
        final_memory.add_user_message("Now produce your FINAL synthesis:");

        let messages = final_memory.history().to_vec();
        match client.chat(messages).await {
            Ok(response) => {
                if let Some(choice) = response.choices.first() {
                    println!(
                        "\n🐦‍⬛ Multi-Model Debate Synthesis:\n{}",
                        choice.message.content
                    );
                }
            }
            Err(e) => warn!(error = %e, "Multi-model synthesis failed"),
        }
    }

    Ok(())
}

/// Run review-loop mode with multiple LLM providers
pub async fn run_review_loop_multi(
    multi_llm: MultiModelManager,
    _config: Config,
    _ravenfabric: Option<RavenFabricClient>,
    pattern_config: PatternConfig,
) -> crate::error::Result<()> {
    info!("Starting review-loop mode (multi-model)");

    let _system_prompt = &_config.llm.system_prompt;
    let _ = &_system_prompt;
    let task = "Analyze the given task and provide your solution.";

    let producer_persona = "You are a producer. Create high-quality content.";
    let reviewer_persona = "You are a reviewer. Critically evaluate content. Respond with APPROVED: when quality is met.";

    let mut current_content = String::new();
    let mut approved = false;

    for iteration in 0..pattern_config.max_review_iterations {
        info!(iteration = iteration + 1, "Multi-model review-loop");

        let provider_idx = iteration % multi_llm.client_count();
        let client = multi_llm.get_client(provider_idx);

        if let Some(client) = client {
            if iteration == 0 {
                let mut memory = ConversationMemory::new(producer_persona, 10);
                memory.add_user_message(&format!("Create content for: {}", task));
                let messages = memory.history().to_vec();
                match client.chat(messages).await {
                    Ok(response) => {
                        if let Some(choice) = response.choices.first() {
                            current_content = choice.message.content.clone();
                            info!(
                                "Initial content: {} chars via {}",
                                current_content.len(),
                                client.provider_name()
                            );
                        }
                    }
                    Err(e) => warn!(error = %e, "Producer failed"),
                }
            } else {
                // Review
                let mut rev_memory = ConversationMemory::new(reviewer_persona, 10);
                rev_memory.add_user_message(&format!("Review:\n\n{}", current_content));
                let messages = rev_memory.history().to_vec();
                match client.chat(messages).await {
                    Ok(response) => {
                        if let Some(choice) = response.choices.first() {
                            let review = &choice.message.content;
                            if review.contains("APPROVED:") {
                                info!(
                                    "Approved after {} iterations via {}",
                                    iteration + 1,
                                    client.provider_name()
                                );
                                current_content = review
                                    .split("APPROVED:")
                                    .nth(1)
                                    .unwrap_or(&current_content)
                                    .trim()
                                    .to_string();
                                approved = true;
                                break;
                            }
                            // Revise
                            let mut prod_memory = ConversationMemory::new(producer_persona, 10);
                            prod_memory.add_user_message(&format!(
                                "Content:\n{}\n\nFeedback:\n{}\n\nRevise:",
                                current_content, review
                            ));
                            let msgs = prod_memory.history().to_vec();
                            if let Some(next_client) =
                                multi_llm.get_client((iteration + 1) % multi_llm.client_count())
                            {
                                if let Ok(rev_resp) = next_client.chat(msgs).await {
                                    if let Some(rev_choice) = rev_resp.choices.first() {
                                        current_content = rev_choice.message.content.clone();
                                        info!(
                                            "Revised: {} chars via {}",
                                            current_content.len(),
                                            next_client.provider_name()
                                        );
                                    }
                                }
                            }
                        }
                    }
                    Err(e) => warn!(error = %e, "Review failed"),
                }
            }
        }
    }

    if !approved {
        warn!("Review-loop reached max iterations without approval");
    }

    println!("\n🐦‍⬛ Multi-Model Review-Loop Final:\n{}", current_content);
    Ok(())
}

/// Run research-synthesize mode with multiple LLM providers
pub async fn run_research_synthesize_multi(
    multi_llm: MultiModelManager,
    config: Config,
    _ravenfabric: Option<RavenFabricClient>,
    pattern_config: PatternConfig,
) -> crate::error::Result<()> {
    info!("Starting research-synthesize mode (multi-model)");

    let system_prompt = &config.llm.system_prompt;
    let task = "Analyze the given task and provide your solution.";

    let perspectives = [
        (
            "Fact-Finder",
            "Focus on verifiable facts, data, statistics.",
        ),
        (
            "Analyst",
            "Focus on patterns, trends, strategic implications.",
        ),
        (
            "Innovator",
            "Focus on novel approaches and future possibilities.",
        ),
    ];

    let agent_count = pattern_config.research_agent_count.min(perspectives.len());
    let mut results: Vec<(String, String, String)> = Vec::new(); // (role, provider, content)

    for (i, (role, persona)) in perspectives.iter().enumerate().take(agent_count) {
        let client = multi_llm.get_client(i % multi_llm.client_count());

        if let Some(client) = client {
            let mut memory =
                ConversationMemory::new(&format!("{}\n\n{}", system_prompt, persona), 10);
            memory.add_user_message(&format!("Research: {}", task));
            let messages = memory.history().to_vec();

            match client.chat(messages).await {
                Ok(response) => {
                    if let Some(choice) = response.choices.first() {
                        let content = choice.message.content.clone();
                        info!(role = %role, provider = client.provider_name(), "Research completed");
                        results.push((
                            role.to_string(),
                            client.provider_name().to_string(),
                            content,
                        ));
                    }
                }
                Err(e) => warn!(error = %e, role = %role, "Research failed"),
            }
        }
    }

    // Synthesize
    if let Some(client) = multi_llm.get_client(0) {
        let mut synth_memory = ConversationMemory::new("You are a synthesis specialist.", 20);
        let mut input = String::from("Synthesize these findings:\n\n");
        for (role, provider, content) in &results {
            input.push_str(&format!("=== {} ({}) ===\n{}\n", role, provider, content));
        }
        synth_memory.add_user_message(&input);
        let messages = synth_memory.history().to_vec();

        match client.chat(messages).await {
            Ok(response) => {
                if let Some(choice) = response.choices.first() {
                    println!(
                        "\n🐦‍⬛ Multi-Model Research Synthesis:\n{}",
                        choice.message.content
                    );
                }
            }
            Err(e) => warn!(error = %e, "Synthesis failed"),
        }
    }

    Ok(())
}

/// Run voting mode with multiple LLM providers
pub async fn run_voting_multi(
    multi_llm: MultiModelManager,
    config: Config,
    _ravenfabric: Option<RavenFabricClient>,
    pattern_config: PatternConfig,
) -> crate::error::Result<()> {
    info!(
        "Starting voting mode (multi-model) with {} providers",
        multi_llm.client_count()
    );

    let system_prompt = &config.llm.system_prompt;
    let task = "Analyze the given task and provide your solution.";

    let voter_personas = [
        "Conservative: Prefer safe, proven approaches. VOTE: <choice> REASONING: <reasoning>",
        "Aggressive: Prefer bold, ambitious approaches. VOTE: <choice> REASONING: <reasoning>",
        "Balanced: Weigh pros and cons. VOTE: <choice> REASONING: <reasoning>",
        "Detail-oriented: Focus on feasibility. VOTE: <choice> REASONING: <reasoning>",
        "User-centric: Prioritize UX. VOTE: <choice> REASONING: <reasoning>",
    ];

    let voter_count = pattern_config
        .voter_count
        .min(voter_personas.len())
        .min(multi_llm.client_count());
    let mut votes: Vec<(String, String, String, String)> = Vec::new(); // (persona, provider, vote, reasoning)

    for (i, persona) in voter_personas.iter().enumerate().take(voter_count) {
        let client = multi_llm.get_client(i % multi_llm.client_count());

        if let Some(client) = client {
            let mut memory =
                ConversationMemory::new(&format!("{}\n\n{}", system_prompt, persona), 10);
            memory.add_user_message(&format!("Cast your vote on: {}", task));
            let messages = memory.history().to_vec();

            match client.chat(messages).await {
                Ok(response) => {
                    if let Some(choice) = response.choices.first() {
                        let content = choice.message.content.clone();
                        let vote = content
                            .split("VOTE:")
                            .nth(1)
                            .and_then(|s| s.split("REASONING:").next())
                            .map(|s| s.trim().to_string())
                            .unwrap_or_else(|| "Unknown".to_string());
                        let reasoning = content
                            .split("REASONING:")
                            .nth(1)
                            .map(|s| s.trim().to_string())
                            .unwrap_or_default();
                        votes.push((
                            format!("Voter {}", i + 1),
                            client.provider_name().to_string(),
                            vote,
                            reasoning,
                        ));
                    }
                }
                Err(e) => warn!(error = %e, "Voter {} failed", i + 1),
            }
        }
    }

    // Tally
    let mut tally: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
    for (_, _, vote, _) in &votes {
        *tally.entry(vote.clone()).or_insert(0) += 1;
    }

    println!("\n🐦‍⬛ Multi-Model Voting Results:");
    for (persona, provider, vote, reasoning) in &votes {
        println!(
            "{} ({}): VOTE = {} | {}",
            persona, provider, vote, reasoning
        );
    }
    println!("Tally: {:?}", tally);
    println!(
        "🏆 Decision: {}",
        tally
            .iter()
            .max_by_key(|(_, c)| *c)
            .map(|(v, _)| v.clone())
            .unwrap_or_else(|| "No decision".to_string())
    );

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_pattern_config_defaults() {
        let cfg = PatternConfig::default();
        assert_eq!(cfg.max_rounds, 3);
        assert_eq!(cfg.max_review_iterations, 3);
        assert_eq!(cfg.research_agent_count, 3);
        assert_eq!(cfg.voter_count, 3);
        assert!(!cfg.verbose);
    }

    #[test]
    fn test_pattern_config_custom() {
        let cfg = PatternConfig {
            max_rounds: 5,
            max_review_iterations: 5,
            research_agent_count: 5,
            voter_count: 7,
            verbose: true,
        };
        assert_eq!(cfg.max_rounds, 5);
        assert_eq!(cfg.voter_count, 7);
        assert!(cfg.verbose);
    }

    #[test]
    fn test_debate_function_exists() {
        // Compile-time check that debate function signature is valid
        let _ = std::mem::size_of::<PatternConfig>();
    }

    #[test]
    fn test_review_loop_function_exists() {
        let cfg = PatternConfig::default();
        assert_eq!(cfg.max_review_iterations, 3);
    }

    #[test]
    fn test_research_synthesize_function_exists() {
        let cfg = PatternConfig::default();
        assert_eq!(cfg.research_agent_count, 3);
    }

    #[test]
    fn test_voting_function_exists() {
        let cfg = PatternConfig::default();
        assert_eq!(cfg.voter_count, 3);
    }
}