reputation-core 0.1.0

Core calculation engine for the KnowThat Reputation System with advanced scoring algorithms
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
//! Calculator module for reputation score calculation
//! 
//! This module provides the main Calculator struct and coordinates the
//! calculation of reputation scores using submodules for prior, empirical,
//! and confidence calculations.
//! 
//! ## Architecture
//! 
//! The calculator is organized into specialized submodules:
//! - `prior`: Calculates base reputation from agent credentials (50-80 points)
//! - `empirical`: Derives performance score from reviews (0-100 points)
//! - `confidence`: Determines confidence level based on interaction volume
//! - `builder`: Provides fluent API for calculator configuration
//! - `utils`: Utility methods for score analysis and predictions
//! 
//! ## Calculation Flow
//! 
//! 1. **Validation**: Agent data is validated for consistency
//! 2. **Prior Score**: Base score calculated from credentials
//! 3. **Empirical Score**: Performance score from reviews
//! 4. **Confidence**: Weight based on data volume
//! 5. **Final Score**: Weighted combination of prior and empirical
//! 
//! ## Thread Safety
//! 
//! The Calculator is thread-safe and can be shared across threads using Arc:
//! ```no_run
//! use std::sync::Arc;
//! use reputation_core::Calculator;
//! 
//! let calculator = Arc::new(Calculator::default());
//! let calc_clone = Arc::clone(&calculator);
//! 
//! std::thread::spawn(move || {
//!     // Use calc_clone in another thread
//! });
//! ```

use chrono::Utc;
use reputation_types::{AgentData, ReputationScore, ConfidenceLevel, ScoreComponents};
use crate::error::{BuilderError, CalculationError, Result};
use crate::validation;
use crate::config::CalculatorConfig;
use crate::ALGORITHM_VERSION;
use rayon::prelude::*;
use std::time::{Duration, Instant};

mod prior;
mod empirical;
mod confidence;
pub mod builder;
pub mod utils;

// Re-export for internal use
pub(crate) use self::prior::calculate_prior_detailed;
pub(crate) use self::empirical::calculate_empirical;
pub(crate) use self::confidence::calculate_confidence;

/// Calculates reputation scores for MCP agents
/// 
/// The Calculator implements a hybrid scoring system that combines
/// prior reputation (based on credentials) with empirical performance
/// (based on reviews and interactions).
/// 
/// # Example
/// ```
/// use reputation_core::Calculator;
/// use reputation_types::AgentDataBuilder;
/// 
/// let calculator = Calculator::default();
/// let agent = AgentDataBuilder::new("did:example:test")
///     .with_reviews(50, 4.0)
///     .total_interactions(100)  // Must be >= total_reviews
///     .build()
///     .unwrap();
/// 
/// let score = calculator.calculate(&agent).unwrap();
/// assert!(score.score >= 0.0 && score.score <= 100.0);
/// ```
#[derive(Debug)]
pub struct Calculator {
    /// Confidence growth parameter (k in the formula)
    /// Higher values = slower confidence growth
    pub(crate) confidence_k: f64,
    
    /// Base prior score (starting reputation)
    pub(crate) prior_base: f64,
    
    /// Maximum prior score (cap for credential bonuses)
    pub(crate) prior_max: f64,
}

impl Default for Calculator {
    fn default() -> Self {
        Self {
            confidence_k: 15.0,
            prior_base: 50.0,
            prior_max: 80.0,
        }
    }
}

impl Calculator {
    /// Get the confidence growth parameter
    pub fn confidence_k(&self) -> f64 {
        self.confidence_k
    }
    
    /// Get the base prior score
    pub fn prior_base(&self) -> f64 {
        self.prior_base
    }
    
    /// Get the maximum prior score
    pub fn prior_max(&self) -> f64 {
        self.prior_max
    }
    /// Creates a builder for constructing a Calculator with custom configuration
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// 
    /// let calculator = Calculator::builder()
    ///     .confidence_k(20.0)
    ///     .prior_base(60.0)
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn builder() -> builder::CalculatorBuilder {
        builder::CalculatorBuilder::new()
    }
    
    /// Creates a Calculator from a configuration
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::{Calculator, CalculatorConfig};
    /// 
    /// let config = CalculatorConfig {
    ///     confidence_k: 20.0,
    ///     prior_base: 60.0,
    ///     prior_max: 85.0,
    /// };
    /// let calculator = Calculator::from_config(config).unwrap();
    /// ```
    pub fn from_config(config: CalculatorConfig) -> Result<Self> {
        Self::new(config.confidence_k, config.prior_base, config.prior_max)
    }
    
    /// Creates a new Calculator with custom parameters
    /// 
    /// # Parameters
    /// 
    /// - `confidence_k`: Controls confidence growth rate (must be positive)
    /// - `prior_base`: Base prior score (must be 0-100)
    /// - `prior_max`: Maximum prior score cap (must be between prior_base and 100)
    /// 
    /// # Errors
    /// 
    /// Returns an error if parameters are out of valid ranges
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// 
    /// let calculator = Calculator::new(20.0, 60.0, 90.0).unwrap();
    /// ```
    pub fn new(confidence_k: f64, prior_base: f64, prior_max: f64) -> Result<Self> {
        if confidence_k <= 0.0 {
            return Err(BuilderError::InvalidConfig("confidence_k must be positive".to_string()).into());
        }
        if prior_base < 0.0 || prior_base > 100.0 {
            return Err(BuilderError::InvalidConfig("prior_base must be between 0 and 100".to_string()).into());
        }
        if prior_max < prior_base || prior_max > 100.0 {
            return Err(BuilderError::InvalidConfig("prior_max must be between prior_base and 100".to_string()).into());
        }

        Ok(Self {
            confidence_k,
            prior_base,
            prior_max,
        })
    }

    /// Calculates the reputation score for an agent
    /// 
    /// # Algorithm Details
    /// 
    /// 1. **Prior Score Calculation** (50-80 points by default):
    ///    - Base: 50 points
    ///    - MCP Level bonus: 0-15 points (5 per level)
    ///    - Identity verified: +5 points
    ///    - Security audit: +7 points
    ///    - Open source: +3 points
    ///    - Age > 365 days: +5 points
    /// 
    /// 2. **Empirical Score** (0-100 points):
    ///    - Based on average rating (1-5 stars)
    ///    - Converted to 0-100 scale
    /// 
    /// 3. **Confidence Calculation**:
    ///    - Based on total interactions
    ///    - Approaches 1.0 asymptotically
    /// 
    /// # Returns
    /// 
    /// A `ReputationScore` containing:
    /// - `score`: Final reputation (0-100)
    /// - `confidence`: Confidence in the score (0-1)
    /// - `algorithm_version`: Version of the algorithm used
    /// - `calculated_at`: Timestamp of calculation
    /// 
    /// # Errors
    /// 
    /// Returns an error if:
    /// - Agent data validation fails
    /// - Calculation produces NaN or out-of-bounds values
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// use reputation_types::AgentDataBuilder;
    /// 
    /// let calculator = Calculator::default();
    /// let agent = AgentDataBuilder::new("did:example:123")
    ///     .with_reviews(100, 4.5)
    ///     .total_interactions(200)  // Must be >= total_reviews
    ///     .identity_verified(true)
    ///     .build()
    ///     .unwrap();
    /// 
    /// let score = calculator.calculate(&agent).unwrap();
    /// match score.confidence {
    ///     c if c < 0.3 => println!("Low confidence - needs more data"),
    ///     c if c < 0.7 => println!("Moderate confidence"),
    ///     _ => println!("High confidence in score"),
    /// }
    /// ```
    pub fn calculate(&self, agent: &AgentData) -> Result<ReputationScore> {
        // Validate agent data
        validation::validate_agent_data(agent)?;

        // Calculate components with detailed breakdown
        let prior_breakdown = calculate_prior_detailed(agent, self.prior_base, self.prior_max);
        let prior_score = prior_breakdown.total;
        let empirical_score = calculate_empirical(agent);
        let confidence_value = calculate_confidence(agent.total_interactions, self.confidence_k)?;
        
        // Determine confidence level
        let confidence_level = ConfidenceLevel::from_confidence(confidence_value);
        
        // Calculate weights
        let prior_weight = 1.0 - confidence_value;
        let empirical_weight = confidence_value;

        // Blend scores
        let final_score = prior_weight * prior_score + empirical_weight * empirical_score;

        // Validate final score
        if final_score.is_nan() {
            return Err(CalculationError::NaNResult.into());
        }
        if final_score < 0.0 || final_score > 100.0 {
            return Err(CalculationError::ScoreOutOfBounds(final_score).into());
        }

        // Create score components
        let components = ScoreComponents {
            prior_score,
            prior_breakdown,
            empirical_score,
            confidence_value,
            confidence_level,
            prior_weight,
            empirical_weight,
        };

        // Calculate total data points
        let data_points = agent.total_interactions.saturating_add(agent.total_reviews);
        
        // Determine if provisional
        let is_provisional = confidence_value < 0.2;

        Ok(ReputationScore {
            score: final_score.clamp(0.0, 100.0),
            confidence: confidence_value,
            level: confidence_level,
            components,
            is_provisional,
            data_points,
            algorithm_version: ALGORITHM_VERSION.to_string(),
            calculated_at: Utc::now(),
        })
    }

    /// Calculate reputation scores for multiple agents in parallel
    /// 
    /// This method uses rayon to process agents in parallel, providing
    /// significant performance improvements for large batches.
    /// 
    /// # Returns
    /// 
    /// A vector of results in the same order as the input agents.
    /// Each result contains either a ReputationScore or an error.
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// use reputation_types::AgentDataBuilder;
    /// 
    /// let calculator = Calculator::default();
    /// let agents: Vec<_> = (0..100).map(|i| {
    ///     AgentDataBuilder::new(&format!("did:example:agent{}", i))
    ///         .with_reviews(50, 4.0)
    ///         .total_interactions(100)
    ///         .build()
    ///         .unwrap()
    /// }).collect();
    /// 
    /// let results = calculator.calculate_batch(&agents);
    /// assert_eq!(results.len(), agents.len());
    /// ```
    pub fn calculate_batch(&self, agents: &[AgentData]) -> Vec<Result<ReputationScore>> {
        agents
            .par_iter()
            .map(|agent| self.calculate(agent))
            .collect()
    }

    /// Calculate reputation scores with batch processing options
    /// 
    /// This method provides more control over batch processing with options
    /// for chunk size, progress tracking, and detailed timing information.
    /// 
    /// # Arguments
    /// 
    /// * `agents` - Slice of agents to calculate scores for
    /// * `options` - Configuration options for batch processing
    /// 
    /// # Returns
    /// 
    /// A `BatchResult` containing:
    /// - Individual calculation results with timing
    /// - Total processing duration
    /// - Success/failure counts
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::{Calculator, BatchOptions};
    /// use reputation_types::AgentDataBuilder;
    /// 
    /// let calculator = Calculator::default();
    /// let agents: Vec<_> = (0..1000).map(|i| {
    ///     AgentDataBuilder::new(&format!("did:example:agent{}", i))
    ///         .with_reviews(50, 4.0)
    ///         .total_interactions(100)
    ///         .build()
    ///         .unwrap()
    /// }).collect();
    /// 
    /// let options = BatchOptions {
    ///     chunk_size: Some(100),
    ///     fail_fast: false,
    ///     progress_callback: None,
    /// };
    /// 
    /// let result = calculator.calculate_batch_with_options(&agents, options);
    /// println!("Processed {} agents in {:?}", agents.len(), result.total_duration);
    /// println!("Success: {}, Failed: {}", result.successful_count, result.failed_count);
    /// ```
    pub fn calculate_batch_with_options(
        &self,
        agents: &[AgentData],
        options: BatchOptions,
    ) -> BatchResult {
        let batch_start = Instant::now();
        let chunk_size = options.chunk_size.unwrap_or(100);
        
        let calculations: Vec<_> = if let Some(ref callback) = options.progress_callback {
            let processed = std::sync::atomic::AtomicUsize::new(0);
            let total = agents.len();
            
            agents
                .par_chunks(chunk_size)
                .flat_map(|chunk| {
                    chunk.par_iter().map(|agent| {
                        let start = Instant::now();
                        let result = self.calculate(agent);
                        let duration = start.elapsed();
                        
                        if options.fail_fast && result.is_err() {
                            // In fail_fast mode, we'd need a more complex implementation
                            // to actually stop all threads. For now, we just continue.
                        }
                        
                        let calc = BatchCalculation {
                            agent_id: agent.did.clone(),
                            result,
                            duration,
                        };
                        
                        // Update progress
                        let current = processed.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1;
                        callback(current, total);
                        
                        calc
                    })
                })
                .collect()
        } else {
            agents
                .par_chunks(chunk_size)
                .flat_map(|chunk| {
                    chunk.par_iter().map(|agent| {
                        let start = Instant::now();
                        let result = self.calculate(agent);
                        let duration = start.elapsed();
                        
                        BatchCalculation {
                            agent_id: agent.did.clone(),
                            result,
                            duration,
                        }
                    })
                })
                .collect()
        };
        
        let successful_count = calculations.iter().filter(|c| c.result.is_ok()).count();
        let failed_count = calculations.len() - successful_count;
        
        BatchResult {
            calculations,
            total_duration: batch_start.elapsed(),
            successful_count,
            failed_count,
        }
    }
}

/// Options for batch processing
pub struct BatchOptions {
    /// Size of chunks for parallel processing
    pub chunk_size: Option<usize>,
    /// Whether to stop on first error (not fully implemented)
    pub fail_fast: bool,
    /// Optional callback for progress updates
    pub progress_callback: Option<Box<dyn Fn(usize, usize) + Send + Sync>>,
}

impl Default for BatchOptions {
    fn default() -> Self {
        Self {
            chunk_size: None,
            fail_fast: false,
            progress_callback: None,
        }
    }
}

impl std::fmt::Debug for BatchOptions {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("BatchOptions")
            .field("chunk_size", &self.chunk_size)
            .field("fail_fast", &self.fail_fast)
            .field("progress_callback", &self.progress_callback.is_some())
            .finish()
    }
}

/// Result of batch processing
#[derive(Debug)]
pub struct BatchResult {
    /// Individual calculation results
    pub calculations: Vec<BatchCalculation>,
    /// Total time taken for batch processing
    pub total_duration: Duration,
    /// Number of successful calculations
    pub successful_count: usize,
    /// Number of failed calculations
    pub failed_count: usize,
}

/// Individual calculation result in a batch
#[derive(Debug)]
pub struct BatchCalculation {
    /// Agent DID
    pub agent_id: String,
    /// Calculation result
    pub result: Result<ReputationScore>,
    /// Time taken for this calculation
    pub duration: Duration,
}