> For the complete documentation index, see [llms.txt](https://docs.tryterra.co/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.tryterra.co/reference/mobile-sdks/ios-sdk-2.md).

# iOS SDK

Every public type and member of TerraSDK, the iOS SDK: signatures, parameters, return values and errors.

This is the reference for `TerraiOS` 2.x, whose Swift module is `TerraSDK`. For setup and a walkthrough, read the [iOS SDK guide](https://docs.tryterra.co/mobile-sdks/ios-sdk-2). Every call is `async`, and every call that can fail throws a [`TerraError`](#terraerror).

```swift
import TerraSDK
```

## Setup

### Terra

The Terra client: the entry point to every call in the SDK.

```swift
public final class Terra: Sendable
```

`Terra` is a value you construct, not a singleton. Build one per app, at launch, and keep it. Every client in an app shares one stored state, which belongs to the first dev ID that runs against it. Another dev ID gets `TerraError.devIDMismatch` from `connect`, `disconnect` and every sync run, so an app uses one dev ID.

#### Terra.init

Creates a client with the production HealthKit store, Keychain storage and Terra backend wired in.

```swift
@available(iOSApplicationExtension, unavailable)
public convenience init(
    devID: String,
    tokenProvider: (@Sendable () async throws -> String)? = nil,
    dayTotals: DayTotalPolicy = .default,
    devIDMode: DevIDMode = .single
)
```

For an app extension, which cannot reach `UIApplication`, use this one instead:

```swift
public convenience init(
    devID: String,
    tokenProvider: (@Sendable () async throws -> String)? = nil,
    backgroundRestricted: @escaping @Sendable () async -> Bool,
    inBackground: @escaping @Sendable () async -> Bool = { false },
    unlocks: (@Sendable () -> AsyncStream<Void>)? = nil,
    dayTotals: DayTotalPolicy = .default
)
```

| Name                   | Type                                     | Description                                                                                                                                                                                                                                         |
| ---------------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `devID`                | `String`                                 | Your Terra developer ID. Configuration, not a credential.                                                                                                                                                                                           |
| `tokenProvider`        | `(@Sendable () async throws -> String)?` | The closure that returns a fresh auth token from your backend. The SDK calls it only when `connect` needs a new link, never on a restored launch. Optional. Defaults to `nil`: pass the token to [`connect(_:for:using:)`](#terra.connect) instead. |
| `dayTotals`            | [`DayTotalPolicy`](#daytotalpolicy)      | What the uploaded day totals and `daily.steps(in:)` count. Optional. Defaults to `.default`.                                                                                                                                                        |
| `devIDMode`            | [`DevIDMode`](#devidmode)                | `.single` for every integration except a connector app that several Terra customers link the same person through, which passes `.multiple`. App initialiser only. Optional. Defaults to `.single`. Available in 2.3.0 and later.                    |
| `backgroundRestricted` | `@escaping @Sendable () async -> Bool`   | Extension initialiser only. The closure that answers whether iOS refuses this app background work. Pass `{ false }` when unknown, so `.backgroundRestricted` is omitted rather than misreported.                                                    |
| `inBackground`         | `@escaping @Sendable () async -> Bool`   | Extension initialiser only. The closure that answers whether the process is in the background right now. Optional. Defaults to `{ false }`.                                                                                                         |
| `unlocks`              | `(@Sendable () -> AsyncStream<Void>)?`   | Extension initialiser only. A stream that fires when the device is unlocked. Optional. Defaults to `nil`, which uses the system notification.                                                                                                       |

**Returns:** a `Terra` client. The initialisers are synchronous. They start background work, such as resending a key revoke a disconnect still owes Terra, and return without waiting for it.

An extension client keeps its own storage and sees its own connection and delivery history, not the host app's, and it never syncs automatically. To share state between the host and an extension, use an App Group and a Keychain access group.

```swift
let terra = Terra(devID: "<YOUR_DEV_ID>") {
    try await yourBackend.mintTerraToken()
}
```

{% hint style="warning" %}
The token provider runs off the main actor and outlives the call that built it. Capture what it needs, not a view.
{% endhint %}

#### Terra.connect

Links this device to a Terra user for `endUser`, or restores the link made for them.

```swift
@discardableResult
public func connect(_ source: Source, for endUser: EndUser) async throws -> Connection

@discardableResult
public func connect(_ source: Source, for endUser: EndUser, using token: String) async throws -> Connection
```

| Name      | Type                  | Description                                                                        |
| --------- | --------------------- | ---------------------------------------------------------------------------------- |
| `source`  | [`Source`](#source)   | The source to connect. `.health` is Apple Health.                                  |
| `endUser` | [`EndUser`](#enduser) | The person this connection is for. Required.                                       |
| `token`   | `String`              | An auth token you already hold, for example from a scanned QR code or a deep link. |

**Returns:** the [`Connection`](#connection).

A connect names the person it is for, so a stored link is only restored for the person it was made for:

| Stored link                                                                         | Result                                                                                                                      |
| ----------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| None                                                                                | Links with a token from the token provider.                                                                                 |
| Made for the same `endUser`                                                         | Restored from the Keychain with no network call.                                                                            |
| Made for a different end user (another reference, or reference versus `.anonymous`) | The stored link is retired as [`disconnect`](#connection.disconnect) retires it, then the device links again for `endUser`. |
| Made before end users were recorded                                                 | Kept, and recorded as `endUser`'s. No network call.                                                                         |

A restore makes no network call, so a normal launch works offline and never calls the token provider. The token provider is also called when the stored link has no signing key (for example after a restored backup), or when Terra stopped accepting the device's key. With a token, `connect(_:for:using:)` always links fresh, records `endUser`, and never returns the stored connection.

`connect` does not upload anything itself. When the app had already requested access, a sync starts in the background after a new link, and `connect` returns without waiting for it.

| Error                              | When                                                                                                                    |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `TerraError.healthDataUnavailable` | The device has no health store.                                                                                         |
| `TerraError.devIDMismatch`         | The stored link, or the storage domain, belongs to a different dev ID.                                                  |
| `TerraError.linkRevoked`           | Terra stopped accepting the stored link's key and there is no token provider to link again.                             |
| `TerraError.linkAlreadyRunning`    | Another link for this source is in progress.                                                                            |
| `TerraError.tokenUnavailable`      | A new link is needed and there is neither a token nor a token provider.                                                 |
| `TerraError.tokenProviderFailed`   | Your token provider threw. The error it threw is carried unchanged.                                                     |
| `TerraError.tokenRejected`         | The token was expired, already spent or unknown. With a token provider, the SDK asks it once more before throwing this. |
| `TerraError.userLimitReached`      | Your Terra plan has no room for another connected user.                                                                 |
| `TerraError.network`               | The link request failed in transit or Terra returned an error status.                                                   |

#### Terra.connections

The connections that are linked on this device and can still deliver.

```swift
public var connections: [Connection] { get async throws }
```

**Returns:** one [`Connection`](#connection) per linked source. A link Terra has revoked, a link from another dev ID, or a link whose signing key is gone is not listed.

**Throws:** a `TerraError` when stored state cannot be read. It throws rather than answering an empty list, so a storage failure is never mistaken for "not connected".

#### Terra.permissions

The permission namespace.

```swift
public var permissions: Permissions { get }
```

**Returns:** the [`Permissions`](#permissions) namespace.

#### Terra.diagnostics

The diagnostics namespace: why data is or is not arriving, and what the SDK has been doing.

```swift
public var diagnostics: Diagnostics { get }
```

**Returns:** the [`Diagnostics`](#diagnostics) namespace.

#### Terra.body

The `body` namespace: heart rate and body reads, body writes and change hints.

```swift
public var body: BodyMetrics { get }
```

**Returns:** the [`BodyMetrics`](#bodymetrics) namespace.

#### Terra.daily

The `daily` namespace: step and day total reads, step writes and change hints.

```swift
public var daily: DailyMetrics { get }
```

**Returns:** the [`DailyMetrics`](#dailymetrics) namespace.

#### Terra.sleep

The `sleep` namespace: sleep stage reads, writes and change hints.

```swift
public var sleep: SleepMetrics { get }
```

**Returns:** the [`SleepMetrics`](#sleepmetrics) namespace.

#### Terra.activity

The `activity` namespace: workout, route and intensity reads, workout writes and change hints.

```swift
public var activity: ActivityMetrics { get }
```

**Returns:** the [`ActivityMetrics`](#activitymetrics) namespace.

#### Terra.nutrition

The `nutrition` namespace: nutrient and water reads, and meal writes. The reads are available in 2.2.0 and later.

```swift
public var nutrition: NutritionMetrics { get }
```

**Returns:** the [`NutritionMetrics`](#nutritionmetrics) namespace.

#### Terra.menstruation

The `menstruation` namespace: menstrual flow and cycle event reads. Available in 2.2.0 and later.

```swift
public var menstruation: MenstruationMetrics { get }
```

**Returns:** the [`MenstruationMetrics`](#menstruationmetrics) namespace.

#### Terra.athlete

The `athlete` namespace: the person's characteristics. Available in 2.2.0 and later.

```swift
public var athlete: AthleteMetrics { get }
```

**Returns:** the [`AthleteMetrics`](#athletemetrics) namespace.

#### Terra.availability

Returns whether this device has the health store a source reads from. Available in 2.2.0 and later.

```swift
public func availability(for source: Source = .health) async -> StoreAvailability
```

| Name     | Type                | Description                                           |
| -------- | ------------------- | ----------------------------------------------------- |
| `source` | [`Source`](#source) | The source to check. Optional. Defaults to `.health`. |

**Returns:** `.available` when `HKHealthStore.isHealthDataAvailable()` is `true`, otherwise `.unsupportedDevice`. HealthKit is missing on a Mac and on an iPad before iPadOS 17.

It needs no connection, never throws and presents no sheet, so you can call it before `connect` to decide whether to offer Apple Health at all.

```swift
if await terra.availability() == .unsupportedDevice {
    hideHealthSettings()
}
```

#### Terra.linkedDevIDs

The Terra customers linked to this installation, in [`DevIDMode.multiple`](#devidmode). Available in 2.3.0 and later.

```swift
public var linkedDevIDs: LinkedDevIDs { get }
```

**Returns:** the [`LinkedDevIDs`](#linkeddevids) namespace.

#### Terra.devIDMode

The mode this client was constructed in. Available in 2.3.0 and later.

```swift
public var devIDMode: DevIDMode { get }
```

**Returns:** a [`DevIDMode`](#devidmode).

### StoreAvailability

Whether a device has the health store a source reads from. Available in 2.2.0 and later.

```swift
public enum StoreAvailability: Sendable, Equatable
```

| Case                | Description                                                              |
| ------------------- | ------------------------------------------------------------------------ |
| `available`         | The device has HealthKit.                                                |
| `unsupportedDevice` | The device has no HealthKit store. No permission or update changes that. |

### DayTotalPolicy

Decides what the uploaded day totals and `daily.steps(in:)` count.

```swift
public struct DayTotalPolicy: Sendable, Equatable
```

| Property             | Type             | Description                                                                                                                                |
| -------------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `excludeUserEntered` | `Bool`           | Whether samples HealthKit marks as user-entered (`HKMetadataKeyWasUserEntered`) are left out of every day total and of `daily.steps(in:)`. |
| `default`            | `DayTotalPolicy` | Static. The policy that counts everything: HealthKit's own merge, unchanged.                                                               |

#### DayTotalPolicy.init

Creates a policy.

```swift
public init(excludeUserEntered: Bool = false)
```

| Name                 | Type   | Description                                                               |
| -------------------- | ------ | ------------------------------------------------------------------------- |
| `excludeUserEntered` | `Bool` | Whether to leave out hand-entered samples. Optional. Defaults to `false`. |

### DevIDMode

How many Terra dev IDs one installation serves. Available in 2.3.0 and later.

```swift
public enum DevIDMode: Sendable, Equatable
```

| Case       | Description                                                                                                                                                                                                                                                                                                                                                                                    |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `single`   | The default, and the mode for every integration but one kind. The first dev ID to run owns the storage domain, and any other gets `TerraError.devIDMismatch`.                                                                                                                                                                                                                                  |
| `multiple` | For a connector app that several Terra customers link the same person through, each with a link token their own backend minted. The installation keeps one connection per source, one device key and one read and upload pass. Each customer is added with [`linkedDevIDs.link`](#linkeddevids.link) instead of `connect`, and Terra delivers each customer only the data types they selected. |

The mode is recorded in the storage domain, so a single-mode client and a multiple-mode client cannot share one. Each is refused with `devIDMismatch` over the other's domain.

### LinkedDevIDs

The customers linked to this installation in [`DevIDMode.multiple`](#devidmode), reached through [`terra.linkedDevIDs`](#terra.linkeddevids). Available in 2.3.0 and later.

```swift
public struct LinkedDevIDs: Sendable
```

#### LinkedDevIDs.link

Links a customer's connection to this installation with a link token that customer minted.

```swift
@discardableResult
public func link(
    _ devID: String, using token: String, source: Source = .health
) async throws -> DevIDBinding
```

| Name     | Type                | Description                                                 |
| -------- | ------------------- | ----------------------------------------------------------- |
| `devID`  | `String`            | The customer's dev ID.                                      |
| `token`  | `String`            | A link token the customer's backend minted for this person. |
| `source` | [`Source`](#source) | The source to link. Optional. Defaults to `.health`.        |

**Returns:** the customer's [`DevIDBinding`](#devidbinding).

The first customer links the installation. Every later one joins the same link, so the installation still reads once and uploads once, and the new customer is sent the history the others already received. Linking a dev ID that is already linked replaces its binding.

| Error                     | When                                                                                                                    |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `TerraError.linkRefused`  | Terra will not register the shared key on this customer's connection. See [`LinkRefusal`](#linkrefusal). Not retryable. |
| `TerraError.linkConflict` | The link raced another request for the same key. Retryable.                                                             |

#### LinkedDevIDs.unlink

Stops delivering to one customer's connection and leaves every other customer linked.

```swift
public func unlink(_ devID: String, source: Source = .health) async throws
```

| Name     | Type                | Description                                  |
| -------- | ------------------- | -------------------------------------------- |
| `devID`  | `String`            | The customer's dev ID.                       |
| `source` | [`Source`](#source) | The source. Optional. Defaults to `.health`. |

The last customer's unlink disconnects the installation. It succeeds when `devID` is not linked, and when Terra cannot be reached: the removal is retried until Terra answers.

#### LinkedDevIDs.all

The customers currently linked, in the order they linked.

```swift
public func all(source: Source = .health, refresh: Bool = false) async throws -> [DevIDBinding]
```

| Name      | Type                | Description                                                                                                                                                                                                                     |
| --------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`  | [`Source`](#source) | The source. Optional. Defaults to `.health`.                                                                                                                                                                                    |
| `refresh` | `Bool`              | Ask Terra first, so `isActive` is current. Otherwise it is as of Terra's last answer, which is at most a day old while the app runs in the foreground and is refreshed by every link and unlink. Optional. Defaults to `false`. |

**Returns:** one [`DevIDBinding`](#devidbinding) per customer, including customers Terra no longer lists (`isActive` is `false`). `TerraEvent.Kind.devIDBindingChanged` reports each change.

### DevIDBinding

One customer linked to the installation in [`DevIDMode.multiple`](#devidmode). Available in 2.3.0 and later.

```swift
public struct DevIDBinding: Sendable, Equatable, Codable
```

| Property          | Type                | Description                                                                                                                                                               |
| ----------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `devID`           | `String`            | The customer's dev ID.                                                                                                                                                    |
| `userID`          | `String`            | Terra's `user_id` for this customer's connection, the one their webhooks name.                                                                                            |
| `dataTypes`       | `[UploadDataType]?` | The routes this customer selected, as Terra answered at link, or `nil` when it did not say.                                                                               |
| `linkedAt`        | `Date`              | When the binding was made.                                                                                                                                                |
| `unlinkOwedSince` | `Date?`             | Set when `unlink` could not reach Terra. The removal is retried until Terra has been told.                                                                                |
| `goneSince`       | `Date?`             | Set when Terra's answers no longer list this connection, for example because the customer removed it. Nothing is read or sent for it until a later answer lists it again. |
| `isActive`        | `Bool`              | Linked, and Terra still delivers to it.                                                                                                                                   |

### LinkRefusal

Why Terra will not register a shared device key on a customer's connection. `TerraError.linkRefused` carries it. Available in 2.3.0 and later.

```swift
public enum LinkRefusal: String, Sendable, Hashable, CaseIterable
```

| Case                 | Raw value                        | Description                                                      |
| -------------------- | -------------------------------- | ---------------------------------------------------------------- |
| `sharingDisabled`    | `device_key_sharing_disabled`    | Key sharing is switched off for this customer or deployment.     |
| `possessionRequired` | `device_key_possession_required` | The link carried no valid proof that the device holds the key.   |
| `heldByTenant`       | `device_key_held_by_tenant`      | Another connection of the same customer holds the key.           |
| `revoked`            | `device_key_revoked`             | Terra has revoked the key everywhere. Only a fresh key can link. |

### sdkVersion

The SDK version stamped into signed upload envelopes and upload request headers.

```swift
public let sdkVersion = "2.3.0"
```

## Connecting

### EndUser

The person a `connect` is for.

```swift
public enum EndUser: Sendable, Hashable {
    case reference(String)
    case anonymous
}
```

| Case                | Description                                                                               |
| ------------------- | ----------------------------------------------------------------------------------------- |
| `reference(String)` | Your ID for this person: the same value your backend puts in the token as `reference_id`. |
| `anonymous`         | No reference: one link per install. Use it only when you send no `reference_id`.          |

It decides one thing on the device, whether the stored link may be restored. It never reaches Terra as identity: Terra trusts only the reference inside the token. The SDK stores a salted hash of the reference, not the reference itself.

### Source

A data source the SDK can connect.

```swift
public enum Source: String, Sendable, Hashable, CaseIterable, Codable
```

| Case     | Description               |
| -------- | ------------------------- |
| `health` | Apple Health (HealthKit). |

The raw value is stored on the device, so case names are stable.

### Connection

A live link between this device and a Terra user.

```swift
public struct Connection: Sendable
```

A `Connection` is a value. Holding one keeps nothing alive, and getting one twice for the same source gives equal values. A connection from an earlier link refuses to act once that link has been replaced.

| Property        | Type                                  | Description                                                                                                                    |
| --------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `source`        | [`Source`](#source)                   | The source this link is for.                                                                                                   |
| `userID`        | `String`                              | The Terra `user_id` of this link: the ID your backend sees on webhooks and API reads.                                          |
| `workouts`      | [`PlannedWorkouts`](#plannedworkouts) | The workouts Terra has planned for the person on this connection.                                                              |
| `firstSyncDays` | `Int`                                 | Static. How far back the first automatic sync after a link reaches, in days: `730`, the same as Terra's web-provider backfill. |

#### Connection.disconnect

Forgets this connection on the device and tells Terra to stop accepting its key.

```swift
public func disconnect() async throws
```

`disconnect` is idempotent: it succeeds when nothing is stored. It also succeeds when the revoke does not reach Terra. The person is disconnected on the device, and the SDK sends the revoke again from a later launch. To remove the user from Terra, call [deauthenticateUser](https://docs.tryterra.co/reference/health-and-fitness-api/authentication#delete-auth-deauthenticateuser) from your backend.

| Error                      | When                                              |
| -------------------------- | ------------------------------------------------- |
| `TerraError.devIDMismatch` | The storage domain belongs to a different dev ID. |

```swift
for connection in try await terra.connections {
    try await connection.disconnect()
}
```

## Requesting permissions

### Permissions

The permission namespace, reached through [`terra.permissions`](#terra.permissions).

```swift
public struct Permissions: Sendable
```

#### Permissions.request

Requests read and write access for the given categories and types in one HealthKit sheet.

```swift
public func request(
    read: [DataCategory] = [], readTypes: [HealthDataType] = [],
    write: [DataCategory] = [], workouts: [WorkoutScope] = []
) async throws
```

| Name        | Type                                  | Description                                                                                                                                                                                                   |
| ----------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `read`      | [`[DataCategory]`](#datacategory)     | The categories to read. Optional. Defaults to `[]`.                                                                                                                                                           |
| `readTypes` | [`[HealthDataType]`](#healthdatatype) | Individual types to read, for an app whose consent screen and `NSHealthShareUsageDescription` name specific data. Optional. Defaults to `[]`. Available in 2.3.0 and later.                                   |
| `write`     | [`[DataCategory]`](#datacategory)     | The categories to write. Optional. Defaults to `[]`.                                                                                                                                                          |
| `workouts`  | [`[WorkoutScope]`](#workoutscope)     | The workout shapes your app writes, for an app that asks for less than the whole `activity` category. Each scope asks for the workout plus only the energy and distance it names. Optional. Defaults to `[]`. |

`write: [.activity]` asks for the workout and every type a workout can carry: active energy, and walking and running, cycling and swimming distance. To show fewer rows, leave `.activity` out of `write` and pass `workouts` instead. A runs-only app that passes `WorkoutScope(activity: .running, energy: true, distance: true)` is never shown a swimming row. Passing both covers the whole category, since `write: [.activity]` already includes every scope.

The SDK re-sends everything it has ever been asked for alongside the new categories, so calling it again is how you widen access. iOS shows a sheet only for types it has not asked about before, so a repeat call with nothing new shows nothing. When the call grants a category with an upload route the app had not requested before, a sync starts. A call that adds a type starts a sync even when it opens no new route, so the type's history is read straight away.

`.clinicalRecord` is ignored here, in either direction. Ask for Health Records with [`requestClinicalRecords()`](#permissions.requestclinicalrecords).

**Individual types.** When `readTypes` is not empty, the sheet names exactly those types and the types of any category in `read`. From then on the install is type-scoped: the SDK reads, observes and uploads only the requested types and the types of any category in `read`, across every later call. A route syncs only for the requested types it carries, and a field whose type was not requested is left out of the upload rather than sent as zero. A workout keeps its energy, distance and step totals only when `activeEnergy`, `distance` and `steps` are requested. Types join the same running union as categories, so nothing a sheet once named is dropped. An install that never passes `readTypes` keeps the category behaviour. [Permissions](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping#individual-types) lists the HealthKit types behind each `HealthDataType`.

| Error                                            | When                                                                                                                                                                                                                                    |
| ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TerraError.healthDataUnavailable`               | The device has no health store.                                                                                                                                                                                                         |
| `TerraError.authorizationUnavailableInExtension` | It was called from an app extension, which cannot present a sheet.                                                                                                                                                                      |
| `TerraError.distanceNotAttributable`             | A workout scope asks for distance on an activity that records none. Thrown before any sheet appears.                                                                                                                                    |
| `TerraError.workoutsRequired`                    | The running union holds `.workoutRoute`, `.speed`, `.power` or `.cyclingCadence` without `.workouts` or the whole `.activity` category. These are read through the workout they belong to. Thrown before anything is recorded or shown. |

```swift
// Writes body data and runs with their energy and distance, and nothing else.
try await terra.permissions.request(
    read: [.activity, .body, .daily, .sleep],
    write: [.body],
    workouts: [WorkoutScope(activity: .running, energy: true, distance: true)]
)
```

```swift
// Asks for exactly these types, and from then on reads and uploads nothing else.
try await terra.permissions.request(readTypes: [
    .workouts, .steps, .activeEnergy, .distance, .heartRate, .sleepAnalysis, .weight,
])
```

{% hint style="warning" %}
Never split reads and writes into two calls. A HealthKit sheet sets the app's authorization for every type it names to exactly what that sheet asked for, so a read-only sheet for a type you could write silently revokes the write. Always go through `permissions.request`.
{% endhint %}

#### Permissions.requestClinicalRecords

Asks for Apple Health Records on HealthKit's own Health Records sheet. Available in 2.3.0 and later.

```swift
public func requestClinicalRecords() async throws
```

This is the only way to ask for [`.clinicalRecord`](#datacategory). Before calling it:

* Have Health Records (`CLINICAL_RECORD`) enabled for your Terra client. Until then Terra refuses the route, the SDK reports `TerraError.dataTypeNotEnabled`, and it stops reading the route for up to a day at a time.
* Add the HealthKit capability's Clinical Health Records option: `health-records` in the `com.apple.developer.healthkit.access` entitlement.
* Add `NSHealthClinicalHealthRecordsShareUsageDescription` and `NSHealthShareUsageDescription` to your Info.plist.

The SDK sends clinical records to Terra as raw FHIR on the `clinicalRecord` route. There is no local read. iOS 16.4 added clinical notes, and a sheet shown on an earlier iOS never asked for them, so call it again after the person upgrades iOS. Calling it again is safe: HealthKit shows a sheet only for types it has not asked about.

| Error                                             | When                                                                                                           |
| ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `TerraError.healthRecordsUsageDescriptionMissing` | A usage string is missing from the Info.plist. Checked first, because HealthKit would otherwise crash the app. |
| `TerraError.healthRecordsUnavailable`             | The device cannot hold Health Records, for example in a region without the feature.                            |
| `TerraError.healthDataUnavailable`                | The device has no health store.                                                                                |

Nothing is recorded unless the request succeeds.

#### Permissions.writeStatus

Returns whether your app may write a category.

```swift
public func writeStatus(for category: DataCategory) async -> PermissionStatus
```

| Name       | Type                            | Description            |
| ---------- | ------------------------------- | ---------------------- |
| `category` | [`DataCategory`](#datacategory) | The category to check. |

**Returns:** a [`PermissionStatus`](#permissionstatus). Unlike `status(for:)`, a `.denied` here is real. `.unavailable` means the device has no health store.

For `.activity`, the answer covers every type your app asked to write there: all of them after `write: [.activity]`, or only the types your [`WorkoutScope`](#workoutscope)s name. It is `.granted` only when every one of them is granted. A single [`log`](#activitymetrics.log) checks only the types its entries carry, so a run can still log while this says `.denied`, for example over a refused swimming distance.

#### Permissions.status

Returns the read status for a category or, in 2.3.0 and later, a single type.

```swift
public func status(for category: DataCategory) async -> PermissionStatus
public func status(for type: HealthDataType) async -> PermissionStatus
```

| Name       | Type                                | Description            |
| ---------- | ----------------------------------- | ---------------------- |
| `category` | [`DataCategory`](#datacategory)     | The category to check. |
| `type`     | [`HealthDataType`](#healthdatatype) | The type to check.     |

**Returns:** a [`PermissionStatus`](#permissionstatus). With the built-in HealthKit store this is `.notDisclosed` for every category and type the SDK can read, whether or not your app has asked, because iOS never reveals a read decision. It is `.unsupported` for a category the SDK cannot read yet, or a type this iOS version has no HealthKit type for, and `.unavailable` when the device has no health store. `status(for: .clinicalRecord)` is `.unsupported` on a device without Health Records. To tell "never asked" apart, check [`requested`](#permissions.requested).

#### Permissions.requested

Everything a permission sheet has ever been asked for, in both directions.

```swift
public var requested: HealthAccess { get async }
```

**Returns:** a [`HealthAccess`](#healthaccess). It grows and never shrinks, and it is the set the SDK re-sends with every later request. It is the only way to tell "never asked" from an iOS denial, since iOS reports both as `.notDisclosed`.

### DataCategory

The Terra data categories, shared by permission requests and reads.

```swift
public enum DataCategory: String, Sendable, Hashable, CaseIterable, Codable
```

| Case                | Description                                                                                                                                                                                                        |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `activity`          | Workouts, with their stats, events and routes. Read and write.                                                                                                                                                     |
| `body`              | Heart rate and body measurements and vitals. Read and write. Heart rate uploads on the daily route, so asking for `body` also starts the daily upload.                                                             |
| `daily`             | Steps, distances, energy, floors, ring metrics and resting heart rate, as whole local days. Read and write.                                                                                                        |
| `sleep`             | Sleep stages. Read and write.                                                                                                                                                                                      |
| `nutrition`         | Meals, their nutrients, and water. Read and write.                                                                                                                                                                 |
| `menstruation`      | Menstrual flow and cycle events. Read only.                                                                                                                                                                        |
| `athlete`           | Biological sex, date of birth, wheelchair use and move mode. Read only.                                                                                                                                            |
| `healthObservation` | Symptoms, toothbrushing and handwashing, inhaler use, falls, blood alcohol and UV exposure. Read only.                                                                                                             |
| `clinicalRecord`    | Apple Health Records, sent to Terra as raw FHIR. Read only and opt-in: `request` ignores it, and only [`requestClinicalRecords()`](#permissions.requestclinicalrecords) asks for it. Available in 2.3.0 and later. |

The raw values are stored on the device, so case names are stable.

### HealthDataType

One kind of health data, at the granularity a permission sheet can ask for it. The type-level counterpart of [`DataCategory`](#datacategory). Available in 2.3.0 and later.

```swift
public enum HealthDataType: String, Sendable, Hashable, CaseIterable, Codable
```

The raw values are shared with the Android SDK and the React Native and Flutter packages, and are stored on the device. [Permissions](https://docs.tryterra.co/reference/mobile-sdks/permissions-mapping#individual-types) lists the HealthKit types behind each case and the route it feeds.

| Group           | Cases                                                                                                                                                                                                                                                                                                                             |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Day             | `steps`, `activeEnergy`, `basalEnergy`, `distance`, `floorsClimbed`, `swimmingStrokes`, `exerciseTime`, `moveTime`, `standTime`, `heartRate`, `restingHeartRate`                                                                                                                                                                  |
| Sleep           | `sleepAnalysis`                                                                                                                                                                                                                                                                                                                   |
| Workouts        | `workouts`, `workoutRoute`, `speed`, `power`, `cyclingCadence`                                                                                                                                                                                                                                                                    |
| Body            | `weight`, `height`, `bmi`, `bodyFat`, `leanBodyMass`, `waistCircumference`, `bloodPressure`, `bloodGlucose`, `oxygenSaturation`, `bodyTemperature`, `heartRateVariability`, `respiratoryRate`, `vo2Max`, `insulinDelivery`, `heartbeatSeries`, `electrocardiogram`                                                                |
| Nutrition       | One per [`Nutrient`](#nutrient), from `dietaryEnergyConsumed` to `dietaryPantothenicAcid`, and `dietaryWater`                                                                                                                                                                                                                     |
| Cycle tracking  | `menstrualFlow`, `intermenstrualBleeding`, `ovulationTest`, `cervicalMucus`, `sexualActivity`, `pregnancyTest`, `progesteroneTest`, `pregnancy`, `lactation`, `contraceptive`, `persistentIntermenstrualBleeding`, `infrequentCycles`, `irregularCycles`, `prolongedPeriods`, `bleedingDuringPregnancy`, `bleedingAfterPregnancy` |
| Characteristics | `biologicalSex`, `dateOfBirth`, `wheelchairUse`, `activityMoveMode`                                                                                                                                                                                                                                                               |

`workoutRoute`, `speed`, `power` and `cyclingCadence` are read through the workouts they belong to, so request them beside `workouts`. `workouts` is the sessions only: a workout's energy, distance and steps travel only when `activeEnergy`, `distance` and `steps` are requested too. `healthObservation` and `clinicalRecord` have no types.

| Member            | Type                                                               | Description                                                                                                                       |
| ----------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------- |
| `categories`      | `Set<DataCategory>`                                                | The categories whose request includes this type. Steps, energy, distance and swimming strokes are in both `daily` and `activity`. |
| `types(in:)`      | `static func types(in category: DataCategory) -> [HealthDataType]` | Every type a request for the category names. Empty for `healthObservation` and `clinicalRecord`.                                  |
| `nutrient`        | `Nutrient?`                                                        | The nutrient a dietary type reads, or `nil`.                                                                                      |
| `init(nutrient:)` | `init(nutrient: Nutrient)`                                         | The type for a nutrient.                                                                                                          |

### PermissionStatus

The answer to a permission question.

```swift
public enum PermissionStatus: Sendable, Equatable
```

| Case            | Description                                                                                                          |
| --------------- | -------------------------------------------------------------------------------------------------------------------- |
| `granted`       | Access is granted. On iOS only `writeStatus(for:)` reports it.                                                       |
| `denied`        | Access is denied. On iOS only `writeStatus(for:)` reports it.                                                        |
| `notDetermined` | The app has not asked yet. On iOS only `writeStatus(for:)` reports it.                                               |
| `notDisclosed`  | iOS will not say. iOS hides read denials on purpose, so a denied read and an empty store look the same.              |
| `unavailable`   | The device has no health store, so no answer is meaningful. Hide the feature rather than linking to Settings.        |
| `unsupported`   | The device has a health store, but nothing in it can serve this category. Hide this one category and leave the rest. |

### HealthAccess

Everything an app asks the health store for, in both directions, as one value.

```swift
public struct HealthAccess: Sendable, Equatable
```

| Property    | Type                  | Description                                                                                                |
| ----------- | --------------------- | ---------------------------------------------------------------------------------------------------------- |
| `read`      | `Set<DataCategory>`   | The categories to read.                                                                                    |
| `readTypes` | `Set<HealthDataType>` | Individual types to read. Once any are recorded, the install is type-scoped. Available in 2.3.0 and later. |
| `write`     | `Set<DataCategory>`   | The categories to write.                                                                                   |
| `workouts`  | `Set<WorkoutScope>`   | The workout shapes to write, which name a narrower set of types than `write: [.activity]`.                 |
| `isEmpty`   | `Bool`                | Whether `read`, `readTypes`, `write` and `workouts` are all empty.                                         |

#### HealthAccess.init

Creates an access value.

```swift
public init(
    read: Set<DataCategory> = [], readTypes: Set<HealthDataType> = [],
    write: Set<DataCategory> = [], workouts: Set<WorkoutScope> = []
)
```

| Name        | Type                  | Description                                                                                                |
| ----------- | --------------------- | ---------------------------------------------------------------------------------------------------------- |
| `read`      | `Set<DataCategory>`   | The categories to read. Optional. Defaults to `[]`.                                                        |
| `readTypes` | `Set<HealthDataType>` | Individual types to read. Optional. Defaults to `[]`. Available in 2.3.0 and later.                        |
| `write`     | `Set<DataCategory>`   | The categories to write. Optional. Defaults to `[]`.                                                       |
| `workouts`  | `Set<WorkoutScope>`   | The workout shapes to write. Optional. Defaults to `[]`. Scopes for the same activity are merged into one. |

#### HealthAccess.union

Returns everything either access names.

```swift
public func union(_ other: HealthAccess) -> HealthAccess
```

| Name    | Type           | Description                          |
| ------- | -------------- | ------------------------------------ |
| `other` | `HealthAccess` | The access to combine with this one. |

**Returns:** a `HealthAccess` with the union of each set.

#### HealthAccess.intersection

Returns the part of this access that another access also names.

```swift
public func intersection(_ other: HealthAccess) -> HealthAccess
```

| Name    | Type           | Description                   |
| ------- | -------------- | ----------------------------- |
| `other` | `HealthAccess` | The access to intersect with. |

**Returns:** a `HealthAccess` with the shared reads and writes, and the workout scopes for activities both name, with energy and distance kept only where both ask for them.

### WorkoutScope

A workout shape your app intends to write, declared without values, so one sheet can ask for exactly the types it needs.

```swift
public struct WorkoutScope: Sendable, Hashable
```

| Property   | Type                                  | Description                       |
| ---------- | ------------------------------------- | --------------------------------- |
| `activity` | [`WorkoutActivity`](#workoutactivity) | The activity you will log.        |
| `energy`   | `Bool`                                | Whether you will attach energy.   |
| `distance` | `Bool`                                | Whether you will attach distance. |

#### WorkoutScope.init

Creates a workout scope.

```swift
public init(activity: WorkoutActivity, energy: Bool = false, distance: Bool = false)
```

| Name       | Type                                  | Description                                                      |
| ---------- | ------------------------------------- | ---------------------------------------------------------------- |
| `activity` | [`WorkoutActivity`](#workoutactivity) | The activity you will log.                                       |
| `energy`   | `Bool`                                | Whether you will attach energy. Optional. Defaults to `false`.   |
| `distance` | `Bool`                                | Whether you will attach distance. Optional. Defaults to `false`. |

## Background sync

### BackgroundSync

Registers the SDK's background refresh task with iOS.

```swift
public enum BackgroundSync
```

The task identifier is `co.tryterra.sdk.refresh`. Your app must list it under `BGTaskSchedulerPermittedIdentifiers` in Info.plist and enable Background fetch.

#### BackgroundSync.register

Registers the background refresh task for a client and asks iOS for the first wake.

```swift
@discardableResult
public static func register(
    terra: Terra,
    source: Source = .health,
    earliestInterval: TimeInterval = 3600
) -> Bool
```

| Name               | Type                | Description                                                                                                              |
| ------------------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `terra`            | [`Terra`](#terra)   | The client to run on each wake. Build it at launch, not inside a view.                                                   |
| `source`           | [`Source`](#source) | The source whose HealthKit observation is restored on launch. Optional. Defaults to `.health`.                           |
| `earliestInterval` | `TimeInterval`      | The soonest iOS should consider waking the app again, in seconds. A floor, not a schedule. Optional. Defaults to `3600`. |

**Returns:** `true` when this call registered the task with iOS. `false` means one of two things:

* `co.tryterra.sdk.refresh` is missing from `BGTaskSchedulerPermittedIdentifiers`, so the app is never woken for it.
* The task is already registered, for example from a second launch path. This is harmless: the client is still added as a candidate for the wake.

Calling it twice is safe. The second call is a no-op instead of the exception `BGTaskScheduler` raises for a repeated identifier.

{% hint style="warning" %}
Call it before the app finishes launching, before the first `await`. iOS raises when a task is registered after launch, which crashes the app at startup.
{% endhint %}

#### BackgroundSync.registerForHostTask

For an app that schedules its own background task. Call it at launch, before the first `await`, instead of `register`, and call [`run`](#backgroundsync.run) from your task's handler.

```swift
public static func registerForHostTask(terra: Terra, source: Source = .health)
```

| Parameter | Type     | Default   | Description                                                  |
| --------- | -------- | --------- | ------------------------------------------------------------ |
| `terra`   | `Terra`  | required  | The client your handler runs                                 |
| `source`  | `Source` | `.health` | The source whose HealthKit observation is restored on launch |

It restores HealthKit observers without asking iOS for a task, and cancels any refresh request the SDK left pending. While `co.tryterra.sdk.refresh` is listed in `BGTaskSchedulerPermittedIdentifiers`, its handler stays registered so a leftover request is served; that handler submits nothing.

#### BackgroundSync.run

Runs the SDK's background pass from your own background task.

```swift
public static func run(
    terra: Terra, source: Source = .health, within budget: TimeInterval = 18
) async -> Bool
```

| Parameter | Type           | Default   | Description                                                                    |
| --------- | -------------- | --------- | ------------------------------------------------------------------------------ |
| `terra`   | `Terra`        | required  | The client to run                                                              |
| `source`  | `Source`       | `.health` | The source to sync                                                             |
| `budget`  | `TimeInterval` | `18`      | Seconds allowed to start new work. Lower it when your own work shares the task |

**Returns:** `false` only for a retryable failure. Pass it to `setTaskCompleted(success:)`.

Cancel the awaiting task from `expirationHandler` to stop the pass:

```swift
BGTaskScheduler.shared.register(forTaskWithIdentifier: "com.example.refresh", using: .main) { task in
    let work = Task { await BackgroundSync.run(terra: terra) }
    task.expirationHandler = { work.cancel() }
    Task { task.setTaskCompleted(success: await work.value) }
}
```

Register the handler with `using: .main` when it is written in `@MainActor` code such as a SwiftUI `App`.

### BackgroundSyncResult

What one background run managed across every data type.

```swift
public struct BackgroundSyncResult: Sendable
```

| Property            | Type                            | Description                                                                                                             |
| ------------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `outcomes`          | `[UploadDataType: SyncOutcome]` | The [`SyncOutcome`](#syncoutcome) of each data type that ran.                                                           |
| `failures`          | `[UploadDataType: TerraError]`  | The error of each data type that failed.                                                                                |
| `skipped`           | `[UploadDataType: Skip]`        | The data types the run reached and did not send, and why.                                                               |
| `recordsUploaded`   | `Int`                           | The records uploaded across every data type.                                                                            |
| `windowsSkipped`    | `Int`                           | The stretches nothing could send, across every data type. Non-zero means something is wrong that retrying will not fix. |
| `uploadedSomething` | `Bool`                          | Whether anything was uploaded.                                                                                          |
| `hadFailure`        | `Bool`                          | Whether any data type failed.                                                                                           |

`UploadDataType` is listed under [Extension points](#uploaddatatype).

### BackgroundSyncResult.Skip

Why a data type the run reached was not sent.

```swift
public enum Skip: Sendable, Equatable
```

| Case                        | Description                                                                                                                                                                                                                                                      |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `alreadyRunning`            | A run for this data type was already in progress.                                                                                                                                                                                                                |
| `notAuthorized(TerraError)` | The health store refused the read for want of authorization.                                                                                                                                                                                                     |
| `awaitingConverter`         | Terra cannot convert this route yet, so an upload would be accepted and then discarded.                                                                                                                                                                          |
| `notEnabled`                | Your Terra client has not enabled this data type (`TerraError.dataTypeNotEnabled`). Nothing is lost: the SDK keeps its place, holds the route unread for up to a day, and the first run after you enable it sends everything owed. Available in 2.3.0 and later. |

### SyncOutcome

What one data type's sync run did.

```swift
public struct SyncOutcome: Sendable, Equatable
```

| Property          | Type   | Description                                                                                                                      |
| ----------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `recordsUploaded` | `Int`  | The records the server accepted across every window in the run.                                                                  |
| `windowsUploaded` | `Int`  | The windows that carried something. Empty windows are not uploaded and not counted.                                              |
| `windowsSkipped`  | `Int`  | The stretches the server refused as too large even at the smallest split. Their data is not uploaded; everything around them is. |
| `syncedThrough`   | `Date` | How far the data type is now uploaded. Unchanged when nothing was sent.                                                          |

## Reading and writing data

Each namespace groups the reads, writes and change hints of one category. Reads go straight to HealthKit and never touch the network. Writes record data your app measured itself, under your app's name.

Every read throws `TerraError.notConnected` when there is no stored link: call [`connect`](#terra.connect) first. Every `log` asks for write access the first time, when the category is not determined yet.

### TimeRange

The window a read covers.

```swift
public enum TimeRange: Sendable, Equatable
```

| Case                  | Description                                                                                                                   |
| --------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `lastHours(Int)`      | The given number of hours up to now.                                                                                          |
| `lastDays(Int)`       | The given number of calendar days up to now. Uses calendar arithmetic, so a daylight saving change does not shift the window. |
| `today`               | From the start of the current day up to now.                                                                                  |
| `between(Date, Date)` | Between two dates, in either order.                                                                                           |

#### TimeRange.resolve

Resolves the range to a concrete interval.

```swift
public func resolve(now: Date = Date(), calendar: Calendar = .current) -> DateInterval
```

| Name       | Type       | Description                                                       |
| ---------- | ---------- | ----------------------------------------------------------------- |
| `now`      | `Date`     | The current time. Optional. Defaults to `Date()`.                 |
| `calendar` | `Calendar` | The calendar that defines days. Optional. Defaults to `.current`. |

**Returns:** a `DateInterval` with the earlier date as its start. Reads treat it as half-open, `[start, end)`.

### BodyMetrics

The `body` namespace, reached through [`terra.body`](#terra.body).

```swift
public struct BodyMetrics: Sendable
```

#### BodyMetrics.heartRate

Returns the heart rate samples in a window.

```swift
public func heartRate(in range: TimeRange) async throws -> [HeartRateSample]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`HeartRateSample`](#heartratesample)s in the window, each with the app or device that wrote it.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

#### BodyMetrics.restingHeartRate

Returns HealthKit's own resting heart rate figures in a window. Available in 2.2.0 and later.

```swift
public func restingHeartRate(in range: TimeRange) async throws -> [RestingHeartRateSample]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`RestingHeartRateSample`](#restingheartratesample)s overlapping the window, one per day HealthKit computed one. They are HealthKit's figures, never derived from [`heartRate(in:)`](#bodymetrics.heartrate).

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
let resting = try await terra.body.restingHeartRate(in: .lastDays(7))
```

#### BodyMetrics.readings

Returns the body readings in a window: weight, height, BMI, body fat, lean mass, heart rate variability, VO2 max, blood pressure, blood glucose, oxygen saturation, temperature and respiratory rate. Available in 2.2.0 and later.

```swift
public func readings(in range: TimeRange) async throws -> [BodyReading]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`BodyReading`](#bodyreading)s in the window. Each reading's `kind` carries its unit. Blood glucose keeps the unit its writer chose.

ECG recordings, heartbeat series, insulin deliveries and waist circumference are not returned. The upload sends them when your app requested `body`.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
for reading in try await terra.body.readings(in: .lastDays(30)) {
    if case .measurement(.weight, let kilograms) = reading.kind {
        print(kilograms)
    }
}
```

#### BodyMetrics.log

Records heart rates or body vitals in HealthKit under your app's name, and returns each one's ID.

```swift
@discardableResult
public func log(_ entries: [HeartRateEntry]) async throws -> [UUID]

@discardableResult
public func log(_ entries: [BodyEntry]) async throws -> [UUID]

@available(*, deprecated, message: "use terra.nutrition.log(_:) - meals moved to their own namespace")
@discardableResult
public func log(_ entries: [NutritionEntry]) async throws -> [UUID]
```

| Name      | Type                                                                                                        | Description                                                                                                                                                                                                                                                  |
| --------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `entries` | [`[HeartRateEntry]`](#heartrateentry), [`[BodyEntry]`](#bodyentry) or [`[NutritionEntry]`](#nutritionentry) | The records to write. Each present field of a `BodyEntry` becomes its own sample, and all of them share the entry's ID. Entries with no fields are skipped. The `NutritionEntry` overload is deprecated: use [`terra.nutrition.log`](#nutritionmetrics.log). |

**Returns:** one `UUID` per written entry. Keep it: it is the only handle [`delete(id:)`](#bodymetrics.delete) accepts, and write-only access cannot look it up later.

The `HeartRateEntry` write is all or nothing: a failure leaves the store as it was, so you can retry the same array without writing anything twice.

| Error                                | When                                                                         |
| ------------------------------------ | ---------------------------------------------------------------------------- |
| `TerraError.healthDataUnavailable`   | The device has no health store.                                              |
| `TerraError.permissionDenied`        | Write access to `body` is denied or unsupported.                             |
| `TerraError.bloodPressureIncomplete` | A `BodyEntry` carries only one half of a blood pressure. Nothing is written. |

#### BodyMetrics.delete

Removes a sample your app wrote, named by an ID `log` returned.

```swift
public func delete(id: UUID) async throws
```

| Name | Type   | Description                                                             |
| ---- | ------ | ----------------------------------------------------------------------- |
| `id` | `UUID` | An ID `log` returned. A `BodyEntry`'s ID removes the whole observation. |

| Error                         | When                                                                                     |
| ----------------------------- | ---------------------------------------------------------------------------------------- |
| `TerraError.sampleNotFound`   | No sample your app wrote has this ID. Another app's sample and a stale ID look the same. |
| `TerraError.permissionDenied` | Write access to `body` is denied.                                                        |

#### BodyMetrics.changes

Returns a stream of hints that HealthKit gained `body` data.

```swift
public func changes() async -> AsyncStream<HealthChange>
```

**Returns:** a fresh `AsyncStream` of [`HealthChange`](#healthchange) values. Each names the category and the day the data landed on, never the samples: re-read the window you care about.

Nothing that happened before the call returns is reported. A subscriber that stops draining loses its oldest hints, and a dropped hint is not sent again unless new data lands on that day. The data itself is not lost. Drain the stream, or re-read when a screen appears.

```swift
for await change in await terra.body.changes() {
    let samples = try await terra.body.heartRate(in: .between(change.day, .now))
}
```

### DailyMetrics

The `daily` namespace, reached through [`terra.daily`](#terra.daily).

```swift
public struct DailyMetrics: Sendable
```

#### DailyMetrics.steps

Returns step totals per local day and per writing app in a window.

```swift
public func steps(in range: TimeRange) async throws -> [StepCount]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** one [`StepCount`](#stepcount) per day per writing app. Days are the device's current local days. A sample that spans midnight is divided between the days it covers. The client's [`DayTotalPolicy`](#daytotalpolicy) decides whether hand-entered samples count.

{% hint style="warning" %}
A phone and a paired watch each report their own total for the same walk. Do not add the totals up.
{% endhint %}

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

#### DailyMetrics.totals

Returns HealthKit's own total for each local day a window touches. Available in 2.2.0 and later.

```swift
public func totals(in range: TimeRange) async throws -> [DayTotal]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** one [`DayTotal`](#daytotal) per metric per local day, oldest first. The metrics are `distanceWalkingRunning`, `distanceCycling`, `distanceSwimming`, `distanceWheelchair`, `activeEnergyBurned`, `basalEnergyBurned`, `flightsClimbed` and `appleExerciseTime`.

* Each total is a whole local day's, including a day the window covers only in part.
* A day HealthKit has nothing for has no total, not a zero.
* Totals are HealthKit's statistics across every writing app, counted under the client's [`DayTotalPolicy`](#daytotalpolicy). They are the figures the upload sends.
* Steps are not included. Read them with [`steps(in:)`](#dailymetrics.steps), which keeps writers apart.
* A metric your app cannot read has no totals. The read does not throw for it.

| Error                     | When                     |
| ------------------------- | ------------------------ |
| `TerraError.notConnected` | There is no stored link. |

```swift
for total in try await terra.daily.totals(in: .lastDays(7)) where total.metric == .activeEnergyBurned {
    print(total.interval.start, total.value, total.unit)
}
```

#### DailyMetrics.intraday

Returns the energy, distance and floors samples the day totals are made of. Available in 2.2.0 and later.

```swift
public func intraday(in range: TimeRange) async throws -> [IntradaySample]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`IntradaySample`](#intradaysample)s in the window, as HealthKit recorded them. A sample that crosses midnight is returned whole, not divided between the days. For a day's figure, use [`totals(in:)`](#dailymetrics.totals).

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
let samples = try await terra.daily.intraday(in: .today)
```

#### DailyMetrics.log

Records step counts in HealthKit under your app's name, and returns each one's ID.

```swift
@discardableResult
public func log(_ entries: [StepEntry]) async throws -> [UUID]
```

| Name      | Type                        | Description               |
| --------- | --------------------------- | ------------------------- |
| `entries` | [`[StepEntry]`](#stepentry) | The step counts to write. |

**Returns:** one `UUID` per entry, the only handle [`delete(id:)`](#dailymetrics.delete) accepts.

A write is all or nothing, so you can retry the same array safely.

| Error                              | When                                              |
| ---------------------------------- | ------------------------------------------------- |
| `TerraError.healthDataUnavailable` | The device has no health store.                   |
| `TerraError.permissionDenied`      | Write access to `daily` is denied or unsupported. |

#### DailyMetrics.delete

Removes a sample your app wrote, named by an ID `log` returned.

```swift
public func delete(id: UUID) async throws
```

| Name | Type   | Description           |
| ---- | ------ | --------------------- |
| `id` | `UUID` | An ID `log` returned. |

| Error                         | When                                  |
| ----------------------------- | ------------------------------------- |
| `TerraError.sampleNotFound`   | No sample your app wrote has this ID. |
| `TerraError.permissionDenied` | Write access to `daily` is denied.    |

#### DailyMetrics.changes

Returns a stream of hints that HealthKit gained `daily` data.

```swift
public func changes() async -> AsyncStream<HealthChange>
```

**Returns:** a fresh `AsyncStream` of [`HealthChange`](#healthchange) values. It behaves like [`BodyMetrics.changes`](#bodymetrics.changes).

### SleepMetrics

The `sleep` namespace, reached through [`terra.sleep`](#terra.sleep).

```swift
public struct SleepMetrics: Sendable
```

#### SleepMetrics.segments

Returns the sleep stage segments in a window.

```swift
public func segments(in range: TimeRange) async throws -> [SleepSegment]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`SleepSegment`](#sleepsegment)s in the window, as HealthKit recorded them. They are not grouped into nights.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

#### SleepMetrics.log

Records sleep stages in HealthKit under your app's name, and returns each one's ID.

```swift
@discardableResult
public func log(_ entries: [SleepEntry]) async throws -> [UUID]
```

| Name      | Type                          | Description                |
| --------- | ----------------------------- | -------------------------- |
| `entries` | [`[SleepEntry]`](#sleepentry) | The sleep stages to write. |

**Returns:** one `UUID` per entry, the only handle [`delete(id:)`](#sleepmetrics.delete) accepts.

A write is all or nothing, so you can retry the same array safely.

| Error                              | When                                              |
| ---------------------------------- | ------------------------------------------------- |
| `TerraError.healthDataUnavailable` | The device has no health store.                   |
| `TerraError.permissionDenied`      | Write access to `sleep` is denied or unsupported. |

#### SleepMetrics.delete

Removes a sample your app wrote, named by an ID `log` returned.

```swift
public func delete(id: UUID) async throws
```

| Name | Type   | Description           |
| ---- | ------ | --------------------- |
| `id` | `UUID` | An ID `log` returned. |

| Error                         | When                                  |
| ----------------------------- | ------------------------------------- |
| `TerraError.sampleNotFound`   | No sample your app wrote has this ID. |
| `TerraError.permissionDenied` | Write access to `sleep` is denied.    |

#### SleepMetrics.changes

Returns a stream of hints that HealthKit gained `sleep` data.

```swift
public func changes() async -> AsyncStream<HealthChange>
```

**Returns:** a fresh `AsyncStream` of [`HealthChange`](#healthchange) values. It behaves like [`BodyMetrics.changes`](#bodymetrics.changes).

### ActivityMetrics

The `activity` namespace, reached through [`terra.activity`](#terra.activity).

```swift
public struct ActivityMetrics: Sendable
```

#### ActivityMetrics.workouts

Returns the workouts in a window.

```swift
public func workouts(in range: TimeRange) async throws -> [Workout]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`Workout`](#workout)s in the window.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

#### ActivityMetrics.routes

Returns the GPS tracks of the workouts overlapping a window. Available in 2.2.0 and later.

```swift
public func routes(in range: TimeRange) async throws -> [WorkoutRoute]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** one [`WorkoutRoute`](#workoutroute) per route HealthKit holds for those workouts, each naming its workout by `workoutId`. Each track is thinned to at most one point a second and at most `WorkoutRoute.maximumPoints`, which is the track Terra stores.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
let workouts = try await terra.activity.workouts(in: .lastDays(1))
let routes = try await terra.activity.routes(in: .lastDays(1))
for workout in workouts {
    let route = routes.first { $0.workoutId == workout.id }
    print(workout.title ?? "Workout", route?.points.count ?? 0)
}
```

#### ActivityMetrics.intensity

Returns the speed, power and cycling cadence readings recorded inside the workouts overlapping a window. Available in 2.2.0 and later.

```swift
public func intensity(in range: TimeRange) async throws -> [WorkoutIntensitySample]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`WorkoutIntensitySample`](#workoutintensitysample)s of those workouts, each naming its workout by `workoutId`.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
let power = try await terra.activity.intensity(in: .lastDays(1)).filter { $0.kind == .power }
```

#### ActivityMetrics.log

Records workouts in HealthKit under your app's name, and returns each one's ID.

```swift
@discardableResult
public func log(_ entries: [WorkoutEntry]) async throws -> [UUID]
```

| Name      | Type                              | Description            |
| --------- | --------------------------------- | ---------------------- |
| `entries` | [`[WorkoutEntry]`](#workoutentry) | The workouts to write. |

**Returns:** one `UUID` per entry, the only handle [`delete(id:)`](#activitymetrics.delete) accepts.

HealthKit saves one workout at a time. When a later workout fails, the SDK removes the ones already saved, so you can retry the same array safely.

`log` needs only the types its entries carry: the workout, plus active energy when an entry has `totalEnergyKilocalories` and the activity's distance type when it has `totalDistanceMeters`. If one of those has never been asked for, `log` asks for it first, and iOS shows a sheet for it. A refused type the entries do not carry is not checked, so a run logs while [`writeStatus(for: .activity)`](#permissions.writestatus) is `.denied` over a refused swimming distance.

| Error                                | When                                                                                                                             |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| `TerraError.healthDataUnavailable`   | The device has no health store.                                                                                                  |
| `TerraError.permissionDenied`        | Write access is denied for a type the entries carry.                                                                             |
| `TerraError.distanceNotAttributable` | An entry carries a distance for an activity that has no distance type.                                                           |
| `TerraError.rollbackIncomplete`      | A workout failed and some already-saved workouts could not be removed. `remaining` lists their IDs: delete them before retrying. |

#### ActivityMetrics.delete

Removes a workout your app wrote, named by an ID `log` returned.

```swift
public func delete(id: UUID) async throws
```

| Name | Type   | Description           |
| ---- | ------ | --------------------- |
| `id` | `UUID` | An ID `log` returned. |

Deleting a workout also deletes the active energy and distance logged with it, so they stop counting toward the person's daily totals. That includes a workout an earlier SDK release logged: its energy and distance are found through HealthKit's association with the workout, as long as the workout is still there. An energy or distance type your app may no longer write, because the person turned it off after the workout was logged, is left in place.

| Error                         | When                                   |
| ----------------------------- | -------------------------------------- |
| `TerraError.sampleNotFound`   | No workout your app wrote has this ID. |
| `TerraError.permissionDenied` | Write access to workouts is denied.    |

#### ActivityMetrics.changes

Returns a stream of hints that HealthKit gained `activity` data.

```swift
public func changes() async -> AsyncStream<HealthChange>
```

**Returns:** a fresh `AsyncStream` of [`HealthChange`](#healthchange) values. It behaves like [`BodyMetrics.changes`](#bodymetrics.changes).

### NutritionMetrics

The `nutrition` namespace, reached through [`terra.nutrition`](#terra.nutrition).

```swift
public struct NutritionMetrics: Sendable
```

#### NutritionMetrics.quantities

Returns the dietary quantities in a window, one per nutrient sample, as HealthKit holds them. Available in 2.2.0 and later.

```swift
public func quantities(in range: TimeRange) async throws -> [DietaryQuantity]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`DietaryQuantity`](#dietaryquantity) values in the window. They are not grouped into meals: a meal logged with three nutrients reads back as three quantities. Quantities HealthKit grouped into a `food` correlation share a `foodCorrelationID`. Water is not among them: read it with [`hydration(in:)`](#nutritionmetrics.hydration).

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
let quantities = try await terra.nutrition.quantities(in: .lastDays(7))
let byMeal = Dictionary(grouping: quantities, by: \.foodCorrelationID)
```

#### NutritionMetrics.hydration

Returns the water drunk in a window. Available in 2.2.0 and later.

```swift
public func hydration(in range: TimeRange) async throws -> [HydrationSample]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** one [`HydrationSample`](#hydrationsample) per drink as HealthKit recorded it, in millilitres.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
let millilitres = try await terra.nutrition.hydration(in: .today).reduce(0) { $0 + $1.millilitres }
```

#### NutritionMetrics.log

Records meals in HealthKit under your app's name, and returns each one's ID.

```swift
@discardableResult
public func log(_ entries: [NutritionEntry]) async throws -> [UUID]
```

| Name      | Type                                  | Description                                                                                                                                    |
| --------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `entries` | [`[NutritionEntry]`](#nutritionentry) | The meals to write. Each present nutrient becomes its own sample, and all of them share the entry's ID. Entries with no nutrients are skipped. |

**Returns:** one `UUID` per written meal. One [`delete(id:)`](#nutritionmetrics.delete) removes the whole meal.

| Error                              | When                                                  |
| ---------------------------------- | ----------------------------------------------------- |
| `TerraError.healthDataUnavailable` | The device has no health store.                       |
| `TerraError.permissionDenied`      | Write access to `nutrition` is denied or unsupported. |

#### NutritionMetrics.delete

Removes a meal your app wrote, named by an ID `log` returned.

```swift
public func delete(id: UUID) async throws
```

| Name | Type   | Description           |
| ---- | ------ | --------------------- |
| `id` | `UUID` | An ID `log` returned. |

| Error                         | When                                   |
| ----------------------------- | -------------------------------------- |
| `TerraError.sampleNotFound`   | No meal your app wrote has this ID.    |
| `TerraError.permissionDenied` | Write access to `nutrition` is denied. |

### MenstruationMetrics

The `menstruation` namespace, reached through [`terra.menstruation`](#terra.menstruation). Read only: there is no menstruation write. Available in 2.2.0 and later.

```swift
public struct MenstruationMetrics: Sendable
```

#### MenstruationMetrics.flow

Returns the logged flow days overlapping a window. Available in 2.2.0 and later.

```swift
public func flow(in range: TimeRange) async throws -> [MenstruationFlowDay]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** one [`MenstruationFlowDay`](#menstruationflowday) per logged day, each bounded by that day's local midnights. A day logged with no flow is returned as `.noFlow`, not left out.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
let days = try await terra.menstruation.flow(in: .lastDays(90))
```

#### MenstruationMetrics.events

Returns the ovulation tests, cervical mucus observations and intermenstrual bleeding logged in a window. Available in 2.2.0 and later.

```swift
public func events(in range: TimeRange) async throws -> [MenstrualEvent]
```

| Name    | Type                      | Description         |
| ------- | ------------------------- | ------------------- |
| `range` | [`TimeRange`](#timerange) | The window to read. |

**Returns:** the [`MenstrualEvent`](#menstrualevent)s of kind `ovulationTest`, `cervicalMucus` and `intermenstrualBleeding` in the window, each at the instant it was logged. The other kinds are not returned. The upload sends them when your app requested `menstruation`.

| Error                                   | When                                                            |
| --------------------------------------- | --------------------------------------------------------------- |
| `TerraError.notConnected`               | There is no stored link.                                        |
| `TerraError.authorizationNotDetermined` | HealthKit refuses the read because your app never requested it. |

```swift
let positives = try await terra.menstruation.events(in: .lastDays(90))
    .filter { $0.kind == .ovulationTest && $0.value == "positive" }
```

### AthleteMetrics

The `athlete` namespace, reached through [`terra.athlete`](#terra.athlete). Read only: there is no athlete write. Available in 2.2.0 and later.

```swift
public struct AthleteMetrics: Sendable
```

#### AthleteMetrics.profile

Returns the person's HealthKit characteristics as one snapshot. Available in 2.2.0 and later.

```swift
public func profile() async throws -> AthleteProfile?
```

It takes no window, because characteristics have no history.

**Returns:** an [`AthleteProfile`](#athleteprofile). A characteristic the person never filled in, or that your app was not granted, is absent, except `biologicalSex`, which is `.notSet`. `nil` only where the store has no characteristics at all.

| Error                     | When                     |
| ------------------------- | ------------------------ |
| `TerraError.notConnected` | There is no stored link. |

```swift
if let profile = try await terra.athlete.profile(), profile.wheelchairUse == true {
    showPushesInsteadOfSteps()
}
```

## Write entries

The values you pass to `log`. Each entry mints a `recordID` when you create it. HealthKit stores it in the sample's metadata, and it is the ID `log` returns.

### HeartRateEntry

A heart rate to record.

```swift
public struct HeartRateEntry: Sendable, Equatable

public init(time: Date, beatsPerMinute: Double, recordID: UUID = UUID())
```

| Property         | Type     | Description                                                    |
| ---------------- | -------- | -------------------------------------------------------------- |
| `time`           | `Date`   | When the heart rate was measured.                              |
| `beatsPerMinute` | `Double` | The heart rate, in beats per minute.                           |
| `recordID`       | `UUID`   | The record's ID. Optional in `init`. Defaults to a new `UUID`. |

### StepEntry

Steps over a stretch of time.

```swift
public struct StepEntry: Sendable, Equatable

public init(interval: DateInterval, steps: Int, recordID: UUID = UUID())
```

| Property   | Type           | Description                                                                      |
| ---------- | -------------- | -------------------------------------------------------------------------------- |
| `interval` | `DateInterval` | The stretch the steps were taken over. HealthKit rejects a zero-length interval. |
| `steps`    | `Int`          | The step count.                                                                  |
| `recordID` | `UUID`         | The record's ID. Optional in `init`. Defaults to a new `UUID`.                   |

### SleepEntry

One stage of a night.

```swift
public struct SleepEntry: Sendable, Equatable

public init(interval: DateInterval, stage: SleepStage, recordID: UUID = UUID())
```

| Property   | Type                        | Description                                                    |
| ---------- | --------------------------- | -------------------------------------------------------------- |
| `interval` | `DateInterval`              | The stretch of the stage.                                      |
| `stage`    | [`SleepStage`](#sleepstage) | The sleep stage.                                               |
| `recordID` | `UUID`                      | The record's ID. Optional in `init`. Defaults to a new `UUID`. |

### WorkoutEntry

A workout to record.

```swift
public struct WorkoutEntry: Sendable, Equatable

public init(
    interval: DateInterval,
    activity: WorkoutActivity,
    totalEnergyKilocalories: Double? = nil,
    totalDistanceMeters: Double? = nil,
    recordID: UUID = UUID()
)
```

| Property                  | Type                                  | Description                                                                                                                                                |
| ------------------------- | ------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `interval`                | `DateInterval`                        | When the workout ran.                                                                                                                                      |
| `activity`                | [`WorkoutActivity`](#workoutactivity) | The activity.                                                                                                                                              |
| `totalEnergyKilocalories` | `Double?`                             | The energy burned, in kilocalories. Optional. Defaults to `nil`; a missing value is never written as zero.                                                 |
| `totalDistanceMeters`     | `Double?`                             | The distance covered, in metres. Optional. Defaults to `nil`.                                                                                              |
| `recordID`                | `UUID`                                | The record's ID. Optional in `init`. Defaults to a new `UUID`. It also names a workout finished on a locked device, for which HealthKit returns no handle. |

### BodyEntry

One observation of body vitals. Each present field becomes its own sample, and all of them carry this entry's `recordID`.

```swift
public struct BodyEntry: Sendable, Equatable

public init(
    time: Date,
    bodyMassKilograms: Double? = nil, bodyFatPercent: Double? = nil,
    bodyMassIndex: Double? = nil, heightMeters: Double? = nil,
    leanBodyMassKilograms: Double? = nil, bodyTemperatureCelsius: Double? = nil,
    oxygenSaturationPercent: Double? = nil,
    bloodGlucoseMilligramsPerDeciliter: Double? = nil,
    bloodPressureSystolicMillimetersOfMercury: Double? = nil,
    bloodPressureDiastolicMillimetersOfMercury: Double? = nil,
    recordID: UUID = UUID()
)
```

| Property                                     | Type      | Description                                                           |
| -------------------------------------------- | --------- | --------------------------------------------------------------------- |
| `time`                                       | `Date`    | When the observation was taken.                                       |
| `bodyMassKilograms`                          | `Double?` | Body mass, in kilograms.                                              |
| `bodyFatPercent`                             | `Double?` | Body fat percentage.                                                  |
| `bodyMassIndex`                              | `Double?` | Body mass index.                                                      |
| `heightMeters`                               | `Double?` | Height, in metres.                                                    |
| `leanBodyMassKilograms`                      | `Double?` | Lean body mass, in kilograms.                                         |
| `bodyTemperatureCelsius`                     | `Double?` | Body temperature, in degrees Celsius.                                 |
| `oxygenSaturationPercent`                    | `Double?` | Blood oxygen saturation.                                              |
| `bloodGlucoseMilligramsPerDeciliter`         | `Double?` | Blood glucose, in mg/dL.                                              |
| `bloodPressureSystolicMillimetersOfMercury`  | `Double?` | Systolic blood pressure, in mmHg. Must come with the diastolic value. |
| `bloodPressureDiastolicMillimetersOfMercury` | `Double?` | Diastolic blood pressure, in mmHg. Must come with the systolic value. |
| `recordID`                                   | `UUID`    | The record's ID. Optional in `init`. Defaults to a new `UUID`.        |
| `isEmpty`                                    | `Bool`    | Whether no field carries a value, so there is nothing to write.       |

Every value is optional in `init` and defaults to `nil`. Both blood pressure halves are written together as one reading. One half alone throws `TerraError.bloodPressureIncomplete` before anything is written.

### NutritionEntry

One meal or intake, over the interval it was consumed. Each present nutrient becomes its own sample carrying this entry's `recordID`.

```swift
public struct NutritionEntry: Sendable, Equatable

public init(interval: DateInterval, name: String? = nil, nutrients: Nutrients, recordID: UUID = UUID())
```

| Property    | Type                                     | Description                                                            |
| ----------- | ---------------------------------------- | ---------------------------------------------------------------------- |
| `interval`  | `DateInterval`                           | When the meal was consumed.                                            |
| `name`      | `String?`                                | The food's name, shown in the Health app. Optional. Defaults to `nil`. |
| `nutrients` | [`Nutrients`](#nutritionentry.nutrients) | The nutrient values.                                                   |
| `recordID`  | `UUID`                                   | The record's ID. Optional in `init`. Defaults to a new `UUID`.         |
| `isEmpty`   | `Bool`                                   | Whether no nutrient carries a value, so there is nothing to write.     |

### NutritionEntry.Nutrients

The nutrient values of a meal, each in the unit its name states.

```swift
public struct Nutrients: Sendable, Equatable
```

Every property is a `Double?` and a parameter of `init` with a default of `nil`:

`energyKilocalories`, `proteinGrams`, `carbohydratesGrams`, `fiberGrams`, `sugarGrams`, `fatTotalGrams`, `fatSaturatedGrams`, `fatMonounsaturatedGrams`, `fatPolyunsaturatedGrams`, `cholesterolMilligrams`, `sodiumMilligrams`, `potassiumMilligrams`, `calciumMilligrams`, `ironMilligrams`, `magnesiumMilligrams`, `zincMilligrams`, `waterLiters`, `caffeineMilligrams`, `vitaminAMicrograms`, `vitaminCMilligrams`, `vitaminDMicrograms`, `vitaminEMilligrams`, `vitaminKMicrograms`, `vitaminB6Milligrams`, `vitaminB12Micrograms`, `folateMicrograms`, `thiaminMilligrams`, `riboflavinMilligrams`, `niacinMilligrams`, `biotinMicrograms`, `pantothenicAcidMilligrams`, `phosphorusMilligrams`, `iodineMicrograms`, `chromiumMicrograms`, `copperMilligrams`, `manganeseMilligrams`, `molybdenumMicrograms`, `seleniumMicrograms`, `chlorideMilligrams`.

```swift
let meal = NutritionEntry(
    interval: DateInterval(start: start, duration: 15 * 60),
    name: "Oatmeal",
    nutrients: .init(energyKilocalories: 310, proteinGrams: 11, carbohydratesGrams: 54)
)
try await terra.nutrition.log([meal])
```

## Change observation

### HealthChange

A hint that HealthKit gained data in a category: the category and the day, never the data.

```swift
public struct HealthChange: Sendable, Equatable, Hashable

public init(category: DataCategory, day: Date)
```

| Property   | Type                            | Description                                                                                                    |
| ---------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `category` | [`DataCategory`](#datacategory) | The category that gained data.                                                                                 |
| `day`      | `Date`                          | The start of the day the changed data falls on, in the calendar that was current when the change was observed. |

The namespaces' `changes()` streams deliver these. The types below are what a custom [`HealthStore`](#healthstore) uses to report observer wakes; apps that use the built-in store never handle them.

### ObservedChange

What an observer wake turned out to be worth.

```swift
public enum ObservedChange: Sendable, Equatable
```

| Case              | Description                                                                                                                  |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `days(Set<Date>)` | The days that gained data.                                                                                                   |
| `deferred`        | The store could not be read, for example before the device's first unlock. The wake is replayed later rather than discarded. |

### ObservedWake

A wake and the acknowledgement the platform is waiting on.

```swift
public struct ObservedWake: Sendable

public init(_ change: ObservedChange, acknowledging handler: @escaping @Sendable () -> Void = {})
```

| Property | Type                                | Description          |
| -------- | ----------------------------------- | -------------------- |
| `change` | [`ObservedChange`](#observedchange) | What the wake found. |

| Name      | Type                                | Description                                                                                                        |
| --------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| `change`  | [`ObservedChange`](#observedchange) | What the wake found.                                                                                               |
| `handler` | `@escaping @Sendable () -> Void`    | The completion the platform waits on, such as HealthKit's observer completion handler. Optional. Defaults to `{}`. |

#### ObservedWake.acknowledge

Acknowledges the wake, at most once.

```swift
public func acknowledge()
```

### Acknowledgement

Calls its handler at most once, including when it is released without being fired.

```swift
public final class Acknowledgement: @unchecked Sendable

public init(_ handler: @escaping @Sendable () -> Void)
```

| Name      | Type                             | Description               |
| --------- | -------------------------------- | ------------------------- |
| `handler` | `@escaping @Sendable () -> Void` | The closure to call once. |

#### Acknowledgement.fire

Calls the handler if it has not been called yet.

```swift
public func fire()
```

### DeferredWake

A wake the device owes itself, and the link generation it arrived under.

```swift
public struct DeferredWake: Sendable, Equatable

public init(generation: Int, version: Int)
```

| Property     | Type  | Description                                                                                                     |
| ------------ | ----- | --------------------------------------------------------------------------------------------------------------- |
| `generation` | `Int` | The link generation stamped when the wake arrived. A wake whose link has gone is dropped at replay.             |
| `version`    | `Int` | A counter bumped by every deferral of the category, so a replay cannot retire a wake that arrived while it ran. |

## Planned workouts

### PlannedWorkouts

The workouts Terra has planned for a connection's user, reached through [`connection.workouts`](#connection).

```swift
public struct PlannedWorkouts: Sendable
```

Plans are authored in Terra. The device reads them, reports their status, and, once the person allows it, puts them on their Apple Watch with WorkoutKit. See [Planned workouts on Apple Watch](https://docs.tryterra.co/mobile-sdks/planned-workouts-apple-watch).

#### PlannedWorkouts.planned

Returns what is planned for the connected user.

```swift
public func planned() async throws -> [PlannedWorkout]
```

**Returns:** the [`PlannedWorkout`](#plannedworkout)s Terra holds for the user.

| Error                     | When                                                                       |
| ------------------------- | -------------------------------------------------------------------------- |
| `TerraError.notConnected` | The connection's link is gone or has no signing key.                       |
| `TerraError.linkRevoked`  | Terra refused the device's signature twice, so the link is marked revoked. |
| `TerraError.network`      | The request failed in transit or Terra returned an error status.           |

#### PlannedWorkouts.markComplete

Reports a plan as done.

```swift
public func markComplete(id: String, at time: Date = Date()) async throws
```

| Name   | Type     | Description                                             |
| ------ | -------- | ------------------------------------------------------- |
| `id`   | `String` | The plan's [`id`](#plannedworkout), unchanged.          |
| `time` | `Date`   | When the plan was completed. Optional. Defaults to now. |

A plan Terra has already dropped is not an error.

| Error                              | When                                                 |
| ---------------------------------- | ---------------------------------------------------- |
| `TerraError.plannedWorkoutUnnamed` | `id` is empty. Refused before anything is sent.      |
| `TerraError.notConnected`          | The connection's link is gone or has no signing key. |

#### PlannedWorkouts.delete

Deletes a plan.

```swift
public func delete(id: String) async throws
```

| Name | Type     | Description                                    |
| ---- | -------- | ---------------------------------------------- |
| `id` | `String` | The plan's [`id`](#plannedworkout), unchanged. |

| Error                              | When                                                 |
| ---------------------------------- | ---------------------------------------------------- |
| `TerraError.plannedWorkoutUnnamed` | `id` is empty. Refused before anything is sent.      |
| `TerraError.notConnected`          | The connection's link is gone or has no signing key. |

#### PlannedWorkouts.schedulingStatus

Whether Terra's plans can be put on this person's Apple Watch. Never prompts.

```swift
public func schedulingStatus() async -> WorkoutSchedulingStatus
```

**Returns:** a [`WorkoutSchedulingStatus`](#workoutschedulingstatus). `.unsupported` before iOS 17, and on a device WorkoutKit cannot schedule for.

#### PlannedWorkouts.requestScheduling

Asks the person to let your app schedule workouts on their Watch, showing WorkoutKit's sheet if they have not been asked.

```swift
@discardableResult
public func requestScheduling() async -> WorkoutSchedulingStatus
```

Once authorized, every sync run puts new plans on the Watch, moves changed ones, removes deleted ones, and reports workouts your app scheduled itself back to Terra. The first reconciliation runs before this returns, so a plan already waiting is on the Watch when it does.

```swift
if await connection.workouts.schedulingStatus() == .notDetermined {
    await connection.workouts.requestScheduling()
}
```

### WorkoutSchedulingStatus

```swift
public enum WorkoutSchedulingStatus: String, Sendable, Equatable, CaseIterable
```

| Case            | Meaning                                                                          |
| --------------- | -------------------------------------------------------------------------------- |
| `unsupported`   | No WorkoutKit on this OS (before iOS 17), or the device cannot schedule workouts |
| `notDetermined` | The person has not been asked. Only `requestScheduling()` asks                   |
| `denied`        | The person refused, or a policy forbids it. Only the Settings app changes this   |
| `authorized`    | Plans are put on the Watch on every sync run                                     |

### PlannedWorkout

A workout plan authored in Terra.

```swift
public struct PlannedWorkout: Sendable, Equatable, Identifiable, Decodable

public init(
    id: String, plannedOn: DateComponents, activity: WorkoutActivity,
    title: String? = nil, completedAt: Date? = nil
)

public init(from decoder: any Decoder) throws
```

| Property      | Type                                  | Description                                                                                |
| ------------- | ------------------------------------- | ------------------------------------------------------------------------------------------ |
| `id`          | `String`                              | The plan's opaque ID. Pass it back unchanged; it does not parse as a UUID.                 |
| `plannedOn`   | `DateComponents`                      | The planned calendar day (year, month, day), not an instant.                               |
| `activity`    | [`WorkoutActivity`](#workoutactivity) | The planned activity. An activity name Terra uses that has no case is carried as `.other`. |
| `title`       | `String?`                             | The plan's title, if any.                                                                  |
| `completedAt` | `Date?`                               | When this device reported it done, if it has.                                              |

`init(from:)` decodes Terra's JSON (`id`, `planned_date` as `yyyy-MM-dd`, `activity_type`, `title`, `completed_at`) and throws a `DecodingError` for an empty `id` or a malformed date.

## Disconnecting

Call [`Connection.disconnect`](#connection.disconnect) on each connection you want to end. It forgets the link on the device and tells Terra to stop accepting the device's key.

## Diagnosing delivery

### Diagnostics

The diagnostics namespace, reached through [`terra.diagnostics`](#terra.diagnostics). The SDK sends a redacted support report to Terra on its own when something goes wrong, and [`send`](#diagnostics.send) sends one on demand.

```swift
public struct Diagnostics: Sendable
```

#### Diagnostics.events

Returns a stream of typed events describing what the SDK does.

```swift
public func events() -> AsyncStream<TerraEvent>
```

**Returns:** a fresh `AsyncStream` of [`TerraEvent`](#terraevent) values. Events raised before you subscribe are not replayed, and a slow subscriber drops its oldest events once its buffer is full. No event carries a health value.

```swift
for await event in terra.diagnostics.events() {
    if case .uploadFailed(let type, _, let code) = event.kind { log(type, code) }
}
```

#### Diagnostics.lastDelivery

Returns when Terra last accepted an upload from this device.

```swift
public func lastDelivery(for source: Source = .health) async -> Date?
```

| Name     | Type                | Description                                               |
| -------- | ------------------- | --------------------------------------------------------- |
| `source` | [`Source`](#source) | The source to ask about. Optional. Defaults to `.health`. |

**Returns:** the time of the last accepted batch, or `nil` if Terra has never accepted one.

#### Diagnostics.state

Returns why data has stopped arriving, in the SDK's own words.

```swift
public func state(for source: Source = .health) async -> DiagnosticsState
```

| Name     | Type                | Description                                               |
| -------- | ------------------- | --------------------------------------------------------- |
| `source` | [`Source`](#source) | The source to ask about. Optional. Defaults to `.health`. |

**Returns:** a [`DiagnosticsState`](#diagnosticsstate).

#### Diagnostics.report

Returns everything support asks for in one value, with nothing in it that identifies a person.

```swift
public func report(for source: Source = .health) async -> SupportReport
```

| Name     | Type                | Description                                               |
| -------- | ------------------- | --------------------------------------------------------- |
| `source` | [`Source`](#source) | The source to report on. Optional. Defaults to `.health`. |

**Returns:** a [`SupportReport`](#supportreport).

#### Diagnostics.send

Sends a redacted support report to Terra, signed by the connection's key.

```swift
public func send(for source: Source = .health) async throws
```

| Name     | Type                | Description                                               |
| -------- | ------------------- | --------------------------------------------------------- |
| `source` | [`Source`](#source) | The source to report on. Optional. Defaults to `.health`. |

Requested sends are limited to one a minute; a send inside that interval is skipped without an error.

| Error                     | When                                                             |
| ------------------------- | ---------------------------------------------------------------- |
| `TerraError.notConnected` | There is no stored link with a signing key.                      |
| `TerraError.network`      | The request failed in transit or Terra returned an error status. |

### DiagnosticsState

Why data has stopped arriving, as the SDK sees it.

```swift
public enum DiagnosticsState: Sendable, Equatable
```

| Case                           | Description                                                                                                                                                                                                  |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `healthy`                      | Nothing is wrong.                                                                                                                                                                                            |
| `quiet(since: Date)`           | Permissions are granted, but HealthKit has produced no data since this date. A hint, not an error: iOS does not separate a denied read from no data, so this is also what a week without a watch looks like. |
| `backgroundRestricted`         | iOS will not run this app's background work.                                                                                                                                                                 |
| `backgroundRefreshUnscheduled` | A refresh request was submitted and iOS is not holding it, so the app will not be woken. Usually your own refresh task holds the one pending request iOS allows.                                             |
| `pendingRetry`                 | A delivery failed in a way that can be retried, and is backing off before the next attempt.                                                                                                                  |
| `linkRevoked`                  | Terra no longer accepts this device's key. Call `connect` again.                                                                                                                                             |
| `devIDMismatch`                | The stored link was made under a different dev ID than this build.                                                                                                                                           |

`DiagnosticsState` is `Encodable`: `encode(to:)` writes `{"state": "quiet", "since": ...}`.

### DiagnosticsReason

Why a support report left the device.

```swift
public enum DiagnosticsReason: String, Sendable, Equatable, Encodable, CaseIterable
```

| Case                               | Description                                                          |
| ---------------------------------- | -------------------------------------------------------------------- |
| `uploadFailed`                     | A delivery ran out of retries.                                       |
| `backfillAbandoned`                | A window Terra asked for was given up on.                            |
| `backgroundObservationUnavailable` | The app cannot receive background delivery for a category.           |
| `backgroundRestricted`             | iOS refuses this app background work.                                |
| `backgroundRefreshUnscheduled`     | iOS is not holding the SDK's refresh request.                        |
| `quiet`                            | Permissions are granted and nothing has been delivered for two days. |
| `requested`                        | Your app called `diagnostics.send()`.                                |

### DiagnosticsPolicy

The sampling and budget rules for automatic support reports.

```swift
public enum DiagnosticsPolicy
```

| Property            | Type           | Description                                                                              |
| ------------------- | -------------- | ---------------------------------------------------------------------------------------- |
| `automaticPerDay`   | `Int`          | Static. The most automatic reports per rolling day: `4`. Requested reports do not count. |
| `day`               | `TimeInterval` | Static. One day, in seconds.                                                             |
| `week`              | `TimeInterval` | Static. One week, in seconds.                                                            |
| `requestedInterval` | `TimeInterval` | Static. The shortest gap between two requested reports: `60` seconds.                    |

#### DiagnosticsPolicy.admits

Returns whether a send fits the budget, given the sends already made.

```swift
public static func admits(
    _ send: DiagnosticsSend, into ledger: [DiagnosticsSend],
    notWithin interval: TimeInterval, automaticLimit limit: Int?
) -> Bool
```

| Name       | Type                                  | Description                                                          |
| ---------- | ------------------------------------- | -------------------------------------------------------------------- |
| `send`     | [`DiagnosticsSend`](#diagnosticssend) | The send being considered.                                           |
| `ledger`   | `[DiagnosticsSend]`                   | The sends already made.                                              |
| `interval` | `TimeInterval`                        | The time within which a send with the same key is refused.           |
| `limit`    | `Int?`                                | The most non-requested sends per rolling day, or `nil` for no limit. |

**Returns:** `false` when a send with the same key falls within `interval`, or when the day's non-requested sends already reach `limit`.

#### DiagnosticsPolicy.rule

Returns the sampling rule for a reason and the failure that fired it.

```swift
public static func rule(
    for reason: DiagnosticsReason, code: TerraEvent.FailureCode? = nil
) -> Rule?
```

| Name     | Type                                                 | Description                                                                   |
| -------- | ---------------------------------------------------- | ----------------------------------------------------------------------------- |
| `reason` | [`DiagnosticsReason`](#diagnosticsreason)            | The reason for the report.                                                    |
| `code`   | [`TerraEvent.FailureCode?`](#terraevent.failurecode) | The failure that fired an `uploadFailed` report. Optional. Defaults to `nil`. |

**Returns:** the [`Rule`](#diagnosticspolicy.rule-type), or `nil` when that reason and code are never reported.

#### DiagnosticsPolicy.sampled

Returns whether an install falls inside a sampling rate.

```swift
public static func sampled(identity: String, rate: Double) -> Bool
```

| Name       | Type     | Description                                         |
| ---------- | -------- | --------------------------------------------------- |
| `identity` | `String` | The install's identity.                             |
| `rate`     | `Double` | The share of installs that report, from `0` to `1`. |

**Returns:** a deterministic answer for the same identity and rate, from an FNV-1a hash of the identity.

### DiagnosticsPolicy.Rule type

The share of installs that report a reason, and how long one install waits before reporting it again.

```swift
public struct Rule: Sendable, Equatable
```

| Property   | Type           | Description                                                                    |
| ---------- | -------------- | ------------------------------------------------------------------------------ |
| `rate`     | `Double`       | The share of installs that report, from `0` to `1`.                            |
| `interval` | `TimeInterval` | How long one install waits before reporting the same reason and trigger again. |

### DiagnosticsSend

One support report a store remembers having sent, for the budget.

```swift
public struct DiagnosticsSend: Sendable, Equatable, Codable

public init(key: String, at: Date)
```

| Property      | Type     | Description                                                                 |
| ------------- | -------- | --------------------------------------------------------------------------- |
| `key`         | `String` | The reason alone, or `reason:trigger` where the trigger has its own budget. |
| `at`          | `Date`   | When the report was sent.                                                   |
| `ledgerLimit` | `Int`    | Static. How many sends a store keeps: `32`.                                 |

#### DiagnosticsSend.trimmed

Reduces a ledger to `ledgerLimit` entries without losing one the budget still consults.

```swift
public static func trimmed(_ ledger: [DiagnosticsSend], now: Date) -> [DiagnosticsSend]
```

| Name     | Type                | Description         |
| -------- | ------------------- | ------------------- |
| `ledger` | `[DiagnosticsSend]` | The ledger to trim. |
| `now`    | `Date`              | The current time.   |

**Returns:** the ledger unchanged when it is within the limit. Otherwise it drops entries older than a week first, then requested sends, then the oldest.

### SupportReport

A redacted support snapshot. It contains no health reading.

```swift
public struct SupportReport: Sendable, Equatable, Encodable
```

| Property              | Type                                    | Description                                     |
| --------------------- | --------------------------------------- | ----------------------------------------------- |
| `sdkVersion`          | `String`                                | The SDK version.                                |
| `generatedAt`         | `Date`                                  | When the report was built.                      |
| `state`               | [`DiagnosticsState`](#diagnosticsstate) | The diagnostics state.                          |
| `lastDelivery`        | `Date?`                                 | When Terra last accepted an upload.             |
| `isConnected`         | `Bool`                                  | Whether a link is stored.                       |
| `requestedCategories` | `[String]`                              | The categories a sheet has ever asked to read.  |
| `requestedWrites`     | `[String]`                              | The categories a sheet has ever asked to write. |
| `requestedWorkouts`   | `[String]`                              | The workout scopes a sheet has ever named.      |
| `recentEvents`        | `[TerraEvent]`                          | The most recent events, up to 64.               |

#### SupportReport.json

Returns the report as JSON a person can paste into a support ticket.

```swift
public func json() throws -> Data
```

**Returns:** pretty-printed JSON with sorted keys and ISO 8601 dates.

**Throws:** an `EncodingError` if encoding fails.

### TerraEvent

Something the SDK did, typed rather than logged. This is the SDK's logging API.

```swift
public struct TerraEvent: Sendable, Equatable

public init(at: Date, kind: Kind)
```

| Property | Type                       | Description       |
| -------- | -------------------------- | ----------------- |
| `at`     | `Date`                     | When it happened. |
| `kind`   | [`Kind`](#terraevent.kind) | What happened.    |

`TerraEvent` is `Encodable`: `encode(to:)` writes `at`, the case name under `event`, and the case's values.

### TerraEvent.Kind

What happened. No case carries a health value.

```swift
public enum Kind: Sendable, Equatable
```

| Case                                                                                                      | Description                                                                                                                                                                                                                                                               |
| --------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `connected(Source)`                                                                                       | A link was made.                                                                                                                                                                                                                                                          |
| `disconnected(Source)`                                                                                    | A link was ended.                                                                                                                                                                                                                                                         |
| `linkRevoked(Source)`                                                                                     | Terra stopped accepting the device's key. Nothing is signed until the next `connect`.                                                                                                                                                                                     |
| `permissionResult(asked: Set<DataCategory>, covered: Set<DataCategory>)`                                  | A permission request finished. `covered` is the part included in the sheet; iOS does not report read consent.                                                                                                                                                             |
| `backgroundWake(Source)`                                                                                  | A background wake arrived.                                                                                                                                                                                                                                                |
| `backgroundWakeRefused(Source, code: FailureCode)`                                                        | A scheduled wake this client was not allowed to act on, and why.                                                                                                                                                                                                          |
| `backgroundRefreshUnscheduled(identifier: String, source: Source)`                                        | iOS is not holding the refresh request under this task identifier.                                                                                                                                                                                                        |
| `uploadBatch(UploadDataType, source: Source, records: Int, bytes: Int)`                                   | Terra accepted one batch.                                                                                                                                                                                                                                                 |
| `uploadFailed(UploadDataType, source: Source, code: FailureCode)`                                         | A batch failed.                                                                                                                                                                                                                                                           |
| `retryScheduled(UploadDataType, source: Source, afterSeconds: TimeInterval, attempt: Int)`                | A retry is scheduled.                                                                                                                                                                                                                                                     |
| `backfillProgress(UploadDataType, source: Source, uploaded: Int, skipped: Int)`                           | Progress on the first-sync history. `skipped` counts windows given up on.                                                                                                                                                                                                 |
| `dailyDayTooLarge(source: Source, day: Date, bytes: Int)`                                                 | Terra refused one local day as too large to send, so it was given up on.                                                                                                                                                                                                  |
| `sleepWakeDateTooLarge(source: Source, wakeDate: Date, bytes: Int)`                                       | One wake date's sleep was too large to send whole, so it was split. Nothing is lost.                                                                                                                                                                                      |
| `clinicalRecordTooLarge(source: Source, id: UUID, clinicalType: ClinicalRecord.ClinicalType, bytes: Int)` | One clinical record was too large for the route at any size, so it was skipped. `clinicalType` is its category (`allergy`, `condition`, `immunization`, `labResult`, `medication`, `procedure`, `vitalSign`, `coverage` or `clinicalNote`). Available in 2.3.0 and later. |
| `devIDBindingChanged(source: Source, devID: String, active: Bool)`                                        | In [`DevIDMode.multiple`](#devidmode), a customer's connection stopped or started being listed by Terra ([`DevIDBinding.isActive`](#devidbinding)). Available in 2.3.0 and later.                                                                                         |
| `serverBackfillQueued(UploadDataType, source: Source)`                                                    | Terra asked for a window and the device took it on.                                                                                                                                                                                                                       |
| `serverBackfillCompleted(UploadDataType, source: Source, uploaded: Int)`                                  | A window Terra asked for was served in full.                                                                                                                                                                                                                              |
| `serverBackfillAbandoned(UploadDataType, source: Source, code: FailureCode)`                              | A window Terra asked for was given up on, with the last failure.                                                                                                                                                                                                          |
| `serverBackfillRefused(source: Source)`                                                                   | A window was refused because the device already holds as many requests as it will.                                                                                                                                                                                        |
| `serverBackfillUnsupported(source: Source)`                                                               | A window was for a data type this SDK cannot upload, so it was dropped.                                                                                                                                                                                                   |
| `serverBackfillPollFailed(source: Source, code: FailureCode)`                                             | Asking Terra for queued windows failed. The next run tries again.                                                                                                                                                                                                         |
| `backgroundObservationUnavailable(DataCategory, source: Source)`                                          | The app cannot get background delivery for this category, usually because the HealthKit background delivery entitlement is missing.                                                                                                                                       |
| `observationDropped(DataCategory, source: Source)`                                                        | A queued wake was dropped because its link has gone.                                                                                                                                                                                                                      |
| `samplesLogged(DataCategory, count: Int, source: Source)`                                                 | A `log` call wrote samples.                                                                                                                                                                                                                                               |
| `sampleDeleted(DataCategory, source: Source)`                                                             | A `delete` call removed a sample.                                                                                                                                                                                                                                         |
| `plannedWorkoutUpdated(Source)`                                                                           | A planned workout was marked complete or deleted.                                                                                                                                                                                                                         |
| `plannedWorkoutsScheduled(Source, scheduled: Int, removed: Int, refused: Int)`                            | A sync run changed the Watch schedule: plans put on it or moved, workouts taken off it, and plans Terra was told cannot be put on it.                                                                                                                                     |
| `plannedWorkoutScheduleFailed(source: Source, code: FailureCode)`                                         | The plan queue could not be read, acknowledged or reported to. The next run tries again.                                                                                                                                                                                  |
| `tokenRefreshed`                                                                                          | The token provider supplied a token.                                                                                                                                                                                                                                      |
| `deviceKeyRevokeAnswered(Source, outcome: DeviceKeyRevokeOutcome)`                                        | Terra answered a key revoke.                                                                                                                                                                                                                                              |
| `deviceKeyRevokeFailed(Source, code: FailureCode, attempt: Int, owed: Bool)`                              | A key revoke failed. `owed` is `false` when nothing can send it.                                                                                                                                                                                                          |
| `diagnosticsReported(DiagnosticsReason, source: Source)`                                                  | A support report was sent.                                                                                                                                                                                                                                                |

### TerraEvent.FailureCode

A failure code that contains no person-identifying text.

```swift
public enum FailureCode: String, Sendable, Equatable, Encodable
```

Each case names a [`TerraError`](#terraerror) case: `healthDataUnavailable`, `notConnected`, `tokenUnavailable`, `tokenRejected`, `tokenProviderFailed`, `offline`, `timedOut`, `serverError`, `transport`, `malformedResponse`, `userLimitReached`, `upgradeRequired`, `platform`, `deviceKeyUnavailable`, `signatureRejected`, `linkRevoked`, `linkConflict`, `clockSkewed`, `devIDMismatch`, `syncAlreadyRunning`, `linkAlreadyRunning`, `storeLocked`, `storeUnreadable`, `deadlineExceeded`, `permissionDenied`, `authorizationNotDetermined`, `sampleNotFound`, `rollbackIncomplete`, `distanceNotAttributable`, `bloodPressureIncomplete`, `authorizationUnavailableInExtension`, `plannedWorkoutUnnamed`, `routeAwaitingConverter`, and in 2.3.0 and later `workoutsRequired`, `dataTypeNotEnabled` and `linkRefused`. The network cases map to `offline`, `timedOut`, `serverError` (which also covers `throttled`), `transport` and `malformedResponse`.

### DeviceKeyRevokeOutcome

What Terra answered when a disconnect asked it to stop accepting a device key.

```swift
public enum DeviceKeyRevokeOutcome: String, Sendable, Equatable, Encodable
```

| Case             | Description                                                                    |
| ---------------- | ------------------------------------------------------------------------------ |
| `revoked`        | Terra revoked the key.                                                         |
| `alreadyRevoked` | Terra had already forgotten the key.                                           |
| `routeAbsent`    | Terra answered 404, so the key may still be trusted and the revoke stays owed. |

## Errors

### TerraError

Every error the SDK throws.

```swift
public enum TerraError: Error, Sendable
```

The cases are split by what you can do about them. Each has a stable [`code`](#terraerror.code) and an [`isRetryable`](#terraerror.isretryable) answer.

| Case                                                       | `code`                                     | Retryable | Description                                                                                                                                                                                                                                                                                                                                                           |
| ---------------------------------------------------------- | ------------------------------------------ | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `healthDataUnavailable`                                    | `health_data_unavailable`                  | No        | The device cannot serve health data at all. Hide the feature.                                                                                                                                                                                                                                                                                                         |
| `notConnected(Source)`                                     | `not_connected`                            | No        | A read or signed call arrived before `connect`.                                                                                                                                                                                                                                                                                                                       |
| `routeAwaitingConverter(UploadDataType)`                   | `route_awaiting_converter`                 | No        | Terra cannot convert this route yet, so the SDK refuses to send it.                                                                                                                                                                                                                                                                                                   |
| `tokenUnavailable`                                         | `token_unavailable`                        | No        | `connect` needed a token and had neither a token nor a token provider.                                                                                                                                                                                                                                                                                                |
| `tokenRejected`                                            | `token_rejected`                           | No        | The token was expired, already spent or unknown. With a provider, a second token also failed.                                                                                                                                                                                                                                                                         |
| `tokenProviderFailed(any Error & Sendable)`                | `token_provider_failed`                    | No        | Your token provider threw. Its error is carried unchanged.                                                                                                                                                                                                                                                                                                            |
| `network(Network)`                                         | `network.<case>`                           | Per case  | A network failure. See [`TerraError.Network`](#terraerror.network).                                                                                                                                                                                                                                                                                                   |
| `userLimitReached`                                         | `user_limit_reached`                       | No        | Your plan's user allowance is used up, so no new user can connect.                                                                                                                                                                                                                                                                                                    |
| `upgradeRequired`                                          | `upgrade_required`                         | No        | Terra has withdrawn this SDK version. Prompt an app update.                                                                                                                                                                                                                                                                                                           |
| `platform(any Error & Sendable)`                           | `platform`                                 | No        | The OS refused for a reason the SDK does not classify. The OS error is carried.                                                                                                                                                                                                                                                                                       |
| `deviceKeyUnavailable`                                     | `device_key_unavailable`                   | No        | The device's signing key could not be created, read or removed.                                                                                                                                                                                                                                                                                                       |
| `signatureRejected`                                        | `signature_rejected`                       | No        | Terra refused the signature on a signed call.                                                                                                                                                                                                                                                                                                                         |
| `clockSkewed`                                              | `clock_skewed`                             | No        | The device's clock is too far from Terra's for any signature to be fresh. Only correcting the clock fixes it.                                                                                                                                                                                                                                                         |
| `linkRevoked(Source)`                                      | `link_revoked`                             | No        | Terra stopped accepting this device's key. Only a fresh link clears it.                                                                                                                                                                                                                                                                                               |
| `devIDMismatch(Source)`                                    | `dev_id_mismatch`                          | No        | This device's stored state belongs to a different dev ID. `connect` is refused, with a token too. The record is in the Keychain and survives reinstalling the app. Running with the original dev ID clears it, and so does erasing the Keychain (on a simulator, `xcrun simctl keychain <device> reset`).                                                             |
| `linkConflict`                                             | `link_conflict`                            | Yes       | Two requests raced for the same link and this one lost.                                                                                                                                                                                                                                                                                                               |
| `syncAlreadyRunning(UploadDataType)`                       | `sync_already_running`                     | No        | A sync for this data type is already running.                                                                                                                                                                                                                                                                                                                         |
| `linkAlreadyRunning(Source)`                               | `link_already_running`                     | No        | A link for this source is already in progress.                                                                                                                                                                                                                                                                                                                        |
| `storeLocked`                                              | `store_locked`                             | Yes       | The device has not been unlocked since it booted, so stored state cannot be read yet. It clears on unlock.                                                                                                                                                                                                                                                            |
| `storeUnreadable`                                          | `store_unreadable`                         | No        | Stored state could not be decoded and was dropped.                                                                                                                                                                                                                                                                                                                    |
| `deadlineExceeded`                                         | `deadline_exceeded`                        | Yes       | A run ran out of time before sending a batch. Nothing was lost; the next run continues.                                                                                                                                                                                                                                                                               |
| `permissionDenied(DataCategory)`                           | `permission_denied`                        | No        | Access was refused, on a platform that says so. On iOS, only writes report it.                                                                                                                                                                                                                                                                                        |
| `authorizationNotDetermined`                               | `authorization_not_determined`             | No        | HealthKit refused a read your app never requested.                                                                                                                                                                                                                                                                                                                    |
| `sampleNotFound(UUID)`                                     | `sample_not_found`                         | No        | A delete named a sample that is not your app's to remove.                                                                                                                                                                                                                                                                                                             |
| `rollbackIncomplete(remaining: [UUID], cause: TerraError)` | `rollback_incomplete`                      | No        | A `log` failed partway and the samples already written could not be removed. Delete `remaining` before retrying.                                                                                                                                                                                                                                                      |
| `distanceNotAttributable(WorkoutActivity)`                 | `distance_not_attributable`                | No        | A workout carried a distance for an activity with no distance type.                                                                                                                                                                                                                                                                                                   |
| `bloodPressureIncomplete`                                  | `blood_pressure_incomplete`                | No        | A `BodyEntry` carried only one half of a blood pressure.                                                                                                                                                                                                                                                                                                              |
| `plannedWorkoutUnnamed`                                    | `planned_workout_unnamed`                  | No        | A planned workout call had an empty ID.                                                                                                                                                                                                                                                                                                                               |
| `authorizationUnavailableInExtension`                      | `authorization_unavailable_in_extension`   | No        | A permission sheet was requested from an app extension.                                                                                                                                                                                                                                                                                                               |
| `dataTypeNotEnabled(UploadDataType)`                       | `data_type_not_enabled`                    | No        | Terra refused an upload because your Terra client has not enabled this data type. `clinicalRecord` is the one that needs it: Health Records (`CLINICAL_RECORD`) must be enabled for your Terra client. The SDK keeps its place and holds the route unread for up to a day, and the first run after you enable it sends everything owed. Available in 2.3.0 and later. |
| `linkRefused(LinkRefusal)`                                 | `link_refused`                             | No        | In [`DevIDMode.multiple`](#devidmode), Terra will not register the shared key on a customer's connection. See [`LinkRefusal`](#linkrefusal). Available in 2.3.0 and later.                                                                                                                                                                                            |
| `workoutsRequired(HealthDataType)`                         | `workouts_required`                        | No        | A permission request named `.workoutRoute`, `.speed`, `.power` or `.cyclingCadence` without `.workouts` or `.activity`. Carries the type. Available in 2.3.0 and later.                                                                                                                                                                                               |
| `healthRecordsUnavailable`                                 | `health_records_unavailable`               | No        | Health Records were requested on a device that cannot hold them. Hide the Health Records feature. Everything else still works. Available in 2.3.0 and later.                                                                                                                                                                                                          |
| `healthRecordsUsageDescriptionMissing`                     | `health_records_usage_description_missing` | No        | The Info.plist lacks `NSHealthClinicalHealthRecordsShareUsageDescription` or `NSHealthShareUsageDescription`. Add the string and rebuild. Available in 2.3.0 and later.                                                                                                                                                                                               |

`TerraError` conforms to `LocalizedError` and to `Equatable`. `errorDescription` is written for developers reading logs, not for end users. Equality compares the kind of failure and ignores the wrapped errors in `tokenProviderFailed` and `platform`.

#### TerraError.code

The stable code non-Swift callers switch on.

```swift
public var code: String { get }
```

**Returns:** the `snake_case` code from the table above. A network error is `network.` followed by [`Network.code`](#terraerror.network.code). Codes do not change when a case is renamed.

#### TerraError.isRetryable

Whether the same call could succeed if you try again later.

```swift
public var isRetryable: Bool { get }
```

**Returns:** the Retryable column above. For `network(.serverError(status:))` it is `true` for 5xx and 429 and `false` for any other status.

#### TerraError.isAuthorizationRefusal

Whether the health store refused for want of authorization rather than failing.

```swift
public var isAuthorizationRefusal: Bool { get }
```

**Returns:** `true` for `authorizationNotDetermined` and `permissionDenied`, which the person has to grant. `false` for everything else.

#### TerraError.errorDescription

A message for developers.

```swift
public var errorDescription: String? { get }
```

**Returns:** a one-sentence English description of the error. Do not show it to end users.

#### TerraError.==

Compares two errors by kind.

```swift
public static func == (lhs: TerraError, rhs: TerraError) -> Bool
```

**Returns:** whether both are the same case with equal associated values, ignoring the wrapped errors of `tokenProviderFailed` and `platform`.

### TerraError.Network

A network failure.

```swift
public enum Network: Sendable, Equatable
```

| Case                                   | `code`                       | Retryable        | Description                                                                                          |
| -------------------------------------- | ---------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------- |
| `offline`                              | `network.offline`            | Yes              | The device is offline.                                                                               |
| `timedOut`                             | `network.timed_out`          | Yes              | The request timed out.                                                                               |
| `serverError(status: Int)`             | `network.server_error`       | 5xx and 429 only | Terra returned a status the SDK could not act on. Always a real HTTP status.                         |
| `throttled(retryAfter: TimeInterval?)` | `network.throttled`          | Yes              | Terra answered 429, with the `Retry-After` delay when it sent one.                                   |
| `transport(code: Int)`                 | `network.transport`          | Yes              | No HTTP response at all, such as a refused connection or a TLS failure. Carries the `URLError` code. |
| `malformedResponse`                    | `network.malformed_response` | No               | A response the SDK could not read.                                                                   |

#### TerraError.Network.code

The part of `TerraError.code` after `network.`.

```swift
public var code: String { get }
```

**Returns:** `offline`, `timed_out`, `server_error`, `throttled`, `transport` or `malformed_response`.

## Data types

The namespace reads return [`HeartRateSample`](#heartratesample), [`StepCount`](#stepcount), [`SleepSegment`](#sleepsegment) and [`Workout`](#workout), and, in 2.2.0 and later, [`RestingHeartRateSample`](#restingheartratesample), [`WorkoutIntensitySample`](#workoutintensitysample), [`WorkoutRoute`](#workoutroute), [`DayTotal`](#daytotal), [`IntradaySample`](#intradaysample), [`BodyReading`](#bodyreading), [`DietaryQuantity`](#dietaryquantity), [`HydrationSample`](#hydrationsample), [`MenstruationFlowDay`](#menstruationflowday), [`MenstrualEvent`](#menstrualevent) and [`AthleteProfile`](#athleteprofile). The other types are what a [`HealthStore`](#healthstore) returns for upload; you meet them when you write a custom store or use the test kit.

Three conventions hold for every sample:

* The unit is in the property name, such as `beatsPerMinute` or `distanceMeters`.
* `id` is HealthKit's own identifier, stable across reads, so you can use it to reconcile repeated reads.
* `source` says which app or device wrote the record.

Many samples share these properties:

| Property      | Type                            | Description                                                                                                                             |
| ------------- | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `source`      | [`SampleSource`](#samplesource) | The app or device that wrote the record.                                                                                                |
| `userEntered` | `Bool`                          | Whether the value was typed in by hand rather than measured. Defaults to `false` in `init`.                                             |
| `timeZone`    | `TimeZone?`                     | The zone the writer recorded, if any. Absent on most samples, in which case the device's own zone is used. Defaults to `nil` in `init`. |

Every type in this section has a memberwise `init` whose parameters match its properties; the signature is shown with each type.

### SampleSource

The app or device that recorded a sample.

```swift
public struct SampleSource: Sendable, Equatable, Hashable

public init(
    name: String, bundleID: String, productType: String? = nil,
    deviceType: DeviceType? = nil
)
```

| Property      | Type                         | Description                                                                                                                      |
| ------------- | ---------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| `name`        | `String`                     | The app or device as a person would recognise it, for example "Adrian's Apple Watch".                                            |
| `bundleID`    | `String`                     | The writing app's bundle ID, for example `com.apple.health`.                                                                     |
| `productType` | `String?`                    | The hardware model, for example `Watch6,1`. Absent when the store does not report one, which is normal for records an app wrote. |
| `deviceType`  | [`DeviceType?`](#devicetype) | The kind of hardware, where the store says so.                                                                                   |

### DeviceType

The kinds of hardware Terra's source ranking distinguishes.

```swift
public enum DeviceType: String, Sendable, Hashable, CaseIterable
```

| Case     | Description                                                                                    |
| -------- | ---------------------------------------------------------------------------------------------- |
| `phone`  | A phone.                                                                                       |
| `scale`  | A scale.                                                                                       |
| `sensor` | A continuous monitor. Its glucose goes to Terra's detailed series rather than the spot series. |

### MotionContext

How the body was moving when a heart rate was measured.

```swift
public enum MotionContext: String, Sendable, Equatable
```

| Case        | Description                                                      |
| ----------- | ---------------------------------------------------------------- |
| `unknown`   | The watch recorded the sample but could not classify the motion. |
| `sedentary` | At rest.                                                         |
| `active`    | Moving.                                                          |

### HeartRateSample

One heart rate reading.

```swift
public struct HeartRateSample: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    time: Date,
    beatsPerMinute: Double,
    source: SampleSource,
    motionContext: MotionContext? = nil,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property         | Type                               | Description                                          |
| ---------------- | ---------------------------------- | ---------------------------------------------------- |
| `id`             | `UUID`                             | HealthKit's identifier for the sample.               |
| `time`           | `Date`                             | When the reading was taken, from the record.         |
| `beatsPerMinute` | `Double`                           | The heart rate, in beats per minute.                 |
| `motionContext`  | [`MotionContext?`](#motioncontext) | How the body was moving, when the store recorded it. |

Plus `source`, `userEntered` and `timeZone`.

### StepCount

Steps totalled over a window, usually a day, for one writer.

```swift
public struct StepCount: Sendable, Equatable, Identifiable

public init(
    interval: DateInterval, steps: Int, source: SampleSource, userEntered: Bool = false,
    timeZone: TimeZone? = nil, uuid: UUID? = nil
)
```

| Property   | Type           | Description                                                                                                                                 |
| ---------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `interval` | `DateInterval` | The window the steps were counted over.                                                                                                     |
| `steps`    | `Int`          | The step total.                                                                                                                             |
| `uuid`     | `UUID?`        | HealthKit's identifier when this is one raw sample. A day total has none.                                                                   |
| `id`       | `String`       | The identity of the bucket: the whole source plus the start of the interval. A phone and a watch reporting the same day have different IDs. |

Plus `source`, `userEntered` and `timeZone`.

### RestingHeartRateSample

HealthKit's own resting heart rate figure, one per day.

```swift
public struct RestingHeartRateSample: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    interval: DateInterval,
    beatsPerMinute: Double,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property         | Type           | Description                                             |
| ---------------- | -------------- | ------------------------------------------------------- |
| `id`             | `UUID`         | HealthKit's identifier for the sample.                  |
| `interval`       | `DateInterval` | The day the figure describes, as the store reported it. |
| `beatsPerMinute` | `Double`       | The resting heart rate, in beats per minute.            |

Plus `source`, `userEntered` and `timeZone`.

### SleepSegment

One continuous stretch of a single sleep stage, as the store recorded it. A night is many segments; the SDK does not group them.

```swift
public struct SleepSegment: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    interval: DateInterval,
    stage: SleepStage,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property   | Type                        | Description                            |
| ---------- | --------------------------- | -------------------------------------- |
| `id`       | `UUID`                      | HealthKit's identifier for the sample. |
| `interval` | `DateInterval`              | The stretch of the stage.              |
| `stage`    | [`SleepStage`](#sleepstage) | The sleep stage.                       |

Plus `source`, `userEntered` and `timeZone`.

### SleepStage

A sleep stage.

```swift
public enum SleepStage: Sendable, Equatable
```

| Case              | Description                                                                    |
| ----------------- | ------------------------------------------------------------------------------ |
| `inBed`           | In bed.                                                                        |
| `awake`           | Awake.                                                                         |
| `asleep`          | Asleep, without a stage breakdown, as older iOS versions report a whole night. |
| `light`           | Light sleep.                                                                   |
| `deep`            | Deep sleep.                                                                    |
| `rem`             | REM sleep.                                                                     |
| `unknown(String)` | A value the SDK does not recognise yet, with the platform's raw label.         |

### Workout

One recorded workout.

```swift
public struct Workout: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    interval: DateInterval,
    activity: WorkoutActivity,
    activityTypeCode: Int,
    indoor: Bool = false,
    activeEnergyKilocalories: Double? = nil,
    distanceMeters: Double? = nil,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil,
    stats: WorkoutStats? = nil,
    events: [WorkoutEvent] = [],
    title: String? = nil
)
```

| Property                   | Type                                  | Description                                                                                                                                                                                                                           |
| -------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                       | `UUID`                                | HealthKit's identifier for the workout.                                                                                                                                                                                               |
| `interval`                 | `DateInterval`                        | When the workout ran.                                                                                                                                                                                                                 |
| `activity`                 | [`WorkoutActivity`](#workoutactivity) | The activity.                                                                                                                                                                                                                         |
| `activityTypeCode`         | `Int`                                 | HealthKit's own code for the activity, passed through unchanged.                                                                                                                                                                      |
| `indoor`                   | `Bool`                                | Whether it was recorded indoors.                                                                                                                                                                                                      |
| `activeEnergyKilocalories` | `Double?`                             | The active energy, in kilocalories. Absent when the store has none; never faked as zero.                                                                                                                                              |
| `distanceMeters`           | `Double?`                             | The distance, in metres. Absent when the store has none.                                                                                                                                                                              |
| `stats`                    | [`WorkoutStats?`](#workoutstats)      | Further totals, when the store has them.                                                                                                                                                                                              |
| `events`                   | [`[WorkoutEvent]`](#workoutevent)     | Laps, segments, pauses, resumes and markers.                                                                                                                                                                                          |
| `title`                    | `String?`                             | The name the writing app gave the session: its `HKMetadataKeyWorkoutBrandName`, because HealthKit has no title field. `nil` when the writer set none or set a blank one. Never derived from `activity`. Available in 2.2.0 and later. |

Plus `source`, `userEntered` and `timeZone`.

### WorkoutStats

Further totals for a workout. An absent value is different from a reported zero.

```swift
public struct WorkoutStats: Sendable, Equatable

public init(
    steps: Int? = nil,
    basalEnergyKilocalories: Double? = nil,
    swimmingStrokes: Int? = nil,
    swimmingLaps: Int? = nil,
    elevationGainMeters: Double? = nil
)
```

| Property                  | Type      | Description                     |
| ------------------------- | --------- | ------------------------------- |
| `steps`                   | `Int?`    | Steps taken during the workout. |
| `basalEnergyKilocalories` | `Double?` | Basal energy, in kilocalories.  |
| `swimmingStrokes`         | `Int?`    | Swimming strokes.               |
| `swimmingLaps`            | `Int?`    | Swimming laps.                  |
| `elevationGainMeters`     | `Double?` | Elevation gained, in metres.    |
| `isEmpty`                 | `Bool`    | Whether every value is absent.  |

### WorkoutEvent

One thing that happened inside a workout, at an instant or over a stretch.

```swift
public struct WorkoutEvent: Sendable, Equatable

public init(kind: Kind, interval: DateInterval)
```

| Property   | Type                         | Description                                  |
| ---------- | ---------------------------- | -------------------------------------------- |
| `kind`     | [`Kind`](#workoutevent.kind) | What happened.                               |
| `interval` | `DateInterval`               | When. A marker and a resume are zero-length. |

### WorkoutEvent.Kind

The kind of workout event.

```swift
public enum Kind: String, Sendable, CaseIterable
```

| Case      | Description |
| --------- | ----------- |
| `lap`     | A lap.      |
| `segment` | A segment.  |
| `pause`   | A pause.    |
| `resume`  | A resume.   |
| `marker`  | A marker.   |

### WorkoutIntensitySample

One speed, power or cadence reading taken inside a workout.

```swift
public struct WorkoutIntensitySample: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    kind: Kind,
    workoutId: UUID,
    interval: DateInterval,
    value: Double,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property    | Type                                   | Description                              |
| ----------- | -------------------------------------- | ---------------------------------------- |
| `id`        | `UUID`                                 | HealthKit's identifier for the sample.   |
| `kind`      | [`Kind`](#workoutintensitysample.kind) | What was measured, which fixes the unit. |
| `workoutId` | `UUID`                                 | The workout the reading belongs to.      |
| `interval`  | `DateInterval`                         | When the reading was taken.              |
| `value`     | `Double`                               | The reading, in `kind.unit`.             |

Plus `source`, `userEntered` and `timeZone`.

### WorkoutIntensitySample.Kind

What an intensity reading measures.

```swift
public enum Kind: String, Sendable, CaseIterable
```

| Case      | Description        |
| --------- | ------------------ |
| `speed`   | Speed, in `m/s`.   |
| `power`   | Power, in `W`.     |
| `cadence` | Cadence, in `rpm`. |

`unit: String` returns the unit for the case.

### WorkoutActivity

The common workout activities, with anything else passed through as text.

```swift
public enum WorkoutActivity: Sendable, Hashable
```

| Case               | Description                  |
| ------------------ | ---------------------------- |
| `running`          | Running.                     |
| `walking`          | Walking.                     |
| `cycling`          | Cycling.                     |
| `swimming`         | Swimming.                    |
| `strengthTraining` | Strength training.           |
| `other(String)`    | Any other activity, by name. |

### WorkoutRoute

The GPS track of a workout, as a record that names its workout.

```swift
public struct WorkoutRoute: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    workoutId: UUID,
    interval: DateInterval,
    points: [RoutePoint],
    source: SampleSource,
    timeZone: TimeZone? = nil
)
```

| Property                      | Type                          | Description                                          |
| ----------------------------- | ----------------------------- | ---------------------------------------------------- |
| `id`                          | `UUID`                        | HealthKit's identifier for the route.                |
| `workoutId`                   | `UUID`                        | The workout the route belongs to.                    |
| `interval`                    | `DateInterval`                | The span the points fall in.                         |
| `points`                      | [`[RoutePoint]`](#routepoint) | The track.                                           |
| `minimumSecondsBetweenPoints` | `TimeInterval`                | Static. The finest sampling uploaded: `1` second.    |
| `maximumPoints`               | `Int`                         | Static. The most points one route may carry: `5000`. |

Plus `source` and `timeZone`.

#### WorkoutRoute.withinCaps

Thins points to at most one a second and at most `maximumPoints`.

```swift
public static func withinCaps(_ points: [RoutePoint]) -> [RoutePoint]
```

| Name     | Type                          | Description                       |
| -------- | ----------------------------- | --------------------------------- |
| `points` | [`[RoutePoint]`](#routepoint) | The track to thin, in time order. |

**Returns:** the thinned track. The first and last points always survive, and applying it twice gives the same result.

### RoutePoint

One fix on a route.

```swift
public struct RoutePoint: Sendable, Equatable, Hashable

public init(time: Date, latitude: Double, longitude: Double)
```

| Property    | Type     | Description                |
| ----------- | -------- | -------------------------- |
| `time`      | `Date`   | When the fix was taken.    |
| `latitude`  | `Double` | The latitude, in degrees.  |
| `longitude` | `Double` | The longitude, in degrees. |

### DayTotal

One day's total for one metric, computed by HealthKit's own statistics engine.

```swift
public struct DayTotal: Sendable, Equatable

public init(metric: Metric, interval: DateInterval, value: Double, unit: String, timeZone: TimeZone? = nil)
```

| Property   | Type                         | Description                                   |
| ---------- | ---------------------------- | --------------------------------------------- |
| `metric`   | [`Metric`](#daytotal.metric) | The metric.                                   |
| `interval` | `DateInterval`               | The local day the total describes, half-open. |
| `value`    | `Double`                     | The total, in `unit`.                         |
| `unit`     | `String`                     | The unit of `value`.                          |
| `timeZone` | `TimeZone?`                  | The zone of the day.                          |

### DayTotal.Metric

A day total metric.

```swift
public enum Metric: String, Sendable, CaseIterable
```

| Case                     | Description                           |
| ------------------------ | ------------------------------------- |
| `steps`                  | Steps, in `count`.                    |
| `distanceWalkingRunning` | Walking and running distance, in `m`. |
| `distanceCycling`        | Cycling distance, in `m`.             |
| `distanceSwimming`       | Swimming distance, in `m`.            |
| `distanceWheelchair`     | Wheelchair distance, in `m`.          |
| `activeEnergyBurned`     | Active energy, in `kcal`.             |
| `basalEnergyBurned`      | Basal energy, in `kcal`.              |
| `flightsClimbed`         | Floors climbed, in `count`.           |
| `swimmingStrokeCount`    | Swimming strokes, in `count`.         |
| `appleExerciseTime`      | Exercise ring time, in `min`.         |
| `appleMoveTime`          | Move time, in `min`.                  |
| `appleStandTime`         | Stand time, in `min`.                 |
| `appleStandHours`        | Hours stood in, in `count`.           |

`unit: String` returns the unit for the case. `intradayKind: IntradaySample.Kind?` returns the intraday type the metric's samples also upload as: `activeEnergy`, `basalEnergy`, `distance` (for `distanceWalkingRunning`) or `floorsClimbed`, and `nil` for the rest.

### IntradaySample

The detail under a day total. The day total stays the authoritative figure for the day.

```swift
public struct IntradaySample: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    kind: Kind,
    interval: DateInterval,
    value: Double,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property   | Type                           | Description                                               |
| ---------- | ------------------------------ | --------------------------------------------------------- |
| `id`       | `UUID`                         | HealthKit's identifier for the sample.                    |
| `kind`     | [`Kind`](#intradaysample.kind) | What was measured.                                        |
| `interval` | `DateInterval`                 | The stretch the value covers. It must not be zero-length. |
| `value`    | `Double`                       | The value, in `kind.unit`.                                |

Plus `source`, `userEntered` and `timeZone`.

### IntradaySample.Kind

What an intraday sample measures.

```swift
public enum Kind: String, Sendable, CaseIterable
```

| Case            | Description                 |
| --------------- | --------------------------- |
| `activeEnergy`  | Active energy, in `kcal`.   |
| `basalEnergy`   | Basal energy, in `kcal`.    |
| `distance`      | Distance, in `m`.           |
| `floorsClimbed` | Floors climbed, in `count`. |

`unit: String` returns the unit for the case.

### BodyReading

One reading on the `body` route.

```swift
public struct BodyReading: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    kind: Kind,
    interval: DateInterval,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property   | Type                        | Description                                                                                                      |
| ---------- | --------------------------- | ---------------------------------------------------------------------------------------------------------------- |
| `id`       | `UUID`                      | HealthKit's identifier for the sample. Terra deduplicates on type, start, end and source, not on this.           |
| `kind`     | [`Kind`](#bodyreading.kind) | What was measured, and in what unit.                                                                             |
| `interval` | `DateInterval`              | When. Point readings have equal start and end; wrist and skin temperatures and insulin deliveries are intervals. |

Plus `source`, `userEntered` and `timeZone`.

### BodyReading.Kind

What a body reading measured. The case fixes the unit.

```swift
public enum Kind: Sendable, Equatable, Hashable
```

| Case                                                                                                               | Description                                                                                                      |
| ------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------- |
| `measurement(BodyMetric, Double)`                                                                                  | A body composition figure, in the [`BodyMetric`](#bodymetric)'s unit.                                            |
| `bloodPressure(systolic: Double, diastolic: Double)`                                                               | A blood pressure, in mmHg.                                                                                       |
| `bloodGlucose(Double, unit: BloodGlucoseUnit, mealTime: GlucoseMealTime? = nil, specimen: GlucoseSpecimen? = nil)` | A blood glucose reading, in the unit the writing app chose. Terra converts it.                                   |
| `oxygenSaturation(fraction: Double)`                                                                               | Oxygen saturation, as a fraction from 0 to 1.                                                                    |
| `temperature(BodyTemperatureMetric, celsius: Double)`                                                              | A temperature, in degrees Celsius. Wrist and skin values are differences from a baseline and are often negative. |
| `heartRateVariability(HeartRateVariabilityMetric, milliseconds: Double)`                                           | Heart rate variability, in milliseconds.                                                                         |
| `respiratoryRate(breathsPerMinute: Double)`                                                                        | Breaths per minute.                                                                                              |
| `vo2Max(millilitresPerKilogramMinute: Double, testType: VO2MaxTestType? = nil)`                                    | VO2 max, in mL/kg/min.                                                                                           |
| `insulinDelivery(internationalUnits: Double, reason: InsulinDeliveryReason)`                                       | An insulin dose, in international units, with its reason.                                                        |
| `electrocardiogram(Electrocardiogram)`                                                                             | An ECG summary.                                                                                                  |
| `heartbeatSeries(beats: [Heartbeat])`                                                                              | The beats HealthKit observed. Terra derives the intervals.                                                       |

`recordType: String` returns the upload type name for the case, such as `"bodyMeasurement"` or `"bloodPressure"`.

### BodyMetric

The body composition figures a `measurement` carries.

```swift
public enum BodyMetric: String, Sendable, Hashable, CaseIterable
```

| Case                 | Description                                 |
| -------------------- | ------------------------------------------- |
| `weight`             | Weight, in `kg`.                            |
| `height`             | Height, in `cm`.                            |
| `bodyFatPercentage`  | Body fat, in `%` as a fraction from 0 to 1. |
| `leanBodyMass`       | Lean body mass, in `kg`.                    |
| `bmi`                | Body mass index, in `count`.                |
| `waistCircumference` | Waist circumference, in `cm`.               |

`unit: String` returns the unit for the case.

### BloodGlucoseUnit

The two units a blood glucose reading may use.

```swift
public enum BloodGlucoseUnit: String, Sendable, Hashable, CaseIterable
```

| Case                     | Description |
| ------------------------ | ----------- |
| `milligramsPerDecilitre` | `mg/dL`.    |
| `millimolesPerLitre`     | `mmol/L`.   |

### GlucoseMealTime

Where a glucose reading sits relative to a meal.

```swift
public enum GlucoseMealTime: String, Sendable, Hashable, CaseIterable
```

| Case           | Description                                                     |
| -------------- | --------------------------------------------------------------- |
| `preprandial`  | Before a meal.                                                  |
| `postprandial` | After a meal.                                                   |
| `unknown`      | The store recorded the reading and said nothing about the meal. |

### GlucoseSpecimen

What was sampled for a glucose reading.

```swift
public enum GlucoseSpecimen: String, Sendable, Hashable, CaseIterable
```

| Case           | Description                                                                           |
| -------------- | ------------------------------------------------------------------------------------- |
| `capillary`    | Capillary blood.                                                                      |
| `interstitial` | Interstitial fluid, from a continuous monitor. Terra files it in the detailed series. |
| `plasma`       | Plasma.                                                                               |
| `serum`        | Serum.                                                                                |
| `tears`        | Tears.                                                                                |
| `wholeBlood`   | Whole blood.                                                                          |
| `unknown`      | Not recorded.                                                                         |

### BodyTemperatureMetric

Which temperature a reading is.

```swift
public enum BodyTemperatureMetric: String, Sendable, Hashable, CaseIterable
```

| Case    | Description                                                           |
| ------- | --------------------------------------------------------------------- |
| `body`  | Body temperature. Absolute.                                           |
| `basal` | Basal body temperature. Absolute.                                     |
| `wrist` | HealthKit's sleeping wrist temperature. A difference from a baseline. |
| `skin`  | Health Connect's skin temperature. A difference from a baseline.      |

### HeartRateVariabilityMetric

Which heart rate variability statistic a reading is.

```swift
public enum HeartRateVariabilityMetric: String, Sendable, Hashable, CaseIterable
```

| Case    | Description                          |
| ------- | ------------------------------------ |
| `sdnn`  | SDNN, which HealthKit reports.       |
| `rmssd` | RMSSD, which Health Connect reports. |

### VO2MaxTestType

How a VO2 max figure was arrived at.

```swift
public enum VO2MaxTestType: String, Sendable, Hashable, CaseIterable
```

| Case                      | Description                          |
| ------------------------- | ------------------------------------ |
| `maxExercise`             | A maximal exercise test.             |
| `predictedSubMaxExercise` | Predicted from sub-maximal exercise. |
| `predictedNonExercise`    | Predicted without exercise.          |

### InsulinDeliveryReason

Why insulin was delivered.

```swift
public enum InsulinDeliveryReason: String, Sendable, Hashable, CaseIterable
```

| Case    | Description    |
| ------- | -------------- |
| `basal` | Basal insulin. |
| `bolus` | Bolus insulin. |

### Electrocardiogram

An ECG summary. The voltages are not read.

```swift
public struct Electrocardiogram: Sendable, Equatable, Hashable

public init(
    classification: Classification,
    averageHeartRate: Double? = nil,
    samplingFrequencyHz: Double? = nil,
    symptomsStatus: SymptomsStatus? = nil
)
```

| Property              | Type              | Description                                                                                                                                                           |
| --------------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `classification`      | `Classification`  | The result: `sinusRhythm`, `atrialFibrillation`, `inconclusiveLowHeartRate`, `inconclusiveHighHeartRate`, `inconclusivePoorReading`, `inconclusiveOther` or `notSet`. |
| `averageHeartRate`    | `Double?`         | The average heart rate, when the reading produced one.                                                                                                                |
| `samplingFrequencyHz` | `Double?`         | The sampling frequency, in hertz.                                                                                                                                     |
| `symptomsStatus`      | `SymptomsStatus?` | Whether symptoms were reported: `present`, `notPresent` or `notSet`.                                                                                                  |

`Electrocardiogram.Classification` and `Electrocardiogram.SymptomsStatus` are `String`, `Sendable`, `CaseIterable` enums with the cases listed above.

### Heartbeat

One beat in a heartbeat series.

```swift
public struct Heartbeat: Sendable, Equatable, Hashable

public init(millisecondsFromStart: Int64, precededByGap: Bool)
```

| Property                | Type    | Description                                                      |
| ----------------------- | ------- | ---------------------------------------------------------------- |
| `millisecondsFromStart` | `Int64` | The beat's offset from the start of the series, in milliseconds. |
| `precededByGap`         | `Bool`  | Whether the interval before this beat was not observed.          |

### DietaryQuantity

One dietary quantity, as the store recorded it, before anything groups it into a meal.

```swift
public struct DietaryQuantity: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    nutrient: Nutrient,
    value: Double,
    interval: DateInterval,
    mealType: MealType = .unknown,
    name: String? = nil,
    foodCorrelationID: UUID? = nil,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property            | Type                    | Description                                                                         |
| ------------------- | ----------------------- | ----------------------------------------------------------------------------------- |
| `id`                | `UUID`                  | HealthKit's identifier for the sample.                                              |
| `nutrient`          | [`Nutrient`](#nutrient) | The nutrient.                                                                       |
| `value`             | `Double`                | The amount, already in `nutrient.unit`.                                             |
| `interval`          | `DateInterval`          | When it was consumed.                                                               |
| `mealType`          | [`MealType`](#mealtype) | The meal, or `.unknown`. Always `.unknown` on iOS.                                  |
| `name`              | `String?`               | The food's name, where the store carries one.                                       |
| `foodCorrelationID` | `UUID?`                 | The HealthKit food correlation this quantity belongs to, when HealthKit grouped it. |

Plus `source`, `userEntered` and `timeZone`.

### MealType

Which meal an entry was logged against.

```swift
public enum MealType: String, Sendable, Hashable, CaseIterable
```

| Case        | Description                                                              |
| ----------- | ------------------------------------------------------------------------ |
| `breakfast` | Breakfast.                                                               |
| `lunch`     | Lunch.                                                                   |
| `dinner`    | Dinner.                                                                  |
| `snack`     | A snack.                                                                 |
| `unknown`   | Not stated. HealthKit has no meal type, so every iOS entry is `unknown`. |

### Nutrient

The 38 nutrients a meal may carry.

```swift
public enum Nutrient: String, Sendable, Hashable, CaseIterable
```

Cases: `energyConsumed`, `protein`, `carbohydrates`, `fatTotal`, `fatSaturated`, `fatMonounsaturated`, `fatPolyunsaturated`, `sugar`, `fiber`, `cholesterol`, `sodium`, `potassium`, `calcium`, `iron`, `magnesium`, `zinc`, `phosphorus`, `iodine`, `manganese`, `molybdenum`, `selenium`, `copper`, `chromium`, `chloride`, `caffeine`, `vitaminA`, `vitaminC`, `vitaminD`, `vitaminE`, `vitaminK`, `vitaminB6`, `vitaminB12`, `thiamin`, `riboflavin`, `niacin`, `folate`, `biotin`, `pantothenicAcid`.

Water is not a nutrient here: it is a [`HydrationSample`](#hydrationsample).

#### Nutrient.unit

The one unit this nutrient uses.

```swift
public var unit: String { get }
```

**Returns:** `kcal` for `energyConsumed`; `g` for `protein`, `carbohydrates`, the four fats, `sugar` and `fiber`; `mg` for everything else.

{% hint style="warning" %}
Micronutrients are in milligrams, never micrograms, including vitamin D, vitamin K, vitamin B12 and biotin, which nutrition labels print in mcg.
{% endhint %}

### HydrationSample

Water drunk, as the store recorded it.

```swift
public struct HydrationSample: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    interval: DateInterval,
    millilitres: Double,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property      | Type           | Description                            |
| ------------- | -------------- | -------------------------------------- |
| `id`          | `UUID`         | HealthKit's identifier for the sample. |
| `interval`    | `DateInterval` | When it was drunk.                     |
| `millilitres` | `Double`       | The volume, in millilitres.            |

Plus `source`, `userEntered` and `timeZone`.

### MenstruationFlowDay

One logged day of menstrual flow.

```swift
public struct MenstruationFlowDay: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    interval: DateInterval,
    flow: Flow,
    cycleStart: Bool,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property     | Type                                | Description                                                            |
| ------------ | ----------------------------------- | ---------------------------------------------------------------------- |
| `id`         | `UUID`                              | HealthKit's identifier for the sample.                                 |
| `interval`   | `DateInterval`                      | Local midnight to the next local midnight, in `timeZone`.              |
| `flow`       | [`Flow`](#menstruationflowday.flow) | How heavy the flow was.                                                |
| `cycleStart` | `Bool`                              | Whether the store marks this as the first day of a cycle.              |
| `timeZone`   | `TimeZone?`                         | The zone whose midnights cut this day. Absent means the device's zone. |

Plus `source` and `userEntered`.

### MenstruationFlowDay.Flow

How heavy a flow day was.

```swift
public enum Flow: String, Sendable, Hashable, CaseIterable
```

| Case          | Description                                           |
| ------------- | ----------------------------------------------------- |
| `unspecified` | Flow, with no level given.                            |
| `light`       | Light.                                                |
| `medium`      | Medium.                                               |
| `heavy`       | Heavy.                                                |
| `noFlow`      | A logged day with no flow. Its raw value is `"none"`. |

### MenstrualEvent

One cycle event beyond flow: a test result, a marker or a logged activity.

```swift
public struct MenstrualEvent: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    kind: Kind,
    storeIdentifier: String,
    instant: Date,
    value: String? = nil,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property          | Type                           | Description                                                                                                                        |
| ----------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| `id`              | `UUID`                         | HealthKit's identifier for the sample.                                                                                             |
| `kind`            | [`Kind`](#menstrualevent.kind) | The event.                                                                                                                         |
| `instant`         | `Date`                         | When it was logged.                                                                                                                |
| `value`           | `String?`                      | One of `kind.values`. `init` sets it to `nil` for any other value.                                                                 |
| `storeIdentifier` | `String`                       | The store's own name for the type, such as the full `HKCategoryTypeIdentifier` string. Required: Terra drops an event without one. |

Plus `source`, `userEntered` and `timeZone`.

### MenstrualEvent.Kind

A cycle event.

```swift
public enum Kind: String, Sendable, Hashable, CaseIterable
```

| Case                               | Values                                                                                            |
| ---------------------------------- | ------------------------------------------------------------------------------------------------- |
| `intermenstrualBleeding`           | None.                                                                                             |
| `ovulationTest`                    | `negative`, `positive`, `high`, `indeterminate`, `luteinizingHormoneSurge`.                       |
| `cervicalMucus`                    | `dry`, `sticky`, `creamy`, `watery`, `eggWhite`, `unusual`.                                       |
| `sexualActivity`                   | `protected`, `unprotected`, `unspecified`.                                                        |
| `pregnancyTest`                    | `negative`, `positive`, `indeterminate`.                                                          |
| `progesteroneTest`                 | `negative`, `positive`, `indeterminate`.                                                          |
| `pregnancy`                        | None.                                                                                             |
| `lactation`                        | None.                                                                                             |
| `contraceptive`                    | `unspecified`, `implant`, `injection`, `intrauterineDevice`, `intravaginalRing`, `oral`, `patch`. |
| `persistentIntermenstrualBleeding` | None.                                                                                             |
| `infrequentCycles`                 | None.                                                                                             |
| `irregularCycles`                  | None.                                                                                             |
| `prolongedPeriods`                 | None.                                                                                             |
| `bleedingDuringPregnancy`          | `unspecified`, `light`, `medium`, `heavy`, `none`.                                                |
| `bleedingAfterPregnancy`           | `unspecified`, `light`, `medium`, `heavy`, `none`.                                                |

`values: [String]` returns the values for the case, empty for the flag-shaped ones.

### AthleteProfile

HealthKit's characteristics, read as one snapshot.

```swift
public struct AthleteProfile: Sendable, Equatable

public init(
    biologicalSex: BiologicalSex,
    dateOfBirth: Date? = nil,
    wheelchairUse: Bool? = nil,
    activityMoveMode: ActivityMoveMode? = nil
)
```

| Property           | Type                                                    | Description                                                                                          |
| ------------------ | ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `biologicalSex`    | [`BiologicalSex`](#athleteprofile.biologicalsex)        | The store's answer, `notSet` included.                                                               |
| `dateOfBirth`      | `Date?`                                                 | The date of birth.                                                                                   |
| `wheelchairUse`    | `Bool?`                                                 | Whether the person uses a wheelchair. It changes what a daily total means: pushes rather than steps. |
| `activityMoveMode` | [`ActivityMoveMode?`](#athleteprofile.activitymovemode) | Which ring the person closes.                                                                        |

A snapshot has no ID and no timestamp. Terra replaces the athlete record whole on each upload.

### AthleteProfile.BiologicalSex

The biological sex characteristic.

```swift
public enum BiologicalSex: String, Sendable, Hashable, CaseIterable
```

| Case     | Description                                              |
| -------- | -------------------------------------------------------- |
| `female` | Female.                                                  |
| `male`   | Male.                                                    |
| `other`  | Other.                                                   |
| `notSet` | The characteristic holds no value, or reading it failed. |

### AthleteProfile.ActivityMoveMode

Which ring the person closes.

```swift
public enum ActivityMoveMode: String, Sendable, Hashable, CaseIterable
```

| Case            | Description    |
| --------------- | -------------- |
| `activeEnergy`  | Active energy. |
| `appleMoveTime` | Move minutes.  |

### HealthObservation

A HealthKit symptom, self-care event or logged count. The built-in store reads symptoms, self-care events and logged counts (inhaler use, falls, blood alcohol, UV exposure) for the `healthObservation` category.

```swift
public struct HealthObservation: Sendable, Equatable, Identifiable

public init(
    id: UUID,
    storeIdentifier: String,
    category: Category,
    interval: DateInterval,
    severity: Severity? = nil,
    value: Value? = nil,
    source: SampleSource,
    userEntered: Bool = false,
    timeZone: TimeZone? = nil
)
```

| Property          | Type           | Description                                                                               |
| ----------------- | -------------- | ----------------------------------------------------------------------------------------- |
| `id`              | `UUID`         | HealthKit's identifier for the sample.                                                    |
| `storeIdentifier` | `String`       | The platform's own name for the type, unchanged.                                          |
| `category`        | `Category`     | `symptom`, `selfCare` or `lab` (inhaler use, falls, blood alcohol and UV exposure).       |
| `interval`        | `DateInterval` | When.                                                                                     |
| `severity`        | `Severity?`    | How bad a symptom was: `unspecified`, `notPresent`, `mild`, `moderate` or `severe`.       |
| `value`           | `Value?`       | A logged count: `.quantity(Double, unit: String)`. Terra rejects a quantity with no unit. |

Plus `source`, `userEntered` and `timeZone`. `HealthObservation.Category` and `HealthObservation.Severity` are `String`, `Hashable`, `CaseIterable` enums with the cases listed above; `HealthObservation.Value` is an `Equatable` enum with the one case `quantity`.

## Extension points

Most apps never implement these. `Terra(devID:)` wires in the built-in adapters: `HealthKitStore` for HealthKit, `HTTPBackend` for Terra's API, `KeychainDeviceStore` for persisted state and `KeychainDeviceKeyStore` for the signing key. The protocols and the request types they exchange are public so you can build a test double or a custom adapter, and pass it to the dependency-injecting initialiser described under [Testing](#testing).

### TerraBackend

The SDK's side of the Terra HTTP API.

```swift
public protocol TerraBackend: Sendable
```

The SDK never sends a reference id through this protocol. Your backend binds the end user when it mints the token.

#### TerraBackend.link

Spends a one-shot link token and returns the connection it established.

```swift
func link(_ request: LinkRequest) async throws -> LinkGrant
```

| Name      | Type                          | Description                                                             |
| --------- | ----------------------------- | ----------------------------------------------------------------------- |
| `request` | [`LinkRequest`](#linkrequest) | The token, source, dev ID, device identity and public key to link with. |

**Returns:** the [`LinkGrant`](#linkgrant) holding Terra's `user_id`.

| Error                      | When                                            |
| -------------------------- | ----------------------------------------------- |
| `TerraError.tokenRejected` | The token is expired, already spent or unknown. |

#### TerraBackend.upload

Uploads one signed batch.

```swift
func upload(_ request: UploadRequest) async throws
```

| Name      | Type                              | Description       |
| --------- | --------------------------------- | ----------------- |
| `request` | [`UploadRequest`](#uploadrequest) | The signed batch. |

Returning normally means Terra accepted the batch. It does not mean the data was stored: a batch for a data type you have disabled is accepted and dropped.

**Throws:** a `TerraError`.

#### TerraBackend.backfillRequests

Fetches a page of the backfill windows Terra is asking this device to re-upload.

```swift
func backfillRequests(_ request: BackfillPollRequest) async throws -> [BackfillDirective]
```

| Name      | Type                                          | Description      |
| --------- | --------------------------------------------- | ---------------- |
| `request` | [`BackfillPollRequest`](#backfillpollrequest) | The signed poll. |

**Returns:** the windows Terra wants re-uploaded.

The read leases: nothing leaves the queue until `acknowledgeBackfills` names it, so a device that fetches and dies gets the same windows again once the lease lapses.

**Throws:** a `TerraError`.

#### TerraBackend.acknowledgeBackfills

Tells Terra which fetched windows this device has written down, which removes them from the queue.

```swift
func acknowledgeBackfills(_ request: BackfillAckRequest) async throws
```

| Name      | Type                                   | Description                                                        |
| --------- | -------------------------------------- | ------------------------------------------------------------------ |
| `request` | [`BackfillAckRequest`](#signedrequest) | The signed acknowledgement. Its `body` is `{"references": [...]}`. |

The SDK calls it only after the requests are persisted. It is idempotent on Terra's side: a retried acknowledgement is not an error.

**Throws:** a `TerraError`.

#### TerraBackend.sendDiagnostics

Sends one signed support report without retrying.

```swift
func sendDiagnostics(_ request: DiagnosticsRequest) async throws
```

| Name      | Type                                   | Description        |
| --------- | -------------------------------------- | ------------------ |
| `request` | [`DiagnosticsRequest`](#signedrequest) | The signed report. |

**Throws:** a `TerraError`.

#### TerraBackend.revokeDeviceKey

Tells Terra to stop accepting the key this request is signed with.

```swift
func revokeDeviceKey(_ request: RevokeDeviceKeyRequest) async throws
```

| Name      | Type                                       | Description                               |
| --------- | ------------------------------------------ | ----------------------------------------- |
| `request` | [`RevokeDeviceKeyRequest`](#signedrequest) | The revoke, signed by the key it revokes. |

It revokes only the signing key, so the connection survives and a person's other phones keep uploading. It is idempotent: Terra answers a key it has already forgotten with a 401, and the SDK reads that as done.

**Throws:** a `TerraError`.

#### TerraBackend.plannedWorkouts

Returns the workouts Terra has planned for this user.

```swift
func plannedWorkouts(_ request: PlannedWorkoutRequest) async throws -> [PlannedWorkout]
```

| Name      | Type                                              | Description      |
| --------- | ------------------------------------------------- | ---------------- |
| `request` | [`PlannedWorkoutRequest`](#plannedworkoutrequest) | The signed read. |

**Returns:** the user's [`PlannedWorkout`](#plannedworkout) values.

**Throws:** a `TerraError`.

#### TerraBackend.updatePlannedWorkout

Reports a plan done, or removes it.

```swift
func updatePlannedWorkout(_ request: PlannedWorkoutUpdate) async throws
```

| Name      | Type                                            | Description        |
| --------- | ----------------------------------------------- | ------------------ |
| `request` | [`PlannedWorkoutUpdate`](#plannedworkoutupdate) | The signed change. |

A missing plan counts as a successful update.

**Throws:** a `TerraError`.

#### TerraBackend.pendingPlanActions

Reads the WorkoutKit actions Terra has queued for this connection, oldest first.

```swift
func pendingPlanActions(_ request: PlanQueueRequest) async throws -> [PendingPlanAction]
```

| Name      | Type                                 | Description      |
| --------- | ------------------------------------ | ---------------- |
| `request` | [`PlanQueueRequest`](#signedrequest) | The signed read. |

**Returns:** the queued `PendingPlanAction` values. Nothing leaves the queue until `acknowledgePlanActions` names it.

This requirement and the two below have default implementations that throw `TerraError.network(.serverError(status: 501))`, so a conformance that leaves them out still compiles, and Watch scheduling reports `plannedWorkoutScheduleFailed` on every run.

#### TerraBackend.acknowledgePlanActions

Tells Terra which queued actions this device applied or refused, which removes them from the queue.

```swift
func acknowledgePlanActions(_ request: PlanAckRequest) async throws
```

| Name      | Type                               | Description                 |
| --------- | ---------------------------------- | --------------------------- |
| `request` | [`PlanAckRequest`](#signedrequest) | The signed acknowledgement. |

**Throws:** a `TerraError`.

#### TerraBackend.reportScheduledWorkouts

Tells Terra about workouts your app scheduled in WorkoutKit itself.

```swift
func reportScheduledWorkouts(_ request: ScheduledWorkoutReportRequest) async throws
```

| Name      | Type                                              | Description        |
| --------- | ------------------------------------------------- | ------------------ |
| `request` | [`ScheduledWorkoutReportRequest`](#signedrequest) | The signed report. |

**Throws:** a `TerraError`.

### HTTPBackend

The production `TerraBackend`, which talks to Terra's v2 API over `URLSession`.

```swift
public struct HTTPBackend: TerraBackend
```

It maps each request onto one HTTP call and each HTTP result onto a `TerraError`. It decides nothing about retries, tokens or persistence.

#### HTTPBackend.defaultTimeout

The request timeout of the shared session, in seconds.

```swift
public static let defaultTimeout: TimeInterval = 8
```

It is shorter than a background refresh slot, so one stalled request cannot outlive the slot.

#### HTTPBackend.init

Creates a backend for a base URL.

```swift
public init(baseURL: URL, session: URLSession? = nil)
```

| Name      | Type          | Description                                                                                                 |
| --------- | ------------- | ----------------------------------------------------------------------------------------------------------- |
| `baseURL` | `URL`         | The API host. The SDK uses `https://api.tryterra.co`.                                                       |
| `session` | `URLSession?` | The session to send with. Optional. Defaults to `nil`, which uses one shared session with `defaultTimeout`. |

#### HTTPBackend.TerraBackend

`HTTPBackend` implements every [`TerraBackend`](#terrabackend) requirement with these signatures, and maps failures as follows:

```swift
public func link(_ request: LinkRequest) async throws -> LinkGrant
public func upload(_ request: UploadRequest) async throws
public func plannedWorkouts(_ request: PlannedWorkoutRequest) async throws -> [PlannedWorkout]
public func updatePlannedWorkout(_ request: PlannedWorkoutUpdate) async throws
public func pendingPlanActions(_ request: PlanQueueRequest) async throws -> [PendingPlanAction]
public func acknowledgePlanActions(_ request: PlanAckRequest) async throws
public func reportScheduledWorkouts(_ request: ScheduledWorkoutReportRequest) async throws
public func backfillRequests(_ request: BackfillPollRequest) async throws -> [BackfillDirective]
public func acknowledgeBackfills(_ request: BackfillAckRequest) async throws
public func sendDiagnostics(_ request: DiagnosticsRequest) async throws
public func revokeDeviceKey(_ request: RevokeDeviceKeyRequest) async throws
```

| Error                                         | When                                                                                                                |
| --------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `TerraError.tokenRejected`                    | `link` gets a 401.                                                                                                  |
| `TerraError.userLimitReached`                 | `link` gets a 402.                                                                                                  |
| `TerraError.linkConflict`                     | `link` gets a 409.                                                                                                  |
| `TerraError.signatureRejected`                | A signed call gets a 401 and the signed timestamp is within 15 minutes of the server's `Date` header.               |
| `TerraError.clockSkewed`                      | A signed call gets a 401 and the signed timestamp is more than 15 minutes from the server's `Date` header.          |
| `TerraError.upgradeRequired`                  | Any call gets a 426.                                                                                                |
| `TerraError.network(.throttled(retryAfter:))` | Any call gets a 429. `retryAfter` comes from the `Retry-After` header.                                              |
| `TerraError.network(.serverError(status:))`   | Any other non-2xx status, a signed 401 with no `Date` header, or a backfill response larger than 1 MB (status 413). |
| `TerraError.network(.offline)`                | The device has no connection, or the host cannot be found or reached.                                               |
| `TerraError.network(.timedOut)`               | The request timed out.                                                                                              |
| `TerraError.network(.transport(code:))`       | Any other `URLError`.                                                                                               |
| `TerraError.network(.malformedResponse)`      | A 2xx response the SDK cannot decode, or a URL it cannot build.                                                     |

`updatePlannedWorkout` treats a 404 as success. `backfillRequests` drops entries whose dates do not parse instead of failing the page.

### LinkRequest

Everything Terra needs to spend a link token.

```swift
public struct LinkRequest: Sendable, Equatable
```

| Property          | Type                | Description                                                                                                                                       |
| ----------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `token`           | `String`            | The one-shot grant, already bound on Terra's side to you and the end user it was minted for.                                                      |
| `source`          | [`Source`](#source) | The source being linked.                                                                                                                          |
| `devID`           | `String`            | Your developer ID. Required by the endpoint, but not an authentication factor: Terra resolves the customer from the token.                        |
| `providerUserID`  | `String`            | This installation's stable identity, which Terra uses to recognise a returning device. In production it is `identifierForVendor`.                 |
| `appIdentifier`   | `String?`           | The app redeeming, which tells a reinstall from a sibling app. `nil` keeps Terra's behaviour from before this field. Production always sends one. |
| `devicePublicKey` | `String`            | The connection's public signing key, base64 DER SubjectPublicKeyInfo.                                                                             |

#### LinkRequest.init

Creates a link request.

```swift
public init(
    token: String,
    source: Source,
    devID: String,
    providerUserID: String,
    devicePublicKey: String,
    appIdentifier: String? = nil
)
```

| Name              | Type                | Description                                     |
| ----------------- | ------------------- | ----------------------------------------------- |
| `token`           | `String`            | The one-shot link token.                        |
| `source`          | [`Source`](#source) | The source being linked.                        |
| `devID`           | `String`            | Your developer ID.                              |
| `providerUserID`  | `String`            | The installation's stable identity.             |
| `devicePublicKey` | `String`            | The public signing key, base64 DER.             |
| `appIdentifier`   | `String?`           | The redeeming app. Optional. Defaults to `nil`. |

### LinkGrant

What Terra returns when a link token is spent.

```swift
public struct LinkGrant: Sendable, Equatable
```

| Property | Type     | Description                                                                      |
| -------- | -------- | -------------------------------------------------------------------------------- |
| `userID` | `String` | Terra's `user_id` for the connection, the one you see on webhooks and API reads. |

#### LinkGrant.init

Creates a grant.

```swift
public init(userID: String)
```

| Name     | Type     | Description          |
| -------- | -------- | -------------------- |
| `userID` | `String` | The Terra `user_id`. |

### UploadDataType

The route a batch is posted to. Terra maps each route to its own data types.

```swift
public enum UploadDataType: String, Sendable, CaseIterable, Codable
```

| Case                | Description                                                      |
| ------------------- | ---------------------------------------------------------------- |
| `daily`             | Day totals, steps and heart rate.                                |
| `sleep`             | Sleep.                                                           |
| `activity`          | Workouts.                                                        |
| `body`              | Body readings.                                                   |
| `nutrition`         | Meals and water.                                                 |
| `menstruation`      | Menstrual flow and cycle events.                                 |
| `athlete`           | The athlete profile.                                             |
| `healthObservation` | Symptoms, self-care events and logged counts.                    |
| `clinicalRecord`    | Apple Health Records, as raw FHIR. Available in 2.3.0 and later. |

#### UploadDataType.routable

The routes the SDK may schedule an upload on.

```swift
public static var routable: [UploadDataType] { get }
```

### UploadContentEncoding

The coding a transport applies to an upload body before sending it.

```swift
public enum UploadContentEncoding: String, Sendable, Equatable
```

| Case   | Description                                                        |
| ------ | ------------------------------------------------------------------ |
| `gzip` | DEFLATE inside RFC 1952 framing, sent as `Content-Encoding: gzip`. |

### UploadRequest

One signed batch of health data.

```swift
public struct UploadRequest: Sendable, Equatable
```

| Property                | Type                                               | Description                                                                                                                                |
| ----------------------- | -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `source`                | [`Source`](#source)                                | The source the batch was read from.                                                                                                        |
| `dataType`              | [`UploadDataType`](#uploaddatatype)                | The route the batch is posted to.                                                                                                          |
| `providerUserID`        | `String`                                           | The identity Terra resolves the connection by.                                                                                             |
| `timestampMilliseconds` | `Int64`                                            | The signing time in Unix milliseconds, inside the signature. Terra rejects anything outside a 15-minute window.                            |
| `body`                  | `Data`                                             | The batch, as signed.                                                                                                                      |
| `contentEncoding`       | [`UploadContentEncoding?`](#uploadcontentencoding) | The coding a transport must apply to `body` before sending, or `nil` to send it as it is. Terra decodes it before verifying the signature. |
| `signature`             | `String`                                           | Base64 DER ECDSA signature over the source, data type, identity, timestamp and body.                                                       |

#### UploadRequest.init

Creates an upload request.

```swift
public init(
    source: Source,
    dataType: UploadDataType,
    providerUserID: String,
    timestampMilliseconds: Int64,
    body: Data,
    signature: String,
    contentEncoding: UploadContentEncoding? = nil
)
```

| Name                    | Type                                               | Description                                        |
| ----------------------- | -------------------------------------------------- | -------------------------------------------------- |
| `source`                | [`Source`](#source)                                | The source.                                        |
| `dataType`              | [`UploadDataType`](#uploaddatatype)                | The route.                                         |
| `providerUserID`        | `String`                                           | The connection's identity.                         |
| `timestampMilliseconds` | `Int64`                                            | The signing time, Unix milliseconds.               |
| `body`                  | `Data`                                             | The signed bytes.                                  |
| `signature`             | `String`                                           | The base64 DER signature.                          |
| `contentEncoding`       | [`UploadContentEncoding?`](#uploadcontentencoding) | The transport coding. Optional. Defaults to `nil`. |

### PlannedWorkoutRequest

A signed read of the user's planned workouts.

```swift
public struct PlannedWorkoutRequest: Sendable, Equatable
```

| Property                | Type                | Description                          |
| ----------------------- | ------------------- | ------------------------------------ |
| `source`                | [`Source`](#source) | The connection's source.             |
| `providerUserID`        | `String`            | The connection's identity.           |
| `signature`             | `String`            | The base64 DER signature.            |
| `timestampMilliseconds` | `Int64`             | The signing time, Unix milliseconds. |

#### PlannedWorkoutRequest.init

Creates a planned-workout read.

```swift
public init(
    source: Source, providerUserID: String, signature: String, timestampMilliseconds: Int64
)
```

| Name                    | Type                | Description       |
| ----------------------- | ------------------- | ----------------- |
| `source`                | [`Source`](#source) | The source.       |
| `providerUserID`        | `String`            | The identity.     |
| `signature`             | `String`            | The signature.    |
| `timestampMilliseconds` | `Int64`             | The signing time. |

### PlannedWorkoutUpdate

A signed change to one planned workout.

```swift
public struct PlannedWorkoutUpdate: Sendable, Equatable
```

| Property                | Type                                                          | Description                                                                                     |
| ----------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `id`                    | `String`                                                      | The plan's ID.                                                                                  |
| `change`                | [`PlannedWorkoutUpdate.Change`](#plannedworkoutupdate.change) | What happens to the plan.                                                                       |
| `source`                | [`Source`](#source)                                           | The connection's source.                                                                        |
| `providerUserID`        | `String`                                                      | The connection's identity.                                                                      |
| `signature`             | `String`                                                      | The base64 DER signature.                                                                       |
| `timestampMilliseconds` | `Int64`                                                       | The signing time, Unix milliseconds.                                                            |
| `body`                  | `Data`                                                        | The bytes that were signed, and the only bytes a transport may send. The action is inside them. |

#### PlannedWorkoutUpdate.init

Creates a planned-workout update.

```swift
public init(
    id: String, change: Change, source: Source, providerUserID: String,
    signature: String, timestampMilliseconds: Int64, body: Data
)
```

| Name                    | Type                                     | Description                                       |
| ----------------------- | ---------------------------------------- | ------------------------------------------------- |
| `id`                    | `String`                                 | The plan's ID.                                    |
| `change`                | [`Change`](#plannedworkoutupdate.change) | The change.                                       |
| `source`                | [`Source`](#source)                      | The source.                                       |
| `providerUserID`        | `String`                                 | The identity.                                     |
| `signature`             | `String`                                 | The signature over `body`.                        |
| `timestampMilliseconds` | `Int64`                                  | The signing time.                                 |
| `body`                  | `Data`                                   | The signed bytes, from `encodedBody(id:change:)`. |

#### PlannedWorkoutUpdate.encodedBody

Encodes a plan change as the bytes to sign and send.

```swift
public static func encodedBody(id: String, change: Change) throws -> Data
```

| Name     | Type                                     | Description    |
| -------- | ---------------------------------------- | -------------- |
| `id`     | `String`                                 | The plan's ID. |
| `change` | [`Change`](#plannedworkoutupdate.change) | The change.    |

**Returns:** sorted-key JSON with `id`, `action` and, for a completion, `completed_at` in ISO 8601.

| Error                                    | When                        |
| ---------------------------------------- | --------------------------- |
| `TerraError.network(.malformedResponse)` | The body cannot be encoded. |

### PlannedWorkoutUpdate.Change

What an update does to a plan.

```swift
public enum Change: Sendable, Equatable
```

| Case                  | Description                    |
| --------------------- | ------------------------------ |
| `completed(at: Date)` | Marks the plan done at a time. |
| `deleted`             | Removes the plan.              |

### SignedRoute

What a signed body authorises, as the label in the signed message.

```swift
public protocol SignedRoute: Sendable
```

| Requirement                        | Description                                |
| ---------------------------------- | ------------------------------------------ |
| `static var label: String { get }` | The route label inside the signed message. |

### DiagnosticsRoute

The route label for support reports.

```swift
public enum DiagnosticsRoute: SignedRoute
```

| Property         | Type     | Description                                                                                                   |
| ---------------- | -------- | ------------------------------------------------------------------------------------------------------------- |
| `label` (static) | `String` | `"diagnostics"`. Distinct from every upload and backfill label, so a captured report authorises nothing else. |

### BackfillAckRoute

The route label for backfill acknowledgements.

```swift
public enum BackfillAckRoute: SignedRoute
```

| Property         | Type     | Description        |
| ---------------- | -------- | ------------------ |
| `label` (static) | `String` | `"backfills.ack"`. |

### DeviceKeyRevokeRoute

The route label for key revocations.

```swift
public enum DeviceKeyRevokeRoute: SignedRoute
```

| Property         | Type     | Description     |
| ---------------- | -------- | --------------- |
| `label` (static) | `String` | `"disconnect"`. |

`PlanQueueRoute`, `PlanAckRoute` and `ScheduledWorkoutReportRoute` are the route labels for the planned-workout queue: `"plannedWorkouts.pending"`, `"plannedWorkouts.ack"` and `"plannedWorkouts.report"`.

### SignedRequest

A signed body for one route.

```swift
public struct SignedRequest<Route: SignedRoute>: Sendable, Equatable

public typealias DiagnosticsRequest = SignedRequest<DiagnosticsRoute>
public typealias BackfillAckRequest = SignedRequest<BackfillAckRoute>
public typealias RevokeDeviceKeyRequest = SignedRequest<DeviceKeyRevokeRoute>
public typealias PlanQueueRequest = SignedRequest<PlanQueueRoute>
public typealias PlanAckRequest = SignedRequest<PlanAckRoute>
public typealias ScheduledWorkoutReportRequest = SignedRequest<ScheduledWorkoutReportRoute>
```

| Type alias                      | Description                                                                              |
| ------------------------------- | ---------------------------------------------------------------------------------------- |
| `DiagnosticsRequest`            | A signed support report.                                                                 |
| `BackfillAckRequest`            | A signed acknowledgement of fetched backfill windows. `body` is `{"references": [...]}`. |
| `RevokeDeviceKeyRequest`        | A signed request to revoke the signing key it is signed with.                            |
| `PlanQueueRequest`              | A signed read of the planned-workout action queue.                                       |
| `PlanAckRequest`                | A signed acknowledgement of planned-workout actions.                                     |
| `ScheduledWorkoutReportRequest` | A signed report of workouts your app scheduled itself.                                   |

| Property                | Type                | Description                          |
| ----------------------- | ------------------- | ------------------------------------ |
| `signedLabel` (static)  | `String`            | The route's `label`.                 |
| `source`                | [`Source`](#source) | The connection's source.             |
| `providerUserID`        | `String`            | The connection's identity.           |
| `timestampMilliseconds` | `Int64`             | The signing time, Unix milliseconds. |
| `body`                  | `Data`              | The signed bytes.                    |
| `signature`             | `String`            | The base64 DER signature.            |

#### SignedRequest.init

Creates a signed request.

```swift
public init(
    source: Source, providerUserID: String, timestampMilliseconds: Int64,
    body: Data, signature: String
)
```

| Name                    | Type                | Description       |
| ----------------------- | ------------------- | ----------------- |
| `source`                | [`Source`](#source) | The source.       |
| `providerUserID`        | `String`            | The identity.     |
| `timestampMilliseconds` | `Int64`             | The signing time. |
| `body`                  | `Data`              | The signed bytes. |
| `signature`             | `String`            | The signature.    |

#### SignedRequest.encodedBody

Encodes a key revocation as the bytes to sign and send. Available when `Route` is `DeviceKeyRevokeRoute`.

```swift
public static func encodedBody(publicKeyBase64DER: String) throws -> Data
```

| Name                 | Type     | Description                               |
| -------------------- | -------- | ----------------------------------------- |
| `publicKeyBase64DER` | `String` | The public key being revoked, base64 DER. |

**Returns:** sorted-key JSON with `reason` set to `"disconnect"` and `device_public_key`, with slashes unescaped.

| Error                 | When                        |
| --------------------- | --------------------------- |
| `TerraError.platform` | The body cannot be encoded. |

### BackfillPollRequest

A signed read of the backfill queue.

```swift
public struct BackfillPollRequest: Sendable, Equatable
```

| Property                | Type                | Description                                                                                                                                   |
| ----------------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| `signedLabel` (static)  | `String`            | `"backfills"`, the route label inside the signed message. Distinct from the acknowledgement's, so a captured poll never authorises a removal. |
| `source`                | [`Source`](#source) | The connection's source.                                                                                                                      |
| `providerUserID`        | `String`            | The connection's identity.                                                                                                                    |
| `timestampMilliseconds` | `Int64`             | The signing time, Unix milliseconds.                                                                                                          |
| `signature`             | `String`            | Base64 DER ECDSA signature over the resource, the label, the identity and the timestamp.                                                      |

#### BackfillPollRequest.init

Creates a backfill poll.

```swift
public init(
    source: Source, providerUserID: String, timestampMilliseconds: Int64, signature: String
)
```

| Name                    | Type                | Description       |
| ----------------------- | ------------------- | ----------------- |
| `source`                | [`Source`](#source) | The source.       |
| `providerUserID`        | `String`            | The identity.     |
| `timestampMilliseconds` | `Int64`             | The signing time. |
| `signature`             | `String`            | The signature.    |

### BackfillDirective

One window Terra has asked the device to re-upload.

```swift
public struct BackfillDirective: Sendable, Equatable
```

| Property    | Type      | Description                                                                            |
| ----------- | --------- | -------------------------------------------------------------------------------------- |
| `dataType`  | `String`  | Terra's own data type string. The SDK decides above this seam whether it can serve it. |
| `start`     | `Date`    | The window's start.                                                                    |
| `end`       | `Date`    | The window's end.                                                                      |
| `reference` | `String?` | Terra's ID for the request. `nil` for a queue entry written before Terra carried one.  |

#### BackfillDirective.init

Creates a backfill directive.

```swift
public init(dataType: String, start: Date, end: Date, reference: String?)
```

| Name        | Type      | Description                 |
| ----------- | --------- | --------------------------- |
| `dataType`  | `String`  | Terra's data type.          |
| `start`     | `Date`    | The window's start.         |
| `end`       | `Date`    | The window's end.           |
| `reference` | `String?` | Terra's request ID, if any. |

### HealthStore

The OS health store behind one protocol: HealthKit on iOS.

```swift
public protocol HealthStore: Sendable
```

Reads take a resolved `DateInterval`, never a `TimeRange`, and treat it as half-open: a sample whose time or start is exactly `end` belongs to the next window. Requirements marked "default" have an implementation in a protocol extension, so a conformance compiles without them.

**Availability and permissions**

| Requirement                                                              | Description                                                                                                                                                                          |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `var isAvailable: Bool { get }`                                          | Whether the device has a health store at all. `false` means no permission can be granted and no read returns data.                                                                   |
| `var canPresentAuthorization: Bool { get }`                              | Whether this process can present a permission sheet. `false` in an app extension. Default: `true`.                                                                                   |
| `func readStatus(for category: DataCategory) async -> PermissionStatus`  | Returns the platform's answer about read access, which on iOS may be "not disclosed".                                                                                                |
| `func readStatus(for type: HealthDataType) async -> PermissionStatus`    | The same answer for one [`HealthDataType`](#healthdatatype). Default: `.notDisclosed`, or `.unavailable` when `isAvailable` is `false`. Available in 2.3.0 and later.                |
| `var supportsHealthRecords: Bool { get }`                                | Whether the device can hold Health Records. Default: `false`. Available in 2.3.0 and later.                                                                                          |
| `func requestClinicalAccess() async throws`                              | Presents the Health Records sheet. Default: throws `healthRecordsUnavailable`. Available in 2.3.0 and later.                                                                         |
| `func requestAccess(_ access: HealthAccess) async throws`                | Presents one sheet covering every type `access` expands to, in both directions, preserving every type already authorized for writing.                                                |
| `func servable(_ access: HealthAccess) async throws -> HealthAccess`     | Returns the part of `access` this platform can put on a sheet. Throws `distanceNotAttributable` for a distance scope whose activity has no distance type. Default: returns `access`. |
| `func writeStatus(for category: DataCategory) async -> PermissionStatus` | Returns whether this app may write the category. Unlike reads, a write denial is reported.                                                                                           |

**Anchored reads and day totals**

| Requirement                                                                                                                          | Description                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `func changes(for dataType: UploadDataType, since anchor: Data?, limit: Int) async throws -> HealthChanges`                          | Returns everything written since `anchor`, by insertion rather than sample time. A `nil` anchor means everything. `limit` caps records across the whole route, and deleted records count against it. Sets `more` when it stops at `limit`. Deletions are not reported. |
| `func changes(for dataType: UploadDataType, since anchor: Data?, limit: Int, attachingContents: Bool) async throws -> HealthChanges` | Returns the same page, optionally without reading the records that hang off it, such as a workout's speed and power. Default: forwards to the three-argument form.                                                                                                     |
| `func dayTotals(in interval: DateInterval, zone: TimeZone) async throws -> [DayTotal]`                                               | Returns day totals for every whole or partial day of `zone` in `interval`, one per metric and day. Default: forwards to `dayTotals(in:)`.                                                                                                                              |
| `func dayTotals(in interval: DateInterval) async throws -> [DayTotal]`                                                               | The form without a zone. Default: returns `[]`.                                                                                                                                                                                                                        |
| `func dayTotals(in interval: DateInterval, zone: TimeZone, policy: DayTotalPolicy) async throws -> [DayTotal]`                       | Returns day totals under a [`DayTotalPolicy`](#daytotalpolicy). Default: forwards to `dayTotals(in:zone:)`.                                                                                                                                                            |
| `var appliesDayTotalPolicy: Bool { get }`                                                                                            | Whether `dayTotals(in:zone:policy:)` honours the policy. Default: `false`.                                                                                                                                                                                             |

**Observation**

| Requirement                                                                                | Description                                                                                                                                                                                                               |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `func observe(_ category: DataCategory, source: Source) -> AsyncStream<ObservedWake>`      | Streams the days new data landed on in this category, starting after the stream is created. Never yields an empty set. Each value carries the acknowledgement the platform waits on. See [`ObservedWake`](#observedwake). |
| `func enableBackgroundObservation(_ category: DataCategory, source: Source) async -> Bool` | Asks the platform to keep waking the app for this category. Returns `false` when the host cannot grant it, for example without the HealthKit background delivery entitlement.                                             |
| `func replayObservation(_ category: DataCategory, source: Source) async -> ObservedChange` | Re-reads what a deferred wake could not. See [`ObservedChange`](#observedchange).                                                                                                                                         |

**Writes**

| Requirement                                                                  | Description                                                                                                       |
| ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `func save(_ entries: [HeartRateEntry]) async throws -> [UUID]`              | Stores entries atomically and returns their IDs in input order.                                                   |
| `func save(_ entries: [StepEntry]) async throws -> [UUID]`                   | Same, for steps.                                                                                                  |
| `func save(_ entries: [SleepEntry]) async throws -> [UUID]`                  | Same, for sleep.                                                                                                  |
| `func save(_ entries: [BodyEntry]) async throws -> [UUID]`                   | Same, for body entries. Default: throws `permissionDenied(.body)`.                                                |
| `func save(_ entries: [NutritionEntry]) async throws -> [UUID]`              | Same, for meals. Default: throws `permissionDenied(.nutrition)`.                                                  |
| `func save(_ entry: WorkoutEntry) async throws -> UUID`                      | Stores one workout and returns its ID.                                                                            |
| `func writeAccess(for entries: [WorkoutEntry]) async throws -> HealthAccess` | Returns the access needed to write this batch, and throws for entries already denied, before anything is written. |
| `func requireWritable(_ entries: [WorkoutEntry]) async throws`               | Throws unless everything the batch needs is authorized for writing.                                               |
| `func delete(_ id: UUID, in category: DataCategory) async throws`            | Removes a sample this app wrote, or throws `sampleNotFound`. A sample another app owns is reported as not found.  |

**Windowed reads**

| Requirement                                                                                            | Description                                                                                                                                                                                                                                                            |
| ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `func heartRate(in interval: DateInterval) async throws -> [HeartRateSample]`                          | Returns heart-rate samples in the window.                                                                                                                                                                                                                              |
| `func restingHeartRate(in interval: DateInterval) async throws -> [RestingHeartRateSample]`            | Returns the store's resting heart rate, one per day the window touches.                                                                                                                                                                                                |
| `func stepSamples(in interval: DateInterval) async throws -> [StepCount]`                              | Returns raw step samples with the intervals the store attributed them to.                                                                                                                                                                                              |
| `func intradaySamples(in interval: DateInterval) async throws -> [IntradaySample]`                     | Returns the raw energy, distance and floors samples under the day totals. Default: `[]`.                                                                                                                                                                               |
| `func sleep(in interval: DateInterval) async throws -> [SleepSegment]`                                 | Returns sleep segments in the window.                                                                                                                                                                                                                                  |
| `func workouts(in interval: DateInterval) async throws -> [Workout]`                                   | Returns workouts in the window.                                                                                                                                                                                                                                        |
| `func workoutIntensity(inside workouts: [Workout]) async throws -> [WorkoutIntensitySample]`           | Returns speed, power and cadence readings for these workouts. Default: `[]`.                                                                                                                                                                                           |
| `func workoutRoutes(of workouts: [Workout]) async throws -> [WorkoutRoute]`                            | Returns the route each workout left, where it left one. Default: `[]`.                                                                                                                                                                                                 |
| `func bodyReadings(in interval: DateInterval) async throws -> [BodyReading]`                           | Returns every `body` reading in the window. Default: `[]`.                                                                                                                                                                                                             |
| `func bodyReadings(in interval: DateInterval, recordTypes: Set<String>) async throws -> [BodyReading]` | Returns only the readings whose `kind.recordType` is in `recordTypes`. [`BodyMetrics.readings`](#bodymetrics.readings) calls it so the store does not read the ECGs and heartbeat series it drops. Default: filters `bodyReadings(in:)`. Available in 2.2.0 and later. |
| `func dietaryQuantities(in interval: DateInterval) async throws -> [DietaryQuantity]`                  | Returns dietary quantities, ungrouped. Water is not among them. Default: `[]`.                                                                                                                                                                                         |
| `func hydration(in interval: DateInterval) async throws -> [HydrationSample]`                          | Returns water intake. Default: `[]`.                                                                                                                                                                                                                                   |
| `func menstruationFlow(in interval: DateInterval) async throws -> [MenstruationFlowDay]`               | Returns menstrual flow. Default: `[]`.                                                                                                                                                                                                                                 |
| `func menstrualEvents(in interval: DateInterval) async throws -> [MenstrualEvent]`                     | Returns cycle events beyond flow. Default: `[]`.                                                                                                                                                                                                                       |
| `func healthObservations(in interval: DateInterval) async throws -> [HealthObservation]`               | Returns health observations. Default: `[]`.                                                                                                                                                                                                                            |
| `func athleteProfile() async throws -> AthleteProfile?`                                                | Returns the store's characteristics as one snapshot, or `nil` where the store has no such notion. Default: `nil`.                                                                                                                                                      |

### HealthChanges

What one anchored read returned, sorted by kind.

```swift
public struct HealthChanges: Sendable
```

| Property                | Type                                                    | Description                                                                                                           |
| ----------------------- | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `heartRate`             | [`[HeartRateSample]`](#heartratesample)                 | Heart-rate samples.                                                                                                   |
| `steps`                 | [`[StepCount]`](#stepcount)                             | Step samples.                                                                                                         |
| `restingHeartRate`      | [`[RestingHeartRateSample]`](#restingheartratesample)   | Resting heart rate.                                                                                                   |
| `sleep`                 | [`[SleepSegment]`](#sleepsegment)                       | Sleep segments.                                                                                                       |
| `workouts`              | [`[Workout]`](#workout)                                 | Workouts.                                                                                                             |
| `workoutIntensity`      | [`[WorkoutIntensitySample]`](#workoutintensitysample)   | Speed, power and cadence readings associated with workouts.                                                           |
| `workoutRoutes`         | [`[WorkoutRoute]`](#workoutroute)                       | The GPS tracks of the workouts.                                                                                       |
| `intensityArrivals`     | [`[WorkoutIntensityArrival]`](#workoutintensityarrival) | Intensity readings the page reported, re-read from their workout afterwards.                                          |
| `routeArrivals`         | [`[WorkoutRouteArrival]`](#workoutroutearrival)         | Routes the page reported, without their points.                                                                       |
| `body`                  | [`[BodyReading]`](#bodyreading)                         | Readings on the `body` route.                                                                                         |
| `nutrients`             | [`[DietaryQuantity]`](#dietaryquantity)                 | Dietary quantities, before grouping into entries.                                                                     |
| `hydration`             | [`[HydrationSample]`](#hydrationsample)                 | Water intake.                                                                                                         |
| `menstruation`          | [`[MenstruationFlowDay]`](#menstruationflowday)         | Menstrual flow.                                                                                                       |
| `menstrualEvents`       | [`[MenstrualEvent]`](#menstrualevent)                   | Cycle events beyond flow.                                                                                             |
| `healthObservations`    | [`[HealthObservation]`](#healthobservation)             | Health observations.                                                                                                  |
| `athlete`               | [`AthleteProfile?`](#athleteprofile)                    | The store's characteristics, read once per sync.                                                                      |
| `dayTotals`             | [`[DayTotal]`](#daytotal)                               | Day totals from the platform's statistics engine.                                                                     |
| `intraday`              | [`[IntradaySample]`](#intradaysample)                   | Intraday samples, beside the day totals.                                                                              |
| `readAt`                | `Date?`                                                 | When the store was read. It becomes the upload's `capturedAt`, which Terra uses to order two uploads of the same day. |
| `bodySeriesArrivals`    | [`[BodySeriesArrival]`](#bodyseriesarrival)             | Heartbeat series the page reported, without their beats.                                                              |
| `totalRelevantInstants` | `[Date]`                                                | Instants whose days' totals need re-reading.                                                                          |
| `anchor`                | `Data?`                                                 | The anchor to pass to the next call. `nil` only when the store had nothing to give one for.                           |
| `more`                  | `Bool`                                                  | Whether the store stopped at `limit`. Come back with `anchor` when `true`.                                            |
| `isEmpty`               | `Bool`                                                  | Whether the page holds no records, arrivals or instants. Read-only.                                                   |

#### HealthChanges.init

Creates a page.

```swift
public init(
    heartRate: [HeartRateSample] = [], steps: [StepCount] = [],
    restingHeartRate: [RestingHeartRateSample] = [],
    sleep: [SleepSegment] = [], workouts: [Workout] = [],
    anchor: Data? = nil, more: Bool = false
)
```

| Name               | Type                       | Description                    |
| ------------------ | -------------------------- | ------------------------------ |
| `heartRate`        | `[HeartRateSample]`        | Optional. Defaults to `[]`.    |
| `steps`            | `[StepCount]`              | Optional. Defaults to `[]`.    |
| `restingHeartRate` | `[RestingHeartRateSample]` | Optional. Defaults to `[]`.    |
| `sleep`            | `[SleepSegment]`           | Optional. Defaults to `[]`.    |
| `workouts`         | `[Workout]`                | Optional. Defaults to `[]`.    |
| `anchor`           | `Data?`                    | Optional. Defaults to `nil`.   |
| `more`             | `Bool`                     | Optional. Defaults to `false`. |

Set the other properties after creating the value.

### BodySeriesArrival

One heartbeat series an anchored page reported, without its beats.

```swift
public struct BodySeriesArrival: Sendable, Equatable, Hashable

public init(id: UUID, instant: Date)
```

| Property  | Type   | Description        |
| --------- | ------ | ------------------ |
| `id`      | `UUID` | The series' ID.    |
| `instant` | `Date` | The series' start. |

### WorkoutIntensityArrival

One intensity reading an anchored page reported, without the reading itself.

```swift
public struct WorkoutIntensityArrival: Sendable, Equatable, Hashable

public init(id: UUID, instant: Date)
```

| Property  | Type   | Description         |
| --------- | ------ | ------------------- |
| `id`      | `UUID` | The reading's ID.   |
| `instant` | `Date` | The reading's time. |

### WorkoutRouteArrival

One route an anchored page reported, without its points.

```swift
public struct WorkoutRouteArrival: Sendable, Equatable, Hashable

public init(id: UUID, instant: Date)
```

| Property  | Type   | Description       |
| --------- | ------ | ----------------- |
| `id`      | `UUID` | The route's ID.   |
| `instant` | `Date` | The route's time. |

### HealthKitStore

The production `HealthStore`, backed by HealthKit.

```swift
public actor HealthKitStore: HealthStore
```

Compiled only where HealthKit exists.

#### HealthKitStore.init

Creates a HealthKit store that keeps its observation anchors in a device store.

```swift
public init(anchors: any DeviceStore = KeychainDeviceStore())
```

| Name      | Type              | Description                                                                                         |
| --------- | ----------------- | --------------------------------------------------------------------------------------------------- |
| `anchors` | `any DeviceStore` | Where observation anchors are kept between launches. Optional. Defaults to `KeychainDeviceStore()`. |

#### HealthKitStore.isAvailable

Whether the device has HealthKit, from `HKHealthStore.isHealthDataAvailable()`.

```swift
public nonisolated let isAvailable: Bool
```

#### HealthKitStore.HealthStore

`HealthKitStore` implements every [`HealthStore`](#healthstore) requirement, including the ones with defaults. What differs from the protocol's description:

| Member                                                      | Behaviour                                                                                                                                                                                                                                                                                                                 |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `readStatus(for:)`                                          | Returns `.unavailable` without HealthKit, `.unsupported` for a category the SDK does not read, and `.notDisclosed` otherwise. HealthKit never reports read access.                                                                                                                                                        |
| `canPresentAuthorization`                                   | `false` inside an app extension bundle.                                                                                                                                                                                                                                                                                   |
| `servable(_:)`                                              | Returns an empty `HealthAccess` without HealthKit. Drops categories with no HealthKit type.                                                                                                                                                                                                                               |
| `requestAccess(_:)`                                         | Does nothing without HealthKit. Adds every type already authorized for writing to the sheet, so a read request never downgrades a write.                                                                                                                                                                                  |
| `writeStatus(for:)`                                         | Returns `.granted` when any type in the category is allowed, else `.notDetermined` when any is undetermined, else `.denied`. For `.activity` it is `.granted` only when every type your app asked to write is allowed. Returns `.unsupported` for a category with no writable type, and `.unavailable` without HealthKit. |
| `writeAccess(for:)`, `requireWritable(_:)`, `delete(_:in:)` | Throw `permissionDenied` when a type the call needs is denied.                                                                                                                                                                                                                                                            |
| `delete(_:in:)`                                             | Deletes by the ID `log` returned, which needs no read access. For body entries and meals it removes every sample that shares the ID.                                                                                                                                                                                      |
| `appliesDayTotalPolicy`                                     | `true`.                                                                                                                                                                                                                                                                                                                   |
| `dayTotals(in:)`                                            | Uses the current time zone and the default policy.                                                                                                                                                                                                                                                                        |
| `enableBackgroundObservation(_:source:)`                    | Enables `.immediate` background delivery for every type in the category. Returns `false` if any type is refused, or without HealthKit.                                                                                                                                                                                    |
| `replayObservation(_:source:)`                              | Returns `.days([])` without HealthKit or for a category with no types.                                                                                                                                                                                                                                                    |
| `athleteProfile()`                                          | Reports a biological sex it cannot read as `notSet`, and any other field it cannot read as `nil`.                                                                                                                                                                                                                         |

### DeviceStore

Device-local state that has to survive relaunch.

```swift
public protocol DeviceStore: Sendable
```

The SDK reads and writes everything it persists through this protocol: the connection, link generations, sync marks and anchors, the backfill queue, deferred wakes, pending key revocations and the diagnostics ledger. Its methods are synchronous. Writes that take `ifGeneration` must check the stored connection's generation and write in one atomic step, and throw `TerraError.notConnected` when it no longer matches.

{% hint style="warning" %}
`updateConnection(_:ifGeneration:)` and `releaseDiagnosticsSend(_:)` are required, with no default. A store that copies `StoredConnection` field by field instead of through `Codable` must copy `dayZones` too.
{% endhint %}

**Identity and ownership**

| Requirement                                                          | Description                                                                                                                                                                                                     |
| -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `var storageDomain: String { get }`                                  | The installation this store speaks for. Must be stable across instances over the same storage.                                                                                                                  |
| `func activeDevID() throws -> String?`                               | Returns the dev ID that owns this storage domain, or `nil` before one claimed it.                                                                                                                               |
| `@discardableResult func claimDevID(_ devID: String) throws -> Bool` | Claims the domain for `devID` in one compare-and-set. Returns `false`, writing nothing, when a different dev ID owns it. Idempotent for the owner. Throws, rather than returning `false`, when it cannot write. |
| `func loadProviderUserID() throws -> String?`                        | Returns this installation's stable identity, or `nil` on a first launch or after a reinstall.                                                                                                                   |
| `func saveProviderUserID(_ id: String) throws`                       | Stores the installation's identity.                                                                                                                                                                             |

**Requested access**

| Requirement                                                                                    | Description                                                                                                                               |
| ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `func loadRequestedAccess() throws -> HealthAccess`                                            | Returns everything a permission sheet has ever been asked for, in both directions.                                                        |
| `@discardableResult func recordRequestedAccess(_ access: HealthAccess) throws -> HealthAccess` | Merges `access` into the stored union and returns the new union, in one lock hold. Must keep anything stored that this build cannot name. |

**Connection and link generations**

| Requirement                                                                                                                           | Description                                                                                                                                                                                                                    |
| ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `func loadConnection(source: Source) throws -> StoredConnection?`                                                                     | Returns the stored connection, or `nil` when none has been established.                                                                                                                                                        |
| `func beginLink(source: Source, owing revocation: PendingRevocation?) throws -> LinkTransition`                                       | Opens a new generation, clears the old link's progress and removes its connection, as one transition. Keeps a connection with `revokedAt` set, re-keyed to the new generation, until `completeLink` replaces it.               |
| `func completeLink(_ connection: StoredConnection) throws`                                                                            | Stores the connection `beginLink` opened. Throws `notConnected` if a newer link has begun since.                                                                                                                               |
| `@discardableResult func updateConnection(_ connection: StoredConnection, ifGeneration generation: Int) throws -> Bool`               | Rewrites the whole stored connection when it still belongs to `generation`. Returns whether it did.                                                                                                                            |
| `@discardableResult func endLink(source: Source, ifGeneration generation: Int?, owing revocation: PendingRevocation?) throws -> Int?` | Ends the link, forgetting its connection and progress as one transition, after storing `revocation`. Pass `nil` to end the current link. Returns the generation whose key may be revoked, or `nil` if the source never linked. |
| `func linkGeneration(source: Source) -> Int`                                                                                          | Returns the persisted generation counter. `0` before any link. Readable before first unlock.                                                                                                                                   |
| `func claimLink(source: Source) -> Bool`                                                                                              | Claims the one link in flight for this source, or returns `false`. Not persisted.                                                                                                                                              |
| `func releaseLink(source: Source)`                                                                                                    | Releases the link claim.                                                                                                                                                                                                       |

**Sync progress**

| Requirement                                                                                                           | Description                                                                                        |
| --------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `func loadSyncedThrough(source: Source, dataType: UploadDataType) throws -> Date?`                                    | Returns how far this data type has been uploaded, or `nil`.                                        |
| `func saveSyncedThrough(_ date: Date, source: Source, dataType: UploadDataType, ifGeneration generation: Int) throws` | Advances the mark, only on `generation`.                                                           |
| `func loadSyncedFrom(source: Source, dataType: UploadDataType) throws -> Date?`                                       | Returns the start of the oldest window uploaded, or `nil`.                                         |
| `func saveSyncedFrom(_ date: Date, source: Source, dataType: UploadDataType, ifGeneration generation: Int) throws`    | Lowers that start, only on `generation`.                                                           |
| `func loadSyncAnchor(source: Source, dataType: UploadDataType) throws -> Data?`                                       | Returns the health store's opaque anchor for this route, or `nil`.                                 |
| `func saveSyncAnchor(_ anchor: Data, source: Source, dataType: UploadDataType, ifGeneration generation: Int) throws`  | Stores the anchor, only on `generation`.                                                           |
| `func claimSync(source: Source, dataType: UploadDataType, generation: Int) -> Bool`                                   | Claims this route and generation for one run, or returns `false` if a run holds it. Not persisted. |
| `func releaseSync(source: Source, dataType: UploadDataType, generation: Int)`                                         | Releases the run claim. A no-op without the claim.                                                 |
| `func beginRetry(source: Source, dataType: UploadDataType, generation: Int)`                                          | Records that a delivery is backing off before another attempt.                                     |
| `func endRetry(source: Source, dataType: UploadDataType, generation: Int)`                                            | Clears the retry record.                                                                           |
| `func pausedUntil(source: Source) -> Date?`                                                                           | Returns when Terra last told this source to stop sending, and until when. Transient.               |
| `func pause(source: Source, until: Date)`                                                                             | Records a pause.                                                                                   |

**Backfill queue**

| Requirement                                                                                                                                   | Description                                                                                                                        |
| --------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `func loadServerBackfills(source: Source) throws -> [StoredBackfillRequest]`                                                                  | Returns the unfinished backfill windows, oldest first. Throws `storeUnreadable` for a queue it cannot decode, after discarding it. |
| `@discardableResult func upsertServerBackfill(_ request: StoredBackfillRequest, source: Source, ifGeneration generation: Int) throws -> Bool` | Records a request or updates its progress. Returns `false` when the queue is full and refused it.                                  |
| `func removeServerBackfill(reference: String, source: Source, ifGeneration generation: Int) throws`                                           | Forgets one request by its reference.                                                                                              |

**Observation**

| Requirement                                                                                                                  | Description                                                                                                                                                      |
| ---------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `func loadObservationAnchor(key: String) throws -> Data?`                                                                    | Returns the observation anchor for a key, or `nil`. Separate from the sync anchor.                                                                               |
| `func saveObservationAnchor(_ anchor: Data, key: String) throws`                                                             | Stores an observation anchor.                                                                                                                                    |
| `func lastWakeSync(source: Source, dataType: UploadDataType) -> Date?`                                                       | Returns when a wake last drove a sync of this route. Transient.                                                                                                  |
| `func noteWakeSync(source: Source, dataType: UploadDataType, at time: Date)`                                                 | Records a wake-driven sync.                                                                                                                                      |
| `func claimWakeSync(_ category: DataCategory, source: Source, dataType: UploadDataType, generation: Int) -> Bool`            | Claims the wake-driven pass, or returns `false` and leaves `category` owed to the running pass. Not persisted.                                                   |
| `func takeWakesOwed(source: Source, dataType: UploadDataType, generation: Int) -> Set<DataCategory>`                         | Takes the owed categories without ending the run.                                                                                                                |
| `func releaseWakeSync(source: Source, dataType: UploadDataType, generation: Int) -> Set<DataCategory>`                       | Ends the run and takes what is owed, in one step.                                                                                                                |
| `func loadDeferredObservations(source: Source) throws -> [DataCategory: DeferredWake]`                                       | Returns the categories whose wake arrived while the device was locked. Persisted. Emptied only by `beginLink` and `endLink`.                                     |
| `@discardableResult func deferObservation(_ category: DataCategory, source: Source, generation: Int) throws -> DeferredWake` | Records a wake against the link it arrived under. An older generation never replaces a newer one. Returns the stored entry. See [`DeferredWake`](#deferredwake). |
| `func retireObservation(_ category: DataCategory, source: Source, ifStillAt wake: DeferredWake) throws`                      | Removes a deferred wake only if nothing deferred the category again since `wake` was read.                                                                       |

**Key revocations**

| Requirement                                                                 | Description                                                                                                                                       |
| --------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `func loadPendingRevocations(source: Source) throws -> [PendingRevocation]` | Returns the revokes this source owes Terra, least-tried first. They outlive the link. Undecodable records come back with `isDeliverable` `false`. |
| `func savePendingRevocation(_ revocation: PendingRevocation) throws`        | Records a revocation, or replaces the one held for its generation.                                                                                |
| `func removePendingRevocation(source: Source, generation: Int) throws`      | Removes a revocation. Removing a missing one succeeds.                                                                                            |
| `func claimRevocations(source: Source) -> Bool`                             | Claims the revocation pass, or returns `false` and records the refused claim. Not persisted.                                                      |
| `@discardableResult func releaseRevocations(source: Source) -> Bool`        | Releases the pass and returns whether a claim was refused while it ran.                                                                           |

**Diagnostics**

| Requirement                                                                                                                         | Description                                                                                                                         |
| ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `func linkDiagnostics(source: Source) throws -> LinkDiagnostics?`                                                                   | Returns what diagnostics reports about one source, read together, or `nil` when nothing is connected.                               |
| `func saveLastDelivery(_ date: Date, source: Source, ifGeneration generation: Int) throws`                                          | Records the last accepted delivery, only on `generation`. Cleared when the link ends.                                               |
| `func loadDiagnosticsSends() throws -> [DiagnosticsSend]`                                                                           | Returns the support reports this installation has sent, oldest first. See [`DiagnosticsSend`](#diagnosticssend).                    |
| `func reserveDiagnosticsSend(_ send: DiagnosticsSend, notWithin interval: TimeInterval, automaticLimit limit: Int?) throws -> Bool` | Admits `send` under [`DiagnosticsPolicy`](#diagnosticspolicy) and appends it to the ledger, or returns `false` and records nothing. |
| `func releaseDiagnosticsSend(_ send: DiagnosticsSend) throws`                                                                       | Removes a reservation whose report never reached Terra. A missing entry is not an error.                                            |

### KeychainDeviceStore

The production `DeviceStore`, backed by the Keychain and a `UserDefaults` suite.

```swift
public struct KeychainDeviceStore: DeviceStore
```

It implements every [`DeviceStore`](#devicestore) requirement. Two stores with the same `domain` share one lock, so two `Terra` instances over one domain act as one installation. Its `UserDefaults` suite is `<domain>.store`, never `.standard`. The record of requested access is shared by every domain in the app, because HealthKit authorization is per app.

#### KeychainDeviceStore.init

Creates a store for a storage domain.

```swift
public init(domain: String = "co.tryterra.sdk")
```

| Name     | Type     | Description                                                                                                                   |
| -------- | -------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `domain` | `String` | The Keychain service and defaults namespace. Optional. Defaults to `"co.tryterra.sdk"`, the domain every `Terra` client uses. |

#### KeychainDeviceStore.storageDomain

The `domain` the store was created with.

```swift
public var storageDomain: String { get }
```

### StoredConnection

What the SDK remembers about a connection between launches.

```swift
public struct StoredConnection: Sendable, Equatable, Codable
```

It holds no secret: the link token was spent at connect time.

| Property         | Type                                  | Description                                                                                                                                                                                                                                               |
| ---------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`         | [`Source`](#source)                   | The source.                                                                                                                                                                                                                                               |
| `userID`         | `String`                              | Terra's `user_id`.                                                                                                                                                                                                                                        |
| `providerUserID` | `String`                              | The identity Terra indexes the connection by, which the SDK signs under. Empty for a record written before this field existed.                                                                                                                            |
| `generation`     | `Int`                                 | The link this connection came from. Strictly increasing and never reused. `0` for a record written before this field existed.                                                                                                                             |
| `devID`          | `String`                              | The dev ID the connection was linked under.                                                                                                                                                                                                               |
| `revokedAt`      | `Date?`                               | When Terra stopped accepting this link's key, or `nil` while it still does. Never cleared: only a fresh link replaces it.                                                                                                                                 |
| `dayZones`       | [`[DayZoneStretch]`](#dayzonestretch) | The zone each stretch of uploaded days was first uploaded in.                                                                                                                                                                                             |
| `endUser`        | `String?`                             | Which [`EndUser`](#enduser) the link was made for: a SHA-256 of the reference salted with the dev ID, or a fixed marker for `.anonymous`. Never the raw reference. `nil` for a record written before this field existed, which the next `connect` adopts. |

#### StoredConnection.init

Creates a stored connection, or decodes one.

```swift
public init(source: Source, userID: String, providerUserID: String = "", generation: Int = 0,
            devID: String = "", revokedAt: Date? = nil, dayZones: [DayZoneStretch] = [],
            endUser: String? = nil)

public init(from decoder: any Decoder) throws
```

| Name             | Type                | Description                                                                                       |
| ---------------- | ------------------- | ------------------------------------------------------------------------------------------------- |
| `source`         | [`Source`](#source) | The source.                                                                                       |
| `userID`         | `String`            | Terra's `user_id`.                                                                                |
| `providerUserID` | `String`            | The signing identity. Optional. Defaults to `""`.                                                 |
| `generation`     | `Int`               | The link generation. Optional. Defaults to `0`.                                                   |
| `devID`          | `String`            | The dev ID. Optional. Defaults to `""`.                                                           |
| `revokedAt`      | `Date?`             | The revocation time. Optional. Defaults to `nil`.                                                 |
| `dayZones`       | `[DayZoneStretch]`  | The remembered zones. Optional. Defaults to `[]`.                                                 |
| `endUser`        | `String?`           | The recorded end user. Optional. Defaults to `nil`.                                               |
| `decoder`        | `any Decoder`       | The decoder. Every key except `source` and `userID` may be missing and falls back to its default. |

### LinkTransition

What one `beginLink` did.

```swift
public struct LinkTransition: Sendable, Hashable

public init(opened: Int, ended: Int?)
```

| Property | Type   | Description                                   |
| -------- | ------ | --------------------------------------------- |
| `opened` | `Int`  | The generation it opened.                     |
| `ended`  | `Int?` | The generation it replaced, if there was one. |

### DayZoneStretch

A stretch of local days the daily route uploaded in one zone.

```swift
public struct DayZoneStretch: Sendable, Equatable, Codable

public init(start: Date, end: Date, zone: String)
```

| Property         | Type     | Description                                                                     |
| ---------------- | -------- | ------------------------------------------------------------------------------- |
| `start`          | `Date`   | The stretch's start, a day boundary.                                            |
| `end`            | `Date`   | The stretch's end, a day boundary.                                              |
| `zone`           | `String` | An IANA time zone identifier.                                                   |
| `limit` (static) | `Int`    | `256`, the most stretches one connection keeps. The oldest are dropped past it. |

### StoredBackfillRequest

One backfill window Terra asked for, and how far this device has got through it.

```swift
public struct StoredBackfillRequest: Sendable, Equatable, Codable
```

| Property              | Type                                | Description                                                                                 |
| --------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------- |
| `reference`           | `String`                            | Terra's ID for the request, or `dataType:start:end` where it sent none. Stable across runs. |
| `dataType`            | [`UploadDataType`](#uploaddatatype) | The route.                                                                                  |
| `start`               | `Date`                              | The window's start.                                                                         |
| `end`                 | `Date`                              | The window's end.                                                                           |
| `servedThrough`       | `Date`                              | How much of the window has been accepted. Starts at `start`.                                |
| `failedRuns`          | `Int`                               | Runs that failed without moving `servedThrough`. Reset by any progress.                     |
| `receivedAt`          | `Date`                              | When the device fetched it.                                                                 |
| `queueLimit` (static) | `Int`                               | `64`, the most requests one device holds at a time.                                         |

#### StoredBackfillRequest.init

Creates a stored backfill request.

```swift
public init(
    reference: String, dataType: UploadDataType, start: Date, end: Date,
    servedThrough: Date? = nil, failedRuns: Int = 0, receivedAt: Date
)
```

| Name            | Type                                | Description                                                        |
| --------------- | ----------------------------------- | ------------------------------------------------------------------ |
| `reference`     | `String`                            | The request's key.                                                 |
| `dataType`      | [`UploadDataType`](#uploaddatatype) | The route.                                                         |
| `start`         | `Date`                              | The window's start.                                                |
| `end`           | `Date`                              | The window's end.                                                  |
| `servedThrough` | `Date?`                             | Progress so far. Optional. Defaults to `nil`, which means `start`. |
| `failedRuns`    | `Int`                               | Failed runs so far. Optional. Defaults to `0`.                     |
| `receivedAt`    | `Date`                              | When it was fetched.                                               |

### PendingRevocation

A key revoke a disconnect still owes Terra.

```swift
public struct PendingRevocation: Sendable, Equatable, Codable
```

Each attempt is re-signed, because of Terra's 15-minute freshness window. There is no attempt cap and no expiry.

| Property         | Type                | Description                                                                                       |
| ---------------- | ------------------- | ------------------------------------------------------------------------------------------------- |
| `source`         | [`Source`](#source) | The source.                                                                                       |
| `providerUserID` | `String`            | The identity the link presented.                                                                  |
| `generation`     | `Int`               | The generation whose key is revoked.                                                              |
| `attempts`       | `Int`               | Attempts so far. The queue is ordered least-tried first.                                          |
| `deferredAt`     | `Date`              | When the revoke was deferred.                                                                     |
| `isDeliverable`  | `Bool`              | `false` for a record whose stored value could not be decoded (empty `providerUserID`). Read-only. |

#### PendingRevocation.init

Creates a pending revocation.

```swift
public init(
    source: Source, providerUserID: String, generation: Int,
    attempts: Int = 0, deferredAt: Date
)
```

| Name             | Type                | Description                                 |
| ---------------- | ------------------- | ------------------------------------------- |
| `source`         | [`Source`](#source) | The source.                                 |
| `providerUserID` | `String`            | The link's identity.                        |
| `generation`     | `Int`               | The key's generation.                       |
| `attempts`       | `Int`               | Attempts so far. Optional. Defaults to `0`. |
| `deferredAt`     | `Date`              | When it was deferred.                       |

### LinkDiagnostics

What one link looks like to diagnostics, as of one read.

```swift
public struct LinkDiagnostics: Sendable, Equatable

public init(generation: Int, lastDelivery: Date?, isRetrying: Bool, isRevoked: Bool)
```

| Property       | Type    | Description                                                                         |
| -------------- | ------- | ----------------------------------------------------------------------------------- |
| `generation`   | `Int`   | The link generation.                                                                |
| `lastDelivery` | `Date?` | When Terra last accepted a batch on this link. Delivery time, not history progress. |
| `isRetrying`   | `Bool`  | Whether a delivery is backing off.                                                  |
| `isRevoked`    | `Bool`  | Whether Terra has stopped accepting the link's key.                                 |

### DeviceKeyStore

Where the per-link signing keys live.

```swift
public protocol DeviceKeyStore: Sendable
```

Creating and reading are separate calls, and only linking may create: a key created anywhere else is one Terra never registered.

| Requirement                                                                  | Description                                                                                 |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `func createKey(for source: Source, generation: Int) throws -> DeviceKey`    | Returns the link's signing key, creating one if there is none. Only the link path calls it. |
| `func existingKey(for source: Source, generation: Int) throws -> DeviceKey?` | Returns the link's existing signing key, or `nil`. Never creates.                           |
| `func deleteKey(for source: Source, generation: Int) throws`                 | Forgets that generation's key, so a signed-out device cannot keep uploading.                |

### DeviceKey

A signing key and the public half Terra stores against the connection.

```swift
public struct DeviceKey: Sendable
```

| Property             | Type     | Description                                        |
| -------------------- | -------- | -------------------------------------------------- |
| `publicKeyBase64DER` | `String` | The public key as base64 DER SubjectPublicKeyInfo. |

#### DeviceKey.init

Creates a key from its public half and a signing function.

```swift
public init(publicKeyBase64DER: String, sign: @escaping @Sendable (Data) throws -> Data)
```

| Name                 | Type                              | Description                                                                                                |
| -------------------- | --------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `publicKeyBase64DER` | `String`                          | The public key, base64 DER SubjectPublicKeyInfo.                                                           |
| `sign`               | `@Sendable (Data) throws -> Data` | The function that returns a DER ECDSA signature over a message. It hashes the message with SHA-256 itself. |

#### DeviceKey.signature

Signs a prepared message.

```swift
public func signature(over message: Data) throws -> String
```

| Name      | Type   | Description                              |
| --------- | ------ | ---------------------------------------- |
| `message` | `Data` | The message to sign. Do not pre-hash it. |

**Returns:** the base64 DER ECDSA signature for the `terra-signature` header.

**Throws:** whatever `sign` throws.

### KeychainDeviceKeyStore

The production `DeviceKeyStore`: keys in the Secure Enclave, references in the Keychain.

```swift
public struct KeychainDeviceKeyStore: DeviceKeyStore
```

Where the device has no Secure Enclave, such as the simulator, it uses a software P-256 key with the same signing and wire behaviour. Keys are stored as this-device-only items available after first unlock, so they never move to new hardware with a backup.

#### KeychainDeviceKeyStore.init

Creates a key store for a Keychain service.

```swift
public init(service: String = "co.tryterra.sdk.devicekey")
```

| Name      | Type     | Description                                                                                            |
| --------- | -------- | ------------------------------------------------------------------------------------------------------ |
| `service` | `String` | The Keychain service. Optional. Defaults to `"co.tryterra.sdk.devicekey"`, which is what `Terra` uses. |

#### KeychainDeviceKeyStore.createKey

Returns the link's signing key, creating and storing one if there is none.

```swift
public func createKey(for source: Source, generation: Int) throws -> DeviceKey
```

| Name         | Type                | Description          |
| ------------ | ------------------- | -------------------- |
| `source`     | [`Source`](#source) | The source.          |
| `generation` | `Int`               | The link generation. |

**Returns:** the [`DeviceKey`](#devicekey). If another caller created one at the same time, theirs is returned.

| Error                             | When                                                                                                |
| --------------------------------- | --------------------------------------------------------------------------------------------------- |
| `TerraError.storeLocked`          | The device has not been unlocked since it booted.                                                   |
| `TerraError.deviceKeyUnavailable` | The Keychain refused the read or the write, or an enclave key was restored where no enclave exists. |

#### KeychainDeviceKeyStore.existingKey

Returns the link's existing signing key, or `nil`.

```swift
public func existingKey(for source: Source, generation: Int) throws -> DeviceKey?
```

| Name         | Type                | Description          |
| ------------ | ------------------- | -------------------- |
| `source`     | [`Source`](#source) | The source.          |
| `generation` | `Int`               | The link generation. |

**Returns:** the key, or `nil` when none is stored.

| Error                             | When                                                             |
| --------------------------------- | ---------------------------------------------------------------- |
| `TerraError.storeLocked`          | The device has not been unlocked since it booted.                |
| `TerraError.deviceKeyUnavailable` | The Keychain refused the read, or the stored key cannot be used. |

#### KeychainDeviceKeyStore.deleteKey

Deletes the link's signing key.

```swift
public func deleteKey(for source: Source, generation: Int) throws
```

| Name         | Type                | Description          |
| ------------ | ------------------- | -------------------- |
| `source`     | [`Source`](#source) | The source.          |
| `generation` | `Int`               | The link generation. |

Deleting a key that is not there succeeds.

| Error                             | When                             |
| --------------------------------- | -------------------------------- |
| `TerraError.deviceKeyUnavailable` | The Keychain refused the delete. |

## Testing

`TerraTestKit` holds test doubles for every extension point. Link it into test targets only: the SwiftPM product `TerraTestKit`, or the `TerraiOSTestKit` pod. Build `Terra` from the doubles through its dependency-injecting initialiser, which is behind `@_spi(Testing)`, and your tests can drive links, permission sheets, writes and failures with no device and no network.

Members marked `@_spi(TestRig)` in the test kit drive the SDK's own internals. They are not part of the customer surface and are not listed here.

### Terra.init (testing)

Creates a client from injected dependencies.

```swift
@_spi(Testing) import TerraSDK
import TerraTestKit
```

```swift
@_spi(Testing)
public convenience init(
    devID: String,
    health: HealthStore,
    backend: TerraBackend,
    store: DeviceStore,
    keys: DeviceKeyStore,
    tokenProvider: (@Sendable () async throws -> String)? = nil,
    backgroundRestricted: @escaping @Sendable () async -> Bool = { false },
    backgroundRefreshScheduled: @escaping @Sendable (String) async -> Bool? = { _ in nil },
    inBackground: @escaping @Sendable () async -> Bool = { false },
    unlocks: @escaping @Sendable () -> AsyncStream<Void> = { AsyncStream { _ in } },
    vendorIdentity: @escaping @Sendable () async -> String? = { nil },
    appIdentifier: String? = nil,
    deviceZone: @escaping @Sendable () -> TimeZone = { .current },
    syncsAutomatically: Bool = false,
    foregrounds: @escaping @Sendable () -> AsyncStream<Void> = { AsyncStream { _ in } },
    dayTotals: DayTotalPolicy = .default,
    workoutSchedule: any WorkoutSchedule = UnavailableWorkoutSchedule()
)
```

| Name                         | Type                                     | Description                                                                                                                                                |
| ---------------------------- | ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `devID`                      | `String`                                 | Your developer ID.                                                                                                                                         |
| `health`                     | [`HealthStore`](#healthstore)            | The health store, for example `FakeHealthStore()`.                                                                                                         |
| `backend`                    | [`TerraBackend`](#terrabackend)          | The backend, for example `FakeBackend()`.                                                                                                                  |
| `store`                      | [`DeviceStore`](#devicestore)            | The persisted state, for example `InMemoryDeviceStore()`.                                                                                                  |
| `keys`                       | [`DeviceKeyStore`](#devicekeystore)      | The signing keys, for example `InMemoryDeviceKeyStore()`.                                                                                                  |
| `tokenProvider`              | `(@Sendable () async throws -> String)?` | The link token provider. Optional. Defaults to `nil`.                                                                                                      |
| `backgroundRestricted`       | `@Sendable () async -> Bool`             | Whether background refresh is restricted. Optional. Defaults to `{ false }`.                                                                               |
| `backgroundRefreshScheduled` | `@Sendable (String) async -> Bool?`      | Whether a refresh task with this identifier is pending, or `nil` if unknown. Optional. Defaults to `{ _ in nil }`.                                         |
| `inBackground`               | `@Sendable () async -> Bool`             | Whether the app is in the background now. Optional. Defaults to `{ false }`.                                                                               |
| `unlocks`                    | `@Sendable () -> AsyncStream<Void>`      | Fires when the device unlocks. Optional. Defaults to a stream that never fires.                                                                            |
| `vendorIdentity`             | `@Sendable () async -> String?`          | The device's vendor identity. Optional. Defaults to `{ nil }`.                                                                                             |
| `appIdentifier`              | `String?`                                | The app identifier sent at link. Optional. Defaults to `nil`.                                                                                              |
| `deviceZone`                 | `@Sendable () -> TimeZone`               | The device's time zone. Optional. Defaults to `{ .current }`.                                                                                              |
| `syncsAutomatically`         | `Bool`                                   | Whether the client syncs on its own. Optional. Defaults to `false`, so a test drives runs itself.                                                          |
| `foregrounds`                | `@Sendable () -> AsyncStream<Void>`      | Fires when the app becomes active. Optional. Defaults to a stream that never fires.                                                                        |
| `dayTotals`                  | [`DayTotalPolicy`](#daytotalpolicy)      | The day-total policy. Optional. Defaults to `.default`.                                                                                                    |
| `workoutSchedule`            | `any WorkoutSchedule`                    | The Apple Watch workout schedule, for example `FakeWorkoutSchedule()`. Optional. Defaults to `UnavailableWorkoutSchedule()`, which reports `.unsupported`. |

```swift
let health = FakeHealthStore()
let backend = FakeBackend(grant: LinkGrant(userID: "user-1"))
let terra = Terra(
    devID: "test-dev-id",
    health: health,
    backend: backend,
    store: InMemoryDeviceStore(),
    keys: InMemoryDeviceKeyStore(),
    tokenProvider: { "token-1" })

try await terra.connect(.health, for: .reference("user-ref"))
#expect(await backend.linkedTokens == ["token-1"])
```

With `syncsAutomatically` `false`, nothing uploads on its own. The same SPI exposes `Connection.sync(_:backfillDays:)` and `Connection.syncAll(backfillDays:)`, which run an upload on demand in tests.

### FakeBackend

A `TerraBackend` that never touches the network and records what it was sent.

```swift
public actor FakeBackend: TerraBackend

public init(grant: LinkGrant = LinkGrant(userID: "fake-user"), failures: [TerraError] = [])
```

`failures` are thrown by successive `link` calls before one succeeds. `[.tokenRejected]` reproduces a token that expired between minting and spending.

| Member                                                                                                   | Description                                                                                                                                               |
| -------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `linkRequests: [LinkRequest]`                                                                            | Every link request, in order.                                                                                                                             |
| `linkedTokens: [String]`                                                                                 | The tokens spent, in order.                                                                                                                               |
| `uploads: [UploadRequest]`                                                                               | Every batch it accepted, in order. Rejected batches are absent.                                                                                           |
| `uploadAttempts: Int`                                                                                    | Calls to `upload`, accepted or not.                                                                                                                       |
| `failUploads(with failure: TerraError)`                                                                  | Fails every upload from now on.                                                                                                                           |
| `failUploads(with failure: TerraError, times: Int)`                                                      | Fails the next `times` uploads, then accepts.                                                                                                             |
| `stopFailingUploads()`                                                                                   | Accepts uploads again.                                                                                                                                    |
| `backfillPolls: [String]`                                                                                | The identities `backfillRequests` was called with, in order.                                                                                              |
| `backfillAcks: [[String]]`                                                                               | Every acknowledgement, as the reference lists sent.                                                                                                       |
| `stageBackfills(_ directives: [BackfillDirective])`                                                      | Returns these from the next `backfillRequests` call.                                                                                                      |
| `failBackfillPolls(with error: TerraError)`                                                              | Fails backfill polls.                                                                                                                                     |
| `failBackfillAcks(with error: TerraError)`                                                               | Fails backfill acknowledgements.                                                                                                                          |
| `diagnosticsReports: [DiagnosticsRequest]`                                                               | Every support report sent, accepted or not.                                                                                                               |
| `failDiagnostics(with error: TerraError)`                                                                | Fails support reports.                                                                                                                                    |
| `revocations: [RevokeDeviceKeyRequest]`                                                                  | Every key revoke it accepted, in order.                                                                                                                   |
| `revokeAttempts: Int`                                                                                    | Calls to `revokeDeviceKey`, accepted or not.                                                                                                              |
| `revokeAlreadyRevoked` (static)                                                                          | `TerraError.signatureRejected`, the answer for a key Terra already forgot. The SDK treats it as done.                                                     |
| `revokeRouteAbsent` (static)                                                                             | `TerraError.network(.serverError(status: 404))`, the answer from an API without the revoke route. The SDK keeps the revoke owed and sends it again later. |
| `failRevokes(with error: TerraError)`                                                                    | Fails every revoke from now on.                                                                                                                           |
| `failRevokes(with error: TerraError, times: Int)`                                                        | Fails the next `times` revokes, then accepts.                                                                                                             |
| `stopFailingRevokes()`                                                                                   | Accepts revokes again.                                                                                                                                    |
| `setPlannedWorkouts(_ workouts: [PlannedWorkout], for providerUserID: String, source: Source = .health)` | Stages a user's plans.                                                                                                                                    |
| `failPlannedWorkouts(with error: TerraError?)`                                                           | Fails plan reads and updates, or stops with `nil`.                                                                                                        |
| `plannedReads: [PlannedWorkoutRequest]`                                                                  | Every plan read.                                                                                                                                          |
| `plannedUpdates: [PlannedWorkoutUpdate]`                                                                 | Every plan update. Updates are applied to the staged plans.                                                                                               |
| `stagePlanActions(_ actions: [PendingPlanAction], for providerUserID: String, source: Source = .health)` | Queues Watch schedule actions for a connection.                                                                                                           |
| `queuedPlanActions(for providerUserID: String, source: Source = .health) -> [PendingPlanAction]`         | The actions still queued: staged and not yet acknowledged.                                                                                                |
| `failPlanQueue(with error: TerraError?)`                                                                 | Fails `pendingPlanActions`, or stops with `nil`.                                                                                                          |
| `failPlanAcks(with error: TerraError?)`                                                                  | Fails `acknowledgePlanActions`, or stops with `nil`.                                                                                                      |
| `planQueueReads: [PlanQueueRequest]`                                                                     | Calls to `pendingPlanActions`, failed or not.                                                                                                             |
| `planAcks: [PlanAckRequest]`                                                                             | Every acknowledgement it accepted, in order.                                                                                                              |
| `scheduledReports: [[String]]`                                                                           | Every report of workouts the app scheduled itself, as the WorkoutKit IDs it named.                                                                        |

### FakeHealthStore

A `HealthStore` you stage samples, permission states and failures on.

```swift
public actor FakeHealthStore: HealthStore

public init(
    isAvailable: Bool = true, canPresentAuthorization: Bool = true,
    statuses: [DataCategory: PermissionStatus] = [:]
)

public init(
    isAvailable: Bool = true, canPresentAuthorization: Bool = true,
    statuses: [DataCategory: PermissionStatus] = [:], appliesDayTotalPolicy: Bool
)
```

It implements every `HealthStore` requirement over what you stage. A category with no staged status reads as `.notDisclosed`.

| Member                                                                                                                                                                                                                                                                                                                                                | Description                                                                                       |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
| `setStatus(_ status: PermissionStatus, for category: DataCategory)`                                                                                                                                                                                                                                                                                   | Stages a read status.                                                                             |
| `setWriteStatus(_ status: PermissionStatus, for attachment: WorkoutAttachment)`                                                                                                                                                                                                                                                                       | Stages a refusal of a workout's energy or distance.                                               |
| `setHeartRate(_:)`, `setRestingHeartRate(_:)`, `setSteps(_:)`, `setStepSamples(_:)`, `setIntraday(_:)`, `setSleep(_:)`, `setWorkouts(_:)`, `setWorkoutRoutes(_:)`, `setWorkoutIntensity(_:)`, `setBodyReadings(_:)`, `setDietaryQuantities(_:)`, `setHydration(_:)`, `setMenstruationFlow(_:)`, `setMenstrualEvents(_:)`, `setHealthObservations(_:)` | Replaces what the store holds of that kind. `setSteps` and `setStepSamples` stage the same array. |
| `setAthleteProfile(_ profile: AthleteProfile?)`                                                                                                                                                                                                                                                                                                       | Stages the characteristics. `nil` is a store with no such notion.                                 |
| `stagePages(_ pages: [HealthChanges])`                                                                                                                                                                                                                                                                                                                | Returns these pages, in order, from the next anchored reads.                                      |
| `failNextRead(with error: TerraError)`                                                                                                                                                                                                                                                                                                                | Fails the next read.                                                                              |
| `failEveryRead(with error: TerraError?)`                                                                                                                                                                                                                                                                                                              | Fails every read until cleared with `nil`.                                                        |
| `failNextIntensityRead(with error: TerraError)`                                                                                                                                                                                                                                                                                                       | Fails the next workout intensity read.                                                            |
| `refuseIntensityKind(_ kind: WorkoutIntensitySample.Kind)`                                                                                                                                                                                                                                                                                            | Refuses one intensity kind for good.                                                              |
| `failNextPermissionRequest(with error: TerraError)`                                                                                                                                                                                                                                                                                                   | Fails the next permission request.                                                                |
| `requestAccessCalls: [HealthAccess]`                                                                                                                                                                                                                                                                                                                  | Every permission request, as asked.                                                               |
| `writesNamedOnLastSheet() -> Set<DataCategory>`                                                                                                                                                                                                                                                                                                       | The write categories on the last sheet.                                                           |
| `windowsRead(_ read: WindowedRead) -> [DateInterval]`                                                                                                                                                                                                                                                                                                 | The windows a kind of read was asked for.                                                         |
| `attachmentsAsked: [Bool]`                                                                                                                                                                                                                                                                                                                            | The `attachingContents` value of each anchored read.                                              |
| `loggedSource` (static)                                                                                                                                                                                                                                                                                                                               | The `SampleSource` a logged sample comes back with: `"This app"`, `"com.tryterra.testkit"`.       |

`WindowedRead` is a nested `String` enum naming the windowed reads.

### WorkoutAttachment

The parts of a workout a store authorizes separately from the workout itself.

```swift
public enum WorkoutAttachment: Sendable, Hashable
```

| Case                       | Description                         |
| -------------------------- | ----------------------------------- |
| `energy`                   | The workout's energy.               |
| `distance(DistanceMedium)` | The workout's distance, per medium. |

### DistanceMedium

The kinds of movement a store files a distance under.

```swift
public enum DistanceMedium: Sendable, Hashable
```

| Case       | Description          |
| ---------- | -------------------- |
| `foot`     | Walking and running. |
| `cycling`  | Cycling.             |
| `swimming` | Swimming.            |

### InMemoryDeviceStore

A `DeviceStore` backed by memory, standing in for the Keychain and user defaults.

```swift
public final class InMemoryDeviceStore: DeviceStore, @unchecked Sendable

public init(
    connections: [Source: StoredConnection] = [:],
    requested: HealthAccess = HealthAccess(),
    providerUserID: String? = nil,
    activeDevID: String? = nil,
    storageDomain: String = UUID().uuidString,
    accessRecord: AccessRecord? = nil
)
```

Two stores with the same `storageDomain` share one state, as two `KeychainDeviceStore`s do. The default domain is unique per instance. Seeded `connections` spend their generations, so the next link opens a new one.

| Member                                                           | Description                                                                   |
| ---------------------------------------------------------------- | ----------------------------------------------------------------------------- |
| `failEverything(with error: TerraError?)`                        | Makes every call throw, for example `.storeLocked`, until cleared with `nil`. |
| `failNextBackfillReads(_ count: Int, with error: TerraError)`    | Fails the next `count` backfill queue reads.                                  |
| `failNextBackfillWrites(_ count: Int, with error: TerraError)`   | Fails the next `count` backfill queue writes.                                 |
| `failNextBackfillRemovals(_ count: Int, with error: TerraError)` | Fails the next `count` backfill queue removals.                               |

### AccessRecord

A shareable record of requested access, so two `InMemoryDeviceStore`s can share one app-wide authorization record.

```swift
public final class AccessRecord: @unchecked Sendable

public init(_ requested: HealthAccess = HealthAccess())
```

### InMemoryDeviceKeyStore

A `DeviceKeyStore` that holds software P-256 keys in memory.

```swift
public final class InMemoryDeviceKeyStore: DeviceKeyStore, @unchecked Sendable

public init(failure: TerraError? = nil)
```

Signing matches the shipped store: the same curve, hash and DER encoding. Pass `failure` to make every operation throw.

| Member                                                | Description                                                         |
| ----------------------------------------------------- | ------------------------------------------------------------------- |
| `hasKey(for source: Source, generation: Int) -> Bool` | Whether a key is held, so a test can prove disconnect destroyed it. |
| `keyCount(for source: Source) -> Int`                 | Keys held at any generation for this source.                        |
