agentleFS
somz22somz22/personal-health-fitbit/.agents/skills/health-analysis/SKILL.md

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

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
  1. Very specific:

    CRITICAL: Always use v_*_clean views instead of raw tables.

    line 63
  2. Distinctive:

    Before performing analysis, check for the user's personal health context:

    line 317
  3. Very specific:

    If HEALTH_CONTEXT.md does not exist, analyze data without personal context and note that baselines are unknown.

    line 330
  4. Very specific:

    Never query raw tables (daily_heart_rate) directly for analysis.

    line 335
  5. Distinctive:

    Do not compare against population averages.

    line 338
  6. Distinctive:

    Look for peak HR > 150 bpm from intraday data

    line 350
  7. Distinctive:

    Look for sustained periods (>10 minutes) above 130 bpm

    line 351
  8. Distinctive:

    Anxiety/stress: Check time of day and context

    line 357
  9. Distinctive:

    Medication effects: Check medication_logs

    line 359
  10. Very specific:

    Always check medication_logs before making causal claims.

    line 363
  11. Very specific:

    All timestamps in the database are stored with a +00:00 UTC offset

    line 366
  12. Very specific:

    If TIMEZONE is set in .env, the sync converts device-local timestamps to real UTC

    line 367
  13. Very specific:

    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 …

    line 368
  14. Distinctive:

    When analyzing sleep or intraday data for a specific local time window, convert accordingly

    line 369
  15. Distinctive:

    When analysis reveals significant findings, store them for tracking over time.

    line 374
  16. Very specific:

    Always write insights to Supabase, then phf pull to sync them locally.

    line 400
  17. Distinctive:

    Run these queries in sequence for a comprehensive daily analysis:

    line 421
  18. Distinctive:

    Look for simultaneous: rising RHR + falling VO2 max + reduced exercise frequency:

    line 480
  19. Distinctive:

    If the DuckDB data is not fresh enough, pull fresh data from Fitbit:

    line 514
  20. Distinctive:

    When starting a new analysis session, run these to establish ground truth before making any claims:

    line 527
  21. Very specific:

    Data freshness: Check sync_checkpoints to see when each domain was last synced

    line 529
  22. Distinctive:

    Recent exercise reality: Use the exercise detection query (recipe #6), not just "active minutes"

    line 531
  23. Very specific:

    Lab data freshness: Check most recent lab_reports date

    line 532
  24. Distinctive:

    Wear quality: Run wear quality distribution (recipe #10) to know how much data is trustworthy

    line 533

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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)

TableKey ColumnsUnique Constraint
patientsid (UUID PK), name, date_of_birth, gender, known_conditions[], fitbit_user_id—
daily_activitypatient_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_ratepatient_id, source, date, resting_hr, zone_min, zone_cal(patient_id, source, date)
daily_sleeppatient_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_hrvpatient_id, source, date, daily_rmssd, deep_rmssd(patient_id, source, date)
daily_spo2patient_id, source, date, avg_spo2, min_spo2, max_spo2(patient_id, source, date)
daily_breathing_ratepatient_id, source, date, full_sleep_br, deep_sleep_br, light_sleep_br, rem_sleep_br(patient_id, source, date)
daily_temperaturepatient_id, source, date, skin_temp_deviation(patient_id, source, date)
daily_cardio_scorepatient_id, source, date, vo2_max_low, vo2_max_high(patient_id, source, date)
daily_weightpatient_id, source, date, weight_kg, bmi, body_fat_pct(patient_id, source, date)
intraday_heart_ratepatient_id, source, timestamp (TIMESTAMPTZ), heart_rate (INTEGER)(patient_id, source, timestamp)
lab_reportspatient_id, report_date, lab, test_name, source_file—
lab_resultsreport_id (FK), category, parameter, value_numeric, value_text, unit, ref_range, status, interpretation, method, metadata (JSON)—
medicationspatient_id, name, dosage, frequency, active—
medication_logspatient_id, medication_id (FK), date, taken, taken_at, notes—
daily_logspatient_id, date, mood, energy, stress, exercise_done, exercise_type, exercise_minutes, symptoms (JSON), notes—
sync_checkpointspatient_id, domain, last_synced_date, last_run_at, status, error_message—

Layer 2 — Clean Views (ALWAYS use these for analysis)

ViewBase TableFilter Logic
v_hr_cleandaily_heart_rateOnly good-wear days with non-null resting HR
v_hrv_cleandaily_hrvOnly good-wear days with valid RMSSD values (deep > 0, daily > 0)
v_sleep_cleandaily_sleepMain sleep only (is_main_sleep = true), minimum 2h, deep > 0 min
v_activity_cleandaily_activityOnly "good" wear days (from daily_wear_quality)
v_intraday_cleanintraday_heart_rateOnly "good" wear days
daily_wear_qualityCompositeClassifies 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)

TablePurpose
analysis_insightsSignificant health findings with severity and evidence
analysis_comparisonsPeriod-over-period comparisons (e.g., this month vs last)
analysis_nap_scoresNap 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 month

2. 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 month

3. 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 7

4. 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 7

5. 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 hour

6. 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 DESC

7. 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 DESC

Important: 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 7

9. 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 30

10. 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 DESC

11. 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 60

12. 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 90

To 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.date

13. 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 30

14. 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 8

15. 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_date

16. 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 30

17. 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 30

How 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.md

This 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:00 UTC offset
  • If TIMEZONE is set in .env, the sync converts device-local timestamps to real UTC
  • 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 before 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

CategoryWhen to Use
cardiacRHR changes, HR spikes, arrhythmia indicators
sleepSleep pattern changes, efficiency drops, timing shifts
activityExercise frequency, deconditioning signals, step trends
autonomicHRV changes, RHR-HRV correlation analysis
metabolicWeight trends, VO2 max changes
giGastrocardiac reflex detections, bloating patterns
labsLab result interpretations, biomarker trends
medicationCompliance patterns, medication effect observations

Severity Levels

SeverityWhen to UseExample
criticalImmediate health concern requiring attentionRHR jumped 15+ bpm in one week
warningNeeds monitoring, potential issue developingSleep efficiency dropped below 70% for 5+ days
infoNotable observation, not urgentVO2 max improved by 2 points over past month
positiveGood news, improvement detectedRHR 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:

  1. 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
  2. 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
  3. Yesterday's activity:
    SELECT date, steps, active_minutes_very, calories_active
    FROM v_activity_clean ORDER BY date DESC LIMIT 1
  4. 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
  5. 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 8

Detect 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 e

Querying 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 HRV

This 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:

  1. Data freshness: Check sync_checkpoints to see when each domain was last synced
  2. Current RHR trend: Query monthly RHR averages (recipe #1 above)
  3. Recent exercise reality: Use the exercise detection query (recipe #6), not just "active minutes"
  4. Lab data freshness: Check most recent lab_reports date
  5. Wear quality: Run wear quality distribution (recipe #10) to know how much data is trustworthy
  6. Read HEALTH_CONTEXT.md: For user baselines and personal context

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.