agentleFS
somz22somz22/personal-health-fitbit/AGENTS.md

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.

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

    If HEALTH_CONTEXT.md does not exist or phf doctor shows failures, this is a new user.

    line 20
  2. Distinctive:

    Ask personalization questions (conditions, medications, goals, backfill period)

    line 25
  3. Distinctive:

    Create patient record + initial backfill

    line 26
  4. Very specific:

    Run phf doctor to verify everything

    line 29
  5. Distinctive:

    "Active minutes" does NOT mean structured exercise: Use peak HR >150 from intraday data to identify real exercise days.

    line 195
  6. Very specific:

    Check medication_logs: when correlating metrics -- medications affect heart rate, HRV, sleep, etc.

    line 199
  7. Distinctive:

    Before making health claims, establish ground truth:

    line 206
  8. Very specific:

    Check data freshness: phf status

    line 207
  9. Very specific:

    Read HEALTH_CONTEXT.md for user baselines and conditions

    line 208
  10. Very specific:

    Check lab_reports dates -- don't cite old lab numbers as "current"

    line 210
  11. Very specific:

    Verify medication compliance in medication_logs (may be sparse)

    line 211
  12. Very specific:

    Read that file for this user's patient ID, baselines, conditions, and goals.

    line 215
  13. Very specific:

    Do not write personal health data here — this file is public.

    line 216

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

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

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_*_clean views (not raw tables) to exclude not-worn/partial-wear days
  • Read HEALTH_CONTEXT.md for the user's personal baselines, conditions, and goals
  • Store findings in the analysis_insights table 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:

  1. Supabase project creation + schema deployment
  2. Fitbit app registration + phf auth (browser-based OAuth2)
  3. Ask personalization questions (conditions, medications, goals, backfill period)
  4. Create patient record + initial backfill
  5. Generate personalized HEALTH_CONTEXT.md
  6. Append user-specific context to this file
  7. Run phf doctor to 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)

TablePurposeKey Columns
patientsUser profileid, name, date_of_birth, known_conditions, fitbit_user_id
daily_activitySteps, distance, caloriessteps, distance_km, calories_total, active_minutes_*
daily_heart_rateResting HR, HR zonesresting_hr, zone_min, zone_cal
daily_sleepSleep stages and qualityduration_ms, efficiency, minutes_rem/light/deep, is_main_sleep
daily_hrvHeart rate variabilitydaily_rmssd, deep_rmssd
daily_spo2Blood oxygenavg_spo2, min_spo2, max_spo2
daily_breathing_rateRespiratory ratefull_sleep_br, deep_sleep_br
daily_temperatureSkin temp variationskin_temp_deviation
daily_cardio_scoreVO2 Max estimatevo2_max_low, vo2_max_high
daily_weightWeight and body compweight_kg, bmi, body_fat_pct
intraday_heart_ratePer-minute HRtimestamp, heart_rate
lab_reports / lab_resultsBlood workparameter, value_numeric, unit, ref_range, status
medications / medication_logsMedication trackingname, dosage, frequency, taken, taken_at
daily_logsSubjective daily entriesmood, energy, stress, symptoms (JSON)
sync_checkpointsSync statedomain, last_synced_date, status

Layer 2 -- Derived Views (Clean Data)

ViewFilters Applied
daily_wear_qualityClassifies each day as good/partial/not_worn
v_sleep_cleanMain sleep only, >= 120 min asleep, deep > 0
v_activity_cleanOnly days with good wear quality
v_hr_cleanOnly good-wear days with non-null resting HR
v_hrv_cleanOnly good-wear days with valid RMSSD values
v_intraday_cleanOnly readings from good-wear days

Layer 3 -- Analysis Tables

TablePurpose
analysis_insightsAI-generated findings with severity and evidence JSON
analysis_comparisonsBefore/after period comparisons
analysis_nap_scoresNap 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 month

Weekly 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 week

Sleep 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 date

Activity 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 date

Intraday 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 timestamp

Track 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_date

Skills Available

SkillCommandPurpose
Setup/health-setupOnboarding, Fitbit auth, first sync, personalization
Sync/health-syncSync Fitbit data (Fitbit -> Supabase -> DuckDB)
Analysis/health-analysisQuery and analyze health data (primary skill)
Logging/health-loggingLog 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 1

Store 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

  1. Always use clean views (v_*_clean) to exclude not-worn and partial-wear days.
  2. Compare against the user's OWN baselines (defined in HEALTH_CONTEXT.md), not population averages.
  3. "Active minutes" does NOT mean structured exercise. Use peak HR >150 from intraday data to identify real exercise days.
  4. Distinguish Fitbit RHR from daytime average HR. Fitbit RHR is algorithmic (measured at rest/sleep). Daytime HR at a desk is a different metric.
  5. Store significant findings in analysis_insights with severity (critical/warning/info/positive) and evidence JSON. Always write to Supabase, then phf pull to sync locally.
  6. All timestamps in the database are UTC. Fitbit returns device-local time; if TIMEZONE is set in .env, the sync converts to real UTC. If unset, timestamps are stored as-is with +00:00 offset (may be inaccurate for non-UTC users). Convert to user's timezone for display.
  7. Check medication_logs when correlating metrics -- medications affect heart rate, HRV, sleep, etc.
  8. Naps are compensatory, not restorative. More naps usually means worse night sleep.
  9. lab_results column names: parameter (not biomarker), value_numeric (not value), status (not flag).
  10. 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:

  1. Check data freshness: phf status
  2. Read HEALTH_CONTEXT.md for user baselines and conditions
  3. Query recent RHR/HRV trends (don't rely on stale summaries)
  4. Check lab_reports dates -- don't cite old lab numbers as "current"
  5. 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 -->

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.