Sleep analyzer
Analyze sleep data, identify sleep patterns, assess sleep quality, and provide personalized sleep-improvement advice. Supports correlation analysis with other health data.From its SKILL.md
npx -y skills add rbr7/MedClawMini --skill sleep-analyzerAssembled from the repository path, not quoted from the project. Check it against their README if it does not work.
One thing to look at
- 0 stars0 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.
SKILL.md
18.8 KB, ~5.0k tokens by cl100k_base, as published. Nobody here has run it
Sleep Analyzer Skill
Analyze sleep data, identify sleep patterns, assess sleep quality, and provide personalized sleep-improvement advice.
Functions
1. Sleep-trend analysis
Analyze trends in sleep duration, quality, and efficiency; identify what is improving or needs attention.
Analysis dimensions:
- Sleep-duration trend (change in average duration)
- Sleep-efficiency trend (change in efficiency %)
- Sleep-timing pattern (bedtime, sleep-onset, wake time)
- Sleep-consistency score
- Weekend vs. weekday comparison (social jet lag)
Output:
- Trend direction (improving/stable/declining)
- Magnitude and percentage of change
- Trend-significance assessment
- Best sleep-window identification
- Improvement suggestions
2. Sleep-quality assessment
Comprehensively assess sleep quality and identify key factors affecting it.
Assessment content:
- PSQI score tracking and trend
- Subjective sleep-quality distribution (good/fair/poor)
- Nighttime-awakening analysis (count, duration, cause)
- Sleep-stage analysis (deep, light, REM proportions)
- Post-sleep restfulness assessment
Output:
- Sleep-quality grade (excellent/good/fair/poor)
- Quality trend
- Main influencing factors
- Quality-improvement priorities
3. Sleep-problem identification
Identify common sleep problems and risk factors.
Identification content:
-
Insomnia patterns:
- Difficulty falling asleep (sleep latency >30 min)
- Difficulty staying asleep (>2 awakenings or total wake time >30 min)
- Early awakening (waking >30 min earlier than intended)
- Mixed insomnia
-
Sleep-apnea risk:
- STOP-BANG questionnaire score
- Symptom analysis (snoring, gasping awake, daytime sleepiness)
- Risk level (low/medium/high)
-
Other issues:
- Irregular-schedule detection
- Sleep-debt calculation (ideal vs. actual duration)
- Social-jet-lag assessment
Output:
- Whether a problem is present
- Problem type and severity
- Risk-factor list
- Whether to recommend seeking care
4. Correlation analysis
Analyze the correlation between sleep and other health metrics.
Supported correlations:
-
Sleep ↔ exercise:
- Sleep difference on exercise vs. rest days
- Effect of exercise timing (morning/afternoon/evening)
- Exercise intensity vs. sleep quality
-
Sleep ↔ diet:
- Caffeine intake vs. sleep duration and onset
- Alcohol's effect on sleep structure
- Dinner time vs. sleep quality
-
Sleep ↔ mood:
- Bidirectional sleep–mood relationship
- Stress level vs. sleep quality
- Sleep deprivation vs. daytime mood
-
Sleep ↔ chronic disease:
- Sleep vs. hypertension
- Sleep vs. glycemic control
- Sleep vs. weight change
Output:
- Correlation coefficient (-1 to 1)
- Correlation strength (weak/medium/strong)
- Statistical significance
- Causal-relationship inference
- Practical suggestions
5. Personalized recommendations
Generate personalized sleep-improvement advice from the user's data.
Recommendation types:
-
Schedule adjustment:
- Best bedtime/wake time
- Consistency-improvement plan
- Nap-management advice
-
Pre-sleep preparation:
- Bedtime-routine design
- Relaxation-technique recommendations
- Screen-time management
-
Sleep-environment optimization:
- Temperature, humidity, light, noise
- Bedding-comfort suggestions
-
Lifestyle adjustments:
- Exercise, diet, caffeine, alcohol management
- Stress-management advice
-
CBT-I elements:
- Stimulus control
- Sleep restriction
- Cognitive restructuring
Output:
- Priority-ranked suggestion list
- Specific implementation steps
- Expected effects
- Implementation timeline
Usage
Triggers
Trigger this skill when the user requests:
- Sleep-trend analysis
- Sleep-quality assessment
- Sleep-problem identification
- Sleep-improvement advice
- Correlation analysis between sleep and other health metrics
Execution Steps
Step 1: Determine the analysis scope
Clarify the requested analysis type and time range:
- Type: trend/quality/problems/correlation/advice
- Time range: week/month/quarter/custom
Step 2: Read data
Primary data sources:
data-example/sleep-tracker.json- main sleep datadata-example/sleep-logs/YYYY-MM/YYYY-MM-DD.json- daily sleep records
Related data sources:
data-example/fitness-tracker.json- exercise datadata-example/hypertension-tracker.json- blood-pressure datadata-example/diabetes-tracker.json- blood-glucose datadata-example/diet-records/- food recordsdata-example/mood-tracker.json- mood data
Step 3: Data analysis
Run the appropriate algorithm for the analysis type:
Trend analysis:
- Linear regression for trend slope
- Moving average to smooth fluctuation
- Statistical-significance test
Correlation analysis:
- Pearson correlation
- Lagged-correlation analysis (delayed effects)
- Multivariate regression
Pattern recognition:
- Time-series pattern recognition
- Outlier detection
- Periodicity analysis
Step 4: Generate the report
Output the analysis report in the standard format (see "Output Format").
Output Format
Sleep-quality analysis report
# Sleep Quality Analysis Report
## Analysis period
2025-03-20 to 2025-06-20 (3 months)
---
## Sleep-duration trend
- **Trend**: ⬆️ improving
- **Start**: avg 6.2 hours/night
- **Current**: avg 7.1 hours/night
- **Change**: +0.9 hours (+14.5%)
- **Interpretation**: marked increase, near the ideal target (7.5 hours)
---
## Sleep efficiency
- **Average sleep efficiency**: 85.3%
- **Range**: 78%-92%
- **On-target rate**: 63% (>85% is on target)
- **Interpretation**: normal efficiency with room to improve
**Efficiency distribution**:
- Excellent (>90%): 15 nights
- Good (85-90%): 28 nights
- Needs improvement (<85%): 47 nights
---
## Schedule regularity
- **Average bedtime**: 23:15 (range: 22:30-01:00)
- **Average wake time**: 07:05 (range: 06:30-08:30)
- **Consistency score**: 72/100
- **Social jet lag**: 45 minutes (later sleep/wake on weekends)
- **Interpretation**: largely regular, but with large weekend variability
**Suggestions**:
- 🎯 Keep a consistent wake time, including weekends
- 🎯 Adjust bedtime gradually; avoid excessive weekend delay
---
## Sleep-quality distribution
| Quality grade | Nights | Share | Trend |
|---------------|--------|-------|-------|
| Excellent | 8 | 9% | ⬆️ |
| Very good | 12 | 13% | ➡️ |
| Good | 15 | 17% | ⬆️ |
| Fair | 42 | 47% | ⬇️ |
| Poor | 10 | 11% | ⬇️ |
| Very poor | 3 | 3% | ➡️ |
**Interpretation**: quality is mostly "fair", but nights of "good"+ are increasing
---
## Nighttime-awakening analysis
- **Average awakenings**: 1.8/night
- **Average awakening duration**: 18 minutes
- **Main causes**:
1. Need to urinate (45%)
2. Noise (25%)
3. Too warm (15%)
4. Other (15%)
**Suggestions**:
- 🎯 Limit fluids for 2 hours before bed
- 🎯 Optimize bedroom temperature (18-22℃)
- 🎯 Use a white-noise machine to mask background noise
---
## PSQI assessment trend
- **Latest score**: 8 (fair sleep quality)
- **Previous score**: 10 (2025-03-20)
- **Change**: -2 (improvement)
- **Trend**: ⬆️ continued improvement
**Component changes**:
- Subjective sleep quality: 2→2 (stable)
- Sleep latency: 2→2 (stable)
- Sleep duration: 2→1 (improving)
- Sleep efficiency: 2→1 (improving)
- Sleep disturbance: 2→1 (improving)
---
## Sleep-problem identification
### Insomnia assessment
- **Type**: mixed insomnia
- **Frequency**: 4-5 nights/week
- **Duration**: 18 months
- **Main symptoms**:
- ✗ Difficulty falling asleep (latency >30 min)
- ✗ Difficulty staying asleep (>2 awakenings)
- ✓ No early awakening
- **Impact**:
- Daytime fatigue: moderate
- Irritability: yes
- Concentration difficulty: yes
- Work performance: mildly affected
- **Suggestion**: 🏥 lasting >3 months; recommend consulting a sleep specialist
### Sleep-apnea screening (STOP-BANG)
- **Score**: 3/8
- **Risk level**: medium
- **Positive items**:
- ✗ Snoring
- ✗ Tired (daytime fatigue)
- ✓ Observed apnea (none observed)
- ✗ Pressure (hypertension)
- ✓ BMI > 28
- ✓ Age > 50
- ✗ Neck size > 40cm
- ✓ Gender = male
- **Suggestion**: ⚠️ recommend a sleep study (PSG)
---
## Correlation analysis
### Sleep ↔ exercise
**Exercise day vs. rest day**:
- Exercise-day average sleep: 7.3 hours
- Rest-day average sleep: 6.8 hours
- Difference: +0.5 hours (+7.4%)
**Effect of exercise timing**:
- Morning exercise: sleep 7.5 h, quality 7.8/10
- Afternoon exercise: sleep 7.2 h, quality 7.5/10
- Evening exercise: sleep 6.8 h, quality 6.8/10
**Correlation**: medium positive (r = 0.42)
**Conclusion**: regular exercise improves sleep, but avoid vigorous exercise 2-3 hours before bed
**Suggestions**:
- 🎯 Keep a regular exercise habit
- 🎯 Move exercise to morning or afternoon
- 🎯 Avoid vigorous exercise 2-3 hours before bed
---
### Sleep ↔ caffeine
**Caffeine-timing analysis**:
- Intake before 2 PM: avg sleep 7.2 h, latency 25 min
- Intake after 2 PM: avg sleep 6.7 h, latency 40 min
- Difference: -0.5 h duration, +15 min latency
**Correlation**: medium negative (r = -0.38)
**Conclusion**: caffeine after 2 PM significantly affects sleep
**Suggestions**:
- 🎯 Avoid caffeine after 2 PM
- 🎯 Avoid caffeine entirely 6 hours before bed
---
### Sleep ↔ mood
**Effect of sleep quality on next-day mood**:
- Good sleep: 82% chance of positive next-day mood
- Fair sleep: 45% chance
- Poor sleep: 18% chance
**Effect of pre-sleep mood on falling asleep**:
- High pre-sleep stress: latency 45 min
- Low pre-sleep stress: latency 20 min
- Difference: +25 min
**Correlation**: strong bidirectional (r = 0.65)
**Conclusion**: sleep and mood significantly affect each other
**Suggestions**:
- 🎯 Do stress management before bed (meditation, deep breathing)
- 🎯 Build a relaxing bedtime routine
- 🎯 Keep a mood journal to identify stress patterns
---
## Insights and Suggestions
### Key insights
1. **Schedule inconsistency is the main problem**
- Social jet lag of 45 min
- Weekend schedule deviates markedly from weekdays
- Affects: circadian disruption, "Monday jet lag"
2. **Evening exercise affects sleep onset**
- Latency +15 min on evening-exercise days
- Suggestion: adjust exercise timing
3. **Sleep environment can be optimized**
- Noise accounts for 25% of awakenings
- Too warm accounts for 15%
- Suggestion: targeted improvements
---
### Priority action plan
#### Priority 1: build a consistent schedule (2 weeks)
**Goal**: raise consistency score to 85
**Specific actions**:
1. Fixed wake time 07:00 (including weekends)
2. Fixed bedtime 23:00
3. Limit naps to <30 min, before 3 PM
4. Adjust weekend schedule gradually (15 min earlier each time)
**Expected effect**:
- Consistency score: 72 → 85
- Efficiency: +3-5%
- Less Monday fatigue
---
#### Priority 2: create a bedtime routine (3 weeks)
**Goal**: establish a stable bedtime routine
**Specific actions**:
1. Start the routine 1 hour earlier (22:00)
2. Turn off electronics (22:30)
3. Dim bedroom lighting
4. Relaxing activity (reading, meditation, warm bath)
5. Keep the bedroom quiet, dark, and cool (18-22℃)
**Expected effect**:
- Latency: 30 → 20 min
- Quality: fair → good
- Lower pre-sleep stress
---
#### Priority 3: optimize the sleep environment (1 week)
**Goal**: remove environmental disturbances
**Specific actions**:
1. Install blackout curtains
2. Use a white-noise machine
3. Optimize temperature to 18-22℃
4. Remove the bedroom clock
5. Replace pillow and mattress for comfort
**Expected effect**:
- Awakenings: 1.8 → 1.2/night
- Better sleep continuity
- Better morning state
---
#### Priority 4: lifestyle adjustments (4 weeks)
**Goal**: remove habits that harm sleep
**Specific actions**:
1. Move exercise to morning or afternoon
2. Stop caffeine after 2 PM
3. Avoid alcohol 3 hours before bed
4. Avoid large meals 2 hours before bed
5. Avoid work-related discussion 1 hour before bed
**Expected effect**:
- Duration: +0.3 h
- Quality: +1 point
- PSQI: 8 → 6
---
## Long-term goals
- **Sleep duration**: reach 7.5 hours/night (currently 7.1)
- **Sleep efficiency**: >90% (currently 85%)
- **PSQI score**: ≤5 (currently 8)
- **Consistency**: ≥85 (currently 72)
- **Sleep latency**: <20 min (currently 28)
---
## Medical Safety Reminder
⚠️ **Care-seeking advice**:
- 🏥 Insomnia lasting >3 months: consult a sleep specialist
- 🏥 STOP-BANG ≥3: recommend a sleep study (PSG)
- 🏥 Severe sleepiness affecting driving safety: seek care immediately
---
**Report generated**: 2025-06-20
**Analysis period**: 2025-03-20 to 2025-06-20 (90 days)
**Records**: 90 nights
**Sleep Analyzer version**: v1.0
Data Structure
Sleep-record data
{
"sleep_records": [
{
"id": "sleep_20250620001",
"date": "2025-06-20",
"sleep_times": {
"bedtime": "23:00",
"sleep_onset_time": "23:30",
"wake_time": "07:00",
"out_of_bed_time": "07:15"
},
"sleep_metrics": {
"sleep_duration_hours": 7.0,
"time_in_bed_hours": 8.25,
"sleep_latency_minutes": 30,
"sleep_efficiency": 84.8
},
"sleep_quality": {
"subjective_quality": "fair",
"quality_score": 5,
"rested_feeling": "somewhat"
},
"factors": {
"exercise": true,
"exercise_time": "evening",
"caffeine_after_2pm": false,
"screen_time_before_bed_minutes": 60
}
}
]
}
Algorithm Notes
Sleep-quality scoring
def calculate_sleep_quality_score(record):
"""
Compute a sleep-quality score (0-10)
Factor weights:
- Duration: 30%
- Efficiency: 25%
- Sleep latency: 20%
- Nighttime awakenings: 15%
- Subjective quality: 10%
"""
score = 0
# Duration score (ideal 7-9 hours)
duration = record['sleep_duration_hours']
if 7 <= duration <= 9:
duration_score = 10
elif 6 <= duration < 7 or 9 < duration <= 10:
duration_score = 7
else:
duration_score = 4
score += duration_score * 0.30
# Efficiency score (>90% excellent)
efficiency = record['sleep_efficiency']
efficiency_score = min(efficiency / 90 * 10, 10)
score += efficiency_score * 0.25
# Latency score (<15 min excellent)
latency = record['sleep_latency_minutes']
if latency <= 15:
latency_score = 10
elif latency <= 30:
latency_score = 7
elif latency <= 45:
latency_score = 4
else:
latency_score = 1
score += latency_score * 0.20
# Awakenings score (0 excellent)
awakenings = record['awakenings']['count']
awakening_score = max(10 - awakenings * 2, 0)
score += awakening_score * 0.15
# Subjective-quality score
quality_map = {
'excellent': 10,
'very_good': 8,
'good': 7,
'fair': 5,
'poor': 3,
'very_poor': 1
}
subjective_score = quality_map.get(
record['sleep_quality']['subjective_quality'],
5
)
score += subjective_score * 0.10
return round(score, 1)
Schedule-regularity scoring
def calculate_sleep_consistency_score(records):
"""
Compute a schedule-regularity score (0-100)
Factors:
- Bedtime standard deviation
- Wake-time standard deviation
- Duration standard deviation
- Weekday vs. weekend difference
"""
# Extract time data
bedtimes = [r['bedtime'] for r in records]
wake_times = [r['wake_time'] for r in records]
durations = [r['sleep_duration_hours'] for r in records]
# Standard deviation (minutes)
bedtime_std = time_to_minutes_std(bedtimes)
wake_std = time_to_minutes_std(wake_times)
duration_std = statistics.stdev(durations)
# Weekday vs. weekend difference
weekday_avg = avg([r['sleep_duration_hours']
for r in records if is_weekday(r)])
weekend_avg = avg([r['sleep_duration_hours']
for r in records if is_weekend(r)])
diff = abs(weekday_avg - weekend_avg)
# Overall score
score = 100
score -= bedtime_std * 0.5 # bedtime SD effect
score -= wake_std * 0.5 # wake-time SD effect
score -= duration_std * 2 # duration SD effect
score -= diff * 10 # weekday/weekend difference
return max(0, min(100, round(score)))
Correlation analysis
def calculate_correlation(sleep_data, other_data, lag_days=0):
"""
Compute the correlation between sleep and another metric
Args:
- sleep_data: list of sleep data
- other_data: list of other-metric data
- lag_days: lag in days (for delayed effects)
Returns:
- correlation_coefficient
- p_value
- interpretation
"""
# Align data (accounting for lag)
aligned = align_data_with_lag(sleep_data, other_data, lag_days)
# Pearson correlation
from scipy import stats
corr, p_value = stats.pearsonr(
aligned['sleep_values'],
aligned['other_values']
)
# Interpret
if abs(corr) < 0.3:
strength = "weak"
elif abs(corr) < 0.7:
strength = "medium"
else:
strength = "strong"
direction = "positive" if corr > 0 else "negative"
significant = p_value < 0.05
interpretation = f"{strength} {direction} correlation"
if significant:
interpretation += " (statistically significant)"
return {
'correlation_coefficient': round(corr, 3),
'p_value': round(p_value, 4),
'interpretation': interpretation,
'significant': significant
}
Medical Safety Statement
The analysis and advice provided by this skill is for reference only and does not constitute a medical diagnosis or treatment plan.
What this skill CAN do:
- ✅ Analyze sleep data and patterns
- ✅ Identify sleep-problem risk
- ✅ Provide sleep-hygiene advice
- ✅ Assess correlation with other health metrics
What this skill CANNOT do:
- ❌ Diagnose insomnia, sleep apnea, etc.
- ❌ Prescribe sleep aids or treatment
- ❌ Replace professional sleep-medicine care
- ❌ Manage severe sleep disorders
When to seek care:
- 🏥 Insomnia lasting >3 months
- 🏥 Suspected sleep apnea (STOP-BANG ≥3)
- 🏥 Severe sleepiness affecting safety
- 🏥 Sudden severe sleep problems
Reference Resources
- AASM sleep-scoring standards: https://aasm.org/
- PSQI scale: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3455216/
- STOP-BANG questionnaire: https://www.stopbang.ca/
- CBT-I therapy: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3455216/
Skill version: v1.0 Created: 2026-01-02 Maintainer: MedClawMini
What ships with it
Read from the repository
Just SKILL.md. No reference files, no scripts.