> 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/android-sdk-2.md).

# Android SDK

Every public type and member of terra-android, the Android SDK, and its Samsung and test kit artifacts: signatures, parameters, return values and errors.

This is the reference for `terra-android` 2.x, whose Kotlin package is `co.tryterra.sdk`, with the `terra-android-samsung` add-on and `terra-android-testkit`. For setup and a walkthrough, read the [Android SDK guide](https://docs.tryterra.co/mobile-sdks/android-sdk-2). Calls that do I/O are `suspend` functions, and every call that can fail throws a [`TerraError`](#terraerror).

## Setup

### Terra

The Terra client. You build one in `Application.onCreate` and keep it for the life of the process.

```kotlin
public class Terra
```

`Terra` is a value you construct, not a singleton. Every client in an app shares one stored state, which belongs to the first dev ID that runs against it, so an app uses one dev ID. The namespaces on `Terra` (`permissions`, `diagnostics`, `body`, `nutrition`, `menstruation`, `daily`, `sleep`, `activity`) are bound to `Source.HEALTH`. `menstruation` is available in 2.2.1 and later. To reach the Samsung store, use [`Terra.on`](#terra.on).

```kotlin
val terra = Terra(context, devId = "your-dev-id", tokenProvider = { yourBackend.terraToken() })
val launcher = terra.permissions.launcher(activity) // in onCreate, before the activity is STARTED
terra.connect(Source.HEALTH, EndUser.Reference(user.id))
terra.permissions.request(read = setOf(DataCategory.DAILY), launcher = launcher)
BackgroundSync.register(context, terra)
```

**Seam constructor.** Builds a client from collaborators you supply instead of the production adapters.

```kotlin
@TerraSeam
public constructor(
    devId: String,
    registry: StoreRegistry,
    backend: TerraBackend,
    store: DeviceStore,
    keys: DeviceKeyStore,
    installIdentity: InstallIdentity,
    appIdentifier: String,
    tokenProvider: (suspend () -> String)? = null,
    oemBackgroundRestricted: suspend () -> Boolean = { false },
    backgroundWorkScheduled: suspend () -> Boolean? = { null },
    work: CoroutineDispatcher = Dispatchers.Default,
    deviceZone: ZoneId = ZoneId.systemDefault(),
    now: () -> Instant = Instant::now,
    syncsAutomatically: Boolean = false,
    dayTotals: DayTotalPolicy = DayTotalPolicy(),
    devIdMode: DevIdMode = DevIdMode.SINGLE,
)
```

Requires opt-in to [`@TerraSeam`](#terraseam). It exists so tests can drive a whole client against fakes on a plain JVM; see the test kit. `registry`, `backend`, `store`, `keys` and `installIdentity` are the extension-point types ([`StoreRegistry`](#storeregistry), [`TerraBackend`](#terrabackend), [`DeviceStore`](#devicestore), [`DeviceKeyStore`](#devicekeystore), [`InstallIdentity`](#installidentity)). A client built this way does not start sync runs on its own.

#### Terra.invoke

Builds the production client. At the call site it reads `Terra(context, ...)`.

```kotlin
public operator fun invoke(
    context: Context,
    devId: String,
    tokenProvider: (suspend () -> String)? = null,
    dayTotals: DayTotalPolicy = DayTotalPolicy(),
    devIdMode: DevIdMode = DevIdMode.SINGLE,
    stores: StoreRegistration.() -> Unit = {},
): Terra
```

| Name            | Type                                | Description                                                                                                                                                                                                                                                                                               |
| --------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `context`       | `Context`                           | Any context. Health Connect, the Keystore, the encrypted store and WorkManager all need one.                                                                                                                                                                                                              |
| `devId`         | `String`                            | Your developer ID. Configuration, not a credential.                                                                                                                                                                                                                                                       |
| `tokenProvider` | `(suspend () -> String)?`           | A function that returns a one-time auth token minted by your backend. The SDK calls it only when `connect` has to create a new link. A restored launch never calls it. Optional. Defaults to `null`: pass the token to [`connect(source, forUser, token)`](#terra.connect) instead.                       |
| `dayTotals`     | [`DayTotalPolicy`](#daytotalpolicy) | What the uploaded day totals and `daily.steps` count. Applies to the Health Connect store. Optional. Defaults to `DayTotalPolicy()`, Health Connect's own aggregate of everything.                                                                                                                        |
| `devIdMode`     | [`DevIdMode`](#devidmode)           | `SINGLE` for every integration except a connector app that several Terra customers link the same person through, which passes `MULTIPLE` and links each customer with [`linkedDevIds`](#terra.linkeddevids) instead of `connect`. Optional. Defaults to `DevIdMode.SINGLE`. Available in 2.3.0 and later. |
| `stores`        | `StoreRegistration.() -> Unit`      | A block that registers optional stores, such as `samsungHealth()` from the Samsung add-on. Health Connect is always registered. Optional. Defaults to an empty block.                                                                                                                                     |

**Returns:** a new `Terra` client.

{% hint style="warning" %}
Name the `tokenProvider` argument. The last parameter is `stores`, so a trailing lambda binds there, and the client ends up with no token provider.
{% endhint %}

```kotlin
terra = Terra(
    this,
    devId = BuildConfig.TERRA_DEV_ID,
    tokenProvider = { yourBackend.mintTerraToken() },
) {
    samsungHealth()
}
```

#### Terra.against

Builds the same client as [`Terra.invoke`](#terra.invoke), against `baseUrl` instead of the production API.

```kotlin
@TerraSeam
public fun against(
    context: Context,
    devId: String,
    baseUrl: String,
    tokenProvider: (suspend () -> String)? = null,
    dayTotals: DayTotalPolicy = DayTotalPolicy(),
    devIdMode: DevIdMode = DevIdMode.SINGLE,
    stores: StoreRegistration.() -> Unit = {},
): Terra
```

| Name             | Type     | Description                                                                    |
| ---------------- | -------- | ------------------------------------------------------------------------------ |
| `baseUrl`        | `String` | The Terra API base URL to reach, for example a stack on a developer's machine. |
| other parameters |          | As on [`Terra.invoke`](#terra.invoke).                                         |

**Returns:** a new `Terra` client.

Requires opt-in to [`@TerraSeam`](#terraseam). It is for development builds only: a production app never retargets the API.

#### Terra.DEFAULT\_STORAGE\_DOMAIN

The storage domain every client keeps its state under.

```kotlin
public const val DEFAULT_STORAGE_DOMAIN: String = AndroidDeviceStore.DEFAULT_STORAGE_DOMAIN
```

#### Terra.PRODUCTION\_BASE\_URL

The Terra API base URL the production client talks to.

```kotlin
public const val PRODUCTION_BASE_URL: String = "https://api.tryterra.co"
```

#### Terra.MAX\_APP\_IDENTIFIER\_LENGTH

The longest app identifier the link route accepts.

```kotlin
public const val MAX_APP_IDENTIFIER_LENGTH: Int = 255
```

#### Terra.appIdentifier

Returns what this installation presents as the app when it links: the package name and the storage domain.

```kotlin
@TerraSeam
public fun appIdentifier(packageName: String?, storageDomain: String): String
```

| Name            | Type      | Description                                                                                     |
| --------------- | --------- | ----------------------------------------------------------------------------------------------- |
| `packageName`   | `String?` | The app's package name. `null` is sent as `unknown`.                                            |
| `storageDomain` | `String`  | The storage domain, [`DEFAULT_STORAGE_DOMAIN`](#terra.default_storage_domain) for every client. |

**Returns:** `"<packageName>/<storageDomain>"`, or its SHA-256 in hex when that is longer than [`MAX_APP_IDENTIFIER_LENGTH`](#terra.max_app_identifier_length).

The SDK computes this for you. It separates two of your apps signed with one key. Requires opt-in to [`@TerraSeam`](#terraseam).

### StoreRegistration

The receiver of the `stores` block on [`Terra.invoke`](#terra.invoke), where a build registers stores beyond Health Connect.

```kotlin
public class StoreRegistration internal constructor(
    public val context: Context,
    public val zone: ZoneId,
)
```

Add-on artifacts extend it. The Samsung add-on declares `samsungHealth()` as an extension on this type.

| Property  | Type      | Description                                                                                                                    |
| --------- | --------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `context` | `Context` | The context passed to `Terra(...)`, for a store that needs one.                                                                |
| `zone`    | `ZoneId`  | The client's local-day time zone, read once when the client is built. A store uses it to decide which day a record belongs to. |

#### StoreRegistration.register

Registers a store under its own source, replacing any earlier registration for that source.

```kotlin
public fun register(store: HealthStore)
```

| Name    | Type                          | Description            |
| ------- | ----------------------------- | ---------------------- |
| `store` | [`HealthStore`](#healthstore) | The store to register. |

#### StoreRegistration.has

Returns whether a store has been registered for a source.

```kotlin
public fun has(source: Source): Boolean
```

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

**Returns:** `true` when a store is registered for `source`.

#### StoreRegistration.claimHealthConnectOrigin

Tells Health Connect to leave out the records that another registered store already uploads.

```kotlin
@TerraSeam
public fun claimHealthConnectOrigin(
    packageName: String,
    source: Source,
    reported: suspend (requested: Set<DataCategory>) -> Set<HealthConnectRecordType>,
)
```

| Name          | Type                                                          | Description                                                                                                                                               |
| ------------- | ------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `packageName` | `String`                                                      | The package Health Connect files the other store's records under.                                                                                         |
| `source`      | [`Source`](#source)                                           | The source whose store uploads those records. Must already be registered.                                                                                 |
| `reported`    | `suspend (Set<DataCategory>) -> Set<HealthConnectRecordType>` | A function that returns the [`HealthConnectRecordType`](#healthconnectrecordtype)s the other store would upload right now for the categories asked of it. |

Requires opt-in to [`@TerraSeam`](#terraseam). It is the Samsung add-on's part of the de-duplication rule described in [Samsung Health](https://docs.tryterra.co/mobile-sdks/samsung-health), not a call for your app. Health Connect excludes nothing while `source` has no active link, for a type `reported` leaves out, or when `reported` throws. Day totals are never filtered.

### SourceScope

Everything a client offers for one source.

```kotlin
public interface SourceScope
```

[`Terra.on`](#terra.on) returns one. `terra.body` and the other shorthands on `Terra` are `on(Source.HEALTH)`.

| Property       | Type                                          | Description                                                    |
| -------------- | --------------------------------------------- | -------------------------------------------------------------- |
| `permissions`  | [`Permissions`](#permissions)                 | Requests and reports access for this source.                   |
| `diagnostics`  | [`Diagnostics`](#diagnostics)                 | Reports why data is or is not arriving for this source.        |
| `body`         | [`BodyMetrics`](#bodymetrics)                 | Heart rate and body vitals.                                    |
| `nutrition`    | [`NutritionMetrics`](#nutritionmetrics)       | Meals and intake.                                              |
| `menstruation` | [`MenstruationMetrics`](#menstruationmetrics) | Menstrual flow and cycle events. Available in 2.2.1 and later. |
| `daily`        | [`DailyMetrics`](#dailymetrics)               | Steps and day totals.                                          |
| `sleep`        | [`SleepMetrics`](#sleepmetrics)               | Sleep stages.                                                  |
| `activity`     | [`ActivityMetrics`](#activitymetrics)         | Workouts, their routes and their intensity readings.           |

### TerraSeam

Marks the parts of the SDK that take its collaborators directly instead of building them.

```kotlin
@RequiresOptIn(
    message = "The seam takes the SDK's collaborators and store parts directly. Customers use Terra(context, devId, ...).",
    level = RequiresOptIn.Level.ERROR,
)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CONSTRUCTOR, AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
public annotation class TerraSeam
```

Using a member marked with it without `@OptIn(TerraSeam::class)` is a compile error. It marks the `Terra` constructor, [`Terra.against`](#terra.against), and the parts a store add-on shares with Health Connect. An app built for production never needs it.

### TerraTesting

Marks the hooks that start a sync run on demand.

```kotlin
@RequiresOptIn(
    message = "Syncing is automatic. This hook is for tests and harnesses that need a run on demand.",
    level = RequiresOptIn.Level.ERROR,
)
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.FUNCTION)
public annotation class TerraTesting
```

The SDK decides when to sync, so your app has no call that starts one. This marks [`Terra.syncAll`](#terra.syncall) and [`BackgroundSync.syncNow`](#backgroundsync.syncnow), which stay for tests and harnesses.

## Connecting

### EndUser

The person a `connect` is for.

```kotlin
public sealed interface EndUser {
    public data class Reference(public val id: String) : EndUser
    public data object Anonymous : EndUser
}
```

| Type            | Description                                                                               |
| --------------- | ----------------------------------------------------------------------------------------- |
| `Reference(id)` | 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.

#### Terra.connect

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

```kotlin
public suspend fun connect(source: Source, forUser: EndUser): StoredConnection

public suspend fun connect(source: Source, forUser: EndUser, token: String): StoredConnection
```

| Name      | Type                  | Description                                                                                           |
| --------- | --------------------- | ----------------------------------------------------------------------------------------------------- |
| `source`  | [`Source`](#source)   | The store to link.                                                                                    |
| `forUser` | [`EndUser`](#enduser) | The person this connection is for. Required.                                                          |
| `token`   | `String`              | A one-time auth token you already hold, for example from a QR code or a deep link. Optional overload. |

**Returns:** the [`StoredConnection`](#storedconnection) for `source`. Its `userId` is the Terra `user_id` on your webhooks.

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 `forUser`                                                                  | Restored with no network call.                                                                                               |
| Made for a different end user (another reference, or a reference versus `EndUser.Anonymous`) | The stored link is retired as [`Terra.disconnect`](#terra.disconnect) retires it, then the device links again for `forUser`. |
| Made before end users were recorded                                                          | Kept, and recorded as `forUser`'s. No network call.                                                                          |

A restore calls neither the network nor the token provider, so a normal launch works offline. With a token, the SDK always links fresh and records `forUser`: passing a token states a new or different user, so a stored connection never satisfies it.

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

| Error                              | When                                                                                                                                                                                |
| ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TerraError.TokenUnavailable`      | No token was passed and the client has no `tokenProvider`.                                                                                                                          |
| `TerraError.TokenRejected`         | The token was expired, already spent, or unknown.                                                                                                                                   |
| `TerraError.TokenProviderFailed`   | Your `tokenProvider` threw. The cause is attached.                                                                                                                                  |
| `TerraError.DevIdMismatch`         | A different dev ID owns this storage domain, or the stored connection was linked under one. Also thrown by every `connect` on a client built in [`DevIdMode.MULTIPLE`](#devidmode). |
| `TerraError.LinkAlreadyRunning`    | Another `connect` for the same source is in flight. Wait for it rather than retrying.                                                                                               |
| `TerraError.HealthDataUnavailable` | No store is registered for `source`, for example `SAMSUNG_HEALTH` without the add-on.                                                                                               |
| `TerraError.UserLimitReached`      | Your plan's user allowance is used up.                                                                                                                                              |

#### Terra.connections

Returns every source this install holds a usable link for.

```kotlin
public suspend fun connections(): List<StoredConnection>
```

**Returns:** the [`StoredConnection`](#storedconnection)s this client can use. A record linked under another dev ID is left out, and nothing is returned when another dev ID owns the stored state.

#### Terra.on

Returns the namespaces for one source, for a build that carries more than one store.

```kotlin
public fun on(source: Source): SourceScope
```

| Name     | Type                | Description                          |
| -------- | ------------------- | ------------------------------------ |
| `source` | [`Source`](#source) | The store whose namespaces you want. |

**Returns:** the [`SourceScope`](#sourcescope) for `source`.

| Error                              | When                                                                                          |
| ---------------------------------- | --------------------------------------------------------------------------------------------- |
| `TerraError.HealthDataUnavailable` | This build registered no store for `source`. The reason is `StoreAvailability.ModuleMissing`. |

```kotlin
samsungLauncher = terra.on(Source.SAMSUNG_HEALTH).permissions.launcher(this)
terra.on(Source.SAMSUNG_HEALTH).permissions.request(
    read = setOf(DataCategory.DAILY, DataCategory.SLEEP),
    launcher = samsungLauncher,
)
```

#### Terra.availability

Returns whether this device can serve a source, and if not, why. Available in 2.2.1 and later.

```kotlin
public suspend fun availability(source: Source = Source.HEALTH): StoreAvailability
```

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

**Returns:** the store's own [`StoreAvailability`](#storeavailability). `ProviderAppMissing` or `ProviderAppTooOld` means Health Connect needs installing or updating. `ModuleMissing` means `source` is `Source.SAMSUNG_HEALTH` and this build registered no Samsung store.

It needs no connection, prompts for nothing and does not throw for an unavailable store, so you can call it before `connect` to decide whether to offer the link.

```kotlin
when (val availability = terra.availability()) {
    StoreAvailability.Available -> showConnectButton()
    StoreAvailability.ProviderAppMissing, is StoreAvailability.ProviderAppTooOld -> showInstallHealthConnect()
    else -> hideHealthFeatures()
}
```

#### Terra.syncAll

Runs one sync now, in the foreground: every route the store serves, then the windows Terra asked for, then a poll for new ones.

```kotlin
@TerraTesting
public suspend fun syncAll(
    source: Source = Source.HEALTH,
    backfillDays: Int = Core.FIRST_SYNC_DAYS,
): RunOutcome
```

| Name           | Type                | Description                                                                                           |
| -------------- | ------------------- | ----------------------------------------------------------------------------------------------------- |
| `source`       | [`Source`](#source) | The source to sync. Optional. Defaults to `Source.HEALTH`.                                            |
| `backfillDays` | `Int`               | How many days back a first sync reaches. Optional. Defaults to the SDK's first-sync reach (730 days). |

**Returns:** a [`RunOutcome`](#runoutcome). Ordinary failures are counted into it rather than thrown.

Requires opt-in to [`@TerraTesting`](#terratesting). Syncing is automatic, and every automatic trigger runs this same body. Use it only in tests and harnesses.

### Source

The store a connection reads from.

```kotlin
public enum class Source(
    public val resource: String,
)
```

| Case             | Description                                                                                                                                                                                       |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `HEALTH`         | Health Connect. `resource` is `"health_connect"`.                                                                                                                                                 |
| `SAMSUNG_HEALTH` | Samsung Health, read directly through the `terra-android-samsung` add-on. `resource` is `"samsung"`. Without the add-on, using it throws `TerraError.HealthDataUnavailable` with `ModuleMissing`. |

| Property   | Type     | Description                                                                      |
| ---------- | -------- | -------------------------------------------------------------------------------- |
| `resource` | `String` | Terra's name for the store behind this source, as it appears in signed requests. |

### Linker

Establishes, restores and ends links on behalf of `Terra`.

```kotlin
public class Linker internal constructor(...)
```

Its constructor is internal, and no public member of `Terra` returns one. Use [`Terra.connect`](#terra.connect), [`Terra.connections`](#terra.connections) and [`Terra.disconnect`](#terra.disconnect). Its public members are the same operations:

```kotlin
public suspend fun connect(source: Source, forUser: EndUser): StoredConnection
public suspend fun connect(source: Source, forUser: EndUser, token: String): StoredConnection
public suspend fun connections(): List<StoredConnection>
public suspend fun disconnect(source: Source)
public suspend fun retryPendingRevocations(source: Source)
```

`retryPendingRevocations` sends the key revocations Terra is still owed for links this device already ended. It never throws.

### DevIdMode

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

```kotlin
public enum class DevIdMode
```

| Case       | Description                                                                                                                                                                                                                                                                                            |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `SINGLE`   | The default for every integration. The first dev ID to run owns the storage domain, and any other dev ID is refused with `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, and Terra delivers each customer only the data types that customer selected. |

You choose the mode when you build the client, with the `devIdMode` parameter of [`Terra.invoke`](#terra.invoke). The mode is recorded with the storage domain's owner, so a single-mode client over a multiple-mode domain, and the reverse, are refused with `TerraError.DevIdMismatch`. In `MULTIPLE` mode, [`Terra.connect`](#terra.connect) is refused with `TerraError.DevIdMismatch`: link each customer with [`linkedDevIds`](#terra.linkeddevids). React Native and Flutter apps choose the mode with the `co.tryterra.sdk.DEV_ID_MODE` manifest meta-data, set to `multiple`.

#### Terra.devIdMode

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

```kotlin
public val devIdMode: DevIdMode
```

#### Terra.linkedDevIds

The customers linked to this installation, in `DevIdMode.MULTIPLE`. Available in 2.3.0 and later.

```kotlin
public val linkedDevIds: LinkedDevIds
```

### LinkedDevIds

Links, unlinks and lists the customers one installation serves in `DevIdMode.MULTIPLE`. Every call throws `TerraError.DevIdMismatch` on a client built in `DevIdMode.SINGLE`. Available in 2.3.0 and later.

```kotlin
public class LinkedDevIds internal constructor(...)
```

#### LinkedDevIds.link

Links `devId`'s connection to this installation, with a link token that customer's backend minted.

```kotlin
public suspend fun link(devId: String, token: String, source: Source = Source.HEALTH): DevIdBinding
```

| Name     | Type                | Description                                                |
| -------- | ------------------- | ---------------------------------------------------------- |
| `devId`  | `String`            | The customer's developer ID.                               |
| `token`  | `String`            | A link token that customer's backend minted.               |
| `source` | [`Source`](#source) | The source to link. Optional. Defaults to `Source.HEALTH`. |

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

The first customer links the installation. Every later customer joins the same link, so the installation still reads once and uploads once, and the later customer is sent the history the others already received. Linking a dev ID that is already linked replaces its binding. A permanent refusal from Terra throws [`TerraError.LinkRefused`](#terraerror).

#### LinkedDevIds.unlink

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

```kotlin
public suspend fun unlink(devId: String, source: Source = Source.HEALTH)
```

When no other customer is active, the unlink disconnects the installation. It succeeds when `devId` is not linked, and when Terra cannot be reached: the SDK retries the removal until Terra answers.

#### LinkedDevIds.all

Returns the customers linked now, in the order they linked.

```kotlin
public suspend fun all(source: Source = Source.HEALTH, refresh: Boolean = false): List<DevIdBinding>
```

| Name      | Type                | Description                                                                                                                                                            |
| --------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`  | [`Source`](#source) | The source to list. Optional. Defaults to `Source.HEALTH`.                                                                                                             |
| `refresh` | `Boolean`           | Ask Terra first, so a customer that removed its connection since the last answer reads as inactive at once rather than at the next run. Optional. Defaults to `false`. |

**Returns:** one [`DevIdBinding`](#devidbinding) per linked customer.

### DevIdBinding

One customer's connection to this installation's shared link, in `DevIdMode.MULTIPLE`. Available in 2.3.0 and later.

```kotlin
public data class DevIdBinding(
    public val devId: String,
    public val userId: String,
    public val dataTypes: List<UploadDataType>?,
    public val linkedAt: Instant,
    public val unlinkOwedSince: Instant? = null,
    public val goneSince: Instant? = null,
    public val absences: Int = 0,
)
```

| Property          | Type                    | Description                                                                                                                       |
| ----------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| `devId`           | `String`                | The customer's developer ID.                                                                                                      |
| `userId`          | `String`                | Terra's ID for this customer's connection: the `user_id` on that customer's webhooks.                                             |
| `dataTypes`       | `List<UploadDataType>?` | The routes this customer selected, as Terra answered at link, or `null` when it did not say.                                      |
| `linkedAt`        | `Instant`               | When the binding was made.                                                                                                        |
| `unlinkOwedSince` | `Instant?`              | Set when `unlink` could not reach Terra. The binding no longer counts, and the SDK retries the removal.                           |
| `goneSince`       | `Instant?`              | Set when Terra has answered twice in a row without this connection. The binding stays listed, but nothing is read or sent for it. |
| `absences`        | `Int`                   | Terra answers in a row that left this connection out.                                                                             |
| `isLive`          | `Boolean`               | `true` while no unlink is owed.                                                                                                   |
| `isActive`        | `Boolean`               | `true` while live and not gone: Terra still delivers to this customer.                                                            |

## Requesting permissions

### DataCategory

A category of health data, as you name it when you ask for access.

```kotlin
public enum class DataCategory
```

| Case           | Description                           |
| -------------- | ------------------------------------- |
| `ACTIVITY`     | Workouts.                             |
| `BODY`         | Body measurements and vitals.         |
| `DAILY`        | Steps and day totals, and heart rate. |
| `SLEEP`        | Sleep stages.                         |
| `NUTRITION`    | Meals and hydration.                  |
| `MENSTRUATION` | Menstrual flow and cycle events.      |

Android has six categories against iOS's eight. `athlete` and `healthObservation` have no Health Connect record; see [`UnmappedCategory`](#unmappedcategory).

### PermissionStatus

What the platform says about one permission.

```kotlin
public enum class PermissionStatus
```

| Case             | Description                                                                                                |
| ---------------- | ---------------------------------------------------------------------------------------------------------- |
| `GRANTED`        | Granted. A category is granted only when every record type behind it is granted.                           |
| `DENIED`         | Asked for and refused. Only a trip to Settings changes it.                                                 |
| `NOT_DETERMINED` | Never asked for. Call `permissions.request`.                                                               |
| `NOT_DISCLOSED`  | Never returned on Android, which discloses read grants. Kept so code shared with iOS handles the same set. |
| `UNSUPPORTED`    | The device or store cannot provide it, so prompting does not help.                                         |

### HealthDataType

One kind of health data, at the granularity a permission request can ask for it: the type-level twin of [`DataCategory`](#datacategory). Pass these as `readTypes` to [`Permissions.request`](#permissions.request) to ask for exactly the types your consent screen names. Available in 2.3.0 and later.

```kotlin
public enum class HealthDataType(public val wire: String)
```

| Case                                                     | `wire`                                               | Health Connect records and permissions                                                                                                                                                                  |
| -------------------------------------------------------- | ---------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `STEPS`                                                  | `steps`                                              | `StepsRecord` (and step cadence), `READ_STEPS`.                                                                                                                                                         |
| `ACTIVE_ENERGY`                                          | `activeEnergy`                                       | `ActiveCaloriesBurnedRecord`, `READ_ACTIVE_CALORIES_BURNED`.                                                                                                                                            |
| `BASAL_ENERGY`                                           | `basalEnergy`                                        | `BasalMetabolicRateRecord`, `READ_BASAL_METABOLIC_RATE`.                                                                                                                                                |
| `DISTANCE`                                               | `distance`                                           | `DistanceRecord`, `READ_DISTANCE`.                                                                                                                                                                      |
| `FLOORS_CLIMBED`                                         | `floorsClimbed`                                      | `FloorsClimbedRecord`, `READ_FLOORS_CLIMBED`.                                                                                                                                                           |
| `HEART_RATE`                                             | `heartRate`                                          | `HeartRateRecord`, `READ_HEART_RATE`.                                                                                                                                                                   |
| `RESTING_HEART_RATE`                                     | `restingHeartRate`                                   | `RestingHeartRateRecord`, `READ_RESTING_HEART_RATE`.                                                                                                                                                    |
| `SLEEP_ANALYSIS`                                         | `sleepAnalysis`                                      | `SleepSessionRecord`, `READ_SLEEP`.                                                                                                                                                                     |
| `WORKOUTS`                                               | `workouts`                                           | `ExerciseSessionRecord` and `ElevationGainedRecord`, `READ_EXERCISE` and `READ_ELEVATION_GAINED`. Granted by `READ_EXERCISE` alone.                                                                     |
| `WORKOUT_ROUTE`                                          | `workoutRoute`                                       | The session's route, under `READ_EXERCISE_ROUTES`, which Health Connect asks per session. Needs `WORKOUTS`.                                                                                             |
| `SPEED`                                                  | `speed`                                              | `SpeedRecord`, `READ_SPEED`. Needs `WORKOUTS`.                                                                                                                                                          |
| `POWER`                                                  | `power`                                              | `PowerRecord`, `READ_POWER`. Needs `WORKOUTS`.                                                                                                                                                          |
| `CYCLING_CADENCE`                                        | `cyclingCadence`                                     | `CyclingPedalingCadenceRecord`, `READ_EXERCISE`. Needs `WORKOUTS`.                                                                                                                                      |
| `WEIGHT`                                                 | `weight`                                             | `WeightRecord`, `READ_WEIGHT`.                                                                                                                                                                          |
| `HEIGHT`                                                 | `height`                                             | `HeightRecord`, `READ_HEIGHT`.                                                                                                                                                                          |
| `BODY_FAT`                                               | `bodyFat`                                            | `BodyFatRecord`, `READ_BODY_FAT`.                                                                                                                                                                       |
| `LEAN_BODY_MASS`                                         | `leanBodyMass`                                       | `LeanBodyMassRecord`, `READ_LEAN_BODY_MASS`.                                                                                                                                                            |
| `BONE_MASS`                                              | `boneMass`                                           | `BoneMassRecord`, `READ_BONE_MASS`.                                                                                                                                                                     |
| `BODY_WATER_MASS`                                        | `bodyWaterMass`                                      | `BodyWaterMassRecord`, `READ_BODY_WATER_MASS`.                                                                                                                                                          |
| `BLOOD_PRESSURE`                                         | `bloodPressure`                                      | `BloodPressureRecord`, `READ_BLOOD_PRESSURE`.                                                                                                                                                           |
| `BLOOD_GLUCOSE`                                          | `bloodGlucose`                                       | `BloodGlucoseRecord`, `READ_BLOOD_GLUCOSE`.                                                                                                                                                             |
| `OXYGEN_SATURATION`                                      | `oxygenSaturation`                                   | `OxygenSaturationRecord`, `READ_OXYGEN_SATURATION`.                                                                                                                                                     |
| `BODY_TEMPERATURE`                                       | `bodyTemperature`                                    | `BodyTemperatureRecord`, `BasalBodyTemperatureRecord` and `SkinTemperatureRecord`, `READ_BODY_TEMPERATURE`, `READ_BASAL_BODY_TEMPERATURE` and `READ_SKIN_TEMPERATURE`. Granted once any one of them is. |
| `HEART_RATE_VARIABILITY`                                 | `heartRateVariability`                               | `HeartRateVariabilityRmssdRecord`, `READ_HEART_RATE_VARIABILITY`.                                                                                                                                       |
| `RESPIRATORY_RATE`                                       | `respiratoryRate`                                    | `RespiratoryRateRecord`, `READ_RESPIRATORY_RATE`.                                                                                                                                                       |
| `VO2_MAX`                                                | `vo2Max`                                             | `Vo2MaxRecord`, `READ_VO2_MAX`.                                                                                                                                                                         |
| `DIETARY_ENERGY_CONSUMED` ... `DIETARY_PANTOTHENIC_ACID` | `dietaryEnergyConsumed` ... `dietaryPantothenicAcid` | One per [`Nutrient`](#nutrient). `NutritionRecord`, `READ_NUTRITION`. The SDK keeps only the requested nutrients of each meal.                                                                          |
| `DIETARY_WATER`                                          | `dietaryWater`                                       | `HydrationRecord`, `READ_HYDRATION`.                                                                                                                                                                    |
| `MENSTRUAL_FLOW`                                         | `menstrualFlow`                                      | `MenstruationFlowRecord` and `MenstruationPeriodRecord`, `READ_MENSTRUATION`.                                                                                                                           |
| `INTERMENSTRUAL_BLEEDING`                                | `intermenstrualBleeding`                             | `IntermenstrualBleedingRecord`, `READ_INTERMENSTRUAL_BLEEDING`.                                                                                                                                         |
| `OVULATION_TEST`                                         | `ovulationTest`                                      | `OvulationTestRecord`, `READ_OVULATION_TEST`.                                                                                                                                                           |
| `CERVICAL_MUCUS`                                         | `cervicalMucus`                                      | `CervicalMucusRecord`, `READ_CERVICAL_MUCUS`.                                                                                                                                                           |
| `SEXUAL_ACTIVITY`                                        | `sexualActivity`                                     | `SexualActivityRecord`, `READ_SEXUAL_ACTIVITY`.                                                                                                                                                         |

Only the types Health Connect can serve are here. Apple's ring minutes, BMI, waist circumference, insulin, ECG, heartbeat series, swimming strokes, the other cycle events and the athlete characteristics have no Health Connect record. Samsung Health is asked by category only.

| Member     | Type        | Description                                                                                                                   |
| ---------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `wire`     | `String`    | The name shared with the iOS SDK and the React Native and Flutter wrappers. It is also stored in the requested-access record. |
| `nutrient` | `Nutrient?` | The nutrient a dietary type reads, or `null` for every other type, `DIETARY_WATER` included.                                  |

#### HealthDataType.fromWire

Returns the type named `wire`, or `null` for a name this build does not know.

```kotlin
public fun fromWire(wire: String): HealthDataType?
```

#### HealthDataType.of

Returns the dietary type behind a nutrient.

```kotlin
public fun of(nutrient: Nutrient): HealthDataType
```

### WorkoutScope

One workout shape your app intends to log, and what it attaches to it.

```kotlin
public data class WorkoutScope(
    public val activity: WorkoutActivity,
    public val energy: Boolean = false,
    public val distance: Boolean = false,
)
```

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

A workout's energy and distance are separate Health Connect records with their own grants. `write = setOf(DataCategory.ACTIVITY)` asks for the exercise session, active calories and distance. To ask for fewer, leave `ACTIVITY` out of `write` and pass scopes in `workouts`: each one asks for the session plus only the attachments it names.

### Permissions

Requests access and reports what was granted, for one source.

```kotlin
public class Permissions internal constructor(...)
```

You reach it through `terra.permissions` or `terra.on(source).permissions`. Every request presents the running union of everything this install has ever asked for, never just what you pass, so a later, narrower request cannot lose a category.

#### Permissions.launcher

Registers the permission sheet with a screen, for `request` to present through later.

```kotlin
public fun launcher(host: ActivityResultCaller): PermissionLauncher
```

| Name   | Type                   | Description                                                                  |
| ------ | ---------------------- | ---------------------------------------------------------------------------- |
| `host` | `ActivityResultCaller` | The `ComponentActivity`, or a `Fragment` from its own `onCreate` or earlier. |

**Returns:** a [`PermissionLauncher`](#permissionlauncher) to pass to [`request`](#permissions.request). Keep it for the screen's lifetime.

| Error                 | When                                                                                                                                        |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `TerraError.Platform` | It was called after the activity started, wrapping an `IllegalStateException`. Android refuses the registration once the host is `STARTED`. |

{% hint style="warning" %}
Call it from `onCreate`, before anything that suspends, `connect` included. Nothing in it suspends, so it can sit in a field initialiser.
{% endhint %}

#### Permissions.request

Presents one Health Connect sheet for reads, writes and workout scopes, plus everything asked for before, and returns what was granted.

```kotlin
public suspend fun request(
    read: Set<DataCategory> = emptySet(),
    write: Set<DataCategory> = emptySet(),
    workouts: Set<WorkoutScope> = emptySet(),
    launcher: PermissionLauncher,
    readTypes: Set<HealthDataType> = emptySet(),
): HealthAccess
```

| Name        | Type                                        | Description                                                                                                                                                                                                                                         |
| ----------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `read`      | `Set<DataCategory>`                         | The categories to read. Optional. Defaults to none.                                                                                                                                                                                                 |
| `write`     | `Set<DataCategory>`                         | The categories to write. Optional. Defaults to none.                                                                                                                                                                                                |
| `workouts`  | `Set<WorkoutScope>`                         | The workout shapes you log, for an app that asks for less than the whole `ACTIVITY` category: the session, plus energy and distance only when a scope names them. Optional. Defaults to none. `write = setOf(ACTIVITY)` already covers every scope. |
| `launcher`  | [`PermissionLauncher`](#permissionlauncher) | The launcher [`launcher`](#permissions.launcher) returned for this source.                                                                                                                                                                          |
| `readTypes` | `Set<HealthDataType>`                       | Individual [`HealthDataType`](#healthdatatype)s to read, for an app that asks for less than a whole category. Health Connect only. Optional. Defaults to none. Available in 2.3.0 and later.                                                        |

**Returns:** a [`HealthAccess`](#healthaccess) with what is granted, narrowed to what this call asked for. Its `readTypes` holds the requested types with at least one permission granted, and is empty for a request that named none.

The union is recorded before the sheet appears, so a process killed while the sheet is up has still asked. When the request asks to read anything, the sheet also asks for background read and history read, if your manifest declares them. A request that newly grants an upload route starts a sync run.

Once any type is recorded, the install is type-scoped: the SDK reads and uploads only the requested types and the types of any category in `read`. A route syncs only for the requested types it carries, and counts as readable once one requested type feeding it is granted. Types join the same running union categories do. An install that never passes `readTypes` keeps the category rules. See [Request individual types](https://docs.tryterra.co/mobile-sdks/android-sdk-2#request-individual-types) in the guide.

| Error                              | When                                                                                                                                                                   |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TerraError.HealthDataUnavailable` | The store cannot serve reads at all, for example Health Connect is missing or needs an update.                                                                         |
| `TerraError.DevIdMismatch`         | A different dev ID owns this storage domain.                                                                                                                           |
| `IllegalArgumentException`         | `launcher` was made for another source, or `readTypes` is not empty on a store asked by category only, such as Samsung Health.                                         |
| `IllegalStateException`            | A sheet presented through `launcher` is still waiting for an answer, or the launcher was unregistered.                                                                 |
| `TerraError.WorkoutsRequired`      | The running union would hold `WORKOUT_ROUTE`, `SPEED`, `POWER` or `CYCLING_CADENCE` without `WORKOUTS` or the whole `ACTIVITY` category. Nothing is recorded or shown. |

#### Permissions.requested

Returns everything this install has ever asked for, which is what the next request presents.

```kotlin
public suspend fun requested(): HealthAccess
```

**Returns:** the running [`HealthAccess`](#healthaccess) record. It grows and never shrinks.

#### Permissions.status

Returns whether a category may be read.

```kotlin
public suspend fun status(category: DataCategory): PermissionStatus
```

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

**Returns:** `GRANTED` only when every record type behind the category is granted, `DENIED` when it was asked for and is not granted, `NOT_DETERMINED` when it was never asked for, and `UNSUPPORTED` when the store is unavailable. Never `NOT_DISCLOSED`.

Returns whether one type may be read. Available in 2.3.0 and later.

```kotlin
public suspend fun status(type: HealthDataType): PermissionStatus
```

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

**Returns:** `GRANTED` once **any** permission behind the type is granted, `DENIED` when it was asked for, by name or through a category, and nothing behind it is granted, `NOT_DETERMINED` when it was never asked for, and `UNSUPPORTED` when the store is unavailable or is asked by category only, such as Samsung Health. Never `NOT_DISCLOSED`.

Any rather than all, unlike a category: a person who allowed basal temperature and not skin temperature has allowed `BODY_TEMPERATURE`. `WORKOUTS` is granted by `READ_EXERCISE` alone. `READ_ELEVATION_GAINED` without it does not grant `WORKOUTS`.

#### Permissions.writeStatus

Returns whether a category may be written, with the same all-or-nothing rule as `status`.

```kotlin
public suspend fun writeStatus(category: DataCategory): PermissionStatus
```

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

**Returns:** the write [`PermissionStatus`](#permissionstatus) for `category`.

For `ACTIVITY`, the answer covers every type your app asked to write there: the session, active calories and distance after `write = setOf(ACTIVITY)`, or only the types your [`WorkoutScope`](#workoutscope)s name. It is `GRANTED` only when all of them are granted. A single [`log`](#activitymetrics.log) checks only the grants its entries use, so a run without energy can log while this says `DENIED` over a refused energy grant.

#### Permissions.backgroundReadStatus

Returns whether this install may read while it is in the background.

```kotlin
public suspend fun backgroundReadStatus(): PermissionStatus
```

**Returns:** the status of `READ_HEALTH_DATA_IN_BACKGROUND`. `UNSUPPORTED` means the device cannot do it and prompting is pointless. `DENIED` means the person said no and only Settings changes it. `NOT_DETERMINED` means `request` has not run yet.

Without it, background runs read nothing and `diagnostics.state()` reports `BackgroundRestricted(BACKGROUND_READ_DENIED)`.

#### Permissions.historyReadStatus

Returns whether this install may read data recorded more than 30 days before its first grant.

```kotlin
public suspend fun historyReadStatus(): PermissionStatus
```

**Returns:** the status of `READ_HEALTH_DATA_HISTORY`. Without it, Android 14 and above serve only the last 30 days, and a sync run stops its history at that boundary and reports it with a `HistoryReadUnavailable` event.

#### Permissions.statuses

Returns the read status of every category, in one call.

```kotlin
public suspend fun statuses(): Map<DataCategory, PermissionStatus>
```

**Returns:** a map from each [`DataCategory`](#datacategory) to its read [`PermissionStatus`](#permissionstatus), with one call to the platform rather than one per category.

### PermissionLauncher

The permission sheet, registered with one screen and ready to present.

```kotlin
public class PermissionLauncher internal constructor(
    internal val registration: AccessRegistration,
    public val source: Source,
)
```

[`Permissions.launcher`](#permissions.launcher) returns it and [`Permissions.request`](#permissions.request) takes it. `request` refuses a launcher made for another source.

| Property | Type                | Description                           |
| -------- | ------------------- | ------------------------------------- |
| `source` | [`Source`](#source) | The source whose store registered it. |

#### PermissionLauncher.unregister

Releases the registration when the screen goes away.

```kotlin
public fun unregister(): Unit
```

A launcher left registered outlives its screen and keeps its callback alive. A request still waiting on an unregistered launcher fails rather than hangs. Call it from `onDestroy`.

### HealthConnectPermissions

Health Connect permission names, and the sets each category expands to.

```kotlin
public object HealthConnectPermissions
```

Use it in a test that keeps your manifest in step with the categories you request.

#### HealthConnectPermissions.BACKGROUND\_READ

The background-read permission name.

```kotlin
public const val BACKGROUND_READ: String = "android.permission.health.READ_HEALTH_DATA_IN_BACKGROUND"
```

#### HealthConnectPermissions.HISTORY\_READ

The history-read permission name.

```kotlin
public const val HISTORY_READ: String = "android.permission.health.READ_HEALTH_DATA_HISTORY"
```

#### HealthConnectPermissions.EVERY\_FEATURE\_AVAILABLE

A feature-status function that answers "available" for every feature.

```kotlin
public val EVERY_FEATURE_AVAILABLE: (Int) -> Int = { HealthConnectFeatures.FEATURE_STATUS_AVAILABLE }
```

It is the default `featureStatus` below, so a caller with no device still gets the full set.

#### HealthConnectPermissions.readPermissions

Returns the read permissions a set of categories expands to, without duplicates.

```kotlin
@JvmOverloads
public fun readPermissions(
    categories: Set<DataCategory>,
    featureStatus: (Int) -> Int = EVERY_FEATURE_AVAILABLE,
): Set<String>
```

| Name            | Type                | Description                                                                                                                                                                                   |
| --------------- | ------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `categories`    | `Set<DataCategory>` | The categories you request.                                                                                                                                                                   |
| `featureStatus` | `(Int) -> Int`      | `HealthConnectFeatures.getFeatureStatus`, to leave out types the provider cannot serve. Optional. Defaults to [`EVERY_FEATURE_AVAILABLE`](#healthconnectpermissions.every_feature_available). |

**Returns:** the `android.permission.health.READ_*` names to declare in your manifest. `READ_EXERCISE_ROUTES` is never included; see [`READ_EXERCISE_ROUTES`](#read_exercise_routes).

#### HealthConnectPermissions.writePermissions

Returns the write permissions a set of categories expands to, over the record types each can write.

```kotlin
public fun writePermissions(categories: Set<DataCategory>): Set<String>
```

| Name         | Type                | Description               |
| ------------ | ------------------- | ------------------------- |
| `categories` | `Set<DataCategory>` | The categories you write. |

**Returns:** the `WRITE_*` permission names. For `ACTIVITY` that is `WRITE_EXERCISE`, `WRITE_ACTIVE_CALORIES_BURNED` and `WRITE_DISTANCE`.

An overload takes a whole [`HealthAccess`](#healthaccess) and adds its workout scopes' permissions, as [`workoutPermissions`](#healthconnectpermissions.workoutpermissions) returns them. It is the set a `log` is checked against as well as the set a request asks for:

```kotlin
public fun writePermissions(access: co.tryterra.sdk.health.HealthAccess): Set<String>
```

#### HealthConnectPermissions.writableRecordTypes

Returns the record types a `log` into a category can produce.

```kotlin
public fun writableRecordTypes(category: DataCategory): Set<HealthConnectRecordType>
```

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

**Returns:** the [`HealthConnectRecordType`](#healthconnectrecordtype)s: `STEPS` for `DAILY`, `SLEEP_SESSION` for `SLEEP`, `EXERCISE_SESSION`, `ACTIVE_CALORIES` and `DISTANCE` for `ACTIVITY`, `NUTRITION` and `HYDRATION` for `NUTRITION`, nine body types for `BODY`, and none for `MENSTRUATION`.

#### HealthConnectPermissions.workoutPermissions

Returns the write permissions a set of workout scopes needs.

```kotlin
public fun workoutPermissions(scopes: Set<WorkoutScope>): Set<String>
```

| Name     | Type                | Description                 |
| -------- | ------------------- | --------------------------- |
| `scopes` | `Set<WorkoutScope>` | The workout shapes you log. |

**Returns:** the exercise-session write permission, plus active calories if any scope asks for energy and distance if any asks for distance. Empty for no scopes. The activity itself does not change the set.

#### HealthConnectPermissions.grantedWorkoutScopes

Returns which of the asked-for workout scopes a set of grants supports.

```kotlin
public fun grantedWorkoutScopes(granted: Set<String>, asked: Set<WorkoutScope>): Set<WorkoutScope>
```

| Name      | Type                | Description                     |
| --------- | ------------------- | ------------------------------- |
| `granted` | `Set<String>`       | The granted permission names.   |
| `asked`   | `Set<WorkoutScope>` | The scopes that were asked for. |

**Returns:** empty without the exercise-session grant. Otherwise each asked scope, with an attachment dropped when its grant is missing.

#### HealthConnectPermissions.permissions

Returns every permission one access request asks the platform for.

```kotlin
@JvmOverloads
public fun permissions(
    access: co.tryterra.sdk.health.HealthAccess,
    featureStatus: (Int) -> Int = EVERY_FEATURE_AVAILABLE,
): Set<String>
```

| Name            | Type                            | Description                                                                     |
| --------------- | ------------------------------- | ------------------------------------------------------------------------------- |
| `access`        | [`HealthAccess`](#healthaccess) | The reads, writes and workout scopes to ask for.                                |
| `featureStatus` | `(Int) -> Int`                  | As on [`readPermissions`](#healthconnectpermissions.readpermissions). Optional. |

**Returns:** the read, write and workout permissions, plus `BACKGROUND_READ` and `HISTORY_READ` when `access` reads anything.

#### HealthConnectPermissions.grantedCategories

Returns the categories a set of grants fully covers for reading.

```kotlin
@JvmOverloads
public fun grantedCategories(
    granted: Set<String>,
    featureStatus: (Int) -> Int = EVERY_FEATURE_AVAILABLE,
): Set<DataCategory>
```

| Name            | Type           | Description                        |
| --------------- | -------------- | ---------------------------------- |
| `granted`       | `Set<String>`  | The granted permission names.      |
| `featureStatus` | `(Int) -> Int` | As on `readPermissions`. Optional. |

**Returns:** the categories whose every read permission is in `granted`. A half-granted category is not included; see `partiallyGranted`.

#### HealthConnectPermissions.grantedWriteCategories

Returns the categories a set of grants fully covers for writing.

```kotlin
public fun grantedWriteCategories(granted: Set<String>): Set<DataCategory>
```

| Name      | Type          | Description                   |
| --------- | ------------- | ----------------------------- |
| `granted` | `Set<String>` | The granted permission names. |

**Returns:** the categories whose every writable record type is granted.

#### HealthConnectPermissions.partiallyGranted

Returns the categories with some but not all of their record types granted, and what is missing.

```kotlin
@JvmOverloads
public fun partiallyGranted(
    granted: Set<String>,
    featureStatus: (Int) -> Int = EVERY_FEATURE_AVAILABLE,
): Map<DataCategory, Set<HealthConnectRecordType>>
```

| Name            | Type           | Description                        |
| --------------- | -------------- | ---------------------------------- |
| `granted`       | `Set<String>`  | The granted permission names.      |
| `featureStatus` | `(Int) -> Int` | As on `readPermissions`. Optional. |

**Returns:** a map from each partly granted category to its missing record types.

#### HealthConnectPermissions.permittedRecordTypes

Returns the record types of a category that a set of grants covers.

```kotlin
@JvmOverloads
public fun permittedRecordTypes(
    category: DataCategory,
    granted: Set<String>,
    featureStatus: (Int) -> Int = EVERY_FEATURE_AVAILABLE,
): Set<HealthConnectRecordType>
```

| Name            | Type                            | Description                        |
| --------------- | ------------------------------- | ---------------------------------- |
| `category`      | [`DataCategory`](#datacategory) | The category to check.             |
| `granted`       | `Set<String>`                   | The granted permission names.      |
| `featureStatus` | `(Int) -> Int`                  | As on `readPermissions`. Optional. |

**Returns:** the record types in `category` whose read permission is granted.

### HealthConnectTypes

Which Health Connect record types and permissions each [`HealthDataType`](#healthdatatype) asks for and reads. Available in 2.3.0 and later.

```kotlin
public object HealthConnectTypes
```

```kotlin
public fun recordTypes(type: HealthDataType): Set<HealthConnectRecordType>
public fun grantingRecordTypes(type: HealthDataType): Set<HealthConnectRecordType>
public fun categories(type: HealthDataType): Set<DataCategory>
public fun types(category: DataCategory): List<HealthDataType>
@JvmOverloads
public fun readPermissions(
    types: Set<HealthDataType>,
    featureStatus: (Int) -> Int = HealthConnectPermissions.EVERY_FEATURE_AVAILABLE,
): Set<String>
@JvmOverloads
public fun grantedTypes(
    granted: Set<String>,
    featureStatus: (Int) -> Int = HealthConnectPermissions.EVERY_FEATURE_AVAILABLE,
): Set<HealthDataType>
```

| Function              | Description                                                                                                                                                               |
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `recordTypes`         | The record types `type` reads. Empty for `WORKOUT_ROUTE`, which is read off a session.                                                                                    |
| `grantingRecordTypes` | The record types whose read permission grants `type`. The same as `recordTypes`, except that `WORKOUTS` is granted by the exercise session alone.                         |
| `categories`          | The categories whose request includes `type`. Heart rate, for example, is in `ACTIVITY`, `BODY`, `DAILY` and `SLEEP`.                                                     |
| `types`               | Every type a request for `category` reads.                                                                                                                                |
| `readPermissions`     | The read permissions a request for `types` presents. Use it in a test that keeps your manifest in step with the types you request. `READ_EXERCISE_ROUTES` is never in it. |
| `grantedTypes`        | The types with at least one permission in `granted`.                                                                                                                      |

### READ\_EXERCISE\_ROUTES

The one Health Connect read permission the SDK names and never asks for.

```kotlin
public const val READ_EXERCISE_ROUTES: String = "android.permission.health.READ_EXERCISE_ROUTES"
```

Health Connect grants it only in Settings or through its own route consent screen, so it is never in `readPermissions`. If your app holds it and requests `ACTIVITY`, routes are uploaded with workouts. In the background, routes are usually withheld unless the app also holds background read.

### UnmappedCategory

The two iOS categories Health Connect cannot answer.

```kotlin
public enum class UnmappedCategory(public val parityName: String, public val reason: String)
```

| Case                 | Description                                                                          |
| -------------------- | ------------------------------------------------------------------------------------ |
| `ATHLETE`            | iOS `athlete`. Health Connect has no record for it.                                  |
| `HEALTH_OBSERVATION` | iOS `healthObservation`. No Health Connect record type covers clinical observations. |

| Property     | Type                                    | Description                  |
| ------------ | --------------------------------------- | ---------------------------- |
| `parityName` | `String`                                | The iOS category name.       |
| `reason`     | `String`                                | Why Android cannot serve it. |
| `status`     | [`PermissionStatus`](#permissionstatus) | Always `UNSUPPORTED`.        |

## Background sync

### BackgroundSync

Schedules the SDK's sync runs with WorkManager.

```kotlin
public object BackgroundSync
```

No custom `WorkerFactory` or `Configuration.Provider` is needed.

#### BackgroundSync.register

Registers a client for scheduled sync, and asks for a run now unless the client starts its own.

```kotlin
@JvmOverloads
public fun register(
    context: Context,
    terra: Terra,
    processExit: ProcessExitPolicy = DEFAULT_PROCESS_EXIT,
): Boolean
```

| Name          | Type                                      | Description                                                                                    |
| ------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `context`     | `Context`                                 | Any context. The SDK keeps the application context.                                            |
| `terra`       | [`Terra`](#terra)                         | The client to run on each background run. Build it in `Application.onCreate`.                  |
| `processExit` | [`ProcessExitPolicy`](#processexitpolicy) | What a finished background run may do with your process. Optional. Defaults to `KEEP_PROCESS`. |

**Returns:** `false` when the client was refused and nothing was scheduled. That happens when another `Terra` instance is already registered and this one asks for stores the first cannot serve. `true` otherwise.

The schedule is a periodic run every [`PERIOD_MINUTES`](#backgroundsync.period_minutes) whenever the device has a network connection. `register` is idempotent: calling it again replaces the schedule rather than duplicating it, and on the next launch it restores a schedule the system threw away, for example after a manufacturer force-stopped the app.

{% hint style="warning" %}
Call it from `Application.onCreate`, not an activity. WorkManager starts your process for a background run with no activity in it, and a client built in a screen does not exist then. Check the return value.
{% endhint %}

#### BackgroundSync.cancel

Stops scheduled sync for a client's storage domain and forgets its clients.

```kotlin
public suspend fun cancel(context: Context, terra: Terra): Boolean
```

| Name      | Type              | Description                              |
| --------- | ----------------- | ---------------------------------------- |
| `context` | `Context`         | Any context.                             |
| `terra`   | [`Terra`](#terra) | The client that registered the schedule. |

**Returns:** `false` when `terra` did not register this schedule or does not own its storage domain. Nothing is cancelled in that case.

Use it when you tear down an integration. A disconnect does not need it: a run with no stored connection does nothing.

#### BackgroundSync.isScheduled

Returns whether WorkManager holds this app's periodic work for a storage domain.

```kotlin
public suspend fun isScheduled(context: Context, storageDomain: String): Boolean?
```

| Name            | Type      | Description                                                                          |
| --------------- | --------- | ------------------------------------------------------------------------------------ |
| `context`       | `Context` | Any context.                                                                         |
| `storageDomain` | `String`  | The storage domain, [`Terra.DEFAULT_STORAGE_DOMAIN`](#terra.default_storage_domain). |

**Returns:** `true` or `false`, or `null` when WorkManager cannot be asked, for example when it is not initialised.

#### BackgroundSync.syncNow

Asks for one run as soon as the network allows, without waiting for the next periodic run.

```kotlin
@TerraTesting
public fun syncNow(context: Context, terra: Terra): Boolean
```

| Name      | Type              | Description        |
| --------- | ----------------- | ------------------ |
| `context` | `Context`         | Any context.       |
| `terra`   | [`Terra`](#terra) | The client to run. |

**Returns:** `false` for the reason `register` returns it, and nothing is enqueued.

Requires opt-in to [`@TerraTesting`](#terratesting). A link, a permission grant and a return to the foreground each start a run on their own.

#### BackgroundSync.workName

Returns the unique WorkManager name the periodic work for a storage domain is enqueued under.

```kotlin
public fun workName(storageDomain: String): String
```

| Name            | Type     | Description                  |
| --------------- | -------- | ---------------------------- |
| `storageDomain` | `String` | The client's storage domain. |

**Returns:** `"co.tryterra.sdk.sync"` followed by a separator and the domain.

#### BackgroundSync.refreshWorkName

Returns the unique WorkManager name of the one-shot run for a storage domain.

```kotlin
public fun refreshWorkName(storageDomain: String): String
```

| Name            | Type     | Description                  |
| --------------- | -------- | ---------------------------- |
| `storageDomain` | `String` | The client's storage domain. |

**Returns:** the one-shot work name for `storageDomain`.

#### BackgroundSync.PERIOD\_MINUTES

The period of the scheduled run, which is WorkManager's minimum.

```kotlin
public const val PERIOD_MINUTES: Long = 15
```

#### BackgroundSync.RUN\_BUDGET\_SECONDS

How long a background run works before it stops and leaves the rest for the next run.

```kotlin
public const val RUN_BUDGET_SECONDS: Long = 8 * 60
```

#### BackgroundSync.DEFAULT\_PROCESS\_EXIT

The process-exit policy `register` uses when you do not pass one.

```kotlin
public val DEFAULT_PROCESS_EXIT: ProcessExitPolicy = ProcessExitPolicy.KEEP_PROCESS
```

### ProcessExitPolicy

What the SDK may do with your process once a background run has finished.

```kotlin
public enum class ProcessExitPolicy
```

| Case             | Description                                                                                                                                                                                                                                  |
| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `KEEP_PROCESS`   | Leaves the process alone. The default, because the SDK cannot see push handlers, bound services, content providers or your own jobs.                                                                                                         |
| `EXIT_WHEN_IDLE` | Ends the process after a background run when nothing else in it is doing anything: no activity has been created, nothing user-visible is running, and no other work is running. The exit happens after WorkManager records the run's result. |

Some manufacturers' battery managers freeze the process a background run leaves behind, which stops later runs. `EXIT_WHEN_IDLE` prevents that. Use it only if your process exists to sync.

### ProcessExitDecision

Why a process was left alone after a background run, or that it exited.

```kotlin
public enum class ProcessExitDecision(public val wire: String)
```

The SDK reports it on every run in a `TerraEvent.Kind.ProcessExitDecided` event.

| Case                     | Description                                                           |
| ------------------------ | --------------------------------------------------------------------- |
| `EXIT`                   | The process was ended. `wire` is `exit`.                              |
| `KEEP_POLICY_OFF`        | The policy is `KEEP_PROCESS`.                                         |
| `KEEP_ACTIVITY_CREATED`  | An activity has been created in this process.                         |
| `KEEP_USER_VISIBLE`      | Something user-visible is running, such as a foreground service.      |
| `KEEP_OTHER_WORK`        | WorkManager is running other work in this process.                    |
| `KEEP_RESULT_UNRECORDED` | WorkManager never recorded the run's result, so nothing may be ended. |
| `KEEP_EXIT_IN_FLIGHT`    | Another run in this process is already deciding.                      |

| Property | Type     | Description                                                       |
| -------- | -------- | ----------------------------------------------------------------- |
| `wire`   | `String` | The spelling in diagnostics reports, for example `keepPolicyOff`. |

### BackgroundSetup

Returns the settings screens that can lift a manufacturer's background restriction.

```kotlin
public object BackgroundSetup
```

The SDK never opens these on its own. You decide when to show them.

#### BackgroundSetup.oemSetupIntents

Returns the screens that can lift a background restriction on this device, most specific first.

```kotlin
public fun oemSetupIntents(context: Context): List<Intent>
```

| Name      | Type      | Description  |
| --------- | --------- | ------------ |
| `context` | `Context` | Any context. |

**Returns:** intents for screens that exist and are exported on this device, for example Xiaomi's autostart page first and the battery-optimisation list on a Pixel. The last entries resolve everywhere, so the list is not empty on a normal device. It never throws.

Start them from an `Activity`. No flags are set on them.

```kotlin
BackgroundSetup.oemSetupIntents(context).firstOrNull()?.let { activity.startActivity(it) }
```

{% hint style="warning" %}
Do not declare `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` for the SDK. Play restricts it, and the SDK does not need it.
{% endhint %}

### RunOutcome

What one sync run achieved.

```kotlin
public data class RunOutcome(
    public val connected: Boolean = true,
    public val skipped: Map<UploadDataType, Skip> = emptyMap(),
    public val routesSynced: Int = 0,
    public val recordsUploaded: Int = 0,
    public val backfillsServed: Int = 0,
    public val backfillsQueued: Int = 0,
    public val restricted: BackgroundRestrictionReason? = null,
    public val ranOutOfTime: Boolean = false,
    public val retryable: Boolean = false,
    public val throttled: Boolean = false,
)
```

Returned by [`Terra.syncAll`](#terra.syncall).

| Property          | Type                                                           | Description                                                                                     |
| ----------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- |
| `connected`       | `Boolean`                                                      | Whether this device holds a link. `false` means the run did nothing, correctly.                 |
| `skipped`         | `Map<UploadDataType, Skip>`                                    | Routes the run reached and did not send, and why. Keys are [`UploadDataType`](#uploaddatatype). |
| `routesSynced`    | `Int`                                                          | Routes the run brought fully up to date.                                                        |
| `recordsUploaded` | `Int`                                                          | Records uploaded.                                                                               |
| `backfillsServed` | `Int`                                                          | Windows Terra had asked for that this run delivered in full.                                    |
| `backfillsQueued` | `Int`                                                          | Windows this run newly took on.                                                                 |
| `restricted`      | [`BackgroundRestrictionReason?`](#backgroundrestrictionreason) | Why this run did no reads, or `null` if it did.                                                 |
| `ranOutOfTime`    | `Boolean`                                                      | Whether the run hit its deadline with work still queued.                                        |
| `retryable`       | `Boolean`                                                      | Whether anything failed in a way that coming back sooner would fix.                             |
| `throttled`       | `Boolean`                                                      | Whether the store's read quota stopped this run's reads partway.                                |

### RunOutcome.Skip

Why a route a run reached was not sent.

```kotlin
public enum class Skip
```

| Case                 | Description                                                                                           |
| -------------------- | ----------------------------------------------------------------------------------------------------- |
| `AWAITING_CONVERTER` | Terra has no converter deployed for the route yet, so an upload would be accepted and then discarded. |

### TerraSyncWorker

The WorkManager worker that runs one scheduled background run.

```kotlin
public class TerraSyncWorker(
    context: Context,
    parameters: WorkerParameters,
) : CoroutineWorker(context, parameters)
```

WorkManager constructs it; you do not. It finds the client registered for its storage domain through [`BackgroundSync.register`](#backgroundsync.register) and runs every registered source. A run that finds no client, or is refused by a precondition such as a dev ID mismatch, succeeds rather than retries.

## Reading data

Local reads go to the device's store and never touch the network. Each namespace below also holds its category's `log`, `delete` and `changes` members.

Every read:

* throws `TerraError.NotConnected` before `connect`,
* throws `TerraError.HealthDataUnavailable` when the store is unavailable,
* throws `TerraError.AuthorizationNotDetermined` for a category this install has never requested, rather than returning an empty list,
* throws `TerraError.PermissionDenied` when the person refused the record type,
* throws `TerraError.DevIdMismatch` when a different dev ID owns the storage domain,
* throws `TerraError.ReadQuotaExceeded` when the store's read quota is spent,
* treats the window as half-open, `[start, end)`,
* returns every record in the window. It reads in chunks to bound memory, but never caps the result, so ask for the window you will show.

### TimeRange

A window to read over.

```kotlin
public sealed interface TimeRange
```

| Case                                    | Description                                                                                                                        |
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `LastDays(days: Int)`                   | The last `days` local days, counted on the calendar, so a daylight-saving day is not read short. A negative count names no window. |
| `LastHours(hours: Int)`                 | The last `hours` hours. A negative count names no window.                                                                          |
| `Today`                                 | Since local midnight.                                                                                                              |
| `Between(start: Instant, end: Instant)` | From `start` to `end`. The ends may be passed in either order.                                                                     |

#### TimeRange.resolve

Returns the absolute window this range names at a given instant.

```kotlin
public fun resolve(now: Instant, zone: ZoneId): SampleInterval

public fun resolve(now: Instant): SampleInterval = resolve(now, ZoneId.systemDefault())
```

| Name   | Type      | Description                                                                                                      |
| ------ | --------- | ---------------------------------------------------------------------------------------------------------------- |
| `now`  | `Instant` | The instant to resolve against.                                                                                  |
| `zone` | `ZoneId`  | The time zone whose days `Today` and `LastDays` count. Optional overload. Defaults to the device's current zone. |

**Returns:** a half-open [`SampleInterval`](#sampleinterval). The client resolves ranges itself; call this only to resolve one outside a client.

### ActivityMetrics

Workouts.

```kotlin
public class ActivityMetrics internal constructor(...)
```

You reach it through `terra.activity`.

A workout's energy and distance are separate records in Health Connect, each with its own write grant. A `log` needs only the grants its entries use, so a run without energy is never refused over the energy grant.

{% hint style="warning" %}
**A write grant revoked after use leaves that type's record behind.** Say the person turns off the active calories or distance write grant after your app logged a workout that carried it. A correction that drops the field, and a `delete`, both succeed, and the earlier energy or distance record stays in Health Connect. Without the grant the SDK cannot look for that record. Once the grant is restored, logging the entry again or deleting it removes the record.
{% endhint %}

#### ActivityMetrics.workouts

Returns the workouts the store holds in a window.

```kotlin
public suspend fun workouts(range: TimeRange): List<Workout>
```

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

**Returns:** the [`Workout`](#workout)s this device recorded in `range`.

**Throws:** the read errors listed under [Reading data](#reading-data).

#### ActivityMetrics.routes

Returns the GPS tracks of the sessions in a window. Available in 2.2.1 and later.

```kotlin
public suspend fun routes(range: TimeRange): List<WorkoutRoute>
```

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

**Returns:** one [`WorkoutRoute`](#workoutroute) per session that has a track, each naming its session by `workoutId`. Each track is thinned to at most one point a second and at most `MAX_POINTS`, which is the track Terra stores. Health Connect grants a track per session under `READ_EXERCISE_ROUTES`, so a session whose track the person never allowed has none here.

The read checks the `ACTIVITY` category.

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val routes = terra.activity.routes(TimeRange.LastDays(1))
val routeByWorkout = routes.associateBy { it.workoutId }
```

#### ActivityMetrics.intensity

Returns the speed, power and cycling cadence readings in a window. Available in 2.2.1 and later.

```kotlin
public suspend fun intensity(range: TimeRange): List<WorkoutIntensitySample>
```

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

**Returns:** the [`WorkoutIntensitySample`](#workoutintensitysample)s in `range`. Health Connect stores them apart from any session, so none names a workout: match one to a session by its time.

The read checks the `ACTIVITY` category and narrows to `DataType.SPEED`, `POWER` and `CYCLING_CADENCE`. Refusing some of the three returns the rest; refusing all three throws `TerraError.PermissionDenied`.

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val power = terra.activity.intensity(TimeRange.LastDays(1)).filter { it.metric == WorkoutIntensitySample.Metric.POWER }
```

#### ActivityMetrics.log

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

```kotlin
public suspend fun log(entries: List<WorkoutEntry>): List<RecordId>
```

| Name      | Type                 | Description                                    |
| --------- | -------------------- | ---------------------------------------------- |
| `entries` | `List<WorkoutEntry>` | The [`WorkoutEntry`](#workoutentry)s to write. |

**Returns:** one [`RecordId`](#recordid) per entry, in order. It is the only handle `delete` accepts.

All or nothing: a failure leaves the store as it was, so you can retry the same list without writing anything twice.

`log` checks only the grants its entries use: the session, plus active calories when an entry has `totalEnergyKilocalories` and distance when it has `totalDistanceMeters`. It does not use [`writeStatus(ACTIVITY)`](#permissions.writestatus), which answers for everything your app asked to write.

| Error                                   | When                                                                                                                                                                                                                               |
| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `TerraError.AuthorizationNotDetermined` | No request has ever asked for `ACTIVITY` writes or a workout scope. Unlike iOS, `log` does not present a sheet: call `permissions.request(write = setOf(DataCategory.ACTIVITY))`, or `permissions.request(workouts = ...)`, first. |
| `TerraError.PermissionDenied`           | A grant the entries use is refused.                                                                                                                                                                                                |
| `TerraError.HealthDataUnavailable`      | The store is unavailable.                                                                                                                                                                                                          |
| `TerraError.DevIdMismatch`              | A different dev ID owns the storage domain.                                                                                                                                                                                        |

#### ActivityMetrics.delete

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

```kotlin
public suspend fun delete(id: RecordId)
```

| Name | Type                    | Description                             |
| ---- | ----------------------- | --------------------------------------- |
| `id` | [`RecordId`](#recordid) | An ID `log` returned for this category. |

Deletes the session and the active calories and distance logged with it. It needs only the session's write grant. A refused energy or distance grant is skipped, so an earlier record of that type stays if the grant was revoked after use.

| Error                              | When                                                                                                                            |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `TerraError.SampleNotFound`        | `id` is not a record this app wrote in this category: another app's record, an ID from a read, or one for a different category. |
| `TerraError.PermissionDenied`      | The exercise session write grant is not held.                                                                                   |
| `TerraError.HealthDataUnavailable` | The store is unavailable.                                                                                                       |

{% hint style="warning" %}
An ID for a record the person has since deleted in Health Connect returns normally, having removed nothing.
{% endhint %}

#### ActivityMetrics.changes

Returns a stream of hints that the store gained workout data.

```kotlin
public fun changes(): Flow<HealthChange>
```

**Returns:** a cold `Flow` of [`HealthChange`](#healthchange) hints: the category and the day, never the samples. Re-read the day through `workouts`.

Health Connect cannot notify an app of new data, so the SDK polls. A hint arrives up to [`DEFAULT_POLL_SECONDS`](#changehints.default_poll_seconds) after the record. Nothing written before collection starts is reported. Each call returns a fresh stream; collecting starts the polling and cancelling stops it.

### BodyMetrics

Heart rate and the body's vitals.

```kotlin
public class BodyMetrics internal constructor(...)
```

You reach it through `terra.body`.

#### BodyMetrics.heartRate

Returns the heart-rate readings the store holds in a window.

```kotlin
public suspend fun heartRate(range: TimeRange): List<HeartRateSample>
```

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

**Returns:** the [`HeartRateSample`](#heartratesample)s in `range`. Heart rate is read under the `BODY` category.

**Throws:** the read errors listed under [Reading data](#reading-data).

#### BodyMetrics.restingHeartRate

Returns Health Connect's own resting heart rate figures in a window. Available in 2.2.1 and later.

```kotlin
public suspend fun restingHeartRate(range: TimeRange): List<RestingHeartRateSample>
```

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

**Returns:** the [`RestingHeartRateSample`](#restingheartratesample)s in `range`. They are Health Connect's figures, never derived from [`heartRate`](#bodymetrics.heartrate).

{% hint style="warning" %}
Health Connect files resting heart rate under the daily grant, so the read checks `DAILY`, not `BODY`. An app that requested only `BODY` gets `TerraError.AuthorizationNotDetermined`. Request `DAILY` as well.
{% endhint %}

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val resting = terra.body.restingHeartRate(TimeRange.LastDays(7))
```

#### BodyMetrics.readings

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

```kotlin
public suspend fun readings(range: TimeRange): List<BodyReading>
```

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

**Returns:** the [`BodyReading`](#bodyreading)s in `range`. Each reading's `kind` carries its unit. Blood glucose keeps the unit its writer chose. Health Connect has no BMI record, so there is none here. Bone mass, body water mass and the basal metabolic rate are not returned; the upload sends them when your app requested `BODY`.

The read checks the `BODY` category and narrows to the body types it returns. Refusing some of them returns the rest; refusing all of them throws `TerraError.PermissionDenied`.

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val weights = terra.body.readings(TimeRange.LastDays(30))
    .map { it.kind }
    .filterIsInstance<BodyReading.Kind.Measurement>()
    .filter { it.metric == BodyMeasurement.Metric.WEIGHT }
```

#### BodyMetrics.log

Records heart rates or body vitals under your app's name and returns each entry's ID.

```kotlin
public suspend fun log(entries: List<HeartRateEntry>): List<RecordId>

@JvmName("logBody")
public suspend fun log(entries: List<BodyEntry>): List<RecordId>
```

| Name      | Type                                        | Description                                                                      |
| --------- | ------------------------------------------- | -------------------------------------------------------------------------------- |
| `entries` | `List<HeartRateEntry>` or `List<BodyEntry>` | The [`HeartRateEntry`](#heartrateentry)s or [`BodyEntry`](#bodyentry)s to write. |

**Returns:** one [`RecordId`](#recordid) per written entry. For `BodyEntry`, each present field becomes its own record and all share the entry's ID, so one `delete` removes the whole observation. Entries with no fields are skipped and get no ID.

| Error                                   | When                                                                                        |
| --------------------------------------- | ------------------------------------------------------------------------------------------- |
| `TerraError.BloodPressureIncomplete`    | A `BodyEntry` carries only one half of a blood pressure. Raised before anything is written. |
| `TerraError.AuthorizationNotDetermined` | No request has ever asked for `BODY` writes.                                                |
| `TerraError.PermissionDenied`           | The write was refused, or is unsupported.                                                   |
| `TerraError.HealthDataUnavailable`      | The store is unavailable.                                                                   |

From Java, the `BodyEntry` overload is `logBody`.

#### BodyMetrics.delete

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

```kotlin
public suspend fun delete(id: RecordId)
```

| Name | Type                    | Description                             |
| ---- | ----------------------- | --------------------------------------- |
| `id` | [`RecordId`](#recordid) | An ID `log` returned for this category. |

| Error                                   | When                                                   |
| --------------------------------------- | ------------------------------------------------------ |
| `TerraError.SampleNotFound`             | `id` is not a record this app wrote in this category.  |
| `TerraError.AuthorizationNotDetermined` | No request has ever asked for writes in this category. |
| `TerraError.PermissionDenied`           | The write grant is refused.                            |
| `TerraError.HealthDataUnavailable`      | The store is unavailable.                              |

#### BodyMetrics.changes

Returns a stream of hints that the store gained body data.

```kotlin
public fun changes(): Flow<HealthChange>
```

**Returns:** a `Flow` of [`HealthChange`](#healthchange) hints. Behaves as [`ActivityMetrics.changes`](#activitymetrics.changes) does.

### DailyMetrics

Steps and the day's totals.

```kotlin
public class DailyMetrics internal constructor(...)
```

You reach it through `terra.daily`.

#### DailyMetrics.steps

Returns steps in a window, as one total per local day per writing app.

```kotlin
public suspend fun steps(range: TimeRange): List<StepCount>
```

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

**Returns:** [`StepCount`](#stepcount)s, one per local day per writing app. A record that spans midnight is split between the days in proportion. With `DayTotalPolicy(excludeUserEntered = true)`, typed-in steps are left out.

**Throws:** the read errors listed under [Reading data](#reading-data).

{% hint style="warning" %}
A phone and a paired watch each count the same walk, so do not add the totals for one day together.
{% endhint %}

#### DailyMetrics.totals

Returns Health Connect's own totals for each local day a window touches. Available in 2.2.1 and later.

```kotlin
public suspend fun totals(range: TimeRange): List<DayTotal>
```

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

**Returns:** [`DayTotal`](#daytotal)s, one per metric per local day, oldest first. The read returns `DISTANCE_WALKING_RUNNING`, `DISTANCE_CYCLING`, `DISTANCE_SWIMMING`, `DISTANCE_WHEELCHAIR`, `ACTIVE_ENERGY_BURNED`, `BASAL_ENERGY_BURNED` and `FLIGHTS_CLIMBED` where the store computes them. Health Connect does not split distance by activity, so it answers walking and running distance only.

* Each total is a whole local day's, including a day `range` covers only in part.
* A day with nothing recorded has no total, not a zero.
* Totals are Health Connect's aggregate, counted under the client's [`DayTotalPolicy`](#daytotalpolicy). They are the figures the upload sends.
* Steps are not included. Read them with [`steps`](#dailymetrics.steps), which keeps writers apart.
* A total is an aggregate, not a record, so a refused grant does not throw `TerraError.PermissionDenied`. The metric is left out, as the upload leaves it out.

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val totals = terra.daily.totals(TimeRange.LastDays(7))
val energyByDay = totals.filter { it.metric == DayTotal.Metric.ACTIVE_ENERGY_BURNED }
    .associate { it.interval.start to it.value }
```

#### DailyMetrics.intraday

Returns the active energy, distance and floors records the day totals are made of. Available in 2.2.1 and later.

```kotlin
public suspend fun intraday(range: TimeRange): List<IntradaySample>
```

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

**Returns:** the [`IntradaySample`](#intradaysample)s in `range`, whole as Health Connect holds them. A record that crosses midnight is returned whole. For a day's figure, use [`totals`](#dailymetrics.totals).

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val floors = terra.daily.intraday(TimeRange.Today).filter { it.metric == IntradaySample.Metric.FLOORS_CLIMBED }
```

#### DailyMetrics.log

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

```kotlin
public suspend fun log(entries: List<StepEntry>): List<RecordId>
```

| Name      | Type              | Description                              |
| --------- | ----------------- | ---------------------------------------- |
| `entries` | `List<StepEntry>` | The [`StepEntry`](#stepentry)s to write. |

**Returns:** one [`RecordId`](#recordid) per entry.

**Throws:** the `log` errors listed under [`ActivityMetrics.log`](#activitymetrics.log), for `DAILY`.

#### DailyMetrics.delete

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

```kotlin
public suspend fun delete(id: RecordId)
```

| Name | Type                    | Description                             |
| ---- | ----------------------- | --------------------------------------- |
| `id` | [`RecordId`](#recordid) | An ID `log` returned for this category. |

| Error                                   | When                                                   |
| --------------------------------------- | ------------------------------------------------------ |
| `TerraError.SampleNotFound`             | `id` is not a record this app wrote in this category.  |
| `TerraError.AuthorizationNotDetermined` | No request has ever asked for writes in this category. |
| `TerraError.PermissionDenied`           | The write grant is refused.                            |
| `TerraError.HealthDataUnavailable`      | The store is unavailable.                              |

#### DailyMetrics.changes

Returns a stream of hints that the store gained daily data.

```kotlin
public fun changes(): Flow<HealthChange>
```

**Returns:** a `Flow` of [`HealthChange`](#healthchange) hints. Behaves as [`ActivityMetrics.changes`](#activitymetrics.changes) does.

### SleepMetrics

Sleep.

```kotlin
public class SleepMetrics internal constructor(...)
```

You reach it through `terra.sleep`.

#### SleepMetrics.segments

Returns the sleep stages the store holds in a window, as segments.

```kotlin
public suspend fun segments(range: TimeRange): List<SleepSegment>
```

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

**Returns:** the [`SleepSegment`](#sleepsegment)s in `range`. Segments are never stitched into nights.

**Throws:** the read errors listed under [Reading data](#reading-data).

#### SleepMetrics.log

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

```kotlin
public suspend fun log(entries: List<SleepEntry>): List<RecordId>
```

| Name      | Type               | Description                                                                                                |
| --------- | ------------------ | ---------------------------------------------------------------------------------------------------------- |
| `entries` | `List<SleepEntry>` | The [`SleepEntry`](#sleepentry)s to write. Each entry is one stage and becomes one Health Connect session. |

**Returns:** one [`RecordId`](#recordid) per entry.

**Throws:** the `log` errors listed under [`ActivityMetrics.log`](#activitymetrics.log), for `SLEEP`.

#### SleepMetrics.delete

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

```kotlin
public suspend fun delete(id: RecordId)
```

| Name | Type                    | Description                             |
| ---- | ----------------------- | --------------------------------------- |
| `id` | [`RecordId`](#recordid) | An ID `log` returned for this category. |

| Error                                   | When                                                   |
| --------------------------------------- | ------------------------------------------------------ |
| `TerraError.SampleNotFound`             | `id` is not a record this app wrote in this category.  |
| `TerraError.AuthorizationNotDetermined` | No request has ever asked for writes in this category. |
| `TerraError.PermissionDenied`           | The write grant is refused.                            |
| `TerraError.HealthDataUnavailable`      | The store is unavailable.                              |

#### SleepMetrics.changes

Returns a stream of hints that the store gained sleep data.

```kotlin
public fun changes(): Flow<HealthChange>
```

**Returns:** a `Flow` of [`HealthChange`](#healthchange) hints. Behaves as [`ActivityMetrics.changes`](#activitymetrics.changes) does.

### Reads

The shared read path behind the namespaces' read members.

```kotlin
public class Reads internal constructor(...)
```

Its constructor is internal, and no public member of `Terra` returns one. Use the namespace members, which forward to these:

```kotlin
public suspend fun heartRate(range: TimeRange): List<HeartRateSample>
public suspend fun steps(range: TimeRange): List<StepCount>
public suspend fun segments(range: TimeRange): List<SleepSegment>
public suspend fun workouts(range: TimeRange): List<Workout>
```

In 2.2.1 and later it also has:

```kotlin
public suspend fun quantities(range: TimeRange): List<DietaryQuantity>
public suspend fun flow(range: TimeRange): List<MenstruationFlowDay>
public suspend fun restingHeartRate(range: TimeRange): List<RestingHeartRateSample>
public suspend fun intraday(range: TimeRange): List<IntradaySample>
public suspend fun readings(range: TimeRange): List<BodyReading>
public suspend fun routes(range: TimeRange): List<WorkoutRoute>
public suspend fun intensity(range: TimeRange): List<WorkoutIntensitySample>
public suspend fun hydration(range: TimeRange): List<HydrationSample>
public suspend fun events(range: TimeRange): List<MenstrualEvent>
public suspend fun totals(range: TimeRange): List<DayTotal>
```

## Writing data

`log` and `delete` live on the [`activity`](#activitymetrics.log), [`body`](#bodymetrics.log), [`daily`](#dailymetrics.log), [`nutrition`](#nutritionmetrics.log) and [`sleep`](#sleepmetrics.log) namespaces. Request write access with `permissions.request(write = ...)` first: `log` never presents a sheet on Android.

### NutritionMetrics

Meals and intake. It has no `changes()`: re-read the window when your screen appears. Nutrition in Health Connect uploads to Terra when your app requests `NUTRITION`.

```kotlin
public class NutritionMetrics internal constructor(
    private val writes: Writes,
    private val reads: Reads,
)
```

You reach it through `terra.nutrition`. In 2.1.0 it has only `log` and `delete`, and its constructor takes only `writes`.

#### NutritionMetrics.quantities

Returns the nutrients of the meals in a window, one quantity per nutrient. Available in 2.2.1 and later.

```kotlin
public suspend fun quantities(range: TimeRange): List<DietaryQuantity>
```

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

**Returns:** the [`DietaryQuantity`](#dietaryquantity) values in `range`. Health Connect stores a meal as one record; the read returns one quantity per nutrient that record holds. A nutrient the record left empty is not returned. A meal's quantities share a `foodCorrelationId`, which is the meal's record ID. Water is not among them: read it with [`hydration`](#nutritionmetrics.hydration).

The read checks the `NUTRITION` category and narrows to `DataType.NUTRITION`, so a refused nutrition grant throws `TerraError.PermissionDenied` even when water is allowed.

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val meals = terra.nutrition.quantities(TimeRange.LastDays(7)).groupBy { it.foodCorrelationId }
```

#### NutritionMetrics.hydration

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

```kotlin
public suspend fun hydration(range: TimeRange): List<HydrationSample>
```

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

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

The read checks the `NUTRITION` category and narrows to `DataType.HYDRATION`.

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val millilitres = terra.nutrition.hydration(TimeRange.Today).sumOf { it.millilitres }
```

#### NutritionMetrics.log

Records meals under your app's name and returns each meal's ID.

```kotlin
public suspend fun log(entries: List<NutritionEntry>): List<RecordId>
```

| Name      | Type                   | Description                                        |
| --------- | ---------------------- | -------------------------------------------------- |
| `entries` | `List<NutritionEntry>` | The [`NutritionEntry`](#nutritionentry)s to write. |

**Returns:** one [`RecordId`](#recordid) per written meal. A meal's nutrients become one record, plus a second for water, sharing the ID, so one `delete` removes the whole meal. Entries with no nutrient are skipped and get no ID.

**Throws:** the `log` errors listed under [`ActivityMetrics.log`](#activitymetrics.log), for `NUTRITION`.

#### NutritionMetrics.delete

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

```kotlin
public suspend fun delete(id: RecordId)
```

| Name | Type                    | Description                             |
| ---- | ----------------------- | --------------------------------------- |
| `id` | [`RecordId`](#recordid) | An ID `log` returned for this category. |

| Error                                   | When                                                   |
| --------------------------------------- | ------------------------------------------------------ |
| `TerraError.SampleNotFound`             | `id` is not a meal this app wrote.                     |
| `TerraError.AuthorizationNotDetermined` | No request has ever asked for writes in this category. |
| `TerraError.PermissionDenied`           | The write grant is refused.                            |
| `TerraError.HealthDataUnavailable`      | The store is unavailable.                              |

### MenstruationMetrics

The menstrual cycle. Read only: the SDK has no menstruation write. It has no `changes()`. Available in 2.2.1 and later.

```kotlin
public class MenstruationMetrics internal constructor(private val reads: Reads)
```

You reach it through `terra.menstruation`, or `terra.on(source).menstruation`.

#### MenstruationMetrics.flow

Returns the flow days in a window. Available in 2.2.1 and later.

```kotlin
public suspend fun flow(range: TimeRange): List<MenstruationFlowDay>
```

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

**Returns:** one [`MenstruationFlowDay`](#menstruationflowday) per logged day, covering the whole local day the flow was logged on. `cycleStart` comes from the period the day belongs to.

The read checks the `MENSTRUATION` category and narrows to `DataType.MENSTRUATION_FLOW`, so a refused flow grant throws `TerraError.PermissionDenied` even when other cycle events are allowed.

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val days = terra.menstruation.flow(TimeRange.LastDays(90))
```

#### MenstruationMetrics.events

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

```kotlin
public suspend fun events(range: TimeRange): List<MenstrualEvent>
```

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

**Returns:** the [`MenstrualEvent`](#menstrualevent)s in `range`, each at the instant it was logged. Sexual activity is not returned; the upload sends it when your app requested `MENSTRUATION`.

The read checks the `MENSTRUATION` category and narrows to `DataType.INTERMENSTRUAL_BLEEDING`, `OVULATION_TEST` and `CERVICAL_MUCUS`.

**Throws:** the read errors listed under [Reading data](#reading-data).

```kotlin
val ovulationTests = terra.menstruation.events(TimeRange.LastDays(90))
    .filter { it.event == MenstruationEventSample.Event.OVULATION_TEST }
```

### WriteEntry

One record to write to the store.

```kotlin
public sealed interface WriteEntry
```

Implemented by `HeartRateEntry`, `StepEntry`, `SleepEntry`, `WorkoutEntry`, `BodyEntry` and `NutritionEntry`.

| Property   | Type                            | Description                                                                                                                                                                                |
| ---------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `recordId` | [`RecordId`](#recordid)         | The handle `log` returns for this entry and `delete` accepts. Minted when the entry is built and stamped into the record, so sending the same entry twice replaces rather than duplicates. |
| `category` | [`DataCategory`](#datacategory) | The category whose write grant the entry needs.                                                                                                                                            |

### HeartRateEntry

A heart rate to record.

```kotlin
public data class HeartRateEntry(
    public val time: Instant,
    public val beatsPerMinute: Double,
    override val recordId: RecordId = RecordHandles.mint(DataCategory.BODY),
) : WriteEntry
```

| Property         | Type                    | Description                          |
| ---------------- | ----------------------- | ------------------------------------ |
| `time`           | `Instant`               | When the reading was taken.          |
| `beatsPerMinute` | `Double`                | The heart rate.                      |
| `recordId`       | [`RecordId`](#recordid) | The handle. Defaults to a fresh one. |

`category` is `BODY`.

### StepEntry

Steps over a stretch of time.

```kotlin
public data class StepEntry(
    public val interval: SampleInterval,
    public val steps: Int,
    override val recordId: RecordId = RecordHandles.mint(DataCategory.DAILY),
) : WriteEntry
```

| Property   | Type                                | Description                                                                                 |
| ---------- | ----------------------------------- | ------------------------------------------------------------------------------------------- |
| `interval` | [`SampleInterval`](#sampleinterval) | The stretch the steps were taken over. It must not be zero-length: both stores refuse that. |
| `steps`    | `Int`                               | The step count.                                                                             |
| `recordId` | [`RecordId`](#recordid)             | The handle. Defaults to a fresh one.                                                        |

`category` is `DAILY`.

### SleepEntry

One stage of a night.

```kotlin
public data class SleepEntry(
    public val interval: SampleInterval,
    public val stage: SleepStage,
    override val recordId: RecordId = RecordHandles.mint(DataCategory.SLEEP),
) : WriteEntry
```

| Property   | Type                                | Description                          |
| ---------- | ----------------------------------- | ------------------------------------ |
| `interval` | [`SampleInterval`](#sampleinterval) | When the stage started and ended.    |
| `stage`    | [`SleepStage`](#sleepstage)         | The stage.                           |
| `recordId` | [`RecordId`](#recordid)             | The handle. Defaults to a fresh one. |

`category` is `SLEEP`.

### WorkoutEntry

A workout to record.

```kotlin
public data class WorkoutEntry(
    public val interval: SampleInterval,
    public val activity: WorkoutActivity,
    public val totalEnergyKilocalories: Double? = null,
    public val totalDistanceMeters: Double? = null,
    override val recordId: RecordId = RecordHandles.mint(DataCategory.ACTIVITY),
) : WriteEntry
```

| Property                  | Type                                  | Description                                                                                                                                               |
| ------------------------- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `interval`                | [`SampleInterval`](#sampleinterval)   | When the workout started and ended.                                                                                                                       |
| `activity`                | [`WorkoutActivity`](#workoutactivity) | The activity.                                                                                                                                             |
| `totalEnergyKilocalories` | `Double?`                             | Energy burned. `null` when you did not measure it. Needs the active calories write grant, from `write = setOf(ACTIVITY)` or a scope with `energy = true`. |
| `totalDistanceMeters`     | `Double?`                             | Distance covered. `null` when you did not measure it. Needs the distance write grant, from `write = setOf(ACTIVITY)` or a scope with `distance = true`.   |
| `recordId`                | [`RecordId`](#recordid)               | The handle. Defaults to a fresh one. Logging an entry again with the same `recordId` corrects the record it wrote.                                        |

`category` is `ACTIVITY`. Health Connect has one distance record for every activity, so `TerraError.DistanceNotAttributable` is never raised on Android.

### BodyEntry

One observation of the body's vitals.

```kotlin
public data class BodyEntry(
    public val time: Instant,
    public val bodyMassKilograms: Double? = null,
    public val bodyFatPercent: Double? = null,
    public val bodyMassIndex: Double? = null,
    public val heightMeters: Double? = null,
    public val leanBodyMassKilograms: Double? = null,
    public val bodyTemperatureCelsius: Double? = null,
    public val oxygenSaturationPercent: Double? = null,
    public val bloodGlucoseMilligramsPerDeciliter: Double? = null,
    public val bloodPressureSystolicMillimetersOfMercury: Double? = null,
    public val bloodPressureDiastolicMillimetersOfMercury: Double? = null,
    override val recordId: RecordId = RecordHandles.mint(DataCategory.BODY),
) : WriteEntry
```

| Property                                                                                  | Type                    | Description                                                                                                                                                                                             |
| ----------------------------------------------------------------------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `time`                                                                                    | `Instant`               | When the observation was taken.                                                                                                                                                                         |
| `bodyMassKilograms` ... `bloodGlucoseMilligramsPerDeciliter`                              | `Double?`               | Each measurement, in the unit its name says. Every field is optional, and each present one becomes its own record, except `bodyMassIndex`: Health Connect has no BMI record type, so it is not written. |
| `bloodPressureSystolicMillimetersOfMercury`, `bloodPressureDiastolicMillimetersOfMercury` | `Double?`               | Written together as one blood-pressure record. A lone half is refused with `TerraError.BloodPressureIncomplete`.                                                                                        |
| `recordId`                                                                                | [`RecordId`](#recordid) | The handle every record from this entry shares. Defaults to a fresh one.                                                                                                                                |
| `isEmpty`                                                                                 | `Boolean`               | `true` when no field carries a value. Such an entry is skipped.                                                                                                                                         |

`category` is `BODY`.

### NutritionEntry

One meal or intake, over the interval it was consumed.

```kotlin
public data class NutritionEntry(
    public val interval: SampleInterval,
    public val name: String? = null,
    public val nutrients: Nutrients = Nutrients(),
    override val recordId: RecordId = RecordHandles.mint(DataCategory.NUTRITION),
) : WriteEntry
```

| Property    | Type                                     | Description                                                        |
| ----------- | ---------------------------------------- | ------------------------------------------------------------------ |
| `interval`  | [`SampleInterval`](#sampleinterval)      | When it was consumed.                                              |
| `name`      | `String?`                                | The food's name, shown in the health app. Optional.                |
| `nutrients` | [`Nutrients`](#nutritionentry.nutrients) | What it contained. Defaults to none.                               |
| `recordId`  | [`RecordId`](#recordid)                  | The handle. Defaults to a fresh one.                               |
| `isEmpty`   | `Boolean`                                | `true` when no nutrient carries a value. Such an entry is skipped. |

`category` is `NUTRITION`.

### NutritionEntry.Nutrients

The nutrients in a meal, in the units their names say.

```kotlin
public data class Nutrients(
    public val energyKilocalories: Double? = null,
    public val proteinGrams: Double? = null,
    public val carbohydratesGrams: Double? = null,
    public val fiberGrams: Double? = null,
    public val sugarGrams: Double? = null,
    public val fatTotalGrams: Double? = null,
    public val fatSaturatedGrams: Double? = null,
    public val fatMonounsaturatedGrams: Double? = null,
    public val fatPolyunsaturatedGrams: Double? = null,
    public val cholesterolMilligrams: Double? = null,
    public val sodiumMilligrams: Double? = null,
    public val potassiumMilligrams: Double? = null,
    public val calciumMilligrams: Double? = null,
    public val ironMilligrams: Double? = null,
    public val magnesiumMilligrams: Double? = null,
    public val zincMilligrams: Double? = null,
    public val waterLiters: Double? = null,
    public val caffeineMilligrams: Double? = null,
    public val vitaminAMicrograms: Double? = null,
    public val vitaminCMilligrams: Double? = null,
    public val vitaminDMicrograms: Double? = null,
    public val vitaminEMilligrams: Double? = null,
    public val vitaminKMicrograms: Double? = null,
    public val vitaminB6Milligrams: Double? = null,
    public val vitaminB12Micrograms: Double? = null,
    public val folateMicrograms: Double? = null,
    public val thiaminMilligrams: Double? = null,
    public val riboflavinMilligrams: Double? = null,
    public val niacinMilligrams: Double? = null,
    public val biotinMicrograms: Double? = null,
    public val pantothenicAcidMilligrams: Double? = null,
    public val phosphorusMilligrams: Double? = null,
    public val iodineMicrograms: Double? = null,
    public val chromiumMicrograms: Double? = null,
    public val copperMilligrams: Double? = null,
    public val manganeseMilligrams: Double? = null,
    public val molybdenumMicrograms: Double? = null,
    public val seleniumMicrograms: Double? = null,
    public val chlorideMilligrams: Double? = null,
)
```

Every field is optional and named with its unit. `waterLiters` becomes a separate hydration record that shares the meal's `recordId`.

### RecordId

The store's own identifier for a record, or a handle the SDK minted for a write.

```kotlin
@JvmInline
public value class RecordId(public val value: String)
```

| Property | Type     | Description                                               |
| -------- | -------- | --------------------------------------------------------- |
| `value`  | `String` | The identifier. Opaque: Health Connect IDs are not UUIDs. |

#### RecordId.sample

Returns the ID the reading at an index of a series record is uploaded under.

```kotlin
public fun sample(index: Int): RecordId
```

| Name    | Type  | Description                           |
| ------- | ----- | ------------------------------------- |
| `index` | `Int` | The reading's position in the series. |

**Returns:** `"terra-sample.<index>.<value>"`.

#### RecordId.SERIES\_SAMPLE\_PREFIX

The prefix of an ID the SDK minted for one reading of a series record.

```kotlin
public const val SERIES_SAMPLE_PREFIX: String = "terra-sample."
```

#### RecordId.SERIES\_SAMPLE\_TERMINATOR

The separator between the index and the store's own ID in a minted series ID.

```kotlin
public const val SERIES_SAMPLE_TERMINATOR: String = "."
```

### RecordHandles

Mints and recognises the handles `log` returns.

```kotlin
public object RecordHandles
```

A handle carries the SDK's prefix and the category, so `delete` can refuse an ID that is not this app's before it asks the store.

#### RecordHandles.PREFIX

The prefix every handle carries.

```kotlin
public const val PREFIX: String = "terra.1"
```

#### RecordHandles.mint

Returns a fresh handle for a record in a category.

```kotlin
public fun mint(category: DataCategory): RecordId
```

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

**Returns:** a new [`RecordId`](#recordid) of the form `terra.1/<CATEGORY>/<uuid>`.

#### RecordHandles.isOursFor

Returns whether an ID is a handle this SDK minted for a record in a category.

```kotlin
public fun isOursFor(id: RecordId, category: DataCategory): Boolean
```

| Name       | Type                            | Description                    |
| ---------- | ------------------------------- | ------------------------------ |
| `id`       | [`RecordId`](#recordid)         | The ID to check.               |
| `category` | [`DataCategory`](#datacategory) | The category to check against. |

**Returns:** `true` when `id` starts with this SDK's prefix for `category`.

### Writes

The shared write path behind the namespaces' `log` and `delete` members.

```kotlin
public class Writes internal constructor(...)
```

Its constructor is internal, and no public member of `Terra` returns one. Use the namespace members, which forward to these:

```kotlin
public suspend fun log(category: DataCategory, entries: List<WriteEntry>): List<RecordId>
public suspend fun delete(category: DataCategory, id: RecordId)
```

## Change observation

### HealthChange

A hint that the store gained data: the category and the day, never the data.

```kotlin
public data class HealthChange(
    public val category: DataCategory,
    public val day: Instant,
)
```

| Property   | Type                            | Description                                           |
| ---------- | ------------------------------- | ----------------------------------------------------- |
| `category` | [`DataCategory`](#datacategory) | The category that changed.                            |
| `day`      | `Instant`                       | The start of the local day the changed data falls on. |

Re-read that day through the namespace's read member, where permission is checked as usual. The `changes()` members are on [`ActivityMetrics`](#activitymetrics.changes), [`BodyMetrics`](#bodymetrics.changes), [`DailyMetrics`](#dailymetrics.changes) and [`SleepMetrics`](#sleepmetrics.changes).

### ChangeHints

Produces change hints by polling Health Connect's change feed.

```kotlin
public class ChangeHints internal constructor(...)
```

Its constructor is internal, and no public member of `Terra` returns one. Use the namespaces' `changes()` members.

```kotlin
public fun changes(category: DataCategory): Flow<HealthChange>
```

#### ChangeHints.DEFAULT\_POLL\_SECONDS

How long a hint may lag the data it describes.

```kotlin
public const val DEFAULT_POLL_SECONDS: Long = 60
```

If a change token outlives Health Connect's 30-day retention, the stream starts again from a fresh baseline and raises a `ChangeTokenExpired` event. The sync still uploads the records.

## Disconnecting

#### Terra.disconnect

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

```kotlin
public suspend fun disconnect(source: Source): Unit
```

| Name     | Type                | Description              |
| -------- | ------------------- | ------------------------ |
| `source` | [`Source`](#source) | The store to disconnect. |

It succeeds when nothing is stored, so calling it twice is safe. It also succeeds when the revocation does not reach Terra: the device is disconnected locally, and the SDK retries the revocation on a later `connect` or sync run. The device key stays until the revocation settles.

| Error                           | When                                                          |
| ------------------------------- | ------------------------------------------------------------- |
| `TerraError.DevIdMismatch`      | A different dev ID owns this storage domain.                  |
| `TerraError.LinkAlreadyRunning` | A `connect` or `disconnect` for the same source is in flight. |

To remove the user from Terra, call `deauthenticateUser` from your backend.

## Diagnosing delivery

### Diagnostics

Reports why data is or is not arriving, as this client saw it.

```kotlin
public class Diagnostics
```

You reach it through `terra.diagnostics` or `terra.on(source).diagnostics`; you do not construct it. The SDK sends a redacted support report to Terra on its own when something goes wrong, and [`send`](#diagnostics.send) sends one on demand. Everything it reports is built from values that carry no health reading. Every member defaults to the source the namespace was built for.

#### Diagnostics.events

Returns a stream of everything the SDK does, as it happens.

```kotlin
public fun events(): Flow<TerraEvent>
```

**Returns:** a `Flow` of [`TerraEvent`](#terraevent)s. Events raised before collection starts are not replayed, and a collector that stops draining loses its oldest events.

#### Diagnostics.lastDelivery

Returns when Terra last accepted a batch from this device.

```kotlin
public suspend fun lastDelivery(source: Source = permissions.source): Instant?
```

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

**Returns:** the time of the last accepted upload, or `null` if nothing has reached Terra yet.

#### Diagnostics.state

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

```kotlin
public suspend fun state(source: Source = permissions.source): DiagnosticsState
```

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

**Returns:** the first [`DiagnosticsState`](#diagnosticsstate) that applies, ordered by how little your app can do about it: a revoked link first, a device that is only quiet last.

```kotlin
when (val state = terra.diagnostics.state()) {
    is DiagnosticsState.BackgroundRestricted -> state.reason
    is DiagnosticsState.BackgroundRefreshUnscheduled -> Unit // register was never called
    is DiagnosticsState.Quiet -> state.since
    else -> Unit
}
```

#### Diagnostics.report

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

```kotlin
public suspend fun report(source: Source = permissions.source): SupportReport
```

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

**Returns:** a [`SupportReport`](#supportreport) built from the permission record and the recent event history.

#### Diagnostics.send

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

```kotlin
public suspend fun send(source: Source = permissions.source)
```

| Name     | Type                | Description                                                                                                                                                            |
| -------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source` | [`Source`](#source) | The connection to sign with. Optional. Defaults to this namespace's source, so `terra.on(Source.SAMSUNG_HEALTH).diagnostics.send()` signs with the Samsung connection. |

It is exempt from the daily cap on automatic reports, but two calls within a minute send one report. It sends nothing when `source` has no connection, and returns without throwing when Terra refuses the request or the network fails.

#### Diagnostics.considerAutomaticReport

Considers sending an automatic report for an event.

```kotlin
public suspend fun considerAutomaticReport(kind: TerraEvent.Kind)
```

| Name   | Type                                  | Description                            |
| ------ | ------------------------------------- | -------------------------------------- |
| `kind` | [`TerraEvent.Kind`](#terraevent.kind) | The event that might warrant a report. |

The SDK calls this itself when it raises an event. A failure reports itself; a success is a chance to check the state and report it if it is bad. Sending is subject to [`DiagnosticsPolicy`](#diagnosticspolicy).

#### Diagnostics.QUIET\_AFTER\_SECONDS

How long permissions can be granted with nothing delivered before the state is `Quiet`.

```kotlin
public const val QUIET_AFTER_SECONDS: Long = 48 * 60 * 60
```

#### Diagnostics.TICKS\_STALE\_AFTER\_SECONDS

How long WorkManager can hold this app's work without running it before the reason is `TICKS_NOT_RUNNING`.

```kotlin
public const val TICKS_STALE_AFTER_SECONDS: Long = 48 * 60 * 60
```

#### Diagnostics.ANDROID

The platform name a report carries.

```kotlin
public const val ANDROID: String = "android"
```

#### Diagnostics.DEFAULT\_WORK\_NAME

The prefix of the WorkManager work names background sync registers under.

```kotlin
public const val DEFAULT_WORK_NAME: String = "co.tryterra.sdk.sync"
```

### DiagnosticsState

What the SDK reports when you ask why data has stopped arriving.

```kotlin
public sealed interface DiagnosticsState
```

| Case                                                        | Description                                                                                                                                            |
| ----------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `Healthy`                                                   | Nothing is wrong.                                                                                                                                      |
| `Quiet(since: Instant)`                                     | Permissions are granted but nothing has been delivered since `since`. Often a person who has not worn their watch, so a hint rather than a fault.      |
| `BackgroundRestricted(reason: BackgroundRestrictionReason)` | The device will not let this app read in the background. `reason` says which of several causes is true.                                                |
| `BackgroundRefreshUnscheduled`                              | WorkManager does not hold this app's periodic work, so no background run will arrive. `BackgroundSync.register` was never called, or returned `false`. |
| `PendingRetry`                                              | A delivery failed retryably and is waiting before another attempt.                                                                                     |
| `LinkRevoked`                                               | Terra no longer accepts this device's key. Call `connect` again; the token provider is called to link again.                                           |

### BackgroundRestrictionReason

Why background reads are not happening.

```kotlin
public enum class BackgroundRestrictionReason(public val wire: String)
```

| Case                                 | Description                                                                                                                                                          |
| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `OEM_RESTRICTED`                     | The manufacturer's battery manager has restricted this app. Only the person can lift it; show [`BackgroundSetup.oemSetupIntents`](#backgroundsetup.oemsetupintents). |
| `BACKGROUND_READ_DENIED`             | `READ_HEALTH_DATA_IN_BACKGROUND` was asked for and refused. Settings fixes it.                                                                                       |
| `HEALTH_CONNECT_FEATURE_UNAVAILABLE` | This device's Health Connect has no background-read feature.                                                                                                         |
| `STORE_FEATURE_UNAVAILABLE`          | The store behind this source, which is not Health Connect, cannot read in the background.                                                                            |
| `TICKS_NOT_RUNNING`                  | Background runs are scheduled but none has run for 48 hours. Usually a manufacturer restriction, so the same fix as `OEM_RESTRICTED`.                                |

| Member                                                            | Description                                                                                                                     |
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `wire: String`                                                    | The spelling in diagnostics reports, for example `oemRestricted`.                                                               |
| `featureUnavailable(source: Source): BackgroundRestrictionReason` | Companion function. Returns `HEALTH_CONNECT_FEATURE_UNAVAILABLE` for `Source.HEALTH` and `STORE_FEATURE_UNAVAILABLE` otherwise. |

### DiagnosticsReason

Why a support report left the device.

```kotlin
public enum class DiagnosticsReason(public val wire: String)
```

| Case                                 | Description                                                          |
| ------------------------------------ | -------------------------------------------------------------------- |
| `UPLOAD_FAILED`                      | A delivery ran out of retries.                                       |
| `BACKFILL_ABANDONED`                 | A window Terra asked for was given up on.                            |
| `BACKGROUND_OBSERVATION_UNAVAILABLE` | The app cannot read a category in the background.                    |
| `BACKGROUND_RESTRICTED`              | The device is refusing this app background work.                     |
| `BACKGROUND_REFRESH_UNSCHEDULED`     | WorkManager does not hold this app's periodic work.                  |
| `QUIET`                              | Permissions are granted and nothing has been delivered for two days. |
| `REQUESTED`                          | Your app called `diagnostics.send()`.                                |

`wire` is the spelling in reports, for example `uploadFailed`.

### DiagnosticsPolicy

How often a report may leave a device, and from what share of devices.

```kotlin
public object DiagnosticsPolicy
```

| Member                                            | Description                                               |
| ------------------------------------------------- | --------------------------------------------------------- |
| `const val AUTOMATIC_PER_DAY: Int = 4`            | Automatic reports per rolling day. `REQUESTED` is exempt. |
| `const val DAY_SECONDS: Long = 24 * 60 * 60`      | One day, in seconds.                                      |
| `const val WEEK_SECONDS: Long = 7 * DAY_SECONDS`  | One week, in seconds.                                     |
| `const val REQUESTED_INTERVAL_SECONDS: Long = 60` | The minimum gap between two requested reports.            |

#### DiagnosticsPolicy.admits

Returns whether a send fits the budget a ledger already holds.

```kotlin
public fun admits(
    send: DiagnosticsSend,
    ledger: List<DiagnosticsSend>,
    notWithinSeconds: Long,
    automaticLimit: Int?,
): Boolean
```

| Name               | Type                                  | Description                                               |
| ------------------ | ------------------------------------- | --------------------------------------------------------- |
| `send`             | [`DiagnosticsSend`](#diagnosticssend) | The send to check.                                        |
| `ledger`           | `List<DiagnosticsSend>`               | The sends already made.                                   |
| `notWithinSeconds` | `Long`                                | The minimum gap since a send with the same key.           |
| `automaticLimit`   | `Int?`                                | The daily cap on non-requested sends, or `null` for none. |

**Returns:** `false` when a send with the same key falls within `notWithinSeconds`, or the day's non-requested sends have reached `automaticLimit`.

#### DiagnosticsPolicy.rule

Returns the sampling rate and repeat interval for a reason, or `null` when it is never reported.

```kotlin
public fun rule(reason: DiagnosticsReason, code: TerraEvent.FailureCode? = null): Rule?
```

| Name     | Type                                                 | Description                                                                     |
| -------- | ---------------------------------------------------- | ------------------------------------------------------------------------------- |
| `reason` | [`DiagnosticsReason`](#diagnosticsreason)            | Why the report would be sent.                                                   |
| `code`   | [`TerraEvent.FailureCode?`](#terraevent.failurecode) | The failure that fired an `UPLOAD_FAILED` report. Optional. Defaults to `null`. |

**Returns:** a `Rule` (below), or `null` for an upload failure code that is never reported.

#### DiagnosticsPolicy.sampled

Returns whether this install is in the sampled share for a rate.

```kotlin
public fun sampled(identity: String, rate: Double): Boolean
```

| Name       | Type     | Description                                             |
| ---------- | -------- | ------------------------------------------------------- |
| `identity` | `String` | The install's identity. It is hashed and never sent.    |
| `rate`     | `Double` | The share of installs that report, from `0.0` to `1.0`. |

**Returns:** the same answer on every run for the same install and rate.

**`DiagnosticsPolicy.Rule`** is the share of installs that report a reason, and how long one install waits to repeat it.

```kotlin
public data class Rule(public val rate: Double, public val intervalSeconds: Long)
```

| Property          | Type     | Description                                             |
| ----------------- | -------- | ------------------------------------------------------- |
| `rate`            | `Double` | The share of installs that report, from `0.0` to `1.0`. |
| `intervalSeconds` | `Long`   | The minimum gap between two reports from one install.   |

### DiagnosticsSend

One report this device sent, as the budget remembers it.

```kotlin
public data class DiagnosticsSend(public val key: String, public val at: Instant)
```

| Property | Type      | Description                                                           |
| -------- | --------- | --------------------------------------------------------------------- |
| `key`    | `String`  | The reason, or `reason:trigger` where the trigger has its own budget. |
| `at`     | `Instant` | When it was sent.                                                     |

| Companion member                                                                  | Description                                                                                                                    |
| --------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `const val LEDGER_LIMIT: Int = 32`                                                | How many sends a store keeps.                                                                                                  |
| `fun trimmed(ledger: List<DiagnosticsSend>, now: Instant): List<DiagnosticsSend>` | Returns `ledger` cut to `LEDGER_LIMIT` entries, dropping first those older than a week, then requested sends, then the oldest. |

### SupportReport

A redacted support snapshot that contains no health readings.

```kotlin
public data class SupportReport(
    public val sdkVersion: String,
    public val generatedAt: Instant,
    public val state: DiagnosticsState,
    public val lastDelivery: Instant?,
    public val isConnected: Boolean,
    public val requestedCategories: List<String>,
    public val requestedWrites: List<String>,
    public val requestedWorkouts: List<String>,
    public val recentEvents: List<TerraEvent>,
)
```

| Property              | Type                                    | Description                                                                                    |
| --------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `sdkVersion`          | `String`                                | The SDK version.                                                                               |
| `generatedAt`         | `Instant`                               | When the report was built.                                                                     |
| `state`               | [`DiagnosticsState`](#diagnosticsstate) | The state at that time.                                                                        |
| `lastDelivery`        | `Instant?`                              | When Terra last accepted a batch.                                                              |
| `isConnected`         | `Boolean`                               | Whether the source is linked.                                                                  |
| `requestedCategories` | `List<String>`                          | Categories a request has ever asked to read.                                                   |
| `requestedWrites`     | `List<String>`                          | Categories a request has ever asked to write.                                                  |
| `requestedWorkouts`   | `List<String>`                          | The workout scopes requests have named.                                                        |
| `recentEvents`        | `List<TerraEvent>`                      | The most recent events, oldest first, up to [`EventBus.RECENT_LIMIT`](#eventbus.recent_limit). |

### TerraEvent

Something the SDK did, typed rather than logged.

```kotlin
public data class TerraEvent(public val at: Instant, public val kind: Kind)
```

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

No event carries a health value. Counts in events are counts of records, bytes or windows.

### TerraEvent.Kind

What happened.

```kotlin
public sealed interface Kind
```

| Case                                                      | Description                                                                                                                                                                                     |
| --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Connected(source)`                                       | A source was linked.                                                                                                                                                                            |
| `Disconnected(source)`                                    | A source was disconnected.                                                                                                                                                                      |
| `LinkRevoked(source)`                                     | Terra stopped accepting this device's key. Nothing is signed under the link until the next `connect`.                                                                                           |
| `PermissionResult(asked, covered)`                        | A permission request finished. `covered` is the subset of `asked` the platform granted.                                                                                                         |
| `BackgroundWake(source)`                                  | A background run started.                                                                                                                                                                       |
| `BackgroundWorkGap(source, afterSeconds)`                 | A scheduled run arrived `afterSeconds` after the one before it, so the schedule was not honoured.                                                                                               |
| `BackgroundWorkReset(identifier, source, attempt)`        | A WorkManager backoff was cleared so delivery can resume. `identifier` is `tick` or `now`; `attempt` is how many failures had built it up.                                                      |
| `BackgroundRefreshUnscheduled(identifier, source)`        | WorkManager does not hold this app's periodic work. `identifier` is the work name.                                                                                                              |
| `UploadBatch(dataType, source, records, bytes)`           | Terra accepted one batch.                                                                                                                                                                       |
| `UploadFailed(dataType, source, code)`                    | A batch failed.                                                                                                                                                                                 |
| `RetryScheduled(dataType, source, afterSeconds, attempt)` | A failed batch will be retried.                                                                                                                                                                 |
| `BackfillProgress(dataType, source, uploaded, skipped)`   | The first sync walked part of its history. `skipped` counts windows given up on.                                                                                                                |
| `ServerBackfillQueued(dataType, source)`                  | Terra asked for a window and the device took it on.                                                                                                                                             |
| `ServerBackfillCompleted(dataType, source, uploaded)`     | A requested window was served to its end.                                                                                                                                                       |
| `ServerBackfillAbandoned(dataType, source, code)`         | A requested window was given up on. `code` is the last failure.                                                                                                                                 |
| `ServerBackfillRefused(source)`                           | A requested window was refused because the device's queue is full.                                                                                                                              |
| `ServerBackfillUnsupported(source)`                       | A requested window was for a data type this SDK cannot upload, so it was dropped.                                                                                                               |
| `ServerBackfillPollFailed(source, code)`                  | Polling for requested windows failed. The next run tries again.                                                                                                                                 |
| `BackgroundObservationUnavailable(category, source)`      | The app cannot read this category in the background, so hints are foreground only.                                                                                                              |
| `ObservationDropped(category, source)`                    | A queued wake was discarded because its link is gone.                                                                                                                                           |
| `ChangeTokenExpired(source)`                              | The change feed's token outlived Health Connect's 30-day retention.                                                                                                                             |
| `HistoryReadUnavailable(dataType, source)`                | A backfill reached data older than 30 days without `READ_HEALTH_DATA_HISTORY`, so it stopped there.                                                                                             |
| `ReadQuotaExceeded(dataType, source)`                     | Health Connect's read quota is spent, so the route stopped and resumes on a later run. Not data loss.                                                                                           |
| `RouteConsentRequired(source)`                            | A workout has a route the app was never given `READ_EXERCISE_ROUTES` to read.                                                                                                                   |
| `SamplesLogged(category, count, source)`                  | A `log` wrote `count` records.                                                                                                                                                                  |
| `SampleDeleted(category, source)`                         | A `delete` removed a record.                                                                                                                                                                    |
| `TokenRefreshed`                                          | Declared for parity with iOS. No code path in this release raises it.                                                                                                                           |
| `DeviceKeyRevokeAnswered(source, outcome)`                | Terra answered a key revocation. Only `ROUTE_ABSENT` leaves it owed.                                                                                                                            |
| `DeviceKeyRevokeFailed(source, code, attempt, owed)`      | A key revocation failed. `owed` is `false` when nothing can send it again.                                                                                                                      |
| `ProcessExitDecided(decision)`                            | What [`EXIT_WHEN_IDLE`](#processexitpolicy) decided after a background run, as a [`ProcessExitDecision`](#processexitdecision).                                                                 |
| `DiagnosticsReported(reason, source)`                     | A support report left the device.                                                                                                                                                               |
| `DevIDBindingChanged(source, devId, active)`              | In [`DevIdMode.MULTIPLE`](#devidmode), a customer's connection left Terra's answer (`active` is `false`) or came back (`true`). `devId` is the customer's dev ID. Available in 2.3.0 and later. |

`dataType` is an [`UploadDataType`](#uploaddatatype); `code` is a [`FailureCode`](#terraevent.failurecode).

Like `TokenRefreshed`, these cases are declared and never raised in this release: `Connected`, `Disconnected`, `LinkRevoked`, `PermissionResult`, `BackgroundRefreshUnscheduled`, `BackfillProgress`, `BackgroundObservationUnavailable`, `ObservationDropped`, `DeviceKeyRevokeAnswered` and `DeviceKeyRevokeFailed`.

### TerraEvent.FailureCode

A failure code that contains no person-identifying text.

```kotlin
public enum class FailureCode(public val wire: String)
```

There is one case per `TerraError` case, plus the network failures. `wire` matches the iOS spelling, so reports from both platforms read the same.

| Case                                     | `wire`                                |
| ---------------------------------------- | ------------------------------------- |
| `HEALTH_DATA_UNAVAILABLE`                | `healthDataUnavailable`               |
| `NOT_CONNECTED`                          | `notConnected`                        |
| `TOKEN_UNAVAILABLE`                      | `tokenUnavailable`                    |
| `TOKEN_REJECTED`                         | `tokenRejected`                       |
| `TOKEN_PROVIDER_FAILED`                  | `tokenProviderFailed`                 |
| `OFFLINE`                                | `offline`                             |
| `TIMED_OUT`                              | `timedOut`                            |
| `SERVER_ERROR`                           | `serverError`                         |
| `TRANSPORT`                              | `transport`                           |
| `MALFORMED_RESPONSE`                     | `malformedResponse`                   |
| `USER_LIMIT_REACHED`                     | `userLimitReached`                    |
| `UPGRADE_REQUIRED`                       | `upgradeRequired`                     |
| `PLATFORM`                               | `platform`                            |
| `DEVICE_KEY_UNAVAILABLE`                 | `deviceKeyUnavailable`                |
| `SIGNATURE_REJECTED`                     | `signatureRejected`                   |
| `LINK_REVOKED`                           | `linkRevoked`                         |
| `DEV_ID_MISMATCH`                        | `devIDMismatch`                       |
| `LINK_CONFLICT`                          | `linkConflict`                        |
| `CLOCK_SKEWED`                           | `clockSkewed`                         |
| `SYNC_ALREADY_RUNNING`                   | `syncAlreadyRunning`                  |
| `LINK_ALREADY_RUNNING`                   | `linkAlreadyRunning`                  |
| `STORE_LOCKED`                           | `storeLocked`                         |
| `STORE_UNREADABLE`                       | `storeUnreadable`                     |
| `DEADLINE_EXCEEDED`                      | `deadlineExceeded`                    |
| `PERMISSION_DENIED`                      | `permissionDenied`                    |
| `AUTHORIZATION_NOT_DETERMINED`           | `authorizationNotDetermined`          |
| `SAMPLE_NOT_FOUND`                       | `sampleNotFound`                      |
| `ROLLBACK_INCOMPLETE`                    | `rollbackIncomplete`                  |
| `DISTANCE_NOT_ATTRIBUTABLE`              | `distanceNotAttributable`             |
| `BLOOD_PRESSURE_INCOMPLETE`              | `bloodPressureIncomplete`             |
| `AUTHORIZATION_UNAVAILABLE_IN_EXTENSION` | `authorizationUnavailableInExtension` |
| `ROUTE_AWAITING_CONVERTER`               | `routeAwaitingConverter`              |
| `READ_QUOTA_EXCEEDED`                    | `readQuotaExceeded`                   |
| `LINK_REFUSED`                           | `linkRefused`                         |
| `WORKOUTS_REQUIRED`                      | `workoutsRequired`                    |

`LINK_REFUSED` and `WORKOUTS_REQUIRED` are available in 2.3.0 and later. An exhaustive `when` over `FailureCode` needs their arms.

`OFFLINE` and `TIMED_OUT` are never produced from a `TerraError` on Android.

#### TerraEvent.FailureCode.of

Returns the failure code for an error.

```kotlin
public fun of(error: TerraError): FailureCode
```

| Name    | Type                        | Description       |
| ------- | --------------------------- | ----------------- |
| `error` | [`TerraError`](#terraerror) | The error to map. |

**Returns:** the matching code. A `Network` error maps to `TRANSPORT`, `MALFORMED_RESPONSE` or `SERVER_ERROR`; a throttle reports as `SERVER_ERROR`.

### DeviceKeyRevokeOutcome

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

```kotlin
public enum class DeviceKeyRevokeOutcome(public val wire: String)
```

| Case              | Description                                                                         |
| ----------------- | ----------------------------------------------------------------------------------- |
| `REVOKED`         | Terra revoked the key.                                                              |
| `ALREADY_REVOKED` | Terra had already forgotten the key (a 401).                                        |
| `ROUTE_ABSENT`    | The route answered 404. The key may still be trusted, so the revocation stays owed. |

### EventBus

Fans the SDK's events out to subscribers, and keeps the most recent ones for support reports.

```kotlin
public class EventBus(
    private val recentLimit: Int = RECENT_LIMIT,
    bufferCapacity: Int = BUFFER_LIMIT,
)
```

| Name             | Type  | Description                                                                                                   |
| ---------------- | ----- | ------------------------------------------------------------------------------------------------------------- |
| `recentLimit`    | `Int` | How many recent events to keep. Optional. Defaults to [`RECENT_LIMIT`](#eventbus.recent_limit).               |
| `bufferCapacity` | `Int` | How far a subscriber may fall behind before it loses its oldest events. Optional. Defaults to `BUFFER_LIMIT`. |

The SDK builds its own. Read events through [`Diagnostics.events`](#diagnostics.events).

#### EventBus.events

Returns a fresh view of the event stream.

```kotlin
public fun events(): Flow<TerraEvent>
```

**Returns:** a shared `Flow` of [`TerraEvent`](#terraevent)s. Two collectors each see every event.

#### EventBus.emit

Records an event and hands it to every subscriber.

```kotlin
public fun emit(event: TerraEvent)
```

| Name    | Type                        | Description          |
| ------- | --------------------------- | -------------------- |
| `event` | [`TerraEvent`](#terraevent) | The event to record. |

It never suspends and never fails.

#### EventBus.recentEvents

Returns the most recent events, oldest first.

```kotlin
public fun recentEvents(): List<TerraEvent>
```

**Returns:** up to `recentLimit` events.

#### EventBus.RECENT\_LIMIT

How many events a support report carries.

```kotlin
public const val RECENT_LIMIT: Int = 64
```

#### EventBus.BUFFER\_LIMIT

How far a subscriber may fall behind before it starts losing its oldest events.

```kotlin
public const val BUFFER_LIMIT: Int = 256
```

### DiagnosticsWire

Encodes events, states and support reports as the JSON Terra receives.

```kotlin
public object DiagnosticsWire
```

The wire form is shared with the iOS SDK. You only need it to print a report the way Terra stores it.

| Member                                                                                                                              | Description                                                                                                                         |
| ----------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `const val SCHEMA: Int = 1`                                                                                                         | The report envelope's shape version.                                                                                                |
| `fun event(event: TerraEvent): JsonObject`                                                                                          | Returns one event as a flat object, such as `{"at": ..., "event": "uploadBatch", "records": 12}`.                                   |
| `fun state(state: DiagnosticsState): JsonObject`                                                                                    | Returns the state as a flat object, such as `{"state": "quiet", "since": ...}`. `reason` appears only under `backgroundRestricted`. |
| `fun report(report: SupportReport): JsonObject`                                                                                     | Returns the whole report.                                                                                                           |
| `fun envelope(reason: DiagnosticsReason, trigger: String?, report: SupportReport, platform: String, osVersion: String): JsonObject` | Returns the JSON body of an automatic or requested report. `platform` and `osVersion` are the only facts about the host it carries. |
| `fun bytes(json: JsonObject): ByteArray`                                                                                            | Returns the encoded bytes of one object, with keys in a stable order.                                                               |

### DiagnosticsWire.Key

Every key an encoded event or state may carry.

```kotlin
public object Key
```

| Member             | Value                                                                                                   |
| ------------------ | ------------------------------------------------------------------------------------------------------- |
| `AT`               | `"at"`                                                                                                  |
| `EVENT`            | `"event"`                                                                                               |
| `SOURCE`           | `"source"`                                                                                              |
| `DATA_TYPE`        | `"dataType"`                                                                                            |
| `CATEGORY`         | `"category"`                                                                                            |
| `CODE`             | `"code"`                                                                                                |
| `REASON`           | `"reason"`                                                                                              |
| `OUTCOME`          | `"outcome"`                                                                                             |
| `IDENTIFIER`       | `"identifier"`                                                                                          |
| `RECORDS`          | `"records"`                                                                                             |
| `BYTES`            | `"bytes"`                                                                                               |
| `UPLOADED`         | `"uploaded"`                                                                                            |
| `SKIPPED`          | `"skipped"`                                                                                             |
| `ATTEMPT`          | `"attempt"`                                                                                             |
| `AFTER_SECONDS`    | `"afterSeconds"`                                                                                        |
| `OWED`             | `"owed"`                                                                                                |
| `ASKED`            | `"asked"`                                                                                               |
| `COVERED`          | `"covered"`                                                                                             |
| `DEV_ID`           | `"devID"`. Available in 2.3.0 and later.                                                                |
| `ACTIVE`           | `"active"`. Available in 2.3.0 and later.                                                               |
| `STATE`            | `"state"`                                                                                               |
| `SINCE`            | `"since"`                                                                                               |
| `all: Set<String>` | Every event key above: `AT` to `COVERED`, and `DEV_ID` and `ACTIVE`. `STATE` and `SINCE` are not in it. |

Each key is a `public const val ...: String`.

## Errors

### TerraError

Everything the SDK throws, as one closed set with retryability attached.

```kotlin
public sealed class TerraError(
    message: String,
    cause: Throwable? = null,
) : Exception(message, cause)
```

The cases mirror the iOS SDK's, so shared code handles one vocabulary and gets the same `isRetryable` answer. Android has no `planned_workout_unnamed`, `network.offline` or `network.timed_out`: both network failures arrive as `network.transport`.

| Property                 | Type      | Description                                                                                                                                                            |
| ------------------------ | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `code`                   | `String`  | The stable `snake_case` name for the case, shared with iOS. Switch on it from React Native or Flutter bindings. Dotted for `Network`, for example `network.transport`. |
| `isRetryable`            | `Boolean` | Whether the same call could succeed if tried again with nothing else changed.                                                                                          |
| `isAuthorizationRefusal` | `Boolean` | Whether the store refused for want of authorization, which a person can clear. `true` for `PermissionDenied` and `AuthorizationNotDetermined`.                         |

| Case                                                                    | `code`                                   | Retryable            | When                                                                                                                                                                                                                                                                                                            |
| ----------------------------------------------------------------------- | ---------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `HealthDataUnavailable(reason: StoreAvailability)`                      | `health_data_unavailable`                | No                   | No usable store for the source. `reason` is a [`StoreAvailability`](#storeavailability): for example the add-on is missing, or the provider app is missing or too old.                                                                                                                                          |
| `NotConnected(source: Source)`                                          | `not_connected`                          | No                   | A call that needs a linked user ran before `connect`.                                                                                                                                                                                                                                                           |
| `PermissionDenied(category: DataCategory)`                              | `permission_denied`                      | No                   | The store refused a read or write the person has not granted.                                                                                                                                                                                                                                                   |
| `Platform(underlying: Throwable)`                                       | `platform`                               | No                   | A platform call failed in a way the SDK does not model. The throwable is attached.                                                                                                                                                                                                                              |
| `TokenRejected`                                                         | `token_rejected`                         | No                   | The auth token was expired, already spent, or unknown.                                                                                                                                                                                                                                                          |
| `TokenUnavailable`                                                      | `token_unavailable`                      | No                   | `connect` was called with no token and no `tokenProvider`.                                                                                                                                                                                                                                                      |
| `TokenProviderFailed(underlying: Throwable)`                            | `token_provider_failed`                  | No                   | Your `tokenProvider` threw. The cause is attached.                                                                                                                                                                                                                                                              |
| `DeviceKeyUnavailable(reason: String, underlying: Throwable? = null)`   | `device_key_unavailable`                 | No                   | The connection's signing key is gone or unusable, for example after a restore to a new phone. Link again.                                                                                                                                                                                                       |
| `SignatureRejected`                                                     | `signature_rejected`                     | No                   | Terra verified no registered key against the request's signature.                                                                                                                                                                                                                                               |
| `ClockSkewed`                                                           | `clock_skewed`                           | No                   | The device clock is outside Terra's 15-minute signing window. Only correcting the clock helps.                                                                                                                                                                                                                  |
| `UserLimitReached`                                                      | `user_limit_reached`                     | No                   | Your plan's user allowance is used up.                                                                                                                                                                                                                                                                          |
| `LinkConflict`                                                          | `link_conflict`                          | Yes                  | The link raced another registration.                                                                                                                                                                                                                                                                            |
| `UpgradeRequired`                                                       | `upgrade_required`                       | No                   | Terra no longer accepts this SDK version.                                                                                                                                                                                                                                                                       |
| `LinkAlreadyRunning(source: Source)`                                    | `link_already_running`                   | No                   | Another `connect` for the source is in flight. Wait for it rather than retrying.                                                                                                                                                                                                                                |
| `LinkRevoked(source: Source)`                                           | `link_revoked`                           | No                   | Terra no longer accepts this device's key, for example because another device linked the same user. Only a fresh link clears it.                                                                                                                                                                                |
| `DevIdMismatch(source: Source)`                                         | `dev_id_mismatch`                        | No                   | The stored connection or the storage domain belongs to a different dev ID, or to a client built in the other [`DevIdMode`](#devidmode). `connect` is refused, with a token too, and is always refused in `DevIdMode.MULTIPLE`. Running with the original dev ID clears it, and so does clearing the app's data. |
| `LinkRefused(reason: String)`                                           | `link_refused`                           | No                   | Terra refused, permanently, to share this device's key with the customer a [`LinkedDevIds.link`](#linkeddevids.link) was for. `reason` is Terra's code, such as `device_key_sharing_disabled`. Available in 2.3.0 and later.                                                                                    |
| `SyncAlreadyRunning(dataType: UploadDataType)`                          | `sync_already_running`                   | No                   | A sync for this route is already running. Let it finish.                                                                                                                                                                                                                                                        |
| `RouteAwaitingConverter(dataType: UploadDataType)`                      | `route_awaiting_converter`               | No                   | Terra has no converter deployed for the route yet. No route in this release is held.                                                                                                                                                                                                                            |
| `StoreLocked`                                                           | `store_locked`                           | Yes                  | The device has not been unlocked since it booted, so stored state cannot be read yet.                                                                                                                                                                                                                           |
| `StoreUnreadable`                                                       | `store_unreadable`                       | No                   | Stored state is present and cannot be decoded.                                                                                                                                                                                                                                                                  |
| `DeadlineExceeded`                                                      | `deadline_exceeded`                      | Yes                  | The run's time ran out before this batch was sent. Nothing is lost.                                                                                                                                                                                                                                             |
| `ReadQuotaExceeded(source: Source)`                                     | `read_quota_exceeded`                    | Yes                  | The store's read quota is spent for now. Android only.                                                                                                                                                                                                                                                          |
| `AuthorizationNotDetermined`                                            | `authorization_not_determined`           | No                   | A read or write touched a category no request has ever asked for. Call `permissions.request`. On a type-scoped install, a local read is refused this way unless the install asked for one of the types it returns.                                                                                              |
| `WorkoutsRequired(type: HealthDataType)`                                | `workouts_required`                      | No                   | A permission request named `type` (`WORKOUT_ROUTE`, `SPEED`, `POWER` or `CYCLING_CADENCE`) without `WORKOUTS` or the whole `ACTIVITY` category. Nothing is recorded or shown. Available in 2.3.0 and later.                                                                                                     |
| `SampleNotFound(id: RecordId)`                                          | `sample_not_found`                       | No                   | A `delete` named a record that is not this app's to remove.                                                                                                                                                                                                                                                     |
| `RollbackIncomplete(remaining: List<RecordId>, underlying: TerraError)` | `rollback_incomplete`                    | No                   | A `log` failed partway and the records already written could not be removed. Delete `remaining` before retrying.                                                                                                                                                                                                |
| `DistanceNotAttributable(activity: WorkoutActivity)`                    | `distance_not_attributable`              | No                   | Never raised on Android. Kept so code shared with iOS compiles.                                                                                                                                                                                                                                                 |
| `BloodPressureIncomplete`                                               | `blood_pressure_incomplete`              | No                   | A `BodyEntry` carried only one half of a blood pressure.                                                                                                                                                                                                                                                        |
| `AuthorizationUnavailableInExtension`                                   | `authorization_unavailable_in_extension` | No                   | Never raised on Android. Kept so code shared with iOS compiles.                                                                                                                                                                                                                                                 |
| `Network(failure: NetworkFailure)`                                      | `network.<failure.code>`                 | Depends on `failure` | The transport failed, or Terra answered with a status the SDK does not model specially.                                                                                                                                                                                                                         |

### NetworkFailure

What went wrong below the HTTP status line, or at it.

```kotlin
public sealed class NetworkFailure
```

| Case                                  | `code`               | Retryable        | Description                                                                                   |
| ------------------------------------- | -------------------- | ---------------- | --------------------------------------------------------------------------------------------- |
| `Transport(underlying: Throwable)`    | `transport`          | Yes              | The request never completed: no route, a timeout, a dropped connection.                       |
| `MalformedResponse`                   | `malformed_response` | No               | A 2xx whose body the SDK could not read.                                                      |
| `Throttled(retryAfterSeconds: Long?)` | `throttled`          | Yes              | Terra asked the device to slow down. `retryAfterSeconds` is Terra's `Retry-After`, when sent. |
| `ServerError(status: Int)`            | `server_error`       | 5xx and 429 only | Any other status. `status` is the HTTP status.                                                |

| Property | Type     | Description                                          |
| -------- | -------- | ---------------------------------------------------- |
| `code`   | `String` | The part after the dot in `TerraError.Network.code`. |

Unlike iOS, Android has no `offline` or `timed_out` network code: both arrive as `transport`.

## Data types

Values a read returns, and the types they are built from. [`StoredConnection`](#storedconnection) (returned by `connect`), [`HealthAccess`](#healthaccess) (returned by `permissions.request`) and [`UploadDataType`](#uploaddatatype) (an upload route) are described under Extension points.

Most samples share these properties:

| Property      | Type                            | Description                                                                 |
| ------------- | ------------------------------- | --------------------------------------------------------------------------- |
| `id`          | [`RecordId`](#recordid)         | The store's own identifier for the record.                                  |
| `source`      | [`SampleSource`](#samplesource) | The app or device that wrote it.                                            |
| `userEntered` | `Boolean`                       | Whether a person typed it in. Defaults to `false`.                          |
| `timeZone`    | `ZoneId?`                       | The zone the writer recorded, if any. The device's own is used when absent. |

### SampleInterval

A half-open span of time, `[start, end)`.

```kotlin
public data class SampleInterval(public val start: Instant, public val end: Instant)
```

| Property | Type      | Description          |
| -------- | --------- | -------------------- |
| `start`  | `Instant` | The start, included. |
| `end`    | `Instant` | The end, excluded.   |

### SampleSource

Who recorded a sample.

```kotlin
public data class SampleSource(
    public val name: String,
    public val bundleId: String,
    public val productType: String? = null,
    public val deviceType: String? = null,
)
```

| Property      | Type      | Description                                                                                                   |
| ------------- | --------- | ------------------------------------------------------------------------------------------------------------- |
| `name`        | `String`  | The writing app or device, as a person would recognise it.                                                    |
| `bundleId`    | `String`  | The writing app's package name. Named after the wire field.                                                   |
| `productType` | `String?` | The hardware model. Absent when the store reports none, which is normal for app-written records.              |
| `deviceType`  | `String?` | The kind of device that wrote the record, such as `scale` or `phone`, or `null` where the store says nothing. |

### MotionContext

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

```kotlin
public enum class MotionContext(public val wire: String)
```

| Case        | Description                                                                              |
| ----------- | ---------------------------------------------------------------------------------------- |
| `UNKNOWN`   | The device recorded the sample but could not classify the motion. Different from `null`. |
| `SEDENTARY` | At rest.                                                                                 |
| `ACTIVE`    | Moving.                                                                                  |

### HeartRateSample

One heart-rate reading.

```kotlin
public data class HeartRateSample(
    public val id: RecordId,
    public val time: Instant,
    public val beatsPerMinute: Double,
    public val source: SampleSource,
    public val motionContext: MotionContext? = null,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property         | Type                               | Description                                   |
| ---------------- | ---------------------------------- | --------------------------------------------- |
| `time`           | `Instant`                          | When it was measured, from the record.        |
| `beatsPerMinute` | `Double`                           | The heart rate.                               |
| `motionContext`  | [`MotionContext?`](#motioncontext) | How the body was moving, when the store says. |

### StepCount

Steps totalled over a window, usually a day.

```kotlin
public data class StepCount(
    public val interval: SampleInterval,
    public val steps: Int,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val id: RecordId? = null,
    public val timeZone: ZoneId? = null,
)
```

| Property   | Type                                | Description                                                                           |
| ---------- | ----------------------------------- | ------------------------------------------------------------------------------------- |
| `interval` | [`SampleInterval`](#sampleinterval) | The window the steps were counted over.                                               |
| `steps`    | `Int`                               | The step count.                                                                       |
| `id`       | [`RecordId?`](#recordid)            | The store's identifier, present only for one raw record rather than a computed total. |

### RestingHeartRateSample

The store's own resting-heart-rate figure, one per day.

```kotlin
public data class RestingHeartRateSample(
    public val id: RecordId,
    public val interval: SampleInterval,
    public val beatsPerMinute: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property         | Type                                | Description                            |
| ---------------- | ----------------------------------- | -------------------------------------- |
| `interval`       | [`SampleInterval`](#sampleinterval) | The day the figure describes.          |
| `beatsPerMinute` | `Double`                            | The device's figure, never recomputed. |

### SleepSegment

One stretch of a single sleep stage, as the store recorded it.

```kotlin
public data class SleepSegment(
    public val id: RecordId,
    public val interval: SampleInterval,
    public val stage: SleepStage,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property   | Type                                | Description                       |
| ---------- | ----------------------------------- | --------------------------------- |
| `interval` | [`SampleInterval`](#sampleinterval) | When the stage started and ended. |
| `stage`    | [`SleepStage`](#sleepstage)         | The stage.                        |

A segment is not a whole night. The SDK does not stitch segments into sessions.

### SleepStage

A sleep stage.

```kotlin
public sealed interface SleepStage
```

| Case                   | Description                                                            |
| ---------------------- | ---------------------------------------------------------------------- |
| `InBed`                | In bed, not necessarily asleep. Health Connect never produces it.      |
| `Awake`                | Awake.                                                                 |
| `Asleep`               | Asleep, with no stage breakdown. Distinct from `Light`.                |
| `Light`                | Light sleep.                                                           |
| `Deep`                 | Deep sleep.                                                            |
| `Rem`                  | REM sleep.                                                             |
| `Unknown(raw: String)` | A stage the SDK does not recognise. `raw` is the platform's own label. |

### WorkoutActivity

A workout's activity: the common ones, with everything else passed through.

```kotlin
public sealed interface WorkoutActivity
```

| Case                   | Description                   |
| ---------------------- | ----------------------------- |
| `Running`              | Running.                      |
| `Walking`              | Walking.                      |
| `Cycling`              | Cycling.                      |
| `Swimming`             | Swimming.                     |
| `StrengthTraining`     | Strength training.            |
| `Other(label: String)` | Any other activity, by label. |

#### WorkoutActivity.reportName

Returns the name an activity is reported under in diagnostics.

```kotlin
public fun reportName(activity: WorkoutActivity): String
```

| Name       | Type                                  | Description           |
| ---------- | ------------------------------------- | --------------------- |
| `activity` | [`WorkoutActivity`](#workoutactivity) | The activity to name. |

**Returns:** `"Running"`, `"Walking"`, `"Cycling"`, `"Swimming"`, `"Strength Training"`, or the `Other` label.

### Workout

One recorded workout.

```kotlin
public data class Workout(
    public val id: RecordId,
    public val interval: SampleInterval,
    public val activity: WorkoutActivity,
    public val activityTypeCode: Int,
    public val indoor: Boolean? = null,
    public val activeEnergyKilocalories: Double? = null,
    public val distanceMeters: Double? = null,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
    public val stats: WorkoutStats? = null,
    public val events: List<WorkoutEvent> = emptyList(),
    public val title: String? = null,
)
```

| Property                   | Type                                  | Description                                                                                                                                                                                                       |
| -------------------------- | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `interval`                 | [`SampleInterval`](#sampleinterval)   | When the workout started and ended.                                                                                                                                                                               |
| `activity`                 | [`WorkoutActivity`](#workoutactivity) | The interpreted activity.                                                                                                                                                                                         |
| `activityTypeCode`         | `Int`                                 | The store's own activity code, unchanged.                                                                                                                                                                         |
| `indoor`                   | `Boolean?`                            | Whether it happened indoors, or `null` where the store never said. Health Connect records no indoor flag of its own.                                                                                              |
| `activeEnergyKilocalories` | `Double?`                             | Active energy burned. `null` when there is no estimate, never faked as zero.                                                                                                                                      |
| `distanceMeters`           | `Double?`                             | Distance covered.                                                                                                                                                                                                 |
| `stats`                    | [`WorkoutStats?`](#workoutstats)      | Totals the store computed over the session, or `null`.                                                                                                                                                            |
| `events`                   | `List<WorkoutEvent>`                  | Laps, segments and markers, earliest first. Empty when there are none.                                                                                                                                            |
| `title`                    | `String?`                             | The name the writing app gave the session, from `ExerciseSessionRecord.title`, or `null` where it gave none. Never derived from `activity`. Read only: the upload does not send it. Available in 2.2.1 and later. |

### WorkoutStats

What a store totalled over a workout's window. Every field is optional.

```kotlin
public data class WorkoutStats(
    public val steps: Double? = null,
    public val basalEnergyKcal: Double? = null,
    public val swimmingStrokes: Double? = null,
    public val swimmingLaps: Double? = null,
    public val elevationGainM: Double? = null,
)
```

| Property          | Type      | Description                                                        |
| ----------------- | --------- | ------------------------------------------------------------------ |
| `steps`           | `Double?` | Steps taken in the session.                                        |
| `basalEnergyKcal` | `Double?` | Resting energy over the session. Never filled from Health Connect. |
| `swimmingStrokes` | `Double?` | Swimming strokes.                                                  |
| `swimmingLaps`    | `Double?` | Swimming laps.                                                     |
| `elevationGainM`  | `Double?` | Metres ascended.                                                   |
| `isEmpty`         | `Boolean` | `true` when no figure is set.                                      |

### WorkoutEvent

One annotation inside a workout.

```kotlin
public data class WorkoutEvent(
    public val kind: WorkoutEventKind,
    public val interval: SampleInterval,
)
```

| Property        | Type                                    | Description                                             |
| --------------- | --------------------------------------- | ------------------------------------------------------- |
| `kind`          | [`WorkoutEventKind`](#workouteventkind) | What the annotation is.                                 |
| `interval`      | [`SampleInterval`](#sampleinterval)     | When it applies. A marker's interval has equal ends.    |
| `CHRONOLOGICAL` | `Comparator<WorkoutEvent>`              | Companion. Orders events by start, then end, then kind. |

### WorkoutEventKind

What a workout was annotated with.

```kotlin
public enum class WorkoutEventKind(public val wire: String)
```

| Case      | Description                                 |
| --------- | ------------------------------------------- |
| `LAP`     | A lap.                                      |
| `SEGMENT` | A segment.                                  |
| `PAUSE`   | A pause. Health Connect never produces it.  |
| `RESUME`  | A resume. Health Connect never produces it. |
| `MARKER`  | A marker. Health Connect never produces it. |

### WorkoutIntensitySample

One reading from a workout's traces: speed, power or cadence.

```kotlin
public data class WorkoutIntensitySample(
    public val id: RecordId,
    public val time: Instant,
    public val metric: Metric,
    public val value: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property | Type      | Description                      |
| -------- | --------- | -------------------------------- |
| `time`   | `Instant` | When it was measured.            |
| `metric` | `Metric`  | The quantity, below.             |
| `value`  | `Double`  | The value, in the metric's unit. |

It carries no parent workout: Health Connect does not link these records to a session.

| `Metric` case | `wire`    | `unit`                                                   | `dataType`                 |
| ------------- | --------- | -------------------------------------------------------- | -------------------------- |
| `SPEED`       | `speed`   | `m/s`                                                    | `DataType.SPEED`           |
| `POWER`       | `power`   | `W`                                                      | `DataType.POWER`           |
| `CADENCE`     | `cadence` | `rpm`. Pedalling cadence only; step cadence is not read. | `DataType.CYCLING_CADENCE` |

`dataType` is the grant a read of the metric narrows to. It is a constructor value of `Metric` in 2.2.1 and later.

### WorkoutRoute

Where a workout went.

```kotlin
public data class WorkoutRoute(
    public val id: RecordId,
    public val workoutId: RecordId,
    public val interval: SampleInterval,
    public val points: List<RoutePoint>,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property    | Type                                | Description                                                                |
| ----------- | ----------------------------------- | -------------------------------------------------------------------------- |
| `workoutId` | [`RecordId`](#recordid)             | The `id` of the [`Workout`](#workout) this track belongs to. Never absent. |
| `interval`  | [`SampleInterval`](#sampleinterval) | The span of the track.                                                     |
| `points`    | `List<RoutePoint>`                  | Earliest first, at most one a second, at most `MAX_POINTS`.                |

| Companion member                                             | Description                                                                                                                |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| `const val MIN_SECONDS_BETWEEN_POINTS: Long = 1`             | The finest sampling a route carries.                                                                                       |
| `const val MAX_POINTS: Int = 5_000`                          | The most points one route carries.                                                                                         |
| `fun withinCaps(points: List<RoutePoint>): List<RoutePoint>` | Returns `points` thinned to one a second, then evenly decimated to `MAX_POINTS`. The first and last points always survive. |

### RoutePoint

One point on a workout's track.

```kotlin
public data class RoutePoint(
    public val time: Instant,
    public val latitude: Double,
    public val longitude: Double,
)
```

| Property    | Type      | Description                  |
| ----------- | --------- | ---------------------------- |
| `time`      | `Instant` | When the point was recorded. |
| `latitude`  | `Double`  | Latitude, in degrees.        |
| `longitude` | `Double`  | Longitude, in degrees.       |

### IntradaySample

One stretch of a day, for one of the quantities a day total is made of.

```kotlin
public data class IntradaySample(
    public val id: RecordId,
    public val interval: SampleInterval,
    public val metric: Metric,
    public val value: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property   | Type                                | Description                                                   |
| ---------- | ----------------------------------- | ------------------------------------------------------------- |
| `interval` | [`SampleInterval`](#sampleinterval) | The stretch the quantity accumulated over. Never zero-length. |
| `metric`   | `Metric`                            | The quantity, below.                                          |
| `value`    | `Double`                            | The value, in the metric's unit.                              |

| `Metric` case    | `wire`          | `unit`  | `dataType`                |
| ---------------- | --------------- | ------- | ------------------------- |
| `ACTIVE_ENERGY`  | `activeEnergy`  | `kcal`  | `DataType.ACTIVE_ENERGY`  |
| `DISTANCE`       | `distance`      | `m`     | `DataType.DISTANCE`       |
| `FLOORS_CLIMBED` | `floorsClimbed` | `count` | `DataType.FLOORS_CLIMBED` |

### DayTotal

One day's total for one metric, from the platform's own statistics engine.

```kotlin
public data class DayTotal(
    public val metric: Metric,
    public val interval: SampleInterval,
    public val value: Double,
    public val unit: String,
    public val timeZone: ZoneId? = null,
)
```

| Property   | Type                                | Description                        |
| ---------- | ----------------------------------- | ---------------------------------- |
| `metric`   | `Metric`                            | The metric, below.                 |
| `interval` | [`SampleInterval`](#sampleinterval) | The local day the total describes. |
| `value`    | `Double`                            | The total.                         |
| `unit`     | `String`                            | The unit.                          |

Terra prefers this total over its own sum of samples.

| `Metric` case              | `wire`                   | `unit`  | `dataType`      |
| -------------------------- | ------------------------ | ------- | --------------- |
| `STEPS`                    | `steps`                  | `count` | `STEPS`         |
| `DISTANCE_WALKING_RUNNING` | `distanceWalkingRunning` | `m`     | `DISTANCE`      |
| `DISTANCE_CYCLING`         | `distanceCycling`        | `m`     | `DISTANCE`      |
| `DISTANCE_SWIMMING`        | `distanceSwimming`       | `m`     | `DISTANCE`      |
| `DISTANCE_WHEELCHAIR`      | `distanceWheelchair`     | `m`     | `DISTANCE`      |
| `ACTIVE_ENERGY_BURNED`     | `activeEnergyBurned`     | `kcal`  | `ACTIVE_ENERGY` |
| `BASAL_ENERGY_BURNED`      | `basalEnergyBurned`      | `kcal`  | `null`          |
| `FLIGHTS_CLIMBED`          | `flightsClimbed`         | `count` | `null`          |
| `SWIMMING_STROKE_COUNT`    | `swimmingStrokeCount`    | `count` | `null`          |

`dataType` is the read grant a total rides on, or `null` where it has none of its own.

### DayTotalPolicy

What a day total counts, chosen once when you build the client.

```kotlin
public data class DayTotalPolicy(
    public val excludeUserEntered: Boolean = false,
)
```

| Property             | Type      | Description                                                                                                                                                |
| -------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `excludeUserEntered` | `Boolean` | Leaves typed-in steps out of the steps day total and out of `daily.steps`. Defaults to `false`, which counts everything Health Connect's aggregate merges. |

Pass it as `dayTotals` to [`Terra.invoke`](#terra.invoke), so the number on your screen and the number Terra stores agree. It applies to the Health Connect store only.

{% hint style="warning" %}
`excludeUserEntered` covers steps only, and approximates Health Connect's figure: the SDK sums each app's non-manual step records per local day and takes the largest app's sum. On a day where a phone and a watch each covered part of the time, it reports the larger part rather than both. A day whose only steps were typed in uploads a total of zero.
{% endhint %}

### DataType

One record type behind a permission, at the granularity a store grants.

```kotlin
public enum class DataType
```

| Case                      | Description                                                                                                                                      |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `HEART_RATE`              | Heart rate.                                                                                                                                      |
| `RESTING_HEART_RATE`      | Resting heart rate.                                                                                                                              |
| `STEPS`                   | Steps.                                                                                                                                           |
| `SLEEP_STAGE`             | Sleep stages.                                                                                                                                    |
| `WORKOUT`                 | Workouts.                                                                                                                                        |
| `ACTIVE_ENERGY`           | Active energy.                                                                                                                                   |
| `DISTANCE`                | Distance.                                                                                                                                        |
| `FLOORS_CLIMBED`          | Floors climbed.                                                                                                                                  |
| `NUTRITION`               | Health Connect's `NutritionRecord`, under `READ_NUTRITION`. Water is a separate grant.                                                           |
| `MENSTRUATION_FLOW`       | Menstrual flow, under `READ_MENSTRUATION`, which also covers the periods a flow day's `cycleStart` is read from.                                 |
| `HYDRATION`               | `HydrationRecord`, under `READ_HYDRATION`.                                                                                                       |
| `SPEED`                   | `SpeedRecord`, under `READ_SPEED`.                                                                                                               |
| `POWER`                   | `PowerRecord`, under `READ_POWER`.                                                                                                               |
| `CYCLING_CADENCE`         | `CyclingPedalingCadenceRecord`, under `READ_EXERCISE`.                                                                                           |
| `WEIGHT`                  | `WeightRecord`, under `READ_WEIGHT`.                                                                                                             |
| `HEIGHT`                  | `HeightRecord`, under `READ_HEIGHT`.                                                                                                             |
| `BODY_FAT`                | `BodyFatRecord`, under `READ_BODY_FAT`.                                                                                                          |
| `LEAN_BODY_MASS`          | `LeanBodyMassRecord`, under `READ_LEAN_BODY_MASS`.                                                                                               |
| `HEART_RATE_VARIABILITY`  | `HeartRateVariabilityRmssdRecord`, under `READ_HEART_RATE_VARIABILITY`.                                                                          |
| `VO2_MAX`                 | `Vo2MaxRecord`, under `READ_VO2_MAX`.                                                                                                            |
| `BLOOD_PRESSURE`          | `BloodPressureRecord`, under `READ_BLOOD_PRESSURE`.                                                                                              |
| `BLOOD_GLUCOSE`           | `BloodGlucoseRecord`, under `READ_BLOOD_GLUCOSE`.                                                                                                |
| `OXYGEN_SATURATION`       | `OxygenSaturationRecord`, under `READ_OXYGEN_SATURATION`.                                                                                        |
| `BODY_TEMPERATURE`        | Body, basal and skin temperature: three records under three grants, named as one. Allowing any one of them is a temperature read, not a refusal. |
| `RESPIRATORY_RATE`        | `RespiratoryRateRecord`, under `READ_RESPIRATORY_RATE`.                                                                                          |
| `INTERMENSTRUAL_BLEEDING` | `IntermenstrualBleedingRecord`, under `READ_INTERMENSTRUAL_BLEEDING`.                                                                            |
| `OVULATION_TEST`          | `OvulationTestRecord`, under `READ_OVULATION_TEST`.                                                                                              |
| `CERVICAL_MUCUS`          | `CervicalMucusRecord`, under `READ_CERVICAL_MUCUS`.                                                                                              |

The cases from `NUTRITION` on are available in 2.2.1 and later. A local read narrows its request to its own types, so a refused grant throws `TerraError.PermissionDenied` even where another type on the same upload route is allowed. An exhaustive `when` over `DataType` needs an arm for each case.

### BodyMeasurement

One body measurement: a weight, a height, a body fat fraction, a lean mass.

```kotlin
public data class BodyMeasurement(
    public val id: RecordId,
    public val time: Instant,
    public val metric: Metric,
    public val value: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property | Type      | Description                                              |
| -------- | --------- | -------------------------------------------------------- |
| `time`   | `Instant` | When it was measured.                                    |
| `metric` | `Metric`  | The measurement, below.                                  |
| `value`  | `Double`  | The value in the metric's `unit`, converted at the read. |

| `Metric` case          | `wire`               | `unit`                                           |
| ---------------------- | -------------------- | ------------------------------------------------ |
| `WEIGHT`               | `weight`             | `kg`                                             |
| `HEIGHT`               | `height`             | `cm`                                             |
| `BODY_FAT_PERCENTAGE`  | `bodyFatPercentage`  | `%`, as a fraction from 0 to 1                   |
| `LEAN_BODY_MASS`       | `leanBodyMass`       | `kg`                                             |
| `BONE_MASS`            | `boneMass`           | `kg`. Android only.                              |
| `BODY_WATER_MASS`      | `bodyWaterMass`      | `kg`, a mass and not a percentage. Android only. |
| `BASAL_METABOLIC_RATE` | `basalMetabolicRate` | `kcal/day`. Android only.                        |

In 2.2.1 and later, `Metric.dataType: DataType?` returns the grant a local read of the metric narrows to: `WEIGHT`, `HEIGHT`, `BODY_FAT` or `LEAN_BODY_MASS`, and `null` for the three [`BodyMetrics.readings`](#bodymetrics.readings) does not return.

### BloodPressureSample

One blood-pressure reading, both values together.

```kotlin
public data class BloodPressureSample(
    public val id: RecordId,
    public val time: Instant,
    public val systolicMillimetersOfMercury: Double,
    public val diastolicMillimetersOfMercury: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property                        | Type      | Description                  |
| ------------------------------- | --------- | ---------------------------- |
| `time`                          | `Instant` | When it was measured.        |
| `systolicMillimetersOfMercury`  | `Double`  | Systolic pressure, in mmHg.  |
| `diastolicMillimetersOfMercury` | `Double`  | Diastolic pressure, in mmHg. |

### BloodGlucoseSample

One glucose reading, in the unit the store reported it in.

```kotlin
public data class BloodGlucoseSample(
    public val id: RecordId,
    public val time: Instant,
    public val value: Double,
    public val unit: BloodGlucoseUnit,
    public val mealTime: MealTime? = null,
    public val specimen: Specimen? = null,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property   | Type                                    | Description                                                                                                                              |
| ---------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `time`     | `Instant`                               | When it was measured.                                                                                                                    |
| `value`    | `Double`                                | The reading, in `unit`. Not converted on the device.                                                                                     |
| `unit`     | [`BloodGlucoseUnit`](#bloodglucoseunit) | The unit.                                                                                                                                |
| `mealTime` | `MealTime?`                             | `PREPRANDIAL`, `POSTPRANDIAL` or `UNKNOWN` (the store said nothing about a meal), or `null`.                                             |
| `specimen` | `Specimen?`                             | What was sampled: `CAPILLARY`, `INTERSTITIAL` (a continuous monitor), `PLASMA`, `SERUM`, `TEARS`, `WHOLE_BLOOD` or `UNKNOWN`, or `null`. |

`MealTime` and `Specimen` are nested enums, each with a `wire: String` spelling.

### BloodGlucoseUnit

The unit a glucose reading was reported in.

```kotlin
public enum class BloodGlucoseUnit(public val wire: String)
```

| Case                       | Description |
| -------------------------- | ----------- |
| `MILLIGRAMS_PER_DECILITRE` | `mg/dL`.    |
| `MILLIMOLES_PER_LITRE`     | `mmol/L`.   |

### OxygenSaturationSample

One oxygen saturation reading, as a fraction.

```kotlin
public data class OxygenSaturationSample(
    public val id: RecordId,
    public val time: Instant,
    public val fraction: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property   | Type      | Description                                                                       |
| ---------- | --------- | --------------------------------------------------------------------------------- |
| `time`     | `Instant` | When it was measured.                                                             |
| `fraction` | `Double`  | The saturation, for example `0.97`. Health Connect's `97` is divided at the read. |

### BodyTemperatureSample

One temperature reading, absolute or relative depending on the metric.

```kotlin
public data class BodyTemperatureSample(
    public val id: RecordId,
    public val interval: SampleInterval,
    public val metric: Metric,
    public val celsius: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property   | Type                                | Description                                                                                                         |
| ---------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `interval` | [`SampleInterval`](#sampleinterval) | When it was measured. Equal ends for `BODY` and `BASAL`.                                                            |
| `metric`   | `Metric`                            | `BODY`, `BASAL` or `SKIN`.                                                                                          |
| `celsius`  | `Double`                            | Degrees Celsius: absolute for `BODY` and `BASAL`, a difference from a baseline for `SKIN`, which is often negative. |

### HeartRateVariabilitySample

One heart-rate-variability reading, as RMSSD.

```kotlin
public data class HeartRateVariabilitySample(
    public val id: RecordId,
    public val time: Instant,
    public val rmssdMilliseconds: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property            | Type      | Description                                                                                             |
| ------------------- | --------- | ------------------------------------------------------------------------------------------------------- |
| `time`              | `Instant` | When it was measured.                                                                                   |
| `rmssdMilliseconds` | `Double`  | RMSSD, in milliseconds. Health Connect records RMSSD only, where iOS records SDNN: never merge the two. |

### RespiratoryRateSample

One respiratory-rate reading.

```kotlin
public data class RespiratoryRateSample(
    public val id: RecordId,
    public val time: Instant,
    public val breathsPerMinute: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property           | Type      | Description           |
| ------------------ | --------- | --------------------- |
| `time`             | `Instant` | When it was measured. |
| `breathsPerMinute` | `Double`  | Breaths per minute.   |

### Vo2MaxSample

One VO2 max figure.

```kotlin
public data class Vo2MaxSample(
    public val id: RecordId,
    public val time: Instant,
    public val millilitresPerKilogramPerMinute: Double,
    public val testType: TestType? = null,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property                          | Type        | Description                                                                                                                        |
| --------------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `time`                            | `Instant`   | When it was measured.                                                                                                              |
| `millilitresPerKilogramPerMinute` | `Double`    | VO2 max, in mL/kg/min.                                                                                                             |
| `testType`                        | `TestType?` | `MAX_EXERCISE`, `PREDICTED_SUB_MAX_EXERCISE` or `PREDICTED_NON_EXERCISE`, or `null` where the store's method maps to none of them. |

### Nutrient

One nutrient a meal can carry, with its fixed unit.

```kotlin
public enum class Nutrient(public val wire: String, public val unit: String)
```

| Cases                                                                                                                                                                                                                                                                                                                                                              | `unit` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------ |
| `ENERGY_CONSUMED`                                                                                                                                                                                                                                                                                                                                                  | `kcal` |
| `PROTEIN`, `CARBOHYDRATES`, `FAT_TOTAL`, `FAT_SATURATED`, `FAT_MONOUNSATURATED`, `FAT_POLYUNSATURATED`, `SUGAR`, `FIBER`                                                                                                                                                                                                                                           | `g`    |
| `CHOLESTEROL`, `SODIUM`, `POTASSIUM`, `CALCIUM`, `IRON`, `MAGNESIUM`, `ZINC`, `PHOSPHORUS`, `IODINE`, `MANGANESE`, `MOLYBDENUM`, `SELENIUM`, `COPPER`, `CHROMIUM`, `CHLORIDE`, `CAFFEINE`, `VITAMIN_A`, `VITAMIN_C`, `VITAMIN_D`, `VITAMIN_E`, `VITAMIN_K`, `VITAMIN_B6`, `VITAMIN_B12`, `THIAMIN`, `RIBOFLAVIN`, `NIACIN`, `FOLATE`, `BIOTIN`, `PANTOTHENIC_ACID` | `mg`   |

`wire` is the camel-case name, for example `fatTotal`. Micronutrients are always milligrams, including those labels print in micrograms. Water is not a nutrient here; it is a [`HydrationSample`](#hydrationsample).

### MealSample

One logged meal and what it contained.

```kotlin
public data class MealSample(
    public val id: RecordId,
    public val interval: SampleInterval,
    public val mealType: MealType,
    public val name: String? = null,
    public val nutrients: Map<Nutrient, Double>,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property    | Type                                | Description                                                                           |
| ----------- | ----------------------------------- | ------------------------------------------------------------------------------------- |
| `interval`  | [`SampleInterval`](#sampleinterval) | When it was eaten.                                                                    |
| `mealType`  | `MealType`                          | `BREAKFAST`, `LUNCH`, `DINNER`, `SNACK` or `UNKNOWN` (the store did not say).         |
| `name`      | `String?`                           | What the store called it.                                                             |
| `nutrients` | `Map<Nutrient, Double>`             | Each recorded [`Nutrient`](#nutrient), in its unit. A missing key was never recorded. |

### HydrationSample

One drink.

```kotlin
public data class HydrationSample(
    public val id: RecordId,
    public val interval: SampleInterval,
    public val millilitres: Double,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property      | Type                                | Description        |
| ------------- | ----------------------------------- | ------------------ |
| `interval`    | [`SampleInterval`](#sampleinterval) | When it was drunk. |
| `millilitres` | `Double`                            | The volume, in mL. |

### MenstruationFlowSample

One logged day of a period.

```kotlin
public data class MenstruationFlowSample(
    public val id: RecordId,
    public val interval: SampleInterval,
    public val flow: Flow,
    public val cycleStart: Boolean,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property     | Type                                | Description                                                                                |
| ------------ | ----------------------------------- | ------------------------------------------------------------------------------------------ |
| `interval`   | [`SampleInterval`](#sampleinterval) | Local midnight to the next local midnight, in `timeZone`.                                  |
| `flow`       | `Flow`                              | `UNSPECIFIED`, `LIGHT`, `MEDIUM`, `HEAVY` or `NONE`. Health Connect never produces `NONE`. |
| `cycleStart` | `Boolean`                           | Whether this is the first day of a period, from Health Connect's period record.            |

### MenstruationEventSample

One logged cycle event that is not a flow day.

```kotlin
public data class MenstruationEventSample(
    public val id: RecordId,
    public val time: Instant,
    public val event: Event,
    public val storeIdentifier: String,
    public val value: Value? = null,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property          | Type      | Description                                                                         |
| ----------------- | --------- | ----------------------------------------------------------------------------------- |
| `time`            | `Instant` | When it was logged.                                                                 |
| `event`           | `Event`   | `INTERMENSTRUAL_BLEEDING`, `OVULATION_TEST`, `CERVICAL_MUCUS` or `SEXUAL_ACTIVITY`. |
| `storeIdentifier` | `String`  | The store's own name for the record type, for example `OvulationTestRecord`.        |
| `value`           | `Value?`  | The result, or `null` for a flag event such as intermenstrual bleeding.             |

`Value` cases: `NEGATIVE`, `POSITIVE`, `HIGH`, `INDETERMINATE`, `LUTEINIZING_HORMONE_SURGE` (iOS only), `DRY`, `STICKY`, `CREAMY`, `WATERY`, `EGG_WHITE`, `UNUSUAL`, `PROTECTED`, `UNPROTECTED`, `UNSPECIFIED`. `Event` and `Value` each carry a `wire: String` spelling.

In 2.2.1 and later, `Event.dataType: DataType?` returns the grant a local read of the event narrows to, and `null` for `SEXUAL_ACTIVITY`, which [`MenstruationMetrics.events`](#menstruationmetrics.events) does not return.

### MenstruationFlowDay

One logged day of a period, as [`MenstruationMetrics.flow`](#menstruationmetrics.flow) returns it. Available in 2.2.1 and later.

```kotlin
public typealias MenstruationFlowDay = MenstruationFlowSample
```

An alias of [`MenstruationFlowSample`](#menstruationflowsample): the read and the upload see the same day with the same fields. Apple's type has the same name.

### MenstrualEvent

One cycle event, as [`MenstruationMetrics.events`](#menstruationmetrics.events) returns it. Available in 2.2.1 and later.

```kotlin
public typealias MenstrualEvent = MenstruationEventSample
```

An alias of [`MenstruationEventSample`](#menstruationeventsample). Apple's type has the same name.

### DietaryQuantity

One nutrient of one logged meal, as [`NutritionMetrics.quantities`](#nutritionmetrics.quantities) returns it. Available in 2.2.1 and later.

```kotlin
public data class DietaryQuantity(
    public val id: RecordId,
    public val nutrient: Nutrient,
    public val value: Double,
    public val interval: SampleInterval,
    public val mealType: MealSample.MealType = MealSample.MealType.UNKNOWN,
    public val name: String? = null,
    public val foodCorrelationId: RecordId? = null,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property            | Type                                | Description                                                                                                                                                                 |
| ------------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                | [`RecordId`](#recordid)             | This quantity's own ID: the meal's record ID with the nutrient folded in, stable across reads of the same record. `nutrition.delete` does not accept it.                    |
| `nutrient`          | [`Nutrient`](#nutrient)             | The nutrient.                                                                                                                                                               |
| `value`             | `Double`                            | The amount, in `nutrient.unit`.                                                                                                                                             |
| `interval`          | [`SampleInterval`](#sampleinterval) | When the meal was eaten.                                                                                                                                                    |
| `mealType`          | `MealSample.MealType`               | What the store said the meal was. `UNKNOWN` means it did not say.                                                                                                           |
| `name`              | `String?`                           | The food's name, from `NutritionRecord.name`, where the store carries one.                                                                                                  |
| `foodCorrelationId` | [`RecordId?`](#recordid)            | The record this quantity was read from, shared by every quantity of the same meal. Always set on Android. It is the ID `nutrition.delete` takes for a meal your app logged. |

The field names match Apple's `DietaryQuantity`, so the React Native wrapper reads one type on both platforms.

### BodyReading

One body reading, as [`BodyMetrics.readings`](#bodymetrics.readings) returns it. Available in 2.2.1 and later.

```kotlin
public data class BodyReading(
    public val id: RecordId,
    public val kind: Kind,
    public val interval: SampleInterval,
    public val source: SampleSource,
    public val userEntered: Boolean = false,
    public val timeZone: ZoneId? = null,
)
```

| Property   | Type                                | Description                                                                           |
| ---------- | ----------------------------------- | ------------------------------------------------------------------------------------- |
| `kind`     | `Kind`                              | What was measured, below. The case fixes the unit.                                    |
| `interval` | [`SampleInterval`](#sampleinterval) | When. A point reading has equal start and end. Only skin temperature spans a stretch. |

It is built from the per-kind samples the upload reads, such as [`BodyMeasurement`](#bodymeasurement) and [`BloodPressureSample`](#bloodpressuresample), which keep their own types.

`Kind` is a sealed interface:

| Case                                                                                                                                                | Description                                                                        |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `Measurement(metric: BodyMeasurement.Metric, value: Double)`                                                                                        | Weight, height, body fat or lean mass, in `metric.unit`.                           |
| `BloodPressure(systolicMillimetersOfMercury: Double, diastolicMillimetersOfMercury: Double)`                                                        | A blood pressure, in mmHg.                                                         |
| `BloodGlucose(value: Double, unit: BloodGlucoseUnit, mealTime: BloodGlucoseSample.MealTime? = null, specimen: BloodGlucoseSample.Specimen? = null)` | A blood glucose reading, in the unit the store reported. Never converted.          |
| `OxygenSaturation(fraction: Double)`                                                                                                                | Oxygen saturation, as a fraction from 0 to 1.                                      |
| `Temperature(metric: BodyTemperatureSample.Metric, celsius: Double)`                                                                                | A temperature. Absolute for body and basal, a difference from a baseline for skin. |
| `HeartRateVariability(rmssdMilliseconds: Double)`                                                                                                   | RMSSD, the only statistic Health Connect records.                                  |
| `RespiratoryRate(breathsPerMinute: Double)`                                                                                                         | Breaths per minute.                                                                |
| `Vo2Max(millilitresPerKilogramPerMinute: Double, testType: Vo2MaxSample.TestType? = null)`                                                          | VO2 max, in mL/kg/min.                                                             |

## Extension points

The types in this section are the SDK's adapters: the Terra backend, the OS health store, the on-device storage and the signing key. `Terra(context, devId = ..., tokenProvider = ...)` wires the production adapters for you, so most apps never name any of them. They are public so you can drive a whole client against fakes in your own tests (see [Testing](#testing)) and so the Samsung add-on can plug in a second store.

Members marked `@TerraSeam` need `@OptIn(TerraSeam::class)`. The opt-in level is `ERROR`: the compiler refuses a call without it. They are parts for a store author or a test, not API your app calls.

### TerraBackend

The SDK's side of the Terra HTTP API.

```kotlin
public interface TerraBackend
```

[HttpBackend](#httpbackend) is the production implementation. The SDK never sends a reference id: identity is bound when your backend mints the token.

#### TerraBackend.link

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

```kotlin
public suspend fun link(request: LinkRequest): LinkGrant
```

| Name      | Type                          | Description                                |
| --------- | ----------------------------- | ------------------------------------------ |
| `request` | [`LinkRequest`](#linkrequest) | The token and the device identity to link. |

**Returns:** the [`LinkGrant`](#linkgrant) for the new connection.

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

#### TerraBackend.upload

Uploads one signed batch.

```kotlin
public suspend fun upload(request: UploadRequest): UploadResult
```

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

**Returns:** the [`UploadResult`](#uploadresult) Terra answered with.

Returning normally means Terra accepted the batch, not that it stored it. A batch for a data type you have disabled is accepted and dropped. The request carries no bearer credential: the signature is the authentication.

#### TerraBackend.revokeDeviceKey

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

```kotlin
public suspend fun revokeDeviceKey(request: RevokeDeviceKeyRequest)
```

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

It revokes only the key that signed it, so the person's other phones keep uploading under their own keys. When no live key is left on a connection an SDK link created, Terra ends the connection.

#### TerraBackend.pollBackfills

Asks Terra which backfill windows it wants this device to send.

```kotlin
public suspend fun pollBackfills(request: BackfillPollRequest): List<BackfillDirective>
```

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

**Returns:** the windows Terra wants, or an empty list when the queue is drained.

The read is non-destructive: a window stays leased to this device until [`acknowledgeBackfills`](#terrabackend.acknowledgebackfills) names it, and lapses back otherwise.

#### TerraBackend.acknowledgeBackfills

Tells Terra the device now owes the named windows, so it may release their leases.

```kotlin
public suspend fun acknowledgeBackfills(request: BackfillAckRequest)
```

| Name      | Type                                        | Description                                              |
| --------- | ------------------------------------------- | -------------------------------------------------------- |
| `request` | [`BackfillAckRequest`](#backfillackrequest) | The signed acknowledgement naming the window references. |

#### TerraBackend.sendDiagnostics

Sends a redacted support report, signed by the connection key.

```kotlin
public suspend fun sendDiagnostics(request: DiagnosticsRequest)
```

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

#### TerraBackend.sdkInit

Asks Terra which connections share this device's key and which routes those customers selected. Used in [`DevIdMode.MULTIPLE`](#devidmode). Available in 2.3.0 and later.

```kotlin
public suspend fun sdkInit(request: SdkInitRequest): SdkInitGrant
```

| Name      | Type                                | Description         |
| --------- | ----------------------------------- | ------------------- |
| `request` | [`SdkInitRequest`](#sdkinitrequest) | The signed request. |

**Returns:** an [`SdkInitGrant`](#sdkinitgrant). The default implementation throws `TerraError.Network(NetworkFailure.ServerError(404))`, which the SDK reads as "not known" and falls back to the selections each link returned, so an existing `TerraBackend` conformance compiles unchanged.

In 2.3.0 and later, [`UploadRequest`](#uploadrequest), [`RevokeDeviceKeyRequest`](#revokedevicekeyrequest), [`BackfillPollRequest`](#backfillpollrequest), [`BackfillAckRequest`](#backfillackrequest), [`DiagnosticsRequest`](#diagnosticsrequest) and `SdkInitRequest` carry `public val target: String? = null`: the one connection of a shared key the request is for, by Terra `user_id`, or `null` for every connection the key is registered on. Only `DevIdMode.MULTIPLE` sets it. It is inside the signature, and [`HttpBackend`](#httpbackend) sends it as the `target_user_id` query parameter.

### SdkInitRequest

A signed request for Terra's view of the connections sharing this device's key. Available in 2.3.0 and later.

```kotlin
public class SdkInitRequest(
    public val source: Source,
    public val providerUserId: String,
    public val timestampMillis: Long,
    public val signature: String,
    public val target: String? = null,
)
```

`SdkInitRequest.SIGNED_LABEL` is `"init"`, and `SdkInitRequest.BODY` is an empty `ByteArray`.

### SdkInitGrant

What Terra answers to [`sdkInit`](#terrabackend.sdkinit). Available in 2.3.0 and later.

```kotlin
public data class SdkInitGrant(
    public val userIds: List<String>,
    public val dataTypes: List<UploadDataType>,
)
```

| Property    | Type                   | Description                                                              |
| ----------- | ---------------------- | ------------------------------------------------------------------------ |
| `userIds`   | `List<String>`         | The Terra `user_id` of every connection registered on this device's key. |
| `dataTypes` | `List<UploadDataType>` | The union of the routes those customers selected.                        |

### KeyPossession

A device key's signature over a link token, which proves the device holds the key a later customer's link registers. Available in 2.3.0 and later.

```kotlin
public data class KeyPossession(
    public val timestampMillis: Long,
    public val signature: String,
)
```

### PartialDeliveryFailure

Thrown by [`TerraBackend.upload`](#terrabackend.upload) when Terra delivered a shared key's upload to some of its connections and not to the ones named. Available in 2.3.0 and later.

```kotlin
public class PartialDeliveryFailure(public val failedUserIds: List<String>) : Exception
```

It is not a `TerraError` and never leaves the SDK: the SDK queues a targeted retry for each named connection.

### HttpBackend

The production [`TerraBackend`](#terrabackend), talking to Terra's v2 API over OkHttp.

```kotlin
public class HttpBackend internal constructor(
    baseUrl: String,
    private val client: OkHttpClient = defaultClient,
    private val io: CoroutineDispatcher = Dispatchers.IO,
) : TerraBackend
```

The primary constructor is `internal`; use the public [constructor](#httpbackend.constructor).

It maps each request onto one HTTP call and each HTTP failure onto a `TerraError`. Retries, fresh tokens and persistence are decided above it.

#### HttpBackend.constructor

Creates the production backend against a base URL.

```kotlin
public constructor(baseUrl: String) : this(baseUrl, defaultClient)
```

| Name      | Type     | Description                                                    |
| --------- | -------- | -------------------------------------------------------------- |
| `baseUrl` | `String` | The Terra API base URL, for example `https://api.tryterra.co`. |

This is the only public constructor, and it names no OkHttp type, so your build does not need OkHttp to call it.

How HTTP failures map to errors:

| Error                                                  | When                                                                                                   |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `TerraError.TokenRejected`                             | `link` gets a 401.                                                                                     |
| `TerraError.UserLimitReached`                          | `link` gets a 402.                                                                                     |
| `TerraError.LinkRefused`                               | `link` gets a 409 naming a permanent device-key refusal. Available in 2.3.0 and later.                 |
| `TerraError.LinkConflict`                              | `link` gets any other 409.                                                                             |
| `TerraError.ClockSkewed`                               | A signed request gets a 401 and the server's `Date` is more than 15 minutes from the signed timestamp. |
| `TerraError.SignatureRejected`                         | A signed request gets a 401 and the clocks agree.                                                      |
| `TerraError.UpgradeRequired`                           | Any request gets a 426.                                                                                |
| `TerraError.Network(NetworkFailure.Throttled)`         | Any request gets a 429. Carries the `Retry-After` seconds.                                             |
| `TerraError.Network(NetworkFailure.ServerError)`       | Any other non-2xx status, including 413 and a signed 401 with no `Date` header.                        |
| `TerraError.Network(NetworkFailure.Transport)`         | The call failed before a response arrived.                                                             |
| `TerraError.Network(NetworkFailure.MalformedResponse)` | A response body could not be read.                                                                     |

#### HttpBackend.DEFAULT\_TIMEOUT\_SECONDS

The request timeout, kept shorter than a background slot.

```kotlin
public const val DEFAULT_TIMEOUT_SECONDS: Long = 8
```

### LinkRequest

Everything Terra needs to spend a link token.

```kotlin
public data class LinkRequest(
    public val token: String,
    public val source: Source,
    public val devId: String,
    public val providerUserId: String,
    public val devicePublicKey: String,
    public val appIdentifier: String? = null,
    public val possession: KeyPossession? = null,
)
```

| Property          | Type                               | Description                                                                                                                                                                                                                     |
| ----------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `token`           | `String`                           | The one-shot grant, already bound server-side to your account 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 account from the token.                                                                                                       |
| `providerUserId`  | `String`                           | This installation's stable identity, which Terra uses to recognise a returning device.                                                                                                                                          |
| `devicePublicKey` | `String`                           | The connection's public signing key, base64 DER SubjectPublicKeyInfo.                                                                                                                                                           |
| `appIdentifier`   | `String?`                          | The app redeeming the token, which is how Terra tells a reinstall from a sibling app. Optional. Defaults to `null`.                                                                                                             |
| `possession`      | [`KeyPossession?`](#keypossession) | In `DevIdMode.MULTIPLE`, the existing device key's signature over the token, for every customer after the first. Optional. Defaults to `null`. Available in 2.3.0 and later. `LinkRequest.POSSESSION_LABEL` is `"auth.redeem"`. |

### LinkGrant

What Terra returns when a link token is spent.

```kotlin
public data class LinkGrant(
    public val userId: String,
    public val dataTypes: List<UploadDataType>? = null,
)
```

| Property    | Type                    | Description                                                                                                    |
| ----------- | ----------------------- | -------------------------------------------------------------------------------------------------------------- |
| `userId`    | `String`                | The Terra `user_id` of the connection.                                                                         |
| `dataTypes` | `List<UploadDataType>?` | The routes the customer selected, when Terra says. Optional. Defaults to `null`. Available in 2.3.0 and later. |

### UploadContentEncoding

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

```kotlin
public enum class UploadContentEncoding(public val header: String)
```

| Case   | Description                 |
| ------ | --------------------------- |
| `GZIP` | Gzip. `header` is `"gzip"`. |

### UploadRequest

One signed batch of health data.

```kotlin
public class UploadRequest(
    public val source: Source,
    public val dataType: UploadDataType,
    public val providerUserId: String,
    public val timestampMillis: Long,
    public val body: ByteArray,
    public val signature: String,
    public val recordCount: Int,
    public val contentEncoding: UploadContentEncoding? = null,
)
```

Not a data class, because `body` is a `ByteArray` and a generated `equals` would compare references.

| 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 the connection is filed under.                                                                                                                   |
| `timestampMillis` | `Long`                                             | Unix milliseconds, inside the signature. Terra rejects anything outside a 15-minute window.                                                                   |
| `body`            | `ByteArray`                                        | The encoded [`UploadEnvelope`](#uploadenvelope).                                                                                                              |
| `signature`       | `String`                                           | Base64 DER ECDSA signature over the source, the data type, the identity, the timestamp and `body`.                                                            |
| `recordCount`     | `Int`                                              | How many records `body` encodes.                                                                                                                              |
| `contentEncoding` | [`UploadContentEncoding?`](#uploadcontentencoding) | The coding to apply to `body` before sending, or `null` to send it as it is. The signature always covers the uncompressed body. Optional. Defaults to `null`. |

### UploadResult

What Terra said about one batch.

```kotlin
public data class UploadResult(public val accepted: Int)
```

| Property   | Type  | Description                                                                                              |
| ---------- | ----- | -------------------------------------------------------------------------------------------------------- |
| `accepted` | `Int` | The number of records in the batch Terra accepted. `HttpBackend` sets it to the request's `recordCount`. |

### RevokeDeviceKeyRequest

A signed request to revoke the signing key it is signed with.

```kotlin
public class RevokeDeviceKeyRequest(
    public val source: Source,
    public val providerUserId: String,
    public val timestampMillis: Long,
    public val body: ByteArray,
    public val signature: String,
)
```

| Property          | Type                | Description                                                                                        |
| ----------------- | ------------------- | -------------------------------------------------------------------------------------------------- |
| `source`          | [`Source`](#source) | The source of the link being ended.                                                                |
| `providerUserId`  | `String`            | The identity the connection is filed under.                                                        |
| `timestampMillis` | `Long`              | Unix milliseconds, inside the signature.                                                           |
| `body`            | `ByteArray`         | Names the public half of the key being revoked. Built with [`body`](#revokedevicekeyrequest.body). |
| `signature`       | `String`            | Base64 DER ECDSA signature over the request.                                                       |

#### RevokeDeviceKeyRequest.SIGNED\_LABEL

The label that sits where an upload's data type sits inside the signed message.

```kotlin
public const val SIGNED_LABEL: String = "disconnect"
```

It differs from every upload type, so a captured upload cannot authorise a revocation and a captured revocation cannot be replayed as data.

#### RevokeDeviceKeyRequest.body

Returns the bytes a revocation signs over, naming the key being revoked.

```kotlin
public fun body(publicKeyBase64DER: String): ByteArray
```

| Name                 | Type     | Description                                                           |
| -------------------- | -------- | --------------------------------------------------------------------- |
| `publicKeyBase64DER` | `String` | The public key, in the base64 DER encoding the link registered it in. |

**Returns:** the UTF-8 JSON `{"device_public_key":"<key>","reason":"disconnect"}`.

In 2.3.0 and later, `public fun unlinkBody(publicKeyBase64DER: String, userId: String): ByteArray` returns the body a [`LinkedDevIds.unlink`](#linkeddevids.unlink) signs: the same JSON with `"reason":"unlink"` and the customer's `user_id`.

### BackfillPollRequest

A signed ask for the backfill windows Terra wants this device to send.

```kotlin
public class BackfillPollRequest(
    public val source: Source,
    public val providerUserId: String,
    public val timestampMillis: Long,
    public val signature: String,
)
```

| Property          | Type                | Description                                  |
| ----------------- | ------------------- | -------------------------------------------- |
| `source`          | [`Source`](#source) | The source the windows are for.              |
| `providerUserId`  | `String`            | The identity the connection is filed under.  |
| `timestampMillis` | `Long`              | Unix milliseconds, inside the signature.     |
| `signature`       | `String`            | Base64 DER ECDSA signature over the request. |

#### BackfillPollRequest.SIGNED\_LABEL

The label that sits where an upload's data type sits inside the signed message.

```kotlin
public const val SIGNED_LABEL: String = "backfills"
```

#### BackfillPollRequest.BODY

The empty body a poll signs over.

```kotlin
public val BODY: ByteArray = ByteArray(0)
```

### BackfillDirective

One window Terra has asked this device to send.

```kotlin
public data class BackfillDirective(
    public val dataType: String,
    public val start: Instant,
    public val end: Instant,
    public val reference: String,
)
```

| Property    | Type      | Description                                                                                                                                                                            |
| ----------- | --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dataType`  | `String`  | The server's data category name, such as `body` or `daily`. It is the server's vocabulary, not [`UploadDataType`](#uploaddatatype), and can name categories this SDK has no route for. |
| `start`     | `Instant` | The start of the window.                                                                                                                                                               |
| `end`       | `Instant` | The end of the window.                                                                                                                                                                 |
| `reference` | `String`  | The server's name for the lease, which an acknowledgement names. A directive without one is refused by the decoder.                                                                    |

### BackfillAckRequest

A signed acknowledgement that the device has taken responsibility for some windows.

```kotlin
public class BackfillAckRequest(
    public val source: Source,
    public val providerUserId: String,
    public val timestampMillis: Long,
    public val body: ByteArray,
    public val signature: String,
    public val references: List<String>,
)
```

The SDK sends it only after the windows are on disk, never before.

| Property          | Type                | Description                                   |
| ----------------- | ------------------- | --------------------------------------------- |
| `source`          | [`Source`](#source) | The source the windows are for.               |
| `providerUserId`  | `String`            | The identity the connection is filed under.   |
| `timestampMillis` | `Long`              | Unix milliseconds, inside the signature.      |
| `body`            | `ByteArray`         | `{"references":[...]}`, inside the signature. |
| `signature`       | `String`            | Base64 DER ECDSA signature over the request.  |
| `references`      | `List<String>`      | The references `body` encodes.                |

#### BackfillAckRequest.SIGNED\_LABEL

The label that sits where an upload's data type sits inside the signed message.

```kotlin
public const val SIGNED_LABEL: String = "backfills.ack"
```

### DiagnosticsRequest

A signed support report.

```kotlin
public class DiagnosticsRequest(
    public val source: Source,
    public val providerUserId: String,
    public val timestampMillis: Long,
    public val body: ByteArray,
    public val signature: String,
)
```

| Property          | Type                | Description                                                                 |
| ----------------- | ------------------- | --------------------------------------------------------------------------- |
| `source`          | [`Source`](#source) | The source the report is about.                                             |
| `providerUserId`  | `String`            | The identity the connection is filed under.                                 |
| `timestampMillis` | `Long`              | Unix milliseconds, inside the signature.                                    |
| `body`            | `ByteArray`         | A diagnostics envelope around a redacted [`SupportReport`](#supportreport). |
| `signature`       | `String`            | Base64 DER ECDSA signature over the request.                                |

#### DiagnosticsRequest.SIGNED\_LABEL

The label that sits where an upload's data type sits inside the signed message.

```kotlin
public const val SIGNED_LABEL: String = "diagnostics"
```

### SignedMessage

Builds the exact bytes Terra's ingest verifies a signature against.

```kotlin
public object SignedMessage
```

#### SignedMessage.build

Returns the preimage for one signed request.

```kotlin
public fun build(
    resource: String,
    dataType: String,
    providerUserId: String,
    timestampMillis: Long,
    body: ByteArray,
    target: String? = null,
): ByteArray
```

| Name              | Type        | Description                                                                                                                                                                     |
| ----------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `resource`        | `String`    | The provider resource, exactly as it travels.                                                                                                                                   |
| `dataType`        | `String`    | The route, or a request's `SIGNED_LABEL`.                                                                                                                                       |
| `providerUserId`  | `String`    | The identity the connection is filed under, unnormalised.                                                                                                                       |
| `timestampMillis` | `Long`      | Unix milliseconds, rendered as plain decimal.                                                                                                                                   |
| `body`            | `ByteArray` | The request body.                                                                                                                                                               |
| `target`          | `String?`   | The one connection of a shared key the request is for, or `null`. When set, the label slot reads `dataType@target`. Optional. Defaults to `null`. Available in 2.3.0 and later. |

**Returns:** `resource \n dataType \n providerUserId \n timestamp \n` as UTF-8, followed by the body bytes.

`SignedMessage.SEPARATOR` is `'@'`, and `SignedMessage.isNameable(target: String): Boolean` answers whether a target holds no line break. Both are available in 2.3.0 and later.

### HealthStore

The OS health store behind one interface: Health Connect in the core SDK, Samsung Health in the add-on.

```kotlin
public interface HealthStore
```

[`HealthConnectStore`](#healthconnectstore) and [`SamsungHealthStore`](#samsunghealthstore) implement it. The testkit's [`FakeHealthStore`](#fakehealthstore) implements it on a plain JVM.

{% hint style="warning" %}
In 2.3.0 and later, [`readScopes`](#healthstore.readscopes), both [`dayTotals`](#healthstore.daytotals) overloads and [`changes`](#healthstore.changes) take a `requestedTypes` parameter that defaults to `null`. Callers are unaffected, but an app that implements its own `HealthStore` must declare the parameter in its overrides to compile.
{% endhint %}

#### HealthStore.source

The source this store is, as a caller names it in `connect`.

```kotlin
public val source: Source
```

#### HealthStore.wireProvider

The provider label Terra's ingest route is keyed on, for example `health_connect` or `samsung`.

```kotlin
public val wireProvider: String
```

#### HealthStore.capabilities

What this store can do, fixed per store and per SDK version.

```kotlin
public val capabilities: StoreCapabilities
```

#### HealthStore.historyWindowDays

How far back this store serves without a history grant, in calendar days.

```kotlin
public val historyWindowDays: Long
```

#### HealthStore.appliesDayTotalPolicy

Whether [`dayTotals`](#healthstore.daytotals) honours a [`DayTotalPolicy`](#daytotalpolicy).

```kotlin
public val appliesDayTotalPolicy: Boolean get() = false
```

When `false`, the client counts everything for this store, in `daily.steps` too, so the screen and the upload agree. Health Connect's is `true`; Samsung's is `false`.

#### HealthStore.routedBy

Returns the routes a grant on a category feeds on this store, before Terra's converter gate.

```kotlin
public fun routedBy(category: DataCategory): List<UploadDataType>
```

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

**Returns:** every route the category's record types travel on. A category is not a route: `SLEEP` grants respiratory rate on Health Connect, and respiratory rate rides the body route.

The overload for one type is available in 2.3.0 and later:

```kotlin
public fun routedBy(type: HealthDataType): List<UploadDataType> = emptyList()
```

It returns the routes a request for `type` feeds. The default answers an empty list, for a store asked by category only, and [`Permissions.request`](#permissions.request) refuses a type no route reads.

#### HealthStore.routesFor

Returns the routes a sync may schedule for a grant on a category.

```kotlin
public fun routesFor(category: DataCategory): List<UploadDataType> =
    routedBy(category).filterNot { it in UploadDataType.awaitingConverter }
```

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

**Returns:** [`routedBy`](#healthstore.routedby) without the routes Terra cannot convert yet.

#### HealthStore.category

Returns the category a read of a route belongs to, for reporting a refusal a person can act on.

```kotlin
public fun category(route: UploadDataType): DataCategory
```

| Name    | Type                                | Description              |
| ------- | ----------------------------------- | ------------------------ |
| `route` | [`UploadDataType`](#uploaddatatype) | The route that was read. |

**Returns:** the category to name in the refusal.

#### HealthStore.categoriesOf

Returns the categories a body measurement of a metric is granted under, on this store.

```kotlin
public fun categoriesOf(metric: BodyMeasurement.Metric): Set<DataCategory>
```

| Name     | Type                     | Description               |
| -------- | ------------------------ | ------------------------- |
| `metric` | `BodyMeasurement.Metric` | The measurement's metric. |

**Returns:** the categories whose grant covers that metric.

#### HealthStore.availability

Reports whether this store can serve reads on this device, right now.

```kotlin
public suspend fun availability(): StoreAvailability
```

**Returns:** a [`StoreAvailability`](#storeavailability).

#### HealthStore.registerAccess

Registers whatever this store needs in order to present a permission request later.

```kotlin
public fun registerAccess(host: ActivityResultCaller): AccessRegistration
```

| Name   | Type                   | Description                                           |
| ------ | ---------------------- | ----------------------------------------------------- |
| `host` | `ActivityResultCaller` | The activity or fragment the sheet is presented from. |

**Returns:** an [`AccessRegistration`](#accessregistration) the host releases with `unregister()` when the screen goes.

{% hint style="warning" %}
Call it before `host` is STARTED, in practice from `onCreate`. AndroidX refuses to register an activity result contract once the host is STARTED.
{% endhint %}

#### HealthStore.beginRequest

Takes a registration for one request, or returns `null` when it cannot present a sheet.

```kotlin
public fun beginRequest(registration: AccessRegistration): AccessRequest?
```

| Name           | Type                                        | Description                             |
| -------------- | ------------------------------------------- | --------------------------------------- |
| `registration` | [`AccessRegistration`](#accessregistration) | A registration this kind of store made. |

**Returns:** an [`AccessRequest`](#accessrequest), or `null` when a sheet presented through `registration` is still waiting or it has been unregistered. It has no side effects.

| Error                      | When                                                  |
| -------------------------- | ----------------------------------------------------- |
| `IllegalArgumentException` | `registration` was made by a different kind of store. |

#### HealthStore.requestAccess

Presents one request covering everything an access expands to, and reports what was granted.

```kotlin
public suspend fun requestAccess(access: HealthAccess, request: AccessRequest): HealthAccess
```

| Name      | Type                              | Description                                                                              |
| --------- | --------------------------------- | ---------------------------------------------------------------------------------------- |
| `access`  | [`HealthAccess`](#healthaccess)   | What to ask for.                                                                         |
| `request` | [`AccessRequest`](#accessrequest) | The request [`beginRequest`](#healthstore.beginrequest) returned. This call consumes it. |

**Returns:** the access granted after the sheet answers. In 2.3.0 and later, its `readTypes` holds the types of `access` with at least one permission granted, and is empty where `access` named none.

| Error                      | When                                             |
| -------------------------- | ------------------------------------------------ |
| `IllegalArgumentException` | `request` was made by a different kind of store. |

#### HealthStore.granted

Returns the exact set currently granted.

```kotlin
public suspend fun granted(): HealthAccess
```

**Returns:** the granted [`HealthAccess`](#healthaccess). Android discloses read grants, unlike HealthKit. Its `readTypes` is always empty: [`grantedReadTypes`](#healthstore.grantedreadtypes) answers for types.

#### HealthStore.grantedReadTypes

Returns every type with at least one permission behind it granted. Available in 2.3.0 and later.

```kotlin
public suspend fun grantedReadTypes(): Set<HealthDataType> = emptySet()
```

**Returns:** the granted [`HealthDataType`](#healthdatatype)s. The default answers an empty set, for a store asked by category only.

#### HealthStore.grantsWrite

Returns whether every record type an access names for writing is granted right now.

```kotlin
public suspend fun grantsWrite(access: HealthAccess): Boolean
```

| Name     | Type                            | Description                             |
| -------- | ------------------------------- | --------------------------------------- |
| `access` | [`HealthAccess`](#healthaccess) | The writes and workout scopes to check. |

**Returns:** `true` when every write grant `access` needs is held. A workout `log` asks it about the types its entries carry, and `writeStatus(ACTIVITY)` about the types the app requested.

It has a default that answers from [`granted`](#healthstore.granted), which is exact for a store whose grants are per category. The Health Connect store answers from its per-record-type grants instead.

#### HealthStore.readScopes

Returns this store's own names for what it may read on a route's behalf right now.

```kotlin
public suspend fun readScopes(
    dataType: UploadDataType,
    requested: Set<DataCategory>? = null,
    requestedTypes: Set<HealthDataType>? = null,
): Set<String>
```

| Name             | Type                                | Description                                                                                                                                      |
| ---------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `dataType`       | [`UploadDataType`](#uploaddatatype) | The route.                                                                                                                                       |
| `requested`      | `Set<DataCategory>?`                | The categories this install has asked for, which narrow the answer to what the route will actually read. Optional. Defaults to `null`.           |
| `requestedTypes` | `Set<HealthDataType>?`              | The types this install asked for individually, which narrow the answer the same way. Optional. Defaults to `null`. Available in 2.3.0 and later. |

**Returns:** opaque per-permission names. They are only ever compared with a previous answer from the same store, to tell whether a grant has widened since a change anchor was taken.

#### HealthStore.featureStatus

Reports whether a platform feature is granted, refused, never asked for, or absent from this device.

```kotlin
public suspend fun featureStatus(feature: Feature): PermissionStatus
```

| Name      | Type                  | Description                      |
| --------- | --------------------- | -------------------------------- |
| `feature` | [`Feature`](#feature) | Background read or history read. |

**Returns:** a [`PermissionStatus`](#permissionstatus). `UNSUPPORTED` is the device's answer and `DENIED` the person's.

#### HealthStore.read

Reads one page of a request's window.

```kotlin
public suspend fun read(request: ReadRequest): ReadPage
```

| Name      | Type                          | Description                           |
| --------- | ----------------------------- | ------------------------------------- |
| `request` | [`ReadRequest`](#readrequest) | The window, route and limits to read. |

**Returns:** a [`ReadPage`](#readpage). A page with `more` set is a prefix, and its `cursor` is where the rest starts. Every record in the window reaches a caller that keeps asking with the cursor it was last given, and none arrives twice within one walk.

| Error                                     | When                                             |
| ----------------------------------------- | ------------------------------------------------ |
| [`ReadQuotaExceeded`](#readquotaexceeded) | The provider's read quota for this app is spent. |

#### HealthStore.dayTotals

Returns one total per metric and local day touching an interval, from the platform's statistics engine.

```kotlin
public suspend fun dayTotals(
    interval: SampleInterval,
    zone: ZoneId,
    requested: Set<DataCategory>? = null,
    requestedTypes: Set<HealthDataType>? = null,
): List<DayTotal>

public suspend fun dayTotals(
    interval: SampleInterval,
    zone: ZoneId,
    requested: Set<DataCategory>?,
    policy: DayTotalPolicy,
    requestedTypes: Set<HealthDataType>? = null,
): List<DayTotal> = dayTotals(interval, zone, requested, requestedTypes)
```

| Name             | Type                                | Description                                                                                                                                                     |
| ---------------- | ----------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `interval`       | [`SampleInterval`](#sampleinterval) | The half-open window.                                                                                                                                           |
| `zone`           | `ZoneId`                            | The caller's zone, which decides where each local day starts.                                                                                                   |
| `requested`      | `Set<DataCategory>?`                | The categories this install has asked for, or `null` for every total the store can produce. Defaults to `null` in the first overload.                           |
| `requestedTypes` | `Set<HealthDataType>?`              | The types this install asked for individually. A total is produced only for a requested type. Optional. Defaults to `null`. Available in 2.3.0 and later.       |
| `policy`         | [`DayTotalPolicy`](#daytotalpolicy) | What the totals count. The default implementation ignores it; stores where [`appliesDayTotalPolicy`](#healthstore.appliesdaytotalpolicy) is `true` override it. |

**Returns:** the [`DayTotal`](#daytotal) list.

| Error                                     | When                                             |
| ----------------------------------------- | ------------------------------------------------ |
| [`ReadQuotaExceeded`](#readquotaexceeded) | The provider's read quota for this app is spent. |

#### HealthStore.changes

Returns everything written since an anchor, in insertion order, one page at a time.

```kotlin
public suspend fun changes(
    dataType: UploadDataType,
    anchor: ChangeAnchor?,
    requested: Set<DataCategory>? = null,
    requestedTypes: Set<HealthDataType>? = null,
): HealthChanges
```

| Name             | Type                                | Description                                                                                                                                                      |
| ---------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dataType`       | [`UploadDataType`](#uploaddatatype) | The route whose changes to read.                                                                                                                                 |
| `anchor`         | [`ChangeAnchor?`](#changeanchor)    | Where the last page ended, or `null` to establish a baseline.                                                                                                    |
| `requested`      | `Set<DataCategory>?`                | The categories this install has asked for, or `null` for every type the route covers. Optional. Defaults to `null`.                                              |
| `requestedTypes` | `Set<HealthDataType>?`              | The types this install asked for individually. A change token names only the record types they read. Optional. Defaults to `null`. Available in 2.3.0 and later. |

**Returns:** one [`HealthChanges`](#healthchanges) page.

{% hint style="warning" %}
A `null` anchor establishes a baseline and returns nothing. It does not mean "everything you have". History is the windowed read's job.
{% endhint %}

| Error                                     | When                                             |
| ----------------------------------------- | ------------------------------------------------ |
| [`ReadQuotaExceeded`](#readquotaexceeded) | The provider's read quota for this app is spent. |

#### HealthStore.save

Writes entries under this app's name and reports what the store filed.

```kotlin
public suspend fun save(entries: List<WriteEntry>): List<WrittenRecord>
```

| Name      | Type               | Description           |
| --------- | ------------------ | --------------------- |
| `entries` | `List<WriteEntry>` | The entries to write. |

**Returns:** one [`WrittenRecord`](#writtenrecord) per entry, in the order given.

All or nothing where the store allows it. A store that cannot write a batch atomically removes what it already wrote before it throws.

| Error                           | When                                                            |
| ------------------------------- | --------------------------------------------------------------- |
| `TerraError.RollbackIncomplete` | A failed batch could not be fully removed. Names the survivors. |

#### HealthStore.delete

Removes the record an id names, which is only ever one this app wrote.

```kotlin
public suspend fun delete(id: RecordId, category: DataCategory)
```

| Name       | Type                            | Description                                                              |
| ---------- | ------------------------------- | ------------------------------------------------------------------------ |
| `id`       | [`RecordId`](#recordid)         | The handle `save` returned.                                              |
| `category` | [`DataCategory`](#datacategory) | The category the entry was written under. Stores delete per record type. |

Health Connect answers an id it holds nothing under with a silent success, so a store may report nothing about a missing record. A store that can tell throws `TerraError.SampleNotFound`.

A record type whose write grant is refused is skipped, because the store cannot look for a record of that type without it. If the person revoked that grant after the app wrote a record of the type, the record stays until the grant is restored and the delete is repeated.

### AccessRegistration

What a store registered with a host in order to present a request later.

```kotlin
public interface AccessRegistration
```

#### AccessRegistration.unregister

Releases what was registered.

```kotlin
public fun unregister()
```

After this the registration cannot present anything.

### AccessRequest

One registration, taken for one request, and the only thing [`requestAccess`](#healthstore.requestaccess) presents through.

```kotlin
public interface AccessRequest
```

#### AccessRequest.abandon

Gives the request back without presenting anything.

```kotlin
public fun abandon()
```

Only for a caller that took one and then failed before handing it to `requestAccess`. Once `requestAccess` has it, calling this does nothing.

### HealthAccess

What a caller may do with a store, as one value.

```kotlin
public data class HealthAccess(
    public val read: Set<DataCategory> = emptySet(),
    public val write: Set<DataCategory> = emptySet(),
    public val workouts: Set<WorkoutScope> = emptySet(),
    public val readTypes: Set<HealthDataType> = emptySet(),
)
```

| Property       | Type                  | Description                                                                                                                                                                                                                                                                                                               |
| -------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `read`         | `Set<DataCategory>`   | Categories to read. Defaults to empty.                                                                                                                                                                                                                                                                                    |
| `write`        | `Set<DataCategory>`   | Categories to write. Defaults to empty.                                                                                                                                                                                                                                                                                   |
| `workouts`     | `Set<WorkoutScope>`   | Workout shapes to write, which name a narrower set of types than `write = setOf(ACTIVITY)`. Defaults to empty.                                                                                                                                                                                                            |
| `readTypes`    | `Set<HealthDataType>` | Individual types to read. Once any are recorded, the install is type-scoped: the SDK reads and uploads only these types and the types of the categories in `read`. Empty keeps the category rules. As a grant, the requested types with at least one permission granted. Defaults to empty. Available in 2.3.0 and later. |
| `isEmpty`      | `Boolean`             | Whether every set is empty.                                                                                                                                                                                                                                                                                               |
| `isTypeScoped` | `Boolean`             | Whether `readTypes` is not empty. Available in 2.3.0 and later.                                                                                                                                                                                                                                                           |

#### HealthAccess.union

Returns the union with another access.

```kotlin
public fun union(other: HealthAccess): HealthAccess
```

| Name    | Type           | Description            |
| ------- | -------------- | ---------------------- |
| `other` | `HealthAccess` | The access to fold in. |

**Returns:** the union. Workout scopes for the same activity merge into one, with their energy and distance flags OR-ed. `readTypes` are unioned too.

#### HealthAccess.intersection

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

```kotlin
public fun intersection(other: HealthAccess): HealthAccess
```

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

**Returns:** the intersection. Workout scopes match per activity, and an attachment survives only where both sides set it.

### Feature

A platform capability a store may or may not expose on a given device.

```kotlin
public enum class Feature
```

| Case              | Description                                 |
| ----------------- | ------------------------------------------- |
| `BACKGROUND_READ` | Reading while the app is in the background. |
| `HISTORY_READ`    | Reading past the store's history window.    |

### StoreAvailability

Whether a store can serve reads on this device, right now.

```kotlin
public sealed interface StoreAvailability
```

`TerraError.HealthDataUnavailable` carries one of these as its reason.

| Case                                         | Description                                                                                                                                                      |
| -------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Available`                                  | The store can serve reads.                                                                                                                                       |
| `ModuleMissing`                              | `Source.SAMSUNG_HEALTH` was asked for without the Samsung add-on registered.                                                                                     |
| `ProviderAppMissing`                         | No Health Connect app on Android 13 and below, or no Samsung Health installed. Samsung Health disabled, not initialised or on a child account also reports this. |
| `ProviderAppTooOld(installed: String)`       | The provider app needs an update. `installed` is its version, or `"unknown"` when it exposes none.                                                               |
| `PartnerPolicyMissing(types: Set<DataType>)` | The partner policy does not cover these types, so the store withholds them. The Samsung store reports it only when no type at all is readable.                   |
| `FeatureUnavailable(feature: Feature)`       | A platform feature the request needs is missing on this device.                                                                                                  |

### StoreCapabilities

What a store can do, fixed per store and per SDK version.

```kotlin
public data class StoreCapabilities(
    public val backgroundRead: Boolean,
    public val historyRead: Boolean,
    public val writes: Boolean,
    public val routes: Set<UploadDataType>,
)
```

| Property         | Type                  | Description                                         |
| ---------------- | --------------------- | --------------------------------------------------- |
| `backgroundRead` | `Boolean`             | Whether the store can read in the background.       |
| `historyRead`    | `Boolean`             | Whether the store can read past its history window. |
| `writes`         | `Boolean`             | Whether the store writes. `false` for Samsung.      |
| `routes`         | `Set<UploadDataType>` | The routes the store can upload.                    |

### ChangeAnchor

An opaque resume point issued by a store's change feed.

```kotlin
@JvmInline
public value class ChangeAnchor(public val value: String)
```

Persist it and hand it back unmodified.

### ReadCursor

An opaque resume point for one windowed read, issued by the store that truncated it.

```kotlin
@JvmInline
public value class ReadCursor(public val value: String)
```

It describes a position inside one call's window. It is not persisted and is not a [`ChangeAnchor`](#changeanchor).

### ReadRequest

One windowed read.

```kotlin
public data class ReadRequest @JvmOverloads constructor(
    public val dataType: UploadDataType,
    public val interval: SampleInterval,
    public val limit: Int = DEFAULT_LIMIT,
    public val requested: Set<DataCategory>? = null,
    public val cursor: ReadCursor? = null,
    public val types: Set<DataType>? = null,
    public val requestedTypes: Set<HealthDataType>? = null,
)
```

| Property         | Type                                | Description                                                                                                                                                                                                                        |
| ---------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `dataType`       | [`UploadDataType`](#uploaddatatype) | The route to read.                                                                                                                                                                                                                 |
| `interval`       | [`SampleInterval`](#sampleinterval) | The resolved window.                                                                                                                                                                                                               |
| `limit`          | `Int`                               | The most records to return before truncating. Defaults to `DEFAULT_LIMIT`.                                                                                                                                                         |
| `requested`      | `Set<DataCategory>?`                | The categories this install has asked for, or `null` to read everything the route covers. Defaults to `null`.                                                                                                                      |
| `cursor`         | [`ReadCursor?`](#readcursor)        | Where to carry on from, or `null` to start at the beginning. Only a cursor the same store returned for the same `dataType`, `interval` and `requested`. Defaults to `null`.                                                        |
| `types`          | `Set<DataType>?`                    | The record types this call wants, or `null` for everything `requested` leaves readable. Defaults to `null`.                                                                                                                        |
| `requestedTypes` | `Set<HealthDataType>?`              | The types this install asked for individually, or `null` when it is not type-scoped. A record type is readable when a category in `requested` holds it or one of these reads it. Defaults to `null`. Available in 2.3.0 and later. |

#### ReadRequest.DEFAULT\_LIMIT

The default page limit.

```kotlin
public const val DEFAULT_LIMIT: Int = 10_000
```

### HealthSamples

Samples by kind rather than as one list, because the routes they upload to differ.

```kotlin
public data class HealthSamples(
    public val heartRate: List<HeartRateSample> = emptyList(),
    public val steps: List<StepCount> = emptyList(),
    public val restingHeartRate: List<RestingHeartRateSample> = emptyList(),
    public val sleep: List<SleepSegment> = emptyList(),
    public val workouts: List<Workout> = emptyList(),
    public val dayTotals: List<DayTotal> = emptyList(),
    public val bodyMeasurements: List<BodyMeasurement> = emptyList(),
    public val bloodPressure: List<BloodPressureSample> = emptyList(),
    public val bloodGlucose: List<BloodGlucoseSample> = emptyList(),
    public val oxygenSaturation: List<OxygenSaturationSample> = emptyList(),
    public val bodyTemperature: List<BodyTemperatureSample> = emptyList(),
    public val heartRateVariability: List<HeartRateVariabilitySample> = emptyList(),
    public val respiratoryRate: List<RespiratoryRateSample> = emptyList(),
    public val vo2Max: List<Vo2MaxSample> = emptyList(),
    public val meals: List<MealSample> = emptyList(),
    public val hydration: List<HydrationSample> = emptyList(),
    public val menstruationFlow: List<MenstruationFlowSample> = emptyList(),
    public val workoutIntensity: List<WorkoutIntensitySample> = emptyList(),
    public val intraday: List<IntradaySample> = emptyList(),
    public val menstruationEvents: List<MenstruationEventSample> = emptyList(),
    public val workoutRoutes: List<WorkoutRoute> = emptyList(),
)
```

Each property is a list of the sample type it names, empty by default. `workoutIntensity` holds the speed, power and cadence readings a workout left; `intraday` holds the active energy, distance and floors a day total is made of; `menstruationEvents` holds cycle events beyond flow; `workoutRoutes` holds the tracks the workouts left. The sample types are documented under [Data types](#data-types).

| Property  | Type      | Description                  |
| --------- | --------- | ---------------------------- |
| `isEmpty` | `Boolean` | Whether every list is empty. |

### ReadPage

One page of a windowed read.

```kotlin
public data class ReadPage @JvmOverloads constructor(
    public val samples: HealthSamples = HealthSamples(),
    public val more: Boolean = false,
    public val cursor: ReadCursor? = null,
    public val routeConsentRequired: Boolean = false,
)
```

| Property               | Type                              | Description                                                                                                                                            |
| ---------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `samples`              | [`HealthSamples`](#healthsamples) | The records read.                                                                                                                                      |
| `more`                 | `Boolean`                         | The store stopped at the request's limit rather than running out.                                                                                      |
| `cursor`               | [`ReadCursor?`](#readcursor)      | Where the rest of the window begins, when `more` is set and the store can say. `null` with `more` set means the caller reads the window whole instead. |
| `routeConsentRequired` | `Boolean`                         | A workout in this page had a track the store would not hand over without consent.                                                                      |

### HealthChanges

One page of a store's change feed.

```kotlin
public data class HealthChanges(
    public val samples: HealthSamples = HealthSamples(),
    public val invalidatedDays: List<Instant> = emptyList(),
    public val anchor: ChangeAnchor? = null,
    public val more: Boolean = false,
    public val tokenExpired: Boolean = false,
    public val routeConsentRequired: Boolean = false,
)
```

| Property               | Type                              | Description                                                                                                               |
| ---------------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `samples`              | [`HealthSamples`](#healthsamples) | The records written since the anchor.                                                                                     |
| `invalidatedDays`      | `List<Instant>`                   | Local day starts whose totals changed through records the seam carries no value type for. The caller re-reads these days. |
| `anchor`               | [`ChangeAnchor?`](#changeanchor)  | The anchor for the next call. `null` only when the store had nothing to issue one for.                                    |
| `more`                 | `Boolean`                         | Another page follows, and `anchor` is where to ask for it.                                                                |
| `tokenExpired`         | `Boolean`                         | The feed cannot account for what happened before this page, so `anchor` is a fresh baseline and not a resume point.       |
| `routeConsentRequired` | `Boolean`                         | A workout in this page had a track the store would not hand over without consent.                                         |

### WrittenRecord

One entry as the store filed it.

```kotlin
public data class WrittenRecord(public val id: RecordId)
```

| Property | Type                    | Description                                                 |
| -------- | ----------------------- | ----------------------------------------------------------- |
| `id`     | [`RecordId`](#recordid) | The caller's handle, the client record id the entry minted. |

### ReadQuotaExceeded

The provider refused a read because this app has spent its read quota for now.

```kotlin
public class ReadQuotaExceeded(cause: Throwable) :
    Exception("the health store's read quota is spent: ${cause.message}", cause)
```

| Name    | Type        | Description                   |
| ------- | ----------- | ----------------------------- |
| `cause` | `Throwable` | The provider's own exception. |

Health Connect meters reads per app. On Android 14 and above the buckets are 2,000 per 15 minutes and 16,000 per day in the foreground, and 1,000 and 8,000 in the background. A two-year first sync can pass the shorter bucket, so this is a normal state: the sync stops the route where it is and resumes once the quota refills. [`read`](#healthstore.read), [`dayTotals`](#healthstore.daytotals) and [`changes`](#healthstore.changes) throw it in place of the provider's exception, and a store must throw it rather than answer short.

### StoreRegistry

The stores this build has, looked up by [`Source`](#source).

```kotlin
public class StoreRegistry private constructor(private val stores: Map<Source, HealthStore>)
```

Your app normally registers stores through [`StoreRegistration`](#storeregistration) in the `Terra(...)` block. A registry is what the `@TerraSeam` `Terra` constructor takes.

| Property     | Type          | Description                            |
| ------------ | ------------- | -------------------------------------- |
| `registered` | `Set<Source>` | The sources a store is registered for. |

#### StoreRegistry.store

Returns the store for a source.

```kotlin
public fun store(source: Source): HealthStore
```

| Name     | Type                | Description            |
| -------- | ------------------- | ---------------------- |
| `source` | [`Source`](#source) | The source to look up. |

**Returns:** the registered [`HealthStore`](#healthstore).

| Error                                                               | When                                 |
| ------------------------------------------------------------------- | ------------------------------------ |
| `TerraError.HealthDataUnavailable(StoreAvailability.ModuleMissing)` | No store is registered for `source`. |

#### StoreRegistry.contains

Reports whether a store is registered for a source.

```kotlin
public fun contains(source: Source): Boolean
```

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

**Returns:** `true` when a store is registered.

#### StoreRegistry.of

Builds a registry from stores.

```kotlin
public fun of(vararg stores: HealthStore): StoreRegistry
```

| Name     | Type                 | Description                                                                                                    |
| -------- | -------------------- | -------------------------------------------------------------------------------------------------------------- |
| `stores` | `vararg HealthStore` | The stores, each registered under its own `source`. A later store for the same source replaces an earlier one. |

**Returns:** the registry.

### StoreRegistry.Builder

Builds a [`StoreRegistry`](#storeregistry) one store at a time.

```kotlin
public class Builder
```

#### StoreRegistry.Builder.register

Registers a store under its own `source`.

```kotlin
public fun register(store: HealthStore): Builder
```

| Name    | Type                          | Description            |
| ------- | ----------------------------- | ---------------------- |
| `store` | [`HealthStore`](#healthstore) | The store to register. |

**Returns:** this builder. A later registration for the same source replaces the earlier one, which is how a test swaps a fake in over the real store.

#### StoreRegistry.Builder.build

Builds the registry.

```kotlin
public fun build(): StoreRegistry
```

**Returns:** the [`StoreRegistry`](#storeregistry).

### ReadTokens

Encodes a store's per-record-type page tokens as one [`ReadCursor`](#readcursor). `@TerraSeam`.

```kotlin
@TerraSeam
public object ReadTokens
```

#### ReadTokens.encode

Encodes page tokens as one cursor.

```kotlin
public fun encode(tokens: Map<String, String>): ReadCursor?
```

| Name     | Type                  | Description                                                           |
| -------- | --------------------- | --------------------------------------------------------------------- |
| `tokens` | `Map<String, String>` | Page tokens keyed by record-type name. A type that ran out is absent. |

**Returns:** the cursor, or `null` when every type ran out.

#### ReadTokens.decode

Decodes a cursor back into page tokens.

```kotlin
public fun decode(cursor: ReadCursor?, resumable: Collection<String>): Map<String, String>?
```

| Name        | Type                         | Description                                                |
| ----------- | ---------------------------- | ---------------------------------------------------------- |
| `cursor`    | [`ReadCursor?`](#readcursor) | The cursor to decode, or `null` for a read from the start. |
| `resumable` | `Collection<String>`         | The record types this read would issue.                    |

**Returns:** the tokens, or `null` when `cursor` is `null`.

| Error                      | When                                                                                                          |
| -------------------------- | ------------------------------------------------------------------------------------------------------------- |
| `IllegalArgumentException` | The cursor does not parse, names no record type, carries an empty token, or names a type outside `resumable`. |

### StoreSupport

Rules every store follows, shared between the core SDK and the add-on. `@TerraSeam`.

```kotlin
@TerraSeam
public object StoreSupport
```

#### StoreSupport.UNKNOWN\_VERSION

The version reported when the provider is too old but its version cannot be read.

```kotlin
public const val UNKNOWN_VERSION: String = "unknown"
```

#### StoreSupport.providerAppTooOld

Returns a `ProviderAppTooOld` availability for an installed version.

```kotlin
public fun providerAppTooOld(installedVersion: String?): StoreAvailability.ProviderAppTooOld
```

| Name               | Type      | Description                                             |
| ------------------ | --------- | ------------------------------------------------------- |
| `installedVersion` | `String?` | The provider's version, or `null` when it exposes none. |

**Returns:** `ProviderAppTooOld(installedVersion ?: UNKNOWN_VERSION)`.

#### StoreSupport.localDaysSpanned

Returns every local day an interval reaches into, as the instants they begin at.

```kotlin
public fun localDaysSpanned(start: Instant, end: Instant, zone: ZoneId): List<Instant>
```

| Name    | Type      | Description                                                                                              |
| ------- | --------- | -------------------------------------------------------------------------------------------------------- |
| `start` | `Instant` | The start of the interval.                                                                               |
| `end`   | `Instant` | The end of the interval. A record ending exactly at midnight does not reach the day that midnight opens. |
| `zone`  | `ZoneId`  | The zone whose local days to count.                                                                      |

**Returns:** the local-midnight instants, oldest first. An instant (`end` equal to `start`) spans the one day it falls on.

### SampleCollector

One mutable list per [`HealthSamples`](#healthsamples) field, filled by a store as records arrive. `@TerraSeam`.

```kotlin
@TerraSeam
public class SampleCollector
```

It has one `MutableList` property per `HealthSamples` property, with the same names and element types, plus:

| Property               | Type      | Description                                                                              |
| ---------------------- | --------- | ---------------------------------------------------------------------------------------- |
| `routeConsentRequired` | `Boolean` | A record in this page held a track the person has not allowed this app to read. Mutable. |

#### SampleCollector.samples

Returns everything collected so far, as one page.

```kotlin
public fun samples(): HealthSamples
```

**Returns:** a [`HealthSamples`](#healthsamples) holding copies of every list.

### HealthConnectStore

Health Connect behind the [`HealthStore`](#healthstore) seam.

```kotlin
public class HealthConnectStore(
    private val context: Context,
    private val clientProvider: () -> HealthConnectClient = { HealthConnectClient.getOrCreate(context) },
    private val zone: () -> ZoneId = ZoneId::systemDefault,
    private val versions: WriteVersions,
    private val now: () -> Instant = Instant::now,
    private val excludedOrigins: suspend () -> Map<HealthConnectRecordType, Set<String>> = { emptyMap() },
) : HealthStore
```

It reads records and lets Terra aggregate them. The exception is `dayTotals`, which asks Health Connect's own statistics engine. `Terra(context, devId = ...)` always registers one for `Source.HEALTH` unless you registered your own.

| Name              | Type                                                      | Description                                                                                                                                                                                      |
| ----------------- | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `context`         | `Context`                                                 | The context the client and package manager are reached through.                                                                                                                                  |
| `clientProvider`  | `() -> HealthConnectClient`                               | Builds the Health Connect client on demand, so the store can still answer `availability()` on a device without Health Connect. Optional. Defaults to `HealthConnectClient.getOrCreate(context)`. |
| `zone`            | `() -> ZoneId`                                            | The zone local days are counted in. Optional. Defaults to `ZoneId::systemDefault`.                                                                                                               |
| `versions`        | [`WriteVersions`](#writeversions)                         | Issues the `clientRecordVersion` each write is filed under. Required: the wall clock cannot rank two corrections written in the same millisecond.                                                |
| `now`             | `() -> Instant`                                           | The clock. Optional. Defaults to `Instant::now`.                                                                                                                                                 |
| `excludedOrigins` | `suspend () -> Map<HealthConnectRecordType, Set<String>>` | The writing apps whose records this store leaves out, by package name, per record type. Asked on every read. Optional. Defaults to none.                                                         |

Behaviour specific to this store:

* `source` is `Source.HEALTH`, `wireProvider` is `"health_connect"`, and `historyWindowDays` is `30`.
* `capabilities` reports background read, history read, writes, and every [`UploadDataType`](#uploaddatatype).
* `appliesDayTotalPolicy` is `true`.
* `granted()` reports a category only when every one of its record types is granted, and never reports workout scopes. Health Connect has one session write grant for every activity, so only `requestAccess` can say which scopes were granted.
* `requestAccess` reads the result back through `granted()` rather than from the sheet's callback.
* `featureStatus` answers `UNSUPPORTED` when the device lacks the feature, then `GRANTED` or `DENIED`.

| Error                                        | When                                                                                        |
| -------------------------------------------- | ------------------------------------------------------------------------------------------- |
| `TerraError.Platform(IllegalStateException)` | `registerAccess` ran after the host was STARTED, or on a host that is already destroyed.    |
| `IllegalArgumentException`                   | `beginRequest` or `requestAccess` got a registration or request another kind of store made. |

#### HealthConnectStore.HISTORY\_WINDOW\_DAYS

How far back Health Connect serves without `READ_HEALTH_DATA_HISTORY`.

```kotlin
public const val HISTORY_WINDOW_DAYS: Long = 30
```

#### HealthConnectStore.WIRE\_PROVIDER

The provider label Terra's ingest route is keyed on.

```kotlin
public const val WIRE_PROVIDER: String = "health_connect"
```

#### HealthConnectStore.MAX\_PAGE\_SIZE

The largest page Health Connect accepts.

```kotlin
public const val MAX_PAGE_SIZE: Int = 5_000
```

#### HealthConnectStore.MAX\_INSERT\_RECORDS

The most records one `insertRecords` call may carry. A bulk `log` is batched to fit.

```kotlin
public const val MAX_INSERT_RECORDS: Int = 1_000
```

#### HealthConnectStore.PROVIDER\_PACKAGE\_NAME

The Health Connect APK's package on Android 13 and below.

```kotlin
public const val PROVIDER_PACKAGE_NAME: String = "com.google.android.apps.healthdata"
```

Only used to read a version name for a message. The availability decision comes from `getSdkStatus`.

#### HealthConnectStore.UNKNOWN\_VERSION

The version reported when the provider is too old but exposes no version.

```kotlin
public const val UNKNOWN_VERSION: String = StoreSupport.UNKNOWN_VERSION
```

#### HealthConnectStore.availabilityFor

Returns the store availability for a Health Connect SDK status.

```kotlin
public fun availabilityFor(sdkStatus: Int, installedVersion: String?): StoreAvailability
```

| Name               | Type      | Description                                                                                                 |
| ------------------ | --------- | ----------------------------------------------------------------------------------------------------------- |
| `sdkStatus`        | `Int`     | The value of `HealthConnectClient.getSdkStatus`.                                                            |
| `installedVersion` | `String?` | The provider's version name, or `null` on Android 14 and above, where Health Connect is a framework module. |

**Returns:** `Available` for `SDK_AVAILABLE`, `ProviderAppTooOld` for `SDK_UNAVAILABLE_PROVIDER_UPDATE_REQUIRED`, and `ProviderAppMissing` for anything else.

### HealthConnectRecordType

Every Health Connect record type this SDK asks for, with what it means to Terra.

```kotlin
public enum class HealthConnectRecordType(
    public val recordType: KClass<out Record>,
    public val readPermission: String,
    public val categories: Set<DataCategory>,
    public val dataType: DataType? = null,
    public val carries: SampleKind? = null,
    public val platformFeature: Int? = null,
    public val route: UploadDataType? = null,
)
```

| Property          | Type                                 | Description                                                                                                          |
| ----------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------- |
| `recordType`      | `KClass<out Record>`                 | The Health Connect record class.                                                                                     |
| `readPermission`  | `String`                             | The read permission, spelled out.                                                                                    |
| `categories`      | `Set<DataCategory>`                  | The categories whose request covers this type.                                                                       |
| `dataType`        | `DataType?`                          | The per-type name a partner-policy or permission report uses, when one exists.                                       |
| `carries`         | [`SampleKind?`](#samplekind)         | The [`HealthSamples`](#healthsamples) field this type lands in, or `null` when the seam carries no value for it yet. |
| `platformFeature` | `Int?`                               | The Health Connect feature this type needs, where it needs one.                                                      |
| `route`           | [`UploadDataType?`](#uploaddatatype) | The upload route its records travel on, or `null` for a type nothing uploads.                                        |
| `writePermission` | `String`                             | The write permission, derived from `readPermission`.                                                                 |

Each permission below is prefixed with `android.permission.health.`.

| Case                      | Record                            | Read permission                | Categories                   | Route        | Carries                                             |
| ------------------------- | --------------------------------- | ------------------------------ | ---------------------------- | ------------ | --------------------------------------------------- |
| `HEART_RATE`              | `HeartRateRecord`                 | `READ_HEART_RATE`              | ACTIVITY, BODY, DAILY, SLEEP | DAILY        | HEART\_RATE                                         |
| `RESTING_HEART_RATE`      | `RestingHeartRateRecord`          | `READ_RESTING_HEART_RATE`      | DAILY, SLEEP                 | DAILY        | RESTING\_HEART\_RATE                                |
| `HEART_RATE_VARIABILITY`  | `HeartRateVariabilityRmssdRecord` | `READ_HEART_RATE_VARIABILITY`  | ACTIVITY, BODY, DAILY, SLEEP | BODY         | HEART\_RATE\_VARIABILITY                            |
| `STEPS`                   | `StepsRecord`                     | `READ_STEPS`                   | ACTIVITY, DAILY              | DAILY        | STEPS                                               |
| `STEPS_CADENCE`           | `StepsCadenceRecord`              | `READ_STEPS`                   | ACTIVITY, DAILY              | -            | -                                                   |
| `SLEEP_SESSION`           | `SleepSessionRecord`              | `READ_SLEEP`                   | SLEEP                        | SLEEP        | SLEEP                                               |
| `EXERCISE_SESSION`        | `ExerciseSessionRecord`           | `READ_EXERCISE`                | ACTIVITY                     | ACTIVITY     | WORKOUT                                             |
| `CYCLING_CADENCE`         | `CyclingPedalingCadenceRecord`    | `READ_EXERCISE`                | ACTIVITY                     | ACTIVITY     | WORKOUT\_INTENSITY                                  |
| `ACTIVE_CALORIES`         | `ActiveCaloriesBurnedRecord`      | `READ_ACTIVE_CALORIES_BURNED`  | ACTIVITY, DAILY              | DAILY        | INTRADAY                                            |
| `TOTAL_CALORIES`          | `TotalCaloriesBurnedRecord`       | `READ_TOTAL_CALORIES_BURNED`   | ACTIVITY, DAILY              | -            | -                                                   |
| `BASAL_METABOLIC_RATE`    | `BasalMetabolicRateRecord`        | `READ_BASAL_METABOLIC_RATE`    | ACTIVITY, BODY, DAILY        | BODY         | BODY\_MEASUREMENT                                   |
| `DISTANCE`                | `DistanceRecord`                  | `READ_DISTANCE`                | ACTIVITY, DAILY              | DAILY        | INTRADAY                                            |
| `FLOORS_CLIMBED`          | `FloorsClimbedRecord`             | `READ_FLOORS_CLIMBED`          | ACTIVITY, DAILY              | DAILY        | INTRADAY                                            |
| `ELEVATION_GAINED`        | `ElevationGainedRecord`           | `READ_ELEVATION_GAINED`        | ACTIVITY, DAILY              | -            | -                                                   |
| `POWER`                   | `PowerRecord`                     | `READ_POWER`                   | ACTIVITY                     | ACTIVITY     | WORKOUT\_INTENSITY                                  |
| `SPEED`                   | `SpeedRecord`                     | `READ_SPEED`                   | ACTIVITY                     | ACTIVITY     | WORKOUT\_INTENSITY                                  |
| `WEIGHT`                  | `WeightRecord`                    | `READ_WEIGHT`                  | BODY                         | BODY         | BODY\_MEASUREMENT                                   |
| `HEIGHT`                  | `HeightRecord`                    | `READ_HEIGHT`                  | BODY                         | BODY         | BODY\_MEASUREMENT                                   |
| `BODY_FAT`                | `BodyFatRecord`                   | `READ_BODY_FAT`                | BODY                         | BODY         | BODY\_MEASUREMENT                                   |
| `LEAN_BODY_MASS`          | `LeanBodyMassRecord`              | `READ_LEAN_BODY_MASS`          | BODY                         | BODY         | BODY\_MEASUREMENT                                   |
| `BONE_MASS`               | `BoneMassRecord`                  | `READ_BONE_MASS`               | BODY                         | BODY         | BODY\_MEASUREMENT                                   |
| `BODY_WATER_MASS`         | `BodyWaterMassRecord`             | `READ_BODY_WATER_MASS`         | BODY                         | BODY         | BODY\_MEASUREMENT                                   |
| `BODY_TEMPERATURE`        | `BodyTemperatureRecord`           | `READ_BODY_TEMPERATURE`        | BODY                         | BODY         | BODY\_TEMPERATURE                                   |
| `BASAL_BODY_TEMPERATURE`  | `BasalBodyTemperatureRecord`      | `READ_BASAL_BODY_TEMPERATURE`  | BODY                         | BODY         | BODY\_TEMPERATURE                                   |
| `SKIN_TEMPERATURE`        | `SkinTemperatureRecord`           | `READ_SKIN_TEMPERATURE`        | BODY                         | BODY         | BODY\_TEMPERATURE. Needs `FEATURE_SKIN_TEMPERATURE` |
| `BLOOD_GLUCOSE`           | `BloodGlucoseRecord`              | `READ_BLOOD_GLUCOSE`           | BODY                         | BODY         | BLOOD\_GLUCOSE                                      |
| `BLOOD_PRESSURE`          | `BloodPressureRecord`             | `READ_BLOOD_PRESSURE`          | BODY                         | BODY         | BLOOD\_PRESSURE                                     |
| `OXYGEN_SATURATION`       | `OxygenSaturationRecord`          | `READ_OXYGEN_SATURATION`       | BODY, SLEEP                  | BODY         | OXYGEN\_SATURATION                                  |
| `VO2_MAX`                 | `Vo2MaxRecord`                    | `READ_VO2_MAX`                 | BODY                         | BODY         | VO2\_MAX                                            |
| `RESPIRATORY_RATE`        | `RespiratoryRateRecord`           | `READ_RESPIRATORY_RATE`        | BODY, SLEEP                  | BODY         | RESPIRATORY\_RATE                                   |
| `NUTRITION`               | `NutritionRecord`                 | `READ_NUTRITION`               | NUTRITION                    | NUTRITION    | MEAL                                                |
| `HYDRATION`               | `HydrationRecord`                 | `READ_HYDRATION`               | NUTRITION                    | NUTRITION    | HYDRATION                                           |
| `MENSTRUATION_FLOW`       | `MenstruationFlowRecord`          | `READ_MENSTRUATION`            | MENSTRUATION                 | MENSTRUATION | MENSTRUATION\_FLOW                                  |
| `MENSTRUATION_PERIOD`     | `MenstruationPeriodRecord`        | `READ_MENSTRUATION`            | MENSTRUATION                 | MENSTRUATION | -                                                   |
| `INTERMENSTRUAL_BLEEDING` | `IntermenstrualBleedingRecord`    | `READ_INTERMENSTRUAL_BLEEDING` | MENSTRUATION                 | MENSTRUATION | MENSTRUATION\_EVENT                                 |
| `OVULATION_TEST`          | `OvulationTestRecord`             | `READ_OVULATION_TEST`          | MENSTRUATION                 | MENSTRUATION | MENSTRUATION\_EVENT                                 |
| `CERVICAL_MUCUS`          | `CervicalMucusRecord`             | `READ_CERVICAL_MUCUS`          | MENSTRUATION                 | MENSTRUATION | MENSTRUATION\_EVENT                                 |
| `SEXUAL_ACTIVITY`         | `SexualActivityRecord`            | `READ_SEXUAL_ACTIVITY`         | MENSTRUATION                 | MENSTRUATION | MENSTRUATION\_EVENT                                 |

#### HealthConnectRecordType.isSupported

Reports whether this provider can answer for this type at all.

```kotlin
public fun isSupported(featureStatus: (Int) -> Int): Boolean
```

| Name            | Type           | Description                               |
| --------------- | -------------- | ----------------------------------------- |
| `featureStatus` | `(Int) -> Int` | `HealthConnectFeatures.getFeatureStatus`. |

**Returns:** `true` when the type needs no platform feature, or its feature is available.

#### HealthConnectRecordType.forCategory

Returns the record types a category expands to, which is what a permission request covers.

```kotlin
public fun forCategory(category: DataCategory): Set<HealthConnectRecordType>

public fun forCategory(
    category: DataCategory,
    featureStatus: (Int) -> Int,
): Set<HealthConnectRecordType>
```

| Name            | Type           | Description                                                                                     |
| --------------- | -------------- | ----------------------------------------------------------------------------------------------- |
| `category`      | `DataCategory` | The category.                                                                                   |
| `featureStatus` | `(Int) -> Int` | The provider's feature answers. When passed, types the provider cannot answer for are left out. |

**Returns:** every type whose `categories` contains `category`.

### SampleKind

Which field of [`HealthSamples`](#healthsamples) a record type lands in.

```kotlin
public enum class SampleKind
```

| Case                     | Description                                           |
| ------------------------ | ----------------------------------------------------- |
| `HEART_RATE`             | `heartRate`.                                          |
| `RESTING_HEART_RATE`     | `restingHeartRate`.                                   |
| `STEPS`                  | `steps`.                                              |
| `INTRADAY`               | `intraday`.                                           |
| `WORKOUT_INTENSITY`      | `workoutIntensity`.                                   |
| `SLEEP`                  | `sleep`.                                              |
| `WORKOUT`                | `workouts`. A session's track has no kind of its own. |
| `BODY_MEASUREMENT`       | `bodyMeasurements`.                                   |
| `BLOOD_PRESSURE`         | `bloodPressure`.                                      |
| `BLOOD_GLUCOSE`          | `bloodGlucose`.                                       |
| `OXYGEN_SATURATION`      | `oxygenSaturation`.                                   |
| `BODY_TEMPERATURE`       | `bodyTemperature`.                                    |
| `HEART_RATE_VARIABILITY` | `heartRateVariability`.                               |
| `RESPIRATORY_RATE`       | `respiratoryRate`.                                    |
| `VO2_MAX`                | `vo2Max`.                                             |
| `MEAL`                   | `meals`.                                              |
| `HYDRATION`              | `hydration`.                                          |
| `MENSTRUATION_FLOW`      | `menstruationFlow`.                                   |
| `MENSTRUATION_EVENT`     | `menstruationEvents`.                                 |

### RouteAvailability

Which of Health Connect's three answers a session's route is.

```kotlin
public enum class RouteAvailability
```

| Case               | Description                                                                                                                                 |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| `PRESENT`          | The session has a track and the app may read it.                                                                                            |
| `CONSENT_REQUIRED` | The person has not been through the route consent dialog. `READ_EXERCISE_ROUTES` cannot be granted through the ordinary permission request. |
| `ABSENT`           | The session has no track.                                                                                                                   |

### SessionTotal

What a workout's own window is totalled over, and where each total lands.

```kotlin
public enum class SessionTotal(public val recordType: HealthConnectRecordType)
```

`ExerciseSessionRecord` carries no figures, so the store asks Health Connect's aggregate engine for these over the session's window. Swimming strokes, laps and basal energy are never totalled for a workout. On a type-scoped install, a total is computed only where the install may read the record it sums: `STEPS`, `DISTANCE` and `ACTIVE_ENERGY` need the matching [`HealthDataType`](#healthdatatype) requested, and `ELEVATION_GAIN` comes with `WORKOUTS`.

| Case             | Description                                                          |
| ---------------- | -------------------------------------------------------------------- |
| `STEPS`          | From `STEPS`. Lands in `stats.steps`.                                |
| `DISTANCE`       | From `DISTANCE`. Lands in `Workout.distanceMeters`.                  |
| `ACTIVE_ENERGY`  | From `ACTIVE_CALORIES`. Lands in `Workout.activeEnergyKilocalories`. |
| `ELEVATION_GAIN` | From `ELEVATION_GAINED`. Lands in `stats.elevationGainM`.            |

#### SessionTotal.days

Returns every local day a record can change a session total in.

```kotlin
public fun days(record: Record, zone: ZoneId): List<Instant>
```

| Name     | Type     | Description                         |
| -------- | -------- | ----------------------------------- |
| `record` | `Record` | A Health Connect record.            |
| `zone`   | `ZoneId` | The zone whose local days to count. |

**Returns:** the local-midnight instants, or empty for a record type no session total reads.

#### SessionTotal.applyTo

Returns a workout carrying session totals, leaving alone anything the record already stated.

```kotlin
public fun applyTo(workout: Workout, totals: Map<SessionTotal, Double>): Workout
```

| Name      | Type                        | Description                               |
| --------- | --------------------------- | ----------------------------------------- |
| `workout` | `Workout`                   | The workout read from the session record. |
| `totals`  | `Map<SessionTotal, Double>` | The totals the engine produced.           |

**Returns:** the workout with the totals filled in.

#### SessionTotal.removeFrom

Returns a workout without the figures some totals would have filled. Available in 2.3.0 and later.

```kotlin
public fun removeFrom(workout: Workout, totals: Set<SessionTotal>): Workout
```

**Returns:** the workout with those fields cleared, and `stats` dropped once nothing is left in it. A type-scoped install that did not request `STEPS`, `DISTANCE` or `ACTIVE_ENERGY` uploads its workouts without the matching total.

### HealthConnectRoutes

Which Health Connect record types each upload route reads.

```kotlin
public object HealthConnectRoutes
```

```kotlin
@JvmOverloads
public fun recordTypes(
    route: UploadDataType,
    requested: Set<DataCategory>?,
    types: Set<DataType>? = null,
    requestedTypes: Set<HealthDataType>? = null,
): List<HealthConnectRecordType>
public fun recordTypes(route: UploadDataType): List<HealthConnectRecordType>
public fun admits(
    type: HealthConnectRecordType,
    requested: Set<DataCategory>?,
    requestedTypes: Set<HealthDataType>? = null,
): Boolean
@JvmOverloads
public fun readScopes(
    route: UploadDataType,
    requested: Set<DataCategory>?,
    granted: Set<String>,
    requestedTypes: Set<HealthDataType>? = null,
): Set<String>
@JvmOverloads
public fun attachedPermissions(
    route: UploadDataType,
    requested: Set<DataCategory>? = null,
    requestedTypes: Set<HealthDataType>? = null,
): Set<String>
@JvmOverloads
public fun recordTypesBehindTotals(
    route: UploadDataType,
    requested: Set<DataCategory>? = null,
    requestedTypes: Set<HealthDataType>? = null,
): List<HealthConnectRecordType>
public fun recordType(metric: BodyMeasurement.Metric): HealthConnectRecordType
public fun supported(
    types: List<HealthConnectRecordType>,
    featureStatus: (Int) -> Int,
): List<HealthConnectRecordType>
public fun routedBy(category: DataCategory): List<UploadDataType>
public fun routedBy(type: HealthDataType): List<UploadDataType>
public fun routesFor(category: DataCategory): List<UploadDataType>
public fun readPermissions(route: UploadDataType): Set<String>
public fun category(route: UploadDataType): DataCategory
```

| Function                                               | Description                                                                                                                                           |
| ------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `recordTypes(route, requested, types, requestedTypes)` | The record types `route` reads for an install that asked about `requested` and, in 2.3.0 and later, `requestedTypes`, narrowed to `types` when given. |
| `admits`                                               | Whether an install that asked about `requested` and `requestedTypes` reads `type`. Available in 2.3.0 and later.                                      |
| `recordTypes(route)`                                   | The record types `route` reads, in the order the read issues them.                                                                                    |
| `readScopes`                                           | The permissions `route` actually reads under, out of what the OS reports as `granted`.                                                                |
| `attachedPermissions`                                  | The permissions behind data `route` reads off a record rather than as a record of itself.                                                             |
| `recordTypesBehindTotals`                              | The record types whose arrivals change a total `route` carries.                                                                                       |
| `recordType(metric)`                                   | The record type behind one body measurement metric.                                                                                                   |
| `supported`                                            | `types` without the ones this provider is too old to answer for.                                                                                      |
| `routedBy`                                             | Every route a grant on `category`, or in 2.3.0 and later a request for one `HealthDataType`, feeds.                                                   |
| `routesFor`                                            | The routes a sync may schedule for a grant on `category`.                                                                                             |
| `readPermissions(route)`                               | The read permissions a sync of `route` needs.                                                                                                         |
| `category(route)`                                      | The category a read of `route` belongs to, for reporting a refusal.                                                                                   |

### HealthConnectDayTotals

Which day totals Health Connect's statistics engine can produce.

```kotlin
public object HealthConnectDayTotals
```

| Member        | Type                           | Description                                                                                                                                                                                          |
| ------------- | ------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `SUPPORTED`   | `List<DayTotal.Metric>`        | `STEPS`, `DISTANCE_WALKING_RUNNING`, `ACTIVE_ENERGY_BURNED`, `BASAL_ENERGY_BURNED` and `FLIGHTS_CLIMBED`, in the order the store requests them.                                                      |
| `UNSUPPORTED` | `Map<DayTotal.Metric, String>` | `DISTANCE_CYCLING`, `DISTANCE_SWIMMING` and `DISTANCE_WHEELCHAIR` (Health Connect does not split distance by activity) and `SWIMMING_STROKE_COUNT` (no record counts strokes), each with its reason. |

```kotlin
public fun days(record: Record, zone: ZoneId): List<Instant>
public fun recordTypes(route: UploadDataType): List<HealthConnectRecordType>
public fun recordType(metric: DayTotal.Metric): HealthConnectRecordType?
```

| Function      | Description                                                                                     |
| ------------- | ----------------------------------------------------------------------------------------------- |
| `days`        | Every local day in `zone` that `record` contributes a total to, and nothing for any other type. |
| `recordTypes` | The record types a day total on `route` is computed from.                                       |
| `recordType`  | The record type behind one day-total metric, or `null` when none can produce it.                |

### HealthConnectWrites

Turns write entries into the Health Connect records they become.

```kotlin
public object HealthConnectWrites
```

#### HealthConnectWrites.records

Returns the records an entry becomes, in the order they are written.

```kotlin
public fun records(entry: WriteEntry, zone: ZoneId, version: Long): List<Record>
```

| Name      | Type         | Description                                            |
| --------- | ------------ | ------------------------------------------------------ |
| `entry`   | `WriteEntry` | The entry to write.                                    |
| `zone`    | `ZoneId`     | The zone the records are stamped with.                 |
| `version` | `Long`       | The `clientRecordVersion` the records are filed under. |

**Returns:** the Health Connect records. Every record carries the entry's own id as its `clientRecordId`, so one delete removes all of them and writing the same entry twice is an upsert.

| Error                                | When                                                |
| ------------------------------------ | --------------------------------------------------- |
| `TerraError.BloodPressureIncomplete` | A body entry carries half a blood pressure reading. |

### RecordMapping

Health Connect records, as Terra samples.

```kotlin
public object RecordMapping
```

The store calls these to turn each record it reads into the sample types under [Data types](#data-types). Every mapper that takes `labels` resolves the writing app's display name through it.

#### RecordMapping.AppLabels

How a source name is resolved when the store offers none.

```kotlin
public fun interface AppLabels {
    public fun label(packageName: String): String
}
```

#### RecordMapping.PACKAGE\_NAME\_LABELS

Uses the package name as the label, which is what Health Connect itself reports.

```kotlin
public val PACKAGE_NAME_LABELS: AppLabels
```

#### RecordMapping.mappers

```kotlin
public fun source(
    packageName: String,
    deviceModel: String?,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): SampleSource
public fun source(
    packageName: String,
    deviceModel: String?,
    deviceType: Int?,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): SampleSource
public fun source(metadata: Metadata, labels: AppLabels = PACKAGE_NAME_LABELS): SampleSource
public fun userEntered(metadata: Metadata): Boolean
public fun heartRate(
    record: HeartRateRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): List<HeartRateSample>
public fun restingHeartRate(
    record: RestingHeartRateRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): RestingHeartRateSample
public fun steps(
    record: StepsRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): StepCount
public fun activeEnergy(
    record: ActiveCaloriesBurnedRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): IntradaySample
public fun distance(
    record: DistanceRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): IntradaySample
public fun floorsClimbed(
    record: FloorsClimbedRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): IntradaySample
public fun sleep(
    record: SleepSessionRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): List<SleepSegment>
public fun workout(
    record: ExerciseSessionRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): Workout
public fun speed(
    record: SpeedRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): List<WorkoutIntensitySample>
public fun power(
    record: PowerRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): List<WorkoutIntensitySample>
public fun cyclingCadence(
    record: CyclingPedalingCadenceRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): List<WorkoutIntensitySample>
public fun workoutRoute(
    record: ExerciseSessionRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): WorkoutRoute?
public fun routeAvailability(result: ExerciseRouteResult): RouteAvailability
public fun dayTotal(
    metric: DayTotal.Metric,
    dayStart: Instant,
    dayEnd: Instant,
    value: Double?,
    zone: ZoneId?,
): DayTotal?
public fun intermenstrualBleeding(
    record: IntermenstrualBleedingRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): MenstruationEventSample
public fun ovulationTest(
    record: OvulationTestRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): MenstruationEventSample?
public fun cervicalMucus(
    record: CervicalMucusRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): MenstruationEventSample?
public fun sexualActivity(
    record: SexualActivityRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): MenstruationEventSample?
public fun weight(record: WeightRecord, labels: AppLabels = PACKAGE_NAME_LABELS): BodyMeasurement
public fun height(record: HeightRecord, labels: AppLabels = PACKAGE_NAME_LABELS): BodyMeasurement
public fun bodyFat(record: BodyFatRecord, labels: AppLabels = PACKAGE_NAME_LABELS): BodyMeasurement
public fun leanBodyMass(record: LeanBodyMassRecord, labels: AppLabels = PACKAGE_NAME_LABELS): BodyMeasurement
public fun boneMass(record: BoneMassRecord, labels: AppLabels = PACKAGE_NAME_LABELS): BodyMeasurement
public fun bodyWaterMass(record: BodyWaterMassRecord, labels: AppLabels = PACKAGE_NAME_LABELS): BodyMeasurement
public fun basalMetabolicRate(
    record: BasalMetabolicRateRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): BodyMeasurement
public fun bloodPressure(
    record: BloodPressureRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): BloodPressureSample
public fun bloodGlucose(
    record: BloodGlucoseRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): BloodGlucoseSample
public fun oxygenSaturation(
    record: OxygenSaturationRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): OxygenSaturationSample
public fun bodyTemperature(
    record: BodyTemperatureRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): BodyTemperatureSample
public fun basalBodyTemperature(
    record: BasalBodyTemperatureRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): BodyTemperatureSample
public fun skinTemperature(
    record: SkinTemperatureRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): List<BodyTemperatureSample>
public fun heartRateVariability(
    record: HeartRateVariabilityRmssdRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): HeartRateVariabilitySample
public fun respiratoryRate(
    record: RespiratoryRateRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): RespiratoryRateSample
public fun vo2Max(
    record: Vo2MaxRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): Vo2MaxSample
public fun meal(record: NutritionRecord, labels: AppLabels = PACKAGE_NAME_LABELS): MealSample?
public fun hydration(
    record: HydrationRecord,
    labels: AppLabels = PACKAGE_NAME_LABELS,
): HydrationSample
public fun menstruationFlow(
    record: MenstruationFlowRecord,
    zone: ZoneId,
    labels: AppLabels = PACKAGE_NAME_LABELS,
    cycleStarts: Set<Instant> = emptySet(),
): MenstruationFlowSample
public fun cycleStartDays(records: List<MenstruationPeriodRecord>, zone: ZoneId): Set<Instant>
public fun markingCycleStarts(
    flows: List<MenstruationFlowSample>,
    startDays: Set<Instant>,
): List<MenstruationFlowSample>
public fun periodDays(record: MenstruationPeriodRecord, zone: ZoneId): List<Instant>
```

| Function                                                                                   | Description                                                                                                                                                                                              |
| ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`                                                                                   | Builds a [`SampleSource`](#samplesource) from the writing app's package, the device model and, in the second overload, Health Connect's device type. The third overload reads both from record metadata. |
| `userEntered`                                                                              | Whether a person typed this record in rather than a sensor recording it.                                                                                                                                 |
| `heartRate`                                                                                | Every beat sample in the record, one sample each.                                                                                                                                                        |
| `restingHeartRate`                                                                         | The store's own resting figure, carried through rather than recomputed.                                                                                                                                  |
| `steps`                                                                                    | One step bucket exactly as the store recorded it, never a day's sum.                                                                                                                                     |
| `activeEnergy`, `distance`, `floorsClimbed`                                                | One intraday sample per record.                                                                                                                                                                          |
| `sleep`                                                                                    | A sleep session as segments.                                                                                                                                                                             |
| `workout`                                                                                  | One workout, as far as the session record alone states it.                                                                                                                                               |
| `speed`, `power`, `cyclingCadence`                                                         | Every reading in the series, one workout intensity sample each.                                                                                                                                          |
| `workoutRoute`                                                                             | The track a session left, or `null` where the store held none.                                                                                                                                           |
| `routeAvailability`                                                                        | Which of Health Connect's three route answers a result is.                                                                                                                                               |
| `dayTotal`                                                                                 | One day total from a value the statistics engine produced, or `null` when there is no value.                                                                                                             |
| `intermenstrualBleeding`, `ovulationTest`, `cervicalMucus`, `sexualActivity`               | One cycle event per record. The last three return `null` for a record with nothing to report.                                                                                                            |
| `weight`, `height`, `bodyFat`, `leanBodyMass`                                              | One body measurement, in the unit the wire fixes for it. `bodyFat` converts Health Connect's `0..100` to a `0..1` fraction.                                                                              |
| `boneMass`, `bodyWaterMass`, `basalMetabolicRate`                                          | The Health Connect measures HealthKit has no record for.                                                                                                                                                 |
| `bloodPressure`                                                                            | One reading, both values.                                                                                                                                                                                |
| `bloodGlucose`                                                                             | One glucose reading, in millimoles per litre.                                                                                                                                                            |
| `oxygenSaturation`, `bodyTemperature`, `basalBodyTemperature`, `respiratoryRate`, `vo2Max` | One sample per record.                                                                                                                                                                                   |
| `skinTemperature`                                                                          | Every delta in a skin-temperature record, one sample each.                                                                                                                                               |
| `heartRateVariability`                                                                     | RMSSD, the only statistic Health Connect records.                                                                                                                                                        |
| `meal`                                                                                     | One meal, or `null` when the record names nothing that was eaten.                                                                                                                                        |
| `hydration`                                                                                | One hydration sample per record.                                                                                                                                                                         |
| `menstruationFlow`                                                                         | One flow record as the day it belongs to, with `cycleStart` set when that day is in `cycleStarts`.                                                                                                       |
| `cycleStartDays`                                                                           | The local day each period began on.                                                                                                                                                                      |
| `markingCycleStarts`                                                                       | The flows with `cycleStart` set on the days `startDays` names.                                                                                                                                           |
| `periodDays`                                                                               | Every local day a period record covers.                                                                                                                                                                  |

### HealthConnectSleepStages

Health Connect's sleep stages, in Terra's vocabulary.

```kotlin
public object HealthConnectSleepStages

public fun terraStage(stage: Int): SleepStage
public const val RAW_OUT_OF_BED: String = "out_of_bed"
public const val RAW_UNKNOWN: String = "unknown"
public const val RAW_UNRECOGNISED: String = "health_connect_stage_"
public fun healthConnectStage(stage: SleepStage): Int
```

| Member                          | Description                                                                                            |
| ------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `terraStage`                    | The Terra stage for a Health Connect stage constant.                                                   |
| `healthConnectStage`            | The Health Connect constant for a Terra stage, which a write files it under.                           |
| `RAW_OUT_OF_BED`, `RAW_UNKNOWN` | The legacy SDK's own spellings, kept so a stage means the same thing across SDK versions.              |
| `RAW_UNRECOGNISED`              | The prefix for a stage constant this SDK version predates, carried verbatim so Terra can still map it. |

### HealthConnectExerciseTypes

Health Connect's exercise types, in Terra's vocabulary.

```kotlin
public object HealthConnectExerciseTypes

public fun activity(exerciseType: Int): WorkoutActivity
public const val RAW_UNRECOGNISED: String = "health_connect_exercise_"
public fun exerciseType(activity: WorkoutActivity): Int
```

| Member             | Description                                                                             |
| ------------------ | --------------------------------------------------------------------------------------- |
| `activity`         | The Terra activity for a Health Connect exercise type.                                  |
| `exerciseType`     | The Health Connect exercise type for a Terra activity, which a write files it under.    |
| `RAW_UNRECOGNISED` | The prefix for an exercise type this SDK version predates. Terra maps the integer code. |

### HealthConnectMealTypes

Health Connect's meal types, in the spelling the nutrition route carries.

```kotlin
public object HealthConnectMealTypes

public fun mealName(mealType: Int): String
public fun terraMealType(mealType: Int): MealSample.MealType
```

| Member          | Description                                         |
| --------------- | --------------------------------------------------- |
| `mealName`      | The Terra meal name for a Health Connect meal type. |
| `terraMealType` | The Terra meal type for a Health Connect meal type. |

### HealthConnectMenstruationFlow

Health Connect's menstrual flow levels, in Terra's vocabulary.

```kotlin
public object HealthConnectMenstruationFlow

public fun flowName(flow: Int): String
public fun terraFlow(flow: Int): MenstruationFlowSample.Flow
```

| Member      | Description                                             |
| ----------- | ------------------------------------------------------- |
| `flowName`  | The Terra flow name for a Health Connect flow constant. |
| `terraFlow` | The Terra flow for a Health Connect flow constant.      |

### HealthConnectDeviceTypes

What kind of device wrote a record, in the wire's vocabulary.

```kotlin
public object HealthConnectDeviceTypes

public fun deviceTypeName(deviceType: Int?): String?
```

| Member           | Description                                                                               |
| ---------------- | ----------------------------------------------------------------------------------------- |
| `deviceTypeName` | The wire's name for a Health Connect device type, or `null` where it says nothing useful. |

### HealthConnectBloodGlucose

Health Connect's blood-glucose metadata, in the wire's vocabulary.

```kotlin
public object HealthConnectBloodGlucose

public fun mealTime(relationToMeal: Int): BloodGlucoseSample.MealTime
public fun specimen(specimenSource: Int): BloodGlucoseSample.Specimen
```

| Member     | Description                                                                    |
| ---------- | ------------------------------------------------------------------------------ |
| `mealTime` | Where a glucose reading sits relative to a meal.                               |
| `specimen` | What was sampled, which decides whether a reading is a continuous-monitor one. |

### HealthConnectVo2Max

Health Connect's six VO2 measurement methods, as the wire's three test types.

```kotlin
public object HealthConnectVo2Max

public fun testType(measurementMethod: Int): Vo2MaxSample.TestType?
```

| Member     | Description                                                                                              |
| ---------- | -------------------------------------------------------------------------------------------------------- |
| `testType` | The wire's test type for one of Health Connect's six measurement methods, or `null` where it names none. |

### HealthConnectNutrients

Health Connect's `NutritionRecord` fields, as the wire's nutrient keys.

```kotlin
public object HealthConnectNutrients

public fun nutrients(record: NutritionRecord): Map<Nutrient, Double>
```

| Member      | Description                                                                 |
| ----------- | --------------------------------------------------------------------------- |
| `nutrients` | Every nutrient a nutrition record carries, in [`Nutrient.unit`](#nutrient). |

### DeviceKey

The device's half of the upload credential.

```kotlin
public interface DeviceKey
```

The private key is generated on the device and never leaves it. This type deliberately does not carry it.

#### DeviceKey.publicKey

The P-256 public key as base64 DER SubjectPublicKeyInfo, the encoding Terra's ingest parses.

```kotlin
public val publicKey: String
```

#### DeviceKey.signature

Returns the base64 DER ECDSA signature over a message.

```kotlin
public suspend fun signature(message: ByteArray): String
```

| Name      | Type        | Description                                                  |
| --------- | ----------- | ------------------------------------------------------------ |
| `message` | `ByteArray` | The bytes to sign, unhashed. The key applies SHA-256 itself. |

**Returns:** the signature for the `terra-signature` header.

### DeviceKeyStore

Where the device's signing key lives.

```kotlin
public interface DeviceKeyStore
```

[`AndroidKeystoreDeviceKeyStore`](#androidkeystoredevicekeystore) is the production implementation; [`InMemoryDeviceKeyStore`](#inmemorydevicekeystore) is the testkit's. Creating and reading are separate calls, and only linking creates.

#### DeviceKeyStore.createKey

Returns the key for a source and link generation, creating one if there is none.

```kotlin
public suspend fun createKey(source: Source, generation: Int): DeviceKey
```

| Name         | Type                | Description                 |
| ------------ | ------------------- | --------------------------- |
| `source`     | [`Source`](#source) | The source the link is for. |
| `generation` | `Int`               | The link generation.        |

**Returns:** the [`DeviceKey`](#devicekey).

{% hint style="warning" %}
Only the link path may call this. A key created anywhere else is one Terra has never registered, and every upload signed with it is rejected.
{% endhint %}

#### DeviceKeyStore.key

Returns a generation's existing key, or `null` when there is none.

```kotlin
public suspend fun key(source: Source, generation: Int): DeviceKey?
```

| Name         | Type                | Description                 |
| ------------ | ------------------- | --------------------------- |
| `source`     | [`Source`](#source) | The source the link is for. |
| `generation` | `Int`               | The link generation.        |

**Returns:** the key, or `null`. It never creates one.

#### DeviceKeyStore.deleteKey

Forgets a generation's key, so a signed-out device cannot keep uploading.

```kotlin
public suspend fun deleteKey(source: Source, generation: Int)
```

| Name         | Type                | Description                 |
| ------------ | ------------------- | --------------------------- |
| `source`     | [`Source`](#source) | The source the link is for. |
| `generation` | `Int`               | The link generation.        |

### DeviceKeys

The one place a public key becomes the string Terra stores, shared by every [`DeviceKeyStore`](#devicekeystore).

```kotlin
public object DeviceKeys
```

#### DeviceKeys.publicKeyBase64

Returns a public key as base64 DER SubjectPublicKeyInfo.

```kotlin
public fun publicKeyBase64(key: PublicKey): String
```

| Name  | Type        | Description        |
| ----- | ----------- | ------------------ |
| `key` | `PublicKey` | The key to encode. |

**Returns:** the base64 string.

| Error                             | When                                                                                           |
| --------------------------------- | ---------------------------------------------------------------------------------------------- |
| `TerraError.DeviceKeyUnavailable` | The key is not an EC key, not on P-256, not exportable, or not a 91-byte SubjectPublicKeyInfo. |

### AndroidKeystoreDeviceKeyStore

The production [`DeviceKeyStore`](#devicekeystore): P-256 keys generated inside the Android Keystore.

```kotlin
public class AndroidKeystoreDeviceKeyStore(
    private val service: String = DEFAULT_SERVICE,
    private val io: CoroutineDispatcher = Dispatchers.IO,
) : DeviceKeyStore
```

| Name      | Type                  | Description                                                                                                     |
| --------- | --------------------- | --------------------------------------------------------------------------------------------------------------- |
| `service` | `String`              | Scopes key aliases so two Terra clients in one app do not share a key. Optional. Defaults to `DEFAULT_SERVICE`. |
| `io`      | `CoroutineDispatcher` | Where every Keystore call runs. Optional. Defaults to `Dispatchers.IO`.                                         |

Keys are generated in the TEE and never in StrongBox. On a device with no secure hardware the Keystore places the key in software, and the SDK accepts it. `createKey` returns the existing key for a generation rather than replacing it.

| Error                             | When                                                                                                                                      |
| --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `TerraError.DeviceKeyUnavailable` | The Keystore could not be opened, refused to read, generate or delete a key, or the alias holds something other than a P-256 private key. |

#### AndroidKeystoreDeviceKeyStore.DEFAULT\_SERVICE

The default alias namespace.

```kotlin
public const val DEFAULT_SERVICE: String = "co.tryterra.sdk.devicekey"
```

### InstallIdentity

This installation's stable identity, which Terra uses to recognise a returning device.

```kotlin
public fun interface InstallIdentity {
    public fun value(): String
}
```

If it changed between launches, every launch would create a new Terra user or replace the previous connection. [`AndroidInstallIdentity`](#androidinstallidentity) is the production implementation.

#### InstallIdentity.value

Returns the identity.

```kotlin
public fun value(): String
```

**Returns:** the identity string.

### AndroidInstallIdentity

The production [`InstallIdentity`](#installidentity): the device's `ANDROID_ID`, which the 1.x SDK also sent.

```kotlin
public class AndroidInstallIdentity(private val context: Context) : InstallIdentity
```

| Name      | Type      | Description                                    |
| --------- | --------- | ---------------------------------------------- |
| `context` | `Context` | The context `Settings.Secure` is read through. |

`value()` returns `ANDROID_ID`. When the device reports none, a blank one or all zeros, it returns a random value of the same shape: sixteen lowercase hex characters. Since Android 8 the value is scoped per app signing key and per device user. It resets on a factory reset and on a reinstall after the signing key changes, so the SDK persists the settled value rather than re-reading it on every link.

{% hint style="warning" %}
Do not hash or extend this value. Terra routes a link as Android because the identity is exactly 16 characters long.
{% endhint %}

### StoredConnection

A link between this install and one Terra user, as persisted.

```kotlin
public data class StoredConnection(
    public val source: Source,
    public val userId: String,
    public val providerUserId: String,
    public val generation: Int = 0,
    public val devId: String = "",
    public val endUser: String? = null,
    public val devIdBindings: List<DevIdBinding> = emptyList(),
    public val sharedDataTypes: List<UploadDataType>? = null,
    public val sharedDataTypesAt: Instant? = null,
    public val primaryDevId: String? = null,
    public val pendingLinks: List<PendingDevIdLink> = emptyList(),
)
```

| Property            | Type                     | Description                                                                                                                                                                                                                                                                  |
| ------------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `source`            | [`Source`](#source)      | The linked source.                                                                                                                                                                                                                                                           |
| `userId`            | `String`                 | Terra's id for the connection, the `user_id` on webhooks and API reads.                                                                                                                                                                                                      |
| `providerUserId`    | `String`                 | The identity the connection is filed under, stored so a later change to `ANDROID_ID` does not move the device to a connection that does not exist.                                                                                                                           |
| `generation`        | `Int`                    | Increments every time the device key is replaced. Defaults to `0`.                                                                                                                                                                                                           |
| `devId`             | `String`                 | The developer id the connection was linked under. Empty for a record written before the field existed. Defaults to `""`.                                                                                                                                                     |
| `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. `null` for a record written before the field existed, which the next `connect` adopts. Defaults to `null`. |
| `devIdBindings`     | `List<DevIdBinding>`     | In [`DevIdMode.MULTIPLE`](#devidmode), one [`DevIdBinding`](#devidbinding) per linked customer. Defaults to empty. Available in 2.3.0 and later, as are the fields below.                                                                                                    |
| `sharedDataTypes`   | `List<UploadDataType>?`  | The union of customer selections from Terra's last init answer, or `null` until it answers. Defaults to `null`.                                                                                                                                                              |
| `sharedDataTypesAt` | `Instant?`               | When that answer arrived. Defaults to `null`.                                                                                                                                                                                                                                |
| `primaryDevId`      | `String?`                | The customer support reports go to: the first linked, moved only when that customer unlinks or is gone. Defaults to `null`.                                                                                                                                                  |
| `pendingLinks`      | `List<PendingDevIdLink>` | Customer links started and not yet seen to finish, each a `PendingDevIdLink(devId, startedAt)`. Defaults to empty.                                                                                                                                                           |
| `liveBindings`      | `List<DevIdBinding>`     | The bindings with no unlink owed.                                                                                                                                                                                                                                            |
| `activeBindings`    | `List<DevIdBinding>`     | The live bindings Terra still delivers to.                                                                                                                                                                                                                                   |
| `primaryBinding`    | `DevIdBinding?`          | The pinned primary customer while it is active, else the earliest-linked active one.                                                                                                                                                                                         |

#### StoredConnection.isForeignTo

Reports whether this record belongs to a Terra environment the configured developer id does not name.

```kotlin
public fun isForeignTo(configured: String): Boolean
```

| Name         | Type     | Description                                     |
| ------------ | -------- | ----------------------------------------------- |
| `configured` | `String` | The developer id the client is configured with. |

**Returns:** `true` when `devId` is set and differs from `configured`. A record with an empty `devId` is never foreign.

### DeviceStore

Everything the SDK remembers between launches, behind one interface.

```kotlin
public interface DeviceStore
```

No health value is ever persisted here: only identity, resume points and delivery bookkeeping. [`AndroidDeviceStore`](#androiddevicestore) is the production implementation; [`InMemoryDeviceStore`](#inmemorydevicestore) is the testkit's.

Members that take `ifGeneration` are conditional writes: the store refuses them, and returns `false`, when the connection's generation has moved on since the caller read it.

#### DeviceStore.connection

Returns the stored connection for a source, or `null`.

```kotlin
public suspend fun connection(source: Source): StoredConnection?
```

| Name     | Type                | Description            |
| -------- | ------------------- | ---------------------- |
| `source` | [`Source`](#source) | The source to look up. |

**Returns:** the [`StoredConnection`](#storedconnection), or `null` when none is stored.

#### DeviceStore.putConnection

Stores a connection, replacing any for the same source.

```kotlin
public suspend fun putConnection(connection: StoredConnection)
```

| Name         | Type                                    | Description              |
| ------------ | --------------------------------------- | ------------------------ |
| `connection` | [`StoredConnection`](#storedconnection) | The connection to store. |

#### DeviceStore.removeConnection

Removes the stored connection for a source.

```kotlin
public suspend fun removeConnection(source: Source)
```

| Name     | Type                | Description                            |
| -------- | ------------------- | -------------------------------------- |
| `source` | [`Source`](#source) | The source whose connection to remove. |

#### DeviceStore.connections

Returns every stored connection.

```kotlin
public suspend fun connections(): List<StoredConnection>
```

**Returns:** the stored connections.

#### DeviceStore.updateConnection

Rewrites a source's connection in one step, unless the link has moved on from a generation. Available in 2.3.0 and later.

```kotlin
public suspend fun updateConnection(
    source: Source,
    ifGeneration: Int,
    transform: (StoredConnection) -> StoredConnection?,
): Boolean
```

| Name           | Type                                      | Description                                                  |
| -------------- | ----------------------------------------- | ------------------------------------------------------------ |
| `source`       | [`Source`](#source)                       | The connection to rewrite.                                   |
| `ifGeneration` | `Int`                                     | The generation the stored connection must still have.        |
| `transform`    | `(StoredConnection) -> StoredConnection?` | Returns the record to write, or `null` to leave it as it is. |

**Returns:** `true` when a record was written. The default reads and writes in two steps, which is atomic only for a store with one writer. [`DevIdMode.MULTIPLE`](#devidmode) uses it to change bindings.

#### DeviceStore.activeDevId

Returns the developer id this storage domain is owned by, or `null` before one claimed it.

```kotlin
public suspend fun activeDevId(): String?
```

**Returns:** the owning developer id, or `null` on a fresh install or one linked before the record existed.

#### DeviceStore.claimDevId

Claims this storage domain for a developer id, or reports that a different id already holds it.

```kotlin
public suspend fun claimDevId(devId: String): Boolean
```

| Name    | Type     | Description                           |
| ------- | -------- | ------------------------------------- |
| `devId` | `String` | The developer id claiming the domain. |

**Returns:** `false` when a different developer id owns the domain, in which case nothing was written. Idempotent for the id that already owns it. A store that cannot take the write throws rather than returning `false`.

#### DeviceStore.providerUserId

Returns the settled install identity, or `null` before the first link settled one.

```kotlin
public suspend fun providerUserId(): String?
```

**Returns:** the identity, or `null`.

#### DeviceStore.saveProviderUserId

Stores the install identity.

```kotlin
public suspend fun saveProviderUserId(value: String)
```

| Name    | Type     | Description            |
| ------- | -------- | ---------------------- |
| `value` | `String` | The identity to store. |

#### DeviceStore.settleProviderUserId

Returns the identity this install is filed under, settling a candidate's answer if there is none.

```kotlin
public suspend fun settleProviderUserId(candidate: () -> String): String
```

| Name        | Type           | Description                                                                 |
| ----------- | -------------- | --------------------------------------------------------------------------- |
| `candidate` | `() -> String` | Produces an identity. Called at most once, and only when nothing is stored. |

**Returns:** the stored identity. Read-modify-write in one call, so two links in flight settle the same value.

#### DeviceStore.claimGeneration

Claims the generation a fresh link for a source will open, and never hands it out twice.

```kotlin
public suspend fun claimGeneration(source: Source): Int
```

| Name     | Type                | Description              |
| -------- | ------------------- | ------------------------ |
| `source` | [`Source`](#source) | The source being linked. |

**Returns:** the new generation. Monotonic across disconnects.

#### DeviceStore.lastDelivery

Returns when data for a source last reached Terra, or `null` if it never has.

```kotlin
public suspend fun lastDelivery(source: Source): Instant?
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** the instant, or `null`.

#### DeviceStore.noteDelivery

Records a delivery.

```kotlin
public suspend fun noteDelivery(source: Source, at: Instant)
```

| Name     | Type                | Description             |
| -------- | ------------------- | ----------------------- |
| `source` | [`Source`](#source) | The source delivered.   |
| `at`     | `Instant`           | When Terra accepted it. |

#### DeviceStore.flush

Blocks until everything written so far is on disk.

```kotlin
public suspend fun flush(): Unit = Unit
```

It exists for the process exit `ProcessExitPolicy.EXIT_WHEN_IDLE` performs. The default does nothing, which is complete for a store whose writes are durable when they return.

#### DeviceStore.linkRevoked

Reports whether Terra has stopped accepting this device's key for a source.

```kotlin
public suspend fun linkRevoked(source: Source): Boolean
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** `true` once a re-signed request has been refused a second time. Persisted, so later syncs fail with `TerraError.LinkRevoked` without a request.

#### DeviceStore.markLinkRevoked

Records that Terra has refused this device's key, unless the link has been replaced since.

```kotlin
public suspend fun markLinkRevoked(source: Source, ifGeneration: Int): Boolean
```

| Name           | Type                | Description                           |
| -------------- | ------------------- | ------------------------------------- |
| `source`       | [`Source`](#source) | The source.                           |
| `ifGeneration` | `Int`               | The generation the refusal was about. |

**Returns:** `false` when the write was refused.

#### DeviceStore.retryPending

Reports whether a delivery for a source failed retryably and is waiting to try again.

```kotlin
public suspend fun retryPending(source: Source): Boolean
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** `true` while a retry is pending.

#### DeviceStore.noteRetryPending

Records whether a retry is pending.

```kotlin
public suspend fun noteRetryPending(source: Source, pending: Boolean)
```

| Name      | Type                | Description                 |
| --------- | ------------------- | --------------------------- |
| `source`  | [`Source`](#source) | The source.                 |
| `pending` | `Boolean`           | Whether a retry is pending. |

#### DeviceStore.reserveDiagnosticsSend

Takes a diagnostics send slot if the budget admits it, and records it in the same write.

```kotlin
public suspend fun reserveDiagnosticsSend(
    send: DiagnosticsSend,
    notWithinSeconds: Long,
    automaticLimit: Int?,
): Boolean
```

| Name               | Type              | Description                                           |
| ------------------ | ----------------- | ----------------------------------------------------- |
| `send`             | `DiagnosticsSend` | The report about to be sent.                          |
| `notWithinSeconds` | `Long`            | The minimum gap since the last send of the same kind. |
| `automaticLimit`   | `Int?`            | The cap on automatic sends, or `null` for none.       |

**Returns:** `false` when the budget refuses.

#### DeviceStore.releaseDiagnosticsSend

Gives back a slot for a report that never left the device.

```kotlin
public suspend fun releaseDiagnosticsSend(send: DiagnosticsSend)
```

| Name   | Type              | Description                     |
| ------ | ----------------- | ------------------------------- |
| `send` | `DiagnosticsSend` | The send whose slot to release. |

#### DeviceStore.recordRequestedAccess

Folds an access into the running record of everything this install has asked a source for, and returns the union.

```kotlin
public suspend fun recordRequestedAccess(source: Source, access: HealthAccess): HealthAccess
```

| Name     | Type                            | Description                        |
| -------- | ------------------------------- | ---------------------------------- |
| `source` | [`Source`](#source)             | The source asked. Kept per source. |
| `access` | [`HealthAccess`](#healthaccess) | The access just requested.         |

**Returns:** the union of everything ever requested of `source`.

#### DeviceStore.loadRequestedAccess

Returns everything ever requested of a source.

```kotlin
public suspend fun loadRequestedAccess(source: Source): HealthAccess
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** the access, empty before the first request.

#### DeviceStore.claimSync

Takes the sync claim for one route, or reports that something else holds it.

```kotlin
public suspend fun claimSync(source: Source, dataType: UploadDataType): Boolean
```

| Name       | Type                                | Description |
| ---------- | ----------------------------------- | ----------- |
| `source`   | [`Source`](#source)                 | The source. |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.  |

**Returns:** `false` when another run holds the claim. It refuses rather than waits. Claims are held in memory, never persisted.

#### DeviceStore.releaseSync

Hands back a sync claim.

```kotlin
public suspend fun releaseSync(source: Source, dataType: UploadDataType)
```

| Name       | Type                                | Description |
| ---------- | ----------------------------------- | ----------- |
| `source`   | [`Source`](#source)                 | The source. |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.  |

Safe to call for a claim the caller never held.

#### DeviceStore.claimBackfillQueue

Takes the backfill queue's claim for a source, or reports that another poll holds it.

```kotlin
public suspend fun claimBackfillQueue(source: Source): Boolean
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** `false` when another poll holds it.

#### DeviceStore.releaseBackfillQueue

Hands back the backfill queue's claim.

```kotlin
public suspend fun releaseBackfillQueue(source: Source)
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

#### DeviceStore.claimLink

Takes the link claim for a source, or reports that something else holds it.

```kotlin
public suspend fun claimLink(source: Source): Boolean
```

| Name     | Type                | Description              |
| -------- | ------------------- | ------------------------ |
| `source` | [`Source`](#source) | The source being linked. |

**Returns:** `false` when another link is in flight. Terra registers one key per link, so two concurrent links would leave the device signing with a key the server does not verify against.

#### DeviceStore.releaseLink

Hands back a link claim.

```kotlin
public suspend fun releaseLink(source: Source)
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

Safe to call for a claim the caller never held.

#### DeviceStore.syncedThrough

Returns the end of the newest window walked forward for a route, or `null` before the first.

```kotlin
public suspend fun syncedThrough(source: Source, dataType: UploadDataType): Instant?
```

| Name       | Type                                | Description |
| ---------- | ----------------------------------- | ----------- |
| `source`   | [`Source`](#source)                 | The source. |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.  |

**Returns:** the mark, or `null`.

#### DeviceStore.saveSyncedThrough

Records the forward mark for a route, refusing if the connection has moved on.

```kotlin
public suspend fun saveSyncedThrough(
    at: Instant,
    source: Source,
    dataType: UploadDataType,
    ifGeneration: Int,
): Boolean
```

| Name           | Type                                | Description                  |
| -------------- | ----------------------------------- | ---------------------------- |
| `at`           | `Instant`                           | The new mark.                |
| `source`       | [`Source`](#source)                 | The source.                  |
| `dataType`     | [`UploadDataType`](#uploaddatatype) | The route.                   |
| `ifGeneration` | `Int`                               | The generation the run read. |

**Returns:** `false` when the write was refused.

#### DeviceStore.syncedFrom

Returns the start of the oldest window this link has walked, or `null` before the first.

```kotlin
public suspend fun syncedFrom(source: Source, dataType: UploadDataType): Instant?
```

| Name       | Type                                | Description |
| ---------- | ----------------------------------- | ----------- |
| `source`   | [`Source`](#source)                 | The source. |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.  |

**Returns:** the floor, or `null`.

#### DeviceStore.saveSyncedFrom

Records the history floor for a route, refusing if the connection has moved on.

```kotlin
public suspend fun saveSyncedFrom(
    at: Instant,
    source: Source,
    dataType: UploadDataType,
    ifGeneration: Int,
): Boolean
```

| Name           | Type                                | Description                  |
| -------------- | ----------------------------------- | ---------------------------- |
| `at`           | `Instant`                           | The new floor.               |
| `source`       | [`Source`](#source)                 | The source.                  |
| `dataType`     | [`UploadDataType`](#uploaddatatype) | The route.                   |
| `ifGeneration` | `Int`                               | The generation the run read. |

**Returns:** `false` when the write was refused.

#### DeviceStore.recheckFrom

Returns how far back a run must reach, whatever horizon its caller asked for, or `null` for none.

```kotlin
public suspend fun recheckFrom(source: Source, dataType: UploadDataType): Instant?
```

| Name       | Type                                | Description |
| ---------- | ----------------------------------- | ----------- |
| `source`   | [`Source`](#source)                 | The source. |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.  |

**Returns:** the recheck floor, set when a change token expires and cleared once a walk has reached it.

#### DeviceStore.saveRecheckFrom

Records or clears the recheck floor for a route.

```kotlin
public suspend fun saveRecheckFrom(
    at: Instant?,
    source: Source,
    dataType: UploadDataType,
    ifGeneration: Int,
): Boolean
```

| Name           | Type                                | Description                       |
| -------------- | ----------------------------------- | --------------------------------- |
| `at`           | `Instant?`                          | The floor, or `null` to clear it. |
| `source`       | [`Source`](#source)                 | The source.                       |
| `dataType`     | [`UploadDataType`](#uploaddatatype) | The route.                        |
| `ifGeneration` | `Int`                               | The generation the run read.      |

**Returns:** `false` when the write was refused.

#### DeviceStore.syncAnchor

Returns the store's change-feed position for a route, or `null` before the first anchored pass.

```kotlin
public suspend fun syncAnchor(source: Source, dataType: UploadDataType): ChangeAnchor?
```

| Name       | Type                                | Description |
| ---------- | ----------------------------------- | ----------- |
| `source`   | [`Source`](#source)                 | The source. |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.  |

**Returns:** the [`ChangeAnchor`](#changeanchor), or `null`.

#### DeviceStore.saveSyncAnchor

Records the change-feed position for a route.

```kotlin
public suspend fun saveSyncAnchor(
    anchor: ChangeAnchor?,
    source: Source,
    dataType: UploadDataType,
    ifGeneration: Int,
): Boolean
```

| Name           | Type                                | Description                        |
| -------------- | ----------------------------------- | ---------------------------------- |
| `anchor`       | [`ChangeAnchor?`](#changeanchor)    | The anchor, or `null` to clear it. |
| `source`       | [`Source`](#source)                 | The source.                        |
| `dataType`     | [`UploadDataType`](#uploaddatatype) | The route.                         |
| `ifGeneration` | `Int`                               | The generation the run read.       |

**Returns:** `false` when the write was refused.

#### DeviceStore.anchorGrants

Returns the read scopes a route's change anchor was issued under, or `null` before one was.

```kotlin
public suspend fun anchorGrants(source: Source, dataType: UploadDataType): Set<String>?
```

| Name       | Type                                | Description |
| ---------- | ----------------------------------- | ----------- |
| `source`   | [`Source`](#source)                 | The source. |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.  |

**Returns:** [`HealthStore.readScopes`](#healthstore.readscopes)'s answer at the time, verbatim. A widened grant means the anchor no longer covers everything readable.

#### DeviceStore.saveAnchorGrants

Records the grant set an anchor was issued under.

```kotlin
public suspend fun saveAnchorGrants(
    scopes: Set<String>,
    source: Source,
    dataType: UploadDataType,
    ifGeneration: Int,
): Boolean
```

| Name           | Type                                | Description                  |
| -------------- | ----------------------------------- | ---------------------------- |
| `scopes`       | `Set<String>`                       | The read scopes.             |
| `source`       | [`Source`](#source)                 | The source.                  |
| `dataType`     | [`UploadDataType`](#uploaddatatype) | The route.                   |
| `ifGeneration` | `Int`                               | The generation the run read. |

**Returns:** `false` when the write was refused. Written last, after the reset it justifies.

#### DeviceStore.clearMarks

Forgets every mark, floor, anchor and owed backfill for a source.

```kotlin
public suspend fun clearMarks(source: Source)
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

Called on disconnect and on a relink.

#### DeviceStore.nextWriteVersion

Returns the next `clientRecordVersion` a write may be filed under, higher than every one before it.

```kotlin
public suspend fun nextWriteVersion(at: Instant): Long
```

| Name | Type      | Description                               |
| ---- | --------- | ----------------------------------------- |
| `at` | `Instant` | The clock reading that seeds the counter. |

**Returns:** the version. Persisted and strictly increasing, even when the clock steps back.

#### DeviceStore.savePendingRevocation

Records a revoke this device owes Terra and could not deliver, or replaces the one it holds.

```kotlin
public suspend fun savePendingRevocation(revocation: PendingRevocation): Boolean
```

| Name         | Type                                      | Description      |
| ------------ | ----------------------------------------- | ---------------- |
| `revocation` | [`PendingRevocation`](#pendingrevocation) | The owed revoke. |

**Returns:** `false` when the write failed.

#### DeviceStore.pendingRevocations

Returns every revoke a source still owes, oldest first.

```kotlin
public suspend fun pendingRevocations(source: Source): List<PendingRevocation>
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** the owed revokes.

#### DeviceStore.removePendingRevocation

Forgets one owed revoke, once it has been delivered or can never be.

```kotlin
public suspend fun removePendingRevocation(source: Source, generation: Int)
```

| Name         | Type                | Description                           |
| ------------ | ------------------- | ------------------------------------- |
| `source`     | [`Source`](#source) | The source.                           |
| `generation` | `Int`               | The link generation the revoke names. |

#### DeviceStore.backfills

Returns the backfill windows Terra asked for that this device still owes, oldest arrival first.

```kotlin
public suspend fun backfills(source: Source): List<StoredBackfillRequest>
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** the [`StoredBackfillRequest`](#storedbackfillrequest) queue.

#### DeviceStore.upsertBackfill

Records or updates one owed backfill window.

```kotlin
public suspend fun upsertBackfill(
    request: StoredBackfillRequest,
    source: Source,
    ifGeneration: Int,
): Boolean
```

| Name           | Type                                              | Description                     |
| -------------- | ------------------------------------------------- | ------------------------------- |
| `request`      | [`StoredBackfillRequest`](#storedbackfillrequest) | The window.                     |
| `source`       | [`Source`](#source)                               | The source.                     |
| `ifGeneration` | `Int`                                             | The generation the caller read. |

**Returns:** `false` when the queue is full or the connection has moved on. The caller must then not acknowledge the window.

#### DeviceStore.removeBackfill

Removes one owed backfill window.

```kotlin
public suspend fun removeBackfill(reference: String, source: Source, ifGeneration: Int): Boolean
```

| Name           | Type                | Description                     |
| -------------- | ------------------- | ------------------------------- |
| `reference`    | `String`            | The window's server reference.  |
| `source`       | [`Source`](#source) | The source.                     |
| `ifGeneration` | `Int`               | The generation the caller read. |

**Returns:** `false` when the write was refused.

### ScheduleMarks

A store that also remembers whether the scheduler is honouring the background schedule.

```kotlin
public interface ScheduleMarks
```

Optional. A [`DeviceStore`](#devicestore) that does not implement it still works, but diagnostics then never report that scheduled runs have stopped. [`AndroidDeviceStore`](#androiddevicestore) and [`InMemoryDeviceStore`](#inmemorydevicestore) implement it.

#### ScheduleMarks.lastScheduledTick

Returns when a scheduled run for a source last ran to its end, or `null` before any has.

```kotlin
public suspend fun lastScheduledTick(source: Source): Instant?
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** the instant, or `null`, which diagnostics read as healthy. A run that found nothing to send still counts.

#### ScheduleMarks.noteScheduledTick

Records a completed scheduled run, unless the schedule has moved on.

```kotlin
public suspend fun noteScheduledTick(source: Source, at: Instant, ifSchedule: Int): Boolean
```

| Name         | Type                | Description                                        |
| ------------ | ------------------- | -------------------------------------------------- |
| `source`     | [`Source`](#source) | The source.                                        |
| `at`         | `Instant`           | When the run ended.                                |
| `ifSchedule` | `Int`               | The schedule generation the run read at its start. |

**Returns:** `false` when the write was refused.

#### ScheduleMarks.scheduleGeneration

Returns which schedule a source's runs belong to.

```kotlin
public suspend fun scheduleGeneration(source: Source): Int
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

**Returns:** the generation, `0` before any schedule was cancelled.

#### ScheduleMarks.supersedeSchedule

Moves a source on to its next schedule, forgetting what the last one had done.

```kotlin
public suspend fun supersedeSchedule(source: Source)
```

| Name     | Type                | Description |
| -------- | ------------------- | ----------- |
| `source` | [`Source`](#source) | The source. |

Called when a schedule is cancelled, and nowhere else.

### WriteVersions

Where the `clientRecordVersion` a write is filed under comes from.

```kotlin
public fun interface WriteVersions
```

Health Connect keeps the higher version of two records sharing a `clientRecordId`, so versions must be durable and strictly increasing. [`AndroidDeviceStore`](#androiddevicestore) implements it with [`nextWriteVersion`](#devicestore.nextwriteversion).

#### WriteVersions.next

Returns the next version, higher than every one already issued.

```kotlin
public suspend fun next(at: Instant): Long
```

| Name | Type      | Description                                         |
| ---- | --------- | --------------------------------------------------- |
| `at` | `Instant` | The clock reading. It only seeds the first version. |

**Returns:** the version.

### StoredBackfillRequest

One backfill window Terra asked this device for, as the device holds it.

```kotlin
public data class StoredBackfillRequest(
    public val reference: String,
    public val dataType: UploadDataType,
    public val start: Instant,
    public val end: Instant,
    public val servedThrough: Instant = start,
    public val failedRuns: Int = 0,
    public val receivedAt: Instant,
    public val target: String? = null,
)
```

| Property        | Type                                | Description                                                                                                                                                                                    |
| --------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `reference`     | `String`                            | The server's name for the request, which an acknowledgement names.                                                                                                                             |
| `dataType`      | [`UploadDataType`](#uploaddatatype) | The route.                                                                                                                                                                                     |
| `start`         | `Instant`                           | The start of the window.                                                                                                                                                                       |
| `end`           | `Instant`                           | The end of the window.                                                                                                                                                                         |
| `servedThrough` | `Instant`                           | How far a previous run got. The next run resumes here. Defaults to `start`.                                                                                                                    |
| `failedRuns`    | `Int`                               | Runs that achieved nothing. Defaults to `0`.                                                                                                                                                   |
| `receivedAt`    | `Instant`                           | When the device stored the request.                                                                                                                                                            |
| `target`        | `String?`                           | In [`DevIdMode.MULTIPLE`](#devidmode), the one connection this window is for, by Terra `user_id`, or `null` for every connection on the key. Defaults to `null`. Available in 2.3.0 and later. |

#### StoredBackfillRequest.QUEUE\_LIMIT

How many windows the device will owe at once.

```kotlin
public const val QUEUE_LIMIT: Int = 64
```

A full queue is not polled at all, so Terra keeps anything that would not fit.

### PendingRevocation

A revoke Terra is owed for a link this device has already ended.

```kotlin
public data class PendingRevocation(
    public val source: Source,
    public val providerUserId: String,
    public val generation: Int,
    public val deferredAt: Instant,
)
```

| Property         | Type                | Description                                         |
| ---------------- | ------------------- | --------------------------------------------------- |
| `source`         | [`Source`](#source) | The source of the ended link.                       |
| `providerUserId` | `String`            | The identity the connection is filed under.         |
| `generation`     | `Int`               | The link generation, which names the key to revoke. |
| `deferredAt`     | `Instant`           | When the revoke was first deferred.                 |

The key for `generation` is kept while a record naming it stands, because the revoke must be signed with it.

### AndroidDeviceStore

The production [`DeviceStore`](#devicestore), split across two files by sensitivity.

```kotlin
public class AndroidDeviceStore(
    context: Context,
    private val storageDomain: String = DEFAULT_STORAGE_DOMAIN,
    private val io: CoroutineDispatcher = Dispatchers.IO,
) : DeviceStore, WriteVersions, ScheduleMarks
```

| Name            | Type                  | Description                                                                                             |
| --------------- | --------------------- | ------------------------------------------------------------------------------------------------------- |
| `context`       | `Context`             | Any context. The store keeps the application context.                                                   |
| `storageDomain` | `String`              | Names both files. Optional. Defaults to `DEFAULT_STORAGE_DOMAIN`, the domain every `Terra` client uses. |
| `io`            | `CoroutineDispatcher` | Where disk access runs. Optional. Defaults to `Dispatchers.IO`.                                         |

The connection, Terra user id, provider user id and link generation go into `EncryptedSharedPreferences`, wrapped by a Keystore key. Resume points and the last delivery go into ordinary `SharedPreferences`. The encrypted file opens lazily, so building the store on a device not yet unlocked since boot does not fail.

| Error                             | When                                     |
| --------------------------------- | ---------------------------------------- |
| `TerraError.DeviceKeyUnavailable` | The encrypted store could not be opened. |

#### AndroidDeviceStore.DEFAULT\_STORAGE\_DOMAIN

The default storage domain.

```kotlin
public const val DEFAULT_STORAGE_DOMAIN: String = "co.tryterra.sdk"
```

### UploadDataType

Which route a batch is posted to. Terra maps these to its own data types.

```kotlin
public enum class UploadDataType(public val wire: String)
```

| Case           | Description                                                                                                    |
| -------------- | -------------------------------------------------------------------------------------------------------------- |
| `DAILY`        | `wire` `"daily"`. Heart rate, steps, resting heart rate, intraday samples and day totals, as whole local days. |
| `SLEEP`        | `wire` `"sleep"`. Sleep stage segments.                                                                        |
| `ACTIVITY`     | `wire` `"activity"`. Workouts, their intensity samples and routes.                                             |
| `BODY`         | `wire` `"body"`. Body measurements and vitals.                                                                 |
| `NUTRITION`    | `wire` `"nutrition"`. Meals and hydration.                                                                     |
| `MENSTRUATION` | `wire` `"menstruation"`. Flow days and cycle events.                                                           |

There is no `ATHLETE` route on Android: Health Connect has no record for it. See [`UnmappedCategory`](#unmappedcategory).

### UploadEnvelope

The v3 upload envelope: one route's records, as the device read them.

```kotlin
@Serializable
public data class UploadEnvelope(
    public val capturedAt: Long,
    public val records: List<UploadRecord>,
    public val version: Int = WIRE_VERSION,
    public val sdkVersion: String = SDK_VERSION,
)
```

A daily envelope is the whole of one local day. Terra upserts the day from it without merging, so a type absent from the payload is absent from the stored day.

| Property     | Type                 | Description                                                                                                                 |
| ------------ | -------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `capturedAt` | `Long`               | When the device read the store for these records, in Unix milliseconds. Among two uploads for one day, the newer read wins. |
| `records`    | `List<UploadRecord>` | The records.                                                                                                                |
| `version`    | `Int`                | The wire version. Defaults to `WIRE_VERSION`.                                                                               |
| `sdkVersion` | `String`             | The SDK version that encoded it. Defaults to the running SDK's version.                                                     |

#### UploadEnvelope.WIRE\_VERSION

The wire version this SDK writes.

```kotlin
public const val WIRE_VERSION: Int = 3
```

### UploadRecord

One sample on the wire.

```kotlin
@Serializable
public data class UploadRecord(
    public val type: String,
    public val start: Long,
    public val end: Long,
    public val tzOffsetMinutes: Int,
    public val userEntered: Boolean,
    public val tzIdentifier: String? = null,
    public val value: UploadValue? = null,
    public val unit: String? = null,
    public val motionContext: String? = null,
    public val metric: String? = null,
    public val stage: String? = null,
    public val activityType: Int? = null,
    public val activityName: String? = null,
    public val indoor: Boolean? = null,
    public val totalEnergyKcal: Double? = null,
    public val totalDistanceMeters: Double? = null,
    public val source: UploadSource? = null,
    public val id: String? = null,
    public val systolic: Double? = null,
    public val diastolic: Double? = null,
    public val mealTime: String? = null,
    public val specimen: String? = null,
    public val testType: String? = null,
    public val flow: String? = null,
    public val cycleStart: Boolean? = null,
    public val mealType: String? = null,
    public val name: String? = null,
    public val nutrients: Map<String, UploadNutrient>? = null,
    public val stats: UploadWorkoutStats? = null,
    public val events: List<UploadWorkoutEvent>? = null,
    public val event: String? = null,
    public val storeIdentifier: String? = null,
    public val workoutId: String? = null,
    public val points: List<UploadRoutePoint>? = null,
)
```

One type with optional fields for every sample kind. Absent fields are omitted from the JSON.

| Property                | Type                                         | Description                                                                                                           |
| ----------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `type`                  | `String`                                     | The record type.                                                                                                      |
| `start`, `end`          | `Long`                                       | Unix milliseconds.                                                                                                    |
| `tzOffsetMinutes`       | `Int`                                        | The UTC offset in minutes when the sample was recorded.                                                               |
| `userEntered`           | `Boolean`                                    | Hand-entered rather than measured. Terra marks the record MANUAL.                                                     |
| `tzIdentifier`          | `String?`                                    | The IANA zone behind the offset. Required on `menstruationFlow`.                                                      |
| `value`                 | [`UploadValue?`](#uploadvalue)               | The reading: a number for every type but `menstrualEvent`, which carries a word.                                      |
| `unit`                  | `String?`                                    | The unit of `value`.                                                                                                  |
| `motionContext`         | `String?`                                    | The motion context of a heart rate sample.                                                                            |
| `metric`                | `String?`                                    | `dailyTotal` only: which metric the value totals.                                                                     |
| `stage`                 | `String?`                                    | The sleep stage.                                                                                                      |
| `activityType`          | `Int?`                                       | The store's own activity code, mapped to a name by Terra.                                                             |
| `activityName`          | `String?`                                    | The activity name, for diagnostics only. Ignored when it disagrees with `activityType`.                               |
| `indoor`                | `Boolean?`                                   | Whether a workout was indoors.                                                                                        |
| `totalEnergyKcal`       | `Double?`                                    | A workout's active energy.                                                                                            |
| `totalDistanceMeters`   | `Double?`                                    | A workout's distance.                                                                                                 |
| `source`                | [`UploadSource?`](#uploadsource)             | Provenance.                                                                                                           |
| `id`                    | `String?`                                    | The store's own identifier, for diagnostics and re-sends. Not the dedup key, which stays type, start, end and source. |
| `systolic`, `diastolic` | `Double?`                                    | `bloodPressure` only. Both or neither.                                                                                |
| `mealTime`              | `String?`                                    | `bloodGlucose` only: where the reading sits relative to a meal.                                                       |
| `specimen`              | `String?`                                    | `bloodGlucose` only: what was sampled.                                                                                |
| `testType`              | `String?`                                    | `vo2Max` only: how the figure was arrived at.                                                                         |
| `flow`                  | `String?`                                    | `menstruationFlow` only.                                                                                              |
| `cycleStart`            | `Boolean?`                                   | `menstruationFlow` only, and required there.                                                                          |
| `mealType`              | `String?`                                    | `nutritionEntry` only. `unknown` when the store names none.                                                           |
| `name`                  | `String?`                                    | `nutritionEntry` only: what the store called the meal.                                                                |
| `nutrients`             | `Map<String, UploadNutrient>?`               | `nutritionEntry` only: each nutrient, keyed by its wire name.                                                         |
| `stats`                 | [`UploadWorkoutStats?`](#uploadworkoutstats) | `workout` only: what the store totalled over the session.                                                             |
| `events`                | `List<UploadWorkoutEvent>?`                  | `workout` only: laps, segments and markers.                                                                           |
| `event`                 | `String?`                                    | `menstrualEvent` only: which event the record is.                                                                     |
| `storeIdentifier`       | `String?`                                    | `menstrualEvent` only: the store's own name for the record type.                                                      |
| `workoutId`             | `String?`                                    | `workoutRoute` only: the `id` of the session the track belongs to.                                                    |
| `points`                | `List<UploadRoutePoint>?`                    | `workoutRoute` only: the track, earliest first.                                                                       |

### UploadRoutePoint

One point of a track on the wire.

```kotlin
@Serializable
public data class UploadRoutePoint(
    public val t: Long,
    public val lat: Double,
    public val lon: Double,
)
```

| Property | Type     | Description        |
| -------- | -------- | ------------------ |
| `t`      | `Long`   | Unix milliseconds. |
| `lat`    | `Double` | Latitude.          |
| `lon`    | `Double` | Longitude.         |

### UploadWorkoutEvent

One workout annotation on the wire.

```kotlin
@Serializable
public data class UploadWorkoutEvent(
    public val kind: String,
    public val start: Long,
    public val end: Long,
)
```

| Property       | Type     | Description                                    |
| -------------- | -------- | ---------------------------------------------- |
| `kind`         | `String` | The annotation kind, such as a lap or segment. |
| `start`, `end` | `Long`   | Unix milliseconds, present on every kind.      |

### UploadWorkoutStats

The per-workout statistics on the wire.

```kotlin
@Serializable
public data class UploadWorkoutStats(
    public val steps: Double? = null,
    public val basalEnergyKcal: Double? = null,
    public val swimmingStrokes: Double? = null,
    public val swimmingLaps: Double? = null,
    public val elevationGainM: Double? = null,
)
```

Each key names its own unit, and a store that answered two of the five sends two keys.

### UploadValue

A reading on the wire: a bare number or a bare string.

```kotlin
@Serializable(with = UploadValueSerializer::class)
public sealed interface UploadValue
```

| Case                    | Description                           |
| ----------------------- | ------------------------------------- |
| `Number(value: Double)` | A figure, written as the bare number. |
| `Text(value: String)`   | A word, written as the bare string.   |

#### UploadValue.of

Wraps an optional number.

```kotlin
public fun of(value: Double?): UploadValue?
```

| Name    | Type      | Description            |
| ------- | --------- | ---------------------- |
| `value` | `Double?` | The number, or `null`. |

**Returns:** `Number(value)`, or `null` when `value` is `null`.

### UploadNutrient

One nutrient on the wire.

```kotlin
@Serializable
public data class UploadNutrient(public val value: Double, public val unit: String)
```

| Property | Type     | Description                |
| -------- | -------- | -------------------------- |
| `value`  | `Double` | The amount.                |
| `unit`   | `String` | The unit the amount is in. |

### UploadSource

Provenance on the wire.

```kotlin
@Serializable
public data class UploadSource(
    public val name: String,
    public val bundleId: String,
    public val productType: String? = null,
    public val deviceType: String? = null,
)
```

| Property      | Type      | Description                                                                               |
| ------------- | --------- | ----------------------------------------------------------------------------------------- |
| `name`        | `String`  | The writing app's name.                                                                   |
| `bundleId`    | `String`  | The writing app's package.                                                                |
| `productType` | `String?` | The device model. Terra ranks a watch's account above a phone's using it with `bundleId`. |
| `deviceType`  | `String?` | What kind of device wrote it: `scale`, `phone`, `sensor`.                                 |

#### UploadSource.constructor

Builds the wire provenance from a sample's source.

```kotlin
public constructor(source: SampleSource) :
    this(source.name, source.bundleId, source.productType, source.deviceType)
```

| Name     | Type                            | Description          |
| -------- | ------------------------------- | -------------------- |
| `source` | [`SampleSource`](#samplesource) | The sample's source. |

### UploadPayload

Turns read samples into the envelope for one route.

```kotlin
public object UploadPayload
```

Every function takes `deviceZone`, the zone a sample with no zone of its own is filed against, and `capturedAt`, the read instant.

```kotlin
public fun daily(
    heartRate: List<HeartRateSample>,
    steps: List<StepCount>,
    restingHeartRate: List<RestingHeartRateSample> = emptyList(),
    dayTotals: List<DayTotal> = emptyList(),
    deviceZone: ZoneId,
    capturedAt: Instant,
    intraday: List<IntradaySample> = emptyList(),
): UploadEnvelope

public fun sleep(
    segments: List<SleepSegment>,
    deviceZone: ZoneId,
    capturedAt: Instant,
): UploadEnvelope

public fun activity(
    workouts: List<Workout>,
    deviceZone: ZoneId,
    capturedAt: Instant,
    intensity: List<WorkoutIntensitySample> = emptyList(),
    routes: List<WorkoutRoute> = emptyList(),
): UploadEnvelope

public fun body(
    bodyMeasurements: List<BodyMeasurement> = emptyList(),
    bloodPressure: List<BloodPressureSample> = emptyList(),
    bloodGlucose: List<BloodGlucoseSample> = emptyList(),
    oxygenSaturation: List<OxygenSaturationSample> = emptyList(),
    bodyTemperature: List<BodyTemperatureSample> = emptyList(),
    heartRateVariability: List<HeartRateVariabilitySample> = emptyList(),
    respiratoryRate: List<RespiratoryRateSample> = emptyList(),
    vo2Max: List<Vo2MaxSample> = emptyList(),
    deviceZone: ZoneId,
    capturedAt: Instant,
): UploadEnvelope

public fun nutrition(
    meals: List<MealSample> = emptyList(),
    hydration: List<HydrationSample> = emptyList(),
    deviceZone: ZoneId,
    capturedAt: Instant,
): UploadEnvelope

public fun menstruation(
    flow: List<MenstruationFlowSample> = emptyList(),
    deviceZone: ZoneId,
    capturedAt: Instant,
    events: List<MenstruationEventSample> = emptyList(),
): UploadEnvelope

public fun forRoute(
    dataType: UploadDataType,
    samples: HealthSamples,
    deviceZone: ZoneId,
    capturedAt: Instant,
): UploadEnvelope
```

| Function       | Description                                                                                                                                                   |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `daily`        | Heart rate, steps, day totals, resting heart rate and intraday samples as one daily batch. The caller owes a whole local day of every daily type it may read. |
| `sleep`        | Sleep stage segments, one record each.                                                                                                                        |
| `activity`     | Workouts with their intensity samples and routes. Workout events outside the session are dropped.                                                             |
| `body`         | The body route's measurements and vitals. Heart rate stays on the daily route.                                                                                |
| `nutrition`    | Meals and hydration as one batch.                                                                                                                             |
| `menstruation` | Flow days and cycle events. Flow records always carry `tzIdentifier`.                                                                                         |
| `forRoute`     | The envelope for `dataType`, built from one read's [`HealthSamples`](#healthsamples).                                                                         |

### Core

The sync engine for one store: reads windows, encodes, signs and uploads them.

```kotlin
public class Core internal constructor(
    // internal constructor parameters
)
```

The constructor is `internal`, and the client keeps its instance private, so your app cannot obtain one. The SDK runs it for you; see [Background sync](#background-sync). The members below are public for the SDK's own modules.

#### Core.sync

Uploads one range of one route, with no mark and no history walk.

```kotlin
public suspend fun sync(
    dataType: UploadDataType,
    range: TimeRange,
    now: () -> Instant = Instant::now,
): Int
```

| Name       | Type                                | Description                                                           |
| ---------- | ----------------------------------- | --------------------------------------------------------------------- |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.                                                            |
| `range`    | [`TimeRange`](#timerange)           | The range to upload. On the daily route it grows to whole local days. |
| `now`      | `() -> Instant`                     | The clock. Optional. Defaults to `Instant::now`.                      |

**Returns:** the number of records uploaded.

| Error                          | When                                    |
| ------------------------------ | --------------------------------------- |
| `TerraError.ReadQuotaExceeded` | The store's read quota ran out partway. |

#### Core.syncPending

Brings a route current from its mark, then walks its history back.

```kotlin
public suspend fun syncPending(
    dataType: UploadDataType,
    backfillDays: Int = FIRST_SYNC_DAYS,
    now: () -> Instant = Instant::now,
    deadline: Instant? = null,
): SyncOutcome
```

| Name           | Type                                | Description                                                                                                                                |
| -------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `dataType`     | [`UploadDataType`](#uploaddatatype) | The route.                                                                                                                                 |
| `backfillDays` | `Int`                               | How far back to reach. Optional. Defaults to `FIRST_SYNC_DAYS`.                                                                            |
| `now`          | `() -> Instant`                     | The clock. Optional. Defaults to `Instant::now`.                                                                                           |
| `deadline`     | `Instant?`                          | When to stop starting windows and change pages, or `null` for none. Checked before a window, not during one. Optional. Defaults to `null`. |

**Returns:** a [`SyncOutcome`](#syncoutcome).

#### Core.constants

```kotlin
public const val FIRST_SYNC_DAYS: Int = 730
public const val MAX_CHANGE_PAGES: Int = 32
public const val MAX_UPLOAD_BYTES: Int = 25 shl 20
public const val LATE_ARRIVAL_LOOKBACK_SECONDS: Long = 24 * 60 * 60
```

| Constant                        | Description                                                                                                                                       |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `FIRST_SYNC_DAYS`               | How far back the first sync after a link reaches: two years, newest first. Health Connect serves only 30 days without `READ_HEALTH_DATA_HISTORY`. |
| `MAX_CHANGE_PAGES`              | How many change-feed pages one run delivers before leaving the rest for the next.                                                                 |
| `MAX_UPLOAD_BYTES`              | The largest uncompressed body the ingest route accepts: 25 MiB.                                                                                   |
| `LATE_ARRIVAL_LOOKBACK_SECONDS` | How far behind the mark a forward walk re-reads while no change anchor exists: one day.                                                           |

#### Core.encode

Returns the bytes an envelope puts on the wire.

```kotlin
public fun encode(envelope: UploadEnvelope): ByteArray
```

| Name       | Type                                | Description   |
| ---------- | ----------------------------------- | ------------- |
| `envelope` | [`UploadEnvelope`](#uploadenvelope) | The envelope. |

**Returns:** UTF-8 JSON. Absent fields are dropped rather than sent as `null`.

### SyncOutcome

What one sync pass over a route did.

```kotlin
public data class SyncOutcome(
    public val recordsUploaded: Int = 0,
    public val windowsUploaded: Int = 0,
    public val windowsSkipped: Int = 0,
    public val lateArrivalsUploaded: Int = 0,
    public val syncedThrough: Instant,
)
```

| Property               | Type      | Description                                                                                                        |
| ---------------------- | --------- | ------------------------------------------------------------------------------------------------------------------ |
| `recordsUploaded`      | `Int`     | Records uploaded.                                                                                                  |
| `windowsUploaded`      | `Int`     | Windows that carried records. Empty windows are not counted.                                                       |
| `windowsSkipped`       | `Int`     | Windows given up on. Non-zero means data was deliberately dropped: too small to split and still too large to send. |
| `lateArrivalsUploaded` | `Int`     | Records the change feed carried that the windowed walk could not have seen. Also counted in `recordsUploaded`.     |
| `syncedThrough`        | `Instant` | The route's mark after the pass.                                                                                   |

### Backfills

The backfill windows Terra asks this device for, and the rule that keeps them from being lost.

```kotlin
public class Backfills internal constructor(
    // internal constructor parameters
)
```

Like [`Core`](#core), your app cannot obtain one. Nothing leaves the device's queue until an acknowledgement names it, and a window this device cannot read is left for another phone on the same connection.

#### Backfills.poll

Fetches what Terra wants, writes it to the queue, and acknowledges exactly what landed there.

```kotlin
public suspend fun poll(now: () -> Instant = Instant::now): PollOutcome
```

| Name  | Type            | Description                                      |
| ----- | --------------- | ------------------------------------------------ |
| `now` | `() -> Instant` | The clock. Optional. Defaults to `Instant::now`. |

**Returns:** a [`PollOutcome`](#backfills.polloutcome). A full queue is not polled at all.

| Error                      | When                                           |
| -------------------------- | ---------------------------------------------- |
| `TerraError.DevIdMismatch` | Another developer id owns this storage domain. |
| `TerraError.NotConnected`  | The source has no connection or no key.        |

#### Backfills.hasStarvedRequest

Reports whether a queued window has waited long enough to go before fresh data.

```kotlin
public suspend fun hasStarvedRequest(now: Instant): Boolean
```

| Name  | Type      | Description       |
| ----- | --------- | ----------------- |
| `now` | `Instant` | The current time. |

**Returns:** `true` when a request has waited longer than `PATIENCE_SECONDS`.

#### Backfills.noteProgress

Records that a run got part of the way through a request.

```kotlin
public suspend fun noteProgress(
    request: StoredBackfillRequest,
    servedThrough: Instant,
    connection: StoredConnection,
)
```

| Name            | Type                                              | Description                                              |
| --------------- | ------------------------------------------------- | -------------------------------------------------------- |
| `request`       | [`StoredBackfillRequest`](#storedbackfillrequest) | The request.                                             |
| `servedThrough` | `Instant`                                         | How far the run got. Reaching `end` removes the request. |
| `connection`    | [`StoredConnection`](#storedconnection)           | The connection the run served.                           |

Progress resets the request's failure count.

| Error                      | When                                           |
| -------------------------- | ---------------------------------------------- |
| `TerraError.DevIdMismatch` | Another developer id owns this storage domain. |

#### Backfills.noteFailure

Records a run that achieved nothing, and abandons the request once it has failed enough.

```kotlin
public suspend fun noteFailure(reference: String, connection: StoredConnection): Boolean
```

| Name         | Type                                    | Description                    |
| ------------ | --------------------------------------- | ------------------------------ |
| `reference`  | `String`                                | The request's reference.       |
| `connection` | [`StoredConnection`](#storedconnection) | The connection the run served. |

**Returns:** `true` when the request reached `MAX_RUNS` failures and was dropped.

| Error                      | When                                           |
| -------------------------- | ---------------------------------------------- |
| `TerraError.DevIdMismatch` | Another developer id owns this storage domain. |

#### Backfills.route

Returns the route a server-side data category uploads through, or `null` when there is none.

```kotlin
public fun route(serverDataType: String): UploadDataType?
```

| Name             | Type     | Description                                                                           |
| ---------------- | -------- | ------------------------------------------------------------------------------------- |
| `serverDataType` | `String` | The server's category name, matched case-insensitively against `UploadDataType.wire`. |

**Returns:** the route, or `null` for a category such as `athlete` or `healthObservation` that this SDK has no route for. Such windows are acknowledged and dropped.

#### Backfills.windowKey

Returns the identity of a window, for deduplication.

```kotlin
public fun windowKey(dataType: UploadDataType, start: Instant, end: Instant): String
```

| Name       | Type                                | Description              |
| ---------- | ----------------------------------- | ------------------------ |
| `dataType` | [`UploadDataType`](#uploaddatatype) | The route.               |
| `start`    | `Instant`                           | The start of the window. |
| `end`      | `Instant`                           | The end of the window.   |

**Returns:** `"<wire>:<startMillis>:<endMillis>"`.

#### Backfills.constants

```kotlin
public const val MAX_RUNS: Int = 5
public const val LIFETIME_DAYS: Long = 30
public const val PATIENCE_SECONDS: Long = 24 * 60 * 60
```

| Constant           | Description                                                               |
| ------------------ | ------------------------------------------------------------------------- |
| `MAX_RUNS`         | How many failed runs a request survives before the device gives up on it. |
| `LIFETIME_DAYS`    | How long a request stays owed before it is dropped as stale.              |
| `PATIENCE_SECONDS` | How long a queued request waits before it goes ahead of fresh data.       |

### Backfills.PollOutcome

What one poll settled.

```kotlin
public data class PollOutcome(
    public val queued: Int = 0,
    public val duplicates: Int = 0,
    public val unsupported: Int = 0,
    public val degenerate: Int = 0,
    public val unreadable: Int = 0,
    public val refused: Boolean = false,
    public val acknowledged: List<String> = emptyList(),
)
```

| Property       | Type           | Description                                                                         |
| -------------- | -------------- | ----------------------------------------------------------------------------------- |
| `queued`       | `Int`          | Windows newly written to the queue.                                                 |
| `duplicates`   | `Int`          | Windows offered again that the device already owed. Acknowledged, not stored twice. |
| `unsupported`  | `Int`          | Windows naming a category this SDK has no route for.                                |
| `degenerate`   | `Int`          | Windows already over when they arrived, or inverted.                                |
| `unreadable`   | `Int`          | Windows naming a route this device cannot read. Neither stored nor acknowledged.    |
| `refused`      | `Boolean`      | The poll took no work on: the queue was full, or another poll held it.              |
| `acknowledged` | `List<String>` | Every reference this poll settled, in order.                                        |

### Chunks

How a requested range becomes the windows a sync walks.

```kotlin
public object Chunks
```

```kotlin
public const val CHUNK_DAYS: Long = 31
public const val MINIMUM_SPLIT_SECONDS: Long = 3_600
public const val DAILY_CHUNK_DAYS: Long = 1
public fun of(
    whole: SampleInterval,
    zone: ZoneId,
    days: Long = CHUNK_DAYS,
): List<SampleInterval>
public fun wholeDays(whole: SampleInterval, zone: ZoneId): SampleInterval
public fun splittable(window: SampleInterval): Boolean
public fun middle(window: SampleInterval): Instant
public fun daySeam(window: SampleInterval, zone: ZoneId): Instant?
```

| Member                  | Description                                                                                                                  |
| ----------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `CHUNK_DAYS`            | How far one window reaches before it is cut: 31 days.                                                                        |
| `MINIMUM_SPLIT_SECONDS` | The narrowest stretch a 413 split will cut: one hour. Below it a window is given up on.                                      |
| `DAILY_CHUNK_DAYS`      | How far one daily window reaches: exactly one local day.                                                                     |
| `of`                    | `whole` cut into half-open windows of at most `days`, oldest first, each seam snapped back to local midnight in `zone`.      |
| `wholeDays`             | `whole` grown outwards to the local-day boundaries that contain it.                                                          |
| `splittable`            | Whether `window` is wider than `MINIMUM_SPLIT_SECONDS`.                                                                      |
| `middle`                | The instant halfway through `window`, where a 413 cuts it.                                                                   |
| `daySeam`               | The local midnight nearest the middle of `window`, or `null` when it holds one day or less. Where a 413 cuts a daily window. |

### Backoff

How long to wait before trying an upload again.

```kotlin
public object Backoff
```

#### Backoff.SPREAD

How much of each wait is random.

```kotlin
public const val SPREAD: Double = 0.5
```

#### Backoff.wait

Returns the wait after a number of failed attempts, in seconds.

```kotlin
public fun wait(failures: Int, error: TerraError, random: Random = Random): Double
```

| Name       | Type         | Description                                            |
| ---------- | ------------ | ------------------------------------------------------ |
| `failures` | `Int`        | Failed attempts so far.                                |
| `error`    | `TerraError` | The last failure.                                      |
| `random`   | `Random`     | The randomness source. Optional. Defaults to `Random`. |

**Returns:** Terra's `Retry-After`, stretched by up to 25%, when the failure was a throttle that carried one. Otherwise a random wait between half of and the full `2^failures` seconds.

### RetryBudget

How many more attempts one leaf of a sync may spend, and how long it has already slept.

```kotlin
public class RetryBudget(
    public var attemptsLeft: Int = MAX_ATTEMPTS,
)
```

| Property            | Type      | Description                                                                                  |
| ------------------- | --------- | -------------------------------------------------------------------------------------------- |
| `attemptsLeft`      | `Int`     | Attempts left, the first send included. Resets on every success. Defaults to `MAX_ATTEMPTS`. |
| `slept`             | `Double`  | Seconds already spent waiting across every leaf sharing this budget. Read-only from outside. |
| `hasAnotherAttempt` | `Boolean` | Whether another attempt is left after the one that just failed.                              |
| `failures`          | `Int`     | How many attempts have already failed.                                                       |

#### RetryBudget.succeeded

Records a success, which restores the leaf's attempts without touching the shared sleep.

```kotlin
public fun succeeded()
```

#### RetryBudget.charge

Charges a wait against the budget, or refuses when the cap would be passed.

```kotlin
public fun charge(wait: Double): Boolean
```

| Name   | Type     | Description          |
| ------ | -------- | -------------------- |
| `wait` | `Double` | The wait in seconds. |

**Returns:** `false`, charging nothing, when `slept + wait` would pass `MAX_TOTAL_BACKOFF`. Otherwise spends one attempt and the wait.

#### RetryBudget.constants

```kotlin
public const val MAX_ATTEMPTS: Int = 3
public const val MAX_TOTAL_BACKOFF: Double = 60.0
```

| Constant            | Description                                                 |
| ------------------- | ----------------------------------------------------------- |
| `MAX_ATTEMPTS`      | Three attempts per leaf: the send and two retries.          |
| `MAX_TOTAL_BACKOFF` | The most one window's split may sleep in total, in seconds. |

### WindowResult

What one window's delivery achieved.

```kotlin
public data class WindowResult(
    public val records: Int = 0,
    public val skipped: Int = 0,
    public val coveredThrough: Instant? = null,
    public val incomplete: Boolean = false,
)
```

| Property         | Type       | Description                                                                             |
| ---------------- | ---------- | --------------------------------------------------------------------------------------- |
| `records`        | `Int`      | Records delivered.                                                                      |
| `skipped`        | `Int`      | Stretches given up on because they were too small to split and still too large to send. |
| `coveredThrough` | `Instant?` | Everything from the window's start up to here reached Terra. A prefix claim, not a sum. |
| `incomplete`     | `Boolean`  | The store served part of the window and said there was more.                            |

#### WindowResult.joined

Returns two halves of a split window as one result.

```kotlin
public fun joined(first: WindowResult, second: WindowResult, middle: Instant): WindowResult
```

| Name     | Type           | Description               |
| -------- | -------------- | ------------------------- |
| `first`  | `WindowResult` | The earlier half.         |
| `second` | `WindowResult` | The later half.           |
| `middle` | `Instant`      | Where the window was cut. |

**Returns:** the sums of both halves. The second half's ground counts only when `first.coveredThrough == middle`.

### WindowPartiallyFailed

A failure that left delivered ground behind it.

```kotlin
public class WindowPartiallyFailed(
    public val underlying: Throwable,
    public val result: WindowResult,
) : Exception(underlying)
```

| Property     | Type                            | Description            |
| ------------ | ------------------------------- | ---------------------- |
| `underlying` | `Throwable`                     | The failure.           |
| `result`     | [`WindowResult`](#windowresult) | What landed before it. |

### Divide

Splits already-read samples at an instant, for the 413 path.

```kotlin
public object Divide
```

#### Divide.at

Returns samples cut at an instant, by the millisecond each record puts on the wire.

```kotlin
public fun at(middle: Instant, samples: HealthSamples, before: SampleInterval, after: SampleInterval): Pair<HealthSamples, HealthSamples>
```

| Name      | Type                                | Description                    |
| --------- | ----------------------------------- | ------------------------------ |
| `middle`  | `Instant`                           | Where to cut.                  |
| `samples` | [`HealthSamples`](#healthsamples)   | The samples one read returned. |
| `before`  | [`SampleInterval`](#sampleinterval) | The earlier half's window.     |
| `after`   | [`SampleInterval`](#sampleinterval) | The later half's window.       |

**Returns:** the two halves. A day total goes to every half its day overlaps.

## Samsung Health add-on

`co.tryterra:terra-android-samsung` reads Samsung Health's own store as `Source.SAMSUNG_HEALTH`, through Samsung's Health Data SDK, which your app packages itself. It needs Android 10 (API 29). For setup, partner approval and how it splits records with Health Connect, see the [Samsung Health guide](https://docs.tryterra.co/mobile-sdks/samsung-health).

### samsungHealth

Registers the Samsung Health store with the client you are building.

```kotlin
public fun StoreRegistration.samsungHealth(dedupeHealthConnect: Boolean = true)
```

| Name                  | Type      | Description                                                                                                                        |
| --------------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `dedupeHealthConnect` | `Boolean` | Whether the Health Connect store leaves out the records Samsung Health mirrored into Health Connect. Optional. Defaults to `true`. |

Call it inside the `stores` block of `Terra(...)`, which receives a [`StoreRegistration`](#storeregistration). The store uses the client's own day grid.

```kotlin
import co.tryterra.sdk.health.samsung.samsungHealth

terra = Terra(
    this,
    devId = BuildConfig.TERRA_DEV_ID,
    tokenProvider = { yourBackend.mintTerraToken() },
) {
    samsungHealth()
}
```

The Samsung store uploads only what Samsung Health created itself; what Samsung Health imported from other apps is left to Health Connect. With `dedupeHealthConnect = true`, Health Connect leaves out the record types the Samsung store reports right now: while the Samsung link is active, the category was requested from Samsung, the read is granted and Samsung Health answers. When any of that stops holding, Health Connect reports those records again. Pass `false` to have Health Connect report everything it holds.

{% hint style="warning" %}
Day totals are never de-duplicated. Health Connect's aggregate cannot exclude an app, so its daily steps, energy, distance and floors stay the whole device's figure, and so do Samsung's.
{% endhint %}

Without this registration, `connect(Source.SAMSUNG_HEALTH, forUser)` throws `TerraError.HealthDataUnavailable(StoreAvailability.ModuleMissing)`.

### SamsungHealthStore

Samsung Health behind the [`HealthStore`](#healthstore) seam.

```kotlin
public class SamsungHealthStore internal constructor(
    private val client: SamsungHealthClient,
    private val zone: () -> ZoneId,
    private val now: () -> Instant,
    private val config: SamsungConfig,
) : HealthStore
```

[`samsungHealth`](#samsunghealth) builds it for you. Construct one directly only when you assemble your own registry.

How it differs from [`HealthConnectStore`](#healthconnectstore):

* `source` is `Source.SAMSUNG_HEALTH` and `wireProvider` is `"samsung"`.
* It reads only. `capabilities.writes` is `false`; `save` with entries and `delete` throw `TerraError.Platform(UnsupportedOperationException)`.
* `MENSTRUATION` is not a route: Samsung has no cycle type.
* `appliesDayTotalPolicy` is `false`: its day totals are Samsung's own.
* There are no step records, so the daily route's steps exist only as day totals.

`availability()` asks for the grant state of every type and reads the answer from the error, since Samsung has no status call:

| Availability                   | When                                                                                                              |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
| `Available`                    | Samsung Health answered, or the partner policy refuses only some types. Refused types are left out of everything. |
| `PartnerPolicyMissing(types)`  | The partner policy refuses every type. Your app is not approved by Samsung and developer mode is off.             |
| `ProviderAppMissing`           | Samsung Health is not installed, disabled, not initialised, or on a child account.                                |
| `ProviderAppTooOld(installed)` | Samsung Health needs an update.                                                                                   |

#### SamsungHealthStore.constructor

Creates the store over Samsung's Health Data SDK.

```kotlin
public constructor(context: Context, zone: () -> ZoneId = ZoneId::systemDefault) :
    this(RealSamsungHealthClient(context), zone, Instant::now, SamsungConfig())
```

| Name      | Type           | Description                                                                        |
| --------- | -------------- | ---------------------------------------------------------------------------------- |
| `context` | `Context`      | The context the Samsung SDK is reached through.                                    |
| `zone`    | `() -> ZoneId` | The zone local days are counted in. Optional. Defaults to `ZoneId::systemDefault`. |

#### SamsungHealthStore.resolution

Returns the remedy Samsung offers for its own unavailability, or `null` when it offers none.

```kotlin
public suspend fun resolution(): ((Activity) -> Unit)?
```

**Returns:** a function that starts Samsung's own flow from an `Activity`, for example when Samsung Health is disabled or has never been opened. `null` when Samsung Health is usable or offers no fix.

```kotlin
val store = SamsungHealthStore(context)
store.resolution()?.invoke(activity)
```

#### SamsungHealthStore.constants

```kotlin
public const val WIRE_PROVIDER: String = "samsung"
public const val PROVIDER_PACKAGE: String = "com.sec.android.app.shealth"
public const val HISTORY_WINDOW_DAYS: Long = 36_500
```

| Constant              | Description                                                                   |
| --------------------- | ----------------------------------------------------------------------------- |
| `WIRE_PROVIDER`       | The provider label Terra's ingest route is keyed on.                          |
| `PROVIDER_PACKAGE`    | Samsung Health's package, and the origin it writes into Health Connect under. |
| `HISTORY_WINDOW_DAYS` | A finite "no floor". Samsung documents no history limit.                      |

## Testing

`co.tryterra:terra-android-testkit` holds fakes for every [extension point](#extension-points), so your tests can drive links, permission sheets, writes and failures on a plain JVM. Add it with `testImplementation`. Build a client from them with the `@TerraSeam` [`Terra`](#terra) constructor.

`PublicSurfaceCompiles` in the testkit is `internal`: a compile-time check that the SDK's public surface names no OkHttp type. It is not API.

### FakeBackend

A [`TerraBackend`](#terrabackend) that keeps every request instead of posting it.

```kotlin
public class FakeBackend(
    public var userId: String = "terra-user-1",
) : TerraBackend
```

| Member                                                        | Type                                  | Description                                                             |
| ------------------------------------------------------------- | ------------------------------------- | ----------------------------------------------------------------------- |
| `userId`                                                      | `String`                              | The `user_id` every link grants. Defaults to `"terra-user-1"`.          |
| `uploads`                                                     | `MutableList<UploadRequest>`          | Every accepted batch, oldest first.                                     |
| `links`                                                       | `MutableList<LinkRequest>`            | Every redemption, oldest first.                                         |
| `revocations`                                                 | `MutableList<RevokeDeviceKeyRequest>` | Every revocation, oldest first.                                         |
| `backfillPolls`                                               | `MutableList<BackfillPollRequest>`    | Every poll, oldest first.                                               |
| `backfillAcks`                                                | `MutableList<List<String>>`           | The references of each acknowledgement.                                 |
| `diagnostics`                                                 | `MutableList<DiagnosticsRequest>`     | Every report, oldest first.                                             |
| `uploadAttempts`                                              | `Int`                                 | Every upload handed over, refused ones included.                        |
| `pendingBackfills`                                            | `List<BackfillDirective>`             | What the next poll answers. Cleared by the poll that reads it.          |
| `failNextUpload`, `failNextLink`, `failNextPoll`              | `Throwable?`                          | Thrown by the next call instead of answering, then cleared.             |
| `failEveryUpload`, `failRevoke`, `failAck`, `failDiagnostics` | `Throwable?`                          | Thrown by every call.                                                   |
| `failAfter`                                                   | `Int?`                                | How many uploads succeed before every later one fails.                  |
| `failEveryNthUpload`                                          | `Int?`                                | Fails every nth upload and serves the rest.                             |
| `refuseOver`                                                  | `Int?`                                | The largest batch accepted. Larger ones get a 413.                      |
| `refuseEveryUpload`                                           | `Boolean`                             | Answers 413 to every batch.                                             |
| `onPoll`                                                      | `(suspend () -> Unit)?`               | Runs inside each poll, after the request arrives and before the answer. |

```kotlin
public fun lastDiagnosticsText(): String?
public fun lastBodyText(): String?
```

`lastDiagnosticsText` returns the body of the most recent report as text; `lastBodyText` returns the body of the most recent batch as text.

### FakeHealthStore

A [`HealthStore`](#healthstore) whose contents your test decides.

```kotlin
public class FakeHealthStore(
    override val source: Source = Source.HEALTH,
    override val wireProvider: String = "health_connect",
) : HealthStore
```

Stage data with one setter per [`HealthSamples`](#healthsamples) field:

```kotlin
public fun setHeartRate(samples: List<HeartRateSample>)
public fun setStepSamples(samples: List<StepCount>)
public fun setIntraday(samples: List<IntradaySample>)
public fun setRestingHeartRate(samples: List<RestingHeartRateSample>)
public fun setSleep(samples: List<SleepSegment>)
public fun setWorkoutIntensity(samples: List<WorkoutIntensitySample>)
public fun setWorkoutRoutes(routes: List<WorkoutRoute>)
public fun setWorkouts(samples: List<Workout>)
public fun setDayTotals(totals: List<DayTotal>)
public fun setBodyMeasurements(samples: List<BodyMeasurement>)
public fun setBloodPressure(samples: List<BloodPressureSample>)
public fun setBloodGlucose(samples: List<BloodGlucoseSample>)
public fun setOxygenSaturation(samples: List<OxygenSaturationSample>)
public fun setBodyTemperature(samples: List<BodyTemperatureSample>)
public fun setHeartRateVariability(samples: List<HeartRateVariabilitySample>)
public fun setRespiratoryRate(samples: List<RespiratoryRateSample>)
public fun setVo2Max(samples: List<Vo2MaxSample>)
public fun setMeals(samples: List<MealSample>)
public fun setHydration(samples: List<HydrationSample>)
public fun setMenstruationEvents(samples: List<MenstruationEventSample>)
public fun setMenstruationFlow(samples: List<MenstruationFlowSample>)
```

Drive the change feed:

```kotlin
public fun stageChange(samples: HealthSamples, route: UploadDataType)
public fun stageInvalidatedDay(
    dayStart: Instant,
    route: UploadDataType = UploadDataType.DAILY,
)
public fun removeStaged(ids: List<RecordId>, route: UploadDataType)
public fun scope(route: UploadDataType, type: DataType): String
```

`stageChange` adds a page as an arrival after every anchor issued so far. `stageInvalidatedDay` adds a page that says a day's total moved, with no sample. `removeStaged` stands in for the person deleting records in the health app. `scope` returns how `readScopes` spells one type's scope.

Shape answers and failures with these properties:

| Property                                                             | Type                                      | Description                                                            |
| -------------------------------------------------------------------- | ----------------------------------------- | ---------------------------------------------------------------------- |
| `stagedAvailability`                                                 | `StoreAvailability`                       | What `availability()` answers.                                         |
| `grantedAccess`                                                      | `HealthAccess`                            | What `granted()` answers.                                              |
| `deniedRead`                                                         | `Set<DataCategory>`                       | Categories refused however often they are asked for.                   |
| `unauthorised`                                                       | `Set<DataType>`                           | Record types withheld because the app was never granted them.          |
| `partnerRefused`                                                     | `Set<DataType>`                           | Record types the partner policy does not cover.                        |
| `readableScopes`                                                     | `MutableMap<UploadDataType, Set<String>>` | What `readScopes` reports, per route.                                  |
| `featureStatuses`                                                    | `MutableMap<Feature, PermissionStatus>`   | What `featureStatus` answers per feature.                              |
| `capabilitiesOverride`                                               | `StoreCapabilities?`                      | Stands in for a build that does not support something.                 |
| `routedByOverride`, `categoryOverride`, `categoriesOfOverride`       | function or `null`                        | Stand in for a store whose route table differs from Health Connect's.  |
| `pageLimit`                                                          | `Int?`                                    | A cap imposed whatever `ReadRequest.limit` asks.                       |
| `dropReadCursor`                                                     | `Boolean`                                 | Answers a truncated page with no cursor.                               |
| `recordsPerEntry`                                                    | `Int`                                     | How many store records each written entry becomes.                     |
| `expireNextChangeToken`                                              | `Boolean`                                 | Answers the next `changes` call with an expired token.                 |
| `holdNextRequest`                                                    | `CompletableDeferred<Unit>?`              | Awaited by the next `requestAccess`, standing in for a sheet still up. |
| `failNextRead`, `failNextRequest`, `failNextChanges`, `failNextSave` | `Throwable?`                              | Thrown by the next call, then cleared.                                 |
| `failEveryRead`, `failEveryDelete`, `failEveryFeatureStatus`         | `Throwable?`                              | Thrown by every call.                                                  |
| `onRead`                                                             | `(suspend () -> Unit)?`                   | Runs inside each `read`, after the request arrives.                    |

And inspect what the SDK did:

| Property           | Type                              | Description                                       |
| ------------------ | --------------------------------- | ------------------------------------------------- |
| `reads`            | `MutableList<ReadRequest>`        | Every read request, oldest first.                 |
| `requests`         | `MutableList<HealthAccess>`       | Every access `requestAccess` was handed.          |
| `registrations`    | `Int`                             | How many times `registerAccess` ran.              |
| `written`          | `MutableList<WriteEntry>`         | Every entry handed to `save`.                     |
| `changeRoutes`     | `MutableList<UploadDataType>`     | Every route `changes` was asked about.            |
| `changeScopes`     | `MutableList<Set<DataCategory>?>` | The requested set each `changes` call carried.    |
| `dayTotalZones`    | `MutableList<ZoneId>`             | Every zone `dayTotals` was asked in.              |
| `dayTotalPolicies` | `MutableList<DayTotalPolicy>`     | The policy each `dayTotals` read was asked under. |

### FakeResultCaller

An `ActivityResultCaller` you can hand to `permissions.launcher` off a device.

```kotlin
public class FakeResultCaller : ActivityResultCaller
```

Every method fails if called. Pair it with [`FakeHealthStore`](#fakehealthstore), which registers and answers without touching the host.

### InMemoryDeviceKeyStore

A [`DeviceKeyStore`](#devicekeystore) backed by software P-256 keys held in memory.

```kotlin
public class InMemoryDeviceKeyStore(
    private val failure: Throwable? = null,
) : DeviceKeyStore
```

| Member           | Type         | Description                                                                                                             |
| ---------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------- |
| `failure`        | `Throwable?` | Constructor parameter. Thrown by every operation, for a device that cannot produce a key. Optional. Defaults to `null`. |
| `signingFailure` | `Throwable?` | Thrown instead of signing, for a key that exists and will not sign.                                                     |

```kotlin
public fun hasKey(source: Source, generation: Int): Boolean
public fun keyCount(source: Source): Int
```

`hasKey` reports whether a key is held, so a test can prove disconnect destroyed it. `keyCount` returns the number of keys held at any generation for a source.

### InMemoryDeviceStore

A [`DeviceStore`](#devicestore) that forgets everything when the process does.

```kotlin
public class InMemoryDeviceStore(
    connections: Map<Source, StoredConnection> = emptyMap(),
    providerUserId: String? = null,
    activeDevId: String? = null,
) : DeviceStore, ScheduleMarks
```

| Name             | Type                            | Description                                                                                            |
| ---------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------ |
| `connections`    | `Map<Source, StoredConnection>` | Connections to start with, so a test can open on an already-linked device. Optional. Defaults to none. |
| `providerUserId` | `String?`                       | The settled install identity to start with. Optional. Defaults to `null`.                              |
| `activeDevId`    | `String?`                       | The developer id the domain starts owned by. Optional. Defaults to `null`.                             |
