paladin-ai-core 0.5.1

Pure domain types for the Paladin framework — zero infrastructure dependencies
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
//! Conclave Domain Entity
//!
//! Conclave implements the MixtureOfAgents (MoA) orchestration pattern where multiple
//! expert Paladins process the same task in parallel from different perspectives, and
//! a designated aggregator Paladin synthesizes their outputs into a single,
//! high-quality response.
//!
//! This pattern is particularly useful for:
//! - Complex decision-making requiring multiple expert perspectives
//! - Code review with security, performance, and maintainability analysis
//! - Strategy evaluation from technical, business, and risk viewpoints
//! - Research synthesis combining multiple analytical approaches
//!
//! # Example
//!
//! ```ignore
//! use paladin_core::platform::container::battalion::conclave::{Conclave, ConclaveConfig};
//! use paladin_core::platform::container::battalion::BattalionConfig;
//!
//! let battalion_config = BattalionConfig::new("expert_panel");
//! let conclave_config = ConclaveConfig::new("TechnicalAnalysis", battalion_config);
//!
//! let experts = vec![technical_expert, business_expert, security_expert];
//! let aggregator = chief_analyst;
//!
//! let conclave = Conclave::new(
//!     experts,
//!     aggregator,
//!     conclave_config,
//! ).expect("Valid conclave");
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::{BattalionConfig, BattalionError};
use crate::platform::container::execution_result::PaladinResult;
use crate::platform::container::paladin::Paladin;

/// Observability level for Conclave execution
///
/// Controls the level of detail in logging and metrics collection during
/// Conclave execution. Higher levels provide more detailed information but
/// may impact performance.
///
/// # Levels
///
/// - **Minimal**: Only final aggregated result and overall status
/// - **Standard**: Execution time per expert, total time, retry counts, success/failure status
/// - **Verbose**: Full expert outputs, token usage, LLM provider details, timestamps
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ObservabilityLevel {
    /// Minimal observability - only final result and status
    Minimal,

    /// Standard observability - execution metrics and status per expert
    #[default]
    Standard,

    /// Verbose observability - full details including outputs and token usage
    Verbose,
}

/// Configuration for Conclave orchestration
///
/// Defines the behavior and settings for a Conclave execution including retry logic,
/// timeout, synthesis prompt customization, and observability level.
///
/// # Examples
///
/// ```
/// use paladin_core::platform::container::battalion::conclave::{ConclaveConfig, ObservabilityLevel};
/// use paladin_core::platform::container::battalion::BattalionConfig;
///
/// let battalion_config = BattalionConfig::new("expert_panel");
/// let mut config = ConclaveConfig::new("Analysis", battalion_config);
///
/// config = config
///     .with_retry_attempts(3)
///     .with_timeout(600)
///     .with_observability(ObservabilityLevel::Verbose)
///     .with_expert_names(true);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConclaveConfig {
    /// Name of the Conclave
    pub name: String,

    /// Base Battalion configuration
    pub battalion_config: BattalionConfig,

    /// Timeout for entire Conclave execution in seconds
    pub timeout_seconds: u64,

    /// Number of retry attempts for failed experts (0-5)
    pub retry_attempts: u32,

    /// Custom synthesis prompt template for aggregator
    ///
    /// If None, a default template will be used. The template can include
    /// placeholders that will be replaced with actual values:
    /// - `{original_task}`: The original input task
    /// - `{expert_outputs}`: Formatted expert outputs
    pub synthesis_prompt: Option<String>,

    /// Include expert names in aggregator prompt
    pub include_expert_names: bool,

    /// Maximum tokens per expert output (prevents excessive context)
    pub max_expert_output_tokens: Option<usize>,

    /// Observability level for logging and metrics
    pub observability_level: ObservabilityLevel,
}

impl ConclaveConfig {
    /// Create a new ConclaveConfig with default settings
    ///
    /// # Arguments
    ///
    /// * `name` - Name identifier for this Conclave
    /// * `battalion_config` - Base Battalion configuration
    ///
    /// # Default Values
    ///
    /// - `timeout_seconds`: 300 (5 minutes)
    /// - `retry_attempts`: 2
    /// - `synthesis_prompt`: None (uses default template)
    /// - `include_expert_names`: true
    /// - `max_expert_output_tokens`: None (no limit)
    /// - `observability_level`: Standard
    pub fn new(name: impl Into<String>, battalion_config: BattalionConfig) -> Self {
        Self {
            name: name.into(),
            battalion_config,
            timeout_seconds: 300,
            retry_attempts: 2,
            synthesis_prompt: None,
            include_expert_names: true,
            max_expert_output_tokens: None,
            observability_level: ObservabilityLevel::default(),
        }
    }

    /// Set timeout in seconds (builder pattern)
    pub fn with_timeout(mut self, seconds: u64) -> Self {
        self.timeout_seconds = seconds;
        self
    }

    /// Set retry attempts (builder pattern)
    ///
    /// Valid range: 0-5 attempts. Values outside this range will be clamped.
    pub fn with_retry_attempts(mut self, attempts: u32) -> Self {
        self.retry_attempts = attempts.min(5);
        self
    }

    /// Set custom synthesis prompt template (builder pattern)
    pub fn with_synthesis_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.synthesis_prompt = Some(prompt.into());
        self
    }

    /// Set whether to include expert names in aggregator prompt (builder pattern)
    pub fn with_expert_names(mut self, include: bool) -> Self {
        self.include_expert_names = include;
        self
    }

    /// Set maximum expert output tokens (builder pattern)
    pub fn with_max_expert_tokens(mut self, max_tokens: usize) -> Self {
        self.max_expert_output_tokens = Some(max_tokens);
        self
    }

    /// Set observability level (builder pattern)
    pub fn with_observability(mut self, level: ObservabilityLevel) -> Self {
        self.observability_level = level;
        self
    }
}

/// Conclave orchestration pattern
///
/// A Conclave executes multiple expert Paladins in parallel on the same task,
/// then synthesizes their outputs through an aggregator Paladin. This implements
/// the MixtureOfAgents pattern for high-quality response generation through
/// expert consensus.
///
/// # Minimum Requirements
///
/// - At least 2 expert Paladins
/// - Exactly 1 aggregator Paladin
/// - All Paladins must have unique names
///
/// # Example
///
/// ```ignore
/// use paladin_core::platform::container::battalion::conclave::Conclave;
///
/// let conclave = Conclave::new(
///     vec![expert1, expert2, expert3],
///     aggregator,
///     config,
/// )?;
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Conclave {
    /// Expert Paladins that analyze the task in parallel
    pub experts: Vec<Paladin>,

    /// Aggregator Paladin that synthesizes expert outputs
    pub aggregator: Paladin,

    /// Configuration for this Conclave
    pub config: ConclaveConfig,
}

impl Conclave {
    /// Create a new Conclave with the given experts, aggregator, and configuration
    ///
    /// # Arguments
    ///
    /// * `experts` - Vector of expert Paladins (minimum 2)
    /// * `aggregator` - Aggregator Paladin for synthesis
    /// * `config` - Conclave configuration
    ///
    /// # Returns
    ///
    /// * `Ok(Conclave)` - Successfully created Conclave
    /// * `Err(BattalionError::ValidationError)` - If validation fails
    ///
    /// # Validation Rules
    ///
    /// - At least 2 expert Paladins required
    /// - All expert names must be unique
    /// - Aggregator name must be unique from all experts
    ///
    /// # Example
    ///
    /// ```ignore
    /// let conclave = Conclave::new(
    ///     vec![technical_expert, business_expert],
    ///     synthesizer,
    ///     config,
    /// )?;
    /// ```
    pub fn new(
        experts: Vec<Paladin>,
        aggregator: Paladin,
        config: ConclaveConfig,
    ) -> Result<Self, BattalionError> {
        let conclave = Self {
            experts,
            aggregator,
            config,
        };

        conclave.validate()?;
        Ok(conclave)
    }

    /// Validate the Conclave configuration
    ///
    /// Ensures:
    /// - At least 2 expert Paladins
    /// - All Paladin names are unique (including aggregator)
    /// - Configuration values are within valid ranges
    ///
    /// # Errors
    ///
    /// Returns `BattalionError::ValidationError` if any validation rule fails.
    pub fn validate(&self) -> Result<(), BattalionError> {
        // Check minimum number of experts
        if self.experts.len() < 2 {
            return Err(BattalionError::ValidationError(format!(
                "Conclave requires at least 2 experts, found {}",
                self.experts.len()
            )));
        }

        // Check for duplicate names among experts
        let mut expert_names = std::collections::HashSet::new();
        for expert in &self.experts {
            let name = &expert.node.name;
            if !expert_names.insert(name.clone()) {
                return Err(BattalionError::ValidationError(format!(
                    "Duplicate expert name: '{}'",
                    name
                )));
            }
        }

        // Check aggregator name doesn't conflict with expert names
        let aggregator_name = &self.aggregator.node.name;
        if expert_names.contains(aggregator_name) {
            return Err(BattalionError::ValidationError(format!(
                "Aggregator name '{}' conflicts with an expert name",
                aggregator_name
            )));
        }

        // Validate retry attempts is within acceptable range
        if self.config.retry_attempts > 5 {
            return Err(BattalionError::ValidationError(format!(
                "Retry attempts must be 0-5, found {}",
                self.config.retry_attempts
            )));
        }

        // Validate timeout is reasonable
        if self.config.timeout_seconds < 10 {
            return Err(BattalionError::ValidationError(
                "Timeout must be at least 10 seconds".to_string(),
            ));
        }

        if self.config.timeout_seconds > 3600 {
            return Err(BattalionError::ValidationError(
                "Timeout cannot exceed 3600 seconds (1 hour)".to_string(),
            ));
        }

        Ok(())
    }

    /// Get the name of this Conclave from configuration
    pub fn name(&self) -> &str {
        &self.config.name
    }

    /// Get the number of experts in this Conclave
    pub fn expert_count(&self) -> usize {
        self.experts.len()
    }
}

/// Status of Conclave execution
///
/// Indicates the overall outcome of a Conclave execution, taking into account
/// both expert execution results and aggregator success.
///
/// # Status Values
///
/// - **Success**: All experts succeeded and aggregator produced output
/// - **PartialSuccess**: Some experts failed but aggregator synthesized available outputs
/// - **Failed**: Critical failure (all experts failed or aggregator failed)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ConclaveStatus {
    /// All experts succeeded and aggregation completed successfully
    Success,

    /// Some experts failed but enough succeeded for aggregation to proceed
    PartialSuccess,

    /// Critical failure - either all experts failed or aggregator failed
    Failed,
}

/// Result of Conclave execution
///
/// Contains the outputs from all experts, the aggregated result, execution metrics,
/// and status information. This provides complete visibility into the Conclave execution
/// for analysis and debugging.
///
/// # Example
///
/// ```ignore
/// let result: ConclaveResult = conclave_service.execute(&conclave, input).await?;
///
/// println!("Status: {:?}", result.status);
/// println!("Total time: {}ms", result.execution_time_ms);
/// println!("Successful experts: {}/{}", result.successful_expert_count(), result.expert_outputs.len());
///
/// for (name, output) in &result.expert_outputs {
///     println!("Expert '{}': {}", name, output.content);
/// }
///
/// println!("Aggregated: {}", result.aggregated_output.content);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConclaveResult {
    /// Outputs from each expert, keyed by expert name
    pub expert_outputs: HashMap<String, PaladinResult>,

    /// Synthesized output from the aggregator
    pub aggregated_output: PaladinResult,

    /// Total execution time in milliseconds
    pub execution_time_ms: u64,

    /// Execution time per expert in milliseconds
    pub expert_execution_times: HashMap<String, u64>,

    /// Number of retry attempts per expert
    pub retry_counts: HashMap<String, u32>,

    /// Overall execution status
    pub status: ConclaveStatus,
}

impl ConclaveResult {
    /// Count of experts that succeeded
    pub fn successful_expert_count(&self) -> usize {
        self.expert_outputs.len()
    }

    /// Check if all experts succeeded
    pub fn all_experts_succeeded(&self) -> bool {
        self.status == ConclaveStatus::Success
    }

    /// Check if execution completed (even with partial success)
    pub fn is_completed(&self) -> bool {
        matches!(
            self.status,
            ConclaveStatus::Success | ConclaveStatus::PartialSuccess
        )
    }
}

/// Error types specific to Conclave operations
///
/// These errors extend the base `BattalionError` with Conclave-specific failure modes.
#[derive(Debug, Clone, thiserror::Error)]
pub enum ConclaveError {
    /// All expert Paladins failed after retry attempts
    #[error("All experts failed after retries")]
    AllExpertsFailed,

    /// Aggregator Paladin failed to synthesize outputs
    #[error("Aggregator failed: {0}")]
    AggregatorFailed(String),

    /// Configuration error specific to Conclave
    #[error("Configuration error: {0}")]
    ConfigurationError(String),

    /// Execution timed out
    #[error("Execution timeout after {0} seconds")]
    Timeout(u64),

    /// Specific expert failed
    #[error("Expert '{0}' failed: {1}")]
    ExpertError(String, String),
}

// Conversion from ConclaveError to BattalionError for error propagation
impl From<ConclaveError> for BattalionError {
    fn from(error: ConclaveError) -> Self {
        match error {
            ConclaveError::AllExpertsFailed => {
                BattalionError::ValidationError("All experts failed".to_string())
            }
            ConclaveError::AggregatorFailed(msg) => BattalionError::AggregationError(msg),
            ConclaveError::ConfigurationError(msg) => BattalionError::ConfigurationError(msg),
            ConclaveError::Timeout(seconds) => BattalionError::Timeout(seconds),
            ConclaveError::ExpertError(name, msg) => {
                BattalionError::PaladinError(format!("Expert '{}': {}", name, msg))
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base::entity::node::Node;
    use crate::platform::container::paladin::{MaxLoops, PaladinData, PaladinStatus};

    fn create_test_paladin(name: &str) -> Paladin {
        let paladin_data = PaladinData {
            system_prompt: format!("You are {}", name),
            name: name.to_string(),
            user_name: "TestUser".to_string(),
            model: "gpt-4o".to_string(),
            temperature: 0.7,
            max_loops: MaxLoops::Fixed(1),
            stop_words: vec![],
            status: PaladinStatus::Idle,
            vision_enabled: false,
            ..Default::default()
        };

        Node::new(paladin_data, Some(name.to_string()))
    }

    fn create_test_config() -> ConclaveConfig {
        let battalion_config = BattalionConfig::new("test_conclave");
        ConclaveConfig::new("TestConclave", battalion_config)
    }

    #[test]
    fn test_conclave_creation_success() {
        let experts = vec![
            create_test_paladin("Expert1"),
            create_test_paladin("Expert2"),
            create_test_paladin("Expert3"),
        ];
        let aggregator = create_test_paladin("Aggregator");
        let config = create_test_config();

        let result = Conclave::new(experts, aggregator, config);
        assert!(result.is_ok());

        let conclave = result.unwrap();
        assert_eq!(conclave.expert_count(), 3);
        assert_eq!(conclave.name(), "TestConclave");
    }

    #[test]
    fn test_conclave_insufficient_experts() {
        let experts = vec![create_test_paladin("Expert1")];
        let aggregator = create_test_paladin("Aggregator");
        let config = create_test_config();

        let result = Conclave::new(experts, aggregator, config);
        assert!(result.is_err());

        if let Err(BattalionError::ValidationError(msg)) = result {
            assert!(msg.contains("at least 2 experts"));
        } else {
            panic!("Expected ValidationError");
        }
    }

    #[test]
    fn test_conclave_duplicate_expert_names() {
        let experts = vec![
            create_test_paladin("Expert1"),
            create_test_paladin("Expert1"), // Duplicate
            create_test_paladin("Expert3"),
        ];
        let aggregator = create_test_paladin("Aggregator");
        let config = create_test_config();

        let result = Conclave::new(experts, aggregator, config);
        assert!(result.is_err());

        if let Err(BattalionError::ValidationError(msg)) = result {
            assert!(msg.contains("Duplicate expert name"));
        } else {
            panic!("Expected ValidationError");
        }
    }

    #[test]
    fn test_conclave_aggregator_name_conflicts() {
        let experts = vec![
            create_test_paladin("Expert1"),
            create_test_paladin("Expert2"),
        ];
        let aggregator = create_test_paladin("Expert1"); // Same name as expert
        let config = create_test_config();

        let result = Conclave::new(experts, aggregator, config);
        assert!(result.is_err());

        if let Err(BattalionError::ValidationError(msg)) = result {
            assert!(msg.contains("conflicts with an expert name"));
        } else {
            panic!("Expected ValidationError");
        }
    }

    #[test]
    fn test_conclave_config_builder() {
        let battalion_config = BattalionConfig::new("test");
        let config = ConclaveConfig::new("TestConclave", battalion_config)
            .with_timeout(600)
            .with_retry_attempts(3)
            .with_expert_names(false)
            .with_observability(ObservabilityLevel::Verbose)
            .with_synthesis_prompt("Custom prompt");

        assert_eq!(config.timeout_seconds, 600);
        assert_eq!(config.retry_attempts, 3);
        assert!(!config.include_expert_names);
        assert_eq!(config.observability_level, ObservabilityLevel::Verbose);
        assert!(config.synthesis_prompt.is_some());
    }

    #[test]
    fn test_conclave_config_retry_attempts_clamping() {
        let battalion_config = BattalionConfig::new("test");
        let config = ConclaveConfig::new("TestConclave", battalion_config).with_retry_attempts(10); // Exceeds maximum

        assert_eq!(config.retry_attempts, 5); // Should be clamped to 5
    }

    #[test]
    fn test_conclave_timeout_validation() {
        let experts = vec![
            create_test_paladin("Expert1"),
            create_test_paladin("Expert2"),
        ];
        let aggregator = create_test_paladin("Aggregator");

        // Test timeout too small
        let battalion_config = BattalionConfig::new("test");
        let mut config = ConclaveConfig::new("TestConclave", battalion_config);
        config.timeout_seconds = 5; // Too small

        let result = Conclave::new(experts.clone(), aggregator.clone(), config);
        assert!(result.is_err());

        // Test timeout too large
        let battalion_config = BattalionConfig::new("test");
        let mut config = ConclaveConfig::new("TestConclave", battalion_config);
        config.timeout_seconds = 4000; // Too large

        let result = Conclave::new(experts, aggregator, config);
        assert!(result.is_err());
    }

    #[test]
    fn test_observability_level_default() {
        assert_eq!(ObservabilityLevel::default(), ObservabilityLevel::Standard);
    }

    #[test]
    fn test_conclave_status_equality() {
        assert_eq!(ConclaveStatus::Success, ConclaveStatus::Success);
        assert_ne!(ConclaveStatus::Success, ConclaveStatus::Failed);
        assert_ne!(ConclaveStatus::Success, ConclaveStatus::PartialSuccess);
    }

    #[test]
    fn test_conclave_error_conversion() {
        let conclave_error = ConclaveError::AllExpertsFailed;
        let battalion_error: BattalionError = conclave_error.into();

        match battalion_error {
            BattalionError::ValidationError(msg) => {
                assert!(msg.contains("All experts failed"));
            }
            _ => panic!("Expected ValidationError"),
        }
    }
}