diff --git a/AGENTS.md b/AGENTS.md index 19a9a859..7bfbc42f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,11 +23,12 @@ Read these before making decisions — they are the project's memory and outrank 7. **`build-history/v2.1.2/spec.md`** — version 2.1.2: repaired calculation methods, SQL migration step 6, session effort and strength-set fields, and the three kinds of skill (tool, calculation, coaching) with the CrossFit and HYROX coaching skills. 8. **`build-history/v2.1.3/spec.md`** — version 2.1.3, the last released version: an optional host program (`ath-host`, in `host/`) for sharing a record, human coach authorship, SQL migration step 7, and two storage backends — native SQLite files, and libSQL databases written through a local working copy (D268, D269). Its `appendix/` holds the hosted-storage study, the hosting experiments, and the build evidence. `docs/hosting.md` is the guide for operators and app developers. 9. **`build-history/v3.0.0/spec.md`** — version 3.0.0, approved and being built, the current version: new record types, device recordings, one Rust core with a WebAssembly build, and a clearer version rule (D290–D317). New data follows [`docs/what-goes-in-the-record.md`](docs/what-goes-in-the-record.md) (D291). -10. **`build-history/*/decisions.md`** — every decision with the alternatives that were rejected and why (D1 onward, numbered continuously across version folders). Do not relitigate these without new information; if a decision is superseded, append a new D-number in the current version's file. Don't rewrite earlier entries. Don't create addendum files. -11. **`build-history/*/appendix/`** — the long-form studies that informed decisions. Link each study from its D-number. Do not move the decision into the appendix, and do not trim the study down to the decision line. -12. **`build-history/*/progress.md`** — what's done and what's next. -13. **`docs/connections.md`** — per-provider data research (what WHOOP/Oura/Garmin/Apple Health each provide via which path). -14. **`SPEC.md`** — the public field-level format reference. The normative model for version 3.0.0 is the Rust model in `core/src/model/` with its semantic checks. JSON Schema and the npm protocol declarations are generated from it. The Zod schemas in `packages/npm/src/schema.ts` are 2.1.x compatibility code for JavaScript callers (D209); they mirror the Rust model, including the 2.1.2 optional fields (D238, D239) and the 2.1.3 coach author (D255), are tested against the Rust validator, and are not where records are designed. +10. **`build-history/v2.2.0/`** — a plan for 2.2.0. It is not the software until the maintainer approves it and a later pull request builds it. +11. **`build-history/*/decisions.md`** — every decision with the alternatives that were rejected and why (D1 onward, numbered continuously across version folders). Do not relitigate these without new information; if a decision is superseded, append a new D-number in the current version's file. Don't rewrite earlier entries. Don't create addendum files. +12. **`build-history/*/appendix/`** — the long-form studies that informed decisions. Link each study from its D-number. Do not move the decision into the appendix, and do not trim the study down to the decision line. +13. **`build-history/*/progress.md`** — what's done and what's next. +14. **`docs/connections.md`** — per-provider data research (what WHOOP/Oura/Garmin/Apple Health each provide via which path). +15. **`SPEC.md`** — the public field-level format reference. The normative model for version 3.0.0 is the Rust model in `core/src/model/` with its semantic checks. JSON Schema and the npm protocol declarations are generated from it. The Zod schemas in `packages/npm/src/schema.ts` are 2.1.x compatibility code for JavaScript callers (D209); they mirror the Rust model, including the 2.1.2 optional fields (D238, D239) and the 2.1.3 coach author (D255), are tested against the Rust validator, and are not where records are designed. For v1 storage, IDs, revisions, import behavior, and final schema names, D82–D105 supersede the relevant parts of D4, D25, D36, D40, D43, D48, D62, D64, and D65. The old decisions still diff --git a/build-history/README.md b/build-history/README.md index 4a04d123..5715ff2d 100644 --- a/build-history/README.md +++ b/build-history/README.md @@ -41,6 +41,7 @@ build-history/ | [v2.1.1](v2.1.1/spec.md) | Built, not yet released: the complete native rebuild. See its [decisions](v2.1.1/decisions.md), [progress](v2.1.1/progress.md), and [release evidence](v2.1.1/appendix/release-evidence.md). | | [v2.1.2](v2.1.2/spec.md) | Built, not released: calculation repairs, session effort, the CrossFit and HYROX coaching skills, and setup guidance in every skill. See its [decisions](v2.1.2/decisions.md) and [progress](v2.1.2/progress.md). | | [v2.1.3](v2.1.3/spec.md) | Built, not released: an optional host for sharing a record, coach authorship, and native and libSQL storage backends. See its [decisions](v2.1.3/decisions.md), [progress](v2.1.3/progress.md), [storage study](v2.1.3/appendix/hosted-storage-options.md), and [build evidence](v2.1.3/appendix/release-evidence.md). | +| [v2.2.0](v2.2.0/spec.md) | A plan. It is not built. See its [decisions](v2.2.0/decisions.md) and [progress](v2.2.0/progress.md). | | [v3.0.0](v3.0.0/spec.md) | Planned and approved, not built: thresholds, events, approvals, interval targets, device recordings, saved calculations, injury and illness reports, one engine with a WebAssembly build, and a clearer version rule. See its [decisions](v3.0.0/decisions.md) and [progress](v3.0.0/progress.md). | ## Drafts that were not approved diff --git a/build-history/v2.2.0/appendix/open-wearables-api.md b/build-history/v2.2.0/appendix/open-wearables-api.md new file mode 100644 index 00000000..4b24f8ae --- /dev/null +++ b/build-history/v2.2.0/appendix/open-wearables-api.md @@ -0,0 +1,658 @@ +# Open Wearables, as checked on 6 November 2026 + +This study is the evidence for the 2.2.0 plan. The rules are in +[the specification](../spec.md) and [the decisions](../decisions.md). Provider +software changes. A fact below is tied to the page or the file it came from. +Nothing here was read from a live server, and no key was used. Files +under `tests/fixtures/exports/open-wearables/` are not evidence. A claim +about what the server sends cites the Open Wearables docs or the pinned +0.11.0 OpenAPI file already named in this appendix. Later checks are +dated in their own sections. The last one is 15 November 2026. + +## What the product is + +Open Wearables is the program in the public repository +`the-momentum/open-wearables`. The repository describes it as a self-hosted +platform that puts wearable data behind one API. The license file reported by +GitHub is MIT. The repository was created on 30 October 2025. GitHub reported +the default branch `main` pushed at 13:43 UTC on 6 November 2026. + +The newest published release on that date was `0.11.0`, published at 16:10 UTC +on 2 November 2026, at commit `183e8cc4f6de897dbd288c93d49a691f2cf721ae`. +Its title is "0.11 - Daily +aggregates & faster summaries". The commit on `main` that day, +`7ca121dd4e48`, is "chore: update OW to 1.0 (#2065)". There was no GitHub +release named 1.0.0. + +The GitHub homepage field is `https://docs.openwearables.io`. This study did +not fetch that host. The pages it did fetch are on +`https://openwearables.io/docs`. The API introduction there says the reference +is generated from `docs/openapi.json` on every change, so the website describes +current `main`, and a self-hosted copy should be read from that copy's own +`/openapi.json`. + +Checked: + +- Repository: `https://github.com/the-momentum/open-wearables` +- Release `0.11.0`: `https://github.com/the-momentum/open-wearables/releases/tag/0.11.0` +- API introduction, fetched 6 November 2026: `https://openwearables.io/docs/api-reference/introduction` +- Integration guide, fetched the same day: `https://openwearables.io/docs/dev-guides/integration-guide` +- Doc index: `https://openwearables.io/docs/llms.txt` +- OpenAPI at the `0.11.0` tag: `docs/openapi.json`, `info.version` `0.11.0` +- OpenAPI on `main` the same day: `docs/openapi.json`, `info.version` `1.0.0` + +The integration guide says "self-hosted or cloud". In the same guide the cloud +case is a deployment the reader runs. This study did not find a separate +hosted service, in the repository description, the `0.11.0` notes, or the API +introduction, that stores data for people who do not run the server. + +Open Wearables is not Junction. Junction remains the other shipped mapping +file, and this plan does not call it. + +## The reads this plan uses + +D277 names every read. The paths below are the ones this study opened +first. Each is under `/api/v1` and takes a user id in the path. The user +id is an Open Wearables UUID. Dates are required on the paged reads. + +| Read | Path on `0.11.0` | Page shape | +|---|---|---| +| Sleep | `GET /api/v1/users/{user_id}/events/sleep` | `data`, `pagination`, `metadata` | +| Workouts | `GET /api/v1/users/{user_id}/events/workouts` | `data`, `pagination`, `metadata` | +| Timeseries | `GET /api/v1/users/{user_id}/timeseries` | `data`, `pagination`, `metadata` | + +`pagination.has_more` is required in the OpenAPI schema. `next_cursor` is +null when there is no next page. The cursor code in `0.11.0` is a URL-safe +base64 of a timestamp, an id, and an optional `prev_` prefix +(`backend/app/utils/pagination.py`). `limit` defaults to 50 and the maximum +is 1000. + +Sleep and timeseries take `filter_by_priority`, default `false`. The `0.11.0` +sleep handler passes that flag into the query. The `0.11.0` timeseries handler +does the same. On `main` (OpenAPI `1.0.0`, not a release), an omitted +`source_selection` means all devices when `filter_by_priority` is false. The +`main` workout list uses all devices when `source_selection` is omitted. The +`0.11.0` workout list has no priority flag. It returns the workouts in range. + +Timeseries `resolution` defaults to `raw`. The enum is `raw`, `1min`, `5min`, +`15min`, `1hour`, `1day`, `1week`, `1month`. The `0.11.0` service copies that +value into `metadata.resolution` (`timeseries_service.py` around the +`TimeseriesMetadata` construction). + +The `0.11.0` OpenAPI parameter `types` is an array of `SeriesType`. It omits +`style` and `explode`. For a query parameter, OpenAPI's default style is +`form`, and the default explode for `form` is true, which is one query +parameter per value. A comma-joined string is not a member of that enum. +This study did not send the request. The plan sends one parameter per type. + +The `0.11.0` release notes say day and session values are no longer samples. +They are read with `resolution=1day` or from the sleep or workout. The notes +say a sample row can carry `window_seconds`, and an aggregate can carry +`computed_by` of `provider` or `open_wearables`. The raw sample builder in +`timeseries_service.py` (the `_to_sample` call in the raw return) does not +pass `computed_by`. The field exists on the schema and can be null. + +`ComputedBy` is `provider` or `open_wearables`. The description says who +computed an aggregate. + +## Fields the mapping already names + +Sleep, from the `0.11.0` schema `SleepSession`: `id`, `start_time`, +`end_time`, `zone_offset`, `source`, `duration_seconds`, +`sleep_duration_seconds`, `time_in_bed_seconds`, `efficiency_percent`, +`stages`, `sleep_stage_intervals`, `is_nap`. Stages have `awake_minutes`, +`light_minutes`, `deep_minutes`, `rem_minutes`. The session object does not +carry resting heart rate, heart-rate variability, blood oxygen, skin +temperature, or respiration. `sleep_stage_intervals` is null unless the +query sends `include=stages` (`event_record_service.py` on this commit). +Stage minute totals are returned either way. Workout zones need +`include=zones`. Workout segments need `include=segments`. `source` has +`provider`, `source`, `device`, `device_type`, `device_id`, and read-only +`device_name`. `metadata.py` on this commit says `device_id` tells +same-model devices apart. `provider` is the integration, and `source` is +the writer inside it. + +The timeseries route defaults `types` to an empty list. The repository +filters by type only when that list is nonempty. An empty list is every +series. + +Workouts, from `Workout`: `id`, `type`, `name`, `start_time`, `end_time`, +`zone_offset`, `source`, `entry_source`, `intensity`, the distance, heart-rate, +and elevation fields the mapping already names, plus fields it does not name. +`entry_source` is `manual`, `automatic`, or `unknown`, and the response +allows null. The SDK maps an unsupported method to `unknown` and a +missing method to null. The schema text says `manual` is a self-reported +entry with no device measurement behind it. `unknown` and null are not +that entry, and they are not `automatic`. + +Timeseries, from `TimeSeriesSample`: `timestamp`, `zone_offset`, `type`, +`value`, `unit`, `source`, `is_daily_total`, `window_seconds`, `period_end`, +`computed_by`, `stats`. + +`start_time` and `timestamp` are schema format `date-time`. This study did not +capture a live JSON body, so it does not claim the wire format beyond that +schema. `zone_offset` is a separate string, `+01:00` or `-05:30`, or null. + +The 2.1.0 mapping file's timeseries lines do not name `heart_rate`. In +Athletic Standard, `heart_rate` is a series quantity +(`series_quantity_unit` in `src/model/data.rs`, unchanged in 2.1.1). It is not one of the point +quantities the 2.1.0 mapping engine writes. D277 stores that stream as +measurement samples. The 2.1.0 file, by itself, still has nowhere to put it. + +## Time bounds + +The API introduction says a date-only start is midnight UTC and a date-only +end covers that whole UTC day. + +The `0.11.0` parser does not say UTC. `parse_query_datetime` in +`backend/app/utils/dates.py` accepts a numeric Unix timestamp in seconds +before it tries `datetime.fromisoformat`. A date-only string becomes midnight +with no timezone. `parse_query_end_datetime` turns a date-only end into the +next midnight, also with no timezone, because the comparison is `<`. This +study did not follow those naive values into the database session, so it does +not claim which timezone PostgreSQL applies. Athletic Standard's own command +still refuses a numeric bound. That is this program's rule, not the server's. + +A full timestamp is sent through as parsed. The docs say a value with an +explicit time is used as given, and `end_time` at midnight includes nothing +later that day. + +## Credentials + +Data routes depend on `ApiKeyDep` (`backend/app/services/api_key_service.py` +on `0.11.0`). That dependency accepts a developer login JWT or the header +`X-Open-Wearables-API-Key`. A missing or unknown key is HTTP 401, detail +"Authentication required: provide JWT token or API key" or "Invalid or +missing API key". + +The integration guide says the key is not a bearer token, and +`Authorization: Bearer` with the API key returns 401. The OpenAPI operation +security lists `OAuth2PasswordBearer` and marks the API-key header optional. +Both can be true: the header is optional in the schema because a developer +JWT is the other way in. The header is how an integration authenticates. + +`POST /api/v1/users/{user_id}/token` returns a token the `0.11.0` route text +limits to SDK endpoints. `get_current_developer` in `backend/app/utils/auth.py` +rejects a token whose scope is `sdk` on developer routes. There is no +user-scoped token for the sleep, workout, and timeseries reads. The API key +is an administrator key for the whole deployment. The integration guide and +the credentials page say that. + +`GET /api/v1/users` lists every user and uses page/limit pagination, not the +cursor used by the three data reads. `GET /api/v1/users/{user_id}/personal-record` +returns birth date, gender, and sex. + +`DELETE` exists for one sleep, one workout, one provider connection, and one +provider's stored data. Those are writes against the server. None of the +three read routes takes `updated_since` or returns a deletion list. Sync +routes (`/sync`, `/sync/historical`, `/sync/runs`, `/sync/stream`) report or +start provider sync. They are not a feed of changed records. + +`GET /api/v1/config` returns feature flags and requires a developer JWT. It +has no version field. The docs point at `/openapi.json` for the running +version. That file is the full specification (about 600 KB at `0.11.0` and +about 700 KB on `main` the day of this study). + +Health scores use `limit` and `offset`. The `0.11.0` notes say Open Wearables +stops computing its own scores on 6 November 2026. Recovery summaries are +daily objects with a `date` and no instant. They include `avg_hrv_rmssd_ms` +and `avg_hrv_sdnn_ms` as separate fields. + +No rate-limit field was in the API introduction or in the three `0.11.0` +route files. A limit may still exist in middleware this study did not open. + +## Coverage audit on 7 November 2026 + +The same commit, `183e8cc4f6de897dbd288c93d49a691f2cf721ae`, was read again +for every user data route. The OpenAPI file is `docs/openapi.json`, +`info.version` `0.11.0`. The storage rule is section 2 of the +specification, as D277 says. This section records what the source shows. + +`SeriesType` is the enum in `backend/app/schemas/enums/series_types.py`. +Each entry in `SERIES_TYPE_DEFINITIONS` is an id, a name, and a unit. +`heart_rate` is `bpm`. `latitude` and `longitude` are `degrees`. The raw +path in `timeseries_service.py` copies `recorded_at`, `zone_offset`, the +type, the value, and `window_seconds`. It does not set `period_end` or +`computed_by`. The response `metadata.resolution` is the raw or day +label. A series row does not carry that label. The archive capsule +copies it. D282 writes that capsule only at the database revision where +the safety facts were read. + +`_aggregated_timeseries` handles `1min`, `5min`, `15min`, and `1hour`. It +sets `window_seconds` from `BUCKET_SIZES` and does not set `period_end`. +Those rows are buckets of raw samples, built when the query runs. + +`_period_timeseries` handles `1day`, `1week`, and `1month`. The timestamp +is `CalendarPeriod.of_date(period, zone_offset).start`. `period_end` is +the start of the next period. For a day, `computed_by` is the stored row's +value. For a week or a month, the code sets `computed_by` to +`open_wearables`. The comment says weeks start on Monday and months on +the first, from the local day. One response row is one period, one +source, and one series type. `stats` is the combined object. + +`SleepSession` has no resting heart rate, heart-rate variability, blood +oxygen, respiration, or temperature. `SleepSummary` has +`avg_heart_rate_bpm`, `avg_hrv_sdnn_ms`, `avg_hrv_rmssd_ms`, +`avg_respiratory_rate`, and `avg_spo2_percent`, plus a `date` and optional +`start_time` and `end_time`. `RecoverySummary` has `resting_heart_rate_bpm`, +`avg_hrv_rmssd_ms`, `avg_hrv_sdnn_ms`, `avg_spo2_percent`, and +`recovery_score`. It has no temperature field. The SDNN field text says +the value is null for current rows because they come from WHOOP and +WHOOP's HRV there is RMSSD. The class prose calls `recovery_score` +deprecated, WHOOP-only, and 0 to 100. The recovery query selects by +category, not by WHOOP, and copies `provider` and `value` unchanged. +Polar writes recovery scores on the 1 to 6 range. D280 uses that range +table and the copied provider. It does not use the prose as the scale. +`BodyLatest` has `skin_temperature_celsius` +and `skin_temperature_measured_at`. `BodyAveraged` has `period_start`, +`period_end`, and separate RMSSD and SDNN fields. + +Workout `segments` is an array of objects. `event_record_service.py` +fills it only when `include=segments`. Zones are filled only when +`include=zones`. The provider workout routes describe a live call to +Suunto, Polar, or Garmin. They are not the stored workout object. + +Sleep totals, workout totals, and activity totals describe sums of the +listed rows. The personal-record response fields are `birth_date`, +`gender`, and `sex`. + +## Contract read on 7 November 2026 + +The same commit was read again for the summary, score, meal, cycle, body, +and personal-record contracts. The storage rule is section 2 of the +specification, as D277 says. This section records the source facts that +rule uses. `SERIES_TYPE_DEFINITIONS` has 141 +entries. + +Raw rows keep the 2.1.0 kind when the mapping already names one. Those +series are `heart_rate_variability_rmssd`, `heart_rate_variability_sdnn`, +`resting_heart_rate`, `respiratory_rate`, `skin_temperature`, +`oxygen_saturation`, `heart_rate_recovery_one_minute`, `vo2_max`, +`garmin_stress_level`, and `garmin_body_battery`. + +The table below is the mapping for all 141 series. The storage rule is +section 2 of the specification. +`input_value` and the input unit are the server's number and unit. +`standard_value` equals `input_value` except where the conversion is +`divide by 100`. A day row uses the day record in the last column. It is +never a measurement sample. Apple skin temperature stays +`wrist_temperature_sleeping` when the writer is `apple`. `weight` is stored +as `body_weight`. The series name stays in `supplied_fields`. + +Sleep summary numbers in `event_record_repository.py` sum every non-nap +session in the source and date. The summary service sets `start_time` and +`end_time` from the longest main sleep. Those bounds stay on the original +object. They are not the period of the summed fields. + +| Series | Input unit | Raw class | Target | Standard unit | Conversion | Day record | +|---|---|---|---|---|---|---| +| `heart_rate` | `bpm` | measurement_sample | `heart_rate` | `bpm` | unchanged | provider_summary window | +| `resting_heart_rate` | `bpm` | point | `resting_heart_rate` | `bpm` | unchanged | provider_summary window | +| `heart_rate_variability_sdnn` | `ms` | point | `hrv_sdnn` | `ms` | unchanged | provider_summary window | +| `heart_rate_recovery_one_minute` | `bpm` | point | `hr_recovery` | `bpm` | unchanged | provider_summary window, summary type `hr_recovery` | +| `walking_heart_rate` | `bpm` | point | `walking_heart_rate` | `bpm` | unchanged | provider_summary window | +| `heart_rate_variability_rmssd` | `ms` | point | `hrv_rmssd` | `ms` | unchanged | provider_summary window | +| `oxygen_saturation` | `percent` | point | `oxygen_saturation` | `%` | alias | provider_summary window | +| `blood_glucose` | `mg_dl` | measurement_sample | `blood_glucose` | `mg_dl` | unchanged | provider_summary window | +| `blood_pressure_systolic` | `mmHg` | point | `blood_pressure_systolic` | `mmHg` | unchanged | provider_summary window | +| `blood_pressure_diastolic` | `mmHg` | point | `blood_pressure_diastolic` | `mmHg` | unchanged | provider_summary window | +| `respiratory_rate` | `brpm` | point | `respiratory_rate` | `brpm` | unchanged | provider_summary window | +| `sleeping_breathing_disturbances` | `count` | measurement_sample | `sleeping_breathing_disturbances` | `count` | unchanged | provider_summary window | +| `blood_alcohol_content` | `mg_dl` | measurement_sample | `blood_alcohol_content` | `mg_dl` | unchanged | provider_summary window | +| `peripheral_perfusion_index` | `score` | source_report | `peripheral_perfusion_index` | `score` | unchanged | source_report window | +| `forced_vital_capacity` | `liters` | measurement_sample | `forced_vital_capacity` | `liters` | unchanged | provider_summary window | +| `forced_expiratory_volume_1` | `liters` | measurement_sample | `forced_expiratory_volume_1` | `liters` | unchanged | provider_summary window | +| `peak_expiratory_flow_rate` | `L/min` | measurement_sample | `peak_expiratory_flow_rate` | `L/min` | unchanged | provider_summary window | +| `breathing_disturbance_index` | `score` | source_report | `breathing_disturbance_index` | `score` | unchanged | source_report window | +| `height` | `cm` | point | `height` | `cm` | unchanged | provider_summary window | +| `weight` | `kg` | point | `body_weight` | `kg` | unchanged | provider_summary window | +| `body_fat_percentage` | `percent` | point | `body_fat_percentage` | `%` | alias | provider_summary window | +| `body_mass_index` | `kg_m2` | source_report | `body_mass_index` | `kg_m2` | unchanged | source_report window | +| `lean_body_mass` | `kg` | point | `lean_body_mass` | `kg` | unchanged | provider_summary window | +| `body_temperature` | `celsius` | point | `body_temperature` | `°C` | alias | provider_summary window | +| `skin_temperature` | `celsius` | point | `skin_temperature` | `°C` | alias | provider_summary window | +| `waist_circumference` | `cm` | measurement_sample | `waist_circumference` | `cm` | unchanged | provider_summary window | +| `body_fat_mass` | `kg` | measurement_sample | `body_fat_mass` | `kg` | unchanged | provider_summary window | +| `skeletal_muscle_mass` | `kg` | measurement_sample | `skeletal_muscle_mass` | `kg` | unchanged | provider_summary window | +| `skin_temperature_deviation` | `celsius` | measurement_sample | `skin_temperature_deviation` | `°C` | alias | provider_summary window | +| `skin_temperature_trend_deviation` | `celsius` | measurement_sample | `skin_temperature_trend_deviation` | `°C` | alias | provider_summary window | +| `bone_mass` | `kg` | measurement_sample | `bone_mass` | `kg` | unchanged | provider_summary window | +| `body_water_mass` | `kg` | measurement_sample | `body_water_mass` | `kg` | unchanged | provider_summary window | +| `vo2_max` | `ml_kg_min` | provider_summary | `vo2_max` | `ml/kg/min` | alias | provider_summary window | +| `six_minute_walk_test_distance` | `meters` | measurement_sample | `six_minute_walk_test_distance` | `m` | alias | provider_summary window | +| `cardiovascular_age` | `years` | source_report | `cardiovascular_age` | `years` | unchanged | source_report window | +| `steps` | `count` | measurement_sample | `steps` | `count` | unchanged | provider_summary window | +| `active_energy` | `kcal` | measurement_sample | `active_energy` | `kcal` | unchanged | provider_summary window | +| `basal_energy` | `kcal` | measurement_sample | `basal_energy` | `kcal` | unchanged | provider_summary window | +| `stand_time` | `minutes` | measurement_sample | `stand_time` | `min` | alias | provider_summary window | +| `exercise_time` | `minutes` | measurement_sample | `exercise_time` | `min` | alias | provider_summary window | +| `physical_effort` | `met` | measurement_sample | `physical_effort` | `MET` | alias | provider_summary window | +| `flights_climbed` | `count` | measurement_sample | `flights_climbed` | `count` | unchanged | provider_summary window | +| `active_time` | `minutes` | measurement_sample | `active_time` | `min` | alias | provider_summary window | +| `total_energy` | `kcal` | measurement_sample | `total_energy` | `kcal` | unchanged | provider_summary window | +| `distance_walking_running` | `meters` | measurement_sample | `distance_walking_running` | `m` | alias | provider_summary window | +| `distance_cycling` | `meters` | measurement_sample | `distance_cycling` | `m` | alias | provider_summary window | +| `distance_swimming` | `meters` | measurement_sample | `distance_swimming` | `m` | alias | provider_summary window | +| `distance_downhill_snow_sports` | `meters` | measurement_sample | `distance_downhill_snow_sports` | `m` | alias | provider_summary window | +| `distance_other` | `meters` | measurement_sample | `distance_other` | `m` | alias | provider_summary window | +| `walking_step_length` | `cm` | measurement_sample | `walking_step_length` | `m` | divide by 100 | provider_summary window | +| `walking_speed` | `m_per_s` | measurement_sample | `walking_speed` | `m/s` | alias | provider_summary window | +| `walking_double_support_percentage` | `percent` | measurement_sample | `walking_double_support_percentage` | `%` | alias | provider_summary window | +| `walking_asymmetry_percentage` | `percent` | measurement_sample | `walking_asymmetry_percentage` | `%` | alias | provider_summary window | +| `walking_steadiness` | `percent` | measurement_sample | `walking_steadiness` | `%` | alias | provider_summary window | +| `stair_descent_speed` | `m_per_s` | measurement_sample | `stair_descent_speed` | `m/s` | alias | provider_summary window | +| `stair_ascent_speed` | `m_per_s` | measurement_sample | `stair_ascent_speed` | `m/s` | alias | provider_summary window | +| `running_power` | `watts` | measurement_sample | `running_power` | `W` | alias | provider_summary window | +| `running_speed` | `m_per_s` | measurement_sample | `running_speed` | `m/s` | alias | provider_summary window | +| `running_vertical_oscillation` | `cm` | measurement_sample | `running_vertical_oscillation` | `cm` | unchanged | provider_summary window | +| `running_ground_contact_time` | `ms` | measurement_sample | `running_ground_contact_time` | `ms` | unchanged | provider_summary window | +| `running_stride_length` | `cm` | measurement_sample | `running_stride_length` | `m` | divide by 100 | provider_summary window | +| `running_vertical_ratio` | `percent` | measurement_sample | `running_vertical_ratio` | `%` | alias | provider_summary window | +| `running_stance_time_balance` | `percent` | measurement_sample | `running_stance_time_balance` | `%` | alias | provider_summary window | +| `swimming_stroke_count` | `count` | measurement_sample | `swimming_stroke_count` | `count` | unchanged | provider_summary window | +| `underwater_depth` | `meters` | measurement_sample | `underwater_depth` | `m` | alias | provider_summary window | +| `cadence` | `rpm` | measurement_sample | `cadence` | `rpm` | unchanged | provider_summary window | +| `power` | `watts` | measurement_sample | `power` | `W` | alias | provider_summary window | +| `speed` | `m_per_s` | measurement_sample | `speed` | `m/s` | alias | provider_summary window | +| `workout_effort_score` | `score` | source_report | `workout_effort_score` | `score` | unchanged | source_report window | +| `estimated_workout_effort_score` | `score` | source_report | `estimated_workout_effort_score` | `score` | unchanged | source_report window | +| `distance` | `meters` | measurement_sample | `distance` | `m` | alias | provider_summary window | +| `elevation_gain` | `meters` | measurement_sample | `elevation_gain` | `m` | alias | provider_summary window | +| `environmental_audio_exposure` | `dB` | measurement_sample | `environmental_audio_exposure` | `dB` | unchanged | provider_summary window | +| `headphone_audio_exposure` | `dB` | measurement_sample | `headphone_audio_exposure` | `dB` | unchanged | provider_summary window | +| `environmental_sound_reduction` | `dB` | measurement_sample | `environmental_sound_reduction` | `dB` | unchanged | provider_summary window | +| `time_in_daylight` | `minutes` | measurement_sample | `time_in_daylight` | `min` | alias | provider_summary window | +| `water_temperature` | `celsius` | measurement_sample | `water_temperature` | `°C` | alias | provider_summary window | +| `uv_exposure` | `count` | measurement_sample | `uv_exposure` | `count` | unchanged | provider_summary window | +| `inhaler_usage` | `count` | measurement_sample | `inhaler_usage` | `count` | unchanged | provider_summary window | +| `weather_temperature` | `celsius` | measurement_sample | `weather_temperature` | `°C` | alias | provider_summary window | +| `weather_humidity` | `percent` | measurement_sample | `weather_humidity` | `%` | alias | provider_summary window | +| `elevation` | `meters` | measurement_sample | `elevation` | `m` | alias | provider_summary window | +| `latitude` | `degrees` | measurement_sample | `latitude` | `deg` | alias | provider_summary window | +| `longitude` | `degrees` | measurement_sample | `longitude` | `deg` | alias | provider_summary window | +| `air_temperature` | `celsius` | measurement_sample | `air_temperature` | `°C` | alias | provider_summary window | +| `garmin_stress_level` | `score` | provider_score | `garmin_stress_level` | `score` | unchanged; scale 1-100 | provider_score window | +| `garmin_skin_temperature` | `celsius` | measurement_sample | `garmin_skin_temperature` | `°C` | alias | provider_summary window | +| `garmin_fitness_age` | `years` | source_report | `garmin_fitness_age` | `years` | unchanged | source_report window | +| `garmin_body_battery` | `percent` | provider_score | `garmin_body_battery` | `score` | unchanged; input percent; scale 0-100 | provider_score window | +| `withings_pulse_wave_velocity` | `m_per_s` | measurement_sample | `withings_pulse_wave_velocity` | `m/s` | alias | provider_summary window | +| `withings_metabolic_age` | `years` | source_report | `withings_metabolic_age` | `years` | unchanged | source_report window | +| `dietary_energy_consumed` | `kcal` | source_report | `dietary_energy_consumed` | `kcal` | unchanged | source_report window | +| `dietary_carbohydrates` | `g` | source_report | `dietary_carbohydrates` | `g` | unchanged | source_report window | +| `dietary_fiber` | `g` | source_report | `dietary_fiber` | `g` | unchanged | source_report window | +| `dietary_sugar` | `g` | source_report | `dietary_sugar` | `g` | unchanged | source_report window | +| `dietary_fat_total` | `g` | source_report | `dietary_fat_total` | `g` | unchanged | source_report window | +| `dietary_fat_saturated` | `g` | source_report | `dietary_fat_saturated` | `g` | unchanged | source_report window | +| `dietary_fat_monounsaturated` | `g` | source_report | `dietary_fat_monounsaturated` | `g` | unchanged | source_report window | +| `dietary_fat_polyunsaturated` | `g` | source_report | `dietary_fat_polyunsaturated` | `g` | unchanged | source_report window | +| `dietary_cholesterol` | `mg` | source_report | `dietary_cholesterol` | `mg` | unchanged | source_report window | +| `dietary_protein` | `g` | source_report | `dietary_protein` | `g` | unchanged | source_report window | +| `dietary_sodium` | `mg` | source_report | `dietary_sodium` | `mg` | unchanged | source_report window | +| `dietary_potassium` | `mg` | source_report | `dietary_potassium` | `mg` | unchanged | source_report window | +| `dietary_calcium` | `mg` | source_report | `dietary_calcium` | `mg` | unchanged | source_report window | +| `dietary_iron` | `mg` | source_report | `dietary_iron` | `mg` | unchanged | source_report window | +| `dietary_magnesium` | `mg` | source_report | `dietary_magnesium` | `mg` | unchanged | source_report window | +| `dietary_phosphorus` | `mg` | source_report | `dietary_phosphorus` | `mg` | unchanged | source_report window | +| `dietary_zinc` | `mg` | source_report | `dietary_zinc` | `mg` | unchanged | source_report window | +| `dietary_copper` | `mg` | source_report | `dietary_copper` | `mg` | unchanged | source_report window | +| `dietary_manganese` | `mg` | source_report | `dietary_manganese` | `mg` | unchanged | source_report window | +| `dietary_selenium` | `mcg` | source_report | `dietary_selenium` | `mcg` | unchanged | source_report window | +| `dietary_chromium` | `mcg` | source_report | `dietary_chromium` | `mcg` | unchanged | source_report window | +| `dietary_molybdenum` | `mcg` | source_report | `dietary_molybdenum` | `mcg` | unchanged | source_report window | +| `dietary_iodine` | `mcg` | source_report | `dietary_iodine` | `mcg` | unchanged | source_report window | +| `dietary_chloride` | `mg` | source_report | `dietary_chloride` | `mg` | unchanged | source_report window | +| `dietary_vitamin_a` | `mcg` | source_report | `dietary_vitamin_a` | `mcg` | unchanged | source_report window | +| `dietary_vitamin_b6` | `mg` | source_report | `dietary_vitamin_b6` | `mg` | unchanged | source_report window | +| `dietary_vitamin_b12` | `mcg` | source_report | `dietary_vitamin_b12` | `mcg` | unchanged | source_report window | +| `dietary_vitamin_c` | `mg` | source_report | `dietary_vitamin_c` | `mg` | unchanged | source_report window | +| `dietary_vitamin_d` | `mcg` | source_report | `dietary_vitamin_d` | `mcg` | unchanged | source_report window | +| `dietary_vitamin_e` | `mg` | source_report | `dietary_vitamin_e` | `mg` | unchanged | source_report window | +| `dietary_vitamin_k` | `mcg` | source_report | `dietary_vitamin_k` | `mcg` | unchanged | source_report window | +| `dietary_thiamin` | `mg` | source_report | `dietary_thiamin` | `mg` | unchanged | source_report window | +| `dietary_riboflavin` | `mg` | source_report | `dietary_riboflavin` | `mg` | unchanged | source_report window | +| `dietary_niacin` | `mg` | source_report | `dietary_niacin` | `mg` | unchanged | source_report window | +| `dietary_folate` | `mcg` | source_report | `dietary_folate` | `mcg` | unchanged | source_report window | +| `dietary_pantothenic_acid` | `mg` | source_report | `dietary_pantothenic_acid` | `mg` | unchanged | source_report window | +| `dietary_biotin` | `mcg` | source_report | `dietary_biotin` | `mcg` | unchanged | source_report window | +| `dietary_caffeine` | `mg` | source_report | `dietary_caffeine` | `mg` | unchanged | source_report window | +| `dietary_fat_trans` | `g` | source_report | `dietary_fat_trans` | `g` | unchanged | source_report window | +| `dietary_energy_from_fat` | `kcal` | source_report | `dietary_energy_from_fat` | `kcal` | unchanged | source_report window | +| `dietary_fat_unsaturated` | `g` | source_report | `dietary_fat_unsaturated` | `g` | unchanged | source_report window | +| `dietary_folic_acid` | `mcg` | source_report | `dietary_folic_acid` | `mcg` | unchanged | source_report window | +| `electrodermal_activity` | `count` | measurement_sample | `electrodermal_activity` | `count` | unchanged | provider_summary window | +| `push_count` | `count` | measurement_sample | `push_count` | `count` | unchanged | provider_summary window | +| `atrial_fibrillation_burden` | `count` | measurement_sample | `atrial_fibrillation_burden` | `count` | unchanged | provider_summary window | +| `insulin_delivery` | `count` | measurement_sample | `insulin_delivery` | `count` | unchanged | provider_summary window | +| `number_of_times_fallen` | `count` | measurement_sample | `number_of_times_fallen` | `count` | unchanged | provider_summary window | +| `number_of_alcoholic_beverages` | `count` | source_report | `number_of_alcoholic_beverages` | `count` | unchanged | source_report window | +| `nike_fuel` | `count` | source_report | `nike_fuel` | `count` | unchanged | source_report window | +| `hydration` | `mL` | source_report | `hydration` | `mL` | unchanged | source_report window | + +`get_day_rows` keeps one row per data source, series, and local day. It +orders provider-computed rows first, then the later `period_start`. +`_period_timeseries` rebuilds the response bounds with `CalendarPeriod`. +A week or month forces `computed_by` to `open_wearables`. A day page's +`limit` counts periods. The service floors that count at 1, and one period +can contain one row per source and series. + +`HEALTH_SCORE_RANGES` sets the finite scales. Sleep is 0 to 100 for +internal, WHOOP, and Samsung, and 1 to 100 for Oura, Garmin, and Polar. +Oura readiness and Oura activity are 1 to 100. Polar readiness is 0 to 10. +Garmin stress and Garmin body battery are 0 to 100. WHOOP and Suunto +recovery are 0 to 100. Polar recovery is 1 to 6. WHOOP strain is 0 to 21. +Polar strain has no finite maximum. The route text says `provider: internal` scores were +computed by Open Wearables and are still returned. WHOOP recovery +components include `skin_temp_celsius` when the provider sent it. + +`get_menstrual_cycles` sets `end_datetime` to null. `get_body_summary` +uses `datetime.now`, omits `device_id`, and does not put a time on +`BodySlowChanging`. The personal-record response is `birth_date`, +`gender`, `sex`, and `user_id`. A field that was never set is null. + +`summaries_service.py` reads skin temperature from the latest sample +window. When that read is empty, `latest_day_value` supplies the newest +day value and `period_start`. The service unpacks that pair into the same +`skin_temperature_measured_at` field. The response does not say which +read it was. `heart_rate_recovery_one_minute` is series id 4, unit `bpm`. +`TimeSeriesSampleBase.value` is a number with no positive minimum. The +column is `numeric_unbounded`. + +## Stored workouts and the live provider routes + +Checked at commit `183e8cc4f6de897dbd288c93d49a691f2cf721ae` on 8 November +2026. No server was called, and no vendor account was used. + +The stored workout response is the `Workout` model in +`schemas/responses/activity/events.py`. It has the Open Wearables id and +the normalized fields. It has no `external_id`. The database row does +have `external_id`. The public model does not return it. + +The live routes are `vendor_workouts.py`. Both handlers call +`get_workouts_from_api` or `get_workout_detail_from_api` and return that +value. Neither handler inserts a workout row. + +The authenticated client can still change the server. Checked in the same +commit on 14 November 2026. `refresh_access_token` calls +`update_tokens` and saves the new vendor token. `revoke_connection` marks +the connection revoked and calls `on_connection_revoked`, which emits +`connection.revoked`. Revoke runs when refresh is missing, when refresh +is rejected, and after auth has failed for `DEAD_GRANT_AFTER` of one day. +The client writes Redis keys `token_refresh_lock` and +`provider_auth_failing_since`. On HTTP 429, `RETRY_BASE_DELAY` is 15 +seconds and `MAX_RETRIES` is 3, so the waits are 15, 30, and 60 seconds. +A nearby comment says 1, 2, and 4 seconds. The constant is 15. + +`GET /api/v1/users/{user_id}/connections` returns the user's connections. +The pinned Open Wearables Strava page lists 200 requests per 15 minutes +for a standard tier and 400 for extended access. Those are Strava's +overall limits. The lower read limit, which covers every GET, is in the +15 November 2026 section below. Garmin's live method accepts upload +start and end. A range the method itself splits can hide a failed chunk. +This plan has the client send shorter windows instead. The 15 November +2026 section gives their length. + +Polar's live methods pass `samples`, `zones`, and `route` through to +`/v3/exercises`. The save path calls the list method without those +arguments, so the request uses false. `ExerciseJSON` can parse samples, +zones, and route. `_normalize_workout` copies the sport, the device, the +times, the average and maximum heart rate, the calories, and the +distance. It does not copy samples, zones, or route. The Polar provider +page says the exercise list is the exercises available in Polar Flow. It +does not say Polar keeps every past exercise. + +`ingest_workout_samples` defaults to false. `store_fit_files` defaults to +false. `raw_payload_storage` defaults to `disabled`. `store_raw_payload` +returns immediately when the backend is disabled. `store_fit_file` +returns immediately when FIT storage is disabled. Garmin's activity-file +branch still downloads a FIT file and can save parsed segments and zones. +It adds FIT samples to `series_sample` only when `ingest_workout_samples` +is true. Strava's stream save returns zero when that flag is false. Those +are settings. This study does not know how a particular deployment set +them. When the flags are off, the samples and the FIT bytes are not +stored. The stored timeseries read can return samples only when a save +path wrote them. + +Garmin's live list sends `uploadStartTimeInSeconds` and +`uploadEndTimeInSeconds`. With no range, the method uses the last 24 +hours. Its `load_data` saves nothing and says activities arrive by +webhook. Suunto's published parameters are `since`, `limit`, `offset`, +and `filter_by_modification_time`. Whoop's start, end, and `nextToken` +are not parameters of the route. The method then sends no start and caps +`limit` at 25. Oura's dates and `next_token` are not on the route. +Strava's `after` and `before` are not on the route. The method defaults +to page 1 and `strava_events_per_page` of 200. Fitbit's detail method is +the base method, which raises `NotImplementedError`. Its list method uses +the last 30 days when no dates are passed. Withings uses +`pull_sync_lookback` or 30 days and does not implement detail. Sensorbio +uses `limit` and `last-timestamp` 0 and does not implement detail. Google +Health does not implement the live method. Apple, Samsung, Health +Connect, and Ultrahuman leave `workouts` unset, and the route answers +501. + +A missing live payload is not the same fact as a stored row the list +route did not include. The stored list returns what normalization saved. +The live route returns what the provider method returns on that call. A +flag that is off explains samples and FIT bytes that were never written. +A route parameter that does not exist explains a provider page that +cannot take this pull's range. A provider that has no live method is not +an empty workout history. + +## Checks on 15 November 2026 + +The live-route facts below were read again at commit +`183e8cc4f6de897dbd288c93d49a691f2cf721ae`, for the review findings and +for Athletic Standard 2.1.1. No server was called, and no vendor account +was used. Every path below is in the Open Wearables repository at that +commit, under `backend/app/`. + +Connections. `UserConnectionWithCapabilities`, in +`schemas/model_crud/user_management/user_connection.py`, has `user_id`, +`provider`, `provider_user_id`, `provider_username`, `scope`, `id`, +`status`, `last_synced_at`, `created_at`, `updated_at`, `icon_url`, +`max_historical_days`, `rest_pull`, four webhook flags, `live_sync_mode`, +and `linked_user_ids`. The route fills `linked_user_ids` with other users +linked to the same vendor account. `ConnectionStatus`, in +`schemas/auth/connection_status.py`, is `active`, `revoked`, or `expired`. + +Live routes. Both handlers in `api/routes/v1/vendor_workouts.py` return the provider +method's value unchanged. The list handler passes `since`, `limit` +(default 50, at most 100), `offset`, `filter_by_modification_time` +(default true), `samples`, `zones`, `route`, `summary_start_time`, and +`summary_end_time` to every provider. Each provider reads the ones it +uses. + +Client. `_make_api_request` in `services/providers/api_client.py` makes +at most four attempts. Each attempt uses `provider_request_timeout_seconds`, +which is 30 seconds by default and at most 300 in `config.py`. A 429 waits 15, then +30, then 60 seconds. A 401 reloads the token once and tries again. That +reload can refresh the vendor token under `token_refresh_lock`, and a +refresh the vendor rejects revokes the connection. The second try is one +of the four attempts. A 401 or 403 that remains is noted in +`provider_auth_failing_since`. When one comes a day or more after the +first noted failure, with no success between, the server revokes the +connection. That day is `DEAD_GRANT_AFTER`. A success clears the note. A +timeout or another transport error is not retried. A token refresh holds +`token_refresh_lock` for up to 60 seconds and waits up to 10 seconds for +it. So with the default timeout, one GET can take about 225 seconds, plus +a refresh. After the last 429 retry the client raises HTTP 429. Any other +vendor error status except 401 is raised with the vendor's own status, so +a vendor 404 reaches the caller as 404. A transport error becomes 500. The +route answers 501 only for a provider whose `workouts` is unset, so a +Garmin call never gets the route's own 501. + +Garmin. `get_workouts_from_api` in `services/providers/garmin/workouts.py` reads +`summary_start_time` and `summary_end_time` as an integer first, then as +ISO 8601. It turns both into naive local times with +`datetime.fromtimestamp` and compares them. A difference over 24 hours +goes to `get_workouts_historical`, which fetches 24-hour pieces and logs +and skips a piece that fails. On a server whose local zone moves its +clock forward, a true 24-hour window that crosses that change is 25 local +hours. When the clock moves back, it is 23 local hours. A 23-hour window +is at most 24 local hours where the clock moves by one hour. In +`Antarctica/Troll`, which moves its clock by two hours, a 23-hour window +is 25 local hours. Those numbers come from Python's +`datetime.fromtimestamp` with `TZ` set to `America/Chicago` and to +`Antarctica/Troll`, run on 15 November 2026 across the 2026 changes. +So this plan sends windows of exactly 82,800 seconds, 23 hours, on a +fixed grid that starts at the Unix epoch. A one-year range is 381 or 382 +windows. A window of 24 local hours or less is sent to Garmin as +`uploadStartTimeInSeconds` and `uploadEndTimeInSeconds` with both +integers unchanged, so the grid reaches Garmin as sent. Detail calls +`/wellness-api/rest/activities/{activity_id}`. This study did not find that +path in Garmin's public docs. `ActivityJSON` types `activityId` as an +integer or a string. The Garmin wellness models declare an optional +`userAccessToken`. `ActivityJSON` does not, but the live route returns +Garmin's objects unchanged. + +Suunto. `get_workout_detail` in `services/providers/suunto/workouts.py` names its argument +`workout_key` and calls `/v3/workouts/{workout_key}`. The route calls +`get_workouts_from_api`, which sends one page: `since`, `limit` at most +100, `offset`, and `filter-by-modification-time`. The internal +`get_workouts` walks every page until a short one, but the route does not +call it. So each route call returns one page, and the caller pages by +`offset`. The route's `filter_by_modification_time` defaults to true, so +this plan sends false. + +Whoop. The method in `services/providers/whoop/workouts.py` caps `limit` +at 25, takes `nextToken` from the request, and reads `next_token` in the +response. `WhoopWorkoutCollectionJSON`, in +`schemas/providers/whoop/workout_import.py`, declares `records` and +`next_token` with no alias, so Whoop's own response key is `next_token`. +The route never passes `nextToken`, so one call reads only the first +page. Oura's method in `services/providers/oura/workouts.py` sends and +reads `next_token`. + +Sensorbio. The route's method in `services/providers/sensorbio/workouts.py` +sends `last-timestamp` 0 and `limit` at most 50, and returns that one +response. It does not follow `links.next`, so it reads the oldest 50 +entries. + +Strava. `get_workouts_from_api` in `services/providers/strava/workouts.py` +sends `page` 1 and `per_page` from +`strava_events_per_page`, which is 200 by default, and ignores `limit`. +Strava's API reference, fetched 15 November 2026, lists `DetailedActivity` +fields that include `laps`, `splits_metric`, `splits_standard`, +`segment_efforts`, `best_efforts`, `map`, `photos`, `gear`, +`description`, `calories`, and `embed_token`. It calls `embed_token` the +token used to embed a Strava activity. Strava's rate-limit page, +`https://developers.strava.com/docs/rate-limits/`, fetched the same day, +says limits are per application. The default overall limit is 200 +requests per 15 minutes and 2,000 a day. The default non-upload limit, +which covers every GET, is 100 per 15 minutes and 1,000 a day. After the +upgrade on the API settings page, the read limit is 200 and 2,000, and +the overall limit is 400 and 4,000. A request over a limit gets a 429. + +## What was not checked + +- A running server's JSON, including the exact `start_time` text. +- A live provider account, a sync call, or a historical-sync call. +- Whether Docker tag `latest` matches release `0.11.0` or `main`. +- The database timezone applied to a date-only bound. +- Middleware rate limits. +- Any timeout the server's web process puts in front of the live routes. +- Garmin's public docs for the detail path and for a per-minute rate. The + review cited about 100 requests a minute. This study did not find it. +- Which local timezone a given deployment runs in. +- Whether a Garmin activity object from the live list carries + `userAccessToken`. +- The host `https://docs.openwearables.io`. diff --git a/build-history/v2.2.0/appendix/vendor-original-size.md b/build-history/v2.2.0/appendix/vendor-original-size.md new file mode 100644 index 00000000..d9c7080a --- /dev/null +++ b/build-history/v2.2.0/appendix/vendor-original-size.md @@ -0,0 +1,70 @@ +# Size of a vendor original in a package + +This study was measured on 16 November 2026 for the live-original proposal, +now D287. It used no real +data. Every value below is invented. + +## Method + +`ath export` at `0de71bb` writes each record and each revision with +`json::to_deterministic_pretty` in `src/json.rs`. That printer puts two +spaces before each level, sorts keys, and writes `": "` after each key. +`ArrayWriter::item` in `src/package/export.rs` then indents every line +four more spaces and writes `,` and a new line before each item. The +stored `record_revisions.record_json` is compact. A short Python script +copied those rules and the JavaScript number text for these values. It +then measured one synthetic original. + +The original follows the pinned Polar `ExerciseJSON` model in +`backend/app/schemas/providers/polar/exercise_import.py` at Open +Wearables commit `183e8cc4f6de897dbd288c93d49a691f2cf721ae`. It is a +one-hour run: + +- a route of 3,600 points, one a second. Each point has `latitude` and + `longitude` to six decimals, `time`, `satellites`, and `fix`. +- six sample strings with one value a second: heart rate, speed, + cadence, altitude, temperature, and distance +- five heart-rate zones, and the model's summary fields +- the envelope in section 2 of the specification. `list` has no samples, + zones, or route. `detail` has all three. +- the `source_report` fields around the envelope, with invented ids and + times + +A second shape drops the samples and the zones and keeps the route. + +## Results + +| Shape | Compact `record_json` | One exported item | Ratio | Exported, one revision | Exported, two revisions | +|---|---|---|---|---|---| +| Route, samples, and zones | 412,909 bytes | 847,259 bytes | 2.05 | 1,694,355 bytes | 2,541,611 bytes | +| Route only | 311,189 bytes | 744,471 bytes | 2.39 | 1,488,779 bytes | 2,233,247 bytes | + +An original with one revision is in the main document twice: once as its +current record and once as that revision. So it exports at about four +times its compact column bytes. Each later revision adds one more item. + +Under 256 MiB of exported bytes: + +- 158 originals of the first shape fit with one revision each, or 105 + with two. +- 180 originals of the route-only shape fit with one revision each, or + 120 with two. + +The earlier bound counted 128 MiB of compact `record_json`. With one +revision for each original, that is about 525 MiB of the first shape as +export writes it, and about 612 MiB of the route-only shape. Both are +over the 512 MiB package read cap. + +The deepest value is a route point's field, five levels inside the +record's `data`. In the package it is eight levels deep. A package reads +back at 127 levels or fewer. `check_nesting` allows 128, but serde_json +1.0.154 refuses 128 when the read parses the document. + +## What was not measured + +- A real vendor response. Route point text and sample strings differ by + device and by sport. +- Garmin, Strava, and Suunto details. Their laps, splits, and sample + arrays nest in other ways. +- How long `ath check` takes to measure every original in a database + near the bound. A write measures only the items it writes. diff --git a/build-history/v2.2.0/decisions.md b/build-history/v2.2.0/decisions.md new file mode 100644 index 00000000..6384407a --- /dev/null +++ b/build-history/v2.2.0/decisions.md @@ -0,0 +1,1950 @@ +# Decisions — v2.2.0 + +These are proposals in [spec.md](spec.md). The maintainer has not adopted +them. This pull request does not build them. A change of mind before +approval is an edit of the proposal. After approval, a change is a new +D-number. + +## Numbering + +These proposals are D272 through D289. They were first written as D198 +through D215, when D197 was the last decision on `main`. Version 2.1.1 then +used D208 through D226. D224 keeps D198 through D207 reserved for the +unapproved 2.1.1 draft in +[v2.1.1/appendix/draft-2.1.1/](../v2.1.1/appendix/draft-2.1.1/spec.md), so +they are never reused. On 15 November 2026 each proposal moved to the next +free number, D227 through D244, in the same order. Version 2.1.2 then used +D227 through D253. On 21 November 2026 each proposal moved again, to D254 +through D271, in the same order. Version 2.1.3 then used D254 through D271. +On 24 November 2026 each proposal moved again, to D272 through D289, in the +same order. In this folder, D208 through D226 mean the 2.1.1 decisions, +D227 through D253 mean the 2.1.2 decisions, and D254 through D271 mean the +2.1.3 decisions. Reviews written before 15 November 2026 use the first +numbers. Reviews written from that day until 21 November 2026 use the +second numbers. Reviews written from 21 November 2026 until 24 November +2026 use the third numbers. + +| First | After 2.1.1 | After 2.1.2 | Now | Subject | +|---|---|---|---|---| +| D198 | D227 | D254 | D272 | Version 2.2.0 and one manual pull | +| D199 | D228 | D255 | D273 | Pages, and the shipped mapping writes the records | +| D200 | D229 | D256 | D274 | The key, the server, and the user id | +| D201 | D230 | D257 | D275 | A page is atomic and a repeat is safe | +| D202 | D231 | D258 | D276 | Work left out of this build | +| D203 | D232 | D259 | D277 | Stored measurements are kept | +| D204 | D233 | D260 | D278 | Meaning, source, and time | +| D205 | D234 | D261 | D279 | Units, windows, reported records, and identities | +| D206 | D235 | D262 | D280 | The new record type and refused originals | +| D207 | D236 | D263 | D281 | The migration rename, the counts, and the archive | +| D208 | D237 | D264 | D282 | The archive's safety facts | +| D209 | D238 | D265 | D283 | A typed workout is a session | +| D210 | D239 | D266 | D284 | Skin-temperature times | +| D211 | D240 | D267 | D285 | Heart-rate recovery of zero | +| D212 | D241 | D268 | D286 | A manual session window | +| D213 | D242 | D269 | D287 | A live workout original | +| D214 | D243 | D270 | D288 | The live vendor read | +| D215 | D244 | D271 | D289 | Vendor originals and credentials | + +## Changes on 15 November 2026 + +The plan was read again against `main` at `0de71bb`, the merge of 2.1.1. +These edits follow from that reading: + +- D275 and D282. A page is one 2.1.1 import preview and one apply. The + preview never writes. The apply refuses the page when the database + revision moved after the preview. The earlier text counted a page inside + a write transaction, rolled the count back, and read the safety facts a + second time under the write lock. Version 2.1.1 has no such step. +- D281 and D282. A deleted source or a deleted record leaves its rows out, + as D182 and D190 say. It no longer refuses the page. It still stops the + archive of that page. +- D272 and D281. Step 7 runs on the store's own connection. Foreign keys + are turned off before its transaction starts, in `src/store/migrate.rs`. +- D273. The pull gives each page to a reader that holds the page in + memory. `MappedReader` in 2.1.1 reads a file path. +- D274. The Open Wearables key is a third `KeyAccount`, beside the gateway + keys and the Garmin token. `ath key clear garmin` stays refused, as it is + in 2.1.1. +- D275, D277, D278, and D288. Limits and timeouts are named constants, as + 2.1.1 does. One response may be at most `MAX_PULL_RESPONSE_BYTES`, which + is 10 MiB. The earlier text said 8 MiB. +- D276. The source rules go in `src/import/provider.rs` and a new + `src/import/binding.rs`, where 2.1.1 stages and applies an import. They + no longer go in `src/store/write.rs`. The protocol's record writes join + the owner writes that store a whole source record. +- D277, D280, and D281. Sentences that called the new migration step 5 now + say step 6. Step 5 is the published 2.1.1 migration. + +These edits answer the thirteen findings of the review at `e145fa6`: + +- D287. The stored original's JSON layout, its key, its counts, and owner + deletion and correction. +- D288. Connections, statuses, Suunto keys, detail rules, timeouts, request + budgets, Garmin windows, id spelling, start times, and the count of every + object left out. Garmin windows are 23 hours, not 24, because the pinned + server measures a window in naive local time. +- D289. A credential-shaped value is withheld and counted. It no longer + refuses the page. + +## Changes after the review at `d636d7a` + +These edits answer the review of this plan at `d636d7a`: + +- D272. A new database runs its migrations on the connection + `Store::create` opened, not through `Store::transaction`. The two 2.1.1 + checks that expect one transaction to reach the last schema are named, + with the check that replaces each. +- D275. The 2.1.1 comment on the 10 MiB response cap names only Garmin. + The build rewrites it and the route list to name both pulls. +- D276. The `src/import/provider.rs` list is complete. It adds a + `connector` source call, because `route_source` stages only + `export_file` sources, and a count by record type in + `src/import/staging.rs`. The revision a preview read is already public. +- D288. A Garmin detail that answers 404 or 501 is `not_available`, not + `failed`. Garmin stays `completed`, and the list object is stored whole. + The pinned detail path is not in Garmin's public docs. +- D287. On route `open_wearables`, an owner correction is replaced only + when the server's data differs from the newest revision an import wrote. + Each replaced correction is counted per provider and for stored records, + in the text, in `--json`, and in the preview. The skill says where a + workout fix belongs. +- D288. An HTTP 429 stops that provider for the command, as a timeout + does. Credential values are withheld before any comparison. +- D275 and D281. A committed vendor page is a protected write. It sets + `written` and `database_changed`, and its originals add to + `committed.source_report`. +- D288. When one Garmin activity id is in two windows with different + objects, the later window's copy is kept and the earlier is counted as + `superseded`. +- D287. Vendor originals have a 128 MiB total bound, because a package + holds them in its main document under the 512 MiB read cap. `ath export` + refuses to publish a document over that cap. +- D288. A Suunto list object with no `workoutKey` gets no detail call and + is `not_available`. A detail over the response cap is `too_large`, and a + detail the privacy scan refuses is `refused`. Both make the provider + `incomplete`. +- D288. A preview reads each list and makes no detail call, so a preview + then `--yes` reads each list twice and makes each detail call once. One + command sends at most 100 Suunto list requests. A detail can come + minutes after its list object, and the plan says so. +- D289. The page cursors `next_token` and `nextToken` are not + credential-shaped. A user name or password in a URL, and a + credential-shaped pair in a URL fragment, are withheld too. +- D288. The daylight-saving sentence names both directions. A forward + change makes 24 real hours read as 25 local hours, and a backward change + makes them read as 23. A zone that moves its clock by two hours is not + covered by the 23-hour window. +- D276. The `__proto__` citation names `check_supplied_fields`, which + still refuses the key at any depth on import. D214 in 2.1.1 changed only + the native reader. +- D288. For Garmin, Suunto, Whoop, and Oura, which name no detail field, a + new detail with fewer fields replaces the stored one, and the stored + detail stays in the record's history. +- D275. Each of the four page refusals names the owner's fix, or says + 2.2 has none. + +## Changes after the review at `3c3f660` + +These edits answer the reviews of this plan at `3c3f660`. No decision +number is added: + +- D288. The opening of the specification says what the flag reads on a + preview and on `--json`: the connections list and each active + provider's list, with no detail call. The help text, the examples, and + their test say the same. +- D288. A preview, which every `--json` run is, labels every vendor count + and both owner-correction counts `estimated`. It calls the count of ids + `--yes` would detail `would_detail`, prints `estimated` on each + provider line, and says that it made no detail calls, in the text and + in `vendor_workouts.notice`. +- D288. The first Garmin detail call in a command is a probe. When it + answers 400, 403, 404, 405, or 501, no other Garmin detail call is made + in that command. The other due ids are `deferred`, Garmin stays + `completed`, and its line says detail is unavailable. An id that was + `not_available` is called again only when its list object changed. A + 401 on any live request stops that provider for the command, as a 429 + does. This is the stated default, and the maintainer still has to + confirm it. +- D287 and D288. Each Garmin envelope keeps its `upload_window`. On a + later command, a copy from a window that ends at or before the start of + the stored copy's window is `superseded`. It writes nothing and never + replaces an owner correction. Comparisons leave the window out. +- D287 and D276. The vendor-original bound is 256 MiB, half of the 512 MiB + read cap, counted in the bytes export writes. The earlier bound counted + 128 MiB of compact JSON, which could export to about 525 MiB. It holds + about 158 one-hour Polar workouts with routes and samples. `ath + correct`, the protocol writes, a package merge, and a native restore + check it too. Every pull prints the total used and warns from 80%. The + export check also refuses an item past the 128-level nesting limit. + Storing originals in their own files is an open question for the + maintainer. +- D288. A detail that timed out is `failed`, as one that got 429 or 401 + is. Only ids still due a detail call become `deferred`. An id due no + call keeps its own count. Each id goes in the first group of the detail + order it matches, and a `too_large` or `refused` id is no longer in the + first group. +- D288. One `--yes` command sends 24 Strava requests when only the last + request was retried, or 25 after a token reload, which leaves about 75. + The ceiling is 84, because the pull cannot see a server retry that + ended in success. +- D288 and D276. A vendor object with a `__proto__` key is refused alone + as `unusable_name`, and the provider stays `completed`. The import check + would otherwise fail that provider's page on every command. +- D275. The rebind fix says that it merges the two devices' history on + one source. The source's history keeps the old binding. +- D287. The file-import sentences and the corrected-original test follow + the owner-correction rule. A vendor page's counts stay apart from + `archive_committed`. +- D273 and D276. Page counts come from one SQL count beside + `Staging::count`, not from `ProviderPreview::planned`, which copies each + row's `data_json`. +- D287. The owner-correction rule reads + `record_revisions.became_known_at_basis`, not `changed_by`, because + `ath grade` writes the same tool actor as an import. +- D288. The Suunto list cap is named `MAX_SUUNTO_LIST_REQUESTS`. +- D287. A package merge counts as an owner correction only where the + person resolved a conflict, because `merge_in` copies the package's + revisions with their own bases. The counts name that part + `merge_choices_replaced`, and the line adds `(M of them merge + choices)`. Body-snapshot records rarely keep a correction, because the + server's averaging window moves with every request. The rule still + covers every record the `open_wearables` pull writes, and other routes + keep D182. The maintainer still has to confirm that scope. + +## Changes after the reviews at `57838e1` + +These edits answer the reviews of this plan at `57838e1`. No decision +number is added: + +- D288. Garmin windows sit on a fixed grid. Each starts at a multiple of + 82,800 seconds after the Unix epoch, and the first and last windows are + widened to whole grid windows. So two commands send equal windows or + windows that do not overlap, and the earlier-window test always + applies to a pull. A pull's new read of the stored window is a change. + Any other overlap, which only a saved file can carry, counts as + `ambiguous_window`. The stored copy is kept, and no owner correction + is replaced. +- D288. Only a 404 or 501 on the Garmin probe marks the probed id + `not_available`. Any other error status, except 401 and 429, defers + every due id, and the next command probes again. A 5xx also makes + Garmin `incomplete`. An id that got 404 or 501 keeps the time as + `detail_checked_at` and is asked again after 30 days, or sooner when its + list object changes. An original with a current owner correction is + asked again only when its list object changes. +- D288 and D276. When only a detail holds a `__proto__` key, the clean + list object is stored with `detail_status` `refused` and `refused_by` + `unusable_name`, and the detail is asked for again only when the list + object changes. Each refused object and refused detail is named in + `left_out.examples` by provider, vendor id, reason, and key path. +- D288 and D287. A vendor object nested 123 levels or more is refused as + `too_deep`, counted, and named with its depth. A deep detail keeps its + clean list object, as a `__proto__` detail does. The read refuses 128 + levels, though `check_nesting` allows 128, so the export check now + refuses an item that reaches 128. That is why the cut is 123 and not + 124. +- D287. Step 7 creates `vendor_original_sizes`, one row for each + original with its current item's size and the sum of its revision + items, as export writes them. A write measures only the items it + writes, and the bound and the usage line read the sum. Only `ath check` + measures every original again, and `ath repair` fixes a row that + differs. +- D288 and D287. Wording. When the probe stops Garmin, its deferred + count adds `(not asked: detail unavailable this run)`. After a 401, the + provider's line says to reconnect the provider in Open Wearables if + this repeats. A merge choice is a conflict resolved as imported or + corrected, because choosing the local side writes nothing. Strava's + usual case is 21 requests. The 80% warning says that a later version + may lift the bound, and it names no plan question. + +## Changes after version 2.1.2 + +Version 2.1.2 merged on 21 November 2026. It adopted D227 through D253 +and published migration step 6. Step 6 stores `2.1.2` and SQL schema 6 +in `spec/sql/migrations/006-version-2-1-2.sql`. These proposals moved to +D254 through D271. The migration this plan then added was step 7. It would +have stored `2.2.0` and SQL schema 7. Steps 1 through 6 stayed as published. +The 15 November note above still says that the edit that day changed the +planned migration from step 5 to step 6. That sentence records that day. +The next section is the reading after version 2.1.3. + +## Changes after version 2.1.3 + +Version 2.1.3 merged on 24 November 2026. It adopted D254 through D271 +and published migration step 7. Step 7 stores `2.1.3` and SQL schema 7 +in `spec/sql/migrations/007-version-2-1-3.sql`. It adds three internal +tables and no athlete-owned column. These proposals moved to D272 through +D289. The migration this plan adds is step 8. It stores `2.2.0` and SQL +schema 8. Steps 1 through 7 stay as published. The section above records +the step 7 plan. The migration in the proposals is step 8. The rest of +this plan is still the reading against version 2.1.1 at `0de71bb`, except +the decision numbers, the migration step, and the version lists. + +## D272. Version 2.2.0 is one manual pull, and the program and the record share that number + +`ath pull openwearables` reads the stored representations D277 lists from an +Open Wearables server the person runs, for one user and one range they name. The +command is manual. The person runs it. The program does not schedule it, +retry a failed request, or sign the person in to a device maker. + +The program, the record, and the database become `2.2.0` together. D152 made +those one number. D184 kept that rule. Version 2.1.1 kept it too. Version +2.1.2 kept it too. Version 2.1.3 kept it too. Migration step 5 is already +published. It stores `2.1.1` and SQL schema 5 in +`spec/sql/migrations/005-version-2-1-1.sql`. Migration step 6 is already +published. It stores `2.1.2` and SQL schema 6 in +`spec/sql/migrations/006-version-2-1-2.sql`. Migration step 7 is already +published. It stores `2.1.3` and SQL schema 7 in +`spec/sql/migrations/007-version-2-1-3.sql`. This pull adds step 8. Step 8 +stores `2.2.0` and SQL schema 8. It adds no column to an existing table. It +rebuilds `provider_summaries` and `provider_scores`, and it creates +`source_reports`, as D279 describes. D281 drops the record views and +the two cross-table triggers around the root rename. Existing rows keep +their numbers. Steps 1 through 7 are not edited (D165). Step 6 adds +`athlete_reports.workout_session_id`. Step 7 adds three internal tables and +no athlete-owned column. Step 8 does not rebuild `athlete_reports` or those +internal tables, so that column and those tables stay. + +In 2.1.3, `install_schema` in `src/store/mod.rs` runs the whole chain in one +transaction with foreign keys on. `Store::create` calls it on a new +connection before any `Store` exists, and it opens its own transaction. +`ath migrate` and `apply_pending_without_backup` run their steps inside +`Store::transaction`, which refuses to write when foreign keys are off. +Step 8 needs them off while it rebuilds tables that other tables point to. +So `install_schema` commits steps 1 through 7 first, and step 8 runs in its +own transaction on the same connection. Step 8 is one function in +`src/store/migrate.rs` that takes the connection, so init and migrate both +call it. It turns +foreign keys off before that transaction begins, because SQLite ignores the +setting inside a transaction, and reads the setting back. The step runs +`PRAGMA foreign_key_check` and refuses any row it returns. It sets +`user_version` 8 and commits. Foreign keys are turned on again and read +back, whether the step committed or not. + +Two checks in 2.1.3 expect one transaction to reach the last schema. +`install_schema` refuses unless the metadata reads `SQL_SCHEMA_VERSION` +and `ATHLETIC_STANDARD_VERSION` (`src/store/mod.rs`, lines 628 through +631 at `a3d3eba`). `apply_steps` refuses unless its last step reached +`SQL_SCHEMA_VERSION` (`src/store/migrate.rs`, lines 333 through 337). With +the constant at 8, both would fail once steps 1 through 7 commit at schema +7. So the first transaction checks for schema 7 and `2.1.3`. `apply_steps` +checks for the last step it was given. The step-8 function checks for +schema 8, `2.2.0`, and `user_version` 8 before it commits. + +`ath migrate` keeps its verified +backup. Inside the step-8 transaction it checks again that the file, the +database ID, the schema, and the database revision are the ones its earlier +steps left. `MIGRATION_CHAIN` in that file and `spec/sql/contract.json` gain +the step. +`packages/npm/package.json` exports point at `schema/2.2.0/`. +`READABLE_DATABASE_VERSIONS` and `ACCEPTED_RECORD_VERSIONS` keep `1.0.0`, +`2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, and `2.1.3`, and gain `2.2.0`. +`IMPORTABLE_PACKAGE_VERSIONS` gains `2.2.0` and keeps `2.0.0`, `2.1.0`, +`2.1.1`, `2.1.2`, and `2.1.3`. A `2.1.3` package still imports. A `2.1.3` +database does not open until `ath migrate`. + +The build is one pull request after this plan is approved. It is not split +into a version change, a client, and a mapping change. + +The version numbers below are proposals. They are not specs, and they are +not adopted. + +- 2.2.0 is this pull. D277 says which stored measurements it keeps. +- 2.3.0 is a proposed Junction pull. This release does not call Junction. +- 2.4.0 is proposed automatic incremental sync, saved sign-in refresh, + retries, and backfill. This release has none of those. A smaller page + after the local response cap, described in D277, is not that retry. +- An earlier draft of this plan left day aggregates and the heart-rate + stream out and suggested 2.5.0 for them. D277 supersedes that draft. + D88 still forbids a fabricated instant. It does not forbid keeping a + bound the server sent. +- A connector interface that every future source would implement is not + part of this release. This release adds one module for this server. + +File imports stay: Apple Health, WHOOP, Oura, Garmin, and Strava. `ath pull +garmin` stays as it is. Mapped import for every route other than +`open_wearables` stays as it is. Open Wearables mapped import gains the +shared binding refusal in the specification. It no longer accepts a second +device id, or a refresh of history that has no established binding. + +Evidence: [appendix/open-wearables-api.md](appendix/open-wearables-api.md). + +Rejected alternatives: + +- Leave the record at 2.1.0 while the program becomes 2.2.0. Rejected because + D152 and D184 already rejected a split. +- Ship the pull as three pull requests. Rejected because the maintainer asked + for one versioned build. +- Pull Junction, start sync jobs, or add a connector trait in this release. + Rejected because this release has to make one manual read reliable first. + The later version numbers are proposals, not adopted assignments. +- Leave day aggregates and the heart-rate stream for a later version, or + request them while still calling that later version their home. Superseded + by D277. The current proposal stores them in this pull and says so. + +## D273. The pull fetches pages and the shipped mapping writes the records + +New module `src/runtime/open_wearables.rs` requests the reads +in D277 and gives each page to the mapping engine. In 2.1.1, `MappedReader` +in `src/import/mapping.rs` reads a JSON file from a path. The pull adds a +second reader beside it, `MappedPage`, that holds one decoded page in memory. +It runs the same checks as `MappedReader::read` and the same +`Run::map_input`. `preview_route` in `src/import/provider.rs` stages and +matches the page, and `ProviderPreview::apply` writes it. The command is +added in `src/cli/`, +beside `ath pull garmin` in `src/cli/commands/routes.rs`. Version 2.1.1 +superseded D174's TypeScript front end and the separate `ath-core` library +in D155 and D162. This pull does not bring either back. The library is the +`athleticstandard` crate at the repository root. The HTTP client is +the `ureq` 2.12 dependency the Garmin pull already uses. No new crate. + +The mapping file is resolved with `resolve_mapping` in `src/assets/mod.rs`, +name `open-wearables`. An installed copy in `.agents/mappings/` wins, which +is D179. The pull does not grow a second rule for what a path looks like. +`is_mapping_path` in that file is the one rule. + +The mapping file chooses every stored field. The pull does not rename a +field, choose a unit, or decide that a value is RMSSD or SDNN. A field the +file does not name stays in `supplied_fields` under the name it arrived with +(D153, D161). `field_basis` stays whatever the file already states (D185, +D187, D192). + +Sleep and workout responses are envelopes with `data` and `metadata`. The +shipped file's page section is `timeseries`, so the mapping engine would +leave that envelope out. The pull passes sleep rows as `{ "sleep": [ ... ] }` and +workout rows as `{ "workout": [ ... ] }`. It passes each timeseries response +through unchanged, so `metadata.resolution` still reaches the mapping. The +pull does not drop one row and keep its neighbors. The API key, the +server's origin or the selected user id echoed in a response, a same-key +`device_id` collision, or a bad envelope rejects the whole page first. A +value under a credential-shaped key is withheld and counted instead, as +D289 says. A manual workout is written. D283 stores +it as a workout session. The other rows in that page are still written. + +The timeseries query's `types` list is the `type.` lines in the +resolved mapping file, read when the command runs. The prefix is that +section's `type_field`. Each name is one repeated `types` query parameter. +A name that appears twice is sent once. `skin_temperature` is that case. A +comma-joined string is not a member of the `SeriesType` enum. This study did +not send that request, so it does not claim a live 422. The Rust source has +no second copy of those names. + +On Open Wearables 0.11.0 the route defaults `types` to an empty list, and +the repository applies a type filter only when the list is nonempty +(`data_point_series_repository.py`). An empty list therefore returns every +series. D277 omits `types` on the raw read and the day read for that +reason. A mapping that cannot store those series fails before any network +call. A comma-joined type string is still not sent. + +`heart_rate` is a series quantity. D277 stores the raw stream as +measurement samples. Workout `avg_heart_rate_bpm` and +`max_heart_rate_bpm` stay as the file already maps them. + +The pull counts each page by record type and action with one SQL count +over its staged plan, beside `Staging::count` in `src/import/staging.rs` +(D276). `ProviderPreview::planned` already lists each row's `record_type` +and `action`, but it also copies each row's whole `data_json`, and a +vendor page holds every original's whole envelope. The count reads no +record data. The mapped-import report from +`report_value` in `src/import/provider.rs` keeps its `outcome` field. The +pull adds the counts into the committed result for a page it applied, and +into `estimated` for a page it only previewed. It does not add `outcome` +across pages. A preview writes nothing, so estimated counts are against the +database as it was before this command. They are not equal to the write +when the same match key appears on two pages, or when the server changes +between runs. The write still follows D182. This proposal does not keep a +command-wide preview overlay. + +The read order is the order in D277. A failure in a later read +leaves the earlier read's pages committed and the reads after the failure +`not_attempted`. The result says so. See D275. + +D277 is the coverage rule. An earlier draft of this decision left the day +rows, the summaries, and the heart-rate stream unrequested. That draft is +superseded. D88 still forbids inventing a midnight. The period type in +D277 stores the bound the server sent. An Open Wearables window is not +labeled as a Whoop cycle or an Oura day. + +Sleep requests `include=stages`. Workouts request `include=zones` and +`include=segments`. Stage minute totals return either way. The timeline, +the zones, and the segments are null when the expansion is omitted, so +omitting it would drop them before `supplied_fields` can keep them. A page +over the response cap is handled as D277 says. + +Rejected alternatives: + +- Teach the pull the Open Wearables field names in Rust. Rejected because + D161 put those names in the mapping file so a second source does not become + a second record format. +- Pass the sleep envelope straight to the mapping engine. Rejected because + the current page rule would leave the page out. The check is `page_rows` and + `row_fits` in `src/import/mapping.rs`. +- Request every series type and let `left_out` drop the ones the mapping + cannot store. Rejected. D277 stores them. `left_out` remains a row the + server returned and this program refused for a named reason. +- Map `heart_rate` samples as points, or map a day summary onto midnight. + Rejected. `heart_rate` is stored as a measurement sample. A day row is + stored as a reporting window (D88, D110, D277). +- Refuse an empty `types` list in order to avoid heart rate and location. + Superseded by D277. Omitting `types` is how 0.11.0 returns every series, + and those series are stored. A comma-joined string is still not a member + of the enum. +- Put `device_id` on the sensor string, and therefore on the match key, for + both import and pull. Not this proposal. It needs no new column, and the + mapping engine already joins configured sensor paths, but it changes + source, baseline, and key identity. Old triple-key rows would stay where + they are, and dedupe against them cannot be promised. A `device_id` that + contains `|` collides with the join unless those values are refused or + the join is encoded. The shared binding in the specification keeps the + current keys and refuses the unsafe write instead. +- Guard the pull only, or treat `source_devices.hardware` as the binding. + Rejected. Import after pull would still replace the point, and hardware + is one mutable column. The point's revisions do not contain `device_id` + today, because that path is removed as hardware. +- Put the receipt in `supplied_fields`, under `device_binding` or another + name. Rejected. D185 keeps that object for names the source sent. A 2.1.0 + source may already hold an arbitrary value at that name, and step 8 must + not turn that value into authority. The receipt is the source object's own + key `device_binding`. +- Treat a nonempty string at the new key as proof no matter who wrote it, + or require a signature so the owner cannot change it. Rejected. The + automatic path writes the key only by the checked rule. `ath correct`, + package restore, and an accepted package merge store the whole source the + owner supplied. A hand-edited database file is outside this proposal. + +## D274. The key, the server, and the user id stay out of the record + +The API key is an administrator key for every user on that deployment. The +pull sends it only as the header `X-Open-Wearables-API-Key`. It is saved with +`ath key set openwearables` in the operating system password store, the same +store D75 uses. The environment name for a script is `OPEN_WEARABLES_API_KEY`. +The command reads that variable and the password store in this process, +in `src/runtime/keyring.rs`. There is no child process and no +`ATH_CORE_OPEN_WEARABLES_KEY`. `ath pull garmin` already reads +`GARMIN_PERSONAL_API_KEY` the same way. The key is +not a command argument. If the password store is missing, the command refuses +and does not write a file. + +Open Wearables is not a gateway. `Gateway::ALL` in `src/runtime/keyring.rs` +stays `vercel` and `openrouter`. `KeyAccount` in that file gains +`OpenWearables`, saved under the account `openwearables`, the way 2.1.1 +added `Garmin`. `account_secret` reads `OPEN_WEARABLES_API_KEY` before the +saved key, as it reads `GARMIN_PERSONAL_API_KEY` for Garmin. `key_clear` in +`src/cli/commands/model.rs` accepts `openwearables` before it parses a +gateway name. `ath key clear` with no name still clears only the gateway +keys, and it still exits successfully when that is what it did. +When a saved Open Wearables key remains, the text adds two sentences: the +Open Wearables key remains saved, and `ath key clear openwearables` removes +it. When no saved Open Wearables key remains, the gateway sentences stay as +they are today. `ath key clear vercel` and `ath key clear openrouter` do not +remove the Open Wearables key and do not gain that sentence. + +`ath key clear openwearables` deletes the password-store key only. It does +not unset `OPEN_WEARABLES_API_KEY`. The text says the saved key was removed. +When the environment variable is set, the text also says that key is still +available and a pull can still use it. When the variable is unset, the text +does not claim an environment key remains. + +`ath key` keeps its gateway lines. It adds separate lines for a saved Open +Wearables key and for `OPEN_WEARABLES_API_KEY`, and it prints neither value. +`ath key --json` keeps `saved` and `environment` as the gateway lists they +are today, and adds `openwearables.saved` and `openwearables.environment`. +Garmin's key command is unchanged. In 2.1.1, `ath key clear garmin` is +refused because `garmin` is not a gateway name. This pull keeps that, and +the specification's section 9 lists it as a separate follow-up. + +The server is `--base-url` or `OPEN_WEARABLES_BASE_URL`. The user id is +`--user` or `OPEN_WEARABLES_USER_ID`. Neither is written into the database, +the export, a config file, or a log line. The pull never calls `GET /users`. +D278 reads the personal record and drops its `user_id` before the scan. +Birth date, gender, and sex are stored. One command reads one user. + +`--base-url` is an origin: scheme, host, and optional port. No user name, no +password, no path other than empty or `/`, no query, and no fragment. `http` +is allowed only for `localhost`, `127.0.0.1`, and `::1`. Any other host +requires `https`. The pull appends `/api/v1` itself. Redirects are not +followed. A timeout, a non-JSON body, or an HTTP error becomes the page +failure in D275. The printed error is a fixed sentence and the HTTP status. A problem `code` +is printed only when it is one short token and does not contain the key, +the origin, or the user id. Otherwise it is withheld. A transport error or +a parser error is replaced with a fixed sentence that has no URL, no path, +and no user id. + +After the body is read inside the size cap and parsed, and before the page +reaches `MappedPage`, `open_wearables.rs` walks every object key and every +string. A value that contains the API key, the selected origin, or the +selected user id rejects the whole page. The row is not rewritten. A value +under a credential-shaped key is a different case. D289 withholds that one +value and counts it. A scan of the raw text +misses a Unicode escape. The raw-text scan and the check before printing +stay as defense in depth. They are not what keeps the key out of a committed +page. Named clear of the saved key does not revoke it on the server. + +The shell history can contain the server and the user id when they are +passed as flags. The key is not a flag. `ath key set openwearables`, or +`OPEN_WEARABLES_API_KEY` already held by the shell, keeps the key off the +command line. Putting the key on the same line as the command would store +it in shell history. Do not do that. + +Rejected alternatives: + +- Store the server and the user id on the source row so the next pull can + omit them. Rejected because the export would carry them, and agents read + the export. +- Remember them in a file beside the database. Rejected because that file is + easy to commit and easy to copy into a backup by mistake. +- Accept a bearer token or a user-scoped SDK token for these reads. Rejected + because the 0.11.0 server does not accept the API key as a bearer token, + and the SDK token is limited to SDK routes. See the appendix. +- List users and pull every user the key can see. Rejected because the key + sees the whole deployment, and this record is one athlete. + +## D275. A page is atomic, a missing row is not a deletion, and the same command is safe to repeat + +Each response page is one 2.1.1 import preview and, under `--yes`, one +apply. `preview_route` in `src/import/provider.rs` stages and matches the +page in one read transaction, at one database revision, and never writes. +`ProviderPreview::apply` writes that plan in one transaction, as D189 +requires. It refuses the plan when the database revision moved after the +preview. A failure writes nothing for that page. The pull itself is a +series of those pages. The order and the terminal condition of each read +are the table in the specification's section 2. A committed page follows +D189. A committed page does not mean the pull is complete. + +The command previews unless `--yes` is present. `--json` does not write, +with or without `--yes`, matching `ath import --mapping`. `--yes` without +`--json` writes each protected page as that page succeeds. A refused +page is not a success. The pull-only archive in D282 is a separate +preview and apply. It goes ahead only when the database revision has not +moved since the protected preview. + +The command returns one bounded outcome for the mode it ran. A preview, +including public `--json`, has `written` false, protected and archive +committed zeros, estimated counts, and `range_complete` false. A +confirmed `--yes` has the actual protected and archive counts. `written` is +true when a protected transaction in the command created or revised a +counted record. An archive does not make it true. `database_changed` is +true when a protected transaction or an archive transaction committed a +change. A vendor page (D287) is a protected transaction, so a committed +vendor original makes both flags true even when every stored page was +unchanged. A successful repeat of an unchanged command has both flags false. +The command prints the +confirmed outcome as text. It prints the preview outcome as public JSON. +On a partial failure it keeps the confirmed outcome and then exits +nonzero. It prints the text before it uses that status. There is no +separate child process. Version 2.1.1 removed that split. + +Each read in that table is `completed`, `failed`, or `not_attempted`. The +token is `not_attempted` in the outcome and in the text. There is no +`skipped` read. `range_complete` is true only on a `--yes` write whose +ranged reads reached their terminal conditions. The success sentence also +requires the personal record and the body snapshot to have completed. A retained +count with an incomplete range is a partial pull. The message names the +failed read, names any `not_attempted` read, and gives the retained counts. +A failed read says to run the same command again. An identity refusal uses +the sentence in the specification's section 3: a replacement id is blocked +even at a new time, a 2.1.0 Open Wearables history cannot be refreshed until +reconciliation, and +a rerun cannot repair either one. Each page refusal also names the +owner's fix where 2.2 has one. `ath correct` on the source can set a new +`device_binding`, bind history that one device wrote, or replace a +malformed receipt. A new `device_binding` puts the old device's history +and the new device's rows on one source, and a point carries no device +id, so they can no longer be told apart. That rebind is the owner's +explicit merge, and the refusal text says so. The source's history keeps +the old binding. A changed workout kind has no fix that keeps the +record. `ath erase` removes it, and the next pull stores the new kind. A +bound source that receives rows with no id, and history from more than +one device, have no fix in 2.2. A preview that fails makes no database +changes, including for pages that had already been counted. + +Before `MappedPage`, a cursor page and an offset page must be a JSON +object, `data` must be an array, `pagination` must be an object, and +`has_more` must be a boolean. Anything else fails that page. It is not an +empty success. Body may be one object or JSON `null`. `null` is a completed +empty snapshot. The personal record is one object. The result keeps a +`left_out` total, a count for each reason, and at most 20 examples. + +An empty ranged result whose ranged reads completed has `range_complete` +true. The personal record and the body snapshot can still be written. +Those writes are counted. They are not ranged rows. A repeat uses the match +key from D181 and the replace from D182, so an unchanged row is not written +again. An owner correction on this route is kept until the server's data +for that record changes (D287). A rerun after a partial write leaves the committed rows in place, +runs the failed read again, and runs any read that was `not_attempted`. + +`has_more: false` is the successful end of a cursor read and of the offset +read. A repeated cursor, a null cursor while `has_more` is true, and the +1000-page cap fail that read. An offset retry uses the same offset. A body +over the response cap, `MAX_PULL_RESPONSE_BYTES` in `src/input_policy.rs`, +is handled by D278. The failed page is not written. Later reads are +`not_attempted`. The success line is not printed. A cursor with the +`prev_` prefix is not sent. `limit` starts at 1000. One attempt is made per +request, except the smaller page D278 sends after the response cap. A +transport error is not retried. The stored reads use a 30-second connect +timeout and a 120-second read timeout, the values +`src/runtime/garmin_pull.rs` uses. Live vendor requests use 30 and 360 +seconds, for the reason in D288. Each timeout is a named constant. In +2.1.1 the comment on `MAX_PULL_RESPONSE_BYTES` calls it one Garmin +personal connection response, and the route list above it names only the +Garmin pull. The build rewrites both to name the Open Wearables pull too. +The value stays 10 MiB. + +A row that this range did not return is left where it is. The pull does not +call `DELETE`. There is no deletion feed on these reads. Absence can be +a short range, a failed page, or a server filter. D190 still applies: a +source the person has deleted stays deleted, and its rows are left out. A +record the person has deleted stays deleted, and that object is left out +(D182). + +`--from` and `--to` are sent unchanged. Both are dates `YYYY-MM-DD`, or both +are timestamps with an offset. A mix is refused. The command prints one line +that a date-only bound is interpreted by Open Wearables, and that Athletic +Standard did not convert it to the athlete's timezone (D88). The appendix +records the disagreement between the docs and the 0.11.0 parser. + +The queries are the table in the specification's section 2. An earlier +draft of this proposal listed three reads and treated every page as a +cursor envelope. D278 supersedes that draft. `source_selection` is not +sent. On 0.11.0 the parameter does not exist. On current `main`, omitting +it returns every device when the priority flag is false. Summary routes +still select a source. That selection is not a client filter. + +Rejected alternatives: + +- One transaction for the whole range. Rejected because a raw range can be + large, and a failure at the end would discard pages that had already + succeeded. Each page stays atomic under D189. The pull's result still says + the requested range is incomplete when a later read failed or was not + attempted. +- Treat a committed page as a finished pull. Rejected because the person and + an agent would read a partial database as the whole requested range. +- Store a resume cursor in the database. Rejected because the same command + finds the same rows by their match keys, so a stored cursor would be a + second copy of progress. +- Delete local rows missing from the response. Rejected because the read has + no tombstone, and a partial range would hide history the server still has. +- Retry, refresh a token, or start a historical sync. Rejected because those + are 2.4.0. A 401 or a 429 fails the page and writes nothing for it. +- Convert a date-only bound into the athlete profile timezone. Rejected + because D88 forbids rewriting a source bound into a timezone the source + did not use. + +## D276. The Windows cleanup and the maintainability notes are not part of this build + +Checked again on version 2.1.1 at `0de71bbd6474916af0408a4090bc2c74a1a3aed2`, +the merge of pull request 44. The earlier check was version 2.1.0 at +`8db90b42ac654767e9e9570a121bbbd4fde3348a`, the merge of pull request 39. + +Failed `ath init` still deletes the new file, the wal file, and the shm +file. `Store::create` in `src/store/mod.rs` calls `remove_partial_database`, +which unlinks those three paths. The `init` command in +`src/cli/commands/init.rs` unlinks the same three paths if creation fails +after that. Neither path collects abandoned temporary directories first. +`make_owned_temporary_directory` in `src/files/staging.rs` does, and import +working data uses it. The database file is not one of those directories. +Version 2.1.0 spec section 12 left the production database cleanup out and +named no later version. Version 2.1.1 did not take that work. The cleanup +does not run on a pull. This build does not change it. D282 rolls a failed +step 8 back before this cleanup runs. + +`src/import/mapping.rs` is 1703 lines and `src/import/provider.rs` is +1297. The store is already several files. `src/store/mod.rs` is 848 +lines, `src/store/write.rs` is 508, `src/store/encode.rs` is 549, and +`src/store/check.rs` is 1044. `persist.rs` is gone. The pull is a new +module so `mapping.rs` and the store files do not grow for HTTP. +`mapping.rs` may add `MappedPage`, which D273 names, and the +`vendor_workout` section, which D287 names. D277 also adds the +measurement-sample target, the reporting-window write, and the segment +copy. Nothing beyond that is added to `mapping.rs`. + +Version 2.1.1 stages, matches, and applies a keyed import in +`src/import/provider.rs`. A keyed import there only creates sources. It +never revises one. So the source rules go there, not in +`src/store/write.rs`. The matching step runs the open-wearables +device-binding check and reads the page's safety snapshot. Both live in a +new file, `src/import/binding.rs`, so `provider.rs` grows little. That +check is shared by mapped import and pull, and it is limited to route +`open_wearables`. The staged plan may create a source with the checked +receipt. It may write that receipt on an existing unbound source only when +the snapshot shows no accepted or deleted record and no source device. +That first bind is a source correction with the source's expected +revision. `ProviderPreview::apply` refuses any other staged change to +`device_binding`. Those writes keep every other source field and the +normal revision and `data_json` bookkeeping. `provider.rs` also gains the +crate-private read of a stored vendor original that D288 uses. It gains +`connector_source` beside `route_source`, because `route_source` stages +only an `export_file` source that names a vendor. The writer +`open_wearables` sources, the archive source, and each `vendor_workout` +source are `connector` sources with no vendor. `Staging::count` in +`src/import/staging.rs` counts by action only, so a count by record type +goes beside it for the page counts. D273 uses it instead of counting +`ProviderPreview::planned`, which copies each row's `data_json`. The +revision a preview read is +already public as `ProviderPreview::destination_database_revision`. + +`Store::apply` in `src/store/write.rs` writes a whole record. There is no +`Store::revise`, and a correction carries the whole record. The owner and +library writes store a whole source record: `ath correct`, the protocol +operations `records.write`, `records.write_changes`, and `records.correct`, +native package restore, and an accepted package merge. They keep the +receipt the caller supplied. `Store` keeps its connection private (D223). +D278 also allows `measurement_sample` insert and update, and a null value +and unit pair on provider summaries and provider scores. A half-null pair +is refused. `write_current_state` in `src/store/encode.rs` is the only +record-to-table mapping. Package restore, repair, and the record check use +it. There is no TypeScript writer to update. D279 also allows +`source_report` insert and update, and withdrawal of a child whose anchor +is in this response. D287 adds the vendor-original size check to +`apply_in` in `src/store/write.rs`, for a change that writes an original. +Nothing beyond that is added to the store. Other +routes do not call the receipt operations. Splitting `mapping.rs` is +separate work. It is not required to make the pull correct. + +`ath key clear garmin` is refused in 2.1.1, because `key_clear` in +`src/cli/commands/model.rs` accepts only gateway names. D274 keeps that. +Making the Garmin key removable is separate work. + +`check_supplied_fields` is in `src/import/shared.rs`. A keyed import calls +it before it builds a candidate (D191). It refuses an empty name and a +`__proto__` key at any depth. Version 2.1.1's D214 changed only the +native reader, which keeps such a key and checks it, so the import +refusal still applies. There is no `persist.rs` and no +`ath-core persist` command. The pull writes through `MappedPage` and the +2.1.1 import, so the import check covers it. The vendor read in D288 runs +the same check on each vendor object first. A list object with the key is +refused alone. A detail with the key is refused, and its clean list +object is stored. A name check outside import is separate work. + +`is_mapping_path` exists once, in `src/assets/mod.rs`. The pull uses +`resolve_mapping` in that file. There is no second path rule to remove. + +Rejected alternatives: + +- Fix the Windows cleanup, split `mapping.rs`, and add a name check outside + import inside the 2.2.0 pull request. Rejected because none of them changes + what the pull writes, and the maintainer asked not to widen this build. +- Block the pull on those fixes. Rejected for the same reason. A later + change can take any one of them on its own. +- Put the source rules in `Store::apply`. Rejected. In 2.1.1 every + `Store::apply` caller that can write a source is an owner or library + write, and the one automatic source writer is `ProviderPreview::apply`. + A rule in `Store::apply` would also block the owner's own correction. + +## D277. Stored Open Wearables measurements are kept in this pull + +D278 supersedes the classification, source identity, time, score, endpoint, +and size sentences in this proposal. D279 supersedes D278 where they +disagree. The decision to keep the returned health data in this pull +stands. Where a paragraph below disagrees with D282, D282 is the proposal. + +This supersedes the earlier draft, inside D272 and D273, that left day +values, the heart-rate stream, sleep and recovery summaries, meals, and +workout segments out of this pull. Those drafts are not deleted above. +They are not the current proposal. The specification's section 2 is the +list of reads, the storage rule, and the omissions that remain. + +A raw series that 2.1.0 already stores as a point stays a point, on the +same match key. A raw `heart_rate` series is a measurement sample because +that quantity already exists and it is not a point. Every other pinned +series type that has no quantity yet gains one. The unit and the number +come from the server. A row with `period_end` is a provider summary with +period type `open_wearables_reporting_window`. `recorded_at` is unset. +`start_at` and `end_at` are the server's `timestamp` and `period_end`. + +`ProviderReportingPeriodType` gains that one value. `ValueBasis` gains +`aggregator`, used when `computed_by` is `open_wearables`. Series +quantities gain the missing pinned types. `quantity` is already an +unconstrained text column, so those names add no SQL column. Step 7 +rebuilds `provider_summaries` so `standard_value` and `standard_unit` can +be null together. Existing summary rows are copied with their numbers. +The device receipt still adds no column. The receipt, the transaction, +the preview counts, and the public non-writing `--json` rule are +unchanged. + +The mapping file `mappings/open-wearables.md` is rewritten in the build +so a raw point, a raw sample, a day window, and a segment follow section +2. A resolved file that does not do that fails before any request. D179 +still lets an installed file win. This check stops the 2.1.0 file from +dropping rows the pull can store. + +Rejected alternatives: + +- Keep the earlier draft and store these values in a later version. + Rejected. The server already returns them, and a later version was + being used as a reason to leave them out. +- Store a day row as a point at the period start. Rejected. That would + make a reporting window look like one instant (D88, D110). +- Drop latitude, longitude, segments, or a large series to keep a + response under the response cap. Rejected. The smaller page in the specification + stores the rows. D278 states the minimum-page limit without naming a + series type. +- Call the live provider workout proxy or the totals routes so the pull + can say it hit every path. Rejected. Those routes are not the stored + measurements. D278 does read the personal record. An earlier sentence + in this list left it out. That sentence is superseded. +- Invent a midnight, a zero, or an SDNN value from an RMSSD value. + Rejected. A null stays absent. `RecoverySummary` at the pinned commit + has no skin-temperature field. A health-score component can still carry + one. D278 says so. + +## D278. Returned values keep their meaning, source, and time + +D279 supersedes the sentences below that call dietary or index series +provider summaries, that store a day row as the same class as its raw +sample, that build a sensor by joining parts with `:` and `-`, that put +main-sleep bounds on a summed field, that leave a missing device id as +`left_out`, that omit a manual workout, and that treat `received_at` as +the time a revision was written. The values stay in this pull. The +device-receipt rules stay. Where this proposal disagrees with D279, D279 +is the proposal. + +This corrects D277. The corrections that D279 does not replace are the +contracts in the specification's section 2. + +A device source is still the 2.1.0 sensor, and its receipt rules are +unchanged. A summary the server builds without `device_id`, a meal or +cycle without one, a null timeseries source, and a health score use the +separate sensors in that section. They do not borrow a device id, and +their history does not block a later device binding. A raw or day sample +that has a source and no device id is still refused. + +A number is classified before it is normalized. Existing raw points, raw +`vo2_max`, and the two raw Garmin scores keep their kinds and keys. Dietary +series and the named indexes, ages, and effort scores are provider +summaries. The other raw series readings are measurement samples. Day rows +use the same classes on the server's calendar window. That window is not +the provider's original interval. + +Health-score `provider` is the author. `source` is the input and may be +null. `provider: internal` is basis `aggregator`. A finite range in +`constants/health_scores.py` is the scale. An unknown or unbounded range +is not given `0-100`. The original object, including components and +`event_record_id`, is kept. + +Sleep main-sleep bounds apply only to the fields section 2 names. Body is +the server's current snapshot, not the requested range. Fields with no +time use `not_provided_by_source` and no invented instant. Age is +calculated. BMI is not labeled measured. The personal record's birth date, +gender, and sex are stored. Its `user_id` is not. The athlete profile is +not used for them, because that record cannot hold a full birth date, the +gender values, or a source. + +Cursor pages, offset pages, and the two one-shot reads have the terminal +conditions in the table. A smaller page repeats the same uncommitted +cursor or offset. A minimum page or an unpaginated response that is still +over the response cap, 10 MiB, is an incomplete read. The message names the read. It does not +name a series type. Menstrual cycles keep an in-range start and a future +end. A later start is not stored. The page is still followed to the end. + +Step 7 rebuilds `provider_summaries` and `provider_scores` so value and +unit are both null or both present. It copies existing rows and keeps +their ids, revisions, import keys, and tombstones. `src/store/write.rs` +may insert and update samples and those paired-null rows. +`write_current_state` in `src/store/encode.rs` writes the same pair. +Package restore, repair, and the record check use that encoder. Half-null +is refused. No other store change is included. + +Rejected alternatives: + +- Put a summary with no device id on the bound device source. Rejected. + The summary would be refused, or the missing id would be invented. +- Leave birth date, gender, and sex out because they are sensitive. + Rejected. They are health data. The user id is the part that stays out. +- Use the athlete profile for those three fields. Rejected. The profile + has no source, no full birth date, and no room for every gender value. +- Call every numeric series a measurement sample. Rejected. Intake, + indexes, ages, effort scores, and the existing summary and score lines + would change meaning or identity. +- Treat body as a read of `--from` and `--to`, or date the undated fields + with the average window or the pull time. Rejected. The route has no + date parameters, and those times would be invented. +- Give every health score the scale `0-100` or the basis `provider`. + Rejected. The pinned range table and `provider: internal` say otherwise. +- Stop a day read at `limit` 1 and report one oversized series. Rejected. + That limit counts periods, and one period can hold many rows. + +## D279. Units, windows, reported records, and identities stay distinct + +D280 supersedes the sentences below that put every source-present series +through the device check, that compare null-source rows by type and +timestamp alone, that leave a refused original unstored in every case, +that map `heart_rate_recovery_one_minute` to a quantity of that same +name, and that call `hydration` a measurement sample. The units, day +windows, sleep bounds, and reported-record direction stay. D281 +supersedes D280 where they disagree. D282 supersedes D281 where they +disagree. Where this proposal disagrees with D282, D282 is the proposal, +except the sentences that store a manual workout as a source report. +D283 supersedes those sentences. + +This corrects D278. The returned health data stays in this pull. The +specification's section 2 and the appendix series table are the contract. + +Every series has an input number, an input unit, a standard number, and a +standard unit. The input pair is the server's pair. The standard number +equals the input number except for `walking_step_length` and +`running_stride_length`. Those quantities are metres in Athletic Standard +and centimetres on the server, so the standard number is the input number +divided by 100. A 70 cm step is 0.70 m. The aliases change the unit text +and not the number: `percent` to `%`, `celsius` to `°C`, `degrees` to +`deg`, `meters` to `m`, `m_per_s` to `m/s`, `watts` to `W`, `met` to +`MET`, `minutes` to `min`, and `ml_kg_min` to `ml/kg/min`. A new quantity +uses that alias, or the server unit token when it has no alias. Existing +quantity units are not edited. + +A raw row keeps the class in the appendix table. A day row is never a +measurement sample. Its `timestamp` is the start of a calendar period, and +`window_seconds` is null. The stored period is +`open_wearables_reporting_window`, from that timestamp to `period_end`, +with `recorded_at` unset. The window is not called the measurement +instant. Raw points, raw `vo2_max`, and the two raw Garmin scores keep +their kinds and keys. Day heart rate, day steps, and day speed are window +summaries. Day Garmin scores stay scores on the window. + +Sleep summary numbers cover every non-nap session in the selected source +and date. The longest session supplies `start_time` and `end_time` on the +original object only. Those bounds are not a period on the summed fields. +A 360 minute total from two main sleeps stays on `provider_date`. This +program does not re-sum the sessions and does not invent the missing +interval. + +`source_report` is a new record type. It has a source, so it is not an +athlete report and not a nutrition entry. It is not one of the seven +measured types. D161 still forbids turning a personal report into a +measured record. Dietary series, alcoholic-beverage counts, meal and +nutrient numbers, index, age, and effort series, personal-record fields, +predicted and coded cycle content, BMI, calculated age, and an unbounded +health score use this type. The eight range calculations and +`provider-period-summary` do not read it. A manual workout is a workout +session. D283 is that rule. An automatic workout stays a measured +session on the device source. + +A new sensor is `ow1:` plus a JSON array with no spaces. JSON `null`, an +empty string, and `-` stay different. Legacy device sensors are not +rewritten. A health score's sensor is `["score", provider]`, using the +top-level author. The input source is not in that array, so a change from +null to a known input revises the same score. A null-source timeseries +uses `["unattributed", "timeseries"]` and the writer `open_wearables`. +Two unequal payloads at the same type and time refuse the call. The +personal record uses `["personal_record"]` and that same writer. A meal +or cycle uses the event array even when `device_id` is present. That id +stays in the array and in the original object. It does not establish +`device_binding`. A manual workout does not use that array. D283 puts it +on the manual source. + +A raw or day row whose `source` object has no `device_id` is an incoming +device row. The whole call is refused, including a valid row on the same +page. It is not marked `left_out` before the check. Null-source rows do +not enter that check. + +The same returned object can change a child from a number to null or +remove a nutrient. That child is revised to an absent value and unit. +The id and the first `received_at` stay. D182 copies that `received_at` +onto the revision. `became_known_at` is when the revision was written. A +later number returns on the same child. A range that does not return the +object does not withdraw its children. A refused page rolls the +withdrawal back. + +A finished range with a failed body or personal-record read says the +range is complete, names the failed snapshot, and exits nonzero. It does +not print the success sentence. A preview says a snapshot would be +stored. It does not say it was stored. An empty ranged result does not +mean the command wrote nothing. + +`computed_by` omitted on a raw row keeps basis `provider_or_aggregator`. +`computed_by: null` omits the basis. The raw Garmin scores keep basis +`provider`. `provider: internal` keeps basis `aggregator`. The scale text +comes only from `HEALTH_SCORE_RANGES`, including the `1-100` rows. + +Rejected alternatives: + +- Store a day heart-rate, step, or speed row as a measurement sample at + the calendar start. Rejected. That start is not a measurement instant, + and a sample requires `recorded_at`. +- Add an interval-sample table so a day row can carry a duration. + Rejected for this release. The reporting window already holds the + bounds the server returned, and a day row does not carry + `window_seconds`. +- Put the longest sleep's bounds on the summed duration. Rejected. The + sum covers every non-nap session, and the bounds cover one session. +- Keep colon-joined sensors with `-` for a missing part. Rejected. A + colon in a part and a literal hyphen collide with that encoding. +- Treat a second null-source payload as a correction. Rejected. There is + no sample id, so the program cannot tell a correction from a second + observation. +- Call dietary intake a provider summary or a workout session. Rejected. + SPEC section 5.4 and D161 keep those measured types for measured + records. A source report preserves the object without making it a + measurement. +- Call a manual workout a provider summary. Rejected. D283 stores it as + a workout session. It is not a provider summary. +- Leave a removed nutrient current because the store compares emitted + keys. Rejected. The same object no longer contains that number. + +## D280. The new record type, numberless inputs, and refused originals stay separable + +D281 supersedes the sentences below that leave the record views in place +during the rename, that set `written` false for an archive without +defining `database_changed`, that archive a page from the first error, +that hash the series row without its resolution, and that give a +null-source reported series both the report sensor and the unattributed +sensor. The root check, the numberless readers, and the reported-record +direction stay. D282 supersedes D281 where they disagree. Where this +proposal disagrees with D282, D282 is the proposal. + +This corrects D279. The returned health data stays in this pull. The +specification is the contract. + +`records.record_type` is a closed check. `source_report` is not in it. +Creating `source_reports` does not make a root row insertable. Step 7 +adds `source_report` to that check in the generated contract. It does +not edit migrations 001 through 006, and it does not drop the check. +Ordinary writes keep foreign keys on. The migration connection may turn +them off only before its own transaction, rebuild `records` and the two +nullable typed tables by copy, rename, and recreate, then require +`foreign_key_check` and `integrity_check` before commit. D281 drops the +two record views and the two cross-table triggers before that rename and +recreates them unchanged. A drop of +`records` inside the ordinary foreign-key transaction is not the +procedure. Fresh init and a populated, deleted, history-bearing upgrade +both have to accept a source report afterward. + +A numberless provider summary or provider score is excluded by the +instant reader and the period reader before the limit, the count, and +the numeric decode. It is not zero, and it is not the previous revision. +Source reports stay out of those readers. The formulas stay. + +`RecoverySummary.recovery_score` takes its scale from +`HEALTH_SCORE_RANGES` and the provider the builder copied. Polar recovery +is 1 to 6. A provider the table does not name is a source report. The +WHOOP-only prose is not the scale. + +Raw `heart_rate_recovery_one_minute` is quantity `hr_recovery`. The +server name and the old key stay. `hydration` is a source report. A +device id does not make that intake a sample. + +Sleep, workout, meal, cycle, and score ids must be UUIDs. A raw HTTP +personal record must have a `user_id` UUID equal to the selected user +before that field is removed. The canonical envelope does not contain +it. A missing id refuses the protected page. It is not `left_out`, and +it is not archived. + +`entry_source` `unknown`, null, and omission are `unknown_workout` +reports. They are not sessions and not manual reports. The same server +id with a different kind refuses the page. + +A refused protected page is not applied, so it writes nothing. For a +missing device id on a device-targeted series row, and for unequal +null-source payloads of one full match key, a later archive preview and +apply stores kind `original` with no amount and no device receipt. D282 +is when that archive may write. D281 is the capsule and the command counts. `written` stays false when only the archive +changed. The command +exits nonzero. Credential failures, invalid ids, conflicting device ids, +legacy history, and kind changes are not archived. Those originals are +not kept, because storing them would invent an id or keep a payload the +guard rejected. Preview does not see a cross-page null-source conflict. +A raw midnight row and a day window that starts then are different keys. + +Rejected alternatives: + +- Rebuild `records` with `DROP TABLE` inside the foreign-key write + transaction. Rejected. The child links cascade or the drop fails, and + the history would not survive. +- Leave foreign keys off after migrate. Rejected. Ordinary writes keep + the check. +- Decode a null summary as zero or as its previous number. Rejected. The + current row says the number is absent. +- Use 0 to 100 for every recovery summary because the class prose says + so. Rejected. Polar writes 1 to 6, and the query copies that value. +- Add a point quantity named `heart_rate_recovery_one_minute`. Rejected. + `hr_recovery` is the existing quantity and the existing key. +- Treat unknown provenance as automatic when a device id is present. + Rejected. The id is not a measurement label. +- Archive every refused page, or write the archive inside the refused + page's apply. Rejected. The first keeps rejected secrets and rejected + devices. The second stores the refused write. +- Drop the originals of a missing device id so the refusal stays one + transaction. Rejected for the two reasons above. The archive is a + second transaction with a failed protected-write status. The other + refusal reasons stay unstored. + +## D281. The migration rename, the command counts, and the archive decision stay consistent + +D282 supersedes the sentences below that classify database facts before +either transaction, that leave the archive with only an archive-source +check, and that leave a failed init file in place. The migration graph, +the command counts, the capsule, and the report routing stay. Where this +proposal disagrees with D282, D282 is the proposal. + +This corrects D280. The returned health data stays in this pull. The +specification is the contract. + +Step 7 drops `sql_v1_current_records`, `sql_v1_active_records`, and the +two `record_revisions` triggers that read `records` before it drops +`records`. It recreates them from the `001` text after the new root +exists, in the same transaction. Foreign keys are turned off only before +that transaction, on the store's own connection, in +`src/store/migrate.rs`. No ordinary write can run while they are off, +because `write_transaction` refuses one. After every exit the connection +reads `foreign_keys` back as on, or the command fails and closes the +store. A failure before commit restores the old schema, the old rows, +and the old version. `writable_schema` is not used. Files 001 through +006 stay unchanged. + +`written` counts protected creates and revisions across the command, +including vendor originals. Those are `source_report` records, so they +also add to `committed.source_report`. An +archive-only change leaves it false and sets `database_changed` true. +Archive counts are separate from protected counts. A later page does not +clear either. A failed archive apply keeps the refusal, writes nothing, +and leaves earlier commits. The pull text for a new +archive-only change is `Protected write refused; N originals archived; +database changed; pull incomplete.` + +D282 reads database-dependent vetoes in the protected preview, at one +database revision. The archive goes ahead only at that same revision. A +veto there, including on a `left_out` row, forbids the archive. A deleted +source or a deleted record leaves its rows out (D182, D190) and also +forbids the archive. The privacy scan still comes +first. The archive is pull-only. A mapped file import does not gain it. +A deleted archive source is not recreated, and the archive writes no +device receipt. + +Each archived series row is a capsule of `resource`, the response +`resolution`, and the unchanged row. The hash is of that capsule. A raw +capsule and a day capsule are different records. A stored capsule that +hashes equal but differs is an archive failure, not a merge. + +A reported series uses only the report sensor, including when `source` +is null. A measured series with `source: null` uses only the unattributed +sensor. Age is a source report with no `field_basis`. + +Rejected alternatives: + +- Leave the views in place until commit. Rejected. SQLite checks them + when the replacement table is renamed, and the missing `records` name + fails that check. +- Count an archive as `written`. Rejected. The protected import failed. + The database change is reported by `database_changed` and the archive + counts. +- Archive whichever error the mapper returns first. Rejected. A later + conflicting device id would then be stored. +- Give a mapped file import the same second transaction. Rejected. The + file has no selected-server privacy context, and the shared mapper + would gain a write the import did not ask for. +- Hash the series row and infer the resolution later. Rejected. The + resolution is on the response, not on the row. + +## D282. The archive goes ahead only at the revision where the safety facts were read + +This corrects D281. The returned health data stays in this pull. The +specification is the contract. The first version of this decision read +the safety facts under one write lock and read them again under a second +one. Version 2.1.1 has no write-locked preview, so this version uses the +2.1.1 revision check instead. + +Privacy, required ids, and supplied-field names are checked on the +returned page before either preview. A failure builds neither preview. + +Receipts, bindings, history, source deletion, stored records, import +keys, tombstones, null-source payloads, and workout kinds are read in the +protected preview. `preview_route` in `src/import/provider.rs` reads +them in one read transaction, at one database revision. The read +includes a row the mapping would leave out. That read is the safety +snapshot. A veto in it refuses the protected page, and the archive is +not attempted. A deleted source or a deleted record leaves its rows out +(D182, D190), and it also stops the archive of that page. A read from +before that preview is not the snapshot. + +The archive is a second preview and apply. Its preview reads the archive +source and the target capsules, including tombstones. It is built only +when the database revision still equals the snapshot's revision. Its +apply refuses a moved revision, as every 2.1.1 apply does. Every +athlete-data write in 2.1.1 moves that revision. A restore into an empty +database instead sets a new database ID, and the apply refuses another +database ID. So a binding, a deletion, or an owner correction made after +the snapshot sets `archive` to `not_attempted`, and the archive writes +nothing. A deleted source or a deleted record is not copied onto a new +archive identity. A deleted archive source is not recreated. A deleted +capsule is not replaced. If the page names a row the bounded read cannot +cover, the page is not archived. There is no retry. + +A failed step 8 during init rolls back to the committed step 7 schema +before the existing init cleanup runs. Init fails. D276's cleanup is +unchanged. A migrate of an existing 2.1.3 database keeps that file and +schema 7 when step 8 rolls back. An older database keeps the steps that +committed before step 8, as D272 says. + +Rejected alternatives: + +- Read the safety facts again under a second write lock, as the first + version of this decision did. Rejected. The revision check already says + whether anything changed after the snapshot. A second read would repeat + that check in new code. +- Use a read from before the protected preview as the archive decision. + Rejected. Another command can bind the source before that preview, and + the protected veto would then be stored. +- Recheck only the archive source before the archive. Rejected. The owner + can delete the original source or record in between, and the payload + would be stored under a new identity. +- Leave a failed init file at step 7. Rejected. The existing caller + removes that file, and this build does not change that cleanup. + +## D283. A workout the person typed is a workout session + +This supersedes only the sentences in D272 and D279 that store a manual +workout as a source report or leave it out. D272 through D282 otherwise +stay as written. The specification is the contract. + +`entry_source` `manual` is a `workout_session`. Its source type is +`manual`. `field_basis.value` is `entered_by_hand`. It is not a device +measurement. `device_id`, if the server sent one, stays on the original +object. It does not set `device_binding`, and it does not put the +workout on the watch's source. The server workout id is the match key, +so a later pull updates the same workout. Name, type, start, end, +distance, heart rate, elevation, zones, and segments are stored the same +way they are stored on an automatic workout. `activity_type` still +records that Open Wearables normalized the sport name. D286 corrects the +next rule. The numbers on this session do not enter the eight range +calculations or `provider-period-summary`. `workout-drift` may use the +session's start and end when the caller names that session. The samples +in that window still exclude a manual source. The session does not enter +a device baseline. + +`unknown`, JSON null, and a missing `entry_source` stay source reports of +kind `unknown_workout`. They are not a workout session, and they are not +manual. + +Rejected alternatives: + +- Store a manual workout as a source report. Rejected. The workout object + says a manual entry is self-reported and has no device measurement + behind it. The record is a workout, and the source is the person. +- Call a manual workout a provider summary. Rejected. It is a session. +- Treat `unknown`, JSON null, or a missing `entry_source` as manual. + Rejected. Those values are not the self-reported entry. + +## D284. A body skin-temperature time is not an instant by itself + +This corrects the sentence that treats a non-null +`skin_temperature_measured_at` as a measurement instant. The other body +rules stay. + +The body service reads a skin-temperature sample in the latest window. +When that sample is missing, it reads the newest day value and uses that +day's `period_start` as the same timestamp. The response has no field +that says which read it used. The amount, the unit, and the timestamp +stay on the original object. The skin-temperature child is time-unknown. +It has no `recorded_at`. The program does not choose by comparing +timestamps, and it does not invent bounds. Body temperature and blood +pressure still use their own times. A raw skin-temperature sample and a +day skin-temperature window keep the series rules they already have. + +Rejected alternatives: + +- Treat every non-null body timestamp as an instant. Rejected. The day + fallback writes `period_start` into the same field. +- Drop the timestamp. Rejected. The original object keeps what the server + sent. + +## D285. A finite heart-rate recovery stays, including zero + +This corrects the positive point gate for one quantity. The quantity, +the unit, and the import key stay `hr_recovery` and `bpm`. + +Open Wearables stores `heart_rate_recovery_one_minute` as a number in +bpm. The sample value has no positive minimum. The mapping and the v1 +point check currently reject a point at or below zero, except +`temperature_deviation`. A finite `hr_recovery`, including zero and a +negative number, passes that check. A non-finite value does not. Other +points stay positive. `temperature_deviation` stays signed. +The exception is the point check in `src/model/data.rs`. +`packages/npm/src/schema.ts` is frozen compatibility code and is not where +this check is added. No table is rebuilt for this check. + +Rejected alternatives: + +- Keep the positive gate and drop a recovery of zero. Rejected. The + server can return that number, and this pull said a returned zero stays + zero for this quantity. +- Allow zero for every point. Rejected. The other positive checks stay. + +## D286. A manual session can set a window, and its numbers stay out + +This corrects the D283 sentence that says the calculations do not read a +manual workout. It does not change the calculation code. + +`read_inputs` and `read_period` exclude `source_type` `manual`. They have +no `include_manual` switch. `workout-drift` loads the session the caller +names, including a manual session, and uses its start and end as the +window. The samples then come from `read_inputs`, so a manual source's +numbers are not inputs. The session's own heart rate and distance are not +inputs. `query_measurements`, `query_series`, and `query_sessions` in +`src/store/query.rs` omit manual sources unless `include_manual` is true. +The JavaScript names `queryMeasurements`, `querySeries`, and +`querySessions` in `packages/npm/src/database.ts` call those functions. +A generic record listing +is not those three functions. A typed workout must not enter a device +baseline. + +Rejected alternatives: + +- Refuse a manual session as the drift window. Rejected. The current + command already accepts that window and then reads the other sources' + samples. This proposal does not take that away. +- Let a manual heart rate enter a baseline when `include_manual` is set. + Rejected. The calculation SQL has no such switch. + +## D287. A provider-live workout is kept as an original + +D288 is the live-read procedure. D289 is the privacy choice. Where this +proposal disagrees with either, those decisions are the proposal. + +The stored workout list is the normalized session. The provider route +handlers return the vendor object and do not insert a workout row. +Defaults leave workout samples, FIT bytes, and raw payloads unstored +unless that deployment turned the flag on. This pull can store the vendor +object when the person passes `--vendor-workouts`. + +The original is a `source_report` of kind `original`, subject +`vendor_workout`, writer `open_wearables`, sensor +`ow1:["vendor_workout", provider]`. The match key is the provider plus +the vendor workout id. It is not a second workout session, and it is not +joined to the stored session by time. The public stored workout has no +`external_id`. Device names, device ids, routes, and nested samples stay +inside the original. They do not set `device_binding`, and they are not +measurement samples. Calculations do not read the original. + +Each original is one envelope. It holds `provider`, `vendor_id` as text, +`start` and `start_kind` when the object has a start, `list`, `detail` +when a detail is stored, and `detail_status`. Sensorbio adds +`list_parent`. Garmin adds `upload_window`, the window its object came +from, and `detail_checked_at` when a detail call answered 404 or 501. +The specification's section 2 shows the JSON. The whole +envelope is kept in `supplied_fields`, and `provider_record_id` is +`vendor_id`. The match key is the writer, the sensor, the resource +`vendor_workout`, the provider, and the vendor id, escaped by D181. + +The rewritten `mappings/open-wearables.md` gains a section named +`vendor_workout`. It declares the record type, the kind, the subject, the +writer, the sensor, the key, and the start. A saved file of envelopes +imports through that section. File import writes each envelope as the +file holds it, as D182 does for every mapped import, except the +owner-correction rule below and the Garmin window rule in D288. The +detail rules in +D288 run before the mapping engine sees an envelope, so the mapping +engine has no vendor exception. + +The pull writes one provider's originals as one page, after that +provider's list and detail calls finish. That page is one preview and, +under `--yes`, one apply, as D275 says for every page. A vendor page +never holds a stored row or an archive capsule. A failed or refused +vendor page leaves that provider `incomplete`. It does not change the +stored pages or the archive. + +The vendor page uses the 2.1.1 keyed rules. An original the person +deleted is left out on every later pull and is not recreated (D182). A +deleted `vendor_workout` source leaves out every object from that +provider (D190). + +An owner correction is kept until the server's data changes. On route +`open_wearables` only, a pull or a mapped import compares a candidate for +an owner-corrected record with the newest revision an import wrote: the +newest one whose `record_revisions.became_known_at_basis` is +`provider_import`. The basis says how a revision became known. The rule +does not read `changed_by`, because an import writes the tool actor +`ath`, and `ath grade` writes that same actor with basis `local_write`. +A protocol caller can choose the basis, so a write that chooses +`provider_import` counts as an import. The rule does not compare with +the owner's revision. Equal +writes nothing, and the correction stays current. Different replaces the +correction, and the count `owner_corrections_replaced` shows it on that +provider's line, in `--json`, and in the preview, which says `estimated: +would replace N owner corrections; delete an original to keep it`. The +correction stays in the history. The rule covers every record on that +route, so a workout fix on the stored session also survives a pull of +unchanged data. For that route it supersedes the D182 sentence that a +mapped import replaces a changed object. Other routes keep D182. That +scope is the stated default, and the maintainer still has to confirm it. +The stored-original read in D288 uses the same import revision, so an +owner's edit does not trigger a detail call. The skill says that a +workout fix belongs on the session or in a note, not on the vendor +original. Deleting an original keeps the person's version in its history +and stops every later pull from changing it. + +A package merge counts as an owner correction only where the person +resolved a conflict as imported or corrected. `merge_in` in +`src/package/restore.rs` copies the package's revisions with their own +bases, so a record merged without a conflict keeps its import revisions +as imports. `resolve_in` writes such a resolution as a new revision with +basis `package_merge` and the athlete as actor. Choosing the local side +writes nothing. That is the person's choice, +so the rule keeps it as it keeps an edit. The counts name it accurately: +`merge_choices_replaced` is the part of `owner_corrections_replaced` that +were merge choices, and the line adds `(M of them merge choices)`. + +Body-snapshot records rarely keep a correction. The server averages +heart rate and HRV over a window that ends at the request, and the body +records' match keys have no date, so the snapshot almost always differs +from the last pull. The count shows each replacement. + +Each provider's line counts originals as new, changed, and unchanged. It +counts owner corrections replaced, with the merge choices among them, +details by outcome, objects left out by reason, and withheld values. + +Vendor originals have a total size bound, `MAX_VENDOR_ORIGINAL_BYTES`. It +is half of the 512 MiB package read cap, 256 MiB, counted in the bytes +`ath export` writes for every revision of every original, including a +deleted one. A native package writes them in its main document, +`athlete.ath.json`, with every record that is not a measurement sample: +the current record under `records` and each revision under +`record_revisions`. Only samples go to `series/` files. Version 2.1.1 +reads that document only up to 512 MiB, and a mapped import file only up +to 512 MiB. Export pretty-prints each item, so the bound counts those +bytes and not the compact `record_json` column. One function measures an +item for both. The database keeps each original's size in +`vendor_original_sizes`: its current item, and the sum of its revision +items. A write measures only the items it writes, and only `ath check` +measures every original again. A synthetic one-hour Polar run with a +route exports at 2.05 times its compact size, and each original is in +the document at least twice. So the earlier bound, 128 MiB of compact +JSON, could export to about 525 MiB. The new bound holds about 158 such +workouts with one revision each, or about 105 with two. Evidence: +[appendix/vendor-original-size.md](appendix/vendor-original-size.md). + +Every write that adds a vendor-original revision checks the bound: a pull +page, a mapped import, `ath correct`, the protocol record writes, a +package merge, and a native restore. A page that would pass it is +refused, its objects count as `size_cap`, and that provider is +`incomplete`. Every pull prints how much of the bound the originals use, +in the text and in `--json`. From 80% it warns, and the warning names +`ath erase`, says the erase cannot be undone, and says that a later +version may lift the bound. It is written for the person, so it names no +plan question. `ath export` gains a +check that refuses to publish a document over the 512 MiB read cap or an +item that reaches 128 levels, because 2.1.1 can write a package it +cannot read back. The read parses with serde_json, which refuses 128 +levels, though `check_nesting` allows 128. The package puts a vendor +object five levels down, so the pull refuses a vendor object nested 123 +levels or more as `too_deep`, and no vendor original trips that check. +Each listed object is in exactly one detail count or +one left-out count, so no object is dropped without a count. + +The pull uses the published query parameters and does not add its own +retry. It does not call sync or historical sync. A completed provider +line means that provider's stated limit was reached. It does not mean the +vendor returned lifetime history. The same API key is used. No new vendor +permission is added. + +Rejected alternatives: + +- Leave the live routes unread. Rejected. The vendor object is available + from the server and is not the stored workout. +- Make the live object a second workout session. Rejected. The stored + session already exists, and the public workout has no vendor id to join + them. +- Call sync or historical sync to fill the gap. Rejected. Those routes + are writes this pull does not call. +- Store the list object and the detail as two records. Rejected. They + describe one workout, and nothing in either object joins them except + the id the envelope already uses. +- Store vendor originals with no size bound. Rejected. They share the + package's main document, and an export past its read cap could not be + restored. +- Store only the list object once the bound is near. Rejected. The pull + would drop details while it reported success. +- Count the bound in compact `record_json` bytes, as the earlier text + did. Rejected. Export pretty-prints each item and writes each original + at least twice, so a database under that bound could not be exported + and read back. +- Give vendor originals more than half of the read cap. Not chosen. + Nothing bounds the other records in the main document, and a long + history of points, summaries, and sessions shares it. +- Check the bound only on pulls and mapped imports. Rejected. `ath + correct`, a merge, or a restore could then take a database past it, and + its export could become unreadable. +- Measure every stored original on each write, as the earlier text did. + Rejected. Near the bound, one `ath correct` would first pretty-print + about 256 MiB. +- Keep one cached total. Rejected. A new revision also changes the + original's current item, and one total cannot say how much of the old + item to take away. +- Store originals in their own package files now. Not chosen in this + plan. It changes the package format. Section 9 of the specification + lists it, and section 10 leaves it as an open question for the + maintainer. +- Replace an owner correction whenever the candidate differs from the + current record, as D182 does and as the first version of this decision + did. Rejected. A pull repeats the same server data, so every pull would + undo every correction even when the server had not changed. +- Never replace an owner correction. Rejected. A later fix by the vendor + would be lost, and nothing would say so. +- Limit the rule to vendor originals. Rejected. The skill sends workout + fixes to the stored session, and the D182 rule would undo those on every + pull. The maintainer can narrow it before approval. +- Use the rule on every mapped route. Not chosen for this release. Other + routes import a file the person chose, and D182 stays their rule. +- Treat a `package_merge` revision as an import. Rejected. It is a + conflict the person resolved, and a pull of changed data would replace + that choice with no count. +- Count merge choices only as owner corrections. Rejected. The line would + name an edit the person never made, so the counts name merge choices + as their own part. + +## D288. A live vendor read is opt-in, and one failure stays on that provider + +This supersedes the D287 sentences that said a live GET does not write on +the server, that a failed provider stops the later providers, that Polar's +list asks for samples, zones, and route, that a start outside the range +is dropped, and that the server splits a Garmin range. + +On 15 November 2026 this decision was revised for the review at +`e145fa6` and for 2.1.1. The specification's section 2 is the full +procedure. + +`--vendor-workouts` is off unless the person passes it. Off, preview and +`--json` call neither the connections route nor a live workout route. +On, a preview reads the connections list and each active provider's list, +and it makes no detail call. Every vendor count it prints, and the +owner-correction and merge-choice counts, are labeled `estimated`, in +the text and in `--json`. The count of ids `--yes` would detail is +`would_detail`. The +preview says that it made no detail calls, so detail failures, size +limits, and refusals are only known after `--yes`. The preview writes +nothing in this database and prints `vendor requests were made`. +"Nothing stored" and "nothing written" always mean this database. A +preview and then `--yes` read each list twice, and the preview and the +help say so. Running `--yes` alone reads each list once. + +The server, while answering the GET, can save a refreshed vendor token, +revoke a connection, emit `connection.revoked`, write `token_refresh_lock` +and `provider_auth_failing_since`, and on HTTP 429 sleep 15, then 30, +then 60 seconds, up to three retries. This program does not add a retry +of its own. Every run with the flag says, before its first live request, +that the server may refresh and save vendor tokens, may revoke a +connection, and may wait about 105 seconds on a rate limit. That holds +for a preview, for `--yes`, and for `--json`, which puts the three +sentences in `vendor_workouts.notice`. The flag's help text says the +same. + +The pull reads `GET /users/{id}/connections` first. Each item's `user_id` +must be the selected user, or the list is refused. The pull keeps only +`provider` and `status` from each item. It drops the rest, including +`linked_user_ids`, which holds other users' ids. The list is never +stored, so the privacy scan does not run on it. A provider is called only +when its status is `active` and it has a live list method. `revoked`, +`expired`, a missing item, and an unknown status are `not_attempted`, and +the line shows the status. Those providers are never called, because a +call could make the server try a refresh or a revoke. The order is +Garmin, Polar, Suunto, Whoop, Fitbit, Oura, Strava, Withings, Sensorbio. +One failure leaves that line `incomplete`. The others still run. + +Garmin is read by this program in windows on a fixed grid, one call +each. Each window starts at a multiple of 82,800 seconds, 23 hours, +after the Unix epoch, and lasts 82,800 seconds. The first and last +windows are the grid windows that hold the range's first and last +seconds, so they can reach up to 23 hours past the range. Every command +uses the same grid, so windows from two commands are equal or do not +overlap. Windows that started at `--from`, as the earlier text had them, +overlapped only partly when two commands had different ranges. Each +window sends integer Unix seconds. The pinned server passes a window it +does not split to Garmin unchanged, so a grid window still reaches Garmin +as one 23-hour read. The pinned server splits a window it sees as longer +than 24 hours and drops a failed piece without saying so. It measures in +naive local time. +When the server's clock moves forward an hour, 24 real hours read as 25 +local hours, and the server would split the window. When the clock moves +back, they read as 23. A 23-hour window reads as 24 at most where the +clock moves by one hour. A zone that moves it by two hours, such as +`Antarctica/Troll`, is not covered. Any failed window makes Garmin +`incomplete`. The pull keeps calling Garmin detail at the pinned path, +`/wellness-api/rest/activities/{activity_id}`. That path is not in +Garmin's public docs, and this study did not find it there. The first +Garmin detail call in a command is a probe. When it answers HTTP 404 or +501, the pull makes no other Garmin detail call in that command. The +probed id is `not_available`, each other id still due a call is +`deferred`, every list object is stored, and Garmin stays `completed`. +The line says `Garmin detail unavailable (HTTP n); list objects stored`, +and its deferred count adds `(not asked: detail unavailable this run)`. +Any other error status on the probe, except 401 and 429, also stops the +Garmin detail calls, and every due id is `deferred`, the probed id +included. A 400, 403, or 405 does not show that the activity has no +detail, so the next command probes that id again. Garmin stays +`completed` after a 4xx status. It is `incomplete` after a 5xx status, +because the server reported a fault. After a 2xx answer to the probe, +the calls go on, and a later 404 or 501 is `not_available` for that id. +Any other Garmin detail error is `failed`. + +An id that got 404 or 501 keeps the time of that answer as +`detail_checked_at`. It is asked again when its list object changes, or +30 days after that time, after every other due id. A repeat answer writes +the new time. An id a command does not ask keeps `not_available` and its +time, so a missing path does not rewrite those originals. An original +with a current owner correction is asked again only when its list object +changes, because a repeat answer would not be written over the +correction. So a missing path costs one call in a command, not the +budget of 100. This is the stated default. The maintainer still has to +confirm it before approval. + +Polar's list omits samples, zones, and route, and detail +asks for all three. Suunto's detail is called at `workoutKey`. A list +object with no `workoutKey` gets no detail call and is `not_available`, +because nothing this study read shows that Suunto's detail accepts a +`workoutId`. Its `payload` is unwrapped, and the record key is +`workoutId`. One command sends at most 100 Suunto list requests, +`MAX_SUUNTO_LIST_REQUESTS`. A cap that stops a list after a full page makes +Suunto `incomplete`, and the objects already read are still written. Whoop's response names its +next page `next_token`. The request name, `nextToken`, is not sent. +Sensorbio reads only the oldest 50 entries, and its line says so. + +A stored detail is never lost. A detail is fetched for an id with no +stored detail, unless an earlier command marked it `not_available` less +than 30 days before, and again only when the list object changed. Credential +values (D289) are withheld before any comparison, so a token that changed +between pulls does not make a list object look changed. A list-only +object never replaces a stored detail. A new detail that is thinner than +the stored one writes nothing. Thinner means a detail field the +specification's table names for that provider is filled in the stored +detail and empty in the new one. Garmin, Suunto, Whoop, and Oura name no +detail field, so a new detail from them replaces the stored one even when +it has fewer fields. The stored detail stays in the record's history as +the earlier revision. A deferred or failed detail keeps the +stored detail and adds no revision. A detail over the 10 MiB response cap +is `too_large`, because the detail route has no smaller page. A detail +the privacy scan refuses is `refused` by `privacy_scan`. Neither is +stored. A failed, mismatched, too large, or privacy-refused detail makes +the provider `incomplete` and the exit nonzero, because a limit may +refuse work but must not report it as complete. A too large or +privacy-refused id is retried after the new and changed ids. A detail +with a `__proto__` key is `refused` as `unusable_name`, as the next +paragraphs say. A deferred detail leaves the provider `completed`, with a +separate deferred count. A detail is read after the provider's whole +list, so it can come minutes after its list object, and the vendor can +change the workout in between. The envelope does not record when each +part was read. + +Live requests go one at a time, at least one second apart. The read +timeout is 360 seconds. The server's own retries can take about 225 +seconds, so the client waits for them. A live request that still times +out ends that provider for the command, so two requests to one provider +never overlap. An HTTP 429 ends that provider the same way, because the +server has already spent its three retries on the vendor's limit. An +HTTP 401 ends it the same way. The server has already reloaded or +refreshed the vendor token and tried once more, each later 401 would make +it do that again, and a refresh the vendor rejects revokes the +connection. After a 401 the provider's line tells the person to +reconnect the provider in Open Wearables if this repeats. The detail +call that got 429 or 401, or that timed out, is +`failed`. Each id still due a detail call is `deferred`. An id that was +due no call keeps its own count, such as `kept`. What the provider +already returned is still written, and the provider is `incomplete`. A +command makes at most 100 detail calls to one provider and at most 20 to +Strava. Ids with no stored detail go first, oldest start first. Each id +goes in the first group of the order it matches. Strava's limit belongs +to the whole application, so the deployment's own sync shares it. The +server tries one request at most four times and the pull sees only the +last answer. So one command sends 21 Strava requests in the usual case, +24 or 25 when only the last request was retried, and at most 84. The +review cited about 100 requests a +minute for Garmin. This study did not find that number in Garmin's public +docs. The one-second pace keeps this command at 60 a minute or fewer. + +A vendor id is text. A JSON integer is written in decimal, so `123` and +`"123"` are one id. An integer above 9007199254740991 is refused, because +D213 would change its digits. When one Garmin activity id is in two +windows with different objects, the later window's copy is kept, because +windows select by upload time and the later window holds the later +upload. The earlier copy counts as `superseded`. Inside one window, two +different objects with one id are both refused. Each Garmin envelope +keeps its `upload_window`, so the rule also holds across commands. A copy +from a window that ends at or before the start of the stored copy's +window was uploaded first. It is `superseded`, it writes nothing, and it +is not a server change, so it replaces no owner correction. A copy from a +window that starts at or after the stored window's end was uploaded +later, and a pull's new read of the stored window is a later read. Both +are changes. Any other pair of windows overlaps, or is equal in a mapped +import of saved envelopes, whose read time is unknown. Then the order of +the copies is unknown. The candidate counts as `ambiguous_window`, the +stored copy is kept, nothing is written, and no owner correction is +replaced. The grid means a pull never makes such a pair, but a saved +file can carry any window. Comparisons leave `upload_window` out, because +Garmin can return an unchanged object in a later window. + +The start becomes `input_timestamp` by the rules in the specification: +text keeps its offset or says it has none, and Unix seconds or +milliseconds keep their digits. The start is stored and is not a filter. + +A vendor list object with a `__proto__` key at any depth is refused alone +as `unusable_name`, and the provider stays `completed`. The import check +(D191) refuses that key and fails the whole import. Vendor JSON is +outside ath's control, so one such object would otherwise fail that +provider's page on every command, with no count and no fix. The vendor +read runs the same check on each list object and each detail before the +page is staged. When only the detail holds the key, the clean list object +is stored with `detail_status` `refused`, `refused_by` `unusable_name`, +and the key's path in `refused_path`. That detail is asked for again only +when its list object changes, because a rerun gets the same detail. Each +refused object and refused detail is named in `left_out.examples`, inside +its 20-line bound, by provider, vendor id, reason, and key path. + +A vendor object nested 123 levels or more is refused the same way as +`too_deep`, and it is named with its depth. The package puts the object +five levels down, and the read refuses 128 levels, so storing it would +make every later export fail until the person erased the original. A +saved envelope that deep is left out of a mapped import too. + +Every returned original is stored, including a start outside `--from` and +`--to`. The count is `vendor workout originals`. `range_complete` uses +only the stored ranged reads. Each line says whether its limit covers the +requested range and whether more data exists. An object the pull does not +write is counted by reason. + +The unwrap, the id, the start field, the detail key, the detail unwrap, +the detail fields, the budget, and the read timeout for each provider are +the table in the spec. File import uses the same envelope. The provider +logic lives in `src/runtime/vendor_workouts.rs`, driven by one table. +`src/runtime/open_wearables.rs` calls that module. + +Rejected alternatives: + +- Call every provider the server lists. Rejected. A call to a revoked or + expired connection can make the server try a refresh or a revoke. +- Store the connections list. Rejected. It holds other users' ids, and it + is not health data. +- Write the list object over a stored detail when the new detail fails or + is deferred. Rejected. The person would lose data they already have. +- Count a Garmin detail 404 as `failed`, as the earlier text did. + Rejected. If the path does not exist, Garmin would be `incomplete` on + every command, and the person could not fix it. +- Drop the Garmin detail call because the path is not in Garmin's public + docs. Rejected. The pinned server calls it, and a deployment where it + works would lose every Garmin detail. +- Call Garmin detail for every due id after a 404, as the earlier text + did. Rejected. A missing path would spend up to 100 calls in every + command. +- Mark every id the probe stopped as `not_available`. Rejected. Those ids + were not asked. A 404 can mean one missing activity, and the mark would + stop their details until their list objects changed. +- Mark the probed id `not_available` after a 400, 403, or 405, as the + earlier text did. Rejected. Those statuses do not show that the + activity has no detail. A permission not yet granted would leave that + workout list-only until its list object changed. +- Ask a `not_available` id again only when its list object changes, as + the earlier text did. Rejected. Where the path works, one passing 404 + would leave that workout list-only for good. +- Ask a `not_available` id again on every command. Rejected. Each + activity with no detail would spend a call on every command. +- Keep the recheck time outside the envelope. Rejected. A restore would + lose it, and the export would not hold all of the record's state. +- Treat a 401 on the probe as a missing path. Rejected. A 401 is what an + expired or revoked grant answers, so the person may need to reconnect + Garmin. Its line must not say only that detail is unavailable. +- Keep calling a provider after a 401. Rejected. Each call could make the + server refresh the vendor token, and a rejected refresh revokes the + connection. +- Use a 30-second read timeout. Rejected. The server's own retries take + longer. The client would give up, and a rerun could send a second + request while the first still runs. +- Retry a live request that timed out. Rejected for the same reason. +- Keep calling a provider after a 429. Rejected. The server has already + waited about 105 seconds and retried three times, and more calls would + spend a limit the deployment's own sync shares. + +- Leave live reads on by default. Rejected. The server can change a token + and revoke a connection while answering the GET. +- Stop the later providers after one failure. Rejected. A person connected + only to Garmin must still finish when another provider is absent, and a + failed provider must not hide a finished one. +- Let the server split a Garmin range. Rejected. A failed window must be + visible as incomplete. +- Call Suunto detail at `workoutId` when the list object has no + `workoutKey`, as the earlier text did. Rejected. No source this study + read shows that call works, and a wrong call would count as `failed` on + every command. +- Make detail calls in a preview. Rejected. A preview and then `--yes` + would make every detail call twice, and Strava's limit is shared. +- Count a too large detail as `not_available`. Rejected. The vendor has + the detail, and this program's own cap refused it, so the provider did + not finish. +- Refuse both copies when one Garmin id is in two windows with different + objects, as inside one response. Rejected. A re-upload is an ordinary + Garmin event, and the later window holds the later copy. +- Compare Garmin windows only inside one command, as the earlier text + did. Rejected. A later command that reads only an earlier window would + store the older copy again, and it would count that as a server change + that replaces an owner correction. +- Count a different `upload_window` as a change. Rejected. Garmin can + return an unchanged object in a later window, and that would revise an + original the vendor did not change. +- Start the windows at `--from`, as the earlier text did. Rejected. Two + commands with different ranges then send windows that overlap only + partly, and the earlier-window test cannot order the copies. A command + that read the older copy would replace the newer one and an owner + correction with it. +- Treat a partly overlapping window as a change. Rejected. Which copy is + newer is unknown, and a change would replace an owner correction with + what may be the older copy. +- Drop an original whose start is outside the requested range. Rejected. + The live methods do not filter by workout start, so a drop would hide a + returned object. +- Refuse the list object too when only its detail holds a `__proto__` + key, as the earlier text did. Rejected. Nothing would be stored, and + every command would spend a detail call on that id again. +- Ask for a name-refused detail again after the new and changed ids, as + a privacy-refused one is. Rejected. The vendor returns the same detail, + so the call would be spent on every command for no gain. +- Count refused objects without naming them. Rejected. With the provider + `completed`, a count alone does not tell the person which workout or + which key. +- Store a vendor object of any depth and let export refuse it, as the + earlier text did. Rejected. One deep object would block every export + until the person erased it. +- Refuse from 124 levels, which the reviews proposed from the 128 that + `check_nesting` allows. Rejected. serde_json refuses 128 levels when + the read parses the document, so a 123-level object would be stored + and then fail to read back. + +## D289. Vendor originals stay whole. The maintainer can change this + +This is a labeled choice. The default in this proposal is to keep each +vendor object whole, including account ids, Polar user URLs, and full GPS +routes. The reason is a complete, portable copy of what the vendor +returned. The output and the spec say those fields are included. Only a +credential-shaped value is withheld, as the next paragraphs say. + +The scan still refuses the API key, the selected origin, and the selected +user id, wherever they appear. That includes a value under a +credential-shaped key. + +A credential-shaped key does not refuse the page. Its value is withheld. +The value is replaced by the text `[withheld by ath]`, and the pull +records the JSON path and counts it. A key is credential-shaped when its +letters and digits, with case ignored and every other character dropped, +end in `token` or `secret`, or are `apikey`, `authorization`, or +`password`. The page cursors `next_token` and `nextToken`, matched +exactly, are not credential-shaped. Whoop and Oura name their next page +`next_token`, and withholding it would turn a null into text. A query +parameter or a fragment pair with a credential-shaped name inside a URL +string is withheld the same way, and so is a user name or password before +the `@`. The URL keeps its scheme, host, port, and path. `polar_user` and a +coordinate are not credential-shaped. The rule covers stored reads and +vendor reads alike. + +Garmin's summary objects can carry an optional `userAccessToken`. The +pinned server declares it on its Garmin wellness models, and the live +route returns Garmin's objects unchanged. Refusing the page would refuse +every Garmin page that carries it, and the workouts on it would be lost. Withholding keeps the workout and keeps the vendor's token +out of the record. The stored original then differs from the vendor's +object only at the withheld paths, and the count says how many there +are. The maintainer can change the key list or the marker before +approval. + +Rejected alternatives: + +- Strip account ids, user URLs, and routes before storage. Not chosen. + The stored object would no longer be the object the vendor returned. + The maintainer can replace this decision before approval. +- Refuse the whole page when a credential-shaped key appears, as the + first version of this decision did. Rejected. One optional Garmin field + would block every Garmin page, and the person would lose those workouts. +- Drop a credential-shaped field without a marker. Rejected. The stored + original would not show that a value was removed. diff --git a/build-history/v2.2.0/progress.md b/build-history/v2.2.0/progress.md new file mode 100644 index 00000000..42f1de02 --- /dev/null +++ b/build-history/v2.2.0/progress.md @@ -0,0 +1,20 @@ +# v2.2.0 progress + +This folder is the plan. The maintainer has not approved it. Nothing in the +program, the record, or the database has changed for 2.2.0. + +| Step | What | Status | +|---|---|---| +| 0 | The plan: proposals D272–D289, and the Open Wearables study. The proposals were D198–D215 until 2.1.1 used D208–D226, then D227–D244 until 2.1.2 used D227–D253, then D254–D271 until 2.1.3 used D254–D271. Checked against 2.1.1 at `0de71bb` on 15 November 2026: a page is one import preview and one apply, and D282 uses the revision check. D284 through D286 stay. D287 and D288 answer the review at `e145fa6`. D289 withholds a credential-shaped value. The pass after the review at `d636d7a` amends D272, D275, D276, D281, D287, D288, and D289. The pass after the reviews at `3c3f660` amends D273, D275, D276, D287, and D288 and adds no decision number. The pass after the reviews at `57838e1` amends D276, D287, and D288 and adds no decision number. Three questions stay open for the maintainer, in section 10 of the specification: the Garmin detail default, the owner-correction scope, and storing vendor originals in their own files. Still not adopted. The new head needs a fresh review | written, not approved | +| 1 | Version 2.2.0 and migration step 8. Step 5 is the published 2.1.1 migration. Step 6 is the published 2.1.2 migration. Step 7 is the published 2.1.3 migration. No new column on an existing table. The root check gains `source_report` by the copy in D281. Summary and score values may be omitted in pairs (D272, D281) | not started | +| 2 | `ath pull openwearables` in the `athleticstandard` crate, with the rewritten mapping (D273, D275, D281) | not started | +| 3 | Key, server, and user id kept out of the record (D274) | not started | +| 4 | Fixture tests, with no live key in CI | not started | +| 5 | Generated schema, demo athlete, skill command reference, and the public-data list | not started | +| 6 | Laptop card and the proof in the build pull request | not started | + +The build, after approval, is one pull request. It is not three. + +The Windows failed-init cleanup, the size of `src/import/mapping.rs`, a +way to clear the Garmin key, and a name check outside import stay out of +that pull request (D276). `persist.rs` is already gone. diff --git a/build-history/v2.2.0/spec.md b/build-history/v2.2.0/spec.md new file mode 100644 index 00000000..a2fda863 --- /dev/null +++ b/build-history/v2.2.0/spec.md @@ -0,0 +1,3533 @@ +# Athletic Standard 2.2.0 + +Status: **plan only. The maintainer has not approved it. Not approved for build.** + +`ath pull openwearables` reads one person's stored health data from an Open +Wearables server they run. When `--vendor-workouts` is passed, it also +reads the live workout list and detail. It writes the stored reads with +the mapping this release ships. It writes a live original only when that +flag is on and the person confirms the write. The proposals are D272 through D289 in +[decisions.md](decisions.md). They are not adopted. The evidence is +[appendix/open-wearables-api.md](appendix/open-wearables-api.md), checked on +6, 7, 8, and 14 November 2026. + +This pull request is the plan. The build after approval is one later pull +request. This plan does not change a version number, a schema, a fixture, or +the program. + +Version 2.1.1 on `main` `0de71bbd6474916af0408a4090bc2c74a1a3aed2` is the +software this plan is read against. That commit is the merge of pull request +44. An earlier reading used version 2.1.0 at +`8db90b42ac654767e9e9570a121bbbd4fde3348a`, the merge of pull request 39. + +Version 2.1.2 on `main` `073f9bce8537b9f720e8dd5365919ef99684f116` is the +merge of pull request 45. It adopted D227 through D253 and published +migration step 6. + +Version 2.1.3 on `main` `a3d3ebafa4bff45aca1a8642ac91be999c10db60` is the +software now. That commit is the merge of pull request 47. It adopted +D254 through D271 and published migration step 7. This plan's proposals +are D272 through D289, and the migration it adds is step 8. The reading +below is still against version 2.1.1, except the decision numbers, the +migration step, and the version lists. + +## 1. What a person does + +They already run Open Wearables and have already connected their devices in +that server's own portal. This command does not sign them in to Garmin, WHOOP, +Oura, Apple, or anyone else. It does not start a sync. + +They save the key once: + +```text +ath key set openwearables +``` + +The program asks them to paste the key and does not print it. A script may set +`OPEN_WEARABLES_API_KEY` instead. + +They name the server, the user, and the range: + +```text +ath pull openwearables \ + --base-url http://127.0.0.1:8000 \ + --user 00000000-0000-4000-8000-000000000001 \ + --from 2026-01-01 \ + --to 2026-01-07 +``` + +The same three values may come from `OPEN_WEARABLES_BASE_URL`, +`OPEN_WEARABLES_USER_ID`, and the key variable above. A flag wins over the +environment when both are set. + +`--vendor-workouts` is off unless the person passes it. Without it, the +command does not call the connections route or either live workout route. +With it, the connections list and each active provider's list are read, +including on a preview and on `--json`. A preview makes no detail call. +The server may then refresh and save vendor tokens, revoke a connection, +and wait about 105 seconds on a rate limit. The help text and every run +with the flag say so (section 2). + +The first run writes nothing. `--json` writes nothing, including when +`--yes` is also present. That is the same rule as `ath import --mapping`. +`ath pull garmin --json` still writes. `--file` chooses a database, as on +the other commands. + +A review of the previous head asked for the committed result in JSON as well +as in text. This proposal does not add a JSON mode that writes. Section 7 +requires `--json` and `--json --yes` to leave the database unchanged. The +committed result is the text of `--yes` without `--json`. A writing JSON +report would be a different choice. It is not this proposal. + +Preview text, and every `--json` result, labels counts `estimated`. That +includes every vendor count, and the owner-correction and merge-choice +counts, in section 2. +Each page is previewed against the database as it was before this command. A +preview writes nothing. A match key that appears on two pages, or a server that changes +between the preview and `--yes`, can make the estimate differ from the +write. The estimate is not a promise of the final new, changed, and +unchanged split. Exact equality would need a command-wide overlay. This +proposal does not add one, and it does not add that work to `mapping.rs`. + +Preview text prints: + +- one line that a date-only bound is sent as typed, and Open Wearables decides + what that day means +- `preview only; nothing stored in this database` +- `reads finished` or `reads incomplete` +- one line each for the twelve reads in section 2: `completed`, `failed`, + or `not_attempted` +- one line each for the live workout providers: `completed`, `incomplete`, + or `not_attempted`, the connection status when it is not `active`, + whether that limit covers the requested range, whether more data exists, + and the detail and left-out counts in section 2. Those counts follow the + word `estimated`, and the count of ids `--yes` would detail is `would + detail` +- when `--vendor-workouts` is on, before the first live request: the three + sentences about server changes in section 2 +- when `--vendor-workouts` is on: `vendor requests were made` +- when `--vendor-workouts` is on: `preview made no detail calls; detail + failures, size limits and refusals are only known after --yes` +- when `--vendor-workouts` is on: `vendor workout originals`, then + `estimated`, then new, changed, and unchanged counts +- on every run: `vendor originals use X MiB of 256 MiB`, the total stored + before this command. It is not an estimate. From 80% of the bound, the + size warning in section 2 follows it +- when a credential-shaped value was withheld: the count and up to 20 + paths, as section 4 says +- when `--vendor-workouts` is on, this sentence: a workout can appear twice, + once as the vendor original and once as the stored session. The original + is the source report whose subject is `vendor_workout`. It is never a + session and never a calculation input +- when `--vendor-workouts` is on: `These originals keep the vendor's account ids, user URLs, and full routes.` +- for body, on a preview: `body snapshot would store` or `body snapshot + would be empty`. On a confirmed write: `body snapshot stored`, + `body snapshot empty`, or `body snapshot incomplete` +- estimated counts, by record type, of sleep sessions, workouts, points, + measurement samples, summaries, scores, and source reports +- committed counts of zero on a preview +- the coverage lines in section 2 +- `left_out` as a total, a count for each reason, and at most 20 example + lines. When there are more lines, it says the list was shortened, as + 2.1.1 previews do with `MAX_PREVIEW_RECORD_IDS` +- `nothing written to this database; pass --yes after reviewing this preview`. + The shared `NOTHING_WRITTEN` line in `src/cli/commands/routes.rs` stays + as it is for the other commands + +`--yes` without `--json` commits each successful page. That commit is one +`ProviderPreview::apply` transaction (D189). It is not a completed pull. The text +prints actual committed counts for pages kept. It prints `requested range + through is complete` only when every stored ranged read in +section 2 reached that read's terminal condition. A live workout line does +not change that sentence. Body is not one of those ranged reads. The +success sentence `pulled openwearables from through ` is +printed only when that range is complete, body and the personal record +completed, and every live provider is `completed` or `not_attempted`. +An `incomplete` live provider prints `vendor workouts incomplete:` and the +provider name. The exit is then nonzero. The success sentence is not +printed. The stored range sentence can still say the range is complete. A finished range with an incomplete body snapshot does not +print that sentence. The body line still says the snapshot is incomplete. + +If a later page fails, the command keeps a typed outcome and then exits +nonzero. It prints that outcome as text, then uses the exit status. There +is no child process. Version 2.1.1 removed that split. When a ranged read failed, the text says the +requested range is incomplete. When every ranged read completed and body +or the personal record failed, the text says the requested range is +complete and names the snapshot that failed. It names any read that is +`not_attempted`, and it prints the retained counts. The exit is nonzero +in both cases. The success sentence is not printed. A failed read says to +run the same command again. An identity refusal uses the sentence in +section 3, which says a rerun cannot +repair the device id. It does not print the success sentence. A refused +page is not applied, so it makes no database changes. +Records already stored stay, including their revisions. An archive, when +section 2 allows one, is a later pull-only preview and apply. It does not print +the success sentence. `written` is true when any protected transaction +in this command created or revised a counted record. An archive does not +make `written` true. `database_changed` is true when any protected +transaction or any archive transaction in this command committed a +change, including the first insert of the archive source. A vendor page +in section 2 is a protected transaction. Its originals are `source_report` +records, so they add to `committed.source_report` as well as to the +vendor originals count and that provider's counts. A committed vendor +page that creates or revises an original makes `written` true and +`database_changed` true, even when every stored page was unchanged. A +first `vendor_workout` source counts as a database change. A later page +does not reset either flag or the counts from an earlier page. An empty +ranged result can still store the personal record or the body snapshot. +Those writes are counted as protected rows. They are not ranged rows. +`written` is false and `database_changed` is false when the confirmed +command committed no protected change and no archive change. Rows stored by an earlier +command can still be there. + +Public `--json`, with or without `--yes`, is only the preview outcome below. +`written` is false. `database_changed` is false. `committed` and +`archive_committed` are zero. `estimated` holds the protected +page-local estimates. `estimated_archive` holds the archive estimates. +`range_complete` is false. `reads_finished` is true only when +every stored read completed. `range_complete` ignores the live workout +lines. The read status token is `not_attempted`, in this object and in +the text. The object has no key, server, user id, or request path. +`vendor_workouts` is always present. + +```json +{ + "from": "2026-01-01", + "to": "2026-01-07", + "written": false, + "database_changed": false, + "range_complete": false, + "reads_finished": false, + "reads": { + "sleep": "completed", + "workouts": "failed", + "timeseries_raw": "not_attempted", + "timeseries_day": "not_attempted" + }, + "estimated": { + "sleep_session": { "new": 1, "changed": 0, "unchanged": 0 } + }, + "committed": { + "sleep_session": { "new": 0, "changed": 0, "unchanged": 0 } + }, + "estimated_archive": { + "source_report": { "new": 0, "changed": 0, "unchanged": 0 } + }, + "archive_committed": { + "source_report": { "new": 0, "changed": 0, "unchanged": 0 } + }, + "left_out": { "total": 0, "by_reason": {}, "examples": [], "shortened": false }, + "withheld": { "total": 0, "paths": [], "shortened": false }, + "estimated_owner_corrections_replaced": 0, + "estimated_merge_choices_replaced": 0, + "vendor_workouts": { + "requested": false, + "requests_made": false, + "notice": [], + "used_bytes": 0, + "bound_bytes": 268435456, + "estimated": { + "originals": { "new": 0, "changed": 0, "unchanged": 0 } + }, + "providers": { + "garmin": { + "status": "not_attempted", + "connection_status": null, + "covers_requested_range": false, + "more": false, + "limit": "not requested", + "estimated": { + "owner_corrections_replaced": 0, + "merge_choices_replaced": 0, + "details": { + "would_detail": 0, + "kept": 0, + "deferred": 0, + "failed": 0, + "mismatch": 0, + "thinner": 0, + "not_available": 0, + "too_large": 0, + "refused": 0 + }, + "left_out": { "total": 0, "by_reason": {} } + } + } + } + } +} +``` + +`notice` is empty without the flag, except for the size warning. With +the flag, `notice` holds the three sentences about server changes in +section 2, on every run, including a preview. Every `--json` run is a +preview, so with the flag `notice` also holds `preview made no detail +calls; detail failures, size limits and refusals are only known after +--yes`. From 80% of the bound, with or without the flag, `notice` also +holds the size warning in section 2. `used_bytes` is the vendor-original +total stored before this command, as export measures it, and +`bound_bytes` is `MAX_VENDOR_ORIGINAL_BYTES`. Both are facts, so they are +not under `estimated`. `connection_status` is `active`, `revoked`, +`expired`, `unknown status`, or `null` when the server listed no +connection for that provider. + +The top-level `estimated_owner_corrections_replaced` counts owner +corrections of stored records that the stored pages would replace, by the +owner-correction rule in section 2. Each provider's +`estimated.owner_corrections_replaced` counts its vendor originals. Both +are estimates, and their keys say so. Beside each, +`estimated_merge_choices_replaced` and `estimated.merge_choices_replaced` +count the part of it that were merge choices. A merge choice is a +conflict the person resolved as imported or corrected in a package +merge, as section 2 says. When +a provider's count is above zero, the preview prints `estimated: would +replace N owner corrections; delete an original to keep it` on that +provider's line. When the top-level count is above zero, it prints +`estimated: would replace N owner corrections of stored records because +the server's data changed`. When some were merge choices, each line adds +`(M of them merge choices)` after `owner corrections`. After `--yes` the +same lines say `replaced N owner corrections`, without `estimated`, and +that each correction stays in the record's history. The text uses the +singular when N or M is 1. + +Every vendor count in a preview is under an `estimated` key: +`vendor_workouts.estimated.originals`, and each provider's `estimated` +object with its owner-correction count, its `details`, and its +`left_out`. A provider's status, connection status, coverage, `more`, and +limit describe the reads this command made, so they stay outside it. +`details.would_detail` counts the ids `--yes` would detail now. `--yes` +prints the same counts without `estimated`, and it says `stored` for the +details it wrote. `withheld` counts the values withheld from what this +command read, so a preview counts them in list objects only. + +The same record types are present for workouts, points, summaries, scores, +and source reports. The example above is shortened. Polar, Suunto, Whoop, +Fitbit, Oura, Strava, Withings, and Sensorbio use the same fields as +`garmin`. Those names are the public `--json` keys. It is the preview +outcome. A preview does not say a snapshot was stored. + +The command returns a different outcome for `--yes` without `--json`. That +outcome has the actual `committed` counts, the actual `archive_committed` +counts, the actual `owner_corrections_replaced` and +`merge_choices_replaced` counts, the actual vendor counts with `stored` +in place of `would_detail`, +`database_changed`, `protected_write`, `archive`, +`range_complete`, and `snapshots_complete`. `committed` counts protected +records only. `archive_committed` counts archive records only, including +a created archive source, counted once. A record is in one of those +maps. `new`, `changed`, and `unchanged` are the created, revised, and +unchanged counts in each map. `range_complete` is true when the stored ranged reads +finished and no protected page in those reads was refused. A live workout +line does not change it. `snapshots_complete` +is true when the personal record and the body snapshot finished. `written` +is true when any protected transaction in this command created or revised +a counted record. A command that only repeats unchanged protected pages, +and that commits no archive change, has `written` false, +`database_changed` false, both completion flags true, and unchanged +protected counts. An earlier change keeps both flags true. A failed ranged page has `range_complete` false. A +failed snapshot after a finished range has `range_complete` true and +`snapshots_complete` false. The command prints sentences from this outcome. +It does not print the outcome as public JSON. Public `--json`, with or +without `--yes`, applies neither the protected preview nor the archive +preview. + +`--date` stays required only for `garmin`. In 2.1.1, `PULL` in +`src/cli/spec.rs` marks `--date` mandatory, so the parser refuses any pull +without it: `error: required option '--date ' not specified`. The +build drops that mark. `pull` in `src/cli/commands/routes.rs` then checks +`--date` for `garmin` and prints that same text, so `ath pull garmin` +without a date fails as it does today. `--from` and `--to` are required +only for `openwearables`, and they are flags, not environment variables. +`--base-url` and `--user` are required for `openwearables` unless the +environment named above supplies them. `--base-url` already exists for +`garmin`, where it names a test server's API root. For `openwearables` it +names the server origin, as D274 says. `ath pull garmin --date YYYY-MM-DD` +is otherwise unchanged, and it still writes without a preview. +`ath pull` with any other name still fails. The failure text +`pull currently reads garmin` becomes `pull reads garmin or openwearables`. + +The flag's help in `src/cli/spec.rs` says: also read live vendor workouts; +the server may refresh and save vendor tokens, revoke a connection, and +wait about 105 seconds on a rate limit. It also says that a preview and +`--json` read the connections list and each active provider's list and +make no detail call, and that a preview and then `--yes` read each list +twice. `src/cli/examples/pull.txt` says the same things, and it says that +"nothing stored" means this database only. + +The saved key can read every user on that server. `ath key` shows whether a +key is saved in the password store and whether `OPEN_WEARABLES_API_KEY` is +set, without printing either value. Those are different facts. `ath key` +with no further word does not remove the saved key. + +`ath key clear` with no name still clears only the gateway keys, `vercel` +and `openrouter`, and it still exits successfully. Open Wearables is not a +gateway name, so this command does not delete that saved key. When a saved +Open Wearables key remains, the text keeps the gateway sentence and adds +`The Open Wearables key remains saved.` and `Remove it with ath key clear +openwearables.` When no saved Open Wearables key remains, the gateway +sentences stay as they are today. + +`ath key clear openwearables` removes the saved key from the password store. +It does not change `OPEN_WEARABLES_API_KEY`, and it does not revoke the key +on the server. When that variable is set, the text says the saved key was +removed and the environment key is still available, so a pull can still use +it. `ath key` still reports the environment key after the saved key is gone. +When the variable is unset, the text says only that the saved key was +removed. `ath key clear vercel` and `ath key clear openrouter` stay the +gateway commands they are today. + +## 2. What this pull stores + +This section is the storage rule, as D277 says. D277 keeps these values +in this pull. D278 corrected source, time, and score direction. D279 corrects units, day +windows, sleep bounds, identity encoding, reported records, and child +withdrawal. D280 corrects the root record type, numberless calculation +inputs, recovery scales, required ids, workout provenance, hydration, +and the archive of a refused original. D281 corrects the migration +dependencies, the command counts, the archive capsule, and null-source +report routing. D282 corrects when the archive reads the database, and +the failed-init sentence. D283 stores a workout the person typed as a +workout session. D284 keeps a body skin-temperature time unknown when the +response does not say it is an instant. D285 keeps a finite +`hr_recovery`, including zero and a negative number. D286 keeps the +current manual-session calculation rule. D287 stores the live +workout list and detail as originals. D288 is the live-read procedure. +D289 keeps each vendor object whole. An earlier draft +left day values, the heart-rate stream, summaries, and workout segments for +a later version. That draft is superseded. File imports stay. The Garmin pull stays. A Junction pull is proposed as +2.3.0. Automatic sync, retries, token refresh, and backfill are proposed as +2.4.0. None of those numbers is adopted. This release does not add its +own token refresh. A live read can still make the server refresh one, as +section 2 says. This release adds one module for +this server. It does not add a connector interface. + +This pull stores the representations Open Wearables 0.11.0 returns for one +user. A ranged read stores that range. Body does not. A returned number +keeps the server's unit. A returned null stays absent and is not stored as +zero. A returned zero stays zero, except a point quantity whose rule still +requires a positive number. `hr_recovery` is not one of those quantities. +A finite zero and a finite negative `hr_recovery` stay. `temperature_deviation` +stays signed. Other points stay positive. A row the server did not return is not +labeled provider-unavailable. Priority selection, a day-row pick, and a +rollup can omit a stored row from the response. That omission is unknown +here. It is not a null, and it is not a refusal. `left_out` counts only a +row the server returned and this program refused. + +The promise is the returned object. It is not a copy of the Open Wearables +database, and it is not every device on a route that selects one source. +Sleep events, workouts, and raw and day timeseries send +`filter_by_priority=false` where that parameter exists. Sleep, activity, +and recovery summaries have no such parameter. Their services select a +source. This pull does not send a priority switch and does not change the +server's priority. Activity summaries also add together data sources that +share provider, writer, model, and type +(`series_aggregate_repository.py`, `daily_activity`). The stored source is +the source object on the response. It is not a receipt that every +contributor was that device. + +The twelve reads, in order, use these paths under +`/api/v1/users/{user_id}`: + +| Read | Path and query | Response and end | What the time means | +|---|---|---|---| +| `sleep` | `/events/sleep`. `start_date`, `end_date`, `limit`, `cursor`, `filter_by_priority=false`, `include=stages` | Cursor page. Ends at `has_more: false` | Session start and end | +| `workouts` | `/events/workouts`. dates, `limit`, `cursor`, `include=zones`, `include=segments`. No priority parameter | Cursor page. Ends at `has_more: false` | Session start and end | +| `timeseries_raw` | `/timeseries`. `start_time`, `end_time`, `limit`, `cursor`, `resolution=raw`, `filter_by_priority=false`. `types` omitted | Cursor page. Ends at `has_more: false` | Sample `timestamp` | +| `timeseries_day` | `/timeseries`. Same, with `resolution=1day` | Cursor page. `limit` counts periods, not rows. Ends at `has_more: false` | Server calendar window, not the provider's original interval | +| `sleep_summary` | `/summaries/sleep`. dates, `limit`, `cursor`. No priority parameter | Cursor page. Ends at `has_more: false` | `date`, plus main-sleep bounds only on the fields named below | +| `activity_summary` | `/summaries/activity`. dates, `limit`, `cursor`. No priority parameter | Cursor page. Ends at `has_more: false` | `date` only | +| `recovery_summary` | `/summaries/recovery`. dates, `limit`, `cursor`. No priority parameter | Cursor page. Ends at `has_more: false` | `date` only | +| `health_scores` | `/health-scores`. dates, `limit`, `offset`. No category or provider filter | Offset page with `pagination.has_more`. Ends at `has_more: false` | Score `recorded_at` | +| `meals` | `/events/meals`. dates, `limit`, `cursor` | Cursor page. Ends at `has_more: false` | Meal `timestamp` | +| `cycles` | `/events/menstrual-cycles`. dates, `limit`, `cursor`. The service clears `end_datetime` | Cursor page, then the local start rule below. Ends at `has_more: false` | Cycle `start_time` and `end_time` | +| `personal_record` | `/personal-record`. No dates | One object. The top-level `user_id` is removed before the privacy scan and is not stored | No measurement time | +| `body` | `/summaries/body`. No dates, no limit. `average_period` and `latest_window_hours` omitted, so the server uses 7 days and 4 hours | One `BodySummary`, or JSON `null`. `null` is an empty snapshot, not a bad page | Current snapshot. Not the requested range | + +A cursor page is a JSON object whose `data` is an array and whose +`pagination` is an object with boolean `has_more`, checked before mapping. +An offset page is the same, and it has no `next_cursor` requirement. Body +and the personal record are not those envelopes. A cursor rule applied to +them is a failed read. Health-score `metadata` is not a record. + +The menstrual-cycle service sets `end_datetime` to null so a predicted +future end is not dropped. This program still sends the requested dates. +Before mapping, it keeps a cycle whose start falls in the requested range +and keeps that cycle's end as sent, including an end after the range. For +date bounds, the date is the `YYYY-MM-DD` at the start of `start_time`, +with no timezone conversion, and the dates are inclusive. For timestamp +bounds, the start instant is greater than or equal to `--from` and less +than `--to`. A start that cannot be compared, because it has no offset, is +`left_out`. It is not given `Z`. A start after the range is not stored and +is not `left_out`. Paging continues until `has_more` is false. The server +still applies its own start bound, so a cycle that started before `--from` +is not returned. That is the server's filter. + +A page over the response cap, `MAX_PULL_RESPONSE_BYTES` (10 MiB), is not +mapped. On a cursor or offset read, the same +cursor or the same offset is sent again with `limit` halved, down to 1. +The discarded response writes nothing and does not advance the cursor or +the offset. A transport failure is not retried. Day `limit` counts periods. +A `limit` of 1 can still hold many rows, one for each source and series in +that period. The server also floors that period count at 1. If the minimum +page is still over the cap, the read is incomplete. The message names the +read and, for timeseries, the resolution. It does not name a series type, +and it does not say one row was too large. Body and the personal record +have no limit. An oversized response fails that read and names the read. +Earlier committed pages stay. The pull does not drop a series, a segment, +or a location to stay under the cap. + +A device source uses the 2.1.0 sensor, `device_type|device|source`. Its +receipt rules in section 3 are unchanged. A sleep session or a workout +with `entry_source` `automatic` enters that source when it has a nonempty +`device_id`, or when it is id-less on a new source with no history. A raw +or day row enters that check only when the appendix class is a point, a +measurement sample, `vo2_max`, or one of the two Garmin scores. A missing, +null, or blank `device_id` on that row refuses the protected transaction +before any measured write. It is not classified `left_out` first. A valid +row beside it on the same page is not stored as a measurement. No id is +copied from another row. Intake, index, age, effort, and `hydration` do +not enter that check. A device id on those rows is original data. It is +not a receipt and it is not evidence the value was measured. + +`entry_source` `automatic` is a workout session on the device source, as +the paragraph above says. `entry_source` `manual` is a workout session +on the source whose `source_type` is `manual`. `field_basis.value` is +`entered_by_hand`. It is not a device measurement. A `device_id` the +server sent stays on the original object. It does not set +`device_binding`, and the workout is not stored on the watch's source. +The server workout id is the match key. A later pull of that same +workout updates the session. Name, type, start, end, distance, heart +rate, elevation, zones, and segments are stored the same way they are +stored on an automatic workout. `field_basis.activity_type` is +`aggregator_normalized`, because Open Wearables normalized the sport +name. The numbers on this session do not enter the eight range +calculations or `provider-period-summary`. `workout-drift` may use the +session's start and end as its window when the caller names that session. +The samples in that window still exclude `source_type` `manual`. +`query_measurements`, `query_series`, and `query_sessions` in +`src/store/query.rs` omit manual sources unless `include_manual` is true. +This pull does not change those three functions. Other record listings are not that switch. The session does not enter a device +baseline. `unknown`, JSON +null, and a missing `entry_source` are source reports of kind +`unknown_workout`. They are not a workout session, and they are not +manual. The original keeps null and absence distinct. Unknown is not +labeled manual, and it is not labeled automatic because a model or a +device id is present. A repeated server workout id that arrives as a +different kind or sensor refuses the protected page. The stored record +stays. The new interpretation is not written beside it. The text says +the classification changed and a rerun cannot choose. `ath correct` +remains the owner's way to replace the record. + +Sleep, workout, meal, cycle, and health-score objects need a `id` that is +a UUID string. Missing, null, blank, and any other shape refuse the +protected page before a source, a row, or hardware changes. The row is not +`left_out`. No empty or time-based id is invented. A valid neighbor on +that page is not stored. Each page of the command is its own preview and +apply, so only the failed page is refused, and earlier committed pages +stay. + +A new sensor is the prefix `ow1:` plus a JSON array. The array has no +spaces. A missing part is JSON `null`. An empty string and the text `-` +stay strings. JSON escaping keeps a colon, a quote, and a backslash +inside one part. Two different tuples therefore stay different sensors. +The legacy device sensor is not rewritten into this form. D181 still +escapes `:` and `\` when the sensor is placed in a match key. + +The array shapes are: + +- Summary or body: `["summary", family, provider, device, device_type, source, device_id]` +- Meal, cycle, or unknown workout: `["event", family, provider, device, device_type, source, device_id]` +- Reported series, including a row whose `source` is null: `["report", resolution, provider, device, device_type, source, device_id]`. `resolution` is `raw` or `1day`. +- Health score: `["score", provider]`. `provider` is the top-level author, + or JSON `null` when that field is null. The input `source` is not in + the array. +- Measured series with `source: null`: `["unattributed", "timeseries"]`. A reported series does not use this sensor. +- Archive originals: `["archive"]` +- Personal record: `["personal_record"]` +- Vendor originals: `["vendor_workout", provider]`. `provider` is the + provider name in the route path, such as `garmin` or `suunto`. + +The writer is `source.provider` when that string is nonempty. A health +score uses its top-level `provider` when that string is nonempty. The +personal record, a null-provider score, a measured series with +`source: null`, and a reported series whose provider is missing use the +writer `open_wearables`. That word names this route. It is not a device +maker and it is not an invented author. The vendor is omitted. +`source_type` is `connector`. These sensors do not establish +`device_binding`. Their history is not history of a device source. + +A health score never uses the unattributed timeseries sensor. A change +of its input `source` from null to an object, or the reverse, revises +the same score. The writer, the sensor, and the score id stay put. + +A null-source timeseries row has no sample id. A measured row uses the +unattributed sensor. A reported row uses the report sensor and does not +also get an unattributed record. The comparison is that one full match +key: writer, sensor, resource, resolution, series type, UTC timestamp, +and, for a day row, `period_end`. A raw row at midnight and a day window +that starts at that midnight are different keys. Two rows with one key +are one normalized record only when the whole returned row is equal. A +different value, in the same page or a later confirmed call, refuses the +protected page. The stored normalized row stays. The text says the +rows are ambiguous and a rerun cannot choose the normalized row. `ath +correct` remains the owner's way to replace that row. A preview page +writes nothing, and the command memory holds device-binding facts only. +A preview therefore does not claim to see a null-source conflict from an +earlier preview page. A confirmed `--yes` page does see an earlier +committed page. + +File import and pull use one envelope table. The pull passes these +objects. A saved file imports the same object. A mapping that sends a +device row to another sensor, or that changes a series class in the +appendix table, fails before any request. + +| Resource | Envelope | Writer | Sensor | Anchor | Child | +|---|---|---|---|---|---| +| Sleep session | `{ "sleep": data }` | `source.provider` | legacy device | `sleep_session`, D181 id key | stage and duration fields on that session | +| Automatic workout | `{ "workout": data }` | `source.provider` | legacy device | `workout_session`, D181 id key | existing typed fields; untyped numbers are source reports | +| Manual workout | `{ "workout": data }` | `source.provider` | not the device sensor | `workout_session` on the manual source, server id | same typed fields, zones, and segments as an automatic workout | +| Unknown, null, or omitted `entry_source` | `{ "workout": data }` | `source.provider` | `ow1` event | `source_report` `unknown_workout`, server id | none. The original object is the record | +| Measured raw series with `device_id` | timeseries object, `resolution` `raw` | `source.provider` | legacy device | the raw class in the appendix, D181 time key | none | +| Measured raw or day series, source present, no `device_id` | timeseries object | `source.provider` | legacy device, then the protected page is refused | no measured row. Section 2 may archive the original | none | +| Reported series, source present or null | timeseries object | `source.provider`, or `open_wearables` when that string is missing | `ow1` report only | `source_report`, appendix subject | none. The amount is the reported pair | +| Measured series, `source` null | timeseries object | `open_wearables` | `ow1` unattributed only | the raw class, full match key | none. An unequal payload refuses the protected page and may be archived | +| Day series | timeseries object, `resolution` `1day` | same as the raw row | same as the raw row | window form in the appendix. Key adds `1day` and `period_end` | none | +| Sleep, activity, or recovery summary | `{ "sleep_summary": data }`, `{ "activity_summary": data }`, or `{ "recovery_summary": data }` | `source.provider` | `ow1` summary | `source_report` subject `object`, date | one measured child per numeric field, field path in the key | +| Body | the object | umbrella `source.provider`, or `open_wearables` when it is missing | `ow1` summary, family `body` | `source_report` subject `object` | slow-changing weight, height, fat, and muscle are time-unknown provider summaries; averaged heart rate and HRV use the server window; body temperature and blood pressure use their own times; skin temperature is time-unknown; age and BMI are source reports | +| Health score | `{ "health_score": data }` | top-level `provider`, or `open_wearables` | `ow1` score | `provider_score` when the scale table has a finite range, otherwise `source_report` | none. Components stay on the record | +| Meal | `{ "meal": data }` | `source.provider` | `ow1` event | `source_report` subject `object`, meal id | one `source_report` per numeric field path | +| Cycle | `{ "cycle": data }` | `source.provider` | `ow1` event | `source_report` subject `object`, cycle id | one `source_report` per numeric reported length | +| Personal record | the object after `user_id` is removed | `open_wearables` | `ow1` personal | `source_report` subject `personal_record` | none | +| Vendor workout | the vendor envelope in the vendor section below | `open_wearables` | `ow1:["vendor_workout", provider]` | `source_report` kind `original`, subject `vendor_workout`. The key ends with the provider and the vendor id | none. The whole envelope is the record | + +`source_report` is not one of the seven measured record types in SPEC +section 5.4. It has a source, so it is not an athlete report and it is +not a nutrition entry. Nutrition entries have no source. D161 still says +a mapping cannot turn a personal report into a measured record. A source +report stores that report without making it a measurement. The eight +range calculations in `src/calculate/range.rs`, `provider-period-summary` +among them, do not read it. Step 7 creates the `source_reports` table. Value and unit are both present or both absent. +`report_kind` is one of `intake`, `account`, `predicted`, `code`, `text`, +`unknown_workout`, `index`, or `original`. Gender uses +`account`. It is not copied into `sex` or the athlete profile. The +receipt still adds no column. + +One source report has this JSON shape. Extra fields are refused. + +```json +{ + "source_id": "record id of the source", + "report_kind": "intake", + "subject": "hydration", + "provider_record_id": "optional server id", + "reported_at": "optional UTC timestamp", + "input_timestamp": { + "timestamp_text": "the server timestamp, as sent", + "utc_offset_text": "the offset at the end of that text", + "utc_offset_meaning": "meaning_not_documented", + "timestamp_basis": "source_offset_timestamp" + }, + "provider_reporting_periods": [], + "amount": { + "input_value": 250, + "input_unit": "mL", + "standard_value": 250, + "standard_unit": "mL" + }, + "received_at": "when this program first stored it", + "received_at_basis": "import_time", + "supplied_fields": {} +} +``` + +`amount` is optional. When it is present, both input fields and both +standard fields are present. It is a reported pair. It is not a measured +`SourceValue`, and `field_basis` is absent. A day report omits +`reported_at` and uses `open_wearables_reporting_window` for the server's +timestamp and `period_end`. Kind `original` omits `amount` and omits +reporting periods. `input_timestamp` is the receipt that `input_receipt` +in `src/import/mapping.rs` writes for a timestamp text. A `Z` text is +`source_instant` with `documented_recording_offset`. Any other offset is +`source_offset_timestamp` with `meaning_not_documented`. When the server +gave no time, it is `missing_timestamp_receipt` in +`src/import/candidate.rs`. `received_at_basis` is `import_time`, as every +2.1.1 mapped import writes. A vendor original's start follows the rule in +the vendor section below. The record is registered on `RecordType`, the +current and revision unions, the package schema, the table description in +`src/store/encode.rs`, repair, and the root SQL check. It is not added to the seven measured types or to +the point, sample, or session readers. + +Match keys for the new records are the writer, the sensor, the resource, +the server id or the date or the body group, and the subject. The anchor +subject is `object`. A child subject is the field path, one key part, so +`nutrients.dietary_sugar` and `calories_kcal` do not collide. Two meals +at one timestamp stay two records because the meal id differs. Legacy +device keys are unchanged. + +The original server object is stored on the anchor, in `supplied_fields`, +including nulls, text, booleans, codes, and nested objects. A normalized +number is a child. Its `input_value` and `input_unit` are the server's +number and unit. `supplied_fields` hold that leaf. The appendix table is +the mapping for all 141 series, raw and day. `standard_value` equals +`input_value` except for `walking_step_length` and `running_stride_length`. +Those quantities are metres. The server sends centimetres, so +`standard_value` is `input_value / 100`. A 70 cm step is 0.70 m. A 120 cm +stride is 1.20 m. The other aliases change the unit text and not the +number: `percent` to `%`, `celsius` to `°C`, `degrees` to `deg`, `meters` +to `m`, `m_per_s` to `m/s`, `watts` to `W`, `met` to `MET`, `minutes` to +`min`, and `ml_kg_min` to `ml/kg/min`. A new quantity uses that alias, or +the server's unit token when it has no alias. Existing quantity units are +not edited to match the server token. + +No day row is a measurement sample. The day `timestamp` is +`CalendarPeriod.of_date(...).start`. `period_end` is the next boundary. +`window_seconds` is null. Those bounds are the reporting window +`open_wearables_reporting_window` on a provider summary, a provider +score, or a source report. `recorded_at` is unset. `duration_ms` is unset. +The program does not turn the two bounds into a duration, so a 23-hour or +25-hour local day stays the server's two timestamps. The window is not +called the measurement instant. Integer `window_seconds` on a raw sample +sets `duration_ms` to that count times 1000. The original field stays. Raw `heart_rate` stays a sample at the +server timestamp. Day `heart_rate`, day steps, and day speed are window +summaries. The two Garmin day scores stay scores on their existing +scales, with the window and without `recorded_at`. Raw points, raw +`vo2_max`, and the two raw Garmin scores keep their kinds and keys. Raw +`heart_rate_recovery_one_minute` is the point quantity `hr_recovery`, in +bpm. A finite value stays, including zero and a negative number. The +mapping's positive check and the v1 point check gain that exception +beside `temperature_deviation`. The exception is the point check in +`src/model/data.rs`. `packages/npm/src/schema.ts` is frozen compatibility +code and is not where this check is added. No table +is rebuilt for the check. The server series name stays in `supplied_fields`. The 2.1.0 import +key stays. A day row of that series is a window summary whose summary +type is also `hr_recovery`. Its key adds `1day` and `period_end`, so it +does not replace the raw point. A mapped file and a pull, in either +order, keep one record id. + +`computed_by: provider` sets basis `provider`. `computed_by: +open_wearables` sets basis `aggregator`. `computed_by: null` omits the +basis and keeps the null. A raw row that omits `computed_by` keeps the +2.1.0 basis `provider_or_aggregator`. That omission is not the JSON null. +The raw Garmin scores keep basis `provider` from the existing lines. +A health score with top-level `provider: internal` has basis +`aggregator`. A vendor name there has basis `provider`. A null provider +omits the basis. The device writer is not this author. + +A finite range in `constants/health_scores.py` is the only scale. The +text is `{min}-{max}`. The unit is `score` when the number is present. +Sleep is `0-100` for internal, WHOOP, and Samsung, and `1-100` for Oura, +Garmin, and Polar. Oura readiness is `1-100`. Polar readiness is `0-10`. +Oura activity is `1-100`. Garmin stress and Garmin body battery are +`0-100`. WHOOP and Suunto recovery are `0-100`. Polar recovery is `1-6`. +WHOOP strain is `0-21`. Polar strain has no finite maximum. A missing +category or provider is not given a scale. That score is a +`source_report`. The number stays in the original object. The raw series +`garmin_stress_level` and `garmin_body_battery` stay the existing score +lines. They are not these health-score rows. A null value uses the same kind as a present value for +that provider and category. Components are not extra scores. RMSSD and +SDNN stay separate. `RecoverySummary.recovery_score` uses the same range +table, with category recovery and the provider copied onto the summary's +`source`. Polar is `1-6`. WHOOP and Suunto are `0-100`. A provider that +is missing or absent from that table does not get `0-100`. That child is +a source report, and the number stays in the original object. The schema +prose that says the field is WHOOP-only and 0 to 100 is not the scale. +The number is not rescaled. A null uses the same kind as a present value +for that provider, and the child is withdrawn as section 2 says. The +anchor keeps the null. + +WHOOP recovery components can include `skin_temp_celsius`. The score +object keeps that component. `RecoverySummary` has no skin-temperature +field. A non-null SDNN is stored. RMSSD is not copied into it. The body +snapshot does not fill historical temperature. + +Sleep summary numbers are sums or weighted values across every non-nap +session in the selected source and date. `start_time` and `end_time` are +only the longest main sleep, or the service's minimum start and maximum +end when no main sleep exists. Those bounds stay inside the anchor's +original object. They are not a reporting period on `duration_minutes`, +time in bed, efficiency, stage minutes, or interruptions. Two main sleeps, +00:00–04:00 and 06:00–08:00, can sum to 360 minutes. That 360 stays on +`provider_date`. It is not placed inside the four-hour sleep. This +program does not re-sum the sessions and does not invent an interval. +Nap totals and the heart-rate, HRV, respiration, and blood-oxygen +averages are also date-only. The session list stays on the anchor. The +service can add a missing part as zero when it builds +`total_duration_minutes`. A returned zero stays zero. A null stays null. + +Activity fields are date-only provider summaries. `floors_climbed` is +described as calculated from elevation. `total_calories_kcal` can be the +provider total or a sum. The response does not say which, so the basis +stays `provider_or_aggregator`. Intensity minutes can be returned as zero +where the service fills a missing key with zero. + +Body is the current snapshot. It is not the requested range. The anchor +is a `source_report`. Weight, height, fat, and muscle are provider +summaries with `timestamp_missing_reason: not_provided_by_source`, no +`recorded_at`, and no borrowed window. Age and BMI are `source_report` +children. Age is calculated by the service. The child is a source report +and has no `field_basis`. BMI is not labeled measured. The averaged +heart-rate and HRV values are provider summaries on the server's +`period_start` and `period_end`. Those bounds are not copied onto the +slow-changing fields. Body temperature and blood pressure use their own +measured-at times when the server sends those times. Skin temperature +does not. The body service can put a day row's `period_start` into +`skin_temperature_measured_at` when no sample is in the latest window, +and the response has no field that says which one it did. The amount, +the unit, and that timestamp stay on the original object. The skin-temperature +child is time-unknown. It has no `recorded_at`. The program does not +decide by comparing timestamps, and it does not invent a window from +that timestamp. A raw skin-temperature sample and a day skin-temperature +window stay the series records they already are. A null time on body +temperature or blood pressure uses the time-unknown receipt. A null group +withdraws that group's existing children. It does not delete them because +a different request omitted the snapshot. + +Meal numbers, nutrient numbers, dietary series, alcoholic-beverage +counts, `hydration`, and the index, age, and effort series are +`source_report` records. `hydration` is intake. The server's amount and +millilitre sum are not a sample and not a day measurement. A device id +on that row does not make them measured. They are not provider summaries +and not nutrition entries. A +nutrient keeps the value and unit on its leaf. Cycle codes, predicted +lengths, booleans, text, and `pregnancy_snapshot` stay on the cycle +anchor. A numeric cycle length is also a `source_report` child, not a +measurement. On an automatic workout, a number that is not already a +typed session field stays in `supplied_fields` and is a `source_report` +child. It is not a provider summary. `intensity` stays under that name. +Segments and zones stay under the server's names. A manual workout is +the workout session in the table. It is not a source report, a point, or +a device receipt. + +The same returned object can change a child from a number to null, or +remove a nutrient. The mapper emits that child again with value and unit +both absent. The record id, the revisions, and the first `received_at` +stay. D182 copies the stored `received_at` onto the new revision. +`became_known_at` is when that revision was written. A later number +returns on the same child. A range that does not return the object does +not withdraw its children. A refused page writes nothing, so its +withdrawals are not written either. + +A page is one 2.1.1 import. `preview_route` in `src/import/provider.rs` +stages the page and matches it against the database in one read +transaction, at one database revision. It writes nothing. With `--yes`, +`ProviderPreview::apply` writes that plan in one write transaction. The +apply refuses the plan when the database revision moved after the +preview, when a corrected record's revision moved, or when a match key +now names another record. A protected refusal is found by the preview, +so the page is not applied. It does not become a successful pull. The +archive is pull-only. `ath import --mapping` uses the same protected +envelopes and the same refusal, and it does not build an archive. A +refused file import keeps no original. + +Before the preview, the pull checks the page itself. The order of +the rows does not matter. The privacy scan is first. A hit builds +no preview. A missing or malformed required UUID, a supplied +field whose name is not allowed, and any other decoded-field failure are +the same kind of check. They use the returned JSON. They do not use the +database. One such failure builds no preview. A timeseries row +has no required UUID. A query-bucket `left_out` row is not one of these +failures, and it is not archived. + +The database facts are read in the page's matching step, inside the read +transaction above. The read covers every row on the page, including a row +the mapping would leave out. For each named source it reads the receipt, +the binding, deletion, and history, and history includes tombstones. For +each named record and import key it reads deletion, the current revision, +and, for a workout, the stored kind. For each null-source full key it +reads the stored payload. That set of facts is the safety snapshot. It +belongs to the database revision the preview read. The apply refuses a +moved revision, so a page is never written against facts it did not read. + +One database veto anywhere in that snapshot refuses the protected page. +The vetoes are a conflicting device id, unbound history, a malformed +receipt, and a workout kind that differs from the stored record. The +archive is not attempted after a veto. A missing device id on a +timeseries row is not this veto. + +Each refusal names what the owner can do, and the text says the same: + +- A conflicting device id. If the new device replaces the old one, the + owner runs `ath correct` on the source and sets `device_binding` to the + new id. Later rows from the new device are then accepted. A new row + replaces an old one only where both have the same match key, which + includes the time. The old device's rows stay on that source, and the + binding then names only the new id. A point carries no device id, so + the two devices' rows on that source can no longer be told apart. The + rebind is the owner's explicit merge of the two histories. The + source's history keeps the old binding, and `ath records show + --history` shows it. When the incoming id is missing, null, + or blank, 2.2 has no fix that keeps the source. Removing the key would make the + source unbound history, which is refused too. Deleting the source + leaves out every later row from it (D190). +- Unbound history. If one device wrote all of that history, the owner + runs `ath correct` on the source and adds `device_binding` with that + device's id. Nothing checks that claim. When more than one device wrote + it, 2.2 has no fix. Splitting that history is the later reconciliation. +- A malformed receipt. The owner runs `ath correct` on the source and + sets `device_binding` to the device's id as a nonempty string. +- A workout kind that differs from the stored record. 2.2 has no fix that + keeps the stored record. `ath erase` removes the record, its revisions, + and its import key, and the next pull stores the workout as a new + record of the new kind. Erase cannot be undone, and the skill describes + it as privacy removal. The refusal text says both. + +A deleted source or a deleted record is not a veto. A row whose source the +person deleted is left out, and the line says so (D190). A row whose +match key names a record the person deleted is left out, and the line +says so (D182). The rest of the page is written. These are the 2.1.1 +keyed-import rules, and a deleted row is never recreated. A deleted source +or a deleted record named anywhere on the page still forbids the archive +of that page. + +An owner correction is kept until the server's data changes. This rule +is new in 2.2.0. It covers every record on route `open_wearables`, from a +pull or from `ath import --mapping open-wearables`. Every other route +keeps D182 as it is. That scope is the plan's default, and the maintainer +still has to confirm it (section 10). An import writes each revision with basis +`provider_import`. The basis is the revision column +`record_revisions.became_known_at_basis`, which says how that revision +became known. The rule reads that column, not `changed_by`. An import's +`changed_by` is the tool actor `ath`. `ath grade` writes that same actor +when it corrects a link, with basis `local_write`, in +`src/prediction/grade.rs`. So `changed_by` cannot tell an import from +another write. A revision with any other basis is an owner correction +here. `ath correct` writes basis `local_write`, and a protocol write uses +the basis its caller gives. A package merge copies the package's +revisions with their own bases, in `merge_in` in +`src/package/restore.rs`. So a record merged without a conflict keeps its +import revisions as imports. Only a conflict the person resolved as +imported or corrected writes a new revision, in `resolve_in`, with basis +`package_merge` and the athlete as actor. Choosing the local side writes +nothing. That revision is a merge choice. It counts as +an owner correction, and the counts in section 1 also name it as a merge +choice. A native restore copies each revision's basis, so a restored +database keeps the same answer. When a page's candidate names a stored +record by its import key, and that record is not deleted: + +1. A candidate equal to the current record writes nothing, as in 2.1.1. +2. When the current revision has basis `provider_import`, a different + candidate replaces it, as in 2.1.1 (D182). +3. When the current revision is an owner correction, the candidate is + compared with the newest revision whose basis is `provider_import`. + Equal means the server has not changed that record since an import last + wrote it. Nothing is written, and the correction stays current. + Different means the server's data changed. The candidate replaces the + correction, and that counts as one `owner_corrections_replaced`. When + the correction was a merge choice, it also counts as one + `merge_choices_replaced`. The correction stays in the record's + history. A record with no `provider_import` revision is replaced and + counted the same way. + +Body-snapshot records rarely keep a correction. The server averages heart +rate and HRV over a window that ends at the request, 7 days and 4 hours +by default, and the body records' match keys have no date. So the +snapshot almost always differs from the last pull. A correction of the +snapshot's original, or of a value the server averages, is replaced on +almost every pull, and the count shows it. + +The comparison is the 2.1.1 comparison, with the compared revision's +`received_at`. Section 4 withholds credential values before the candidate +is built, so a withheld value is the same marker on both sides. A +protocol or library caller chooses the basis freely, so a write that +chooses `provider_import` counts as an import revision. + +The archive is allowed only when that snapshot has no veto, names no +deleted source or record, and has one of these eligible facts: a +device-targeted series row whose source has no device id, or a +null-source series row, measured or reported, whose full match key has a +different payload in this page or already stored. An eligible row does not +authorize the archive when a veto is also on the page. A confirmed command +keeps the snapshot's database revision for the archive. A preview never +applies an archive. + +When the archive revalidation below matches the safety snapshot, the +archive stores one capsule per returned series row on that page, not a +query-bucket row and not a non-series row. A workout or a meal on that page is not a capsule. A +later page that does not refuse can store it. The capsule is: + +```json +{ + "resource": "timeseries", + "resolution": "raw", + "row": {} +} +``` + +`resolution` is the response's `metadata.resolution`, copied. It is not +inferred from `window_seconds` or `period_end`. `row` is the original +series object, unchanged. The capsule is the same object for a pull and +for a later native export and import. Kind is `original`. There is no +`amount` and no reporting period. The number stays inside `row`. The +match key is the writer, the archive sensor, and the SHA-256 of the +canonical capsule, with keys sorted and no extra whitespace. The same +capsule is one record. A raw capsule and a day capsule are different +even when the row bodies match. The hash is not a sample id. This plan +does not claim that two different capsules cannot hash equal. If the key +is already stored and the stored capsule differs, the archive fails before +it writes and does not revise the old capsule. + +The archive source uses writer `open_wearables`, sensor `ow1:["archive"]`, +and `source_type` `connector`. The receipt operations are not called, and +`device_binding` is not written. + +The archive is its own preview and apply, after the protected refusal. Its +preview stages one capsule per returned series row. It matches them +against the archive source and each target capsule, including a deleted +one. It goes ahead only when its database revision is still the one the +protected preview read. Otherwise `archive` is `not_attempted` and nothing +is written. Its apply refuses a moved revision, as every 2.1.1 apply does, +and `archive` is then `not_attempted` too. + +The archive does not read the safety facts a second time. Every write to a +database moves its revision: `Store::apply` in `src/store/write.rs`, +`ProviderPreview::apply`, repair in `src/store/repair.rs`, restore in +`src/package/restore.rs`, and erase in `src/package/erase.rs` all advance +it. So an unchanged revision means the binding, the history, the +tombstones, and the vetoes are the ones the protected preview read. The +fetched payload is not stored under the archive source, and it is not +given a new identity. + +A deleted archive source leaves every capsule out and is not recreated +(D190). A deleted capsule is left out and is not replaced (D182). The +archive refuses its own plan when that plan would revise a stored capsule, +so a stored capsule is never revised. If the pull cannot name this bounded +set for a row, it does not archive the page. There is no retry. A page that +committed an archive still sees that archive. A deletion after this archive +commits is a later command. + +`protected_write` is `committed` or `refused`. `archive` is +`not_attempted`, `stored`, `unchanged`, or `failed`. `committed` is the +protected counts. `archive_committed` is the archive counts. A record is +not in both. `written` follows section 1 and is not set by the archive +alone. `database_changed` is true when this command's archive apply +committed a new source or a new capsule, and it stays true if an earlier +page already changed the database. A later refusal does not clear the +earlier counts. When the archive stores N new capsules and the command +has no protected change, the text is `Protected write refused; N +originals archived; database changed; pull incomplete.` A repeat that +stores nothing says `0 originals archived` and says the database is +unchanged only when no earlier page changed it. The unchanged text is +`Protected write refused; 0 originals archived; database unchanged; pull +incomplete.` After an earlier change it is `Protected write refused; 0 +originals archived; database changed; pull incomplete.` A third payload +adds its own new count and does not replace the earlier capsule. If the +archive apply fails, its transaction writes nothing, `archive` is `failed`, +the protected refusal remains, earlier commits remain, the success +sentence is not printed, and the exit is nonzero. The text is `Protected +write refused; archive failed; database unchanged; pull incomplete.` +After an earlier change it says `database changed`. It does not print a +partial archive count. When the archive is `not_attempted` after a +protected refusal, the text is `Protected write refused; archive not +attempted; database unchanged; pull incomplete.` After an earlier change +it says `database changed`. That result adds no archive count. A +preview, including `--json` and `--json --yes`, applies neither the +protected plan nor the archive. `estimated_archive` comes from the +archive's own preview and is labeled estimated. + +A page of only reported series, with no device id, is an ordinary source +report write. It is not an archive, and it does not refuse the device +check. A normalized row is not revised from an archive. + +A provider summary or provider score may omit `value` only together with +its unit. One without the other is refused. Step 7 rebuilds both typed +tables so the pair can be null, copies every existing row, and keeps +record ids, `data_json`, import keys, revisions, tombstones, and reporting +periods. Scale on a provider score stays required. No number is invented. +The time-unknown summary is valid only with the missing-timestamp reason +above. + +The following are not requested. Each line is the reason. + +- Resolutions `1min`, `5min`, `15min`, and `1hour`. They are buckets built + at query time from raw samples. The raw samples are stored. +- Resolutions `1week` and `1month`. They are built from day rows. The day + rows are stored. +- Sleep totals, workout totals, and activity totals. They add up rows the + lists return. +- The data summary and the data timeline. They count stored rows. +- Accounts, sync, OAuth, webhooks, API keys, config, uploads, and every + `DELETE`. They are not health readings. The API key, the server address, + and the user id are not written into the athlete record. `/sync` and + `/sync/historical` are not called. The connections list is called only + when `--vendor-workouts` is on. + +### Live vendor workouts + +`--vendor-workouts` is off by default. Off, the command makes no request +to `/api/v1/users/{user_id}/connections` and no request to either live +workout route. Preview and `--json` without the flag make those zero +requests. On, the same preview and `--json` read the connections list and +each active provider's list. They make no detail call, write nothing in +this database, and print `vendor requests were made`. "Nothing stored" +and "nothing written" always mean this database. The server can still +change, as the next paragraph says. + +A preview's `details` counts are estimates from the stored originals, and +they are under the `estimated` key. `would_detail` counts the ids that +`--yes` would detail now, and `deferred` the ids past the budget. `kept` +and `not_available` are counted as `--yes` would count them, and so is +an `unusable_name` or `too_deep` refusal whose list object is unchanged. +`failed`, +`mismatch`, `thinner`, and `too_large` are zero in a preview, and so is +any other `refused`, because only a detail call can find them. The +preview says so: `preview +made no detail calls; detail failures, size limits and refusals are only +known after --yes`. A preview and then `--yes` read each provider's list twice. That is +one extra call for most providers, every window again for Garmin, and +every page again for Suunto. To read each list once, run `--yes` without +a separate preview. The preview and the flag's help say so. + +A live call can change the server. `api_client.py` at +the pinned commit can refresh a vendor token and save it, revoke a +connection when refresh is missing or auth has failed for a day, and emit +`connection.revoked`. It writes the Redis keys `token_refresh_lock` and +`provider_auth_failing_since`. On HTTP 429 it sleeps 15, then 30, then 60 +seconds, up to three retries, so one request can wait about 105 seconds. +This pull does not add its own retry. It does not add a vendor token or a +new scope. The server may still do the work above while answering the GET. + +Every run with the flag says this in three sentences, before its first +live request. The server may refresh and save vendor tokens. It may revoke +a connection. It may wait about 105 seconds on a rate limit. A preview and +a `--yes` run print the sentences. A `--json` run puts them in +`vendor_workouts.notice`, so its output stays one JSON value. The flag's +help text says the same. + +With the flag on, the pull reads the connections list first. It checks +that each item's `user_id` is the selected user. Any other value refuses +the list, because it is not this user's list. The pull then keeps only +`provider` and `status` from each item and drops every other field, +including `linked_user_ids`, which holds other users' ids. The list is +never stored. Nothing from it is printed except a provider name from the +table below and a status. So the privacy scan in section 4 does not run on +this list, and the selected user id inside it does not refuse it. A +refused list makes every provider `not_attempted`, and the vendor read is +`incomplete`. + +A provider is called only when its item has `status` `active`. The +pinned `ConnectionStatus` also has `revoked` and `expired`. Those +providers are `not_attempted`, and their line shows that status. They are +never called, because a call could make the server try a refresh or a +revoke. A provider with no item is `not_attempted`, and its status is +`null`. A status the pin does not define is not active, and it is printed +as `unknown status`. + +The order is fixed: Garmin, Polar, Suunto, Whoop, Fitbit, Oura, Strava, +Withings, Sensorbio. An active provider with no live list method is +`not_attempted`. That is not a failure. One provider's failure leaves its +line `incomplete`, and the other providers still run. Apple, Samsung, +Health Connect, Ultrahuman, and Google Health have no live list method. +Their stored workouts still come from `/events/workouts`. + +Live requests go one at a time. Each starts at least one second after the +previous live request started. The connect timeout is 30 seconds. The read +timeout is 360 seconds. The server's own provider timeout, +`provider_request_timeout_seconds`, defaults to 30 seconds. So one GET can +take four attempts and three waits, about 225 seconds, plus any token +refresh under the server's lock. The longer read timeout lets the server +finish those retries first. If a live request still times out, the server +may still be working on it. The pull then sends no other request to that +provider in this command, so two requests to one provider never overlap. +That provider is `incomplete`. The next provider still runs, and it uses +a different vendor account and limit. An HTTP 429 from a live request +stops that provider the same way. The server has already waited and +retried three times, so the vendor's limit is spent. An HTTP 401 stops +that provider the same way. The server has already reloaded the vendor +token, or refreshed it, and tried once more. Each later request would +make it do that again, and a refresh the vendor rejects revokes the +connection. No later list call, window, or detail call goes to that +provider in this command. After a 401, the provider's line says, for +example, `Garmin answered 401: reconnect the provider in Open Wearables +if this repeats`. The detail call that got 429 or 401, or that +timed out, counts as `failed`. Every id still due a detail call by the +order below counts as `deferred`, and a later command details it. An id +that was due no call keeps its own count, such as `kept` or +`not_available`, and so does a Garmin id due only for its 30-day recheck. +What the provider already returned is still written as +that provider's page: the list objects, and the details already fetched. +A later Garmin window +after a 429, a 401, or a timeout is not sent, unlike a window that failed +another way. A server whose provider timeout is +raised can outlast this timeout. The same rule covers that case. The +stored reads keep 30 seconds to connect and 120 seconds to read, the values +`src/runtime/garmin_pull.rs` uses. + +Budgets keep one command inside the providers' limits: + +- The pace above keeps this command at 60 live requests a minute or + fewer. The review cited about 100 a minute for Garmin. This study did + not find that number in Garmin's public docs. +- Garmin is read in windows of exactly 82,800 seconds, 23 hours, one + call each. Every window is sent. A one-year range is 381 or 382 + windows, so it takes more than six minutes before any detail call. +- A command makes at most 100 detail calls to one provider, and at most 20 + to Strava. Ids past the budget are `deferred`. The next paragraphs say + which ids go first. +- Strava's limit is per application, so the deployment's own sync shares + it. Strava's rate-limit page, fetched 15 November 2026, gives a default + of 100 read requests per 15 minutes and 1,000 a day. Strava calls them + non-upload requests. One list call and 20 detail calls are 21 + requests. The server tries one request at most four times. It retries + a 429 up to three times, and a 401 once after it reloads the token. + The pull sees only the last answer, and it stops calling Strava after + a final 429. In the usual case nothing is retried, and one `--yes` + command sends 21 Strava requests. When only the last request was + retried, it sends 24, or 25 after a token reload. That still leaves + about 75 for the deployment's own sync in the same 15 minutes. + The ceiling is 84, four tries for each of the 21 requests, because the + pull cannot see a retry that ended in success. A preview first adds one + list call. The Strava line says that its limit is shared. + +The routes are +`GET /api/v1/providers/{provider}/users/{user_id}/workouts` and +`GET /api/v1/providers/{provider}/users/{user_id}/workouts/{workout_id}`. +At the pinned commit both return the provider's raw response. The server +does not reshape it. The table below is the whole provider logic. Every +live request has the 30-second connect timeout and the 360-second read +timeout above. + +| Provider | List unwrap | Id | Start | Detail key | Detail unwrap | Detail fields | Budget | Read timeout | +|---|---|---|---|---|---|---|---|---| +| Garmin | the JSON array | `activityId` | `startTimeInSeconds`, Unix seconds | `activityId` | the object | none named | every window; 100 details | 360 s | +| Polar | the JSON array | `id` | `start_time`, text with no offset | `id` | the object | `samples`, `zones`, `route` | 1 list; 100 details | 360 s | +| Suunto | `payload` | `workoutId` | `startTime`, Unix milliseconds | `workoutKey`. No call without it | `payload` | none named | at most 100 list pages of 100; 100 details | 360 s | +| Whoop | `records` | `id` | `start`, text with offset | `id` | the object | none named | 1 list; 100 details | 360 s | +| Fitbit | the JSON array. The method reads `activities` | `logId` | `startTime`, text with offset | no detail call | none | none | 1 list | 360 s | +| Oura | `data` | `id` | `start_datetime`, text with offset | `id` | the object | none named | 1 list; 100 details | 360 s | +| Strava | the JSON array | `id` | `start_date`, text with `Z` | `id` | the object | `laps`, `splits_metric`, `splits_standard`, `segment_efforts`, `best_efforts`, `map` | 1 list; 20 details | 360 s | +| Withings | the JSON array. The method reads `series` | `id` | `startdate`, Unix seconds | no detail call | none | none | 1 list | 360 s | +| Sensorbio | `data[].activities[]`. The parent is kept as `list_parent` | `id` on the nested activity | `start_time`, Unix milliseconds | no detail call | none | none | 1 list | 360 s | + +- Garmin. The pull reads the range in windows on a fixed grid. Each + window starts at a multiple of 82,800 seconds after the Unix epoch and + lasts 82,800 seconds. The first window holds the range's first second, + and the last window holds its last second. So the first can start up + to 23 hours early, and the last can end up to 23 hours late. Every + command uses the same grid, so a window from one command either equals + a window from another or does not overlap it. The pull + sends `summary_start_time` and `summary_end_time` as integer Unix + seconds. The server puts those values in `uploadStartTimeInSeconds` and + `uploadEndTimeInSeconds`, so a window selects by upload time, not by + start. Each window ends where the next begins. The last window can end + after the command runs, as a date `--to` of today already does. The + pinned server sends a window it does not split to Garmin with both + numbers unchanged, so Garmin gets the grid as sent. It splits a window + it sees as longer than 24 hours, and it drops a failed piece without + saying so. It measures the window in naive local time. When the + server's clock moves forward an hour, as in spring, 24 real hours read + as 25 local hours, so a 24-hour window would be split. When the clock + moves back, as in autumn, 24 real hours read as 23. A 23-hour window + reads as 24 hours at most, so it is never split where the clock moves + by one hour. A zone that moves its clock by two hours, such as + `Antarctica/Troll`, can make a 23-hour window read as 25 hours. The pull + does not know the server's zone. + A failed window makes Garmin `incomplete`, and later windows still run. + The pull calls Garmin detail at the pinned path, + `/wellness-api/rest/activities/{activity_id}`. That path is not in + Garmin's public docs. This study looked and did not find it, so the path + may not exist. The first Garmin detail call in a command is a probe. + When it answers HTTP 404 or 501, the pull makes no other Garmin detail + call in that command. The probed id counts as `not_available`. Each + other id still due a detail call counts as `deferred`, because it was + not asked. An id due only for its 30-day recheck keeps `not_available` + instead, as the detail order below says. Every list object is stored, + Garmin stays `completed`, and its line says `Garmin detail unavailable + (HTTP n); list objects stored`, with the status the probe got. The + deferred count on that line reads `N deferred (not asked: detail + unavailable this run)`, so the person does not wait for those details. + So a missing path costs one detail call in a command. When the probe + answers any other error status, except 401 and 429, the pull also makes + no other Garmin detail call, and the line is the same. Every id due a + call counts as `deferred`, the probed id included, except an id due + only for its 30-day recheck. A status such as 400, 403, or 405 does not + show that the activity has no detail, so the next command probes the + same oldest id again. After a 4xx status Garmin stays + `completed`. After a 5xx status Garmin is `incomplete`, and the exit is + nonzero, because the server reported a fault. After a 2xx answer to the + probe, the later Garmin detail calls go on. A later Garmin detail + that answers 404 or 501 is `not_available` for that id, and the next id + is still called. Any other failed Garmin detail is `failed`, and Garmin + is `incomplete`. A 401, a 429, or a timeout stops Garmin as above. A 404 + or 501 on a Garmin list window is not this rule. It fails that window. + Every other provider's detail 404 is `failed`. The pinned client passes + a vendor's status through unchanged, and the route answers 501 only for + a provider it has no workout method for, so this study cannot tell a + missing path from a missing activity. This is the plan's stated + default. The maintainer still has to confirm it (D288). +- Polar. The list sends `samples`, `zones`, and `route` false, the route's + default, so the list stays small. Detail sends all three true. A list + over the response cap fails that list, because the route has no smaller + page. +- Suunto. The list sends `since` as the requested start in Unix + milliseconds, `filter_by_modification_time=false`, and `limit` 100, and + pages `offset` until a short page. False means creation time. A page + over the response cap is asked again with a smaller `limit`, down to 1. + One command sends at most `MAX_SUUNTO_LIST_REQUESTS`, 100 Suunto list + requests, counting those smaller retries. When the cap stops a list + whose last page was full, Suunto is `incomplete`, `more` is true, and + the objects already read are still written. Each page waits for the + one-second pace, so the cap also bounds the list to about 100 seconds. + A later `--from` reads fewer pages, because `since` is the requested + start. + The record key is `workoutId`. Detail is called at `workoutKey`. A list + object with no `workoutKey` gets no detail call, and its detail is + `not_available`. The pinned detail method calls + `/v3/workouts/{workout_key}`, and nothing this study read shows that + Suunto accepts a `workoutId` there. Detail unwraps + `payload`. A detail matches when its `workoutId` or its `workoutKey` + equals the list object's. The pinned `WorkoutJSON` model has no + `workoutKey`. The pinned tests and Suunto's own API use it, so the list + object may carry it. Detail sends no `extensions` parameter. +- Whoop. One call. The method caps `limit` at 25. The response's + next-page field is `next_token`. The request parameter is `nextToken`, + and the route does not send it. `more` is true when the response has a + `next_token` that is not null. +- Oura. One call with no date and no `next_token`. `more` is true when the + response has a `next_token` that is not null. +- Strava. One list call at page 1. `per_page` is the server setting + `strava_events_per_page`, default 200. `more` is true when the page + length equals `per_page`. The detail object also carries `embed_token`. + Section 4 withholds that value. +- Fitbit. The list uses the last 30 days when the route sends no dates. + Detail is not implemented and is not called. +- Withings. The list uses `pull_sync_lookback` or 30 days, widens each + edge by one local day, and pages inside the method. Detail is not called. +- Sensorbio. The method sends `last-timestamp` 0 and `limit` at most 50, + and it does not follow `links.next`. So it reads only the oldest 50 + entries. `more` is true when `links.next` is present. Detail is not + called. Each nested activity is one object. Its parent entry, without + the `activities` array, is kept beside it as `list_parent`, so the + parent's `timestamp` and `name` are not lost. + +Every returned original is stored, including one whose start is outside +`--from` and `--to`. The same rule is used for every provider. The count +is `vendor workout originals`. `range_complete` uses only the stored +ranged reads. Each live line names its limit, says whether that limit +covers the requested range, and sets `more` as the notes above say. Those +next-page values are not followed. The published route does not accept +them as the next request. `covers_requested_range` is false for every +provider in this pin. None of the live methods filter by the workout's +start inside `--from` and `--to`. + +The pull converts the range once for Garmin and Suunto, because their +parameters are numbers. A date `--from` is midnight UTC that day. A date +`--to` ends at midnight UTC after that day. That is the rule the Open +Wearables API introduction gives for a date-only bound. A timestamp bound +converts exactly. A fraction of a second rounds down for the start and up +for the end, so the windows cover the whole range. Garmin then widens the +range to whole grid windows, as the Garmin row above says. The stored +reads still send `--from` and `--to` unchanged. + +A vendor id is text. A JSON string is used as it is, unless it is empty. +A JSON integer is written in decimal. So `123` and `"123"` are one id and +one record. An integer above 9007199254740991 is refused. D213 stores every +number the way JavaScript does, so its digits would change. Any other +number, and any other JSON type, is refused as an id. An object that holds +an integer above that size anywhere inside it is refused for the same +reason. A refused object refuses only itself, and the count says why. Two +different objects with one id in one provider's response refuse both, +because the pull cannot tell which is right. Two equal objects are one. + +A vendor list object that holds a key named `__proto__` at any depth is +refused as `unusable_name`, and it gets no detail call. The import check +in section 3 refuses that key in any supplied field, and it fails the +whole import. So `src/runtime/vendor_workouts.rs` runs the same check on +each list object and each detail before the page is staged. When only +the detail holds the key, the clean list object is stored with +`detail_status` `refused`, `refused_by` `unusable_name`, and the key's +path in `refused_path`. The detail is not stored. A later command asks +for that detail again only when the list object changes, so the call is +not spent on every command. Only that object is refused, and the others +are written. The provider stays `completed`, as it does for the other +refused objects, because a rerun gets the same object. A refused list +object is not stored, so a later command reads it and refuses it again, +with no detail call. + +Each object refused this way is named in `left_out.examples`, inside the +20-line bound. The line gives the provider, the vendor id as a JSON +string or `no id`, the reason, and the JSON path of the key, in the form +the withheld paths use. For example: `polar "1002": unusable_name at +detail.samples[3].__proto__`. A refused detail is named the same way, +though its original is stored and its count is under `details`. + +Garmin is read in windows, and one activity can be in two windows when +Garmin received it again. A window selects by upload time, so the later +window holds the later copy. For Garmin only, an object in a later window +replaces a different object with the same id from an earlier window. The +earlier copy counts as `superseded` in `left_out`, and the later copy goes +through the detail rules. Equal copies in two windows are one object, and +nothing is counted. Inside one window, two different objects with one id +still refuse both as `duplicate_id`. + +Each Garmin envelope keeps the window its object came from, as +`upload_window`, so the same rule holds across commands. Take a Garmin +candidate that differs from the newest `provider_import` revision of its +original, when both have an `upload_window`. A window holds only objects +uploaded inside it, so the windows order the two copies: + +- The candidate's window ends at or before the start of the stored + window. The candidate was uploaded first. It counts as `superseded`, + and nothing is written. +- The candidate's window starts at or after the end of the stored window. + The candidate was uploaded later, and it is a change. +- A pull reads the stored window again. The candidate is a later read of + the same window, and it is a change. +- Any other pair of windows. They overlap, or they are equal in a mapped + import of saved envelopes, whose read time is unknown. The pull's grid + never makes such a pair, but a saved file can carry any window. The + order of the two copies is unknown. The candidate counts as + `ambiguous_window`, the stored copy is kept, and nothing is written. + +A `superseded` or `ambiguous_window` candidate is not a server change, so +it never replaces an owner correction. The stored-original read returns +the stored window, so the pull makes no detail call for that candidate. +When either side has no `upload_window`, this rule does not apply. The +rule runs in matching for route `open_wearables`, so a mapped import of +saved envelopes follows it too. + +Every comparison of a vendor original on that route leaves +`upload_window` out: the 2.1.1 equality test, the owner-correction rule, +and the difference test above. Garmin can return an unchanged object in a +later window, and a saved file can carry any window. So an unchanged +object read through another window writes nothing. The stored original +keeps the window it was stored with, and that window still holds its +upload. The owner-correction rule and the difference test also leave +`detail_checked_at` out, because only this program's clock changed it. +The 2.1.1 equality test keeps it, so a repeat 404 or 501 is written and +its 30 days start again. + +The start column names one field and how to read it: + +- Text with an offset or `Z`. The receipt is the one `input_receipt` in + `src/import/mapping.rs` writes. `reported_at` is that instant in UTC. +- Text with no offset, such as Polar's `start_time`. The receipt is the + one `offset_timestamp_receipt` in `src/import/candidate.rs` writes for + such text. `timestamp_text` is the text, and `timestamp_basis` is + `source_offset_timestamp`, the basis 2.1.1 writes for provider text with + or without an offset. `utc_offset_missing_reason` is + `not_provided_by_source`. The receipt has no `utc_offset_text` and no + `utc_offset_meaning`, because the 2.1.1 receipt check refuses a meaning + without offset text, so the helper drops the meaning it is given. There + is no `reported_at`, because the text names no instant. Polar's separate + `start_time_utc_offset` stays in `list`. This pull does not join the two. +- Unix seconds or milliseconds. The receipt keeps the digits as + `timestamp_text`, with `timestamp_basis` `source_instant` and + `utc_offset_missing_reason` `not_applicable`. `reported_at` is that + instant in UTC, with milliseconds. A new helper beside + `offset_timestamp_receipt` writes this receipt. It passes the 2.1.1 + receipt checks: a text has a basis, and the missing offset has a reason. +- Missing, or any other value. The receipt is `missing_timestamp_receipt`. + There is no `reported_at`. + +The start is stored and is not a filter. + +The pull withholds credential values, by the rule in section 4, in each +list object and each detail before it compares anything. The detail +order, the `kept` check, the thinner check, and the owner-correction rule +all compare withheld copies. So a Garmin list object whose +`userAccessToken` changed between pulls still equals its stored copy, and +it gets no detail call. + +For each listed id, the pull first reads the stored original, if there is +one. That read is crate-private and lives in `src/import/provider.rs`. It +returns whether the original exists, whether it is deleted, whether it +holds a detail, its stored `list`, and, for Garmin, its +`upload_window`. It reads the newest revision whose +`record_revisions.became_known_at_basis` is `provider_import`, not an +owner correction, so a person's edit does not look like a vendor change +and does not spend a detail call. + +The pull calls detail only when the provider has a detail call and its +budget allows. It spends the budget in this order. First come ids with no +stored detail that no earlier command marked `not_available`, +`too_large`, or `refused`. Then come ids whose list object differs from +the stored `list`. Then come ids an earlier command marked `too_large`, +or `refused` with `refused_by` `privacy_scan`. Last come Garmin ids that +a 404 or 501 marked `not_available` +at least 30 days before this command started, by their +`detail_checked_at`. An original whose current revision is an owner +correction is not in that last group, because a repeat answer would not +be written over the correction, and its time would never move. Each id +goes in the first group it matches. So an id that was `not_available`, +`too_large`, or `refused` and whose list object changed is in the second +group. Any other id marked `not_available` whose list object is unchanged +gets no detail call. It counts as `not_available` again. So does an id +`refused` as `unusable_name` or `too_deep`, which counts as `refused` +again. Inside each +group the oldest start goes first. An id without a start instant goes +last in its group, in list order. So a Garmin path that answers 404 +costs one detail call in a command, and only when some id is due a call. +An id whose original holds a detail and whose list object is unchanged +gets no detail call. A deleted original gets no detail call. A detail is +fetched again only when the list object changed. A provider that changes +a detail without changing the list object is not seen, and the line does +not claim it. + +A Garmin id that got 404 or 501 is asked again after 30 days, or sooner +when its list object changes. A repeat 404 or 501 writes the original +again with the new `detail_checked_at` and the stored `upload_window`. It +counts as `not_available` and as a changed original. An id in the last +group that this command does not ask, for any reason, keeps +`not_available` and its time. That covers a probe that stopped Garmin, a +401, 429, or timeout that stopped it, and a spent budget. The id does not +count as `deferred`, so a missing path does not rewrite those originals. +Any other `not_available` comes from a provider with no detail call or a +Suunto object with no `workoutKey`, so there is no call to make again. + +A list object and its detail are not read at the same moment. The pull +reads a provider's whole list first, then its details one second apart, +so a detail can come minutes after its list object. A one-year Garmin +range sends 381 or 382 windows, more than six minutes, before its first +detail. +The vendor can change the workout in between. A `kept` detail was read by +an earlier command. The envelope does not record when each part was read, +and the pull does not claim the two parts are one moment's copy. + +The detail must name the same id. A detail that names another id is a +`mismatch`, and it is not stored. + +What is written for one id depends on what this command got: + +- A new detail that is not thinner than the stored one. The original is + written with this list object and this detail. The id counts as + `stored`. +- A new detail that is thinner. Nothing is written for that id, and the + stored original stays. The id counts as `thinner`. A detail is thinner + when one of the provider's detail fields in the table is a nonempty value + in the stored detail and is missing, null, or empty in the new one. A + provider with no named detail field has no thinner detail. Garmin, + Suunto, Whoop, and Oura name none, so a new detail from them replaces + the stored one even when it has fewer fields. The stored detail is not + lost. It stays in the record's history as the earlier revision, and + `ath records show --history` shows it. The line does not + claim the new detail is complete. +- No new detail call, because the stored detail is current. The pull sends + the envelope with the stored detail, so the original counts as + `unchanged` and nothing is written. The id counts as `kept`. +- No new detail, and none stored. The original is written with the list + object alone. `detail_status` says why: `deferred`, `failed`, + `mismatch`, `not_available`, `too_large`, or `refused`. The id counts + under the same word. + `not_available` means the provider has no detail call, a Garmin detail + call for that id answered 404 or 501, or a Suunto list object has no + `workoutKey`. A + detail response over `MAX_PULL_RESPONSE_BYTES` is `too_large`, because + the detail route has no smaller page. A detail + that the privacy scan in section 4 refuses, because it holds the key, + the origin, or the user id, is `refused` by `privacy_scan`. A detail + with a `__proto__` key is `refused` as `unusable_name`. None of those + is stored, and each is counted on the provider's line. +- No new detail, but one is stored, and the list object changed. Nothing + is written for that id, and no revision is added. The stored detail + stays. The id counts as `deferred`, `failed`, `mismatch`, + `not_available`, `too_large`, or `refused`. + +A list-only object therefore never replaces a stored detail. A `failed`, +`mismatch`, or `too_large` detail, or one `refused` by the privacy scan, +makes the provider `incomplete`, and the exit is nonzero. A detail +refused as `unusable_name` or `too_deep` leaves the provider `completed`, +because a rerun gets the same detail. A `not_available` detail leaves the +provider `completed`. A `deferred` detail leaves the provider +`completed`, with the deferred count on its line, and the next command +details those ids first. A deferred id that the provider stops listing is +never detailed by a later command. The deferred count shows how many are +waiting. + +Each original is one envelope. The pull builds it, and a saved file holds +the same object: + +```json +{ + "provider": "suunto", + "vendor_id": "1001", + "start": 1767254400000, + "start_kind": "unix_milliseconds", + "list": { "workoutId": 1001, "workoutKey": "abc", "startTime": 1767254400000 }, + "detail": { "workoutId": 1001, "workoutKey": "abc", "startTime": 1767254400000 }, + "detail_status": "stored" +} +``` + +- `provider` is the provider name in the route path. +- `vendor_id` is the id from the table's id column, as text. +- `start` is the value at the table's start column, copied unchanged. It + is absent when the object has none. `start_kind` is `text`, + `unix_seconds`, or `unix_milliseconds`, from the table. It is absent + when `start` is. +- `list` is the list object. `list_parent` is present only for Sensorbio. +- `upload_window` is present only for Garmin. It holds `start` and `end`, + the integer Unix seconds of the grid window the list object came from, + such as `{ "start": 1767200400, "end": 1767283200 }`. +- `detail` is the detail object after the table's detail unwrap. It is + absent when no detail is stored. +- `detail_status` is `stored`, `deferred`, `failed`, `mismatch`, + `not_available`, `too_large`, or `refused`. +- `detail_checked_at` is present only when a Garmin detail answered 404 + or 501 and `detail_status` is `not_available`. It holds the integer Unix + seconds of that answer, by the pull's clock. +- `refused_by` is present only when `detail_status` is `refused`. It is + `privacy_scan`, `unusable_name`, or `too_deep`. `refused_path` is + present only with + `unusable_name`. It is the JSON path of the key in the detail, and it + names keys and indexes, never a value. The privacy scan runs first, so + the path never holds the key, the origin, or the user id. +- A value that section 4 withholds is replaced in place by its marker. + Nothing else in `list`, `list_parent`, or `detail` is changed. + +The record is a `source_report` of kind `original` and subject +`vendor_workout`. Its writer is `open_wearables`, its sensor is +`ow1:["vendor_workout", provider]`, and its `source_type` is `connector`. +`provider_record_id` is `vendor_id`. `input_timestamp` and `reported_at` +follow the start rule above. `received_at_basis` is `import_time`. The +whole envelope is kept in `supplied_fields`, including the fields the +mapping reads. The match key is the writer, the sensor, the resource +`vendor_workout`, the provider, and the vendor id, escaped by D181. So the +Suunto record in section 7 has a key that ends `suunto|1001`. + +Vendor originals have a total size bound. A native package writes them in +its main document, `athlete.ath.json`, with every other record that is +not a measurement sample. The current record is under `records`, and each +revision is under `record_revisions`. Only measurement samples go to the +`series/` files. So each original is in that one document at least twice. +Version 2.1.1 reads a package document only up to +`MAX_PACKAGE_DOCUMENT_BYTES`, which is 512 MiB, and a mapped import file +only up to `MAX_MAPPED_INPUT_BYTES`, also 512 MiB. + +`MAX_VENDOR_ORIGINAL_BYTES` in `src/input_policy.rs` is half of +`MAX_PACKAGE_DOCUMENT_BYTES`, 256 MiB. It counts the bytes `ath export` +writes for vendor originals. For each original, including a deleted one, +that is its item under `records` and each of its items under +`record_revisions`. Export writes each item with +`json::to_deterministic_pretty`, two spaces for each level, and indents +every line four spaces more. The stored `record_json` is compact, so the +bound does not count it. One function beside the item writer in +`src/package/export.rs` measures an item, so the bound and export count +the same bytes. The originals therefore take at most half of the main +document. The other half is for every other record. Nothing bounds those +records, so the export check below is the last guard. + +A synthetic one-hour Polar run with a 3,600-point route, six sample +strings, and five zones is 413 KB as compact `record_json`. Each item of +it that export writes is 847 KB, 2.05 times as large. With one revision, +the original is in the document twice, 1.69 MB. So the bound holds about +158 such workouts with one revision each, or about 105 with two. The +earlier bound, 128 MiB of compact JSON, would export to about 525 MiB of +them, over the read cap. +[appendix/vendor-original-size.md](appendix/vendor-original-size.md) +records the measurement. + +Every write that adds a vendor-original revision checks the bound before +it writes: + +- A pull page and `ath import --mapping open-wearables`, in the matching + step. A page that would pass the bound is refused. It writes nothing, + its objects count as `size_cap` in `left_out`, and that provider is + `incomplete`. +- `ath correct` and the protocol record writes, for a change that creates + or revises a vendor original. The check is in `apply_in` in + `src/store/write.rs`, which `Store::apply` and `apply_with_attachments` + both call. +- A package merge and a native restore, in `src/package/restore.rs`. A + package that 2.2.0 exported always passes, because every write keeps + its database under the bound. + +Each refusal names the bound and the bytes the originals would use. It +says that a package holding them could not be read back. Deleting an +original does not lower the total, because its revisions stay. `ath +erase` removes the record and its revisions, so it does. + +Every run of `ath pull openwearables` prints `vendor originals use X MiB +of 256 MiB`, with X to one decimal. A preview prints the total stored +before this command, and `--yes` prints the total after it. `--json` has +`vendor_workouts.used_bytes` and `vendor_workouts.bound_bytes`. From 80% +of the bound, the run also prints a warning, and `--json` puts it in +`vendor_workouts.notice`. The warning says three things. At the bound, +new vendor pages are refused. `ath erase` of an original frees its space, +but it removes that original and its history and cannot be undone. A +later version may lift the bound. The warning names no person and no +plan question. Whether this release stores originals in their own files +instead is open in section 10. + +The database keeps each original's size, so no write measures them all. +Step 7 creates the table `vendor_original_sizes`. It has one row for +each vendor original, deleted ones included. The row holds `record_id`, +`record_item_bytes`, and `revision_items_bytes`. `record_item_bytes` is +the original's item under `records` as export writes it. +`revision_items_bytes` is the sum of its items under `record_revisions`. +The row references `records` with `ON DELETE CASCADE`, so `ath erase` +removes it with the record. The table is not in the package. It is kept +in step with the record, the way the typed tables are. + +Every write that changes an original updates its row in the same +transaction. A new revision measures two items: the new revision item, +which is added to `revision_items_bytes`, and the new current item, which +replaces `record_item_bytes`. A delete measures the current item again, +because its `is_deleted` value changes. A package merge and a native +restore measure each item they write. Revision items never change after +they are written, so no write measures an old one. The bound check reads +the sum of every row, takes away the old rows of the originals the write +changes, and adds their new sizes. The pull's usage line reads the same +sum. + +Only `ath check` measures every original again. It compares each with +its row, and a difference is an error that names the record. A missing +row or a row with no original is an error too. `ath repair` writes the +measured sizes, makes a verified backup first, and adds no revision. + +`ath export` in 2.1.1 writes the main document and the series files with +no size check, so it can publish a package that `src/package/load.rs` +refuses to read. The build adds that check to `src/package/export.rs`. +Export counts the bytes of each document it writes into its staging +folder and the nesting depth of each item. A document may not pass +`MAX_PACKAGE_DOCUMENT_BYTES`, and an item may not reach +`MAX_PACKAGE_JSON_NESTING`, 128 levels, counted from the document. When +either happens, export fails before the rename, removes the staging +folder, publishes nothing, and names the document. `check_nesting` in +`src/package/load.rs` allows 128 levels. But the read then parses with +serde_json through `src/json.rs`, and serde_json refuses 128 levels. With +serde_json 1.0.154, the version in `Cargo.lock`, 127 levels parse and +128 do not. So 127 is the deepest package that reads back. + +The package puts a vendor object five levels down: the document, +`records` or `record_revisions`, the item, `data`, and +`supplied_fields`. So a vendor object nested 123 levels or more would +reach 128 in the package. The pull refuses such an object as `too_deep`, +by the same rules as `unusable_name`. A list object or list parent that +deep is not stored and gets no detail call. A detail that deep is not +stored, and the clean list object is stored with `detail_status` +`refused` and `refused_by` `too_deep`. That detail is asked for again +only when the list object changes. The provider stays `completed`. Each +such object is named in `left_out.examples` with its depth instead of a +path, such as `polar "1003": too_deep at 125 levels`. A mapped import of +saved envelopes leaves out an envelope whose `list`, `list_parent`, or +`detail` is that deep, as `too_deep`. So no vendor original can make +export fail by its depth. + +ath does not write a saved file of envelopes. Written compact or with a +two-space indent, such a file is smaller than its originals as export +writes them, so it fits the 512 MiB mapped-import cap. + +The pull writes one provider's originals as one page, after that +provider's list and detail calls finish. The page is one preview at one +database revision. With `--yes` and without `--json`, it is then one +`ProviderPreview::apply`, which refuses a moved revision as every 2.1.1 +apply does. A stored page and an archive never hold a vendor original, and +a vendor original is never a capsule. A vendor page that fails or is +refused leaves that provider `incomplete`. It does not change a stored +page or an archive in the same command, and a refused stored page does not +change the vendor page. + +The vendor page uses the 2.1.1 keyed rules. If the person deleted an +original, a later pull leaves that object out, says so on its line, and +does not recreate it (D182). That happens on every later pull. If the +person deleted a provider's `vendor_workout` source, every object from +that provider is left out (D190). If the person corrected an original with +`ath correct`, the owner-correction rule above applies. A later pull +whose envelope equals the newest `provider_import` revision adds nothing, +and the correction stays current. A later pull whose envelope differs +replaces the correction and counts it in `owner_corrections_replaced`. +The person's revision stays in the history. To keep a pull from changing +an original at all, the person deletes it. The deleted original then +keeps the person's version in its history, and every later pull leaves +that object out. A workout fix belongs on the stored session or in a +note, not on the vendor original. The skill says so (section 6). + +Each provider's line, and its object in `--json`, counts these. In a +preview they are estimates under `estimated`, as section 1 says. + +- `originals`: new, changed, and unchanged records. +- `owner_corrections_replaced`: owner corrections that this page replaces, + by the owner-correction rule above. Each is also counted as a changed + original. +- `merge_choices_replaced`: the part of `owner_corrections_replaced` + that were merge choices. +- `details`: `stored`, which a preview calls `would_detail`, `kept`, + `deferred`, `failed`, `mismatch`, `thinner`, `not_available`, + `too_large`, and `refused`. +- `left_out`: objects not written, by reason: `missing_id`, + `unusable_id`, `unsafe_number`, `unusable_name`, `duplicate_id`, + `too_deep`, `superseded`, `ambiguous_window`, `deleted_record`, + `deleted_source`, `response_refused`, and `size_cap`. +- `withheld`: values that section 4 withheld, with up to 20 paths. + +Each listed object is in exactly one detail count or one left-out count. +A list response that fails or that the privacy scan refuses stores nothing +from that response. Its objects count as `response_refused` when they +could be read, and the provider is `incomplete`. + +The original is not a workout session. The stored session stays matched +by the Open Wearables workout id. The public stored workout has no +`external_id`, so the two records are not joined by time, distance, or +device. A device id inside the vendor object does not set +`device_binding`. Nested samples stay inside the original. The eight +range calculations do not read it. + +The rewritten `mappings/open-wearables.md` gains a section named +`vendor_workout`. It declares the record type `source_report`, kind +`original`, and subject `vendor_workout`. It names the writer +`open_wearables`, the sensor from `provider`, the key from `provider` and +`vendor_id`, and the start from `start` and `start_kind`. It keeps the +whole envelope in `supplied_fields`. A saved file of envelopes, under +`vendor_workout`, imports through that section with `ath import --mapping +open-wearables`. File import does not apply the detail rules above. It +writes each envelope as the file holds it, as D182 does for every mapped +import, except the owner-correction rule, the Garmin window rule, and +the depth check above. Export and import keep one original id. + +The provider table, the detail rules, and the thinner check live in +`src/runtime/vendor_workouts.rs`. They run before the mapping engine sees +an envelope, so the mapping engine has no vendor exception. +`open_wearables.rs` calls that module. It does not grow a provider branch. + +Day rows are one selected row per source, series, and local day. The +repository prefers `computed_by: provider`, then the later provider row. +With the sample fallback on, a missing day can be computed while reading. +The returned `timestamp` and `period_end` come from `CalendarPeriod`, not +from the provider interval that was stored. `stats` and `computed_by` are +kept. They are the server's window receipt, not the original provider +period. + +## 3. How a response becomes records + +The pull resolves `open-wearables` through `resolve_mapping` in +`src/assets/mod.rs`. It parses and +checks the file before the first request. A bad file fails with no network +call. A resolved file that does not implement section 2 also fails before +any request. An installed 2.1.0 copy still wins under D179, and this check +stops it from quietly dropping the rows section 2 stores. + +File import and pull use the same envelopes. A cursor or offset page passes +its `data` array to the section named in the mapping file. A timeseries +page passes the response object, because `metadata.resolution` is required. +Body passes the object. JSON `null` is not mapped. The personal record +passes the object after `user_id` is removed. Pagination and health-score +`metadata` are not records. + +Everything after that is the mapping engine that 2.1.1 carries over from +2.1.0: match keys (D181), replace on change (D182) except for the owner +corrections section 2 keeps, source and device +(D183), one write transaction per page (D189), a deleted source left out +(D190), and the supplied-field check (D191). `keyed_candidate` in +`src/import/shared.rs` calls `check_supplied_fields` for every mapped +record, and a failure refuses the import. It refuses an empty name, and a key named +`__proto__` at any depth, in a record's `supplied_fields` and in each +route point's `supplied_fields`. Version 2.1.1's D214 changed only the +native reader, which now keeps a `__proto__` key and checks it like any +other key. D214 did not lift this import refusal, so it still applies. +A vendor original keeps its whole envelope in `supplied_fields`, so the +same check covers every vendor object. The pull runs it on each vendor +object first and refuses only that object, as section 2 says. A saved +file of envelopes that holds the key still fails its import (D191). +A Garmin file import remains a different `data_route`, so both copies of +one workout stay (D161). A second pull of the same Open Wearables object, +or an `ath import --mapping open-wearables` of a saved copy of that object, +keeps the same rows. An identical vendor original changes no row. A +changed object replaces the stored one, except under the owner-correction +rule and the Garmin window rule in section 2. The mapping engine has no +vendor exception. Section 2's detail rules decide which vendor envelopes +reach it. + +On a device source, the writer is `source.provider`. The sensor string is +`source.device_type`, `source.device`, and `source.source`. Section 2's +other sensors are different sources. They do not enter the device check. +Two devices with different triples are +two sources and two baselines. Two devices that share the triple share one +source and one baseline. `source.device_id` is copied to `source_device.hardware`. +It does not split the source, and it is not part of the match key (D181, +D183). Route, writer, and sensor are the source identity. The mapping +`name` is a label. Changing `name` alone does not change the source or the +match key. File import and pull of the same mapped object, in either order, +keep one record id when route, writer, and sensor are the same. + +Open Wearables uses `device_id` to tell same-model devices apart when a +provider sends it. The pinned field is optional (`str | None`) in +`backend/app/schemas/utils/metadata.py` at +`183e8cc4f6de897dbd288c93d49a691f2cf721ae`. This study does not treat that +id as stable or unique for every provider. A timeseries sample has no +sample id. Its match key is the writer, the sensor, the kind, the type, and +the UTC time. Two `device_id` values therefore share one key. The mapping +removes `source.device_id` from the point because that path is hardware, so +the point and its revisions do not carry it. `source_devices.hardware` is +one mutable column. A later write can revise it. It is not a binding. +D45 records hardware without splitting a source. D181 and D182 then replace +one key with a different payload. None of those decisions says a second +device's observation may replace the first. + +The recommended rule keeps the match key, the sensor, and the baseline. +Putting `device_id` into the sensor list would split sources and baselines, +change keys, and drop the promise that an old triple-key row and a new pull +are one record. The sensor join uses `|`, so a `device_id` that contains +`|` is not a safe extra part unless values containing `|` are refused or +the join is encoded. That identity change is not this proposal. Old rows +are not rewritten, moved, or deleted. + +Both `ath import --mapping` and `ath pull` go through `preview_route` and +`ProviderPreview::apply` in `src/import/provider.rs`. The check lives in the +matching step there, for route `open_wearables` only. It reads its facts in +the read transaction, at the preview's database revision, and decides +before a staged plan can change a device source or a timeseries record on +that source. The apply refuses a moved revision, so the write sees the +facts the check read. Summary, event, score, and unattributed sensors do +not enter it. Other routes are not checked. A pull-only check would leave +import-after-pull able to replace the point. The check reads every +accepted row, including a row after the first source device. + +The receipt is the source object's own key `device_binding`. The 2.2.0 +source schema makes it an optional nonempty string. D185 keeps +`supplied_fields` for names the source sent, so the receipt is a sibling of +that object, as `field_basis` is a sibling on a measured record. The +receipt adds no column and copies no field onto old sources. A source migrated +from 2.1.0 has no `device_binding` key. A string already stored at +`supplied_fields.device_binding` stays in `supplied_fields`. Migration does +not treat it as the receipt. Renaming that supplied name would still leave +an old free-form value able to authorize a write, so this proposal does not +do that. + +An established binding is that source key holding a nonempty string. The +automatic path reads only that key. The same name anywhere in a raw payload, +a mapped file, or nested `supplied_fields` is source data. The mapping may +keep it on the measured record. It is not copied onto the source, and it +cannot replace or erase the source key. + +The value the automatic path compares is the row's `source.device_id`. The +mapping `name` does not choose it. The shipped file points `device_hardware` +at `source.device_id`. A resolved mapping that points `device_hardware` +somewhere else fails before any write, because that file cannot satisfy this +contract. The source already stored stays unchanged. + +The check runs on device-targeted rows. That includes a measured raw or +day row whose `source` object has no `device_id`. That row is not marked +`left_out` before the check. A reported series does not enter this check. +A query-bucket row that is already `left_out` does not establish a +binding and does not supply the id. Summary, event, score, report, +archive, unattributed, and personal-record rows do not enter this check. +The call is one of these states: + +- The source is deleted. D190 leaves its rows out. The call does not revive + the source and does not set a binding. +- The source has an established binding, and the incoming id equals it. The + row may repeat unchanged or correct the stored value under D182 and the + owner-correction rule in section 2. The binding stays. Hardware is not replaced with a different id. Other fields + already on the source stay. +- The source has an established binding, and the incoming id is different, + missing, null, or blank. The call is refused before any mutation. Equal + point values with a different id are still refused. A new timestamp does + not make the new id acceptable. The text says the replacement device is + blocked, including when the sample time is new, and that running the + command again cannot change the id. It names the fix in section 2: + when the new device replaces the old one, `ath correct` on the source + sets `device_binding` to the new id. It also says that the fix merges + the old device's history and the new device's rows on that source, so + they can no longer be told apart. +- The source exists, the source key is absent, and any history exists. + History includes a deleted record and a deleted source device, not only + live rows. `existing_source` in `src/import/provider.rs` keeps + `records.is_deleted = 0`, so it is not + this test. The store read below includes the deleted rows. The call is + refused. Hardware is not promoted. The text + says this Open Wearables history cannot be refreshed until a separate + reconciliation exists, and that running the command again cannot create + the binding. It also says that when one device wrote that history, + `ath correct` on the source can add `device_binding` with that device's + id. This is the block for 2.1.0 history. It is not the coverage + choice in section 2. +- The source key is present and is not a nonempty string. The call is + refused. The stored value is left as it is. The text says this command + cannot use that binding, a rerun cannot repair it, and `ath correct` on + the source can set it to the device's id. +- The source is new for this call, or it already exists with the source key + absent and with no history. Accepted rows that are only sleep and + workouts, and that all lack an id, are stored. The source has no + `device_binding`. The result says the device id is unknown. An accepted + device-targeted timeseries row with no id is refused. Accepted rows that + mix a nonempty id with a missing id are refused. A reported series is + not one of these rows. Accepted rows that share one nonempty + `source.device_id` store that string on the source in the same + transaction as the first accepted write. That source may be created in + this call, or it may already exist with no receipt and no history. A call + that accepts no rows creates no binding. A refused call is not applied, + so it creates no source and binds none. + +A second device is refused rather than merged. Only the owner's rebind +in section 2 merges two devices' history on one source. That refusal is +not archived. On `--yes`, an earlier committed page stays, the failed page +makes no database changes, the range is not complete, and the exit is +nonzero. File import refuses the whole call and writes nothing. +`--json` and `--json --yes` make no database changes. Device reads +that have `filter_by_priority` send `false`. Summary routes have no such +switch. Section 2 states that limit. + +Preview keeps two facts in memory for this command, for each source sensor: +the binding it would have stored, and an unbound source it would have +created once that source has accepted history. A summary sensor does not +supply a binding for the device sensor. The pull passes those facts to the +next preview page's matching step, including a later page that adds an id +after an id-less sleep page. The memory is discarded with the process. It +does not hold null-source payloads, so a preview does not use it to judge +those conflicts. It does not change the estimated record counts. A second +command's matching reads the committed source. + +Owner and library writes store a whole source record and do not run this +device-id guard. In 2.1.1 they are `ath correct` in +`src/cli/commands/edit.rs`, the protocol operations `records.write`, +`records.write_changes`, and `records.correct` in +`src/protocol/ops/records.rs`, native package restore, and a package merge +the person accepts, both in `src/package/restore.rs`. `ath correct` and the +protocol operations store the source `data` the caller supplied, after the +schema check. Native package restore copies the package's records. A +package merge the person accepts for a changed source stores that source +record. A 2.2.0 record keeps `device_binding` when the +record has it. A 2.1.0 record does not gain the key, and a supplied field +of the same name stays a supplied field. The next mapped pull or mapped +import then uses the source key that those operations left behind. A 2.2.0 +export and restore keeps the key and the import keys, so the same id can +correct a point and a different id is refused. No signature is added. A +person who replaces the database file is outside this rule. + +`Store::apply` in `src/store/write.rs` writes a whole source record. There +is no partial `revise`. In 2.1.1, every `Store::apply` caller that can +write a source is one of the owner and library writes above. The one +automatic source writer is `ProviderPreview::apply`. A keyed import there +only creates sources. It never revises one. So the binding rule is +enforced in `ProviderPreview::apply`. A staged source for route +`open_wearables` may carry `device_binding` only as the checked rule above +set it. The first bind of an existing source is a source correction in +that plan, with the source's expected revision. No other staged change may +set, change, or clear `device_binding`. Such a plan is refused, and the +source stays unchanged. Other record types are unchanged. + +The store connection is private (D223). `Run::source` in +`src/import/mapping.rs` asks `CandidateSink::route_source` in +`src/import/provider.rs` for a source by writer, route, and sensor. That +call takes no receipt. The mapping receives a provisional source id. It +does not hold the source JSON, and it does not read the database. The +facts come from the matching step. A later automatic write cannot fill +the receipt in, because `ProviderPreview::apply` refuses any staged change +to `device_binding` that the checked rule did not make. + +`src/import/provider.rs` therefore gains these source reads and writes, +besides the typed writes in section 6. It gains nothing beyond those: + +- In matching, read the committed receipt, and whether any record or + source device for that source exists, including a deleted row. +- In matching, read the sources, records, import keys, and archive keys + named by one page, including tombstones and the current revision. This is + the safety snapshot in section 2. It does not scan the database. +- In the staged plan, create a source with the checked receipt already in + its JSON. +- In the staged plan, write the checked receipt on an existing source only + when the receipt is absent and the same matching read shows no accepted + or deleted record and no source device. Every other source field stays. + The write is a correction with the source's expected revision. Writer, + route, sensor, import keys, and baselines stay. +- In `ProviderPreview::apply`, refuse any other staged change to + `device_binding`. +- In the sink, stage a `connector` source. `route_source` stages only an + `export_file` source that names a vendor, and it reuses only a staged + `export_file` source. The writer-`open_wearables` sensors in section 2, + the archive source, and each `vendor_workout` source are `connector` + sources with no vendor. So a new `connector_source(writer, sensor)` + goes beside `route_source`. Matching finds its stored source by writer, + route, and sensor, including a deleted one, as `keyed_existing_source` + already does. A device source still comes from `route_source`. +- In the preview, count the staged plan by record type and action. + `Staging::count` in `src/import/staging.rs` counts by action only. A count + by record type goes beside it, and `ProviderPreview` exposes it. Each + page's counts in section 1 come from that count. It is one SQL count. + `ProviderPreview::planned` also lists each row's record type and + action, but it copies each row's whole `data_json`, so the counts do not + use it. +- A crate-private read of a stored vendor original, for the detail rules + in section 2. +- In matching, for route `open_wearables` only, the owner-correction rule + in section 2. `KeyedPolicy` gains a flag that only that route sets. + `record_by_import_key` also returns the current revision's + `record_revisions.became_known_at_basis`. For an owner correction, + matching reads the newest revision of that record whose basis is + `provider_import` and compares the candidate with it. The page's report counts + each replaced correction. For a `vendor_workout` row, matching leaves + `upload_window` out of each comparison, leaves `detail_checked_at` out + of the owner-correction rule and the window test, and applies the + Garmin window rule in section 2. +- In matching, for a page with `vendor_workout` rows, the size bound in + section 2. It reads the stored total from `vendor_original_sizes`, + measures the items the page's new and changed envelopes would write, + and refuses the page when the total would pass + `MAX_VENDOR_ORIGINAL_BYTES`. The apply writes those rows in the same + transaction. + +The pull reads the revision a preview matched at from +`ProviderPreview::destination_database_revision`, which is already public. +No accessor is added for it. + +The reads run in the matching step's read transaction. The writes run in +the page's one apply transaction. A refused call writes none of them. +Other routes do not call them, and `route_source` is unchanged for them. +It does not add a table or a trait. The +binding check and the safety snapshot go in one new file, +`src/import/binding.rs`, because `src/import/provider.rs` is already 1297 +lines. The automatic path does not replace `detail`, `vendor`, or +`supplied_fields`. + +`zone_offset` is not copied into `start_at`. It remains in `supplied_fields` +when the server sends it. The timestamp text is the server's `start_time`, +`end_time`, or `timestamp`. A timestamp with no offset is left out by the +mapping. The pull does not add `Z`. + +`computed_by`, `window_seconds`, `is_nap`, `intensity`, and `efficiency_percent` +stay under those names when they are present. `computed_by` sets the basis +in section 2. It does not change the writer. Raw samples on 0.11.0 are +built without that field. Day rows carry it, and those rows are stored. + +## 4. Credentials, privacy, and the network + +D274 is the rule. The key never enters the athlete database, the export, the +preview, or an error line. The pull reads the paths in section 2. Connections and the two live +workout routes are included only when `--vendor-workouts` is on. +It does not list users. A raw HTTP personal-record response includes `user_id`. That field must +be a string UUID equal to the selected user id. Absence, null, a +non-string, and any other string refuse the page before redaction and +before mapping. A matching string is removed before the scan below and +is not stored. The canonical import envelope is that object after the +removal. File import of the envelope does not put `user_id` back. An +envelope that still has `user_id` is not that envelope, and the scan +rejects it. Birth date, +gender, and sex are stored. They are account health data, not the API key. + +The process refuses a base URL that could carry the key in the URL itself. +It refuses plain `http` except to loopback. It does not follow a redirect, so +the key cannot be sent to a second host. One attempt per request, then +stop. The stored reads use 30 seconds to connect and 120 seconds to read, +as `src/runtime/garmin_pull.rs` does. A live vendor request uses 30 +seconds to connect and 360 seconds to read, for the reason in section 2. +The timeouts are named constants in `src/runtime/open_wearables.rs`. One +response may be at most `MAX_PULL_RESPONSE_BYTES`, which is 10 MiB. One +read may be at most 1000 pages. One Suunto list may be at most +`MAX_SUUNTO_LIST_REQUESTS`, which is 100 requests. Only Suunto's list is +paged, so the name says Suunto. Those limits are named constants in +`src/input_policy.rs`, where 2.1.1 keeps every limit on untrusted input. +In 2.1.1 the comment on `MAX_PULL_RESPONSE_BYTES` says it is the bytes of +one Garmin personal connection response. The route list at the top of +that file's route limits names only the Garmin pull. The build rewrites +that comment to name both pulls, and it adds the Open Wearables pull and +its new limits to that list. The value stays 10 MiB. + +The body is read inside that cap and parsed before the page reaches +`MappedPage`. The guard is in `open_wearables.rs`. It walks every decoded +object key and every decoded string. A value that contains the API key, +the selected origin, or the selected user id rejects the whole page, even +under a credential-shaped key. + +A credential-shaped key does not reject the page. Its value is withheld. +A key is credential-shaped when its letters and digits, with case ignored +and every other character dropped, end in `token` or `secret`, or are +`apikey`, `authorization`, or `password`. That covers `userAccessToken`, +`access_token`, `refresh-token`, `id_token`, `session_token`, `token`, +`embed_token`, `client_secret`, and `apiKey`. Two names that end in +`token` are page cursors, not credentials: `next_token` and `nextToken`, +matched exactly. Whoop's and Oura's responses name their next page +`next_token`. Whoop's model at the pin reads that key with no alias, and +Whoop's request parameter is `nextToken`. Those two keys keep their +values. The scan for the key, the origin, and the user id still covers +them. The pull reads `more` from the response before it withholds +anything, so a null `next_token` stays null. + +A withheld value is replaced by the +text `[withheld by ath]`, whatever type it had. A string that is an +absolute URL keeps its scheme, host, port, and path. A user name or +password in it, before the `@`, is replaced by the same text. Each query +parameter, and each `name=value` pair in the fragment after `#`, whose +name is credential-shaped has its value replaced by the same text. So +`#access_token=...` is withheld. A URL that does not parse keeps its +text, and the scan above still runs on it. The pull +records the JSON path of each withheld value and counts them. It prints +the count and up to 20 paths, and it says when that list was shortened. +Nothing else in the object changes. The rule applies to every page, +stored reads and vendor reads alike. Garmin's summary objects can carry +an optional `userAccessToken`. The pinned server declares it on its Garmin +wellness models, and the live route returns Garmin's objects unchanged. +Refusing the page would refuse every Garmin page that carries it. +`polar_user` and a route coordinate are not credential-shaped. +D289 keeps the rest of the vendor object, including account ids, Polar +user URLs, and full routes. The matching personal-record `user_id` is the +only field of a stored read that is dropped before this walk. Any other +copy of the user id still rejects the page. The connections list is not +walked, as section 2 says. +A raw personal-record `user_id` that is absent, null, the wrong type, or +not the selected user refuses the page before the drop. The page is not +rewritten and it is not mapped. A Unicode escape such as `\u0073` is visible +only after parsing, so a scan of the raw text is not enough. The raw-text +scan still runs on a body that did not parse, and the command still refuses +to print the key. Those checks are defense in depth. They do not repair a +page that has already committed. + +Printed failure text is a fixed sentence plus the HTTP status. A server +problem `code` is printed only when it is a single token of letters, digits, +`_`, or `-`, at most 64 characters, and it does not contain the key, the +origin, or the user id. Any other code is withheld. A transport error or a +parser error is replaced with a fixed sentence. The sentence has no URL, no +path, and no user id. The result keeps a `left_out` total, a count for +each reason, and at most 20 example lines. It does not keep every id or +every source string. The command prints from this process, as every 2.1.1 +command does. The 20 example lines are the bound. + +There is no Athletic Standard telemetry on this command. The server the person +named is the only host contacted. + +A deployment API key can read every user on that server. The command cannot +shrink that key. It can avoid using the extra power: one user id, the +reads in section 2, no user list. + +## 5. Version, migration, and what stays compatible + +The build sets `2.2.0` on the package, the record, and the +`athleticstandard` crate, by the same constants 2.1.3 uses. +`ATHLETIC_STANDARD_VERSION` is in `src/model/package.rs`. `SQL_SCHEMA_VERSION` is in +`src/store/migrate.rs`. Migration step 8 is a new SQL file and a narrow +runner arm. Step 5 is already +`spec/sql/migrations/005-version-2-1-1.sql`. Step 6 is already +`spec/sql/migrations/006-version-2-1-2.sql`. Step 7 is already +`spec/sql/migrations/007-version-2-1-3.sql`. Step 8 updates +`athleticstandard_version` to `2.2.0` and `sql_schema_version` to 8. No +column is added to an existing table. The contract adds +`source_report` to the `records.record_type` check, creates +`source_reports` and `vendor_original_sizes`, and rebuilds +`provider_summaries` and +`provider_scores` as section 2 describes. Files `001` through `007` stay +byte-identical. Step 6's nullable `athlete_reports.workout_session_id` +stays. Step 7's three internal tables stay. Step 8 does not rebuild those +tables. The check is not removed, and +ordinary store writes do not turn foreign keys off. + +SQLite cannot change that check in place. `records` and +`record_revisions` reference each other. The link from a record to its +current revision is deferred. The link from a revision back to the +record, and the links from typed rows, import keys, deletions, +attachments, reporting periods, and the other child tables, use +`ON DELETE CASCADE` and are not deferred. Triggers and views name +`records`. `PRAGMA foreign_keys` does not change inside a transaction. +`configure` in `src/store/mod.rs` requires foreign keys on before +`install_schema` runs. A `DROP TABLE records` inside that transaction +would fail or cascade through the children. Step 8 does not do that. +`write_transaction` in the same file refuses to write when foreign keys +are off. `Store::transaction` uses it. `ath migrate` and +`apply_pending_without_backup` run steps 2 through 7 through +`Store::transaction`. A new database does not. `Store::create` opens a +connection, runs `configure` and `enable_wal`, and calls `install_schema` +on that connection before any `Store` exists. `install_schema` opens its +own transaction with `rusqlite::Transaction::new_unchecked`. + +Today `install_schema` runs the whole chain, steps 1 through 7, in that +one transaction. It sets `user_version` to `SQL_SCHEMA_VERSION`. Then it +refuses unless the metadata reads `SQL_SCHEMA_VERSION` and +`ATHLETIC_STANDARD_VERSION`, in `src/store/mod.rs` lines 628 through 631 +at `a3d3eba`. `apply_steps` in `src/store/migrate.rs` has the same kind of +final check, in lines 333 through 337. It refuses unless the last step it +ran reached `SQL_SCHEMA_VERSION`. When the constant becomes 8 and steps 1 +through 7 commit at schema 7, both checks would fail. So the build changes +both. The first `install_schema` transaction stops after step 7, sets +`user_version` 7, checks for schema 7 and `2.1.3`, and commits. +`apply_steps` checks that it reached the last step it was given. The +step-8 function makes the final check before it commits: schema 8, +`2.2.0`, and `user_version` 8. + +Step 7 is one function in `src/store/migrate.rs`. It takes the +connection and opens its own transaction. At init it runs on the +connection `Store::create` opened. On migrate it runs on the store's +connection. It does not use `Store::transaction`. Before `BEGIN IMMEDIATE`, it sets +`PRAGMA foreign_keys=OFF` and reads the pragma back. The value must be 0. Turning foreign keys off does not turn off the schema +check SQLite runs during `ALTER TABLE`. `sql_v1_current_records` and +`sql_v1_active_records` select from `records`. The triggers +`record_revisions_record_type_matches_parent_insert` and +`record_revisions_record_type_matches_parent_update` are defined on +`record_revisions` and also read `records`. Dropping `records` does not +drop them. A rename while they still point at a missing `records` fails. +`writable_schema` is not used. + +Inside that one transaction the order is fixed. + +1. Drop `sql_v1_current_records` and `sql_v1_active_records`. +2. Drop the two cross-table triggers named above. +3. Create `records_next` with the old columns and the check extended by + `source_report`. Copy every root row. Drop `records`. Rename + `records_next` to `records`. +4. Rebuild `provider_summaries` and `provider_scores` the same way. + Copy deleted rows. Keep record ids, `data_json`, import keys, + revisions, and periods. Value and unit may be null together. + Recreate `provider_summaries_lookup_idx` and + `provider_scores_lookup_idx` from the text in `001`. No view and no + trigger in `001` names those two tables. A generated object whose + text names one of them is dropped before that rebuild and recreated + from the same text afterward. There is no search of the whole schema. +5. Recreate `records_record_type_idx` and the triggers defined on + `records`, from the text in `001`: + `records_current_revision_must_exist`, + `records_deleted_flag_must_match_deletion_row`, + `record_erasure_blocks_current_record_insert`, and + `record_erasure_blocks_current_record_update`. +6. Recreate the two views and the two cross-table triggers from that + same text, unchanged. +7. Create `source_reports` and its type trigger, and + `vendor_original_sizes`. A 2.1.3 database has no vendor original, so + the new table starts empty. +8. `PRAGMA foreign_key_check` is empty and `PRAGMA integrity_check` is + `ok`. +9. Set the version rows and `user_version` 8. + +`sql_v1_database_info`, `sql_v1_record_revisions`, and +`sql_v1_record_deletions` do not name `records`, so they stay through the +gap. Then the transaction commits. After commit, and after a rollback or +an error, the runner sets `PRAGMA foreign_keys=ON` and reads it back. The +value must be 1. If it is not, the command fails and closes the store. +`write_transaction` would refuse a later write on that connection anyway, +and the next open turns foreign keys on in `configure`. A failure before +commit restores the views, the +cross-table triggers, the old check, the rows, and the version. The D124 +backup is already on disk. Device receipts stay in the copied source +JSON. They are not rewritten. + +A new database commits migration steps 1 through 7, then runs step 8. +Item 9 in the list above sets `user_version`. If step 8 fails during init, that transaction +rolls back to the committed step 7 schema before the existing failed-init +cleanup runs. Init reports failure. `Store::create` still calls +`remove_partial_database`, which deletes the new file, the wal file, and +the shm file. D276 leaves that cleanup in place, and this build does not +change it. A file that cleanup does not delete is not left with the views +dropped. A migrate of a database that already existed is a separate case. +`apply_after_backup` and `apply_pending_without_backup` in +`src/store/migrate.rs` run the steps up to 7 in `Store::transaction`, as +2.1.3 does, and commit. They then run step 8 in its own transaction. For a +2.1.3 database, a step 8 rollback leaves the file at schema 7 with foreign +keys on. For an older database, the earlier steps stay committed, so the +file is now a 2.1.3 database. The message says which schema the file is +at and names the verified backup. Running `ath migrate` again runs only +step 8. `apply_step` keeps its signature for steps 2 through 7. Step 8 is +a separate function in that file. +`MIGRATION_CHAIN` in that file and `spec/sql/contract.json` gain the step. +The native tests check that the contract matches the embedded SQL. +`packages/npm/package.json` exports and `packages/npm/test/public-api.test.ts` +point at `schema/2.2.0/`. + +`READABLE_DATABASE_VERSIONS` and `ACCEPTED_RECORD_VERSIONS` become `1.0.0`, +`2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, `2.1.3`, and `2.2.0`. Both sets already contain `1.0.0`. +Dropping it would make a 1.0.0 database unloadable, so migrate could not +open it. `IMPORTABLE_PACKAGE_VERSIONS` is `2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, +and `2.1.3` today. It gains `2.2.0` and keeps those five. `Store::open` rejects a +`2.1.3` database until `ath migrate`, with the refusal it already uses for +an older database. A `2.1.3` database will not open until that migrate. + +The build generates `schema/2.2.0/` and does not rewrite `schema/2.1.3/`, +`schema/2.1.2/`, `schema/2.1.1/`, `schema/2.1.0/`, or `schema/2.0.0/`. The 2.2.0 source object gains optional `device_binding`. +`ProviderReportingPeriodType` gains `open_wearables_reporting_window`. +`ValueBasis` gains `aggregator`. Series quantities gain the sample series +whose units are in the appendix table. Intake, index, age, and effort +series do not gain quantities. The record type `source_report` is added to `RecordType` in +`src/model/`, the current and revision unions, the package schema, and the +table description in `src/store/encode.rs`. `src/store/check.rs` compares +stored rows with that description. It is not a measured type. Its table has `record_id`, `source_id`, +`report_kind`, `subject`, optional `reported_at`, optional +`standard_value` and `standard_unit` together, optional +`provider_record_id`, `received_at`, and `data_json`. It has no required +measured value. `provider_summary.value` and +`provider_score.value` may be omitted together with the unit, as section 2 +says. A provider summary may also omit `recorded_at` and reporting periods +when its input timestamp uses `not_provided_by_source`. No other field is +added. The folder exists +so the package version and the schema path +stay aligned. The demo athlete is +regenerated because the stored version is inside it. The demo is +`examples/demo-athlete/athlete.ath.sqlite`. The preserved 2.1.0 demo in +`tests/fixtures/version-2-1-0/` is not regenerated. The 0.4.3 file in +`tests/fixtures/version-0-4-3/` is not regenerated. `tests/fixtures/version-2-0-0/` is not +regenerated. + +`build.rs` compiles every file under `mappings/` into the program, and +`src/assets/mod.rs` reads the compiled copy. No package list changes. The +build rewrites `mappings/open-wearables.md` so it implements section 2. Other mapping +files stay as they are. `ATH_WRITE_GENERATED=1 cargo test --test generated` +runs because help text, the schema, and the demo change (D80, and the 2.1.1 +generator decision). `AGENTS.md`, `build-history/README.md`, and `SPEC.md` are +updated in the build so they name 2.2.0 as the software. `docs/connections.md` +keeps the file imports and is updated to the coverage in section 2, including +that `RecoverySummary` at the pinned commit has no skin-temperature field. +This +plan's edits to `AGENTS.md` and `build-history/README.md` only point at the +plan. + +A database from 2.1.3 needs `ath migrate` before the pull. The migrate +command still previews, backs up, and asks (D124). `Store::open` only +refuses. A noninteractive open and an open with `--json` do not migrate. An +interactive open can preview, back up, ask, and then migrate. + +## 6. Where the code goes + +| Piece | Place | +|---|---| +| HTTP, timeouts, page loop, envelope split, privacy walk, and withheld values | `src/runtime/open_wearables.rs` | +| Live provider table, unwrap, windows, pacing, detail budget and rules, and the vendor envelope | `src/runtime/vendor_workouts.rs` | +| Command `pull openwearables`, and the `--date` check for `garmin` | `src/cli/spec.rs` and `src/cli/commands/routes.rs` | +| Flags, key, preview text, refusal if the key appears | `src/cli/`, `src/cli/help.rs`, `src/runtime/keyring.rs`, and `key_clear` in `src/cli/commands/model.rs` | +| Reader for one decoded page | `MappedPage`, beside `MappedReader` in `src/import/mapping.rs` | +| Mapping names and field rules, including the `vendor_workout` section | the existing file `mappings/open-wearables.md` | +| Stage, match, and write each page | `preview_route` and `ProviderPreview::apply` in `src/import/provider.rs`. The revision a preview read is the public `destination_database_revision` | +| A `connector` source with no vendor | new `connector_source` beside `route_source` in `src/import/provider.rs` | +| Page counts by record type | a count beside `Staging::count` in `src/import/staging.rs`, exposed by `ProviderPreview` | +| Owner-correction rule and its count, the Garmin window rule, and the depth check for saved envelopes | `match_keyed` and `record_by_import_key` in `src/import/provider.rs`, behind a `KeyedPolicy` flag that only route `open_wearables` sets | +| Where a workout fix belongs | one paragraph in `skills/athletic-standard/SKILL.md`, under "Stable IDs and revisions" | +| Total size bound for vendor originals, in the bytes export writes | `MAX_VENDOR_ORIGINAL_BYTES` in `src/input_policy.rs`. One function beside `ArrayWriter::item` in `src/package/export.rs` measures an item. The bound is checked in the matching step in `src/import/provider.rs`, in `apply_in` in `src/store/write.rs`, and in `merge_in`, `resolve_in`, and native restore in `src/package/restore.rs` | +| Stored sizes of vendor originals | `vendor_original_sizes`, created by the step 8 SQL file. The rows are written beside the typed rows in `src/store/write.rs` and `src/package/restore.rs`. `ath check` compares them in `src/store/check.rs`, and `ath repair` rewrites them in `src/store/repair.rs` | +| The vendor-original total and its warning | the pull's text and `--json` outcome, from `pull` in `src/cli/commands/routes.rs` | +| Export refuses a document over the package read cap, or an item that reaches the nesting limit | `src/package/export.rs`, before the staging folder is renamed | +| The pull's `__proto__` and depth checks on each vendor object | `src/runtime/vendor_workouts.rs`, before the page is staged | +| Device-binding facts and the safety snapshot | new `src/import/binding.rs`, called from the matching step in `src/import/provider.rs` for route `open_wearables` | +| Create or first-bind with the checked receipt, and refuse any other `device_binding` change | the staged plan and `ProviderPreview::apply` in `src/import/provider.rs` | +| Stored-original read for the vendor detail rules | a crate-private read in `src/import/provider.rs` | +| Response cap, page cap, Suunto list cap, and the comment and route list that now name both pulls | named constants in `src/input_policy.rs` | +| Receipt for a start in Unix seconds or milliseconds | a helper beside `offset_timestamp_receipt` in `src/import/candidate.rs` | +| Measurement samples, source reports, paired null value and unit, and child withdrawal | `write_current_state` and `typed_columns` in `src/store/encode.rs`. Package restore, repair, and the record check use that encoder | +| Step 7 with foreign keys off | its own transaction in `src/store/migrate.rs`, and `install_schema` in `src/store/mod.rs` | +| Whole source record from the owner or a library caller | existing `ath correct`, protocol `records.write`, `records.write_changes`, and `records.correct`, package restore, and an accepted package merge | + +`src/store/`, `src/import/mapping.rs`, and `src/runtime/garmin_pull.rs` are +not the home for this client. `garmin_pull.rs` remains the Garmin pull. +The two clients may each call `ureq`. +A shared trait is the later connector work, and this release does not add it. + +The build adds this paragraph to `skills/athletic-standard/SKILL.md`, +under "Stable IDs and revisions": "Fix an Open Wearables workout on its +workout session, or write a note. Do not correct the vendor original. It +is the vendor's own copy. A later pull keeps your correction until the +server's data for that record changes. Then the pull replaces it, counts +it, and keeps your correction in the record's history." This plan pull +request does not edit the skill, because the skill describes the +released version. + +`mapping.rs` changes for `MappedPage` and for the preservation writes in +section 2: the measurement-sample target, the reporting-window write, the +segment copy, and the `vendor_workout` section. HTTP stays out of +`mapping.rs`. The mapped-import report from `report_value` in +`src/import/provider.rs` keeps its `outcome` field. The pull counts each +page by record type from its staged plan. For route `open_wearables` only, +the matching step runs the device-binding check in section 3 before a +staged plan can change a source device or a timeseries record. That check +is the shared mapped-import and pull enforcement. It is not a new match +key and it does not apply to any other route. The matching step also +reads the page's safety snapshot: the sources, records, import keys, and +archive keys named by that page, including tombstones and the current +revision. It does not scan the database. `ProviderPreview::apply` refuses +any `device_binding` change the checked rule did not make. The store +inserts and updates `measurement_sample` and `source_report`, and it +accepts a provider +summary or provider score whose `value` and unit are both present or both +absent. A half-null pair is refused. When an anchor in this response no +longer emits a child, that child is revised to the absent pair in the same +transaction. `write_current_state` in `src/store/encode.rs` writes that +pair and the new table. Package restore, repair, and the record check use +that encoder. `RecordType` in `src/model/` gains the `source_report` entry. +The eight range calculations, `provider-period-summary` among them, do not +read `source_reports`. `read_inputs` and +`read_period` also exclude `source_type` `manual`, and they have no +`include_manual` switch. `workout-drift` loads the named session first, +including a manual session, and uses that session's start and end as the +window. Its samples then go through `read_inputs`. A manual source's +numbers stay out. `query_measurements`, `query_series`, and +`query_sessions` in `src/store/query.rs` omit manual sources unless +`include_manual` is true. The JavaScript names in +`packages/npm/src/database.ts` call those functions. +This proposal does not change that code. A generic record listing is +not those three functions. In +`read_inputs` and `read_period`, a provider summary or provider score +whose `standard_value` or `standard_unit` is null is excluded in the SQL, +before the limit, the count, the grouping, and the numeric decode. A null +is not stored as zero and is not replaced by an older revision. The +session-summary branch of `read_period` uses the same filter on the +extracted number and unit. Formulas and source grouping stay as they are. +The archive is the pull-only preview and apply in section 2. A mapped file +import does not build it. It goes ahead only at the database revision the +protected preview read, and its apply refuses a moved revision. It does +not call the receipt operations. No other store behavior changes. The +owner and library writes in section 3 stay whole-record writes. They are +named there so the binding survives a 2.2.0 round trip. They are not a +new importer. The pull sums only `sleep_session`, `workout_session`, +`point_measurement`, `measurement_sample`, `provider_summary`, +`provider_score`, and `source_report`. A committed protected page adds +those counts to `committed`. A committed archive page adds its counts +only to `archive_committed`. A preview page adds its protected estimates +to `estimated` and its archive estimates to `estimated_archive`. It does +not add `outcome` across pages. `outcome` counts the source-device row in +the same group. Filtering that row out of the totals does not make a +preview equal a write. A preview page writes nothing, so page two does not +see page one. A vendor page is a protected page. Its originals add to +`committed.source_report` and to the vendor counts. + +The command reads the saved key and `OPEN_WEARABLES_API_KEY` in this +process, in `src/runtime/keyring.rs`. It has no `--key` flag. The +decoded-key walk in section 4 runs before `MappedPage`. The command +checks its own text before printing. + +The command returns the preview outcome from section 1 when the mode is a +preview, including public `--json`. It returns the confirmed outcome when +the mode is `--yes` without `--json`. On a partial failure it keeps that +confirmed outcome and then exits nonzero. It prints text from the confirmed +outcome and public JSON from the preview outcome. The success sentence is +printed only after `--yes` when `range_complete` and `snapshots_complete` +are both true. There is no child process. + +The program runs on Linux, macOS, and Windows with the same command. The +fixture server listens on `127.0.0.1` and an ephemeral port, which is the +pattern `src/runtime/garmin_pull.rs` already tests. Mapping paths stay +`resolve_mapping` in `src/assets/mod.rs`. No new installer and no new +system library. + +## 7. Tests + +CI has no Open Wearables account, no API key, and no Docker Compose. The +acceptance tests are the fixture server and the synthetic files already in +`tests/fixtures/exports/open-wearables/`. Those files are on the public-data +list. A new file, such as a two-page response or the two-window Garmin +fixture below, is synthetic, +invented, and added to `tools/public-data-allowlist.json` with its path +and SHA-256. `tests/public_data.rs` enforces that list. No real +export is copied. + +Before the first request, `--from` and `--to` are both dates or both +timestamps with an offset, `--from` is not after `--to`, and a calendar date +is a real date. A number is refused here even though Open Wearables accepts +Unix seconds. A bad bound does not open a socket. + +Rust tests, run by the existing `cargo test` job on Linux, macOS, and Windows: + +- two pages, the second `next_cursor`, then `has_more: false`. `--yes` + with a finished body and personal record prints the success sentence. + A finished range whose body read fails says the range is complete, names + the body snapshot, does not print the success sentence, and exits + nonzero. A preview says the snapshot would be stored. An empty ranged + result can still store the personal record +- the same session id on two pages, identical payload: the preview estimate + counts two new rows, and `--yes` counts one new and one unchanged +- the same session id on two pages, changed payload: the preview estimate + counts two new rows, and `--yes` counts one new and one changed +- a valid page, then a failing page, under `--yes`. The failure is one of a + 401, a 429, a repeated or null cursor, a vetoed page, or a minimum page + that is still over the response cap. Page 1 remains. Page 2 adds no rows and no revisions. No later read + runs. The exit is nonzero. The success sentence is absent. The text gives + the retained counts. The same command run again stores no second copy +- the same failure sequence with no `--yes`, and again with `--json --yes`, + makes no database changes. Rows that were already stored stay. A + successful `--json --yes` of a readable range is also a preview and makes + no database changes +- an installed mapping that does not implement section 2 fails before any + request. The server sees no request. Raw and day timeseries requests omit + `types`. A comma-joined type string is not sent +- a cursor or offset page fails before `MappedPage` when the object is + missing, `data` is not an array, `pagination` is missing, or `has_more` + is not a boolean. That failure is not an empty success. A body response + of JSON `null` is a completed empty snapshot and writes nothing. A body + object is mapped. A health-score page ends on `has_more: false`, and a + smaller retry uses the same offset +- `filter_by_priority=false` is present on the reads that have the flag. + Raw timeseries sends `resolution=raw`. Day timeseries sends + `resolution=1day`. Sleep sends `include=stages`. Workouts send + `include=zones` and `include=segments`. A fixture with stages omitted has + null intervals and still has stage totals. A fixture with `include=stages` + keeps the intervals under the server's names. A fixture with + `include=zones` keeps the nested heart-rate and power zones under the + server's names. A fixture with segments keeps the original objects, and a + segment that has a label is also a typed segment +- a raw `heart_rate` row becomes a measurement sample in bpm at the + server's timestamp. Export and import keep that timestamp, unit, and + value. A day row for heart rate, steps, running speed, resting heart + rate, RMSSD, SDNN, and blood oxygen becomes a provider summary with + `open_wearables_reporting_window`, no `recorded_at`, and the server's + `timestamp` and `period_end`. Check, export, and import keep that window + and do not invent an instant. A step length of 70 cm is stored as 0.70 m. + A stride of 120 cm is stored as 1.20 m. The input number and `cm` stay + on the record. Raw `heart_rate_recovery_one_minute` is quantity + `hr_recovery` in bpm. A finite zero and a finite negative value are + stored. Import, a repeat pull, and the package export and import keep + the quantity, the unit, the key, and the value. A heart-rate point of + zero is still left out. A negative `temperature_deviation` is still + stored. A 2.1.0 mapped file and this pull, in either + order, keep one record id and the old import key. Every row in the appendix table has one raw fixture and + one day fixture. Check, export, and import keep the input pair, the + standard pair, and the day window. Raw + `vo2_max` stays `provider_summary.vo2_max` on its 2.1.0 key. A day + `vo2_max` row is a different window summary. Raw `garmin_stress_level` + and `garmin_body_battery` stay provider scores on their existing scales + and keys. They do not become samples. A null RMSSD beside a present SDNN + stores only the SDNN. A sleep-summary respiratory rate is date-only. The + sleep session from the same night still has no respiration field. Nap + totals do not receive main-sleep bounds. Two main sleeps of 240 and 120 + minutes store duration 360 on `provider_date` only. Skin temperature is stored + from a series row or from body latest when that time is present. A + recovery object does not gain a skin field. A WHOOP health-score + component named `skin_temp_celsius` stays on that object. + A 2.1.0 raw point and a + pull of that same raw point stay one record. A heart-rate sample from + device B does not replace device A's sample. A negative latitude and a + negative longitude are stored +- a response larger than the response cap on a cursor or offset read is + requested again with a smaller limit, the same cursor or offset, and the + rows are stored. A day page at `limit` 1 that holds many small rows and is + still over the cap leaves that read incomplete and names the read and + `resolution=1day`. It does not name a series type. An oversized body + response names `body` and writes nothing. The export after a pull, and a + native package import, keep period bounds, units, `computed_by`, + segments, score components, meal nutrients, and a pregnancy snapshot +- a summary shaped like `summaries_service.py`, with no `device_id`, is + stored after a bound raw page. The device receipt and the device's + points stay. The same summary stored first does not block a later raw + page from binding its device source. File import then pull, pull then + file import, and import then import keep one summary id. A refused + device page refuses only that page. Two meals with one timestamp and + different ids stay two records. Two summary fields on one date stay two + records. A page with one bound heart-rate row and one same-triple row + whose `device_id` is missing refuses the protected page. Neither row + is stored as a measurement. The pull archive stores both series rows + as capsules, with `resolution` copied from the response and no device + receipt. A mapped file import of that page refuses and stores no + capsule. A later pull page that has only the valid row stores that + measurement. The capsule remains a different record. Export and native + import keep the resolution. A raw capsule and a day capsule of the same + row body stay two records. A sleep id that + is missing, beside a valid workout, refuses the page before any write + and is not archived. The next page is still refused on its own failure. + A measured timeseries row with + `source: null` is stored on the unattributed sensor when the payload + matches. A reported row with `source: null` uses the report sensor + only. A different payload with the same full key, including + resolution and `period_end`, refuses the protected write and archives + the new original. A mapped file import of that changed payload writes + nothing. A raw midnight row and a day window that starts then + stay two records. A preview of those two pages does not claim the + conflict, because the first preview page wrote nothing. A confirmed + second page does. +- each of the four page refusals prints the owner's fix from section 2, + and each fix works. After `ath correct` sets `device_binding` on a bound + source to a new id, the next pull accepts rows with that id, and a new + row replaces an old one only where the match keys are equal. The + refusal text says the rebind merges the two devices' history on that + source, and `ath records show --history` shows the old + binding in the source's history. After + `ath correct` adds `device_binding` to an unbound source written by + 2.1.0, the next pull refreshes that history. After `ath correct` + replaces a malformed receipt with a nonempty string, the next pull + goes on. A bound source that receives rows with no id stays refused, + and its text names no rebinding fix. After `ath erase` of a workout + whose kind changed, the next pull stores the new kind as a new record + with a new record id. +- a missing device id beside a conflicting device id, in either row order, + refuses the protected page and stores no capsule and no revision. The + same veto holds for an unbound legacy history and a missing workout UUID + on the same page as an eligible row. A deleted source on a page with an + eligible row leaves that source's rows out with the D190 line. The + eligible row still refuses the protected page, and the deleted source + stops the archive, so no capsule is stored. The API key, the server + origin, or the selected user id on a neighboring object builds no + preview. A deleted archive source is not recreated. An existing device + receipt is unchanged. On an empty + database, the first eligible archive sets + `written` false, `database_changed` true, `archive` `stored`, and the + text `Protected write refused; N originals archived; database changed; + pull incomplete.` A repeat on that empty database sets `archive` + `unchanged`, `written` false, `database_changed` false, and the text + `Protected write refused; 0 originals archived; database unchanged; pull + incomplete.` A third payload adds one archive count and + leaves the earlier capsule. An archive apply failure on that + empty database sets `archive` `failed`, keeps the refusal, adds no + archive row, leaves `written` false and `database_changed` false, and + uses the text `Protected write refused; archive failed; database + unchanged; pull incomplete.` The same four results after an earlier + committed sleep page keep that page's `written` true, its `committed` + counts, and `database_changed` true. The failure text then says + `database changed`. + Preview and `--json --yes` apply neither plan +- two connections, both row orders. After the protected preview and before + its apply, the other connection commits a binding of device C on source + S. The page has a series for S with device B. The protected apply + refuses because the database revision moved. `archive` is + `not_attempted`. No capsule, source revision, or receipt change is + written. The same refusal holds when the other connection commits a + tombstone or history on S instead of the binding. A page whose safety + snapshot has no veto and whose protected preview refused it, then a + deletion of S before the archive, leaves `archive` `not_attempted` and + does not archive S's payload. The same holds when the other connection + deletes the normalized record or its import key, deletes the archive + source or an existing capsule, or makes an owner correction, between + the protected preview and the archive apply. Nothing is recreated, and + no second identity is stored. An already deleted neighbor, in either + row order, is left out with its line, and the page is not archived. The + API key on the page builds no preview. An earlier committed sleep page + keeps `written` true, its `committed` counts, and `database_changed` + true. The text is `Protected write refused; archive not attempted; + database changed; pull incomplete.` +- every athlete-data write moves the database revision: `Store::apply`, + `ProviderPreview::apply`, repair, erase, and a package merge. A restore + into an empty database sets the package's revision and database ID, and + the apply refuses another database ID. A test commits each of these + between a protected preview and an archive apply, and each one makes the + archive `not_attempted` +- sensors `ow1:["summary","sleep",null]` and a colon inside a provider + name stay different from a shifted tuple. The text `-` is not the same + sensor as a missing part. A score whose input source changes from null + to an object keeps its id. A personal record repeats. A personal record + with no birth date uses the time-unknown receipt. A meal with calories + and two nutrients stays three children plus the anchor +- an internal health score has basis `aggregator`. A vendor score has + basis `provider`. A null `provider` omits the basis. Polar readiness uses + scale `0-10`, Polar recovery uses `1-6`, and WHOOP strain uses `0-21`. + A score with no finite range keeps its number on the anchor and does not + use scale `0-100`. An Oura sleep score uses `1-100`. A Polar recovery + summary value of 3 and the Polar health score use scale `1-6`. A WHOOP + recovery summary uses `0-100`. An author missing from the range table + is a source report and is not given `0-100`. A null value and a + later number revise the same record. `computed_by: null` omits the basis + and keeps the null. A raw row that omits `computed_by` keeps + `provider_or_aggregator` +- body fetched during a historical range is the current object. Weight + with no time has no `recorded_at` and does not use the average window. + A latest value with a null time is stored the same way. A body object + whose `skin_temperature_measured_at` is a raw-looking instant, and one + whose timestamp is a day `period_start`, both keep the amount, the unit, + and the timestamp on the original. The skin-temperature child has no + `recorded_at`. Import, pull, and the native package roundtrip keep that + child out of an instant calculation. A raw skin-temperature sample and a + day skin-temperature window keep their own classes. Age is a source + report. The service calculates it, and the record has no `field_basis`. + BMI's basis is omitted. The three groups can arrive + together or alone. JSON null and a returned zero and a missing field + stay three different results +- a dietary series, `number_of_alcoholic_beverages`, and `hydration` are + source reports, not samples, not provider summaries, and not nutrition + entries. Raw and day hydration stay out of the eight range calculations + and out of `provider-period-summary`. A device id on the hydration row + does not create a receipt. A null-source hydration, + `dietary_energy_consumed`, or index row, raw and day, uses only the + report sensor. File import then + pull, pull then file import, and a repeat keep one record and no + receipt. A changed payload refuses the protected write. A pull with no + veto archives that new capsule and leaves the stored report. A mapped + file import writes nothing. The row is not a calculation input. A cycle + code, a predicted length, and a pregnancy snapshot stay on the anchor. + A cycle that starts in range and ends later keeps that end. A cycle that + starts later is not stored, and the read can still complete. Birth date, + gender, and sex are source reports. Gender is not copied into the + athlete profile. A matching `user_id` is not stored. A different, + absent, null, or non-string `user_id` on the HTTP object refuses the + page. The canonical envelope without `user_id` imports. The athlete + profile is unchanged +- step 8 keeps an old summary's id, number, unit, `data_json`, import key, + revisions, and tombstone. A numeric summary can be corrected to + numberless and back. A half-null value and unit is refused. A sample + repeats and corrects. `ath check`, export, native import, and restore + accept the numberless summary, the numberless score, and the sample. A + meal nutrient that changes from a number to null, then back, keeps one + child id. A null body group withdraws that group's children. A refused + page restores the withdrawn child. A range calculation that sees a + numeric summary and a numberless summary uses only the numeric row. + The same is true for a score, on the instant reader and the period + reader. An all-numberless set adds no inputs and does not fail the + calculation. After value, then null, then value, the calculation sees + the current number and not the withdrawn one +- two distinct sensor triples become two sources. Device A is stored, then + a separate operation contains only device B at the same triple, type, and + instant, with a different value. The operation fails. The current point, + its revisions, the source, and hardware are unchanged, and the range is + not complete. The pairs are pull then pull, pull then pull in reverse, + file import then pull, and pull then file import. The same collision + inside one page, and split across two pages, refuses the failed page + instead of keeping one device and dropping the other. On `--yes`, an + earlier committed page stays. Preview and `--json --yes` make no database + changes. Equal values with different ids still fail. B at a different + timestamp fails before hardware changes, and a later B row does not + replace A's older point +- the same `device_id` with the same payload is unchanged. The same + `device_id` with a changed value revises that record and does not change + the binding. Import then pull, and pull then import, of that one device + keep one record id. Mapped file import of device A, then a second mapped + file import of only device B, fails the same way. A missing, null, or + blank id does not replace a bound source. A 2.1.0 source that already has + history and has no source key `device_binding` is refused, including when + the only history is a deleted record or a deleted source device, and + including when `supplied_fields.device_binding` is already the string for + device B. The same misleading field in a 2.1.0 package is still a supplied + field after import. Device B does not replace A's point. The supplied + field and the hardware stay. No source key is added. A sample keeps basis + `provider_or_aggregator`. A raw Garmin score keeps basis `provider`. An + internal score keeps basis `aggregator` +- a raw page and a mapped file that carry `device_binding` on the row, on a + nested source object, and inside `supplied_fields` do not set, replace, or + erase the source key. A mapping whose `name` changes and whose + `device_hardware` stays `source.device_id` keeps the same binding. A + mapping whose `device_hardware` points elsewhere is refused before any + write. A mapping that sends a device row to an `ow1` sensor, or that + changes a series class in the appendix table, is refused before any + request +- an existing open-wearables source has no receipt, no record, and no + source device. The first accepted write stores the checked receipt on + that source. Its other fields, its writer, its route, its sensor, and + its baselines stay. The revision and `data_json` record that receipt. A + source whose only history is a deleted record or a deleted source device + is still refused, and that refusal writes no receipt +- a new source of only id-less sleep is stored with no source key. A later + timeseries row with an id is refused, and the sleep row stays. One call + that accepts both an id and a missing id is refused. A `left_out` row does + not create a binding. The first preview page is id-less sleep and the + second preview page has an id for that same source: the preview refuses + and writes nothing +- a mapped page never revises a stored source except by the checked first + bind. A staged plan that would set, change, or clear `device_binding` + any other way is refused by `ProviderPreview::apply`, and the source is + unchanged. `ath correct` with a complete source object replaces that + object, and protocol `records.correct` does the same. After that + correction, a mapped write follows the source key the correction stored +- export a 2.2.0 database that has an established binding, import that + package, and the source key and the import keys are still there. The same + id can correct the point. A different id is refused, with no new point + revision, source revision, or hardware revision. A stored source key that + is not a nonempty string refuses the automatic write and is left unchanged +- `page-sleep.json` becomes a sleep session. A manual workout and its + automatic neighbor from one response stay two records. The automatic + workout is a session on the device source. The manual workout is a + workout session on the manual source, with `field_basis.value` + `entered_by_hand` and no device receipt. A `device_id` on that object + stays on the original. A workout with `entry_source` `unknown`, null, + or omitted is an `unknown_workout` report. It is not a session and not + a manual workout. The same server id arriving later as `automatic` + refuses the page, and the stored session stays. A later pull of the + same manual workout updates that session. Export and import keep the + pair that was accepted. `workout-drift` named on that manual session + uses its start and end. A wearable sample inside the window is an input. + A manual sample and the session's own heart rate and distance are not. + `query_measurements`, `query_series`, and `query_sessions` omit the manual + session unless `include_manual` is true. That switch is not claimed for + every record listing. + `page-raw.json` is stored. + RMSSD and SDNN stay different quantities +- a changed end time keeps the record id and increases the revision +- a `__proto__` key nested inside a supplied field fails the page, because + `check_supplied_fields` refuses it (D191). An empty supplied-field name + fails it too. A package that holds a `__proto__` key still restores, + because D214 keeps the key in the native reader +- a Polar list of three objects, where one detail has a `__proto__` key + nested in a route point. All three originals are stored. The one with + the bad detail holds its list object, `detail_status` `refused`, + `refused_by` `unusable_name`, and the key's path in `refused_path`. + Polar's details count 1 `refused`, Polar is `completed`, the exit is 0, + and the page is not refused. One `left_out.examples` line names + `polar`, that vendor id, and the key's path. A second pull with the + same list objects makes no detail call for that id and counts it + `refused` again. A Polar list object with the key gets no detail call, + is not stored, counts 1 `unusable_name` in `left_out`, and is named the + same way +- a literal key, a Unicode-escaped key in a nested unconsumed field, the + key used as an object key, the selected origin, and the selected user id + each reject the page before mapping. The database, its revisions, and the + export do not contain them. The error text does not contain them. A page + that committed earlier remains. A problem `code` or a transport error that + contains those values is withheld +- a redirect is not followed. `http` to a non-loopback host is refused. A + base URL with a user name, a query, or a path is refused. A user id that + is not a UUID is refused before a socket opens +- the 1000-page cap is tested with a small limit passed into the loop +- a timestamp with no offset is left out. The stored fixture's timestamps + include `Z`. The test does not add `Z` +- a deleted mapped source is left out. A Garmin file import of a different + workout remains a second source +- `left_out` in the result is a total, a count for each reason, and at + most 20 example lines. With 21 lines it says the list was shortened +- on a mixed page with new, matching, and changed rows of three record + types, the count beside `Staging::count` gives the same numbers as + counting `ProviderPreview::planned` by record type and action +- a synthetic Polar list without samples, zones, and route, then one + detail with all three true, stores one original with `detail_status` + `stored`. The nested samples are not measurement samples. A second + identical pull makes no detail call for that id, counts it `kept`, + changes no row, and reports no database change for that original. A + changed list object whose new detail has an empty `route` writes + nothing for that id, counts it `thinner`, and keeps the stored original. + The stored workout with a different Open Wearables id stays a separate + session. A device id on the vendor object does not set `device_binding`. + The result text does not print a route coordinate. It does say the + originals keep account ids, user URLs, and full routes +- a Strava detail with `laps`, `splits_metric`, `segment_efforts`, and + `map` is stored. A later changed list object whose detail has no + `segment_efforts` is `thinner` and writes nothing. A Whoop detail is + never `thinner`, because the table names no Whoop detail field. After a + changed Whoop list object, a new detail with fewer fields replaces the + stored one, and the earlier detail is still in the record's history. + Garmin, Suunto, and Oura behave the same +- a failed Polar detail for a new id stores the list object with + `detail_status` `failed`. Polar is `incomplete`, and the command exits + nonzero. The same failure for an id that has a stored detail and a + changed list object writes nothing and adds no revision. A detail that + names another id is `mismatch`, is not stored, and also makes Polar + `incomplete` +- a Polar detail over `MAX_PULL_RESPONSE_BYTES`, with the cap lowered for + the test, is `too_large`. The list object is stored alone, Polar is + `incomplete`, and the exit is nonzero. A Polar detail that holds the + selected user id is `refused` by `privacy_scan`, is not stored, and makes Polar + `incomplete`. The list object of that id passed the scan and is stored. + On the next command, a new Polar id is detailed before either of them +- 101 Polar ids with no stored detail. The first pull makes 100 detail + calls, oldest start first, and the newest id is `deferred`. Polar stays + `completed` with `deferred` 1. The second pull details that id first +- 45 Strava ids with no stored detail. The first pull details the 20 + oldest starts and stores the other 25 with `detail_status` `deferred`. + Strava stays `completed`, its line counts 25 deferred, and the exit is + zero when nothing else failed. A second pull details ids 21 to 40 in + start order. A third pull details the last five. A deferred id whose + original already has a detail, and whose list object changed, keeps + that detail, writes nothing, and adds no revision +- an owner corrects a stored Polar original with `ath correct`. The next + pull with the same server data writes nothing for it, the correction + stays current, and Polar's `owner_corrections_replaced` is 0. That pull + makes no detail call for the id, because the stored-original read uses + the newest `provider_import` revision. After the server's list object + changes, the preview prints `estimated: would replace 1 owner + correction; delete an original to keep it`, and `--json` has Polar's + `estimated.owner_corrections_replaced` 1. `--yes` replaces the + correction, counts it as a changed original and as 1 replaced, and + keeps the owner's revision in the history. A deleted original is left + out instead, and the count stays 0 +- an owner corrects a stored sleep session. A pull with the same server + data keeps the correction, and `--json` has + `estimated_owner_corrections_replaced` 0. A pull whose session changed + replaces it, and the count is 1 in the preview, in `--json`, and after + `--yes`. The preview says `estimated: would replace 1 owner correction + of stored records because the server's data changed`. `ath import + --mapping open-wearables` of a file that holds the same data also keeps + the correction. Another route keeps its 2.1.1 rule. The matching unit + test reads the basis from `record_revisions.became_known_at_basis`. A + revision whose `changed_by` is the tool actor `ath` and whose basis is + `local_write` counts as an owner correction +- a package merge of two sleep sessions. The first had no conflict, and + its merged revision keeps basis `provider_import`, so a pull whose + session changed replaces it with no owner-correction count. The person + resolved a conflict on the second as imported, so its current revision + has basis `package_merge`. A pull whose session changed replaces it, and both + `estimated_owner_corrections_replaced` and + `estimated_merge_choices_replaced` are 1. The preview line adds `(1 of + them a merge choice)`. A native export and restore keeps every + revision's basis, so the same pull reports the same counts before and + after the restore +- a body snapshot whose owner corrected its original, pulled again after + the server's averaging window moved, replaces the correction and counts + 1 `estimated_owner_corrections_replaced` +- without `--vendor-workouts`, preview and `--json` make zero requests to + the connections route and to both workout routes. `requests_made` is + false, `notice` is empty, and every live line is `not_attempted`. With + the flag, preview and `--json` still write nothing, `requests_made` is + true, and the text says vendor requests were made. The fixture server + sees the connections request and each list request, and no detail + request. The help text of `--vendor-workouts` and + `src/cli/examples/pull.txt` say that a preview and `--json` read the + connections list and each active provider's list and make no detail + call, and the generated `skills/athletic-standard/references/cli.md` + matches them. The preview counts the ids `--yes` would detail as + `would_detail`, and says that a preview then `--yes` reads each list + twice. A Strava preview then `--yes` sends two list calls and at most 20 + detail calls +- `--vendor-workouts --json` with three new Polar ids writes nothing, and + the fixture server sees no detail request. Every vendor count, and the + owner-correction and merge-choice counts, are under a key named + `estimated`. Polar's + `would_detail` is 3, and no key that means stored is above zero. + `notice` holds the line that the preview made no detail calls. The text + preview prints that line, and its Polar line contains `estimated`. + `--yes` on the same data prints the same counts without `estimated`, + with `stored` 3 +- every run with the flag, as a preview, under `--yes`, and with `--json`, + says before its first live request that the server may refresh and save + vendor tokens, may revoke a connection, and may wait about 105 seconds + on a rate limit. `--json` holds those three sentences in + `vendor_workouts.notice` and is still one JSON value. The help text of + `--vendor-workouts` and `src/cli/examples/pull.txt` say the same, and + the generated `skills/athletic-standard/references/cli.md` matches them +- a connections list for the selected user whose items carry `user_id`, + `linked_user_ids`, `id`, `provider`, `status`, and other fields passes. + It is not stored, and no other user's id is printed. One item whose + `user_id` is another user refuses the list, and every provider is + `not_attempted` +- an active Garmin connection and a revoked Polar connection call only + Garmin. Polar is `not_attempted` with `connection_status` `revoked`, and + the fixture server sees no Polar request. `expired` is the same. A + status the pin does not define prints `unknown status` and is not + called +- a connections list with only Garmin completes Garmin and marks Polar, + Suunto, Whoop, Fitbit, Oura, Strava, Withings, and Sensorbio + `not_attempted`. A failed Polar list does not stop Garmin +- a Suunto list object `{"workoutId": 1001, "workoutKey": "abc"}` calls + detail at `abc`. The detail's `payload` is unwrapped. One record is + stored, and its key ends `suunto|1001`. A detail that names 1001 or + `abc` matches. A list object with no `workoutKey` makes no detail call. + It is stored with `detail_status` `not_available`, and Suunto stays + `completed` +- a Suunto fixture that always returns full pages, with a small list cap + and a short pace passed into the loop as the 1000-page test does, stops + at the cap. Suunto is `incomplete`, `more` is true, the objects already + read are stored, and the exit is nonzero. `MAX_SUUNTO_LIST_REQUESTS` is + checked as a named constant of 100 +- a Garmin `activityId` of `123` and a later `"123"` are one record. An + integer above 9007199254740991 refuses only that object and counts it + as `unsafe_number`. A fractional id refuses only that object and counts + it as `unusable_id`. Two different objects with one id are both + refused as `duplicate_id` +- a synthetic database of route-heavy Polar originals totals just under + `MAX_VENDOR_ORIGINAL_BYTES`, as export measures it. Each original has a + 3,600-point route, six sample strings, and five zones, and some have a + second revision. `ath export` succeeds, its main document is at most + 512 MiB, and the originals' items in it total the measured bytes. `ath + import` of that package into a database made by `ath init --empty` + keeps every record id, revision, deletion, and import key, and the + restored database passes `ath check`. One more original is refused by a + pull page, by a mapped import of the same envelopes, by `ath correct`, + by a protocol record write, by a package merge, and by a native + restore. Each refusal writes nothing. The page counts its objects as + `size_cap` and makes that provider `incomplete` +- after a pull, an `ath correct` of one original, a delete, a package + merge, a native restore, and an `ath erase` in the size fixtures, the + sum of `vendor_original_sizes` equals the bytes `ath export` writes for + vendor-original items under `records` and `record_revisions`. The test + counts those bytes in the exported main document. `ath check` passes + after each step. A row changed by hand fails `ath check`, which names + the record, and `ath repair` puts the measured size back. An `ath + correct` of one original measures two items +- the pull prints `vendor originals use X MiB of 256 MiB` on a run + without the flag, on a preview, and on `--yes`, and `--json` has + `used_bytes` and `bound_bytes`. Under 80% of the bound there is no size + warning. At 80% the text and `vendor_workouts.notice` hold the warning. + It names `ath erase`, says the erase cannot be undone, and says that a + later version may lift the bound. It does not say `maintainer` +- an export whose main document would pass the read cap, with that cap + lowered for the test, fails before the rename and publishes nothing. So + does an export whose item would reach `MAX_PACKAGE_JSON_NESTING`, 128 + levels, from a record the test writes straight into the database. An + item 127 levels deep exports, and `ath import` reads it back +- a Polar list of three objects, where one detail is nested 125 levels. + That detail is not stored. Its list object is stored with + `detail_status` `refused` and `refused_by` `too_deep`, and the other two + originals are stored. Polar's details count 1 `refused`, Polar is + `completed`, the exit is 0, and one `left_out.examples` line names + `polar`, that vendor id, and 125 levels. `ath export` then succeeds, + and `ath import` reads the package back. A detail nested 122 levels is + stored, exports, and reads back. One nested 123 levels is refused. A + list object nested 125 levels is not stored, gets no detail call, and + counts 1 `too_deep` in `left_out`. A mapped import of a saved envelope + whose `detail` is nested 125 levels leaves it out as `too_deep` +- a synthetic Garmin fixture returns activity 555 in the first window with + `durationInSeconds` 1800 and in the second window with 1860. One original + is stored, and its `list` is the second window's object. Garmin's + `left_out` counts 1 `superseded`, and Garmin is `completed`. The same id + with equal objects in both windows stores one original and counts + nothing. The same id twice in one window, with different objects, + refuses both as `duplicate_id` +- a two-command Garmin fixture. The first command reads both windows and + stores the 1860 copy with the second window as its `upload_window`. A + second command reads only the first window and sees the 1800 copy. It + counts 1 `superseded`, makes no detail call for it, and writes nothing. + When the person had corrected that original, the correction stays + current, and `owner_corrections_replaced` is 0. In the other order, the + second command's later copy replaces the stored earlier copy as a + change. A third command reads the unchanged 1860 copy through a later + window, as when Garmin received it again, and writes nothing +- a Garmin fixture with two ranges one day apart. Activity 557 was + uploaded at 22:30 UTC on 16 January 2026, and again with a different + `durationInSeconds` at 06:00 UTC on 17 January. The first command, + `--from 2026-01-16 --to 2026-01-17`, sends four windows, from 02:00 UTC + on 15 January to 22:00 UTC on 18 January. It stores the 06:00 copy with + the window from 00:00 to 23:00 UTC on 17 January, and it counts the + 22:30 copy `superseded`. The person then corrects that original. The + second command, `--from 2026-01-15 --to 2026-01-16`, sends three + windows, from 03:00 UTC on 14 January to 00:00 UTC on 17 January. Its + last window returns the 22:30 copy and ends where the stored window + starts. That copy counts 1 `superseded` and gets no detail call. + Nothing is written, and `owner_corrections_replaced` is 0 +- two Garmin commands whose `--from` timestamps are 12 hours apart, + `2026-01-16T00:00:00Z` and `2026-01-16T12:00:00Z`, each for two days. + Each window both commands send has the same `summary_start_time` and + `summary_end_time` in both, and each is a multiple of 82,800. The + second command gets activity 558 with a different object in one of + those windows. Its copy is a later read of the same window, so it + replaces the stored copy as a change. When an owner correction was + current, it is replaced, and `owner_corrections_replaced` is 1 +- a mapped import of a saved Garmin envelope with a different object, + whose `upload_window` overlaps the stored copy's window without being + equal. It counts 1 `ambiguous_window`, writes nothing, and keeps the + stored copy and any owner correction, so `owner_corrections_replaced` + is 0. A saved envelope with a different object and the stored window + counts the same way +- a three-day Garmin range, `--from 2026-01-01 --to 2026-01-03`, sends + four windows of 82,800 seconds. The first starts at 1767200400, 17:00 + UTC on 31 December 2025, and the last ends at 13:00 UTC on 4 January. + Each window sends `summary_start_time` and `summary_end_time` as + integer Unix seconds. Each start is a multiple of 82,800, and each + window starts where the last one ended. A date `--from` starts at + midnight UTC. One failed window makes Garmin `incomplete` and never + `completed`. A later window + still runs +- three Garmin ids are due a detail call, and the first detail call + answers HTTP 404. The fixture server sees no second Garmin detail + request. The first id is stored with `detail_status` `not_available` + and a `detail_checked_at` equal to the test clock, and the other two + with `deferred`. Garmin is `completed`, its line says `Garmin detail + unavailable (HTTP 404); list objects stored` and `2 deferred (not + asked: detail unavailable this run)`, and the command exits 0. + HTTP 501 does the same. On the next command, the `not_available` id, + whose list object is unchanged, gets no call and counts as + `not_available` again, and the probe is the older of the two deferred + ids. When the probe gets a detail, a later Garmin detail that answers + 404 is `not_available`, and the next id is still called. A later Garmin + detail that answers HTTP 500 is `failed`, Garmin is `incomplete`, and + the exit is nonzero. A Polar detail that answers 404 is `failed`. A + Garmin list window that answers 404 fails that window +- three Garmin ids are due a detail call, and the probe answers HTTP 403. + The fixture server sees one Garmin detail request. All three ids are + stored with `deferred`, none is `not_available`, Garmin is + `completed`, and the exit is 0. The next command probes the same oldest + id again. HTTP 400 and 405 do the same. A probe that answers HTTP 503 + also defers all three, and Garmin is `incomplete` with a nonzero exit +- a Garmin id that a 404 marked `not_available`, with an unchanged list + object and the command's clock passed in. At 29 days after its + `detail_checked_at` it gets no call. At 30 days it is called after every + other group. A repeat 404 writes one revision with the new + `detail_checked_at` and the stored `upload_window`, and it counts + `not_available` 1 and one changed original. A detail stores it. When + the probe answers 404 for another id first, the recheck id keeps + `not_available` and its time, and nothing is written for it. When the + original's current revision is an owner correction, it gets no call at + 30 days +- a live detail that answers HTTP 401, for Garmin and for Polar, counts + as `failed`. The fixture server sees no later request to that provider + in the command. Each id still due a call is `deferred`, the provider is + `incomplete`, and the exit is nonzero. The Garmin line says `Garmin + answered 401: reconnect the provider in Open Wearables if this + repeats`, and the Polar line says the same with `Polar`. A Garmin + window that answers 401 sends no later window +- live requests go one at a time, at least one second apart by the + fixture server's clock. A live request that times out, with the read + timeout shortened for the test, stops every later request to that + provider in the command. The next provider still runs. The 360-second + value is checked as a named constant +- four Polar ids with no stored detail, with the read timeout shortened + for the test, where detail call two times out. Id one stores its + detail, id two is `failed`, and ids three and four are `deferred`. + Polar is `incomplete`, and the fixture server sees no third detail + request +- five Strava ids with no stored detail, where the third detail call + answers HTTP 429, and a sixth id with a stored detail and an unchanged + list object. The fixture server sees no later Strava request. Ids one + and two store their details. Id three is `failed`. Ids four and five + are `deferred`. Id six stays `kept`. All six list objects are stored. + Strava is `incomplete`, the next provider still runs, and the exit is + nonzero. A 429 on a Garmin window sends no later window +- three Garmin ids: a new id, an id that was `not_available` whose list + object changed, and an id that was `not_available` whose list object is + unchanged. The new id is detailed first, then the changed id. The + unchanged id gets no detail call and counts `not_available`. An id that + was `too_large` and whose list object changed is detailed with the + changed ids, before an unchanged `too_large` id +- a Garmin list object with `userAccessToken` is pulled twice, with a + different token value the second time. The second pull counts it + `kept`, makes no detail call, and writes nothing for it +- an empty database is pulled once without `--vendor-workouts`, which + stores the personal record. A second pull of the same stored data with + the flag, whose only new rows are two Garmin originals, reports + `written` true and `database_changed` true, `committed.source_report` + new 2, and Garmin `originals` new 2. A third identical pull reports both + flags false +- a Garmin list object with `userAccessToken` stores that original with + the value `[withheld by ath]`. The record, the export, the text, and + `--json` do not hold the token. `withheld` counts 1 and names the path. + The same holds for `access_token`, `refresh-token`, `id_token`, + `session_token`, `token`, `embed_token`, `client_secret`, `apiKey`, + `authorization`, and `password`, and for a `token` query parameter in a + URL string. The URL keeps its address and its other parameters. A user + name and password before the `@` in a URL, and an `access_token` pair in + a URL fragment, are withheld the same way. The API + key under a credential-shaped key still refuses the page. A `polar_user` + URL and a route coordinate are stored unchanged +- a Whoop response whose `next_token` is `"abc"` keeps that value, does + not count it as withheld, and sets `more` true. A null `next_token` + stays null and sets `more` false. An Oura response does the same. A key + named `NEXT_TOKEN` is still withheld, because the exemption matches the + two names exactly +- a Sensorbio body stores `data[].activities[].id`, with the parent entry + as `list_parent`. A missing id refuses that object, counts it as + `missing_id`, and keeps the others. File import of the saved original, + then export, keeps one record id. Sensorbio's line says it reads only + the oldest 50 entries +- a Polar exercise whose start is outside `--from` and `--to` is stored + and counted under `vendor workout originals`. `range_complete` still + follows the stored ranged reads. A Polar `start_time` with no offset has + no `reported_at`, and its receipt says the source gave no offset. A + Suunto start in Unix milliseconds keeps the digits and stores + `reported_at` with milliseconds. Both receipts pass `ath check` +- a Whoop response with a `next_token` that is not null, an Oura + response with a `next_token` that is not null, a Sensorbio response + with `links.next`, and a Strava page + whose length equals `per_page` set `more` true. The fixture server sees + no `nextToken` sent to Whoop. `covers_requested_range` is false +- a vendor original that the person deleted is left out on every later + pull, counted as `deleted_record`, and not recreated. A deleted + `vendor_workout` source leaves out every object from that provider as + `deleted_source`. An original that the person corrected gains a + revision with the server's envelope when a later envelope differs from + the newest `provider_import` revision, and the correction stays in its + history. An envelope equal to that import revision writes nothing, even + though it differs from the correction, and the correction stays current +- with the flag on, a run whose protected page is refused and archived + still writes the vendor page and keeps its counts apart from + `archive_committed`. A refused + vendor page leaves the archive and the stored pages as they were +- a vendor list response that the privacy scan refuses stores nothing + from that response, counts its readable objects as `response_refused`, + and makes the provider `incomplete`. In every vendor test, each listed + object is in exactly one detail count or one left-out count +- `--json` includes `vendor_workouts.requested`, `requests_made`, + `notice`, `used_bytes`, `bound_bytes`, `estimated.originals`, and each + provider's `status`, `connection_status`, `covers_requested_range`, + `more`, `limit`, and `estimated` with `owner_corrections_replaced`, + `merge_choices_replaced`, `details`, and `left_out`. The top level has + `estimated_owner_corrections_replaced` and + `estimated_merge_choices_replaced` + +Migration tests, in the build gate: + +- a synthetic 2.1.3 database makes `Store::open` refuse before any network + call. `ath migrate` previews without writing. It still previews, backs up, + and asks, as D124 requires. The target it names is `2.2.0` +- a confirmed migrate backs up, then sets the record version to `2.2.0`, + SQL schema 8, and `user_version` 8. Record ids, revisions, deletions, + attachments, import keys, reporting periods, and device receipts are + unchanged. `PRAGMA foreign_key_check` is empty. A deleted row and its + history are still there. The upgraded database is populated, including + a tombstone. `sql_v1_current_records` and + `sql_v1_active_records` still return rows. An insert that would make a + revision type disagree with its record is still rejected. A second + migrate does nothing. A failure injected before the step 8 commit + leaves the old views, the two cross-table triggers, the rows, the + version, and `foreign_keys` read back as on. A successful migrate + leaves `foreign_keys` on. A source report can then be created, revised, + checked, exported, restored, and repaired from `data_json` without + becoming a measured type +- `ath init` creates a database that is already `2.2.0`, SQL schema 8, and + `user_version` 8, and `ath check` exits 0. The fresh database accepts a + source report, the same two views are queryable, and a mismatched + revision type is rejected. A failed init rolls step 8 back and then the + existing cleanup removes the new file. A failed step 8 migrate of a + populated 2.1.3 database leaves that file, schema 7, the views, and + foreign-key enforcement. Step 7 still + writes `2.1.3` and schema 7, and `install_schema` commits that + transaction before step 8. Its check accepts schema 7 and `2.1.3` there. + A step 8 that is made to stop before it sets the version rows fails the + step-8 check for schema 8 and `2.2.0`, and init fails. Init runs on the + connection `Store::create` opened and never calls `Store::transaction` +- `apply_steps` given steps 2 through 7 passes its final check at schema 7. + Given a list that ends before 7, it still refuses when the database + stops short of the last step in that list +- a 2.0.0 database whose step 8 is made to fail after steps 3 to 7 + committed is a 2.1.3 database at schema 7. The message says so and names + the verified backup. A second `ath migrate` runs only step 8 and + finishes. `Store::transaction` still refuses a write while foreign keys + are off, and step 8 does not use it +- `ath migrate` re-checks the file, the database ID, the schema, and the + revision its earlier steps left before step 8. A change made between the + two transactions stops step 8 and changes nothing more +- databases at `1.0.0`, `2.0.0`, `2.1.0`, `2.1.1`, and `2.1.2` still open for migrate. Packages at + `2.0.0`, `2.1.0`, `2.1.1`, `2.1.2`, and `2.1.3` still import. `spec/sql/migrations/004-version-2-1.sql`, + `spec/sql/migrations/005-version-2-1-1.sql`, `spec/sql/migrations/006-version-2-1-2.sql`, + `spec/sql/migrations/007-version-2-1-3.sql`, and the folders `schema/2.0.0/`, + `schema/2.1.0/`, `schema/2.1.1/`, `schema/2.1.2/`, and `schema/2.1.3/` stay byte-identical + +Rust tests use `MemorySecretStore` in `src/runtime/keyring.rs` and do not +open the real password store. They cover: + +- the missing-key sentence +- `ath key set openwearables` +- `ath key clear` with no name, when an Open Wearables key is saved, clears + `vercel` and `openrouter` only, exits successfully, and prints that the + Open Wearables key remains saved, with the command `ath key clear + openwearables` +- `ath key clear` with no name, when no Open Wearables key is saved, keeps + today's gateway sentences +- `ath key clear vercel` does not remove a saved Open Wearables key +- `ath key clear garmin` is still refused, as in 2.1.1 +- `OPEN_WEARABLES_API_KEY` is used before the saved key, as + `GARMIN_PERSONAL_API_KEY` is for Garmin +- `ath key clear openwearables` removes the saved key and, when + `OPEN_WEARABLES_API_KEY` is set, says that variable is still available. The + variable is still set afterward +- `ath key --json` keeps `saved` and `environment` as gateway lists and adds + `openwearables.saved` and `openwearables.environment` +- a preview `--json` has `written: false`, protected and archive + committed zeros, `estimated` counts, and `range_complete: false` +- `--json --yes` is a preview. After a later-page failure, and after a + readable range, neither preview is applied and the database is + unchanged +- `ath pull garmin` with no `--date` fails with `error: required option + '--date ' not specified`, as in 2.1.1. `ath pull openwearables` + needs no `--date`. `ath pull other` fails with `pull reads garmin or + openwearables` + +`cargo fmt --check`, `cargo clippy --all-targets -- -D warnings`, and +`cargo test` pass. In `packages/npm`, `npm ci`, `npm run typecheck`, and +`npm test` pass. That is the gate before the build is called done. + +## 8. You test this (Laptop) + +The card uses the fixture server the tests use. It does not use a real +account or a real export. The fixture user has a Garmin connection and no +other connection. The card does not pass `--vendor-workouts`, so it makes +no live vendor request. The build starts that server on `127.0.0.1` and an +ephemeral port, prints the port, and uses the fixture key and the fixture +user id. The range is `--from 2026-01-01 --to 2026-01-07`. The person pastes +the fixture key once into `ath key set openwearables`. + +1. Setup. Success: `ath init --yes --empty` creates the database, the key + command saves the fixture key, and the key is not on screen. Failure: + init fails, or the key is printed. +2. Preview. Success: the pull without `--yes` says nothing is stored, shows + estimated counts that include a heart-rate sample and a day summary, shows + a body snapshot line, makes no vendor request, and `ath check` still + passes. Failure: a row is written, a vendor request is made, or the key + appears. +3. Write. Success: the same command with `--yes` says the requested range is + complete, shows the body snapshot line, shows committed counts, and + `ath check` exits 0. The stored range can be complete with only Garmin + connected. Failure: the success sentence appears while the + range or the body snapshot is incomplete, or `ath check` fails. +4. Repeat. Success: `--yes` again reports the stored rows unchanged. + Failure: a second copy of a sleep session or a point appears. +5. Compatibility. Success: one synthetic Apple, WHOOP, or Oura import still + passes `ath check`, and `ath pull garmin` with no date still fails with + `error: required option '--date ' not specified`. Failure: that + import or the Garmin command breaks. + +The automated cases in section 7 are not extra card steps. + +The build's proof is one phone message. That message contains a +screenshot of each step inline and one video that plays in the conversation. +A video that plays only on the pull request page is not that packet. The +images are not committed. The numbers on screen are the fixture's invented +values. The release workflow on Linux, macOS, and Windows is the +cross-platform proof. The video is one system. + +This plan pull request has no screenshots and no video. + +## 9. Separate follow-ups + +D276 records the check. None of these is a prerequisite for the pull, and none +is in the build pull request. + +- Failed `ath init` and failed `Store::create` still delete the database + file in the same process that closed it, without the abandoned-directory + cleanup `make_owned_temporary_directory` uses. On Windows that delete can + fail with `EBUSY`. Version 2.1.0 spec section 12 left it out + and named no later version. Version 2.1.1 did not take it. A failed step 8 + rolls back before that cleanup. This build does not replace the cleanup. +- `src/import/mapping.rs` is 1703 lines, `src/import/provider.rs` is 1297, + and `src/store/check.rs` is 1044. The pull does not add HTTP to them. + `mapping.rs` gains `MappedPage`, the `vendor_workout` section, and the + preservation writes in section 2. `provider.rs` gains the staged first + bind, the `device_binding` refusal in `ProviderPreview::apply`, the + `connector` source call, and the stored-original read. `staging.rs` gains + the count by record type. The binding check and the safety snapshot go in + the new `src/import/binding.rs`. `src/store/encode.rs` gains the sample, + source-report, withdrawal, and paired-null writes in section 6, and + `src/calculate/range.rs` gains the null filter. Splitting `mapping.rs` + stays out. +- `ath key clear garmin` is refused in 2.1.1, because `key_clear` in + `src/cli/commands/model.rs` accepts only gateway names. `ath key set + garmin` works. This pull leaves that as it is. Making the Garmin key + removable is separate work. +- `persist.rs` and `ath-core persist` are gone. A name check outside import + is separate work. The pull does not add one. +- The mapping path rule is already `is_mapping_path` in `src/assets/mod.rs`. + There is no duplicate to delete. +- Vendor originals live in the package's main document, under its 512 MiB + read cap. Storing them in their own package files, as samples are, would + lift the 256 MiB bound in section 2. That is a package format change, + and this plan does not make it. The bound holds about 158 one-hour + Polar workouts with routes and samples, so whether 2.2.0 should store + originals in their own files is an open question for the maintainer, in + section 10. + +No maintainability note under another name was found in the 2.1.0 or +2.1.1 decision logs. The sizes above are the code at 2.1.1, not a +recorded D-number. + +## 10. Risks and the approval + +Cloud-agent time for the build is uncertain. The published history has no +measured run for this pull. + +Risks: + +- A server newer than 0.11.0 can add a default that hides a second device. + Current `main` does not, when the queries in D275 are sent. The client is + tested against the stored fixture. That fixture is not a live response, and + a live timestamp without an offset is left out. A breaking envelope needs a + new fixture before the pull trusts it. +- A raw range can be large. A page over the response cap, 10 MiB, is read + again with a smaller limit. A 429 or another transport failure still + stops that read, keeps earlier pages, and withholds the success line. The + study did not read the rate-limit middleware. +- A failed step 8 on a database older than 2.1.3 leaves it at 2.1.3, + because the earlier steps committed first. The message says so and names + the verified backup, and a second `ath migrate` finishes. Step 8 needs + foreign keys off, and the earlier steps run with them on, so they cannot + share one transaction. +- A live read can change the server. It can refresh a token, revoke a + connection, or wait on a rate limit. The command says so before its + first live request. It cannot stop the server from doing it. +- Strava's limit is shared with the deployment's own sync. One command can + use most of a 15-minute window. +- The pinned Garmin detail path and the cited Garmin rate were not found + in Garmin's public docs. If the path does not exist, the first Garmin + detail call in a command answers an error such as 404. The pull then + makes no other Garmin detail call in that command, Garmin stays + `completed`, and each Garmin original holds its list object only. That + costs one detail call in each command that has a Garmin id due a call. + An id that got 404 or 501 is asked again after 30 days. Each repeat + answer writes one small revision of that original. + Where the path works, an id that once got 404 or 501 is not called + again until its list object changes. This is the stated default, and + the maintainer still has to confirm it. +- A later pull replaces an owner correction when the server's data for + that record changed since an import last wrote it. The preview and the + result count each one. The correction stays in the history. Deleting + the record stops later pulls from changing it, and it also takes the + record out of current data. This rule covers every record on route + `open_wearables`, not only vendor originals. Other routes keep D182. + That scope is the stated default, and the maintainer still has to + confirm it. A conflict the person resolved in a package merge counts as + an owner correction, and the counts name it as a merge choice. A + body-snapshot correction rarely survives, because the server's + averaging window moves with every request. +- A deferred id that the provider stops listing is never detailed. Its + list object stays stored, and the deferred count shows that it waits. +- Vendor originals share the main package document and its 512 MiB read + cap. The bound, 256 MiB as export writes them, refuses a vendor write + before a package would become unreadable. About 158 one-hour Polar + workouts with routes and samples reach it with one revision each, and + about 105 with two. Every pull shows the total, and from 80% it warns. + At the bound, that provider stays `incomplete` until originals are + erased, which removes them and their history, or until a later version + stores them in their own files. Nothing bounds the other half of the + document. A long history of other records can still reach the read + cap, and the export check then refuses to publish. +- Date-only bounds mean whatever Open Wearables decides. The docs and the + 0.11.0 parser disagree about UTC. This release does not correct that server. +- Section 2 stores returned periods, series, and snapshots. It does not + invent a measurement time. A null stays null. A row the server did not + return stays unknown. The device receipt is a separate rule. +- Fields on a sleep or workout object that the mapping does not consume are + stored under the server's names. Latitude and longitude are stored when + the server sends them. +- The administrator key is more powerful than this command. A leaked key from + the password store exposes every user on that deployment. The command's job + is to avoid copying the key into the record. + +The build, after approval, is one pull request in this order. First the +schema and step 8: the root `record_type` check, the period type, the +`aggregator` basis, the sample series quantities in the appendix table, +the `source_report` type and table, the paired null value and unit, and +the time-unknown summary. The point check in `src/model/data.rs` and the +mapping's positive check accept a finite `hr_recovery`, including zero and +a negative number. `packages/npm/src/schema.ts` is not where that check is +added. No table is rebuilt for that check. Then the store, the +calculation null filter, the staging and apply changes in +`src/import/provider.rs` and `src/import/binding.rs`, the archive, and the +record paths in section 6. Then the mapping engine, `MappedPage`, and +`mappings/open-wearables.md`. Then the stored reads, the vendor read, the +cycle filter, the smaller-page split, and the tests in section 7. The +laptop card and the phone proof are part of that same pull request. This +plan pull request has no media. + +The maintainer approves or rejects this plan before any build. D272 through +D289 are the proposal. They are not adopted. The stored workout and the +live original stay separate records, because the public stored +workout has no vendor id. That split is part of this proposal. D289 is the +privacy choice, and the maintainer can change it before approval. Reviews of earlier heads were +incorporated here. None of those reviews approves this revision. The next +head needs re-review. An earlier review accepted a +migration with no new column, under D152 and D184. That acceptance does not +adopt D272. The +optional source key adds no column. + +1. One number, 2.2.0. Readable sets keep `1.0.0`. Step 8 runs on create and + on migrate. Step 5 stays the published 2.1.1 migration. Step 6 stays the + published 2.1.2 migration. Step 7 stays the published 2.1.3 migration. The device + receipt adds no column. Step 8 extends the + root check with `source_report` by the copy in section 5, creates + `source_reports`, and rebuilds `provider_summaries` and + `provider_scores` so a numberless object can omit `value` and its unit + together. Existing ids and rows are copied. Before the root rename, + step 8 drops and later recreates `sql_v1_current_records`, + `sql_v1_active_records`, and the two `record_revisions` triggers that + read `records`. Foreign keys stay on for ordinary writes. Step 8 turns + them off on the store's own connection, only before its transaction, + and reads them back on after every exit. A + `2.1.3` database does not open until `ath migrate`. This release does + not schedule a pull, add its own token refresh, backfill, or store a + cursor (D272). A live read can still make the server refresh a vendor + token (D288). +2. Store the returned representations in section 2. Device receipts stay + on device sources. Summaries without a device id use their own sensors. + Null stays null. A missing response is not called provider-unavailable. + The omissions in section 2 are the ones with a reason (D277, D280). +3. The key, the selected origin, and the selected user id are rejected in + decoded JSON before a page is mapped. Failure text uses a fixed sentence. + `ath key clear` with no name still clears only the gateway keys and says + when the Open Wearables key remains. Named clear removes the saved key + only. It does not unset the environment and it does not revoke the server + key (D274). A credential-shaped value is withheld and counted. It does + not refuse the page (D289). +4. Preview is the default and its counts are estimates. `--json` does not + write. `--yes` commits each successful page under D189, and a committed + page is not a completed pull. The text of `--yes` shows retained counts + and whether the requested range is complete. A missing row is not deleted. + Raw and day reads omit `types` and store every series. The same sensor + triple keeps one + source. A second `device_id` does not replace or suppress the first, in + a later command or in a mapped file import, including import then import. + The receipt is the source key `device_binding`. A 2.1.0 supplied field of + that name does not become the receipt. Unbound history is refused and + left in place. `ath correct`, the protocol record writes, and a native + 2.2.0 package restore are the owner's whole source record (D275, D276). +5. The Windows cleanup, the Garmin key removal, and the maintainability + notes stay separate. `src/import/mapping.rs` gains `MappedPage`, the + `vendor_workout` section, and the preservation writes in section 2. + `src/import/provider.rs` gains the staged first bind, the + `device_binding` refusal in `ProviderPreview::apply`, the `connector` + source call, and the stored-original read. `src/import/staging.rs` gains + the count by record type. The new `src/import/binding.rs` holds the binding + check and the bounded safety snapshot. `src/store/encode.rs` gains the + sample, source-report, withdrawal, and paired-null writes in section 6, + and `src/calculate/range.rs` gains the null filter. The pull command + builds the archive preview and applies it only at the snapshot's + revision. `mapping.rs` does not start it. Failed-init cleanup stays as + it is (D276, D282). +6. The live vendor read is off by default and warns before its first + request. It calls only active connections and never stores the + connections list. It keeps every stored detail, counts every object it + does not write, and withholds credential-shaped values. The stored + workout and the vendor original stay two records. On route + `open_wearables`, an owner correction is kept until the server's data + for that record changes, and each correction a page replaces is counted + (D287, D288, D289). + +These questions stay open for the maintainer. The plan states a default +for each, and the default is not adopted: + +1. Garmin detail. The default probes the undocumented detail path once + per command. When the probe answers an error status other than 401 or + 429, the pull makes no other Garmin detail call in that command. Only + 404 and 501 mark the probed id `not_available`, and such an id is + asked again after 30 days (D288). +2. The owner-correction scope. The default covers every record the + `open_wearables` pull writes. Other routes keep D182 (D287). +3. Storing vendor originals in their own package files. The default keeps + them in the main document under the 256 MiB bound, which holds about + 158 route-heavy one-hour Polar workouts (D287).