// COTTON HEALTH'S ENGINE (13 Nov 2026): attached at launch by the app that// links HealthKit (`App/Cotton/CottonApp.swift`, `COTTON_HEALTH`). It does// two things and asks the person nothing://// * It attaches the Read Apple Health door's reader (`DeviceReadings`):// the door's tap is the one place the person is asked.// * Once the person HAS answered (`status`, which never prompts), it keeps// an observer on every type and asks HealthKit for hourly background// delivery, so what the watch and phone record lands without opening// the app. Registered at launch, before the first frame, as HealthKit// needs to find them when it wakes the app; and again after the door's// first read, the first time there is an answer to stand on.importCottonKitimportCottonUIimportFoundationimportHealthKit@MainActorpublicfinalclassHealthEngine {publicstaticlet shared = HealthEngine()privatevaropen: (@Sendable () async -> (any CottonCalling)?)?privatevar reader: HealthReader?privatevar observing = falseprivatelet store = HKHealthStore()/// Attach the door's reader and, where the person already answered, the/// observers. `open` gives the core once it is open.publicfunc attach(_ open: @escaping @Sendable () async -> (any CottonCalling)?) {self.open = openDeviceReadings.reader = AppleHealthDoor(engine: self)Task { await observe() } }/// The one reader over the open core.func reader(_ core: any CottonCalling) -> HealthReader {iflet reader { return reader }let made = HealthReader(core: core) reader = madereturn made }/// Observers and background delivery for every read type, once the/// person has answered; nothing at all before that.func observe() async {guard !observing, letopen, let core = awaitopen() else { return }let reader = reader(core)guardlet types = try? await reader.types(),awaitSystemCapabilityAuthority().status(.appleHealth) == .authorized else { return } observing = truefor type in types where type.anchored && type.statisticsFit {guardlet sampleType = type.sampleType else { continue } store.execute(Self.observer(sampleType, reader: reader))try? await store.enableBackgroundDelivery(for: sampleType, frequency: .hourly) } }/// An observer that reads what changed and then tells HealthKit it is/// done. Built `nonisolated`: HealthKit calls it off the main queue, and/// a handler written inside this main-actor type would carry a/// main-queue assertion into that call. nonisolated staticfunc observer(_ type: HKSampleType, reader: HealthReader) -> HKObserverQuery { HKObserverQuery(sampleType: type, predicate: nil) { _, finished, error inlet done = ObserverDone(finished)guard error == nilelse { return done.call() }Task { _ = await reader.readAnswered() done.call() } } }}/// HealthKit's completion for one observer wake, called once the read is done.privatefinalclassObserverDone: @unchecked Sendable {let call: () -> Voidinit(_ call: @escaping () -> Void) {self.call = call }}/// The Read Apple Health door: ask, read, say it.structAppleHealthDoor: DeviceReading {let engine: HealthEnginefunc read(_ reads: DefinitionDeviceReads, core: any CottonCalling) async -> DeviceReadSaid {let reader = await engine.reader(core)let outcome = await reader.read()await engine.observe()returnSelf.said(outcome) }staticfunc said(_ outcome: HealthReadOutcome) -> DeviceReadSaid {switch outcome {case .read(let changed) where changed == 0:DeviceReadSaid(line: ShellLines.line("cards", "health.read.nothing"), failed: false)case .read(let changed):DeviceReadSaid(line: ShellLines.line("cards", "health.read.landed", ["n": "\(changed)"]), failed: false)case .locked:DeviceReadSaid(line: ShellLines.line("cards", "health.read.locked"), failed: true)case .unavailable:DeviceReadSaid(line: ShellLines.line("cards", "health.read.unavailable"), failed: true)case .failed(let why):DeviceReadSaid(line: ShellLines.line("cards", "health.read.failed", ["why": why]), failed: true) } }}