# Briefcase Core

The core Rust library for Briefcase AI - High-performance AI observability, replay, and decision tracking.

[![Crates.io](https://img.shields.io/crates/v/briefcase-core.svg)](https://crates.io/crates/briefcase-core)
[![Documentation](https://docs.rs/briefcase-core/badge.svg)](https://docs.rs/briefcase-core)
[![CI](https://github.com/briefcasebrain/briefcase-ai-core/workflows/CI/badge.svg)](https://github.com/briefcasebrain/briefcase-ai-core/actions)

## Features

- **High Performance** - Zero-copy serialization and minimal memory overhead
- **AI Decision Tracking** - Capture inputs, outputs, and context for every AI decision
- **Deterministic Replay** - Reproduce AI decisions exactly with full context preservation
- **Comprehensive Observability** - Monitor model performance, drift, and behavior
- **Enterprise Security** - Built-in data sanitization and privacy controls
- **Flexible Storage** - SQLite, cloud storage, and custom backends
- **Cross-Platform** - Works on Linux, macOS, Windows, and WebAssembly

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
briefcase-core = "2.1"
```

## Quick Start

```rust
use briefcase_core::*;
use serde_json::json;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Create a decision snapshot
    let decision = DecisionSnapshot::new("ai_function")
        .add_input(Input::new("user_query", json!("Hello world"), "string"))
        .add_output(Output::new("response", json!("Hello back!"), "string").with_confidence(0.95))
        .with_execution_time(120.5);

    // Save to storage
    let storage = storage::SqliteBackend::in_memory()?;
    let decision_id = storage.save_decision(decision).await?;

    println!("Saved decision: {}", decision_id);
    Ok(())
}
```

## Core Components

### DecisionSnapshot

The main data structure for tracking AI decisions:

```rust
let decision = DecisionSnapshot::new("function_name")
    .with_module("my_module")
    .add_input(input)
    .add_output(output)
    .with_model_parameters(params)
    .with_execution_time(100.5)
    .add_tag("version", "1.0");
```

### Model Parameters

Track model configuration for reproducibility:

```rust
let params = ModelParameters::new("gpt-4")
    .with_provider("openai")
    .with_version("1.0")
    .with_parameter("temperature", json!(0.7))
    .with_hyperparameter("max_tokens", json!(1000));
```

### Execution Context

Capture environment for deterministic replay:

```rust
let context = ExecutionContext::new()
    .with_runtime_version("Rust 1.70")
    .with_dependency("tokio", "1.0")
    .with_random_seed(42)
    .with_env_var("DEBUG", "true");
```

## Storage Backends

### SQLite

```rust
// In-memory database
let storage = storage::SqliteBackend::in_memory()?;

// File-based database
let storage = storage::SqliteBackend::file("decisions.db")?;
```

### Custom Storage

Implement the `StorageBackend` trait for custom storage solutions:

```rust
use briefcase_core::storage::StorageBackend;
use async_trait::async_trait;

pub struct CustomBackend;

#[async_trait]
impl StorageBackend for CustomBackend {
    async fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError> {
        // Custom implementation
    }

    async fn load_decision(&self, id: &str) -> Result<DecisionSnapshot, StorageError> {
        // Custom implementation
    }
}
```

## Features

### Default Features

```toml
[dependencies]
briefcase-core = "2.1"
```

### Async Support

```toml
[dependencies]
briefcase-core = { version = "2.1", features = ["async"] }
```

### Storage Backends

```toml
[dependencies]
briefcase-core = { version = "2.1", features = ["sqlite-storage"] }
```

### Sync Only (for WebAssembly)

```toml
[dependencies]
briefcase-core = { version = "2.1", default-features = false, features = ["sync-only"] }
```

## Advanced Usage

### Data Sanitization

```rust
use briefcase_core::sanitization::Sanitizer;

let sanitizer = Sanitizer::new();
let result = sanitizer.sanitize("Contact me at john@example.com");
println!("Sanitized: {}", result.sanitized);
```

### Drift Detection

```rust
use briefcase_core::drift::DriftCalculator;

let calculator = DriftCalculator::new();
let outputs = vec!["Hello world".to_string(), "Hello world!".to_string()];
let metrics = calculator.calculate_drift(&outputs);
println!("Consistency score: {:.2}", metrics.consistency_score);
```

### Cost Calculation

```rust
use briefcase_core::cost::CostCalculator;

let calculator = CostCalculator::new();
let estimate = calculator.estimate_cost("gpt-4", 1000, 500)?;
println!("Estimated cost: ${:.4}", estimate.total_cost);
```

### ModelExecutor

```rust
use briefcase_core::replay::{ModelExecutor, ExecutionConfig, ExecutionResult};

// ModelExecutor is an async trait for plugging in actual model execution during replay
// ReplayEngine optionally accepts an Arc<dyn ModelExecutor>
let executor = Arc::new(MyCustomExecutor::new());
let engine = ReplayEngine::new(storage).with_executor(executor);
```

The `ModelExecutor` trait allows you to inject custom model execution logic during replay operations. This enables:
- Real model re-execution with actual API calls
- Custom inference implementations
- Mock executors for testing
- Model-specific optimization strategies

## Performance

- **Zero-copy operations** - Efficient data handling without unnecessary allocations
- **Minimal overhead** - Designed for high-throughput production environments
- **Memory efficient** - Optimized data structures and algorithms
- **Concurrent processing** - Thread-safe operations with async support

## Platform Support

- **Linux** - All distributions with glibc 2.17+
- **macOS** - 10.12+ (Sierra and later)
- **Windows** - Windows 7+ (with latest updates)
- **WebAssembly** - Browser and Node.js environments

## Language Bindings

This core library powers bindings for other languages:

- **Python**: [`briefcase-ai`](https://pypi.org/project/briefcase-ai/) - Python package
- **WebAssembly**: [`briefcase-wasm`](https://www.npmjs.com/package/briefcase-wasm) - NPM package for browsers and Node.js

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes in `crates/core/`
4. Run tests: `cargo test -p briefcase-core`
5. Submit a pull request

## Documentation

- **API Documentation**: [docs.rs/briefcase-core](https://docs.rs/briefcase-core)
- **Homepage**: [briefcasebrain.com](https://briefcasebrain.com)
- **Examples and Integration Guide**: [docs.briefcasebrain.com](https://docs.briefcasebrain.com)

## License

GPL-3.0 License - see [LICENSE](https://github.com/briefcasebrain/briefcase-ai-core/blob/main/LICENSE) file for details.

## Related Crates

- [`briefcase-wasm`](https://crates.io/crates/briefcase-wasm) - WebAssembly bindings
- [`briefcase-python`](https://crates.io/crates/briefcase-python) - Python FFI bindings
- [`briefcase-server`](https://crates.io/crates/briefcase-server) - Actix-web HTTP API server

---

**Briefcase AI** - Making AI decisions transparent, reproducible, and observable.