health-analysis
Skill2 starsChanged 8 months agoMITView on GitHub
Analyze personal health data from Fitbit — query heart rate, HRV, sleep, activity trends, detect anomalies, generate daily/weekly reports, store insights
- Reads credentials
- Sends data out
In this repository5 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/CLAUDE.mdCLAUDE.md
- health-loggingSkill
- health-setupSkill
- health-syncSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
24 rules. About 0 are common, 14 are distinctive, and 10 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈14
Distinctive · estimate
This author's own choices. Worth a look.
10
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 63
CRITICAL: Always use v_*_clean views instead of raw tables.
- Distinctive: line 317
Before performing analysis, check for the user's personal health context:
- Very specific: line 330
If HEALTH_CONTEXT.md does not exist, analyze data without personal context and note that baselines are unknown.
- Very specific: line 335
Never query raw tables (daily_heart_rate) directly for analysis.
- Distinctive: line 338
Do not compare against population averages.
- Distinctive: line 350
Look for peak HR > 150 bpm from intraday data
- Distinctive: line 351
Look for sustained periods (>10 minutes) above 130 bpm
- Distinctive: line 357
Anxiety/stress: Check time of day and context
- Distinctive: line 359
Medication effects: Check medication_logs
- Very specific: line 363
Always check medication_logs before making causal claims.
- Very specific: line 366
All timestamps in the database are stored with a +00:00 UTC offset
- Very specific: line 367
If TIMEZONE is set in .env, the sync converts device-local timestamps to real UTC
- Very specific: line 368
If TIMEZONE is unset, timestamps are stored as device-local time with a +00:00 marker (may be inaccurate for non-UTC users — check .env …
- Distinctive: line 369
When analyzing sleep or intraday data for a specific local time window, convert accordingly
- Distinctive: line 374
When analysis reveals significant findings, store them for tracking over time.
- Very specific: line 400
Always write insights to Supabase, then phf pull to sync them locally.
- Distinctive: line 421
Run these queries in sequence for a comprehensive daily analysis:
- Distinctive: line 480
Look for simultaneous: rising RHR + falling VO2 max + reduced exercise frequency:
- Distinctive: line 514
If the DuckDB data is not fresh enough, pull fresh data from Fitbit:
- Distinctive: line 527
When starting a new analysis session, run these to establish ground truth before making any claims:
- Very specific: line 529
Data freshness: Check sync_checkpoints to see when each domain was last synced
- Distinctive: line 531
Recent exercise reality: Use the exercise detection query (recipe #6), not just "active minutes"
- Very specific: line 532
Lab data freshness: Check most recent lab_reports date
- Distinctive: line 533
Wear quality: Run wear quality distribution (recipe #10) to know how much data is trustworthy
≈ “Common” is an estimate: at least 1 in 5 of the 372,429 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Health Analysis Skill
This is the primary skill for the Personal Health Fitbit system. It enables AI agents to query, analyze, and interpret Fitbit health data stored in a local DuckDB database.
How to Connect to Data
import duckdb
con = duckdb.connect('data/health.duckdb', read_only=True)
result = con.sql("YOUR QUERY")
print(result.show())Or from the command line:
python3 -c "
import duckdb
con = duckdb.connect('data/health.duckdb', read_only=True)
con.sql('YOUR QUERY').show()
"Schema Overview
Layer 1 — Fact Tables (Raw Data)
| Table | Key Columns | Unique Constraint |
patients | id (UUID PK), name, date_of_birth, gender, known_conditions[], fitbit_user_id | — |
daily_activity | patient_id, source, date, steps, distance_km, floors, calories_total, calories_bmr, calories_active, active_minutes_lightly, active_minutes_fairly, active_minutes_very, sedentary_minutes | (patient_id, source, date) |
daily_heart_rate | patient_id, source, date, resting_hr, zone_min, zone_cal | (patient_id, source, date) |
daily_sleep | patient_id, source, date, log_id, is_main_sleep, duration_ms, efficiency, minutes_asleep, minutes_awake, minutes_rem, minutes_light, minutes_deep, time_in_bed, start_time, end_time | (patient_id, source, log_id) |
daily_hrv | patient_id, source, date, daily_rmssd, deep_rmssd | (patient_id, source, date) |
daily_spo2 | patient_id, source, date, avg_spo2, min_spo2, max_spo2 | (patient_id, source, date) |
daily_breathing_rate | patient_id, source, date, full_sleep_br, deep_sleep_br, light_sleep_br, rem_sleep_br | (patient_id, source, date) |
daily_temperature | patient_id, source, date, skin_temp_deviation | (patient_id, source, date) |
daily_cardio_score | patient_id, source, date, vo2_max_low, vo2_max_high | (patient_id, source, date) |
daily_weight | patient_id, source, date, weight_kg, bmi, body_fat_pct | (patient_id, source, date) |
intraday_heart_rate | patient_id, source, timestamp (TIMESTAMPTZ), heart_rate (INTEGER) | (patient_id, source, timestamp) |
lab_reports | patient_id, report_date, lab, test_name, source_file | — |
lab_results | report_id (FK), category, parameter, value_numeric, value_text, unit, ref_range, status, interpretation, method, metadata (JSON) | — |
medications | patient_id, name, dosage, frequency, active | — |
medication_logs | patient_id, medication_id (FK), date, taken, taken_at, notes | — |
daily_logs | patient_id, date, mood, energy, stress, exercise_done, exercise_type, exercise_minutes, symptoms (JSON), notes | — |
sync_checkpoints | patient_id, domain, last_synced_date, last_run_at, status, error_message | — |
Layer 2 — Clean Views (ALWAYS use these for analysis)
| View | Base Table | Filter Logic |
v_hr_clean | daily_heart_rate | Only good-wear days with non-null resting HR |
v_hrv_clean | daily_hrv | Only good-wear days with valid RMSSD values (deep > 0, daily > 0) |
v_sleep_clean | daily_sleep | Main sleep only (is_main_sleep = true), minimum 2h, deep > 0 min |
v_activity_clean | daily_activity | Only "good" wear days (from daily_wear_quality) |
v_intraday_clean | intraday_heart_rate | Only "good" wear days |
daily_wear_quality | Composite | Classifies each day as 'good', 'partial', or 'not_worn' based on HR reading count, steps, sedentary minutes |
CRITICAL: Always use v_*_clean views instead of raw tables. Raw tables include days the watch was not worn, which produces garbage data that skews all analysis.
Layer 3 — Analysis Tables (AI-Generated)
| Table | Purpose |
analysis_insights | Significant health findings with severity and evidence |
analysis_comparisons | Period-over-period comparisons (e.g., this month vs last) |
analysis_nap_scores | Nap quality assessments |
Key Analysis Patterns (SQL Recipes)
1. Monthly Resting Heart Rate Trend
SELECT strftime(date, '%Y-%m') as month,
round(avg(resting_hr), 1) as avg_rhr,
round(min(resting_hr), 1) as min_rhr,
round(max(resting_hr), 1) as max_rhr,
count(*) as days
FROM v_hr_clean
GROUP BY month ORDER BY month2. Heart Rate Variability Trend
SELECT strftime(date, '%Y-%m') as month,
round(avg(deep_rmssd), 1) as avg_hrv_deep,
round(avg(daily_rmssd), 1) as avg_hrv_daily,
count(*) as days
FROM v_hrv_clean
GROUP BY month ORDER BY month3. Last 7 Days Sleep Analysis
SELECT date,
round(minutes_asleep / 60.0, 1) as hours_slept,
efficiency,
minutes_deep,
minutes_rem,
minutes_light,
minutes_awake,
strftime(start_time, '%H:%M') as bedtime,
strftime(end_time, '%H:%M') as wake_time
FROM v_sleep_clean
ORDER BY date DESC LIMIT 74. Last 7 Days Activity Summary
SELECT date,
steps,
active_minutes_very,
active_minutes_fairly,
active_minutes_lightly,
sedentary_minutes,
calories_total,
calories_active,
distance_km
FROM v_activity_clean
ORDER BY date DESC LIMIT 75. Intraday Heart Rate Profile for a Specific Day
SELECT strftime(timestamp, '%H') as hour,
round(avg(heart_rate), 1) as avg_hr,
min(heart_rate) as min_hr,
max(heart_rate) as max_hr,
count(*) as readings,
sum(CASE WHEN heart_rate > 100 THEN 1 ELSE 0 END) as mins_above_100,
sum(CASE WHEN heart_rate > 120 THEN 1 ELSE 0 END) as mins_above_120,
sum(CASE WHEN heart_rate > 150 THEN 1 ELSE 0 END) as mins_above_150
FROM v_intraday_clean
WHERE date(timestamp) = '2026-03-19'
GROUP BY hour ORDER BY hour6. Detect Real Exercise Days (Peak HR > 150)
"Active minutes" from Fitbit includes casual walking. To find actual structured exercise, look for sustained high heart rate:
SELECT date(timestamp) as date,
max(heart_rate) as peak_hr,
sum(CASE WHEN heart_rate > 150 THEN 1 ELSE 0 END) as mins_above_150,
sum(CASE WHEN heart_rate > 130 THEN 1 ELSE 0 END) as mins_above_130,
round(avg(heart_rate), 1) as day_avg_hr
FROM v_intraday_clean
GROUP BY date(timestamp)
HAVING max(heart_rate) > 150
ORDER BY date DESC7. Detect Bloating / Gastrocardiac Reflex Episodes
High HR during the midday window (11 AM - 2 PM) without corresponding high activity may indicate postprandial HR spikes (gastrocardiac reflex):
SELECT date(timestamp) as date,
round(avg(heart_rate), 1) as noon_avg_hr,
max(heart_rate) as noon_peak_hr,
sum(CASE WHEN heart_rate >= 100 THEN 1 ELSE 0 END) as mins_above_100,
sum(CASE WHEN heart_rate >= 110 THEN 1 ELSE 0 END) as mins_above_110
FROM v_intraday_clean
WHERE strftime(timestamp, '%H')::INT BETWEEN 11 AND 14
GROUP BY date(timestamp)
HAVING sum(CASE WHEN heart_rate >= 100 THEN 1 ELSE 0 END) > 10
ORDER BY date DESCImportant: Cross-reference with activity data. High noon HR + low steps = likely gastrocardiac. High noon HR + high steps = exercise.
8. Sleep Nadir Heart Rate (Lowest HR During Sleep)
The lowest HR during sleep (typically 3-6 AM) is a strong indicator of cardiovascular fitness:
SELECT date(timestamp) as date,
round(avg(heart_rate), 1) as sleep_window_avg_hr,
min(heart_rate) as nadir_hr
FROM v_intraday_clean
WHERE strftime(timestamp, '%H')::INT BETWEEN 3 AND 6
GROUP BY date(timestamp)
ORDER BY date DESC LIMIT 79. VO2 Max Trend
SELECT date,
vo2_max_low,
vo2_max_high,
round((vo2_max_low + vo2_max_high) / 2.0, 1) as vo2_mid
FROM daily_cardio_score
ORDER BY date DESC LIMIT 3010. Wear Quality Distribution
SELECT wear_status, count(*) as days,
round(count(*) * 100.0 / sum(count(*)) OVER (), 1) as pct
FROM daily_wear_quality
GROUP BY wear_status
ORDER BY days DESC11. 30-Day Rolling Baseline for Any Metric
SELECT date, resting_hr,
round(avg(resting_hr) OVER (
ORDER BY date ROWS BETWEEN 29 PRECEDING AND CURRENT ROW
), 1) as rolling_30d_avg
FROM v_hr_clean
ORDER BY date DESC LIMIT 6012. RHR vs HRV Correlation
SELECT h.date, h.resting_hr, v.deep_rmssd, v.daily_rmssd
FROM v_hr_clean h
INNER JOIN v_hrv_clean v ON h.date = v.date
ORDER BY h.date DESC LIMIT 90To calculate the correlation coefficient:
SELECT round(corr(h.resting_hr, v.deep_rmssd), 3) as rhr_hrv_correlation,
count(*) as days
FROM v_hr_clean h
INNER JOIN v_hrv_clean v ON h.date = v.date13. Sleep Duration vs Next-Day RHR
SELECT s.date as sleep_date,
round(s.minutes_asleep / 60.0, 1) as hours_slept,
s.efficiency,
h.resting_hr as next_day_rhr
FROM v_sleep_clean s
INNER JOIN v_hr_clean h ON h.date = s.date + INTERVAL '1 day'
ORDER BY s.date DESC LIMIT 3014. Weekly Summary
SELECT strftime(date, '%Y-W%W') as week,
round(avg(resting_hr), 1) as avg_rhr,
count(*) as days_worn
FROM v_hr_clean
GROUP BY week ORDER BY week DESC LIMIT 815. Lab Results Tracking (Key Biomarkers)
SELECT lr.parameter,
lr.value_numeric,
lr.unit,
lr.status,
lr.ref_range,
rep.report_date,
rep.lab
FROM lab_results lr
JOIN lab_reports rep ON lr.report_id = rep.id
WHERE lr.parameter IN ('vitamin_b12', 'vitamin_d', 'sgot_ast', 'sgpt_alt',
'ldl', 'hba1c', 'hs_crp', 'lipoprotein_a', 'rdw_cv', 'homocysteine')
ORDER BY lr.parameter, rep.report_date16. Medication Compliance Check
SELECT ml.date,
m.name as medication,
ml.taken,
ml.taken_at,
ml.notes
FROM medication_logs ml
JOIN medications m ON ml.medication_id = m.id
ORDER BY ml.date DESC, m.name
LIMIT 3017. Identify Data Gaps
WITH date_range AS (
SELECT generate_series(
(SELECT min(date) FROM daily_heart_rate),
current_date,
INTERVAL '1 day'
)::DATE as date
)
SELECT dr.date
FROM date_range dr
LEFT JOIN daily_heart_rate h ON dr.date = h.date
WHERE h.date IS NULL
ORDER BY dr.date DESC
LIMIT 30How to Read User's Health Context
Before performing analysis, check for the user's personal health context:
# Check if HEALTH_CONTEXT.md exists in the project root
cat HEALTH_CONTEXT.mdThis file contains:
- User's age, weight, known conditions
- Personal baselines (best RHR, best HRV, typical sleep, step goals)
- First principles (what levers matter most for this person)
- What the AI agent should know (triggers, patterns, conditions)
If HEALTH_CONTEXT.md does not exist, analyze data without personal context and note that baselines are unknown.
Analysis Principles
Always Use Clean Views
Never query raw tables (daily_heart_rate) directly for analysis. Always use v_hr_clean, v_hrv_clean, v_sleep_clean, v_activity_clean. These filter out garbage data from not-worn and partial-wear days.
Compare Against the User's Own Baselines
Do not compare against population averages. Every person's "normal" is different. Look for:
- Deviations from THEIR 30-day rolling average
- Trends (improving, declining, flat)
- Changes relative to THEIR best period
Distinguish Fitbit RHR from Daytime HR
- Fitbit RHR (from
daily_heart_rate.resting_hr): Algorithmic, computed from the lowest sustained HR periods. Typically 60-75 bpm for a healthy adult. - Daytime average HR (from intraday data): Average HR during waking hours. Typically 80-100+ bpm, much higher than RHR.
- These are fundamentally different metrics. Do not conflate them.
Active Minutes vs Real Exercise
Fitbit's "active minutes" include casual walking and any elevated HR. To identify real structured exercise:
- Look for peak HR > 150 bpm from intraday data
- Look for sustained periods (>10 minutes) above 130 bpm
- Cross-reference with step count (high HR + high steps = running/walking exercise; high HR + low steps = cycling/weights or gastrocardiac)
HR Spikes Without Activity
High intraday HR spikes (>100-120 bpm) during sedentary periods may indicate:
- Gastrocardiac reflex (bloating-triggered): Check if it occurs post-meal (11 AM - 2 PM window)
- Anxiety/stress: Check time of day and context
- Caffeine: Morning spikes after coffee
- Medication effects: Check medication_logs
- Sensor artifact: Very brief single-reading spikes may be noise
Medication Awareness
Always check medication_logs before making causal claims. Some medications affect heart rate, HRV, sleep architecture, and other metrics. If medication data is sparse or empty, note this limitation.
Timestamp Handling
- All timestamps in the database are stored with a
+00:00UTC offset - If
TIMEZONEis set in.env, the sync converts device-local timestamps to real UTC - If
TIMEZONEis unset, timestamps are stored as device-local time with a+00:00marker (may be inaccurate for non-UTC users — check.envbefore relying on exact times) - When analyzing sleep or intraday data for a specific local time window, convert accordingly
- Example: IST = UTC + 5:30, so "3 AM IST" = "21:30 UTC (previous day)"
How to Store Insights
When analysis reveals significant findings, store them for tracking over time.
Insight Categories
| Category | When to Use |
cardiac | RHR changes, HR spikes, arrhythmia indicators |
sleep | Sleep pattern changes, efficiency drops, timing shifts |
activity | Exercise frequency, deconditioning signals, step trends |
autonomic | HRV changes, RHR-HRV correlation analysis |
metabolic | Weight trends, VO2 max changes |
gi | Gastrocardiac reflex detections, bloating patterns |
labs | Lab result interpretations, biomarker trends |
medication | Compliance patterns, medication effect observations |
Severity Levels
| Severity | When to Use | Example |
critical | Immediate health concern requiring attention | RHR jumped 15+ bpm in one week |
warning | Needs monitoring, potential issue developing | Sleep efficiency dropped below 70% for 5+ days |
info | Notable observation, not urgent | VO2 max improved by 2 points over past month |
positive | Good news, improvement detected | RHR reached new 30-day low |
Store via Supabase (source of truth)
Always write insights to Supabase, then phf pull to sync them locally. Do NOT insert directly into DuckDB — that creates split-brain state where local insights are invisible to other clients.
curl -s -X POST "$SUPABASE_URL/rest/v1/analysis_insights" \
-H "apikey: $SUPABASE_SERVICE_KEY" -H "Authorization: Bearer $SUPABASE_SERVICE_KEY" \
-H "Content-Type: application/json" -H "Prefer: return=representation" \
-d '{
"patient_id": "PATIENT_UUID",
"date": "2026-03-20",
"category": "cardiac",
"finding": "RHR trending upward...",
"severity": "warning",
"evidence": {"rhr_2w_ago": 67, "rhr_current": 72},
"source": "ai_analysis"
}'Analysis Templates
Daily Health Check
Run these queries in sequence for a comprehensive daily analysis:
- Yesterday's vitals:
SELECT h.date, h.resting_hr, v.deep_rmssd as hrv FROM v_hr_clean h LEFT JOIN v_hrv_clean v ON h.date = v.date ORDER BY h.date DESC LIMIT 1 - Last night's sleep:
SELECT date, round(minutes_asleep/60.0,1) as hours, efficiency, minutes_deep, minutes_rem, strftime(start_time, '%H:%M') as bedtime FROM v_sleep_clean ORDER BY date DESC LIMIT 1 - Yesterday's activity:
SELECT date, steps, active_minutes_very, calories_active FROM v_activity_clean ORDER BY date DESC LIMIT 1 - Any HR anomalies yesterday:
SELECT strftime(timestamp, '%H') as hour, max(heart_rate) as peak, sum(CASE WHEN heart_rate > 100 THEN 1 ELSE 0 END) as mins_above_100 FROM v_intraday_clean WHERE date(timestamp) = current_date - 1 GROUP BY hour HAVING max(heart_rate) > 110 ORDER BY hour - Compare to 30-day baseline:
SELECT round(avg(resting_hr),1) as baseline_rhr, round(stddev(resting_hr),1) as rhr_stddev FROM v_hr_clean WHERE date >= current_date - 30
Weekly Trend Report
-- Weekly averages for the past 8 weeks
SELECT strftime(date, '%Y-W%W') as week,
round(avg(h.resting_hr),1) as rhr,
round(avg(v.deep_rmssd),1) as hrv,
round(avg(s.minutes_asleep/60.0),1) as sleep_hrs,
round(avg(s.efficiency),1) as sleep_eff,
round(avg(a.steps),0) as steps,
count(DISTINCT h.date) as days_data
FROM v_hr_clean h
LEFT JOIN v_hrv_clean v ON h.date = v.date
LEFT JOIN v_sleep_clean s ON h.date = s.date
LEFT JOIN v_activity_clean a ON h.date = a.date
GROUP BY week ORDER BY week DESC LIMIT 8Detect Deconditioning
Look for simultaneous: rising RHR + falling VO2 max + reduced exercise frequency:
WITH recent AS (
SELECT round(avg(h.resting_hr),1) as rhr,
round(avg(c.vo2_max_low),1) as vo2
FROM v_hr_clean h
LEFT JOIN daily_cardio_score c ON h.date = c.date
WHERE h.date >= current_date - 14
),
baseline AS (
SELECT round(avg(h.resting_hr),1) as rhr,
round(avg(c.vo2_max_low),1) as vo2
FROM v_hr_clean h
LEFT JOIN daily_cardio_score c ON h.date = c.date
WHERE h.date BETWEEN current_date - 44 AND current_date - 15
),
exercise AS (
SELECT
sum(CASE WHEN date(timestamp) >= current_date - 14 THEN 1 ELSE 0 END) as recent_exercise_mins,
sum(CASE WHEN date(timestamp) BETWEEN current_date - 44 AND current_date - 15 THEN 1 ELSE 0 END) as baseline_exercise_mins
FROM v_intraday_clean WHERE heart_rate > 150
)
SELECT
r.rhr as recent_rhr, b.rhr as baseline_rhr,
r.vo2 as recent_vo2, b.vo2 as baseline_vo2,
e.recent_exercise_mins, e.baseline_exercise_mins,
CASE WHEN r.rhr > b.rhr + 3 AND r.vo2 < b.vo2 - 1 THEN 'DECONDITIONING SIGNAL'
ELSE 'Stable' END as assessment
FROM recent r, baseline b, exercise eQuerying Fitbit API Directly (Freshest Data)
If the DuckDB data is not fresh enough, pull fresh data from Fitbit:
phf sync --days 1 # All domains, today only
phf sync --domain heart_rate --days 1 # Just heart rate
phf sync --domain sleep --days 1 # Just sleep
phf sync --domain hrv --days 1 # Just HRVThis fetches from the Fitbit API, writes to Supabase, and pulls to DuckDB in one step.
New Session Grounding Checklist
When starting a new analysis session, run these to establish ground truth before making any claims:
- Data freshness: Check
sync_checkpointsto see when each domain was last synced - Current RHR trend: Query monthly RHR averages (recipe #1 above)
- Recent exercise reality: Use the exercise detection query (recipe #6), not just "active minutes"
- Lab data freshness: Check most recent
lab_reportsdate - Wear quality: Run wear quality distribution (recipe #10) to know how much data is trustworthy
- Read HEALTH_CONTEXT.md: For user baselines and personal context
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

