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
//! Utility methods for reputation score analysis and predictions
//! 
//! Provides helpful methods for understanding scores, planning interactions,
//! and comparing agents.

use crate::{Calculator, Result, CalculationError};
use reputation_types::{AgentData, ScoreComponents};
use serde::{Serialize, Deserialize};

/// Detailed explanation of how a score was calculated
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScoreExplanation {
    /// The final calculated score
    pub final_score: f64,
    /// The confidence level (0-1)
    pub confidence: f64,
    /// Human-readable explanation
    pub explanation: String,
    /// Detailed score breakdown
    pub breakdown: ScoreComponents,
}

/// Prediction of score changes from additional reviews
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScorePrediction {
    /// Current reputation score
    pub current_score: f64,
    /// Predicted score after new reviews
    pub predicted_score: f64,
    /// Change in score (can be negative)
    pub score_change: f64,
    /// Change in confidence level
    pub confidence_change: f64,
    /// Number of reviews to be added
    pub reviews_added: u32,
    /// Average rating of new reviews
    pub rating_used: f64,
}

/// Comparison between two agents' reputation scores
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentComparison {
    /// DID of first agent
    pub agent_a_id: String,
    /// DID of second agent
    pub agent_b_id: String,
    /// Score of first agent
    pub score_a: f64,
    /// Score of second agent
    pub score_b: f64,
    /// Difference in scores (A - B)
    pub score_difference: f64,
    /// Confidence level of first agent
    pub confidence_a: f64,
    /// Confidence level of second agent
    pub confidence_b: f64,
    /// DID of agent with higher score
    pub higher_score_agent: String,
    /// DID of agent with higher confidence (more reliable)
    pub more_reliable_agent: String,
}

impl Calculator {
    /// Calculate how many additional interactions are needed to reach a target confidence level
    /// 
    /// # Arguments
    /// 
    /// * `current` - Current number of interactions
    /// * `target` - Target confidence level (0.0 to 1.0)
    /// 
    /// # Returns
    /// 
    /// Number of additional interactions needed
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// 
    /// let calc = Calculator::default();
    /// 
    /// // How many more interactions to reach 90% confidence?
    /// let needed = calc.interactions_for_confidence(50, 0.9).unwrap();
    /// println!("Need {} more interactions for 90% confidence", needed);
    /// ```
    pub fn interactions_for_confidence(&self, current: u32, target: f64) -> Result<u32> {
        if target < 0.0 || target > 1.0 {
            return Err(CalculationError::InvalidConfidence(target).into());
        }
        
        // Handle edge cases
        if target == 0.0 {
            return Ok(0);
        }
        if target == 1.0 {
            // Can never reach exactly 1.0
            return Err(CalculationError::InvalidConfidence(target).into());
        }
        
        // Solve for n: target = n / (n + k)
        // Rearranging: n = (target * k) / (1 - target)
        let required_total = (target * self.confidence_k) / (1.0 - target);
        let required_total = required_total.ceil() as u32;
        
        // Return additional interactions needed
        Ok(required_total.saturating_sub(current))
    }
    
    /// Calculate what the confidence level will be after additional interactions
    /// 
    /// # Arguments
    /// 
    /// * `current` - Current number of interactions
    /// * `additional` - Additional interactions to add
    /// 
    /// # Returns
    /// 
    /// The confidence level after the additional interactions
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// 
    /// let calc = Calculator::default();
    /// 
    /// // What will confidence be after 50 more interactions?
    /// let future_confidence = calc.confidence_after_interactions(100, 50);
    /// println!("Confidence will be {:.1}%", future_confidence * 100.0);
    /// ```
    pub fn confidence_after_interactions(&self, current: u32, additional: u32) -> f64 {
        let total = current.saturating_add(additional) as f64;
        total / (total + self.confidence_k)
    }
    
    /// Explain how a reputation score was calculated in human-readable format
    /// 
    /// Provides a detailed breakdown of all components that went into the score.
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// use reputation_types::AgentDataBuilder;
    /// 
    /// let calc = Calculator::default();
    /// let agent = AgentDataBuilder::new("did:example:123")
    ///     .with_reviews(50, 4.2)
    ///     .total_interactions(100)
    ///     .mcp_level(2)
    ///     .identity_verified(true)
    ///     .build()
    ///     .unwrap();
    /// 
    /// let explanation = calc.explain_score(&agent).unwrap();
    /// println!("{}", explanation.explanation);
    /// ```
    pub fn explain_score(&self, agent: &AgentData) -> Result<ScoreExplanation> {
        let score = self.calculate(agent)?;
        
        // Build detailed explanation
        let mut explanation_parts = vec![
            format!("Reputation score of {:.1} calculated from:", score.score),
            format!(""),
            format!("📊 Score Components:"),
            format!("• Prior score: {:.1} points", score.components.prior_score),
        ];
        
        // Add prior breakdown details
        let prior = &score.components.prior_breakdown;
        explanation_parts.push(format!("  - Base score: {:.1}", prior.base_score));
        if prior.mcp_bonus > 0.0 {
            explanation_parts.push(format!("  - MCP bonus: +{:.1}", prior.mcp_bonus));
        }
        if prior.identity_bonus > 0.0 {
            explanation_parts.push(format!("  - Identity verified: +{:.1}", prior.identity_bonus));
        }
        if prior.security_audit_bonus > 0.0 {
            explanation_parts.push(format!("  - Security audit: +{:.1}", prior.security_audit_bonus));
        }
        if prior.open_source_bonus > 0.0 {
            explanation_parts.push(format!("  - Open source: +{:.1}", prior.open_source_bonus));
        }
        if prior.age_bonus > 0.0 {
            explanation_parts.push(format!("  - Age bonus: +{:.1}", prior.age_bonus));
        }
        
        // Add empirical score details
        explanation_parts.push(format!(""));
        explanation_parts.push(format!("• Empirical score: {:.1} points", score.components.empirical_score));
        if agent.total_reviews > 0 {
            explanation_parts.push(format!("  - From {} reviews", agent.total_reviews));
            if let Some(rating) = agent.average_rating {
                explanation_parts.push(format!("  - Average rating: {:.1}/5.0", rating));
            }
        } else {
            explanation_parts.push(format!("  - No reviews yet"));
        }
        
        // Add confidence details
        explanation_parts.push(format!(""));
        explanation_parts.push(format!("🎯 Confidence Level: {:.1}% ({})", 
            score.confidence * 100.0, 
            match score.level {
                reputation_types::ConfidenceLevel::Low => "Low",
                reputation_types::ConfidenceLevel::Medium => "Medium",
                reputation_types::ConfidenceLevel::High => "High",
            }
        ));
        explanation_parts.push(format!("  - Based on {} interactions", agent.total_interactions));
        if score.is_provisional {
            explanation_parts.push(format!("  - ⚠️ Provisional score (low confidence)"));
        }
        
        // Add weighting details
        explanation_parts.push(format!(""));
        explanation_parts.push(format!("⚖️ Weighting:"));
        explanation_parts.push(format!("  - Prior weight: {:.1}%", (1.0 - score.confidence) * 100.0));
        explanation_parts.push(format!("  - Empirical weight: {:.1}%", score.confidence * 100.0));
        
        Ok(ScoreExplanation {
            final_score: score.score,
            confidence: score.confidence,
            explanation: explanation_parts.join("\n"),
            breakdown: score.components,
        })
    }
    
    /// Predict how the score will change with additional reviews
    /// 
    /// # Arguments
    /// 
    /// * `agent` - Current agent data
    /// * `new_reviews` - Number of new reviews to add
    /// * `new_rating` - Average rating of new reviews (1.0 to 5.0)
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// use reputation_types::AgentDataBuilder;
    /// 
    /// let calc = Calculator::default();
    /// let agent = AgentDataBuilder::new("did:example:123")
    ///     .with_reviews(50, 4.0)
    ///     .total_interactions(50)
    ///     .build()
    ///     .unwrap();
    /// 
    /// // What if they get 10 more 5-star reviews?
    /// let prediction = calc.predict_score_change(&agent, 10, 5.0).unwrap();
    /// println!("Score would change by {:.1} points", prediction.score_change);
    /// ```
    pub fn predict_score_change(
        &self,
        agent: &AgentData,
        new_reviews: u32,
        new_rating: f64,
    ) -> Result<ScorePrediction> {
        // Validate rating
        if new_rating < 1.0 || new_rating > 5.0 {
            return Err(crate::ValidationError::InvalidRating(new_rating).into());
        }
        
        // Calculate current score
        let current_score = self.calculate(agent)?;
        
        // Clone and modify agent data for prediction
        let mut future_agent = agent.clone();
        future_agent.total_reviews = future_agent.total_reviews.saturating_add(new_reviews);
        future_agent.total_interactions = future_agent.total_interactions.saturating_add(new_reviews);
        
        // Recalculate average rating
        if let Some(current_rating) = agent.average_rating {
            let current_weight = agent.total_reviews as f64;
            let new_weight = new_reviews as f64;
            let total_weight = current_weight + new_weight;
            
            future_agent.average_rating = Some(
                ((current_rating * current_weight) + (new_rating * new_weight)) / total_weight
            );
        } else {
            // First reviews
            future_agent.average_rating = Some(new_rating);
        }
        
        // Update positive/negative review counts (approximate)
        let positive_ratio = new_rating / 5.0;
        let new_positive = (new_reviews as f64 * positive_ratio).round() as u32;
        let new_negative = new_reviews.saturating_sub(new_positive);
        
        future_agent.positive_reviews = future_agent.positive_reviews.saturating_add(new_positive);
        future_agent.negative_reviews = future_agent.negative_reviews.saturating_add(new_negative);
        
        // Calculate future score
        let future_score = self.calculate(&future_agent)?;
        
        Ok(ScorePrediction {
            current_score: current_score.score,
            predicted_score: future_score.score,
            score_change: future_score.score - current_score.score,
            confidence_change: future_score.confidence - current_score.confidence,
            reviews_added: new_reviews,
            rating_used: new_rating,
        })
    }
    
    /// Compare two agents' reputation scores
    /// 
    /// Provides a detailed comparison including scores, confidence levels,
    /// and which agent is more reliable.
    /// 
    /// # Example
    /// 
    /// ```
    /// use reputation_core::Calculator;
    /// use reputation_types::AgentDataBuilder;
    /// 
    /// let calc = Calculator::default();
    /// 
    /// let agent_a = AgentDataBuilder::new("did:example:alice")
    ///     .with_reviews(100, 4.5)
    ///     .total_interactions(150)
    ///     .build()
    ///     .unwrap();
    /// 
    /// let agent_b = AgentDataBuilder::new("did:example:bob")
    ///     .with_reviews(20, 4.8)
    ///     .total_interactions(25)
    ///     .build()
    ///     .unwrap();
    /// 
    /// let comparison = calc.compare_agents(&agent_a, &agent_b).unwrap();
    /// println!("Higher score: {}", comparison.higher_score_agent);
    /// println!("More reliable: {}", comparison.more_reliable_agent);
    /// ```
    pub fn compare_agents(
        &self,
        agent_a: &AgentData,
        agent_b: &AgentData,
    ) -> Result<AgentComparison> {
        let score_a = self.calculate(agent_a)?;
        let score_b = self.calculate(agent_b)?;
        
        Ok(AgentComparison {
            agent_a_id: agent_a.did.clone(),
            agent_b_id: agent_b.did.clone(),
            score_a: score_a.score,
            score_b: score_b.score,
            score_difference: score_a.score - score_b.score,
            confidence_a: score_a.confidence,
            confidence_b: score_b.confidence,
            higher_score_agent: if score_a.score >= score_b.score {
                agent_a.did.clone()
            } else {
                agent_b.did.clone()
            },
            more_reliable_agent: if score_a.confidence >= score_b.confidence {
                agent_a.did.clone()
            } else {
                agent_b.did.clone()
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use reputation_types::AgentDataBuilder;
    
    #[test]
    fn test_interactions_for_confidence() {
        let calc = Calculator::default();
        
        // Test basic calculation
        let needed = calc.interactions_for_confidence(0, 0.5).unwrap();
        assert_eq!(needed, 15); // k / (1 - 0.5) = 15
        
        let needed = calc.interactions_for_confidence(10, 0.5).unwrap();
        assert_eq!(needed, 5); // 15 - 10 = 5
        
        // Test high confidence target
        let needed = calc.interactions_for_confidence(0, 0.9).unwrap();
        assert_eq!(needed, 136); // ceil((0.9 * 15) / 0.1) = 136 due to floating point precision
        
        // Test invalid targets
        assert!(calc.interactions_for_confidence(0, -0.1).is_err());
        assert!(calc.interactions_for_confidence(0, 1.1).is_err());
        assert!(calc.interactions_for_confidence(0, 1.0).is_err()); // Can't reach 1.0
    }
    
    #[test]
    fn test_confidence_after_interactions() {
        let calc = Calculator::default();
        
        // Test basic cases
        let conf = calc.confidence_after_interactions(0, 15);
        assert!((conf - 0.5).abs() < 0.001);
        
        let conf = calc.confidence_after_interactions(15, 15);
        assert!((conf - 0.667).abs() < 0.001);
        
        let conf = calc.confidence_after_interactions(135, 0);
        assert!((conf - 0.9).abs() < 0.001);
    }
    
    #[test]
    fn test_explain_score() {
        let calc = Calculator::default();
        
        let agent = AgentDataBuilder::new("did:test:explain")
            .with_reviews(50, 4.2)
            .total_interactions(100)
            .mcp_level(2)
            .identity_verified(true)
            .build()
            .unwrap();
        
        let explanation = calc.explain_score(&agent).unwrap();
        
        assert!(explanation.explanation.contains("Reputation score"));
        assert!(explanation.explanation.contains("Prior score"));
        assert!(explanation.explanation.contains("Empirical score"));
        assert!(explanation.explanation.contains("Confidence Level"));
        assert!(explanation.explanation.contains("MCP bonus"));
        assert!(explanation.explanation.contains("Identity verified"));
        assert_eq!(explanation.final_score, explanation.breakdown.prior_score * (1.0 - explanation.confidence) 
                   + explanation.breakdown.empirical_score * explanation.confidence);
    }
    
    #[test]
    fn test_predict_score_change() {
        let calc = Calculator::default();
        
        let agent = AgentDataBuilder::new("did:test:predict")
            .with_reviews(50, 4.0)
            .total_interactions(50)
            .build()
            .unwrap();
        
        // Predict improvement with good reviews
        let prediction = calc.predict_score_change(&agent, 10, 5.0).unwrap();
        assert!(prediction.score_change > 0.0);
        assert!(prediction.confidence_change > 0.0);
        assert_eq!(prediction.reviews_added, 10);
        assert_eq!(prediction.rating_used, 5.0);
        
        // Predict decline with bad reviews
        let prediction = calc.predict_score_change(&agent, 10, 1.0).unwrap();
        assert!(prediction.score_change < 0.0);
        
        // Test invalid rating
        assert!(calc.predict_score_change(&agent, 10, 6.0).is_err());
    }
    
    #[test]
    fn test_compare_agents() {
        let calc = Calculator::default();
        
        let agent_a = AgentDataBuilder::new("did:test:alice")
            .with_reviews(100, 4.5)
            .total_interactions(150)
            .build()
            .unwrap();
        
        let agent_b = AgentDataBuilder::new("did:test:bob")
            .with_reviews(20, 4.8)
            .total_interactions(25)
            .build()
            .unwrap();
        
        let comparison = calc.compare_agents(&agent_a, &agent_b).unwrap();
        
        // Agent A has higher confidence, Agent B has slightly higher empirical but lower final score
        // Agent A: 100 interactions, 4.5 rating, high confidence
        // Agent B: 20 interactions, 4.8 rating, lower confidence
        assert!(comparison.score_a > comparison.score_b);
        assert_eq!(comparison.higher_score_agent, "did:test:alice");
        assert!(comparison.confidence_a > comparison.confidence_b);
        assert_eq!(comparison.more_reliable_agent, "did:test:alice");
    }
    
    #[test]
    fn test_edge_cases() {
        let calc = Calculator::default();
        
        // Test with zero reviews
        let agent = AgentDataBuilder::new("did:test:new")
            .build()
            .unwrap();
        
        let explanation = calc.explain_score(&agent).unwrap();
        assert!(explanation.explanation.contains("No reviews yet"));
        
        // Test score prediction with no current reviews
        let prediction = calc.predict_score_change(&agent, 5, 4.0).unwrap();
        assert!(prediction.score_change != 0.0);
    }
}