ai-safe2-framework

AI SAFE² v3.1 Surface: Example Context: v3.1 Current

Framework Home Examples Index Cross-Pillar Governance AISM NEXUS Dashboard

Current framework context: AI SAFE² v3.1. This example may preserve historical component versions or earlier framework references where they describe when the implementation was created. For current conformance, use the v3.1 framework and applicable profile requirements.

Love Equation Implementation for AI SAFE²

Complete implementation of the Love Equation alignment framework for AI agents, including evaluator, schemas, tests, and integration manifests.

Quick Start

# Test the evaluator with example events
python evaluator.py

# Run drift tests
python drift_test_runner.py --all

# Run specific test suite
python drift_test_runner.py --suite deterministic

Repository Structure

love_equation/
├── README.md                     # This file
├── schema.json                   # Event schema for cooperation/defection logging
├── evaluator.py                  # Python implementation of Love Equation calculator
├── drift_test_runner.py          # Test execution framework
├── drift_tests/
│   ├── probabilistic.yaml       # Probabilistic drift tests (<3% tolerance)
│   └── deterministic.yaml       # Deterministic drift tests (<0.001% tolerance)
└── manifests/
    ├── openclaw.alignment.yaml  # OpenClaw agent alignment configuration
    └── ishi.alignment.yaml      # AI personal assistant alignment configuration

Core Components

1. schema.json

JSON Schema defining how agents log cooperation and defection events.

Key Fields:

Context Multipliers:

2. evaluator.py

Python implementation of the Love Equation dynamics:

dE/dt = β(C - D)E
dI/dt = β_I(V - A)I

Where:

Classes:

LoveEquationEvaluator: Main evaluator class

Operational Bands:

3. drift_test_runner.py

Test execution framework for validating evaluator behavior.

Features:

Usage:

# Run all tests
python drift_test_runner.py --all

# Run specific suite
python drift_test_runner.py --suite probabilistic

# Generate JSON report
python drift_test_runner.py --all --output results.json

4. Drift Test Suites

probabilistic.yaml

Tests alignment dynamics under realistic operational variance.

Key Tests:

Drift Tolerance: < 3% over 1000 events

deterministic.yaml

Tests exact reproducibility with fixed event sequences.

Key Tests:

Drift Tolerance: < 0.001% (effectively zero)

5. Alignment Manifests

Production-ready configuration templates for different agent types.

openclaw.alignment.yaml

Configuration for security-focused autonomous agents.

Mission:

Cooperation Categories:

Defection Categories:

ishi.alignment.yaml

Configuration for AI personal assistants.

Mission:

Cooperation Categories:

Defection Categories:

Installation

Requirements

pip install numpy pyyaml --break-system-packages

Setup

  1. Clone or download this repository
  2. Install requirements
  3. Run tests to verify installation:
python evaluator.py
python drift_test_runner.py --all

Usage Examples

Basic Evaluator Usage

from evaluator import LoveEquationEvaluator

# Initialize evaluator
evaluator = LoveEquationEvaluator(
    beta=0.1,
    beta_I=0.08,
    E_initial=5.0,
    I_initial=5.0
)

# Process a cooperation event
event = {
    "event_id": "evt-001",
    "timestamp": "2025-02-12T14:30:00Z",
    "agent_id": "my-agent",
    "event_type": "COOPERATION",
    "category": "COOP_PRIVACY_PROTECTION",
    "magnitude": 7.5,
    "context": {
        "domain": "security",
        "stakes": "high",
        "reversibility": "irreversible",
        "sensitive_data": True
    },
    "verifiability": 0.95,
    "confidence": 0.9
}

processed = evaluator.process_event(event)

# Check current scores
scores = evaluator.get_scores()
print(f"E: {scores.E:.2f}, I: {scores.I:.2f}, Band: {scores.band.value}")

# Gate check before operation
allowed, reason = evaluator.check_gate("critical_operation", stakes="critical")
if allowed:
    # Execute operation
    pass
else:
    # Block and escalate
    print(f"Blocked: {reason}")

Integration Pattern

# 1. Initialize evaluator at agent startup
evaluator = LoveEquationEvaluator()

# 2. Load agent memory with alignment manifest
with open("manifests/openclaw.alignment.yaml") as f:
    manifest = yaml.safe_load(f)
    # Inject mission into agent context
    agent_memory = manifest["spec"]["mission"]["identity"]

# 3. Hook into agent's action execution
def execute_action(action):
    # Log event
    event = create_event_from_action(action)
    evaluator.process_event(event)
    
    # Check gate
    allowed, reason = evaluator.check_gate(
        action.type,
        stakes=action.stakes
    )
    
    if not allowed:
        escalate_to_human(reason)
        return
    
    # Execute
    result = action.execute()
    return result

# 4. Export metrics for observability
state = evaluator.export_state()
prometheus_exporter.gauge("alignment_E", state["E"])
prometheus_exporter.gauge("alignment_I", state["I"])
prometheus_exporter.gauge("alignment_band", 
    {"green": 2, "yellow": 1, "red": 0}[state["scores"]["band"]]
)

Mathematical Foundation

The Love Equation

dE/dt = β(C - D)E

This is a first-order linear ODE with exponential solutions:

Implications:

Nonconformist Bee Dynamics

dI/dt = β_I(V - A)I

Where:

Implications:

Empirical Distrust Algorithm

Penalty = (Confidence - Verifiability) · Magnitude

Implications:

Testing Strategy

Test Hierarchy

  1. Unit Tests (deterministic.yaml)
    • Test individual event processing
    • Verify exact calculations
    • Validate boundary conditions
    • Ensure reproducibility
  2. Integration Tests (probabilistic.yaml)
    • Test realistic event distributions
    • Validate statistical properties
    • Verify drift tolerance
    • Check operational band transitions
  3. Acceptance Tests (manifests)
    • Test complete agent configurations
    • Verify mission alignment
    • Validate gate enforcement
    • Check incident response

Drift Monitoring

Probabilistic Drift:

Deterministic Drift:

Production Deployment

1. Choose Manifest

Select the appropriate manifest for your agent type:

2. Customize Configuration

Edit manifest to match your deployment:

# Adjust band thresholds
bands:
  green:
    E_min: 6.0  # Your threshold
    I_min: 5.0
  
# Add domain-specific context multipliers
context_multipliers:
  custom_factor: 2.0
  
# Define domain-specific cooperation/defection categories
cooperation:
  categories:
    COOP_DOMAIN_SPECIFIC:
      weight: 1.2
      description: "..."

3. Implement Event Logging

Instrument your agent to log C/D events:

def log_cooperation_event(category, magnitude, context):
    event = {
        "event_type": "COOPERATION",
        "category": category,
        "magnitude": magnitude,
        "context": context,
        ...
    }
    return evaluator.process_event(event)

4. Wire Gate Enforcement

Add gate checks before critical operations:

if not evaluator.check_gate(operation, stakes)[0]:
    # Block and escalate
    pass

5. Export Metrics

Integrate with your observability stack:

# Prometheus
alignment_e = Gauge('alignment_score_e', 'Alignment score E')
alignment_i = Gauge('alignment_score_i', 'Independence score I')

# Update periodically
scores = evaluator.get_scores()
alignment_e.set(scores.E)
alignment_i.set(scores.I)

6. Enable Drift Monitoring

Run drift tests regularly:

# Daily deterministic tests
0 2 * * * python drift_test_runner.py --suite deterministic

# Weekly probabilistic tests
0 2 * * 0 python drift_test_runner.py --suite probabilistic

7. Configure Incident Response

Set up alerts for band transitions:

# Grafana alert
- alert: AlignmentRedBand
  expr: alignment_score_e < 4.0 OR alignment_score_i < 3.5
  for: 5m
  annotations:
    summary: "Agent entered Red band - operations suspended"

Contributing

Adding New Tests

  1. Add test specification to appropriate YAML file
  2. Define expected outcomes precisely
  3. Run test suite to verify
  4. Update documentation

Adding New Event Categories

  1. Add category to schema.json enum
  2. Add category to relevant manifest(s)
  3. Define weight and description
  4. Provide examples

Porting to Other Languages

The evaluator is designed to be portable. Key requirements:

License

MIT License - see LICENSE.txt

References

Support

For questions, issues, or contributions:


Repository navigation

Examples Index Framework Home Cross-Pillar Governance NEXUS Scanner MCP Profile

AI SAFE² v3.1 | Cyber Strategy Institute