Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sleep & Recovery Methodology

This document describes the scientific methodology and implementation of Pierre’s sleep analysis and recovery intelligence system.

Overview

Pierre’s sleep and recovery system provides:

  • sleep quality scoring: Multi-factor analysis based on NSF/AASM guidelines
  • HRV analysis: Heart rate variability trend detection for recovery assessment
  • holistic recovery scoring: Combines TSB, sleep quality, and HRV
  • rest day recommendations: AI-powered training/rest decisions
  • evidence-based: Algorithms based on peer-reviewed sports science research

Target audience: Developers, coaches, athletes, and users seeking deep understanding of Pierre’s recovery intelligence.

Table of Contents


Tool-to-Algorithm Mapping

This section provides a comprehensive mapping between MCP tools and their underlying algorithms, implementation files, and test coverage.

Sleep & Recovery Tools (5 tools)

Tool NameAlgorithm/IntelligenceImplementationTest File
analyze_sleep_qualityNSF/AASM sleep scoring + HRV trend analysissrc/tools/implementations/sleep.rs:96-193tests/intelligence_sleep_analysis_test.rs
calculate_recovery_scoreWeighted multi-factor aggregation (TSB + Sleep + HRV)src/tools/implementations/sleep.rs:199-329tests/intelligence_recovery_calculator_test.rs
suggest_rest_dayRecovery threshold analysis + confidence scoringsrc/tools/implementations/sleep.rs:335-470tests/sleep_recovery_integration_test.rs
track_sleep_trendsRolling average comparison + trend detectionsrc/tools/implementations/sleep.rs:588-686tests/sleep_recovery_integration_test.rs
optimize_sleep_scheduleTSB-based sleep duration adjustmentsrc/tools/implementations/sleep.rs:696-815tests/sleep_recovery_integration_test.rs

Intelligence Module Dependencies

ModuleAlgorithmSource File
SleepAnalyzerNSF/AASM sleep quality scoringsrc/intelligence/sleep_analysis.rs
RecoveryCalculatorMulti-factor recovery aggregationsrc/intelligence/recovery_calculator.rs
TrainingLoadCalculatorTSB calculation (CTL/ATL)src/intelligence/training_load.rs
RecoveryAggregationAlgorithmWeighted average scoringsrc/intelligence/algorithms.rs

Algorithm Reference Summary

AlgorithmScientific BasisKey Parameters
Sleep Duration ScoreNSF guidelines (Watson et al., 2015)Optimal: 7-9 hours, athletes: 8-10 hours
Sleep Stage ScoreAASM stage distributionDeep: 15-25%, REM: 20-25%, Light: 50-60%
Sleep Efficiency ScoreTime asleep / time in bedExcellent: >90%, Good: 85-90%
HRV Trend AnalysisPlews et al. (2013)Baseline deviation, 7-day rolling average
Recovery AggregationWeighted averageTSB: 40%, Sleep: 35%, HRV: 25% (full data)
Rest Day ThresholdRecovery score thresholdsRest if score < 40, easy if < 60

1. Sleep Quality Analysis

Duration Scoring (NSF Guidelines)

DurationScoreCategory
≥ 8.0 hours100Optimal for athletes
7.0-8.0 hours80-100Recommended
6.0-7.0 hours50-80Suboptimal
< 6.0 hours0-50Insufficient

Sleep Stage Quality

Pierre analyzes sleep stages based on AASM recommendations:

StageOptimal RangePurpose
Deep Sleep15-25%Physical restoration, growth hormone release
REM Sleep20-25%Cognitive recovery, memory consolidation
Light Sleep50-60%Transition sleep, body maintenance

Efficiency Scoring

EfficiencyScoreCategory
≥ 90%100Excellent
85-90%80-100Good
75-85%50-80Fair
< 75%0-50Poor

Quality Categories

#![allow(unused)]
fn main() {
pub enum SleepQualityCategory {
    Excellent,  // Score > 85, >8 hours, high efficiency
    Good,       // Score 70-85, 7-8 hours
    Fair,       // Score 50-70, 6-7 hours
    Poor,       // Score < 50, <6 hours or low efficiency
}
}

2. HRV Trend Analysis

HRV Metrics

Pierre uses RMSSD (Root Mean Square of Successive Differences) as the primary HRV metric:

StatusBaseline DeviationInterpretation
Recovered> +5%Parasympathetic dominance, ready for training
Normal-5% to +5%Balanced autonomic state
Fatigued< -5%Sympathetic dominance, recovery needed
Significantly Suppressed< -15%High stress/fatigue, rest recommended

Trend Detection

#![allow(unused)]
fn main() {
pub enum HrvTrend {
    Improving,  // 7-day avg > previous 7-day avg
    Stable,     // Within ±5% of previous period
    Declining,  // 7-day avg < previous 7-day avg
}
}

Recovery Status from HRV

#![allow(unused)]
fn main() {
pub enum HrvRecoveryStatus {
    Recovered,              // HRV elevated, ready for training
    Normal,                 // HRV at baseline
    MildlyFatigued,        // HRV slightly suppressed
    SignificantlySuppressed, // HRV markedly below baseline
}
}

3. Holistic Recovery Scoring

Multi-Factor Aggregation

Pierre combines three recovery indicators:

  1. TSB Score (Training Stress Balance)

    • Derived from CTL (Chronic Training Load) and ATL (Acute Training Load)
    • TSB = CTL - ATL
    • Positive TSB = fresh, negative TSB = fatigued
  2. Sleep Quality Score

    • Composite of duration, stages, and efficiency
    • Weighted by data completeness
  3. HRV Score

    • Based on baseline deviation and trend
    • Optional but highly valuable

Weighting Algorithm

#![allow(unused)]
fn main() {
pub enum RecoveryAggregationAlgorithm {
    WeightedAverage {
        // Full data (TSB + Sleep + HRV)
        tsb_weight_full: f64,    // Default: 0.40
        sleep_weight_full: f64,  // Default: 0.35
        hrv_weight_full: f64,    // Default: 0.25

        // No HRV data (TSB + Sleep only)
        tsb_weight_no_hrv: f64,  // Default: 0.55
        sleep_weight_no_hrv: f64, // Default: 0.45
    },
}
}

Data Completeness

LevelSourcesConfidence
FullTSB + Sleep + HRVHigh
PartialTSB + SleepMedium
TSB OnlyActivity data onlyLower

Recovery Categories

ScoreCategoryTraining Readiness
≥ 80ExcellentReady for hard training
60-80GoodReady for moderate training
40-60FairEasy training only
< 40PoorRest needed

4. Rest Day Recommendation

Decision Algorithm

The suggest_rest_day tool uses multi-factor analysis:

IF recovery_score < 40:
    STRONGLY recommend rest (confidence: high)
ELSE IF recovery_score < 60:
    Suggest rest or easy training (confidence: medium)
ELSE IF TSB < -20 AND sleep_score < 70:
    Suggest rest despite moderate recovery (confidence: medium)
ELSE:
    Training OK (confidence based on data completeness)

Confidence Scoring

Data AvailabilityConfidence Boost
Full (TSB + Sleep + HRV)+20%
Partial (TSB + Sleep)+10%
TSB OnlyBase
Consistent indicators+10%
Recent trend data+5%

Output Structure

#![allow(unused)]
fn main() {
pub struct RestDayRecommendation {
    pub rest_recommended: bool,
    pub confidence: f64,           // 0-100
    pub recovery_score: f64,       // 0-100
    pub primary_reasons: Vec<String>,
    pub supporting_factors: Vec<String>,
    pub alternatives: Vec<String>, // e.g., "active recovery", "yoga"
}
}

5. Sleep Schedule Optimization

Duration Recommendations

Base recommendations adjusted by training load:

ConditionAdjustment
TSB < -10 (fatigued)+0.5-1.0 hours
ATL > 100 (high acute load)+0.5 hours
High-intensity workout plannedPrioritize quality
Rest dayBase recommendation

Bedtime Calculation

bedtime = wake_time - target_hours - wind_down_time

Where:

  • wake_time: User’s typical wake time
  • target_hours: 8-9 hours (adjusted for fatigue)
  • wind_down_time: 30 minutes default

6. Configuration

Sleep Parameters

[sleep_recovery]
# Duration thresholds
athlete_min_hours = 7.0
athlete_optimal_hours = 8.0
athlete_max_hours = 10.0

# Stage targets (percentage)
deep_sleep_min_percent = 15.0
deep_sleep_optimal_percent = 20.0
rem_sleep_min_percent = 20.0
rem_sleep_optimal_percent = 25.0

# Efficiency thresholds
efficiency_excellent = 90.0
efficiency_good = 85.0
efficiency_fair = 75.0

Recovery Scoring Weights

[recovery_scoring]
# Full data weights (must sum to 1.0)
tsb_weight_full = 0.40
sleep_weight_full = 0.35
hrv_weight_full = 0.25

# No HRV weights (must sum to 1.0)
tsb_weight_no_hrv = 0.55
sleep_weight_no_hrv = 0.45

TSB Thresholds

[training_stress_balance]
fresh_tsb = 10.0      # Positive TSB indicates freshness
optimal_tsb = 0.0     # Balance point
fatigued_tsb = -10.0  # Negative indicates fatigue
overtrained_tsb = -30.0  # High risk zone

7. Scientific References

Sleep Science

  1. Watson, N.F., et al. (2015). Recommended Amount of Sleep for a Healthy Adult. Sleep, 38(6), 843-844.

  2. Hirshkowitz, M., et al. (2015). National Sleep Foundation’s sleep time duration recommendations. Sleep Health, 1(1), 40-43.

  3. Simpson, N.S., et al. (2017). Sleep and recovery in team sport athletes. British Journal of Sports Medicine, 51(3), 179-186.

HRV and Recovery

  1. Shaffer, F., & Ginsberg, J.P. (2017). An Overview of Heart Rate Variability Metrics and Norms. Frontiers in Public Health, 5, 258.

  2. Plews, D.J., et al. (2013). Training adaptation and heart rate variability in elite endurance athletes. International Journal of Sports Physiology and Performance, 8(5), 512-519.

  3. Buchheit, M. (2014). Monitoring training status with HR measures: Do all roads lead to Rome? Frontiers in Physiology, 5, 73.

Overtraining and Recovery

  1. Meeusen, R., et al. (2013). Prevention, diagnosis, and treatment of the overtraining syndrome. European Journal of Sport Science, 13(1), 1-24.

  2. Halson, S.L. (2014). Monitoring training load to understand fatigue in athletes. Sports Medicine, 44(Suppl 2), S139-147.

Athlete Sleep

  1. Leeder, J., et al. (2012). Sleep duration and quality in elite athletes. International Journal of Sports Physiology and Performance, 7(4), 340-345.

  2. Fullagar, H.H., et al. (2015). Sleep and athletic performance: The effects of sleep loss on exercise performance. Sports Medicine, 45(2), 161-186.