reputation-core 0.1.0

Core calculation engine for the KnowThat Reputation System with advanced scoring algorithms
Documentation
# Reputation Core

[![Crates.io](https://img.shields.io/crates/v/reputation-core.svg)](https://crates.io/crates/reputation-core)
[![Documentation](https://docs.rs/reputation-core/badge.svg)](https://docs.rs/reputation-core)
[![License](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](https://github.com/knowthat-ai/reputation-engine)

Core calculation engine for the KnowThat Reputation System with advanced scoring algorithms.

## Overview

This crate provides the core reputation calculation engine for MCP (Model Context Protocol) agents. It implements a sophisticated hybrid approach that combines prior reputation scores with empirical performance data to produce reliable, confidence-weighted reputation scores.

## Algorithm

The reputation system uses a weighted calculation that balances two key components:

- **Prior Score**: Initial reputation based on agent credentials and verification (50-80 points)
- **Empirical Score**: Performance-based score derived from user reviews and ratings (0-100 points)
- **Confidence Factor**: Statistical confidence in the empirical data based on interaction volume (0-1)

### Mathematical Foundation

```text
final_score = (1 - confidence) ร— prior_score + confidence ร— empirical_score
```

Where confidence grows asymptotically with interactions:

```text
confidence = interactions / (interactions + k)
```

This approach ensures:

- New agents start with reasonable prior-based scores
- Scores become more performance-driven as data accumulates
- Statistical confidence increases with interaction volume

## Features

### ๐Ÿš€ Performance & Scalability

- **Batch Processing**: Parallel calculation of multiple agent scores
- **Optimized Algorithms**: Efficient mathematical operations
- **Memory Safe**: `#![forbid(unsafe_code)]` guarantee

### ๐Ÿ› ๏ธ Developer Experience

- **Builder Pattern**: Fluent API for calculator configuration
- **Type Safety**: Strong typing with comprehensive validation
- **Error Handling**: Detailed error types with context

### ๐Ÿ“Š Advanced Analytics

- **Enhanced Score Structure**: Detailed breakdowns with confidence levels
- **Utility Methods**: Score analysis, predictions, and comparisons
- **Trend Analysis**: Performance tracking over time

### ๐Ÿงช Quality Assurance

- **Property Testing**: Comprehensive invariant verification
- **Fuzz Testing**: Robustness testing with random inputs
- **Test Vectors**: Standardized test cases for validation

## Usage

Add this to your `Cargo.toml`:

```toml
[dependencies]
reputation-core = "0.1.0"
reputation-types = "0.1.0"
```

### Basic Example

```rust
use reputation_core::Calculator;
use reputation_types::{AgentData, AgentDataBuilder};

// Create agent data
let agent = AgentDataBuilder::new("did:example:123")
    .with_reviews(100, 4.3)
    .mcp_level(2)
    .identity_verified(true)
    .build()
    .unwrap();

// Calculate reputation
let calculator = Calculator::default();
let score = calculator.calculate(&agent)?;

println!("Score: {:.2} ({}% confidence)",
    score.score, (score.confidence * 100.0) as u8);
```

### Builder Pattern Configuration

```rust
use reputation_core::CalculatorBuilder;

let calculator = CalculatorBuilder::new()
    .prior_weight(0.3)
    .confidence_threshold(0.8)
    .decay_factor(0.95)
    .build();

let score = calculator.calculate(&agent)?;
```

### Batch Processing

```rust
use reputation_core::Calculator;

let agents: Vec<AgentData> = get_agents_from_database();
let calculator = Calculator::default();

// Process all agents in parallel
let scores = calculator.calculate_batch(&agents)?;

for (agent, score) in agents.iter().zip(scores.iter()) {
    println!("{}: {:.2}", agent.agent_id, score.score);
}
```

### Advanced Analytics

```rust
use reputation_core::{Calculator, utils};

let calculator = Calculator::default();
let score = calculator.calculate(&agent)?;

// Analyze score components
let breakdown = utils::analyze_score_breakdown(&score);
println!("Prior contribution: {:.1}%", breakdown.prior_weight * 100.0);
println!("Performance contribution: {:.1}%", breakdown.empirical_weight * 100.0);

// Predict future score
let predicted = utils::predict_score_with_interactions(&agent, 50)?;
println!("Predicted score with 50 more interactions: {:.2}", predicted.score);
```

## Configuration Options

The calculator supports extensive configuration:

```rust
let calculator = CalculatorBuilder::new()
    // Weighting factors
    .prior_weight(0.3)                    // How much to weight prior vs empirical
    .confidence_threshold(0.8)            // Minimum confidence for high trust
    .decay_factor(0.95)                   // Time-based score decay

    // Performance calculation
    .review_weight(0.7)                   // Weight of review scores
    .interaction_weight(0.3)              // Weight of interaction volume
    .verification_bonus(10.0)             // Bonus for identity verification

    // Prior calculation
    .mcp_level_bonus(15.0)               // Bonus per MCP level
    .base_prior_score(50.0)              // Starting prior score

    .build();
```

## Error Handling

The crate provides comprehensive error handling:

```rust
use reputation_core::{Calculator, Error};

match calculator.calculate(&agent) {
    Ok(score) => println!("Score: {:.2}", score.score),
    Err(Error::ValidationError(msg)) => eprintln!("Invalid data: {}", msg),
    Err(Error::CalculationError(msg)) => eprintln!("Calculation failed: {}", msg),
    Err(e) => eprintln!("Error: {}", e),
}
```

## Testing

The crate includes extensive testing infrastructure:

```bash
# Run all tests
cargo test

# Run property-based tests
cargo test --features proptest

# Run benchmarks
cargo bench

# Run fuzz tests
cd fuzz && cargo fuzz run fuzz_calculator
```

## Performance

Typical performance characteristics:

- **Single calculation**: ~50-100 nanoseconds
- **Batch processing**: ~10,000 agents/second
- **Memory usage**: Minimal allocation, stack-based calculations
- **Parallel efficiency**: Scales linearly with CPU cores

## License

Licensed under either of:

- Apache License, Version 2.0 ([LICENSE-APACHE]../../LICENSE-APACHE)
- MIT License ([LICENSE-MIT]../../LICENSE-MIT)

at your option.

## Contributing

This is part of the [KnowThat Reputation Engine](https://github.com/knowthat-ai/reputation-engine) project. Please see the main repository for contribution guidelines.

## See Also

- [`reputation-types`]https://crates.io/crates/reputation-types - Core data types
- [`reputation-wasm`]https://npmjs.com/package/@knowthat/reputation-wasm - WebAssembly bindings
- [Documentation]https://docs.rs/reputation-core - Full API documentation