iOS Issue: HealthKit Sleep Category Data Not Exported

Title: Missing HKCategoryTypeIdentifierSleepAnalysis in HealthKit export

Priority: High (blocks accurate sleep tracking in coach)

Affected: P247 iOS app → HealthKit export → Backend → Coach/Brief system


Problem

The iOS app’s HealthKit export is missing sleep category data. When the app pulls HealthKit data and exports it to the backend, it includes workouts, steps, heart rate, and other metrics — but zero sleep entries.

This causes:

  1. Backend coach receives no HealthKit sleep data
  2. System falls back to SleepCycle data (which is often inaccurate)
  3. Coach gives wrong sleep feedback (e.g., saying 17.8 hours when actual HealthKit shows 7h 50min)

Root Cause

The HealthKit request doesn’t include the sleep category:

  • HKCategoryTypeIdentifierSleepAnalysis (sleep data) — NOT requested
  • App requests workouts, steps, HR, etc., but not sleep

Solution

Add sleep category to the HealthKit request and export it.

Implementation Steps

  1. Add sleep to HealthKit request permissions:
    • Request HKCategoryTypeIdentifierSleepAnalysis permission during onboarding
    • Ask for “Read” permission (user allows app to read sleep data from Apple Health)
  2. Export sleep data in the daily HealthKit export:
    • Query HKCategoryTypeIdentifierSleepAnalysis for the past 7+ days
    • Include in the /health/apple/latest.json export (currently empty for sleep)
    • Structure:
      {
        "results": {
          "HKCategoryTypeIdentifierSleepAnalysis": [
            {
              "startDate": "2026-03-22T22:30:00Z",
              "endDate": "2026-03-23T06:20:00Z",
              "value": "HKCategoryValueSleepAnalysisAsleep"
            }
          ]
        }
      }
      
  3. Backend will then:
    • Parse sleep start/end times
    • Calculate total sleep hours, core/deep/REM/awake breakdown
    • Write to daily-metrics.json with sleep_source: "healthkit"
    • Coach will use this data instead of SleepCycle

Test

  1. Pull 7 days of HealthKit data via the app
  2. Check /health/apple/latest.json — should have entries in HKCategoryTypeIdentifierSleepAnalysis
  3. Backend auto-syncs and updates daily-metrics.json with accurate sleep hours
  4. Coach feedback now matches actual HealthKit sleep data

Questions?

Backend will auto-parse and sync once the data is exported. No backend changes needed — we’re ready to receive it.


Original Issue: Coach hallucinating sleep data from SleepCycle (17.8h) when actual HealthKit shows 7h 50min.