// THE APPLE HEALTH READER (Cotton Health, 13 Nov 2026): what changed in // HealthKit since this device's anchors, read type by type and landed in the // person's own database through the core (`health.land`), sealed there. The // core says which types to read and what to send for each (`health.types`) // and folds every day; this file only queries HealthKit and says what it // found, in the shape `cotton_core::health::land` reads. // // * One anchored query per type, a page of samples at a time; each page's // batch lands with that type's new anchor, which the core keeps only // once every row of it has landed. A refused batch advances nothing. // * Days: the day's statistics for every day the page touched, at local // midnight, in the type's unit; a touched day now holding nothing is // sent as `value: null`, and its row goes. // * Intervals (sleep, mindful minutes, stand hours, the period's flow): // every sample touching the page's days, sent whole. // * Workouts and measurements: each sample, with its uuid; deleted // objects by uuid. // // Read-only: nothing here writes to HealthKit. Nothing reads before the gate // (`DeviceCapability.appleHealth`) answered and the data key is held. import CottonKit import Foundation import HealthKit /// One HealthKit type as the core names it (`health.types`). struct HealthReadType: Decodable, Sendable, Equatable { let healthkit: String let kind: String var unit: String? = nil let sends: [String] var statistics: String? = nil /// The types HealthKit is asked to read for this one: a correlation is /// never asked for itself, only through its parts (blood pressure /// through its systolic and diastolic types), whose samples it holds. var asked: [HKObjectType] { guard kind == "correlation" else { return sampleType.map { [$0] } ?? [] } return healthkit == HKCorrelationTypeIdentifier.bloodPressure.rawValue ? [HKQuantityType(.bloodPressureSystolic), HKQuantityType(.bloodPressureDiastolic)] : [] } /// What `health.land` refolds when HealthKit reports a deletion: a day's /// number or a category's days, whose samples a deleted object no longer /// names. var refolds: Bool { sends.contains("days") || sends.contains("intervals") } /// The type queried for its samples. Made by HealthKit's optional /// factories: an identifier this iOS does not know is no type (it is /// not read), never the exception the throwing initialisers raise. var sampleType: HKSampleType? { switch kind { case "quantity": HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier(rawValue: healthkit)) case "category": HKObjectType.categoryType(forIdentifier: HKCategoryTypeIdentifier(rawValue: healthkit)) case "correlation": HKObjectType.correlationType(forIdentifier: HKCorrelationTypeIdentifier(rawValue: healthkit)) case "workout": HKWorkoutType.workoutType() default: nil } } /// Can HealthKit answer the statistics the core asks of this type? A /// cumulative type sums and a discrete one averages or keeps its last; /// asked the other way HealthKit raises. `HealthTypesTests` holds every /// type the core names to this; a type that fails it is not read. var statisticsFit: Bool { guard sends.contains("days") else { return true } guard let quantity = sampleType as? HKQuantityType, let unit = unit.flatMap({ $0.isEmpty ? nil : HKUnit(from: $0) }), quantity.is(compatibleWith: unit) else { return false } return (quantity.aggregationStyle == .cumulative) == (statistics == "cumulativeSum") } /// Read by its own anchored query: a type sent only for a workout's /// statistics (heart rate) is read with the workout instead. var anchored: Bool { sends.contains { $0 != "workouts" } || kind == "workout" } } /// How one read went, for the door to say. public enum HealthReadOutcome: Equatable, Sendable { /// Rows put or removed, summed over every batch. case read(changed: Int) /// This device holds no data key yet: the rows are sealed. case locked /// HealthKit is not on this device, or the person was not asked. case unavailable /// A batch was refused or a query failed; what the core or HealthKit said. case failed(String) } /// Reads HealthKit into the open database. One read at a time: a second /// asked while one runs waits for it. public actor HealthReader { let core: any CottonCalling let store = HKHealthStore() /// Samples per anchored page. static let page = 2000 public init(core: any CottonCalling) { self.core = core } /// The core's types, and Apple Health's asking attached with them. func types() async throws -> [HealthReadType] { struct Types: Decodable { let types: [HealthReadType] } let types = try await core.call(CottonMethod.healthTypes, as: Types.self).types SystemCapabilityAuthority.attachAppleHealth(AppleHealthAccess(read: Set(types.filter(\.statisticsFit).flatMap(\.asked)))) return types } /// Ask (at this act, never before), then read every type since its anchor. public func read(asking authority: any CapabilityAuthority = SystemCapabilityAuthority()) async -> HealthReadOutcome { let types: [HealthReadType] do { types = try await self.types() } catch { return .failed(Self.said(error)) } guard await authority.gate([.appleHealth]).isReady else { return .unavailable } guard await keyHeld() else { return .locked } var changed = 0 for type in types where type.anchored && type.statisticsFit { switch await readType(type, types: types) { case .success(let count): changed += count case .failure(.locked): return .locked case .failure(.said(let why)): return .failed(why) } } return .read(changed: changed) } /// Read without asking: what an observer's wake does, only once the /// person has answered. public func readAnswered() async -> HealthReadOutcome { _ = try? await types() guard await SystemCapabilityAuthority().status(.appleHealth) == .authorized else { return .unavailable } return await read() } enum Refusal: Error { case locked, said(String) } func keyHeld() async -> Bool { guard let status = try? await core.callJSON(CottonMethod.sealStatus) else { return false } return status["keyHeld"]?.bool == true } // MARK: - One type, page by page func readType(_ type: HealthReadType, types: [HealthReadType]) async -> Result { guard let sampleType = type.sampleType else { return .success(0) } var anchor = await kept(type.healthkit) var changed = 0 var deletions = false while true { let descriptor = HKAnchoredObjectQueryDescriptor(predicates: [.sample(type: sampleType)], anchor: anchor, limit: Self.page) let page: HKAnchoredObjectQueryDescriptor.Result do { page = try await descriptor.result(for: store) } catch { return .failure(.said(Self.said(error))) } var batch = HealthBatch() do { try await batch.take(page.addedSamples, of: type, from: self) } catch { return .failure(.said(Self.said(error))) } batch.deleted = page.deletedObjects.map(\.uuid.uuidString) deletions = deletions || (anchor != nil && !page.deletedObjects.isEmpty) let next = Self.archived(page.newAnchor) switch await land(batch, anchors: next.map { [type.healthkit: $0] } ?? [:]) { case .success(let count): changed += count case .failure(let refusal): return .failure(refusal) } anchor = page.newAnchor if page.addedSamples.count + page.deletedObjects.count < Self.page { break } } // A deleted sample names no day: the days it fed are read again, // every day this database holds of the type to today. if deletions && type.refolds { switch await refold(type) { case .success(let count): changed += count case .failure(let refusal): return .failure(refusal) } } return .success(changed) } /// Days per refold batch: a day's statistics, or a category's samples. static let refoldDays = (statistics: 120, samples: 31) /// Every day of `type` from the first this database holds to today, sent /// whole: a day's statistics (none, and its row goes) or a category's /// samples folded again. No anchor moves: the pages already kept it. func refold(_ type: HealthReadType) async -> Result { struct Ask: Encodable { let type: String } guard let held = try? await core.callJSON(CottonMethod.healthHeld, Ask(type: type.healthkit)), let first = held["from"]?.string else { return .success(0) } let today = HealthDays.day(Date()) let all = HealthDays.between(first, max(first, today)) let size = type.sends.contains("days") ? Self.refoldDays.statistics : Self.refoldDays.samples var changed = 0 for start in stride(from: 0, to: all.count, by: size) { let days = Array(all[start.. HKQueryAnchor? { struct Ask: Encodable { let type: String } guard let answer = try? await core.callJSON(CottonMethod.healthAnchor, Ask(type: healthkit)), let text = answer["anchor"]?.string, let data = Data(base64Encoded: text) else { return nil } return try? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: data) } static func archived(_ anchor: HKQueryAnchor) -> String? { (try? NSKeyedArchiver.archivedData(withRootObject: anchor, requiringSecureCoding: true))?.base64EncodedString() } func land(_ batch: HealthBatch, anchors: [String: String]) async -> Result { do { let landed = try await core.callJSON(CottonMethod.healthLand, batch.request(anchors: anchors)) return .success((landed["put"]?.int ?? 0) + (landed["removed"]?.int ?? 0)) } catch let error as CottonCallError where error.code == "seal_key_missing" { return .failure(.locked) } catch { return .failure(.said(Self.said(error))) } } static func said(_ error: any Error) -> String { (error as? CottonCallError)?.message ?? error.localizedDescription } // MARK: - Queries a page needs /// The day's statistics for each of `days` (local midnight to midnight). func dayStatistics(_ type: HKQuantityType, option: String?, unit: HKUnit, days: [String]) async throws -> [JSONValue] { guard let first = days.first, let last = days.last, let from = HealthDays.start(of: first), let lastStart = HealthDays.start(of: last), let to = HealthDays.calendar.date(byAdding: .day, value: 1, to: lastStart) else { return [] } let options: HKStatisticsOptions = switch option { case "cumulativeSum": .cumulativeSum case "discreteAverage": [.discreteAverage, .discreteMin, .discreteMax] default: .mostRecent } let descriptor = HKStatisticsCollectionQueryDescriptor( predicate: .quantitySample(type: type, predicate: HKQuery.predicateForSamples(withStart: from, end: to)), options: options, anchorDate: from, intervalComponents: DateComponents(day: 1)) let collection = try await descriptor.result(for: store) return days.map { day in var entry: [String: JSONValue] = ["type": .string(type.identifier), "day": .string(day)] guard let start = HealthDays.start(of: day), let statistics = collection.statistics(for: start) else { entry["value"] = .null return .object(entry) } let value: HKQuantity? = switch option { case "cumulativeSum": statistics.sumQuantity() case "discreteAverage": statistics.averageQuantity() default: statistics.mostRecentQuantity() } entry["value"] = value.map { .number($0.doubleValue(for: unit)) } ?? .null if option == "discreteAverage" { if let least = statistics.minimumQuantity() { entry["min"] = .number(least.doubleValue(for: unit)) } if let most = statistics.maximumQuantity() { entry["max"] = .number(most.doubleValue(for: unit)) } } return .object(entry) } } /// Every sample of a category type touching `from`…`to`, whole. func samples(_ type: HKCategoryType, from: String, to: String) async throws -> [HKCategorySample] { guard let start = HealthDays.start(of: from), let lastStart = HealthDays.start(of: to), let end = HealthDays.calendar.date(byAdding: .day, value: 1, to: lastStart) else { return [] } let descriptor = HKSampleQueryDescriptor( predicates: [.categorySample(type: type, predicate: HKQuery.predicateForSamples(withStart: start, end: end))], sortDescriptors: [SortDescriptor(\.startDate)]) return try await descriptor.result(for: store) } } /// Local days, as the core keys them (`YYYY-MM-DD` where the device stands). enum HealthDays { static var calendar: Calendar { var calendar = Calendar(identifier: .gregorian) calendar.timeZone = .current return calendar } static func day(_ date: Date) -> String { let parts = calendar.dateComponents([.year, .month, .day], from: date) return String(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0) } static func start(of day: String) -> Date? { let parts = day.split(separator: "-").compactMap { Int($0) } guard parts.count == 3 else { return nil } return calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2])) } /// Every day `from` to `to` (`YYYY-MM-DD`), inclusive. static func between(_ from: String, _ to: String) -> [String] { guard let first = start(of: from), let last = start(of: to) else { return [] } var out: [String] = [] var at = first while at <= last { out.append(day(at)) guard let next = calendar.date(byAdding: .day, value: 1, to: at) else { break } at = next } return out } /// Every day from the one `start` falls on to the one `end` falls on. static func touched(_ start: Date, _ end: Date) -> [String] { var out: [String] = [] var at = calendar.startOfDay(for: start) let last = calendar.startOfDay(for: max(start, end)) while at <= last, out.count < 400 { out.append(day(at)) guard let next = calendar.date(byAdding: .day, value: 1, to: at) else { break } at = next } return out } /// An instant with this device's offset ("2026-11-12T06:40:00+05:30"). static func instant(_ date: Date) -> String { let format = ISO8601DateFormatter() format.timeZone = .current format.formatOptions = [.withInternetDateTime] return format.string(from: date) } }