// 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.importCottonKitimportFoundationimportHealthKit/// One HealthKit type as the core names it (`health.types`).structHealthReadType: Decodable, Sendable, Equatable {let healthkit: Stringlet kind: Stringvar unit: String? = nillet 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 { returntrue }guardlet quantity = sampleType as? HKQuantityType,let unit = unit.flatMap({ $0.isEmpty ? nil : HKUnit(from: $0) }), quantity.is(compatibleWith: unit) else { returnfalse }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.publicenumHealthReadOutcome: 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 CottonCallinglet store = HKHealthStore()/// Samples per anchored page.staticlet page = 2000publicinit(core: any CottonCalling) {self.core = core }/// The core's types, and Apple Health's asking attached with them.func types() asyncthrows -> [HealthReadType] {structTypes: Decodable { let types: [HealthReadType] }let types = tryawait core.call(CottonMethod.healthTypes, as: Types.self).typesSystemCapabilityAuthority.attachAppleHealth(AppleHealthAccess(read: Set(types.filter(\.statisticsFit).flatMap(\.asked))))return types }/// Ask (at this act, never before), then read every type since its anchor.publicfunc read(asking authority: any CapabilityAuthority = SystemCapabilityAuthority()) async -> HealthReadOutcome {let types: [HealthReadType]do { types = tryawaitself.types() } catch { return .failed(Self.said(error)) }guardawait authority.gate([.appleHealth]).isReady else { return .unavailable }guardawait keyHeld() else { return .locked }var changed = 0for type in types where type.anchored && type.statisticsFit {switchawait readType(type, types: types) {case .success(let count): changed += countcase .failure(.locked): return .lockedcase .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.publicfunc readAnswered() async -> HealthReadOutcome { _ = try? await types()guardawaitSystemCapabilityAuthority().status(.appleHealth) == .authorized else { return .unavailable }returnawait read() }enumRefusal: Error { case locked, said(String) }func keyHeld() async -> Bool {guardlet status = try? await core.callJSON(CottonMethod.sealStatus) else { returnfalse }return status["keyHeld"]?.bool == true }// MARK: - One type, page by pagefunc readType(_ type: HealthReadType, types: [HealthReadType]) async -> Result<Int, Refusal> {guardlet sampleType = type.sampleType else { return .success(0) }var anchor = await kept(type.healthkit)var changed = 0var deletions = falsewhiletrue {let descriptor = HKAnchoredObjectQueryDescriptor(predicates: [.sample(type: sampleType)], anchor: anchor, limit: Self.page)let page: HKAnchoredObjectQueryDescriptor<HKSample>.Resultdo { page = tryawait descriptor.result(for: store) } catch { return .failure(.said(Self.said(error))) }var batch = HealthBatch()do {tryawait 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)switchawait land(batch, anchors: next.map { [type.healthkit: $0] } ?? [:]) {case .success(let count): changed += countcase .failure(let refusal): return .failure(refusal) } anchor = page.newAnchorif 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 {switchawait refold(type) {case .success(let count): changed += countcase .failure(let refusal): return .failure(refusal) } }return .success(changed) }/// Days per refold batch: a day's statistics, or a category's samples.staticlet 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<Int, Refusal> {structAsk: Encodable { let type: String }guardlet 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.samplesvar changed = 0for start in stride(from: 0, to: all.count, by: size) {let days = Array(all[start..<min(start + size, all.count)])var batch = HealthBatch()do {if type.sends.contains("days"), let quantity = type.sampleType as? HKQuantityType,let unit = type.unit.flatMap({ $0.isEmpty ? nil : HKUnit(from: $0) }) { batch.days = tryawait dayStatistics(quantity, option: type.statistics, unit: unit, days: days) } elseiflet category = type.sampleType as? HKCategoryType, let from = days.first, let to = days.last {tryawait batch.takeWhole(category, of: type, from: from, to: to, reader: self) } } catch {return .failure(.said(Self.said(error))) }switchawait land(batch, anchors: [:]) {case .success(let count): changed += countcase .failure(let refusal): return .failure(refusal) } }return .success(changed) }func kept(_ healthkit: String) async -> HKQueryAnchor? {structAsk: Encodable { let type: String }guardlet answer = try? await core.callJSON(CottonMethod.healthAnchor, Ask(type: healthkit)),let text = answer["anchor"]?.string, let data = Data(base64Encoded: text) else { returnnil }returntry? NSKeyedUnarchiver.unarchivedObject(ofClass: HKQueryAnchor.self, from: data) }staticfunc archived(_ anchor: HKQueryAnchor) -> String? { (try? NSKeyedArchiver.archivedData(withRootObject: anchor, requiringSecureCoding: true))?.base64EncodedString() }func land(_ batch: HealthBatch, anchors: [String: String]) async -> Result<Int, Refusal> {do {let landed = tryawait core.callJSON(CottonMethod.healthLand, batch.request(anchors: anchors))return .success((landed["put"]?.int ?? 0) + (landed["removed"]?.int ?? 0)) } catchlet error asCottonCallErrorwhere error.code == "seal_key_missing" {return .failure(.locked) } catch {return .failure(.said(Self.said(error))) } }staticfunc 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]) asyncthrows -> [JSONValue] {guardlet 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": .cumulativeSumcase"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 = tryawait descriptor.result(for: store)return days.map { day invar entry: [String: JSONValue] = ["type": .string(type.identifier), "day": .string(day)]guardlet start = HealthDays.start(of: day), let statistics = collection.statistics(for: start) else { entry["value"] = .nullreturn .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)) } ?? .nullif option == "discreteAverage" {iflet least = statistics.minimumQuantity() { entry["min"] = .number(least.doubleValue(for: unit)) }iflet 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) asyncthrows -> [HKCategorySample] {guardlet 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)])returntryawait descriptor.result(for: store) }}/// Local days, as the core keys them (`YYYY-MM-DD` where the device stands).enumHealthDays {staticvar calendar: Calendar {var calendar = Calendar(identifier: .gregorian) calendar.timeZone = .currentreturn calendar }staticfunc day(_ date: Date) -> String {let parts = calendar.dateComponents([.year, .month, .day], from: date)returnString(format: "%04d-%02d-%02d", parts.year ?? 0, parts.month ?? 0, parts.day ?? 0) }staticfunc start(of day: String) -> Date? {let parts = day.split(separator: "-").compactMap { Int($0) }guard parts.count == 3else { returnnil }return calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2])) }/// Every day `from` to `to` (`YYYY-MM-DD`), inclusive.staticfunc between(_ from: String, _ to: String) -> [String] {guardlet first = start(of: from), let last = start(of: to) else { return [] }var out: [String] = []var at = firstwhile at <= last { out.append(day(at))guardlet 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.staticfunc 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))guardlet 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").staticfunc instant(_ date: Date) -> String {let format = ISO8601DateFormatter() format.timeZone = .current format.formatOptions = [.withInternetDateTime]return format.string(from: date) }}