personal-health-fitbit
AGENTS.md2 starsChanged 8 months agoMITView on GitHub
Open-source personal health analytics. Fitbit data syncs through Supabase to a local DuckDB database. You analyze the data using SQL, detect trends and anomalies, and store insights back into the database. IMPORTANT: During setup, the ONLY way to connect to Fitbit is phf auth (browser-based OAuth2 PKCE). Do NOT ask the user about proxies, alternative auth methods, or advanced configuration. Just guide them to register a Fitbit app and run phf auth. If HEALTH_CONTEXT.md does not exist or phf doctor…
- Reads credentials
- Sends data out
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 33,315 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository5 other files it gives its agents.
- .claude/CLAUDE.mdCLAUDE.md
- health-analysisSkill
- health-loggingSkill
- health-setupSkill
- health-syncSkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
13 rules. About 0 are common, 4 are distinctive, and 9 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈4
Distinctive · estimate
This author's own choices. Worth a look.
9
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 20
If HEALTH_CONTEXT.md does not exist or phf doctor shows failures, this is a new user.
- Distinctive: line 25
Ask personalization questions (conditions, medications, goals, backfill period)
- Distinctive: line 26
Create patient record + initial backfill
- Very specific: line 29
Run phf doctor to verify everything
- Distinctive: line 195
"Active minutes" does NOT mean structured exercise: Use peak HR >150 from intraday data to identify real exercise days.
- Very specific: line 199
Check
medication_logs: when correlating metrics -- medications affect heart rate, HRV, sleep, etc. - Distinctive: line 206
Before making health claims, establish ground truth:
- Very specific: line 207
Check data freshness: phf status
- Very specific: line 208
Read HEALTH_CONTEXT.md for user baselines and conditions
- Very specific: line 210
Check lab_reports dates -- don't cite old lab numbers as "current"
- Very specific: line 211
Verify medication compliance in medication_logs (may be sparse)
- Very specific: line 215
Read that file for this user's patient ID, baselines, conditions, and goals.
- Very specific: line 216
Do not write personal health data here — this file is public.
≈ “Common” is an estimate: at least 1 in 5 of the 42,283 AGENTS.md 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
Personal Health Fitbit -- AI Agent Playbook
Overview
Open-source personal health analytics. Fitbit data syncs through Supabase to a local DuckDB database. You analyze the data using SQL, detect trends and anomalies, and store insights back into the database.
Quick Start
- DuckDB:
data/health.duckdb(local replica, source of truth is Supabase) - Always use
v_*_cleanviews (not raw tables) to exclude not-worn/partial-wear days - Read
HEALTH_CONTEXT.mdfor the user's personal baselines, conditions, and goals - Store findings in the
analysis_insightstable with severity + evidence JSON
First-Time Setup
IMPORTANT: During setup, the ONLY way to connect to Fitbit is phf auth (browser-based
OAuth2 PKCE). Do NOT ask the user about proxies, alternative auth methods, or advanced
configuration. Just guide them to register a Fitbit app and run phf auth.
If HEALTH_CONTEXT.md does not exist or phf doctor shows failures, this is a new
user. Use the /health-setup skill to walk through interactive onboarding:
- Supabase project creation + schema deployment
- Fitbit app registration +
phf auth(browser-based OAuth2) - Ask personalization questions (conditions, medications, goals, backfill period)
- Create patient record + initial backfill
- Generate personalized HEALTH_CONTEXT.md
- Append user-specific context to this file
- Run
phf doctorto verify everything
The setup script scripts/setup_supabase.py automates schema, pg_cron, and verification.
Data Access
import duckdb
con = duckdb.connect('data/health.duckdb', read_only=True)
result = con.sql("SELECT * FROM v_hr_clean ORDER BY date DESC LIMIT 7")
print(result.show())From the command line:
python3 -c "
import duckdb
con = duckdb.connect('data/health.duckdb', read_only=True)
con.sql('YOUR QUERY').show()
"Schema (3 Layers)
Layer 1 -- Fact Tables (Raw Data)
| Table | Purpose | Key Columns |
patients | User profile | id, name, date_of_birth, known_conditions, fitbit_user_id |
daily_activity | Steps, distance, calories | steps, distance_km, calories_total, active_minutes_* |
daily_heart_rate | Resting HR, HR zones | resting_hr, zone_min, zone_cal |
daily_sleep | Sleep stages and quality | duration_ms, efficiency, minutes_rem/light/deep, is_main_sleep |
daily_hrv | Heart rate variability | daily_rmssd, deep_rmssd |
daily_spo2 | Blood oxygen | avg_spo2, min_spo2, max_spo2 |
daily_breathing_rate | Respiratory rate | full_sleep_br, deep_sleep_br |
daily_temperature | Skin temp variation | skin_temp_deviation |
daily_cardio_score | VO2 Max estimate | vo2_max_low, vo2_max_high |
daily_weight | Weight and body comp | weight_kg, bmi, body_fat_pct |
intraday_heart_rate | Per-minute HR | timestamp, heart_rate |
lab_reports / lab_results | Blood work | parameter, value_numeric, unit, ref_range, status |
medications / medication_logs | Medication tracking | name, dosage, frequency, taken, taken_at |
daily_logs | Subjective daily entries | mood, energy, stress, symptoms (JSON) |
sync_checkpoints | Sync state | domain, last_synced_date, status |
Layer 2 -- Derived Views (Clean Data)
| View | Filters Applied |
daily_wear_quality | Classifies each day as good/partial/not_worn |
v_sleep_clean | Main sleep only, >= 120 min asleep, deep > 0 |
v_activity_clean | Only days with good wear quality |
v_hr_clean | Only good-wear days with non-null resting HR |
v_hrv_clean | Only good-wear days with valid RMSSD values |
v_intraday_clean | Only readings from good-wear days |
Layer 3 -- Analysis Tables
| Table | Purpose |
analysis_insights | AI-generated findings with severity and evidence JSON |
analysis_comparisons | Before/after period comparisons |
analysis_nap_scores | Nap detection and scoring |
Common Queries
Monthly RHR trend
SELECT strftime(date, '%Y-%m') AS month, round(avg(resting_hr), 1) AS avg_rhr, count(*) AS days
FROM v_hr_clean GROUP BY month ORDER BY monthWeekly HRV trend
SELECT date_trunc('week', date) AS week, round(avg(deep_rmssd), 1) AS avg_hrv, count(*) AS days
FROM v_hrv_clean GROUP BY week ORDER BY weekSleep duration trend (last 30 days)
SELECT date, round(minutes_asleep / 60.0, 1) AS hours, efficiency
FROM v_sleep_clean WHERE date >= current_date - 30 ORDER BY dateActivity summary (last 14 days)
SELECT date, steps, round(distance_km, 1) AS km, calories_total,
active_minutes_fairly + active_minutes_very AS active_min
FROM v_activity_clean WHERE date >= current_date - 14 ORDER BY dateIntraday HR for a specific day (find exercise peaks)
SELECT timestamp, heart_rate FROM v_intraday_clean
WHERE date(timestamp) = '2025-07-01' AND heart_rate > 120 ORDER BY timestampTrack a lab biomarker over time
SELECT lr.report_date, res.parameter, res.value_numeric, res.unit, res.status
FROM lab_results res JOIN lab_reports lr ON res.report_id = lr.id
WHERE res.parameter = 'vitamin_d' ORDER BY lr.report_dateSkills Available
| Skill | Command | Purpose |
| Setup | /health-setup | Onboarding, Fitbit auth, first sync, personalization |
| Sync | /health-sync | Sync Fitbit data (Fitbit -> Supabase -> DuckDB) |
| Analysis | /health-analysis | Query and analyze health data (primary skill) |
| Logging | /health-logging | Log medications, daily entries, lab reports |
See .agents/skills/*/SKILL.md for detailed instructions.
CLI Commands
phf auth # Authorize with Fitbit (opens browser, OAuth2 PKCE)
phf auth --reauth # Re-authorize (if tokens expired)
phf pull # Supabase -> DuckDB (incremental)
phf pull --full # Full re-sync from Supabase
phf pull --table X # Sync a single table
phf sync # Fitbit -> Supabase -> DuckDB (last 3 days)
phf sync --days 7 # Sync last 7 days
phf sync --domain sleep # Sync only one domain
phf status # Show sync status, data freshness, row counts
phf doctor # Diagnose setup issues (13 checks)
phf export --csv # Export all tables to CSV
phf export --json # Export all tables to JSON
phf backup # Snapshot DuckDB to data/backups/How to Check Things (Supabase API)
Check sync status
curl -s "$SUPABASE_URL/rest/v1/sync_checkpoints?select=domain,last_synced_date&order=domain" \
-H "apikey: $SUPABASE_SERVICE_KEY" -H "Authorization: Bearer $SUPABASE_SERVICE_KEY"Query fresh Fitbit data
phf sync --domain sleep --days 1
phf sync --domain heart_rate --days 1
phf sync --domain hrv --days 1Store a finding
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": "...", "category": "...", "finding": "...", "severity": "critical/warning/info/positive", "evidence": {}}'Run DDL against Supabase
curl -s -X POST "https://api.supabase.com/v1/projects/$SUPABASE_PROJECT_REF/database/query" \
-H "Authorization: Bearer $SUPABASE_PAT" -H "Content-Type: application/json" \
-d '{"query": "YOUR SQL HERE"}'Key Principles
- Always use clean views (
v_*_clean) to exclude not-worn and partial-wear days. - Compare against the user's OWN baselines (defined in
HEALTH_CONTEXT.md), not population averages. - "Active minutes" does NOT mean structured exercise. Use peak HR >150 from intraday data to identify real exercise days.
- Distinguish Fitbit RHR from daytime average HR. Fitbit RHR is algorithmic (measured at rest/sleep). Daytime HR at a desk is a different metric.
- Store significant findings in
analysis_insightswith severity (critical/warning/info/positive) and evidence JSON. Always write to Supabase, thenphf pullto sync locally. - All timestamps in the database are UTC. Fitbit returns device-local time; if
TIMEZONEis set in.env, the sync converts to real UTC. If unset, timestamps are stored as-is with+00:00offset (may be inaccurate for non-UTC users). Convert to user's timezone for display. - Check
medication_logswhen correlating metrics -- medications affect heart rate, HRV, sleep, etc. - Naps are compensatory, not restorative. More naps usually means worse night sleep.
- lab_results column names:
parameter(not biomarker),value_numeric(not value),status(not flag). - Supabase batch inserts require all objects to have identical keys -- add nulls for missing fields.
New Session Checklist
Before making health claims, establish ground truth:
- Check data freshness:
phf status - Read
HEALTH_CONTEXT.mdfor user baselines and conditions - Query recent RHR/HRV trends (don't rely on stale summaries)
- Check
lab_reportsdates -- don't cite old lab numbers as "current" - Verify medication compliance in
medication_logs(may be sparse)
<!-- PERSONALIZATION_START --><!-- User-specific context lives in HEALTH_CONTEXT.md (gitignored).
Read that file for this user's patient ID, baselines, conditions, and goals.
Do not write personal health data here — this file is public. --><!-- PERSONALIZATION_END -->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.

