reputation-types 0.1.0

Core types and data structures for the KnowThat Reputation Engine
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
use crate::AgentData;
use chrono::{DateTime, Utc};

/// Builder for constructing `AgentData` instances with a fluent API.
/// 
/// The builder provides a convenient way to create `AgentData` instances with
/// validation and sensible defaults. All fields except the DID are optional.
/// 
/// # Examples
/// 
/// ## Basic Usage
/// 
/// ```
/// use reputation_types::AgentDataBuilder;
/// 
/// // Simple agent with minimal data
/// let agent = AgentDataBuilder::new("did:example:123")
///     .build()
///     .unwrap();
/// 
/// // Agent with reviews
/// let agent = AgentDataBuilder::new("did:example:123")
///     .total_interactions(150)
///     .with_reviews(100, 4.5)
///     .mcp_level(2)
///     .identity_verified(true)
///     .build()
///     .unwrap();
/// ```
/// 
/// ## Using the Convenience Constructor
/// 
/// ```
/// use reputation_types::AgentData;
/// 
/// let agent = AgentData::builder("did:example:456")
///     .total_interactions(300)
///     .with_reviews(250, 4.8)
///     .mcp_level(3)
///     .identity_verified(true)
///     .security_audit_passed(true)
///     .open_source(true)
///     .build()
///     .unwrap();
/// ```
/// 
/// ## Setting Individual Review Counts
/// 
/// ```
/// use reputation_types::AgentDataBuilder;
/// 
/// let agent = AgentDataBuilder::new("did:example:789")
///     .positive_reviews(180)
///     .negative_reviews(20)
///     .total_interactions(500)
///     .build()
///     .unwrap();
/// 
/// // The builder will automatically calculate:
/// // - total_reviews: 200 (180 + 20)
/// // - average_rating: 4.6 (based on positive/negative ratio)
/// ```
/// 
/// ## Error Handling
/// 
/// ```
/// use reputation_types::{AgentDataBuilder, BuilderError};
/// 
/// // Empty DID returns an error
/// let result = AgentDataBuilder::new("")
///     .build();
/// assert!(matches!(result, Err(BuilderError::InvalidField(_))));
/// 
/// // Invalid rating returns an error
/// let result = AgentDataBuilder::new("did:example:123")
///     .average_rating(6.0)
///     .build();
/// assert!(matches!(result, Err(BuilderError::InvalidField(_))));
/// ```
#[derive(Debug, Clone)]
pub struct AgentDataBuilder {
    did: String,
    created_at: DateTime<Utc>,
    mcp_level: Option<u8>,
    identity_verified: bool,
    security_audit_passed: bool,
    open_source: bool,
    total_interactions: u32,
    total_reviews: u32,
    average_rating: Option<f64>,
    positive_reviews: u32,
    negative_reviews: u32,
}

impl AgentDataBuilder {
    /// Creates a new builder with the required DID field.
    /// 
    /// All other fields are initialized with sensible defaults:
    /// - `created_at`: Current UTC time
    /// - `mcp_level`: None
    /// - `identity_verified`: false
    /// - `security_audit_passed`: false
    /// - `open_source`: false
    /// - All numeric fields: 0
    pub fn new(did: impl Into<String>) -> Self {
        Self {
            did: did.into(),
            created_at: Utc::now(),
            mcp_level: None,
            identity_verified: false,
            security_audit_passed: false,
            open_source: false,
            total_interactions: 0,
            total_reviews: 0,
            average_rating: None,
            positive_reviews: 0,
            negative_reviews: 0,
        }
    }

    /// Sets the creation timestamp.
    pub fn created_at(mut self, created_at: DateTime<Utc>) -> Self {
        self.created_at = created_at;
        self
    }

    /// Sets the MCP level.
    pub fn mcp_level(mut self, level: u8) -> Self {
        self.mcp_level = Some(level);
        self
    }

    /// Sets whether the agent's identity is verified.
    pub fn identity_verified(mut self, verified: bool) -> Self {
        self.identity_verified = verified;
        self
    }

    /// Sets whether the agent has passed security audit.
    pub fn security_audit_passed(mut self, passed: bool) -> Self {
        self.security_audit_passed = passed;
        self
    }

    /// Sets whether the agent is open source.
    pub fn open_source(mut self, is_open_source: bool) -> Self {
        self.open_source = is_open_source;
        self
    }

    /// Sets the total number of interactions.
    pub fn total_interactions(mut self, count: u32) -> Self {
        self.total_interactions = count;
        self
    }

    /// Sets the total number of reviews.
    pub fn total_reviews(mut self, count: u32) -> Self {
        self.total_reviews = count;
        self
    }

    /// Sets the average rating.
    pub fn average_rating(mut self, rating: f64) -> Self {
        self.average_rating = Some(rating);
        self
    }

    /// Sets the number of positive reviews.
    pub fn positive_reviews(mut self, count: u32) -> Self {
        self.positive_reviews = count;
        self
    }

    /// Sets the number of negative reviews.
    pub fn negative_reviews(mut self, count: u32) -> Self {
        self.negative_reviews = count;
        self
    }

    /// Convenience method to set review data based on total reviews and average rating.
    /// 
    /// This method automatically calculates:
    /// - Positive and negative review counts based on the average rating
    /// - The average rating is clamped between 1.0 and 5.0
    /// 
    /// # Examples
    /// 
    /// ```
    /// use reputation_types::AgentDataBuilder;
    /// 
    /// let agent = AgentDataBuilder::new("did:example:123")
    ///     .total_interactions(150)
    ///     .with_reviews(100, 4.5)  // 87 positive, 13 negative
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn with_reviews(mut self, total: u32, average_rating: f64) -> Self {
        self.total_reviews = total;
        
        // Store the rating as-is, validation happens in build()
        self.average_rating = Some(average_rating);
        
        if total > 0 {
            // Calculate positive/negative based on average
            // A 5.0 rating = 100% positive, 1.0 rating = 0% positive
            let positive_ratio = (average_rating.max(1.0).min(5.0) - 1.0) / 4.0;
            self.positive_reviews = (total as f64 * positive_ratio).round() as u32;
            self.negative_reviews = total.saturating_sub(self.positive_reviews);
        } else {
            self.positive_reviews = 0;
            self.negative_reviews = 0;
        }
        
        self
    }

    /// Builds the `AgentData` instance with validation.
    /// 
    /// # Errors
    /// 
    /// Returns an error if:
    /// - The DID is empty
    /// - The total reviews don't match positive + negative reviews (if all are set)
    /// - The average rating is outside the valid range (1.0-5.0)
    /// - The creation date is in the future
    pub fn build(self) -> Result<AgentData, BuilderError> {
        // Validate DID
        if self.did.is_empty() {
            return Err(BuilderError::InvalidField("DID cannot be empty".to_string()));
        }
        if !self.did.starts_with("did:") {
            return Err(BuilderError::InvalidField("DID must start with 'did:' prefix".to_string()));
        }
        if self.did.contains("..") || self.did.contains("//") || self.did.contains('\'') || 
           self.did.contains('"') || self.did.contains(';') || self.did.contains("--") ||
           self.did.contains('\n') || self.did.contains('\t') || self.did.contains('<') ||
           self.did.contains('>') || self.did.contains('\0') || self.did.contains('\r') ||
           self.did.contains("javascript:") {
            return Err(BuilderError::InvalidField("DID contains invalid format".to_string()));
        }
        if self.did.len() > 1000 {
            return Err(BuilderError::InvalidField("DID exceeds maximum length".to_string()));
        }
        let parts: Vec<&str> = self.did.split(':').collect();
        if parts.len() < 3 || parts[1].is_empty() || parts[2].is_empty() {
            return Err(BuilderError::InvalidField("DID must have format 'did:method:id'".to_string()));
        }

        // Validate creation date
        if self.created_at > Utc::now() {
            return Err(BuilderError::InvalidField("Creation date cannot be in the future".to_string()));
        }

        // Update total_reviews if not explicitly set but positive/negative are set
        let total_reviews = if self.total_reviews == 0 && (self.positive_reviews > 0 || self.negative_reviews > 0) {
            self.positive_reviews + self.negative_reviews
        } else {
            self.total_reviews
        };

        // Validate review counts if all are set
        if total_reviews > 0 && self.positive_reviews + self.negative_reviews > 0 {
            if total_reviews != self.positive_reviews + self.negative_reviews {
                return Err(BuilderError::InvalidField(
                    format!(
                        "Total reviews ({}) must equal positive ({}) + negative ({}) reviews",
                        total_reviews, self.positive_reviews, self.negative_reviews
                    )
                ));
            }
        }
        
        // Validate reviews don't exceed interactions
        if total_reviews > self.total_interactions {
            return Err(BuilderError::InvalidField(
                format!(
                    "Total reviews ({}) cannot exceed total interactions ({})",
                    total_reviews, self.total_interactions
                )
            ));
        }

        // Calculate average rating if not set but we have review data
        let average_rating = match self.average_rating {
            Some(rating) => {
                // Validate rating range and special values
                if rating.is_nan() || rating.is_infinite() {
                    return Err(BuilderError::InvalidField(
                        format!("Average rating must be a valid number, got {}", rating)
                    ));
                }
                if rating < 1.0 || rating > 5.0 {
                    return Err(BuilderError::InvalidField(
                        format!("Average rating must be between 1.0 and 5.0, got {}", rating)
                    ));
                }
                Some(rating)
            }
            None => {
                if total_reviews > 0 && (self.positive_reviews > 0 || self.negative_reviews > 0) {
                    // Calculate from positive/negative ratio
                    let positive_ratio = self.positive_reviews as f64 / total_reviews as f64;
                    Some(1.0 + (positive_ratio * 4.0))
                } else {
                    None
                }
            }
        };

        // Validate MCP level if set
        if let Some(level) = self.mcp_level {
            if level > 3 {
                return Err(BuilderError::InvalidField(
                    format!("MCP level must be between 0 and 3, got {}", level)
                ));
            }
        }

        Ok(AgentData {
            did: self.did,
            created_at: self.created_at,
            mcp_level: self.mcp_level,
            identity_verified: self.identity_verified,
            security_audit_passed: self.security_audit_passed,
            open_source: self.open_source,
            total_interactions: self.total_interactions,
            total_reviews,
            average_rating,
            positive_reviews: self.positive_reviews,
            negative_reviews: self.negative_reviews,
        })
    }
}

/// Errors that can occur when building AgentData
#[derive(Debug, Clone, PartialEq)]
pub enum BuilderError {
    /// A field has an invalid value
    InvalidField(String),
}

impl std::fmt::Display for BuilderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BuilderError::InvalidField(msg) => write!(f, "Invalid field: {}", msg),
        }
    }
}

impl std::error::Error for BuilderError {}

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

    #[test]
    fn test_builder_minimal() {
        let agent = AgentDataBuilder::new("did:example:123")
            .build()
            .unwrap();

        assert_eq!(agent.did, "did:example:123");
        assert_eq!(agent.mcp_level, None);
        assert!(!agent.identity_verified);
        assert!(!agent.security_audit_passed);
        assert!(!agent.open_source);
        assert_eq!(agent.total_interactions, 0);
        assert_eq!(agent.total_reviews, 0);
        assert_eq!(agent.average_rating, None);
        assert_eq!(agent.positive_reviews, 0);
        assert_eq!(agent.negative_reviews, 0);
    }

    #[test]
    fn test_builder_with_all_fields() {
        let created_at = Utc::now() - Duration::days(30);
        let agent = AgentDataBuilder::new("did:example:456")
            .created_at(created_at)
            .mcp_level(3)
            .identity_verified(true)
            .security_audit_passed(true)
            .open_source(true)
            .total_interactions(1000)
            .total_reviews(100)
            .average_rating(4.2)
            .positive_reviews(80)
            .negative_reviews(20)
            .build()
            .unwrap();

        assert_eq!(agent.did, "did:example:456");
        assert_eq!(agent.created_at, created_at);
        assert_eq!(agent.mcp_level, Some(3));
        assert!(agent.identity_verified);
        assert!(agent.security_audit_passed);
        assert!(agent.open_source);
        assert_eq!(agent.total_interactions, 1000);
        assert_eq!(agent.total_reviews, 100);
        assert_eq!(agent.average_rating, Some(4.2));
        assert_eq!(agent.positive_reviews, 80);
        assert_eq!(agent.negative_reviews, 20);
    }

    #[test]
    fn test_with_reviews_helper() {
        let agent = AgentDataBuilder::new("did:example:789")
            .total_interactions(150)
            .with_reviews(100, 4.5)
            .build()
            .unwrap();

        assert_eq!(agent.total_reviews, 100);
        assert_eq!(agent.average_rating, Some(4.5));
        assert_eq!(agent.positive_reviews, 88); // (4.5 - 1.0) / 4.0 * 100 = 87.5, rounded to 88
        assert_eq!(agent.negative_reviews, 12);
    }

    #[test]
    fn test_with_reviews_edge_cases() {
        // Test with perfect rating
        let agent = AgentDataBuilder::new("did:example:1")
            .total_interactions(60)
            .with_reviews(50, 5.0)
            .build()
            .unwrap();
        assert_eq!(agent.positive_reviews, 50);
        assert_eq!(agent.negative_reviews, 0);

        // Test with worst rating
        let agent = AgentDataBuilder::new("did:example:2")
            .total_interactions(60)
            .with_reviews(50, 1.0)
            .build()
            .unwrap();
        assert_eq!(agent.positive_reviews, 0);
        assert_eq!(agent.negative_reviews, 50);

        // Test with rating above 5.0 (should fail)
        let result = AgentDataBuilder::new("did:example:3")
            .with_reviews(100, 6.0)
            .build();
        assert!(result.is_err());

        // Test with rating below 1.0 (should fail)
        let result = AgentDataBuilder::new("did:example:4")
            .with_reviews(100, 0.5)
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn test_validation_empty_did() {
        let result = AgentDataBuilder::new("")
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            BuilderError::InvalidField(msg) => assert!(msg.contains("DID cannot be empty")),
        }
    }

    #[test]
    fn test_validation_future_date() {
        let result = AgentDataBuilder::new("did:example:123")
            .created_at(Utc::now() + Duration::days(1))
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            BuilderError::InvalidField(msg) => assert!(msg.contains("future")),
        }
    }

    #[test]
    fn test_validation_review_mismatch() {
        let result = AgentDataBuilder::new("did:example:123")
            .total_reviews(100)
            .positive_reviews(60)
            .negative_reviews(50) // 60 + 50 = 110 != 100
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            BuilderError::InvalidField(msg) => assert!(msg.contains("must equal")),
        }
    }

    #[test]
    fn test_validation_invalid_rating() {
        let result = AgentDataBuilder::new("did:example:123")
            .average_rating(5.5)
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            BuilderError::InvalidField(msg) => assert!(msg.contains("between 1.0 and 5.0")),
        }
    }

    #[test]
    fn test_validation_invalid_mcp_level() {
        let result = AgentDataBuilder::new("did:example:123")
            .mcp_level(10)
            .build();

        assert!(result.is_err());
        match result.unwrap_err() {
            BuilderError::InvalidField(msg) => assert!(msg.contains("MCP level")),
        }
    }

    #[test]
    fn test_auto_calculate_total_reviews() {
        let agent = AgentDataBuilder::new("did:example:123")
            .total_interactions(120)
            .positive_reviews(75)
            .negative_reviews(25)
            .build()
            .unwrap();

        assert_eq!(agent.total_reviews, 100);
    }

    #[test]
    fn test_auto_calculate_average_rating() {
        let agent = AgentDataBuilder::new("did:example:123")
            .total_interactions(120)
            .positive_reviews(80)
            .negative_reviews(20)
            .build()
            .unwrap();

        // 80/100 = 0.8 positive ratio, 1.0 + (0.8 * 4.0) = 4.2
        assert_eq!(agent.average_rating, Some(4.2));
    }

    #[test]
    fn test_builder_is_cloneable() {
        let builder = AgentDataBuilder::new("did:example:123")
            .mcp_level(2)
            .identity_verified(true);

        let builder2 = builder.clone();
        let agent1 = builder.build().unwrap();
        let agent2 = builder2.build().unwrap();

        assert_eq!(agent1.did, agent2.did);
        assert_eq!(agent1.mcp_level, agent2.mcp_level);
        assert_eq!(agent1.identity_verified, agent2.identity_verified);
    }

    #[test]
    fn test_method_chaining() {
        // This test ensures all methods return Self for proper chaining
        let _agent = AgentDataBuilder::new("did:example:123")
            .created_at(Utc::now())
            .mcp_level(2)
            .identity_verified(true)
            .security_audit_passed(true)
            .open_source(true)
            .total_interactions(1000)
            .with_reviews(100, 4.5)
            .build()
            .unwrap();
    }

    #[test]
    fn test_builder_error_display() {
        let error = BuilderError::InvalidField("test error".to_string());
        assert_eq!(error.to_string(), "Invalid field: test error");
        
        // Test that it implements std::error::Error
        let _: &dyn std::error::Error = &error;
    }
}