# SessionValidator - Comprehensive Session View Validation

## Overview

The **SessionValidator** is a comprehensive validation agent that ensures professional-grade consistency across Session View productions by checking four critical dimensions:

1. **BPM Coherence** - All samples within ±5 BPM of project tempo
2. **Key Harmony** - All MIDI clips use correct key/scale
3. **Sample Rotation** - No consecutive scenes use same sample
4. **Energy Matching** - Sample RMS matches scene energy requirements

## Location

```
AbletonMCP_AI/mcp_server/engines/session_validator.py
```

## Usage

### Method 1: MCP Tool (Recommended)

Use the `validate_session_production` MCP tool directly:

```python
# Validate a 13-scene production at 95 BPM in Am
validate_session_production(bpm=95, key="Am", num_scenes=13)
```

### Method 2: Direct Python API

```python
from AbletonMCP_AI.mcp_server.engines import SessionValidator, init_metadata_store
from AbletonMCP_AI import get_song

# Initialize
song = get_song()
metadata_store = init_metadata_store()
validator = SessionValidator(song, metadata_store)

# Run validation
results = validator.validate_production(
    target_bpm=95,
    key="Am",
    num_scenes=13
)

# Check if passed
if results['passed']:
    print("✓ Production validation PASSED")
else:
    print("✗ Production validation FAILED")
    print(results['summary'])

# Get detailed report
report = validator.get_detailed_report(results)
print(report)
```

## Validation Categories

### 1. BPM Coherence

**Purpose:** Ensures all loaded audio samples are rhythmically compatible with the project tempo.

**How it works:**
- Iterates through all tracks and clip slots in Session View
- Extracts sample paths from audio clips
- Queries metadata store for each sample's BPM
- Calculates deviation from target BPM
- Marks samples outside ±5 BPM tolerance as violations

**Score Calculation:**
```
score = samples_within_tolerance / total_samples_checked
```

**Example Violations:**
```
• kick_95bpm.wav: 95.2 BPM (deviation: 0.2) ✓
• snare_128bpm.wav: 128.0 BPM (deviation: 33.0) ✗
```

**Recommendations:**
- Warp clips to match project tempo
- Select samples with BPM closer to project tempo
- Use BPM-coherent sample pools

### 2. Key Harmony

**Purpose:** Verifies all MIDI clips use notes that belong to the specified musical key.

**How it works:**
- Identifies MIDI tracks by name (drums, bass, chords, melody)
- Extracts MIDI notes from each clip
- Checks each note against the valid scale for the project key
- Flags out-of-key notes as violations

**Supported Keys:**
- Minor: Am, Cm, Dm, Gm, Em, Fm, Bm
- Major: C, D, G, E, F, A

**Score Calculation:**
```
score = clips_with_no_violations / total_midi_clips_checked
```

**Example Violations:**
```
• Bass Track: 3 out-of-key notes (C#4, F#3, G#3) in Am
• Chords Track: 2 out-of-key notes (F#4, C#5) in Am
```

**Recommendations:**
- Transpose out-of-key notes to fit the scale
- Use scale-constrained MIDI generation
- Enable key filtering when selecting samples

### 3. Sample Rotation

**Purpose:** Prevents repetitive timbres by ensuring consecutive scenes use different samples.

**How it works:**
- Builds a map of samples used in each scene
- Compares scene N and scene N+1 for each track
- Flags identical consecutive samples as violations
- Allows re-use after one scene gap (A-B-A pattern is OK)

**Score Calculation:**
```
score = transitions_without_repetition / total_transitions_checked
```

**Example Violations:**
```
• Scene 2 → Scene 3 on Kick Track: kick_95bpm.wav (repeated)
• Scene 4 → Scene 5 on Snare Track: snare_heavy.wav (repeated)
```

**Recommendations:**
- Use sample rotation system to vary timbres
- Prepare multiple sample options per role
- Implement variety in drum patterns between scenes

### 4. Energy Matching

**Purpose:** Ensures sample dynamics match the expected energy profile of each section.

**How it works:**
- Defines expected energy levels per scene type:
  - Intro/Outro: **soft** (RMS 0.0-0.3)
  - Verse/Bridge: **medium** (RMS 0.3-0.7)
  - Chorus/Drop/Build: **hard** (RMS 0.7-1.0)
- Queries metadata store for sample RMS values
- Compares actual RMS to expected range
- Flags mismatched samples as violations

**Score Calculation:**
```
score = samples_matching_energy / total_samples_checked
```

**Example Violations:**
```
• Scene 4/Chorus: soft_pad.wav (RMS: 0.25, expected: 0.7-1.0)
• Scene 0/Intro: loud_kick.wav (RMS: 0.85, expected: 0.0-0.3)
```

**Recommendations:**
- Select samples with appropriate dynamics for each section
- Use gain staging to adjust sample energy
- Apply compression to control dynamic range

## Results Format

### Overall Structure

```json
{
  "bpm_coherence": {
    "name": "BPM Coherence",
    "score": 0.92,
    "passed": true,
    "details": [...],
    "violations": [...],
    "recommendations": [...]
  },
  "key_harmony": {
    "name": "Key Harmony",
    "score": 0.85,
    "passed": true,
    "details": [...],
    "violations": [...],
    "recommendations": [...]
  },
  "sample_rotation": {
    "name": "Sample Rotation",
    "score": 0.78,
    "passed": false,
    "details": [...],
    "violations": [...],
    "recommendations": [...]
  },
  "energy_matching": {
    "name": "Energy Matching",
    "score": 0.88,
    "passed": true,
    "details": [...],
    "violations": [...],
    "recommendations": [...]
  },
  "overall_score": 0.86,
  "passed": true,
  "summary": "Session View Validation Summary...",
  "detailed_report": "..."
}
```

### Pass/Fail Threshold

**Default threshold: 0.85 (85%)**

- **PASSED** (≥0.85): Production meets professional standards
- **FAILED** (<0.85): Production needs improvement

Threshold can be adjusted in the validator:

```python
validator.coherence_threshold = 0.90  # Stricter
validator.coherence_threshold = 0.80  # More lenient
```

## Integration with Production Workflow

### After `build_session_production`

```python
# Build 13-scene production
build_session_production(genre="reggaeton", tempo=95, key="Am", num_scenes=13)

# Validate immediately after
validate_session_production(bpm=95, key="Am", num_scenes=13)

# Review results and fix issues if needed
```

### Before Export

```python
# Final validation before rendering
results = validate_session_production(bpm=95, key="Am", num_scenes=13)

if results['passed']:
    # Proceed with export
    render_full_mix(output_path="final_mix.wav")
else:
    # Fix issues first
    print(results['recommendations'])
```

### Automated QA Pipeline

```python
def production_qa(bpm, key, num_scenes):
    """Automated QA check for productions."""
    results = validate_session_production(bpm, key, num_scenes)
    
    if not results['passed']:
        # Auto-fix common issues
        fix_quality_issues(issues=['bpm_coherence', 'sample_rotation'])
        
        # Re-validate
        results = validate_session_production(bpm, key, num_scenes)
    
    return results
```

## Example Output

### Passing Production

```
Session View Validation Summary
================================
Configuration: 95 BPM | Key: Am | 13 scenes

Overall Score: 0.91 (PASSED)
Threshold: 0.85

Category Scores:
  • BPM Coherence:     0.95
  • Key Harmony:       0.88
  • Sample Rotation:   0.92
  • Energy Matching:   0.89

Total Violations: 8
```

### Failing Production

```
Session View Validation Summary
================================
Configuration: 95 BPM | Key: Am | 13 scenes

Overall Score: 0.72 (FAILED)
Threshold: 0.85

Category Scores:
  • BPM Coherence:     0.65
  • Key Harmony:       0.78
  • Sample Rotation:   0.68
  • Energy Matching:   0.77

Total Violations: 34

Recommendations:
  • Found 12 samples outside ±5 BPM tolerance
  • Consider warping clips to match project tempo or selecting different samples
  • Found 8 MIDI clips with out-of-key notes in Am
  • Consider transposing notes to fit the key or using scale-constrained MIDI generation
  • Found 10 instances of consecutive scene repetition
  • Use sample rotation to vary timbres between adjacent scenes
  • Found 4 samples with mismatched energy levels
  • Select samples with appropriate dynamics for each section
```

## API Reference

### Class: SessionValidator

```python
class SessionValidator:
    def __init__(self, song, metadata_store)
    
    def validate_production(target_bpm, key, num_scenes) -> Dict
    def get_detailed_report(results) -> str
    
    # Internal validation methods
    def _validate_bpm_coherence(target_bpm, tolerance=5.0) -> Dict
    def _validate_key_harmony(key) -> Dict
    def _validate_sample_rotation(num_scenes) -> Dict
    def _validate_energy_matching(num_scenes, target_bpm) -> Dict
```

### Function: validate_session_production

```python
def validate_session_production(
    song,
    metadata_store,
    target_bpm: float,
    key: str,
    num_scenes: int
) -> Dict[str, Any]
```

## Troubleshooting

### Issue: "BPM not found in metadata store"

**Solution:** Run library analysis first:

```python
analyze_library(force_reanalyze=False)
```

### Issue: "Unknown key"

**Solution:** Use supported keys:

```python
# Valid keys
supported_keys = ["Am", "Cm", "Dm", "Gm", "Em", "Fm", "Bm", 
                  "C", "D", "G", "E", "F", "A"]
```

### Issue: Validation always fails

**Solutions:**
1. Lower threshold temporarily: `validator.coherence_threshold = 0.75`
2. Check each category score to identify weak points
3. Review detailed violations report for specific issues
4. Use sample rotation system during production

## Best Practices

1. **Validate Early, Validate Often**
   - Run validation after building initial scenes
   - Re-validate after making changes
   - Final validation before export

2. **Address Violations by Priority**
   - BPM Coherence (highest priority - affects timing)
   - Key Harmony (musical consistency)
   - Sample Rotation (variety and interest)
   - Energy Matching (dynamics and feel)

3. **Use Recommendations**
   - Each violation category includes specific recommendations
   - Follow recommendations to improve scores
   - Re-validate after applying fixes

4. **Document Your Standards**
   - Save validation reports with projects
   - Track improvement over time
   - Establish minimum acceptable scores for releases

## Related Tools

- `build_session_production` - Creates Session View productions
- `analyze_library` - Analyzes sample library for metadata
- `select_coherent_kit` - Selects BPM-coherent samples
- `get_sample_fatigue_report` - Checks sample usage patterns
- `full_quality_check` - Comprehensive project QA

## Version History

- **v1.0** (2026-04-13): Initial implementation
  - BPM Coherence validation
  - Key Harmony validation
  - Sample Rotation validation
  - Energy Matching validation
  - MCP tool integration
  - Detailed reporting
